spaceforge / frontend /src /App.tsx
2Btainment's picture
UI v2: analyze manifest, mode radio, target cards, compat matrix, progress/log/download; backward-compatible API
bc2711b verified
Raw History Blame Contribute Delete
12.5 kB
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { analyzeSpace, deleteBuild, downloadUrl, getBuild, getLogs, startBuild } from "./api/client";
import { ModeBadge } from "./components/ModeBadge";
import { MODES, TARGET_META, TARGET_ORDER } from "./components/targets";
import type { AnalyzeResponse, BuildStatus, TargetInfo } from "./types";
const PROJECT_TARGETS = new Set(["tauri", "linux_appimage", "android", "arch_pkgbuild"]);
function fmtSize(n: number) {
return n >= 1048576 ? `${(n / 1048576).toFixed(2)} MB` : `${(n / 1024).toFixed(1)} KB`;
}
function hw(h: unknown): string {
if (!h) return "unknown";
if (typeof h === "object") { const o = h as { current?: string; requested?: string }; return o.current || o.requested || "unknown"; }
return String(h);
}
function modeLabel(m?: string) { return MODES.find((x) => x.id === m)?.label || m || "—"; }
export default function App() {
const [url, setUrl] = useState("https://huggingface.co/spaces/gradio/hello_world");
const [token, setToken] = useState("");
const [analyzing, setAnalyzing] = useState(false);
const [building, setBuilding] = useState(false);
const [error, setError] = useState<string | null>(null);
const [analysis, setAnalysis] = useState<AnalyzeResponse | null>(null);
const [mode, setMode] = useState<string>("hybrid");
const [target, setTarget] = useState<string | null>(null);
const [build, setBuild] = useState<BuildStatus | null>(null);
const [logs, setLogs] = useState("");
const cancelled = useRef(false);
const targets: TargetInfo[] = useMemo(() => {
const ts = analysis?.compatibility.targets || [];
return [...ts].sort((a, b) => TARGET_ORDER.indexOf(a.id) - TARGET_ORDER.indexOf(b.id));
}, [analysis]);
const modeEnabled = (m: string) => targets.some((t) => t.available && t.mode === m);
useEffect(() => {
const t = targets.find((x) => x.id === target);
if (t && t.mode !== mode) setTarget(null);
}, [mode, target, targets]);
const onAnalyze = useCallback(async () => {
setError(null); setBuild(null); setLogs(""); setTarget(null); setAnalyzing(true);
try {
const res = await analyzeSpace(url.trim(), token.trim() || undefined);
setAnalysis(res);
const firstMode = ["hybrid", "hosted_wrapper", "local"].find((m) => res.compatibility.targets.some((t) => t.available && t.mode === m));
if (firstMode) setMode(firstMode);
} catch (e) {
setAnalysis(null);
setError(`Analyze failed: ${e instanceof Error ? e.message : String(e)}`);
} finally { setAnalyzing(false); }
}, [url, token]);
const onBuild = useCallback(async () => {
if (!target) return;
setError(null); setBuilding(true); setLogs(""); cancelled.current = false;
try {
const { build_id } = await startBuild(url.trim(), target, mode, token.trim() || undefined);
let st = await getBuild(build_id);
setBuild(st);
while ((st.status === "queued" || st.status === "running") && !cancelled.current) {
await new Promise((r) => setTimeout(r, 1200));
st = await getBuild(build_id);
setBuild(st);
setLogs(await getLogs(build_id));
}
if (!cancelled.current) setLogs(await getLogs(build_id));
} catch (e) {
setError(`Build failed: ${e instanceof Error ? e.message : String(e)}`);
} finally { setBuilding(false); }
}, [url, target, mode, token]);
const onDiscard = useCallback(async () => {
if (!build) return;
cancelled.current = true;
try { await deleteBuild(build.id); setBuild(null); setLogs(""); }
catch (e) { setError(`Delete failed: ${e instanceof Error ? e.message : String(e)}`); }
}, [build]);
const space = analysis?.space;
const mf = analysis?.manifest && !analysis.manifest.error ? analysis.manifest : undefined;
const pct = Math.round((build?.progress ?? 0) * 100);
return (
<div className="app">
<header className="top">
<div className="brand"><span className="logo">⬢</span><div><h1>SpaceForge</h1><p>Turn Hugging Face Spaces into Apps</p></div></div>
</header>
{error ? <div className="error" role="alert">{error}</div> : null}
<section className="card">
<label className="lbl" htmlFor="url">Hugging Face Space URL</label>
<div className="row">
<input id="url" type="text" value={url} onChange={(e) => setUrl(e.target.value)}
placeholder="https://huggingface.co/spaces/owner/name" />
<button onClick={onAnalyze} disabled={analyzing || building || !url.trim()} data-testid="analyze">
{analyzing ? "Analyzing…" : "Analyze Space"}
</button>
</div>
<div className="row" style={{ marginTop: ".6rem" }}>
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} autoComplete="off"
placeholder="Optional HF token for private Spaces (used per request, never stored or bundled)" aria-label="HF token" />
</div>
</section>
{space ? (
<section className="card">
<div className="space-head"><span className="emoji">{space.emoji}</span>
<div><h2>{space.title}</h2><div className="hint">{space.repo_id}{space.short_description ? ` · ${space.short_description}` : ""}</div></div></div>
<h3>Detected</h3>
<div className="chips" data-testid="detected">
<span className="chip">SDK: {space.sdk}{space.sdk_version ? ` ${space.sdk_version}` : ""}</span>
<span className="chip">Language: {mf?.runtime.language || "unknown"}</span>
<span className={`chip ${space.needs_gpu ? "warn" : ""}`}>{space.needs_gpu ? "GPU" : "CPU"} · {hw(space.hardware)}</span>
<span className="chip">{space.private ? "Private" : "Public"}</span>
<span className="chip">Runtime: {space.runtime_stage}</span>
{mf?.runtime.port ? <span className="chip">Port {mf.runtime.port}</span> : null}
{mf?.runtime.entrypoint ? <span className="chip">Entry: {mf.runtime.entrypoint}</span> : null}
{mf?.license ? <span className="chip">License: {mf.license}</span> : null}
</div>
{mf ? (
<div className="meta">
{mf.requirements.secrets.length ? <div className="warnbox">⚠ This Space reads secrets/env vars: <b>{mf.requirements.secrets.join(", ")}</b>. SpaceForge never bundles secrets into packages — the live Space must keep them.</div> : null}
{mf.requirements.models.length ? <div><span className="k">Models</span> {mf.requirements.models.join(", ")}</div> : null}
{mf.requirements.datasets.length ? <div><span className="k">Datasets</span> {mf.requirements.datasets.join(", ")}</div> : null}
{mf.requirements.heavy_ml ? <div><span className="k">ML stack</span> heavy (torch/transformers…) — not packaged locally</div> : null}
<div><span className="k">Files scanned</span> {mf.files_detected.join(", ") || "—"}</div>
<div><span className="k">Internet needed</span> {mf.requirements.internet ? "yes" : "no"}</div>
</div>
) : null}
{analysis!.compatibility.warnings.map((w) => <div className="hint warn-t" key={w}>⚠ {w}</div>)}
<h3>Compatibility matrix</h3>
<div className="matrix-wrap"><table className="matrix" data-testid="matrix">
<thead><tr><th>Target</th>{MODES.map((m) => <th key={m.id}>{m.label}</th>)}</tr></thead>
<tbody>{targets.map((t) => (
<tr key={t.id}><td>{TARGET_META[t.id]?.label || t.label}</td>
{MODES.map((m) => <td key={m.id} className={t.mode === m.id ? (t.available ? "y" : "s") : "n"}>
{t.mode === m.id ? (t.available ? "✓" : "soon") : "—"}</td>)}</tr>))}</tbody>
</table></div>
<div className="hint">Each package type has exactly one honest delivery mode; "—" means that combination is not offered.</div>
</section>
) : null}
{analysis ? (
<section className="card">
<h3 style={{ marginTop: 0 }}>Conversion mode</h3>
<div className="modes" role="radiogroup">
{MODES.map((m) => {
const en = modeEnabled(m.id);
return (
<label key={m.id} className={`mode ${mode === m.id ? "on" : ""} ${en ? "" : "disabled"}`} data-testid={`mode-${m.id}`}>
<input type="radio" name="mode" value={m.id} checked={mode === m.id} disabled={!en} onChange={() => setMode(m.id)} />
<div><b>{m.label}</b> {en ? null : <span className="soon">not possible</span>}<div className="hint">{m.desc}</div></div>
</label>);
})}
</div>
<h3>Target</h3>
<div className="cards">
{targets.map((t) => {
const meta = TARGET_META[t.id];
const inMode = t.mode === mode;
const dis = !t.available || !inMode;
return (
<button key={t.id} type="button" disabled={dis} data-testid={`target-${t.id}`}
className={`tcard ${target === t.id ? "sel" : ""}`} onClick={() => setTarget(t.id)}
title={t.reason || ""}>
<span className="ticon">{meta?.icon || "📦"}</span>
<span className="tname">{meta?.label || t.label}</span>
<ModeBadge mode={t.mode} />
<span className="tplat">{meta?.platform}</span>
{!t.available ? <span className="soon">coming soon</span> : !inMode ? <span className="tplat">other mode: {modeLabel(t.mode)}</span> : null}
</button>);
})}
</div>
<div className="row" style={{ marginTop: "1rem" }}>
<button onClick={onBuild} disabled={building || !target} data-testid="build">{building ? "Building…" : "Build Package"}</button>
{!target ? <span className="hint">Select a target first.</span> : null}
</div>
</section>
) : null}
{build ? (
<section className="card" data-testid="build-panel">
<h3 style={{ marginTop: 0 }}>Build <code>{build.id}</code> — {build.status}</h3>
<div className="bar"><div style={{ width: `${pct}%` }} className={build.status === "error" ? "err" : ""} /></div>
<div className="hint">{build.stage || build.status} · {pct}%</div>
{logs ? <pre className="logs">{logs.trim().split("\n").map((l) => {
const bad = /error|timeout|failed|Blocked|status=error/i.test(l);
const ok = /ok →|finished status=done/.test(l);
return `${bad ? "✗" : ok ? "✓" : "·"} ${l}`;
}).join("\n")}</pre> : null}
{Object.entries(build.errors).map(([tid, err]) => (
<div className="error" key={tid}><b>{TARGET_META[tid]?.label || tid} failed:</b> {err}</div>))}
{Object.entries(build.artifacts).map(([tid, a]) => {
const project = a.artifact_kind === "project-zip" && PROJECT_TARGETS.has(tid);
return (
<div className="download" key={tid}>
<div>
<div className="fname">{a.filename}</div>
<div className="hint">≈ {fmtSize(a.size)} · {TARGET_META[tid]?.label || tid} · mode: <ModeBadge mode={a.mode} />
{" "}· {project ? <b className="warn-t">Buildprojekt (no binary — build on your machine)</b> : a.binary_included ? "binary" : "ZIP package"}</div>
{a.notes ? <div className="hint">{a.notes}</div> : null}
<div className="hint">Source: {space?.repo_id} · License: {mf?.license || "not declared — check the Space before redistributing"} · Expires {new Date(build.expires_at * 1000).toLocaleTimeString()}</div>
{a.mode !== "local" ? <div className="hint">Needs internet: loads the live Space ({space?.embed_url}).</div> : null}
</div>
<a className="dl" href={downloadUrl(build.id, tid)} download={a.filename} data-testid={`download-${tid}`}>Download</a>
</div>);
})}
{build.status !== "queued" && build.status !== "running" ? (
<button className="secondary" onClick={onDiscard} data-testid="discard">Delete build from server</button>) : null}
</section>
) : null}
<footer className="footer">SpaceForge · 2Btainment</footer>
</div>
);
}