File size: 28,848 Bytes
3def6cd
 
 
 
 
 
 
4d1c109
 
 
3def6cd
 
 
 
 
 
4d1c109
3def6cd
 
 
 
 
 
 
 
 
 
 
 
 
4d1c109
3def6cd
 
 
 
 
 
46b16c9
 
 
4d1c109
46b16c9
 
 
 
4d1c109
46b16c9
 
 
 
 
4d1c109
46b16c9
 
 
 
4d1c109
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1c109
 
 
 
 
 
 
 
 
 
 
46b16c9
 
 
 
 
 
 
 
 
 
 
3def6cd
4d1c109
 
 
3def6cd
4d1c109
 
3def6cd
 
4d1c109
 
 
 
3def6cd
 
 
 
 
 
 
4d1c109
 
 
3def6cd
 
4d1c109
3def6cd
 
4d1c109
 
 
 
3def6cd
 
 
 
 
 
4d1c109
 
 
3def6cd
 
4d1c109
 
 
 
 
 
 
3def6cd
 
 
 
 
 
 
 
 
 
 
4d1c109
 
3def6cd
 
 
 
 
 
 
 
 
 
46b16c9
 
 
3def6cd
 
46b16c9
3def6cd
4d1c109
 
3def6cd
46b16c9
3def6cd
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
 
4d1c109
3def6cd
4d1c109
3def6cd
46b16c9
4d1c109
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1c109
3def6cd
46b16c9
4d1c109
46b16c9
 
 
 
 
 
 
 
 
 
3def6cd
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
 
4d1c109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
 
 
 
46b16c9
3def6cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1c109
3def6cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1c109
 
 
3def6cd
 
 
 
 
 
 
 
 
46b16c9
3def6cd
 
 
 
 
 
 
 
 
 
46b16c9
3def6cd
 
 
 
 
 
 
4d1c109
3def6cd
 
 
 
 
 
 
 
 
 
 
 
 
46b16c9
3def6cd
 
 
 
 
 
 
 
4d1c109
3def6cd
 
 
 
 
 
 
 
 
 
 
 
 
46b16c9
3def6cd
 
 
 
 
a19901a
3def6cd
 
 
 
 
 
 
46b16c9
3def6cd
 
46b16c9
 
 
 
 
3def6cd
4d1c109
 
 
 
 
 
 
3def6cd
a19901a
46b16c9
3def6cd
46b16c9
 
3def6cd
 
46b16c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
 
46b16c9
 
 
 
4d1c109
46b16c9
3def6cd
46b16c9
4d1c109
3def6cd
 
 
 
 
 
 
46b16c9
 
 
3def6cd
46b16c9
 
 
 
 
3def6cd
46b16c9
 
 
 
 
 
3def6cd
46b16c9
 
3def6cd
46b16c9
3def6cd
46b16c9
3def6cd
4d1c109
 
 
 
46b16c9
 
 
4d1c109
46b16c9
 
 
 
4d1c109
46b16c9
 
 
 
4d1c109
46b16c9
3def6cd
4d1c109
 
 
 
 
 
 
 
a19901a
 
4d1c109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3def6cd
 
a19901a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
"""
vROM Hub Space β€” Browse, submit, and manage vROM packages.

Tabs:
- Browse: View all published vROMs in the registry
- Submit: Request a new vROM to be built from documentation URLs
- Admin: Approve/reject submissions, trigger builds (philipp-zettl only)

Mobile-optimized: single demo.load, lazy admin loading, cached hub downloads,
no blocking spinners, pre-rendered tab children.
"""

import json
import logging
import os
import re
import time
import uuid
from datetime import datetime, timezone
from typing import Optional

import gradio as gr
from huggingface_hub import HfApi

# ─── Config ─────────────────────────────────────────────────────────────

ADMIN_USERNAMES = {"philipp-zettl"}
REGISTRY_REPO = "philipp-zettl/vrom-registry"
SUBMISSIONS_REPO = "philipp-zettl/vrom-submissions"
SUBMISSIONS_FILE = "submissions.json"
CACHE_TTL = 30  # seconds β€” how long to cache hub downloads

logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(name)s | %(message)s")
logger = logging.getLogger("vrom-hub-space")

hf_api = HfApi(token=os.environ.get("HF_TOKEN"))

# ─── Mobile-friendly CSS ────────────────────────────────────────────────

MOBILE_CSS = """
/* Fix: gradio-container clips horizontal overflow */
.gradio-container {
    overflow-x: auto !important;
}

/* Fix: ensure any table can scroll horizontally on mobile */
.table-wrap {
    overflow-x: auto !important;
    -webkit-overflow-scrolling: touch;
}

/* Fix: minimum tap target for all buttons */
button {
    min-height: 44px !important;
}

/* Fix: tab overflow β€” ensure tabs scroll instead of clipping */
.tab-container {
    overflow-x: auto !important;
    overflow-y: hidden !important;
}

/* vROM card styles */
.vrom-card {
    border: 1px solid var(--border-color-primary, #e0e0e0);
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    background: var(--background-fill-primary, #fff);
}
.vrom-card-title {
    font-weight: 700;
    font-size: 17px;
    margin-bottom: 4px;
    word-break: break-word;
}
.vrom-card-meta {
    color: var(--body-text-color-subdued, #666);
    font-size: 13px;
    margin-bottom: 8px;
}
.vrom-card-desc {
    font-size: 14px;
    margin-bottom: 8px;
    word-break: break-word;
}
.vrom-tag {
    display: inline-block;
    background: var(--color-accent-soft, #e0e7ff);
    border-radius: 6px;
    padding: 2px 8px;
    font-size: 12px;
    margin: 2px 2px 2px 0;
}
.vrom-files {
    margin-top: 8px;
    font-size: 13px;
}
.vrom-files a {
    color: var(--link-text-color, #2563eb);
    text-decoration: none;
    margin-right: 12px;
}
.vrom-files a:hover {
    text-decoration: underline;
}
.vrom-empty {
    text-align: center;
    padding: 40px 20px;
    color: var(--body-text-color-subdued, #666);
    font-size: 16px;
}

/* Submission card styles (admin) */
.sub-card {
    border: 1px solid var(--border-color-primary, #e0e0e0);
    border-radius: 10px;
    padding: 14px;
    margin-bottom: 10px;
    background: var(--background-fill-primary, #fff);
}
.sub-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 4px;
}
.sub-card-name {
    font-weight: 600;
    font-size: 15px;
    word-break: break-word;
}
.sub-card-id {
    font-family: monospace;
    font-size: 12px;
    color: var(--body-text-color-subdued, #888);
    background: var(--background-fill-secondary, #f3f4f6);
    padding: 2px 6px;
    border-radius: 4px;
}
.sub-card-meta {
    font-size: 13px;
    color: var(--body-text-color-subdued, #666);
    margin-top: 4px;
}
.status-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 600;
}
.status-pending { background: #fef3c7; color: #92400e; }
.status-building { background: #dbeafe; color: #1e40af; }
.status-published { background: #d1fae5; color: #065f46; }
.status-rejected { background: #fee2e2; color: #991b1b; }
.status-failed { background: #fce7f3; color: #9d174d; }

/* Only apply hover effects on devices that support hover (not mobile) */
@media (hover: hover) {
    .vrom-card:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .sub-card:hover {
        box-shadow: 0 1px 6px rgba(0,0,0,0.08);
        border-color: var(--color-accent, #6366f1);
    }
}

/* Mobile-specific overrides */
@media (max-width: 640px) {
    .gradio-container {
        padding: 8px !important;
    }
    .vrom-card {
        padding: 12px;
    }
}
"""


# ─── Cached Hub Downloads ──────────────────────────────────────────────
# Avoids blocking force_download=True on every page load / OAuth redirect.
# The Refresh buttons always bust the cache via force=True.

_registry_cache = {"data": [], "ts": 0}
_submissions_cache = {"data": {"version": "1.0.0", "submissions": []}, "ts": 0}


def load_registry(force: bool = False) -> list[dict]:
    now = time.time()
    if not force and now - _registry_cache["ts"] < CACHE_TTL:
        return _registry_cache["data"]
    try:
        path = hf_api.hf_hub_download(
            repo_id=REGISTRY_REPO, filename="registry.json",
            repo_type="dataset", force_download=True,
        )
        with open(path, "r") as f:
            data = json.load(f)
        result = data.get("vroms", [])
        _registry_cache.update({"data": result, "ts": now})
        return result
    except Exception as e:
        logger.error(f"Failed to load registry: {e}")
        return _registry_cache["data"] or []


def load_submissions(force: bool = False) -> dict:
    now = time.time()
    if not force and now - _submissions_cache["ts"] < CACHE_TTL:
        return _submissions_cache["data"]
    try:
        path = hf_api.hf_hub_download(
            repo_id=SUBMISSIONS_REPO, filename=SUBMISSIONS_FILE,
            repo_type="dataset", force_download=True,
        )
        with open(path, "r") as f:
            result = json.load(f)
        _submissions_cache.update({"data": result, "ts": now})
        return result
    except Exception as e:
        logger.error(f"Failed to load submissions: {e}")
        return _submissions_cache["data"]


# ─── Helpers ────────────────────────────────────────────────────────────

def is_admin(profile: Optional[gr.OAuthProfile]) -> bool:
    return profile is not None and profile.username in ADMIN_USERNAMES


def save_submissions(data: dict):
    content = json.dumps(data, indent=2, ensure_ascii=False)
    hf_api.upload_file(
        path_or_fileobj=content.encode("utf-8"),
        path_in_repo=SUBMISSIONS_FILE,
        repo_id=SUBMISSIONS_REPO,
        repo_type="dataset",
        commit_message=f"Update submissions ({datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')})",
    )
    # Bust the cache after writing
    _submissions_cache["ts"] = 0


def slugify(text: str) -> str:
    text = text.lower().strip()
    text = re.sub(r'[^\w\s-]', '', text)
    text = re.sub(r'[\s_]+', '-', text)
    text = re.sub(r'-+', '-', text)
    return text[:50].strip('-')


def _escape_html(text: str) -> str:
    """Escape HTML special characters."""
    return (text or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


# ─── Browse Tab β€” Card-based layout ────────────────────────────────────

def get_registry_cards_html(force: bool = False):
    vroms = load_registry(force=force)
    if not vroms:
        return '<div class="vrom-empty">πŸ“­ No vROMs published yet.<br>Submit a request to get started!</div>'

    cards = []
    for v in vroms:
        name = _escape_html(v.get("name", v.get("id", "?")))
        vrom_id = _escape_html(v.get("id", "?"))
        version = _escape_html(str(v.get("version", "?")))
        vectors = v.get("vectors", "?")
        size_mb = v.get("size_mb", "?")
        dims = v.get("dimensions", "?")
        desc = _escape_html(v.get("description", "No description."))
        official = ' <span title="Official">βœ…</span>' if v.get("official") else ""

        tags_html = "".join(
            f'<span class="vrom-tag">{_escape_html(t)}</span>'
            for t in v.get("tags", [])
        )

        files = v.get("files", {})
        files_html = ""
        if files:
            links = []
            for label, key in [("manifest", "manifest"), ("index", "index"), ("chunks", "chunks")]:
                url = files.get(key, "")
                if url:
                    links.append(f'<a href="{_escape_html(url)}" target="_blank">πŸ“„ {label}</a>')
            if links:
                files_html = f'<div class="vrom-files">{"&nbsp;Β·&nbsp;".join(links)}</div>'

        cards.append(f"""<div class="vrom-card">
  <div class="vrom-card-title">πŸ“¦ {name}{official}</div>
  <div class="vrom-card-meta">
    <code>{vrom_id}</code> Β· v{version} Β· {vectors} vectors Β· {size_mb} MB Β· {dims}d
  </div>
  <div>{tags_html}</div>
  <div class="vrom-card-desc">{desc}</div>
  {files_html}
</div>""")

    return "\n".join(cards)


# ─── Admin HTML helpers ─────────────────────────────────────────────────

def get_pending_cards_html(profile: Optional[gr.OAuthProfile], force: bool = False):
    if not is_admin(profile):
        return ""
    data = load_submissions(force=force)
    pending = [s for s in data["submissions"] if s["status"] == "pending"]
    if not pending:
        return '<div class="vrom-empty" style="padding:20px">No pending submissions.</div>'

    cards = []
    for s in pending:
        name = _escape_html(s.get("name", "?"))
        sub_id = _escape_html(s["id"])
        vrom_id = _escape_html(s.get("vrom_id", "?"))
        submitter = _escape_html(s.get("submitter", "?"))
        n_urls = len(s.get("urls", []))
        date = s.get("submitted_at", "?")[:10]
        urls_preview = ", ".join(s["urls"][:2])
        if len(s["urls"]) > 2:
            urls_preview += f" (+{len(s['urls'])-2} more)"
        urls_preview = _escape_html(urls_preview)

        cards.append(f"""<div class="sub-card">
  <div class="sub-card-header">
    <span class="sub-card-name">{name}</span>
    <span class="sub-card-id">{sub_id}</span>
  </div>
  <div class="sub-card-meta">
    <strong>{vrom_id}</strong> Β· by {submitter} Β· {n_urls} URL(s) Β· {date}
  </div>
  <div style="font-size:12px;color:var(--body-text-color-subdued,#888);margin-top:4px;word-break:break-all">{urls_preview}</div>
</div>""")

    return "\n".join(cards)


def get_all_submissions_html(profile: Optional[gr.OAuthProfile], force: bool = False):
    if not is_admin(profile):
        return ""
    data = load_submissions(force=force)
    if not data["submissions"]:
        return '<div class="vrom-empty" style="padding:20px">No submissions yet.</div>'

    status_class = {"pending": "status-pending", "building": "status-building",
                    "published": "status-published", "rejected": "status-rejected",
                    "failed": "status-failed"}
    status_emoji = {"pending": "⏳", "building": "πŸ”¨", "published": "πŸ“¦",
                    "rejected": "❌", "failed": "πŸ’₯"}

    cards = []
    for s in data["submissions"]:
        name = _escape_html(s.get("name", "?"))
        sub_id = _escape_html(s["id"])
        submitter = _escape_html(s.get("submitter", "?"))
        status = s.get("status", "?")
        cls = status_class.get(status, "")
        emoji = status_emoji.get(status, "❓")
        date = s.get("submitted_at", "?")[:10]

        cards.append(f"""<div class="sub-card" style="cursor:default">
  <div class="sub-card-header">
    <span class="sub-card-name">{name}</span>
    <span class="status-badge {cls}">{emoji} {_escape_html(status)}</span>
  </div>
  <div class="sub-card-meta">
    <span class="sub-card-id">{sub_id}</span> Β· by {submitter} Β· {date}
  </div>
</div>""")

    return "\n".join(cards)


# ─── Submit handler ─────────────────────────────────────────────────────

def handle_submit(name, urls, description, tags, version, profile: Optional[gr.OAuthProfile]):
    if not name or not name.strip():
        raise gr.Error("Name is required.")
    if not urls or not urls.strip():
        raise gr.Error("At least one documentation URL is required.")

    url_list = [u.strip() for u in urls.strip().split("\n") if u.strip()]
    if not url_list:
        raise gr.Error("Please enter at least one valid URL.")
    for u in url_list:
        if not u.startswith("http"):
            raise gr.Error(f"Invalid URL: {u}")

    tag_list = [t.strip() for t in tags.split(",") if t.strip()] if tags else []
    vrom_id = slugify(name)
    submitter = profile.username if profile else "anonymous"

    data = load_submissions(force=True)
    registry_ids = {v["id"] for v in load_registry()}
    if vrom_id in registry_ids:
        raise gr.Error(f"A vROM with ID `{vrom_id}` already exists in the registry.")
    pending_ids = {s["vrom_id"] for s in data["submissions"] if s["status"] == "pending"}
    if vrom_id in pending_ids:
        raise gr.Error(f"A submission for `{vrom_id}` is already pending review.")

    submission = {
        "id": str(uuid.uuid4())[:8], "vrom_id": vrom_id, "name": name.strip(),
        "description": description.strip() if description else "",
        "urls": url_list, "tags": tag_list,
        "version": version.strip() if version else "1.0.0",
        "submitter": submitter, "status": "pending",
        "submitted_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "reviewed_at": None, "reviewed_by": None, "review_note": None, "build_error": None,
    }
    data["submissions"].append(submission)
    save_submissions(data)

    gr.Info(f"Submitted! Your request for '{name}' is pending admin review.")
    logger.info(f"New submission: {vrom_id} by {submitter} ({len(url_list)} URLs)")

    return (
        f"### βœ… Submission received!\n\n"
        f"**vROM ID:** `{vrom_id}`  \n"
        f"**Submitted by:** {submitter}  \n"
        f"**URLs:** {len(url_list)} documentation page(s)  \n"
        f"**Status:** ⏳ Pending admin review\n\n"
        f"You'll see it appear in the Browse tab once approved and built."
    )


# ─── Admin action handlers ─────────────────────────────────────────────

def get_submission_detail(sub_id: str, profile: Optional[gr.OAuthProfile]):
    if not is_admin(profile):
        return "πŸ”’ Not authorized."
    if not sub_id or not sub_id.strip():
        return "Enter a submission ID above."
    data = load_submissions()
    for s in data["submissions"]:
        if s["id"] == sub_id.strip():
            urls_md = "\n".join(f"- {u}" for u in s["urls"])
            tags_md = ", ".join(f"`{t}`" for t in s.get("tags", [])) or "none"
            return (
                f"### πŸ“‹ Submission `{s['id']}`\n\n"
                f"**Name:** {s['name']}  \n**vROM ID:** `{s['vrom_id']}`  \n"
                f"**Version:** {s.get('version', '1.0.0')}  \n**Submitter:** {s['submitter']}  \n"
                f"**Status:** {s['status']}  \n**Tags:** {tags_md}  \n"
                f"**Submitted:** {s['submitted_at']}  \n\n"
                f"**Description:**  \n{s.get('description', 'No description.')}\n\n"
                f"**URLs:**\n{urls_md}\n\n"
                f"{'**Build Error:** ' + s['build_error'] if s.get('build_error') else ''}"
            )
    return f"Submission `{sub_id}` not found."


def approve_submission(sub_id: str, profile: Optional[gr.OAuthProfile]):
    if not is_admin(profile):
        raise gr.Error("Unauthorized β€” admins only.")
    if not sub_id or not sub_id.strip():
        raise gr.Error("Enter a submission ID.")

    data = load_submissions(force=True)
    submission = None
    for s in data["submissions"]:
        if s["id"] == sub_id.strip():
            submission = s
            break
    if submission is None:
        raise gr.Error(f"Submission `{sub_id}` not found.")
    if submission["status"] != "pending":
        raise gr.Error(f"Submission is already '{submission['status']}', not pending.")

    submission["status"] = "building"
    submission["reviewed_at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    submission["reviewed_by"] = profile.username
    save_submissions(data)

    gr.Info(f"Building vROM '{submission['name']}'... This may take a minute.")
    logger.info(f"Admin {profile.username} approved {sub_id}, starting build")

    try:
        from vrom_hub import VromHubBackend
        hub = VromHubBackend(registry_repo=REGISTRY_REPO)
        result = hub.submit_project(
            vrom_id=submission["vrom_id"], name=submission["name"],
            description=submission.get("description", ""),
            version=submission.get("version", "1.0.0"),
            urls=submission["urls"], tags=submission.get("tags", []),
            official=False, upload=True,
        )
        submission["status"] = "published"
        submission["build_error"] = None
        save_submissions(data)

        # Bust registry cache since a new vROM was published
        _registry_cache["ts"] = 0

        stats = result["stats"]
        logger.info(f"vROM '{submission['vrom_id']}' published: {stats['vectors']} vectors")
        gr.Info(f"Published! {stats['vectors']} vectors, {stats['total_tokens']} tokens")

        return (
            f"### βœ… Published `{submission['vrom_id']}`\n\n"
            f"**Vectors:** {stats['vectors']}  \n**Tokens:** {stats['total_tokens']}  \n"
            f"**Index size:** {stats['index_size_mb']} MB  \n"
            f"**Hub:** [{submission['vrom_id']}]({result.get('hub_url', '#')})"
        ), get_pending_cards_html(profile), get_all_submissions_html(profile)

    except Exception as e:
        submission["status"] = "failed"
        submission["build_error"] = str(e)
        save_submissions(data)
        logger.error(f"Build failed for {sub_id}: {e}")
        return (
            f"### πŸ’₯ Build failed for `{submission['vrom_id']}`\n\n"
            f"**Error:** {str(e)}\n\n"
            f"The submission has been marked as failed. You can retry or reject it."
        ), get_pending_cards_html(profile), get_all_submissions_html(profile)


def reject_submission(sub_id: str, note: str, profile: Optional[gr.OAuthProfile]):
    if not is_admin(profile):
        raise gr.Error("Unauthorized β€” admins only.")
    if not sub_id or not sub_id.strip():
        raise gr.Error("Enter a submission ID.")
    data = load_submissions(force=True)
    for s in data["submissions"]:
        if s["id"] == sub_id.strip():
            if s["status"] not in ("pending", "failed"):
                raise gr.Error(f"Can only reject pending/failed submissions, not '{s['status']}'.")
            s["status"] = "rejected"
            s["reviewed_at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
            s["reviewed_by"] = profile.username
            s["review_note"] = note.strip() if note else None
            save_submissions(data)
            logger.info(f"Admin {profile.username} rejected {sub_id}")
            gr.Info(f"Rejected submission '{s['name']}'.")
            return (
                f"### ❌ Rejected `{s['vrom_id']}`\n\n**Note:** {note or 'No reason given.'}"
            ), get_pending_cards_html(profile), get_all_submissions_html(profile)
    raise gr.Error(f"Submission `{sub_id}` not found.")


def retry_submission(sub_id: str, profile: Optional[gr.OAuthProfile]):
    if not is_admin(profile):
        raise gr.Error("Unauthorized β€” admins only.")
    if not sub_id or not sub_id.strip():
        raise gr.Error("Enter a submission ID.")
    data = load_submissions(force=True)
    for s in data["submissions"]:
        if s["id"] == sub_id.strip():
            if s["status"] != "failed":
                raise gr.Error(f"Can only retry failed submissions, not '{s['status']}'.")
            s["status"] = "pending"
            s["build_error"] = None
            s["reviewed_at"] = None
            s["reviewed_by"] = None
            save_submissions(data)
            logger.info(f"Admin {profile.username} reset {sub_id} to pending")
            gr.Info(f"Reset '{s['name']}' to pending.")
            return (
                f"### πŸ”„ Reset `{s['vrom_id']}` to pending"
            ), get_pending_cards_html(profile), get_all_submissions_html(profile)
    raise gr.Error(f"Submission `{sub_id}` not found.")


# ─── UI ─────────────────────────────────────────────────────────────────

with gr.Blocks(title="🧩 vROM Hub") as demo:
    gr.Markdown(
        "# 🧩 vROM Hub\n"
        "> Browse, submit, and manage [vROM](https://github.com/philsupertramp/vecdb-wasm) "
        "packages β€” pre-computed vector knowledge bases for in-browser semantic search."
    )

    with gr.Row():
        login_btn = gr.LoginButton(size="sm")

    with gr.Tabs():
        # ── Browse Tab ──────────────────────────────────────────────
        with gr.Tab("Browse", id="browse"):
            gr.Markdown("### πŸ“‹ Published vROMs\nAvailable for instant use via `AgentMemory.mount(id)`.")
            refresh_browse_btn = gr.Button("πŸ”„ Refresh", size="sm", min_width=120)
            browse_cards = gr.HTML("")

            def refresh_browse_clicked():
                return get_registry_cards_html(force=True)
            refresh_browse_btn.click(
                refresh_browse_clicked,
                outputs=[browse_cards],
                show_progress="minimal",
            )

        # ── Submit Tab ──────────────────────────────────────────────
        with gr.Tab("Submit", id="submit"):
            gr.Markdown(
                "### βž• Request a new vROM\n"
                "Submit documentation URLs and we'll build a vector knowledge base from them.\n"
                "An admin will review your request before building."
            )
            sub_name = gr.Textbox(
                label="Project Name",
                placeholder="e.g. My Project Documentation",
                info="Human-readable name for the vROM",
            )
            sub_urls = gr.Textbox(
                label="Documentation URLs (one per line)",
                placeholder="https://example.com/docs/getting-started\nhttps://example.com/docs/api-reference",
                lines=5,
                info="URLs to markdown or HTML documentation pages",
            )
            sub_desc = gr.Textbox(
                label="Description",
                placeholder="What does this documentation cover?",
                lines=2,
            )
            sub_tags = gr.Textbox(
                label="Tags (comma-separated)",
                placeholder="python, api, docs",
            )
            sub_version = gr.Textbox(label="Version", value="1.0.0")

            with gr.Accordion("πŸ’‘ Tips & Specs", open=False):
                gr.Markdown(
                    "- Each URL should point to a single documentation page\n"
                    "- Markdown pages work best\n"
                    "- HTML pages are auto-converted to markdown\n"
                    "- Include 5–50 pages for best results\n"
                    "- The vROM ID is auto-generated from the name\n\n"
                    "**Specs:** all-MiniLM-L6-v2 (384d) Β· ~256 token chunks Β· HNSW (m=16, cosine)"
                )

            submit_btn = gr.Button("πŸš€ Submit Request", variant="primary", size="lg")
            submit_status = gr.Markdown("")
            submit_btn.click(
                handle_submit,
                inputs=[sub_name, sub_urls, sub_desc, sub_tags, sub_version],
                outputs=submit_status,
                show_progress="minimal",
            )

        # ── Admin Tab ───────────────────────────────────────────────
        with gr.Tab("Admin", id="admin") as admin_tab:
            admin_panel = gr.Column(visible=False)
            not_admin_msg = gr.Markdown(
                "### πŸ”’ Admin Access Required\n\nSign in with the admin account to manage submissions.",
                visible=True,
            )
            with admin_panel:
                gr.Markdown("### ⏳ Pending Submissions")
                refresh_admin_btn = gr.Button("πŸ”„ Refresh", size="sm", min_width=120)
                pending_html = gr.HTML("")

                gr.Markdown("---\n### Review Submission")
                admin_sub_id = gr.Textbox(
                    label="Submission ID",
                    placeholder="Enter the ID from the cards above",
                )
                detail_btn = gr.Button("πŸ” View Details", min_width=140)
                detail_md = gr.Markdown("")

                approve_btn = gr.Button("βœ… Approve & Build", variant="primary", size="lg")
                reject_note = gr.Textbox(
                    label="Rejection note (optional)",
                    placeholder="Reason for rejection",
                )
                with gr.Row():
                    reject_btn = gr.Button("❌ Reject", variant="stop", min_width=140)
                    retry_btn = gr.Button("πŸ”„ Retry Failed", min_width=140)
                admin_status = gr.Markdown("")

                gr.Markdown("---\n### πŸ“Š All Submissions")
                all_html = gr.HTML("")

                detail_btn.click(
                    get_submission_detail, inputs=[admin_sub_id], outputs=[detail_md],
                    show_progress="minimal",
                )
                approve_btn.click(
                    approve_submission, inputs=[admin_sub_id],
                    outputs=[admin_status, pending_html, all_html],
                    show_progress="minimal",
                )
                reject_btn.click(
                    reject_submission, inputs=[admin_sub_id, reject_note],
                    outputs=[admin_status, pending_html, all_html],
                    show_progress="minimal",
                )
                retry_btn.click(
                    retry_submission, inputs=[admin_sub_id],
                    outputs=[admin_status, pending_html, all_html],
                    show_progress="minimal",
                )

                def refresh_admin_clicked(profile: Optional[gr.OAuthProfile]):
                    return get_pending_cards_html(profile, force=True), get_all_submissions_html(profile, force=True)
                refresh_admin_btn.click(
                    refresh_admin_clicked, outputs=[pending_html, all_html],
                    show_progress="minimal",
                )

    # ── SINGLE demo.load β€” runs once on page load (including post-OAuth redirect)
    # Uses cached hub downloads (no network blocking), no spinner,
    # no concurrency limit. Handles browse + admin visibility in one call.
    def on_page_load(profile: Optional[gr.OAuthProfile]):
        # Browse cards β€” uses cache (fast, no network on repeat loads)
        cards_html = get_registry_cards_html(force=False)

        # Admin visibility
        admin_visible = is_admin(profile)
        if admin_visible:
            pending = get_pending_cards_html(profile, force=False)
            all_subs = get_all_submissions_html(profile, force=False)
        else:
            pending = ""
            all_subs = ""

        return (
            cards_html,
            gr.update(visible=admin_visible),
            gr.update(visible=not admin_visible),
            pending,
            all_subs,
        )

    demo.load(
        on_page_load,
        outputs=[browse_cards, admin_panel, not_admin_msg, pending_html, all_html],
        show_progress="hidden",     # No spinner β€” prevents UI freeze
        concurrency_limit=None,     # No queueing β€” runs immediately
    )

if __name__ == "__main__":
    demo.launch(ssr_mode=False, css=MOBILE_CSS)