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:
@@ -0,0 +1,35 @@
|
||||
# ShellBook web
|
||||
|
||||
From the repository root, install with `npx -y [email protected] 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 [email protected] --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.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<title>ShellBook</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLDivElement>(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 <div className="editor" ref={root} />;
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
hosts: HostInfo[];
|
||||
onChange(name: string, value: string): void;
|
||||
}) {
|
||||
return (
|
||||
<form
|
||||
className="params"
|
||||
aria-label="Notebook parameters"
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
>
|
||||
{notebook.params.map((param) => {
|
||||
const id = `param-${param.name}`;
|
||||
const common = {
|
||||
id,
|
||||
required: param.required,
|
||||
value: values[param.name] ?? "",
|
||||
"aria-labelledby": `${id}-label`,
|
||||
"aria-invalid": !!errors[param.name],
|
||||
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
|
||||
onChange: (
|
||||
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
|
||||
) => onChange(param.name, e.target.value),
|
||||
};
|
||||
return (
|
||||
<label key={param.name} htmlFor={id}>
|
||||
<span id={`${id}-label`}>
|
||||
{param.label ?? param.name}
|
||||
{param.required && <b title="Required"> *</b>}
|
||||
</span>
|
||||
{param.type === "host" || param.type === "choice" ? (
|
||||
<select {...common}>
|
||||
<option value="">Select…</option>
|
||||
{(param.type === "host"
|
||||
? hosts.map((h) => h.name)
|
||||
: (param.options ?? [])
|
||||
).map((option) => (
|
||||
<option key={option}>{option}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
{...common}
|
||||
type={param.type === "secret" ? "password" : "text"}
|
||||
autoComplete={param.type === "secret" ? "new-password" : "off"}
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
{errors[param.name] && (
|
||||
<small id={`${id}-error`} className="error">
|
||||
{errors[param.name]}
|
||||
</small>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<pre className="script">
|
||||
<code>
|
||||
{script
|
||||
.split(/(\{\{[^}]+\}\})/g)
|
||||
.map((part, i) =>
|
||||
part.startsWith("{{") ? (
|
||||
<mark key={i}>{part}</mark>
|
||||
) : (
|
||||
<span
|
||||
key={i}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: hljs.highlight(part, { language: "bash" }).value,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</code>
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
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 (
|
||||
<article
|
||||
className={`step ${run?.status ?? ""}`}
|
||||
aria-label={step.attrs.title ?? step.attrs.id}
|
||||
>
|
||||
<header>
|
||||
<span className="badge">{step.kind}</span>
|
||||
<h3>{step.attrs.title ?? step.attrs.id}</h3>
|
||||
<span className="target">
|
||||
{rendered.local
|
||||
? "local · ShellBook server"
|
||||
: (rendered.host ?? "No host selected")}
|
||||
</span>
|
||||
{step.attrs.sudo && <span className="badge">sudo</span>}
|
||||
{(step.attrs.confirm ||
|
||||
(step.kind === "run" && host?.tags.includes("prod"))) && (
|
||||
<span className="badge">confirm</span>
|
||||
)}
|
||||
</header>
|
||||
<Script script={rendered.script} />
|
||||
{invalid && (
|
||||
<p className="error" role="status">
|
||||
{rendered.missing.length > 0 &&
|
||||
`Missing: ${rendered.missing.join(", ")}. `}
|
||||
{Object.entries(rendered.invalid)
|
||||
.map(([name, error]) => `${name}: ${error}`)
|
||||
.join("; ")}
|
||||
</p>
|
||||
)}
|
||||
<div className="actions">
|
||||
<button onClick={() => void copy(false)}>Copy</button>
|
||||
<button disabled={!host || invalid} onClick={() => void copy(true)}>
|
||||
Copy as ssh one-liner
|
||||
</button>
|
||||
<span className="spacer" />
|
||||
<button
|
||||
className="primary"
|
||||
disabled={invalid || busy || !connected || (!rendered.local && !host)}
|
||||
onClick={onRun}
|
||||
>
|
||||
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
|
||||
</button>
|
||||
</div>
|
||||
{notice && <small role="status">{notice}</small>}
|
||||
{run && (
|
||||
<section className="result" aria-label="Run output">
|
||||
<div role="status">
|
||||
{run.status === "success"
|
||||
? "✅ Succeeded"
|
||||
: run.status === "failure"
|
||||
? "❌ Failed"
|
||||
: run.status === "hostKey"
|
||||
? "Awaiting host key confirmation"
|
||||
: "Running…"}
|
||||
{run.exitCode !== undefined && ` · exit ${run.exitCode}`}
|
||||
{run.durationMs !== undefined &&
|
||||
` · ${(run.durationMs / 1000).toFixed(2)}s`}
|
||||
</div>
|
||||
<pre aria-live="polite">
|
||||
{run.output.map((chunk, i) => (
|
||||
<span className={chunk.stream} key={i}>
|
||||
{chunk.data}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
{run.error && <p className="error">{run.error}</p>}
|
||||
{run.artifacts.map((name) => (
|
||||
<a
|
||||
className="artifact"
|
||||
key={name}
|
||||
href={artifact(run.runId, name)}
|
||||
download
|
||||
>
|
||||
↓ {name}
|
||||
</a>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function TerminalSlot() {
|
||||
return (
|
||||
<aside className="terminal" aria-label="Terminal panel">
|
||||
<h2>Terminal</h2>
|
||||
<p>Claude Code terminal · M4</p>
|
||||
<div className="terminal-slot" />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type {
|
||||
NotebookListResponse,
|
||||
HostsResponse,
|
||||
NotebookResponse,
|
||||
SaveNotebookResponse,
|
||||
StartRunRequest,
|
||||
StartRunResponse,
|
||||
ServerEvent,
|
||||
} from "@shellbook/core";
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(public status: number) {
|
||||
super(`Request failed (${status})`);
|
||||
}
|
||||
}
|
||||
async function json<T>(
|
||||
path: string,
|
||||
method = "GET",
|
||||
body?: unknown,
|
||||
): Promise<T> {
|
||||
const response = await fetch(`/api${path}`, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) throw new HttpError(response.status);
|
||||
return response.status === 204
|
||||
? (undefined as T)
|
||||
: (response.json() as Promise<T>);
|
||||
}
|
||||
export interface Api {
|
||||
me(): Promise<unknown>;
|
||||
login(password: string): Promise<unknown>;
|
||||
list(): Promise<NotebookListResponse>;
|
||||
hosts(): Promise<HostsResponse>;
|
||||
notebook(path: string): Promise<NotebookResponse>;
|
||||
save(
|
||||
path: string,
|
||||
source: string,
|
||||
baseVersion: string,
|
||||
): Promise<SaveNotebookResponse>;
|
||||
run(request: StartRunRequest): Promise<StartRunResponse>;
|
||||
events(
|
||||
receive: (event: ServerEvent) => void,
|
||||
connection: (connected: boolean) => void,
|
||||
): () => void;
|
||||
artifact(runId: string, name: string): string;
|
||||
}
|
||||
export const liveApi: Api = {
|
||||
me: () => json("/auth/me"),
|
||||
login: (password) => json("/auth/login", "POST", { password }),
|
||||
list: () => json("/notebooks"),
|
||||
hosts: () => json("/hosts"),
|
||||
notebook: (path) => json(`/notebooks/${encodeURIComponent(path)}`),
|
||||
save: (path, source, baseVersion) =>
|
||||
json(`/notebooks/${encodeURIComponent(path)}`, "PUT", {
|
||||
source,
|
||||
baseVersion,
|
||||
}),
|
||||
run: (request) => json("/runs", "POST", request),
|
||||
artifact: (id, name) =>
|
||||
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
|
||||
events(receive, connection) {
|
||||
const ws = new WebSocket(
|
||||
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/events`,
|
||||
);
|
||||
ws.onopen = () => connection(true);
|
||||
ws.onclose = () => connection(false);
|
||||
ws.onerror = () => connection(false);
|
||||
ws.onmessage = (message) => {
|
||||
try {
|
||||
receive(JSON.parse(String(message.data)) as ServerEvent);
|
||||
} catch {
|
||||
connection(false);
|
||||
}
|
||||
};
|
||||
return () => ws.close();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
|
||||
export interface RunState {
|
||||
runId: string;
|
||||
notebookPath: string;
|
||||
stepId: string;
|
||||
status: "running" | "success" | "failure" | "hostKey";
|
||||
output: { stream: "stdout" | "stderr"; data: string }[];
|
||||
exitCode?: number;
|
||||
durationMs?: number;
|
||||
artifacts: string[];
|
||||
error?: string;
|
||||
hostKey?: Extract<ServerEvent, { type: "run.hostKeyUnknown" }>;
|
||||
}
|
||||
export interface Session {
|
||||
runs: Record<string, RunState>;
|
||||
latest: Record<string, string>;
|
||||
runtime: Record<string, Record<string, string>>;
|
||||
artifactSources: Record<string, Record<string, string>>;
|
||||
}
|
||||
export const emptySession: Session = {
|
||||
runs: {},
|
||||
latest: {},
|
||||
runtime: {},
|
||||
artifactSources: {},
|
||||
};
|
||||
export const stepKey = (path: string, id: string) => JSON.stringify([path, id]);
|
||||
export type Action =
|
||||
| ServerEvent
|
||||
| { type: "requested"; runId: string; request: StartRunRequest };
|
||||
export function eventReducer(state: Session, event: Action): Session {
|
||||
if (event.type === "file.changed" || event.type === "file.deleted")
|
||||
return state;
|
||||
if (event.type === "requested" || event.type === "run.started") {
|
||||
const info = event.type === "requested" ? event.request : event;
|
||||
const previous = state.runs[event.runId];
|
||||
return {
|
||||
...state,
|
||||
runs: {
|
||||
...state.runs,
|
||||
[event.runId]: previous ?? {
|
||||
runId: event.runId,
|
||||
notebookPath: info.notebookPath,
|
||||
stepId: info.stepId,
|
||||
status: "running",
|
||||
output: [],
|
||||
artifacts: [],
|
||||
},
|
||||
},
|
||||
latest: {
|
||||
...state.latest,
|
||||
[stepKey(info.notebookPath, info.stepId)]: event.runId,
|
||||
},
|
||||
};
|
||||
}
|
||||
const run = state.runs[event.runId];
|
||||
if (!run) return state;
|
||||
let updated: RunState = run;
|
||||
let next = state;
|
||||
switch (event.type) {
|
||||
case "run.output":
|
||||
updated = {
|
||||
...run,
|
||||
output: [...run.output, { stream: event.stream, data: event.data }],
|
||||
};
|
||||
break;
|
||||
case "run.error":
|
||||
updated = { ...run, status: "failure", error: event.message };
|
||||
break;
|
||||
case "run.hostKeyUnknown":
|
||||
updated = { ...run, status: "hostKey", hostKey: event };
|
||||
break;
|
||||
case "run.finished": {
|
||||
updated = {
|
||||
...run,
|
||||
status: event.exitCode === 0 ? "success" : "failure",
|
||||
exitCode: event.exitCode,
|
||||
durationMs: event.durationMs,
|
||||
artifacts: event.artifacts,
|
||||
};
|
||||
if (event.exitCode === 0) {
|
||||
next = {
|
||||
...state,
|
||||
runtime: {
|
||||
...state.runtime,
|
||||
[run.notebookPath]: {
|
||||
...state.runtime[run.notebookPath],
|
||||
...(event.captured
|
||||
? { [event.captured.name]: event.captured.value }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
artifactSources: {
|
||||
...state.artifactSources,
|
||||
[run.notebookPath]: {
|
||||
...state.artifactSources[run.notebookPath],
|
||||
...Object.fromEntries(
|
||||
event.artifacts.map((name) => [name, event.runId]),
|
||||
),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { ...next, runs: { ...state.runs, [event.runId]: updated } };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
import { liveApi } from "./api";
|
||||
import "./style.css";
|
||||
|
||||
const api =
|
||||
import.meta.env.VITE_MOCK === "1"
|
||||
? (await import("./mock/api")).mockApi
|
||||
: liveApi;
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App api={api} />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
import type { Api } from "../api";
|
||||
import { HttpError } from "../api";
|
||||
import { parseNotebook, renderStep } from "./core";
|
||||
import initial from "./ssh-key.md?raw";
|
||||
let source = initial;
|
||||
let version = 1;
|
||||
let counter = 0;
|
||||
const listeners = new Set<(event: ServerEvent) => void>();
|
||||
const emit = (event: ServerEvent) =>
|
||||
listeners.forEach((listener) => listener(event));
|
||||
const hosts = [
|
||||
{
|
||||
name: "staging",
|
||||
user: "admin",
|
||||
address: "192.0.2.10",
|
||||
port: 22,
|
||||
tags: ["demo"],
|
||||
},
|
||||
{
|
||||
name: "production",
|
||||
user: "ops",
|
||||
address: "192.0.2.20",
|
||||
port: 2222,
|
||||
tags: ["prod"],
|
||||
},
|
||||
];
|
||||
const artifactUrl = URL.createObjectURL(
|
||||
new Blob(["Demo artifact only. No real key material.\n"], {
|
||||
type: "text/plain",
|
||||
}),
|
||||
);
|
||||
export const mockApi: Api = {
|
||||
me: async () => ({ authenticated: true }),
|
||||
login: async () => undefined,
|
||||
list: async () => ({
|
||||
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
|
||||
}),
|
||||
hosts: async () => ({ hosts }),
|
||||
notebook: async (path) => ({
|
||||
path,
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
version: String(version),
|
||||
}),
|
||||
save: async (_path, next, base) => {
|
||||
if (base !== String(version)) throw new HttpError(409);
|
||||
source = next;
|
||||
version++;
|
||||
return { version: String(version) };
|
||||
},
|
||||
events: (receive, connected) => {
|
||||
listeners.add(receive);
|
||||
connected(true);
|
||||
return () => {
|
||||
listeners.delete(receive);
|
||||
};
|
||||
},
|
||||
artifact: () => artifactUrl,
|
||||
run: async (request: StartRunRequest) => {
|
||||
const notebook = parseNotebook(source);
|
||||
const block = notebook.blocks.find(
|
||||
(b) => b.type === "step" && b.step.attrs.id === request.stepId,
|
||||
);
|
||||
if (!block || block.type !== "step") throw new Error("Unknown demo step");
|
||||
const rendered = renderStep(
|
||||
notebook,
|
||||
block.step,
|
||||
request.params,
|
||||
request.runtime,
|
||||
hosts.map((h) => h.name),
|
||||
);
|
||||
const runId = `demo-${++counter}`;
|
||||
setTimeout(() => {
|
||||
emit({
|
||||
type: "run.started",
|
||||
runId,
|
||||
notebookPath: request.notebookPath,
|
||||
stepId: request.stepId,
|
||||
script: rendered.script,
|
||||
host: rendered.host,
|
||||
});
|
||||
if (rendered.host === "production" && !request.acceptHostKey) {
|
||||
emit({
|
||||
type: "run.hostKeyUnknown",
|
||||
runId,
|
||||
host: "production",
|
||||
fingerprint: "SHA256:DEMO-VERIFY-OUT-OF-BAND",
|
||||
changed: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
emit({
|
||||
type: "run.output",
|
||||
runId,
|
||||
stream: "stdout",
|
||||
data: "Demo stream — no shell commands execute.\n",
|
||||
});
|
||||
setTimeout(() => {
|
||||
const failed = request.stepId === "password-login-disabled";
|
||||
emit({
|
||||
type: "run.output",
|
||||
runId,
|
||||
stream: failed ? "stderr" : "stdout",
|
||||
data: failed
|
||||
? "Demo: password authentication is enabled.\n"
|
||||
: "Demo: completed successfully.\n",
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId,
|
||||
exitCode: failed ? 1 : 0,
|
||||
durationMs: 850,
|
||||
artifacts: rendered.artifacts,
|
||||
captured: block.step.attrs.capture
|
||||
? { name: block.step.attrs.capture, value: "demo-value" }
|
||||
: undefined,
|
||||
});
|
||||
}, 850);
|
||||
}, 50);
|
||||
return { runId };
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
/** TEMPORARY M0 fallback. Demo-only Vite alias; never used in production.
|
||||
* Remove this file and the alias when core lands. Parser supports the fixture
|
||||
* body syntax only; frontmatter definitions are fixed to spec §3.1.
|
||||
*/
|
||||
import type {
|
||||
Block,
|
||||
Notebook,
|
||||
ParamValues,
|
||||
RenderedStep,
|
||||
Step,
|
||||
StepAttrs,
|
||||
} from "../../../../packages/core/src/types";
|
||||
export function shellQuote(value: string): string {
|
||||
return value && /^[A-Za-z0-9._/@:=+-]+$/.test(value)
|
||||
? value
|
||||
: `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
export function parseNotebook(source: string): Notebook {
|
||||
const lines = source
|
||||
.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")
|
||||
.split(/\r?\n/);
|
||||
function parse(
|
||||
start: number,
|
||||
nested = false,
|
||||
): { blocks: Block[]; end: number } {
|
||||
const blocks: Block[] = [];
|
||||
let prose = "";
|
||||
const range = { startLine: 1, endLine: 1 };
|
||||
const flush = () => {
|
||||
if (prose) blocks.push({ type: "markdown", text: prose, range });
|
||||
prose = "";
|
||||
};
|
||||
for (let i = start; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
if (nested && line === ":::") {
|
||||
flush();
|
||||
return { blocks, end: i };
|
||||
}
|
||||
const after = line.match(/^:::after\{step=(\S+?)( failed)?\}$/);
|
||||
if (after) {
|
||||
flush();
|
||||
const inner = parse(i + 1, true);
|
||||
blocks.push({
|
||||
type: "after",
|
||||
stepId: after[1]!,
|
||||
onFailure: !!after[2],
|
||||
blocks: inner.blocks,
|
||||
range,
|
||||
});
|
||||
i = inner.end;
|
||||
continue;
|
||||
}
|
||||
const fence = line.match(/^```(?:sh|bash) \{(run|check) (.*)\}$/);
|
||||
if (fence) {
|
||||
flush();
|
||||
const raw = fence[2]!;
|
||||
const attrs = Object.fromEntries(
|
||||
[...raw.matchAll(/([\w]+)=(?:"([^"]*)"|([^\s]+))/g)].map((m) => [
|
||||
m[1],
|
||||
m[2] ?? m[3],
|
||||
]),
|
||||
);
|
||||
const title = attrs.title ?? "Step";
|
||||
const stepAttrs: StepAttrs = {
|
||||
id: attrs.id ?? title.toLowerCase().replace(/\s+/g, "-"),
|
||||
title,
|
||||
host: attrs.host,
|
||||
local: attrs.on === "local",
|
||||
sudo: /(?:^|\s)sudo(?:\s|$)/.test(raw),
|
||||
confirm: /(?:^|\s)confirm(?:\s|$)/.test(raw),
|
||||
artifacts: attrs.artifacts?.split(",") ?? [],
|
||||
uploads: attrs.upload
|
||||
? attrs.upload.split(",").map((pair: string) => {
|
||||
const [src, dst] = pair.split(":");
|
||||
return { src: src!, dst: dst! };
|
||||
})
|
||||
: [],
|
||||
timeoutSec: 30,
|
||||
capture: attrs.capture,
|
||||
};
|
||||
const script: string[] = [];
|
||||
while (++i < lines.length && lines[i] !== "```") script.push(lines[i]!);
|
||||
blocks.push({
|
||||
type: "step",
|
||||
step: {
|
||||
kind: fence[1] as Step["kind"],
|
||||
lang: "sh",
|
||||
attrs: stepAttrs,
|
||||
script: script.join("\n"),
|
||||
range,
|
||||
},
|
||||
});
|
||||
} else prose += line + "\n";
|
||||
}
|
||||
flush();
|
||||
return { blocks, end: lines.length };
|
||||
}
|
||||
return {
|
||||
title: "New server SSH key",
|
||||
params: [
|
||||
{ name: "host", type: "host", required: true, label: "Target server" },
|
||||
{
|
||||
name: "user",
|
||||
type: "name",
|
||||
required: true,
|
||||
default: "admin",
|
||||
label: "Login user",
|
||||
},
|
||||
{
|
||||
name: "keyname",
|
||||
type: "name",
|
||||
required: false,
|
||||
default: "id_ed25519_{{host}}",
|
||||
},
|
||||
],
|
||||
blocks: parse(0).blocks,
|
||||
diagnostics: [
|
||||
{
|
||||
severity: "warning",
|
||||
message:
|
||||
"Mock demo: frontmatter schema is fixed; prose and step edits are supported. No commands execute.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
export function renderText(
|
||||
text: string,
|
||||
values: ParamValues,
|
||||
notebook: Notebook,
|
||||
): string {
|
||||
return text.replace(/\{\{(\w+)\}\}/g, (token, name: string) =>
|
||||
notebook.params.find((p) => p.name === name)?.type === "secret"
|
||||
? "••••"
|
||||
: values[name] || token,
|
||||
);
|
||||
}
|
||||
export function resolveParams(
|
||||
notebook: Notebook,
|
||||
input: ParamValues,
|
||||
hosts: readonly string[],
|
||||
) {
|
||||
const values = { ...input };
|
||||
const errors: Record<string, string> = {};
|
||||
for (let i = 0; i < notebook.params.length; i++)
|
||||
for (const p of notebook.params)
|
||||
if (values[p.name] === undefined && p.default !== undefined) {
|
||||
const expanded = renderText(p.default, values, notebook);
|
||||
if (!expanded.includes("{{")) values[p.name] = expanded;
|
||||
}
|
||||
for (const p of notebook.params) {
|
||||
const value = values[p.name] ?? "";
|
||||
if (!value && p.required) errors[p.name] = "Required";
|
||||
else if (
|
||||
value &&
|
||||
((p.type === "host" && !hosts.includes(value)) ||
|
||||
(p.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) ||
|
||||
(p.type === "choice" && !p.options?.includes(value)))
|
||||
)
|
||||
errors[p.name] = "Invalid value";
|
||||
}
|
||||
return { values, errors };
|
||||
}
|
||||
export function renderStep(
|
||||
notebook: Notebook,
|
||||
step: Step,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hosts: readonly string[],
|
||||
): RenderedStep {
|
||||
const resolved = resolveParams(notebook, values, hosts);
|
||||
const all = { ...runtime, ...resolved.values };
|
||||
const missing = notebook.params
|
||||
.filter((p) => p.required && !all[p.name])
|
||||
.map((p) => p.name);
|
||||
const invalid = { ...resolved.errors };
|
||||
const script = step.script.replace(
|
||||
/\{\{(\w+)\}\}/g,
|
||||
(token, name: string) => {
|
||||
if (notebook.params.find((p) => p.name === name)?.type === "secret") {
|
||||
invalid[name] = "Use an environment variable for secrets";
|
||||
return token;
|
||||
}
|
||||
if (!all[name]) {
|
||||
if (!missing.includes(name)) missing.push(name);
|
||||
return token;
|
||||
}
|
||||
return shellQuote(all[name]!);
|
||||
},
|
||||
);
|
||||
return {
|
||||
stepId: step.attrs.id,
|
||||
kind: step.kind,
|
||||
host: renderText(step.attrs.host ?? "", all, notebook),
|
||||
local: step.attrs.local,
|
||||
script,
|
||||
artifacts: step.attrs.artifacts.map((a) => renderText(a, all, notebook)),
|
||||
uploads: step.attrs.uploads.map((u) => ({
|
||||
src: renderText(u.src, all, notebook),
|
||||
dst: renderText(u.dst, all, notebook),
|
||||
})),
|
||||
missing,
|
||||
invalid,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: New server SSH key
|
||||
params:
|
||||
host: { type: host, required: true, label: Target server }
|
||||
user: { type: name, required: true, default: admin, label: Login user }
|
||||
keyname: { type: name, default: "id_ed25519_{{host}}" }
|
||||
---
|
||||
|
||||
# New server SSH key
|
||||
|
||||
Creates a key pair for **{{user}}** on **{{host}}** and authorizes it.
|
||||
|
||||
```sh {check host="{{host}}" title="User exists"}
|
||||
id {{user}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" title="Password login disabled"}
|
||||
sshd -T | grep -qx 'passwordauthentication no'
|
||||
```
|
||||
|
||||
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
|
||||
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
|
||||
```
|
||||
|
||||
```sh {run host="{{host}}" id=authorize title="Authorize key" confirm upload="{{keyname}}.pub:/tmp/new_key.pub"}
|
||||
install -d -m 700 -o {{user}} -g {{user}} ~{{user}}/.ssh
|
||||
cat /tmp/new_key.pub >> ~{{user}}/.ssh/authorized_keys
|
||||
rm /tmp/new_key.pub
|
||||
```
|
||||
|
||||
:::after{step=keygen}
|
||||
Download the private key above, then save it:
|
||||
|
||||
- **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}`
|
||||
- **Windows:** `C:\Users\<you>\.ssh\{{keyname}}`
|
||||
:::
|
||||
@@ -0,0 +1,24 @@
|
||||
import { shellQuote } from "@shellbook/core";
|
||||
import type { HostInfo } from "@shellbook/core";
|
||||
|
||||
/** Copy transport only: the script body is preserved byte for byte. */
|
||||
export function sshCommand(
|
||||
host: HostInfo,
|
||||
script: string,
|
||||
sudo = false,
|
||||
): string {
|
||||
if (
|
||||
!Number.isInteger(host.port) ||
|
||||
host.port < 1 ||
|
||||
host.port > 65535 ||
|
||||
!host.user ||
|
||||
!host.address ||
|
||||
/[\r\n\0]/.test(host.user + host.address)
|
||||
) {
|
||||
throw new Error("Invalid SSH destination");
|
||||
}
|
||||
let delimiter = "EOF";
|
||||
const lines = script.split(/\r?\n/);
|
||||
while (lines.includes(delimiter)) delimiter += "_";
|
||||
return `ssh -p ${host.port} -- ${shellQuote(`${host.user}@${host.address}`)} ${shellQuote(`${sudo ? "sudo -n " : ""}bash -euo pipefail -s`)} <<'${delimiter}'\n${script}${script.endsWith("\n") ? "" : "\n"}${delimiter}`;
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
@import "highlight.js/styles/github-dark.css";
|
||||
:root {
|
||||
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
color: #dce3ec;
|
||||
background: #11151b;
|
||||
color-scheme: dark;
|
||||
--panel: #191f28;
|
||||
--line: #303a49;
|
||||
--muted: #9ba9bb;
|
||||
--accent: #86dab9;
|
||||
--code: #10151c;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
button,
|
||||
input,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
button {
|
||||
cursor: pointer;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
background: var(--panel);
|
||||
color: inherit;
|
||||
padding: 7px 11px;
|
||||
}
|
||||
button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
color: #12261f;
|
||||
font-weight: 650;
|
||||
}
|
||||
input,
|
||||
select {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
background: var(--code);
|
||||
color: inherit;
|
||||
padding: 8px;
|
||||
}
|
||||
input:focus,
|
||||
select:focus,
|
||||
button:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.app {
|
||||
display: grid;
|
||||
grid-template-columns: 230px minmax(0, 1fr);
|
||||
min-height: 100vh;
|
||||
}
|
||||
.with-terminal {
|
||||
grid-template-columns: 230px minmax(0, 1fr) 300px;
|
||||
}
|
||||
.sidebar {
|
||||
background: var(--panel);
|
||||
border-right: 1px solid var(--line);
|
||||
padding: 24px 14px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.sidebar h1 {
|
||||
font-size: 23px;
|
||||
margin: 0 10px 32px;
|
||||
letter-spacing: -1px;
|
||||
}
|
||||
.sidebar h1 span {
|
||||
display: block;
|
||||
font-size: 10px;
|
||||
letter-spacing: 3px;
|
||||
color: var(--muted);
|
||||
margin-top: 8px;
|
||||
}
|
||||
.sidebar nav button {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
margin-bottom: 6px;
|
||||
padding: 12px;
|
||||
border-color: transparent;
|
||||
}
|
||||
.sidebar nav button.selected {
|
||||
background: var(--code);
|
||||
border-color: var(--line);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
small {
|
||||
font-size: 12px;
|
||||
}
|
||||
.sidebar small {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
margin-top: 5px;
|
||||
}
|
||||
.connection {
|
||||
margin-top: auto !important;
|
||||
padding: 10px;
|
||||
}
|
||||
main {
|
||||
min-width: 0;
|
||||
}
|
||||
.toolbar {
|
||||
min-height: 60px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 24px;
|
||||
}
|
||||
.toolbar > span {
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.params {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: var(--panel);
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 14px 24px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
.params label {
|
||||
flex: 1;
|
||||
min-width: 145px;
|
||||
max-width: 280px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.params label > span {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.params b {
|
||||
color: var(--accent);
|
||||
}
|
||||
.notebook {
|
||||
max-width: 1100px;
|
||||
margin: auto;
|
||||
padding: 22px 28px 80px;
|
||||
}
|
||||
.prose {
|
||||
line-height: 1.7;
|
||||
}
|
||||
.prose h1 {
|
||||
font-size: 30px;
|
||||
letter-spacing: -0.7px;
|
||||
}
|
||||
.prose code {
|
||||
background: var(--panel);
|
||||
padding: 2px 5px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.prose pre {
|
||||
overflow: auto;
|
||||
}
|
||||
.step {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
background: var(--panel);
|
||||
margin: 20px 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.step header {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
padding: 13px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.step h3 {
|
||||
font-size: 14px;
|
||||
margin: 0;
|
||||
}
|
||||
.badge {
|
||||
font:
|
||||
11px ui-monospace,
|
||||
monospace;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 3px 6px;
|
||||
color: var(--accent);
|
||||
}
|
||||
.target {
|
||||
margin-left: auto;
|
||||
font:
|
||||
12px ui-monospace,
|
||||
monospace;
|
||||
color: var(--muted);
|
||||
}
|
||||
pre.script {
|
||||
background: var(--code);
|
||||
margin: 0;
|
||||
padding: 22px 18px;
|
||||
overflow: auto;
|
||||
font:
|
||||
14px/1.8 "Cascadia Code",
|
||||
Consolas,
|
||||
monospace;
|
||||
tab-size: 2;
|
||||
user-select: text;
|
||||
}
|
||||
.script mark {
|
||||
background: #714c22;
|
||||
color: #ffe3a7;
|
||||
border-bottom: 2px solid #ffc568;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.step > .actions {
|
||||
padding: 0 14px;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.step > small {
|
||||
display: block;
|
||||
padding: 0 14px 12px;
|
||||
}
|
||||
.error {
|
||||
color: #ff9d9d;
|
||||
}
|
||||
.step > .error {
|
||||
padding: 0 14px;
|
||||
}
|
||||
.result {
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 14px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.result pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
max-height: 330px;
|
||||
overflow: auto;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.stderr {
|
||||
color: #ff9d9d;
|
||||
}
|
||||
.success {
|
||||
border-color: #38765f;
|
||||
}
|
||||
.failure {
|
||||
border-color: #914e56;
|
||||
}
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
.artifact {
|
||||
display: inline-block;
|
||||
margin: 6px 15px 0 0;
|
||||
}
|
||||
.after {
|
||||
border-left: 3px solid var(--accent);
|
||||
padding-left: 18px;
|
||||
}
|
||||
.banner {
|
||||
padding: 14px 24px;
|
||||
background: var(--panel);
|
||||
}
|
||||
.banner button {
|
||||
margin-left: 12px;
|
||||
}
|
||||
.terminal {
|
||||
border-left: 1px solid var(--line);
|
||||
padding: 20px;
|
||||
background: var(--code);
|
||||
}
|
||||
.terminal h2 {
|
||||
font-size: 15px;
|
||||
}
|
||||
.terminal p,
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.editor {
|
||||
border: 1px solid var(--line);
|
||||
font-size: 13px;
|
||||
background: var(--code);
|
||||
}
|
||||
.cm-editor {
|
||||
min-height: 280px;
|
||||
}
|
||||
.cm-scroller {
|
||||
max-height: 480px;
|
||||
}
|
||||
.cm-gutters {
|
||||
background: var(--panel) !important;
|
||||
color: var(--muted) !important;
|
||||
border-color: var(--line) !important;
|
||||
}
|
||||
.cm-activeLine {
|
||||
background: #8881 !important;
|
||||
}
|
||||
.cm-cursor {
|
||||
border-left-color: var(--accent) !important;
|
||||
}
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: #000a;
|
||||
z-index: 10;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.modal-backdrop section {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 24px;
|
||||
max-width: 600px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.modal-backdrop h2 {
|
||||
font-size: 20px;
|
||||
}
|
||||
.modal-backdrop button {
|
||||
margin: 12px 8px 0 0;
|
||||
}
|
||||
.login {
|
||||
max-width: 360px;
|
||||
margin: 15vh auto;
|
||||
padding: 20px;
|
||||
}
|
||||
.login input {
|
||||
margin: 10px 0 16px;
|
||||
}
|
||||
.login button {
|
||||
width: 100%;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color-scheme: light;
|
||||
color: #233244;
|
||||
background: #fafbfc;
|
||||
--panel: #f0f3f6;
|
||||
--line: #cbd4df;
|
||||
--muted: #57687d;
|
||||
--accent: #197b59;
|
||||
--code: #fff;
|
||||
}
|
||||
.error,
|
||||
.stderr {
|
||||
color: #b42738;
|
||||
}
|
||||
.hljs-built_in,
|
||||
.hljs-string,
|
||||
.hljs-attr {
|
||||
color: #13654a;
|
||||
}
|
||||
.hljs-keyword,
|
||||
.hljs-variable {
|
||||
color: #8f3d8b;
|
||||
}
|
||||
button.primary {
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.app,
|
||||
.with-terminal {
|
||||
grid-template-columns: 170px minmax(0, 1fr);
|
||||
}
|
||||
.terminal {
|
||||
grid-column: 2;
|
||||
}
|
||||
.notebook {
|
||||
padding: 16px;
|
||||
}
|
||||
.params {
|
||||
padding: 12px;
|
||||
}
|
||||
.toolbar {
|
||||
padding: 10px;
|
||||
}
|
||||
.target {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
@media (max-width: 580px) {
|
||||
.app,
|
||||
.with-terminal {
|
||||
display: block;
|
||||
}
|
||||
.sidebar {
|
||||
height: auto;
|
||||
position: static;
|
||||
padding: 12px;
|
||||
}
|
||||
.sidebar h1 {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.sidebar nav button {
|
||||
padding: 8px;
|
||||
}
|
||||
.connection {
|
||||
display: none !important;
|
||||
}
|
||||
.params {
|
||||
position: static;
|
||||
}
|
||||
.toolbar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.toolbar > span {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.step .actions button {
|
||||
font-size: 12px;
|
||||
}
|
||||
.terminal {
|
||||
min-height: 200px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
vi.mock("@shellbook/core", () => import("../mock/core"));
|
||||
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 { App } from "../App";
|
||||
import { HttpError } from "../api";
|
||||
import type { Api } from "../api";
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
import { parseNotebook } from "../mock/core";
|
||||
import source from "../mock/ssh-key.md?raw";
|
||||
|
||||
function harness() {
|
||||
let receive: (event: ServerEvent) => void = () => {};
|
||||
let id = 0;
|
||||
const api: Api = {
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn().mockResolvedValue(undefined),
|
||||
list: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
|
||||
}),
|
||||
hosts: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
hosts: [
|
||||
{
|
||||
name: "staging",
|
||||
user: "admin",
|
||||
address: "example.test",
|
||||
port: 22,
|
||||
tags: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
notebook: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
path: "ssh-key.md",
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
version: "1",
|
||||
}),
|
||||
save: vi.fn().mockResolvedValue({ version: "2" }),
|
||||
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
|
||||
events: (callback, connected) => {
|
||||
receive = callback;
|
||||
connected(true);
|
||||
return () => {};
|
||||
},
|
||||
artifact: () => "/download",
|
||||
};
|
||||
return { api, emit: (event: ServerEvent) => act(() => receive(event)) };
|
||||
}
|
||||
async function ready(api: Api) {
|
||||
render(<App api={api} />);
|
||||
fireEvent.change(await screen.findByLabelText("Target server *"), {
|
||||
target: { value: "staging" },
|
||||
});
|
||||
}
|
||||
it("shows login on 401 and sends the password only to login", async () => {
|
||||
const { api } = harness();
|
||||
vi.mocked(api.me).mockRejectedValue(new HttpError(401));
|
||||
render(<App api={api} />);
|
||||
fireEvent.change(await screen.findByLabelText("Password"), {
|
||||
target: { value: "login-secret" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign in" }));
|
||||
await screen.findByLabelText("Target server *");
|
||||
expect(api.login).toHaveBeenCalledWith("login-secret");
|
||||
expect(document.body.textContent).not.toContain("login-secret");
|
||||
});
|
||||
it("runs all checks and summarizes their streamed results", async () => {
|
||||
const { api, emit } = harness();
|
||||
await ready(api);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Run all checks" }));
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(2));
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "1",
|
||||
exitCode: 0,
|
||||
durationMs: 20,
|
||||
artifacts: [],
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "2",
|
||||
exitCode: 1,
|
||||
durationMs: 20,
|
||||
artifacts: [],
|
||||
});
|
||||
expect(screen.getByText(/1 \/ 2/)).toHaveTextContent("❌ 1");
|
||||
});
|
||||
it("reveals after sections only on success and passes artifact provenance", async () => {
|
||||
const { api, emit } = harness();
|
||||
await ready(api);
|
||||
expect(
|
||||
screen.queryByText(/Download the private key/),
|
||||
).not.toBeInTheDocument();
|
||||
fireEvent.click(
|
||||
within(
|
||||
screen.getByRole("article", { name: "Generate key pair" }),
|
||||
).getByRole("button", { name: "Run" }),
|
||||
);
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(1));
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "1",
|
||||
exitCode: 0,
|
||||
durationMs: 30,
|
||||
artifacts: ["key.pub"],
|
||||
captured: { name: "captured", value: "value" },
|
||||
});
|
||||
expect(screen.getByText(/Download the private key/)).toBeInTheDocument();
|
||||
fireEvent.click(
|
||||
within(screen.getByRole("article", { name: "Authorize key" })).getByRole(
|
||||
"button",
|
||||
{ name: "Run" },
|
||||
),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm and run" }));
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(2));
|
||||
expect(vi.mocked(api.run).mock.calls[1]?.[0]).toMatchObject({
|
||||
runtime: { captured: "value" },
|
||||
artifactSources: { "key.pub": "1" },
|
||||
});
|
||||
emit({
|
||||
type: "run.hostKeyUnknown",
|
||||
runId: "2",
|
||||
host: "staging",
|
||||
fingerprint: "SHA256:test",
|
||||
changed: true,
|
||||
});
|
||||
expect(screen.getByRole("dialog")).toHaveTextContent("HOST KEY CHANGED");
|
||||
fireEvent.click(
|
||||
screen.getByRole("button", { name: "Trust this fingerprint and retry" }),
|
||||
);
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(3));
|
||||
expect(vi.mocked(api.run).mock.calls[2]?.[0].acceptHostKey).toBe(
|
||||
"SHA256:test",
|
||||
);
|
||||
});
|
||||
it("sends baseVersion and retains draft on conflict; file events preserve dirty edits", async () => {
|
||||
const { api, emit } = harness();
|
||||
vi.mocked(api.save).mockRejectedValue(new HttpError(409));
|
||||
await ready(api);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit Markdown" }));
|
||||
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), {
|
||||
target: { value: source + "\nDraft text\n" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await screen.findByText(/The file changed on disk/);
|
||||
expect(api.save).toHaveBeenCalledWith(
|
||||
"ssh-key.md",
|
||||
source + "\nDraft text\n",
|
||||
"1",
|
||||
);
|
||||
emit({ type: "file.changed", path: "ssh-key.md" });
|
||||
expect(api.notebook).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByLabelText("Notebook Markdown")).toHaveValue(
|
||||
source + "\nDraft text\n",
|
||||
);
|
||||
});
|
||||
it("reloads the open notebook on clean file changes", async () => {
|
||||
const { api, emit } = harness();
|
||||
await ready(api);
|
||||
emit({ type: "file.changed", path: "ssh-key.md" });
|
||||
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
it("retains edits made while a file reload is in flight", async () => {
|
||||
const { api, emit } = harness();
|
||||
await ready(api);
|
||||
let finish!: (value: Awaited<ReturnType<Api["notebook"]>>) => void;
|
||||
vi.mocked(api.notebook).mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
emit({ type: "file.changed", path: "ssh-key.md" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit Markdown" }));
|
||||
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), {
|
||||
target: { value: source + "\nIn-flight draft\n" },
|
||||
});
|
||||
await act(async () =>
|
||||
finish({
|
||||
path: "ssh-key.md",
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
version: "2",
|
||||
}),
|
||||
);
|
||||
expect(screen.getByLabelText("Notebook Markdown")).toHaveValue(
|
||||
source + "\nIn-flight draft\n",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
vi.mock("@shellbook/core", () => import("../mock/core"));
|
||||
import { ParamsForm } from "../ParamsForm";
|
||||
import { StepCard } from "../StepCard";
|
||||
import type { Notebook, RenderedStep, Step } from "@shellbook/core";
|
||||
const notebook: Notebook = {
|
||||
title: "Test",
|
||||
params: [
|
||||
{ name: "host", type: "host", required: true },
|
||||
{
|
||||
name: "mode",
|
||||
type: "choice",
|
||||
required: false,
|
||||
options: ["safe", "fast"],
|
||||
},
|
||||
{ name: "token", type: "secret", required: true },
|
||||
],
|
||||
blocks: [],
|
||||
diagnostics: [],
|
||||
};
|
||||
const host = {
|
||||
name: "staging",
|
||||
user: "ops",
|
||||
address: "example.test",
|
||||
port: 22,
|
||||
tags: [],
|
||||
};
|
||||
const step: Step = {
|
||||
kind: "check",
|
||||
lang: "sh",
|
||||
script: "id {{user}}",
|
||||
range: { startLine: 1, endLine: 3 },
|
||||
attrs: {
|
||||
id: "id",
|
||||
local: false,
|
||||
sudo: false,
|
||||
confirm: false,
|
||||
artifacts: [],
|
||||
uploads: [],
|
||||
timeoutSec: 30,
|
||||
},
|
||||
};
|
||||
const rendered: RenderedStep = {
|
||||
stepId: "id",
|
||||
kind: "check",
|
||||
local: false,
|
||||
host: "staging",
|
||||
script: "id admin",
|
||||
artifacts: [],
|
||||
uploads: [],
|
||||
missing: [],
|
||||
invalid: {},
|
||||
};
|
||||
describe("parameter form", () => {
|
||||
it("renders inventory and choices, reports required and validation errors", () => {
|
||||
const change = vi.fn();
|
||||
render(
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={{}}
|
||||
errors={{ host: "Required" }}
|
||||
hosts={[host]}
|
||||
onChange={change}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByLabelText("host *")).toBeRequired();
|
||||
expect(screen.getByLabelText("host *")).toHaveAttribute(
|
||||
"aria-invalid",
|
||||
"true",
|
||||
);
|
||||
fireEvent.change(screen.getByLabelText("host *"), {
|
||||
target: { value: "staging" },
|
||||
});
|
||||
expect(change).toHaveBeenCalledWith("host", "staging");
|
||||
fireEvent.change(screen.getByLabelText("mode"), {
|
||||
target: { value: "safe" },
|
||||
});
|
||||
expect(change).toHaveBeenCalledWith("mode", "safe");
|
||||
});
|
||||
it("keeps secrets in a password field", () => {
|
||||
const { container } = render(
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={{ token: "sensitive" }}
|
||||
errors={{}}
|
||||
hosts={[]}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByLabelText("token *")).toHaveAttribute(
|
||||
"type",
|
||||
"password",
|
||||
);
|
||||
expect(container.textContent).not.toContain("sensitive");
|
||||
});
|
||||
});
|
||||
describe("step card", () => {
|
||||
const props = {
|
||||
step,
|
||||
rendered,
|
||||
host,
|
||||
onRun: vi.fn(),
|
||||
artifact: () => "/download",
|
||||
};
|
||||
it("highlights missing templates and disables execution", () => {
|
||||
render(
|
||||
<StepCard
|
||||
{...props}
|
||||
rendered={{ ...rendered, script: "id {{user}}", missing: ["user"] }}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Check" })).toBeDisabled();
|
||||
expect(screen.getByText("{{user}}").tagName).toBe("MARK");
|
||||
});
|
||||
it("disables invalid params", () => {
|
||||
render(
|
||||
<StepCard
|
||||
{...props}
|
||||
rendered={{ ...rendered, invalid: { user: "Invalid" } }}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Check" })).toBeDisabled();
|
||||
});
|
||||
it("runs a ready step", () => {
|
||||
render(<StepCard {...props} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Check" }));
|
||||
expect(props.onRun).toHaveBeenCalled();
|
||||
});
|
||||
it.each(["running", "success", "failure"] as const)(
|
||||
"shows %s state",
|
||||
(status) => {
|
||||
render(
|
||||
<StepCard
|
||||
{...props}
|
||||
run={{
|
||||
runId: "1",
|
||||
notebookPath: "n",
|
||||
stepId: "id",
|
||||
status,
|
||||
output: [{ stream: "stdout", data: "hello" }],
|
||||
artifacts: ["key.pub"],
|
||||
...(status !== "running"
|
||||
? { exitCode: status === "success" ? 0 : 1, durationMs: 1234 }
|
||||
: {}),
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("hello")).toBeInTheDocument();
|
||||
expect(screen.getByText("↓ key.pub")).toHaveAttribute(
|
||||
"href",
|
||||
"/download",
|
||||
);
|
||||
if (status === "running")
|
||||
expect(screen.getByRole("button", { name: "Running…" })).toBeDisabled();
|
||||
else
|
||||
expect(
|
||||
screen.getByText(
|
||||
status === "success"
|
||||
? /✅ Succeeded.*exit 0.*1.23s/
|
||||
: /❌ Failed.*exit 1.*1.23s/,
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
it("copies exactly the displayed script", async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: { writeText },
|
||||
});
|
||||
render(<StepCard {...props} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
expect(writeText).toHaveBeenCalledWith(rendered.script);
|
||||
await screen.findByText("Copied");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { emptySession, eventReducer, stepKey } from "../events";
|
||||
const started = {
|
||||
type: "run.started" as const,
|
||||
runId: "1",
|
||||
notebookPath: "n.md",
|
||||
stepId: "keygen",
|
||||
script: "secret-free script",
|
||||
};
|
||||
describe("event reducer", () => {
|
||||
it("tracks execution and ordered stdout/stderr, without storing the script", () => {
|
||||
let state = eventReducer(emptySession, started);
|
||||
state = eventReducer(state, {
|
||||
type: "run.output",
|
||||
runId: "1",
|
||||
stream: "stdout",
|
||||
data: "a",
|
||||
});
|
||||
state = eventReducer(state, {
|
||||
type: "run.output",
|
||||
runId: "1",
|
||||
stream: "stderr",
|
||||
data: "b",
|
||||
});
|
||||
expect(state.runs["1"]?.output.map((c) => c.data).join("")).toBe("ab");
|
||||
expect(JSON.stringify(state)).not.toContain(started.script);
|
||||
});
|
||||
it("captures successful values and artifact provenance by notebook", () => {
|
||||
const state = eventReducer(eventReducer(emptySession, started), {
|
||||
type: "run.finished",
|
||||
runId: "1",
|
||||
exitCode: 0,
|
||||
durationMs: 12,
|
||||
artifacts: ["key"],
|
||||
captured: { name: "value", value: "result" },
|
||||
});
|
||||
expect(state.runtime["n.md"]).toEqual({ value: "result" });
|
||||
expect(state.artifactSources["n.md"]).toEqual({ key: "1" });
|
||||
expect(state.runs["1"]?.status).toBe("success");
|
||||
});
|
||||
it("does not publish failed captures", () => {
|
||||
const state = eventReducer(eventReducer(emptySession, started), {
|
||||
type: "run.finished",
|
||||
runId: "1",
|
||||
exitCode: 1,
|
||||
durationMs: 12,
|
||||
artifacts: [],
|
||||
captured: { name: "value", value: "bad" },
|
||||
});
|
||||
expect(state.runtime).toEqual({});
|
||||
expect(state.runs["1"]?.status).toBe("failure");
|
||||
});
|
||||
it("preserves events arriving before the POST response", () => {
|
||||
let state = eventReducer(eventReducer(emptySession, started), {
|
||||
type: "run.error",
|
||||
runId: "1",
|
||||
message: "failed",
|
||||
});
|
||||
state = eventReducer(state, {
|
||||
type: "requested",
|
||||
runId: "1",
|
||||
request: {
|
||||
notebookPath: "n.md",
|
||||
stepId: "keygen",
|
||||
params: { secret: "not retained" },
|
||||
runtime: {},
|
||||
artifactSources: {},
|
||||
},
|
||||
});
|
||||
expect(state.runs["1"]?.status).toBe("failure");
|
||||
expect(JSON.stringify(state)).not.toContain("not retained");
|
||||
});
|
||||
it("records changed host keys for explicit confirmation", () => {
|
||||
const state = eventReducer(eventReducer(emptySession, started), {
|
||||
type: "run.hostKeyUnknown",
|
||||
runId: "1",
|
||||
host: "prod",
|
||||
fingerprint: "SHA256:x",
|
||||
changed: true,
|
||||
});
|
||||
expect(state.runs["1"]?.hostKey?.changed).toBe(true);
|
||||
expect(state.runs["1"]?.status).toBe("hostKey");
|
||||
});
|
||||
it("isolates same step IDs across notebooks", () => {
|
||||
const state = eventReducer(eventReducer(emptySession, started), {
|
||||
...started,
|
||||
runId: "2",
|
||||
notebookPath: "other.md",
|
||||
});
|
||||
expect(state.latest[stepKey("n.md", "keygen")]).toBe("1");
|
||||
expect(state.latest[stepKey("other.md", "keygen")]).toBe("2");
|
||||
});
|
||||
it("ignores unknown run and file events", () => {
|
||||
expect(
|
||||
eventReducer(emptySession, {
|
||||
type: "run.error",
|
||||
runId: "unknown",
|
||||
message: "error",
|
||||
}),
|
||||
).toBe(emptySession);
|
||||
expect(
|
||||
eventReducer(emptySession, { type: "file.changed", path: "n.md" }),
|
||||
).toBe(emptySession);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
afterEach(cleanup);
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
vi.mock("@shellbook/core", () => import("../mock/core"));
|
||||
import { sshCommand } from "../ssh";
|
||||
const host = {
|
||||
name: "test",
|
||||
address: "example.test",
|
||||
user: "ops",
|
||||
port: 2222,
|
||||
tags: [],
|
||||
};
|
||||
describe("SSH copy transport", () => {
|
||||
it("preserves the literal script and uses strict bash flags", () =>
|
||||
expect(sshCommand(host, 'printf "%s" "$HOME"')).toBe(
|
||||
`ssh -p 2222 -- [email protected] 'bash -euo pipefail -s' <<'EOF'\nprintf "%s" "$HOME"\nEOF`,
|
||||
));
|
||||
it("avoids heredoc delimiter collisions", () =>
|
||||
expect(sshCommand(host, "cat\nEOF\nEOF_\n")).toContain(
|
||||
"<<'EOF__'\ncat\nEOF\nEOF_\nEOF__",
|
||||
));
|
||||
it("quotes destination via core and supports sudo", () =>
|
||||
expect(sshCommand({ ...host, user: "o'ps" }, "id", true)).toContain(
|
||||
"'o'\\''[email protected]' 'sudo -n bash -euo pipefail -s'",
|
||||
));
|
||||
it.each([0, 65536, 1.5])("rejects invalid port %s", (port) =>
|
||||
expect(() => sshCommand({ ...host, port }, "id")).toThrow(),
|
||||
);
|
||||
it("rejects newline destinations", () =>
|
||||
expect(() => sshCommand({ ...host, address: "x\ny" }, "id")).toThrow());
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"types": ["vite/client", "vitest/globals", "@testing-library/jest-dom"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineConfig, loadEnv } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const mock =
|
||||
loadEnv(mode, process.cwd(), "").VITE_MOCK === "1" ||
|
||||
process.env.VITE_MOCK === "1";
|
||||
return {
|
||||
plugins: [react()],
|
||||
build: { target: "es2022" },
|
||||
// TEMPORARY: delete this alias and src/mock/core.ts once M0 lands.
|
||||
resolve: {
|
||||
alias: mock
|
||||
? [
|
||||
{
|
||||
find: /^@shellbook\/core$/,
|
||||
replacement: fileURLToPath(
|
||||
new URL("./src/mock/core.ts", import.meta.url),
|
||||
),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
server: {
|
||||
proxy: { "/api": { target: "http://127.0.0.1:8080", ws: true } },
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
import react from "@vitejs/plugin-react";
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: { environment: "jsdom", setupFiles: ["./src/tests/setup.ts"] },
|
||||
});
|
||||
Generated
+2017
-2
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user