Merge branch 't3/notebook-management-authoring'
# Conflicts: # .agents/mind/architecture.md # packages/core/src/protocol.ts
This commit is contained in:
@@ -82,3 +82,31 @@ and reconnect. App tests drive the SSH-key fixture through keygen, sensitive art
|
||||
downloads (including 410), after sections, capture substitution, and authorize
|
||||
artifact provenance. Real tmux/Claude login and browser terminal rendering still
|
||||
need an interactive server check.
|
||||
|
||||
## Notebook management and authoring
|
||||
|
||||
The sidebar groups notebooks into folders and filters by title or path. **New notebook**
|
||||
asks for a name, optional folder and title, then opens a valid starter with a host
|
||||
parameter, a read-only check, and a confirmed run placeholder. **Rename / move** and
|
||||
**Duplicate** take a destination path relative to `notebooks/` (including `.md`).
|
||||
Folders are created automatically; empty folders disappear after moves or deletes.
|
||||
**Delete** requires explicit confirmation. Names use letters, numbers, spaces, dots,
|
||||
underscores and hyphens; traversal, absolute paths, symlinks and Windows device names
|
||||
are rejected. Management needs a real server; the demo reports that limitation.
|
||||
|
||||
In edit mode, the toolbar inserts Check, Run, Artifacts, Upload or Capture examples
|
||||
at the cursor, targeting the local ShellBook server or a declared host parameter.
|
||||
Review example commands and file names before execution. **Parameter** adds a YAML
|
||||
mapping via a form (including choice options and secret rules), preserving unrelated
|
||||
YAML and comments. **After step** selects an existing step for conditional instructions.
|
||||
**Format help** explains attributes and parameter references. Save and live preview
|
||||
continue to use the core parser. Attribute editing remains available in Markdown.
|
||||
|
||||
All mutations use authenticated, same-origin API calls. Save, move, duplicate and
|
||||
delete use optimistic versions (409 means stale content or an occupied destination).
|
||||
Files publish atomically, and the existing watcher refreshes other tabs' lists and
|
||||
clean open documents. External rename/delete retains the old open draft with a
|
||||
notice; select the new path from the refreshed list. Unsaved edits require confirmation
|
||||
before navigation or management. External filesystem writers must be trusted: as with
|
||||
other workspace operations, symlink checks cannot prevent a privileged local process
|
||||
from swapping path components between filesystem calls.
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
"codemirror": "^6.0.1",
|
||||
"highlight.js": "^11.10.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
"@xterm/addon-fit": "^0.10.0"
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"yaml": "^2.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
|
||||
+31
-15
@@ -28,6 +28,7 @@ import type {
|
||||
StartRunRequest,
|
||||
Step,
|
||||
} from "@shellbook/core";
|
||||
import { NotebookList } from "./NotebookList";
|
||||
import { HttpError } from "./api";
|
||||
import type { Api } from "./api";
|
||||
import { emptySession, eventReducer, stepKey } from "./events";
|
||||
@@ -129,6 +130,14 @@ export function App({ api }: { api: Api }) {
|
||||
.catch((e) => setError(String(e)));
|
||||
const close = api.events((event: ServerEvent) => {
|
||||
const open = current.current;
|
||||
if (event.type === "file.changed" || event.type === "file.deleted") {
|
||||
void api
|
||||
.list()
|
||||
.then((result) => {
|
||||
if (active) setList(result.notebooks);
|
||||
})
|
||||
.catch((e) => setError(String(e)));
|
||||
}
|
||||
if (event.type === "file.changed" && event.path === open.doc?.path) {
|
||||
if (open.dirty) setConflict(true);
|
||||
else void load(event.path);
|
||||
@@ -334,21 +343,28 @@ export function App({ api }: { api: Api }) {
|
||||
<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>
|
||||
<NotebookList
|
||||
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
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { useState } from "react";
|
||||
import { parseNotebook, type ParamDef } from "@shellbook/core";
|
||||
import {
|
||||
addParameter,
|
||||
afterSnippet,
|
||||
notebookSteps,
|
||||
stepSnippet,
|
||||
type InsertKind,
|
||||
} from "./authoring";
|
||||
export function AuthoringToolbar({
|
||||
source,
|
||||
insert,
|
||||
replace,
|
||||
}: {
|
||||
source: string;
|
||||
insert(text: string): void;
|
||||
replace(text: string): void;
|
||||
}) {
|
||||
const notebook = parseNotebook(source);
|
||||
const hosts = notebook.params.filter((p) => p.type === "host");
|
||||
const [target, setTarget] = useState("local");
|
||||
const [param, setParam] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [type, setType] = useState<ParamDef["type"]>("string");
|
||||
const [after, setAfter] = useState("");
|
||||
const steps = notebookSteps(notebook.blocks);
|
||||
return (
|
||||
<div className="authoring">
|
||||
<label>
|
||||
Insert target
|
||||
<select value={target} onChange={(e) => setTarget(e.target.value)}>
|
||||
<option value="local">ShellBook server (local)</option>
|
||||
{hosts.map((p) => (
|
||||
<option key={p.name} value={p.name}>
|
||||
Parameter: {p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(
|
||||
[
|
||||
"Check step",
|
||||
"Run step",
|
||||
"Artifacts",
|
||||
"Upload",
|
||||
"Capture",
|
||||
] as InsertKind[]
|
||||
).map((kind) => (
|
||||
<button
|
||||
key={kind}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
insert(stepSnippet(source, kind, target === "local", target))
|
||||
}
|
||||
>
|
||||
{kind}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" onClick={() => setParam(!param)}>
|
||||
Parameter
|
||||
</button>
|
||||
<label>
|
||||
After step
|
||||
<select value={after} onChange={(e) => setAfter(e.target.value)}>
|
||||
<option value="">Choose a step</option>
|
||||
{steps.map((s) => (
|
||||
<option key={s.attrs.id} value={s.attrs.id}>
|
||||
{s.attrs.title ?? s.attrs.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!steps.some((s) => s.attrs.id === after)}
|
||||
onClick={() => insert(afterSnippet(after))}
|
||||
>
|
||||
Insert after note
|
||||
</button>
|
||||
{param && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(e.currentTarget);
|
||||
const def: ParamDef = {
|
||||
name: String(data.get("name")),
|
||||
type,
|
||||
required: data.has("required"),
|
||||
};
|
||||
if (data.get("label")) def.label = String(data.get("label"));
|
||||
if (type !== "secret" && data.get("default"))
|
||||
def.default = String(data.get("default"));
|
||||
if (type === "choice")
|
||||
def.options = String(data.get("options"))
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
try {
|
||||
replace(addParameter(source, def));
|
||||
setParam(false);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(String(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Parameter name
|
||||
<input name="name" required pattern="[A-Za-z_][A-Za-z0-9_]*" />
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as ParamDef["type"])}
|
||||
>
|
||||
{["host", "name", "path", "string", "choice", "secret"].map(
|
||||
(t) => (
|
||||
<option key={t}>{t}</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" name="required" />
|
||||
Required
|
||||
</label>
|
||||
<label>
|
||||
Label
|
||||
<input name="label" />
|
||||
</label>
|
||||
{type !== "secret" && (
|
||||
<label>
|
||||
Default
|
||||
<input name="default" />
|
||||
</label>
|
||||
)}
|
||||
{type === "choice" && (
|
||||
<label>
|
||||
Options (one per line)
|
||||
<textarea name="options" required />
|
||||
</label>
|
||||
)}
|
||||
<button>Add parameter</button>
|
||||
</form>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<details>
|
||||
<summary>Format help</summary>
|
||||
<p>
|
||||
Parameters live in YAML frontmatter: type, required, default, label,
|
||||
options. Use {"{{name}}"} in prose and scripts. Secrets use
|
||||
environment variables ($NAME), with no default.
|
||||
</p>
|
||||
<p>
|
||||
Steps use sh fences with {'{check host="{{host}}"}'} or{" "}
|
||||
{"{run on=local confirm}"}. Checks must be read-only. Optional
|
||||
attributes: id, title, sudo, confirm, timeout (seconds), capture. Run
|
||||
steps support artifacts="file.txt" and
|
||||
upload="file.txt:/tmp/file.txt". After notes appear when their
|
||||
selected step succeeds.
|
||||
</p>
|
||||
<p>
|
||||
Artifact and upload snippets are examples: choose files and commands
|
||||
appropriate to your runbook before running.
|
||||
</p>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+28
-2
@@ -1,3 +1,4 @@
|
||||
import { AuthoringToolbar } from "./AuthoringToolbar";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
@@ -10,6 +11,7 @@ export function Editor({
|
||||
source: string;
|
||||
onChange(source: string): void;
|
||||
}) {
|
||||
const editor = useRef<EditorView>();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const change = useRef(onChange);
|
||||
change.current = onChange;
|
||||
@@ -27,9 +29,33 @@ export function Editor({
|
||||
}),
|
||||
],
|
||||
});
|
||||
return () => view.destroy();
|
||||
editor.current = view;
|
||||
return () => {
|
||||
editor.current = undefined;
|
||||
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} />;
|
||||
return (
|
||||
<>
|
||||
<AuthoringToolbar
|
||||
source={source}
|
||||
insert={(text) => {
|
||||
const view = editor.current;
|
||||
if (!view) return;
|
||||
view.dispatch(view.state.replaceSelection(text));
|
||||
view.focus();
|
||||
}}
|
||||
replace={(text) => {
|
||||
const view = editor.current;
|
||||
if (!view) return;
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<div className="editor" ref={root} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import "./notebooks.css";
|
||||
import { useState } from "react";
|
||||
import type { NotebookSummary } from "@shellbook/core";
|
||||
import type { Api } from "./api";
|
||||
import { newNotebook } from "./authoring";
|
||||
type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
|
||||
function tree(list: NotebookSummary[]): Node {
|
||||
const root: Node = { folders: new Map(), files: [] };
|
||||
for (const file of list) {
|
||||
let node = root;
|
||||
for (const part of file.path.split("/").slice(0, -1)) {
|
||||
if (!node.folders.has(part))
|
||||
node.folders.set(part, { folders: new Map(), files: [] });
|
||||
node = node.folders.get(part)!;
|
||||
}
|
||||
node.files.push(file);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
export function NotebookList({
|
||||
api,
|
||||
list,
|
||||
path,
|
||||
version,
|
||||
onSelect,
|
||||
onChanged,
|
||||
canLeave,
|
||||
}: {
|
||||
api: Api;
|
||||
list: NotebookSummary[];
|
||||
path: string;
|
||||
version?: string;
|
||||
onSelect(path: string): void;
|
||||
onChanged(path?: string): Promise<void>;
|
||||
canLeave(): boolean;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [action, setAction] = useState<
|
||||
"new" | "rename" | "duplicate" | "delete"
|
||||
>();
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const render = (node: Node) => (
|
||||
<>
|
||||
{[...node.folders]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, child]) => (
|
||||
<details key={name} open>
|
||||
<summary>{name}</summary>
|
||||
{render(child)}
|
||||
</details>
|
||||
))}
|
||||
{node.files.map((item) => (
|
||||
<button
|
||||
className={item.path === path ? "selected" : ""}
|
||||
key={item.path}
|
||||
onClick={() => onSelect(item.path)}
|
||||
>
|
||||
{item.title}
|
||||
<small>{item.path}</small>
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<label>
|
||||
Search notebooks
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => {
|
||||
setAction("new");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
New notebook
|
||||
</button>
|
||||
<nav aria-label="Notebooks">
|
||||
{render(
|
||||
tree(
|
||||
list.filter((n) =>
|
||||
`${n.path} ${n.title}`
|
||||
.toLowerCase()
|
||||
.includes(search.toLowerCase()),
|
||||
),
|
||||
),
|
||||
)}
|
||||
</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 && (
|
||||
<form
|
||||
key={`${action}:${path}`}
|
||||
aria-label="Manage notebook"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
const data = new FormData(e.currentTarget);
|
||||
if (!canLeave()) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
let next: string | undefined;
|
||||
if (action === "new") {
|
||||
const folder = String(data.get("folder")).trim();
|
||||
let name = String(data.get("name")).trim();
|
||||
if (!name.endsWith(".md")) name += ".md";
|
||||
const result = await api.create(
|
||||
(folder ? folder + "/" : "") + name,
|
||||
newNotebook(String(data.get("title"))),
|
||||
);
|
||||
next = result.path;
|
||||
} else {
|
||||
if (!version)
|
||||
throw new Error("Reload the notebook before changing it");
|
||||
if (action === "delete")
|
||||
await api.deleteNotebook(path, version);
|
||||
else
|
||||
next = (
|
||||
await api.move(
|
||||
path,
|
||||
String(data.get("path")).trim(),
|
||||
version,
|
||||
action === "duplicate",
|
||||
)
|
||||
).path;
|
||||
}
|
||||
await onChanged(next);
|
||||
setAction(undefined);
|
||||
} catch (err) {
|
||||
setError(
|
||||
`${String(err)}. Refresh the list and retry if the notebook changed.`,
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<strong>
|
||||
{action === "delete"
|
||||
? `Delete ${path}? This cannot be undone.`
|
||||
: action === "new"
|
||||
? "New notebook"
|
||||
: `${action} ${path}`}
|
||||
</strong>
|
||||
{action === "new" ? (
|
||||
<>
|
||||
<label>
|
||||
Name
|
||||
<input name="name" required />
|
||||
</label>
|
||||
<label>
|
||||
Folder (optional)
|
||||
<input name="folder" placeholder="operations/linux" />
|
||||
</label>
|
||||
<label>
|
||||
Title
|
||||
<input name="title" required />
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
action !== "delete" && (
|
||||
<label>
|
||||
Destination path
|
||||
<input
|
||||
name="path"
|
||||
defaultValue={
|
||||
action === "duplicate"
|
||||
? path.replace(/\.md$/, "-copy.md")
|
||||
: path
|
||||
}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
)}
|
||||
<button disabled={busy}>
|
||||
{action === "delete" ? "Confirm delete" : "Apply"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setAction(undefined)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,17 @@ async function json<T>(
|
||||
: (response.json() as Promise<T>);
|
||||
}
|
||||
export interface Api {
|
||||
create(
|
||||
path: string,
|
||||
source: string,
|
||||
): Promise<{ path: string; version: string }>;
|
||||
move(
|
||||
path: string,
|
||||
target: string,
|
||||
baseVersion: string,
|
||||
duplicate?: boolean,
|
||||
): Promise<{ path: string; version: string }>;
|
||||
deleteNotebook(path: string, baseVersion: string): Promise<unknown>;
|
||||
me(): Promise<unknown>;
|
||||
login(password: string): Promise<unknown>;
|
||||
list(): Promise<NotebookListResponse>;
|
||||
@@ -48,6 +59,15 @@ export interface Api {
|
||||
artifact(runId: string, name: string): string;
|
||||
}
|
||||
export const liveApi: Api = {
|
||||
create: (path, source) => json("/notebooks", "POST", { path, source }),
|
||||
move: (path, target, baseVersion, duplicate = false) =>
|
||||
json(
|
||||
`/notebooks/${encodeURIComponent(path)}/${duplicate ? "duplicate" : "rename"}`,
|
||||
"POST",
|
||||
{ path: target, baseVersion },
|
||||
),
|
||||
deleteNotebook: (path, baseVersion) =>
|
||||
json(`/notebooks/${encodeURIComponent(path)}`, "DELETE", { baseVersion }),
|
||||
me: () => json("/auth/me"),
|
||||
login: (password) => json("/auth/login", "POST", { password }),
|
||||
list: () => json("/notebooks"),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { isMap, parseDocument } from "yaml";
|
||||
import {
|
||||
parseNotebook,
|
||||
type Block,
|
||||
type ParamDef,
|
||||
type Step,
|
||||
} from "@shellbook/core";
|
||||
export function notebookSteps(blocks: Block[]): Step[] {
|
||||
return blocks.flatMap((b) =>
|
||||
b.type === "step"
|
||||
? [b.step]
|
||||
: b.type === "after"
|
||||
? notebookSteps(b.blocks)
|
||||
: [],
|
||||
);
|
||||
}
|
||||
const attr = (value: string) =>
|
||||
'"' +
|
||||
value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/[\r\n]/g, " ") +
|
||||
'"';
|
||||
export type InsertKind =
|
||||
| "Check step"
|
||||
| "Run step"
|
||||
| "Artifacts"
|
||||
| "Upload"
|
||||
| "Capture";
|
||||
export function stepSnippet(
|
||||
source: string,
|
||||
kind: InsertKind,
|
||||
local: boolean,
|
||||
host = "host",
|
||||
): string {
|
||||
const ids = new Set(
|
||||
notebookSteps(parseNotebook(source).blocks).map((s) => s.attrs.id),
|
||||
);
|
||||
let n = 1;
|
||||
while (ids.has(`step-${n}`)) n++;
|
||||
const check = kind === "Check step" || kind === "Capture";
|
||||
const extra =
|
||||
kind === "Artifacts"
|
||||
? ' artifacts="result.txt"'
|
||||
: kind === "Upload"
|
||||
? ' upload="result.txt:/tmp/result.txt"'
|
||||
: kind === "Capture"
|
||||
? " capture=result"
|
||||
: "";
|
||||
const script =
|
||||
kind === "Artifacts"
|
||||
? "printf '%s\\n' 'Example result' > result.txt"
|
||||
: kind === "Upload"
|
||||
? "# Use the uploaded /tmp/result.txt here\n:"
|
||||
: check
|
||||
? "uname -s"
|
||||
: "# Replace with your command\n:";
|
||||
return `\n\n\`\`\`sh {${check ? "check" : "run"} ${local ? "on=local" : `host=${attr(`{{${host}}}`)}`} id=step-${n} title=${attr(kind)}${check ? "" : " confirm"}${extra}}\n${script}\n\`\`\`\n`;
|
||||
}
|
||||
export function afterSnippet(id: string): string {
|
||||
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
|
||||
}
|
||||
export function addParameter(source: string, def: ParamDef): string {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(def.name))
|
||||
throw new Error("Invalid parameter name");
|
||||
const match =
|
||||
/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[^\S\r\n]*(?:\r?\n|$)/.exec(
|
||||
source,
|
||||
);
|
||||
const doc = parseDocument(match?.[1] ?? "{}");
|
||||
if (doc.errors.length || !isMap(doc.contents))
|
||||
throw new Error("Fix frontmatter YAML first");
|
||||
if (doc.hasIn(["params", def.name]))
|
||||
throw new Error("Parameter already exists");
|
||||
if (doc.has("params") && !isMap(doc.get("params", true)))
|
||||
throw new Error("params must be a mapping");
|
||||
if (!doc.has("params")) doc.set("params", doc.createNode({}));
|
||||
const { name, ...fields } = def;
|
||||
if (def.type === "secret" && def.default !== undefined)
|
||||
throw new Error("Secrets cannot have defaults");
|
||||
doc.setIn(["params", name], doc.createNode(fields));
|
||||
const next = `---\n${doc.toString()}---\n${match ? source.slice(match[0].length) : source}`;
|
||||
const errors = parseNotebook(next).diagnostics;
|
||||
if (errors.length) throw new Error(errors.map((d) => d.message).join("; "));
|
||||
return next;
|
||||
}
|
||||
export function newNotebook(title: string): string {
|
||||
const doc = parseDocument("{}");
|
||||
doc.set("title", title.trim() || "New notebook");
|
||||
doc.set(
|
||||
"params",
|
||||
doc.createNode({
|
||||
host: { type: "host", required: true, label: "Target server" },
|
||||
}),
|
||||
);
|
||||
let source = `---\n${doc.toString()}---\n\n# ${title.replace(/[\r\n]/g, " ").trim() || "New notebook"}\n`;
|
||||
source += stepSnippet(source, "Check step", false);
|
||||
return source + stepSnippet(source, "Run step", false);
|
||||
}
|
||||
@@ -31,6 +31,15 @@ const artifactUrl = URL.createObjectURL(
|
||||
}),
|
||||
);
|
||||
export const mockApi: Api = {
|
||||
create: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
move: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
deleteNotebook: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
me: async () => ({ authenticated: true }),
|
||||
login: async () => undefined,
|
||||
list: async () => ({
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
.authoring {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
.authoring label,
|
||||
.sidebar form label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.authoring form,
|
||||
.authoring details {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.sidebar form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
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;
|
||||
}
|
||||
@@ -33,6 +33,15 @@ function harness() {
|
||||
let receive: (event: ServerEvent) => void = () => {};
|
||||
let id = 0;
|
||||
const api: Api = {
|
||||
create: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
move: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
deleteNotebook: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn().mockResolvedValue(undefined),
|
||||
list: vi.fn().mockResolvedValue({
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import { parse } from "yaml";
|
||||
import {
|
||||
addParameter,
|
||||
afterSnippet,
|
||||
newNotebook,
|
||||
notebookSteps,
|
||||
stepSnippet,
|
||||
type InsertKind,
|
||||
} from "../authoring";
|
||||
it.each([
|
||||
"Check step",
|
||||
"Run step",
|
||||
"Artifacts",
|
||||
"Upload",
|
||||
"Capture",
|
||||
] as InsertKind[])(
|
||||
"generates valid %s fences for both targets and unique ids",
|
||||
(kind) => {
|
||||
for (const local of [true, false]) {
|
||||
let source = newNotebook('Title: "quoted"');
|
||||
source += stepSnippet(source, kind, local);
|
||||
source += stepSnippet(source, kind, local);
|
||||
source += afterSnippet(
|
||||
notebookSteps(parseNotebook(source).blocks)[0]!.attrs.id,
|
||||
);
|
||||
expect(parseNotebook(source).diagnostics).toEqual([]);
|
||||
expect(notebookSteps(parseNotebook(source).blocks)).toHaveLength(4);
|
||||
}
|
||||
},
|
||||
);
|
||||
it("preserves other YAML, comments, body and existing params", () => {
|
||||
const source =
|
||||
"---\n# keep comment\ntitle: Original\ncustom: {nested: [one, two]}\nparams:\n host: {type: host}\n---\n\n# Body\n";
|
||||
const next = addParameter(source, {
|
||||
name: "mode",
|
||||
type: "choice",
|
||||
required: true,
|
||||
options: ["a", "b"],
|
||||
default: "a",
|
||||
label: "Mode",
|
||||
});
|
||||
expect(parseNotebook(next).diagnostics).toEqual([]);
|
||||
expect(next).toContain("# keep comment");
|
||||
expect(next).toContain("\n\n# Body\n");
|
||||
const yaml = parse(next.split("---")[1]!);
|
||||
expect(yaml.custom).toEqual({ nested: ["one", "two"] });
|
||||
expect(yaml.params.host).toEqual({ type: "host" });
|
||||
expect(yaml.params.mode.options).toEqual(["a", "b"]);
|
||||
expect(() =>
|
||||
addParameter(next, { name: "host", type: "host", required: true }),
|
||||
).toThrow("already exists");
|
||||
});
|
||||
it("adds frontmatter when absent and rejects invalid YAML or secret defaults", () => {
|
||||
expect(
|
||||
parseNotebook(
|
||||
addParameter("# Title\n", {
|
||||
name: "token",
|
||||
type: "secret",
|
||||
required: true,
|
||||
}),
|
||||
).diagnostics,
|
||||
).toEqual([]);
|
||||
expect(() =>
|
||||
addParameter("---\nx: [\n---\n", {
|
||||
name: "a",
|
||||
type: "string",
|
||||
required: false,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
addParameter("# Title", {
|
||||
name: "token",
|
||||
type: "secret",
|
||||
required: true,
|
||||
default: "bad",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import { AuthoringToolbar } from "../AuthoringToolbar";
|
||||
import { NotebookList } from "../NotebookList";
|
||||
import { newNotebook } from "../authoring";
|
||||
import type { Api } from "../api";
|
||||
it("inserts snippets and adds parameters through forms", () => {
|
||||
const insert = vi.fn(),
|
||||
replace = vi.fn();
|
||||
render(
|
||||
<AuthoringToolbar
|
||||
source={newNotebook("Example")}
|
||||
insert={insert}
|
||||
replace={replace}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Run step" }));
|
||||
expect(insert.mock.calls[0]![0]).toContain("on=local");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Parameter" }));
|
||||
fireEvent.change(screen.getByLabelText("Parameter name"), {
|
||||
target: { value: "package" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add parameter" }));
|
||||
expect(
|
||||
parseNotebook(replace.mock.calls[0]![0]).params.some(
|
||||
(p) => p.name === "package",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
it("shows a folder tree, filters, creates and navigates", async () => {
|
||||
const create = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ path: "ops/new.md", version: "1" });
|
||||
const changed = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<NotebookList
|
||||
api={{ create } as unknown as Api}
|
||||
list={[
|
||||
{ path: "ops/a.md", title: "Alpha" },
|
||||
{ path: "b.md", title: "Beta" },
|
||||
]}
|
||||
path=""
|
||||
onSelect={vi.fn()}
|
||||
onChanged={changed}
|
||||
canLeave={() => true}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("ops")).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Search notebooks"), {
|
||||
target: { value: "Alpha" },
|
||||
});
|
||||
expect(screen.queryByText("Beta")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New notebook" }));
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
|
||||
fireEvent.change(screen.getByLabelText("Folder (optional)"), {
|
||||
target: { value: "ops" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Title"), {
|
||||
target: { value: "New" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
await waitFor(() => expect(changed).toHaveBeenCalledWith("ops/new.md"));
|
||||
expect(create.mock.calls[0]![0]).toBe("ops/new.md");
|
||||
expect(parseNotebook(create.mock.calls[0]![1]).diagnostics).toEqual([]);
|
||||
});
|
||||
it("requires explicit delete confirmation and uses the displayed version", async () => {
|
||||
const remove = vi.fn().mockResolvedValue({ deleted: true });
|
||||
const changed = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<NotebookList
|
||||
api={
|
||||
{
|
||||
notebook: async () => ({ version: "latest" }),
|
||||
deleteNotebook: remove,
|
||||
} as unknown as Api
|
||||
}
|
||||
list={[]}
|
||||
path="a.md"
|
||||
version="latest"
|
||||
onSelect={vi.fn()}
|
||||
onChanged={changed}
|
||||
canLeave={() => true}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
|
||||
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
|
||||
});
|
||||
Reference in New Issue
Block a user