Spaces:
Running on Zero

File size: 45,486 Bytes
e7c60d3
8dcd89f
c38a7c7
 
f42c079
 
d808dae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c38a7c7
bf549ce
f42c079
5c4d9b2
f42c079
252e94e
f42c079
afbc7f3
 
 
 
 
 
5c4d9b2
 
f42c079
 
252e94e
d808dae
c38a7c7
252e94e
0ef9fdb
 
c38a7c7
 
 
f42c079
d808dae
c38a7c7
5c4d9b2
 
c9e4526
 
5c4d9b2
afbc7f3
c38a7c7
 
 
 
 
 
 
 
 
 
 
 
c9e4526
c38a7c7
 
f42c079
 
afbc7f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f42c079
 
 
afbc7f3
 
 
5c4d9b2
afbc7f3
c9e4526
5c4d9b2
afbc7f3
 
 
 
 
 
 
 
 
 
 
c9e4526
afbc7f3
 
5c4d9b2
 
 
 
 
 
 
 
 
 
f42c079
 
afbc7f3
5c4d9b2
 
afbc7f3
8dcd89f
 
c38a7c7
 
afbc7f3
c38a7c7
 
 
 
f42c079
8dcd89f
 
c38a7c7
 
c9e4526
 
 
 
c38a7c7
8dcd89f
c38a7c7
afbc7f3
c38a7c7
 
 
 
 
c9e4526
c38a7c7
 
f42c079
c38a7c7
 
 
92c99f6
c38a7c7
f42c079
 
c38a7c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9e4526
c38a7c7
 
92c99f6
c38a7c7
5c4d9b2
f42c079
c9e4526
c38a7c7
 
 
 
 
f42c079
c38a7c7
 
d808dae
 
 
 
 
 
 
 
 
 
c9e4526
 
d808dae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9e4526
 
d808dae
c9e4526
 
 
 
d808dae
 
 
c9e4526
 
 
 
 
 
 
 
 
 
 
c38a7c7
f42c079
c38a7c7
f42c079
 
d808dae
c9e4526
 
 
c38a7c7
38796ae
c38a7c7
5c4d9b2
 
c38a7c7
 
 
92c99f6
38796ae
d808dae
 
 
f42c079
d808dae
 
 
c38a7c7
d808dae
c38a7c7
92c99f6
 
d808dae
f42c079
c38a7c7
 
 
f42c079
c38a7c7
 
 
5c4d9b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9e4526
5c4d9b2
 
 
 
 
 
 
 
 
 
c9e4526
 
 
 
 
 
5c4d9b2
c9e4526
5c4d9b2
 
 
 
 
 
c9e4526
 
f42c079
 
c38a7c7
 
 
 
 
 
 
 
 
 
f42c079
c38a7c7
 
 
 
 
 
 
5c4d9b2
 
 
c38a7c7
 
f42c079
 
 
 
c9e4526
f42c079
 
 
 
5c4d9b2
f42c079
c38a7c7
 
 
f42c079
c38a7c7
 
f42c079
 
 
c38a7c7
 
f42c079
c38a7c7
f42c079
 
 
 
 
c9e4526
f42c079
c38a7c7
 
 
 
0ef9fdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92c99f6
 
 
 
 
 
0ef9fdb
 
92c99f6
 
 
 
 
 
 
0ef9fdb
92c99f6
 
 
0ef9fdb
 
 
92c99f6
 
 
 
c38a7c7
 
 
c9e4526
c38a7c7
 
92c99f6
c38a7c7
 
 
d808dae
 
 
c38a7c7
 
 
 
 
 
ac0f3cd
d808dae
 
 
 
 
c38a7c7
 
 
 
 
 
 
 
d808dae
 
 
 
c38a7c7
d808dae
 
 
 
 
 
 
 
c38a7c7
 
 
 
 
 
 
 
 
92c99f6
c38a7c7
92c99f6
 
c38a7c7
 
d808dae
 
c38a7c7
 
 
 
 
 
 
 
252e94e
 
 
 
c38a7c7
afbc7f3
8dcd89f
252e94e
 
 
f42c079
afbc7f3
 
 
 
 
 
 
 
 
8dcd89f
f42c079
 
 
 
afbc7f3
 
 
 
 
 
 
c38a7c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9e4526
c38a7c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afbc7f3
c38a7c7
8dcd89f
f42c079
c38a7c7
f42c079
c38a7c7
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
import { moveCards, renderProbes, tasks } from './tasks.js?v=rank-settle';

const byId = id => document.getElementById(id);
const escape = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[char]));
const steps = ['encode', 'generate', 'score', 'lock', 'filter', 'rerank', 'output'];
const events = ['encode', 'beam', 'stage1', 'gate', 'filter', 'stage2', 'done'];
const activities = {
  submit: [0, -1, 'Submitting the GPU request…', '正在提交 GPU 请求…'],
  wait: [0, -1, 'Waiting for ZeroGPU to start the request…', '正在等待 ZeroGPU 调度并启动…'],
  runtime: [0, -1, 'GPU assigned. Initializing the inference runtime…', '已分配 GPU,正在初始化推理运行环境…'],
  encode: [1, 0, 'Loading RSCaMa and encoding the image pair…', '正在加载 RSCaMa 并编码双时相影像…'],
  beam: [2, 1, 'Loading the SCST decoder and generating Beam-15…', '正在加载 SCST 解码器并生成 Beam-15…'],
  stage1_load: [3, 2, 'Stage 1 · Loading Elephant-1 and its ranking adapter…', '第一阶段 · 正在加载 Elephant-1 与排序适配器…'],
  stage1_score: [3, 2, 'Stage 1 · Scoring all 15 candidates…', '第一阶段 · 正在为全部 15 条候选评分…'],
  gate: [3, 3, 'Locking the change state from the highest-scoring caption…', '正在根据最高分描述锁定变化状态…'],
  filter: [4, 4, 'Filtering no-change and duplicate captions…', '正在过滤无变化与重复描述…'],
  stage2_load: [4, 5, 'Stage 2 · Loading Elephant-1 and its change adapter…', '第二阶段 · 正在加载 Elephant-1 与变化适配器…'],
  stage2_score: [4, 5, 'Stage 2 · Comparing the eligible change captions…', '第二阶段 · 正在比较保留的变化描述…'],
  output: [5, 6, 'Selecting the final caption and mapping to its original Beam ID…', '正在选定最终描述并回映至原始 Beam ID…'],
};
const monitorNodes = [['ZeroGPU','ZeroGPU'], ['Image encoding','影像编码'], ['Beam-15','Beam-15'], ['Stage 1','第一阶段'], ['Stage 2','第二阶段'], ['Caption','最终描述']];
const labels = {
  heroMethod: ['Reranking with a System-1 Decision Model','System-1 决策模型辅助重排'],
  project: ['Project ↗','项目主页 ↗'], headline: ['The best caption isn’t always ranked first.','排名第一的,不一定是最好的描述。'],
  lede: ['Check what changed, then select the caption that best matches both images.','先判断场景是否变化,再选出最符合双时相影像的描述。'],
  observations: ['Bi-temporal observations','双时相观测'], trace: ['Live GPU Inference','GPU 实时推理'],
  openInference: ['Live GPU Inference','GPU 实时推理'], inferencePath: ['Image pair → Beam-15 → Final caption','双时相影像 → Beam-15 → 最终描述'],
  results: ['Benchmark results','基准成果'], baseline: ['SCST Beam-15 Top-1 → Critique-then-Rerank','SCST Beam-15 首选 → 两阶段重排'],
  listTitle: ['From two images to one caption','从双时相影像到变化描述'], listIntro: ['Choose a preset LEVIR-CC pair to run live. Each pair contains before and after images of the same location.','选择一组 LEVIR-CC 预置影像即可开始实时推理。每组都是同一地点的前后两期影像。'],
  pairs: ['Browse LEVIR-CC image pairs','浏览 LEVIR-CC 双时相影像'], followTrace: ['Follow the decision trace ↓','查看决策过程 ↓'],
  decisionLabs: ['One model, four decisions','一个模型,四项决策任务'],
  decisionIntro: ['Explore how Elephant-1 detects change, verifies a caption, compares two captions, and selects from the Beam-15 pool. These examples don’t use GPU quota.','看 Elephant-1 如何判断变化、核验描述、比较两句描述,以及从 Beam-15 候选池中选出最终描述。浏览示例不消耗 GPU 配额。'],
  taskState: tasks[0].label, taskVerify: ['Caption verification','描述核验'], taskPair: tasks[2].label, taskList: tasks[3].label,
  taskStateHint: ['Images only','仅输入影像'], taskVerifyHint: ['Yes / No','支持 / 不支持'],
  decisionTitle: ['State-Routed Decision Trace','状态分流与决策过程'], traceIntro: ['Stage 1 locks the change state. That decision determines whether to exit, return a candidate directly, or run Stage 2.','第一阶段锁定变化状态,随后按状态与候选数量决定提前退出、直接返回候选,或执行第二阶段。'],
  rankingTitle: ['Candidate Ranking Explorer','候选重排探索'],
  encode: ['Encode the pair','编码双图'], generate: ['Generate Beam-15','生成 Beam-15'], score: ['Score all candidates','全候选评分'], lock: ['Route by state','按状态分流'], filter: ['Filter the pool','过滤候选池'],
  rerank: ['Compare + calibrate','精排与长度校准'], output: ['Map to original Beam ID','回映原始 Beam ID'],
  play: ['▷ Step through','▷ 逐步演示'], pause: ['Ⅱ Pause','Ⅱ 暂停演示'], live: ['Run on GPU','开始 GPU 推理'],
  monitor: ['Runtime monitor','实时运行监控'], elapsed: ['Elapsed','已用时'],
};
const inferenceHash = '#trace-title';
const hubOrigin = 'https://huggingface.co';
const zeroGpuHandshake = 'supports-zerogpu-headers';
let lang = new URLSearchParams(location.search).get('lang') === 'zh' ? 'zh' : 'en';
const text = (en, zh) => lang === 'zh' ? zh : en;
const label = key => text(...labels[key]);
let catalog, selected, trace, phase = 3, mode = 'archive', liveEvent, busy = false, follow = true, failure = null, timer;
let liveActivity, runTimes, clockTimer;
let view = 'swipe', divider = 50, beta = 0.12;
let activeTask = 0, rankedView = false, explorerBeta;
let probeControls;
const pulseTimes = new Map();
const pulseLength = 720;
const taskPanels = ['task-state', 'task-verify', 'task-pair', 'task-list'];
const taskTabs = [...byId('task-grid').querySelectorAll('[role="tab"]')];

function translate() {
  document.documentElement.lang = text('en','zh-CN');
  document.title = `Critique-then-Rerank · ${text('Decision Lab','决策工作台')}`;
  for (const node of document.querySelectorAll('[data-t]')) node.textContent = label(node.dataset.t);
  byId('language').textContent = text('中文','EN');
  byId('language').setAttribute('aria-label', text('切换到中文','Switch to English'));
}

const media = path => `./media/${path.split('/').map(encodeURIComponent).join('/')}`;
const stateLabel = changed => changed ? text('Changed','有变化') : text('Unchanged','无变化');
const rankLabel = index => `#${String(index + 1).padStart(2, '0')}`;
const compareValue = value => text(`Reveal: T₁ ${value}%, T₂ ${100 - value}%`, `显示范围:T₁ ${value}%,T₂ ${100 - value}%`);
const image = (path, later) => `<img src="${media(path)}" width="256" height="256" alt="${later ? text('T₂: later satellite image','T₂:后一时相遥感影像') : text('T₁: earlier satellite image','T₁:前一时相遥感影像')}">`;

const frame = (path, later) => `<div class="frame">${image(path, later)}<span>${later ? 'T₂' : 'T₁'}</span></div>`;
const pair = item => `<div class="pair">${item.media.map((path, index) => frame(path, index === 1)).join('')}</div>`;
const evidence = item => `<figure class="task-evidence"><span class="micro">${text('VISUAL EVIDENCE','影像证据')}</span>${pair(item)}<figcaption class="fine">LEVIR-CC · ${escape(item.name)}</figcaption></figure>`;

function selectTask(index) {
  activeTask = index;
  taskTabs.forEach((button, position) => {
    const current = index === position;
    button.setAttribute('aria-selected', current);
    button.tabIndex = current ? 0 : -1;
    byId(taskPanels[position]).hidden = !current;
    if (position === 0) {
      if (current) byId(taskPanels[position]).tabIndex = 0;
      else byId(taskPanels[position]).removeAttribute('tabindex');
    }
  });
  taskTabs[index].focus({preventScroll:true});
  taskTabs[index].scrollIntoView({block:'nearest', inline:'nearest', container:'nearest'});
}

function renderExplorer() {
  const example = catalog.cases.find(item => item.name === 'test_000125.png');
  const {captions, final} = example.replay;
  byId('rank-explorer').innerHTML = `<div class="verify-grid"><div>${evidence(example)}<div class="rank-jump"><strong>${final + 1} → 1</strong><span>${text('Beam rank → final rank','原始 Beam 排名 → 最终排名')} · β = ${catalog.beta.toFixed(2)}</span></div>
    <blockquote lang="en">${escape(captions[final])}</blockquote></div>
    <div><h3 class="probe-question">${text('How does Beam #15 rise to first?', 'Beam #15 如何升到第一?')}</h3><p class="explain">${text('Compare the generator and visual ranking of all 15 beams. Then adjust β to see how caption length changes the winner.', '对比全部 15 条候选的生成与视觉重排顺序,再调节 β,看看句长如何影响首选。')}</p>
    <div class="view-mode" role="group" aria-label="${text('Ranking order','排序方式')}"><button type="button" data-rank="0" aria-pressed="${!rankedView}">${text('Generator order','生成器排序')}</button><button type="button" data-rank="1" aria-pressed="${rankedView}">${text('Reranked order','视觉重排后')}</button></div>
    <div class="formula explorer-formula"><code>log(max(P(slot), 10⁻³⁰)) − β × words</code><label class="range-label" for="explorer-beta">${text('Length penalty β','长度惩罚 β')}<output id="explorer-beta-value" for="explorer-beta">${explorerBeta.toFixed(2)}</output></label><input class="beta-range" id="explorer-beta" type="range" min="0" max="0.20" step="0.02" value="${explorerBeta}"></div>
    <p class="fine explorer-verdict" id="explorer-winner" role="status"></p><ol class="pool explorer-pool" id="explorer-pool">${captions.map((caption, index) => `<li class="slot" data-beam="${index}"><code></code><span lang="en">${escape(caption)}</span><div class="explorer-score"><code>Beam ${rankLabel(index)}</code><small></small></div></li>`).join('')}</ol></div></div>`;
  updateExplorer(example);
}

function updateExplorer(example) {
  const {captions, stage2} = example.replay;
  const ranked = calibrated(stage2, captions, explorerBeta);
  const winner = ranked[0].index;
  const order = rankedView ? ranked.map(candidate => candidate.index) : captions.map((_, index) => index);
  const scores = new Map(ranked.map(candidate => [candidate.index, candidate.score]));
  byId('explorer-beta-value').textContent = explorerBeta.toFixed(2);
  byId('explorer-beta').setAttribute('aria-valuetext', explorerBeta.toFixed(2));
  byId('explorer-beta').style.setProperty('--fill', `${explorerBeta * 500}%`);
  byId('explorer-winner').textContent = text(`At β = ${explorerBeta.toFixed(2)}: Beam ${rankLabel(winner)} wins.`, `β = ${explorerBeta.toFixed(2)} 时:选中 Beam ${rankLabel(winner)}。`);
  for (const button of byId('rank-explorer').querySelectorAll('[data-rank]')) button.setAttribute('aria-pressed', (button.dataset.rank === '1') === rankedView);
  const pool = byId('explorer-pool');
  pool.scrollTop = 0;
  moveCards(pool, order.map(index => pool.querySelector(`[data-beam="${index}"]`)), (card, rank) => {
    const index = Number(card.dataset.beam);
    card.classList.toggle('winner', index === winner);
    card.firstElementChild.textContent = rank + 1;
    const score = card.querySelector('small');
    score.hidden = !rankedView;
    score.textContent = scores.get(index)?.toFixed(4) ?? '—';
  });
}

function renderTasks() {
  probeControls ??= renderProbes({byId, text, evidence, pair, escape, catalog});
  probeControls();
  renderExplorer();
}

function renderCases() {
  byId('case-grid').innerHTML = catalog.cases.map((item, index) => `<button type="button" class="case" data-case="${index}" aria-pressed="${item === selected}" ${busy ? 'disabled' : ''}>
    <span class="case-thumbs" aria-hidden="true">${item.media.map((path, period) => `<span><img src="${media(path)}" width="256" height="256" alt=""><small>${period ? 'T₂' : 'T₁'}</small></span>`).join('')}</span>
    <span><strong>${escape(text(item.en, item.zh))}</strong><small>${escape(item.name.replace('.png',''))}</small></span></button>`).join('');
}

function renderViewer() {
  const current = selected;
  byId('case-id').textContent = current.name.replace('.png','');
  const [before, after] = current.media;
  const modes = [['swipe',text('Swipe','拉帘')],['pair',text('Side by side','并排')],['video',text('Playback','时序播放')]];
  let stage;
  if (view === 'swipe') stage = `<div class="swipe" style="--split:${divider}%">${image(before, false)}<div class="after">${image(after, true)}</div><span class="t1">T₁ <span>${text('Before','变化前')}</span></span><span class="t2">T₂ <span>${text('After','变化后')}</span></span><span class="divider" aria-hidden="true"></span>
    <span class="divider-grip" aria-hidden="true"><svg viewBox="0 0 24 24" width="24" height="24" fill="none"><path d="m8.5 8-4 4 4 4m7-8 4 4-4 4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
    <input id="divider" type="range" min="0" max="100" value="${divider}" aria-valuetext="${compareValue(divider)}"></div>
    <label class="range-label" for="divider"><span>${text('Drag to compare T₁ / T₂','拖动对比 T₁ / T₂')}</span><output id="divider-value" aria-hidden="true">${divider}%</output></label>`;
  if (view === 'pair') stage = `<div class="pair">${frame(before, false)}${frame(after, true)}</div>`;
  if (view === 'video') stage = `<video controls playsinline preload="metadata" poster="${media(before)}" src="${media(current.clip)}" aria-label="${text('T₁ to T₂ playback','T₁ 到 T₂ 时序播放')}"></video><p class="fine">${text('Original frames only · 2 s per observation','仅播放两张原始影像 · 每个时相 2 秒')}</p>`;
  byId('viewer').innerHTML = `<div class="view-mode">${modes.map(([key, title]) => `<button type="button" data-view="${key}" aria-pressed="${view === key}">${title}</button>`).join('')}</div>${stage}`;
  byId('case-context').innerHTML = `<span class="micro">LEVIR-CC · ${text('PRESET PAIR','预置影像')}</span><h3>${escape(text(selected.title_en, selected.title_zh))}</h3>`;
}

function select(index) {
  if (busy) return;
  stopReplay();
  pulseTimes.clear();
  selected = catalog.cases[index];
  trace = selected.replay;
  phase = 3;
  mode = 'archive';
  beta = catalog.beta;
  divider = 50;
  failure = null;
  renderCases();
  renderViewer();
  render();
}

function stopReplay() {
  clearInterval(timer);
  timer = undefined;
}

function replay() {
  if (busy) return;
  if (timer) {
    stopReplay();
    render();
    return;
  }
  trace = selected.replay;
  mode = 'archive';
  pulseTimes.clear();
  phase = 0;
  beta = catalog.beta;
  failure = null;
  timer = setInterval(() => {
    phase = (phase === 3 && trace.changed === false) || (phase === 4 && trace.eligible.length <= 1) ? 6 : phase + 1;
    if (phase === 6) stopReplay();
    render(true);
  }, 1650);
  render();
}

function level() {
  return mode === 'archive' ? steps.length - 1 : events.indexOf(liveEvent);
}

function updateClock() {
  const showing = mode === 'live' && Boolean(runTimes);
  byId('run-elapsed').hidden = !showing;
  if (!showing) return;
  const seconds = Math.floor(((runTimes.ended ?? performance.now()) - runTimes.started) / 1000);
  const clock = byId('run-clock');
  clock.dateTime = `PT${seconds}S`;
  clock.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
}

function renderMonitor(completed, early, direct, flowing) {
  const current = mode === 'live' && liveActivity !== 'filter' ? activities[liveActivity]?.[0] : undefined;
  const timing = mode === 'live' ? runTimes?.timings ?? {} : {};
  const duration = (key, title) => Number.isFinite(timing[key]) ? `${title} ${timing[key].toFixed(1)} s` : '';
  const breakdown = stage => [duration(`${stage}_load`, text('Load','加载')), duration(`${stage}_score`, text('Score','评分'))].filter(Boolean).join(' · ');
  const wait = runTimes?.gpuStarted - runTimes?.submitted;
  const details = [
    [Number.isFinite(wait) ? text(`Start wait ${(wait / 1000).toFixed(1)} s`, `启动等待 ${(wait / 1000).toFixed(1)} 秒`) : '', duration('runtime', text('Init','初始化'))].filter(Boolean).join(' · '),
    duration('encode', text('Load + encode','加载与编码')),
    duration('beam', text('Load + decode','加载与解码')),
    breakdown('stage1'), breakdown('stage2'),
    completed >= 6 && mode === 'live' ? `Beam ${rankLabel(trace.final)}` : '',
  ];
  const done = [completed >= 0 || (Number.isFinite(runTimes?.gpuStarted) && current !== 0), completed >= 0, completed >= 1, completed >= 3, completed >= 5 && !early && !direct, completed >= 6];
  byId('live-nodes').innerHTML = monitorNodes.map(([en, zh], index) => {
    const state = mode !== 'live' ? 'pending' : index === 4 && early ? 'skipped' : index === 4 && direct ? 'direct'
      : index === current ? (failure ? 'failed' : 'running') : done[index] ? 'done' : 'pending';
    const stateText = {
      pending: text('Pending','待运行'), running: text('In progress','进行中'), done: text('Done','完成'),
      skipped: text('Skipped — Early Exit','已跳过 — 提前退出'), direct: text('No Stage 2 call','未调用 Stage 2'), failed: text('Interrupted','已中断'),
    }[state];
    const connected = mode === 'live' && index < 5 && done[index] && (index !== 3 || done[4] || current === 4 && !failure);
    return `<li data-state="${state}" ${state === 'running' ? 'aria-current="step"' : ''}><div><span class="node-port" aria-hidden="true">${{done:'✓', failed:'!', skipped:'–', direct:'–'}[state] ?? `0${index + 1}`}</span><strong>${text(en, zh)}</strong></div><small>${stateText}</small>${mode === 'live' && details[index] ? `<span class="node-timing">${details[index]}</span>` : ''}${index < 5 ? `<span class="monitor-edge" aria-hidden="true" data-active="${connected}">${pulse(`monitor-${index}`, connected, flowing)}</span>` : ''}</li>`;
  }).join('');
  const progress = byId('live-progress');
  progress.hidden = !busy || completed < 0 || liveEvent === 'done';
  progress.value = completed + 1;
  progress.setAttribute('aria-valuetext', text(`Trace checkpoint ${completed + 1} of 7`, `决策流程进度 ${completed + 1} / 7`));
  updateClock();
}

function pulse(edge, active, flowing, path) {
  if (!active || !flowing) return '';
  const now = performance.now();
  if (!pulseTimes.has(edge)) pulseTimes.set(edge, now);
  const elapsed = now - pulseTimes.get(edge);
  if (elapsed >= pulseLength) return '';
  const delay = `--pulse-delay:-${elapsed.toFixed(1)}ms`;
  return path ? `<path class="trace-pulse" pathLength="100" d="${path}" style="${delay}"/>` : `<i class="connector-pulse" style="${delay}"></i>`;
}

function render(replayTick = false) {
  const reached = level();
  const completed = timer ? phase : reached;
  const focused = document.activeElement?.dataset.step;
  const early = trace?.changed === false && completed >= 3;
  const direct = trace?.changed === true && completed >= 4 && trace.eligible?.length <= 1;
  const activeStep = mode === 'live' && busy ? activities[liveActivity]?.[1] : undefined;
  const flowing = mode === 'live' ? !failure : Boolean(timer) || replayTick;
  renderMonitor(completed, early, direct, flowing);
  byId('pipeline').innerHTML = routing(completed, activeStep, early, direct, flowing);
  if (focused !== undefined) byId('pipeline').querySelector(`[data-step="${focused}"]`)?.focus({preventScroll: true});
  byId('source').textContent = mode === 'archive' ? text('Case walkthrough','案例演示') : text('ZeroGPU · live run','ZeroGPU · 实时推理');
  byId('source').dataset.source = mode;
  const result = failure ? null : mode === 'live' ? liveEvent === 'done' ? trace : null : !timer ? trace : null;
  byId('run-output').innerHTML = result ? captionSelection(result) : '';
  byId('replay').textContent = label(timer ? 'pause' : 'play');
  byId('replay').disabled = busy;
  byId('live').disabled = busy || !catalog.live;
  const status = failure ? failureMessage(failure) : (mode === 'archive'
    ? (catalog.live ? text('Select a step to see how the model made its decision.', '点击任意步骤,查看模型如何做出决策。') : text('Explore the case below. Live inference is temporarily unavailable.', '可以继续查看案例,实时推理暂不可用。'))
    : (liveActivity ? text(...activities[liveActivity].slice(2)) : ({
      encode: text('Images encoded.','双图编码完成。'),
      beam: text('Beam-15 ready.','Beam-15 已生成。'),
      stage1: text('Stage 1 scored all candidates.','第一阶段已完成全候选评分。'),
      gate: trace?.changed ? text('Changed locked.','已锁定有变化。') : text('Unchanged locked. Stage 2 skipped.','已锁定无变化,跳过第二阶段。'),
      filter: text('Change pool ready.','变化候选池已就绪。'),
      stage2: text('Stage 2 scored the pool.','第二阶段已完成评分。'),
      done: text('Inference complete. Inspect any step.','推理完成,可回看任意步骤。'),
    }[liveEvent] ?? '')));
  if (byId('status').textContent !== status) byId('status').textContent = status;
  byId('inspector').innerHTML = reached < 0 ? `<div class="empty">${failure
    ? text('No live result. Choose Step through to explore this pair without using GPU quota.', '本次没有实时结果。点击「逐步演示」可查看这组影像的推理流程,不消耗 GPU 配额。')
    : text('The trace opens as soon as the first step finishes.','第一步完成后即可查看决策记录。')}</div>` : inspect();
  if (phase === 5 && trace?.stage2?.length > 1) updateRanking();
}

function head(index, description) {
  const time = trace?.timings?.[['encode','beam','stage1',null,null,'stage2'][index]];
  return `<div class="inspect-head"><div><span class="micro">STEP 0${index + 1}</span><h3>${label(steps[index])}</h3></div>${time === undefined ? '' : `<time>${time.toFixed(2)} s</time>`}</div><p class="explain">${description}</p>`;
}

function routeSummary(result) {
  if (!result.changed) return text('Unchanged · Early Exit','无变化 · 提前退出');
  if (!result.eligible.length) return text('Empty pool · Stage 1 anchor kept','候选池为空 · 保留第一阶段锚点');
  if (result.eligible.length === 1) return text('One candidate · Returned directly','仅一条候选 · 直接返回');
  return text('Change branch · Stage 2 invoked','变化分支 · 已执行第二阶段');
}

function highlightEdit(original, final) {
  if (original === final) return escape(final);
  const source = original.split(/(\s+)/u);
  const target = final.split(/(\s+)/u);
  let start = 0, end = 0;
  while (start < target.length && start < source.length && target[start] === source[start]) start++;
  while (end < target.length - start && end < source.length - start && target.at(-end - 1) === source.at(-end - 1)) end++;
  const edited = escape(target.slice(start, target.length - end).join(''));
  return escape(target.slice(0, start).join('')) + (edited ? `<mark>${edited}</mark>` : '') + escape(target.slice(target.length - end).join(''));
}

function captionSelection(result) {
  const original = result.captions[0];
  const final = result.captions[result.final];
  const caseId = escape((result.name ?? selected.name).replace(/\.png$/u, ''));
  return `<section class="caption-selection" aria-labelledby="caption-selection-title"><div class="sectionbar"><h4 id="caption-selection-title">${text('Caption Selection','描述选择')}</h4><span class="micro">${mode === 'live' ? text('LIVE RESULT','实时结果') : text('PREVIEW','样例预览')} · LEVIR-CC · ${caseId}</span></div>
    <div class="caption-grid"><div><small>${text('GENERATOR','生成器')} · BEAM #01</small><p lang="en">${escape(original)}</p><span>${text('Original top-1','原始首选')}</span></div>
    <div class="final-caption"><small>${result.eligible?.length > 1 ? text('RERANKED','重排后') : text('OUTPUT','输出')} · BEAM ${rankLabel(result.final)}</small><p lang="en">${highlightEdit(original, final)}</p><span>${text('Final selection','最终选择')}</span></div></div>
    <dl class="caption-path">${[[text('Generator','生成器'), 0], ['Stage 1', result.anchor], [text('Final','最终'), result.final]].map(([title,index]) => `<div><dt>${title}</dt><dd>${rankLabel(index)}</dd></div>`).join('')}</dl>
    <div class="caption-links"><span>${routeSummary(result)}</span><a href="#candidate-ranking">${text('Explore candidate ranking ↓','探索候选重排 ↓')}</a></div></section>`;
}

function routing(completed, activeStep, early, direct, flowing) {
  const short = ['RSCaMa', 'SCST', 'ELEPHANT-1', text('STATE GATE','状态门控'), text('CHANGED','有变化'), 'STAGE 2 · β', 'CAPTION'];
  const stage2 = !early && !direct && (activeStep === 5 || completed >= 5);
  const step = (index, title = label(steps[index])) => {
    const skipped = early && (index === 4 || index === 5);
    const bypass = direct && index === 5;
    const state = skipped ? 'skipped' : bypass ? 'direct' : index === activeStep ? 'running' : index <= completed ? 'done' : 'pending';
    return `<button type="button" data-step="${index}" data-state="${state}" ${index > completed && !skipped && !bypass ? 'disabled' : ''} ${phase === index && completed >= 0 ? 'aria-current="step"' : ''}><small>0${index + 1} / ${short[index]}</small><strong>${title}</strong></button>`;
  };
  const gate = completed >= 3;
  const output = completed >= 6 || activeStep === 6;
  const changed = gate && trace.changed;
  const edge = (id, path, active, kind = 'pre') => `<g class="trace-edge" data-edge="${id}" data-kind="${kind}" data-active="${active}"><path class="trace-line" d="${path}"/>${pulse(id, active, flowing, path)}</g>`;
  const wires = (branches, className = '') => `<svg class="trace-split ${className}" viewBox="0 0 100 22" preserveAspectRatio="none" aria-hidden="true">${branches}</svg>`;
  const entry = [0,1,2].map(index => index < 2 ? `${step(index)}<span class="trace-entry-edge" data-active="${completed >= index}" aria-hidden="true">${pulse(`entry-${index}`, completed >= index, flowing)}</span>` : step(index)).join('');
  return `<div class="trace-entry">${entry}</div>
    ${wires(edge('feed-gate', 'M83.5 0V11H50V22', completed >= 2), 'trace-feed')}
    <div class="trace-gate">${step(3, gate ? `Beam ${rankLabel(trace.anchor)} · ${stateLabel(trace.changed)}` : undefined)}</div>
    ${wires(edge('route-early', 'M50 0V10H25V22', early, 'early') + edge('route-change', 'M50 0V10H75V22', changed, 'change'))}
    <div class="trace-branches" data-route="${gate ? early ? 'early' : 'change' : 'waiting'}">
      <div class="trace-lane trace-early"><div class="trace-terminal" data-active="${early}"><small>${stateLabel(false)}</small><strong>${text('Early Exit','提前退出')}</strong><span>${text('Return Stage 1 anchor','返回第一阶段锚点')}</span></div></div>
      <div class="trace-lane trace-changed">${step(4)}<div class="trace-pool" aria-label="${text('Routes after filtering','过滤后的分流')}">
        <div class="trace-terminal" data-active="${direct && trace.eligible.length === 0}"><small>0</small><span>${text('Keep anchor','保留锚点')}</span></div>
        <div class="trace-terminal" data-active="${direct && trace.eligible.length === 1}"><small>1</small><span>${text('Return survivor','返回保留候选')}</span></div>
        <div class="trace-terminal" data-active="${stage2}"><small>2+</small><span>${text('Run Stage 2','执行第二阶段')}</span></div>
      </div><div class="trace-stage2" data-bypass="${direct}">${wires(edge('enter-stage2', 'M50 0V22', stage2, 'change'), 'trace-pool-feed')}${step(5, early ? text('Skipped — Early Exit','已跳过 — 提前退出') : direct ? text('No Stage 2 call','未调用第二阶段') : undefined)}${direct ? wires(edge('bypass-stage2', 'M40 0H72Q90 0 90 3V19Q90 22 72 22H40', true, 'change'), 'trace-bypass') : ''}</div></div>
    </div>${wires(edge('return-early', 'M25 0V10H50V22', output && early, 'early') + edge('return-change', 'M75 0V10H50V22', output && changed, 'change'))}<div class="trace-out">${step(6)}</div>`;
}

function inspect() {
  if (phase === 0) return head(0, text('RSCaMa encodes the earlier and later views of the same location into joint visual features for the caption generator.','RSCaMa 将同一地点的前后影像编码为联合视觉特征,交给描述生成器。')) + `
    <div class="encoding"><div class="feature-pair">${selected.media.map((path, index) => `<div>${image(path, index === 1)}<b>T${index + 1}</b></div>`).join('')}</div>
    <span class="flow-arrow" aria-hidden="true">→</span><div class="tensor"><i aria-hidden="true"></i><b>RSCaMa</b><small>${trace?.feature_shape ? trace.feature_shape.join(' × ') : text('Joint visual features','联合视觉特征')}</small></div></div>
    <p class="fine">${text('Feature icon is schematic. Both Elephant-1 stages also receive the original image pair when they run.','特征图标为示意;Elephant-1 两阶段执行时也会读取原始双时相影像。')}</p>`;

  if (phase === 1) return head(1, text('The SCST RSCaMa decoder uses beam search to propose 15 captions. Beam #01 is the generator’s baseline; every beam goes to Stage 1.','SCST RSCaMa 通过束搜索生成 15 条描述。Beam #01 是生成器的基线输出,所有候选都进入第一阶段。')) + (trace?.captions ? `
    <div class="deck"><i aria-hidden="true"></i><i aria-hidden="true"></i><div><small>BEAM ${rankLabel(0)} / TOP-1</small><strong lang="en">${escape(trace.captions[0])}</strong></div></div>
    <details><summary>${text('Inspect all Beam-15 candidates','查看全部 15 条候选')}</summary><ol class="beam-list">${trace.captions.map((caption, index) => `<li><code>${rankLabel(index)}</code><span lang="en">${escape(caption)}</span></li>`).join('')}</ol></details>` : pending());

  if (phase === 2) return head(2, text('Elephant-1 reads both images and scores all 15 caption slots.','Elephant-1 读取双图并为全部 15 个候选槽位打分。')) + (trace?.stage1 ? `
    <div class="pool-head"><span>${text('Stage 1 slots · sorted by probability','第一阶段槽位 · 按概率排序')}</span><span>P(slot)</span></div>
    <ol class="pool">${trace.stage1.slice().sort((first, second) => second[1] - first[1]).map(([index, prob]) => {
      const isAnchor = index === trace.anchor;
      return `<li class="slot ${isAnchor ? 'winner' : ''}"><code>${rankLabel(index)}</code><div><span lang="en">${escape(trace.captions[index])}</span><small>caption_${index + 1} · ${stateLabel(!catalog.templates.includes(trace.captions[index]))}${isAnchor ? ` · ${text('ANCHOR','锚点')}` : ''}</small></div><div class="prob"><b>${(prob * 100).toFixed(2)}%</b><span style="--p:${prob * 100}%"></span></div></li>`;
    }).join('')}</ol>` : pending()) + task(0);

  if (phase === 3) {
    const confidence = trace.stage1.find(([index]) => index === trace.anchor)?.[1];
    const next = trace.changed ? text('Next: remove no-change and duplicate captions.','下一步:去掉无变化与重复描述。') : text('Early Exit: return this caption without running Stage 2.','提前退出:直接返回这句描述,不执行第二阶段。');
    return head(3, text('The highest-scoring caption anchors the decision. Its state determines which branch runs.','得分最高的描述成为锚点,由它的变化状态决定走哪条分支。')) + `<div class="gate-readout" data-changed="${trace.changed}"><div><code>BEAM ${rankLabel(trace.anchor)} · ${stateLabel(trace.changed)}</code>${Number.isFinite(confidence) ? `<code>P(slot) ${(confidence * 100).toFixed(1)}%</code>` : ''}</div><p lang="en">${escape(trace.captions[trace.anchor])}</p></div><p class="fine">${next}</p>`;
  }

  if (phase === 4 || phase === 5) {
    if (trace.changed === false) return head(phase, text('Stage 1 locked Unchanged. The anchor goes straight to the output.','第一阶段已锁定无变化,锚点直接作为最终输出。')) + `<div class="empty bypass-note"><h4>${text('Skipped — Early Exit','已跳过 — 提前退出')}</h4><p>${text('No change candidates were filtered or scored by Stage 2.','这条路径不进行变化候选过滤,也不调用第二阶段。')}</p></div>`;
    if (phase === 4) return head(4, text('Drop no-change captions and duplicates before comparing change details.','先去掉无变化描述和重复描述,再比较变化细节。')) + `<div class="eligible"><span>${trace.eligible?.length ?? 0} / ${trace.captions.length} ${text('kept','条保留')}</span>${trace.captions.map((caption, index) => `<code class="${trace.eligible?.includes(index) ? 'kept' : ''}" title="${escape(caption)}">${rankLabel(index)}</code>`).join('')}</div><ol class="beam-list">${trace.captions.map((caption, index) => `<li><code>${rankLabel(index)}</code><span lang="en">${escape(caption)}</span><small>${trace.eligible?.includes(index) ? text('Kept','保留') : text('Filtered','已过滤')}</small></li>`).join('')}</ol>`;
    return head(5, text('Elephant-1 compares the remaining descriptions. β calibrates the score by caption length.','Elephant-1 比较剩余描述,再按句长用 β 校准得分。')) +
      (trace.stage2?.length > 1 ? `<div class="formula"><code>log(max(P(slot), 10⁻³⁰)) − β × words</code><label class="range-label" for="beta">${text('Length penalty β','长度惩罚 β')}<output id="beta-value">${beta.toFixed(2)}</output></label><input class="beta-range" id="beta" type="range" min="0" max="0.20" step="0.02" value="${beta}"><p class="fine">${text('The slider explores this fixed pool. The model output uses the validation-selected β.', '滑块只探索当前候选池;正式输出使用验证集选定的 β。')}</p></div><div id="ranks"></div>` : `<div class="empty">${trace.eligible?.length ? text('One eligible caption: selected directly.','仅一条合格候选,直接选择。') : text('No eligible captions: keep the Stage 1 anchor.','无合格候选,保留第一阶段锚点。')}</div>`) + task(1);
  }

  const slot = trace.stage2?.findIndex(([index]) => index === trace.final);
  const mapping = slot >= 0 && trace.stage2.length > 1 ? `item_${slot + 1} → Beam ${rankLabel(trace.final)}` : `Beam ${rankLabel(trace.final)}`;
  return head(6, `${routeSummary(trace)}.${trace.stage2?.length > 1 ? ` β = ${catalog.beta.toFixed(2)}.` : ''}`) + `<p class="mapping"><code>${mapping}</code></p><div class="comparison">${[
    [text('Generator baseline','生成器基线'),0], [text('Stage 1 anchor','第一阶段锚点'),trace.anchor], [text('Final caption','最终描述'),trace.final],
  ].map(([title, index]) => `<div><small>${title} · BEAM ${rankLabel(index)}</small><p lang="en">${escape(trace.captions[index])}</p></div>`).join('')}</div>`;
}

const pending = () => '';
const task = index => `<details class="task"><summary>${text('Inspect the actual task instruction','查看实际任务指令(英文)')}</summary><p lang="en">${escape(catalog.tasks[index])}</p></details>`;

function calibrated(scores, captions, penalty) {
  return scores.map(([index, probability], slot) => {
    const caption = captions[index];
    const words = caption.trim() ? caption.trim().split(/\s+/u).length : 0;
    const log = Math.log(Math.max(probability, 1e-30));
    return {index, probability, slot, words, log, score: log - penalty * words, caption};
  }).sort((first, second) => second.score - first.score);
}

function updateRanking() {
  byId('beta-value').textContent = beta.toFixed(2);
  byId('beta').setAttribute('aria-valuetext', beta.toFixed(2));
  byId('beta').style.setProperty('--fill', `${beta * 500}%`);
  const ranked = calibrated(trace.stage2, trace.captions, beta);
  byId('ranks').innerHTML = `<div class="pool-head"><span>${text('Eligible pool · sorted by calibrated score','同状态候选 · 按校准分排序')}</span><span>${text('Score','得分')}</span></div><ol class="pool">${ranked.map(({index, probability, slot, words, log, score, caption}, position) => `<li class="slot ${position === 0 ? 'winner warm' : ''}">
    <code>${rankLabel(index)}</code><div><span lang="en">${escape(caption)}</span><small>item_${slot + 1} · P ${(probability * 100).toFixed(2)}% · ln P ${log.toFixed(3)} · ${words} ${text('words','词')} · −${(beta * words).toFixed(3)}</small></div><div class="prob"><b>${score.toFixed(4)}</b>${position === 0 ? `<small>${text('SELECTED','选中')}</small>` : ''}</div></li>`).join('')}</ol>`;
}

async function zeroGpuHeaders() {
  const headers = new Headers({'Content-Type': 'application/json'});
  if (window.parent === window) return headers;

  const support = new AbortController();
  const supported = await new Promise(resolve => {
    const timer = setTimeout(() => resolve(false), 2000);
    window.addEventListener('message', event => {
      if (event.source !== window.parent || event.origin !== hubOrigin || event.data !== zeroGpuHandshake) return;
      clearTimeout(timer);
      resolve(true);
    }, {signal: support.signal});
    window.parent.postMessage(zeroGpuHandshake, hubOrigin);
  }).finally(() => support.abort());
  if (!supported) return headers;

  const channel = new MessageChannel();
  const identity = await new Promise(resolve => {
    const timer = setTimeout(() => resolve(null), 2000);
    channel.port1.onmessage = event => {
      clearTimeout(timer);
      resolve(event.data);
    };
    window.parent.postMessage('zerogpu-headers', hubOrigin, [channel.port2]);
  }).finally(() => channel.port1.close());

  for (const name of ['X-ZeroGPU-Token', 'X-ZeroGPU-UUID']) {
    const value = identity?.[name];
    if (typeof value === 'string' && value && !/[\r\n\0]/.test(value)) headers.set(name, value);
  }
  return headers;
}

function streamFailure(event) {
  try {
    const payload = JSON.parse(event.data);
    const message = typeof payload === 'string' ? payload : payload?.error;
    if (payload?.title === 'ZeroGPU quota exceeded' || /exceeded your (?:free |pro )?zerogpu quota/i.test(message)) {
      const quota = /([\d.]+)\s*s requested\s+vs\.\s+([\d.]+)\s*s left/i.exec(message);
      const needsLogin = /authenticate with a hugging face token/i.test(message);
      return {kind: 'quota', quota: quota?.slice(1), needsLogin};
    }
  } catch {
    return {kind: 'interrupted'};
  }
  return {kind: 'interrupted'};
}

function failureMessage({kind, quota, needsLogin}) {
  if (kind === 'quota') {
    const details = quota ? text(` This run requests ${quota[0]} s; ${quota[1]} s remain.`, `本次需要 ${quota[0]} 秒,剩余 ${quota[1]} 秒。`) : '';
    return text('Not enough ZeroGPU quota to start.', 'ZeroGPU 配额不足,未开始推理。') + details
      + (needsLogin
        ? text(' This request used guest quota. Sign in on huggingface.co and run from the Space’s App tab with that tab active.', '本次请求使用了访客额度。请在 huggingface.co 登录,在 Space 的 App 标签页保持前台并重试。')
        : text(' Retry after your ZeroGPU quota resets.', '请在 ZeroGPU 配额重置后重试。'));
  }
  return text('Live inference was interrupted. Try again or choose Step through.', '实时推理中断,可重试或点击「逐步演示」。');
}

async function run() {
  if (busy || !catalog.live) return;
  stopReplay();
  pulseTimes.clear();
  busy = true;
  mode = 'live';
  failure = null;
  follow = true;
  trace = null;
  liveEvent = undefined;
  liveActivity = 'submit';
  runTimes = {started: performance.now()};
  clockTimer = setInterval(updateClock, 1000);
  phase = 0;
  beta = catalog.beta;
  renderCases();
  render();
  let source;
  try {
    const endpoint = './gradio_api/call/run_case';
    const headers = await zeroGpuHeaders();
    liveActivity = 'wait';
    runTimes.submitted = performance.now();
    render();
    const response = await fetch(endpoint, {method:'POST', headers, redirect:'error', body:JSON.stringify({data:[selected.name]})});
    if (!response.ok) throw new Error('Queue rejected the run');
    const {event_id: eventId} = await response.json();
    if (!eventId) throw new Error('Missing event id');
    source = new EventSource(`${endpoint}/${encodeURIComponent(eventId)}`);
    await new Promise((resolve, reject) => {
      const onTrace = event => {
        try {
          const [payload] = JSON.parse(event.data);
          if (payload?.name !== selected.name) throw new Error('Invalid trace');
          const activity = payload.activity;
          if (activity === undefined ? !events.includes(payload.step)
            : payload.step !== undefined || !Object.hasOwn(activities, activity) || activity === 'submit' || activity === 'wait') throw new Error('Invalid trace');
          if (event.type === 'complete' && payload.step !== 'done') throw new Error('Incomplete trace');
          if (activity === 'runtime') runTimes.gpuStarted ??= performance.now();
          runTimes.timings = payload.timings;
          if (activity) {
            liveActivity = activity;
            render();
            return;
          }
          liveActivity = undefined;
          trace = payload;
          liveEvent = payload.step;
          if (follow) phase = level();
          if (event.type === 'complete') resolve();
          render();
        } catch (error) { reject(error); }
      };
      source.addEventListener('generating', onTrace);
      source.addEventListener('complete', onTrace);
      source.addEventListener('error', event => reject(streamFailure(event)));
    });
  } catch (error) {
    failure = error?.kind === 'quota' ? error : {kind: 'interrupted'};
  } finally {
    source?.close();
    runTimes.ended = performance.now();
    clearInterval(clockTimer);
    busy = false;
    renderCases();
    render();
  }
}

byId('language').addEventListener('click', () => {
  lang = lang === 'en' ? 'zh' : 'en';
  const url = new URL(location.href);
  if (lang === 'zh') url.searchParams.set('lang', 'zh');
  else url.searchParams.delete('lang');
  history.replaceState(null, '', url);
  translate();
  if (catalog) { renderCases(); renderViewer(); renderTasks(); render(); }
});

byId('task-grid').addEventListener('click', event => {
  const button = event.target.closest('[data-task]');
  if (!button || !catalog || Number(button.dataset.task) === activeTask) return;
  selectTask(Number(button.dataset.task));
});
byId('task-grid').addEventListener('keydown', event => {
  if (!catalog || !event.target.closest('[data-task]')) return;
  const count = taskTabs.length;
  const next = {ArrowLeft:(activeTask + count - 1) % count, ArrowRight:(activeTask + 1) % count, Home:0, End:count - 1}[event.key];
  if (next === undefined) return;
  event.preventDefault();
  selectTask(next);
});
byId('rank-explorer').addEventListener('click', event => {
  const button = event.target.closest('[data-rank]');
  if (!button || (button.dataset.rank === '1') === rankedView) return;
  rankedView = button.dataset.rank === '1';
  updateExplorer(catalog.cases.find(item => item.name === 'test_000125.png'));
});
byId('rank-explorer').addEventListener('input', event => {
  if (event.target.id !== 'explorer-beta') return;
  explorerBeta = Number(event.target.value);
  rankedView = true;
  updateExplorer(catalog.cases.find(item => item.name === 'test_000125.png'));
});
byId('case-grid').addEventListener('click', event => {
  const button = event.target.closest('[data-case]');
  if (button) {
    select(Number(button.dataset.case));
    byId('case-grid').querySelector(`[data-case="${button.dataset.case}"]`)?.focus({preventScroll:true});
  }
});
byId('viewer').addEventListener('click', event => {
  const button = event.target.closest('[data-view]');
  if (button && button.dataset.view !== view) {
    view = button.dataset.view;
    renderViewer();
    byId('viewer').querySelector(`[data-view="${view}"]`)?.focus({preventScroll:true});
  }
});
byId('viewer').addEventListener('input', event => {
  if (event.target.id !== 'divider') return;
  divider = Number(event.target.value);
  byId('viewer').querySelector('.swipe').style.setProperty('--split', `${divider}%`);
  event.target.setAttribute('aria-valuetext', compareValue(divider));
  byId('divider-value').textContent = `${divider}%`;
});
byId('pipeline').addEventListener('click', event => {
  const button = event.target.closest('[data-step]');
  if (!button) return;
  stopReplay();
  follow = false;
  phase = Number(button.dataset.step);
  render();
});
byId('inspector').addEventListener('input', event => {
  if (event.target.id !== 'beta') return;
  beta = Number(event.target.value);
  updateRanking();
});
byId('replay').addEventListener('click', () => { if (catalog) replay(); });
byId('live').addEventListener('click', () => { if (catalog) run(); });

translate();
byId('live').disabled = byId('replay').disabled = true;
try {
  const response = await fetch('./catalog');
  if (!response.ok) throw new Error('Catalog unavailable');
  catalog = await response.json();
  explorerBeta = catalog.beta;
  select(0);
  renderTasks();
  if (location.hash === inferenceHash) byId('trace-title').scrollIntoView();
} catch {
  byId('load-error').textContent = text('Examples could not load. Refresh to retry.', '未能加载示例,请刷新重试。');
}