From 08d5441cf26f690106bf38daa6449613559b6df7 Mon Sep 17 00:00:00 2001
From: Florian Schmidt
Date: Mon, 16 Nov 2026 00:21:03 +0100
Subject: [PATCH 1/3] refactor(web): use real core in demos and tests (#4, #5)
---
apps/web/src/mock/api.ts | 2 +-
apps/web/src/mock/core.ts | 204 -------------------------
apps/web/src/tests/app.test.tsx | 3 +-
apps/web/src/tests/components.test.tsx | 1 -
apps/web/src/tests/ssh.test.ts | 3 +-
apps/web/vite.config.ts | 32 +---
6 files changed, 8 insertions(+), 237 deletions(-)
delete mode 100644 apps/web/src/mock/core.ts
diff --git a/apps/web/src/mock/api.ts b/apps/web/src/mock/api.ts
index c3970a5..498ecb3 100644
--- a/apps/web/src/mock/api.ts
+++ b/apps/web/src/mock/api.ts
@@ -1,7 +1,7 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
-import { parseNotebook, renderStep } from "./core";
+import { parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
diff --git a/apps/web/src/mock/core.ts b/apps/web/src/mock/core.ts
deleted file mode 100644
index 824adf1..0000000
--- a/apps/web/src/mock/core.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-/** TEMPORARY M0 fallback. Demo-only Vite alias; never used in production.
- * Remove this file and the alias when core lands. Parser supports the fixture
- * body syntax only; frontmatter definitions are fixed to spec §3.1.
- */
-import type {
- Block,
- Notebook,
- ParamValues,
- RenderedStep,
- Step,
- StepAttrs,
-} from "../../../../packages/core/src/types";
-export function shellQuote(value: string): string {
- return value && /^[A-Za-z0-9._/@:=+-]+$/.test(value)
- ? value
- : `'${value.replace(/'/g, "'\\''")}'`;
-}
-export function parseNotebook(source: string): Notebook {
- const lines = source
- .replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")
- .split(/\r?\n/);
- function parse(
- start: number,
- nested = false,
- ): { blocks: Block[]; end: number } {
- const blocks: Block[] = [];
- let prose = "";
- const range = { startLine: 1, endLine: 1 };
- const flush = () => {
- if (prose) blocks.push({ type: "markdown", text: prose, range });
- prose = "";
- };
- for (let i = start; i < lines.length; i++) {
- const line = lines[i]!;
- if (nested && line === ":::") {
- flush();
- return { blocks, end: i };
- }
- const after = line.match(/^:::after\{step=(\S+?)( failed)?\}$/);
- if (after) {
- flush();
- const inner = parse(i + 1, true);
- blocks.push({
- type: "after",
- stepId: after[1]!,
- onFailure: !!after[2],
- blocks: inner.blocks,
- range,
- });
- i = inner.end;
- continue;
- }
- const fence = line.match(/^```(?:sh|bash) \{(run|check) (.*)\}$/);
- if (fence) {
- flush();
- const raw = fence[2]!;
- const attrs = Object.fromEntries(
- [...raw.matchAll(/([\w]+)=(?:"([^"]*)"|([^\s]+))/g)].map((m) => [
- m[1],
- m[2] ?? m[3],
- ]),
- );
- const title = attrs.title ?? "Step";
- const stepAttrs: StepAttrs = {
- id: attrs.id ?? title.toLowerCase().replace(/\s+/g, "-"),
- title,
- host: attrs.host,
- local: attrs.on === "local",
- sudo: /(?:^|\s)sudo(?:\s|$)/.test(raw),
- confirm: /(?:^|\s)confirm(?:\s|$)/.test(raw),
- artifacts: attrs.artifacts?.split(",") ?? [],
- uploads: attrs.upload
- ? attrs.upload.split(",").map((pair: string) => {
- const [src, dst] = pair.split(":");
- return { src: src!, dst: dst! };
- })
- : [],
- timeoutSec: 30,
- capture: attrs.capture,
- };
- const script: string[] = [];
- while (++i < lines.length && lines[i] !== "```") script.push(lines[i]!);
- blocks.push({
- type: "step",
- step: {
- kind: fence[1] as Step["kind"],
- lang: "sh",
- attrs: stepAttrs,
- script: script.join("\n"),
- range,
- },
- });
- } else prose += line + "\n";
- }
- flush();
- return { blocks, end: lines.length };
- }
- return {
- title: "New server SSH key",
- params: [
- { name: "host", type: "host", required: true, label: "Target server" },
- {
- name: "user",
- type: "name",
- required: true,
- default: "admin",
- label: "Login user",
- },
- {
- name: "keyname",
- type: "name",
- required: false,
- default: "id_ed25519_{{host}}",
- },
- ],
- blocks: parse(0).blocks,
- diagnostics: [
- {
- severity: "warning",
- message:
- "Mock demo: frontmatter schema is fixed; prose and step edits are supported. No commands execute.",
- },
- ],
- };
-}
-export function renderText(
- text: string,
- values: ParamValues,
- notebook: Notebook,
-): string {
- return text.replace(/\{\{(\w+)\}\}/g, (token, name: string) =>
- notebook.params.find((p) => p.name === name)?.type === "secret"
- ? "••••"
- : values[name] || token,
- );
-}
-export function resolveParams(
- notebook: Notebook,
- input: ParamValues,
- hosts: readonly string[],
-) {
- const values = { ...input };
- const errors: Record = {};
- for (let i = 0; i < notebook.params.length; i++)
- for (const p of notebook.params)
- if (values[p.name] === undefined && p.default !== undefined) {
- const expanded = renderText(p.default, values, notebook);
- if (!expanded.includes("{{")) values[p.name] = expanded;
- }
- for (const p of notebook.params) {
- const value = values[p.name] ?? "";
- if (!value && p.required) errors[p.name] = "Required";
- else if (
- value &&
- ((p.type === "host" && !hosts.includes(value)) ||
- (p.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) ||
- (p.type === "choice" && !p.options?.includes(value)))
- )
- errors[p.name] = "Invalid value";
- }
- return { values, errors };
-}
-export function renderStep(
- notebook: Notebook,
- step: Step,
- values: ParamValues,
- runtime: ParamValues,
- hosts: readonly string[],
-): RenderedStep {
- const resolved = resolveParams(notebook, values, hosts);
- const all = { ...runtime, ...resolved.values };
- const missing = notebook.params
- .filter((p) => p.required && !all[p.name])
- .map((p) => p.name);
- const invalid = { ...resolved.errors };
- const script = step.script.replace(
- /\{\{(\w+)\}\}/g,
- (token, name: string) => {
- if (notebook.params.find((p) => p.name === name)?.type === "secret") {
- invalid[name] = "Use an environment variable for secrets";
- return token;
- }
- if (!all[name]) {
- if (!missing.includes(name)) missing.push(name);
- return token;
- }
- return shellQuote(all[name]!);
- },
- );
- return {
- stepId: step.attrs.id,
- kind: step.kind,
- host: renderText(step.attrs.host ?? "", all, notebook),
- local: step.attrs.local,
- script,
- artifacts: step.attrs.artifacts.map((a) => renderText(a, all, notebook)),
- uploads: step.attrs.uploads.map((u) => ({
- src: renderText(u.src, all, notebook),
- dst: renderText(u.dst, all, notebook),
- })),
- missing,
- invalid,
- };
-}
diff --git a/apps/web/src/tests/app.test.tsx b/apps/web/src/tests/app.test.tsx
index 8befdec..1fca128 100644
--- a/apps/web/src/tests/app.test.tsx
+++ b/apps/web/src/tests/app.test.tsx
@@ -7,7 +7,6 @@ import {
within,
} from "@testing-library/react";
import { expect, it, vi } from "vitest";
-vi.mock("@shellbook/core", () => import("../mock/core"));
vi.mock("../Editor", () => ({
Editor: ({
source,
@@ -27,7 +26,7 @@ import { App } from "../App";
import { HttpError } from "../api";
import type { Api } from "../api";
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
-import { parseNotebook } from "../mock/core";
+import { parseNotebook } from "@shellbook/core";
import source from "../mock/ssh-key.md?raw";
function harness() {
diff --git a/apps/web/src/tests/components.test.tsx b/apps/web/src/tests/components.test.tsx
index 9791ffb..283f57a 100644
--- a/apps/web/src/tests/components.test.tsx
+++ b/apps/web/src/tests/components.test.tsx
@@ -1,6 +1,5 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
-vi.mock("@shellbook/core", () => import("../mock/core"));
import { ParamsForm } from "../ParamsForm";
import { StepCard } from "../StepCard";
import type { Notebook, RenderedStep, Step } from "@shellbook/core";
diff --git a/apps/web/src/tests/ssh.test.ts b/apps/web/src/tests/ssh.test.ts
index f4227bd..36fd2a9 100644
--- a/apps/web/src/tests/ssh.test.ts
+++ b/apps/web/src/tests/ssh.test.ts
@@ -1,5 +1,4 @@
-import { describe, expect, it, vi } from "vitest";
-vi.mock("@shellbook/core", () => import("../mock/core"));
+import { describe, expect, it } from "vitest";
import { sshCommand } from "../ssh";
const host = {
name: "test",
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index c305f3f..703bde4 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -1,29 +1,7 @@
-import { defineConfig, loadEnv } from "vite";
+import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
-import { fileURLToPath } from "node:url";
-
-export default defineConfig(({ mode }) => {
- const mock =
- loadEnv(mode, process.cwd(), "").VITE_MOCK === "1" ||
- process.env.VITE_MOCK === "1";
- return {
- plugins: [react()],
- build: { target: "es2022" },
- // TEMPORARY: delete this alias and src/mock/core.ts once M0 lands.
- resolve: {
- alias: mock
- ? [
- {
- find: /^@shellbook\/core$/,
- replacement: fileURLToPath(
- new URL("./src/mock/core.ts", import.meta.url),
- ),
- },
- ]
- : [],
- },
- server: {
- proxy: { "/api": { target: "http://127.0.0.1:8080", ws: true } },
- },
- };
+export default defineConfig({
+ plugins: [react()],
+ build: { target: "es2022" },
+ server: { proxy: { "/api": { target: "http://127.0.0.1:8080", ws: true } } },
});
From a6429e0527715dacdc765ab4306dcede013ac5b4 Mon Sep 17 00:00:00 2001
From: Florian Schmidt
Date: Mon, 16 Nov 2026 00:21:17 +0100
Subject: [PATCH 2/3] feat(web): add xterm terminal panel (#5)
Use @xterm/xterm for terminal emulation and its official @xterm/addon-fit for container sizing. Lazy-load both on first open to keep them out of the main bundle. Preserve the mounted terminal on collapse and offer explicit reconnect; provide an echo transport for demos.
---
apps/web/package.json | 4 +-
apps/web/src/App.tsx | 16 +++-
apps/web/src/TerminalSlot.tsx | 124 +++++++++++++++++++++++++--
apps/web/src/style.css | 25 ++++++
apps/web/src/terminalTransport.ts | 40 +++++++++
apps/web/src/tests/terminal.test.tsx | 116 +++++++++++++++++++++++++
pnpm-lock.yaml | 20 +++++
7 files changed, 336 insertions(+), 9 deletions(-)
create mode 100644 apps/web/src/terminalTransport.ts
create mode 100644 apps/web/src/tests/terminal.test.tsx
diff --git a/apps/web/package.json b/apps/web/package.json
index 9c707c9..d9f5155 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -17,7 +17,9 @@
"@codemirror/lang-markdown": "^6.3.1",
"@codemirror/view": "^6.35.0",
"codemirror": "^6.0.1",
- "highlight.js": "^11.10.0"
+ "highlight.js": "^11.10.0",
+ "@xterm/xterm": "^5.5.0",
+ "@xterm/addon-fit": "^0.10.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 1a670d3..497e765 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -29,7 +29,9 @@ import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm } from "./ParamsForm";
import { StepCard } from "./StepCard";
-import { TerminalSlot } from "./TerminalSlot";
+const TerminalSlot = lazy(() =>
+ import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
+);
const Editor = lazy(() =>
import("./Editor").then((module) => ({ default: module.Editor })),
);
@@ -53,6 +55,7 @@ export function App({ api }: { api: Api }) {
const [values, setValues] = useState({});
const [edit, setEdit] = useState(false);
const [terminal, setTerminal] = useState(false);
+ const [terminalOpened, setTerminalOpened] = useState(false);
const [conflict, setConflict] = useState(false);
const [error, setError] = useState("");
const [connected, setConnected] = useState(false);
@@ -348,7 +351,10 @@ export function App({ api }: { api: Api }) {
@@ -460,7 +466,11 @@ export function App({ api }: { api: Api }) {
>
)}
- {terminal && }
+ {terminalOpened && (
+ Loading terminal...
}>
+
+
+ )}
{confirm && (
TerminalTransport;
+}) {
+ const container = useRef(null);
+ const refit = useRef<() => void>(() => {});
+ const [attempt, setAttempt] = useState(0);
+ const [state, setState] = useState("Connecting");
+ useEffect(() => {
+ let active = true;
+ let ready = false;
+ setState("Connecting");
+ const terminal = new Terminal({
+ cursorBlink: true,
+ fontSize: 13,
+ scrollback: 5000,
+ });
+ const fit = new FitAddon();
+ terminal.loadAddon(fit);
+ terminal.open(container.current!);
+ const media = window.matchMedia?.("(prefers-color-scheme: light)");
+ const theme = () => {
+ terminal.options.theme = media?.matches
+ ? { background: "#ffffff", foreground: "#233244", cursor: "#197b59" }
+ : { background: "#10151c", foreground: "#dce3ec", cursor: "#86dab9" };
+ };
+ theme();
+ media?.addEventListener("change", theme);
+ let socket: TerminalTransport;
+ let timer: ReturnType;
+ const send = (message: TerminalClientMessage) => {
+ if (ready) socket.send(JSON.stringify(message));
+ };
+ const resize = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ if (!active || !container.current?.getBoundingClientRect().width)
+ return;
+ fit.fit();
+ send({
+ type: "resize",
+ cols: Math.min(1000, Math.max(1, terminal.cols)),
+ rows: Math.min(1000, Math.max(1, terminal.rows)),
+ });
+ }, 100);
+ };
+ refit.current = resize;
+ const observer =
+ typeof ResizeObserver === "undefined"
+ ? undefined
+ : new ResizeObserver(resize);
+ observer?.observe(container.current!);
+ window.addEventListener("resize", resize);
+ const input = terminal.onData((data) => send({ type: "input", data }));
+ try {
+ socket = connect("main");
+ socket.onopen = () => {
+ if (active) {
+ ready = true;
+ setState("Connected");
+ resize();
+ }
+ };
+ socket.onmessage = (event) => {
+ if (active) terminal.write(event.data);
+ };
+ const disconnected = () => {
+ if (active) {
+ ready = false;
+ setState("Disconnected");
+ }
+ };
+ socket.onclose = disconnected;
+ socket.onerror = () => {
+ disconnected();
+ socket.close();
+ };
+ } catch {
+ setState("Disconnected");
+ }
+ return () => {
+ active = false;
+ ready = false;
+ clearTimeout(timer);
+ observer?.disconnect();
+ window.removeEventListener("resize", resize);
+ media?.removeEventListener("change", theme);
+ input.dispose();
+ socket?.close();
+ terminal.dispose();
+ };
+ }, [attempt, connect]);
+ useEffect(() => {
+ if (!collapsed) refit.current();
+ }, [collapsed]);
return (
-
)}
diff --git a/apps/web/src/events.ts b/apps/web/src/events.ts
index 2e983d5..57d62d3 100644
--- a/apps/web/src/events.ts
+++ b/apps/web/src/events.ts
@@ -1,5 +1,11 @@
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
+export type DownloadState =
+ | "downloading"
+ | "downloaded"
+ | "unavailable"
+ | "error";
+
export interface RunState {
runId: string;
notebookPath: string;
@@ -9,6 +15,8 @@ export interface RunState {
exitCode?: number;
durationMs?: number;
artifacts: string[];
+ sensitiveArtifacts?: string[];
+ artifactDownloads?: Record
;
error?: string;
hostKey?: Extract;
}
@@ -26,6 +34,12 @@ export const emptySession: Session = {
};
export const stepKey = (path: string, id: string) => JSON.stringify([path, id]);
export type Action =
+ | {
+ type: "artifact.download";
+ runId: string;
+ name: string;
+ state: DownloadState;
+ }
| ServerEvent
| { type: "requested"; runId: string; request: StartRunRequest };
export function eventReducer(state: Session, event: Action): Session {
@@ -58,6 +72,15 @@ export function eventReducer(state: Session, event: Action): Session {
let updated: RunState = run;
let next = state;
switch (event.type) {
+ case "artifact.download":
+ updated = {
+ ...run,
+ artifactDownloads: {
+ ...run.artifactDownloads,
+ [event.name]: event.state,
+ },
+ };
+ break;
case "run.output":
updated = {
...run,
@@ -74,7 +97,11 @@ export function eventReducer(state: Session, event: Action): Session {
// An attempt aborted for host key confirmation also finishes (exit -1);
// keep the prompt open until the user accepts or rejects.
if (run.status === "hostKey") {
- updated = { ...run, exitCode: event.exitCode, durationMs: event.durationMs };
+ updated = {
+ ...run,
+ exitCode: event.exitCode,
+ durationMs: event.durationMs,
+ };
break;
}
updated = {
@@ -83,6 +110,7 @@ export function eventReducer(state: Session, event: Action): Session {
exitCode: event.exitCode,
durationMs: event.durationMs,
artifacts: event.artifacts,
+ sensitiveArtifacts: event.sensitiveArtifacts ?? [],
};
if (event.exitCode === 0) {
next = {
diff --git a/apps/web/src/mock/api.ts b/apps/web/src/mock/api.ts
index 498ecb3..2ca80c6 100644
--- a/apps/web/src/mock/api.ts
+++ b/apps/web/src/mock/api.ts
@@ -112,6 +112,10 @@ export const mockApi: Api = {
exitCode: failed ? 1 : 0,
durationMs: 850,
artifacts: rendered.artifacts,
+ sensitiveArtifacts:
+ request.stepId === "keygen"
+ ? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
+ : [],
captured: block.step.attrs.capture
? { name: block.step.attrs.capture, value: "demo-value" }
: undefined,
diff --git a/apps/web/src/tests/app.test.tsx b/apps/web/src/tests/app.test.tsx
index 1fca128..007d284 100644
--- a/apps/web/src/tests/app.test.tsx
+++ b/apps/web/src/tests/app.test.tsx
@@ -35,32 +35,26 @@ function harness() {
const api: Api = {
me: vi.fn().mockResolvedValue({}),
login: vi.fn().mockResolvedValue(undefined),
- list: vi
- .fn()
- .mockResolvedValue({
- notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
- }),
- hosts: vi
- .fn()
- .mockResolvedValue({
- hosts: [
- {
- name: "staging",
- user: "admin",
- address: "example.test",
- port: 22,
- tags: [],
- },
- ],
- }),
- notebook: vi
- .fn()
- .mockResolvedValue({
- path: "ssh-key.md",
- source,
- notebook: parseNotebook(source),
- version: "1",
- }),
+ list: vi.fn().mockResolvedValue({
+ notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
+ }),
+ hosts: vi.fn().mockResolvedValue({
+ hosts: [
+ {
+ name: "staging",
+ user: "admin",
+ address: "example.test",
+ port: 22,
+ tags: [],
+ },
+ ],
+ }),
+ notebook: vi.fn().mockResolvedValue({
+ path: "ssh-key.md",
+ source,
+ notebook: parseNotebook(source),
+ version: "1",
+ }),
save: vi.fn().mockResolvedValue({ version: "2" }),
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
events: (callback, connected) => {
@@ -128,10 +122,15 @@ it("reveals after sections only on success and passes artifact provenance", asyn
runId: "1",
exitCode: 0,
durationMs: 30,
- artifacts: ["key.pub"],
+ artifacts: ["id_ed25519_staging", "id_ed25519_staging.pub"],
+ sensitiveArtifacts: ["id_ed25519_staging"],
captured: { name: "captured", value: "value" },
});
expect(screen.getByText(/Download the private key/)).toBeInTheDocument();
+ expect(screen.getByText("sensitive \u00b7 one download")).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "\u2193 id_ed25519_staging.pub" }),
+ ).toHaveAttribute("href", "/download");
fireEvent.click(
within(screen.getByRole("article", { name: "Authorize key" })).getByRole(
"button",
@@ -142,7 +141,7 @@ it("reveals after sections only on success and passes artifact provenance", asyn
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(2));
expect(vi.mocked(api.run).mock.calls[1]?.[0]).toMatchObject({
runtime: { captured: "value" },
- artifactSources: { "key.pub": "1" },
+ artifactSources: { id_ed25519_staging: "1", "id_ed25519_staging.pub": "1" },
});
emit({
type: "run.hostKeyUnknown",
@@ -214,3 +213,150 @@ it("retains edits made while a file reload is in flight", async () => {
source + "\nIn-flight draft\n",
);
});
+
+it("renders captured runtime in later scripts and prose and selects failed after sections", async () => {
+ const { api, emit } = harness();
+ const captureSource =
+ source +
+ `
+
+\`\`\`sh {run on=local id=capture capture=directory}
+printf '/tmp/a b'
+\`\`\`
+
+\`\`\`sh {run on=local id=use title="Use capture"}
+printf '%s' {{directory}}
+\`\`\`
+
+Captured directory: {{directory}}
+
+:::after{step=keygen failed}
+Key generation failed. Retry safely.
+:::
+`;
+ vi.mocked(api.notebook).mockResolvedValue({
+ path: "ssh-key.md",
+ source: captureSource,
+ notebook: parseNotebook(captureSource),
+ version: "1",
+ });
+ await ready(api);
+ const later = screen.getByRole("article", { name: "Use capture" });
+ expect(within(later).getByRole("button", { name: "Run" })).toBeDisabled();
+ emit({
+ type: "run.started",
+ runId: "capture-run",
+ notebookPath: "ssh-key.md",
+ stepId: "capture",
+ script: "printf '/tmp/a b'",
+ });
+ emit({
+ type: "run.finished",
+ runId: "capture-run",
+ exitCode: 0,
+ durationMs: 1,
+ artifacts: [],
+ captured: { name: "directory", value: "/tmp/a b" },
+ });
+ expect(later.querySelector("pre.script")).toHaveTextContent(
+ "printf '%s' '/tmp/a b'",
+ );
+ expect(screen.getByText("Captured directory: /tmp/a b")).toBeInTheDocument();
+ fireEvent.click(within(later).getByRole("button", { name: "Run" }));
+ await waitFor(() =>
+ expect(api.run).toHaveBeenCalledWith(
+ expect.objectContaining({ runtime: { directory: "/tmp/a b" } }),
+ ),
+ );
+ emit({
+ type: "run.started",
+ runId: "failed",
+ notebookPath: "ssh-key.md",
+ stepId: "keygen",
+ script: "ssh-keygen",
+ });
+ emit({
+ type: "run.finished",
+ runId: "failed",
+ exitCode: 1,
+ durationMs: 1,
+ artifacts: [],
+ });
+ expect(
+ screen.getByText("Key generation failed. Retry safely."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(/Download the private key/),
+ ).not.toBeInTheDocument();
+});
+
+it.each([200, 410])(
+ "handles a sensitive artifact GET with status %s and retains session state",
+ async (status) => {
+ const { api, emit } = harness();
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue({
+ status,
+ ok: status === 200,
+ blob: async () => new Blob(["key bytes"]),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const create = vi.fn(() => "blob:download");
+ const revoke = vi.fn();
+ Object.defineProperty(URL, "createObjectURL", {
+ configurable: true,
+ value: create,
+ });
+ Object.defineProperty(URL, "revokeObjectURL", {
+ configurable: true,
+ value: revoke,
+ });
+ const click = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+ try {
+ await ready(api);
+ emit({
+ type: "run.started",
+ runId: "key-run",
+ notebookPath: "ssh-key.md",
+ stepId: "keygen",
+ script: "ssh-keygen",
+ });
+ emit({
+ type: "run.finished",
+ runId: "key-run",
+ exitCode: 0,
+ durationMs: 1,
+ artifacts: ["private"],
+ sensitiveArtifacts: ["private"],
+ });
+ const link = screen.getByRole("link", { name: "↓ private" });
+ fireEvent.click(link);
+ fireEvent.click(link);
+ await screen.findByText(
+ status === 410 ? "no longer available" : "Downloaded / consumed",
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledWith("/download", {
+ credentials: "same-origin",
+ cache: "no-store",
+ });
+ expect(link).toHaveAttribute("aria-disabled", "true");
+ expect(link).not.toHaveAttribute("href");
+ expect(click).toHaveBeenCalledTimes(status === 200 ? 1 : 0);
+ if (status === 200) expect(create).toHaveBeenCalledWith(expect.any(Blob));
+ // A notebook reload keeps the reducer's consumed/expired state.
+ emit({ type: "file.changed", path: "ssh-key.md" });
+ await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
+ expect(screen.getByRole("link", { name: "↓ private" })).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ } finally {
+ click.mockRestore();
+ vi.unstubAllGlobals();
+ }
+ },
+);