import { useEffect, useRef, useState } from "react"; import { Loader2, Sparkles, Upload, X, Zap } from "lucide-react"; import { api } from "../lib/api"; import { bumpPluginsRev, getUserId } from "../lib/userId"; import { useApp } from "../lib/store"; import { FAMILY_HINTS } from "../lib/familyHints"; import { useFocusTrap } from "../lib/focusTrap"; import type { NodeSpec } from "../lib/nodeCatalog"; type Example = { name: string; label: string; family: string; tagline: string; color: string; size_bytes: number; }; // Wraps a string lookup against FAMILY_HINTS without TS complaining when // the backend returns a family value not in the union (e.g. someone // shipped a custom family). Falls back to a generic blurb. function familyHint(fam: string): string { return ( (FAMILY_HINTS as Record)[fam] ?? `A "${fam}" block in the pipeline.` ); } // Delay after a successful install before the modal auto-closes. // Long enough for the user to register the success banner; short enough // that they don't lose focus on the canvas they're about to use. const AUTOCLOSE_MS = 1600; /** * Plugin upload modal. Accepts a .zip drag-drop or click-to-select, * POSTs it to /api/plugins/upload, refreshes the in-store plugin list * on success. * * Validation errors from the backend are surfaced verbatim (they're * already written for an end user: "Zip is X bytes; max is Y", * "kind 'input_circuit' collides with a built-in block", etc). */ export function UploadPluginModal({ open, onClose, }: { open: boolean; onClose: () => void; }) { const setPlugins = useApp((s) => s.setPlugins); const installedPlugins = useApp((s) => s.plugins); const session = useApp((s) => s.session); const authStatus = useApp((s) => s.authStatus); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [dragOver, setDragOver] = useState(false); const [examples, setExamples] = useState([]); const [installingExample, setInstallingExample] = useState(null); const inputRef = useRef(null); const autoCloseRef = useRef(null); const dialogRef = useRef(null); // While the modal is open, trap Tab inside it so keyboard users // don't tab out into the obscured background controls. useFocusTrap(open, dialogRef); // Reset transient state every time the modal reopens, and cancel any // pending auto-close from a previous open cycle. Also remember the // element that had focus when we opened so we can put focus back on // close — without this, keyboard / screen-reader users land at the // top of the document after closing. const openerRef = useRef(null); useEffect(() => { if (open) { setError(null); setSuccess(null); setBusy(false); setDragOver(false); setInstallingExample(null); openerRef.current = (document.activeElement as HTMLElement) || null; } else if (openerRef.current) { // Defer one frame so React has flushed; otherwise we focus the // element before the modal's portal unmounts and focus jumps. const target = openerRef.current; requestAnimationFrame(() => { try { target.focus(); } catch { /* element may be gone */ } }); openerRef.current = null; } return () => { if (autoCloseRef.current !== null) { window.clearTimeout(autoCloseRef.current); autoCloseRef.current = null; } }; }, [open]); // Schedule a soft auto-close after a fresh successful install so the // user lands back on the canvas instead of staring at a dialog. We // skip auto-close for the "already installed" hint so the user can // read it. const scheduleAutoClose = () => { if (autoCloseRef.current !== null) { window.clearTimeout(autoCloseRef.current); } autoCloseRef.current = window.setTimeout(() => { autoCloseRef.current = null; onClose(); }, AUTOCLOSE_MS); }; // Fetch the example catalog once per open. We keep this best-effort — // if the backend doesn't expose examples (older deploy / catalog // empty), the section just hides itself. useEffect(() => { if (!open) return; let cancelled = false; api .listExamplePlugins() .then((list) => { if (!cancelled) setExamples(list); }) .catch(() => { if (!cancelled) setExamples([]); }); return () => { cancelled = true; }; }, [open]); // Escape closes the modal. useEffect(() => { if (!open) return; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape" && !busy) onClose(); }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [open, busy, onClose]); if (!open) return null; const handleFile = async (file: File) => { if (busy) return; setError(null); setSuccess(null); // Light client-side checks so the user doesn't have to wait for // an HTTP round trip for obviously-wrong inputs. if (!file.name.toLowerCase().endsWith(".zip")) { setError("Please pick a .zip file."); return; } if (file.size > 1 * 1024 * 1024) { setError(`File is ${(file.size / 1024).toFixed(0)} KB; max is 1024 KB.`); return; } setBusy(true); try { const userId = getUserId(); const manifest = await api.uploadPlugin(userId, file); setSuccess( `Installed ${manifest.label} — find it in the ${manifest.family} row of the block strip.`, ); // Refresh the global plugin list so NodePalette + BlockPicker // pick the new block up immediately. const list = await api.listPlugins(userId); setPlugins(list); bumpPluginsRev(); scheduleAutoClose(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } }; const onDrop = (e: React.DragEvent) => { e.preventDefault(); setDragOver(false); const file = e.dataTransfer.files[0]; if (file) handleFile(file); }; /** Pull the bundled example zip from the backend and pipe it straight * into the same install path as a manual upload. Saves the user one * download + drag step when they just want to try the plugin * workflow end-to-end. */ const installExample = async (ex: Example) => { if (busy) return; setError(null); setSuccess(null); setInstallingExample(ex.name); setBusy(true); try { const res = await fetch(api.exampleZipUrl(ex.name), { credentials: "include", }); if (!res.ok) { throw new Error(`Could not fetch example: HTTP ${res.status}`); } // Belt-and-suspenders: a captive-portal or proxy could serve a // 200 HTML interstitial. Bail with a clear error before sending // it to the upload endpoint, which would surface a confusing // "not a valid zip" message. const ct = res.headers.get("Content-Type") || ""; if (ct && !ct.includes("zip") && !ct.includes("octet-stream")) { throw new Error( `Example download returned ${ct.split(";")[0]}, not a .zip. ` + "Check your network — a captive portal may be intercepting traffic.", ); } const blob = await res.blob(); const file = new File([blob], `${ex.name}.zip`, { type: "application/zip" }); const userId = getUserId(); const manifest = await api.uploadPlugin(userId, file); setSuccess( `Installed ${manifest.label} — find it in the ${manifest.family} row of the block strip.`, ); const list = await api.listPlugins(userId); setPlugins(list); bumpPluginsRev(); scheduleAutoClose(); } catch (err) { const msg = err instanceof Error ? err.message : String(err); // Only the exact "kind X already exists" message gets the // friendly success-styled hint. The 5-plugin cap also starts // with "You already have …" so we match on the kind= marker // to avoid swallowing cap errors as if they were idempotent. if (/already have a plugin with kind=/i.test(msg)) { // Don't schedule auto-close — give the user time to read. setSuccess( `${ex.label} is already installed in this browser — look for it in the block strip after you close this dialog.`, ); } else { setError(msg); } } finally { setBusy(false); setInstallingExample(null); } }; // First-time users (no plugins installed yet) benefit most from // seeing the bundled examples first — the empty drop zone is // meaningless to them. Once they have at least one plugin we trust // them to prefer the drop zone, which is what power users want. const examplesFirst = installedPlugins.length === 0 && examples.length > 0; const dropZone = ( ); const examplesSection = examples.length > 0 && (
Try with a sample
One-click install a bundled block to see how plugins look in your catalog, or save the .zip as a starting point for your own.
    {examples.map((ex) => { const installing = installingExample === ex.name; return (
  • {ex.label.slice(0, 2).toUpperCase()}
    {ex.label} {ex.family}
    {ex.tagline}
    or save .zip
  • ); })}
); return (
!busy && onClose()} >
e.stopPropagation()} >
Upload your own block
{session?.persistence_enabled ? ( <> Add a custom source/algorithm/metric/sink. Saved to your folder under{" "} {session.user_data_repo}{" "} — survives restarts and follows you across devices. ) : ( <> Add a custom source/algorithm/metric/sink to your catalog. Only you see it. )}
{/* Guest-mode banner — only when the deployment has OAuth wired up but the user hasn't signed in. We don't want to show this on dev deployments where OAuth is off. */} {!session && authStatus?.oauth_enabled && (
Guest mode
Plugins you upload here live only in this browser and disappear when the Space restarts (~24 h) or you clear browser data.{" "} Sign in with Hugging Face {" "} to keep them across restarts and devices.
)} {examplesFirst ? ( <> {examplesSection} {dropZone} ) : ( <> {dropZone} {examplesSection} )} {error && (
{error}
)} {success && (
{success}
)}
What's in a plugin .zip?

Two files at the top level of the zip:

  • manifest.json — block name, family (source/backend/algorithm/metric/sink), color, tunable parameters.
  • handler.py — defines{" "} def run(inputs, params): ... ; runs in an isolated sandbox with a 10-minute wall-clock cap and a 1 GB memory cap.

See PLUGIN_SDK.md{" "} in the GitHub repo for the full spec + an example.

); }