index.html 25 KB
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
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>H3 Console</title>
<style>
  :root { color-scheme: light dark; }
  * { box-sizing: border-box; }
  body { font-family: -apple-system, "PingFang SC", sans-serif; margin: 0; padding: 0; display: flex; height: 100vh; overflow: hidden; }

  /* ---- 左侧任务记录 ---- */
  #sidebar { width: 300px; flex-shrink: 0; border-right: 1px solid #ddd; display: flex; flex-direction: column; height: 100vh; }
  #sidebar-header { padding: 16px; border-bottom: 1px solid #ddd; }
  #sidebar-header h1 { font-size: 16px; margin: 0; }
  #job-list { flex: 1; overflow-y: auto; }
  .job-row { padding: 10px 16px; border-bottom: 1px solid #eee; cursor: pointer; }
  .job-row:hover { background: rgba(128,128,128,.08); }
  .job-row.selected { background: rgba(74,170,119,.15); border-left: 3px solid #4a7; }
  .job-row.new-row { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #4a7; }
  .job-row .jr-top { display: flex; justify-content: space-between; align-items: center; font-size: 12px; }
  .job-row .jr-prompt { font-size: 13px; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .job-row .jr-time { font-size: 11px; opacity: .55; margin-top: 2px; }
  #backends { font-size: 11px; opacity: .75; padding: 10px 16px; border-top: 1px solid #ddd; white-space: pre-wrap; }

  /* ---- 右侧主区 ---- */
  #main { flex: 1; overflow-y: auto; padding: 24px 32px; }
  .tabs { display: flex; gap: 8px; margin: 0 0 16px; }
  .tabs button { padding: 8px 16px; border: 1px solid #888; background: transparent; border-radius: 6px; cursor: pointer; }
  .tabs button.active { background: #4a7; color: white; border-color: #4a7; }
  fieldset { border: 1px solid #ccc; border-radius: 8px; margin-bottom: 16px; max-width: 640px; }
  label { display: block; margin: 8px 0 4px; font-size: 13px; opacity: .8; }
  input, select, textarea { padding: 6px; width: 100%; box-sizing: border-box; font-family: inherit; font-size: 14px; }
  textarea { resize: vertical; min-height: 200px; }
  .row { display: flex; gap: 12px; }
  .row > div { flex: 1; }
  button.submit { margin-top: 12px; padding: 10px 20px; background: #4a7; color: white; border: none; border-radius: 6px; cursor: pointer; }
  button.submit:disabled { opacity: .5; cursor: default; }
  .hint { font-size: 12px; opacity: .65; margin: 6px 0 4px; line-height: 1.5; }
  .thumbrow { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 6px; }
  .thumbrow img { height: 60px; border-radius: 4px; }
  .status-done { color: #2a7; } .status-failed { color: #c33; } .status-running { color: #a70; } .status-queued { color: #777; }
  .err { color: #c33; font-size: 13px; margin-top: 8px; }

  /* ---- 任务详情 ---- */
  #detail { max-width: 640px; }
  #detail .back { font-size: 13px; cursor: pointer; opacity: .7; margin-bottom: 12px; display: inline-block; }
  #detail .back:hover { opacity: 1; }
  #detail h2 { font-size: 16px; margin: 0 0 4px; }
  #detail .dl { display: grid; grid-template-columns: 110px 1fr; gap: 6px 12px; font-size: 13px; margin: 16px 0; }
  #detail .dl dt { opacity: .6; }
  #detail .dl dd { margin: 0; word-break: break-all; }
  #detail video { max-width: 100%; margin-top: 12px; border-radius: 6px; }
  #detail .download { display: inline-block; margin-top: 10px; font-size: 13px; }
</style>
</head>
<body>

<div id="sidebar">
  <div id="sidebar-header">
    <h1>H3 Console</h1>
  </div>
  <div id="job-list"></div>
  <div id="backends"></div>
</div>

<div id="main">

<div id="create-view">
  <div class="tabs">
    <button class="active" data-tab="text">文生视频</button>
    <button data-tab="fl2va">首尾帧生视频</button>
    <button data-tab="ref2va">多参考图生视频</button>
  </div>

  <!-- 文生视频 -->
  <fieldset id="tab-text">
    <legend>文生视频</legend>
    <label>Prompt</label>
    <textarea id="text-prompt" rows="10" placeholder="清晨的中式庭院,一位女子坐在长廊上喝茶..."></textarea>
    <div class="row">
      <div><label>分辨率</label><select id="text-res" class="res-select"></select></div>
      <div><label>时长</label><select id="text-dur" class="dur-select"></select></div>
    </div>
    <div class="hint" id="text-hint"></div>
    <div class="row">
      <div><label>Turbo</label><select id="text-turbo" class="turbo-select" data-steps="text-steps"><option value="true" selected>开(4步,快)</option><option value="false">关(多步,慢但更稳)</option></select></div>
      <div><label>步数</label><select id="text-steps"></select></div>
      <div><label>Seed</label><select id="text-seed">
        <option value="0" selected>0</option>
        <option value="42">42</option>
        <option value="123">123</option>
        <option value="2024">2024</option>
        <option value="random">随机</option>
      </select></div>
    </div>
    <button class="submit" onclick="submitJob('text')">提交</button>
    <div class="err" id="text-err"></div>
  </fieldset>

  <!-- 首尾帧 -->
  <fieldset id="tab-fl2va" style="display:none">
    <legend>首尾帧生视频(FL2VA)</legend>
    <label>Prompt</label>
    <textarea id="fl2va-prompt" rows="10" placeholder="..."></textarea>
    <label>首帧图</label>
    <input id="fl2va-first" type="file" accept="image/*" onchange="uploadTo('fl2va-first')">
    <label>尾帧图(可选)</label>
    <input id="fl2va-last" type="file" accept="image/*" onchange="uploadTo('fl2va-last')">
    <div class="thumbrow" id="fl2va-thumbs"></div>
    <div class="row">
      <div><label>分辨率</label><select id="fl2va-res" class="res-select"></select></div>
      <div><label>时长</label><select id="fl2va-dur" class="dur-select"></select></div>
    </div>
    <div class="hint" id="fl2va-hint"></div>
    <div class="row">
      <div><label>Turbo</label><select id="fl2va-turbo" class="turbo-select" data-steps="fl2va-steps"><option value="true" selected>开(4步,快)</option><option value="false">关(多步,慢但更稳)</option></select></div>
      <div><label>步数</label><select id="fl2va-steps"></select></div>
      <div><label>Seed</label><select id="fl2va-seed">
        <option value="0" selected>0</option>
        <option value="42">42</option>
        <option value="123">123</option>
        <option value="2024">2024</option>
        <option value="random">随机</option>
      </select></div>
    </div>
    <button class="submit" onclick="submitJob('fl2va')">提交</button>
    <div class="err" id="fl2va-err"></div>
  </fieldset>

  <!-- 参考图 -->
  <fieldset id="tab-ref2va" style="display:none">
    <legend>多参考图生视频(Ref2VA)</legend>
    <label>Prompt</label>
    <textarea id="ref2va-prompt" rows="10" placeholder="..."></textarea>
    <label>参考图(可多选,没有张数上限,越多序列越长越慢)</label>
    <input id="ref2va-refs" type="file" accept="image/*" multiple onchange="uploadMulti()">
    <div class="thumbrow" id="ref2va-thumbs"></div>
    <div class="row">
      <div><label>分辨率</label><select id="ref2va-res" class="res-select"></select></div>
      <div><label>时长</label><select id="ref2va-dur" class="dur-select"></select></div>
    </div>
    <div class="hint" id="ref2va-hint"></div>
    <div class="row">
      <div><label>Turbo</label><select id="ref2va-turbo" class="turbo-select" data-steps="ref2va-steps"><option value="true" selected>开(4步,快)</option><option value="false">关(多步,慢但更稳)</option></select></div>
      <div><label>步数</label><select id="ref2va-steps"></select></div>
      <div><label>Seed</label><select id="ref2va-seed">
        <option value="0" selected>0</option>
        <option value="42">42</option>
        <option value="123">123</option>
        <option value="2024">2024</option>
        <option value="random">随机</option>
      </select></div>
    </div>
    <button class="submit" onclick="submitJob('ref2va')">提交</button>
    <div class="err" id="ref2va-err"></div>
  </fieldset>
</div>

<div id="detail" style="display:none"></div>

</div>

<script>
const uploaded = { 'fl2va-first': null, 'fl2va-last': null, 'ref2va-refs': [] };
let jobsCache = [];

// URL 是 /task.html/<id> 或 /newtask.html(或裸 /,等同 newtask)——不是两个页面文件,
// server.py 里 /task.html/{tid} 和 /newtask.html 两条路由都返回这同一份 index.html,
// 这里只是从地址栏读出当前该显示哪个视图,方便复制链接分享、刷新页面不丢状态。
function tidFromPath() {
  const m = location.pathname.match(/^\/task\.html\/(.+)$/);
  return m ? decodeURIComponent(m[1]) : null;
}
let selectedId = tidFromPath();

document.querySelectorAll('.tabs button').forEach(btn => btn.onclick = () => {
  document.querySelectorAll('.tabs button').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  ['text','fl2va','ref2va'].forEach(t => document.getElementById('tab-'+t).style.display = (t===btn.dataset.tab ? 'block' : 'none'));
});

function showCreate(pushUrl = true) {
  selectedId = null;
  if (pushUrl) history.pushState(null, '', '/newtask.html');
  document.getElementById('create-view').style.display = 'block';
  document.getElementById('detail').style.display = 'none';
  renderSidebar();
}

// 只支持两档分辨率、三档时长——都是实测过边界的组合,不开放自由填数字撞 OOM。
// 见 h3-console/README.md 和顶层 CHANGELOG「15 秒时长边界实测」:
//   832×480 只在 5s 档稳定,15s 会 OOM;448×256 是 15s 档实测最稳的一档(峰值 12.0G)。
//   10s(243帧) 没专门测过,帧数按 17n+5 公式换算,pipeline 会自动 snap,能提交但结果未验证。
const RESOLUTIONS = [
  { value: '832x480', width: 832, height: 480, label: '832×480(标准档)' },
  { value: '448x256', width: 448, height: 256, label: '448×256(长时长档)' },
];
const DURATIONS = [
  { value: '124', frames: 124, label: '5s(124帧,实测)' },
  { value: '243', frames: 243, label: '10s(243帧,未实测)' },
  { value: '362', frames: 362, label: '15s(362帧,实测)' },
];
// Turbo LoRA 是 4 步蒸馏的,步数选项跟着 Turbo 开关联动——这两个字段本来就是耦合的,
// 分开选很容易选出"关 Turbo 却只给4步"这种没意义的组合。
const STEPS_BY_TURBO = {
  true:  [{ value: '4', label: '4步(推荐,Turbo LoRA 就是4步蒸馏的)' },
          { value: '8', label: '8步(协议允许上限,未专门测过)' }],
  false: [{ value: '20', label: '20步' },
          { value: '50', label: '50步(实测全质量,约9.6倍耗时)' }],
};

// 跟 api.py 的 _rows()/ROWS_LIMIT 保持一致——前端只是把后端已经在强制的这条线提前到选择阶段,
// 不是另一套独立规则,两边算法对不上就会出现"前端放行、后端拒绝"或反过来,所以数字改动两边一起改。
function rows(width, height, frames) {
  const latentFrames = Math.floor((Math.max(frames, 5) - 5) / 17) * 5 + 2;
  return latentFrames * width * height / 1024;
}
const ROWS_LIMIT = 20000;

function fillSelect(select, options) {
  select.innerHTML = options.map(o => `<option value="${o.value}">${o.label}</option>`).join('');
}

function syncDurOptions(prefix) {
  const resSelect = document.getElementById(prefix + '-res');
  const durSelect = document.getElementById(prefix + '-dur');
  const hint = document.getElementById(prefix + '-hint');
  if (!resSelect || !durSelect) return;
  const res = RESOLUTIONS.find(r => r.value === resSelect.value);
  const prevValue = durSelect.value;
  const allowed = DURATIONS.filter(d => rows(res.width, res.height, d.frames) <= ROWS_LIMIT);
  fillSelect(durSelect, allowed);
  durSelect.value = allowed.some(d => d.value === prevValue) ? prevValue : allowed[0].value;
  if (hint) {
    const dropped = DURATIONS.filter(d => !allowed.includes(d)).map(d => d.label);
    hint.textContent = dropped.length
      ? `⚠ ${res.label} 分辨率下,${dropped.join('、')} 会撞显存上限,已不可选。`
      : `${res.label} 分辨率下,${DURATIONS.map(d => d.label).join('/')} 均可选。`;
  }
}

function initParamSelects(prefix) {
  const res = document.getElementById(prefix + '-res');
  const dur = document.getElementById(prefix + '-dur');
  if (res) fillSelect(res, RESOLUTIONS);
  if (dur) fillSelect(dur, DURATIONS);
  if (res) { syncDurOptions(prefix); res.onchange = () => syncDurOptions(prefix); }

  const turboSelect = document.getElementById(prefix + '-turbo');
  if (turboSelect) {
    const stepsSelect = document.getElementById(turboSelect.dataset.steps);
    const syncSteps = () => fillSelect(stepsSelect, STEPS_BY_TURBO[turboSelect.value]);
    turboSelect.onchange = syncSteps;
    syncSteps();
  }
}

['text', 'fl2va', 'ref2va'].forEach(initParamSelects);

async function uploadFile(file) {
  const fd = new FormData(); fd.append('file', file);
  const r = await fetch('/v1/assets', { method: 'POST', body: fd });
  if (!r.ok) throw new Error(await r.text());
  return await r.json();
}

async function uploadTo(inputId) {
  const el = document.getElementById(inputId);
  if (!el.files[0]) return;
  try {
    const res = await uploadFile(el.files[0]);
    uploaded[inputId] = res.url;
    const thumbs = document.getElementById('fl2va-thumbs');
    const img = document.createElement('img'); img.src = res.url; thumbs.appendChild(img);
  } catch (e) { document.getElementById('fl2va-err').textContent = '上传失败: ' + e.message; }
}

async function uploadMulti() {
  const el = document.getElementById('ref2va-refs');
  const thumbs = document.getElementById('ref2va-thumbs');
  for (const f of el.files) {
    try {
      const res = await uploadFile(f);
      uploaded['ref2va-refs'].push(res.url);
      const img = document.createElement('img'); img.src = res.url; thumbs.appendChild(img);
    } catch (e) { document.getElementById('ref2va-err').textContent = '上传失败: ' + e.message; }
  }
}

// 分辨率/时长/Turbo/步数/Seed 五个字段,三个 tab 结构完全一样,抽出来一份读取逻辑。
function readParamSelects(prefix) {
  const res = RESOLUTIONS.find(r => r.value === document.getElementById(prefix + '-res').value);
  const dur = DURATIONS.find(d => d.value === document.getElementById(prefix + '-dur').value);
  const seedRaw = document.getElementById(prefix + '-seed').value;
  return {
    width: res.width, height: res.height, frames: dur.frames,
    turbo: document.getElementById(prefix + '-turbo').value === 'true',
    steps: +document.getElementById(prefix + '-steps').value,
    seed: seedRaw === 'random' ? Math.floor(Math.random() * 2**31) : +seedRaw,
  };
}

async function submitJob(kind) {
  const errBox = document.getElementById(kind + '-err'); errBox.textContent = '';
  let body = {};
  if (kind === 'text') {
    body = { prompt: document.getElementById('text-prompt').value, ...readParamSelects('text') };
  } else if (kind === 'fl2va') {
    if (!uploaded['fl2va-first']) { errBox.textContent = '请先上传首帧图'; return; }
    body = {
      prompt: document.getElementById('fl2va-prompt').value,
      first_frame_url: uploaded['fl2va-first'],
      last_frame_url: uploaded['fl2va-last'] || undefined,
      ...readParamSelects('fl2va'),
    };
  } else if (kind === 'ref2va') {
    if (uploaded['ref2va-refs'].length === 0) { errBox.textContent = '请先上传至少一张参考图'; return; }
    body = {
      prompt: document.getElementById('ref2va-prompt').value,
      reference_image_urls: uploaded['ref2va-refs'],
      ...readParamSelects('ref2va'),
    };
  }
  if (!body.prompt) { errBox.textContent = '请填写 prompt'; return; }
  try {
    const r = await fetch('/v1/videos', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
    if (!r.ok) throw new Error(await r.text());
    const job = await r.json();
    await refreshJobs();
    selectJob(job.id);  // 提交完直接跳到这条任务的详情,能立刻看到排队/运行状态
  } catch (e) { errBox.textContent = '提交失败: ' + e.message; }
}

// 重跑:不直接提交,而是把这条任务当初的 req 灌回"新建任务"表单(对应的 tab、参数、
// 已上传的图片 URL 都原样带过去),跳到 /newtask.html,用户看一眼确认无误后自己点提交——
// 跟正常新建任务走的是同一条路径、同一次人工确认,不是绕过表单直接后台再发一次请求。
function setThumbs(elId, urls) {
  const box = document.getElementById(elId); box.innerHTML = '';
  urls.forEach(u => { if (!u) return; const img = document.createElement('img'); img.src = u; box.appendChild(img); });
}

function prefillCreate(req) {
  const kind = (req.first_frame_url || req.last_frame_url) ? 'fl2va'
    : (req.reference_image_urls || []).length ? 'ref2va' : 'text';

  document.querySelectorAll('.tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === kind));
  ['text', 'fl2va', 'ref2va'].forEach(t => document.getElementById('tab-' + t).style.display = (t === kind ? 'block' : 'none'));

  document.getElementById(kind + '-prompt').value = req.prompt || '';

  const resOpt = RESOLUTIONS.find(o => o.width === req.width && o.height === req.height);
  if (resOpt) document.getElementById(kind + '-res').value = resOpt.value;
  syncDurOptions(kind);  // 按刚设好的分辨率重新过滤时长选项,再决定原来的档位还能不能选
  const durSel = document.getElementById(kind + '-dur');
  const durOpt = DURATIONS.find(o => o.frames === req.frames);
  if (durOpt && [...durSel.options].some(o => o.value === durOpt.value)) durSel.value = durOpt.value;

  const turboSel = document.getElementById(kind + '-turbo');
  turboSel.value = req.turbo === false ? 'false' : 'true';
  turboSel.onchange();  // 联动刷新步数选项,必须在设置步数值之前调用
  const stepsSel = document.getElementById(kind + '-steps');
  if (req.steps != null && [...stepsSel.options].some(o => o.value === String(req.steps))) {
    stepsSel.value = String(req.steps);
  }
  const seedSel = document.getElementById(kind + '-seed');
  if (req.seed != null) {
    if (![...seedSel.options].some(o => o.value === String(req.seed))) {
      const opt = document.createElement('option');
      opt.value = String(req.seed); opt.textContent = req.seed + '(原任务的 seed)';
      seedSel.insertBefore(opt, seedSel.firstChild);
    }
    seedSel.value = String(req.seed);
  }

  if (kind === 'fl2va') {
    uploaded['fl2va-first'] = req.first_frame_url || null;
    uploaded['fl2va-last'] = req.last_frame_url || null;
    setThumbs('fl2va-thumbs', [req.first_frame_url, req.last_frame_url]);
  } else if (kind === 'ref2va') {
    uploaded['ref2va-refs'] = (req.reference_image_urls || []).slice();
    setThumbs('ref2va-thumbs', uploaded['ref2va-refs']);
  }

  showCreate();
}

async function rerunJob(id) {
  try {
    const r = await fetch(`/v1/videos/${id}`);
    if (!r.ok) throw new Error(await r.text());
    const req = (await r.json()).req || {};
    prefillCreate(req);
  } catch (e) { alert('重跑失败: ' + e.message); }
}

function statusLabel(s) {
  const map = { queued: '排队中', running: '运行中', done: '已完成', failed: '失败' };
  return `<span class="status-${s}">${map[s] || s}</span>`;
}

function timeAgo(ts) {
  if (!ts) return '';
  const s = Math.max(0, Math.round(Date.now()/1000 - ts));
  if (s < 60) return s + '秒前';
  if (s < 3600) return Math.round(s/60) + '分钟前';
  return Math.round(s/3600) + '小时前';
}

function fmtTime(ts) {
  if (!ts) return '—';
  return new Date(ts * 1000).toLocaleString('zh-CN', { hour12: false });
}

function renderSidebar() {
  const box = document.getElementById('job-list'); box.innerHTML = '';

  const newRow = document.createElement('div');
  newRow.className = 'job-row new-row' + (selectedId === null ? ' selected' : '');
  newRow.onclick = () => showCreate();
  newRow.innerHTML = `<span>+</span><span>新建任务</span>`;
  box.appendChild(newRow);

  jobsCache.forEach(j => {
    const row = document.createElement('div');
    row.className = 'job-row' + (j.id === selectedId ? ' selected' : '');
    row.onclick = () => selectJob(j.id);
    const prompt = j.req ? (j.req.prompt || '(无 prompt)') : '';
    row.innerHTML = `
      <div class="jr-top"><span>${j.id}</span>${statusLabel(j.status)}</div>
      <div class="jr-prompt" title="${prompt}">${prompt}</div>
      <div class="jr-time">${timeAgo(j.created_at)}</div>`;
    box.appendChild(row);
  });
}

async function selectJob(id, pushUrl = true) {
  selectedId = id;
  if (pushUrl) history.pushState(null, '', '/task.html/' + encodeURIComponent(id));
  document.getElementById('create-view').style.display = 'none';
  document.getElementById('detail').style.display = 'block';
  renderSidebar();
  await refreshDetail();
}

// 浏览器前进/后退要同步这个状态,不然 URL 变了但页面没跟着变
window.addEventListener('popstate', () => {
  const tid = tidFromPath();
  if (tid) selectJob(tid, false); else showCreate(false);
});

async function refreshDetail() {
  if (!selectedId) return;
  const box = document.getElementById('detail');
  try {
    const r = await fetch(`/v1/videos/${selectedId}`);
    if (!r.ok) { box.innerHTML = `<div class="back" onclick="showCreate()">← 新建任务</div><div class="err">找不到这个任务</div>`; return; }
    const j = await r.json();
    const req = j.req || {};

    let resultHtml = '';
    if (j.status === 'done') {
      resultHtml = `<video controls src="/v1/videos/${j.id}/file"></video>
        <a class="download" href="/v1/videos/${j.id}/file" download>下载 mp4${j.size_bytes ? ' ('+(j.size_bytes/1024/1024).toFixed(1)+'MB)' : ''}</a>`;
    } else if (j.status === 'failed') {
      resultHtml = `<div class="err">${(j.error || '未知错误').replace(/</g,'&lt;')}</div>`;
    } else if (j.status === 'running') {
      resultHtml = `<div>已运行 ${j.elapsed_seconds || 0} 秒(共 ${j.total_steps || req.steps || '?'} 步,当前第 ${j.step || 0} 步)</div>`;
    } else {
      resultHtml = `<div>排队中,等待可用的 ${j.partition || ''} 后端…</div>`;
    }

    let refThumbs = '';
    const imgs = [];
    if (req.first_frame_url) imgs.push(['首帧', req.first_frame_url]);
    if (req.last_frame_url) imgs.push(['尾帧', req.last_frame_url]);
    (req.reference_image_urls || []).forEach((u, i) => imgs.push(['参考图'+(i+1), u]));
    if (imgs.length) refThumbs = `<div class="thumbrow">${imgs.map(([label,u]) => `<img src="${u}" title="${label}">`).join('')}</div>`;

    box.innerHTML = `
      <div class="back" onclick="showCreate()">← 新建任务</div>
      <h2>${j.id}</h2>
      <div>${statusLabel(j.status)} <button class="submit" style="padding:4px 12px;margin-left:8px" onclick="rerunJob('${j.id}')">重跑</button></div>
      <dl class="dl">
        <dt>Prompt</dt><dd>${(req.prompt || '').replace(/</g,'&lt;')}</dd>
        <dt>分区</dt><dd>${j.partition || '—'}</dd>
        <dt>分辨率/帧数</dt><dd>${req.width || '?'}×${req.height || '?'} × ${req.frames || '?'}帧</dd>
        <dt>Turbo/步数</dt><dd>${req.turbo === false ? '关' : '开'} / ${req.steps ?? '?'} 步,seed=${req.seed ?? 0}</dd>
        <dt>后端</dt><dd>${j.backend || '(尚未分配)'}</dd>
        <dt>提交时间</dt><dd>${fmtTime(j.created_at)}</dd>
        <dt>开始时间</dt><dd>${fmtTime(j.started_at)}</dd>
        <dt>完成时间</dt><dd>${fmtTime(j.finished_at)}</dd>
        <dt>峰值显存</dt><dd>${j.peak_vram_gb ? j.peak_vram_gb + ' GB' : '—'}</dd>
      </dl>
      ${refThumbs}
      ${resultHtml}
    `;
  } catch (e) { /* 暂时连不上,保留当前显示,下一轮再试 */ }
}

async function refreshJobs() {
  try {
    const r = await fetch('/v1/videos?limit=50'); const d = await r.json();
    jobsCache = d.jobs || [];
    renderSidebar();
    // 只有还在变化的任务(排队/运行中)才需要重新拉详情。`refreshDetail()` 是整段
    // innerHTML 重建,`done` 之后再重建会把正在播放的 <video> 元素连根拔掉——
    // 播放到一半被这个 5 秒轮询打断、进度条弹回 0,这就是"下载和播放好像有问题"的真正原因,
    // 不是文件本身坏了(文件本身一直是好的,见 README「已实测排查过的坑」)。
    const cached = jobsCache.find(j => j.id === selectedId);
    if (selectedId && (!cached || cached.status === 'queued' || cached.status === 'running')) {
      refreshDetail();
    }
  } catch (e) { /* 后端暂时连不上,静默跳过这一轮,下次轮询再试 */ }
}

async function refreshBackends() {
  try {
    const r = await fetch('/v1/backends'); const d = await r.json();
    document.getElementById('backends').textContent =
      `后端: ${d.ready}/${d.total} ready · 排队 ${d.queued} · 运行中 ${d.running}\n` +
      d.backends.map(b => `${b.backend.replace('http://127.0.0.1:','')} gpu${b.gpu} [${b.partition||'?'}] ${b.status}`).join('\n');
  } catch (e) {}
}

// 刷新页面(或直接打开一条分享出去的 /task.html/<id> 链接)时,按当前 URL 决定初始视图
if (selectedId) {
  document.getElementById('create-view').style.display = 'none';
  document.getElementById('detail').style.display = 'block';
  refreshDetail();
}

refreshJobs(); refreshBackends();
setInterval(refreshJobs, 5000);
setInterval(refreshBackends, 8000);
</script>
</body>
</html>