File size: 22,080 Bytes
f636aab
f7ebf60
f636aab
f085505
f636aab
f4a7653
f636aab
 
 
f4a7653
 
f7ebf60
 
 
 
49a08f0
75f0ee4
f7ebf60
 
 
668e353
 
f4a7653
f7ebf60
75f0ee4
 
 
 
 
3838083
75f0ee4
49a08f0
f7ebf60
 
f636aab
f7ebf60
 
 
f636aab
 
f7ebf60
 
f4a7653
 
 
 
f7ebf60
 
f636aab
 
 
 
f7ebf60
f4a7653
 
 
f636aab
 
f7ebf60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4a7653
75f0ee4
f636aab
f4a7653
 
 
 
f7ebf60
 
 
 
 
1740a0a
f636aab
1740a0a
f4a7653
 
f7ebf60
 
 
f4a7653
75f0ee4
 
 
 
 
 
 
 
 
f4a7653
 
 
75f0ee4
f4a7653
75f0ee4
f4a7653
75f0ee4
f4a7653
 
75f0ee4
f4a7653
 
 
 
 
 
 
75f0ee4
49a08f0
 
 
 
75f0ee4
 
49a08f0
 
 
 
f7ebf60
 
f636aab
668e353
f636aab
668e353
 
f4a7653
f636aab
 
f4a7653
f7ebf60
 
 
 
1740a0a
f4a7653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7ebf60
 
 
f4a7653
f636aab
 
f4a7653
f636aab
 
 
 
 
1740a0a
f636aab
 
f4a7653
 
f636aab
 
 
 
 
 
 
 
 
 
1740a0a
 
 
 
 
 
 
f4a7653
 
 
 
f636aab
 
 
 
 
 
 
 
0359b8a
9fa2c5d
 
0359b8a
 
 
 
 
9fa2c5d
0359b8a
 
 
9fa2c5d
0359b8a
c067a74
 
 
 
 
 
975b703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b040ee7
975b703
0359b8a
 
975b703
f636aab
f4a7653
 
 
 
 
 
 
b040ee7
 
 
 
975b703
 
 
f4a7653
975b703
 
 
 
f4a7653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f636aab
f4a7653
 
 
 
 
 
 
 
 
 
 
1740a0a
 
 
f4a7653
1740a0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f636aab
 
975b703
f636aab
0359b8a
 
 
f7ebf60
f636aab
ce8fc15
f636aab
f085505
f4a7653
 
 
f7ebf60
f636aab
 
 
 
 
 
 
 
 
 
 
668e353
f349587
f636aab
668e353
 
 
f636aab
668e353
 
 
b040ee7
 
 
975b703
668e353
 
 
f636aab
 
668e353
 
 
f636aab
668e353
1740a0a
 
 
 
 
 
668e353
 
1740a0a
 
 
 
 
668e353
f4a7653
 
 
 
 
 
 
668e353
 
75f0ee4
 
 
 
 
 
668e353
 
 
 
 
 
 
 
 
f636aab
 
 
 
 
 
668e353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0359b8a
668e353
f7ebf60
75f0ee4
 
 
3838083
 
1740a0a
 
 
 
 
 
 
 
f4a7653
 
1740a0a
f7ebf60
3838083
f636aab
 
f4a7653
 
b040ee7
 
 
f4a7653
b040ee7
 
 
 
f4a7653
 
 
 
 
3838083
f7ebf60
b040ee7
 
 
 
 
 
75f0ee4
 
 
 
 
 
 
 
f7ebf60
f636aab
 
 
 
 
f4a7653
 
 
 
 
 
 
 
 
 
 
f636aab
 
668e353
 
 
f636aab
 
668e353
f636aab
 
 
668e353
f636aab
668e353
f7ebf60
 
 
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
"""armnet eval — a one-click, no-setup policy eval on real hardware.

Pick a task, paste (or pick) a policy repo id, press Run, and watch the rollouts
on a real SO-101 cell: live video, and per-rollout success auto-scored
by the instrumented BusyBox (no human judging). The run is shared — anyone who
opens this Space follows the same fleet in real time.

The task selector sits above the tabs and drives all three: which dataset the
instructions point at, which policy the Live tab defaults to, and which board
the Leaderboard shows. Jobs route to any free BusyBox cell, so more than one
eval can run at once; the Live tab lets you pick which cell's feed to watch.
"""

from __future__ import annotations

import asyncio

import gradio as gr

import config
import leaderboard
from leaderboard import LEADERBOARD
from runner import STATE, display_cell_id, fleet_availability

# The text timer is a lightweight heartbeat so any viewer notices a run another
# viewer started. Video takes a different path: one long-lived generator stream
# per viewer, not one Gradio request per frame. Five FPS is enough to make the
# robot motion readable without making every public viewer encode and receive
# all 20 policy-rate frames.
_TEXT_REFRESH_SECONDS = 2.0
_VIDEO_STREAM_SECONDS = 0.2
_VIDEO_IDLE_SLEEP_SECONDS = 0.25


def _resolve_policy(task_label: str, preset_label: str, custom: str) -> str:
    custom = (custom or "").strip()
    if custom:
        return custom
    task = config.task_for(task_label)
    return task.presets.get(preset_label, task.reference_policy)


def _session_id(request: gr.Request | None) -> str | None:
    return getattr(request, "session_hash", None) if request is not None else None


def _status_markdown(snap: dict) -> str:
    lines = []
    task = snap["task"]
    policy = snap["policy"]
    if not policy:
        return "_Nothing running. Pick a policy and press Run._"
    lines.append(f"**Policy:** `{policy}`")
    cell = display_cell_id(snap.get("cell_id"))
    if cell:
        lines.append(f"**Cell:** `{cell}`")
    if task is not None:
        lines.append(f"**Task:** {task.label}")
    lines.append(f"**Status:** {snap['status']}")
    if snap["job_id"]:
        lines.append(f"**Job:** `{snap['job_id']}`")
    lines.append(
        f"**Progress:** {snap['n_scored']}/{config.N_EPISODES} rollouts scored"
        f" · {snap['n_success']} succeeded"
    )
    if snap["error"]:
        lines.append(f"\n⚠️ **Error:** {snap['error']}")
    return "  \n".join(lines)


def _rollout_markdown(snap: dict) -> str:
    """Render the scored rollouts as a Markdown table.

    Markdown (unlike gr.Dataframe here) re-renders reliably on every Timer tick,
    so the table grows live as each rollout is scored.
    """
    rows = snap["rollouts"]
    if not rows:
        return "### Rollouts\n\n_No rollouts scored yet._"
    lines = ["### Rollouts", "", "| Rollout | Result | Scored by |", "| --- | --- | --- |"]
    for r in rows:
        result = "✅ success" if r["success"] else "❌ fail"
        lines.append(f"| {r['episode']} | {result} | {r['scored_by']} |")
    return "\n".join(lines)


def _summary_markdown(snap: dict) -> str:
    summary = snap["summary"]
    if not summary:
        if snap["n_scored"]:
            rate = 100.0 * snap["n_success"] / snap["n_scored"]
            return f"### Live: {snap['n_success']}/{snap['n_scored']} succeeded ({rate:.0f}%)"
        return ""
    agg = summary.get("aggregated", {}) if isinstance(summary, dict) else {}
    pc = agg.get("pc_success")
    parts = []
    if pc is not None:
        parts.append(f"### Final: {pc:.0f}% success over {agg.get('n_episodes', '?')} rollouts")
    url = summary.get("eval_dataset_url") if isinstance(summary, dict) else None
    if url:
        parts.append(f"[Recorded eval dataset →]({url})")
    return "  \n".join(parts)


def _refresh_text(task_label: str, selected_feed: str | None, request: gr.Request):
    """Lightweight heartbeat for status shared between every viewer."""
    task = config.task_for(task_label)
    session_id = _session_id(request)
    if selected_feed:
        STATE.set_view(session_id, selected_feed)
    snap = STATE.snapshot(session_id=session_id, task_slug=task.slug)
    return (
        _status_markdown(snap),
        _rollout_markdown(snap),
        _summary_markdown(snap),
        "\n".join(snap["events"][-30:]),
        _run_button_update(snap, task),
        _cell_light_html(snap, task),
        _queue_markdown(snap),
        _feed_selector_update(snap),
        _feed_caption(snap),
    )


async def _stream_video(request: gr.Request):
    """Yield newest frames over one Gradio stream, capped at five FPS.

    ``STATE`` itself is fed continuously by the orchestrator websocket. Reading
    only its newest version preserves the old drop-to-stay-live semantics: a
    slow browser skips stale frames instead of building latency.

    The generator deliberately stays alive while the page is open, including
    between evals. That lets a viewer who did not press Run see a shared run
    started by someone else without bringing back a polling request per frame.
    Gradio cancels it when that browser disconnects. The selected cell is read
    from this session's view on every tick so switching feeds does not restart
    the stream.
    """
    session_id = _session_id(request)
    last_version = -1
    last_cell = None
    while True:
        snap = STATE.snapshot(session_id=session_id)
        cell = snap.get("selected_cell")
        version = snap["frame_version"]
        if cell != last_cell:
            last_cell = cell
            last_version = -1
            if snap["latest_frame"] is None:
                yield None
                await asyncio.sleep(_VIDEO_IDLE_SLEEP_SECONDS)
                continue
        if version == last_version or snap["latest_frame"] is None:
            # An async sleep is cancellable when the browser disconnects. The
            # old synchronous generator blocked one of Gradio's 40 worker
            # threads inside next() whenever the Space was idle.
            await asyncio.sleep(_VIDEO_IDLE_SLEEP_SECONDS)
            continue
        last_version = version
        # decode_frame() already resized this once process-wide. Do not make
        # every connected viewer repeat the same PIL work.
        yield snap["latest_frame"]
        await asyncio.sleep(_VIDEO_STREAM_SECONDS)


def _load_leaderboard(task_label: str, sort_choice: str, force: bool = False):
    by = "rate" if "Average" in (sort_choice or "") else "lower"
    return LEADERBOARD.rows(config.task_for(task_label).slug, by=by, force=force)


def _on_run(task_label: str, preset_label: str, custom: str, request: gr.Request):
    task = config.task_for(task_label)
    ok, message = STATE.start_run(_resolve_policy(task_label, preset_label, custom), task)
    snap = STATE.snapshot(session_id=_session_id(request), task_slug=task.slug)
    banner = ("✅ " if ok else "⛔ ") + message
    return (
        banner,
        _status_markdown(snap),
        _run_button_update(snap, task),
        _feed_selector_update(snap),
        _feed_caption(snap),
        _cell_light_html(snap, task),
    )


def _on_feed_change(selected_feed: str, task_label: str, request: gr.Request):
    task = config.task_for(task_label)
    STATE.set_view(_session_id(request), selected_feed)
    snap = STATE.snapshot(session_id=_session_id(request), task_slug=task.slug)
    return (
        _status_markdown(snap),
        _rollout_markdown(snap),
        _summary_markdown(snap),
        "\n".join(snap["events"][-30:]),
        _feed_caption(snap),
    )


def _on_task_change(task_label: str, sort_choice: str, request: gr.Request):
    """Re-point every tab at the newly selected task."""
    task = config.task_for(task_label)
    snap = STATE.snapshot(session_id=_session_id(request), task_slug=task.slug)
    return (
        _instructions_markdown(task),
        gr.update(choices=list(task.presets), value=task.reference_label),
        gr.update(placeholder=task.reference_policy, value=""),
        _cell_light_html(snap, task),
        _run_button_update(snap, task),
        _load_leaderboard(task_label, sort_choice),
        _task_blurb(task),
        _feed_selector_update(snap),
        _feed_caption(snap),
    )


def _task_blurb(task: config.Task) -> str:
    return f"**{task.label}.** {task.blurb}"


def _instructions_markdown(task: config.Task) -> str:
    return (
        "## How to use this Space\n\n"
        f"1. **Train a LeRobot-compatible policy** on either the task-specific "
        f"[`{task.dataset}`](https://huggingface.co/datasets/{task.dataset}) dataset "
        f"or the language-conditioned "
        f"[`{config.MULTITASK_DATASET}`]"
        f"(https://huggingface.co/datasets/{config.MULTITASK_DATASET}) dataset. "
        "Make sure the trained policy is **uploaded to Hugging Face and publicly "
        "available**.\n"
        "2. **Copy your repo ID** into the text box on the **Live** tab and submit it. "
        "Armnet will automatically run and score the policy on a real SO-101 cell. "
        "If every cell is busy, the job waits in the shared queue. If more than one "
        "eval is running, pick which cell's live feed to watch.\n\n"
        "You can run a policy more than once. The more rollouts a policy accumulates, the "
        "closer its **lower confidence interval** matches its **average success rate** — "
        "see the **Leaderboard** tab.\n\n"
        f"Every task has its own dataset and its own board, so pick the one you want at "
        "the top of the page before you start."
    )


# Gradio's Dataframe markdown strips <img> sizing attributes, so force a small,
# inline avatar next to the trainer name via CSS. Hugging Face shows these as
# squares, not circles. Also styles the round, blinking cell-availability light.
_CSS = """
#leaderboard-table img {
  width: 20px !important;
  height: 20px !important;
  min-width: 20px !important;
  border-radius: 2px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 4px 0 0 !important;
  object-fit: cover;
}
#leaderboard-table .lb-verified {
  color: #16a34a;
  font-weight: 600;
  white-space: nowrap;
  cursor: help;
}
.cell-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  margin: 4px 0 2px 0;
}
.cell-dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  display: inline-block;
  flex: 0 0 auto;
}
.cell-dot--green { background: #22c55e; box-shadow: 0 0 7px 1px #22c55e; animation: cell-blink 1.4s ease-in-out infinite; }
.cell-dot--yellow { background: #eab308; box-shadow: 0 0 7px 1px #eab308; animation: cell-blink 1.0s ease-in-out infinite; }
.cell-dot--red { background: #ef4444; box-shadow: 0 0 7px 1px #ef4444; animation: cell-blink 0.8s ease-in-out infinite; }
.cell-dot--grey { background: #9ca3af; }
@keyframes cell-blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.25; } }
"""


def _cell_light_html(snap: dict, task: config.Task) -> str:
    color = snap.get("availability_color")
    caption = snap.get("availability_caption")
    if not color or not caption:
        color, caption = fleet_availability(
            snap.get("cell_statuses") or {},
            aggregate=snap.get("cell_status", {}).get(task.slug, "offline"),
        )
    return _light_html(color, caption)


def _light_html(color: str, caption: str) -> str:
    return (
        '<div class="cell-status">'
        f'<span class="cell-dot cell-dot--{color}"></span>'
        f"<span>{caption}</span>"
        "</div>"
    )


def _feed_caption(snap: dict) -> str:
    policy = snap.get("policy")
    if not policy:
        return ""
    cell = display_cell_id(snap.get("cell_id"))
    task = snap.get("task")
    parts = [f"**Watching:** `{policy}`"]
    if cell:
        parts.append(f"on `{cell}`")
    if task is not None:
        parts.append(f"· {task.label}")
    return " ".join(parts)


def _feed_selector_update(snap: dict):
    feeds = snap.get("live_feeds") or []
    # Offer a choice whenever two evals can be watched — including a run that
    # just finished while another cell is still going.
    shown = feeds if len(feeds) > 1 else []
    choices = []
    for feed in shown:
        cell = display_cell_id(feed["cell_id"]) or "routing"
        suffix = "" if feed["active"] else f" ({feed['status']})"
        choices.append((f"{feed['policy']} · {cell}{suffix}", feed["cell_id"]))
    selected = snap.get("selected_cell")
    values = [choice[1] for choice in choices]
    value = selected if selected in values else (values[0] if values else None)
    return gr.update(choices=choices, value=value, visible=len(choices) > 1)


def _queue_mode(snap: dict, task: config.Task) -> bool:
    statuses = snap.get("cell_statuses") or {}
    if statuses:
        return not any(
            status == "available" for status in statuses.values()
        ) and any(
            status in {"occupied", "maintenance"} for status in statuses.values()
        )
    return snap.get("cell_status", {}).get(task.slug, "offline") == "occupied"


def _can_submit(snap: dict, task: config.Task) -> bool:
    """Allow immediate runs, or queueing while every matching cell is busy."""
    if snap["queued_eval_total"] >= config.MAX_QUEUED_JOBS:
        return False
    statuses = snap.get("cell_statuses") or {}
    if statuses:
        return any(
            status in {"available", "occupied", "maintenance"}
            for status in statuses.values()
        )
    status = snap.get("cell_status", {}).get(task.slug, "offline")
    return status in {"available", "occupied"}


def _run_button_update(snap: dict, task: config.Task):
    queue_mode = _queue_mode(snap, task)
    return gr.update(
        value=(
            f"Queue {config.N_EPISODES} rollouts"
            if queue_mode
            else f"Run {config.N_EPISODES} rollouts"
        ),
        variant="secondary" if queue_mode else "primary",
        interactive=_can_submit(snap, task),
    )


def _queue_markdown(snap: dict) -> str:
    total = snap["queue_total"]
    eval_total = snap["queued_eval_total"]
    lines = [
        f"### Shared queue ({total} waiting)",
        "",
        f"_Armnet eval submissions: {eval_total}/{config.MAX_QUEUED_JOBS}._",
        "",
    ]
    if not snap["queue_items"]:
        lines.append("_No jobs waiting._")
    else:
        lines.extend(
            f"{index}. `{label}`"
            for index, label in enumerate(snap["queue_items"], start=1)
        )
    if eval_total >= config.MAX_QUEUED_JOBS:
        lines.extend(["", "_Armnet eval queue full — submissions are temporarily disabled._"])
    return "\n".join(lines)

_DEFAULT_TASK = config.TASKS[config.DEFAULT_TASK_LABEL]

with gr.Blocks(title="armnet eval — evaluate a policy on real robots") as demo:
    # Inject CSS via a <style> element (Gradio 6 moved the Blocks `css=` arg to
    # launch(), which the Space controls, so this is the portable way).
    gr.HTML(f"<style>{_CSS}</style>")
    gr.Markdown(
        "# armnet eval — evaluate a policy on real robots\n"
        "[armnet.dev](https://armnet.dev/)\n\n"
        "Pick a task, pick or paste a policy, press **Run**, and watch **"
        f"{config.N_EPISODES} rollouts** on a real SO-101 cell. Success is "
        "auto-scored by the instrumented BusyBox — no human judging. Anyone here "
        "can watch live evals; if more than one cell is running, pick which feed "
        "to follow."
    )

    # Above the tabs because it scopes all of them: the dataset the instructions
    # point at, the policy the Live tab defaults to, and the board shown under
    # Leaderboard.
    task_sel = gr.Radio(
        config.TASK_LABELS,
        value=config.DEFAULT_TASK_LABEL,
        label="Task",
    )
    task_blurb = gr.Markdown(_task_blurb(_DEFAULT_TASK))

    with gr.Tabs():
        with gr.Tab("Instructions"):
            instructions = gr.Markdown(_instructions_markdown(_DEFAULT_TASK))
        with gr.Tab("Live"):
            if not config.eval_image_configured():
                gr.Markdown(
                    "> ⚠️ **Not configured.** Set `ARMNET_DEMO_EVAL_IMAGE` (a pre-built "
                    "lerobot-eval runtime image ref) in the Space settings — see the README."
                )

            # Not "cells offline": a page that never gets its first refresh
            # would then look exactly like a fleet that is down.
            cell_light = gr.HTML(_light_html("grey", "checking cells…"))

            with gr.Row():
                preset = gr.Dropdown(
                    label="Pre-trained policy",
                    choices=list(_DEFAULT_TASK.presets),
                    value=_DEFAULT_TASK.reference_label,
                )
                custom = gr.Textbox(
                    label="…or a custom HF repo id",
                    placeholder=_DEFAULT_TASK.reference_policy,
                )
                run_btn = gr.Button(
                    f"Run {config.N_EPISODES} rollouts",
                    variant="primary",
                    interactive=False,
                    scale=0,
                )

            banner = gr.Markdown("")
            queue_view = gr.Markdown(
                "### Shared queue (0 waiting)\n\n"
                f"_Armnet eval submissions: 0/{config.MAX_QUEUED_JOBS}._\n\n"
                "_No jobs waiting._"
            )

            feed_sel = gr.Radio(
                label="Live eval",
                choices=[],
                visible=False,
            )
            feed_caption = gr.Markdown("")

            with gr.Row():
                with gr.Column(scale=3):
                    video = gr.Image(
                        label="Live rollout",
                        height=320,
                        interactive=False,
                        streaming=True,
                    )
                with gr.Column(scale=2):
                    status = gr.Markdown("")
                    summary = gr.Markdown("")
                    rollouts = gr.Markdown("### Rollouts\n\n_No rollouts scored yet._")

            events = gr.Textbox(label="Live log", lines=8, interactive=False, autoscroll=True)

        with gr.Tab("Leaderboard") as leaderboard_tab:
            gr.Markdown(
                "Each task has **its own board** — the one shown follows the task "
                "selected above. Results are **pooled by policy repo + revision** "
                "across every run, and ranked by the **95% lower-bound** success rate "
                "by default — so running more rollouts only helps if the policy is "
                "genuinely good (spamming low-quality evals can't game it). Switch to "
                "*Average success rate* to rank by the raw mean."
            )
            with gr.Row():
                lb_sort = gr.Radio(
                    ["Lower bound (95%)", "Average success rate"],
                    value="Lower bound (95%)",
                    label="Sort by",
                    scale=3,
                )
                lb_refresh = gr.Button("Refresh", scale=0)
            lb_table = gr.Dataframe(
                headers=leaderboard.HEADERS,
                datatype=leaderboard.DATATYPES,
                interactive=False,
                wrap=True,
                label="Leaderboard",
                elem_id="leaderboard-table",
            )

    # Text is cheap enough to poll. Video uses one generator response for the
    # lifetime of the page, so increasing its FPS does not multiply HTTP/API
    # requests per viewer.
    text_timer = gr.Timer(_TEXT_REFRESH_SECONDS)

    text_outputs = [
        status,
        rollouts,
        summary,
        events,
        run_btn,
        cell_light,
        queue_view,
        feed_sel,
        feed_caption,
    ]

    run_btn.click(
        _on_run,
        inputs=[task_sel, preset, custom],
        outputs=[banner, status, run_btn, feed_sel, feed_caption, cell_light],
    )
    # concurrency_limit=None on both: they share one Gradio concurrency group
    # (keyed by the function), and its default limit of 1 would put every
    # viewer's refresh behind a single worker. It only reads a locked snapshot.
    text_timer.tick(
        _refresh_text,
        inputs=[task_sel, feed_sel],
        outputs=text_outputs,
        concurrency_limit=None,
    )
    feed_sel.change(
        _on_feed_change,
        inputs=[feed_sel, task_sel],
        outputs=[status, rollouts, summary, events, feed_caption],
    )

    demo.load(
        _refresh_text,
        inputs=[task_sel, feed_sel],
        outputs=text_outputs,
        concurrency_limit=None,
    )
    demo.load(
        _stream_video,
        outputs=video,
        show_progress="hidden",
        concurrency_limit=None,
        stream_every=_VIDEO_STREAM_SECONDS,
        api_visibility="private",
    )

    # Switching task re-points every tab at once, so a viewer never sees one
    # task's dataset next to another's leaderboard.
    task_sel.change(
        _on_task_change,
        inputs=[task_sel, lb_sort],
        outputs=[
            instructions,
            preset,
            custom,
            cell_light,
            run_btn,
            lb_table,
            task_blurb,
            feed_sel,
            feed_caption,
        ],
    )

    # Leaderboard: load on tab open / sort change / manual refresh (and once on
    # page load). Not on a timer — it changes only when a run finishes, so
    # constant polling would just risk rate limiting for no benefit.
    leaderboard_tab.select(_load_leaderboard, inputs=[task_sel, lb_sort], outputs=[lb_table])
    lb_sort.change(_load_leaderboard, inputs=[task_sel, lb_sort], outputs=[lb_table])
    lb_refresh.click(
        lambda t, s: _load_leaderboard(t, s, force=True),
        inputs=[task_sel, lb_sort],
        outputs=[lb_table],
    )
    demo.load(_load_leaderboard, inputs=[task_sel, lb_sort], outputs=[lb_table])


if __name__ == "__main__":
    demo.queue().launch()