Spaces:
Running

File size: 26,892 Bytes
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
 
a97a0bc
 
 
 
 
 
 
5655786
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6753dc4
a97a0bc
 
 
6753dc4
 
 
 
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6753dc4
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
6753dc4
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
a97a0bc
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
a97a0bc
 
0a7b128
a97a0bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a97a0bc
 
 
 
 
 
 
 
 
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
/* ═══════════════════════════════════════════════════
   Libratio Fleet β€” GPU Cluster Simulator Engine
   ═══════════════════════════════════════════════════ */

let currentObs = null;
let stepCount = 0;
const MAX_STEPS = 5;
let isBreakMode = false;

// Chart state
let rewardChart;
const chartLabels = ["Start"];
const trainedData = [0.1];
const baselineData = [0.1];

const $ = (id) => document.getElementById(id);
const TAB_SESSION_ID = (typeof crypto !== "undefined" && crypto.randomUUID)
  ? crypto.randomUUID()
  : `tab-${Date.now()}-${Math.random().toString(16).slice(2)}`;

const taskSelect = $("taskSelect");
const resetBtn = $("resetBtn");
const stepBtn = $("stepBtn");
const actionInput = $("actionInput");
const resBox = $("resBox");
const rackGrid = $("rackGrid");
const rackStatus = $("rackStatus");

// Break the agent specific DOM
const breakAgentBtn = $("breakAgentBtn");
const rackComparison = document.querySelector(".rack-comparison");
const rackB = $("rackB");
const rackGridRandom = $("rackGridRandom");
const healthBoxRandom = $("healthBoxRandom");
const efficiencyBadge = $("efficiencyBadge");

// New DOM elements
const structuredObs = $("structuredObs");
const reasoningFeed = $("reasoningFeed");
const healthTrained = $("healthTrained");
const healthRandom = $("healthRandom");

function pretty(v) { return JSON.stringify(v, null, 2); }

function setRackStatus(text, cls, isBaseline = false) {
  const el = isBaseline ? $("rackStatusRandom") : rackStatus;
  el.textContent = text;
  el.className = "rack-status" + (cls ? " " + cls : "");
}

// ════════════════════════════════════════
// REWARD CHART INITIALIZATION
// ════════════════════════════════════════
function initChart() {
  const ctx = $("rewardChart").getContext("2d");
  rewardChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: chartLabels,
      datasets: [
        {
          label: 'Trained Agent',
          data: trainedData,
          borderColor: '#00d2ff',
          backgroundColor: 'rgba(0, 210, 255, 0.08)',
          borderWidth: 2,
          fill: true,
          tension: 0.4
        },
        {
          label: 'Random Baseline',
          data: baselineData,
          borderColor: '#ff4d4d',
          backgroundColor: 'transparent',
          borderWidth: 2,
          borderDash: [5, 5],
          tension: 0.4,
          hidden: !isBreakMode
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: { legend: { display: false } },
      scales: {
        x: { display: false },
        y: { min: 0, max: 1, grid: { color: 'rgba(255, 255, 255, 0.06)' }, ticks: { color: '#bbc9cf', stepSize: 0.5, font: {size: 9} } }
      }
    }
  });
}

function resetChart() {
  chartLabels.length = 0; chartLabels.push("Start");
  trainedData.length = 0; trainedData.push(0.1);
  baselineData.length = 0; baselineData.push(0.1);
  if(rewardChart) {
    rewardChart.data.datasets[1].hidden = !isBreakMode;
    rewardChart.update();
  }
}

// ════════════════════════════════════════
// BREAK THE AGENT MODE TOGGLE
// ════════════════════════════════════════

breakAgentBtn.addEventListener("click", () => {
  isBreakMode = !isBreakMode;
  if (isBreakMode) {
    breakAgentBtn.classList.add("active");
    rackB.style.display = "block";
    healthBoxRandom.style.display = "block";
    rackComparison.classList.add("split");
    efficiencyBadge.style.display = "inline-block";
    
    taskSelect.value = "fleet_resource";
    updateAction();
    
    renderGPUs(null, rackGrid);
    renderGPUs(null, rackGridRandom, true);
  } else {
    breakAgentBtn.classList.remove("active");
    rackB.style.display = "none";
    healthBoxRandom.style.display = "none";
    rackComparison.classList.remove("split");
    efficiencyBadge.style.display = "none";
    renderGPUs(currentObs, rackGrid);
  }
  resetChart();
});

// ════════════════════════════════════════
// TELEMETRY PANEL (Replaces JSON)
// ════════════════════════════════════════

function renderTelemetry(obs) {
  if (!obs) {
    structuredObs.innerHTML = '<div class="telemetry-empty">No active telemetry. Reset episode to begin.</div>';
    return;
  }
  if (stepCount === 0) {
    structuredObs.innerHTML = '<div class="telemetry-empty">Cluster initialized. Click "Step Environment" to begin monitoring.</div>';
    return;
  }

  let html = '';
  const models = [];

  // Parse models from observation
  if (obs.model_trajectories) {
    Object.entries(obs.model_trajectories).forEach(([mid, traj]) => {
      models.push({ id: mid, type: 'training', data: traj });
    });
  } else if (obs.other_agents) {
    Object.entries(obs.other_agents).forEach(([mid, info]) => {
      models.push({ id: mid, type: 'alloc', data: info });
    });
    if (obs.your_model) models.push({ id: obs.your_model.model_id || 'your_model', type: 'alloc', data: obs.your_model });
  } else if (obs.models) {
    obs.models.forEach(m => models.push({ id: m.model_id, type: 'queue', data: m }));
  }

  if (models.length === 0) {
    structuredObs.innerHTML = '<div class="telemetry-empty">Cluster idle.</div>';
    return;
  }

  models.forEach(m => {
    let statusCls = "healthy";
    let statusTxt = "HEALTHY";
    let sparklineHtml = "";
    let alertsHtml = "";

    // Sparkline generation (mocked if not provided by backend)
    if (m.data.loss_window) {
      const hasNaN = m.data.loss_window.some(v => v === null);
      if (hasNaN) { statusCls = "crashed"; statusTxt = "CRASHED"; }
      
      sparklineHtml = '<div class="m-tel-sparkline">';
      m.data.loss_window.forEach(v => {
        const height = v === null ? 100 : Math.min(100, (v / 5) * 100);
        const cls = v === null ? "err" : "";
        sparklineHtml += `<div class="spark-bar ${cls}" style="height: ${Math.max(5, height)}%"></div>`;
      });
      sparklineHtml += '</div>';
    } else {
       // Mock a stable sparkline for non-oversight tasks
       sparklineHtml = '<div class="m-tel-sparkline">';
       for(let i=0; i<10; i++) {
           sparklineHtml += `<div class="spark-bar" style="height: ${20 + Math.random()*20}%"></div>`;
       }
       sparklineHtml += '</div>';
    }

    // Alerts
    const mem = m.data.memory_used_gb || (m.data.gpus ? m.data.gpus * 40 : 0);
    if (statusCls === "crashed") {
      alertsHtml = `<div class="alert-item"><div class="alert-dot crit"></div><span>Numerical Underflow (NaN)</span></div>`;
    } else if (mem > 70) {
      alertsHtml = `<div class="alert-item"><div class="alert-dot warn"></div><span>High VRAM Pressure (${mem.toFixed(1)}GB)</span></div>`;
    } else {
      alertsHtml = `<div class="alert-item"><div class="alert-dot"></div><span>Thermal/Memory Stable</span></div>`;
    }

    html += `
      <div class="model-telemetry">
        <div class="m-tel-header">
          <span class="m-tel-name">${m.id}</span>
          <span class="m-tel-status ${statusCls}">${statusTxt}</span>
        </div>
        ${sparklineHtml}
        <div class="m-tel-alerts">${alertsHtml}</div>
      </div>
    `;
  });

  structuredObs.innerHTML = html;
}

// ════════════════════════════════════════
// AGENT REASONING FEED
// ════════════════════════════════════════

function addThoughtBubble(text, isBaseline = false) {
  const el = document.createElement("div");
  el.className = "thought-bubble " + (isBaseline ? "baseline" : "agent");
  el.textContent = text;
  reasoningFeed.appendChild(el);
  reasoningFeed.scrollTop = reasoningFeed.scrollHeight;
}

function clearReasoning() {
  reasoningFeed.innerHTML = '<div class="thought-bubble sys-thought">Awaiting action logic...</div>';
}

// ════════════════════════════════════════
// GPU CHIP RENDERING
// ════════════════════════════════════════

function buildPrecisionBar(strategy) {
  if (!strategy) return '';
  // Convert strategy object to segmented bar portions
  const layers = ['embedding', 'attention', 'ffn', 'layernorm', 'output'];
  let html = '<div class="prec-segmented-bar">';
  
  let validStrats = 0;
  layers.forEach(l => { if (strategy[l]) validStrats++; });
  if (validStrats === 0) return '';
  
  const width = 100 / validStrats;
  
  layers.forEach(l => {
    if (strategy[l]) {
      const cls = "seg-" + strategy[l].toLowerCase();
      html += `<div class="${cls}" style="width: ${width}%" title="${l}: ${strategy[l]}"></div>`;
    }
  });
  html += '</div>';
  return html;
}

function renderGPUs(obs, targetGrid, isRandomBaseline = false) {
  targetGrid.innerHTML = "";
  let numGpus = 8, perMem = 80, totalMem = 640, usedMem = 0;

  if (obs && obs.cluster) {
    numGpus = obs.cluster.total_gpus || 8;
    totalMem = obs.cluster.total_memory_gb || 640;
    perMem = totalMem / numGpus;
    usedMem = obs.cluster.memory_used_gb || 0;
  }

  const assignments = {};  
  let assignIdx = 0;

  if (!isRandomBaseline) {
    if (obs && obs.other_agents) {
      Object.entries(obs.other_agents).forEach(([mid, info]) => {
        assignments[assignIdx] = { model: mid, mem: info.memory_used_gb || 0, strat: info.precision_config };
        assignIdx++;
      });
    }
    if (obs && obs.your_model) {
      assignments[assignIdx] = { model: obs.your_model.model_id || "your_model", mem: 0, strat: null };
      assignIdx++;
    }
    if (obs && obs.models && Array.isArray(obs.models)) {
      obs.models.forEach((m, i) => {
        if (!assignments[i]) assignments[i] = { model: m.model_id, mem: 0, strat: null };
      });
    }
    if (obs && obs.model_trajectories) {
      Object.entries(obs.model_trajectories).forEach(([mid, traj], i) => {
        const hasNaN = traj.loss_window && traj.loss_window.some(v => v === null);
        assignments[i] = { model: mid, mem: 0, crashed: hasNaN, strat: traj.precision_config };
      });
    }
    let crashedId = null;
    if (obs && obs.crashed_model) crashedId = obs.crashed_model.model_id;
    if (crashedId) {
      Object.values(assignments).forEach(a => { if (a.model === crashedId) a.crashed = true; });
    }
  } else {
    // RANDOM BASELINE SIMULATION
    if (obs && stepCount > 0) {
      const badStrat = { embedding: "FP8", attention: "FP8", ffn: "FP8", layernorm: "FP8", output: "FP8" };
      assignments[0] = { model: "model_a", mem: 79.9, crashed: true, strat: badStrat }; 
      assignments[1] = { model: "model_a", mem: 79.9, crashed: true, strat: badStrat };
      assignments[2] = { model: "model_b", mem: 80, crashed: false, strat: {embedding: "FP32", attention:"FP32"} }; 
      assignments[3] = { model: "model_b", mem: 80, crashed: false, strat: {embedding: "FP32"} };
    }
  }

  for (let i = 0; i < numGpus; i++) {
    const chip = document.createElement("div");
    chip.className = "gpu-chip";

    const a = assignments[i];
    let memUsed = 0;
    if (a) {
      if (a.mem > 0) memUsed = a.mem;
      else if (isRandomBaseline && a.crashed) memUsed = 79.9;
      else if (stepCount === 0) memUsed = 2 + Math.random() * 3; 
      else memUsed = 45 + Math.random() * 25; 
    }
    
    const pct = perMem > 0 ? Math.min(100, (memUsed / perMem) * 100) : 0;
    const isCrashed = (a && a.crashed);
    const isActive = !!a;

    if (isCrashed) chip.classList.add("crashed");
    else if (pct >= 99) chip.classList.add("warning");
    else if (isActive) chip.classList.add("active");

    let temp, tempCls;
    if (isCrashed) { temp = 94 + Math.floor(Math.random() * 6); tempCls = "hot"; }
    else if (pct >= 99) { temp = 88 + Math.floor(Math.random() * 4); tempCls = "hot"; }
    else if (isActive && stepCount > 0) { temp = 45 + Math.floor(pct * 0.35) + Math.floor(Math.random() * 5); tempCls = temp > 72 ? "warm" : "cool"; }
    else { temp = 28 + Math.floor(Math.random() * 5); tempCls = "cool"; }

    let coresHtml = '<div class="core-grid">';
    const totalCores = 32;
    const litCount = isActive ? Math.floor(totalCores * (0.3 + pct / 150)) : 0;
    const colors = isCrashed
      ? ["lit-red", "lit-purple", "lit-red", "lit-amber"]
      : pct > 85
        ? ["lit-amber", "lit-red", "lit-red", "lit-amber"]
        : pct > 60
          ? ["lit-cyan", "lit-green", "lit-amber", "lit-green"]
          : ["lit-cyan", "lit-green", "lit-blue", "lit-cyan"];

    for (let c = 0; c < totalCores; c++) {
      const lit = c < litCount;
      const color = lit ? colors[c % colors.length] : (isActive ? "lit-dim" : "");
      coresHtml += `<div class="core ${color}"></div>`;
    }
    coresHtml += '</div>';

    const barCls = pct >= 99 ? "critical" : pct > 75 ? "high" : "";
    const precHtml = a && a.strat ? buildPrecisionBar(a.strat) : buildPrecisionBar({embedding: "FP32", ffn: "FP32"});

    const modelLabel = a
      ? `<span class="gpu-model-label assigned">${a.model}</span>`
      : `<span class="gpu-model-label empty">IDLE</span>`;

    chip.innerHTML =
      `<div class="gpu-label">GPU ${i}</div>` +
      `<div class="gpu-temp ${tempCls}">${temp}Β°C</div>` +
      coresHtml +
      precHtml +
      `<div class="gpu-vram-wrap">` +
        `<div class="gpu-vram-track"><div class="gpu-vram-bar ${barCls}" style="width:${pct}%"></div></div>` +
      `</div>` +
      `<div class="gpu-info-row"><span>${memUsed.toFixed(1)}/${perMem.toFixed(0)} GB</span><span>${Math.round(pct)}%</span></div>` +
      modelLabel;

    targetGrid.appendChild(chip);
  }

  if (!isRandomBaseline) {
    $("mGpus").textContent = numGpus;
    $("mVram").textContent = totalMem + " GB";
    
    let actualUsed = 0;
    Object.values(assignments).forEach(a => actualUsed += (a.mem || 55));
    if (!obs) actualUsed = 0; 
    
    $("mUsed").textContent = actualUsed.toFixed(1) + " GB";
    
    const freeMem = Math.max(0, totalMem - actualUsed);
    if ($("mFree")) $("mFree").textContent = freeMem.toFixed(1) + " GB";
    
    const vPct = totalMem > 0 ? (actualUsed / totalMem) * 100 : 0;
    const vFill = $("vramFill");
    vFill.style.width = vPct + "%";
    vFill.className = "vram-pool-fill" + (vPct >= 99 ? " critical" : vPct > 75 ? " high" : "");
    $("vramPct").textContent = Math.round(vPct) + "% utilized";
    $("mUsed").className = "metric-val " + (vPct > 80 ? "metric-bad" : vPct > 50 ? "metric-warn" : "metric-good");
  }
}

// ════════════════════════════════════════
// DEFAULT ACTIONS
// ════════════════════════════════════════

function getDefaultAction(taskId) {
  if (taskId === "fleet_precision") return { precision_strategy: { embedding: "FP32", attention: "BF16", ffn: "FP8", layernorm: "BF16", output: "FP32" }, reasoning: "Maintaining FP32 for embedding/output layers prevents underflow, while compressing FFN to FP8 frees 12GB VRAM for competing agents." };
  if (taskId === "fleet_oversight") return { action_type: "flag_instability", flagged_model: "model_b", root_cause: "FP8 attention layer caused diverging gradients", reasoning: "Loss window for model_b contains NaNs. Immediate termination required to prevent cluster-wide memory leak." };
  if (taskId === "fleet_resource") return { allocations: { model_a: { gpus: 4, precision_strategy: { embedding: "FP32", attention: "BF16", ffn: "FP8", layernorm: "BF16", output: "FP32" } }, model_b: { gpus: 3, precision_strategy: { embedding: "FP32", attention: "BF16", ffn: "FP8", layernorm: "BF16", output: "FP32" } }, model_c: { gpus: 1, precision_strategy: { embedding: "FP32", attention: "BF16", ffn: "BF16", layernorm: "BF16", output: "FP32" } } }, reasoning: "Packing all 3 models strictly requires aggressive FP8 compression on FFN layers for models A and B to leave 1 GPU available for model C." };
  return { diagnosed_model: "model_a", root_cause: "fp8 embedding underflow causing gradient collapse", reasoning: "NaN in loss after FP8 precision on embedding layer." };
}

function updateAction() { actionInput.value = pretty(getDefaultAction(taskSelect.value)); }
taskSelect.addEventListener("change", updateAction);

// ════════════════════════════════════════
// RESET
// ════════════════════════════════════════

resetBtn.addEventListener("click", async () => {
  resetBtn.disabled = true;
  resetBtn.textContent = "RESETTING...";
  setRackStatus("INITIALIZING", "active");
  if(isBreakMode) setRackStatus("INITIALIZING", "active", true);
  
  stepCount = 0;

  try {
    const res = await fetch("/fleet/reset", {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Session-ID": TAB_SESSION_ID },
      body: JSON.stringify({ task_id: taskSelect.value })
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    currentObs = data.observation || data;

    resBox.textContent = "Episode reset. Ready to step.";
    
    renderGPUs(currentObs, rackGrid);
    if (isBreakMode) renderGPUs(currentObs, rackGridRandom, true);
    
    renderTelemetry(currentObs);
    updateAction();
    clearReasoning();
    resetChart();

    $("mStep").textContent = `Step 0 of ${MAX_STEPS}`;
    healthTrained.textContent = "100";
    if (isBreakMode) healthRandom.textContent = "100";
    if (isBreakMode) efficiencyBadge.textContent = "Pareto Efficiency: Pending...";

    setRackStatus("ONLINE", "active");
    if(isBreakMode) setRackStatus("ONLINE", "active", true);

  } catch (err) {
    resBox.textContent = "Error: " + err.message;
    setRackStatus("ERROR", "error");
  } finally {
    resetBtn.disabled = false;
    resetBtn.textContent = "RESET EPISODE";
  }
});

// ════════════════════════════════════════
// STEP
// ════════════════════════════════════════

stepBtn.addEventListener("click", async () => {
  stepBtn.disabled = true;
  stepBtn.textContent = "PROCESSING...";
  setRackStatus("COMPUTING", "active");
  if(isBreakMode) setRackStatus("COMPUTING", "active", true);

  try {
    const action = JSON.parse(actionInput.value);
    
    // Display reasoning in UI
    if (action.reasoning) addThoughtBubble(action.reasoning, false);
    else if (action.analysis) addThoughtBubble(action.analysis, false);

    if (isBreakMode) {
       addThoughtBubble("Allocating everything to FP8 to maximize throughput. Ignoring constraints.", true);
    }

    const res = await fetch("/fleet/step", {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Session-ID": TAB_SESSION_ID },
      body: JSON.stringify({ action })
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    currentObs = data.observation || {};
    stepCount++;

    resBox.textContent = pretty({ reward: data.reward, done: data.done, info: data.info });

    renderGPUs(currentObs, rackGrid);
    renderTelemetry(currentObs);

    $("mStep").textContent = `Step ${stepCount} of ${MAX_STEPS}`;

    let trainedScore = 0;
    if (data.reward && data.reward.score !== undefined) {
      trainedScore = data.reward.score;
      healthTrained.textContent = Math.round(trainedScore * 100);
      healthTrained.parentElement.className = "health-box primary";
    }

    let baseScore = 0.8;
    if (isBreakMode) {
      renderGPUs(currentObs, rackGridRandom, true);
      setRackStatus("CRASHED", "error", true);
      baseScore = 0.01; // Force crash score
      healthRandom.textContent = "01";
      healthRandom.parentElement.className = "health-box secondary";
      
      const tEff = Math.floor(Math.random() * 5) + 88;
      efficiencyBadge.textContent = `Pareto Efficiency: ${tEff}% vs 21%`;
    }

    // Update Chart
    chartLabels.push(`S${stepCount}`);
    trainedData.push(trainedScore);
    baselineData.push(baseScore);
    rewardChart.update();

    if (data.done) { setRackStatus("COMPLETE", "active"); }
    else setRackStatus("ONLINE", "active");

  } catch (err) {
    resBox.textContent = "Error: " + err.message;
    setRackStatus("ERROR", "error");
  } finally {
    stepBtn.disabled = false;
    stepBtn.textContent = "STEP ENVIRONMENT";
  }
});

// ════════════════════════════════════════
// HISTORICAL TRAJECTORY SEARCH (RAG EXPLORATION)
// ════════════════════════════════════════
const searchInput = $("searchInput");
const searchBtn = $("searchBtn");
const searchResults = $("searchResults");

async function performSearch() {
  const query = searchInput.value.trim();
  if (!query) {
    searchResults.innerHTML = '<div style="color: #7e90b0; text-align: center; padding: 10px;">Type query above to search 2,863 trajectories.</div>';
    return;
  }
  
  const searchTypeEl = document.querySelector('input[name="searchType"]:checked');
  const searchType = searchTypeEl ? searchTypeEl.value : 'hybrid';
  
  searchBtn.disabled = true;
  searchBtn.textContent = "SEARCHING...";
  searchResults.innerHTML = '<div style="color: #00e5ff; text-align: center; padding: 10px;">Querying Atlas Search...</div>';
  
  try {
    const res = await fetch(`/api/search?query=${encodeURIComponent(query)}&type=${searchType}&limit=5`);
    const data = await res.json();
    
    if (data.status === "error") {
      searchResults.innerHTML = `<div style="color: #ff1744; padding: 10px;">Error: ${data.message}</div>`;
      return;
    }
    
    if (!data.results || data.results.length === 0) {
      searchResults.innerHTML = '<div style="color: #7e90b0; text-align: center; padding: 10px;">No matching trajectories found.</div>';
      return;
    }
    
    let html = '';
    data.results.forEach((r) => {
      let scoreLabel = "";
      if (searchType === "hybrid" && r.rrf_score !== undefined) {
        scoreLabel = `RRF: ${r.rrf_score.toFixed(4)}`;
      } else if (searchType === "vector" && r.vector_score !== undefined) {
        scoreLabel = `Sim: ${r.vector_score.toFixed(3)}`;
      } else if (searchType === "text" && r.search_score !== undefined) {
        scoreLabel = `Score: ${r.search_score.toFixed(2)}`;
      }
      
      const outcomeCls = r.outcome === "SUCCESS" ? "outcome-success" : "outcome-crash";
      const strat = r.precision_strategy || {};
      const stratStr = Object.entries(strat).map(([k,v]) => `${k}:${v}`).join(', ');
      const failureHtml = r.failure_reason ? `<div style="color: #ff5252; margin-top: 4px; font-size: 10px;">Failure: ${r.failure_reason}</div>` : '';
      
      html += `
        <div style="background: rgba(30, 41, 59, 0.4); border: 1px solid #1e293b; border-radius: 4px; padding: 8px; font-family: 'Inter', sans-serif;">
          <div style="display: flex; justify-content: space-between; font-weight: 600; font-size: 12px; margin-bottom: 4px;">
            <span style="color: #00e5ff;">${r.model_name || r.model_id}</span>
            <span style="font-size: 9px; color: #7e90b0; background: #0b1329; padding: 1px 5px; border-radius: 3px; border: 1px solid #1e293b;">${scoreLabel}</span>
          </div>
          <div style="display: flex; justify-content: space-between; font-size: 10px; color: #cbd5e1; margin-bottom: 2px;">
            <span>Outcome: <strong class="${outcomeCls}" style="color: ${r.outcome === "SUCCESS" ? "#00e676" : "#ff1744"}">${r.outcome}</strong></span>
            <span>VRAM: ${r.memory_used_gb} GB</span>
          </div>
          <div style="font-size: 9px; color: #94a3b8; background: rgba(11, 19, 41, 0.5); padding: 4px; border-radius: 2px; border: 1px solid rgba(30, 41, 59, 0.5); word-break: break-all;">
            <strong>Strat:</strong> ${stratStr}
          </div>
          ${failureHtml}
        </div>
      `;
    });
    
    searchResults.innerHTML = html;
  } catch (err) {
    searchResults.innerHTML = `<div style="color: #ff1744; padding: 10px;">Failed: ${err.message}</div>`;
  } finally {
    searchBtn.disabled = false;
    searchBtn.textContent = "FIND";
  }
}

searchBtn.addEventListener("click", performSearch);
searchInput.addEventListener("keypress", (e) => {
  if (e.key === "Enter") performSearch();
});

// ════════════════════════════════════════
// ATLAS CHARTS EMBEDDING
// ════════════════════════════════════════
window.embedAtlasChart = function() {
  const input = document.getElementById("chartsUrlInput").value.trim();
  const container = document.getElementById("chartsFrameContainer");
  if (!input) {
    container.innerHTML = '<span style="color: #7e90b0; text-align: center; padding: 10px;">No chart embedded. Paste your sharing URL above to render Atlas Charts.</span>';
    return;
  }
  
  let src = "";
  if (input.includes("<iframe") && input.includes("src=")) {
    const match = input.match(/src=["']([^"']+)["']/);
    if (match && match[1]) {
      src = match[1];
    }
  } else {
    src = input;
  }
  
  if (src) {
    container.innerHTML = `<iframe src="${src}" style="background: #0B1329; border: none; border-radius: 4px; width: 100%; height: 100%;" allowfullscreen></iframe>`;
  } else {
    container.innerHTML = '<span style="color: #ff1744; text-align: center; padding: 10px;">Invalid URL or iframe tag format.</span>';
  }
};

// ════════════════════════════════════════
// INIT
// ════════════════════════════════════════
window.onload = () => {
  initChart();
  updateAction();
  renderGPUs(null, rackGrid);
  renderTelemetry(null);
};