main
John Lauer Publish 0.2.2 6e403aa
// Adom SPICE dashboard: all state lives on the server; this page renders it and posts user actions.
let S = null;
const ENG = {
  ngspice: { name: 'ngspice', where: 'Adom container (BSD, can be hosted)' },
  ltspice: { name: 'LTspice', where: 'Windows host via Adom Bridge, batch mode' },
  pspice: { name: 'PSpice for TI', where: 'Windows host via Adom Bridge, driven through its window' },
};
const $ = (s) => document.querySelector(s);
const post = (path, body) => fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({ fromUi: true }, body)) }).then(r => r.json());
const fmt = (v, d = 3) => v == null ? '-' : (Math.abs(v) >= 100 ? v.toFixed(1) : Math.abs(v) >= 10 ? v.toFixed(2) : v.toFixed(d));
const cost = (t) => t == null ? '-' : `$${(t * S.settings.pricePerMTokLow / 1e6).toFixed(2)}-${(t * S.settings.pricePerMTokHigh / 1e6).toFixed(2)}`;

function toast(text, kind) {
  const d = document.createElement('div'); d.className = 'toast'; d.textContent = text;
  if (kind === 'error') d.style.borderLeftColor = 'var(--red)';
  $('#toasts').appendChild(d); setTimeout(() => d.remove(), 4000);
}

function runFor(e) { return S.runs.filter(r => r.engine === e).slice(-1)[0]; }

function renderEngines() {
  const box = $('#engines'); box.innerHTML = '';
  const list = Object.keys(ENG).map(e => ({ key: e, run: runFor(e) }));
  for (const r of S.runs.filter(r => r.engine === 'reference')) list.push({ key: 'reference', run: r });
  for (const { key, run } of list) {
    const busy = S.busy && S.busy.engine === key;
    const st = busy ? 'running' : run ? run.status : 'idle';
    const c = document.createElement('div'); c.className = 'eng'; c.id = 'eng-' + key;
    const time = run ? (run.timeHidden ? 'hidden (licence)' : run.wall_s != null ? run.wall_s.toFixed(1) + ' s' : '-') : '-';
    c.innerHTML = `<div class="name"><span class="sw" style="background:${S.colors[key]}"></span>${key === 'reference' ? run.label : ENG[key].name}</div>
      <div class="where">${key === 'reference' ? 'Reference run (does not vote)' : ENG[key].where}</div>
      <div class="stats">status <span class="state-${st}">${st}</span><br>sim time ${time}<br>AI tokens ${run && run.tokens != null ? run.tokens.toLocaleString() + '  ' + cost(run.tokens) : '-'}</div>
      <div class="row">${key === 'reference' ? '' : `<button class="run" data-e="${key}" ${S.busy || !S.study ? 'disabled' : ''}>${busy ? 'Running' : 'Run'}</button>`}
      ${run ? `<label class="toggle"><input type="checkbox" data-id="${run.id}" ${run.visible !== false ? 'checked' : ''}> show on charts</label>` : ''}</div>`;
    box.appendChild(c);
  }
  box.querySelectorAll('.run').forEach(b => b.onclick = (ev) => {
    const e = b.dataset.e;
    if (!ev.isTrusted) return;                                   // only real user clicks start runs
    if (e !== 'ngspice' && !confirm(`${ENG[e].name} runs on ${S.settings.bridgeTarget || 'your primary machine'} through Adom Bridge and uses its screen while it works. Start it?`)) return;
    post('run', { engines: [e] }).then(r => r.ok ? toast('Queued ' + ENG[e].name) : toast(r.error, 'error'));
  });
  box.querySelectorAll('input[data-id]').forEach(i => i.onchange = () => post('visible', { id: i.dataset.id, visible: i.checked }));
}

function drawChart(canvas, view, idx) {
  const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;
  canvas.width = W * dpr; canvas.height = H * dpr;
  const g = canvas.getContext('2d'); g.scale(dpr, dpr); g.clearRect(0, 0, W, H);
  const L = 56, R = 10, T = 8, B = 30;
  const series = S.runs.filter(r => r.visible !== false && S.waves[r.id] && S.waves[r.id][idx]);
  if (!series.length) { g.fillStyle = '#9aa4b2'; g.font = '14px Familjen Grotesk'; g.fillText('No runs yet', L, H / 2); return; }
  let x0 = view.from, x1 = view.to, y0 = Infinity, y1 = -Infinity;
  for (const r of series) for (const y of S.waves[r.id][idx].y) { if (y < y0) y0 = y; if (y > y1) y1 = y; }
  if (view.ylim) [y0, y1] = view.ylim; else { const p = (y1 - y0) * 0.08 || 0.1; y0 -= p; y1 += p; }
  const X = (x) => L + (x - x0) / (x1 - x0) * (W - L - R), Y = (y) => T + (1 - (y - y0) / (y1 - y0)) * (H - T - B);
  g.strokeStyle = '#232833'; g.lineWidth = 1; g.fillStyle = '#9aa4b2'; g.font = '12px JetBrains Mono';
  for (let i = 0; i <= 5; i++) {
    const yv = y0 + (y1 - y0) * i / 5, xv = x0 + (x1 - x0) * i / 5;
    g.beginPath(); g.moveTo(L, Y(yv)); g.lineTo(W - R, Y(yv)); g.stroke(); g.fillText(fmt(yv * (view.yscale || 1), 2), 4, Y(yv) + 4);
    g.beginPath(); g.moveTo(X(xv), T); g.lineTo(X(xv), H - B); g.stroke(); g.fillText(fmt(xv * (view.xscale || 1), 2), X(xv) - 14, H - 10);
  }
  const order = ['ngspice', 'ltspice', 'pspice', 'reference'], widths = { ngspice: 6, ltspice: 3.6, pspice: 1.6, reference: 1.8 };
  series.sort((a, b) => order.indexOf(a.engine) - order.indexOf(b.engine));
  for (const r of series) {
    const d = S.waves[r.id][idx]; g.strokeStyle = S.colors[r.engine]; g.lineWidth = widths[r.engine] || 2;
    g.setLineDash(r.engine === 'reference' ? [6, 4] : []); g.lineJoin = 'round'; g.beginPath();
    d.x.forEach((x, i) => { const px = X(x), py = Y(d.y[i]); i ? g.lineTo(px, py) : g.moveTo(px, py); }); g.stroke();
  }
  g.setLineDash([]);
}

function renderCharts() {
  const box = $('#charts');
  if (!S.study) { box.innerHTML = ''; return; }
  if (box.children.length !== S.study.views.length) {
    box.innerHTML = S.study.views.map((v, i) => `<div class="chart"><h3>${v.title}</h3><canvas id="c${i}" style="height:${i === 0 ? 520 : 240}px"></canvas></div>`).join('');
  }
  S.study.views.forEach((v, i) => drawChart($('#c' + i), v, String(i)));
}

function renderAgree() {
  const t = $('#agree');
  if (!S.agreement.length) { t.innerHTML = '<tr><td>No measurements yet.</td></tr>'; return; }
  const single = S.verdict && S.verdict.kind === 'single';
  const engs = Object.keys(ENG).filter(e => runFor(e) && runFor(e).status === 'done');
  const refs = S.runs.filter(r => r.engine === 'reference').map(r => r.label);
  t.innerHTML = `<tr><th>Measurement</th>${engs.map(e => `<th><span class="sw" style="background:${S.colors[e]}"></span> ${ENG[e].name}</th>`).join('')}${single ? '' : '<th>Spread</th><th>Limit</th><th>Engines</th>'}${refs.map(r => `<th>${r}</th>`).join('')}</tr>` +
    S.agreement.map(row => `<tr class="${row.ok === false ? 'flag' : ''}"><td>${row.label || row.metric} <span class="sub">${row.unit}</span></td>
      ${engs.map(e => `<td class="num ${row.outlier === e ? 'outlier' : ''}">${fmt(row.values[e])}</td>`).join('')}
      ${single ? '' : `<td class="num">${fmt(row.spread)}</td><td class="num">${fmt(row.limit)}</td>
      <td class="${row.ok ? 'ok' : row.ok === false ? 'bad' : ''}">${row.ok ? 'agree' : row.ok === false ? 'differ' : '-'}</td>`}
      ${refs.map(r => `<td class="num">${fmt((row.reference || {})[r])}</td>`).join('')}</tr>`).join('');
}

function renderLedger() {
  const t = $('#ledger');
  t.innerHTML = '<tr><th>Run</th><th>Model</th><th>AI thread</th><th>Started</th><th>Sim time</th><th>AI tokens</th><th>Tool calls</th><th>AI cost</th></tr>' +
    S.runs.map(r => `<tr><td><span class="sw" style="background:${S.colors[r.engine]}"></span> ${r.engine === 'reference' ? 'reference' : ENG[r.engine].name}</td><td>${r.label}</td><td>${r.thread || '-'}</td><td>${r.started}</td>
      <td class="num">${r.timeHidden ? 'hidden' : r.wall_s != null ? r.wall_s.toFixed(1) + ' s' : '-'}</td><td class="num">${r.tokens != null ? r.tokens.toLocaleString() : '-'}</td>
      <td class="num">${r.toolCalls != null ? r.toolCalls : '-'}</td><td class="num">${cost(r.tokens)}</td></tr>`).join('');
}

function renderLog(line) {
  const l = $('#log'); const add = (e) => { const d = document.createElement('div'); d.textContent = `${e.t}  ${e.thread ? '[' + e.thread + '] ' : ''}${e.line}`; l.appendChild(d); };
  if (line) add(line); else { l.innerHTML = ''; (S.log || []).forEach(add); }
  l.scrollTop = l.scrollHeight;
}

function render() {
  $('#study').textContent = S.study ? S.study.name : 'no study loaded';
  $('#busy').textContent = S.busy ? `running ${ENG[S.busy.engine].name}...` : '';
  const v = S.verdict || { kind: 'pending', text: 'Load a study to begin.' };
  $('#verdict').className = 'verdict ' + v.kind; $('#verdict').textContent = v.text;
  renderEngines(); renderCharts(); renderAgree(); renderLedger(); renderLog();
}

async function openSettings() {
  const d = await fetch('settings').then(r => r.json());
  $('#settingsBody').innerHTML = Object.entries(d.settings).map(([k, v]) => {
    const help = d.help[k] || '', en = d.enums[k];
    const input = en ? `<select data-k="${k}">${en.map(o => `<option ${String(o) === String(v) ? 'selected' : ''}>${o}</option>`).join('')}</select>`
      : `<input data-k="${k}" value='${typeof v === 'object' ? JSON.stringify(v) : v}'>`;
    return `<div class="setrow"><div><div>${k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase())}</div><div class="help">${help}</div></div>${input}</div>`;
  }).join('');
  $('#ver').textContent = 'Adom SPICE ' + S.version;
  $('#settingsBody').querySelectorAll('[data-k]').forEach(el => el.onchange = () => {
    let v = el.value; try { v = JSON.parse(v); } catch (e) { }
    post('settings', { set: { [el.dataset.k]: v } }).then(r => r.ok ? null : toast(r.error, 'error'));
  });
  $('#settings').classList.remove('hidden');
}
$('#gear').onclick = openSettings;
$('#closeSettings').onclick = () => $('#settings').classList.add('hidden');

const es = new EventSource('events');
es.addEventListener('state', (e) => { S = JSON.parse(e.data); render(); });
es.addEventListener('log', (e) => { if (S) { S.log.push(JSON.parse(e.data)); renderLog(JSON.parse(e.data)); } });
es.addEventListener('toast', (e) => { const d = JSON.parse(e.data); toast(d.text, d.kind); });
es.addEventListener('click', (e) => { const el = document.querySelector(JSON.parse(e.data).selector); if (el) el.click(); });
es.addEventListener('reveal', (e) => { const el = document.querySelector(JSON.parse(e.data).selector); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.add('hl'); setTimeout(() => el.classList.remove('hl'), 2500); } });
window.addEventListener('resize', () => S && renderCharts());