// ---
// Filename: ../ComfyUI_INSTARAW/js/batch_image_generator.js
// Batch Image Generator - Real-time Progress UI
// Following RPG patterns exactly for clean, growing layout
// ---
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { renderComboCards, getComboMaxLength } from "./shared/combo-cards.js";
// Job state constants (match Python JobState enum)
const JobState = {
PENDING: "pending",
GENERATING: "generating",
SUCCESS: "success",
FAILED: "failed",
CACHED: "cached",
RETRYING: "retrying",
CANCELLED: "cancelled",
};
// State styling
const STATE_CONFIG = {
[JobState.PENDING]: { class: "pending", text: "Pending", icon: "âŗ" },
[JobState.GENERATING]: { class: "in-progress", text: "Generating...", icon: "đ" },
[JobState.SUCCESS]: { class: "success", text: "Complete", icon: "â" },
[JobState.FAILED]: { class: "error", text: "Failed", icon: "â" },
[JobState.CACHED]: { class: "cached", text: "Cached", icon: "đĻ" },
[JobState.RETRYING]: { class: "retrying", text: "Retrying...", icon: "đ" },
[JobState.CANCELLED]: { class: "cancelled", text: "Cancelled", icon: "â" },
};
console.log("[BIG] ========== BATCH IMAGE GENERATOR JS LOADED ==========");
// Load PhotoSwipe dynamically from CDN
let photoSwipeLoadPromise = null;
const loadPhotoSwipe = () => {
if (photoSwipeLoadPromise) return photoSwipeLoadPromise; // Already loading/loaded
// Check if PhotoSwipe was loaded by something else (e.g., cached local files)
if (window.PhotoSwipe) {
console.warn("[BIG] PhotoSwipe already exists on window - might be from cached local files. Forcing CSS load...");
// Force load CSS from CDN (local files don't include CSS)
const css = document.createElement('link');
css.rel = 'stylesheet';
css.href = 'https://cdn.jsdelivr.net/npm/photoswipe@5.4.3/dist/photoswipe.css';
document.head.appendChild(css);
console.log("[BIG] Loaded PhotoSwipe CSS from CDN");
photoSwipeLoadPromise = Promise.resolve();
return photoSwipeLoadPromise;
}
photoSwipeLoadPromise = new Promise((resolve, reject) => {
// Load CSS from CDN
const css = document.createElement('link');
css.rel = 'stylesheet';
css.href = 'https://cdn.jsdelivr.net/npm/photoswipe@5.4.3/dist/photoswipe.css';
css.onerror = () => console.error("[BIG] PhotoSwipe CDN CSS failed to load!");
css.onload = () => console.log("[BIG] PhotoSwipe CSS loaded from CDN");
document.head.appendChild(css);
// Load JS
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/photoswipe@5.4.3/dist/umd/photoswipe.umd.min.js';
script.onload = () => {
const lightboxScript = document.createElement('script');
lightboxScript.src = 'https://cdn.jsdelivr.net/npm/photoswipe@5.4.3/dist/umd/photoswipe-lightbox.umd.min.js';
lightboxScript.onload = () => {
console.log("[BIG] PhotoSwipe scripts loaded");
resolve();
};
lightboxScript.onerror = reject;
document.head.appendChild(lightboxScript);
};
script.onerror = reject;
document.head.appendChild(script);
});
return photoSwipeLoadPromise;
};
// Start loading PhotoSwipe on startup (don't await - it's background)
loadPhotoSwipe().then(() => {
console.log("[BIG] PhotoSwipe ready");
}).catch(e => {
console.error("[BIG] Failed to load PhotoSwipe:", e);
});
app.registerExtension({
name: "Comfy.INSTARAW.BatchImageGenerator",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "INSTARAW_BatchImageGenerator") {
console.log("[BIG] Registering custom UI for BatchImageGenerator");
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
onNodeCreated?.apply(this, arguments);
console.log("[BIG] Node created, setting up custom UI");
const node = this;
let cachedHeight = 180;
let isUpdatingHeight = false;
// Create hidden widget to store node identifier (needed for file paths)
// Uses a stable unique ID that persists across sessions
if (!node._ni_widget) {
node._ni_widget = node.addWidget("text", "node_identifier", "", () => {}, { serialize: true });
node._ni_widget.hidden = true;
}
// Generate stable unique ID only if not already set (preserve across saves/loads)
if (!node._ni_widget.value || node._ni_widget.value === "" || node._ni_widget.value === "undefined") {
// Use node.id as base - it's unique within the workflow
node._ni_widget.value = String(node.id);
console.log("[BIG] Generated node_identifier:", node._ni_widget.value);
}
// Create hidden widget to store generated batch data (RPG pattern)
if (!node.widgets?.find(w => w.name === "generated_batch_data")) {
const genBatchWidget = node.addWidget("text", "generated_batch_data", "[]", () => {}, { serialize: true });
genBatchWidget.hidden = true;
console.log("[BIG] Created generated_batch_data widget");
}
// Session storage key - uses node ID only for simplicity
// Node IDs are unique within a ComfyUI session
const getSessionKey = () => {
// Use a simple key based on node ID - it's unique per node in the session
return `instaraw_big_${node.id}`;
};
// Save to session storage (survives tab switches!)
const saveToSession = (data) => {
try {
const key = getSessionKey();
sessionStorage.setItem(key, data);
console.log(`[BIG] đž Saved to sessionStorage[${key}]: ${data.length} chars`);
} catch (e) {
console.warn("[BIG] Failed to save to session storage:", e);
}
};
// Restore from session storage, node.properties, or widget
const restoreFromWidget = () => {
try {
let dataSource = null;
let sourceName = "";
// 1. Try session storage first (survives tab switches!)
const sessionKey = getSessionKey();
const sessionData = sessionStorage.getItem(sessionKey);
if (sessionData && sessionData !== "[]" && sessionData.length > 2) {
dataSource = sessionData;
sourceName = "sessionStorage";
}
// 2. Then try properties
else if (node.properties?.big_jobs_data && node.properties.big_jobs_data !== "[]") {
dataSource = node.properties.big_jobs_data;
sourceName = "properties";
}
// 3. Finally try widget
else {
const genBatchWidget = node.widgets?.find(w => w.name === "generated_batch_data");
if (genBatchWidget && genBatchWidget.value && genBatchWidget.value !== "[]") {
dataSource = genBatchWidget.value;
sourceName = "widget";
}
}
if (dataSource) {
const batchData = JSON.parse(dataSource);
if (batchData && batchData.length > 0) {
console.log(`[BIG] đ Restoring ${batchData.length} jobs from ${sourceName}`);
// Reconstruct image URLs from filenames (we don't store base64 anymore)
// Images are saved to: {ComfyUI}/output/{subdir}/{filename}
// Use ComfyUI's standard /view endpoint to serve them
let reconstructedCount = 0;
batchData.forEach(job => {
// Reconstruct URL if:
// - Job has filename and is success/cached
// - AND either no URL, or URL is base64, or URL uses old formats
const needsReconstruction = job.filename &&
(job.state === "success" || job.state === "cached") &&
(!job.image_url ||
job.image_url.startsWith("data:") ||
job.image_url.startsWith("/extensions/") ||
job.image_url.startsWith("/instaraw/batch_gen_image/"));
if (needsReconstruction) {
// Support both new 'subfolder' and legacy 'output_subdir' keys
// Note: Empty string "" means root output folder (no subfolder)
let subdir;
if ('subfolder' in job) {
subdir = job.subfolder; // Could be "" for root folder
} else if ('output_subdir' in job) {
subdir = job.output_subdir;
} else {
subdir = ""; // Default to root output folder
}
// Use ComfyUI's standard /view endpoint
job.image_url = `/view?filename=${encodeURIComponent(job.filename)}&subfolder=${encodeURIComponent(subdir)}&type=output`;
console.log(`[BIG] đ Reconstructed URL for job ${job.id}: filename="${job.filename}", subdir="${subdir}" â ${job.image_url}`);
reconstructedCount++;
} else if (!job.filename && (job.state === "success" || job.state === "cached")) {
console.warn(`[BIG] â ī¸ Job ${job.id} is ${job.state} but has NO filename! Cannot reconstruct URL.`);
}
});
if (reconstructedCount > 0) {
console.log(`[BIG] đ Reconstructed ${reconstructedCount} image URLs from filenames`);
} else {
console.log(`[BIG] âšī¸ No URLs needed reconstruction. Job details:`);
batchData.forEach(j => {
console.log(`[BIG] Job ${j.id}: state="${j.state}", filename="${j.filename || 'NULL'}", hasUrl=${!!j.image_url}, urlPrefix="${j.image_url?.substring(0, 50) || 'none'}"`);
});
}
// Validate existing image URLs
let invalidUrlCount = 0;
batchData.forEach(job => {
if (job.image_url) {
const isBase64 = job.image_url.startsWith("data:");
const isTempUrl = job.image_url.includes("type=temp");
if (isTempUrl) {
job._urlNeedsValidation = true;
invalidUrlCount++;
}
}
});
if (invalidUrlCount > 0) {
console.log(`[BIG] â ī¸ ${invalidUrlCount} jobs have temp URLs that may need validation`);
}
// For jobs in "generating"/"retrying" state, we'll check backend status
// Don't mark as failed yet - backend might still have results!
const generatingJobs = batchData.filter(j => j.state === "generating" || j.state === "retrying");
const pendingJobs = batchData.filter(j => j.state === "pending");
if (generatingJobs.length > 0) {
console.log(`[BIG] đ ${generatingJobs.length} jobs were generating - checking backend...`);
// Schedule async backend check (don't block restore)
setTimeout(() => checkBackendProgress(batchData), 100);
}
if (pendingJobs.length > 0) {
console.log(`[BIG] âšī¸ ${pendingJobs.length} pending jobs ready to run`);
}
node._bigJobs = batchData;
console.log(`[BIG][fix1] Restored ${batchData.length} jobs, dimensions:`, batchData.map(j => `${j.id}:${j.image_width}x${j.image_height}`).join(', '));
// Recalculate stats (after updating interrupted jobs)
node._bigStats = {
total: batchData.length,
completed: batchData.filter(j => j.state === "success" || j.state === "cached" || j.state === "failed" || j.state === "cancelled").length,
success: batchData.filter(j => j.state === "success").length,
failed: batchData.filter(j => j.state === "failed").length,
cached: batchData.filter(j => j.state === "cached").length,
};
node._bigIsGenerating = false; // Never restore "generating" state
// IMPORTANT: Re-save to session storage after restoring and modifying job states
// This ensures session storage has the corrected states for next tab switch
const correctedData = JSON.stringify(batchData);
saveToSession(correctedData);
// Also update widget and properties with corrected data
node.properties = node.properties || {};
node.properties.big_jobs_data = correctedData;
const widget = node.widgets?.find(w => w.name === "generated_batch_data");
if (widget) widget.value = correctedData;
return true;
}
}
} catch (e) {
console.error("[BIG] Failed to restore:", e);
}
return false;
};
// Check backend for real-time progress of jobs that were "generating"
const checkBackendProgress = async (localJobs) => {
try {
const nodeId = node._ni_widget?.value || String(node.id);
console.log(`[BIG] đ Checking backend progress for node ${nodeId}...`);
const response = await fetch(`/instaraw/batch_gen_progress/${nodeId}`);
const backendData = await response.json();
if (backendData && backendData.jobs && backendData.jobs.length > 0) {
console.log(`[BIG] â
Backend has ${backendData.jobs.length} jobs!`);
// Merge backend data with local jobs
let updatedCount = 0;
localJobs.forEach(localJob => {
const backendJob = backendData.jobs.find(bj => bj.id === localJob.id);
if (backendJob) {
// Backend has data for this job - update local state
if (backendJob.state === "success" || backendJob.state === "cached") {
localJob.state = backendJob.state;
localJob.image_url = backendJob.image_url || localJob.image_url;
localJob.error = null;
updatedCount++;
console.log(`[BIG] â
Job ${localJob.id}: ${backendJob.state}`);
} else if (backendJob.state === "failed") {
localJob.state = "failed";
localJob.error = backendJob.error || "Failed on backend";
updatedCount++;
} else if (backendJob.state === "generating") {
// Still generating on backend! Resume polling
console.log(`[BIG] đ Job ${localJob.id} still generating on backend`);
node._bigIsGenerating = true;
}
}
});
if (updatedCount > 0) {
console.log(`[BIG] â
Updated ${updatedCount} jobs from backend`);
node._bigJobs = localJobs;
updateGeneratedBatchData();
if (node._renderUI) node._renderUI();
}
// If still generating, start polling
if (backendData.is_generating) {
console.log(`[BIG] đ Backend still generating - starting polling`);
if (node._startPolling) node._startPolling();
}
} else {
// Backend has no data - mark generating jobs as interrupted
console.log(`[BIG] â ī¸ No backend data - marking jobs as interrupted`);
localJobs.forEach(job => {
if (job.state === "generating" || job.state === "retrying") {
job.state = "failed";
job.error = "Interrupted by tab switch - click Retry";
}
});
node._bigJobs = localJobs;
updateGeneratedBatchData();
if (node._renderUI) node._renderUI();
}
} catch (e) {
console.error("[BIG] Failed to check backend progress:", e);
// On error, mark as interrupted
localJobs.forEach(job => {
if (job.state === "generating" || job.state === "retrying") {
job.state = "failed";
job.error = "Interrupted - backend check failed";
}
});
node._bigJobs = localJobs;
if (node._renderUI) node._renderUI();
}
};
// Store functions on node so onConfigure can call them
node._restoreFromWidget = restoreFromWidget;
node._getSessionKey = getSessionKey;
node._saveToSession = saveToSession;
node._checkBackendProgress = checkBackendProgress;
// Try initial restore (may fail if widget not loaded yet - onConfigure will retry)
restoreFromWidget();
// Generation state (initialized fresh, onConfigure will restore from widget)
node._bigJobs = node._bigJobs || [];
node._bigIsGenerating = false;
node._bigStats = node._bigStats || { total: 0, completed: 0, success: 0, failed: 0, cached: 0 };
node._bigStartTime = null;
node._bigAbortController = null; // AbortController for smooth cancellation (RPG pattern)
// Save state - no-op now since we rely solely on widget persistence
// (localStorage caused cross-workflow state leakage issues)
const saveState = () => {
// State is saved via updateGeneratedBatchData() which updates the widget
// The widget is serialized with the workflow file
};
// Get connected model/provider info (similar to AIL pattern)
const getConnectedInputValue = (inputName) => {
const input = node.inputs?.find(i => i.name === inputName);
if (!input || !input.link) return null;
const link = app.graph.links[input.link];
if (!link) return null;
const originNode = app.graph.getNodeById(link.origin_id);
if (!originNode) return null;
// Get the widget value from the origin node
const widget = originNode.widgets?.[link.origin_slot];
return widget ? widget.value : null;
};
const getModelProviderInfo = () => {
const model = getConnectedInputValue("model");
const provider = getConnectedInputValue("provider");
// Check if model is Nano Banana Pro (the only supported model for now)
const isNanoBananaPro = model === "Nano Banana Pro" || model === "nano_banana_pro";
const isSupported = isNanoBananaPro;
return { model, provider, isNanoBananaPro, isSupported };
};
// Get widget value from this node
const getWidgetValue = (widgetName, defaultVal = null) => {
const widget = node.widgets?.find(w => w.name === widgetName);
return widget?.value ?? defaultVal;
};
// Helper to read boolean from widget or connected input (prioritizes connection)
const getBooleanValue = (inputName) => {
const widget = node.widgets?.find(w => w.name === inputName);
const input = node.inputs?.find(i => i.name === inputName);
// Prioritize connected input over widget
if (input && input.link) {
const link = app.graph?.links?.[input.link];
if (link) {
const originNode = app.graph.getNodeById(link.origin_id);
if (originNode) {
const srcWidget = originNode.widgets?.[0] || originNode.widgets?.find(w => w.name === "value");
if (srcWidget) return srcWidget.value === true;
}
}
}
return widget?.value === true;
};
// Get multi-image mode info for UI display
const getMultiImageInfo = () => {
const multiImage = getBooleanValue("multi_image");
const provider = getConnectedInputValue("provider") || "";
const isActive = multiImage && provider === "wavespeed.ai";
const isWarning = multiImage && provider && provider !== "wavespeed.ai";
const isNoProvider = multiImage && !provider;
// Check aspect ratio compatibility for multi-image mode
const MULTI_SUPPORTED_RATIOS = ["3:2", "2:3", "3:4", "4:3"];
let aspectRatioRaw = String(getConnectedInputValue("aspect_ratio") || "1:1");
// Extract ratio from labels like "3:4 (Portrait)" -> "3:4"
const match = aspectRatioRaw.match(/(\d+:\d+)/);
const aspectRatio = match ? match[1] : aspectRatioRaw;
const aspectRatioSupported = MULTI_SUPPORTED_RATIOS.includes(aspectRatio);
const aspectRatioWarning = isActive && !aspectRatioSupported;
return { multiImage, provider, isActive, isWarning, isNoProvider, aspectRatio, aspectRatioSupported, aspectRatioWarning };
};
// Toggle 2X multi-image mode
const toggleMultiImageMode = (enabled) => {
const multiImageWidget = node.widgets?.find(w => w.name === "multi_image");
if (multiImageWidget) {
multiImageWidget.value = enabled;
multiImageWidget.callback?.(enabled);
console.log("[BIG] 2X mode toggled:", enabled);
}
};
// Helper to find AIL node connected to an input (traversing through pass-through nodes)
const findConnectedAIL = (inputName) => {
const input = node.inputs?.find(i => i.name === inputName);
if (!input || !input.link) return null;
const traverseToAIL = (nodeToCheck, depth = 0) => {
if (!nodeToCheck || depth > 5) return null;
// Check if this is an AIL node
if (nodeToCheck.type === "INSTARAW_AdvancedImageLoader" && nodeToCheck.properties?.batch_data) {
return nodeToCheck;
}
// Traverse upstream through IMAGE inputs
if (nodeToCheck.inputs) {
for (const inp of nodeToCheck.inputs) {
if ((inp.type === "IMAGE" || inp.name === "images") && inp.link) {
const link = app.graph?.links?.[inp.link];
if (link) {
const upstream = app.graph.getNodeById(link.origin_id);
const result = traverseToAIL(upstream, depth + 1);
if (result) return result;
}
}
}
}
return null;
};
const link = app.graph?.links?.[input.link];
if (!link) return null;
const sourceNode = app.graph.getNodeById(link.origin_id);
return traverseToAIL(sourceNode, 0);
};
const getGenerationPreviewInfo = () => {
// Get generations_per_combination from widget
const genWidget = node.widgets?.find(w => w.name === "generations_per_combination");
const generationsPerCombination = genWidget?.value || 1;
// Try to get prompt count from RPG connection
const promptInput = node.inputs?.find(i => i.name === "prompt_list_positive");
let promptCount = 0;
if (promptInput?.link) {
const link = app.graph.links[promptInput.link];
if (link) {
const rpgNode = app.graph.getNodeById(link.origin_id);
if (rpgNode) {
// RPG stores prompts in _rpgPromptBatch
const promptBatch = rpgNode._rpgPromptBatch || [];
promptCount = promptBatch.length;
}
}
}
// Try to get image count from AIL connection (via RPG)
const imagesInput = node.inputs?.find(i => i.name === "images");
let imageCount = 0;
if (imagesInput?.link) {
const link = app.graph.links[imagesInput.link];
if (link) {
const sourceNode = app.graph.getNodeById(link.origin_id);
if (sourceNode) {
// Could be AIL or RPG
if (sourceNode._linkedImageCount !== undefined) {
imageCount = sourceNode._linkedImageCount; // From RPG
} else if (sourceNode.properties?.batch_data) {
// From AIL directly
try {
const batchData = JSON.parse(sourceNode.properties.batch_data);
imageCount = (batchData.images || batchData.latents || []).length;
} catch (e) {
console.warn("[BIG] Failed to parse AIL batch_data:", e);
}
}
}
}
}
// Calculate total jobs
const totalJobs = promptCount > 0 ? promptCount * generationsPerCombination : 0;
return {
imageCount,
promptCount,
generationsPerCombination,
totalJobs,
hasInputs: promptCount > 0 || imageCount > 0
};
};
// âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
// MODE DETECTION (T2I vs I2I) - Similar to RPG
// âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
const getConnectedImagesInfo = () => {
/**
* Get connected images info (uses cached node data from sync interval).
* Returns { mode, imageCount, imageUrls, sourceNodeId }
*/
// Use cached data from node (updated by polling interval)
return {
mode: node._bigMode || "txt2img",
imageCount: node._bigImageCount || 0,
imageUrls: node._bigImageUrls || [],
sourceNodeId: null
};
};
// Fetch image as base64 from URL (for I2I mode)
const fetchImageAsBase64 = async (imageUrl) => {
try {
// If already a data URL, extract the base64 part
if (imageUrl.startsWith("data:")) {
return imageUrl.split(",")[1];
}
// Fetch from ComfyUI view endpoint
const response = await fetch(imageUrl);
if (!response.ok) {
console.error(`[BIG] Failed to fetch image: ${response.status}`);
return null;
}
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64 = reader.result.split(",")[1];
resolve(base64);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (e) {
console.error("[BIG] Error fetching image as base64:", e);
return null;
}
};
// Store mode info on node for UI
node._bigMode = "txt2img";
node._bigImageCount = 0;
node._bigImageCounts = []; // Breakdown per AIL source for "3Ã10" display
node._bigImageUrls = [];
// Additional image inputs (images2, images3, images4)
node._bigImage2Urls = [];
node._bigImage3Urls = [];
node._bigImage4Urls = [];
// Helper to extract image URLs from a node (recursive for pass-through nodes)
// MUST be defined before _updateModeFromSource which uses it
const extractImageUrlsFromNode = (sourceNode, depth = 0, inputName = "") => {
if (!sourceNode || depth > 5) return []; // Max depth to prevent infinite loops
let urls = [];
const nodeType = sourceNode.type;
const prefix = `[BIG] ${inputName}${depth > 0 ? ` (upstream ${depth})` : ''}`;
// Check for preview images first (works for many node types after execution)
if (sourceNode.imgs && sourceNode.imgs.length > 0) {
urls = sourceNode.imgs.map(img => img.src).filter(Boolean);
if (urls.length > 0) return urls;
}
// Handle specific node types
if (nodeType === "INSTARAW_AdvancedImageLoader") {
try {
const batchData = JSON.parse(sourceNode.properties?.batch_data || "{}");
const order = batchData.order || [];
const ailImages = batchData.images || [];
const ailNodeId = sourceNode.id;
if (ailImages.length > 0) {
urls = order.length > 0
? order.map(imgId => {
const img = ailImages.find(i => i.id === imgId);
return img?.thumbnail
? `/instaraw/view/${img.thumbnail}`
: null;
}).filter(Boolean)
: ailImages.map(img => img?.thumbnail
? `/instaraw/view/${img.thumbnail}`
: null).filter(Boolean);
}
} catch (e) {
console.warn(`[BIG] Error parsing AIL batch_data:`, e);
}
} else if (nodeType === "INSTARAW_RealityPromptGenerator") {
urls = sourceNode._linkedImageUrls || sourceNode._linkedImages?.map(i => i.url) || [];
} else if (sourceNode.properties?.batch_data) {
try {
const batchData = JSON.parse(sourceNode.properties.batch_data);
urls = (batchData.images || []).map(i => i.url || i).filter(Boolean);
} catch (e) {}
}
// If no URLs found, traverse upstream (for pass-through nodes like ImageListFromBatch)
if (urls.length === 0 && sourceNode.inputs) {
// Look for IMAGE type inputs and traverse upstream
for (const input of sourceNode.inputs) {
const isImageType = input.type === "IMAGE" || input.type === "image" ||
input.name === "images" || input.name === "image" ||
input.name?.toLowerCase().includes("image");
if (isImageType && input.link) {
const upstreamLink = app.graph?.links?.[input.link];
if (upstreamLink) {
const upstreamNode = app.graph.getNodeById(upstreamLink.origin_id);
if (upstreamNode) {
urls = extractImageUrlsFromNode(upstreamNode, depth + 1, inputName);
if (urls.length > 0) break;
}
}
}
}
}
return urls;
};
// Helper to update mode from source node (AIL or RPG)
node._updateModeFromSource = (sourceNode) => {
if (!sourceNode) return;
let mode = "txt2img";
let imageCount = 0;
let imageUrls = [];
node._bigImageCounts = []; // Reset breakdown for fresh calculation
// Check if source is AIL
if (sourceNode.type === "INSTARAW_AdvancedImageLoader") {
// Read enable_img2img from AIL (widget or connected input)
const enableImg2ImgWidget = sourceNode.widgets?.find(w => w.name === "enable_img2img");
let enableImg2Img = enableImg2ImgWidget?.value;
// Check if enable_img2img is connected
const enableImg2ImgInput = sourceNode.inputs?.find(i => i.name === "enable_img2img");
if (enableImg2ImgInput && enableImg2ImgInput.link != null) {
const link = app.graph?.links?.[enableImg2ImgInput.link];
if (link) {
const srcNode = app.graph.getNodeById(link.origin_id);
if (srcNode) {
const srcWidget = srcNode.widgets?.[link.origin_slot];
if (srcWidget) enableImg2Img = srcWidget.value;
}
}
}
mode = (enableImg2Img === false || enableImg2Img === "false") ? "txt2img" : "img2img";
// Read images from batch_data
try {
const batchData = JSON.parse(sourceNode.properties?.batch_data || "{}");
const order = batchData.order || [];
const ailImages = batchData.images || [];
const ailNodeId = sourceNode.id;
if (mode === "img2img" && ailImages.length > 0) {
imageUrls = order.length > 0
? order.map(imgId => {
const img = ailImages.find(i => i.id === imgId);
return img?.thumbnail
? `/instaraw/view/${img.thumbnail}`
: null;
}).filter(Boolean)
: ailImages.map(img => img?.thumbnail
? `/instaraw/view/${img.thumbnail}`
: null).filter(Boolean);
imageCount = imageUrls.length;
}
} catch (e) {
console.warn("[BIG] Error parsing AIL batch_data:", e);
}
}
// Check if source is RPG (pass-through)
else if (sourceNode.type === "INSTARAW_RealityPromptGenerator") {
mode = sourceNode._linkedAILMode || "txt2img";
imageUrls = sourceNode._linkedImageUrls || sourceNode._linkedImages?.map(i => i.url) || [];
imageCount = imageUrls.length;
// Get breakdown of images per AIL source
const img1Count = (sourceNode._linkedImages || []).length;
const img2Count = (sourceNode._linkedImages2 || []).length;
const img3Count = (sourceNode._linkedImages3 || []).length;
const img4Count = (sourceNode._linkedImages4 || []).length;
node._bigImageCounts = [img1Count, img2Count, img3Count, img4Count].filter(c => c > 0);
}
// Other nodes - check for images
else if (sourceNode.properties?.batch_data) {
try {
const batchData = JSON.parse(sourceNode.properties.batch_data);
const images = batchData.images || [];
if (images.length > 0) {
mode = "img2img";
imageUrls = images.map(i => i.url || i).filter(Boolean);
imageCount = imageUrls.length;
}
} catch (e) {}
}
// Fallback: use recursive extraction for pass-through nodes
else {
imageUrls = extractImageUrlsFromNode(sourceNode, 0, "images");
if (imageUrls.length > 0) {
mode = "img2img";
imageCount = imageUrls.length;
}
}
node._bigMode = mode;
node._bigImageCount = imageCount;
node._bigImageUrls = imageUrls;
// If _bigImageCounts wasn't set by RPG path, use single source count
if (node._bigImageCounts.length === 0 && imageCount > 0) {
node._bigImageCounts = [imageCount];
}
};
// Helper to get image URLs from any connected image input
const getImageUrlsFromInput = (inputName) => {
const imageInput = node.inputs?.find(input => input.name === inputName);
if (!imageInput || !imageInput.link) return [];
const link = app.graph?.links?.[imageInput.link];
if (!link) return [];
const sourceNode = app.graph.getNodeById(link.origin_id);
if (!sourceNode) return [];
// Use the recursive helper to extract URLs (handles pass-through nodes)
return extractImageUrlsFromNode(sourceNode, 0, inputName);
};
// Update additional image inputs
const updateAdditionalImages = () => {
node._bigImage2Urls = getImageUrlsFromInput("images2");
node._bigImage3Urls = getImageUrlsFromInput("images3");
node._bigImage4Urls = getImageUrlsFromInput("images4");
};
// Track last known values for change detection
let lastKnownProvider = getConnectedInputValue("provider") || "";
let lastKnownModel = getConnectedInputValue("model") || "";
let lastKnownEnableImg2Img = false;
let lastKnownMultiImage = false;
// Flag to track if initial restore from widget is complete
node._bigInitialized = false;
// Periodic mode sync (every 500ms) - only when NOT generating
node._modeSyncInterval = setInterval(() => {
// Skip re-renders during generation - progress polling handles that
if (node._bigIsGenerating) return;
// Skip until onConfigure has had a chance to restore state
// This prevents race conditions where we render before widget data is loaded
if (!node._bigInitialized) return;
// Capture current state for comparison
const oldMode = node._bigMode;
const oldCount = node._bigImageCount;
const oldProvider = lastKnownProvider;
const oldModel = lastKnownModel;
const oldEnableImg2Img = lastKnownEnableImg2Img;
const oldMultiImage = lastKnownMultiImage;
// Update image URLs from connected sources
const imagesInput = node.inputs?.find(input => input.name === "images");
if (imagesInput && imagesInput.link) {
const link = app.graph?.links?.[imagesInput.link];
if (link) {
const sourceNode = app.graph.getNodeById(link.origin_id);
if (sourceNode) {
node._updateModeFromSource(sourceNode);
}
}
} else {
node._bigImageUrls = [];
}
updateAdditionalImages();
// Read current values
const enableImg2Img = getBooleanValue("enable_img2img");
const multiImage = getBooleanValue("multi_image");
const currentProvider = getConnectedInputValue("provider") || "";
const currentModel = getConnectedInputValue("model") || "";
// Determine mode
const hasAnyImageLinks =
(node.inputs?.find(i => i.name === "images")?.link != null) ||
(node.inputs?.find(i => i.name === "images2")?.link != null) ||
(node.inputs?.find(i => i.name === "images3")?.link != null) ||
(node.inputs?.find(i => i.name === "images4")?.link != null);
node._bigMode = (enableImg2Img && hasAnyImageLinks) ? "img2img" : "txt2img";
const img1Count = node._bigImageUrls.length;
const img2Count = node._bigImage2Urls.length;
const img3Count = node._bigImage3Urls.length;
const img4Count = node._bigImage4Urls.length;
const totalImageCount = img1Count + img2Count + img3Count + img4Count;
// Update tracking variables
lastKnownProvider = currentProvider;
lastKnownModel = currentModel;
lastKnownEnableImg2Img = enableImg2Img;
lastKnownMultiImage = multiImage;
node._bigImageCount = totalImageCount;
node._bigImageCounts = [img1Count, img2Count, img3Count, img4Count].filter(c => c > 0);
// Only re-render if something actually changed
const modeChanged = oldMode !== node._bigMode;
const countChanged = oldCount !== totalImageCount;
const providerChanged = oldProvider !== currentProvider;
const modelChanged = oldModel !== currentModel;
const enableChanged = oldEnableImg2Img !== enableImg2Img;
const multiChanged = oldMultiImage !== multiImage;
if (modeChanged || countChanged || providerChanged || modelChanged || enableChanged || multiChanged) {
renderUI();
}
}, 500);
// Container setup (AIL/RPG pattern)
const container = document.createElement("div");
container.className = "instaraw-big-container";
container.style.width = "100%";
container.style.boxSizing = "border-box";
container.style.overflow = "hidden";
container.style.height = `${cachedHeight}px`;
// === Height Management ===
const updateCachedHeight = () => {
if (isUpdatingHeight) return;
isUpdatingHeight = true;
// Safety timeout to prevent stuck flag
const safetyTimeout = setTimeout(() => {
isUpdatingHeight = false;
}, 500);
container.style.overflow = "visible";
container.style.height = "auto";
requestAnimationFrame(() => {
requestAnimationFrame(() => {
clearTimeout(safetyTimeout);
// Use scrollHeight as it measures full content even during transitions
const newHeight = Math.max(container.offsetHeight, container.scrollHeight);
if (newHeight > 0 && Math.abs(newHeight - cachedHeight) > 2) {
cachedHeight = newHeight;
container.style.height = `${newHeight}px`;
const sz = node.computeSize();
node.size[1] = sz[1];
node.onResize?.(sz);
app.graph.setDirtyCanvas(true, false);
} else {
container.style.height = `${cachedHeight}px`;
}
container.style.overflow = "hidden";
isUpdatingHeight = false;
});
});
};
node._updateCachedHeight = updateCachedHeight;
// Helper to attach onload/onerror handlers to all images in container
const attachImageOnloadHandlers = () => {
let hasUnloadedImages = false;
const fallbackSvg = 'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22%3E%3Cpath fill=%22%239ca3af%22 d=%22M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z%22/%3E%3C/svg%3E';
const maxRetries = 3;
container.querySelectorAll('img').forEach(img => {
if (!img._hasOnloadHandler) {
img._hasOnloadHandler = true;
img._retryCount = 0;
img.addEventListener('load', () => updateCachedHeight());
// Handle broken images with simple retry
img.addEventListener('error', () => {
const jobId = img.dataset.jobId;
if (img._retryCount < maxRetries) {
img._retryCount++;
console.log(`[BIG] Image load failed for job ${jobId}, retry ${img._retryCount}/${maxRetries}`);
setTimeout(() => {
// Retry with cache-busting parameter
const baseUrl = img.src.split('&_retry=')[0].split('&_t=')[0];
img.src = `${baseUrl}&_retry=${img._retryCount}&_t=${Date.now()}`;
}, 200 * img._retryCount);
} else {
console.error(`[BIG] Image load failed after ${maxRetries} retries for job ${jobId}`);
img.style.opacity = '0.3';
img.src = fallbackSvg;
updateCachedHeight();
}
});
// Check if image is not yet loaded
if (!img.complete) {
hasUnloadedImages = true;
} else if (img.naturalWidth === 0) {
// Image already failed to load - trigger error handler
img.dispatchEvent(new Event('error'));
}
}
});
// If there are images that haven't loaded yet, schedule extra height updates
if (hasUnloadedImages) {
[200, 500, 1000, 2000].forEach(delay => {
setTimeout(() => updateCachedHeight(), delay);
});
}
};
// Periodic height sync - keep running, only clear when node is removed
const heightSyncInterval = setInterval(() => {
if (!node || !container) {
clearInterval(heightSyncInterval);
return;
}
// Always try to sync, even if offsetHeight is 0 (container might just need reflow)
updateCachedHeight();
}, 2000);
// Store interval for cleanup
node._heightSyncInterval = heightSyncInterval;
// Fast initial syncs for page load
[100, 300, 500, 1000, 1500, 2000].forEach(delay => {
setTimeout(() => {
if (container) {
updateCachedHeight();
}
}, delay);
});
// Poll for progress updates using fetch (works during execution!)
let pollInterval = null;
let lastPollTime = 0;
const startPolling = () => {
if (pollInterval) return;
console.log("[BIG] Starting progress polling...");
// Use a more aggressive polling approach that works during execution
const poll = async () => {
if (!pollInterval) return;
try {
const nodeId = node._ni_widget?.value || String(node.id);
if (nodeId) {
// Use raw fetch to bypass any ComfyUI blocking
const response = await fetch(`/instaraw/batch_gen_progress/${nodeId}`, {
method: 'GET',
headers: { 'Accept': 'application/json' },
});
if (response.ok) {
const data = await response.json();
if (data.jobs && data.jobs.length > 0) {
const wasGenerating = node._bigIsGenerating;
const hadJobs = node._bigJobs.length > 0;
node._bigJobs = data.jobs;
node._bigStats = data.stats || node._bigStats;
node._bigIsGenerating = data.is_generating;
updateGeneratedBatchData();
// First time seeing jobs - do full render
if (!hadJobs && data.jobs.length > 0) {
node._bigStartTime = Date.now();
renderUI();
} else {
// Update existing items
updateProgressItems();
updateProgressHeader();
}
// Generation finished
if (wasGenerating && !data.is_generating) {
console.log("[BIG] Generation complete detected via polling");
renderUI(); // Re-render to show action buttons
stopPolling();
return;
}
}
}
}
} catch (e) {
// Silently ignore poll errors during execution
}
// Schedule next poll
if (pollInterval) {
pollInterval = setTimeout(poll, 400);
}
};
pollInterval = setTimeout(poll, 100);
};
const stopPolling = () => {
if (pollInterval) {
clearTimeout(pollInterval);
pollInterval = null;
console.log("[BIG] Stopped polling");
}
};
// Store polling functions on node for use by checkBackendProgress
node._startPolling = startPolling;
node._stopPolling = stopPolling;
// Listen for ComfyUI execution start - start polling immediately
api.addEventListener("execution_start", (event) => {
console.log("[BIG] Execution started, beginning to poll for progress...");
node._bigStartTime = Date.now();
startPolling();
});
// Listen for ComfyUI execution complete/error - ensure we stop polling
api.addEventListener("execution_complete", () => {
// Give a moment for final updates then stop
setTimeout(() => {
if (!node._bigIsGenerating) {
stopPolling();
}
}, 1000);
});
api.addEventListener("execution_error", () => {
stopPolling();
});
// Also listen for our custom events (they work after execution)
api.addEventListener("instaraw-batch-gen-start", (event) => {
const data = event.detail;
if (data.node_id === node._ni_widget?.value) {
console.log("[BIG] Generation started event received:", data);
node._bigJobs = data.jobs || [];
node._bigStats = {
total: node._bigJobs.length,
completed: 0,
success: 0,
failed: 0,
cached: 0,
};
node._bigIsGenerating = true;
if (!node._bigStartTime) node._bigStartTime = Date.now();
updateGeneratedBatchData();
renderUI();
}
});
// Listen for job updates (works after execution finishes)
api.addEventListener("instaraw-batch-gen-update", (event) => {
const data = event.detail;
if (data.node_id === node._ni_widget?.value) {
const job = node._bigJobs.find(j => j.id === data.job_id);
if (job) {
job.state = data.state;
job.attempts = data.attempts;
job.error = data.error;
job.generation_time = data.generation_time;
// Also update image data for display
if (data.image_url) {
job.image_url = data.image_url;
}
if (data.image_width) {
job.image_width = data.image_width;
}
if (data.image_height) {
job.image_height = data.image_height;
}
updateProgressItem(job);
updateStats();
}
}
});
// Listen for generation complete
api.addEventListener("instaraw-batch-gen-complete", (event) => {
const data = event.detail;
if (data.node_id === node._ni_widget?.value) {
console.log("[BIG] Generation complete event:", data);
node._bigIsGenerating = false;
node._bigStats = data.stats || node._bigStats;
updateGeneratedBatchData();
stopPolling();
renderUI();
}
});
// Listen for save event from legacy Python path
api.addEventListener("instaraw-batch-gen-save", (event) => {
const data = event.detail;
if (data.node_id === node._ni_widget?.value) {
console.log("[BIG] Received generated_batch_data from Python:", data);
// Update the widget with the generated batch data
const widget = node.widgets?.find(w => w.name === "generated_batch_data");
if (widget) {
widget.value = data.generated_batch_data;
console.log("[BIG] Updated generated_batch_data widget");
}
// Also update our internal jobs from the data
try {
const batchData = JSON.parse(data.generated_batch_data);
node._bigJobs = batchData.map(job => ({
id: job.id,
state: job.state,
prompt_positive: job.prompt_positive,
image_url: job.image_url,
image_width: job.image_width,
image_height: job.image_height,
generation_time: job.generation_time,
filename: job.filename,
}));
updateStats();
renderUI();
} catch (e) {
console.error("[BIG] Failed to parse generated_batch_data:", e);
}
}
});
// Listen for RPG prompt changes (repeat counts, etc.) to update sync badge
window.addEventListener("INSTARAW_RPG_PROMPTS_CHANGED", (event) => {
// Check if this RPG is connected to us
const promptInput = node.inputs?.find(i => i.name === "prompt_list_positive");
if (!promptInput?.link) return;
const link = app.graph.links[promptInput.link];
if (!link || link.origin_id !== event.detail.nodeId) return;
// RPG we're connected to changed - re-render to update sync badge
console.log(`[BIG] RPG prompts changed, totalGenerations=${event.detail.totalGenerations}`);
renderUI();
});
// Listen for AIL updates to refresh image preview
window.addEventListener("INSTARAW_AIL_UPDATED", (event) => {
// Check if this AIL is connected to us
const imagesInput = node.inputs?.find(i => i.name === "images");
if (!imagesInput?.link) return;
// Re-render to update sync badge and image preview
renderUI();
});
const updateStats = () => {
const jobs = node._bigJobs;
node._bigStats.completed = jobs.filter(j =>
[JobState.SUCCESS, JobState.FAILED, JobState.CACHED, JobState.CANCELLED].includes(j.state)
).length;
node._bigStats.success = jobs.filter(j => j.state === JobState.SUCCESS).length;
node._bigStats.failed = jobs.filter(j => j.state === JobState.FAILED).length;
node._bigStats.cached = jobs.filter(j => j.state === JobState.CACHED).length;
updateProgressHeader();
};
const escapeHtml = (text) => {
if (!text) return "";
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
};
// Format image count as "3Ã10" when multiple sources with equal counts, or show total
const formatImageCount = () => {
const counts = node._bigImageCounts || [];
const total = node._bigImageCount || 0;
if (counts.length <= 1) {
return `${total} ref image${total !== 1 ? 's' : ''}`;
}
// Check if all counts are equal
const allEqual = counts.every(c => c === counts[0]);
if (allEqual) {
return `${counts.length}Ã${counts[0]} ref images`;
}
// Different counts - show as sum
return `${counts.join('+')} ref images`;
};
const formatTime = (ms) => {
const seconds = Math.floor(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${minutes}m ${secs}s`;
};
// Timer interval for updating elapsed time display
let timerInterval = null;
const startTimer = () => {
if (timerInterval) return;
timerInterval = setInterval(() => {
if (node._bigIsGenerating && node._bigStartTime) {
const header = container.querySelector(".instaraw-big-progress-header h4");
if (header) {
const elapsed = formatTime(Date.now() - node._bigStartTime);
header.textContent = `Generating... (${elapsed})`;
}
}
}, 1000);
};
const stopTimer = () => {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
};
const updateProgressHeader = () => {
const header = container.querySelector(".instaraw-big-progress-header h4");
const kpiRow = container.querySelector(".instaraw-big-kpi-row");
if (header) {
const elapsed = node._bigStartTime ? formatTime(Date.now() - node._bigStartTime) : "0s";
if (node._bigIsGenerating) {
header.textContent = `đ Generating Images... (${elapsed})`;
startTimer();
} else {
header.textContent = `â
Generation Complete (${elapsed})`;
stopTimer();
}
}
// Update KPI values (jobs completed, success, cached, failed)
if (kpiRow) {
const s = node._bigStats;
const kpis = kpiRow.querySelectorAll(".instaraw-big-kpi");
kpis.forEach(kpi => {
const strong = kpi.querySelector("strong");
const label = kpi.querySelector("span")?.textContent?.trim();
if (strong && label) {
if (label === "JOBS") {
strong.textContent = `${s.completed}/${s.total}`;
} else if (label === "SUCCESS") {
strong.textContent = s.success;
} else if (label === "CACHED") {
strong.textContent = s.cached;
} else if (label === "FAILED") {
strong.textContent = s.failed;
}
}
});
}
};
const updateProgressItems = () => {
node._bigJobs.forEach(job => updateProgressItem(job));
};
const updateProgressItem = (job) => {
const itemEl = container.querySelector(`.instaraw-big-progress-item[data-job-id="${job.id}"]`);
if (!itemEl) return;
// Debug: Log if job has image URL
if (job.image_url && job.state === JobState.SUCCESS) {
console.log(`[BIG] Job #${job.id} has image:`, job.image_url, `(${job.image_width}x${job.image_height})`);
}
const stateInfo = STATE_CONFIG[job.state] || STATE_CONFIG[JobState.PENDING];
// Update class for border/background color
itemEl.className = `instaraw-big-progress-item ${stateInfo.class}`;
// Update status badge
const statusBadge = itemEl.querySelector(".instaraw-big-progress-item-status");
if (statusBadge) {
statusBadge.className = `instaraw-big-progress-item-status ${stateInfo.class}`;
let statusText = `${stateInfo.icon} ${stateInfo.text}`;
if (job.state === JobState.RETRYING && job.attempts > 1) {
statusText = `đ Retry #${job.attempts}`;
} else if (job.state === JobState.SUCCESS && job.generation_time) {
// Show retry count if there were retries
if (job.attempts > 1) {
statusText = `â ${job.generation_time.toFixed(1)}s (${job.attempts} tries)`;
} else {
statusText = `â ${job.generation_time.toFixed(1)}s`;
}
} else if (job.state === JobState.FAILED && job.attempts > 1) {
statusText = `â Failed (${job.attempts} tries)`;
}
statusBadge.textContent = statusText;
}
// Update progress bar
const progressFill = itemEl.querySelector(".instaraw-big-progress-item-fill");
if (progressFill) {
// Remove all classes first
progressFill.className = "instaraw-big-progress-item-fill";
progressFill.style.background = "";
if (job.state === JobState.SUCCESS || job.state === JobState.CACHED) {
progressFill.style.width = "100%";
} else if (job.state === JobState.GENERATING || job.state === JobState.RETRYING) {
progressFill.style.width = "100%";
progressFill.classList.add("animating");
} else if (job.state === JobState.FAILED) {
progressFill.style.width = "100%";
progressFill.style.background = "linear-gradient(90deg, #ef4444, #dc2626)";
} else {
progressFill.style.width = "0%";
}
}
// Update message
const messageDiv = itemEl.querySelector(".instaraw-big-progress-item-message");
if (messageDiv) {
if (job.state === JobState.FAILED && job.error) {
messageDiv.textContent = job.error.slice(0, 100);
messageDiv.style.display = "block";
messageDiv.classList.remove("retry-message");
messageDiv.classList.add("error-message");
} else if (job.state === JobState.RETRYING && job.error) {
messageDiv.textContent = `â ī¸ ${job.error.slice(0, 80)}`;
messageDiv.style.display = "block";
messageDiv.classList.remove("error-message");
messageDiv.classList.add("retry-message");
} else {
messageDiv.style.display = "none";
messageDiv.classList.remove("error-message", "retry-message");
}
}
// Show/hide retry button
const retryBtn = itemEl.querySelector(".instaraw-big-job-retry-btn");
if (retryBtn) {
retryBtn.style.display = job.state === JobState.FAILED ? "inline-block" : "none";
}
// Update or create thumbnail (always present now)
const hasImage = job.image_url && (job.state === JobState.SUCCESS || job.state === JobState.CACHED);
const isGenerating = job.state === JobState.GENERATING || job.state === JobState.RETRYING;
let thumbnailContainer = itemEl.querySelector(".instaraw-big-progress-item-thumbnail");
if (!thumbnailContainer) {
// Create thumbnail container - always present
const thumbDiv = document.createElement("div");
thumbDiv.className = "instaraw-big-progress-item-thumbnail" + (hasImage ? "" : " placeholder");
if (hasImage) {
thumbDiv.innerHTML = ``;
} else if (isGenerating) {
console.log("[BIG] Creating video element for job", job.id);
const video = document.createElement("video");
video.className = "instaraw-big-thumbnail-video";
video.autoplay = true;
video.loop = true;
video.muted = true;
video.playsInline = true;
video.src = "extensions/ComfyUI_INSTARAW/Instara_loader.mp4";
// Debug events
video.addEventListener('loadeddata', () => console.log("[BIG] Video loaded:", video.src));
video.addEventListener('error', (e) => console.error("[BIG] Video error:", e, video.error));
thumbDiv.appendChild(video);
console.log("[BIG] Video element appended, src:", video.src);
// Ensure video plays
video.play().then(() => {
console.log("[BIG] Video playing successfully");
}).catch(e => {
console.error("[BIG] Video autoplay failed:", e);
});
} else {
thumbDiv.innerHTML = `