index.html 57.6 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 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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
<!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; }
  #sidebar-filters { padding: 8px 16px; border-bottom: 1px solid #ddd; display: flex; flex-direction: column; gap: 6px; }
  #sidebar-filters input, #sidebar-filters select { font-size: 12px; padding: 4px 6px; width: auto; }
  #sidebar-filters .sf-row { display: flex; gap: 6px; }
  #sidebar-filters .sf-row select { flex: 1; min-width: 0; }
  #job-sort-btn { font-size: 12px; padding: 4px 8px; border: 1px solid #888; background: transparent;
    border-radius: 4px; cursor: pointer; white-space: nowrap; }
  #job-sort-btn:hover { background: rgba(128,128,128,.15); }
  #job-list { flex: 1; overflow-y: auto; }
  #job-list-footer { padding: 10px 16px; text-align: center; font-size: 11px; opacity: .55; }
  .job-row { position: relative; 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-actions { display: flex; align-items: center; gap: 6px; }
  .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; }
  .jr-menu-btn { cursor: pointer; padding: 0 4px; opacity: .55; font-size: 14px; line-height: 1; }
  .jr-menu-btn:hover { opacity: 1; }
  .jr-menu { position: absolute; top: 22px; right: 12px; background: Canvas; color: CanvasText;
    border: 1px solid #888; border-radius: 6px; box-shadow: 0 2px 10px rgba(0,0,0,.25); z-index: 10; min-width: 76px; }
  .jr-menu-item { padding: 8px 12px; font-size: 13px; cursor: pointer; }
  .jr-menu-item:hover { background: rgba(128,128,128,.15); }
  .jr-restore { padding: 3px 10px; font-size: 12px; border: 1px solid #4a7; color: #4a7; background: transparent; border-radius: 4px; cursor: pointer; }
  .jr-restore:hover { background: rgba(74,170,119,.15); }
  #backends { font-size: 11px; opacity: .75; padding: 10px 16px; border-top: 1px solid #ddd; white-space: pre-wrap; }
  #sidebar-footer { padding: 8px 16px; border-top: 1px solid #ddd; }
  #trash-btn { font-size: 17px; background: transparent; border: none; cursor: pointer; opacity: .6; padding: 4px; }
  #trash-btn:hover { opacity: 1; }

  /* ---- 右侧主区 ---- */
  #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: 20px; flex-wrap: wrap; margin-top: 12px; align-items: flex-start; }
  .thumbrow img { height: 160px; width: 160px; object-fit: cover; border-radius: 8px;
    border: 1px solid rgba(128,128,128,.3); display: block; }
  .thumbrow video { height: 200px; width: 340px; max-width: 100%; object-fit: cover;
    border-radius: 8px; border: 1px solid rgba(128,128,128,.3); display: block; background: #000; }
  .thumbrow audio { height: 40px; width: 340px; max-width: 100%; display: block; }
  .thumb-wrap { display: inline-flex; flex-direction: column; gap: 6px; max-width: 340px; }
  .thumb-media { position: relative; display: inline-block; line-height: 0; }
  .thumb-name { font-size: 12px; opacity: .7; max-width: 100%; overflow: hidden;
    text-overflow: ellipsis; white-space: nowrap; }
  .thumb-del { position: absolute; top: -8px; right: -8px; width: 24px; height: 24px; padding: 0;
    border-radius: 50%; border: none; background: #c33; color: #fff; font-size: 15px; line-height: 1;
    cursor: pointer; box-shadow: 0 1px 4px rgba(0,0,0,.35); }
  .thumb-del:hover { background: #a22; }
  .status-done { color: #2a7; } .status-failed { color: #c33; } .status-running { color: #a70; } .status-queued { color: #777; } .status-cancelled { color: #999; }
  .err { color: #c33; font-size: 13px; margin-top: 8px; white-space: pre-wrap; font-family: ui-monospace, Menlo, Consolas, monospace;
         max-height: 400px; overflow-y: auto; background: #fff5f5; border: 1px solid #f3c2c2; border-radius: 6px; padding: 10px; }

  /* ---- 任务详情 ---- */
  #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="new-task-row" class="job-row new-row" onclick="showCreate()">
    <span>+</span><span>新建任务</span>
  </div>
  <div id="sidebar-filters">
    <input id="job-search" type="text" placeholder="搜索 prompt / id…">
    <div class="sf-row">
      <select id="job-status-filter">
        <option value="">全部状态</option>
        <option value="queued">排队中</option>
        <option value="running">运行中</option>
        <option value="done">已完成</option>
        <option value="failed">失败</option>
        <option value="cancelled">已取消</option>
      </select>
      <select id="job-kind-filter">
        <option value="">全部类型</option>
        <option value="text">文生</option>
        <option value="fl2va">首尾帧</option>
        <option value="ref2va">参考图</option>
      </select>
      <button id="job-sort-btn" title="切换排序">↓最新</button>
    </div>
  </div>
  <div id="job-list"></div>
  <div id="backends"></div>
  <div id="sidebar-footer">
    <button id="trash-btn" title="回收站" onclick="toggleTrash()">🗑 回收站</button>
    <button id="reset-gpu-btn" title="硬重启服务,回收显存" onclick="resetGpu()" style="font-size:11px;padding:3px 8px;margin-left:8px">重置显存</button>
  </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">开(4步,快)</option><option value="false" selected>关(多步,慢但更稳)</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>
    <details>
      <summary style="cursor:pointer;font-size:13px;opacity:.8">高级参数(留空 = 用模型默认值)</summary>
      <label>CFG Scale(默认 1.0≈不引导;蒸馏 LoRA 调太高容易出伪影)</label>
      <input id="text-cfg" type="number" step="0.1" min="0" placeholder="留空 = 1.0">
      <label>负面提示词(默认空)</label>
      <textarea id="text-negprompt" rows="2" placeholder="例如:模糊,抖动,拖影,五官变形"></textarea>
    </details>
    <button class="submit" onclick="submitJob('text')">提交</button>
    <button type="button" style="margin-top:12px;margin-left:8px;padding:10px 20px" onclick="clearForm('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')">
    <input id="fl2va-first-url" type="url" placeholder="或粘贴图片 URL,回车添加" onkeydown="if(event.key==='Enter'){event.preventDefault();addSingleUrl('fl2va-first','fl2va-first-url',renderFl2vaThumbs,'fl2va-err')}">
    <label>尾帧图(可选)</label>
    <input id="fl2va-last" type="file" accept="image/*" onchange="uploadTo('fl2va-last')">
    <input id="fl2va-last-url" type="url" placeholder="或粘贴图片 URL,回车添加" onkeydown="if(event.key==='Enter'){event.preventDefault();addSingleUrl('fl2va-last','fl2va-last-url',renderFl2vaThumbs,'fl2va-err')}">
    <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">开(4步,快)</option><option value="false" selected>关(多步,慢但更稳)</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>
    <details>
      <summary style="cursor:pointer;font-size:13px;opacity:.8">高级参数(留空 = 用模型默认值)</summary>
      <label>CFG Scale(默认 1.0≈不引导;蒸馏 LoRA 调太高容易出伪影)</label>
      <input id="fl2va-cfg" type="number" step="0.1" min="0" placeholder="留空 = 1.0">
      <label>负面提示词(默认空)</label>
      <textarea id="fl2va-negprompt" rows="2" placeholder="例如:模糊,抖动,拖影,五官变形"></textarea>
    </details>
    <button class="submit" onclick="submitJob('fl2va')">提交</button>
    <button type="button" style="margin-top:12px;margin-left:8px;padding:10px 20px" onclick="clearForm('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()">
    <input id="ref2va-refs-url" type="url" placeholder="或粘贴图片 URL,回车添加(可加多个)" onkeydown="if(event.key==='Enter'){event.preventDefault();addArrayUrl('ref2va-refs','ref2va-refs-url',renderRefThumbs,'ref2va-err')}">
    <div class="thumbrow" id="ref2va-thumbs"></div>
    <label>参考视频(可选,最多3段,2-15秒,音轨会自动带上)</label>
    <input id="ref2va-videos-input" type="file" accept="video/*" multiple onchange="uploadMultiTagged('ref2va-videos-input','ref2va-videos','ref2va-video-tags')">
    <input id="ref2va-videos-url" type="url" placeholder="或粘贴视频 URL,回车添加(最多3个)" onkeydown="if(event.key==='Enter'){event.preventDefault();addArrayUrl('ref2va-videos','ref2va-videos-url',()=>renderTags('ref2va-video-tags','ref2va-videos'),'ref2va-err',3)}">
    <div class="thumbrow" id="ref2va-video-tags"></div>
    <label>独立音频参考(可选,最多3个,不跟参考视频绑定)</label>
    <input id="ref2va-audios-input" type="file" accept="audio/*" multiple onchange="uploadMultiTagged('ref2va-audios-input','ref2va-audios','ref2va-audio-tags')">
    <input id="ref2va-audios-url" type="url" placeholder="或粘贴音频 URL,回车添加(最多3个)" onkeydown="if(event.key==='Enter'){event.preventDefault();addArrayUrl('ref2va-audios','ref2va-audios-url',()=>renderTags('ref2va-audio-tags','ref2va-audios'),'ref2va-err',3)}">
    <div class="thumbrow" id="ref2va-audio-tags"></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">开(4步,快)</option><option value="false" selected>关(多步,慢但更稳)</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>
    <details>
      <summary style="cursor:pointer;font-size:13px;opacity:.8">高级参数(留空 = 用模型默认值)</summary>
      <label>CFG Scale(默认 1.0≈不引导;蒸馏 LoRA 调太高容易出伪影)</label>
      <input id="ref2va-cfg" type="number" step="0.1" min="0" placeholder="留空 = 1.0">
      <label>负面提示词(默认空)</label>
      <textarea id="ref2va-negprompt" rows="2" placeholder="例如:模糊,抖动,拖影,五官变形"></textarea>
    </details>
    <button class="submit" onclick="submitJob('ref2va')">提交</button>
    <button type="button" style="margin-top:12px;margin-left:8px;padding:10px 20px" onclick="clearForm('ref2va')">清空</button>
    <div class="err" id="ref2va-err"></div>
  </fieldset>
</div>

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

</div>

<script>
// server.py 渲染这个页面时会把这个占位符换成 BASE_PATH 环境变量(比如部署在共享域名的
// 子路径 /console 下时)。留空就是原来的行为,直接挂在域名根路径,局域网直连不受影响。
// 所有原本硬编码 "/xxx" 的绝对路径(fetch、pushState、下载/播放链接)都要在前面拼上它,
// 否则子路径部署时请求会打到域名根路径,而不是我们这个子路径。
const H3_BASE = "__H3_BASE_PATH__";

// 服务器加了 H3_CONSOLE_AUTH_TOKEN 时,/v1/* 接口要求 Authorization: Bearer <token>。
// 没设这个环境变量时 server.py 直接放行,这段代码在本地/局域网(没配token)环境下是空转,
// h3Token() 第一次调用才会真正弹 prompt。
function h3Token() {
  let t = localStorage.getItem('h3_console_token');
  if (t === null) {
    t = window.prompt('请输入 H3 访问令牌 (Access Token)') || '';
    localStorage.setItem('h3_console_token', t);
  }
  return t;
}
function h3FileUrl(path) {
  // <video src>/<a href download> 是浏览器原生请求,加不上 Authorization 头,
  // 只能把 token 拼进查询串——server.py 的 _require_token 两种都认。
  const t = h3Token();
  return t ? `${path}${path.includes('?') ? '&' : '?'}token=${encodeURIComponent(t)}` : path;
}
(function () {
  const origFetch = window.fetch.bind(window);
  window.fetch = async (input, opts = {}) => {
    const url = typeof input === 'string' ? input : input.url;
    if (url.startsWith(H3_BASE + '/v1/')) {
      const t = h3Token();
      if (t) opts = { ...opts, headers: { ...(opts.headers || {}), 'Authorization': 'Bearer ' + t } };
    }
    const r = await origFetch(input, opts);
    if (r.status === 401) {
      localStorage.removeItem('h3_console_token');
      alert('访问令牌无效,请刷新页面重新输入');
    }
    return r;
  };
})();

const uploaded = { 'fl2va-first': null, 'fl2va-last': null, 'ref2va-refs': [], 'ref2va-videos': [], 'ref2va-audios': [] };
let jobsCache = [];
let trashCache = [];
let viewingTrash = false;
let openMenuFor = null;

// 任务列表原来固定 limit=50,服务器上实测已经攒了 232 条未删除任务——超出的 182 条根本
//没请求回来,#job-list 的 overflow-y:auto 只能滚动已加载的这 50 条,看起来像"下拉到底
// 就没了"。改成滚到底部自动把 loadedLimit 加 50 再重新拉,直到某次返回条数小于请求的
// limit(说明已经拉到头,noMoreJobs=true,不用再滚)。search/status/kind/sort 每次改动
// 都把 loadedLimit 重置回 50 重新拉——过滤条件变了,"已经拉到第几页"这个状态就该归零。
let loadedLimit = 50;
let noMoreJobs = false;
let loadingMore = false;
let filterQ = '';
let filterStatus = '';
let filterKind = '';
let sortOrder = 'desc';

function resetPaging() { loadedLimit = 50; noMoreJobs = false; refreshJobs(); }

// URL 是 /task.html/<id> 或 /newtask.html(或裸 /,等同 newtask)——不是两个页面文件,
// server.py 里 /task.html/{tid} 和 /newtask.html 两条路由都返回这同一份 index.html,
// 这里只是从地址栏读出当前该显示哪个视图,方便复制链接分享、刷新页面不丢状态。
function tidFromPath() {
  let p = location.pathname;
  if (H3_BASE && p.startsWith(H3_BASE)) p = p.slice(H3_BASE.length);
  const m = p.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'));
});

let searchDebounce = null;
document.getElementById('job-search').addEventListener('input', e => {
  filterQ = e.target.value.trim();
  clearTimeout(searchDebounce);
  searchDebounce = setTimeout(resetPaging, 300);  // 防抖,不用每敲一个字就打一次请求
});
document.getElementById('job-status-filter').addEventListener('change', e => { filterStatus = e.target.value; resetPaging(); });
document.getElementById('job-kind-filter').addEventListener('change', e => { filterKind = e.target.value; resetPaging(); });
document.getElementById('job-sort-btn').addEventListener('click', e => {
  sortOrder = sortOrder === 'desc' ? 'asc' : 'desc';
  e.target.textContent = sortOrder === 'desc' ? '↓最新' : '↑最早';
  resetPaging();
});

// 滚到列表底部附近就自动加载下一页,不用额外放个"加载更多"按钮——viewingTrash/已经拉到头/
// 上一页还没回来这三种情况都不重复触发。
document.getElementById('job-list').addEventListener('scroll', e => {
  if (viewingTrash || noMoreJobs || loadingMore) return;
  const el = e.target;
  if (el.scrollTop + el.clientHeight < el.scrollHeight - 80) return;
  loadingMore = true;
  loadedLimit += 50;
  refreshJobs().finally(() => { loadingMore = false; });
});

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

// 2026-08-23:Raylight切到SAGE_FP16之后,4个分辨率各自排列组合实测过真实上限(见
// raylight/notes.md)。maxFrames 是每个分辨率最后一个确认能跑的帧数,跟 raylight/server.py
// 的 RESOLUTION_CEILINGS 保持一致——两边算法对不上就会出现"前端放行、后端拒绝"或反过来,
// 数字改动两边一起改。832×480/1024×576/1344×768 三个是真实CUDA OOM边界;448×256 技术上测到
// 3000帧都没OOM,1200帧(50秒)是画质边界(用户看过实际输出判定50秒往后不能看),不是显存边界。
// 2026-09-01:新建任务的默认档位改成竖屏 480×832 / 10s(243帧)/ Turbo关 / 20步——用户要求。
// 默认值统一走下面的 DEFAULT_RES / DEFAULT_DUR,列表顺序不再决定默认选项(初始化和"清空表单"
// 两处都读这两个常量,改一处就够)。Turbo 默认关在三个表单的 <select> 里写死(option selected),
// 20 步是 STEPS_BY_TURBO.false 的第一项,跟着 Turbo 联动自动选中。
// 2026-09-01:竖屏是宽高互换实现的,不是独立的横竖屏参数(生产已有 720×1280 提交案例,见
// docs/todo/h3-showcase-cases.md)。maxFrames 沿用对应横屏档位的实测值——宽高互换总像素数不变,
// 显存/耗时特征预期一致,但没有单独针对竖屏重新跑过 OOM 边界测试,如果发现竖屏更早 OOM 要单独下调。
const RESOLUTIONS = [
  { value: '1344x768', width: 1344, height: 768, label: '1344×768(官方默认分辨率,横屏)', maxFrames: 412 },
  { value: '768x1344', width: 768, height: 1344, label: '768×1344(官方默认分辨率,竖屏)', maxFrames: 412 },
  { value: '832x480', width: 832, height: 480, label: '832×480(标准档,横屏)', maxFrames: 1125 },
  { value: '480x832', width: 480, height: 832, label: '480×832(标准档,竖屏)', maxFrames: 1125 },
  { value: '448x256', width: 448, height: 256, label: '448×256(长时长档,横屏)', maxFrames: 1200 },
  { value: '256x448', width: 256, height: 448, label: '256×448(长时长档,竖屏)', maxFrames: 1200 },
  { value: '1024x576', width: 1024, height: 576, label: '1024×576(高清档,横屏)', maxFrames: 743 },
  { value: '576x1024', width: 576, height: 1024, label: '576×1024(高清档,竖屏)', maxFrames: 743 },
];
const DEFAULT_RES = '480x832';   // 竖屏标准档
const DEFAULT_DUR = '243';       // 10s @24fps
const DURATIONS = [
  { value: '124', frames: 124, label: '5s' },
  { value: '243', frames: 243, label: '10s' },
  { value: '362', frames: 362, label: '15s' },
  { value: '412', frames: 412, label: '17s(1344×768 实测上限)' },
  { value: '600', frames: 600, label: '25s' },
  { value: '743', frames: 743, label: '31s(1024×576 实测上限)' },
  { value: '900', frames: 900, label: '37.5s' },
  { value: '1125', frames: 1125, label: '47s(832×480 实测上限)' },
  { value: '1200', frames: 1200, label: '50s(448×256 画质上限,非显存上限)' },
];
// 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倍耗时)' }],
};

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 => d.frames <= res.maxFrames);
  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} 分辨率实测上限 ${res.maxFrames} 帧,${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); res.value = DEFAULT_RES; }
  if (dur) { fillSelect(dur, DURATIONS); dur.value = DEFAULT_DUR; }
  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(H3_BASE + '/v1/assets', { method: 'POST', body: fd });
  if (!r.ok) throw new Error(await r.text());
  return await r.json();
}

// 外部 URL 不经过 /v1/assets 转存,直接把地址原样交给后端——raylight 拿到 reference_image_urls
// 等字段里的 URL 就是 urllib.request.urlopen() 下载,本机 /v1/assets 生成的 URL 和外部 URL
// 对它没有区别。所以这里跳过上传,直接把用户粘贴的地址塞进 uploaded 状态。
// ponytail: 不校验 URL 是否可达/是图片——排队执行时后端下载失败才会报错,不在提交阶段拦截。
function addSingleUrl(key, inputId, renderFn, errBoxId) {
  const input = document.getElementById(inputId);
  const url = input.value.trim();
  if (!url) return;
  uploaded[key] = url;
  input.value = '';
  document.getElementById(errBoxId).textContent = '';
  renderFn();
}

function addArrayUrl(key, inputId, renderFn, errBoxId, cap) {
  const input = document.getElementById(inputId);
  const url = input.value.trim();
  if (!url) return;
  if (cap && uploaded[key].length >= cap) {
    document.getElementById(errBoxId).textContent = `最多${cap}个,已达上限`;
    return;
  }
  uploaded[key].push(url);
  input.value = '';
  document.getElementById(errBoxId).textContent = '';
  renderFn();
}

// server.py 把原始文件名塞进了存盘文件名里(<aid>__<原名>.ext),这里直接从 URL 反解出来
// 显示——不用单独维护一份 filename 状态,旧任务(改动前上传的,URL 里没有 __ 分段)会
// 退化成显示 uuid 文件名,不算错误,只是没有原名可用。
function filenameFromUrl(u) {
  try {
    const base = decodeURIComponent(u.split('/').pop().split('?')[0]);
    const m = base.match(/^[0-9a-f]{16}__(.+)$/);
    return m ? m[1] : base;
  } catch (e) { return u; }
}

// 每个预览项都包一层 .thumb-wrap,文件名 caption 放在最上面、媒体本体再包一层
// .thumb-media 挂 × 删除按钮——上传上去选错了/传多了,之前只能整个表单清空重来,
// 2026-08-24 用户要求能单个删;文件名是 2026-08-24 补的,之前只有个位置标签看不出传的是
// 哪个文件;2026-08-25 改成放图片上方(之前放下面,用户反馈不够显眼,容易当成没显示)。
function wrapWithDelete(mediaEl, onDelete, caption) {
  const wrap = document.createElement('span');
  wrap.className = 'thumb-wrap';
  if (caption) {
    const cap = document.createElement('span');
    cap.className = 'thumb-name'; cap.textContent = caption; cap.title = caption;
    wrap.appendChild(cap);
  }
  const mediaWrap = document.createElement('span');
  mediaWrap.className = 'thumb-media';
  const del = document.createElement('button');
  del.type = 'button'; del.className = 'thumb-del'; del.textContent = '×'; del.title = '删除';
  del.onclick = onDelete;
  mediaWrap.appendChild(mediaEl); mediaWrap.appendChild(del);
  wrap.appendChild(mediaWrap);
  return wrap;
}

function renderFl2vaThumbs() {
  const box = document.getElementById('fl2va-thumbs'); box.innerHTML = '';
  [['fl2va-first', '首帧'], ['fl2va-last', '尾帧']].forEach(([key, label]) => {
    const u = uploaded[key];
    if (!u) return;
    const img = document.createElement('img'); img.src = u; img.title = label;
    box.appendChild(wrapWithDelete(img, () => {
      uploaded[key] = null;
      document.getElementById(key).value = '';  // 清掉file input,不然重选同一个文件不会触发change
      renderFl2vaThumbs();
    }, `${label} · ${filenameFromUrl(u)}`));
  });
}

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;
    renderFl2vaThumbs();
  } catch (e) { document.getElementById('fl2va-err').textContent = '上传失败: ' + e.message; }
}

function renderRefThumbs() {
  const box = document.getElementById('ref2va-thumbs'); box.innerHTML = '';
  uploaded['ref2va-refs'].forEach((u, i) => {
    const img = document.createElement('img'); img.src = u;
    const label = `参考图${i+1}`; img.title = label;
    box.appendChild(wrapWithDelete(img, () => {
      uploaded['ref2va-refs'].splice(i, 1);
      renderRefThumbs();
    }, `${label} · ${filenameFromUrl(u)}`));
  });
}

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

// 参考视频/独立音频参考共用——不像参考图没有上限,这两个都封顶3个(跟节点协议一致),
// elId 里带 "video"/"audio" 判断放哪种播放器——跟生成结果的视频一样直接能播放预览。
function renderTags(elId, stateKey) {
  const box = document.getElementById(elId); box.innerHTML = '';
  const isVideo = elId.includes('video');
  uploaded[stateKey].forEach((u, i) => {
    const el = document.createElement(isVideo ? 'video' : 'audio');
    el.src = u; el.controls = true;
    const label = (isVideo ? '参考视频' : '参考音频') + (i + 1);
    el.title = label;
    box.appendChild(wrapWithDelete(el, () => {
      uploaded[stateKey].splice(i, 1);
      renderTags(elId, stateKey);
    }, `${label} · ${filenameFromUrl(u)}`));
  });
}

async function uploadMultiTagged(inputId, stateKey, tagsElId) {
  const el = document.getElementById(inputId);
  const errBox = document.getElementById('ref2va-err');
  for (const f of el.files) {
    if (uploaded[stateKey].length >= 3) { errBox.textContent = '最多3个,已达上限'; break; }
    try {
      const res = await uploadFile(f);
      uploaded[stateKey].push(res.url);
    } catch (e) { errBox.textContent = '上传失败: ' + e.message; }
  }
  renderTags(tagsElId, stateKey);
}

// 分辨率/时长/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;
  const out = {
    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,
  };
  // 留空就不放进请求体(不是传 null)——api.py 的 Optional 字段收到 None/缺失都当"不覆盖",
  // 但省略键更直观地对应"没填"。
  const cfgRaw = document.getElementById(prefix + '-cfg').value.trim();
  if (cfgRaw !== '') out.cfg_scale = +cfgRaw;
  const negRaw = document.getElementById(prefix + '-negprompt').value.trim();
  if (negRaw !== '') out.negative_prompt = negRaw;
  return out;
}

async function submitJob(kind) {
  const errBox = document.getElementById(kind + '-err'); errBox.textContent = '';
  if (resetting) { errBox.textContent = 'GPU正在重置,请等重置完成后再提交'; return; }
  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 && uploaded['ref2va-videos'].length === 0 && uploaded['ref2va-audios'].length === 0) {
      errBox.textContent = '请先上传至少一张参考图/一段参考视频/一个参考音频'; return;
    }
    body = {
      prompt: document.getElementById('ref2va-prompt').value,
      reference_image_urls: uploaded['ref2va-refs'],
      reference_video_urls: uploaded['ref2va-videos'],
      reference_audio_urls: uploaded['ref2va-audios'],
      ...readParamSelects('ref2va'),
    };
  }
  if (!body.prompt) { errBox.textContent = '请填写 prompt'; return; }
  try {
    const r = await fetch(H3_BASE + '/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; }
}

// 一键清空——2026-08-24 用户要求:重跑会把整个表单灌满,之前只能一个个手动清,没有回退路径。
// 直接恢复成 initParamSelects 那套默认值(DEFAULT_RES=480×832 竖屏、DEFAULT_DUR=10s、
// Turbo关/20步/seed=0),不是清空成空值——分辨率/时长/Turbo/步数这几个下拉框本来就不允许空选项。
function clearForm(kind) {
  if (!confirm('确定清空这个表单的所有内容?')) return;
  document.getElementById(kind + '-prompt').value = '';
  document.getElementById(kind + '-cfg').value = '';
  document.getElementById(kind + '-negprompt').value = '';
  document.getElementById(kind + '-res').value = DEFAULT_RES;
  syncDurOptions(kind);
  const durSel = document.getElementById(kind + '-dur');
  if ([...durSel.options].some(o => o.value === DEFAULT_DUR)) durSel.value = DEFAULT_DUR;
  const turboSel = document.getElementById(kind + '-turbo');
  turboSel.value = 'false';
  turboSel.onchange();  // 联动刷新步数选项
  document.getElementById(kind + '-seed').value = '0';
  document.getElementById(kind + '-err').textContent = '';

  if (kind === 'fl2va') {
    uploaded['fl2va-first'] = null; uploaded['fl2va-last'] = null;
    document.getElementById('fl2va-first').value = '';
    document.getElementById('fl2va-last').value = '';
    document.getElementById('fl2va-first-url').value = '';
    document.getElementById('fl2va-last-url').value = '';
    renderFl2vaThumbs();
  } else if (kind === 'ref2va') {
    uploaded['ref2va-refs'] = []; uploaded['ref2va-videos'] = []; uploaded['ref2va-audios'] = [];
    document.getElementById('ref2va-refs').value = '';
    document.getElementById('ref2va-videos-input').value = '';
    document.getElementById('ref2va-audios-input').value = '';
    document.getElementById('ref2va-refs-url').value = '';
    document.getElementById('ref2va-videos-url').value = '';
    document.getElementById('ref2va-audios-url').value = '';
    renderRefThumbs();
    renderTags('ref2va-video-tags', 'ref2va-videos');
    renderTags('ref2va-audio-tags', 'ref2va-audios');
  }
}

// 重跑:不直接提交,而是把这条任务当初的 req 灌回"新建任务"表单(对应的 tab、参数、
// 已上传的图片 URL 都原样带过去),跳到 /newtask.html,用户看一眼确认无误后自己点提交——
// 跟正常新建任务走的是同一条路径、同一次人工确认,不是绕过表单直接后台再发一次请求。
function prefillCreate(req) {
  const kind = (req.first_frame_url || req.last_frame_url) ? 'fl2va'
    : ((req.reference_image_urls || []).length || (req.reference_video_urls || []).length || (req.reference_audio_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);
  }

  document.getElementById(kind + '-cfg').value = req.cfg_scale != null ? req.cfg_scale : '';
  document.getElementById(kind + '-negprompt').value = req.negative_prompt || '';

  if (kind === 'fl2va') {
    uploaded['fl2va-first'] = req.first_frame_url || null;
    uploaded['fl2va-last'] = req.last_frame_url || null;
    renderFl2vaThumbs();
  } else if (kind === 'ref2va') {
    uploaded['ref2va-refs'] = (req.reference_image_urls || []).slice();
    uploaded['ref2va-videos'] = (req.reference_video_urls || []).slice();
    uploaded['ref2va-audios'] = (req.reference_audio_urls || []).slice();
    renderRefThumbs();
    renderTags('ref2va-video-tags', 'ref2va-videos');
    renderTags('ref2va-audio-tags', 'ref2va-audios');
  }

  showCreate();
}

async function rerunJob(id) {
  try {
    const r = await fetch(`${H3_BASE}/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); }
}

// 硬重启期间(停止运行中任务/重置显存)端口直接连不上,提交/轮询都会失败——用这个全局开关
// 锁住提交按钮,轮询/health直到真正恢复,不让用户在这段时间瞎点提交撞一堆报错。
let resetting = false;

function setResetting(on) {
  resetting = on;
  document.querySelectorAll('button.submit').forEach(b => {
    b.disabled = on;
    if (on) { b.dataset.origText = b.dataset.origText || b.textContent; b.textContent = '重置中…'; }
    else if (b.dataset.origText) { b.textContent = b.dataset.origText; }
  });
  const btn = document.getElementById('reset-gpu-btn');
  if (btn) btn.disabled = on;
}

async function waitForHealthy() {
  // 重启那几秒端口没监听,fetch会直接抛异常——这是预期中的过程,不是失败,一直重试到连上为止
  while (true) {
    await new Promise(res => setTimeout(res, 3000));
    try {
      const r = await fetch(H3_BASE + '/v1/backends');
      if (r.ok) { const d = await r.json(); if (d.ready >= d.total) return; }
    } catch (e) { /* 重启中,继续等 */ }
  }
}

async function cancelJob(id, running) {
  // running=true 时是"停止":Raylight的Ray子进程不理会ComfyUI的/interrupt,唯一能真正把
  // GPU收回来的办法是硬重启整个服务——所以要把这个代价明确告诉用户,不能假装是优雅停止。
  const msg = running
    ? '确定停止这条正在运行的任务?会硬重启整个服务来打断它(没有更温和的办法,Raylight的计算跑在独立进程里,收不到普通的打断信号),大约15-20秒后GPU恢复可用,重启期间无法提交新任务。'
    : '确定取消这条排队中的任务?';
  if (!confirm(msg)) return;
  try {
    const r = await fetch(`${H3_BASE}/v1/videos/${id}/cancel`, { method: 'POST' });
    if (!r.ok) throw new Error(await r.text());
    if (running) {
      setResetting(true);
      document.getElementById('backends').textContent = '⏳ 正在重置GPU,服务重启中,请稍候…';
      await waitForHealthy();
      setResetting(false);
      await refreshBackends();
    }
    await refreshDetail();
    await refreshJobs();
  } catch (e) { alert((running ? '停止' : '取消') + '失败: ' + e.message); }
}

async function resetGpu() {
  if (!confirm('确定重置GPU?会硬重启整个服务,打断当前正在运行的任务(如果有),大约15-20秒,重置完成前无法提交新任务。')) return;
  try {
    const r = await fetch(`${H3_BASE}/v1/admin/reset-gpu`, { method: 'POST' });
    if (!r.ok) throw new Error(await r.text());
  } catch (e) { alert('触发重置失败: ' + e.message); return; }
  setResetting(true);
  document.getElementById('backends').textContent = '⏳ 正在重置GPU,服务重启中,请稍候…';
  await waitForHealthy();
  setResetting(false);
  await refreshBackends();
  await refreshJobs();
}

function statusLabel(s) {
  const map = { queued: '排队中', running: '运行中', done: '已完成', failed: '失败', cancelled: '已取消' };
  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 = '';
  document.getElementById('sidebar-filters').style.display = viewingTrash ? 'none' : 'flex';
  // "+新建任务" 固定在筛选框上面、列表外面,不随 #job-list 滚动——之前是塞进 job-list 第一
  // 行的,列表一滚就跟着跑没了,2026-08-28 用户反馈要求固定住。
  const newTaskRow = document.getElementById('new-task-row');
  newTaskRow.style.display = viewingTrash ? 'none' : 'flex';
  newTaskRow.classList.toggle('selected', !viewingTrash && selectedId === null);

  if (viewingTrash) {
    const backRow = document.createElement('div');
    backRow.className = 'job-row new-row';
    backRow.onclick = () => backToList();
    backRow.innerHTML = `<span>←</span><span>返回任务列表</span>`;
    box.appendChild(backRow);

    if (!trashCache.length) {
      const empty = document.createElement('div');
      empty.style.cssText = 'padding:16px;font-size:13px;opacity:.6';
      empty.textContent = '回收站是空的';
      box.appendChild(empty);
    }
    trashCache.forEach(j => {
      const row = document.createElement('div');
      row.className = 'job-row';
      const prompt = j.req ? (j.req.prompt || '(无 prompt)') : '';
      row.innerHTML = `
        <div class="jr-top"><span>${j.id}</span>
          <button class="jr-restore" onclick="event.stopPropagation(); restoreJob('${j.id}')">恢复</button></div>
        <div class="jr-prompt" title="${prompt}">${prompt}</div>
        <div class="jr-time">删除于 ${timeAgo(j.deleted_at)}</div>`;
      box.appendChild(row);
    });
    return;
  }

  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)') : '';
    const menuOpen = openMenuFor === j.id;
    row.innerHTML = `
      <div class="jr-top"><span>${j.id}</span>
        <div class="jr-actions">
          ${statusLabel(j.status)}
          <span class="jr-menu-btn" onclick="event.stopPropagation(); toggleJobMenu('${j.id}')">⋯</span>
        </div>
      </div>
      <div class="jr-prompt" title="${prompt}">${prompt}</div>
      <div class="jr-time">${timeAgo(j.created_at)}</div>
      ${menuOpen ? `<div class="jr-menu" onclick="event.stopPropagation()">
        ${j.status === 'queued' ? `<div class="jr-menu-item" onclick="prioritizeJob('${j.id}')">优先插队</div>` : ''}
        <div class="jr-menu-item" onclick="deleteJob('${j.id}')">删除</div>
      </div>` : ''}`;
    box.appendChild(row);
  });

  if (jobsCache.length) {
    const footer = document.createElement('div');
    footer.id = 'job-list-footer';
    footer.textContent = noMoreJobs ? '— 没有更多了 —' : '下拉加载更多…';
    box.appendChild(footer);
  } else if (filterQ || filterStatus || filterKind) {
    const empty = document.createElement('div');
    empty.style.cssText = 'padding:16px;font-size:13px;opacity:.6';
    empty.textContent = '没有匹配的任务';
    box.appendChild(empty);
  }
}

// 任意点击落在某条任务的「⋯」菜单外面,就把菜单收起来——不然点开一个菜单后点别处它会一直挂着
document.addEventListener('click', () => { if (openMenuFor !== null) { openMenuFor = null; renderSidebar(); } });

function toggleJobMenu(id) {
  openMenuFor = (openMenuFor === id) ? null : id;
  renderSidebar();
}

async function prioritizeJob(id) {
  openMenuFor = null;
  try {
    const r = await fetch(`${H3_BASE}/v1/videos/${id}/prioritize`, { method: 'POST' });
    if (!r.ok) throw new Error(await r.text());
    const job = await r.json();
    alert(`已插队到第 ${job.queue_position} 位`);
    await refreshJobs();
    if (selectedId === id) await refreshDetail();
  } catch (e) { alert('插队失败: ' + e.message); }
}

async function deleteJob(id) {
  openMenuFor = null;
  try {
    const r = await fetch(`${H3_BASE}/v1/videos/${id}`, { method: 'DELETE' });
    if (!r.ok) throw new Error(await r.text());
    jobsCache = jobsCache.filter(j => j.id !== id);
    if (selectedId === id) showCreate();
    renderSidebar();
  } catch (e) { alert('删除失败: ' + e.message); }
}

async function restoreJob(id) {
  try {
    const r = await fetch(`${H3_BASE}/v1/videos/${id}/restore`, { method: 'POST' });
    if (!r.ok) throw new Error(await r.text());
    trashCache = trashCache.filter(j => j.id !== id);
    renderSidebar();
  } catch (e) { alert('恢复失败: ' + e.message); }
}

async function loadTrash() {
  try {
    const r = await fetch(H3_BASE + '/v1/videos?trash=true&limit=50');
    trashCache = (await r.json()).jobs || [];
  } catch (e) { /* 下一轮轮询再试 */ }
}

async function toggleTrash() {
  viewingTrash = true;
  await loadTrash();
  renderSidebar();
}

function backToList() {
  viewingTrash = false;
  refreshJobs();  // 立即拉一次主列表,不用等下一轮 5 秒轮询
  renderSidebar();
}

async function selectJob(id, pushUrl = true) {
  selectedId = id;
  if (pushUrl) history.pushState(null, '', H3_BASE + '/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(`${H3_BASE}/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="${h3FileUrl(H3_BASE + '/v1/videos/' + j.id + '/file')}"></video>
        <a class="download" href="${h3FileUrl(H3_BASE + '/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 if (j.status === 'cancelled') {
      resultHtml = `<div class="err">${(j.error || '已取消').replace(/</g,'&lt;')}</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]));
    // 图片点开看大图,参考视频/音频跟生成结果的视频一样用原生播放器直接预览;每个媒体上面
    // 带一行文件名(从上传时 server.py 塞进 URL 里的原名反解出来,见 filenameFromUrl——
    // 引用外部图床的旧任务URL里没有这个原名分段,会退化成显示URL里的原始文件名/hash,
    // 不算错误,只是没有更好的名字可用)。2026-08-25:caption 挪到图片上方(之前在下面,
    // 用户反馈不够显眼)。
    const thumbCap = (label, u) => `${label} · ${filenameFromUrl(u)}`.replace(/</g, '&lt;');
    const viewThumb = (mediaHtml, label, u) =>
      `<span class="thumb-wrap"><span class="thumb-name" title="${thumbCap(label,u)}">${thumbCap(label,u)}</span><span class="thumb-media">${mediaHtml}</span></span>`;
    const imgTags = imgs.map(([label, u]) =>
      viewThumb(`<a href="${u}" target="_blank" title="${label},点击查看大图"><img src="${u}" title="${label}"></a>`, label, u)).join('');
    const videoTags = (req.reference_video_urls || []).map((u, i) =>
      viewThumb(`<video controls src="${u}" title="参考视频${i+1}"></video>`, '参考视频'+(i+1), u)).join('');
    const audioTags = (req.reference_audio_urls || []).map((u, i) =>
      viewThumb(`<audio controls src="${u}" title="参考音频${i+1}"></audio>`, '参考音频'+(i+1), u)).join('');
    if (imgTags || videoTags) refThumbs += `<div class="thumbrow">${imgTags}${videoTags}</div>`;
    if (audioTags) refThumbs += `<div class="thumbrow">${audioTags}</div>`;

    box.innerHTML = `
      <div class="back" onclick="showCreate()">← 新建任务</div>
      <h2>${j.id}</h2>
      <div>${statusLabel(j.status)}${j.status === 'queued' && j.queue_position ? ` <span style="opacity:.7;font-size:13px">排第 ${j.queue_position} 位</span>` : ''} <button class="submit" style="padding:4px 12px;margin-left:8px" onclick="rerunJob('${j.id}')">重跑</button>${j.status === 'queued' ? ` <button style="padding:4px 12px;margin-left:8px" onclick="prioritizeJob('${j.id}')">优先插队</button> <button style="padding:4px 12px;margin-left:8px" onclick="cancelJob('${j.id}',false)">取消</button>` : ''}${j.status === 'running' ? ` <button style="padding:4px 12px;margin-left:8px;color:#c33" onclick="cancelJob('${j.id}',true)">停止</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>时长</dt><dd>${req.frames ? (req.frames / 24).toFixed(1) + ' 秒(按 24fps 折算)' : '?'}</dd>
        <dt>Turbo/步数</dt><dd>${req.turbo === false ? '关' : '开'} / ${req.steps ?? '?'} 步,seed=${req.seed ?? 0}</dd>
        ${req.cfg_scale != null ? `<dt>CFG Scale</dt><dd>${req.cfg_scale}</dd>` : ''}
        ${req.negative_prompt ? `<dt>负面提示词</dt><dd>${req.negative_prompt.replace(/</g,'&lt;')}</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>
        ${(j.started_at && j.finished_at) ? `<dt>生成耗时</dt><dd>${(j.finished_at - j.started_at).toFixed(1)} 秒</dd>` : ''}
        <dt>峰值显存</dt><dd>${j.peak_vram_gb ? j.peak_vram_gb + ' GB' : '—'}</dd>
      </dl>
      ${refThumbs}
      ${resultHtml}
    `;
  } catch (e) { /* 暂时连不上,保留当前显示,下一轮再试 */ }
}

async function refreshJobs() {
  if (viewingTrash) { await loadTrash(); renderSidebar(); return; }
  try {
    const params = new URLSearchParams({ limit: String(loadedLimit), sort: sortOrder });
    if (filterQ) params.set('q', filterQ);
    if (filterStatus) params.set('status', filterStatus);
    if (filterKind) params.set('kind', filterKind);
    const r = await fetch(`${H3_BASE}/v1/videos?${params}`); const d = await r.json();
    jobsCache = d.jobs || [];
    noMoreJobs = jobsCache.length < loadedLimit;
    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(H3_BASE + '/v1/backends'); const d = await r.json();
    let text =
      `后端: ${d.ready}/${d.total} ready · 排队 ${d.queued} · 运行中 ${d.running}\n` +
      d.backends.map(b => {
        // b.status 只是模型健康态(ok/down),不代表这张卡是否正在跑任务——
        // running/queued 是 api.py /health 里单独的计数字段,之前没往界面上带,
        // 导致明明有任务在跑却只显示 "ok",看着像空闲。
        const busy = b.running > 0 ? ` running×${b.running}` : (b.queued > 0 ? ` queued×${b.queued}` : '');
        return `${b.backend.replace('http://127.0.0.1:','')} gpu${b.gpu} [${b.partition||'?'}] ${b.status}${busy}`;
      }).join('\n');
    // 2026-08-24:实时显存/利用率——之前撞过好几次OOM,事后查才发现是别的工作负载(比如旧
    // minimax-h3 四卡worker)在偷偷占显存,提交前完全看不出来。>18GB(跟22.5GB总量比,剩不到
    // 4GB)标红提醒可能会OOM。
    if ((d.gpus || []).length) {
      text += '\n' + d.gpus.map(g => {
        const pct = Math.round(g.memory_used_mb / g.memory_total_mb * 100);
        const warn = g.memory_used_mb > 18000 ? ' ⚠' : '';
        return `GPU${g.index}: ${(g.memory_used_mb/1024).toFixed(1)}/${(g.memory_total_mb/1024).toFixed(1)}GB (${pct}%) ${g.utilization_pct}%util${warn}`;
      }).join('\n');
    }
    document.getElementById('backends').textContent = text;
  } 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>