☰

CamVault Auto Resume Assistant

Automatically resumes paused models with a simple dashboard and progress tracker.

您需要先安裝使用者腳本管理器擴展,如 Tampermonkey、Greasemonkey 或 Violentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey 或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Violentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 Tampermonkey或 Userscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         CamVault Auto Resume Assistant
// @author       Azzanno8
// @license      Copyright Azzanno8
// @namespace    cvault-tools
// @version      1.3
// @description  Automatically resumes paused models with a simple dashboard and progress tracker.
// @match        https://camvault.to/premium/ondemand*
// @match        https://www.camvault.to/premium/ondemand*
// @match        https://camvault.xyz/premium/ondemand*
// @match        https://www.camvault.xyz/premium/ondemand*
// @icon         https://www.google.com/s2/favicons?sz=32&domain=camvault.to
// @icon64       https://www.google.com/s2/favicons?sz=64&domain=camvault.to
// @run-at       document-idle
// @grant        none
//
// ==/UserScript==

(function () {
  "use strict";

  const STATE_KEY = "cv_resume_dashboard_v36";
  const UI_KEY = "cv_resume_dashboard_ui_v1";
  ["cv_resume_dashboard_v34", "cv_resume_dashboard_v35"].forEach((key) => {
    sessionStorage.removeItem(key);
  });

  const CONFIG = {
    betweenActionMs: 900,
    afterPageMs: 1800,
    maxStagnantFullScans: 2,
    loaderPollMs: 150,
    loaderMaxWaitMs: 15000,
    burstSize: 0,
    burstStaggerMs: 40,
    maxEmptyBursts: 2
  };

  const state = Object.assign(
    {
      running: false,
      pendingStartAfterRefresh: false,
      resumedTotal: 0,
      resumedCurrentPage: 0,
      initialPaused: null,
      startedAt: null,
      lastKnownPaused: null,
      stagnantFullScans: 0,
      resumedModels: []
    },
    JSON.parse(sessionStorage.getItem(STATE_KEY) || "{}")
  );
  if (!Array.isArray(state.resumedModels)) state.resumedModels = [];

  const uiState = Object.assign(
    { collapsed: false, collapsedPlatforms: {} },
    JSON.parse(sessionStorage.getItem(UI_KEY) || "{}")
  );
  if (!uiState.collapsedPlatforms || typeof uiState.collapsedPlatforms !== "object") {
    uiState.collapsedPlatforms = {};
  }

  function startRunFromCurrentPage() {
    const pausedAtStart = currentPausedGlobal() || getRows().filter(isPausedRow).length;
    state.running = true;
    state.resumedTotal = 0;
    state.resumedCurrentPage = 0;
    state.initialPaused = pausedAtStart;
    state.startedAt = Date.now();
    state.lastKnownPaused = pausedAtStart;
    state.stagnantFullScans = 0;
    state.resumedModels = [];
    state.pendingStartAfterRefresh = false;

    saveState();
    if (!isSortedPageOne()) {
      updateUI("Sorting paused models to the top...");
      location.href = sortedPageOneHref();
      return;
    }

    updateUI("Started. I'll resume paused models for you.");
    runLoop();
  }

  function saveState() {
    sessionStorage.setItem(STATE_KEY, JSON.stringify(state));
  }

  function saveUiState() {
    sessionStorage.setItem(UI_KEY, JSON.stringify(uiState));
  }

  function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms));
  }

  function isGlobalLoaderVisible() {
    const loader = document.querySelector("#global-loader");
    if (!loader) return false;
    const style = window.getComputedStyle(loader);
    return style.display !== "none" && style.visibility !== "hidden" && parseFloat(style.opacity || "1") > 0;
  }

  async function waitForLoaderToHide(maxWaitMs = CONFIG.loaderMaxWaitMs) {
    const start = Date.now();
    while (state.running && isGlobalLoaderVisible()) {
      if (Date.now() - start >= maxWaitMs) {
        updateUI("Site is taking longer than expected. Continuing anyway...");
        return false;
      }
      await sleep(CONFIG.loaderPollMs);
    }
    return true;
  }

  function parseIntSafe(txt) {
    const m = String(txt || "").match(/\d+/);
    return m ? parseInt(m[0], 10) : 0;
  }

  function getRows() {
    return Array.from(document.querySelectorAll("tr.model-entry"));
  }

  function isPausedRow(row) {
    const status = row.querySelector(".recording-status");
    if (!status) return false;
    return /PAUSED/i.test((status.textContent || "").trim());
  }

  function getModelLink(row) {
    return row.querySelector("td a");
  }

  const KNOWN_PLATFORMS = [
    "stripchat",
    "chaturbate",
    "cam4",
    "bongacams",
    "myfreecams",
    "camsoda",
    "flirt4free",
    "livejasmin",
    "streamate",
    "jerkmate",
    "adultwork",
    "xlovecam"
  ];

  function escapeRe(s) {
    return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }

  function isGluedToName(haystack, platform) {
    if (!platform) return false;
    return new RegExp(`[A-Za-z0-9._]@${escapeRe(platform)}\\b`, "i").test(haystack);
  }

  function pickPlatform(haystack) {
    const text = String(haystack || "").replace(/\s+/g, " ").trim();
    const all = [...text.matchAll(/@\s*([A-Za-z][A-Za-z0-9._-]*)/g)].map((m) => m[1]);
    const candidates = all.filter((p) => !isGluedToName(text, p));
    const known = [...candidates].reverse().find((p) => KNOWN_PLATFORMS.includes(p.toLowerCase()));
    return known || candidates[candidates.length - 1] || "";
  }

  function getModelName(row) {
    const a = getModelLink(row);
    let name = a ? a.textContent.trim().replace(/\s+/g, " ") : "Unknown model";
    name = name.replace(/\s+@\s*[A-Za-z][A-Za-z0-9._-]*\s*$/, "").trim() || name;
    return name || "Unknown model";
  }

  function getModelPlatform(row) {
    const a = getModelLink(row);
    const cell = a ? a.closest("td") : row.querySelector("td");
    if (!cell) return "";
    return pickPlatform(cell.textContent);
  }

  function getModelHref(row) {
    const a = getModelLink(row);
    return a ? (a.getAttribute("href") || "").trim() : "";
  }

  function getModelId(row) {
    return getModelHref(row) || getModelName(row);
  }

  function getModelInfo(row) {
    return {
      id: getModelId(row),
      name: getModelName(row),
      platform: getModelPlatform(row),
      href: getModelHref(row)
    };
  }

  function modelHref(m) {
    if (m && m.href) return m.href;
    const id = (m && m.id) || "";
    const base = id.includes("@@") ? id.slice(0, id.indexOf("@@")) : id;
    if (/^https?:\/\//i.test(base) || base.startsWith("/")) return base;
    return "";
  }

  function hrefPath(href) {
    const raw = String(href || "").trim();
    if (!raw) return "";
    try {
      return new URL(raw, location.origin).pathname.replace(/\/+$/, "");
    } catch (e) {
      return raw.replace(/\/+$/, "");
    }
  }

  function pausedModelMap(rows) {
    const map = new Map();
    for (const row of rows) {
      const info = getModelInfo(row);
      map.set(info.id, info);
    }
    return map;
  }

  function rememberResumed(models) {
    if (!Array.isArray(state.resumedModels)) state.resumedModels = [];
    const seen = new Set(state.resumedModels.map((m) => m.id));
    for (const m of models) {
      if (!m || !m.id || seen.has(m.id)) continue;
      seen.add(m.id);
      state.resumedModels.push({
        id: m.id,
        name: m.name || m.id,
        platform: m.platform || "",
        href: m.href || ""
      });
    }
  }

  function isOnPageOne() {
    const active = document.querySelector(".pagination li.active a");
    return !!active && active.textContent.trim() === "1";
  }

  function getPageOneLink() {
    const links = Array.from(document.querySelectorAll(".pagination a[href]"));
    const first = links.find((a) => {
      const href = a.getAttribute("href") || "";
      return /\/premium\/ondemand(?:\/|$)/.test(href) && !/page:\d+/.test(href);
    });
    return first ? first.getAttribute("href") : "/premium/ondemand";
  }

  function pathOnly(href) {
    try {
      return new URL(href, location.origin).pathname;
    } catch (e) {
      return String(href || "");
    }
  }

  function stripListParams(pathname) {
    return String(pathname || "")
      .replace(/\/page:\d+(?=\/|$)/g, "")
      .replace(/\/sort:[^/]+(?=\/|$)/g, "")
      .replace(/\/direction:[^/]+(?=\/|$)/g, "")
      .replace(/\/+$/, "") || "/premium/ondemand";
  }

  function baseListPath() {
    return stripListParams(pathOnly(getPageOneLink()));
  }

  function sortedPageOneHref() {
    return baseListPath() + "/sort:state/direction:desc";
  }

  function unsortedPageOneHref() {
    return baseListPath();
  }

  function isSortedPageOne() {
    return isOnPageOne() && /\/sort:state\/direction:desc\/?$/.test(location.pathname);
  }

  function isUnsortedList() {
    return isOnPageOne() && !/\/sort:|\/direction:/.test(location.pathname);
  }

  function dispatchRealClick(el) {
    ["mouseover", "mousedown", "mouseup", "click"].forEach((type) => {
      el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
    });
  }

  function readPausedFromSummary() {
    const well = document.querySelector(".well");
    if (!well) return null;

    const blocks = Array.from(well.querySelectorAll("div[class*='col-']"));
    for (const b of blocks) {
      const text = (b.textContent || "").replace(/\s+/g, " ").trim();
      if (/paused/i.test(text)) {
        const strong = b.querySelector("strong");
        const val = strong ? parseIntSafe(strong.textContent) : parseIntSafe(text);
        if (Number.isFinite(val)) return val;
      }
    }
    return null;
  }

  function currentPausedGlobal() {
    const summaryVal = readPausedFromSummary();
    if (summaryVal != null) {
      state.lastKnownPaused = summaryVal;
      return summaryVal;
    }

    if (state.lastKnownPaused != null) return state.lastKnownPaused;
    if (state.initialPaused != null) return Math.max(0, state.initialPaused - state.resumedTotal);
    return null;
  }

  const style = document.createElement("style");
  style.textContent = `
    @keyframes cvPanelIn {
      from { opacity: 0; transform: translateY(8px); }
      to { opacity: 1; transform: translateY(0); }
    }
    @keyframes cvPulseBorder {
      0%, 100% { box-shadow: 0 0 0 rgba(196, 0, 0, 0); }
      50% { box-shadow: 0 0 14px rgba(196, 0, 0, 0.28); }
    }
    #cv-resume-panel{
      position:fixed; right:16px; bottom:16px; z-index:999999;
      width:340px; max-width:calc(100vw - 20px);
      color:#f5f5f5;
      background:linear-gradient(155deg,#0e0e10,#1a1a1f 55%, #111216);
      border:1px solid rgba(196,0,0,.6); border-radius:14px;
      box-shadow:0 14px 36px rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.06);
      font-family:Mulish,Segoe UI,Arial,sans-serif;
      overflow:hidden;
      animation:cvPanelIn .28s ease-out;
    }
    #cv-resume-panel .cv-head{
      display:flex; align-items:center; justify-content:space-between;
      padding:10px 12px;
      background:linear-gradient(180deg,#d50000,#970000);
      border-bottom:1px solid rgba(0,0,0,.45);
    }
    #cv-resume-panel .cv-title{
      font-weight:800; font-size:14px; color:#fff; letter-spacing:.2px;
      text-shadow:0 1px 2px rgba(0,0,0,.45);
    }
    #cv-resume-panel .cv-toggle{
      border:1px solid rgba(255,255,255,.35); background:rgba(0,0,0,.18);
      color:#fff; border-radius:8px; width:28px; height:28px; cursor:pointer; font-weight:800;
      transition:transform .22s ease, background-color .2s ease, border-color .2s ease;
      transform:rotate(0deg) scale(1);
    }
    #cv-resume-panel .cv-toggle:hover{
      background:rgba(0,0,0,.28);
      border-color:rgba(255,255,255,.5);
      transform:scale(1.06);
    }
    #cv-resume-panel.collapsed .cv-toggle{
      transform:rotate(90deg) scale(1);
    }
    #cv-resume-panel .cv-body{padding:12px;}
    #cv-resume-panel .cv-body{
      transform-origin: top;
      transition: opacity .22s ease, transform .22s ease, max-height .24s ease, padding .22s ease;
      opacity:1;
      max-height:520px;
    }
    #cv-resume-panel .cv-grid{display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-bottom:10px;}
    #cv-resume-panel .cv-card{
      background:linear-gradient(180deg,rgba(255,255,255,.04),rgba(255,255,255,.015));
      border:1px solid rgba(255,255,255,.12);
      border-radius:10px; padding:8px 10px;
    }
    #cv-resume-panel .cv-k{font-size:11px; opacity:.85; color:#c8c8c8;}
    #cv-resume-panel .cv-v{font-size:18px; font-weight:800; line-height:1.2;}
    #cv-resume-panel .cv-progress-wrap{
      margin:10px 0 8px; background:rgba(0,0,0,.34); border-radius:999px; overflow:hidden; height:12px;
      border:1px solid rgba(255,255,255,.14);
    }
    #cv-resume-panel .cv-progress{
      height:100%; width:0%;
      background:linear-gradient(90deg,#a90000,#e00000 45%, #ff2b2b);
      transition:width .35s ease;
    }
    #cv-resume-panel .cv-sub{font-size:12px; opacity:.9; margin-bottom:10px;}
    #cv-resume-panel .cv-summary{
      display:block; width:100%; margin:0 0 10px; padding:0;
      border:0; background:transparent; text-align:left; font-family:inherit;
      font-size:12px; font-weight:700; color:#ffb4b4; text-decoration:underline; cursor:pointer;
    }
    #cv-resume-panel .cv-summary:hover{ color:#fff; }
    #cv-resume-panel .cv-summary.is-empty{
      color:#888; text-decoration:none; pointer-events:none; cursor:default; font-weight:600;
    }
    #cv-summary-modal{
      position:fixed; inset:0; z-index:1000000;
      display:flex; align-items:center; justify-content:center; padding:16px;
    }
    #cv-summary-modal[hidden]{ display:none !important; }
    #cv-summary-modal .cv-modal-backdrop{
      position:absolute; inset:0; background:rgba(0,0,0,.62);
    }
    #cv-summary-modal .cv-modal-card{
      position:relative; z-index:1; width:min(420px, 100%); max-height:min(72vh, 560px);
      display:flex; flex-direction:column; color:#f5f5f5; overflow:hidden;
      background:linear-gradient(155deg,#0e0e10,#1a1a1f 55%, #111216);
      border:1px solid rgba(196,0,0,.6); border-radius:14px;
      box-shadow:0 18px 44px rgba(0,0,0,.55);
      font-family:Mulish,Segoe UI,Arial,sans-serif;
    }
    #cv-summary-modal .cv-modal-head{
      display:flex; align-items:center; justify-content:space-between; padding:10px 12px;
      background:linear-gradient(180deg,#d50000,#970000);
    }
    #cv-summary-modal .cv-modal-title{ font-weight:800; font-size:14px; color:#fff; }
    #cv-summary-modal .cv-modal-close{
      border:1px solid rgba(255,255,255,.35); background:rgba(0,0,0,.18);
      color:#fff; border-radius:8px; width:28px; height:28px; cursor:pointer; font-weight:800;
    }
    #cv-summary-modal .cv-modal-meta{ padding:10px 12px 6px; font-size:12px; opacity:.85; }
    #cv-summary-modal .cv-modal-list{
      margin:0; padding:4px 12px 12px; overflow:auto; font-size:13px; line-height:1.45;
      flex:1 1 auto; min-height:0;
    }
    #cv-summary-modal .cv-platform-group{
      margin:0 0 8px;
      border:1px solid rgba(255,255,255,.12);
      border-radius:10px;
      background:rgba(255,255,255,.03);
    }
    #cv-summary-modal .cv-platform-group summary{
      display:flex; align-items:center; justify-content:space-between; gap:8px;
      padding:8px 10px; cursor:pointer; font-weight:800; font-size:13px;
      list-style:none; user-select:none; -webkit-user-select:none;
    }
    #cv-summary-modal .cv-platform-group summary::-webkit-details-marker{ display:none; }
    #cv-summary-modal .cv-platform-group summary::marker{ content:""; }
    #cv-summary-modal .cv-platform-title{
      display:flex; align-items:center; gap:8px; min-width:0;
    }
    #cv-summary-modal .cv-platform-chevron{
      display:inline-block; width:0; height:0;
      border-left:5px solid transparent; border-right:5px solid transparent;
      border-top:6px solid #ffb4b4;
      transform:rotate(-90deg);
      transition:transform .16s ease;
      flex:0 0 auto;
    }
    #cv-summary-modal .cv-platform-group[open] .cv-platform-chevron{
      transform:rotate(0deg);
    }
    #cv-summary-modal .cv-platform-count{
      opacity:.72; font-weight:700; font-size:12px; flex:0 0 auto;
    }
    #cv-summary-modal .cv-platform-models{
      margin:0; padding:0 10px 8px 28px;
    }
    #cv-summary-modal .cv-platform-models li{
      margin:0 0 4px;
      user-select:none;
      -webkit-user-select:none;
    }
    #cv-summary-modal .cv-modal-link{
      color:#ffb4b4; text-decoration:none; font-weight:700;
      cursor:pointer;
      user-select:none;
      -webkit-user-select:none;
    }
    #cv-summary-modal .cv-modal-link:hover{
      color:#fff; text-decoration:underline;
    }
    #cv-resume-panel .cv-actions{display:flex; gap:8px;}
    #cv-resume-panel .cv-btn{
      flex:1; border:0; border-radius:10px; padding:9px 10px; cursor:pointer; font-weight:700;
      transition: transform .16s ease, box-shadow .2s ease, filter .2s ease, opacity .2s ease;
      transform: translateY(0);
    }
    #cv-resume-panel .cv-btn:hover{
      transform: translateY(-1px);
      filter: brightness(1.06);
    }
    #cv-resume-panel .cv-btn:active{
      transform: translateY(1px) scale(.99);
      filter: brightness(.98);
    }
    #cv-toggle{
      background:linear-gradient(180deg,#e10000,#b30000);
      color:#fff;
      box-shadow:0 2px 8px rgba(196,0,0,.35);
    }
    #cv-toggle:hover{
      box-shadow:0 5px 14px rgba(196,0,0,.38);
    }
    #cv-toggle.is-stop{
      background:linear-gradient(180deg,#ff3939,#cf0000);
      color:#fff;
      animation:cvPulseBorder 1.6s ease-in-out infinite;
    }
    #cv-reset{
      background:linear-gradient(180deg,#444b55,#2f353d);
      color:#f8fafc;
    }
    #cv-reset:hover{
      box-shadow:0 4px 10px rgba(0,0,0,.28);
    }
    #cv-resume-panel .cv-log{margin-top:10px; font-size:12px; opacity:.85; min-height:16px;}
    #cv-resume-panel.collapsed .cv-body{
      opacity:0;
      transform:scaleY(.97);
      max-height:0;
      padding-top:0;
      padding-bottom:0;
      overflow:hidden;
      pointer-events:none;
    }
  `;
  document.head.appendChild(style);

  const panel = document.createElement("div");
  panel.id = "cv-resume-panel";
  panel.innerHTML = `
    <div class="cv-head">
      <div class="cv-title">Auto Resume Helper</div>
      <button id="cv-collapse" class="cv-toggle" type="button">−</button>
    </div>
    <div class="cv-body">
      <div class="cv-grid">
        <div class="cv-card"><div class="cv-k">Paused Models</div><div id="cv-paused" class="cv-v">-</div></div>
        <div class="cv-card"><div class="cv-k">Models Resumed</div><div id="cv-resumed" class="cv-v">0</div></div>
        <div class="cv-card"><div class="cv-k">Paused on This Page</div><div id="cv-page" class="cv-v">0</div></div>
        <div class="cv-card"><div class="cv-k">Current Status</div><div id="cv-status" class="cv-v">Idle</div></div>
      </div>
      <div class="cv-progress-wrap"><div id="cv-progress" class="cv-progress"></div></div>
      <div id="cv-sub" class="cv-sub">Overall progress: 0%</div>
      <button id="cv-summary" class="cv-summary is-empty" type="button">No summary yet</button>
      <div class="cv-actions">
        <button id="cv-toggle" class="cv-btn" type="button">Start</button>
        <button id="cv-reset" class="cv-btn" type="button">Reset</button>
      </div>
      <div id="cv-log" class="cv-log"></div>
    </div>
  `;
  document.body.appendChild(panel);

  const modal = document.createElement("div");
  modal.id = "cv-summary-modal";
  modal.hidden = true;
  modal.innerHTML = `
    <div class="cv-modal-backdrop"></div>
    <div class="cv-modal-card" role="dialog" aria-modal="true" aria-labelledby="cv-modal-title">
      <div class="cv-modal-head">
        <div id="cv-modal-title" class="cv-modal-title">Resumed models</div>
        <button id="cv-modal-close" class="cv-modal-close" type="button" title="Close">×</button>
      </div>
      <div id="cv-modal-meta" class="cv-modal-meta"></div>
      <div id="cv-modal-list" class="cv-modal-list"></div>
    </div>
  `;
  document.body.appendChild(modal);

  const el = {
    paused: panel.querySelector("#cv-paused"),
    resumed: panel.querySelector("#cv-resumed"),
    page: panel.querySelector("#cv-page"),
    status: panel.querySelector("#cv-status"),
    progress: panel.querySelector("#cv-progress"),
    sub: panel.querySelector("#cv-sub"),
    log: panel.querySelector("#cv-log"),
    toggle: panel.querySelector("#cv-toggle"),
    reset: panel.querySelector("#cv-reset"),
    collapse: panel.querySelector("#cv-collapse"),
    summary: panel.querySelector("#cv-summary"),
    modal,
    modalMeta: modal.querySelector("#cv-modal-meta"),
    modalList: modal.querySelector("#cv-modal-list"),
    modalClose: modal.querySelector("#cv-modal-close"),
    modalBackdrop: modal.querySelector(".cv-modal-backdrop")
  };

  function applyCollapsed() {
    panel.classList.toggle("collapsed", !!uiState.collapsed);
    el.collapse.textContent = uiState.collapsed ? "+" : "−";
    el.collapse.title = uiState.collapsed ? "Expand" : "Collapse";
    el.collapse.animate(
      [
        { transform: uiState.collapsed ? "rotate(0deg) scale(0.88)" : "rotate(90deg) scale(0.88)", opacity: 0.7 },
        { transform: uiState.collapsed ? "rotate(90deg) scale(1)" : "rotate(0deg) scale(1)", opacity: 1 }
      ],
      { duration: 180, easing: "ease-out" }
    );
  }

  el.collapse.addEventListener("click", () => {
    uiState.collapsed = !uiState.collapsed;
    saveUiState();
    applyCollapsed();
  });

  el.summary.addEventListener("click", openSummaryModal);
  el.modalClose.addEventListener("click", closeSummaryModal);
  el.modalBackdrop.addEventListener("click", closeSummaryModal);
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && !el.modal.hidden) closeSummaryModal();
  });

  function updateUI(message) {
    const pausedGlobal = currentPausedGlobal();
    const pausedPage = getRows().filter(isPausedRow).length;

    el.paused.textContent = pausedGlobal == null ? "-" : String(pausedGlobal);
    el.resumed.textContent = String(state.resumedTotal || 0);
    el.page.textContent = String(pausedPage);
    el.status.textContent = state.running ? "Running" : "Idle";

    let pct = 0;
    if (state.initialPaused && state.initialPaused > 0) {
      pct = Math.round((state.resumedTotal / state.initialPaused) * 100);
      pct = Math.max(0, Math.min(100, pct));
    }

    el.progress.style.width = pct + "%";
    el.sub.textContent = `Overall progress: ${pct}%`;
    if (message) el.log.textContent = message;
    refreshStoredPlatforms();
    refreshSummaryTrigger();
    if (!el.modal.hidden) fillSummaryModal();
    syncToggleButton();
  }

  function formatSummaryTime(ts) {
    if (!ts) return "-";
    return new Date(ts).toLocaleString();
  }

  function compareAlpha(a, b) {
    return String(a || "").localeCompare(String(b || ""), undefined, {
      sensitivity: "base",
      numeric: true
    });
  }

  function platformLabel(m) {
    const raw = m && m.platform ? String(m.platform).trim() : "";
    const name = m && m.name ? String(m.name) : "";
    if (raw && isGluedToName(name, raw)) return "Unknown";
    return raw || "Unknown";
  }

  function findRowByModel(m) {
    const href = modelHref(m);
    const rows = getRows();
    if (href) {
      const wanted = hrefPath(href);
      return rows.find((row) => hrefPath(getModelHref(row)) === wanted) || null;
    }

    const name = (m && m.name) || "";
    if (!name) return null;
    const named = rows.filter((row) => getModelName(row) === name);
    const platform = String((m && m.platform) || "").trim().toLowerCase();
    if (platform) {
      const samePlatform = named.filter((row) => getModelPlatform(row).trim().toLowerCase() === platform);
      return samePlatform.length === 1 ? samePlatform[0] : null;
    }
    return named.length === 1 ? named[0] : null;
  }

  function refreshStoredPlatforms() {
    if (!Array.isArray(state.resumedModels) || !state.resumedModels.length) return;
    let changed = false;
    for (const m of state.resumedModels) {
      if (!m) continue;
      const row = findRowByModel(m);
      if (row) {
        const livePlatform = getModelPlatform(row);
        const liveName = getModelName(row);
        if (livePlatform && livePlatform !== m.platform) {
          m.platform = livePlatform;
          changed = true;
        }
        if (liveName && liveName !== m.name) {
          m.name = liveName;
          changed = true;
        }
      } else if (m.platform && isGluedToName(m.name || "", m.platform)) {
        m.platform = "";
        changed = true;
      }
    }
    if (changed) saveState();
  }

  function groupedResumedModels(models) {
    const groups = new Map();
    for (const m of models) {
      const key = platformLabel(m);
      if (!groups.has(key)) groups.set(key, []);
      groups.get(key).push(m);
    }
    return Array.from(groups.keys())
      .sort(compareAlpha)
      .map((key) => ({
        platform: key,
        models: groups.get(key).slice().sort((a, b) => compareAlpha(a.name, b.name))
      }));
  }

  function createModelRow(m) {
    const li = document.createElement("li");
    const href = modelHref(m);
    const label = m.name || "Unknown model";
    if (href) {
      const a = document.createElement("a");
      a.className = "cv-modal-link";
      a.href = href;
      a.target = "_blank";
      a.rel = "noopener noreferrer";
      a.textContent = label;
      li.appendChild(a);
    } else {
      li.appendChild(document.createTextNode(label));
    }
    return li;
  }

  function fillSummaryModal() {
    const models = Array.isArray(state.resumedModels) ? state.resumedModels : [];
    const groups = groupedResumedModels(models);
    el.modalMeta.textContent = models.length
      ? `${models.length} resumed · ${groups.length} platform${groups.length === 1 ? "" : "s"} · started ${formatSummaryTime(state.startedAt)}`
      : "No models resumed yet.";
    el.modalList.replaceChildren();
    for (const group of groups) {
      const details = document.createElement("details");
      details.className = "cv-platform-group";
      details.open = !uiState.collapsedPlatforms[group.platform];

      const summary = document.createElement("summary");
      const title = document.createElement("span");
      title.className = "cv-platform-title";
      const chevron = document.createElement("span");
      chevron.className = "cv-platform-chevron";
      const name = document.createElement("span");
      name.textContent = group.platform;
      title.appendChild(chevron);
      title.appendChild(name);
      const count = document.createElement("span");
      count.className = "cv-platform-count";
      count.textContent = String(group.models.length);
      summary.appendChild(title);
      summary.appendChild(count);

      const ol = document.createElement("ol");
      ol.className = "cv-platform-models";
      for (const m of group.models) ol.appendChild(createModelRow(m));

      details.appendChild(summary);
      details.appendChild(ol);
      details.addEventListener("toggle", () => {
        uiState.collapsedPlatforms[group.platform] = !details.open;
        saveUiState();
      });
      el.modalList.appendChild(details);
    }
  }

  function openSummaryModal() {
    if (!Array.isArray(state.resumedModels) || !state.resumedModels.length) return;
    fillSummaryModal();
    el.modal.hidden = false;
  }

  function closeSummaryModal() {
    el.modal.hidden = true;
  }

  function refreshSummaryTrigger() {
    const count = Array.isArray(state.resumedModels) ? state.resumedModels.length : 0;
    if (!count) {
      el.summary.textContent = "No summary yet";
      el.summary.classList.add("is-empty");
      closeSummaryModal();
      return;
    }
    el.summary.textContent = `View summary (${count})`;
    el.summary.classList.remove("is-empty");
  }

  function clickResumeButtonOnRow(row) {
    const btn = row.querySelector("a.watched-toggle");
    if (!btn) return false;
    dispatchRealClick(btn);
    return true;
  }

  async function processCurrentPage() {
    state.resumedCurrentPage = 0;
    saveState();
    await waitForLoaderToHide();

    let emptyBursts = 0;
    let useBurst = true;
    let pausedRows = getRows().filter(isPausedRow);

    while (state.running && pausedRows.length > 0) {
      const size = useBurst
        ? (CONFIG.burstSize > 0 ? CONFIG.burstSize : pausedRows.length)
        : 1;
      const burst = pausedRows.slice(0, size);
      const before = pausedModelMap(pausedRows);

      if (burst.length === 1) {
        updateUI(`Resuming "${getModelName(burst[0])}"...`);
      } else {
        updateUI(`Burst: resuming ${burst.length} models at once...`);
      }

      for (const row of burst) {
        if (!state.running) return;
        clickResumeButtonOnRow(row);
        if (CONFIG.burstStaggerMs) await sleep(CONFIG.burstStaggerMs);
      }

      await waitForLoaderToHide();
      await sleep(CONFIG.betweenActionMs);

      pausedRows = getRows().filter(isPausedRow);
      const after = pausedModelMap(pausedRows);
      const justResumed = [];
      for (const [id, info] of before) {
        if (!after.has(id)) justResumed.push(info);
      }
      const resumed = justResumed.length;

      if (resumed > 0) {
        rememberResumed(justResumed);
        state.resumedTotal += resumed;
        state.resumedCurrentPage += resumed;
        saveState();
        emptyBursts = 0;
        updateUI(
          resumed === 1
            ? "Great! 1 model is now resumed."
            : `Great! ${resumed} models are now resumed.`
        );
      } else {
        emptyBursts += 1;
        if (useBurst && burst.length > 1) {
          useBurst = false;
          emptyBursts = 0;
          updateUI("Burst didn't stick. Falling back to one by one.");
          continue;
        }
        if (emptyBursts >= CONFIG.maxEmptyBursts) {
          updateUI("Some models stayed paused on this page. Moving on.");
          break;
        }
      }
    }
  }

  function syncToggleButton() {
    if (!el.toggle) return;
    if (state.running) {
      el.toggle.textContent = "Stop";
      el.toggle.classList.add("is-stop");
    } else {
      el.toggle.textContent = "Start";
      el.toggle.classList.remove("is-stop");
    }
  }

  async function stopRun(msg) {
    state.running = false;
    saveState();
    updateUI(msg);
    if (isUnsortedList()) return;
    await sleep(CONFIG.afterPageMs);
    location.href = unsortedPageOneHref();
  }

  async function finishRun(msg) {
    await stopRun(msg);
  }

  async function runLoop() {
    if (!state.running) return;

    if (!isSortedPageOne()) {
      updateUI("Sorting paused models to the top...");
      await sleep(CONFIG.afterPageMs);
      location.href = sortedPageOneHref();
      return;
    }

    if (state.initialPaused == null) {
      const p = currentPausedGlobal();
      state.initialPaused = p != null ? p : getRows().filter(isPausedRow).length;
      state.startedAt = Date.now();
      saveState();
    }

    const pausedBefore = currentPausedGlobal();
    updateUI("Working on this page...");
    await processCurrentPage();
    if (!state.running) return;

    const pausedNow = currentPausedGlobal();
    const pausedPageNow = getRows().filter(isPausedRow).length;

    if ((pausedNow != null && pausedNow <= 0) || (pausedNow == null && pausedPageNow === 0 && state.initialPaused === state.resumedTotal)) {
      await finishRun("All done. No paused models left.");
      return;
    }

    const currentGlobal = pausedNow == null ? Math.max(0, state.initialPaused - state.resumedTotal) : pausedNow;

    if (pausedBefore != null && currentGlobal >= pausedBefore) {
      state.stagnantFullScans += 1;
    } else {
      state.stagnantFullScans = 0;
    }

    state.lastKnownPaused = currentGlobal;
    saveState();

    if (state.stagnantFullScans >= CONFIG.maxStagnantFullScans) {
      await stopRun("Stopped automatically: no new progress detected.");
      return;
    }

    updateUI("Refreshing page 1 for the next paused models...");
    location.reload();
  }

  el.toggle.addEventListener("click", () => {
    if (state.running) {
      stopRun("Stopped. You can start again anytime.");
      return;
    }
    state.pendingStartAfterRefresh = true;
    saveState();
    if (!isSortedPageOne()) {
      updateUI("Sorting paused models to the top...");
      location.href = sortedPageOneHref();
      return;
    }
    updateUI("Refreshing to get the latest paused count...");
    location.reload();
  });

  el.reset.addEventListener("click", () => {
    state.running = false;
    state.resumedTotal = 0;
    state.resumedCurrentPage = 0;
    state.initialPaused = currentPausedGlobal() || getRows().filter(isPausedRow).length;
    state.startedAt = null;
    state.lastKnownPaused = state.initialPaused;
    state.stagnantFullScans = 0;
    state.resumedModels = [];
    saveState();
    updateUI("Stats cleared.");
  });

  applyCollapsed();
  updateUI("Ready when you are.");

  if (state.pendingStartAfterRefresh && !state.running) {
    setTimeout(startRunFromCurrentPage, 350);
    return;
  }

  if (state.running) {
    setTimeout(runLoop, 350);
  }
})();