diff --git a/apps/web/README.md b/apps/web/README.md index 8148991..cc44204 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -1,8 +1,10 @@ -# ShellBook web +# ShellBook web -From the repository root, install with `npx -y pnpm@9.15.0 install`. +Install from the repository root with `npx -y pnpm@9.15.0 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 pnpm@9.15.0 --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 pnpm@9.15.0 --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 pnpm@9.15.0 --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. 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..d8fd693 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); @@ -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 }) { @@ -460,7 +469,11 @@ export function App({ api }: { api: Api }) { )} - {terminal && } + {terminalOpened && ( + Loading terminal...

}> + +
+ )} {confirm && (
URL.revokeObjectURL(objectUrl), 1000); + onState("downloaded"); + } catch { + onState("error"); + } finally { + busy.current = false; + } + } + return ( + + { + event.preventDefault(); + void download(); + }} + download={name} + > + ↓ {name} + + {sensitive && sensitive · one download} + {state === "downloaded" && sensitive && ( + Downloaded / consumed + )} + {state === "downloading" && Downloading…} + {state === "unavailable" && no longer available} + {state === "error" && ( + + {sensitive + ? "Download failed; one-shot download may have been consumed." + : "Download failed. Try again."} + + )} + + ); +} diff --git a/apps/web/src/StepCard.tsx b/apps/web/src/StepCard.tsx index 4efacb6..83c4d54 100644 --- a/apps/web/src/StepCard.tsx +++ b/apps/web/src/StepCard.tsx @@ -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 (
       
-        {script
-          .split(/(\{\{[^}]+\}\})/g)
-          .map((part, i) =>
-            part.startsWith("{{") ? (
-              {part}
-            ) : (
-              
-            ),
-          )}
+        {script.split(/(\{\{[^}]+\}\})/g).map((part, i) =>
+          part.startsWith("{{") ? (
+            {part}
+          ) : (
+            
+          ),
+        )}
       
     
); @@ -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({ {run.error &&

{run.error}

} {run.artifacts.map((name) => ( - - ↓ {name} - + onArtifactState?.(run.runId, name, state)} + /> ))}
)} diff --git a/apps/web/src/TerminalSlot.tsx b/apps/web/src/TerminalSlot.tsx index d8f8a2d..1244c3c 100644 --- a/apps/web/src/TerminalSlot.tsx +++ b/apps/web/src/TerminalSlot.tsx @@ -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(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 ( -