Bundled example plugins + UX polish from second audit pass
Browse filesLets users try the plugin upload flow end-to-end without writing one
from scratch: the Upload modal now shows a "Try with a sample" section
that fetches /api/plugins/examples and offers per-example Install +
.zip download buttons.
Backend:
- New read-only GET /api/plugins/examples returns minimal metadata
parsed from each bundled zip's manifest.json (label, family, tagline,
color, size). Catalog is empty if the examples dir is missing.
- New read-only GET /api/plugins/examples/{name}.zip returns the raw
zip bytes. Name is constrained to `^[a-z][a-z0-9_]{0,30}$`; resolved
path must stay inside the examples dir (defence in depth against
symlink shenanigans). 400 on bad name, 404 on missing or escaped path.
- manifest.json read inside the zip capped at 64 KB so a malformed
bundled example can't allocate unboundedly.
- Defensive comment about route ordering vs the path-param DELETE.
- Dockerfile COPYs example_plugins/ into the runtime image so the
endpoints have content to serve in production.
Frontend:
- UploadPluginModal: "Try with a sample" section with per-row Install
button (pulls zip → uploads in one click) and direct .zip download
link. Friendly success message instead of error when the user
re-installs an already-present example. Header retitled "Upload your
own block".
- Layout: max-h-[calc(100vh-2rem)] + flex-1 min-h-0 on the scroll area
so a 600px viewport doesn't clip the modal body.
- Accessibility: role="alert" on error, role="status" aria-live=polite
on success, per-row aria-label on Install + Download buttons,
aria-hidden on decorative icons.
- New userId helper bumpPluginsRev() writes localStorage("quda.pluginsRev")
on plugin upload/delete; App.tsx's existing storage listener picks
this up so a second tab refreshes its catalog automatically.
- API client: listExamplePlugins() + exampleZipUrl(name) helpers.
- App.tsx: static-import getUserId (was dynamic) to silence Vite's
mixed-import warning and tighten the initial chunk.
Docs:
- PLUGIN_SDK.md "Example plugins" section now points at the in-app
Try-with-a-sample flow first, and to the repo as a secondary path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Dockerfile +5 -0
- PLUGIN_SDK.md +10 -4
- backend/app/routes/plugins.py +125 -0
- frontend/src/App.tsx +7 -8
- frontend/src/components/NodePalette.tsx +2 -1
- frontend/src/components/UploadPluginModal.tsx +171 -6
- frontend/src/lib/api.ts +24 -0
- frontend/src/lib/userId.ts +16 -0
|
@@ -55,6 +55,11 @@ COPY --chown=user:user backend/ ./backend/
|
|
| 55 |
# Prebuilt frontend bundle from stage 1
|
| 56 |
COPY --chown=user:user --from=frontend /build/dist ./frontend/dist
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Clean caches the user can't write at runtime (HF runs as non-root).
|
| 59 |
RUN chown -R user:user ${APP_HOME}
|
| 60 |
|
|
|
|
| 55 |
# Prebuilt frontend bundle from stage 1
|
| 56 |
COPY --chown=user:user --from=frontend /build/dist ./frontend/dist
|
| 57 |
|
| 58 |
+
# Example plugins (small .zip files) — served read-only at
|
| 59 |
+
# /api/plugins/examples so users can grab one to test the upload flow
|
| 60 |
+
# without writing a plugin from scratch.
|
| 61 |
+
COPY --chown=user:user example_plugins/ ./example_plugins/
|
| 62 |
+
|
| 63 |
# Clean caches the user can't write at runtime (HF runs as non-root).
|
| 64 |
RUN chown -R user:user ${APP_HOME}
|
| 65 |
|
|
@@ -243,11 +243,17 @@ the maintainers.
|
|
| 243 |
|
| 244 |
## Example plugins
|
| 245 |
|
| 246 |
-
|
| 247 |
-
examples
|
|
|
|
|
|
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
## Troubleshooting
|
| 253 |
|
|
|
|
| 243 |
|
| 244 |
## Example plugins
|
| 245 |
|
| 246 |
+
The Upload modal in the running app has a **Try with a sample** section
|
| 247 |
+
that lists the bundled examples below. Click **Install** to pull the
|
| 248 |
+
.zip and install it in one shot, or **.zip** to download the archive
|
| 249 |
+
and crack it open as a starting point for your own plugin.
|
| 250 |
|
| 251 |
+
In the repo, the same archives live under `example_plugins/`:
|
| 252 |
+
|
| 253 |
+
- `count_gates/` — a metric plugin that tallies gate types (returns
|
| 254 |
+
`summary` + `scalars` only, leaves the circuit untouched).
|
| 255 |
+
- `prefix_x/` — an algorithm plugin that prepends an X gate on a
|
| 256 |
+
chosen qubit (returns a new `circuit_qpy_bytes`).
|
| 257 |
|
| 258 |
## Troubleshooting
|
| 259 |
|
|
@@ -8,13 +8,22 @@ user. No global registry, no admin approval.
|
|
| 8 |
Storage is process-local under ``/tmp/quda_plugins/<user_id>/`` so
|
| 9 |
plugins die when the HF Space container restarts. Users can re-upload
|
| 10 |
their .zip if they want them back.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
from __future__ import annotations
|
| 14 |
|
|
|
|
| 15 |
import logging
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
from fastapi import APIRouter, File, HTTPException, Query, UploadFile
|
|
|
|
| 18 |
|
| 19 |
from app.services import plugin_service
|
| 20 |
|
|
@@ -22,6 +31,16 @@ logger = logging.getLogger(__name__)
|
|
| 22 |
router = APIRouter()
|
| 23 |
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
@router.get("/plugins")
|
| 26 |
def list_plugins(user_id: str = Query(...)) -> list[dict]:
|
| 27 |
"""List all plugins this browser has uploaded. Frontend merges
|
|
@@ -82,3 +101,109 @@ def delete_plugin(kind: str, user_id: str = Query(...)) -> dict:
|
|
| 82 |
if not removed:
|
| 83 |
raise HTTPException(status_code=404, detail=f"No plugin with kind={kind!r}.")
|
| 84 |
return {"removed": True, "kind": kind}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
Storage is process-local under ``/tmp/quda_plugins/<user_id>/`` so
|
| 9 |
plugins die when the HF Space container restarts. Users can re-upload
|
| 10 |
their .zip if they want them back.
|
| 11 |
+
|
| 12 |
+
The /api/plugins/examples endpoints are read-only and serve bundled
|
| 13 |
+
sample .zip files so users can try the upload flow end-to-end without
|
| 14 |
+
writing a plugin from scratch.
|
| 15 |
"""
|
| 16 |
|
| 17 |
from __future__ import annotations
|
| 18 |
|
| 19 |
+
import json
|
| 20 |
import logging
|
| 21 |
+
import re
|
| 22 |
+
import zipfile
|
| 23 |
+
from pathlib import Path
|
| 24 |
|
| 25 |
from fastapi import APIRouter, File, HTTPException, Query, UploadFile
|
| 26 |
+
from fastapi.responses import Response
|
| 27 |
|
| 28 |
from app.services import plugin_service
|
| 29 |
|
|
|
|
| 31 |
router = APIRouter()
|
| 32 |
|
| 33 |
|
| 34 |
+
# Path to the bundled example_plugins/ directory. Lives at the repo
|
| 35 |
+
# root (sibling of backend/), which becomes /home/user/app/example_plugins
|
| 36 |
+
# in the Docker image (see Dockerfile COPY). In dev mode (uvicorn run
|
| 37 |
+
# from backend/), the same parents[3] path resolves to the project root.
|
| 38 |
+
_EXAMPLES_DIR = Path(__file__).resolve().parents[3] / "example_plugins"
|
| 39 |
+
|
| 40 |
+
# Match safe filenames: lowercase identifier, no path separators.
|
| 41 |
+
_SAFE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,30}$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
@router.get("/plugins")
|
| 45 |
def list_plugins(user_id: str = Query(...)) -> list[dict]:
|
| 46 |
"""List all plugins this browser has uploaded. Frontend merges
|
|
|
|
| 101 |
if not removed:
|
| 102 |
raise HTTPException(status_code=404, detail=f"No plugin with kind={kind!r}.")
|
| 103 |
return {"removed": True, "kind": kind}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ---- Example plugins ---------------------------------------------------
|
| 107 |
+
#
|
| 108 |
+
# Two read-only endpoints that expose the bundled example_plugins/*.zip
|
| 109 |
+
# files so users can try the upload flow without writing one from scratch.
|
| 110 |
+
# The catalog endpoint reads each zip's manifest.json so the modal can
|
| 111 |
+
# show a meaningful label/tagline next to the download link.
|
| 112 |
+
#
|
| 113 |
+
# Note on route ordering: the only DELETE route above uses /plugins/{kind},
|
| 114 |
+
# which is a different HTTP method from these GETs — no collision today.
|
| 115 |
+
# If a future GET /plugins/{kind} is added (e.g. a detail endpoint),
|
| 116 |
+
# move the /plugins/examples routes ABOVE it so FastAPI matches the
|
| 117 |
+
# literal path first. Both /plugins/examples and /plugins/examples/{name}.zip
|
| 118 |
+
# would otherwise be shadowed by the path-parameter route.
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
_MAX_MANIFEST_READ = 64 * 1024 # 64 KB is way more than any sensible manifest
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _read_manifest_from_zip(zip_path: Path) -> dict | None:
|
| 125 |
+
"""Open a bundled .zip and pull out the manifest.json contents.
|
| 126 |
+
|
| 127 |
+
Returns None if anything looks wrong — we don't want a malformed
|
| 128 |
+
bundled example to take down the whole catalog endpoint. The read
|
| 129 |
+
is capped at _MAX_MANIFEST_READ bytes as defence in depth even
|
| 130 |
+
though these zips are repo-controlled."""
|
| 131 |
+
try:
|
| 132 |
+
with zipfile.ZipFile(zip_path, "r") as zf:
|
| 133 |
+
if "manifest.json" not in zf.namelist():
|
| 134 |
+
return None
|
| 135 |
+
with zf.open("manifest.json") as fh:
|
| 136 |
+
raw = fh.read(_MAX_MANIFEST_READ + 1)
|
| 137 |
+
if len(raw) > _MAX_MANIFEST_READ:
|
| 138 |
+
return None
|
| 139 |
+
return json.loads(raw.decode("utf-8"))
|
| 140 |
+
except (zipfile.BadZipFile, json.JSONDecodeError, OSError, UnicodeDecodeError):
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@router.get("/plugins/examples")
|
| 145 |
+
def list_example_plugins() -> list[dict]:
|
| 146 |
+
"""List the bundled example plugin .zip files (read-only catalog).
|
| 147 |
+
|
| 148 |
+
Returns minimal metadata sourced from each zip's manifest.json so
|
| 149 |
+
the upload modal can show the user a friendly card per example.
|
| 150 |
+
"""
|
| 151 |
+
if not _EXAMPLES_DIR.is_dir():
|
| 152 |
+
# Not shipped — empty catalog rather than 500.
|
| 153 |
+
return []
|
| 154 |
+
out: list[dict] = []
|
| 155 |
+
for zip_path in sorted(_EXAMPLES_DIR.glob("*.zip")):
|
| 156 |
+
name = zip_path.stem
|
| 157 |
+
if not _SAFE_NAME_RE.match(name):
|
| 158 |
+
continue # Skip anything with a suspicious filename
|
| 159 |
+
manifest = _read_manifest_from_zip(zip_path)
|
| 160 |
+
if manifest is None:
|
| 161 |
+
continue
|
| 162 |
+
try:
|
| 163 |
+
size = zip_path.stat().st_size
|
| 164 |
+
except OSError:
|
| 165 |
+
continue
|
| 166 |
+
out.append(
|
| 167 |
+
{
|
| 168 |
+
"name": name,
|
| 169 |
+
"label": str(manifest.get("label", name)),
|
| 170 |
+
"family": str(manifest.get("family", "algorithm")),
|
| 171 |
+
"tagline": str(manifest.get("tagline", "")),
|
| 172 |
+
"color": str(manifest.get("color", "#9333ea")),
|
| 173 |
+
"size_bytes": size,
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
return out
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@router.get("/plugins/examples/{name}.zip")
|
| 180 |
+
def download_example_plugin(name: str) -> Response:
|
| 181 |
+
"""Return the raw .zip bytes for one of the bundled examples.
|
| 182 |
+
|
| 183 |
+
Validation:
|
| 184 |
+
* ``name`` is restricted by ``_SAFE_NAME_RE`` (no path separators).
|
| 185 |
+
* Resolved path must stay inside ``_EXAMPLES_DIR`` (defence in
|
| 186 |
+
depth against symlink shenanigans).
|
| 187 |
+
"""
|
| 188 |
+
if not _SAFE_NAME_RE.match(name):
|
| 189 |
+
raise HTTPException(status_code=400, detail="Invalid example name.")
|
| 190 |
+
target = _EXAMPLES_DIR / f"{name}.zip"
|
| 191 |
+
try:
|
| 192 |
+
resolved = target.resolve(strict=True)
|
| 193 |
+
except (OSError, RuntimeError):
|
| 194 |
+
raise HTTPException(status_code=404, detail="No such example.") from None
|
| 195 |
+
# Guard against the resolved path escaping the examples dir.
|
| 196 |
+
if _EXAMPLES_DIR.resolve() not in resolved.parents:
|
| 197 |
+
raise HTTPException(status_code=404, detail="No such example.")
|
| 198 |
+
try:
|
| 199 |
+
data = resolved.read_bytes()
|
| 200 |
+
except OSError:
|
| 201 |
+
raise HTTPException(status_code=404, detail="No such example.") from None
|
| 202 |
+
return Response(
|
| 203 |
+
content=data,
|
| 204 |
+
media_type="application/zip",
|
| 205 |
+
headers={
|
| 206 |
+
"Content-Disposition": f'attachment; filename="{name}.zip"',
|
| 207 |
+
"Cache-Control": "public, max-age=3600",
|
| 208 |
+
},
|
| 209 |
+
)
|
|
@@ -3,6 +3,7 @@ import { ReactFlowProvider } from "@xyflow/react";
|
|
| 3 |
import "@xyflow/react/dist/style.css";
|
| 4 |
import { PanelLeft, PanelRight } from "lucide-react";
|
| 5 |
import { api } from "./lib/api";
|
|
|
|
| 6 |
import { useApp } from "./lib/store";
|
| 7 |
import { useIsDesktop } from "./lib/useMediaQuery";
|
| 8 |
import { TopBar } from "./components/TopBar";
|
|
@@ -209,14 +210,12 @@ export default function App() {
|
|
| 209 |
// in localStorage). Silent on failure — the user just won't see
|
| 210 |
// their previously-uploaded plugins until they re-upload.
|
| 211 |
const refreshPlugins = () => {
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
});
|
| 219 |
-
});
|
| 220 |
};
|
| 221 |
refreshPlugins();
|
| 222 |
// Multi-tab sync: if the user uploads/deletes a plugin in another
|
|
|
|
| 3 |
import "@xyflow/react/dist/style.css";
|
| 4 |
import { PanelLeft, PanelRight } from "lucide-react";
|
| 5 |
import { api } from "./lib/api";
|
| 6 |
+
import { getUserId } from "./lib/userId";
|
| 7 |
import { useApp } from "./lib/store";
|
| 8 |
import { useIsDesktop } from "./lib/useMediaQuery";
|
| 9 |
import { TopBar } from "./components/TopBar";
|
|
|
|
| 210 |
// in localStorage). Silent on failure — the user just won't see
|
| 211 |
// their previously-uploaded plugins until they re-upload.
|
| 212 |
const refreshPlugins = () => {
|
| 213 |
+
api
|
| 214 |
+
.listPlugins(getUserId())
|
| 215 |
+
.then(setPlugins)
|
| 216 |
+
.catch(() => {
|
| 217 |
+
/* ignore */
|
| 218 |
+
});
|
|
|
|
|
|
|
| 219 |
};
|
| 220 |
refreshPlugins();
|
| 221 |
// Multi-tab sync: if the user uploads/deletes a plugin in another
|
|
@@ -9,7 +9,7 @@ import {
|
|
| 9 |
type PluginNodeSpec,
|
| 10 |
} from "../lib/nodeCatalog";
|
| 11 |
import { useApp } from "../lib/store";
|
| 12 |
-
import { getUserId } from "../lib/userId";
|
| 13 |
import { BlockPicker } from "./BlockPicker";
|
| 14 |
import { UploadPluginModal } from "./UploadPluginModal";
|
| 15 |
|
|
@@ -78,6 +78,7 @@ export function NodePalette({
|
|
| 78 |
await api.deletePlugin(getUserId(), kind);
|
| 79 |
const fresh = await api.listPlugins(getUserId());
|
| 80 |
setPlugins(fresh);
|
|
|
|
| 81 |
} catch {
|
| 82 |
/* silent — the tile staying around is harmless */
|
| 83 |
}
|
|
|
|
| 9 |
type PluginNodeSpec,
|
| 10 |
} from "../lib/nodeCatalog";
|
| 11 |
import { useApp } from "../lib/store";
|
| 12 |
+
import { bumpPluginsRev, getUserId } from "../lib/userId";
|
| 13 |
import { BlockPicker } from "./BlockPicker";
|
| 14 |
import { UploadPluginModal } from "./UploadPluginModal";
|
| 15 |
|
|
|
|
| 78 |
await api.deletePlugin(getUserId(), kind);
|
| 79 |
const fresh = await api.listPlugins(getUserId());
|
| 80 |
setPlugins(fresh);
|
| 81 |
+
bumpPluginsRev();
|
| 82 |
} catch {
|
| 83 |
/* silent — the tile staying around is harmless */
|
| 84 |
}
|
|
@@ -1,9 +1,18 @@
|
|
| 1 |
import { useEffect, useRef, useState } from "react";
|
| 2 |
-
import { Loader2, Upload, X } from "lucide-react";
|
| 3 |
import { api } from "../lib/api";
|
| 4 |
-
import { getUserId } from "../lib/userId";
|
| 5 |
import { useApp } from "../lib/store";
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
/**
|
| 8 |
* Plugin upload modal. Accepts a .zip drag-drop or click-to-select,
|
| 9 |
* POSTs it to /api/plugins/upload, refreshes the in-store plugin list
|
|
@@ -26,6 +35,8 @@ export function UploadPluginModal({
|
|
| 26 |
const [error, setError] = useState<string | null>(null);
|
| 27 |
const [success, setSuccess] = useState<string | null>(null);
|
| 28 |
const [dragOver, setDragOver] = useState(false);
|
|
|
|
|
|
|
| 29 |
const inputRef = useRef<HTMLInputElement | null>(null);
|
| 30 |
|
| 31 |
// Reset transient state every time the modal reopens.
|
|
@@ -35,9 +46,29 @@ export function UploadPluginModal({
|
|
| 35 |
setSuccess(null);
|
| 36 |
setBusy(false);
|
| 37 |
setDragOver(false);
|
|
|
|
| 38 |
}
|
| 39 |
}, [open]);
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
// Escape closes the modal.
|
| 42 |
useEffect(() => {
|
| 43 |
if (!open) return;
|
|
@@ -75,6 +106,7 @@ export function UploadPluginModal({
|
|
| 75 |
// pick the new block up immediately.
|
| 76 |
const list = await api.listPlugins(userId);
|
| 77 |
setPlugins(list);
|
|
|
|
| 78 |
} catch (err) {
|
| 79 |
setError(err instanceof Error ? err.message : String(err));
|
| 80 |
} finally {
|
|
@@ -89,6 +121,49 @@ export function UploadPluginModal({
|
|
| 89 |
if (file) handleFile(file);
|
| 90 |
};
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return (
|
| 93 |
<div
|
| 94 |
role="dialog"
|
|
@@ -98,7 +173,7 @@ export function UploadPluginModal({
|
|
| 98 |
onClick={() => !busy && onClose()}
|
| 99 |
>
|
| 100 |
<div
|
| 101 |
-
className="bg-surface border border-edge rounded-xl shadow-2xl w-full max-w-md flex flex-col overflow-hidden"
|
| 102 |
onClick={(e) => e.stopPropagation()}
|
| 103 |
>
|
| 104 |
<div className="px-4 py-3 border-b border-edge flex items-center justify-between">
|
|
@@ -122,7 +197,7 @@ export function UploadPluginModal({
|
|
| 122 |
</button>
|
| 123 |
</div>
|
| 124 |
|
| 125 |
-
<div className="p-4 space-y-3">
|
| 126 |
<label
|
| 127 |
onDragOver={(e) => {
|
| 128 |
e.preventDefault();
|
|
@@ -168,16 +243,106 @@ export function UploadPluginModal({
|
|
| 168 |
</label>
|
| 169 |
|
| 170 |
{error && (
|
| 171 |
-
<div
|
|
|
|
|
|
|
|
|
|
| 172 |
{error}
|
| 173 |
</div>
|
| 174 |
)}
|
| 175 |
{success && (
|
| 176 |
-
<div
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
{success}
|
| 178 |
</div>
|
| 179 |
)}
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
<details className="text-[11px] text-mute">
|
| 182 |
<summary className="cursor-pointer hover:text-ink">
|
| 183 |
What's in a plugin .zip?
|
|
|
|
| 1 |
import { useEffect, useRef, useState } from "react";
|
| 2 |
+
import { Download, Loader2, Sparkles, Upload, X, Zap } from "lucide-react";
|
| 3 |
import { api } from "../lib/api";
|
| 4 |
+
import { bumpPluginsRev, getUserId } from "../lib/userId";
|
| 5 |
import { useApp } from "../lib/store";
|
| 6 |
|
| 7 |
+
type Example = {
|
| 8 |
+
name: string;
|
| 9 |
+
label: string;
|
| 10 |
+
family: string;
|
| 11 |
+
tagline: string;
|
| 12 |
+
color: string;
|
| 13 |
+
size_bytes: number;
|
| 14 |
+
};
|
| 15 |
+
|
| 16 |
/**
|
| 17 |
* Plugin upload modal. Accepts a .zip drag-drop or click-to-select,
|
| 18 |
* POSTs it to /api/plugins/upload, refreshes the in-store plugin list
|
|
|
|
| 35 |
const [error, setError] = useState<string | null>(null);
|
| 36 |
const [success, setSuccess] = useState<string | null>(null);
|
| 37 |
const [dragOver, setDragOver] = useState(false);
|
| 38 |
+
const [examples, setExamples] = useState<Example[]>([]);
|
| 39 |
+
const [installingExample, setInstallingExample] = useState<string | null>(null);
|
| 40 |
const inputRef = useRef<HTMLInputElement | null>(null);
|
| 41 |
|
| 42 |
// Reset transient state every time the modal reopens.
|
|
|
|
| 46 |
setSuccess(null);
|
| 47 |
setBusy(false);
|
| 48 |
setDragOver(false);
|
| 49 |
+
setInstallingExample(null);
|
| 50 |
}
|
| 51 |
}, [open]);
|
| 52 |
|
| 53 |
+
// Fetch the example catalog once per open. We keep this best-effort —
|
| 54 |
+
// if the backend doesn't expose examples (older deploy / catalog
|
| 55 |
+
// empty), the section just hides itself.
|
| 56 |
+
useEffect(() => {
|
| 57 |
+
if (!open) return;
|
| 58 |
+
let cancelled = false;
|
| 59 |
+
api
|
| 60 |
+
.listExamplePlugins()
|
| 61 |
+
.then((list) => {
|
| 62 |
+
if (!cancelled) setExamples(list);
|
| 63 |
+
})
|
| 64 |
+
.catch(() => {
|
| 65 |
+
if (!cancelled) setExamples([]);
|
| 66 |
+
});
|
| 67 |
+
return () => {
|
| 68 |
+
cancelled = true;
|
| 69 |
+
};
|
| 70 |
+
}, [open]);
|
| 71 |
+
|
| 72 |
// Escape closes the modal.
|
| 73 |
useEffect(() => {
|
| 74 |
if (!open) return;
|
|
|
|
| 106 |
// pick the new block up immediately.
|
| 107 |
const list = await api.listPlugins(userId);
|
| 108 |
setPlugins(list);
|
| 109 |
+
bumpPluginsRev();
|
| 110 |
} catch (err) {
|
| 111 |
setError(err instanceof Error ? err.message : String(err));
|
| 112 |
} finally {
|
|
|
|
| 121 |
if (file) handleFile(file);
|
| 122 |
};
|
| 123 |
|
| 124 |
+
/** Pull the bundled example zip from the backend and pipe it straight
|
| 125 |
+
* into the same install path as a manual upload. Saves the user one
|
| 126 |
+
* download + drag step when they just want to try the plugin
|
| 127 |
+
* workflow end-to-end. */
|
| 128 |
+
const installExample = async (ex: Example) => {
|
| 129 |
+
if (busy) return;
|
| 130 |
+
setError(null);
|
| 131 |
+
setSuccess(null);
|
| 132 |
+
setInstallingExample(ex.name);
|
| 133 |
+
setBusy(true);
|
| 134 |
+
try {
|
| 135 |
+
const res = await fetch(api.exampleZipUrl(ex.name));
|
| 136 |
+
if (!res.ok) {
|
| 137 |
+
throw new Error(`Could not fetch example: HTTP ${res.status}`);
|
| 138 |
+
}
|
| 139 |
+
const blob = await res.blob();
|
| 140 |
+
const file = new File([blob], `${ex.name}.zip`, { type: "application/zip" });
|
| 141 |
+
const userId = getUserId();
|
| 142 |
+
const manifest = await api.uploadPlugin(userId, file);
|
| 143 |
+
setSuccess(
|
| 144 |
+
`Installed ${manifest.label} (kind=${manifest.kind}). Find it in the block strip on the canvas.`,
|
| 145 |
+
);
|
| 146 |
+
const list = await api.listPlugins(userId);
|
| 147 |
+
setPlugins(list);
|
| 148 |
+
bumpPluginsRev();
|
| 149 |
+
} catch (err) {
|
| 150 |
+
const msg = err instanceof Error ? err.message : String(err);
|
| 151 |
+
// The duplicate-install case is friendly here — the user already
|
| 152 |
+
// has this example, no action needed. Frame it as a hint rather
|
| 153 |
+
// than an error.
|
| 154 |
+
if (/already have a plugin/i.test(msg)) {
|
| 155 |
+
setSuccess(
|
| 156 |
+
`${ex.label} is already installed in this browser — look for it in the block strip.`,
|
| 157 |
+
);
|
| 158 |
+
} else {
|
| 159 |
+
setError(msg);
|
| 160 |
+
}
|
| 161 |
+
} finally {
|
| 162 |
+
setBusy(false);
|
| 163 |
+
setInstallingExample(null);
|
| 164 |
+
}
|
| 165 |
+
};
|
| 166 |
+
|
| 167 |
return (
|
| 168 |
<div
|
| 169 |
role="dialog"
|
|
|
|
| 173 |
onClick={() => !busy && onClose()}
|
| 174 |
>
|
| 175 |
<div
|
| 176 |
+
className="bg-surface border border-edge rounded-xl shadow-2xl w-full max-w-md flex flex-col max-h-[calc(100vh-2rem)] overflow-hidden"
|
| 177 |
onClick={(e) => e.stopPropagation()}
|
| 178 |
>
|
| 179 |
<div className="px-4 py-3 border-b border-edge flex items-center justify-between">
|
|
|
|
| 197 |
</button>
|
| 198 |
</div>
|
| 199 |
|
| 200 |
+
<div className="p-4 space-y-3 overflow-y-auto flex-1 min-h-0">
|
| 201 |
<label
|
| 202 |
onDragOver={(e) => {
|
| 203 |
e.preventDefault();
|
|
|
|
| 243 |
</label>
|
| 244 |
|
| 245 |
{error && (
|
| 246 |
+
<div
|
| 247 |
+
role="alert"
|
| 248 |
+
className="text-[12px] text-danger panel-alt p-2 border-danger/40 whitespace-pre-line"
|
| 249 |
+
>
|
| 250 |
{error}
|
| 251 |
</div>
|
| 252 |
)}
|
| 253 |
{success && (
|
| 254 |
+
<div
|
| 255 |
+
role="status"
|
| 256 |
+
aria-live="polite"
|
| 257 |
+
className="text-[12px] text-ok panel-alt p-2 border-ok/40"
|
| 258 |
+
>
|
| 259 |
{success}
|
| 260 |
</div>
|
| 261 |
)}
|
| 262 |
|
| 263 |
+
{examples.length > 0 && (
|
| 264 |
+
<div className="panel-alt p-3 space-y-2">
|
| 265 |
+
<div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-mute">
|
| 266 |
+
<Sparkles className="w-3 h-3 text-accent2" />
|
| 267 |
+
Try with a sample
|
| 268 |
+
</div>
|
| 269 |
+
<div className="text-[11px] text-mute/80 leading-relaxed">
|
| 270 |
+
Install a bundled example to see how a plugin looks in your
|
| 271 |
+
catalog — or download the .zip to crack it open as a
|
| 272 |
+
starting point for your own.
|
| 273 |
+
</div>
|
| 274 |
+
<ul className="space-y-1.5">
|
| 275 |
+
{examples.map((ex) => {
|
| 276 |
+
const installing = installingExample === ex.name;
|
| 277 |
+
return (
|
| 278 |
+
<li
|
| 279 |
+
key={ex.name}
|
| 280 |
+
className="flex items-start gap-2 p-2 rounded-md border border-edge bg-surface"
|
| 281 |
+
>
|
| 282 |
+
<span
|
| 283 |
+
className="inline-flex items-center justify-center text-[10px] font-bold text-white rounded shrink-0"
|
| 284 |
+
style={{
|
| 285 |
+
backgroundColor: ex.color,
|
| 286 |
+
width: "1.75rem",
|
| 287 |
+
height: "1.75rem",
|
| 288 |
+
}}
|
| 289 |
+
aria-hidden
|
| 290 |
+
>
|
| 291 |
+
{ex.label.slice(0, 2).toUpperCase()}
|
| 292 |
+
</span>
|
| 293 |
+
<div className="flex-1 min-w-0">
|
| 294 |
+
<div className="flex items-baseline gap-1.5 flex-wrap">
|
| 295 |
+
<span className="text-[12px] font-medium text-ink truncate">
|
| 296 |
+
{ex.label}
|
| 297 |
+
</span>
|
| 298 |
+
<span className="text-[9px] uppercase tracking-wider text-mute/70 border border-edge rounded px-1">
|
| 299 |
+
{ex.family}
|
| 300 |
+
</span>
|
| 301 |
+
</div>
|
| 302 |
+
<div className="text-[11px] text-mute leading-snug truncate">
|
| 303 |
+
{ex.tagline}
|
| 304 |
+
</div>
|
| 305 |
+
</div>
|
| 306 |
+
<div className="flex flex-col gap-1 shrink-0">
|
| 307 |
+
<button
|
| 308 |
+
type="button"
|
| 309 |
+
disabled={busy}
|
| 310 |
+
onClick={() => installExample(ex)}
|
| 311 |
+
className="flex items-center gap-1 px-2 py-1 rounded text-[11px] font-medium bg-accent2/15 text-accent2 hover:bg-accent2/25 disabled:opacity-50 disabled:cursor-not-allowed"
|
| 312 |
+
title="Fetch the example zip and install it directly"
|
| 313 |
+
aria-label={
|
| 314 |
+
installing
|
| 315 |
+
? `Installing ${ex.label}`
|
| 316 |
+
: `Install ${ex.label} example plugin`
|
| 317 |
+
}
|
| 318 |
+
>
|
| 319 |
+
{installing ? (
|
| 320 |
+
<Loader2 className="w-3 h-3 animate-spin" aria-hidden />
|
| 321 |
+
) : (
|
| 322 |
+
<Zap className="w-3 h-3" aria-hidden />
|
| 323 |
+
)}
|
| 324 |
+
Install
|
| 325 |
+
</button>
|
| 326 |
+
<a
|
| 327 |
+
href={api.exampleZipUrl(ex.name)}
|
| 328 |
+
download={`${ex.name}.zip`}
|
| 329 |
+
className={`flex items-center gap-1 px-2 py-1 rounded text-[11px] text-mute hover:text-ink hover:bg-surfaceAlt ${
|
| 330 |
+
busy ? "pointer-events-none opacity-50" : ""
|
| 331 |
+
}`}
|
| 332 |
+
title="Download the .zip to your computer"
|
| 333 |
+
aria-label={`Download ${ex.label} as .zip`}
|
| 334 |
+
>
|
| 335 |
+
<Download className="w-3 h-3" aria-hidden />
|
| 336 |
+
.zip
|
| 337 |
+
</a>
|
| 338 |
+
</div>
|
| 339 |
+
</li>
|
| 340 |
+
);
|
| 341 |
+
})}
|
| 342 |
+
</ul>
|
| 343 |
+
</div>
|
| 344 |
+
)}
|
| 345 |
+
|
| 346 |
<details className="text-[11px] text-mute">
|
| 347 |
<summary className="cursor-pointer hover:text-ink">
|
| 348 |
What's in a plugin .zip?
|
|
@@ -202,6 +202,30 @@ export const api = {
|
|
| 202 |
{ method: "DELETE" },
|
| 203 |
).then((r) => json<{ removed: boolean; kind: string }>(r)),
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
/**
|
| 206 |
* Stream pipeline execution via SSE. Calls `onStep` for each step as
|
| 207 |
* it completes, then calls `onDone` with the assembled RunResponse.
|
|
|
|
| 202 |
{ method: "DELETE" },
|
| 203 |
).then((r) => json<{ removed: boolean; kind: string }>(r)),
|
| 204 |
|
| 205 |
+
/** Catalog of bundled example .zip plugins users can grab to test
|
| 206 |
+
* the upload flow. The server reads each manifest.json inside the
|
| 207 |
+
* zip and returns its label / family / tagline. */
|
| 208 |
+
listExamplePlugins: () =>
|
| 209 |
+
fetch(`${BASE}/plugins/examples`).then(
|
| 210 |
+
(r) =>
|
| 211 |
+
json<
|
| 212 |
+
Array<{
|
| 213 |
+
name: string;
|
| 214 |
+
label: string;
|
| 215 |
+
family: string;
|
| 216 |
+
tagline: string;
|
| 217 |
+
color: string;
|
| 218 |
+
size_bytes: number;
|
| 219 |
+
}>
|
| 220 |
+
>(r),
|
| 221 |
+
),
|
| 222 |
+
|
| 223 |
+
/** URL the browser can hit (or anchor `download` to) to fetch a
|
| 224 |
+
* bundled example plugin .zip. The browser saves it; the user then
|
| 225 |
+
* drops the same .zip back into the upload modal to install it. */
|
| 226 |
+
exampleZipUrl: (name: string) =>
|
| 227 |
+
`${BASE}/plugins/examples/${encodeURIComponent(name)}.zip`,
|
| 228 |
+
|
| 229 |
/**
|
| 230 |
* Stream pipeline execution via SSE. Calls `onStep` for each step as
|
| 231 |
* it completes, then calls `onDone` with the assembled RunResponse.
|
|
@@ -23,6 +23,22 @@ export function getUserId(): string {
|
|
| 23 |
return fresh;
|
| 24 |
}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
/** RFC4122-ish random hex, no hyphens — fits the backend regex
|
| 27 |
* `[a-zA-Z0-9_-]{8,64}` without ambiguity. */
|
| 28 |
function mintUserId(): string {
|
|
|
|
| 23 |
return fresh;
|
| 24 |
}
|
| 25 |
|
| 26 |
+
/** Bump a localStorage counter so other tabs' `storage` listeners fire.
|
| 27 |
+
* Plugin lists themselves live in Zustand (in-memory per tab); this
|
| 28 |
+
* counter is the only thing that crosses the localStorage boundary
|
| 29 |
+
* for cross-tab sync. */
|
| 30 |
+
export function bumpPluginsRev(): void {
|
| 31 |
+
try {
|
| 32 |
+
const prev = Number(localStorage.getItem("quda.pluginsRev") || "0");
|
| 33 |
+
localStorage.setItem(
|
| 34 |
+
"quda.pluginsRev",
|
| 35 |
+
String(Number.isFinite(prev) ? prev + 1 : 1),
|
| 36 |
+
);
|
| 37 |
+
} catch {
|
| 38 |
+
/* storage blocked — multi-tab sync is best-effort */
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
/** RFC4122-ish random hex, no hyphens — fits the backend regex
|
| 43 |
* `[a-zA-Z0-9_-]{8,64}` without ambiguity. */
|
| 44 |
function mintUserId(): string {
|