Merge branch 't3/web-terminal-artifacts'
This commit is contained in:
+68
-19
@@ -1,8 +1,10 @@
|
||||
# ShellBook web
|
||||
# ShellBook web
|
||||
|
||||
From the repository root, install with `npx -y [email protected] install`.
|
||||
Install from the repository root with `npx -y [email protected] install` (Node 22).
|
||||
The viewer, demo and tests all use the real `@shellbook/core` parser and renderer.
|
||||
Scripts are rendered only by core; the server uses the same substitution path.
|
||||
|
||||
PowerShell demo (no server or core implementation required):
|
||||
## Demo without a server
|
||||
|
||||
```powershell
|
||||
$env:VITE_MOCK = '1'
|
||||
@@ -10,26 +12,73 @@ npx -y [email protected] --filter @shellbook/web dev
|
||||
```
|
||||
|
||||
Open the Vite URL (normally http://localhost:5173). Select staging, run the checks
|
||||
(one deliberately fails), generate demo artifacts, and authorize the key to try
|
||||
confirmation. Production demonstrates the **changed host key** warning. No commands
|
||||
execute and downloaded artifacts contain dummy text. Mock frontmatter parameters
|
||||
are fixed to the spec example; body edits preview and save in memory only.
|
||||
(one deliberately fails), generate the SSH key pair, download the dummy private
|
||||
key, then authorize the public key with confirmation. The private key is marked
|
||||
**sensitive · one download** and its link is disabled after download. The authorize
|
||||
request carries the earlier artifacts' run IDs in `artifactSources`.
|
||||
Production demonstrates the changed host key warning. No commands execute;
|
||||
artifacts contain dummy text. The fixture is parsed from `src/mock/ssh-key.md`.
|
||||
Markdown edits (including frontmatter) preview through core and save in memory.
|
||||
The terminal echoes input without opening a WebSocket or running a shell.
|
||||
Never deploy a build made with `VITE_MOCK=1`.
|
||||
|
||||
Normal backend mode:
|
||||
## Real server
|
||||
|
||||
```powershell
|
||||
Remove-Item Env:VITE_MOCK -ErrorAction SilentlyContinue
|
||||
npx -y pnpm@9.15.0 --filter @shellbook/web dev
|
||||
npx -y pnpm@9.15.0 dev
|
||||
```
|
||||
|
||||
Vite proxies `/api`, including WebSocket upgrades, to 127.0.0.1:8080. Normal builds
|
||||
use core directly. `src/mock/core.ts` is a temporary fixture renderer selected
|
||||
only by the VITE_MOCK alias; remove it and that alias when core lands. Never deploy
|
||||
a build made with VITE_MOCK=1. The terminal slot is intentionally empty until M4.
|
||||
Configure the server's workspace and hosts first (see `../server/README.md`).
|
||||
Vite proxies `/api`, including WebSocket upgrades, to 127.0.0.1:8080.
|
||||
Open **Terminal** and run `claude` using your own CLI login. The server needs tmux
|
||||
and the real Claude Code CLI installed; see `../server/src/terminal/README.md`.
|
||||
The panel lazily loads xterm and its fit addon on first opening. It attaches to
|
||||
`/api/terminal?session=main` using ws/wss according to the page protocol. Input
|
||||
and resize frames follow the core contract; server output is raw terminal text.
|
||||
Resize messages are debounced by 100 ms. The panel stays mounted when collapsed,
|
||||
retaining the connection and scrollback. A closed connection offers **Reconnect**;
|
||||
there is no automatic retry loop. Reconnecting attaches to the existing tmux
|
||||
session. Theme follows the OS dark/light preference, including live changes.
|
||||
Changes made by Claude reload the notebook through the existing file event stream;
|
||||
unsaved editor drafts are retained with a conflict notice.
|
||||
|
||||
`npx -y [email protected] --filter @shellbook/web test` runs jsdom component and reducer
|
||||
tests. `... --filter @shellbook/web build` builds production assets. Clipboard APIs
|
||||
require HTTPS or localhost. SSH copy uses a quoted heredoc (a multiline paste),
|
||||
with strict bash flags matching server execution; secret env values are never copied.
|
||||
Steps using secret environment variables require the operator to provide them when
|
||||
pasting manually. WebSocket disconnects disable execution and require a page reload.
|
||||
## Run results and downloads
|
||||
|
||||
Successful `capture` results enter notebook-scoped runtime values for subsequent
|
||||
scripts and prose. Success/failure `:::after` sections follow the latest run for
|
||||
that step in this browser session. Artifacts from successful runs supply provenance
|
||||
for `upload=` requests.
|
||||
|
||||
Downloads use one fetch GET followed by a blob download so HTTP 410 can be shown as
|
||||
**no longer available**. There is no HEAD/preflight request that could accidentally
|
||||
consume a one-shot file. Sensitive links disable immediately while fetching and
|
||||
remain consumed in session state after success. If a sensitive request fails,
|
||||
the link remains disabled because the server may already have consumed it; an
|
||||
error explains this. Ordinary failed downloads can be retried. Download state is
|
||||
kept across notebook navigation/reloads within the mounted app, not page refreshes;
|
||||
the server enforces one-shot downloads and expiry across tabs and refreshes.
|
||||
|
||||
Clipboard APIs require HTTPS or localhost. SSH copy uses a quoted heredoc with
|
||||
strict bash flags matching execution; secret env values are never copied. Steps
|
||||
using secret environment variables require the operator to provide them when
|
||||
pasting manually. Event WebSocket disconnects disable execution and require a page
|
||||
reload (terminal reconnection is independent).
|
||||
|
||||
## Verification
|
||||
|
||||
From the root:
|
||||
|
||||
```powershell
|
||||
npx -y pnpm@9.15.0 typecheck
|
||||
npx -y pnpm@9.15.0 test
|
||||
npx -y pnpm@9.15.0 build
|
||||
```
|
||||
|
||||
Web-only tests: `npx -y [email protected] --filter @shellbook/web test`.
|
||||
Vitest/Testing Library tests run in jsdom, with xterm modules mocked only in terminal
|
||||
tests. A fake WebSocket checks raw output, input/resize framing, collapse lifetime,
|
||||
and reconnect. App tests drive the SSH-key fixture through keygen, sensitive artifact
|
||||
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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
+16
-3
@@ -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<ParamValues>({});
|
||||
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);
|
||||
@@ -246,6 +249,9 @@ export function App({ api }: { api: Api }) {
|
||||
host={hosts.find((h) => h.name === rendered.host)}
|
||||
run={runFor(block.step.attrs.id)}
|
||||
artifact={api.artifact}
|
||||
onArtifactState={(runId, name, state) =>
|
||||
dispatch({ type: "artifact.download", runId, name, state })
|
||||
}
|
||||
connected={
|
||||
connected &&
|
||||
!dirty &&
|
||||
@@ -348,7 +354,10 @@ export function App({ api }: { api: Api }) {
|
||||
</button>
|
||||
<button
|
||||
aria-expanded={terminal}
|
||||
onClick={() => setTerminal(!terminal)}
|
||||
onClick={() => {
|
||||
setTerminalOpened(true);
|
||||
setTerminal(!terminal);
|
||||
}}
|
||||
>
|
||||
Terminal {terminal ? "→" : "←"}
|
||||
</button>
|
||||
@@ -460,7 +469,11 @@ export function App({ api }: { api: Api }) {
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
{terminal && <TerminalSlot />}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||
<TerminalSlot collapsed={!terminal} />
|
||||
</Suspense>
|
||||
)}
|
||||
{confirm && (
|
||||
<div className="modal-backdrop">
|
||||
<section
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useRef } from "react";
|
||||
import type { DownloadState } from "./events";
|
||||
export function ArtifactDownload({
|
||||
name,
|
||||
url,
|
||||
sensitive,
|
||||
state,
|
||||
onState,
|
||||
}: {
|
||||
name: string;
|
||||
url: string;
|
||||
sensitive: boolean;
|
||||
state?: DownloadState;
|
||||
onState(state: DownloadState): void;
|
||||
}) {
|
||||
const busy = useRef(false);
|
||||
const disabled =
|
||||
state === "downloading" ||
|
||||
state === "unavailable" ||
|
||||
(sensitive && !!state);
|
||||
async function download() {
|
||||
if (busy.current || disabled) return;
|
||||
busy.current = true;
|
||||
onState("downloading");
|
||||
try {
|
||||
// A single GET both retrieves the bytes and detects expired/consumed files.
|
||||
const response = await fetch(url, {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (response.status === 410) {
|
||||
onState("unavailable");
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error(`Download failed (${response.status})`);
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = objectUrl;
|
||||
link.download = name;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
// Give the browser time to start saving before releasing the blob.
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
onState("downloaded");
|
||||
} catch {
|
||||
onState("error");
|
||||
} finally {
|
||||
busy.current = false;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<span className="artifact">
|
||||
<a
|
||||
href={disabled ? undefined : url}
|
||||
role="link"
|
||||
aria-disabled={disabled}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
void download();
|
||||
}}
|
||||
download={name}
|
||||
>
|
||||
↓ {name}
|
||||
</a>
|
||||
{sensitive && <span className="badge">sensitive · one download</span>}
|
||||
{state === "downloaded" && sensitive && (
|
||||
<small> Downloaded / consumed</small>
|
||||
)}
|
||||
{state === "downloading" && <small> Downloading…</small>}
|
||||
{state === "unavailable" && <small> no longer available</small>}
|
||||
{state === "error" && (
|
||||
<small role="alert">
|
||||
{sensitive
|
||||
? "Download failed; one-shot download may have been consumed."
|
||||
: "Download failed. Try again."}
|
||||
</small>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+24
-23
@@ -1,8 +1,9 @@
|
||||
import { ArtifactDownload } from "./ArtifactDownload";
|
||||
import { useState } from "react";
|
||||
import hljs from "highlight.js/lib/core";
|
||||
import bash from "highlight.js/lib/languages/bash";
|
||||
import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
|
||||
import type { RunState } from "./events";
|
||||
import type { DownloadState, RunState } from "./events";
|
||||
import { sshCommand } from "./ssh";
|
||||
hljs.registerLanguage("bash", bash);
|
||||
|
||||
@@ -11,20 +12,18 @@ function Script({ script }: { script: string }) {
|
||||
return (
|
||||
<pre className="script">
|
||||
<code>
|
||||
{script
|
||||
.split(/(\{\{[^}]+\}\})/g)
|
||||
.map((part, i) =>
|
||||
part.startsWith("{{") ? (
|
||||
<mark key={i}>{part}</mark>
|
||||
) : (
|
||||
<span
|
||||
key={i}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: hljs.highlight(part, { language: "bash" }).value,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{script.split(/(\{\{[^}]+\}\})/g).map((part, i) =>
|
||||
part.startsWith("{{") ? (
|
||||
<mark key={i}>{part}</mark>
|
||||
) : (
|
||||
<span
|
||||
key={i}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: hljs.highlight(part, { language: "bash" }).value,
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</code>
|
||||
</pre>
|
||||
);
|
||||
@@ -37,6 +36,7 @@ export function StepCard({
|
||||
onRun,
|
||||
artifact,
|
||||
connected = true,
|
||||
onArtifactState,
|
||||
}: {
|
||||
step: Step;
|
||||
rendered: RenderedStep;
|
||||
@@ -45,6 +45,7 @@ export function StepCard({
|
||||
onRun(): void;
|
||||
artifact(id: string, name: string): string;
|
||||
connected?: boolean;
|
||||
onArtifactState?(runId: string, name: string, state: DownloadState): void;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
const invalid =
|
||||
@@ -129,14 +130,14 @@ export function StepCard({
|
||||
</pre>
|
||||
{run.error && <p className="error">{run.error}</p>}
|
||||
{run.artifacts.map((name) => (
|
||||
<a
|
||||
className="artifact"
|
||||
key={name}
|
||||
href={artifact(run.runId, name)}
|
||||
download
|
||||
>
|
||||
↓ {name}
|
||||
</a>
|
||||
<ArtifactDownload
|
||||
key={`${run.runId}:${name}`}
|
||||
name={name}
|
||||
url={artifact(run.runId, name)}
|
||||
sensitive={run.sensitiveArtifacts?.includes(name) ?? false}
|
||||
state={run.artifactDownloads?.[name]}
|
||||
onState={(state) => onArtifactState?.(run.runId, name, state)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,123 @@
|
||||
export function TerminalSlot() {
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import { terminalTransport } from "./terminalTransport";
|
||||
import type { TerminalTransport } from "./terminalTransport";
|
||||
import type { TerminalClientMessage } from "@shellbook/core";
|
||||
|
||||
export function TerminalSlot({
|
||||
collapsed = false,
|
||||
connect = terminalTransport,
|
||||
}: {
|
||||
collapsed?: boolean;
|
||||
connect?: (session: string) => TerminalTransport;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(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<typeof setTimeout>;
|
||||
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 (
|
||||
<aside className="terminal" aria-label="Terminal panel">
|
||||
<h2>Terminal</h2>
|
||||
<p>Claude Code terminal · M4</p>
|
||||
<div className="terminal-slot" />
|
||||
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
|
||||
<h2>Terminal · main</h2>
|
||||
<p>
|
||||
Run `claude` here — it edits notebooks in this workspace; the view
|
||||
reloads live.
|
||||
</p>
|
||||
<div className="actions">
|
||||
<span role="status">{state}</span>
|
||||
{state === "Disconnected" && (
|
||||
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="terminal-screen" ref={container} />
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
+29
-1
@@ -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<string, DownloadState>;
|
||||
error?: string;
|
||||
hostKey?: Extract<ServerEvent, { type: "run.hostKeyUnknown" }>;
|
||||
}
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, string> = {};
|
||||
for (let i = 0; i < notebook.params.length; i++)
|
||||
for (const p of notebook.params)
|
||||
if (values[p.name] === undefined && p.default !== undefined) {
|
||||
const expanded = renderText(p.default, values, notebook);
|
||||
if (!expanded.includes("{{")) values[p.name] = expanded;
|
||||
}
|
||||
for (const p of notebook.params) {
|
||||
const value = values[p.name] ?? "";
|
||||
if (!value && p.required) errors[p.name] = "Required";
|
||||
else if (
|
||||
value &&
|
||||
((p.type === "host" && !hosts.includes(value)) ||
|
||||
(p.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) ||
|
||||
(p.type === "choice" && !p.options?.includes(value)))
|
||||
)
|
||||
errors[p.name] = "Invalid value";
|
||||
}
|
||||
return { values, errors };
|
||||
}
|
||||
export function renderStep(
|
||||
notebook: Notebook,
|
||||
step: Step,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hosts: readonly string[],
|
||||
): RenderedStep {
|
||||
const resolved = resolveParams(notebook, values, hosts);
|
||||
const all = { ...runtime, ...resolved.values };
|
||||
const missing = notebook.params
|
||||
.filter((p) => p.required && !all[p.name])
|
||||
.map((p) => p.name);
|
||||
const invalid = { ...resolved.errors };
|
||||
const script = step.script.replace(
|
||||
/\{\{(\w+)\}\}/g,
|
||||
(token, name: string) => {
|
||||
if (notebook.params.find((p) => p.name === name)?.type === "secret") {
|
||||
invalid[name] = "Use an environment variable for secrets";
|
||||
return token;
|
||||
}
|
||||
if (!all[name]) {
|
||||
if (!missing.includes(name)) missing.push(name);
|
||||
return token;
|
||||
}
|
||||
return shellQuote(all[name]!);
|
||||
},
|
||||
);
|
||||
return {
|
||||
stepId: step.attrs.id,
|
||||
kind: step.kind,
|
||||
host: renderText(step.attrs.host ?? "", all, notebook),
|
||||
local: step.attrs.local,
|
||||
script,
|
||||
artifacts: step.attrs.artifacts.map((a) => renderText(a, all, notebook)),
|
||||
uploads: step.attrs.uploads.map((u) => ({
|
||||
src: renderText(u.src, all, notebook),
|
||||
dst: renderText(u.dst, all, notebook),
|
||||
})),
|
||||
missing,
|
||||
invalid,
|
||||
};
|
||||
}
|
||||
@@ -439,3 +439,28 @@ a {
|
||||
min-height: 200px;
|
||||
}
|
||||
}
|
||||
.terminal[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.terminal {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
min-width: 0;
|
||||
}
|
||||
.terminal-screen {
|
||||
height: calc(100% - 160px);
|
||||
min-height: 220px;
|
||||
}
|
||||
.with-terminal {
|
||||
grid-template-columns: 230px minmax(0, 1fr) minmax(300px, 40vw);
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.with-terminal {
|
||||
grid-template-columns: 170px minmax(0, 1fr);
|
||||
}
|
||||
.terminal {
|
||||
position: static;
|
||||
height: 500px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { TerminalClientMessage } from "@shellbook/core";
|
||||
|
||||
export interface TerminalTransport {
|
||||
onopen: (() => void) | null;
|
||||
onclose: (() => void) | null;
|
||||
onerror: (() => void) | null;
|
||||
onmessage: ((event: { data: string }) => void) | null;
|
||||
send(data: string): void;
|
||||
close(): void;
|
||||
}
|
||||
export function terminalTransport(session: string): TerminalTransport {
|
||||
if (import.meta.env.VITE_MOCK !== "1")
|
||||
return new WebSocket(
|
||||
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/terminal?session=${encodeURIComponent(session)}`,
|
||||
) as unknown as TerminalTransport;
|
||||
let closed = false;
|
||||
const transport: TerminalTransport = {
|
||||
onopen: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
onmessage: null,
|
||||
send(data) {
|
||||
const message = JSON.parse(data) as TerminalClientMessage;
|
||||
if (!closed && message.type === "input")
|
||||
transport.onmessage?.({ data: message.data.replace(/\r/g, "\r\n") });
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
transport.onclose?.();
|
||||
},
|
||||
};
|
||||
queueMicrotask(() => {
|
||||
if (closed) return;
|
||||
transport.onopen?.();
|
||||
transport.onmessage?.({
|
||||
data: "ShellBook demo terminal (echo only)\r\n$ ",
|
||||
});
|
||||
});
|
||||
return transport;
|
||||
}
|
||||
+175
-30
@@ -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() {
|
||||
@@ -36,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) => {
|
||||
@@ -129,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",
|
||||
@@ -143,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",
|
||||
@@ -215,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();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
const xterm = vi.hoisted(() => ({ instances: [] as any[] }));
|
||||
vi.mock("@xterm/xterm", () => ({
|
||||
Terminal: class {
|
||||
cols = 80;
|
||||
rows = 24;
|
||||
options = {};
|
||||
write = vi.fn();
|
||||
dispose = vi.fn();
|
||||
input?: (data: string) => void;
|
||||
constructor() {
|
||||
xterm.instances.push(this);
|
||||
}
|
||||
loadAddon() {}
|
||||
open() {}
|
||||
onData(callback: (data: string) => void) {
|
||||
this.input = callback;
|
||||
return { dispose: vi.fn() };
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@xterm/addon-fit", () => ({
|
||||
FitAddon: class {
|
||||
fit = vi.fn();
|
||||
},
|
||||
}));
|
||||
import { TerminalSlot } from "../TerminalSlot";
|
||||
class FakeSocket {
|
||||
static instances: FakeSocket[] = [];
|
||||
onopen?: () => void;
|
||||
onclose?: () => void;
|
||||
onerror?: () => void;
|
||||
onmessage?: (event: { data: string }) => void;
|
||||
send = vi.fn();
|
||||
close = vi.fn();
|
||||
constructor(public url: string) {
|
||||
FakeSocket.instances.push(this);
|
||||
}
|
||||
}
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
FakeSocket.instances = [];
|
||||
xterm.instances = [];
|
||||
});
|
||||
it("frames input and fitted resize, renders raw output and preserves connection when collapsed", async () => {
|
||||
vi.stubGlobal("WebSocket", FakeSocket);
|
||||
const { rerender, container } = render(<TerminalSlot />);
|
||||
const socket = FakeSocket.instances[0]!;
|
||||
expect(socket.url).toBe(`ws://${location.host}/api/terminal?session=main`);
|
||||
const element = container.querySelector(".terminal-screen")!;
|
||||
vi.spyOn(element, "getBoundingClientRect").mockReturnValue({
|
||||
width: 500,
|
||||
} as DOMRect);
|
||||
act(() => socket.onopen?.());
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Connected");
|
||||
await waitFor(() =>
|
||||
expect(socket.send).toHaveBeenCalledWith(
|
||||
JSON.stringify({ type: "resize", cols: 80, rows: 24 }),
|
||||
),
|
||||
);
|
||||
act(() => xterm.instances[0].input("claude\r"));
|
||||
expect(socket.send).toHaveBeenCalledWith(
|
||||
JSON.stringify({ type: "input", data: "claude\r" }),
|
||||
);
|
||||
act(() => socket.onmessage?.({ data: "\u001b[31mraw output" }));
|
||||
expect(xterm.instances[0].write).toHaveBeenCalledWith("\u001b[31mraw output");
|
||||
rerender(<TerminalSlot collapsed />);
|
||||
expect(container.querySelector("aside")).toHaveAttribute("hidden");
|
||||
expect(socket.close).not.toHaveBeenCalled();
|
||||
act(() => socket.onmessage?.({ data: "still receiving" }));
|
||||
rerender(<TerminalSlot />);
|
||||
expect(FakeSocket.instances).toHaveLength(1);
|
||||
expect(xterm.instances[0].write).toHaveBeenCalledWith("still receiving");
|
||||
expect(xterm.instances[0].dispose).not.toHaveBeenCalled();
|
||||
});
|
||||
it("offers explicit reconnect after close and cleans up the old connection", () => {
|
||||
vi.stubGlobal("WebSocket", FakeSocket);
|
||||
const view = render(<TerminalSlot />);
|
||||
act(() => FakeSocket.instances[0]!.onclose?.());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
|
||||
expect(FakeSocket.instances).toHaveLength(2);
|
||||
expect(FakeSocket.instances[0]!.close).toHaveBeenCalledTimes(1);
|
||||
act(() => FakeSocket.instances[1]!.onopen?.());
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Connected");
|
||||
view.unmount();
|
||||
expect(FakeSocket.instances[1]!.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses a fake echo terminal in demo mode without a server", async () => {
|
||||
vi.stubEnv("VITE_MOCK", "1");
|
||||
const { terminalTransport } = await import("../terminalTransport");
|
||||
try {
|
||||
const socket = terminalTransport("main");
|
||||
const opened = vi.fn();
|
||||
const output = vi.fn();
|
||||
socket.onopen = opened;
|
||||
socket.onmessage = output;
|
||||
await Promise.resolve();
|
||||
expect(opened).toHaveBeenCalledOnce();
|
||||
socket.send(JSON.stringify({ type: "input", data: "hello\r" }));
|
||||
expect(output).toHaveBeenLastCalledWith({ data: "hello\r\n" });
|
||||
socket.close();
|
||||
socket.send(JSON.stringify({ type: "input", data: "closed" }));
|
||||
expect(output).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
+5
-27
@@ -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 } } },
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user