Merge branch 't3/notebook-management-authoring'
# Conflicts: # .agents/mind/architecture.md # packages/core/src/protocol.ts
This commit is contained in:
@@ -9,5 +9,6 @@
|
|||||||
- [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3.
|
- [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3.
|
||||||
|
|
||||||
- [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets.
|
- [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets.
|
||||||
|
- [2026-11-16] **Notebook management (#9):** a shared mutation queue serializes saves/create/move/duplicate/delete. Exclusive hard-link publication prevents target replacement; saves use temp+rename. The recursive watcher updates lists; deleted open drafts are retained. Frontmatter helpers use YAML document nodes.
|
||||||
|
|
||||||
## Archive
|
## Archive
|
||||||
|
|||||||
@@ -7,4 +7,6 @@
|
|||||||
- [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`.
|
- [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`.
|
||||||
- [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures.
|
- [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures.
|
||||||
|
|
||||||
|
- [2026-11-16] **Notebook root symlinks (#9):** validating only child components after realpath(root) permits a symlinked notebooks root. Notebook reads and mutations validate the root itself before walking children; regression-covered. Workspace CLI/filesystem writers remain trusted against concurrent path swaps.
|
||||||
|
|
||||||
## Archive
|
## Archive
|
||||||
|
|||||||
@@ -17,4 +17,4 @@
|
|||||||
- `architecture.md` — 8 entries — why custom app, stack, AI integration, workspace split
|
- `architecture.md` — 8 entries — why custom app, stack, AI integration, workspace split
|
||||||
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
|
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
|
||||||
- `open.md` — 2 entries — open design questions
|
- `open.md` — 2 entries — open design questions
|
||||||
- `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names)
|
- `gotchas.md` — 6 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
|
import { atomicNotebookWrite, notebookRoot, notebookManagement } from "./notebooks";
|
||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises";
|
import { readFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { parse } from "yaml";
|
import { parse } from "yaml";
|
||||||
import { parseNotebook, type HostInfo } from "@shellbook/core";
|
import { parseNotebook, type HostInfo } from "@shellbook/core";
|
||||||
@@ -34,6 +35,8 @@ export async function safeFile(root: string, name: string): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function readNotebook(config: ServerConfig, name: string) {
|
export async function readNotebook(config: ServerConfig, name: string) {
|
||||||
|
// Name rules apply to creating notebooks only; existing files (git, Claude) stay readable.
|
||||||
|
await notebookRoot(config);
|
||||||
if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed");
|
if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed");
|
||||||
const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name);
|
const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name);
|
||||||
return { file, source: await readFile(file, "utf8") };
|
return { file, source: await readFile(file, "utf8") };
|
||||||
@@ -71,6 +74,7 @@ export class SerialQueue {
|
|||||||
|
|
||||||
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
|
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
|
||||||
const saves = new SerialQueue();
|
const saves = new SerialQueue();
|
||||||
|
notebookManagement(app, config, saves);
|
||||||
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
|
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
|
||||||
app.get("/api/notebooks", async () => {
|
app.get("/api/notebooks", async () => {
|
||||||
const notebooks: { path: string; title: string }[] = [];
|
const notebooks: { path: string; title: string }[] = [];
|
||||||
@@ -84,6 +88,7 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await notebookRoot(config);
|
||||||
await walk(path.join(config.workspaceDir, "notebooks"));
|
await walk(path.join(config.workspaceDir, "notebooks"));
|
||||||
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
|
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||||
});
|
});
|
||||||
@@ -93,10 +98,10 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
|||||||
});
|
});
|
||||||
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
|
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
|
||||||
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
|
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
|
||||||
return saves.run(req.params.path, async () => {
|
return saves.run("notebooks", async () => {
|
||||||
const { file, source } = await readNotebook(config, req.params.path);
|
const { file, source } = await readNotebook(config, req.params.path);
|
||||||
if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed");
|
if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed");
|
||||||
await writeFile(file, req.body.source, "utf8");
|
await atomicNotebookWrite(file, req.body.source);
|
||||||
return { version: version(req.body.source) };
|
return { version: version(req.body.source) };
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import {
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
realpath,
|
||||||
|
writeFile,
|
||||||
|
rename,
|
||||||
|
unlink,
|
||||||
|
rmdir,
|
||||||
|
link,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import type {
|
||||||
|
CreateNotebookRequest,
|
||||||
|
MoveNotebookRequest,
|
||||||
|
DeleteNotebookRequest,
|
||||||
|
} from "@shellbook/core";
|
||||||
|
import { httpError, readNotebook, SerialQueue, version } from "./index";
|
||||||
|
import type { ServerConfig } from "../config";
|
||||||
|
|
||||||
|
export function notebookName(name: string): string {
|
||||||
|
if (
|
||||||
|
typeof name !== "string" ||
|
||||||
|
name.length > 240 ||
|
||||||
|
!name.endsWith(".md") ||
|
||||||
|
name
|
||||||
|
.split("/")
|
||||||
|
.some(
|
||||||
|
(p) =>
|
||||||
|
!/^[A-Za-z0-9][A-Za-z0-9 _.-]*$/.test(p) ||
|
||||||
|
p.includes("..") ||
|
||||||
|
/[. ]$/.test(p) ||
|
||||||
|
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw httpError(
|
||||||
|
400,
|
||||||
|
"Use a relative .md path with letters, numbers, spaces, dots, underscores or hyphens",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Validate the root before resolving any notebook path. */
|
||||||
|
export async function notebookRoot(config: ServerConfig): Promise<string> {
|
||||||
|
const root = path.join(await realpath(config.workspaceDir), "notebooks");
|
||||||
|
try {
|
||||||
|
const info = await lstat(root);
|
||||||
|
if (info.isSymbolicLink() || !info.isDirectory())
|
||||||
|
throw httpError(
|
||||||
|
400,
|
||||||
|
"Symlinks and non-directory parents are not allowed",
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Walk every component; never follow symlinks. */
|
||||||
|
export async function notebookDestination(
|
||||||
|
config: ServerConfig,
|
||||||
|
name: string,
|
||||||
|
): Promise<string> {
|
||||||
|
notebookName(name);
|
||||||
|
let current = await notebookRoot(config);
|
||||||
|
const parts = name.split("/");
|
||||||
|
for (let i = 0; i < parts.length; i++) {
|
||||||
|
current = path.join(current, parts[i]!);
|
||||||
|
try {
|
||||||
|
const info = await lstat(current);
|
||||||
|
if (
|
||||||
|
info.isSymbolicLink() ||
|
||||||
|
(i < parts.length - 1 && !info.isDirectory())
|
||||||
|
)
|
||||||
|
throw httpError(
|
||||||
|
400,
|
||||||
|
"Symlinks and non-directory parents are not allowed",
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function atomicNotebookWrite(
|
||||||
|
file: string,
|
||||||
|
source: string,
|
||||||
|
exclusive = false,
|
||||||
|
) {
|
||||||
|
await mkdir(path.dirname(file), { recursive: true });
|
||||||
|
const temp = path.join(path.dirname(file), `.shellbook-${randomUUID()}.tmp`);
|
||||||
|
try {
|
||||||
|
await writeFile(temp, source, {
|
||||||
|
encoding: "utf8",
|
||||||
|
flag: "wx",
|
||||||
|
mode: 0o600,
|
||||||
|
});
|
||||||
|
// link publishes a complete file without replacing an existing destination.
|
||||||
|
if (exclusive) await link(temp, file);
|
||||||
|
else await rename(temp, file);
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as NodeJS.ErrnoException).code === "EEXIST")
|
||||||
|
throw httpError(409, "Notebook already exists");
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
await unlink(temp).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function prune(config: ServerConfig, file: string) {
|
||||||
|
// Same resolved root as the file path; stop at it, never walk above it.
|
||||||
|
const root = await notebookRoot(config);
|
||||||
|
for (let dir = path.dirname(file); dir.startsWith(root + path.sep); dir = path.dirname(dir)) {
|
||||||
|
try {
|
||||||
|
await rmdir(dir);
|
||||||
|
} catch (e) {
|
||||||
|
if (
|
||||||
|
["ENOTEMPTY", "EEXIST", "ENOENT"].includes(
|
||||||
|
(e as NodeJS.ErrnoException).code ?? "",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function notebookManagement(
|
||||||
|
app: FastifyInstance,
|
||||||
|
config: ServerConfig,
|
||||||
|
queue: SerialQueue,
|
||||||
|
) {
|
||||||
|
app.post<{ Body: CreateNotebookRequest }>("/api/notebooks", async (req) =>
|
||||||
|
queue.run("notebooks", async () => {
|
||||||
|
if (!req.body || typeof req.body.source !== "string")
|
||||||
|
throw httpError(400, "Invalid notebook");
|
||||||
|
const file = await notebookDestination(config, req.body.path);
|
||||||
|
await atomicNotebookWrite(file, req.body.source, true);
|
||||||
|
return { path: req.body.path, version: version(req.body.source) };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
for (const operation of ["rename", "duplicate"] as const) {
|
||||||
|
app.post<{ Params: { path: string }; Body: MoveNotebookRequest }>(
|
||||||
|
`/api/notebooks/:path/${operation}`,
|
||||||
|
async (req) =>
|
||||||
|
queue.run("notebooks", async () => {
|
||||||
|
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||||
|
throw httpError(400, "Missing baseVersion");
|
||||||
|
// Only the new path must satisfy the create rules; the source may predate them.
|
||||||
|
const { file: original, source } = await readNotebook(config, req.params.path);
|
||||||
|
if (version(source) !== req.body.baseVersion)
|
||||||
|
throw httpError(409, "Notebook changed");
|
||||||
|
const target = await notebookDestination(config, req.body.path);
|
||||||
|
await atomicNotebookWrite(target, source, true);
|
||||||
|
if (operation === "rename") {
|
||||||
|
try {
|
||||||
|
await unlink(original);
|
||||||
|
} catch (e) {
|
||||||
|
await unlink(target);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
await prune(config, original);
|
||||||
|
}
|
||||||
|
return { path: req.body.path, version: version(source) };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
app.delete<{ Params: { path: string }; Body: DeleteNotebookRequest }>(
|
||||||
|
"/api/notebooks/:path",
|
||||||
|
async (req) =>
|
||||||
|
queue.run("notebooks", async () => {
|
||||||
|
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||||
|
throw httpError(400, "Missing baseVersion");
|
||||||
|
const { file, source } = await readNotebook(config, req.params.path);
|
||||||
|
if (version(source) !== req.body.baseVersion)
|
||||||
|
throw httpError(409, "Notebook changed");
|
||||||
|
await unlink(file);
|
||||||
|
await prune(config, file);
|
||||||
|
return { deleted: true };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
import { afterEach, expect, it } from "vitest";
|
||||||
|
import { mkdtemp, mkdir, rm, symlink, stat } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { buildApp } from "../src/app";
|
||||||
|
import { notebookName, notebookDestination } from "../src/workspace/notebooks";
|
||||||
|
import { setPassword } from "../src/auth/credentials";
|
||||||
|
const dirs: string[] = [];
|
||||||
|
afterEach(async () => {
|
||||||
|
for (const dir of dirs.splice(0))
|
||||||
|
await rm(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
async function setup(auth = false) {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), "shellbook-notebooks-"));
|
||||||
|
dirs.push(dir);
|
||||||
|
await mkdir(join(dir, "notebooks"));
|
||||||
|
await setPassword(dir, "test password");
|
||||||
|
return {
|
||||||
|
dir,
|
||||||
|
app: await buildApp({
|
||||||
|
config: { workspaceDir: dir, dataDir: dir },
|
||||||
|
auth: auth ? { dataDir: dir } : false,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
it.each([
|
||||||
|
"../x.md",
|
||||||
|
"/x.md",
|
||||||
|
"C:/x.md",
|
||||||
|
"a\\x.md",
|
||||||
|
"a/../x.md",
|
||||||
|
"a//x.md",
|
||||||
|
"a.txt",
|
||||||
|
"a/./x.md",
|
||||||
|
"nul.md",
|
||||||
|
"x\u0000.md",
|
||||||
|
"a./x.md",
|
||||||
|
])("rejects invalid notebook path %s", (name) => {
|
||||||
|
expect(() => notebookName(name)).toThrow();
|
||||||
|
});
|
||||||
|
it("rejects symlink parents, files and notebook root", async () => {
|
||||||
|
const { app, dir } = await setup();
|
||||||
|
try {
|
||||||
|
await mkdir(join(dir, "outside"));
|
||||||
|
await symlink(
|
||||||
|
join(dir, "outside"),
|
||||||
|
join(dir, "notebooks", "linked"),
|
||||||
|
"junction",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
notebookDestination({ workspaceDir: dir } as never, "linked/new.md"),
|
||||||
|
).rejects.toThrow("Symlinks");
|
||||||
|
await rm(join(dir, "notebooks"), { recursive: true });
|
||||||
|
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
|
||||||
|
await expect(
|
||||||
|
notebookDestination({ workspaceDir: dir } as never, "new.md"),
|
||||||
|
).rejects.toThrow("Symlinks");
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("creates, duplicates, moves, saves and deletes with conflicts and prunes folders", async () => {
|
||||||
|
const { app, dir } = await setup();
|
||||||
|
const url = (p: string) => `/api/notebooks/${encodeURIComponent(p)}`;
|
||||||
|
try {
|
||||||
|
const created = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/notebooks",
|
||||||
|
payload: { path: "old/a.md", source: "# A\n" },
|
||||||
|
});
|
||||||
|
expect(created.statusCode).toBe(200);
|
||||||
|
let baseVersion = created.json().version;
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/notebooks",
|
||||||
|
payload: { path: "old/a.md", source: "overwrite" },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(409);
|
||||||
|
for (const op of ["rename", "duplicate"]) {
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: url("old/a.md") + `/${op}`,
|
||||||
|
payload: { path: "new/b.md", baseVersion: "stale" },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(409);
|
||||||
|
}
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: url("old/a.md") + "/duplicate",
|
||||||
|
payload: { path: "copy.md", baseVersion },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(200);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: url("old/a.md") + "/rename",
|
||||||
|
payload: { path: "copy.md", baseVersion },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(409);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: url("old/a.md") + "/rename",
|
||||||
|
payload: { path: "new/b.md", baseVersion },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(200);
|
||||||
|
await expect(stat(join(dir, "notebooks", "old"))).rejects.toThrow();
|
||||||
|
expect((await app.inject(url("new/b.md"))).json().source).toBe("# A\n");
|
||||||
|
const saved = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: url("new/b.md"),
|
||||||
|
payload: { source: "# B", baseVersion },
|
||||||
|
});
|
||||||
|
expect(saved.statusCode).toBe(200);
|
||||||
|
baseVersion = saved.json().version;
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "DELETE",
|
||||||
|
url: url("new/b.md"),
|
||||||
|
payload: { baseVersion: "stale" },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(409);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "DELETE",
|
||||||
|
url: url("new/b.md"),
|
||||||
|
payload: { baseVersion },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(200);
|
||||||
|
await expect(stat(join(dir, "notebooks", "new"))).rejects.toThrow();
|
||||||
|
expect((await app.inject(url("new/b.md"))).statusCode).toBe(404);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("guards every management route with session and origin checks", async () => {
|
||||||
|
const { app } = await setup(true);
|
||||||
|
try {
|
||||||
|
const login = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/auth/login",
|
||||||
|
payload: { password: "test password" },
|
||||||
|
});
|
||||||
|
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
|
||||||
|
for (const [method, url] of [
|
||||||
|
["POST", "/api/notebooks"],
|
||||||
|
["POST", "/api/notebooks/a.md/rename"],
|
||||||
|
["POST", "/api/notebooks/a.md/duplicate"],
|
||||||
|
["DELETE", "/api/notebooks/a.md"],
|
||||||
|
] as const) {
|
||||||
|
expect((await app.inject({ method, url, payload: {} })).statusCode).toBe(
|
||||||
|
401,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
payload: {},
|
||||||
|
headers: { cookie, origin: "https://evil.test" },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(403);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects notebook reads through a symlinked notebooks root", async () => {
|
||||||
|
const { app, dir } = await setup();
|
||||||
|
try {
|
||||||
|
const { writeFile } = await import("node:fs/promises");
|
||||||
|
await mkdir(join(dir, "outside"));
|
||||||
|
await writeFile(join(dir, "outside", "secret.md"), "private");
|
||||||
|
await rm(join(dir, "notebooks"), { recursive: true });
|
||||||
|
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
|
||||||
|
expect((await app.inject("/api/notebooks/secret.md")).statusCode).toBe(400);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("publishes create/move/delete changes to other tabs through the watcher", async () => {
|
||||||
|
const { vi } = await import("vitest");
|
||||||
|
const { EventsHub } = await import("../src/runs");
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), "shellbook-events-"));
|
||||||
|
dirs.push(dir);
|
||||||
|
await mkdir(join(dir, "notebooks"));
|
||||||
|
const hub = new EventsHub();
|
||||||
|
const events: unknown[] = [];
|
||||||
|
hub.subscribe((event) => events.push(event));
|
||||||
|
const app = await buildApp({
|
||||||
|
config: { workspaceDir: dir, dataDir: dir },
|
||||||
|
auth: false,
|
||||||
|
events: hub,
|
||||||
|
watchNotebooks: true,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const created = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/notebooks",
|
||||||
|
payload: { path: "old/a.md", source: "# A" },
|
||||||
|
});
|
||||||
|
await vi.waitFor(() =>
|
||||||
|
expect(events).toContainEqual({ type: "file.changed", path: "old/a.md" }),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/notebooks/old%2Fa.md/rename",
|
||||||
|
payload: { path: "new/a.md", baseVersion: created.json().version },
|
||||||
|
})
|
||||||
|
).statusCode,
|
||||||
|
).toBe(200);
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(events).toContainEqual({ type: "file.deleted", path: "old/a.md" });
|
||||||
|
expect(events).toContainEqual({ type: "file.changed", path: "new/a.md" });
|
||||||
|
});
|
||||||
|
await app.inject({
|
||||||
|
method: "DELETE",
|
||||||
|
url: "/api/notebooks/new%2Fa.md",
|
||||||
|
payload: { baseVersion: created.json().version },
|
||||||
|
});
|
||||||
|
await vi.waitFor(() =>
|
||||||
|
expect(events).toContainEqual({ type: "file.deleted", path: "new/a.md" }),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("does not overwrite concurrent creates", async () => {
|
||||||
|
const { app } = await setup();
|
||||||
|
try {
|
||||||
|
const responses = await Promise.all(
|
||||||
|
["one", "two"].map((source) =>
|
||||||
|
app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/notebooks",
|
||||||
|
payload: { path: "race.md", source },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(responses.map((r) => r.statusCode).sort()).toEqual([200, 409]);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("still opens and saves existing notebooks whose names the create rules would reject", async () => {
|
||||||
|
const { app, dir } = await setup();
|
||||||
|
try {
|
||||||
|
const { writeFile } = await import("node:fs/promises");
|
||||||
|
// Written by git or Claude, not through the create API.
|
||||||
|
await writeFile(join(dir, "notebooks", "Übersicht (alt).md"), "# Old\n");
|
||||||
|
const name = encodeURIComponent("Übersicht (alt).md");
|
||||||
|
const read = await app.inject(`/api/notebooks/${name}`);
|
||||||
|
expect(read.statusCode).toBe(200);
|
||||||
|
const save = await app.inject({ method: "PUT", url: `/api/notebooks/${name}`, payload: { source: "# New\n", baseVersion: read.json().version } });
|
||||||
|
expect(save.statusCode).toBe(200);
|
||||||
|
const moved = await app.inject({ method: "POST", url: `/api/notebooks/${name}/rename`, payload: { path: "uebersicht.md", baseVersion: save.json().version } });
|
||||||
|
expect(moved.statusCode).toBe(200);
|
||||||
|
expect((await app.inject("/api/notebooks/uebersicht.md")).statusCode).toBe(200);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never removes folders outside notebooks/ when the workspace path is a symlink", async () => {
|
||||||
|
const real = await mkdtemp(join(tmpdir(), "shellbook-real-"));
|
||||||
|
const linkParent = await mkdtemp(join(tmpdir(), "shellbook-link-"));
|
||||||
|
dirs.push(real, linkParent);
|
||||||
|
await mkdir(join(real, "notebooks"));
|
||||||
|
const workspace = join(linkParent, "ws");
|
||||||
|
await symlink(real, workspace, "junction");
|
||||||
|
const app = await buildApp({ config: { workspaceDir: workspace, dataDir: real }, auth: false });
|
||||||
|
try {
|
||||||
|
const created = await app.inject({ method: "POST", url: "/api/notebooks", payload: { path: "a/x.md", source: "# X\n" } });
|
||||||
|
expect(created.statusCode).toBe(200);
|
||||||
|
const deleted = await app.inject({ method: "DELETE", url: `/api/notebooks/${encodeURIComponent("a/x.md")}`, payload: { baseVersion: created.json().version } });
|
||||||
|
expect(deleted.statusCode).toBe(200);
|
||||||
|
expect((await stat(join(real, "notebooks"))).isDirectory()).toBe(true);
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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
|
downloads (including 410), after sections, capture substitution, and authorize
|
||||||
artifact provenance. Real tmux/Claude login and browser terminal rendering still
|
artifact provenance. Real tmux/Claude login and browser terminal rendering still
|
||||||
need an interactive server check.
|
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",
|
"codemirror": "^6.0.1",
|
||||||
"highlight.js": "^11.10.0",
|
"highlight.js": "^11.10.0",
|
||||||
"@xterm/xterm": "^5.5.0",
|
"@xterm/xterm": "^5.5.0",
|
||||||
"@xterm/addon-fit": "^0.10.0"
|
"@xterm/addon-fit": "^0.10.0",
|
||||||
|
"yaml": "^2.6.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "^18.3.12",
|
"@types/react": "^18.3.12",
|
||||||
|
|||||||
+31
-15
@@ -28,6 +28,7 @@ import type {
|
|||||||
StartRunRequest,
|
StartRunRequest,
|
||||||
Step,
|
Step,
|
||||||
} from "@shellbook/core";
|
} from "@shellbook/core";
|
||||||
|
import { NotebookList } from "./NotebookList";
|
||||||
import { HttpError } from "./api";
|
import { HttpError } from "./api";
|
||||||
import type { Api } from "./api";
|
import type { Api } from "./api";
|
||||||
import { emptySession, eventReducer, stepKey } from "./events";
|
import { emptySession, eventReducer, stepKey } from "./events";
|
||||||
@@ -129,6 +130,14 @@ export function App({ api }: { api: Api }) {
|
|||||||
.catch((e) => setError(String(e)));
|
.catch((e) => setError(String(e)));
|
||||||
const close = api.events((event: ServerEvent) => {
|
const close = api.events((event: ServerEvent) => {
|
||||||
const open = current.current;
|
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 (event.type === "file.changed" && event.path === open.doc?.path) {
|
||||||
if (open.dirty) setConflict(true);
|
if (open.dirty) setConflict(true);
|
||||||
else void load(event.path);
|
else void load(event.path);
|
||||||
@@ -334,21 +343,28 @@ export function App({ api }: { api: Api }) {
|
|||||||
<h1>
|
<h1>
|
||||||
ShellBook<span>RUNBOOKS</span>
|
ShellBook<span>RUNBOOKS</span>
|
||||||
</h1>
|
</h1>
|
||||||
<nav aria-label="Notebooks">
|
<NotebookList
|
||||||
{list.map((item) => (
|
api={api}
|
||||||
<button
|
list={list}
|
||||||
className={path === item.path ? "selected" : ""}
|
path={path}
|
||||||
key={item.path}
|
version={doc?.version}
|
||||||
onClick={() => {
|
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
|
||||||
if (!dirty || window.confirm("Discard unsaved edits?"))
|
onSelect={(next) => {
|
||||||
void load(item.path);
|
if (!dirty || window.confirm("Discard unsaved edits?"))
|
||||||
}}
|
void load(next);
|
||||||
>
|
}}
|
||||||
{item.title}
|
onChanged={async (next) => {
|
||||||
<small>{item.path}</small>
|
const result = await api.list();
|
||||||
</button>
|
setList(result.notebooks);
|
||||||
))}
|
if (next) await load(next);
|
||||||
</nav>
|
else {
|
||||||
|
++loadSequence.current;
|
||||||
|
setDoc(undefined);
|
||||||
|
setSource("");
|
||||||
|
setConflict(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<small className="connection">
|
<small className="connection">
|
||||||
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
|
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
|
||||||
{connected
|
{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 { useEffect, useRef } from "react";
|
||||||
import { EditorView } from "@codemirror/view";
|
import { EditorView } from "@codemirror/view";
|
||||||
import { basicSetup } from "codemirror";
|
import { basicSetup } from "codemirror";
|
||||||
@@ -10,6 +11,7 @@ export function Editor({
|
|||||||
source: string;
|
source: string;
|
||||||
onChange(source: string): void;
|
onChange(source: string): void;
|
||||||
}) {
|
}) {
|
||||||
|
const editor = useRef<EditorView>();
|
||||||
const root = useRef<HTMLDivElement>(null);
|
const root = useRef<HTMLDivElement>(null);
|
||||||
const change = useRef(onChange);
|
const change = useRef(onChange);
|
||||||
change.current = 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.
|
// Editor lifetime matches edit mode. Parent remounts after reload.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// 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>);
|
: (response.json() as Promise<T>);
|
||||||
}
|
}
|
||||||
export interface Api {
|
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>;
|
me(): Promise<unknown>;
|
||||||
login(password: string): Promise<unknown>;
|
login(password: string): Promise<unknown>;
|
||||||
list(): Promise<NotebookListResponse>;
|
list(): Promise<NotebookListResponse>;
|
||||||
@@ -48,6 +59,15 @@ export interface Api {
|
|||||||
artifact(runId: string, name: string): string;
|
artifact(runId: string, name: string): string;
|
||||||
}
|
}
|
||||||
export const liveApi: Api = {
|
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"),
|
me: () => json("/auth/me"),
|
||||||
login: (password) => json("/auth/login", "POST", { password }),
|
login: (password) => json("/auth/login", "POST", { password }),
|
||||||
list: () => json("/notebooks"),
|
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 = {
|
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 }),
|
me: async () => ({ authenticated: true }),
|
||||||
login: async () => undefined,
|
login: async () => undefined,
|
||||||
list: async () => ({
|
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 receive: (event: ServerEvent) => void = () => {};
|
||||||
let id = 0;
|
let id = 0;
|
||||||
const api: Api = {
|
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({}),
|
me: vi.fn().mockResolvedValue({}),
|
||||||
login: vi.fn().mockResolvedValue(undefined),
|
login: vi.fn().mockResolvedValue(undefined),
|
||||||
list: vi.fn().mockResolvedValue({
|
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"));
|
||||||
|
});
|
||||||
@@ -143,6 +143,18 @@ only, then removed.
|
|||||||
- Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk
|
- Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk
|
||||||
(by Claude or git pull) reload live.
|
(by Claude or git pull) reload live.
|
||||||
|
|
||||||
|
- Notebook management: searchable folder tree; create with name/folder/title and a
|
||||||
|
valid starter, rename/move, duplicate, and explicitly confirmed delete. Paths are
|
||||||
|
relative to `notebooks/`; folders are created as needed and pruned when empty.
|
||||||
|
- Editor toolbar inserts checks, runs, artifact downloads, uploads, captures and
|
||||||
|
after-step notes at the cursor. A parameter form edits YAML frontmatter through
|
||||||
|
a YAML document parser; format help explains syntax. Targets are local or host
|
||||||
|
parameters. Examples must be reviewed before execution.
|
||||||
|
- Mutations use optimistic versions; occupied destinations or stale versions return
|
||||||
|
409. Atomic file publication and recursive watcher events refresh all tabs. An
|
||||||
|
external rename/delete retains the old open draft with a notice and refreshes
|
||||||
|
the tree; users can select the new path. Unsaved navigation requires confirmation.
|
||||||
|
|
||||||
## 6. AI: Claude Code
|
## 6. AI: Claude Code
|
||||||
|
|
||||||
- The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the
|
- The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the
|
||||||
|
|||||||
@@ -135,3 +135,14 @@ export interface ChangePasswordRequest extends NewPasswordRequest { currentPassw
|
|||||||
export interface SessionSettingsResponse { lifetimeSeconds: number }
|
export interface SessionSettingsResponse { lifetimeSeconds: number }
|
||||||
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
|
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
|
||||||
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }
|
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }
|
||||||
|
|
||||||
|
// ---- notebook management (#9) ------------------------------------------------
|
||||||
|
// Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets.
|
||||||
|
// POST /api/notebooks
|
||||||
|
export interface CreateNotebookRequest { path: string; source: string }
|
||||||
|
// POST /api/notebooks/:path/rename or /duplicate
|
||||||
|
export interface MoveNotebookRequest { path: string; baseVersion: string }
|
||||||
|
// DELETE /api/notebooks/:path
|
||||||
|
export interface DeleteNotebookRequest { baseVersion: string }
|
||||||
|
export interface NotebookMutationResponse { path: string; version: string }
|
||||||
|
export interface DeleteNotebookResponse { deleted: boolean }
|
||||||
|
|||||||
Generated
+3
@@ -90,6 +90,9 @@ importers:
|
|||||||
react-markdown:
|
react-markdown:
|
||||||
specifier: ^9.0.1
|
specifier: ^9.0.1
|
||||||
version: 9.1.0(@types/[email protected])([email protected])
|
version: 9.1.0(@types/[email protected])([email protected])
|
||||||
|
yaml:
|
||||||
|
specifier: ^2.6.1
|
||||||
|
version: 2.9.1
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@testing-library/jest-dom':
|
'@testing-library/jest-dom':
|
||||||
specifier: ^6.6.3
|
specifier: ^6.6.3
|
||||||
|
|||||||
Reference in New Issue
Block a user