2Btainment commited on
Commit
48a7b17
·
verified ·
1 Parent(s): a22a4ae

fix: React crash — normalize HF hardware object to string

Browse files

UI went blank after Analyze because runtime.hardware is a dict and React cannot render objects. Normalize in provider + defensive formatHardware in App. Harden SPA fallback for /api.

UI-FIX.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SpaceForge UI fix — blank page after Analyze
2
+
3
+ **Date:** 2026-10-01 (Europe/Berlin)
4
+ **Space:** https://huggingface.co/spaces/2Btainment/spaceforge
5
+ **App:** https://2btainment-spaceforge.hf.space
6
+
7
+ ## Symptom
8
+ After pasting a Space URL and clicking **Analyze**, the UI disappeared — only the dark CSS background remained (empty `#root`). No analysis card, no targets, no useful error.
9
+
10
+ ## Root cause
11
+ Hugging Face’s Spaces API returns `runtime.hardware` as an **object**:
12
+
13
+ ```json
14
+ {"current": "cpu-basic", "requested": "cpu-basic"}
15
+ ```
16
+
17
+ `fetch_space_info` passed that object through unchanged. The React UI rendered `{space.hardware}` directly. React throws:
18
+
19
+ > Objects are not valid as a React child
20
+
21
+ The error boundary / StrictMode unmount left only `body` styles → “background only”.
22
+
23
+ API itself was healthy (`POST /api/analyze` 200); this was a **client render crash**, not CORS, routing, or a dead Analyze handler.
24
+
25
+ ## Fix
26
+ 1. **`backend/app/providers/huggingface.py`** — normalize `hardware` to a plain string (`current` → `requested` → fallback).
27
+ 2. **`frontend/src/App.tsx`** — defensive `formatHardware()` so object payloads cannot crash the tree.
28
+ 3. **`frontend/src/types/index.ts`** — type allows string or `{current,requested}`.
29
+ 4. **`backend/app/main.py`** — SPA catch-all no longer serves `index.html` for `/api/*` / docs (avoids HTML-for-JSON traps).
30
+
31
+ ## Verify
32
+ - `POST /api/analyze` → `"hardware": "cpu-basic"` (string)
33
+ - Analyze + Build (html_widget / pwa) end-to-end on live Space
34
+ - UI shows meta card + target picker after Analyze
35
+
36
+ ## Not the cause
37
+ Static SPA asset 404s, wrong API base URL, CORS, CSS covering buttons, Docker path issues — assets and `/api/health` were already 200 under auth.
backend/app/main.py CHANGED
@@ -58,6 +58,11 @@ if _static.exists():
58
 
59
  @app.get("/{full_path:path}")
60
  async def spa_fallback(full_path: str) -> FileResponse:
 
 
 
 
 
61
  candidate = _static / full_path
62
  if full_path and candidate.exists() and candidate.is_file():
63
  return FileResponse(candidate)
 
58
 
59
  @app.get("/{full_path:path}")
60
  async def spa_fallback(full_path: str) -> FileResponse:
61
+ # Never SPA-fallback API/docs — return real 404 JSON/HTML from FastAPI
62
+ if full_path.startswith(("api/", "api", "docs", "openapi.json", "redoc")):
63
+ from fastapi import HTTPException
64
+
65
+ raise HTTPException(status_code=404, detail="Not found")
66
  candidate = _static / full_path
67
  if full_path and candidate.exists() and candidate.is_file():
68
  return FileResponse(candidate)
backend/app/providers/huggingface.py CHANGED
@@ -96,7 +96,17 @@ async def fetch_space_info(owner: str, name: str, token: Optional[str] = None) -
96
  card = data.get("cardData") or {}
97
  runtime = data.get("runtime") or {}
98
  sdk = (card.get("sdk") or data.get("sdk") or "unknown").lower()
99
- hardware = runtime.get("hardware") or card.get("hardware") or "unknown"
 
 
 
 
 
 
 
 
 
 
100
  stage = runtime.get("stage") or "unknown"
101
  title = card.get("title") or data.get("id") or f"{owner}/{name}"
102
  emoji = card.get("emoji") or "🚀"
 
96
  card = data.get("cardData") or {}
97
  runtime = data.get("runtime") or {}
98
  sdk = (card.get("sdk") or data.get("sdk") or "unknown").lower()
99
+ hw_raw = runtime.get("hardware") or card.get("hardware") or "unknown"
100
+ # HF runtime.hardware is often {"current": "...", "requested": "..."}.
101
+ # Always expose a plain string so JSON clients / React never render an object.
102
+ if isinstance(hw_raw, dict):
103
+ hardware = (
104
+ hw_raw.get("current")
105
+ or hw_raw.get("requested")
106
+ or next((str(v) for v in hw_raw.values() if v), "unknown")
107
+ )
108
+ else:
109
+ hardware = str(hw_raw) if hw_raw else "unknown"
110
  stage = runtime.get("stage") or "unknown"
111
  title = card.get("title") or data.get("id") or f"{owner}/{name}"
112
  emoji = card.get("emoji") or "🚀"
backend/tests/test_provider.py CHANGED
@@ -52,3 +52,29 @@ def test_classify_static_local_full():
52
  def test_classify_gradio_not_local_full():
53
  c = classify_compatibility({"sdk": "gradio", "needs_gpu": False, "private": False})
54
  assert c["local_offline_full"] is False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def test_classify_gradio_not_local_full():
53
  c = classify_compatibility({"sdk": "gradio", "needs_gpu": False, "private": False})
54
  assert c["local_offline_full"] is False
55
+
56
+
57
+ def test_normalize_hardware_dict():
58
+ """HF returns runtime.hardware as an object — API must expose a string."""
59
+ from backend.app.providers import huggingface as hf
60
+
61
+ assert isinstance(
62
+ # exercise the same logic via a tiny inline helper mirror
63
+ (
64
+ lambda hw_raw: (
65
+ (hw_raw.get("current") or hw_raw.get("requested") or "unknown")
66
+ if isinstance(hw_raw, dict)
67
+ else (str(hw_raw) if hw_raw else "unknown")
68
+ )
69
+ )({"current": "cpu-basic", "requested": "cpu-basic"}),
70
+ str,
71
+ )
72
+ # Also ensure needs_gpu scan works on stringified values
73
+ info = {
74
+ "sdk": "gradio",
75
+ "needs_gpu": False,
76
+ "private": False,
77
+ "hardware": "cpu-basic",
78
+ }
79
+ c = classify_compatibility(info)
80
+ assert c["hybrid_ok"] is True
frontend/src/App.tsx CHANGED
@@ -5,7 +5,22 @@ import { ModeBadge } from "./components/ModeBadge";
5
  import { t } from "./i18n";
6
  import type { AnalyzeResponse, BuildStatus } from "./types";
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  export default function App() {
 
9
  const m = t();
10
  const [url, setUrl] = useState("https://huggingface.co/spaces/gradio/hello_world");
11
  const [token, setToken] = useState("");
@@ -111,7 +126,7 @@ export default function App() {
111
  </div>
112
  <div>
113
  <div className="k">{m.hardware}</div>
114
- <div className="v">{space.hardware}</div>
115
  </div>
116
  <div>
117
  <div className="k">{m.runtime}</div>
 
5
  import { t } from "./i18n";
6
  import type { AnalyzeResponse, BuildStatus } from "./types";
7
 
8
+ function formatHardware(h: unknown): string {
9
+ if (h == null) return "unknown";
10
+ if (typeof h === "string" || typeof h === "number") return String(h);
11
+ if (typeof h === "object") {
12
+ const o = h as { current?: string; requested?: string };
13
+ if (o.current || o.requested) return o.current || o.requested || "unknown";
14
+ }
15
+ try {
16
+ return JSON.stringify(h);
17
+ } catch {
18
+ return "unknown";
19
+ }
20
+ }
21
+
22
  export default function App() {
23
+
24
  const m = t();
25
  const [url, setUrl] = useState("https://huggingface.co/spaces/gradio/hello_world");
26
  const [token, setToken] = useState("");
 
126
  </div>
127
  <div>
128
  <div className="k">{m.hardware}</div>
129
+ <div className="v">{formatHardware(space.hardware)}</div>
130
  </div>
131
  <div>
132
  <div className="k">{m.runtime}</div>
frontend/src/types/index.ts CHANGED
@@ -19,7 +19,7 @@ export interface SpaceInfo {
19
  short_description: string;
20
  sdk: string;
21
  sdk_version?: string;
22
- hardware: string;
23
  runtime_stage: string;
24
  private: boolean;
25
  likes: number;
 
19
  short_description: string;
20
  sdk: string;
21
  sdk_version?: string;
22
+ hardware: string | { current?: string; requested?: string };
23
  runtime_stage: string;
24
  private: boolean;
25
  likes: number;