Download app.js from waveshaker/universal-lora-studio-gui: direct link, hf CLI and curl.
- Browser
- Download file 108 kB
-
https://huggingface.co/spaces/waveshaker/universal-lora-studio-gui/resolve/main/app.js
- Command line
-
hf download hf://spaces/waveshaker/universal-lora-studio-gui/app.js
-
curl -L -o app.js https://huggingface.co/spaces/waveshaker/universal-lora-studio-gui/resolve/main/app.js
108 kB
// commit@70f742a386b9cbbfd6df774b19d727485ef5446f
// ==========================================================================
// 🛡️ Dynamic API Base URL
// ==========================================================================
const hostname = window.location.hostname;
let API_BASE_URL = "";
// --------------------------------------------------------------------------
// GUI Space Only: Anonymous Quota Warning (floating / auto-dismiss / manual close)
// --------------------------------------------------------------------------
if (hostname.includes("universal-lora-studio-gui")) {
setTimeout(() => {
if (document.getElementById('gui-anon-warning')) return;
const toast = document.createElement('div');
toast.id = 'gui-anon-warning';
toast.style.cssText = `
position: fixed;
top: 24px;
right: 24px;
background-color: rgba(42, 42, 42, 0.95);
color: #FF7F50;
border: 1px solid #444;
padding: 12px 16px;
border-radius: 8px;
font-size: 13px;
font-weight: 500;
z-index: 99999;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
display: flex;
align-items: flex-start;
gap: 12px;
box-shadow: 0 8px 24px rgba(0,0,0,0.6);
backdrop-filter: blur(8px);
animation: slideInRight 0.4s ease-out;
max-width: 320px;
`;
toast.innerHTML = `
<div style="flex: 1; line-height: 1.5; color: #ccc;">
⚠️ [For Testing Only] You are using the <b style="color: #FF7F50;">Anonymous Quota</b>. It depletes very quickly.
<div style="margin-top: 10px;">
<a href="https://huggingface.co/spaces/waveshaker/universal-lora-studio" target="_blank" style="display: inline-block; color: #fff; background: #FF7F50; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold; font-size: 12px;">
Switch to Studio ↗
</a>
</div>
</div>
<button id="close-anon-warning" style="background: transparent; border: none; color: #888; font-size: 18px; cursor: pointer; padding: 0; line-height: 1; transition: color 0.2s;" onmouseover="this.style.color='#fff'" onmouseout="this.style.color='#888'">
×
</button>
`;
const style = document.createElement('style');
style.innerHTML = `
@keyframes slideInRight {
from { opacity: 0; transform: translateX(40px); }
to { opacity: 1; transform: translateX(0); }
}
`;
document.head.appendChild(style);
document.body.appendChild(toast);
// 封装关闭逻辑
const closeToast = () => {
if (!document.getElementById('gui-anon-warning')) return;
toast.style.opacity = '0';
toast.style.transform = 'translateX(40px)';
toast.style.transition = 'all 0.3s';
setTimeout(() => toast.remove(), 300);
};
// 绑定手动关闭
document.getElementById('close-anon-warning').onclick = closeToast;
// 绑定 10 秒自动关闭
setTimeout(closeToast, 10000);
}, 100);
}
// --------------------------------------------------------------------------
// Environment Routing
// --------------------------------------------------------------------------
// 1. GUI 预览环境
if (hostname.includes("universal-lora-studio-gui")) {
API_BASE_URL = "https://waveshaker-universal-lora-studio-test.hf.space";
}
// 2. 本地开发环境
else if (hostname === "localhost" || hostname === "127.0.0.1") {
API_BASE_URL = "https://waveshaker-universal-lora-studio-test.hf.space";
}
// 3. 测试环境 (Test Space)
else if (hostname.includes("universal-lora-studio-test")) {
API_BASE_URL = ""; // 同源,走相对路径
}
// 4. 线上环境 (Prod Space)
else if (hostname.includes("universal-lora-studio.hf.space") || hostname.includes("universal-lora-studio.static")) {
API_BASE_URL = ""; // 同源,走相对路径
}
// ==========================================================================
// 🔐 ZeroGPU Token Handshake
// ==========================================================================
const ZEROGPU_HEADERS_MSG = "supports-zerogpu-headers";
// 监听 HF 父窗口发来的握手信号
window.addEventListener("message", (event) => {
if (event.data === ZEROGPU_HEADERS_MSG) {
window.supports_zerogpu_headers = true;
}
});
// 向父窗口声明支持,触发后续的 token 索要流程
(function announceZeroGpuSupport() {
const hostname = window.location.hostname;
if (!hostname.endsWith(".hf.space") && !hostname.includes(".dev.")) {
return; // 非 HF 环境,不执行
}
const origin = hostname.includes(".dev.")
? `https://moon-${hostname.split(".")[1]}.dev.spaces.huggingface.tech`
: "https://huggingface.co";
try {
window.parent.postMessage(ZEROGPU_HEADERS_MSG, origin);
} catch (e) {
console.warn("ZeroGPU handshake failed:", e);
}
})();
// 向父窗口索要 x-ip-token(带 2 秒超时兜底)
async function requestZeroGpuToken() {
if (!window.supports_zerogpu_headers) return null;
const hostname = window.location.hostname;
if (!hostname.endsWith(".hf.space") && !hostname.includes(".dev.")) return null;
const origin = hostname.includes(".dev.")
? `https://moon-${hostname.split(".")[1]}.dev.spaces.huggingface.tech`
: "https://huggingface.co";
try {
return await new Promise((resolve) => {
const channel = new MessageChannel();
const timeout = setTimeout(() => {
channel.port1.close();
resolve(null);
}, 2000);
channel.port1.onmessage = ({ data }) => {
clearTimeout(timeout);
resolve(data || null);
};
window.parent.postMessage("zerogpu-headers", origin, [channel.port2]);
});
} catch {
return null;
}
}
// ==========================================================================
// 🛡️ API Layer
// ==========================================================================
// 统一的请求入口:超时 + 指数退避重试。
// "Failed to fetch" / 瞬时 5xx / Space 重启都能扛过去
async function fetchWithRetry(url, options = {}, cfg = {}) {
const {
retries = 3,
timeout = 8000,
backoff = 1000,
} = cfg;
let lastErr;
for (let attempt = 1; attempt <= retries; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetch(url, { ...options, cache: 'no-store', signal: controller.signal });
clearTimeout(timer);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res;
} catch (err) {
clearTimeout(timer);
lastErr = err;
const reason = err.name === 'AbortError' ? `timeout(${timeout}ms)` : err.message;
console.warn(`⚠️ [API Retry ${attempt}/${retries}] GET ${url} → ${reason}`);
if (attempt < retries) {
await new Promise(r => setTimeout(r, backoff * attempt)); // 1s / 2s / 3s
}
}
}
throw lastErr;
}
const BackendAPI = {
// 1. 心跳检测
checkHealth: async function() {
try {
const res = await fetchWithRetry(`${API_BASE_URL}/api/health`, {}, { retries: 1, timeout: 3000 });
const data = await res.json();
return data.status === "ok";
} catch (error) {
return false;
}
},
// 2. 获取全局配置(内部已重试 3 次;仍失败返回 null,由调用方兜底 + 后台补齐)
getConfig: async function() {
try {
const res = await fetchWithRetry(`${API_BASE_URL}/api/config`);
return await res.json();
} catch (error) {
console.error("❌ 获取配置失败(已重试 3 次):", error);
return null;
}
},
// 3. 获取 Base Model 列表
getModels: async function() {
const res = await fetchWithRetry(`${API_BASE_URL}/api/models`, {}, { retries: 3, timeout: 15000 });
return await res.json();
},
// 4. 获取角色 LoRA 图库数据(后端可能触发仓库扫描,给更长超时)
getLoras: async function() {
const res = await fetchWithRetry(`${API_BASE_URL}/api/loras`, {}, { retries: 2, timeout: 20000 });
return await res.json();
},
// 4.5 预热:让后端把模型文件拉进 page cache(纯 CPU/IO,不消耗 ZeroGPU 配额)
// 这是"fire-and-forget",失败只打日志,绝不影响主流程
warmup: async function(payload) {
try {
const res = await fetch(`${API_BASE_URL}/api/warmup`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
cache: 'no-store',
body: JSON.stringify(payload)
});
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();
if (data && (data.skipped || data.queued)) {
console.log(`🔥 [warmup] ${payload.unet_choice} → ${data.skipped || 'queued(seq ' + data.seq + ')'}`);
}
return data;
} catch (e) {
console.warn("⚠️ warmup request failed:", e.message);
return null;
}
},
// 4.6 预热状态(仅调试用,控制台里看;不参与任何 UI 逻辑)
warmupStatus: async function() {
try {
const res = await fetchWithRetry(`${API_BASE_URL}/api/warmup/status`, {}, { retries: 1, timeout: 3000 });
return await res.json();
} catch { return null; }
},
// 5. 提交生成任务
submitGenerate: async function(payload) {
const headers = { 'Content-Type': 'application/json' };
const tokenInfo = await requestZeroGpuToken();
if (tokenInfo) {
if (typeof tokenInfo === 'object') {
Object.assign(headers, tokenInfo);
} else if (typeof tokenInfo === 'string') {
headers['x-ip-token'] = tokenInfo;
}
}
if (!tokenInfo) {
console.warn("⚠️ ZeroGPU token unavailable — usage will NOT be attributed to any account");
addLog("⚠️ ZeroGPU token unavailable (open this Space via huggingface.co)", "error");
}
const res = await fetch(`${API_BASE_URL}/api/generate`, {
method: 'POST',
cache: 'no-store',
headers: headers,
body: JSON.stringify(payload)
});
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
const data = await res.json();
if (data.status === "error") throw new Error(data.message);
return data.task_id;
},
// 6. 轮询任务状态
pollStatus: async function(taskId, callbacks, retries = 0) {
const MAX_RETRIES = 200;
try {
const res = await fetch(`${API_BASE_URL}/api/status/${taskId}`, {
cache: 'no-store'
});
const data = await res.json();
if (data.status === "processing" || data.status === "queued") {
if (callbacks.onProcessing) {
callbacks.onProcessing(data.message || "Processing...");
}
if (retries >= MAX_RETRIES) {
const timeoutMsg = `Timeout: Backend exceeded ${MAX_RETRIES * 500 / 1000}s. Please try again.`;
if (callbacks.onError) callbacks.onError(timeoutMsg);
return;
}
setTimeout(() => this.pollStatus(taskId, callbacks, retries + 1), 500);
}
else if (data.status === "success") {
let finalImageUrl = data.image;
if (finalImageUrl && !finalImageUrl.startsWith('data:') && !finalImageUrl.startsWith('http')) {
finalImageUrl = `${API_BASE_URL}${finalImageUrl}`;
}
if (callbacks.onSuccess) {
// 不 await:pollStatus 本身不是 async 回调链的 gate,但 onSuccess 内部会自己串行
// 若 onSuccess 是 async,这里拿到的是 Promise;拒绝也要吞掉避免 unhandled rejection
const r = callbacks.onSuccess(finalImageUrl, data.seed, data.metrics, data.filename);
if (r && typeof r.catch === 'function') r.catch(e => console.error('[onSuccess] error:', e));
}
}
else if (data.status === "error") {
if (callbacks.onError) callbacks.onError(data.message);
}
else if (data.status === "not_found") {
if (callbacks.onError) callbacks.onError("Task not found (backend may have restarted).");
}
} catch (error) {
if (callbacks.onError) callbacks.onError(error.message);
}
},
};
// ==========================================================================
// 🧠 Global State & Utilities
// ==========================================================================
let generateStartTime = 0;
let currentStageStartTime = 0;
let currentStageName = "";
let isInitializing = false;
let shouldAnimateNextRender = false;
let globalModelData = {};
let currentGalleryData = [];
let renderedCount = 0;
const BATCH_SIZE = 20;
let selectedLora = "";
let backendState = { isReady: false, isChecking: false, healthInterval: null, hasInitData: false };
let globalRootMapping = {};
let _configBackgroundAttempts = 0;
// config 拉取失败时的后台补齐:成功后只补 samplers / schedulers / root_mapping,
// 不覆盖用户已输入的 prompt,也不动当前选中的模型和图库
function retryConfigInBackground() {
if (_configBackgroundAttempts >= 12) {
console.error("❌ 配置后台补齐放弃(12 次 / 约 2 分钟)");
return;
}
_configBackgroundAttempts++;
setTimeout(async () => {
const config = await BackendAPI.getConfig();
if (!config) { retryConfigInBackground(); return; }
globalRootMapping = config.root_mapping || {};
const samplerEl = document.getElementById('sampler');
const schedulerEl = document.getElementById('scheduler');
const keepSampler = samplerEl.value;
const keepScheduler = schedulerEl.value;
samplerEl.innerHTML = (config.samplers ||
["euler", "euler_ancestral", "euler_a", "dpmpp_2m", "dpmpp_2m_sde", "dpmpp_sde", "heun", "lms", "lcm"])
.map(s => `<option value="${s}">${s}</option>`).join('');
schedulerEl.innerHTML = (config.schedulers ||
["simple", "beta", "normal", "karras", "exponential", "sgm_uniform"])
.map(s => `<option value="${s}">${s}</option>`).join('');
// 保住用户当前已选的 sampler / scheduler
if ([...samplerEl.options].some(o => o.value === keepSampler)) samplerEl.value = keepSampler;
if ([...schedulerEl.options].some(o => o.value === keepScheduler)) schedulerEl.value = keepScheduler;
_configBackgroundAttempts = 0;
console.log(`✅ 配置延迟补齐成功 (root_mapping: ${Object.keys(globalRootMapping).length} 条)`);
}, 10000);
}
// ==========================================================================
// 🔥 Warmup Trigger (lite=enter / full=select / touch=heartbeat)
// ==========================================================================
// ⚠️ 三种 mode 必须各有各的 timer:
// 共用一个的话,心跳 touch(延时0) 会 clearTimeout 掉待发的 full(延时400),
// 用户刚切完模型那一次预热就被吃掉了。
const _warmupTimers = { full: null, lite: null, touch: null };
function _clearWarmupTimer(mode) {
if (_warmupTimers[mode]) {
clearTimeout(_warmupTimers[mode]);
_warmupTimers[mode] = null;
}
}
function scheduleWarmup(unetChoice, mode = 'full', charLora = '') {
if (!unetChoice || !backendState.isReady) return;
if (unetChoice.includes('Loading') || unetChoice.includes('Offline')) return;
// 优先级:full(用户明确选择) > lite(进入界面) > touch(保活)
// 低优先级只让路,绝不取消高优先级
if (mode === 'touch') {
if (_warmupTimers.full || _warmupTimers.lite) return; // 已有待发请求 → 心跳直接跳过
} else if (mode === 'lite') {
if (_warmupTimers.full) return; // full 是 lite 的超集
} else {
// full:把待发的 lite/touch 一并取消,避免 0ms 的 lite 抢先读一遍再被 full 覆盖
_clearWarmupTimer('lite');
_clearWarmupTimer('touch');
}
_clearWarmupTimer(mode);
// full 去抖 400ms:防止用户快速下拉连点,起 N 个并发读把磁盘打满
_warmupTimers[mode] = setTimeout(() => {
_warmupTimers[mode] = null;
BackendAPI.warmup({
unet_choice: unetChoice,
char_lora: charLora || '',
char_enable: document.getElementById('char-enable')?.checked ?? true,
mode,
reason: mode === 'lite' ? 'enter' : (mode === 'touch' ? 'touch' : 'select')
});
}, mode === 'full' ? 400 : 0);
}
// ==========================================================================
// 🎛️ UI Helpers (Animation / Slider Binding)
// ==========================================================================
// 物理弹簧动画配置
const ANIM_CONFIG = {
startY: 24,
stiffness: 280,
damping: 0.7,
staggerDelay: 30,
};
function toUnicodeBold(str) {
return str.split('').map(char => {
const code = char.charCodeAt(0);
if (code >= 65 && code <= 90) return String.fromCodePoint(0x1D5D4 + (code - 65));
if (code >= 97 && code <= 122) return String.fromCodePoint(0x1D5EE + (code - 97));
if (code >= 48 && code <= 57) return String.fromCodePoint(0x1D7EC + (code - 48));
return char;
}).join('');
}
// 绑定滑块与数字输入框的双向同步逻辑
function bindSlider(sliderId, inputId) {
const slider = document.getElementById(sliderId);
const input = document.getElementById(inputId);
// 1. 滑块 -> 输入框
slider.addEventListener('input', (e) => {
input.value = e.target.value;
});
// 2. 输入框 -> 滑块(实时同步,不打断用户输入)
input.addEventListener('input', (e) => {
let val = parseFloat(e.target.value);
if (!isNaN(val) && val >= parseFloat(slider.min) && val <= parseFloat(slider.max)) {
slider.value = val;
}
});
// 3. 输入结束 -> 夹边界 + 对齐到 step 网格 + 双向回写
const enforceLimits = () => {
let val = parseFloat(input.value);
const min = parseFloat(slider.min);
const max = parseFloat(slider.max);
const step = parseFloat(slider.step) || 1;
if (isNaN(val)) val = min;
// ① 夹到 [min, max]
val = Math.min(max, Math.max(min, val));
// ② 对齐到 step 网格 —— width/height 的 step=8 就在这里生效
if (step > 0) {
val = min + Math.round((val - min) / step) * step;
// ③ 去掉浮点噪声(cfg 的 step=0.1 会算出 1.2000000000000002)
val = Math.round(val * 1e6) / 1e6;
}
input.value = val; // ← 关键:必须回写 input,否则提交时读到的还是旧值
slider.value = val;
};
input.addEventListener('change', enforceLimits);
input.addEventListener('blur', enforceLimits);
}
bindSlider('width-slider', 'width-input');
bindSlider('height-slider', 'height-input');
bindSlider('steps-slider', 'steps-input');
bindSlider('cfg-slider', 'cfg-input');
// ==========================================================================
// 🏷️ Character LoRA Trigger Words (split into boxes + click-to-copy)
// ==========================================================================
/// 归一化触发词:数组 → 多条;字符串含 ",," 或换行 → 拆分;每条末尾补 ","
// ⚠️ 单个 "," 是条目内部内容,绝不作为分隔符
function normalizeTriggers(trigger) {
let arr;
if (Array.isArray(trigger)) {
// 后端返回数组:每个元素就是一条,不再做任何二次拆分
arr = trigger.map(t => String(t).trim()).filter(Boolean);
} else {
const s = (trigger || "").toString().trim();
if (!s) return [];
// 只有 ",," 或换行才代表"多条"
arr = s
.split(/\s*,\s*,+|\s*\n+\s*/)
.map(x => x.trim())
.filter(Boolean);
}
// 每条末尾没有 ',' 就补一个
return arr.map(t => t.endsWith(",") ? t : t + ",");
}
// ==========================================================================
// 🔗 Gallery 深链(机器跳转用长链:画廊新旧两版都能解析)
// ==========================================================================
// 用 HF 包装页(带导航栏 / README / 点赞),实测包装页会把 #hash 原样透传进 iframe:
// …/spaces/waveshaker/loras_gallery#/showcase/<model>/<cat>/<name>.safetensors → 弹窗自动打开
// ⚠️ 结尾不要带 "/":否则多一次 301,还会在分享文案里显得别扭。
const GALLERY_BASE = "https://huggingface.co/spaces/waveshaker/loras_gallery";
// 备用:无外壳静态直连(首屏快一点,但没有导航栏)。要回切只改上面一行。
// const GALLERY_BASE = "https://waveshaker-loras-gallery.static.hf.space";
// 顺手把页面右上角的 Gallery 链接也统一到同一个常量(避免两处写死、各不相同)
document.getElementById("gallery-link")?.setAttribute("href", GALLERY_BASE);
function buildGalleryLink(kind, path) {
if (!path) return "";
const segs = String(path).split("/").filter(Boolean).map(s => encodeURIComponent(s)).join("/");
return `${GALLERY_BASE}#/${kind}/${segs}`;
}
// ==========================================================================
// 🧩 预设 Prompt(数据源:gallery 的 prompts.json,经后端 /api/prompt 转发)
// ==========================================================================
// 三条护栏,缺一条就会出事故:
// 1) 来源:URL 显式带 prompt=1 —— 没有标记就绝不改文案
// 2) 一次性:_appliedPresetFor 记录已套用的 path —— 后端重连重跑 init 也不会二次覆盖
// 3) 目标安全:只有 prompt 为空 / 仍等于模型 default_prompt 时才允许自动写入
function getPromptEl() {
return document.getElementById("prompt");
}
function getCurrentPrompt() {
const el = getPromptEl();
return el ? el.value : "";
}
function setPromptValue(text, reason) {
const el = getPromptEl();
if (!el) return;
el.value = text;
el.dispatchEvent(new Event("input")); // 与手动输入走同一条路径(触发既有监听)
addLog(`🧩 ${reason}`, "highlight");
}
document.getElementById("prompt").addEventListener("input", (e) => {
if (e.isTrusted === false) return; // 忽略程序化赋值触发的 input
if (_promptPresetText && getCurrentPrompt().trim() === _promptPresetText.trim()) {
setPromptHint("applied");
} else if (_promptSourceItem?.hasPrompt) {
setPromptHint("available"); // 改过了,但仍可一键换回作者原版
} else {
setPromptHint(null);
}
});
// 目标安全判断:空 或 仍等于当前模型的默认 prompt
function isPromptSafeToOverwrite(modelKey) {
const cur = getCurrentPrompt().trim();
if (!cur) return true;
const def = String(globalModelData[modelKey]?.default_prompt || "").trim();
return !!def && cur === def;
}
// ==========================================================================
// 🧩 Prompt 标签状态:常驻文字,不靠 tooltip
// · use author preset → 有配方、当前内容不是它 → 可点(accent)
// · preset applied → 当前内容就是作者预设 → 灰字,不可点
// · 空 → 无配方,或用户已手改
// ==========================================================================
let _promptSourceItem = null; // 当前卡片(点击时要用)
let _promptPresetText = null; // 当前卡片已缓存的预设文本
setPromptHint(null);
function setPromptHint(mode) {
const el = document.getElementById("prompt-hint");
if (!el) return;
el.classList.remove("clickable");
el.onclick = null;
el.removeAttribute("title");
if (mode === "available" && _promptSourceItem) {
el.textContent = " · use author preset";
el.classList.add("clickable");
el.title = "Apply the author's preset prompt (fills this field)";
el.onclick = () => applyPresetManually(_promptSourceItem);
} else if (mode === "applied") {
el.textContent = " · preset applied";
el.title = "This text came from the author's preset";
} else {
el.textContent = "";
}
}
// path -> prompt 文本;null 表示"确认没有预设"(负缓存,避免重复打 404)
const _presetTextCache = new Map();
let _promptHintToken = 0; // 🌟 竞态守卫:快速切卡时丢弃过期的返回
async function fetchPresetPrompt(path) {
if (!path) return null;
if (_presetTextCache.has(path)) return _presetTextCache.get(path); // 命中即返回(含 null)
let text = null;
try {
// 不重试:404 是正常业务结果,重试只会让用户白等
const res = await fetch(`${API_BASE_URL}/api/prompt?path=${encodeURIComponent(path)}`, { cache: "no-store" });
if (res.ok) {
const data = await res.json();
text = (data && data.ok && data.prompt) ? data.prompt : null;
}
} catch (e) {
console.warn("🧩 获取预设 prompt 失败:", e);
}
_presetTextCache.set(path, text);
return text;
}
// 选中卡片时刷新一次:先拿预设文本(内存缓存,命中即零延迟),再决定显示哪种状态
async function refreshPromptHint(item) {
const token = ++_promptHintToken;
_promptSourceItem = item || null;
_promptPresetText = null;
if (!item || !item.hasPrompt) { setPromptHint(null); return; }
const text = await fetchPresetPrompt(item.path);
if (token !== _promptHintToken) return; // 已经切到别的卡了,丢弃过期结果
if (!text) { setPromptHint(null); return; }
_promptPresetText = text;
setPromptHint(getCurrentPrompt().trim() === text.trim() ? "applied" : "available");
}
// 深链入口:URL 带 prompt=1 且当前卡片有 preset 时调用
async function applyPresetForDeepLink(item, modelKey) {
if (!item || !item.path || !item.hasPrompt) return;
if (window._appliedPresetFor === item.path) return; // 护栏 2
if (!isPromptSafeToOverwrite(modelKey)) { // 护栏 3
window._appliedPresetFor = item.path;
addLog("🧩 Prompt was already edited — skipped auto-applying the preset (click 🧩 Prompt to apply).");
return;
}
window._appliedPresetFor = item.path;
const text = await fetchPresetPrompt(item.path);
if (!text) {
addLog("🧩 This LoRA has no preset prompt — keeping the model default.");
return;
}
// 网络回来时用户可能已经开始打字了 → 再校验一次
if (!isPromptSafeToOverwrite(modelKey)) {
addLog("🧩 Prompt was edited meanwhile — skipped applying the preset.");
return;
}
setPromptValue(text, `Applied author preset prompt (${item.filename})`);
_promptPresetText = text;
setPromptHint("applied"); // 深链套用后同样要置位
}
// 与触发词 chips 的 "Copied!" 同一套克制反馈:短暂改文案,不弹任何对话框
function flashActionLabel(el, text, ms = 1200) {
if (!el || el.dataset.flashing === "1") return;
const original = el.textContent;
el.dataset.flashing = "1";
el.textContent = text;
setTimeout(() => {
el.textContent = original;
delete el.dataset.flashing;
}, ms);
}
// 手动入口(Prompt 标签右侧的 "use author preset"):一次点击直接套用,不弹任何对话框
async function applyPresetManually(item) {
if (!item || !item.hasPrompt) return;
const text = await fetchPresetPrompt(item.path);
if (!text) {
addLog("🧩 No preset prompt available for this LoRA.");
setPromptHint(null);
return;
}
setPromptValue(text, `Applied author preset prompt (${item.filename})`);
// setPromptValue 派发的是 synthetic input(isTrusted=false,被监听器忽略),
// 所以这里必须显式置位,否则标签会一直停在 "use author preset"
_promptPresetText = text;
setPromptHint("applied");
}
//===============================================================================================
// 刷新右侧信息列:空态 / 标题 + 文件名 + 深链
function updatePreviewInfo(item) {
const emptyEl = document.getElementById("preview-info-empty");
const contentEl = document.getElementById("preview-info-content");
const titleEl = document.getElementById("preview-info-title");
const fileEl = document.getElementById("preview-info-filename");
const actionsEl = document.getElementById("preview-info-actions");
if (!emptyEl || !contentEl || !titleEl || !fileEl || !actionsEl) return;
if (!item) {
contentEl.style.display = "none";
emptyEl.style.display = "block";
return;
}
emptyEl.style.display = "none";
contentEl.style.display = "flex";
titleEl.textContent = item.title || item.filename.replace(/\.safetensors$/i, "");
fileEl.textContent = item.filename.replace(/\.safetensors$/i, "");
fileEl.title = item.filename;
// 用 DOM 构建,避免任何转义问题
actionsEl.innerHTML = "";
const addAction = (label, href, onClick, title) => {
if (!href && !onClick) return;
const a = document.createElement("a");
a.className = "pi-action";
if (title) a.title = title; // 🌟 原生 tooltip,英文,一行说清
if (onClick) {
a.href = "#";
a.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
onClick(a); // ← 把元素传出去,用于 "✓ Applied" 闪现
});
} else {
a.href = href;
a.target = "_blank";
a.rel = "noopener";
}
a.textContent = label;
actionsEl.appendChild(a);
};
// 与 header 的 "🖼️ Gallery ↗" 保持同一套写法:emoji 前置 + 箭头后置
if (item.hasShowcase) addAction("✨ Showcase ↗", buildGalleryLink("showcase", item.path), null,
"Open this LoRA's ComfyUI showcase in the gallery");
if (item.hasDataset) addAction("📊 Dataset ↗", buildGalleryLink("dataset", item.path), null,
"Open the training dataset in the gallery");
}
// 触发词面板:无 trigger 时整块不渲染;有则直接铺 chips(无展开动画)
function updateTriggerBar(trigger) {
const block = document.getElementById("lora-trigger-block");
const list = document.getElementById("lora-trigger-list");
const scroll = document.getElementById("lora-trigger-scroll");
if (!block || !list) return;
const entries = normalizeTriggers(trigger);
list.innerHTML = "";
// 73% 的条目没有 trigger —— 与其挂一个空标签,不如整块消失
if (!entries.length) {
block.style.display = "none";
return;
}
entries.forEach(t => {
const box = document.createElement("div");
box.className = "pt-box";
box.title = "Click to copy trigger";
const text = document.createElement("span");
text.className = "pt-text";
text.textContent = t;
box.appendChild(text);
bindTriggerBoxCopy(box, text, t);
list.appendChild(box);
});
block.style.display = "flex";
if (scroll) scroll.scrollTop = 0; // 换卡片时回到顶部
}
// 统一的复制入口:Clipboard API 失败(iframe 无 clipboard-write 权限等)→ execCommand 兜底
async function copyTextToClipboard(value) {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(value);
return true;
}
} catch (err) {
console.warn('Clipboard API failed, falling back:', err);
}
try {
const ta = document.createElement('textarea');
ta.value = value;
ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;top:-1000px;left:-1000px;opacity:0;';
document.body.appendChild(ta);
ta.select();
ta.setSelectionRange(0, ta.value.length);
const ok = document.execCommand('copy');
ta.remove();
return ok;
} catch (err) {
console.error('Copy trigger failed:', err);
return false;
}
}
// 单条触发词点击复制(克制反馈:背景微亮 + 文本短暂变 Copied! / Copy failed)
function bindTriggerBoxCopy(box, textEl, value) {
box.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
if (box.classList.contains('copied')) return;
const ok = await copyTextToClipboard(value);
box.classList.add('copied');
textEl.textContent = ok ? 'Copied!' : 'Copy failed';
setTimeout(() => {
box.classList.remove('copied');
if (textEl.textContent === 'Copied!' || textEl.textContent === 'Copy failed') {
textEl.textContent = value;
}
}, 1200);
});
}
// ==========================================================================
// 🎛️ UI Controls (Ratio Presets / Button State)
// ==========================================================================
const RATIO_PRESETS = {
"1:1": { w: 1024, h: 1024 },
"3:4": { w: 888, h: 1184 },
"9:16": { w: 768, h: 1368 },
"4:3": { w: 1184, h: 888 },
"16:9": { w: 1368, h: 768 }
};
document.querySelectorAll('.ratio-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.ratio-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const ratio = btn.dataset.ratio;
const preset = RATIO_PRESETS[ratio];
if (preset) {
document.getElementById('width-slider').value = preset.w;
document.getElementById('width-input').value = preset.w;
document.getElementById('height-slider').value = preset.h;
document.getElementById('height-input').value = preset.h;
}
});
});
function clearActiveRatio() {
document.querySelectorAll('.ratio-btn').forEach(b => b.classList.remove('active'));
}
document.getElementById('width-slider').addEventListener('input', clearActiveRatio);
document.getElementById('width-input').addEventListener('input', clearActiveRatio);
document.getElementById('height-slider').addEventListener('input', clearActiveRatio);
document.getElementById('height-input').addEventListener('input', clearActiveRatio);
// ==========================================================================
// ⏳ Generation Loader Controller
// ==========================================================================
const GenLoader = {
el: null,
dotsEl: null,
startTs: 0,
hideTimer: null,
cycleMs: 2200, // 与 CSS 1.6s 保持一致
dotGrid: 7, // 精准 7×7 网格(与你截图的横竖 7 点完全一致!)
buildDots() {
const box = this.el ? this.el.querySelector('.gen-loader-dots') : null;
if (!box) return;
this.dotsEl = box;
if (box.dataset.built === '1') return;
const N = this.dotGrid; // 7
const c = (N - 1) / 2; // 3(正中心点)
const maxD = 3.5; // 切掉 4 个最尖角(d=4.24),保留其余 45 个点,与截图完全一致!
const frag = [];
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
const d = Math.hypot(x - c, y - c);
// 1. 仅切掉 4 个最外角,保留 Grid 占位
// if (d > maxD) {
// frag.push(`<i style="visibility:hidden;animation:none"></i>`);
// continue;
// }
// 静态二次方梯度:中心点 9.5px,最外圈边缘点 1.4px
const ratio = Math.min(1, d / 3.65);
const baseSize = (1.4 + 6.6 * Math.pow(1 - ratio, 1.85)).toFixed(2);
// 适配 2.2s 周期的涟漪延迟(步长调为 0.28s,保证黑底留白与波浪层次分明)
const delay = (d * 0.28 - 1.1).toFixed(2);
frag.push(
`<i style="--size:${baseSize}px;--d:${delay}s"></i>`
);
}
}
box.innerHTML = frag.join('');
box.dataset.built = '1';
},
/** 重启动画,保证每次点击 Generate 都是从中心开始的一轮完整涟漪 */
restartDots() {
const box = this.dotsEl;
if (!box) return;
box.querySelectorAll('i').forEach(dot => {
dot.style.animation = 'none';
void dot.offsetWidth; // 强制 reflow 打断当前动画
dot.style.animation = '';
});
},
show() {
const el = document.getElementById('gen-loader');
if (!el) return;
clearTimeout(this.hideTimer);
clearTimeout(this._innerTimer);
this.el = el;
this.buildDots(); // ← 首次构建 49 点
this.restartDots(); // ← 每次从中心重新起波
el.classList.remove('fading');
el.classList.add('active');
void el.offsetWidth; // 强制 reflow,让 opacity 过渡生效
el.classList.add('visible');
this.startTs = performance.now();
},
/** 等当前这一轮点阵动画走完,再淡出,然后回调 */
hide(cb) {
const el = document.getElementById('gen-loader');
this.el = el;
if (!el) { if (cb) cb(); return; }
clearTimeout(this.hideTimer); // 外层
clearTimeout(this._innerTimer); // ← 新增:内层渐隐 timer
const elapsed = performance.now() - this.startTs;
const remain = this.cycleMs - (elapsed % this.cycleMs);
this.hideTimer = setTimeout(() => {
el.classList.add('fading');
this._innerTimer = setTimeout(() => { // ← 存引用
el.classList.remove('active', 'visible', 'fading');
if (this.el === el) { this.el = null; this.dotsEl = null; }
if (cb) cb();
}, 300);
}, remain);
},
/** 出错时立刻收起,不等动画 */
hideNow() {
const el = document.getElementById('gen-loader');
clearTimeout(this.hideTimer);
clearTimeout(this._innerTimer); // ← 新增
if (!el) return;
el.classList.remove('active', 'visible', 'fading');
if (this.el === el) { this.el = null; this.dotsEl = null; }
},
};
// ==========================================================================
// 📜 Log Panel banner
// ==========================================================================
const autoScrollToggle = document.getElementById('auto-scroll-toggle');
// 智能滚动日志面板(仅当用户勾选自动滚动时生效)
function smartScroll() {
if (autoScrollToggle && autoScrollToggle.checked) {
const logContent = document.getElementById('log-content');
// 使用 RAF 确保在 DOM 高度更新后再执行滚动
requestAnimationFrame(() => {
logContent.scrollTop = logContent.scrollHeight;
});
}
}
function addLog(message, type = "normal") {
const logContent = document.getElementById('log-content');
const newLine = document.createElement('div');
newLine.className = `log-line ${type === "normal" ? "" : type}`;
const time = new Date().toLocaleTimeString('en-US', { hour12: false });
newLine.innerText = `[${time}] ${message}`;
logContent.appendChild(newLine);
if (logContent.childElementCount > 100) {
logContent.firstElementChild.remove();
}
smartScroll();
}
// ==========================================================================
// 💓 Health Check & Initialization
// ==========================================================================
function setUIState(isGenerating) {
const btn = document.getElementById('generate-btn');
if (!backendState.isReady) {
btn.disabled = true;
btn.innerText = "⏳ Waiting for Backend...";
} else if (isGenerating) {
btn.disabled = true;
btn.innerText = "⏳ Generating...";
} else {
btn.disabled = false;
btn.innerText = "Generate";
}
}
async function performHealthCheck() {
if (backendState.isChecking) return;
backendState.isChecking = true;
const dot = document.getElementById('backend-status-dot');
const wrapper = document.getElementById('backend-status-wrapper');
if (!backendState.isReady) {
setUIState(false);
dot.className = "status-dot loading";
wrapper.title = "Connecting to backend...";
}
const isHealthy = await BackendAPI.checkHealth();
if (isHealthy) {
if (!backendState.isReady) {
backendState.isReady = true;
setUIState(false);
dot.className = "status-dot online";
wrapper.title = "Backend online, ready to generate!";
console.log("🔄 后端恢复连接");
}
// ✅ 初始化与"是否刚恢复连接"解耦:只要还没成功初始化过,每次心跳都给它一次机会。
// 否则首轮 init 在 isInitializing 期间被丢弃时,这里再也不会重试(永久离线态)。
// hasInitData=true 后走 else,保留用户已选角色 / 触发词面板 / 图库。
if (!backendState.hasInitData) {
await loadInitialData();
} else {
refreshWarmMarks(); // ← 加这行
}
} else {
backendState.isReady = false;
setUIState(false);
dot.className = "status-dot offline";
wrapper.title = "Backend offline, trying to reconnect...";
}
backendState.isChecking = false;
}
function startHealthPolling() {
if (backendState.healthInterval) return;
// 递归 setTimeout:离线时 3s 快速重连,在线时降到 30s 只做保活探测
const tick = async () => {
await performHealthCheck();
backendState.healthInterval = setTimeout(tick, backendState.isReady ? 30000 : 3000);
};
backendState.healthInterval = setTimeout(tick, 3000);
}
// =========================================================================
// 🔥 Warm State Marks (module scope — loadInitialData 和 refreshWarmMarks 都要用)
// =========================================================================
const WARM_MARK = {
resident: "🟢 ready",
warm: "🟠 warm start",
cold: "⚪ cold start",
};
function renderWarmStatusByState(st) {
const MAP = {
resident: ["🟢 Loaded — switching is instant", "#4ade80"],
warm: ["🟠 Warm Start — about 8s to load into VRAM", "#fb923c"],
cold: ["⚪ Cold Start — about 25s, reloads from disk", "#a1a1aa"],
};
const el = document.getElementById("unet-warm-status");
if (!el) return;
const it = MAP[st];
el.textContent = it ? it[0] : "";
el.style.color = it ? it[1] : "var(--text-muted)";
}
async function refreshWarmMarks() {
const selectEl = document.getElementById("unet-select");
if (!selectEl) return;
let warmMap;
try {
const r = await fetch(`${API_BASE_URL}/api/models/warm`, { cache: "no-store" });
warmMap = (await r.json()).warm || {};
} catch { return; }
selectEl.querySelectorAll("option").forEach(opt => {
const base = opt.dataset.baseText;
if (!base) return;
const m = WARM_MARK[warmMap[opt.value]];
opt.textContent = m ? `${base} ${m}` : base;
});
renderWarmStatusByState(warmMap[selectEl.value]);
}
let _pendingInitRetry = false;
async function loadInitialData() {
if (isInitializing) {
_pendingInitRetry = true; // ← 不丢弃,记一笔
return;
}
isInitializing = true;
console.log("🟢 [Init] 开始初始化...");
document.getElementById('unet-select').disabled = true;
const config = await BackendAPI.getConfig(); // 内部已带 3 次重试 + 8s 超时
if (!config) {
console.error("❌ 获取配置失败(已重试 3 次),先用内置兜底值,10s 后自动补齐");
retryConfigInBackground();
}
const finalSamplers = config?.samplers || ["euler", "euler_ancestral", "euler_a", "dpmpp_2m", "dpmpp_2m_sde", "dpmpp_sde", "heun", "lms", "lcm"];
const finalSchedulers = config?.schedulers || ["simple", "beta", "normal", "karras", "exponential", "sgm_uniform"];
globalRootMapping = config?.root_mapping || {};
if (config && config.default_prompt) {
document.getElementById('prompt').value = config.default_prompt;
}
document.getElementById('sampler').innerHTML = finalSamplers.map(s => `<option value="${s}">${s}</option>`).join('');
document.getElementById('scheduler').innerHTML = finalSchedulers.map(s => `<option value="${s}">${s}</option>`).join('');
const selectEl = document.getElementById('unet-select');
try {
const data = await BackendAPI.getModels();
console.log("🟢 [Init] Models 数据已拉取");
if (data.models) {
globalModelData = data.models;
selectEl.innerHTML = "";
// 引擎名进 optgroup(浏览器自动加粗),option 只留模型名 → 总宽度更短
Object.keys(data.models).forEach(modelName => {
const opt = document.createElement("option");
opt.value = modelName;
if (modelName.includes(" | ")) {
const parts = modelName.split(" | ");
const enginePart = toUnicodeBold(parts[0]);
const modelPart = parts[1];
opt.textContent = `${enginePart} | ${modelPart}`;
} else {
opt.textContent = toUnicodeBold(modelName);
}
const _wk = (data.models[modelName] || {}).warm_state; // ← 新增 2/3
if (_wk && WARM_MARK[_wk]) opt.textContent += ` ${WARM_MARK[_wk]}`;
opt.dataset.baseText = // ← 新增
modelName.includes(" | ")
? `${toUnicodeBold(modelName.split(" | ")[0])} | ${modelName.split(" | ")[1]}`
: toUnicodeBold(modelName);
selectEl.appendChild(opt);
});
let modelParam = null;
let loraParam = null;
// 优先从 Hash 解析,其次从 Search 解析
if (window.location.hash) {
const hashStr = window.location.hash.substring(1);
const hashParams = new URLSearchParams(hashStr);
modelParam = hashParams.get('model');
loraParam = hashParams.get('lora');
}
if (!modelParam) {
const urlParams = new URLSearchParams(window.location.search);
modelParam = urlParams.get('model');
loraParam = urlParams.get('lora');
}
// 🔗 prompt=1(可选):深链进入时是否套用该 LoRA 的预设 prompt
// 与已有的 ?model=&lora= 解耦:不带这个参数 → 行为完全不变
const _presetParams = new URLSearchParams(
window.location.hash ? window.location.hash.substring(1) : window.location.search
);
const _promptFlag = (_presetParams.get('prompt') || '').toLowerCase();
const wantPreset = (_promptFlag === '1' || _promptFlag === 'true');
let targetModel = Object.keys(data.models)[0];
if (modelParam) {
const targetEngine = globalRootMapping[modelParam] || modelParam;
console.log(`🔗 URL解析: ${modelParam} -> ${targetEngine}`);
for (const key of Object.keys(data.models)) {
const modelEngine = data.models[key].engine;
if (modelEngine === targetEngine) {
targetModel = key;
console.log(`✅ 成功匹配到模型: ${key} (Engine: ${modelEngine})`);
break;
}
}
}
console.log(`🟢 [Init] 准备选中模型: ${targetModel}`);
selectEl.value = targetModel;
window._currentSelectedModel = targetModel;
window._lastUsedArchitecture = globalModelData[targetModel]?.engine || "unknown";
refreshWarmMarks();
// 🔥 进入界面预热(阶梯一级:只读 UNET 头部,约 1s,不阻塞任何 UI)
scheduleWarmup(targetModel, 'lite');
const modelInfo = globalModelData[targetModel];
const infoEl = document.getElementById('model-assets-info');
if (modelInfo && infoEl) {
const te = modelInfo.te_name || "Unknown";
const vae = modelInfo.vae_name || "Unknown";
infoEl.innerHTML = `
<div class="te-vae-container">
<div class="te-wrapper">
<span class="te-label">Text Encoder: </span>
<span class="te-value">${te}</span>
</div>
<div class="vae-wrapper">
<span class="vae-label">VAE: </span>
<span class="vae-value">${vae}</span>
</div>
</div>
`;
}
const modelDefaults = globalModelData[targetModel]?.defaults || {};
if (globalModelData[targetModel]?.default_prompt !== undefined) {
document.getElementById('prompt').value = globalModelData[targetModel].default_prompt;
}
if (modelDefaults.cfg !== undefined) {
document.getElementById('cfg-slider').value = modelDefaults.cfg;
document.getElementById('cfg-input').value = Number(modelDefaults.cfg).toFixed(1);
}
if (modelDefaults.steps !== undefined) {
document.getElementById('steps-slider').value = modelDefaults.steps;
document.getElementById('steps-input').value = modelDefaults.steps;
}
if (modelDefaults.sampler !== undefined) document.getElementById('sampler').value = modelDefaults.sampler;
if (modelDefaults.scheduler !== undefined) document.getElementById('scheduler').value = modelDefaults.scheduler;
if (modelDefaults.char_lora_strength !== undefined) {
document.getElementById('char-strength').value = Number(modelDefaults.char_lora_strength).toFixed(1);
}
// 重置已选角色状态
clearSelection();
renderBaseLoras(targetModel);
window._isDataReady = true;
backendState.hasInitData = true; // ← 只有真正拿到 models 才允许置 true,供心跳重连判断
// 如果没有指定 lora 参数,则触发入场动画
const isPlainEntry = !loraParam;
await fetchAndRenderGallery(targetModel, isPlainEntry);
// 处理 URL 中指定的 LoRA 自动选中与滚动定位
if (loraParam) {
if (!loraParam.endsWith(".safetensors")) {
console.warn(`⚠️ [Init] 忽略无效的 LoRA 参数(缺少 .safetensors 后缀): ${loraParam}`);
} else {
const targetIndex = currentGalleryData.findIndex(item => item.filename === loraParam);
if (targetIndex !== -1) {
const targetItem = currentGalleryData[targetIndex];
console.log(`🟢 [Init] 数据层成功找到 LoRA: ${loraParam},位于第 ${targetIndex + 1} 个`);
// 目标卡片若还没渲染,先补齐(applyLoraSelection 要能高亮到它)
if (targetIndex >= renderedCount) {
const requiredRenderCount = Math.ceil((targetIndex + 1) / BATCH_SIZE) * BATCH_SIZE;
const tempData = currentGalleryData.slice(renderedCount, requiredRenderCount);
const grid = document.getElementById('gallery-grid');
tempData.forEach(item => {
const card = document.createElement('div');
card.className = 'lora-card';
card.dataset.filename = item.filename;
card.innerHTML = `
<img src="${item.webp}" loading="lazy" alt="${item.title}" onerror="this.src='https://via.placeholder.com/300x400?text=No+Image'">
<div class="card-info">
<div class="card-title">${item.title}</div>
</div>
`;
const cardImg = card.querySelector('img');
applyCardShimmer(card, cardImg);
bindCardClick(card, item);
grid.appendChild(card);
});
renderedCount = requiredRenderCount;
}
// 选中逻辑统一走一套
applyLoraSelection(targetItem);
// 🔗 深链套用预设 prompt(三条护栏都在函数内部,这里不做判断)
if (wantPreset) {
applyPresetForDeepLink(targetItem, targetModel);
}
// 🎯 深链滚动定位:只做一次(init 可能重跑,重复定位会打架)
if (window._focusedFor !== loraParam) {
window._focusedFor = loraParam;
focusCardInGallery(loraParam);
}
} else {
console.warn(`⚠️ [Init] 在返回的数据中不存在该 LoRA: ${loraParam}`);
}
}
}
}
} catch (e) {
console.error("❌ 初始化加载失败:", e);
selectEl.innerHTML = `<option value="">🔴 Backend Offline</option>`;
} finally {
isInitializing = false; // ← 新增:允许重连后重新初始化
document.getElementById('unet-select').disabled = false;
// ✅ 初始化期间被丢弃的重试,收尾时补一次
if (_pendingInitRetry) {
_pendingInitRetry = false;
if (!backendState.hasInitData) setTimeout(() => loadInitialData(), 0);
}
// 等待数据就绪后,平滑移除全局 Loading 遮罩
const waitForDataAndHideMask = setInterval(() => {
if (window._isDataReady) {
clearInterval(waitForDataAndHideMask);
const mask = document.getElementById('global-loading-mask');
if (mask) {
setTimeout(() => {
mask.style.opacity = '0';
setTimeout(() => mask.remove(), 300);
}, 100); // 预留 100ms 给浏览器渲染 DOM
}
}
}, 100);
}
}
// ==========================================================================
// 🖼️ Gallery & Card Rendering
// ==========================================================================
function renderBaseLoras(selectedModel) {
const container = document.getElementById('base-lora-container');
container.innerHTML = "";
const loras = globalModelData[selectedModel]?.base_loras || [];
if (loras.length === 0) {
container.innerHTML = `<div style="font-size: 12px; color: var(--text-muted);">No Base LoRA for current model</div>`;
return;
}
loras.forEach((lora) => {
const div = document.createElement('div');
div.className = 'lora-row';
div.innerHTML = `
<label>
<input type="checkbox" class="base-lora-cb" ${lora.defaultEnable ? 'checked' : ''}>
${lora.name}
</label>
<input type="number" class="strength-box base-lora-strength" value="1.0" step="0.05" title="Strength">
`;
container.appendChild(div);
});
}
// 图库请求互斥锁 + 排队(避免切模型时丢失请求)
let isGalleryFetching = false;
let _pendingGalleryReq = null;
async function fetchAndRenderGallery(modelName, triggerAnim = false) {
if (isGalleryFetching) {
// 不丢弃,记住最后一次请求,等当前这次跑完再补
_pendingGalleryReq = { modelName, triggerAnim };
console.log("⏳ 图库正在加载,已排队最新请求:", modelName);
return;
}
isGalleryFetching = true;
const grid = document.getElementById('gallery-grid');
const countEl = document.getElementById('lora-count');
// 首次加载的安全兜底提示
if (!grid.innerHTML.includes("Loading") && !grid.innerHTML.includes("Switching")) {
grid.innerHTML = `<div style="color: var(--text-muted); font-size: 13px; grid-column: span 4;">⏳ Loading character list...</div>`;
}
try {
const modelInfo = globalModelData[modelName];
if (!modelInfo || !modelInfo.engine) {
grid.innerHTML = `<div style="color: var(--text-muted); font-size: 13px; grid-column: span 4;">⏳ Backend data syncing...</div>`;
return;
}
const engineKey = modelInfo.engine;
// // 同一个架构且已经渲染过 → 不重建,避免把滚动位置抹掉
// if (!force && window._renderedEngine === engineKey && currentGalleryData.length) {
// console.log(`🖼️ 图库已是 ${engineKey},跳过重建`);
// return;
// }
const data = await BackendAPI.getLoras();
const lorasDict = data.loras || {};
const lorasForModel = lorasDict[engineKey];
if (!lorasForModel || Object.keys(lorasForModel).length === 0) {
grid.innerHTML = `<div style="color: var(--text-muted); font-size: 13px; grid-column: span 4;">No character LoRA for this model</div>`;
if (countEl) countEl.innerText = "0 Models";
return;
}
currentGalleryData = Object.entries(lorasForModel).map(([filename, info]) => ({
filename: filename,
path: info.path || "", // 🌟 深链要用(后端一直有返回,之前被丢了)
title: (info.title && String(info.title).trim()) || filename.replace(".safetensors", ""),
webp: info.webp,
trigger: info.trigger || "",
hasShowcase: !!info.has_showcase, // ← 新增
hasDataset: !!info.has_dataset, // ← 新增
hasPrompt: !!info.has_prompt // 🌟 有预设 prompt → 显示「🧩 Prompt」
}));
renderedCount = 0;
shouldAnimateNextRender = triggerAnim;
// 🔥 URL 深链(?lora=xxx / #lora=xxx):图库数据一到就并行预取大图,
// 避免"触发词已展开但预览区还在转圈"的那 1~3 秒。
// 与 loadInitialData 里真正的 bigImg.src 赋值命中同一份 HTTP 缓存。
try {
const _p = new URLSearchParams(
window.location.hash ? window.location.hash.substring(1) : window.location.search
);
const _lora = _p.get('lora');
if (_lora && !window._bigImgPrefetched) {
const _hit = currentGalleryData.find(i => i.filename === _lora);
if (_hit && _hit.webp) {
window._bigImgPrefetched = _lora;
const _pre = new Image();
_pre.decoding = 'async';
_pre.src = _hit.webp;
console.log('🔥 [Init] 预取预览大图:', _lora);
}
}
} catch (e) { /* 预取失败不影响主流程 */ }
if (countEl) countEl.innerText = `${currentGalleryData.length} Models`;
// 恢复 Grid 布局(覆盖 Loading 时的 Flex 居中)
grid.style.display = 'grid';
grid.style.height = 'auto';
const _keepTop = grid.parentElement.scrollTop; // ← 保存
grid.innerHTML = "";
loadMoreCards();
grid.parentElement.scrollTop = _keepTop; // ← 还原
// 绑定滚动到底部触发懒加载
const container = document.getElementById('gallery-container');
container.onscroll = () => {
if (container.scrollTop + container.clientHeight >= container.scrollHeight - 50) {
loadMoreCards();
}
};
} catch (error) {
console.error("Severe error in gallery request:", error);
grid.innerHTML = `<div style="color: #ff4444; font-size: 13px; grid-column: span 4;">❌ Failed to load gallery, backend may be restarting</div>`;
if (countEl) countEl.innerText = "Error";
} finally {
// 释放互斥锁
isGalleryFetching = false;
if (_pendingGalleryReq) {
const p = _pendingGalleryReq;
_pendingGalleryReq = null;
fetchAndRenderGallery(p.modelName, p.triggerAnim);
}
}
}
function applyCardShimmer(card, imgElement) {
// 强制卡片裁剪溢出内容,并确保相对定位
card.style.overflow = 'hidden';
// if (getComputedStyle(card).position === 'static') {
// card.style.position = 'relative';
// }
if (!card.style.position) {
card.style.position = 'relative';
}
const overlay = document.createElement('div');
overlay.className = 'shimmer-overlay';
// 扫光层绝对定位,覆盖图片
overlay.style.position = 'absolute';
overlay.style.inset = '0';
overlay.style.zIndex = '10';
overlay.style.transition = 'opacity 0.3s ease-out';
overlay.style.opacity = '1';
card.appendChild(overlay);
// 隐藏原图,防止逐行渲染露馅
imgElement.style.opacity = '0';
imgElement.style.transition = 'opacity 0.3s ease-out';
const revealImage = () => {
// 等待双 RAF,确保浏览器完成布局计算
requestAnimationFrame(() => {
requestAnimationFrame(() => {
imgElement.style.opacity = '1';
overlay.style.opacity = '0';
// 动画结束后移除 DOM
setTimeout(() => {
if (overlay.parentNode) {
overlay.remove();
}
}, 300);
});
});
};
if (imgElement.complete) {
if (imgElement.decode) {
imgElement.decode().then(revealImage).catch(revealImage);
} else {
revealImage();
}
} else {
imgElement.addEventListener('load', () => {
if (imgElement.decode) {
imgElement.decode().then(revealImage).catch(revealImage);
} else {
revealImage();
}
});
imgElement.addEventListener('error', () => {
imgElement.style.opacity = '1'; // 报错也显示占位图
overlay.remove();
});
}
}
// 统一的"清空选中"入口:HUD / 右列 / 大图 / 卡片高亮 一次性同步
function clearSelection() {
selectedLora = "";
const nameEl = document.getElementById("selected-lora-name");
if (nameEl) {
nameEl.innerText = "No character LoRA";
nameEl.classList.add("is-none");
}
const strengthEl = document.getElementById("char-strength");
if (strengthEl) strengthEl.disabled = true;
// 没有角色 LoRA → 复选框禁用,并复位为"未勾选"(☐ 灰,而不是 ☑ 灰)
const enableEl = document.getElementById("char-enable");
if (enableEl) {
enableEl.checked = false;
enableEl.disabled = true;
}
updatePreviewInfo(null);
updateTriggerBar("");
// 🧩 清空选中时也要清标签,否则跨架构切模型后还挂着上一个角色的 "use author preset",
// 点下去会把旧 LoRA 的预设写进新模型的 prompt
_promptSourceItem = null;
_promptPresetText = null;
setPromptHint(null);
const bigImg = document.getElementById("selected-lora-big-img");
const placeholder = document.getElementById("preview-placeholder");
const media = document.querySelector(".preview-media");
if (bigImg) {
bigImg.onload = null;
bigImg.onerror = null;
bigImg.removeAttribute("src");
delete bigImg.dataset.src;
bigImg.style.display = "none";
}
if (media) media.classList.remove("loading");
if (placeholder) placeholder.style.display = "flex";
document.querySelectorAll(".lora-card").forEach(c => c.classList.remove("selected"));
}
// 选中某个 LoRA 的统一入口(点卡片 / URL 深链 都走这里)
function applyLoraSelection(item) {
if (!item) return;
const isSameItem = (selectedLora === item.filename);
document.querySelectorAll(".lora-card").forEach(c => c.classList.remove("selected"));
const cardEl = document.querySelector(`.lora-card[data-filename="${item.filename}"]`);
if (cardEl) cardEl.classList.add("selected");
selectedLora = item.filename;
const enableEl = document.getElementById("char-enable");
const nameEl = document.getElementById("selected-lora-name");
const strengthEl = document.getElementById("char-strength");
// 选中即启用:☑ + 可点(用户仍可手动取消,取消后名字转灰)
if (enableEl) {
enableEl.disabled = false;
enableEl.checked = true;
}
const enabled = enableEl ? enableEl.checked : true;
if (nameEl) {
nameEl.innerText = item.title || item.filename.replace(/\.safetensors$/i, "");
nameEl.classList.toggle("is-none", !enabled);
}
if (strengthEl) strengthEl.disabled = !enabled;
updatePreviewInfo(item);
updateTriggerBar(item.trigger);
// 🧩 Prompt 标签状态:纯文字 UI,必须放在任何图片分支之前
refreshPromptHint(item);
const bigImg = document.getElementById("selected-lora-big-img");
const placeholder = document.getElementById("preview-placeholder");
const media = document.querySelector(".preview-media");
if (!bigImg || !placeholder) return;
// 同一张卡、图已就绪 → 不重复拉图(避免闪烁)
const alreadyShown = bigImg.style.display === "block" && bigImg.dataset.src === item.webp;
if (isSameItem && alreadyShown) return;
placeholder.style.display = "none";
bigImg.style.display = "none";
if (media) media.classList.add("loading");
bigImg.dataset.src = item.webp;
bigImg.onload = () => {
if (media) media.classList.remove("loading");
bigImg.style.display = "block";
bigImg.onload = null;
};
bigImg.onerror = () => {
if (media) media.classList.remove("loading");
bigImg.style.display = "none";
placeholder.style.display = "flex";
bigImg.onerror = null;
};
bigImg.src = item.webp;
}
function bindCardClick(card, item) {
card.addEventListener("click", () => applyLoraSelection(item));
}
// 勾掉复选框 → 名字降级 + 强度置灰("选了但不用"这个状态也要可读)
document.getElementById("char-enable").addEventListener("change", (e) => {
if (e.target.disabled) return;
const on = e.target.checked && !!selectedLora;
const nameEl = document.getElementById("selected-lora-name");
const strengthEl = document.getElementById("char-strength");
if (nameEl) nameEl.classList.toggle("is-none", !on);
if (strengthEl) strengthEl.disabled = !on;
});
// ==========================================================================
// 🎯 深链滚动定位(hidden tab 安全版)
// ==========================================================================
// 问题:右键"在新标签页打开"时文档是 hidden:
// · scrollIntoView({behavior:'smooth'}) 在隐藏文档里被直接丢弃,且不会重试
// · rAF 不执行 → 图片 shimmer / 布局在切回前台那一瞬才稳定
// · setTimeout 被节流,靠它做定位时机不可控
// 解法:把目标记成"待办",只有 visibilityState==='visible' 且几何就绪时才滚;
// 切回前台自动补做,并带少量重试(应对图片加载引起的布局微调)
let _pendingScrollTarget = "";
let _scrollRetryTimer = null;
// const SCROLL_RETRY_DELAYS = [300, 150, 200, 300, 500, 800, 1200];
const SCROLL_RETRY_DELAYS = [300, 400, 600];
function _clearScrollRetry() {
if (_scrollRetryTimer) { clearTimeout(_scrollRetryTimer); _scrollRetryTimer = null; }
}
// 用户一旦自己滚动,就放弃程序定位(用户意图优先)
function _cancelPendingScroll() {
if (!_pendingScrollTarget) return;
console.log(`🖐️ 用户接管滚动,放弃定位 ${_pendingScrollTarget}`);
_pendingScrollTarget = "";
_clearScrollRetry();
}
function _bindScrollCancelOnce() {
const gc = document.getElementById("gallery-container");
if (!gc || gc.dataset.cancelBound === "1") return;
gc.dataset.cancelBound = "1";
gc.addEventListener("wheel", _cancelPendingScroll, { passive: true });
gc.addEventListener("touchmove", _cancelPendingScroll, { passive: true });
gc.addEventListener("mousedown", _cancelPendingScroll, { passive: true });
}
function focusCardInGallery(filename) {
if (!filename) return;
_bindScrollCancelOnce(); // ← 新增这行
if (!filename) return;
_pendingScrollTarget = filename;
_clearScrollRetry();
_scrollStep(0);
}
function _scrollStep(attempt) {
const filename = _pendingScrollTarget;
if (!filename) return;
// ① 隐藏时不滚(滚了也会被丢弃),交给 visibilitychange 补做
if (document.visibilityState !== "visible") return;
const container = document.getElementById("gallery-container");
const card = document.querySelector(`.lora-card[data-filename="${CSS.escape(filename)}"]`);
// ② 几何还没就绪(布局未完成 / 跨架构清空过 / 卡片还没渲染到)→ 退避重试
const ready = container && card && container.clientHeight > 50 && card.offsetHeight > 10;
if (!ready) {
if (attempt < SCROLL_RETRY_DELAYS.length) {
_clearScrollRetry();
_scrollRetryTimer = setTimeout(() => _scrollStep(attempt + 1), SCROLL_RETRY_DELAYS[attempt]);
}
return;
}
// ③ 用容器自身 scrollTop 计算,不用 scrollIntoView(后者会连带滚动整个页面)
const cRect = container.getBoundingClientRect();
const kRect = card.getBoundingClientRect();
const desiredOffset = (container.clientHeight - card.offsetHeight) / 2;
const currentOffset = kRect.top - cRect.top;
const targetTop = Math.max(0, container.scrollTop + currentOffset - desiredOffset);
const arrived = Math.abs(currentOffset - desiredOffset) <= 24;
if (!arrived) {
container.scrollTo({ top: targetTop, behavior: "smooth" });
if (attempt < SCROLL_RETRY_DELAYS.length) {
_clearScrollRetry();
_scrollRetryTimer = setTimeout(() => _scrollStep(attempt + 1), SCROLL_RETRY_DELAYS[attempt]);
return;
}
}
console.log(`🟢 [Init] 滚动定位完成: ${filename}${arrived ? "" : "(重试兜底)"}`);
_pendingScrollTarget = "";
_clearScrollRetry();
}
// 切回前台:补做被丢弃的定位(双 rAF 让布局/shimmer 先稳定)
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && backendState.hasInitData) {
refreshWarmMarks();
}
if (document.visibilityState !== "visible" || !_pendingScrollTarget) return;
console.log("🟢 [Init] 页面已可见,补做滚动定位");
_clearScrollRetry();
requestAnimationFrame(() => requestAnimationFrame(() => _scrollStep(0)));
});
function loadMoreCards() {
const grid = document.getElementById('gallery-grid');
const nextBatch = currentGalleryData.slice(renderedCount, renderedCount + BATCH_SIZE);
if (nextBatch.length === 0) return;
nextBatch.forEach((item, index) => {
const card = document.createElement('div');
card.className = 'lora-card';
card.dataset.filename = item.filename;
// 设置动画初始状态
if (shouldAnimateNextRender) {
card.style.opacity = '0';
card.style.transform = 'translateY(20px)';
card.dataset.animateEntry = "true";
card.dataset.index = index;
}
card.innerHTML = `
<img src="${item.webp}" loading="lazy" alt="${item.title}" onerror="this.src='https://via.placeholder.com/300x400?text=No+Image'">
<div class="card-info">
<div class="card-title">${item.title}</div>
</div>
`;
const cardImg = card.querySelector('img');
applyCardShimmer(card, cardImg);
bindCardClick(card, item);
grid.appendChild(card);
// 错开延迟触发入场动画
if (shouldAnimateNextRender) {
setTimeout(() => {
applySpringAnimation(card);
}, index * ANIM_CONFIG.staggerDelay);
}
});
renderedCount += nextBatch.length;
// 关闭动画开关,确保后续滚动加载的卡片不触发入场动画
shouldAnimateNextRender = false;
}
// ==========================================
// 🪄 Animation: Physical Spring
// ==========================================
function applySpringAnimation(element) {
if (!element || element.dataset.animating === 'true') return;
element.dataset.animating = 'true';
const startY = ANIM_CONFIG.startY;
const omega0 = Math.sqrt(ANIM_CONFIG.stiffness);
const zeta = ANIM_CONFIG.damping;
const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);
const startTime = performance.now();
element.style.transition = '';
element.style.opacity = '0';
element.style.transform = `translate3d(0, ${startY}px, 0)`;
element.style.willChange = 'transform, opacity';
element.style.backfaceVisibility = 'hidden';
void element.offsetWidth;
function step(currentTime) {
const t = (currentTime - startTime) / 1000;
const envelope = Math.exp(-zeta * omega0 * t);
if (Math.abs(envelope * startY) < 0.1) {
// 动画结束:清空 transform 恢复默认状态
element.style.transform = '';
element.style.opacity = 1;
element.style.willChange = 'auto';
element.style.transition = '';
element.dataset.animating = 'false';
return;
}
const positionY = startY * envelope * Math.cos(omegaD * t);
const opacity = Math.min(t / 0.25, 1);
element.style.transform = `translate3d(0, ${positionY}px, 0)`;
element.style.opacity = opacity;
requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
// ==========================================================================
// ⚡ Event Listeners (Generate, Switch, Random Seed)
// ==========================================================================
document.getElementById('random-seed-btn').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('seed').value = Math.floor(Math.random() * 4294967295);
});
// --------------------------------------------------------------------------
// 📋 Copy Logs Logic
// --------------------------------------------------------------------------
document.getElementById('copy-log-btn').addEventListener('click', async () => {
const logContent = document.getElementById('log-content');
const logText = logContent.innerText;
try {
await navigator.clipboard.writeText(logText);
const btn = document.getElementById('copy-log-btn');
const originalText = btn.innerHTML;
btn.innerHTML = '📋 Copied';
setTimeout(() => {
btn.innerHTML = originalText;
btn.style.color = 'var(--text-muted)';
}, 2000);
} catch (err) {
console.error('Failed to copy logs:', err);
alert('Failed to copy logs.');
}
});
document.getElementById('unet-select').addEventListener('change', (e) => {
const selectedModel = e.target.value;
// 先把下拉的新值画出来,再跑后面那堆 DOM 工作
requestAnimationFrame(() => handleModelSwitch(selectedModel));
});
async function handleModelSwitch(selectedModel) {
const currentEngine = globalModelData[selectedModel]?.engine || "unknown";
const lastEngine = window._lastUsedArchitecture || null;
const isCrossArchitecture = (lastEngine !== null && lastEngine !== currentEngine);
// 更新 TE 和 VAE 的展示
const modelInfo = globalModelData[selectedModel];
const infoEl = document.getElementById('model-assets-info');
if (modelInfo && infoEl) {
const te = modelInfo.te_name || "Unknown";
const vae = modelInfo.vae_name || "Unknown";
infoEl.innerHTML = `
<div class="te-vae-container">
<div class="te-wrapper">
<span class="te-label">Text Encoder: </span>
<span class="te-value">${te}</span>
</div>
<div class="vae-wrapper">
<span class="vae-label">VAE: </span>
<span class="vae-value">${vae}</span>
</div>
</div>
`;
}
// 跨架构切换:立即清空旧 DOM,防止视觉残留
if (isCrossArchitecture) {
const grid = document.getElementById('gallery-grid');
// 临时切换为 Flex 居中,用于显示 Loading 提示
grid.style.display = 'flex';
grid.style.justifyContent = 'center';
grid.style.alignItems = 'center';
grid.style.height = '100%';
grid.innerHTML = `<div style="color: var(--text-muted); font-size: 13px;">⏳ Loading LoRAs...</div>`;
document.getElementById('lora-count').innerText = "Loading...";
currentGalleryData = [];
renderedCount = 0;
}
// 处理 Prompt 覆盖
const promptEl = document.getElementById('prompt');
const lastModelName = window._currentSelectedModel || null;
const previousDefaultPrompt = lastModelName ? (globalModelData[lastModelName]?.default_prompt || "") : "";
if (!promptEl.value.trim() || promptEl.value === previousDefaultPrompt) {
if (globalModelData[selectedModel]?.default_prompt) {
promptEl.value = globalModelData[selectedModel].default_prompt;
}
}
// 更新模型默认参数
const modelDefaults = globalModelData[selectedModel]?.defaults || {};
if (modelDefaults.cfg !== undefined) {
document.getElementById('cfg-slider').value = modelDefaults.cfg;
document.getElementById('cfg-input').value = Number(modelDefaults.cfg).toFixed(1);
}
if (modelDefaults.steps !== undefined) {
document.getElementById('steps-slider').value = modelDefaults.steps;
document.getElementById('steps-input').value = modelDefaults.steps;
}
if (modelDefaults.sampler !== undefined) {
document.getElementById('sampler').value = modelDefaults.sampler;
}
if (modelDefaults.scheduler !== undefined) {
document.getElementById('scheduler').value = modelDefaults.scheduler;
}
if (modelDefaults.char_lora_strength !== undefined && (isCrossArchitecture || !selectedLora)) {
document.getElementById('char-strength').value = Number(modelDefaults.char_lora_strength).toFixed(1);
}
// 核心逻辑:仅跨架构时需要重新拉取图库数据
if (isCrossArchitecture) {
// 跨架构:清空已选角色,换 Base LoRA,重新拉数据(并传 true 触发入场动画)
clearSelection();
renderBaseLoras(selectedModel);
fetchAndRenderGallery(selectedModel, true); // 后台异步加载,不阻塞事件
// 强制滚动到图库顶部
const galleryContainer = document.getElementById('gallery-container');
if (galleryContainer) galleryContainer.scrollTop = 0;
} else {
// 同架构:跳过网络请求,保留 DOM 和滚动位置
console.log("🔄 Same architecture, keeping gallery and Base LoRAs intact.");
}
// 更新全局记录
window._currentSelectedModel = selectedModel;
window._lastUsedArchitecture = currentEngine;
// 🔥 用户已明确选了模型 → 立刻预热(时间窗最长:他还要改 prompt / 调参 / 挑角色)
scheduleWarmup(selectedModel, 'full');
refreshWarmMarks(); // ← 立刻(几十毫秒)
setTimeout(refreshWarmMarks, 2000); // ← 预热跑起来了
setTimeout(refreshWarmMarks, 6000); // ← 预热通常已完成,校正成 ●
};
document.getElementById('generate-btn').addEventListener('click', async () => {
if (!backendState.isReady) {
alert("Backend is waking up. Please wait a few seconds and try again!");
return;
}
const resultImage = document.getElementById('result-image');
const placeholderText = document.getElementById('placeholder-text');
const generateBtn = document.getElementById('generate-btn');
const prompt = document.getElementById('prompt').value.trim();
const unet_choice = document.getElementById('unet-select').value;
const custom_w = parseInt(document.getElementById('width-input').value);
const custom_h = parseInt(document.getElementById('height-input').value);
const steps = parseInt(document.getElementById('steps-input').value);
const cfg = parseFloat(document.getElementById('cfg-input').value);
const sampler = document.getElementById('sampler').value;
const scheduler = document.getElementById('scheduler').value;
const seedVal = document.getElementById('seed').value;
const seed = seedVal === "" ? -1 : parseInt(seedVal);
if (!unet_choice || unet_choice.includes('Loading') || unet_choice.includes('Backend Offline')) {
alert("Please select a valid Base Model first."); return;
}
if (!prompt) {
alert("Please enter a prompt.");
return;
}
const baseLoraStates = [];
document.querySelectorAll('#base-lora-container .lora-row').forEach(row => {
const isChecked = row.querySelector('.base-lora-cb').checked;
const rawBaseLoRAStrength = parseFloat(row.querySelector('.base-lora-strength').value);
const baseLoRAStrength = Number.isFinite(rawBaseLoRAStrength) ? rawBaseLoRAStrength : 1.0;
baseLoraStates.push(isChecked, baseLoRAStrength);
});
const charEnable = document.getElementById('char-enable').checked;
const rawCharStrength = parseFloat(document.getElementById('char-strength').value);
const charStrength = Number.isFinite(rawCharStrength) ? rawCharStrength : 1.0;
const requestData = {
prompt: prompt,
unet_choice: unet_choice,
custom_w: custom_w,
custom_h: custom_h,
steps: steps,
cfg: cfg,
seed: seed,
sampler: sampler,
scheduler: scheduler,
char_enable: charEnable,
char_lora: selectedLora || "",
char_strength: charStrength,
base_lora_states: baseLoraStates
};
console.log("🚀 Submitting parameters:", requestData);
if (!requestData.prompt || !requestData.unet_choice || !requestData.custom_w) {
alert("Missing parameters. Please check Prompt / Model / Dimensions.");
return;
}
generateBtn.disabled = true;
generateBtn.innerText = "⏳ Submitting...";
// 清掉上一张图 + 占位符,换成点阵加载动画
resultImage.classList.remove('reveal');
resultImage.style.display = 'none';
placeholderText.style.display = 'none';
GenLoader.show();
generateStartTime = Date.now();
currentStageStartTime = generateStartTime;
currentStageName = "Task Queued";
document.getElementById('log-content').innerHTML = "";
if (window._lastGeneratedModel !== unet_choice) {
const currentEngine = globalModelData[unet_choice]?.engine || "unknown";
const lastModel = window._lastGeneratedModel;
const lastEngine = lastModel ? (globalModelData[lastModel]?.engine || "unknown") : null;
if (lastEngine && lastEngine !== currentEngine) {
addLog(`🔄 Arch Switch: Loading UNet/VAE/TE (Full Swap)...`, "highlight");
} else if (lastEngine === currentEngine) {
addLog(`🔄 Model Update: Swapping UNet (Keep VAE/TE)...`, "highlight");
} else {
addLog(`🔄 Initializing: Loading UNet/VAE/TE (First Load)...`, "highlight");
}
window._lastGeneratedModel = unet_choice;
}
addLog("Task submitted to backend.", "highlight");
try {
const taskId = await BackendAPI.submitGenerate(requestData);
addLog(`Task ID: ${taskId}`);
BackendAPI.pollStatus(taskId, {
onProcessing: (msg) => {
let safeMsg = msg || "🎨 Processing...";
let newStage = "Processing";
// 阶段分类映射(⚠️ 顺序敏感:预热必须排最前,
// 因为 "Waiting for model files" 里含 "Waiting",会被误判成 Queueing)
if (safeMsg.includes("Preparing model files") || safeMsg.includes("Waiting for model files")) {
newStage = "Model Warmup";
}
else if (safeMsg.includes("Rendering") || safeMsg.includes("steps") || safeMsg.includes("Sampling") || safeMsg.includes("KSampler")) {
newStage = "Comfy Backend - Sampling";
}
else if (safeMsg.includes("Downloading")) {
newStage = "Downloading";
}
else if (safeMsg.includes("Requesting") || safeMsg.includes("Waiting") || safeMsg.includes("Queue")) {
newStage = "Queueing";
}
else if (safeMsg.includes("Allocating") || safeMsg.includes("GPU Acquired") || safeMsg.includes("Loading") || safeMsg.includes("Executing") || safeMsg.includes("Workflow")) {
newStage = "Comfy Backend - Model Loading";
}
// 防止状态在 Sampling/Loading 时被排队信息回退覆盖
// ⚠️ 必须排除预热消息(它里面的 "Waiting" 不算排队)
const _isWarmupMsg = safeMsg.includes("model files");
if ((currentStageName === "Comfy Backend - Model Loading" || currentStageName === "Comfy Backend - Sampling")
&& !_isWarmupMsg
&& (safeMsg.includes("Requesting") || safeMsg.includes("Waiting") || safeMsg.includes("Queue"))) {
return;
}
// 阶段切换计时与日志
if (newStage !== currentStageName && newStage !== "Processing") {
const now = Date.now();
const prevDuration = ((now - currentStageStartTime) / 1000).toFixed(1);
if (currentStageName !== "Task Queued" && currentStageName !== "Processing") {
addLog(`⏱️ ${currentStageName} finished in ${prevDuration}s.`);
}
currentStageName = newStage;
currentStageStartTime = now;
addLog(`🚀 Starting ${newStage}...`);
}
// 🔥 预热阶段:按 5% 步进去重打印,避免每个 32MB chunk 刷一行
if (currentStageName === "Model Warmup") {
const lc = document.getElementById('log-content');
const ll = lc.lastElementChild;
const pm = safeMsg.match(/(\d+)%/);
const pct = pm ? parseInt(pm[1], 10) : -1;
const lastPct = (ll && ll.dataset.warmPct !== undefined)
? parseInt(ll.dataset.warmPct, 10) : -2;
if (pct === -1 || lastPct === -2 || Math.abs(pct - lastPct) >= 5) {
const line = document.createElement('div');
line.className = 'log-line';
line.dataset.warmPct = pct;
line.innerText = `[${new Date().toLocaleTimeString('en-US', { hour12: false })}] ${safeMsg}`;
lc.appendChild(line);
if (lc.childElementCount > 100) lc.firstElementChild.remove();
}
smartScroll();
return;
}
// ⏳ Queueing 阶段本地秒级提示(后端排队时只发一次消息,这里自己计时)
if (currentStageName === "Queueing") {
const qElapsed = parseInt((Date.now() - currentStageStartTime) / 1000, 10);
if (qElapsed >= 10 && qElapsed % 5 === 0) {
const lc = document.getElementById('log-content');
const ll = lc.lastElementChild;
const m = ll ? ll.innerText.match(/\((\d+)s\)/) : null;
if (!m || parseInt(m[1], 10) !== qElapsed) {
addLog(`⏳ Waiting for GPU... (${qElapsed}s) — 首次调用可能需要 30–60 秒`);
}
}
smartScroll();
return;
}
const logContent = document.getElementById('log-content');
const lastLog = logContent.lastElementChild;
const lastText = lastLog ? lastLog.innerText : "";
// 处理纯渲染状态(无 steps 信息)
if (safeMsg.includes("Rendering image (GPU processing)") && !safeMsg.includes("steps")) {
const elapsed = ((Date.now() - currentStageStartTime) / 1000).toFixed(0);
const lastLine = logContent.lastElementChild ? logContent.lastElementChild.innerText : "";
const lastElapsedMatch = lastLine.match(/\((\d+)s\)/);
if (!lastLine.includes("Rendering image") || !lastElapsedMatch || parseInt(lastElapsedMatch[1]) !== parseInt(elapsed)) {
addLog(`🎨 Rendering image (GPU processing)... (${elapsed}s)`);
}
smartScroll();
return;
}
// 处理带 steps 的精确进度
if (safeMsg.includes("steps")) {
if (currentStageName !== "Comfy Backend - Sampling") {
const now = Date.now();
const prevDuration = ((now - currentStageStartTime) / 1000).toFixed(1);
if (currentStageName === "Comfy Backend - Model Loading") {
addLog(`⏱️ Comfy Backend - Model Loading finished in ${prevDuration}s.`, "normal");
addLog(`🚀 Starting Comfy Backend - Sampling...`, "normal");
}
currentStageName = "Comfy Backend - Sampling";
currentStageStartTime = now;
}
const lastLine = logContent.lastElementChild;
if (!lastLine || !lastLine.innerText.includes(safeMsg)) {
addLog(`\u2003\u2003${safeMsg}`, "normal");
}
smartScroll();
return;
}
// 过滤重复的 VRAM 等待信息
if (currentStageName === "Loading VRAM" && !safeMsg.includes("Executing") && (safeMsg.includes("Waiting for GPU") || safeMsg.includes("Queue for GPU"))) {
return;
}
// 秒级心跳日志(避免同一秒内重复打印)
if (safeMsg.includes("Loading") || safeMsg.includes("Swapping") || safeMsg.includes("Waiting") || safeMsg.includes("GPU Acquired") || safeMsg.includes("Queue") || safeMsg.includes("Executing") || safeMsg.includes("Sampling") || safeMsg.includes("KSampler") || currentStageName === "Comfy Backend - Sampling") {
const elapsed = ((Date.now() - currentStageStartTime) / 1000).toFixed(0);
const lastLine = logContent.lastElementChild;
let isNewSecond = true;
if (lastLine && lastLine.dataset.lastElapsed === elapsed) {
isNewSecond = false;
}
if (isNewSecond) {
const newLine = document.createElement('div');
newLine.className = 'log-line';
let displayMsg = safeMsg;
if (currentStageName === "Comfy Backend - Model Loading") {
displayMsg = "📦 Loading tensors to VRAM...";
} else if (currentStageName === "Comfy Backend - Sampling") {
displayMsg = "🎨 Running KSampler...";
}
newLine.innerText = `[${new Date().toLocaleTimeString('en-US', { hour12: false })}] ${displayMsg} (Elapsed: ${elapsed}s)`;
newLine.dataset.lastElapsed = elapsed;
logContent.appendChild(newLine);
if (logContent.childElementCount > 100) {
logContent.firstElementChild.remove();
}
}
}
else {
if (!lastText.includes(safeMsg)) {
addLog(safeMsg);
}
}
smartScroll()
},
onSuccess: async (imageBase64, returnedSeed, metrics, filename) => {
placeholderText.style.display = 'none';
console.log("🚨 DEBUG METRICS:", JSON.stringify(metrics));
console.log("✅ 后端返回的正确文件名:", filename);
const now = Date.now();
const totalDuration = ((now - generateStartTime) / 1000).toFixed(1);
const nowForStage = Date.now();
const prevStageDuration = ((nowForStage - currentStageStartTime) / 1000).toFixed(1);
// 补齐最后阶段的时间日志
if (currentStageName === "Comfy Backend - Model Loading") {
addLog(`⏱️ Comfy Backend - Model Loading finished in ${prevStageDuration}s.`, "normal");
addLog(`🚀 Starting Comfy Backend - Sampling...`, "normal");
const realSteps = metrics?.steps || "?";
addLog(`🎨 Rendering: ${realSteps}/${realSteps} steps (100%)`, "normal");
const pureRender = metrics ? (metrics.workflow - metrics.load_time) : 0;
addLog(`⏱️ Comfy Backend - Sampling finished in ${pureRender > 0 ? pureRender.toFixed(2) : "0.0"}s.`, "normal");
} else if (currentStageName === "Comfy Backend - Sampling") {
addLog(`⏱️ Comfy Backend - Sampling finished in ${prevStageDuration}s.`, "normal");
} else if (currentStageName === "Queueing" || currentStageName === "Comfy Workflow") {
addLog(`⏱️ Task execution completed. Syncing final stages...`, "normal");
}
addLog("✅ Generation successful!", "highlight");
addLog(`⏱️ Total Wait Time: ${totalDuration}s`, "highlight");
if (metrics) {
addLog(`----------------------------------------`, "normal");
addLog(`📊 [Backend Precise Metrics]`, "highlight");
const dl = Number(metrics.download || 0);
const q = Number(metrics.queue || 0);
const wf = Number(metrics.workflow || 0);
const load = Number(metrics.load_time || 0);
const pureRender = wf - load > 0 ? (wf - load) : wf;
const serverComputeTotal = (dl + q + wf).toFixed(2);
const networkOverhead = Math.max(0, totalDuration - serverComputeTotal).toFixed(1);
const secPerStep = pureRender > 0 && metrics.steps > 0 ? (pureRender / metrics.steps).toFixed(2) : 0;
const metricsLines = [
`\u2003\u2003⬇️ Resource Download: ${dl.toFixed(2)}s`,
`\u2003\u2003⏳ GPU Queue: ${q.toFixed(2)}s`,
load > 0 ? `\u2003\u2003📦 Model Loading: ${load.toFixed(2)}s` : null,
`\u2003\u2003🎨 Pure Compute (Sampler & Decode): ${pureRender.toFixed(2)}s (${metrics.steps} steps)`,
secPerStep > 0 ? `\u2003\u2003🚀 Average Speed: ${secPerStep}s / step` : null,
`\u2003\u2003🌐 Network Overhead: ~${networkOverhead}s`,
`\u2003\u2003⚙️ Server Compute Total: ${serverComputeTotal}s`
].filter(Boolean);
// 逐行打印 Metrics(打字机效果)
let currentIndex = 0;
const typeMetrics = () => {
if (currentIndex < metricsLines.length) {
requestAnimationFrame(() => {
addLog(metricsLines[currentIndex], "normal");
smartScroll();
currentIndex++;
setTimeout(typeMetrics, 120);
});
} else {
setTimeout(() => {
addLog(`----------------------------------------`, "normal");
smartScroll();
if (returnedSeed !== undefined && returnedSeed !== null) {
addLog(`🎲 Random Seed resolved to: ${returnedSeed}`, "highlight");
smartScroll();
}
}, 300);
}
};
typeMetrics();
} else {
addLog(`⚠️ [Backend Metrics Missing]`, "error");
}
// 阶段三:预加载 + decode → 等动画走完当前一轮 → 淡入 + 轻微放大
// ⚠️ 顺序不能变:decode 成功(图片已可绘制) → GenLoader.hide 渐隐 → reveal 动画
const finalSrc = imageBase64.startsWith('data:')
? imageBase64
: `${imageBase64}?t=${Date.now()}`;
// 1) 预加载到独立 Image,decode 成功 = 浏览器保证能立刻绘制,无空白帧
const pre = new Image();
// 同源 / 跨域都加 decode,不设置 crossOrigin(除非要读像素)
const preReady = new Promise((resolve, reject) => {
pre.onload = () => {
if (pre.decode) {
pre.decode().then(resolve).catch(resolve); // decode 失败也放行,避免 UI 卡死
} else {
resolve();
}
};
pre.onerror = reject;
});
// 2) 8s 超时兜底:极端弱网下别让 GenLoader 一直转
const TIMEOUT_MS = 8000;
const guarded = Promise.race([
preReady,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('image preload timeout')), TIMEOUT_MS)
),
]);
pre.src = finalSrc; // 触发加载
guarded
.then(() => {
GenLoader.hideNow();
resultImage.classList.remove('reveal');
resultImage.src = finalSrc; // 命中缓存,不会二次网络请求
resultImage.style.display = 'block';
void resultImage.offsetWidth; // 强制 reflow,保证动画从初始态起跑
resultImage.classList.add('reveal');
setUIState(false);
refreshWarmMarks(); // ← 加这行
// 3) 图片已可绘制 —— 等点阵动画走完 → 揭示(同一 URL 命中缓存,0 延迟)
// GenLoader.hide(() => {
// resultImage.classList.remove('reveal');
// resultImage.src = finalSrc; // 命中缓存,不会二次网络请求
// resultImage.style.display = 'block';
// void resultImage.offsetWidth; // 强制 reflow,保证动画从初始态起跑
// resultImage.classList.add('reveal');
// setUIState(false);
// });
})
.catch((err) => {
console.warn('[Result Image] preload/decode failed:', err);
// 降级:仍然揭示(避免用户以为生成失败),但跳过动画由 CSS 兜底
GenLoader.hideNow();
resultImage.classList.remove('reveal');
resultImage.src = finalSrc;
resultImage.style.display = 'block';
void resultImage.offsetWidth;
resultImage.classList.add('reveal');
setUIState(false);
refreshWarmMarks();
});
},
onError: (msg) => {
let shortMsg = msg;
if (msg && msg.length > 60) {
shortMsg = msg.substring(0, 60) + "...";
}
GenLoader.hideNow(); // ← 新增
placeholderText.style.display = 'block';
placeholderText.innerText = `❌ Failed: ${shortMsg}`;
setUIState(false);
addLog(`❌ Error: ${msg}`, "error");
}
});
} catch (error) {
GenLoader.hideNow(); // ← 新增
placeholderText.style.display = 'block';
placeholderText.innerText = `❌ Request failed: ${error.message}`;
setUIState(false);
addLog(`❌ Request Error: ${error.message}`, "error");
}
});
// ==========================================================================
// 🚀 Initialization (double-execution guard)
// ==========================================================================
let isAppInitialized = false; // 初始化锁
document.addEventListener("DOMContentLoaded", async () => {
// 并发锁:防止重复触发 DOMContentLoaded
if (isAppInitialized) {
console.log("⚠️ [Init] 拦截到重复的 DOMContentLoaded,已忽略。");
return;
}
isAppInitialized = true;
// 兜底策略:10秒超时后强制解除 Loading 状态(只摘遮罩,不代表数据已就绪)
setTimeout(() => {
window._isDataReady = true;
}, 10000);
console.log("🔥 触发初始化...");
setUIState(false);
try {
const isHealthy = await BackendAPI.checkHealth();
if (isHealthy) {
console.log("✅ 后端在线,开始拉取数据");
backendState.isReady = true;
document.getElementById('backend-status-dot').className = "status-dot online";
setUIState(false);
await loadInitialData();
} else {
console.warn("⚠️ 首次心跳失败,启动后台轮询...");
document.getElementById('backend-status-dot').className = "status-dot offline";
startHealthPolling();
await loadInitialData();
}
} catch (error) {
console.error("❌ 初始化发生严重错误:", error);
document.getElementById('backend-status-dot').className = "status-dot offline";
startHealthPolling();
}
});
// ==========================================================================
// 🔥 Heartbeat Re-warm (visible tab → light touch every 10 min)
// already warm → backend returns "skipped" (≈0 cost); not warm → background refill, never blocks UI
// ==========================================================================
setInterval(() => {
if (document.visibilityState !== 'visible') return;
const unet = document.getElementById('unet-select')?.value;
if (unet) scheduleWarmup(unet, 'touch');
}, 10 * 60 * 1000);
// commit@70f742a386b9cbbfd6df774b19d727485ef5446f
// ==========================================================================
// 🛡️ Dynamic API Base URL
// ==========================================================================
const hostname = window.location.hostname;
let API_BASE_URL = "";
// --------------------------------------------------------------------------
// GUI Space Only: Anonymous Quota Warning (floating / auto-dismiss / manual close)
// --------------------------------------------------------------------------
if (hostname.includes("universal-lora-studio-gui")) {
setTimeout(() => {
if (document.getElementById('gui-anon-warning')) return;
const toast = document.createElement('div');
toast.id = 'gui-anon-warning';
toast.style.cssText = `
position: fixed;
top: 24px;
right: 24px;
background-color: rgba(42, 42, 42, 0.95);
color: #FF7F50;
border: 1px solid #444;
padding: 12px 16px;
border-radius: 8px;
font-size: 13px;
font-weight: 500;
z-index: 99999;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
display: flex;
align-items: flex-start;
gap: 12px;
box-shadow: 0 8px 24px rgba(0,0,0,0.6);
backdrop-filter: blur(8px);
animation: slideInRight 0.4s ease-out;
max-width: 320px;
`;
toast.innerHTML = `
<div style="flex: 1; line-height: 1.5; color: #ccc;">
⚠️ [For Testing Only] You are using the <b style="color: #FF7F50;">Anonymous Quota</b>. It depletes very quickly.
<div style="margin-top: 10px;">
<a href="https://huggingface.co/spaces/waveshaker/universal-lora-studio" target="_blank" style="display: inline-block; color: #fff; background: #FF7F50; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-weight: bold; font-size: 12px;">
Switch to Studio ↗
</a>
</div>
</div>
<button id="close-anon-warning" style="background: transparent; border: none; color: #888; font-size: 18px; cursor: pointer; padding: 0; line-height: 1; transition: color 0.2s;" onmouseover="this.style.color='#fff'" onmouseout="this.style.color='#888'">
×
</button>
`;
const style = document.createElement('style');
style.innerHTML = `
@keyframes slideInRight {
from { opacity: 0; transform: translateX(40px); }
to { opacity: 1; transform: translateX(0); }
}
`;
document.head.appendChild(style);
document.body.appendChild(toast);
// 封装关闭逻辑
const closeToast = () => {
if (!document.getElementById('gui-anon-warning')) return;
toast.style.opacity = '0';
toast.style.transform = 'translateX(40px)';
toast.style.transition = 'all 0.3s';
setTimeout(() => toast.remove(), 300);
};
// 绑定手动关闭
document.getElementById('close-anon-warning').onclick = closeToast;
// 绑定 10 秒自动关闭
setTimeout(closeToast, 10000);
}, 100);
}
// --------------------------------------------------------------------------
// Environment Routing
// --------------------------------------------------------------------------
// 1. GUI 预览环境
if (hostname.includes("universal-lora-studio-gui")) {
API_BASE_URL = "https://waveshaker-universal-lora-studio-test.hf.space";
}
// 2. 本地开发环境
else if (hostname === "localhost" || hostname === "127.0.0.1") {
API_BASE_URL = "https://waveshaker-universal-lora-studio-test.hf.space";
}
// 3. 测试环境 (Test Space)
else if (hostname.includes("universal-lora-studio-test")) {
API_BASE_URL = ""; // 同源,走相对路径
}
// 4. 线上环境 (Prod Space)
else if (hostname.includes("universal-lora-studio.hf.space") || hostname.includes("universal-lora-studio.static")) {
API_BASE_URL = ""; // 同源,走相对路径
}