Compare commits

...
4 Commits
Author SHA1 Message Date
Florian Schmidt dd0af5d580 docs(mind): record web UI shell (#12) 2026-11-16 12:32:01 +01:00
Florian Schmidt e38f9c453c feat(web): rework layout and quality of life (#12)
- App shell: top bar with connection state and Chat/Terminal toggles,
  per-column scrolling, sidebar only on the Notebooks page.
- Hash routes (#/notebooks/<path>, #/hosts, #/settings) so reloads and
  links keep the open notebook and page.
- Parameters sit beside the notebook on wide screens, collapsible, with
  missing-count summary and Reset; non-secret values are remembered per
  notebook in localStorage (secrets and undeclared names never stored).
- Sticky notebook header with breadcrumbs, check summary and run-all;
  Ctrl/Cmd+S saves the Markdown draft.
- Step cards show target, one deduplicated hint for missing values and
  copy feedback.
- Shared Dialog, Menu and CopyButton components; notebook and host
  actions move into menus and modal dialogs.
- Hosts page as a compact list; Settings split into cards with sign out
  for this browser.
2026-11-16 12:32:01 +01:00
Florian Schmidt 16cfcd36ea fix(templates): avoid template syntax in LXC prose (#12)
The literal {{ct.host}} in prose was composed into {{ct.ct.host}} when the
notebook is included; describe the capture in words instead.
2026-11-16 12:31:54 +01:00
Florian Schmidt 382da1736f fix(core): keep unset values visible in prose (#12)
renderText now leaves {{name}} in place when the value is empty, so prose
shows which parameter is still missing instead of a blank.
2026-11-16 12:31:54 +01:00
25 changed files with 2305 additions and 1134 deletions
+1
View File
@@ -14,5 +14,6 @@
- [2026-11-16] **Deploy/update:** host one-liner `bootstrap.sh` (temp dir, nothing left on host); `install.sh` is install-or-update; root-owned `shellbook-update` fetches the installer over HTTPS because root must never run code from the service-user-writable `/opt/shellbook`. - [2026-11-16] **Deploy/update:** host one-liner `bootstrap.sh` (temp dir, nothing left on host); `install.sh` is install-or-update; root-owned `shellbook-update` fetches the installer over HTTPS because root must never run code from the service-user-writable `/opt/shellbook`.
- [2026-11-16] **Chained notebooks (#11):** `::use` is flattened in core (`composeNotebook`): alias-prefixed params/ids/captures with `scope`, so render/run keep one notebook model and one substitution path. Server loads files and injects builtins (`shellbook.*`, server-only); `:::when` gates display and execution; `::host` adds to Hosts via the host-management API. Required params/secrets gate only their own scope, identically in core render and server `prepareRun`. - [2026-11-16] **Chained notebooks (#11):** `::use` is flattened in core (`composeNotebook`): alias-prefixed params/ids/captures with `scope`, so render/run keep one notebook model and one substitution path. Server loads files and injects builtins (`shellbook.*`, server-only); `:::when` gates display and execution; `::host` adds to Hosts via the host-management API. Required params/secrets gate only their own scope, identically in core render and server `prepareRun`.
- [2026-11-16] **Template delivery:** `install.sh` offers each shipped notebook template once (`/etc/shellbook/templates-offered`), copied as the service user, never overwriting or restoring deleted files. - [2026-11-16] **Template delivery:** `install.sh` offers each shipped notebook template once (`/etc/shellbook/templates-offered`), copied as the service user, never overwriting or restoring deleted files.
- [2026-11-16] **Web UI shell (#12):** top bar (tabs, live state, Chat/Terminal), notebook sidebar only on Notebooks, parameter panel beside the notebook via a container query (above it when narrow), dialogs/menus from `ui.tsx`. Page and notebook live in the URL hash (`route.ts`); typed non-secret values are remembered per notebook in localStorage (`paramMemory.ts`, secrets and undeclared names are dropped on read and write).
## Archive ## Archive
+2 -2
View File
@@ -2,7 +2,7 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change. > Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus ## Current Focus
- [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) closed. - [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) and the UI/UX overhaul (#12) closed.
- [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH. - [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH.
## Invariants ## Invariants
@@ -15,7 +15,7 @@
- Everything doable from the web UI; files are storage, not the only way in. - Everything doable from the web UI; files are storage, not the only way in.
## Table of Contents ## Table of Contents
- `architecture.md` — 13 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery - `architecture.md` — 14 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell
- `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped - `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped
- `open.md` — 2 entries — open design questions (sudo password, chat history) - `open.md` — 2 entries — open design questions (sudo password, chat history)
- `gotchas.md` — 15 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture-default deadlock, heredocs) - `gotchas.md` — 15 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture-default deadlock, heredocs)
+292 -182
View File
@@ -42,6 +42,9 @@ import { ParamsForm, type ParamGroup } from "./ParamsForm";
import { HostBlockCard } from "./HostBlockCard"; import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard"; import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel"; import { ChatPanel } from "./ChatPanel";
import { parseRoute, routeHash } from "./route";
import { recallValues, rememberValues } from "./paramMemory";
import { Dialog } from "./ui";
const TerminalSlot = lazy(() => const TerminalSlot = lazy(() =>
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })), import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
); );
@@ -68,11 +71,16 @@ function includedGroups(blocks: Block[]): ParamGroup[] {
: [], : [],
); );
} }
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
function setValuesOnly(values: ParamValues): ParamValues {
return Object.fromEntries(Object.entries(values).filter(([, value]) => value));
}
export function App({ api }: { api: Api }) { export function App({ api }: { api: Api }) {
const initialRoute = useRef(parseRoute(location.hash));
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading"); const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
const [page, setPage] = useState<NavigationPage>("Notebooks"); const [page, setPage] = useState<NavigationPage>(initialRoute.current.page);
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]); const [list, setList] = useState<NotebookSummary[]>();
const [hosts, setHosts] = useState<HostInfo[]>([]); const [hosts, setHosts] = useState<HostInfo[]>([]);
const [doc, setDoc] = useState<NotebookResponse>(); const [doc, setDoc] = useState<NotebookResponse>();
const [source, setSource] = useState(""); const [source, setSource] = useState("");
@@ -113,7 +121,7 @@ export function App({ api }: { api: Api }) {
setConflict(false); setConflict(false);
setError(""); setError("");
if (!same) { if (!same) {
setValues({}); setValues(recallValues(path, next.notebook));
setEdit(false); setEdit(false);
setCheckIds([]); setCheckIds([]);
} }
@@ -123,6 +131,7 @@ export function App({ api }: { api: Api }) {
}, },
[api], [api],
); );
const leave = () => !current.current.dirty || window.confirm("Discard unsaved edits?");
useEffect(() => { useEffect(() => {
void api void api
.me() .me()
@@ -144,7 +153,10 @@ export function App({ api }: { api: Api }) {
if (!active) return; if (!active) return;
setList(notebooks.notebooks); setList(notebooks.notebooks);
setHosts(inventory.hosts); setHosts(inventory.hosts);
if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path); // Open the notebook from the URL, else the first one.
const wanted = initialRoute.current.notebook;
const first = notebooks.notebooks.find((n) => n.path === wanted) ?? notebooks.notebooks[0];
if (first) void load(first.path);
}) })
.catch((e) => setError(String(e))); .catch((e) => setError(String(e)));
const close = api.events((event: ServerEvent) => { const close = api.events((event: ServerEvent) => {
@@ -190,6 +202,25 @@ export function App({ api }: { api: Api }) {
window.addEventListener("beforeunload", guard); window.addEventListener("beforeunload", guard);
return () => window.removeEventListener("beforeunload", guard); return () => window.removeEventListener("beforeunload", guard);
}, [dirty]); }, [dirty]);
// Keep the page and notebook in the URL; back/forward navigate between them.
useEffect(() => {
if (auth !== "ready") return;
// Until the first notebook is open, keep the requested one in the URL.
if (page === "Notebooks" && !doc && list === undefined) return;
const hash = routeHash({ page, notebook: doc?.path });
if (location.hash === hash) return;
if (location.hash) history.pushState(null, "", hash);
else history.replaceState(null, "", hash);
}, [auth, page, doc, list]);
useEffect(() => {
const follow = () => {
const route = parseRoute(location.hash);
setPage(route.page);
if (route.notebook && route.notebook !== current.current.doc?.path && leave()) void load(route.notebook);
};
window.addEventListener("hashchange", follow);
return () => window.removeEventListener("hashchange", follow);
}, [load]);
// The saved notebook comes composed from the server; a draft shows its includes after saving. // The saved notebook comes composed from the server; a draft shows its includes after saving.
const notebook = doc const notebook = doc
@@ -218,6 +249,10 @@ export function App({ api }: { api: Api }) {
}; };
const runFor = (id: string) => const runFor = (id: string) =>
session.runs[session.latest[stepKey(path, id)] ?? ""]; session.runs[session.latest[stepKey(path, id)] ?? ""];
function changeValues(next: ParamValues) {
setValues(next);
if (doc) rememberValues(doc.path, doc.notebook, next);
}
async function start(request: StartRunRequest) { async function start(request: StartRunRequest) {
const key = stepKey(request.notebookPath, request.stepId); const key = stepKey(request.notebookPath, request.stepId);
setPending((previous) => new Set(previous).add(key)); setPending((previous) => new Set(previous).add(key));
@@ -274,7 +309,7 @@ export function App({ api }: { api: Api }) {
<ReactMarkdown> <ReactMarkdown>
{renderText( {renderText(
block.text, block.text,
{ ...runtime, ...resolved.values }, setValuesOnly({ ...runtime, ...resolved.values }),
notebook, notebook,
)} )}
</ReactMarkdown> </ReactMarkdown>
@@ -360,6 +395,8 @@ export function App({ api }: { api: Api }) {
); );
}); });
} }
const canSave =
dirty && !conflict && !notebook?.diagnostics.some((d) => d.severity === "error");
async function save() { async function save() {
if (!doc) return; if (!doc) return;
try { try {
@@ -379,15 +416,44 @@ export function App({ api }: { api: Api }) {
else setError(String(e)); else setError(String(e));
} }
} }
// Ctrl/Cmd+S saves the open draft.
const saveRef = useRef(save);
saveRef.current = save;
const canSaveRef = useRef(canSave);
canSaveRef.current = canSave && edit;
useEffect(() => {
const key = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s" && canSaveRef.current) {
e.preventDefault();
void saveRef.current();
}
};
window.addEventListener("keydown", key);
return () => window.removeEventListener("keydown", key);
}, []);
const keyPrompt = Object.values(session.runs).find( const keyPrompt = Object.values(session.runs).find(
(run) => run.status === "hostKey" && requests.current.has(run.runId), (run) => run.status === "hostKey" && requests.current.has(run.runId),
); );
const checksBusy = notebook
? steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
: false;
const openTerminal = () => {
setTerminalOpened(true);
setChat(false);
setTerminal(true);
};
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />; if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login") if (auth === "login")
return ( return (
<main className="login"> <main className="login">
<h1>ShellBook</h1> <h1>
<p>Sign in to your workspace</p> ShellBook<span>RUNBOOKS</span>
</h1>
<p className="muted">Sign in to your workspace</p>
<form <form
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
@@ -417,193 +483,237 @@ export function App({ api }: { api: Api }) {
</label> </label>
<button className="primary">Sign in</button> <button className="primary">Sign in</button>
</form> </form>
{error && <p role="alert">{error}</p>} {error && <p role="alert" className="error">{error}</p>}
</main> </main>
); );
return ( return (
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}> <div className="app">
<aside className="sidebar"> <header className="topbar">
<h1> <span className="brand">
ShellBook<span>RUNBOOKS</span> ShellBook
</h1> {import.meta.env.VITE_MOCK === "1" && <span className="chip">demo</span>}
<NotebookList </span>
api={api}
list={list}
path={path}
version={doc?.version}
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
onSelect={(next) => {
if (!dirty || window.confirm("Discard unsaved edits?"))
void load(next);
}}
onChanged={async (next) => {
const result = await api.list();
setList(result.notebooks);
if (next) await load(next);
else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}}
/>
<small className="connection">
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
{connected
? "● Events connected"
: "○ Events disconnected · reload to reconnect"}
</small>
</aside>
<main>
<HeaderNavigation page={page} onChange={setPage} /> <HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />} <span className="spacer" />
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />} <span
<div hidden={page !== "Notebooks"}> className={`connection ${connected ? "ok" : "bad"}`}
<div className="toolbar"> title={connected ? "Live updates connected" : "Live updates disconnected; reload to reconnect"}
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button> >
<span>{doc?.notebook.title ?? "Loading workspace…"}</span> {connected ? "Live" : "Offline · reload"}
<button onClick={() => setEdit(!edit)}> </span>
{edit ? "Close editor" : "Edit Markdown"} <button
</button> aria-expanded={chat}
<button className={chat ? "toggled" : ""}
aria-expanded={terminal} onClick={() => {
onClick={() => { setChat(!chat);
setTerminalOpened(true); setTerminal(false);
setChat(false); }}
setTerminal(!terminal); >
}} Chat
> </button>
Terminal {terminal ? "→" : "←"} <button
</button> aria-expanded={terminal}
</div> className={terminal ? "toggled" : ""}
{error && ( onClick={() => {
<p className="banner error" role="alert"> if (terminal) setTerminal(false);
{error} else openTerminal();
<button onClick={() => location.reload()}>Retry</button> }}
</p> >
)} Terminal
{conflict && ( </button>
<div className="banner error" role="alert"> </header>
The file changed on disk. Your draft has been retained. <div className="workspace">
<button {page === "Notebooks" && (
onClick={() => { <aside className="sidebar" aria-label="Notebook list">
if (!dirty || window.confirm("Discard your draft and reload?")) <NotebookList
void load(path); api={api}
list={list ?? []}
path={path}
version={doc?.version}
canLeave={leave}
onSelect={(next) => {
if (next !== path && leave()) void load(next);
}}
onChanged={async (next) => {
const result = await api.list();
setList(result.notebooks);
if (next) await load(next);
else {
++loadSequence.current;
setDoc(undefined);
setSource("");
setConflict(false);
}
}} }}
>
Reload from disk
</button>
</div>
)}
{notebook && (
<>
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
onChange={(name, value) =>
setValues((previous) => ({ ...previous, [name]: value }))
}
/> />
<div className="notebook"> </aside>
{edit && ( )}
<section> <main className="main">
<div className="actions"> {error && (
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong> <p className="banner error" role="alert">
<button {error}
className="primary" <button onClick={() => location.reload()}>Retry</button>
disabled={ </p>
!dirty || )}
conflict || {page === "Settings" && (
notebook.diagnostics.some((d) => d.severity === "error") <SettingsPage openTerminal={openTerminal} onSignOut={() => setAuth("login")} />
} )}
onClick={() => void save()} {page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
> <div className="notebook-page" hidden={page !== "Notebooks"}>
Save {conflict && (
</button> <div className="banner error" role="alert">
</div> The file changed on disk. Your draft has been retained.
<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 <button
disabled={
!connected ||
dirty ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
steps(notebook.blocks).some(
(s) =>
runFor(s.attrs.id)?.status === "running" ||
pending.has(stepKey(path, s.attrs.id)),
)
}
onClick={() => { onClick={() => {
setCheckIds(activeChecks.map((s) => s.attrs.id)); if (!dirty || window.confirm("Discard your draft and reload?"))
activeChecks.forEach(requestRun); void load(path);
}} }}
> >
Run all checks Reload from disk
</button> </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> </div>
{blocks(notebook.blocks)} )}
</div> {!notebook && (
</> <div className="empty">
{list === undefined
? "Loading workspace…"
: list.length
? "Select a notebook."
: "No notebooks yet. Create one with + in the sidebar, or ask Claude in Chat."}
</div>
)}
{notebook && (
<div className="notebook-layout">
<ParamsForm
notebook={notebook}
values={resolved.values}
errors={resolved.errors}
hosts={hosts}
groups={groups}
onChange={(name, value) => changeValues({ ...values, [name]: value })}
onReset={() => changeValues({})}
/>
<article className="notebook">
<header className="notebook-header">
<span className="crumbs" title={path}>
{path.split("/").map((part, i, parts) => (
<span key={i} className={i === parts.length - 1 ? "file" : ""}>
{part}
</span>
))}
{dirty && <span className="chip warn">unsaved</span>}
</span>
<span className="spacer" />
{checkIds.length > 0 && (
<span role="status" className="check-summary">
✅{" "}
{checkIds.filter((id) => runFor(id)?.status === "success").length}{" "}
/ {checkIds.length} · ❌{" "}
{checkIds.filter((id) => runFor(id)?.status === "failure").length}
</span>
)}
<button
title={
activeChecks.length
? "Runs every check step; checks never change hosts"
: "This notebook has no check steps"
}
disabled={
!connected ||
dirty ||
activeChecks.length === 0 ||
!activeChecks.every(runnable) ||
checksBusy
}
onClick={() => {
setCheckIds(activeChecks.map((s) => s.attrs.id));
activeChecks.forEach(requestRun);
}}
>
Run all checks
</button>
<button
className={edit ? "toggled" : ""}
onClick={() => setEdit(!edit)}
>
{edit ? "Close editor" : "Edit Markdown"}
</button>
</header>
{edit && (
<section className="editor-panel">
<div className="actions">
<strong>Markdown</strong>
<span className="muted">
{dirty ? "Unsaved changes · Ctrl+S saves" : "Saved"}
</span>
<span className="spacer" />
{dirty && (
<button
onClick={() => {
if (window.confirm("Discard your unsaved changes?") && doc) setSource(doc.source);
}}
>
Discard
</button>
)}
<button
className="primary"
disabled={!canSave}
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="banner error" key={i}>
{d.line && `Line ${d.line}: `}
{d.message}
</p>
))}
{blocks(notebook.blocks)}
</article>
</div>
)}
</div>
</main>
{chat && (
<ChatPanel
notebookPath={doc?.path}
openNotebook={(next) => {
if (leave()) {
setPage("Notebooks");
void load(next);
}
}}
openTerminal={openTerminal}
onClose={() => setChat(false)}
/>
)} )}
</div> {terminalOpened && (
</main> <Suspense fallback={<p>Loading terminal…</p>}>
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => { <TerminalSlot collapsed={!terminal} onClose={() => setTerminal(false)} />
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path); </Suspense>
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />} )}
{terminalOpened && ( </div>
<Suspense fallback={<p>Loading terminal...</p>}>
<TerminalSlot collapsed={!terminal} />
</Suspense>
)}
{confirm && ( {confirm && (
<div className="modal-backdrop"> <Dialog title="Confirm execution" onClose={() => setConfirm(undefined)}>
<section <p>
role="dialog" Run “{confirm.stepId}” with the displayed parameters? This step
aria-modal="true" can change the target host.
aria-labelledby="confirm-title" </p>
> <div className="dialog-actions">
<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 onClick={() => setConfirm(undefined)}>Cancel</button>
<button <button
className="primary" className="primary"
@@ -614,8 +724,8 @@ export function App({ api }: { api: Api }) {
> >
Confirm and run Confirm and run
</button> </button>
</section> </div>
</div> </Dialog>
)} )}
{keyPrompt?.hostKey && <HostKeyConfirmation {keyPrompt?.hostKey && <HostKeyConfirmation
{...keyPrompt.hostKey} {...keyPrompt.hostKey}
+11 -6
View File
@@ -12,8 +12,8 @@ const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "ht
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string }; type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
/** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */ /** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: { export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: {
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket; notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket;
}) { }) {
const [history, setHistory] = useState<ChatConversation[]>([]); const [history, setHistory] = useState<ChatConversation[]>([]);
const [selected, setSelected] = useState(""); const [selected, setSelected] = useState("");
@@ -68,10 +68,15 @@ export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect =
setError(""); setLogin(false); setSummary(""); setAllowShell(false); setError(""); setLogin(false); setSummary(""); setAllowShell(false);
} }
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } } function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
return <aside className="chat-panel" aria-label="Chat panel"> return <aside className="chat-panel side-panel" aria-label="Chat panel">
<h2>Chat with Claude</h2> <header className="panel-header">
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button> <h2>Chat with Claude</h2>
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div> <span className="spacer" />
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}
<button disabled={busy} onClick={() => choose("")}>New conversation</button>
{onClose && <button className="icon" aria-label="Close chat" onClick={onClose}>×</button>}
</header>
{notebookPath && <p className="muted">About: <code>{notebookPath}</code></p>}
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}> <label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)} <option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
</select></label> </select></label>
+320 -224
View File
@@ -9,8 +9,15 @@ import type {
import { json } from "./api"; import { json } from "./api";
import "./hosts.css"; import "./hosts.css";
import { HostKeyConfirmation } from "./HostKeyConfirmation"; import { HostKeyConfirmation } from "./HostKeyConfirmation";
import { CopyButton, Dialog, Menu } from "./ui";
const base = "/host-management"; const base = "/host-management";
const url = (name: string) => `${base}/${encodeURIComponent(name)}`; const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
const credentialNames: Record<string, string> = {
shellbook: "ShellBook key",
password: "Password",
privateKey: "Private key",
certificate: "Certificate",
};
const empty: HostInfo = { const empty: HostInfo = {
name: "", name: "",
address: "", address: "",
@@ -23,6 +30,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
const [draft, setDraft] = useState<HostInfo>({ ...empty }); const [draft, setDraft] = useState<HostInfo>({ ...empty });
const [editVersion, setEditVersion] = useState(""); const [editVersion, setEditVersion] = useState("");
const [editing, setEditing] = useState<string>(); const [editing, setEditing] = useState<string>();
/** The add/edit server dialog is open. */
const [form, setForm] = useState(false);
const [credentialHost, setCredentialHost] = useState<string>(); const [credentialHost, setCredentialHost] = useState<string>();
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook"); const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -84,54 +93,101 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
); );
} }
} }
const closeForm = () => {
setForm(false);
setEditing(undefined);
setDraft({ ...empty });
};
const closeCredentials = () => {
setCredentialHost(undefined);
setPassword("");
setPrivateKey("");
setPassphrase("");
};
return ( return (
<section className="hosts-page" aria-label="Server management"> <section className="page hosts-page" aria-label="Server management">
<h1>Servers and SSH credentials</h1> <header className="page-header">
{error && <p role="alert">{error}</p>} <div>
{status && <p role="status">{status}</p>} <h1>Hosts</h1>
<button <p className="muted">
disabled={busy} Servers ShellBook connects to over SSH, and how it signs in.
onClick={() => </p>
void perform(async () => { </div>
await load(); <span className="spacer" />
<button disabled={busy} onClick={() => void perform(load)}>
Reload
</button>
<button
className="primary"
disabled={!inventory}
onClick={() => {
setEditing(undefined); setEditing(undefined);
setDraft({ ...empty }); setDraft({ ...empty });
}) setForm(true);
} }}
> >
Reload hosts Add server
</button> </button>
</header>
{error && !form && !credentialHost && (
<p role="alert" className="banner error">
{error}
</p>
)}
{status && (
<p role="status" className="banner ok">
{status}
</p>
)}
{inventory && ( {inventory && (
<> <>
<h2>ShellBook public key</h2>
<pre>{inventory.publicKey}</pre>
<button
onClick={() =>
void perform(async () => {
await navigator.clipboard.writeText(inventory.publicKey);
setStatus("Public key copied");
})
}
>
Copy public key
</button>
<p>{inventory.certificateSupport.reason}</p>
<div className="host-list"> <div className="host-list">
{!inventory.hosts.length && (
<p className="empty">
No servers yet. Add one, or run a notebook such as
infra/lxc-container.md that adds the machine it creates.
</p>
)}
{inventory.hosts.map((host) => ( {inventory.hosts.map((host) => (
<article key={host.name}> <article key={host.name} className="host-row" aria-label={host.name}>
<h2>{host.name}</h2> <div className="host-main">
<p> <h2>{host.name}</h2>
{host.user}@{host.address}:{host.port} <code>
</p> {host.user}@{host.address}
<p>{host.tags.join(", ")}</p> {host.port === 22 ? "" : `:${host.port}`}
<p> </code>
Authentication: {host.credential.type}{" "} </div>
{host.credential.fingerprint}{" "} <div className="host-meta">
{host.credential.setAt && `set ${host.credential.setAt}`} {host.tags.map((tag) => (
</p> <span key={tag} className={`chip ${tag === "prod" ? "warn" : ""}`}>
{tag}
</span>
))}
<span
className="chip"
title={[
host.credential.fingerprint,
host.credential.setAt && `set ${host.credential.setAt}`,
]
.filter(Boolean)
.join(" · ")}
>
{credentialNames[host.credential.type] ?? host.credential.type}
</span>
</div>
<div className="actions"> <div className="actions">
<button <button
disabled={busy} disabled={busy}
aria-label={`Test connection to ${host.name}`}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test
</button>
<button
disabled={busy}
aria-label={`Edit ${host.name}`}
onClick={() => { onClick={() => {
setEditing(host.name); setEditing(host.name);
setEditVersion(inventory.version); setEditVersion(inventory.version);
@@ -142,12 +198,15 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
port: host.port, port: host.port,
tags: host.tags, tags: host.tags,
}); });
setError("");
setForm(true);
}} }}
> >
Edit {host.name} Edit
</button> </button>
<button <button
disabled={busy} disabled={busy}
aria-label={`SSH credentials for ${host.name}`}
onClick={() => { onClick={() => {
setCredentialHost(host.name); setCredentialHost(host.name);
setType("shellbook"); setType("shellbook");
@@ -156,168 +215,201 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
setPassphrase(""); setPassphrase("");
}} }}
> >
SSH credentials for {host.name} Credentials
</button>
<button
disabled={busy}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test connection to {host.name}
</button>
<button
disabled={busy || host.credential.type !== "password"}
onClick={() =>
void perform(async () => {
const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`,
);
setInstall({ host: host.name, script });
})
}
>
Install ShellBook key on {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
)
)
void perform(async () => {
await json(`${url(host.name)}/known-key`, "DELETE");
setStatus("Host key forgotten");
});
}}
>
Forget host key for {host.name}
</button>
<button
disabled={busy}
onClick={() => {
if (
window.confirm(
`Delete ${host.name} and its stored credential?`,
)
)
void perform(async () => {
await json(url(host.name), "DELETE", {
baseVersion: inventory.version,
});
await load();
onChange?.();
});
}}
>
Delete {host.name}
</button> </button>
<Menu label={`More actions for ${host.name}`}>
{(close) => (
<>
<button
role="menuitem"
disabled={busy || host.credential.type !== "password"}
title={
host.credential.type === "password"
? undefined
: "Needs a saved password"
}
onClick={() => {
close();
void perform(async () => {
const { script } = await json<{ script: string }>(
`${url(host.name)}/install-key`,
);
setInstall({ host: host.name, script });
});
}}
>
Install ShellBook key on {host.name}
</button>
<button
role="menuitem"
disabled={busy}
onClick={() => {
close();
if (
window.confirm(
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
)
)
void perform(async () => {
await json(`${url(host.name)}/known-key`, "DELETE");
setStatus("Host key forgotten");
});
}}
>
Forget host key
</button>
<button
role="menuitem"
className="danger"
disabled={busy}
onClick={() => {
close();
if (
window.confirm(
`Delete ${host.name} and its stored credential?`,
)
)
void perform(async () => {
await json(url(host.name), "DELETE", {
baseVersion: inventory.version,
});
await load();
onChange?.();
});
}}
>
Delete {host.name}
</button>
</>
)}
</Menu>
</div> </div>
</article> </article>
))} ))}
</div> </div>
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2> <details className="card public-key">
<form <summary>ShellBook public key</summary>
onSubmit={(e) => { <p className="muted">
e.preventDefault(); Add it to <code>~/.ssh/authorized_keys</code> on a server, or save
void perform(async () => { the server&apos;s password under Credentials and use “Install
await json( ShellBook key” from its ⋯ menu.
editing ? url(editing) : base, </p>
editing ? "PUT" : "POST", <pre>{inventory.publicKey}</pre>
{ <div className="actions">
host: draft, <CopyButton label="Copy public key" text={() => inventory.publicKey} />
baseVersion: editing ? editVersion : inventory.version, </div>
}, <p className="muted">{inventory.certificateSupport.reason}</p>
); </details>
setEditing(undefined); {form && (
setDraft({ ...empty }); <Dialog
await load(); title={editing ? `Edit ${editing}` : "Add server"}
onChange?.(); onClose={closeForm}
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
value={draft.address}
onChange={(e) =>
setDraft({ ...draft, address: e.target.value })
}
/>
</label>
<label>
SSH user
<input
required
value={draft.user}
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
/>
</label>
<label>
Port
<input
required
type="number"
min="1"
max="65535"
value={draft.port}
onChange={(e) =>
setDraft({ ...draft, port: Number(e.target.value) })
}
/>
</label>
<label>
Tags (comma separated)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
<button disabled={busy}>Save server</button>
<button
type="button"
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
}}
> >
New server <form
</button> className="grid-form"
</form> onSubmit={(e) => {
e.preventDefault();
void perform(async () => {
await json(
editing ? url(editing) : base,
editing ? "PUT" : "POST",
{
host: draft,
baseVersion: editing ? editVersion : inventory.version,
},
);
closeForm();
await load();
onChange?.();
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
placeholder="web-1"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
placeholder="10.0.0.5 or host.example.org"
value={draft.address}
onChange={(e) =>
setDraft({ ...draft, address: e.target.value })
}
/>
</label>
<label>
SSH user
<input
required
value={draft.user}
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
/>
</label>
<label>
Port
<input
required
type="number"
min="1"
max="65535"
value={draft.port}
onChange={(e) =>
setDraft({ ...draft, port: Number(e.target.value) })
}
/>
</label>
<label className="full">
Tags (comma separated; “prod” asks before every run)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
{error && (
<p role="alert" className="error full">
{error}
</p>
)}
<div className="dialog-actions full">
<button type="button" onClick={closeForm}>
Cancel
</button>
<button className="primary" disabled={busy}>
Save server
</button>
</div>
</form>
</Dialog>
)}
</> </>
)} )}
{credentialHost && ( {credentialHost && (
<section <Dialog
role="dialog" title={`SSH credentials for ${credentialHost}`}
aria-modal="true" onClose={closeCredentials}
aria-label={`SSH credentials for ${credentialHost}`}
> >
<h2>SSH credentials for {credentialHost}</h2> <p className="muted">
<p>
Saved secrets cannot be read back. Blank fields do not represent the Saved secrets cannot be read back. Blank fields do not represent the
existing credential. existing credential.
</p> </p>
<form <form
className="stack"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
const credential: HostCredentialInput = const credential: HostCredentialInput =
@@ -372,6 +464,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
Private key Private key
<textarea <textarea
required required
rows={6}
value={privateKey} value={privateKey}
onChange={(e) => setPrivateKey(e.target.value)} onChange={(e) => setPrivateKey(e.target.value)}
/> />
@@ -402,51 +495,54 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
</label> </label>
</> </>
)} )}
<button disabled={busy}>Save authentication</button> {error && (
<button <p role="alert" className="error">
type="button" {error}
onClick={() => { </p>
setCredentialHost(undefined); )}
setPassword(""); <div className="dialog-actions">
setPrivateKey(""); <button type="button" onClick={closeCredentials}>
setPassphrase(""); Cancel
}} </button>
> <button className="primary" disabled={busy}>
Cancel Save authentication
</button> </button>
</div>
</form> </form>
</section> </Dialog>
)} )}
{install && ( {install && (
<section <Dialog
role="dialog" wide
aria-modal="true" title={`Install ShellBook key on ${install.host}`}
aria-label="Install ShellBook key" onClose={() => setInstall(undefined)}
> >
<h2>Install ShellBook key on {install.host}</h2> <p className="muted">
<p>
This exact script runs using the stored password. After success, This exact script runs using the stored password. After success,
select ShellBook key in SSH credentials to remove the saved select ShellBook key in SSH credentials to remove the saved
password. password.
</p> </p>
<pre>{install.script}</pre> <pre className="script">{install.script}</pre>
<button <div className="dialog-actions">
disabled={busy} <button onClick={() => setInstall(undefined)}>
onClick={() => Cancel installation
void perform(() => </button>
action(install.host, { <button
action: "install-key", className="primary"
script: install.script, disabled={busy}
}), onClick={() =>
) void perform(() =>
} action(install.host, {
> action: "install-key",
Run displayed script script: install.script,
</button> }),
<button onClick={() => setInstall(undefined)}> )
Cancel installation }
</button> >
</section> Run displayed script
</button>
</div>
</Dialog>
)} )}
{trust && ( {trust && (
<HostKeyConfirmation <HostKeyConfirmation
+109 -63
View File
@@ -3,6 +3,7 @@ import { useState } from "react";
import type { NotebookSummary } from "@shellbook/core"; import type { NotebookSummary } from "@shellbook/core";
import type { Api } from "./api"; import type { Api } from "./api";
import { newNotebook } from "./authoring"; import { newNotebook } from "./authoring";
import { Dialog, Menu } from "./ui";
type Node = { folders: Map<string, Node>; files: NotebookSummary[] }; type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
function tree(list: NotebookSummary[]): Node { function tree(list: NotebookSummary[]): Node {
const root: Node = { folders: new Map(), files: [] }; const root: Node = { folders: new Map(), files: [] };
@@ -40,6 +41,10 @@ export function NotebookList({
>(); >();
const [error, setError] = useState(""); const [error, setError] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const choose = (op: "rename" | "duplicate" | "delete") => {
setAction(op);
setError("");
};
const render = (node: Node) => ( const render = (node: Node) => (
<> <>
{[...node.folders] {[...node.folders]
@@ -51,67 +56,94 @@ export function NotebookList({
</details> </details>
))} ))}
{node.files.map((item) => ( {node.files.map((item) => (
<button <div
className={item.path === path ? "selected" : ""} className={`notebook-item ${item.path === path ? "selected" : ""}`}
key={item.path} key={item.path}
onClick={() => onSelect(item.path)}
> >
{item.title} <button
<small>{item.path}</small> aria-current={item.path === path ? "page" : undefined}
</button> title={item.path}
onClick={() => onSelect(item.path)}
>
{item.title}
</button>
{item.path === path && (
<Menu label={`Actions for ${item.title}`}>
{(close) =>
(["rename", "duplicate", "delete"] as const).map((op) => (
<button
key={op}
role="menuitem"
className={op === "delete" ? "danger" : ""}
onClick={() => {
close();
choose(op);
}}
>
{op === "rename"
? "Rename / move"
: op === "duplicate"
? "Duplicate"
: "Delete"}
</button>
))
}
</Menu>
)}
</div>
))} ))}
</> </>
); );
const shown = list.filter((n) =>
`${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()),
);
return ( return (
<> <>
<label> <div className="sidebar-tools">
Search notebooks
<input <input
type="search" type="search"
aria-label="Search notebooks"
placeholder="Search notebooks"
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
/> />
</label> <button
<button className="icon"
onClick={() => { aria-label="New notebook"
setAction("new"); title="New notebook"
setError(""); onClick={() => {
}} setAction("new");
> setError("");
New notebook }}
</button> >
+
</button>
</div>
<nav aria-label="Notebooks"> <nav aria-label="Notebooks">
{render( {render(tree(shown))}
tree( {!shown.length && (
list.filter((n) => <p className="muted">
`${n.path} ${n.title}` {list.length ? "No notebook matches." : "No notebooks yet."}
.toLowerCase() </p>
.includes(search.toLowerCase()),
),
),
)} )}
</nav> </nav>
{path && (
<div className="actions">
{(["rename", "duplicate", "delete"] as const).map((op) => (
<button
key={op}
onClick={() => {
setAction(op);
setError("");
}}
>
{op === "rename"
? "Rename / move"
: op === "duplicate"
? "Duplicate"
: "Delete"}
</button>
))}
</div>
)}
{action && ( {action && (
<Dialog
title={
action === "new"
? "New notebook"
: action === "rename"
? "Rename or move notebook"
: action === "duplicate"
? "Duplicate notebook"
: "Delete notebook"
}
onClose={() => {
if (!busy) setAction(undefined);
}}
>
<form <form
className="stack"
key={`${action}:${path}`} key={`${action}:${path}`}
aria-label="Manage notebook" aria-label="Manage notebook"
onSubmit={async (e) => { onSubmit={async (e) => {
@@ -158,18 +190,22 @@ export function NotebookList({
} }
}} }}
> >
<strong> {action === "delete" ? (
{action === "delete" <p>
? `Delete ${path}? This cannot be undone.` Delete <code>{path}</code>? This cannot be undone.
: action === "new" </p>
? "New notebook" ) : (
: `${action} ${path}`} action !== "new" && (
</strong> <p className="muted">
From <code>{path}</code>
</p>
)
)}
{action === "new" ? ( {action === "new" ? (
<> <>
<label> <label>
Name Name
<input name="name" required /> <input name="name" required placeholder="debian-upgrade" />
</label> </label>
<label> <label>
Folder (optional) Folder (optional)
@@ -196,18 +232,28 @@ export function NotebookList({
</label> </label>
) )
)} )}
<button disabled={busy}> {error && (
{action === "delete" ? "Confirm delete" : "Apply"} <p role="alert" className="error">
</button> {error}
<button </p>
type="button" )}
disabled={busy} <div className="dialog-actions">
onClick={() => setAction(undefined)} <button
> type="button"
Cancel disabled={busy}
</button> onClick={() => setAction(undefined)}
{error && <p role="alert">{error}</p>} >
Cancel
</button>
<button
className={action === "delete" ? "danger" : "primary"}
disabled={busy}
>
{action === "delete" ? "Confirm delete" : "Apply"}
</button>
</div>
</form> </form>
</Dialog>
)} )}
</> </>
); );
+36 -3
View File
@@ -1,3 +1,4 @@
import { useState } from "react";
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core"; import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core";
/** An included notebook (`::use`) whose parameters the form shows as a group. */ /** An included notebook (`::use`) whose parameters the form shows as a group. */
@@ -13,6 +14,7 @@ export function ParamsForm({
hosts, hosts,
groups = [], groups = [],
onChange, onChange,
onReset,
}: { }: {
notebook: Notebook; notebook: Notebook;
values: ParamValues; values: ParamValues;
@@ -21,7 +23,10 @@ export function ParamsForm({
/** Active included notebooks; parameters of inactive ones are hidden. */ /** Active included notebooks; parameters of inactive ones are hidden. */
groups?: ParamGroup[]; groups?: ParamGroup[];
onChange(name: string, value: string): void; onChange(name: string, value: string): void;
/** Clears the values typed for this notebook. */
onReset?(): void;
}) { }) {
const [open, setOpen] = useState(true);
const field = (param: ParamDef) => { const field = (param: ParamDef) => {
const id = `param-${param.name}`; const id = `param-${param.name}`;
const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name; const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name;
@@ -31,6 +36,8 @@ export function ParamsForm({
value: values[param.name] ?? "", value: values[param.name] ?? "",
"aria-labelledby": `${id}-label`, "aria-labelledby": `${id}-label`,
"aria-invalid": !!errors[param.name], "aria-invalid": !!errors[param.name],
// Red only for a wrong value; an empty field just still needs one.
className: errors[param.name] && values[param.name] ? "invalid" : undefined,
"aria-describedby": errors[param.name] ? `${id}-error` : undefined, "aria-describedby": errors[param.name] ? `${id}-error` : undefined,
onChange: ( onChange: (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>, e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
@@ -61,21 +68,47 @@ export function ParamsForm({
/> />
)} )}
{errors[param.name] && ( {errors[param.name] && (
<small id={`${id}-error`} className="error"> // An empty field only needs a value: say so quietly; a wrong value is an error.
<small id={`${id}-error`} className={values[param.name] ? "error" : "muted"}>
{errors[param.name]} {errors[param.name]}
</small> </small>
)} )}
</label> </label>
); );
}; };
const shown = [
...notebook.params.filter((param) => !param.scope),
...groups.flatMap((group) => notebook.params.filter((param) => param.scope === group.scope)),
];
const missing = shown.filter((param) => param.required && !values[param.name]).length;
if (!shown.length) return null;
return ( return (
<form <form
className="params" className="params"
aria-label="Notebook parameters" aria-label="Notebook parameters"
onSubmit={(e) => e.preventDefault()} onSubmit={(e) => e.preventDefault()}
> >
{notebook.params.filter((param) => !param.scope).map(field)} <header>
{groups.map((group) => { <h2>Parameters</h2>
<small className={missing ? "pending" : "ok"}>
{missing ? `${missing} required missing` : "All required set"}
</small>
{onReset && open && (
<button type="button" className="link" onClick={onReset}>
Reset
</button>
)}
<button
type="button"
className="link"
aria-expanded={open}
onClick={() => setOpen(!open)}
>
{open ? "Hide" : "Show"}
</button>
</header>
{open && notebook.params.filter((param) => !param.scope).map(field)}
{open && groups.map((group) => {
const params = notebook.params.filter((param) => param.scope === group.scope); const params = notebook.params.filter((param) => param.scope === group.scope);
return params.length ? ( return params.length ? (
<fieldset key={group.scope}> <fieldset key={group.scope}>
+112 -63
View File
@@ -6,105 +6,154 @@ import type {
} from "@shellbook/core"; } from "@shellbook/core";
import { settingsApi } from "./settingsApi"; import { settingsApi } from "./settingsApi";
import { PasswordForm } from "./PasswordForm"; import { PasswordForm } from "./PasswordForm";
export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
function duration(seconds: number): string {
const days = seconds / 86400;
return days >= 1
? `${Number.isInteger(days) ? days : days.toFixed(1)} day${days === 1 ? "" : "s"}`
: `${Math.round(seconds / 3600)} hours`;
}
export function SettingsPage({
openTerminal,
onSignOut,
}: {
openTerminal: () => void;
/** Called after this browser signed out. */
onSignOut?: () => void;
}) {
const [info, setInfo] = useState<SystemInfoResponse>(); const [info, setInfo] = useState<SystemInfoResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse>(); const [claude, setClaude] = useState<ClaudeStatusResponse | "error">();
const [session, setSession] = useState<SessionSettingsResponse>(); const [session, setSession] = useState<SessionSettingsResponse>();
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
Promise.all([ const failed = () => {
settingsApi.system(), if (active) setMessage("Unable to load settings. Sign in again or retry.");
settingsApi.claude(), };
settingsApi.session(), // Independent requests: the slower Claude check must not hold back the rest.
]) settingsApi.system().then((i) => active && setInfo(i), failed);
.then(([i, c, s]) => { settingsApi.session().then((s) => active && setSession(s), failed);
if (active) { settingsApi.claude().then(
setInfo(i); (c) => active && setClaude(c),
setClaude(c); () => active && setClaude("error"),
setSession(s); );
}
})
.catch(() => {
if (active)
setMessage("Unable to load settings. Sign in again or retry.");
});
return () => { return () => {
active = false; active = false;
}; };
}, []); }, []);
return ( return (
<div className="notebook"> <div className="page settings-page">
<h1>Settings</h1> <header className="page-header">
<section> <div>
<h1>Settings</h1>
<p className="muted">Sign-in, the Claude CLI and this installation.</p>
</div>
</header>
{message && (
<p role="status" className="banner">
{message}
</p>
)}
<section className="card">
<h2>Password and sessions</h2> <h2>Password and sessions</h2>
<PasswordForm submit={settingsApi.password} /> <PasswordForm submit={settingsApi.password} />
<hr />
{session && ( {session && (
<p> <p className="muted">
Session lifetime: {session.lifetimeSeconds} seconds ( Sessions last {duration(session.lifetimeSeconds)} (
{session.lifetimeSeconds / 86400} days). {session.lifetimeSeconds} seconds).
</p> </p>
)} )}
<button <div className="actions">
disabled={busy} <button
onClick={async () => { disabled={busy}
setBusy(true); onClick={async () => {
try { setBusy(true);
await settingsApi.revoke(); try {
setMessage( await settingsApi.revoke();
"Other sessions signed out. This browser remains signed in.", setMessage(
); "Other sessions signed out. This browser remains signed in.",
} catch { );
setMessage("Unable to sign out sessions. Try again."); } catch {
} finally { setMessage("Unable to sign out sessions. Try again.");
setBusy(false); } finally {
} setBusy(false);
}} }
> }}
Sign out all sessions >
</button> Sign out all sessions
</button>
{onSignOut && (
<button
disabled={busy}
onClick={async () => {
try {
await settingsApi.logout();
onSignOut();
} catch {
setMessage("Unable to sign out. Try again.");
}
}}
>
Sign out this browser
</button>
)}
</div>
</section> </section>
<section> <section className="card">
<h2>Claude CLI</h2> <h2>Claude CLI</h2>
{claude ? ( {claude === undefined ? (
<> <p className="muted">Checking the Claude CLI…</p>
<p> ) : claude === "error" ? (
<p className="error">Unable to check the Claude CLI.</p>
) : (
<ul className="checklist">
<li className={claude.available ? "ok" : "bad"}>
{claude.available {claude.available
? `Available: ${claude.version}` ? `Available: ${claude.version}`
: "Claude is unavailable on PATH or did not respond."} : "Claude is unavailable on PATH or did not respond."}
</p> </li>
<p> <li className={claude.loginAppearsPresent ? "ok" : "bad"}>
{claude.loginAppearsPresent {claude.loginAppearsPresent
? "Credentials file exists; login may be available." ? "Credentials file exists; login may be available."
: "No credentials file found."} : "No credentials file found."}
</p> </li>
</> </ul>
) : (
<p>Checking CLI...</p>
)} )}
<button onClick={openTerminal}>Open terminal to log in</button> <p className="muted">
<p> Run <code>claude</code> in the terminal, then <code>/login</code>.
Run <code>claude</code>, then <code>/login</code>. Credentials are Credentials are checked for existence only.
checked for existence only.
</p> </p>
<div className="actions">
<button onClick={openTerminal}>Open terminal to log in</button>
</div>
</section> </section>
<section> <section className="card">
<h2>About/System</h2> <h2>About this installation</h2>
{info && ( {info ? (
<dl> <dl className="facts">
<dt>ShellBook version</dt> <dt>ShellBook version</dt>
<dd>{info.version}</dd> <dd>{info.version}</dd>
<dt>Workspace</dt> <dt>Workspace</dt>
<dd>{info.workspacePath}</dd> <dd>
<code>{info.workspacePath}</code>
</dd>
<dt>Data directory</dt> <dt>Data directory</dt>
<dd>{info.dataDirPath}</dd> <dd>
<code>{info.dataDirPath}</code>
</dd>
<dt>Node version</dt> <dt>Node version</dt>
<dd>{info.nodeVersion}</dd> <dd>{info.nodeVersion}</dd>
</dl> </dl>
) : (
<p className="muted">Loading…</p>
)} )}
<p className="muted">
Update from the container with <code>shellbook-update</code>.
</p>
</section> </section>
{message && <p role="status">{message}</p>}
</div> </div>
); );
} }
+40 -36
View File
@@ -1,10 +1,10 @@
import { ArtifactDownload } from "./ArtifactDownload"; import { ArtifactDownload } from "./ArtifactDownload";
import { useState } from "react";
import hljs from "highlight.js/lib/core"; import hljs from "highlight.js/lib/core";
import bash from "highlight.js/lib/languages/bash"; import bash from "highlight.js/lib/languages/bash";
import type { HostInfo, RenderedStep, Step } from "@shellbook/core"; import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
import type { DownloadState, RunState } from "./events"; import type { DownloadState, RunState } from "./events";
import { sshCommand } from "./ssh"; import { sshCommand } from "./ssh";
import { CopyButton } from "./ui";
hljs.registerLanguage("bash", bash); hljs.registerLanguage("bash", bash);
function Script({ script }: { script: string }) { function Script({ script }: { script: string }) {
@@ -28,6 +28,20 @@ function Script({ script }: { script: string }) {
</pre> </pre>
); );
} }
/** One short hint for what a step still needs, without repeating a name. */
export function stepProblems(rendered: RenderedStep): string[] {
const problems: string[] = [];
if (rendered.missing.length)
problems.push(`Fill in ${rendered.missing.join(", ")} to run this step.`);
const unresolvedHost = !!rendered.host?.includes("{{");
for (const [name, error] of Object.entries(rendered.invalid)) {
if (rendered.missing.includes(name)) continue;
// The target follows from a missing value; the hint above already covers it.
if (name === "host" && unresolvedHost && rendered.missing.length) continue;
problems.push(`${name}: ${error}`);
}
return problems;
}
export function StepCard({ export function StepCard({
step, step,
rendered, rendered,
@@ -47,56 +61,47 @@ export function StepCard({
connected?: boolean; connected?: boolean;
onArtifactState?(runId: string, name: string, state: DownloadState): void; onArtifactState?(runId: string, name: string, state: DownloadState): void;
}) { }) {
const [notice, setNotice] = useState(""); const problems = stepProblems(rendered);
const invalid = const invalid = problems.length > 0;
rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0;
const busy = run?.status === "running" || run?.status === "hostKey"; const busy = run?.status === "running" || run?.status === "hostKey";
async function copy(ssh: boolean) { const target = rendered.local
try { ? "ShellBook server"
await navigator.clipboard.writeText( : rendered.host && !rendered.host.includes("{{")
ssh && host ? host
? sshCommand(host, rendered.script, step.attrs.sudo) ? `${host.user}@${host.name}`
: rendered.script, : rendered.host
); : "no host selected";
setNotice("Copied");
} catch {
setNotice("Copy failed. Select and copy the script manually.");
}
}
return ( return (
<article <article
className={`step ${run?.status ?? ""}`} className={`step ${step.kind} ${run?.status ?? ""}`}
aria-label={step.attrs.title ?? step.attrs.id} aria-label={step.attrs.title ?? step.attrs.id}
> >
<header> <header>
<span className="badge">{step.kind}</span> <span className={`badge kind-${step.kind}`}>{step.kind}</span>
<h3>{step.attrs.title ?? step.attrs.id}</h3> <h3>{step.attrs.title ?? step.attrs.id}</h3>
<span className="target">
{rendered.local
? "local · ShellBook server"
: (rendered.host ?? "No host selected")}
</span>
{step.attrs.sudo && <span className="badge">sudo</span>} {step.attrs.sudo && <span className="badge">sudo</span>}
{(step.attrs.confirm || {(step.attrs.confirm ||
(step.kind === "run" && host?.tags.includes("prod"))) && ( (step.kind === "run" && host?.tags.includes("prod"))) && (
<span className="badge">confirm</span> <span className="badge warn">confirm</span>
)} )}
<span className={`target ${host || rendered.local ? "" : "unset"}`} title="Runs on">
→ {target}
</span>
</header> </header>
<Script script={rendered.script} /> <Script script={rendered.script} />
{invalid && ( {invalid && (
<p className="error" role="status"> <p className="hint" role="status">
{rendered.missing.length > 0 && {problems.join(" ")}
`Missing: ${rendered.missing.join(", ")}. `}
{Object.entries(rendered.invalid)
.map(([name, error]) => `${name}: ${error}`)
.join("; ")}
</p> </p>
)} )}
<div className="actions"> <div className="actions">
<button onClick={() => void copy(false)}>Copy</button> <CopyButton text={() => rendered.script} />
<button disabled={!host || invalid} onClick={() => void copy(true)}> <CopyButton
Copy as ssh one-liner label="Copy ssh command"
</button> title="An ssh one-liner for your own terminal"
disabled={!host || invalid}
text={() => sshCommand(host!, rendered.script, step.attrs.sudo)}
/>
<span className="spacer" /> <span className="spacer" />
<button <button
className="primary" className="primary"
@@ -106,10 +111,9 @@ export function StepCard({
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"} {busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
</button> </button>
</div> </div>
{notice && <small role="status">{notice}</small>}
{run && ( {run && (
<section className="result" aria-label="Run output"> <section className="result" aria-label="Run output">
<div role="status"> <div role="status" className="result-status">
{run.status === "success" {run.status === "success"
? "✅ Succeeded" ? "✅ Succeeded"
: run.status === "failure" : run.status === "failure"
+19 -9
View File
@@ -9,8 +9,10 @@ import type { TerminalClientMessage } from "@shellbook/core";
export function TerminalSlot({ export function TerminalSlot({
collapsed = false, collapsed = false,
connect = terminalTransport, connect = terminalTransport,
onClose,
}: { }: {
collapsed?: boolean; collapsed?: boolean;
onClose?: () => void;
connect?: (session: string) => TerminalTransport; connect?: (session: string) => TerminalTransport;
}) { }) {
const container = useRef<HTMLDivElement>(null); const container = useRef<HTMLDivElement>(null);
@@ -105,18 +107,26 @@ export function TerminalSlot({
if (!collapsed) refit.current(); if (!collapsed) refit.current();
}, [collapsed]); }, [collapsed]);
return ( return (
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}> <aside className="terminal side-panel" aria-label="Terminal panel" hidden={collapsed}>
<h2>Terminal · main</h2> <header className="panel-header">
<p> <h2>Terminal</h2>
Run `claude` here — it edits notebooks in this workspace; the view <span role="status" className={`dot-status ${state === "Connected" ? "ok" : state === "Disconnected" ? "bad" : ""}`}>
reloads live. {state}
</p> </span>
<div className="actions">
<span role="status">{state}</span>
{state === "Disconnected" && ( {state === "Disconnected" && (
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button> <button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
)} )}
</div> <span className="spacer" />
{onClose && (
<button className="icon" aria-label="Close terminal" onClick={onClose}>
×
</button>
)}
</header>
<p className="muted">
tmux session “main” on the ShellBook server. Run <code>claude</code>{" "}
here; notebook edits show up live.
</p>
<div className="terminal-screen" ref={container} /> <div className="terminal-screen" ref={container} />
</aside> </aside>
); );
+37 -12
View File
@@ -1,12 +1,37 @@
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; } .chat-panel select,
.chat-panel h2, .chat-panel p { margin: .25rem 0; } .chat-panel textarea {
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; } width: 100%;
.chat-panel label { display: block; } }
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; } .chat-messages {
.chat-messages pre { overflow-x: auto; } flex: 1;
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; } min-height: 120px;
.chat-message.user { opacity: .85; } overflow-y: auto;
.chat-shell { margin-top: .5rem; } overflow-wrap: anywhere;
.chat-panel form { flex-shrink: 0; } border-top: 1px solid var(--line);
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } } border-bottom: 1px solid var(--line);
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } } }
.chat-messages pre {
overflow-x: auto;
}
.chat-message {
padding: 0.6rem 0;
border-bottom: 1px solid #64748b55;
}
.chat-message.user {
opacity: 0.85;
}
.chat-panel label.chat-shell {
flex-direction: row;
align-items: center;
gap: 6px;
margin-top: 0.5rem;
}
.chat-panel form {
flex-shrink: 0;
}
.chat-panel form .actions {
margin: 8px 0 0;
}
.chat-panel > p {
margin: 0;
}
+50 -41
View File
@@ -1,49 +1,58 @@
.hosts-page { .host-list {
padding: 1rem; border: 1px solid var(--line);
max-width: 70rem; border-radius: 8px;
background: var(--panel);
margin: 16px 0;
}
.host-list .empty {
padding: 32px 20px;
margin: 0;
}
.host-row {
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 12px 16px;
}
.host-row + .host-row {
border-top: 1px solid var(--line);
}
.host-main {
min-width: 0; min-width: 0;
} }
.hosts-page pre { .host-main h2 {
font-size: 15px;
margin: 0 0 2px;
}
.host-main code {
color: var(--muted);
font-size: 12.5px;
overflow-wrap: anywhere;
}
.host-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.host-row .actions {
margin: 0;
flex-wrap: nowrap;
}
.public-key pre {
white-space: pre-wrap; white-space: pre-wrap;
overflow-wrap: anywhere; overflow-wrap: anywhere;
background: var(--code);
border: 1px solid var(--line);
border-radius: 5px;
padding: 10px 12px;
font-size: 12px;
} }
.hosts-page form { @media (max-width: 760px) {
display: flex; .host-row {
flex-wrap: wrap; grid-template-columns: minmax(0, 1fr);
gap: 0.8rem;
align-items: end;
}
.hosts-page label {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1 1 12rem;
min-width: 0;
}
.hosts-page input,
.hosts-page textarea,
.hosts-page select {
width: 100%;
box-sizing: border-box;
}
.hosts-page article,
.hosts-page [role="dialog"] {
border: 1px solid #777;
padding: 1rem;
margin-block: 1rem;
overflow-wrap: anywhere;
}
.hosts-page .actions {
flex-wrap: wrap;
}
.hosts-page button {
white-space: normal;
}
@media (max-width: 600px) {
.app:has(.hosts-page) {
display: block;
} }
.app:has(.hosts-page) .sidebar { .host-row .actions {
width: auto; flex-wrap: wrap;
} }
} }
+6 -18
View File
@@ -1,3 +1,4 @@
/* Authoring toolbar above the Markdown editor. */
.authoring { .authoring {
display: flex; display: flex;
align-items: end; align-items: end;
@@ -5,30 +6,17 @@
gap: 0.5rem; gap: 0.5rem;
margin: 0.75rem 0; margin: 0.75rem 0;
} }
.authoring label, .authoring label {
.sidebar form label {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.25rem; gap: 0.25rem;
font-size: 12px;
} }
.authoring form, .authoring form,
.authoring details { .authoring details {
flex-basis: 100%; flex-basis: 100%;
} }
.sidebar form { .authoring input,
display: flex; .authoring select {
flex-direction: column; width: auto;
gap: 0.75rem;
margin-top: 1rem;
}
.sidebar input {
min-width: 0;
max-width: 100%;
}
.sidebar nav details {
margin-left: 0.5rem;
}
.sidebar nav summary {
cursor: pointer;
padding: 0.5rem 0;
} }
+39
View File
@@ -0,0 +1,39 @@
import type { Notebook, ParamValues } from "@shellbook/core";
/**
* Remembers the parameter values typed for a notebook in this browser, so a reload or a
* return visit keeps them. Secrets are never stored, and only declared params are kept.
*/
const key = (path: string) => `shellbook:params:${path}`;
function storable(notebook: Notebook, values: ParamValues): ParamValues {
const kept: ParamValues = {};
for (const def of notebook.params) {
const value = Object.hasOwn(values, def.name) ? values[def.name] : undefined;
if (def.type !== "secret" && value) kept[def.name] = value;
}
return kept;
}
export function recallValues(path: string, notebook: Notebook): ParamValues {
try {
const stored: unknown = JSON.parse(localStorage.getItem(key(path)) ?? "{}");
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return {};
const strings = Object.fromEntries(
Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
);
return storable(notebook, strings);
} catch {
return {};
}
}
export function rememberValues(path: string, notebook: Notebook, values: ParamValues): void {
try {
const kept = storable(notebook, values);
if (Object.keys(kept).length) localStorage.setItem(key(path), JSON.stringify(kept));
else localStorage.removeItem(key(path));
} catch {
// Storage may be unavailable (private mode); values then last for this page only.
}
}
+33
View File
@@ -0,0 +1,33 @@
import type { NavigationPage } from "./HeaderNavigation";
/** The page and open notebook, kept in the URL hash so reloads and links keep them. */
export interface Route {
page: NavigationPage;
notebook?: string;
}
const pages: Record<string, NavigationPage> = {
notebooks: "Notebooks",
hosts: "Hosts",
settings: "Settings",
};
export function parseRoute(hash: string): Route {
const [, page = "", ...rest] = hash.replace(/^#/, "").split("/");
const known = pages[page];
if (!known) return { page: "Notebooks" };
if (known !== "Notebooks" || !rest.length) return { page: known };
try {
const notebook = rest.map(decodeURIComponent).join("/");
return notebook ? { page: known, notebook } : { page: known };
} catch {
return { page: known };
}
}
export function routeHash(route: Route): string {
const page = route.page.toLowerCase();
return route.page === "Notebooks" && route.notebook
? `#/${page}/${route.notebook.split("/").map(encodeURIComponent).join("/")}`
: `#/${page}`;
}
+1
View File
@@ -25,6 +25,7 @@ export const settingsApi = {
password: (body: ChangePasswordRequest) => password: (body: ChangePasswordRequest) =>
request<void>("/settings/password", body), request<void>("/settings/password", body),
revoke: () => request<void>("/settings/sessions/revoke", {}), revoke: () => request<void>("/settings/sessions/revoke", {}),
logout: () => request<void>("/auth/logout", {}),
session: () => request<SessionSettingsResponse>("/settings/session"), session: () => request<SessionSettingsResponse>("/settings/session"),
claude: () => request<ClaudeStatusResponse>("/settings/claude"), claude: () => request<ClaudeStatusResponse>("/settings/claude"),
system: () => request<SystemInfoResponse>("/settings/system"), system: () => request<SystemInfoResponse>("/settings/system"),
+912 -465
View File
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -26,6 +26,8 @@ it("adds hosts with accessible fields and optimistic version", async () => {
vi.mocked(json).mockResolvedValue(inventory); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); await screen.findByText("demo");
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
expect(screen.getByRole("dialog", { name: "Add server" })).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } }); fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
fireEvent.change(screen.getByLabelText("Address"), { fireEvent.change(screen.getByLabelText("Address"), {
target: { value: "::1" }, target: { value: "::1" },
@@ -42,7 +44,7 @@ it("sends credentials once and clears password fields", async () => {
vi.mocked(json).mockResolvedValue(inventory); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); await screen.findByText("demo");
fireEvent.click(screen.getByText("SSH credentials for demo")); fireEvent.click(screen.getByRole("button", { name: "SSH credentials for demo" }));
fireEvent.change(screen.getByLabelText("Authentication"), { fireEvent.change(screen.getByLabelText("Authentication"), {
target: { value: "password" }, target: { value: "password" },
}); });
@@ -79,7 +81,8 @@ it("requires fingerprint confirmation and resends the displayed installation scr
}); });
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); await screen.findByText("demo");
fireEvent.click(screen.getByText("Install ShellBook key on demo")); fireEvent.click(screen.getByRole("button", { name: "More actions for demo" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Install ShellBook key on demo" }));
await screen.findByText("literal script"); await screen.findByText("literal script");
expect(json).not.toHaveBeenCalledWith( expect(json).not.toHaveBeenCalledWith(
"/host-management/demo/action", "/host-management/demo/action",
@@ -104,7 +107,7 @@ it("loads external changes without silently changing the version of an open edit
vi.mocked(json).mockResolvedValue(inventory); vi.mocked(json).mockResolvedValue(inventory);
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); await screen.findByText("demo");
fireEvent.click(screen.getByText("Edit demo")); fireEvent.click(screen.getByRole("button", { name: "Edit demo" }));
vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" }); vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
window.dispatchEvent(new Event("shellbook:hosts-changed")); window.dispatchEvent(new Event("shellbook:hosts-changed"));
await waitFor(() => expect(json).toHaveBeenCalledTimes(2)); await waitFor(() => expect(json).toHaveBeenCalledTimes(2));
@@ -124,7 +127,7 @@ it("shows the server's reason for a failed connection test without a conflict hi
}); });
render(<HostsPage />); render(<HostsPage />);
await screen.findByText("demo"); await screen.findByText("demo");
fireEvent.click(screen.getByText("Test connection to demo")); fireEvent.click(screen.getByRole("button", { name: "Test connection to demo" }));
const alert = await screen.findByText(/SSH authentication failed/); const alert = await screen.findByText(/SSH authentication failed/);
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key"); expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
}); });
@@ -75,7 +75,7 @@ it("requires explicit delete confirmation and uses the displayed version", async
deleteNotebook: remove, deleteNotebook: remove,
} as unknown as Api } as unknown as Api
} }
list={[]} list={[{ path: "a.md", title: "A" }]}
path="a.md" path="a.md"
version="latest" version="latest"
onSelect={vi.fn()} onSelect={vi.fn()}
@@ -83,7 +83,10 @@ it("requires explicit delete confirmation and uses the displayed version", async
canLeave={() => true} canLeave={() => true}
/>, />,
); );
fireEvent.click(screen.getByRole("button", { name: "Delete" })); // The open notebook has an actions menu; deleting asks again in a dialog.
fireEvent.click(screen.getByRole("button", { name: "Actions for A" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Delete" }));
expect(screen.getByRole("dialog", { name: "Delete notebook" })).toHaveTextContent("a.md");
expect(remove).not.toHaveBeenCalled(); expect(remove).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" })); fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest")); await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
+6 -1
View File
@@ -1,4 +1,9 @@
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react"; import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest"; import { afterEach } from "vitest";
afterEach(cleanup); afterEach(() => {
cleanup();
// The app keeps its route in the URL and typed values in localStorage.
localStorage.clear();
history.replaceState(null, "", "/");
});
+112
View File
@@ -0,0 +1,112 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({
Editor: ({ source, onChange }: { source: string; onChange(value: string): void }) => (
<textarea aria-label="Notebook Markdown" value={source} onChange={(e) => onChange(e.target.value)} />
),
}));
import { parseNotebook } from "@shellbook/core";
import type { RenderedStep } from "@shellbook/core";
import { App } from "../App";
import type { Api } from "../api";
import { parseRoute, routeHash } from "../route";
import { recallValues, rememberValues } from "../paramMemory";
import { stepProblems } from "../StepCard";
import { Dialog } from "../ui";
import source from "../mock/ssh-key.md?raw";
const secretBook = parseNotebook(`---
params:
host: { type: host }
token: { type: secret }
---
# T
`);
it("round-trips page and notebook routes, including encoded segments", () => {
for (const route of [
{ page: "Hosts" as const },
{ page: "Settings" as const },
{ page: "Notebooks" as const, notebook: "ops/linux/a b#1.md" },
])
expect(parseRoute(routeHash(route))).toEqual(route);
expect(routeHash({ page: "Notebooks", notebook: "a b.md" })).toBe("#/notebooks/a%20b.md");
expect(parseRoute("")).toEqual({ page: "Notebooks" });
expect(parseRoute("#/unknown/x")).toEqual({ page: "Notebooks" });
expect(parseRoute("#/notebooks/%E0%A4%A")).toEqual({ page: "Notebooks" });
});
it("remembers typed values but never secrets or undeclared names", () => {
rememberValues("a.md", secretBook, { host: "web", token: "s3cret", other: "x" });
expect(localStorage.getItem("shellbook:params:a.md")).not.toContain("s3cret");
expect(recallValues("a.md", secretBook)).toEqual({ host: "web" });
// Stored data is untrusted: a secret written by hand is still dropped.
localStorage.setItem("shellbook:params:a.md", JSON.stringify({ token: "x", host: 1 }));
expect(recallValues("a.md", secretBook)).toEqual({});
localStorage.setItem("shellbook:params:a.md", "not json");
expect(recallValues("a.md", secretBook)).toEqual({});
rememberValues("a.md", secretBook, {});
expect(localStorage.getItem("shellbook:params:a.md")).toBeNull();
});
it("names a missing value once instead of repeating it as an invalid host", () => {
const rendered: RenderedStep = {
stepId: "s", kind: "check", local: false, host: "{{host}}", script: "id",
artifacts: [], uploads: [], missing: ["host"],
invalid: { host: "Unknown or missing target host" },
};
expect(stepProblems(rendered)).toEqual(["Fill in host to run this step."]);
expect(stepProblems({ ...rendered, host: "gone", missing: [], invalid: { host: "Unknown or missing target host", port: "bad" } }))
.toEqual(["host: Unknown or missing target host", "port: bad"]);
});
it("closes dialogs with Escape", () => {
const close = vi.fn();
render(<Dialog title="Example" onClose={close}><input aria-label="Field" /></Dialog>);
expect(screen.getByLabelText("Field")).toHaveFocus();
fireEvent.keyDown(document, { key: "Escape" });
expect(close).toHaveBeenCalledOnce();
});
function api(): Api {
const notebook = (path: string) => ({ path, source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1" });
return {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "a.md", title: "A" }, { path: "ops/b.md", title: "B" }] }),
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "staging", user: "admin", address: "x", port: 22, tags: [] }] }),
notebook: vi.fn(async (path: string) => notebook(path)),
save: vi.fn().mockResolvedValue({ version: "2" }),
addHost: vi.fn(),
run: vi.fn(),
events: (_callback, connected) => { connected(true); return () => {}; },
artifact: () => "",
};
}
it("opens the notebook named in the URL, keeps typed values across reloads and shows the route", async () => {
history.replaceState(null, "", "/#/notebooks/ops/b.md");
const first = api();
const view = render(<App api={first} />);
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
expect(first.notebook).toHaveBeenCalledWith("ops/b.md");
expect(first.notebook).not.toHaveBeenCalledWith("a.md");
await waitFor(() => expect(location.hash).toBe("#/notebooks/ops/b.md"));
view.unmount();
render(<App api={api()} />);
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveValue("staging"));
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
expect(screen.getByLabelText("Target server *")).toHaveValue("");
fireEvent.click(screen.getByRole("button", { name: "Hosts" }));
await waitFor(() => expect(location.hash).toBe("#/hosts"));
});
it("saves the draft with Ctrl+S", async () => {
const live = api();
render(<App api={live} />);
fireEvent.click(await screen.findByRole("button", { name: "Edit Markdown" }));
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), { target: { value: source + "\nMore\n" } });
fireEvent.keyDown(window, { key: "s", ctrlKey: true });
await waitFor(() => expect(live.save).toHaveBeenCalledWith("a.md", source + "\nMore\n", "1"));
});
+150
View File
@@ -0,0 +1,150 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
/** Modal dialog: Escape and the backdrop cancel; focus moves into it on open. */
export function Dialog({
title,
onClose,
children,
wide = false,
}: {
title: string;
onClose(): void;
children: ReactNode;
wide?: boolean;
}) {
const id = useId();
const box = useRef<HTMLElement>(null);
const close = useRef(onClose);
close.current = onClose;
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
const first = box.current?.querySelector<HTMLElement>(
"input:not([type=hidden]), select, textarea, button:not(.dialog-close)",
);
first?.focus();
const key = (e: KeyboardEvent) => {
if (e.key === "Escape") close.current();
};
document.addEventListener("keydown", key);
return () => {
document.removeEventListener("keydown", key);
previous?.focus?.();
};
}, []);
return (
<div
className="modal-backdrop"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<section
ref={box}
className={wide ? "dialog wide" : "dialog"}
role="dialog"
aria-modal="true"
aria-labelledby={id}
>
<header>
<h2 id={id}>{title}</h2>
<button type="button" className="dialog-close icon" aria-label="Close" onClick={onClose}>
×
</button>
</header>
{children}
</section>
</div>
);
}
/** A small popup menu; closes on outside click, Escape, or after choosing an item. */
export function Menu({
label,
text = "⋯",
children,
}: {
label: string;
text?: ReactNode;
children: (close: () => void) => ReactNode;
}) {
const [open, setOpen] = useState(false);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const outside = (e: MouseEvent) => {
if (!root.current?.contains(e.target as Node)) setOpen(false);
};
const key = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false);
};
document.addEventListener("mousedown", outside);
document.addEventListener("keydown", key);
return () => {
document.removeEventListener("mousedown", outside);
document.removeEventListener("keydown", key);
};
}, [open]);
return (
<div className="menu" ref={root}>
<button
type="button"
className="icon"
aria-label={label}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(!open)}
>
{text}
</button>
{open && (
<div className="menu-items" role="menu" aria-label={label}>
{children(() => setOpen(false))}
</div>
)}
</div>
);
}
/** Copies text and briefly confirms on the button itself. */
export function CopyButton({
text,
label = "Copy",
disabled,
title,
}: {
text: () => string;
label?: string;
disabled?: boolean;
title?: string;
}) {
const [state, setState] = useState<"" | "done" | "failed">("");
useEffect(() => {
if (!state) return;
const timer = setTimeout(() => setState(""), 1800);
return () => clearTimeout(timer);
}, [state]);
return (
<>
<button
type="button"
disabled={disabled}
title={title}
onClick={async () => {
try {
await navigator.clipboard.writeText(text());
setState("done");
} catch {
setState("failed");
}
}}
>
{label}
</button>
{state && (
<small role="status" className={state === "failed" ? "error" : "ok"}>
{state === "done" ? "Copied" : "Copy failed. Select and copy manually."}
</small>
)}
</>
);
}
+1 -1
View File
@@ -165,7 +165,7 @@ export function renderHost(
/** Substitute prose without quoting; secrets always appear masked. */ /** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string { export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name)); const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match); return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) && values[name] ? values[name]! : match);
} }
/** /**
+2
View File
@@ -153,6 +153,8 @@ describe("rendering and secrets", () => {
it("renders prose with raw values and handles inherited names safely", () => { it("renders prose with raw values and handles inherited names safely", () => {
const n = book(" x: {type: string}"); const n = book(" x: {type: string}");
expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}"); expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}");
// An unset value stays visible as its template instead of vanishing ("on ****").
expect(renderText("on **{{x}}**", { x: "" }, n)).toBe("on **{{x}}**");
expect(render(n, {}, {}).invalid.x).toBeUndefined(); expect(render(n, {}, {}).invalid.x).toBeUndefined();
expect(render(n, {}, {}).missing).toContain("x"); expect(render(n, {}, {}).missing).toContain("x");
}); });
@@ -20,8 +20,8 @@ params:
Creates an unprivileged container on **{{proxmox}}** (connects as a user that may run Creates an unprivileged container on **{{proxmox}}** (connects as a user that may run
`pct`, usually root), starts it with ShellBook's SSH key for root, and adds it to `pct`, usually root), starts it with ShellBook's SSH key for root, and adds it to
Hosts. Other notebooks can include this one with Hosts. Other notebooks can include this one with
`::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine as `::use{notebook="infra/lxc-container.md" as=ct}` and target the new machine through
`{{ct.host}}`. its `host` capture (`ct.host` with that alias).
```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"} ```sh {check host="{{proxmox}}" id=pve title="Proxmox tools are available"}
command -v pct command -v pct