Guest User

Untitled

a guest
Apr 1st, 2026
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         xAI Pro Studio Frontend (v28 - Auto-Retry Fix & Edit Flow)
  3. // @namespace    http://tampermonkey.net/
  4. // @version      28
  5. // @description  Full-Screen UI, Exif Fix, Multi-Image Routing, Dynamic Prompts, Raw PNG Mode, Auto-Retry Moderation, Instant Edit Button
  6. // @match        https://console.x.ai/playground/imagine*
  7. // @match        https://console.x.ai/team/*/imagine*
  8. // @grant        none
  9. // @run-at       document-start
  10. // ==/UserScript==
  11.  
  12. (function() {
  13.     'use strict';
  14.  
  15.     // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  16.     const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  17.     function pad2(n) { return String(n).padStart(2, '0'); }
  18.     function makeTimestamp() {
  19.         const d = new Date();
  20.         return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
  21.     }
  22.     const DOWNLOAD_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`;
  23.     const EDIT_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;
  24.  
  25.     // Load Settings
  26.     let appSettings = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  27.     appSettings.retries = parseInt(appSettings.retries) || 20;
  28.     appSettings.delayMin = parseInt(appSettings.delayMin) || 2000;
  29.     appSettings.delayMax = parseInt(appSettings.delayMax) || 4000;
  30.     if (typeof appSettings.notifications === 'undefined') appSettings.notifications = true;
  31.     if (typeof appSettings.customCSS === 'undefined') appSettings.customCSS = "";
  32.     if (typeof appSettings.saveAsPng === 'undefined') appSettings.saveAsPng = false;
  33.     if (typeof appSettings.apiBaseUrl === 'undefined') appSettings.apiBaseUrl = "";
  34.     if (typeof appSettings.videoPollTimeout === 'undefined') appSettings.videoPollTimeout = 300;
  35.     if (typeof appSettings.autoRetryStuckVideo === 'undefined') appSettings.autoRetryStuckVideo = false;
  36.  
  37.     let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  38.  
  39.     // API URL Helper
  40.     function getApiUrl(path) {
  41.         let base = appSettings.apiBaseUrl || '';
  42.         if (base.endsWith('/')) base = base.slice(0, -1);
  43.         if (!path.startsWith('/') && base) path = '/' + path;
  44.         return base + path;
  45.     }
  46.  
  47.     // ─── DYNAMIC PROMPT PARSER (SPINTAX & RANDOM SEED) ────────────────────────
  48.     function parseDynamicPrompt(text) {
  49.         if (!text) return text;
  50.  
  51.         let parsed = text;
  52.         let prev;
  53.         do {
  54.             prev = parsed;
  55.             parsed = parsed.replace(/\{([^{}]+)\}/g, (match, contents) => {
  56.                 if (contents.includes('|')) {
  57.                     const options = contents.split('|');
  58.                     return options[Math.floor(Math.random() * options.length)];
  59.                 }
  60.                 return match;
  61.             });
  62.         } while (parsed !== prev);
  63.  
  64.         parsed = parsed.replace(/@randomseed/gi, () => {
  65.             return Math.floor(1000000000 + Math.random() * 9000000000).toString();
  66.         });
  67.  
  68.         return parsed.trim();
  69.     }
  70.  
  71.     // ─── BACKGROUND ALERT SYSTEM (AUDIO + TAB BLINK) ──────────────────────────
  72.     let sharedAudioCtx = null;
  73.     let titleBlinkInterval = null;
  74.     const originalTitle = document.title || "xAI Pro Studio";
  75.  
  76.     function initAudio() {
  77.         if (!sharedAudioCtx && appSettings.notifications) {
  78.             try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); }
  79.             catch(e) { console.warn("AudioContext not supported"); }
  80.         }
  81.         if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  82.     }
  83.  
  84.     function notifyUser(isError = false) {
  85.         if (!appSettings.notifications) return;
  86.  
  87.         if (sharedAudioCtx) {
  88.             try {
  89.                 const osc = sharedAudioCtx.createOscillator();
  90.                 const gain = sharedAudioCtx.createGain();
  91.                 osc.connect(gain);
  92.                 gain.connect(sharedAudioCtx.destination);
  93.  
  94.                 if (isError) {
  95.                     osc.type = 'sawtooth';
  96.                     osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime);
  97.                     osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  98.                 } else {
  99.                     osc.type = 'sine';
  100.                     osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime);
  101.                     osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  102.                 }
  103.  
  104.                 gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime);
  105.                 gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  106.  
  107.                 osc.start(sharedAudioCtx.currentTime);
  108.                 osc.stop(sharedAudioCtx.currentTime + 0.5);
  109.             } catch(e) {}
  110.         }
  111.  
  112.         if (!document.hasFocus()) {
  113.             if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  114.             let toggle = true;
  115.             titleBlinkInterval = setInterval(() => {
  116.                 document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle;
  117.                 toggle = !toggle;
  118.             }, 1000);
  119.  
  120.             const clearBlink = () => {
  121.                 clearInterval(titleBlinkInterval);
  122.                 document.title = originalTitle;
  123.                 window.removeEventListener('focus', clearBlink);
  124.             };
  125.             window.addEventListener('focus', clearBlink);
  126.         }
  127.     }
  128.  
  129.     // ─── STEALTH IDENTITY RESETTER ────────────────────────────────────────────
  130.     function stealthIdentityReset() {
  131.         const trackingCookies =['x-anonuserid', 'mixpanel', 'mp_', 'distinct_id'];
  132.         document.cookie.split(';').forEach(c => {
  133.             const name = c.split('=')[0].trim();
  134.             if (trackingCookies.some(tc => name.includes(tc))) {['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => {
  135.                         document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`;
  136.                     });
  137.                 });
  138.             }
  139.         });
  140.  
  141.         for (let i = localStorage.length - 1; i >= 0; i--) {
  142.             const k = localStorage.key(i);
  143.             if (k && !k.startsWith('xai_api_') && trackingCookies.some(tc => k.includes(tc))) {
  144.                 localStorage.removeItem(k);
  145.             }
  146.         }
  147.     }
  148.  
  149.     // ─── EXIF LIBRARY LOADER & WINDOWS METADATA ENCODER ───────────────────────
  150.     let piexifLoaded = false;
  151.     function loadPiexif() {
  152.         if (piexifLoaded) return Promise.resolve(window.piexif);
  153.         return new Promise(resolve => {
  154.             const script = document.createElement('script');
  155.             script.src = 'https://cdn.jsdelivr.net/npm/piexifjs';
  156.             script.onload = () => { piexifLoaded = true; resolve(window.piexif); };
  157.             document.head.appendChild(script);
  158.         });
  159.     }
  160.  
  161.     function toUTF16LE(str) {
  162.         const arr =[];
  163.         for (let i = 0; i < str.length; i++) {
  164.             const code = str.charCodeAt(i);
  165.             arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF);
  166.         }
  167.         arr.push(0, 0); return arr;
  168.     }
  169.  
  170.     function convertToJpegWithExif(base64PngUri, prompt) {
  171.         return new Promise((resolve, reject) => {
  172.             const img = new Image();
  173.             img.onload = async () => {
  174.                 const canvas = document.createElement('canvas');
  175.                 canvas.width = img.width; canvas.height = img.height;
  176.                 const ctx = canvas.getContext('2d');
  177.                 ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  178.                 ctx.drawImage(img, 0, 0);
  179.  
  180.                 let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  181.                 if (prompt) {
  182.                     try {
  183.                         const piexif = await loadPiexif();
  184.                         const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  185.                         const safePrompt = unescape(encodeURIComponent(prompt));
  186.                         exifObj['0th'][piexif.ImageIFD.ImageDescription] = safePrompt;
  187.  
  188.                         const utf16Prompt = toUTF16LE(prompt);
  189.                         exifObj['0th'][40091] = utf16Prompt;
  190.                         exifObj['0th'][40092] = utf16Prompt;
  191.                         exifObj['0th'][40093] = utf16Prompt;
  192.  
  193.                         jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  194.                     } catch (e) {}
  195.                 }
  196.                 resolve(jpegUri);
  197.             };
  198.             img.onerror = reject; img.src = base64PngUri;
  199.         });
  200.     }
  201.  
  202.     async function extractPromptFromImage(file) {
  203.         if (!file.type.includes('image')) return null;
  204.         try {
  205.             const piexif = await loadPiexif();
  206.             return new Promise((resolve) => {
  207.                 const reader = new FileReader();
  208.                 reader.onload = (e) => {
  209.                     try {
  210.                         const exifData = piexif.load(e.target.result);
  211.                         let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  212.                         if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  213.                         if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(e) {} }
  214.  
  215.                         if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  216.                             const xpTitleArr = exifData['0th'][40091];
  217.                             let str = '';
  218.                             for (let i = 0; i < xpTitleArr.length; i += 2) {
  219.                                 const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
  220.                                 if (charCode === 0) break;
  221.                                 str += String.fromCharCode(charCode);
  222.                             }
  223.                             prompt = str;
  224.                         }
  225.                         resolve(prompt ? prompt.trim() : null);
  226.                     } catch (err) { resolve(null); }
  227.                 };
  228.                 reader.readAsDataURL(file);
  229.             });
  230.         } catch (e) { return null; }
  231.     }
  232.  
  233.     // ─── VIDEO THUMBNAIL EXTRACTOR ────────────────────────────────────────────
  234.     function generateVideoThumbnail(file) {
  235.         return new Promise((resolve) => {
  236.             const video = document.createElement('video');
  237.             video.preload = 'metadata';
  238.             video.muted = true;
  239.             video.playsInline = true;
  240.  
  241.             const url = URL.createObjectURL(file);
  242.             video.src = url;
  243.  
  244.             let isSeeked = false;
  245.  
  246.             video.onloadeddata = () => {
  247.                 video.currentTime = Math.min(0.5, video.duration / 2 || 0);
  248.             };
  249.  
  250.             video.onseeked = () => {
  251.                 if (isSeeked) return;
  252.                 isSeeked = true;
  253.                 try {
  254.                     const canvas = document.createElement('canvas');
  255.                     canvas.width = video.videoWidth || 140;
  256.                     canvas.height = video.videoHeight || 140;
  257.                     const ctx = canvas.getContext('2d');
  258.                     ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  259.                     URL.revokeObjectURL(url);
  260.                     resolve(canvas.toDataURL('image/jpeg', 0.8));
  261.                 } catch(e) {
  262.                     URL.revokeObjectURL(url);
  263.                     resolve(null);
  264.                 }
  265.             };
  266.  
  267.             video.onerror = () => {
  268.                 URL.revokeObjectURL(url);
  269.                 resolve(null);
  270.             };
  271.  
  272.             setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
  273.         });
  274.     }
  275.  
  276.     // ─── ASPECT RATIO DATA ────────────────────────────────────────────────────
  277.     const arData =[
  278.         { label: 'Auto', w: 1, h: 1, isAuto: true },
  279.         { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  280.         { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
  281.         { label: '3:2', w: 3, h: 2 }, { label: '9:19.5', w: 9, h: 19.5 }, { label: '19.5:9', w: 19.5, h: 9 },
  282.         { label: '9:20', w: 9, h: 20 }, { label: '20:9', w: 20, h: 9 }, { label: '1:2', w: 1, h: 2 }, { label: '2:1', w: 2, h: 1 }
  283.     ];
  284.  
  285.     function createArIcon(w, h, isAuto) {
  286.         if (isAuto) return `<div style="width: 12px; height: 12px; border: 1px dashed #64748b; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 9px; color: #94a3b8;">A</div>`;
  287.         const scale = 12 / Math.max(w, h);
  288.         return `<div style="width: 14px; height: 14px; display: flex; align-items: center; justify-content: center;"><div style="width: ${w * scale}px; height: ${h * scale}px; border: 1.5px solid #cbd5e1; border-radius: 2px;"></div></div>`;
  289.     }
  290.  
  291.     // ─── UI INJECTION (COMPACT CSS) ───────────────────────────────────────────
  292.     const UI_CSS = `
  293.         ::-webkit-scrollbar { width: 6px; }
  294.         ::-webkit-scrollbar-track { background: #0f172a; }
  295.         ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  296.  
  297.         @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  298.         @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  299.  
  300.         .loading-spinner { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff; border-radius: 50%; animation: spin 1s linear infinite; flex-shrink: 0; }
  301.         .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  302.         .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  303.  
  304.         #xai-pro-app { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999999; background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); font-family: 'Inter', -apple-system, sans-serif; color: #e2e8f0; display: flex; gap: 10px; padding: 10px; box-sizing: border-box; }
  305.         #xai-pro-app * { box-sizing: border-box; }
  306.  
  307.         .panel { background: #1e293b; border-radius: 10px; border: 1px solid #334155; box-shadow: 0 4px 15px rgba(0,0,0,0.4); display: flex; flex-direction: column; overflow: hidden; }
  308.         .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
  309.  
  310.         .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
  311.         .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
  312.         .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
  313.         .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
  314.  
  315.         textarea, select, input[type="text"], input[type="number"], input[type="checkbox"] { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 8px; color: #f8fafc; font-size: 13px; outline: none; transition: 0.2s; color-scheme: dark; }
  316.         textarea, select, input[type="text"], input[type="number"] { width: 100%; }
  317.         textarea:focus, select:focus, input[type="text"]:focus, input[type="number"]:focus { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  318.         .prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  319.         label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  320.  
  321.         .btn-primary { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); color: #fff; border: none; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; }
  322.         .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
  323.         .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  324.  
  325.         .btn-secondary { background: #1e293b; color: #cbd5e1; border: 1px solid #475569; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; display: flex; justify-content: center; align-items: center; }
  326.         .btn-secondary:hover:not(:disabled) { background: #334155; border-color: #64748b; }
  327.  
  328.         .ar-select-box { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; color: #f8fafc; font-size: 13px; }
  329.         #ar-options-container { position: fixed; background: #1e293b; border: 1px solid #334155; border-radius: 6px; box-shadow: 0 10px 25px rgba(0,0,0,0.4); max-height: 250px; overflow-y: auto; display: none; z-index: 99999999; }
  330.         .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  331.         .ar-option:hover { background: #334155; color: #f8fafc; }
  332.  
  333.         .img-wrapper { position: relative; display: block; }
  334.         .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  335.  
  336.         .overlay-btn { position: absolute; top: 6px; background: rgba(15, 23, 42, 0.6); color: white; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; text-decoration: none; backdrop-filter: blur(4px); transition: 0.2s; opacity: 0.75; z-index: 50; cursor: pointer; border: none; padding: 0; }
  337.         .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  338.         .overlay-dl-btn { right: 6px; }
  339.         .overlay-edit-btn { right: 40px; color: #10b981; }
  340.  
  341.         .ref-item { display: flex; align-items: center; gap: 10px; padding: 8px; background: #1e293b; border: 1px solid #334155; border-radius: 6px; margin-bottom: 6px; cursor: grab; box-shadow: 0 2px 4px rgba(0,0,0,0.2); transition: 0.1s; }
  342.         .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  343.         .ref-item:active { cursor: grabbing; }
  344.         .ref-item.dragging { opacity: 0.4; }
  345.         .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  346.         .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  347.         .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
  348.         .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  349.         .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  350.         .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; border-radius: 4px; padding: 6px; cursor: pointer; font-size: 11px; transition: 0.2s; font-weight: bold; width: 100%; text-align: center; }
  351.         .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  352.         .drag-over-top { border-top: 2px solid #22c55e !important; }
  353.         .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  354.  
  355.         .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
  356.         .history-card .overlay-btn { width: 24px; height: 24px; top: 4px; border-radius: 4px; }
  357.         .history-card .overlay-dl-btn { right: 4px; }
  358.         .history-card .overlay-edit-btn { right: 32px; }
  359.         .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
  360.         .history-card p:hover { background: #1e293b; color: #e2e8f0; }
  361.  
  362.         .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; }
  363.         .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
  364.  
  365.         /* Modals Generic Classes */
  366.         .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 999999999; display: none; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
  367.         .modal-box { background: #1e293b; border-radius: 10px; width: 500px; max-width: 90vw; padding: 15px; display: flex; flex-direction: column; gap: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); border: 1px solid #334155; max-height: 90vh; }
  368.         .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  369.         .fav-text { flex: 1; font-size: 12px; color: #cbd5e1; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-right: 10px; transition: color 0.2s; }
  370.         .fav-text:hover { color: #10b981; }
  371.  
  372.         #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  373.         #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
  374.  
  375.         #xai-lightbox { cursor: zoom-out; }
  376.         #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  377.         #xai-lightbox-img { max-width: 100%; max-height: 95vh; display: block; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); }
  378.     `;
  379.  
  380.     const UI_HTML = `
  381.         <div id="xai-pro-app">
  382.             <div id="settings-btn" title="Studio Settings">⚙️</div>
  383.  
  384.             <!-- LEFT COLUMN -->
  385.             <div class="col-left">
  386.                 <div class="panel" style="flex-shrink: 0;">
  387.                     <div style="display: flex; background: rgba(0,0,0,0.2); border-radius: 0 0 6px 6px; margin-bottom: 10px; border-bottom: 1px solid #334155; padding: 10px;">
  388.                         <div style="flex: 1;">
  389.                             <label>Master Action</label>
  390.                             <select id="master-action" style="font-weight: bold; color: #f8fafc; border-color: #475569; box-shadow: 0 2px 4px rgba(0,0,0,0.3);">
  391.                                 <option value="gen_image">🖼️ Generate Image</option>
  392.                                 <option value="gen_video">🎥 Generate Video</option>
  393.                                 <option value="edit_video">✂️ Edit Video</option>
  394.                                 <option value="extend_video">➡️ Extend Video</option>
  395.                             </select>
  396.                         </div>
  397.                     </div>
  398.  
  399.                     <div style="padding: 10px; display: flex; flex-direction: column; gap: 10px;">
  400.                         <div id="setting-ar">
  401.                             <label>Aspect Ratio</label>
  402.                             <div class="ar-select-box" id="ar-select-box">
  403.                                 <div id="ar-selected-icon"></div>
  404.                                 <span id="ar-selected-text">Auto</span>
  405.                             </div>
  406.                         </div>
  407.  
  408.                         <div style="display: flex; gap: 8px;">
  409.                             <div id="setting-res-img" style="flex: 1;">
  410.                                 <label>Resolution</label>
  411.                                 <select id="xai-api-res-img">
  412.                                     <option value="2k" selected>2K (Pro)</option>
  413.                                     <option value="1k">1K</option>
  414.                                 </select>
  415.                             </div>
  416.                             <div id="setting-res-vid" style="flex: 1; display: none;">
  417.                                 <label>Resolution</label>
  418.                                 <select id="xai-api-res-vid">
  419.                                     <option value="720p" selected>720p (HD)</option>
  420.                                     <option value="480p">480p (SD)</option>
  421.                                 </select>
  422.                             </div>
  423.  
  424.                             <div id="setting-batch" style="flex: 1;">
  425.                                 <label>Batch Size</label>
  426.                                 <select id="xai-api-n">
  427.                                     <option value="1" selected>1 Image</option>
  428.                                     <option value="2">2 Images</option>
  429.                                     <option value="3">3 Images</option>
  430.                                     <option value="4">4 Images</option>
  431.                                     <option value="5">5 Images</option>
  432.                                     <option value="8">8 Images</option>
  433.                                     <option value="10">10 Images</option>
  434.                                 </select>
  435.                             </div>
  436.                             <div id="setting-duration" style="flex: 1; display: none;">
  437.                                 <label>Duration</label>
  438.                                 <select id="xai-api-duration">
  439.                                     <option value="5" selected>5 Seconds</option>
  440.                                     <option value="8">8 Seconds</option>
  441.                                     <option value="10">10 Seconds</option>
  442.                                     <option value="12">12 Seconds</option>
  443.                                     <option value="15">15 Seconds</option>
  444.                                     <option value="2">2s Extension</option>
  445.                                     <option value="4">4s Extension</option>
  446.                                     <option value="6">6s Extension</option>
  447.                                 </select>
  448.                             </div>
  449.  
  450.                             <div id="setting-loops" style="flex: 1;">
  451.                                 <label title="How many consecutive API calls to perform in a row">Loops</label>
  452.                                 <input type="number" id="xai-api-loops" value="1" min="1" max="100">
  453.                             </div>
  454.                         </div>
  455.                     </div>
  456.                 </div>
  457.  
  458.                 <div class="panel" style="flex: 1; min-height: 0;">
  459.                     <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
  460.                         <span>Previous Results</span>
  461.                         <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
  462.                     </div>
  463.                     <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
  464.                         <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
  465.                     </div>
  466.                 </div>
  467.             </div>
  468.  
  469.             <!-- CENTER COLUMN -->
  470.             <div class="col-center">
  471.                 <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
  472.                     <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
  473.                     <div id="xai-current-images" style="flex: 1; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 10px; align-content: start; padding-bottom: 10px;"></div>
  474.                 </div>
  475.  
  476.                 <div class="panel" style="flex-shrink: 0; padding: 12px;">
  477.                     <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  478.                         <span style="display: flex; align-items: center; gap: 8px;">
  479.                             <span>Prompt</span>
  480.                             <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
  481.                         </span>
  482.                         <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  483.                     </label>
  484.                     <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed" style="height: 100px; min-height: 70px; margin-bottom: 10px; font-size: 13px;"></textarea>
  485.  
  486.                     <div style="display: flex; align-items: center; justify-content: space-between;">
  487.                         <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
  488.                         <div style="display: flex; gap: 8px;">
  489.                             <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
  490.                             <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
  491.                             <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  492.                         </div>
  493.                     </div>
  494.                 </div>
  495.             </div>
  496.  
  497.             <!-- RIGHT COLUMN -->
  498.             <div class="col-right" id="col-right-dropzone">
  499.                 <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  500.                     <div class="panel-title" id="ref-panel-title">Reference Media</div>
  501.                     <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  502.                         <div id="xai-upload-placeholder" style="border: 2px dashed #475569; border-radius: 8px; width: 100%; padding: 15px 10px; color: #94a3b8; cursor: pointer; text-align: center; transition: 0.2s; margin-bottom: 10px; background: rgba(0,0,0,0.1);">
  503.                             <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  504.                             <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  505.                         </div>
  506.                         <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  507.                         <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  508.                         <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  509.                     </div>
  510.                 </div>
  511.             </div>
  512.  
  513.             <!-- FIXED FLOATING DROPDOWN -->
  514.             <div id="ar-options-container"></div>
  515.  
  516.             <!-- MODALS -->
  517.             <div id="xai-lightbox" class="modal-overlay">
  518.                 <div id="xai-lightbox-wrapper">
  519.                     <img id="xai-lightbox-img" src="">
  520.                     <a id="xai-lightbox-dl" href="#" download="" target="_blank" class="overlay-btn overlay-dl-btn" style="top: 15px; right: 15px; width: 44px; height: 44px; border-radius: 50%; background: rgba(0,0,0,0.7);" title="Download File">${DOWNLOAD_ICON}</a>
  521.                 </div>
  522.             </div>
  523.  
  524.             <!-- SETTINGS MODAL -->
  525.             <div id="xai-settings-modal" class="modal-overlay">
  526.                 <div class="modal-box" style="width: 500px;">
  527.                     <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  528.                     <div style="display:flex; gap:10px;">
  529.                         <div style="flex:1;">
  530.                             <label>Max Retries</label>
  531.                             <input type="number" id="set-retries" min="1" max="100">
  532.                         </div>
  533.                         <div style="flex:1;">
  534.                             <label>Delay Min (ms)</label>
  535.                             <input type="number" id="set-delay-min" min="500" step="500">
  536.                         </div>
  537.                         <div style="flex:1;">
  538.                             <label>Delay Max (ms)</label>
  539.                             <input type="number" id="set-delay-max" min="1000" step="500">
  540.                         </div>
  541.                     </div>
  542.                     <div>
  543.                         <label>API Base URL (Leave empty for default console.x.ai)</label>
  544.                         <input type="text" id="set-api-base-url" placeholder="e.g., https://api.proxy.com">
  545.                     </div>
  546.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  547.                         <input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;">
  548.                         <label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label>
  549.                     </div>
  550.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  551.                         <input type="checkbox" id="set-save-png" style="width: 16px; height: 16px;">
  552.                         <label for="set-save-png" style="margin: 0; cursor: pointer;">Save as Original PNG (Disable JPEG / EXIF Prompt)</label>
  553.                     </div>
  554.                     <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;">
  555.                         <input type="checkbox" id="set-auto-retry-video" style="width: 16px; height: 16px;">
  556.                         <label for="set-auto-retry-video" style="margin: 0; cursor: pointer;">Auto-Retry Stuck Videos (Timeout / Moderated)</label>
  557.                     </div>
  558.                     <div style="margin-top: 4px;">
  559.                         <label>Video Polling Timeout (Seconds)</label>
  560.                         <input type="number" id="set-video-timeout" min="10" step="10">
  561.                     </div>
  562.                     <div>
  563.                         <label>Custom CSS Overrides</label>
  564.                         <textarea id="set-custom-css" style="font-family: monospace; height: 100px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  565.                     </div>
  566.                     <div style="display: flex; gap: 8px; margin-top: 5px;">
  567.                         <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  568.                         <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  569.                     </div>
  570.                 </div>
  571.             </div>
  572.  
  573.             <!-- FAVORITES MODAL -->
  574.             <div id="xai-fav-modal" class="modal-overlay">
  575.                 <div class="modal-box" style="width: 550px;">
  576.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  577.                         <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  578.                         <button id="close-fav-btn" style="background: none; border: none; color: #ef4444; font-size: 20px; cursor: pointer; font-weight: bold; line-height: 1;">&times;</button>
  579.                     </div>
  580.                     <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  581.                     <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  582.                 </div>
  583.             </div>
  584.  
  585.             <!-- CUSTOM PAYLOAD DEBUGGER MODAL -->
  586.             <div id="xai-payload-modal" class="modal-overlay">
  587.                 <div class="modal-box" style="width: 550px;">
  588.                     <div style="display: flex; justify-content: space-between; align-items: center;">
  589.                         <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  590.                         <button id="close-payload-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  591.                     </div>
  592.                     <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  593.                     <div><label>JSON Payload (Editable):</label><textarea id="payload-code" style="background: #0f172a; color: #e2e8f0; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 12px; height: 250px; resize: vertical; border: 1px solid #334155;"></textarea></div>
  594.                     <button id="send-custom-payload-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);"><div class="btn-content">🚀 Send Custom Payload</div></button>
  595.                     <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  596.                 </div>
  597.             </div>
  598.         </div>
  599.     `;
  600.  
  601.     // ─── INITIALIZATION ───────────────────────────────────────────────────────
  602.     let updateUIForEditMedia = null;
  603.  
  604.     const initApp = () => {
  605.         if (!document.body) return setTimeout(initApp, 50);
  606.  
  607.         const hideOriginals = () => {
  608.             Array.from(document.body.children).forEach(child => {
  609.                 if (child.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(child.tagName)) {
  610.                     child.style.display = 'none';
  611.                 }
  612.             });
  613.         };
  614.         hideOriginals();
  615.         new MutationObserver(hideOriginals).observe(document.body, { childList: true });
  616.  
  617.         if (!document.getElementById('xai-pro-app')) {
  618.             const style = document.createElement('style');
  619.             style.innerHTML = UI_CSS;
  620.             document.head.appendChild(style);
  621.  
  622.             const customStyle = document.createElement('style');
  623.             customStyle.id = 'xai-custom-css-block';
  624.             customStyle.innerHTML = appSettings.customCSS;
  625.             document.head.appendChild(customStyle);
  626.  
  627.             document.body.insertAdjacentHTML('beforeend', UI_HTML);
  628.             bindLogic();
  629.         }
  630.     };
  631.  
  632.     let referenceMedia =[];
  633.     let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  634.     let fullPayloadMemory = {};
  635.     let currentAbortController = null;
  636.     let isRequestCancelled = false;
  637.  
  638.     function saveRefs() {
  639.         try {
  640.             localStorage.setItem('xai_api_refs', JSON.stringify(referenceMedia));
  641.         } catch (e) {
  642.             console.warn("[xAI Studio] Could not save references to localStorage (quota exceeded). Images will not persist after refresh.");
  643.         }
  644.     }
  645.  
  646.     function bindLogic() {
  647.         const els = {
  648.             app: document.getElementById('xai-pro-app'),
  649.             prompt: document.getElementById('xai-api-prompt'),
  650.             action: document.getElementById('master-action'),
  651.             resImg: document.getElementById('xai-api-res-img'),
  652.             resVid: document.getElementById('xai-api-res-vid'),
  653.             n: document.getElementById('xai-api-n'),
  654.             duration: document.getElementById('xai-api-duration'),
  655.             loops: document.getElementById('xai-api-loops'),
  656.  
  657.             settingAr: document.getElementById('setting-ar'),
  658.             settingResImg: document.getElementById('setting-res-img'),
  659.             settingResVid: document.getElementById('setting-res-vid'),
  660.             settingBatch: document.getElementById('setting-batch'),
  661.             settingDuration: document.getElementById('setting-duration'),
  662.             settingLoops: document.getElementById('setting-loops'),
  663.  
  664.             fileInput: document.getElementById('xai-api-file'),
  665.             dropzone: document.getElementById('col-right-dropzone'),
  666.             uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  667.             refList: document.getElementById('xai-ref-list'),
  668.             refTitle: document.getElementById('ref-panel-title'),
  669.  
  670.             btn: document.getElementById('xai-api-generate'),
  671.             previewBtn: document.getElementById('xai-preview-btn'),
  672.             cancelBtn: document.getElementById('xai-cancel-btn'),
  673.             status: document.getElementById('xai-api-status'),
  674.             history: document.getElementById('xai-history'),
  675.             currentImages: document.getElementById('xai-current-images'),
  676.             reset: document.getElementById('xai-reset-btn'),
  677.  
  678.             arSelectBox: document.getElementById('ar-select-box'),
  679.             arOptionsCont: document.getElementById('ar-options-container'),
  680.             arSelectedIcon: document.getElementById('ar-selected-icon'),
  681.             arSelectedText: document.getElementById('ar-selected-text'),
  682.  
  683.             lightbox: document.getElementById('xai-lightbox'),
  684.             lightboxImg: document.getElementById('xai-lightbox-img'),
  685.             lightboxDl: document.getElementById('xai-lightbox-dl'),
  686.  
  687.             payloadModal: document.getElementById('xai-payload-modal'),
  688.             payloadEndpoint: document.getElementById('payload-endpoint'),
  689.             payloadCode: document.getElementById('payload-code'),
  690.             closePayloadBtn: document.getElementById('close-payload-btn'),
  691.             sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  692.             customStatus: document.getElementById('custom-payload-status'),
  693.  
  694.             settingsBtn: document.getElementById('settings-btn'),
  695.             settingsModal: document.getElementById('xai-settings-modal'),
  696.             closeSettingsBtn: document.getElementById('close-settings-btn'),
  697.             saveSettingsBtn: document.getElementById('save-settings-btn'),
  698.  
  699.             favBtn: document.getElementById('fav-prompts-btn'),
  700.             favModal: document.getElementById('xai-fav-modal'),
  701.             closeFavBtn: document.getElementById('close-fav-btn'),
  702.             addFavBtn: document.getElementById('add-current-fav-btn'),
  703.             favList: document.getElementById('fav-list')
  704.         };
  705.  
  706.         if (localStorage.getItem('xai_api_prompt')) els.prompt.value = localStorage.getItem('xai_api_prompt');
  707.         els.prompt.addEventListener('input', () => localStorage.setItem('xai_api_prompt', els.prompt.value));
  708.  
  709.         try {
  710.             const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  711.             if (storedGen.action) els.action.value = storedGen.action;
  712.             if (storedGen.resImg) els.resImg.value = storedGen.resImg;
  713.             if (storedGen.resVid) els.resVid.value = storedGen.resVid;
  714.             if (storedGen.n) els.n.value = storedGen.n;
  715.             if (storedGen.duration) els.duration.value = storedGen.duration;
  716.             if (storedGen.loops) els.loops.value = storedGen.loops;
  717.         } catch(e) {}
  718.  
  719.         const updateGenSettingsMemory = () => {
  720.             localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  721.                 action: els.action.value, resImg: els.resImg.value, resVid: els.resVid.value,
  722.                 n: els.n.value, duration: els.duration.value, loops: els.loops.value
  723.             }));
  724.         };
  725.         [els.action, els.resImg, els.resVid, els.n, els.duration, els.loops].forEach(el => el.addEventListener('change', updateGenSettingsMemory));
  726.  
  727.         try {
  728.             const storedRefs = JSON.parse(localStorage.getItem('xai_api_refs'));
  729.             if (Array.isArray(storedRefs)) referenceMedia = storedRefs;
  730.         } catch(e) {}
  731.  
  732.         // ─── SETTINGS BINDINGS ───────────────────────────────────────────────────
  733.         els.settingsBtn.addEventListener('click', () => {
  734.             document.getElementById('set-retries').value = appSettings.retries;
  735.             document.getElementById('set-delay-min').value = appSettings.delayMin;
  736.             document.getElementById('set-delay-max').value = appSettings.delayMax;
  737.             document.getElementById('set-notifications').checked = appSettings.notifications;
  738.             document.getElementById('set-save-png').checked = appSettings.saveAsPng;
  739.             document.getElementById('set-auto-retry-video').checked = appSettings.autoRetryStuckVideo;
  740.             document.getElementById('set-video-timeout').value = appSettings.videoPollTimeout;
  741.             document.getElementById('set-api-base-url').value = appSettings.apiBaseUrl || '';
  742.             document.getElementById('set-custom-css').value = appSettings.customCSS || '';
  743.             els.settingsModal.style.display = 'flex';
  744.         });
  745.  
  746.         els.saveSettingsBtn.addEventListener('click', () => {
  747.             appSettings.retries = parseInt(document.getElementById('set-retries').value) || 20;
  748.             appSettings.delayMin = parseInt(document.getElementById('set-delay-min').value) || 2000;
  749.             appSettings.delayMax = Math.max(appSettings.delayMin, parseInt(document.getElementById('set-delay-max').value) || 4000);
  750.             appSettings.notifications = document.getElementById('set-notifications').checked;
  751.             appSettings.saveAsPng = document.getElementById('set-save-png').checked;
  752.             appSettings.autoRetryStuckVideo = document.getElementById('set-auto-retry-video').checked;
  753.             appSettings.videoPollTimeout = parseInt(document.getElementById('set-video-timeout').value) || 300;
  754.             appSettings.apiBaseUrl = document.getElementById('set-api-base-url').value.trim();
  755.             appSettings.customCSS = document.getElementById('set-custom-css').value;
  756.  
  757.             localStorage.setItem('xai_api_settings', JSON.stringify(appSettings));
  758.             document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS;
  759.  
  760.             els.settingsModal.style.display = 'none';
  761.         });
  762.  
  763.         els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  764.  
  765.         // ─── FAVORITES BINDINGS ──────────────────────────────────────────────────
  766.         function renderFavList() {
  767.             els.favList.innerHTML = '';
  768.             if (favoritePrompts.length === 0) {
  769.                 els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>';
  770.                 return;
  771.             }
  772.             favoritePrompts.forEach((promptText, idx) => {
  773.                 const div = document.createElement('div');
  774.                 div.className = 'fav-item';
  775.                 div.innerHTML = `
  776.                     <div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div>
  777.                    <button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>
  778.                `;
  779.                div.querySelector('.fav-text').addEventListener('click', () => {
  780.                    els.prompt.value = promptText;
  781.                    localStorage.setItem('xai_api_prompt', promptText);
  782.                    els.favModal.style.display = 'none';
  783.                });
  784.                div.querySelector('button').addEventListener('click', () => {
  785.                    favoritePrompts.splice(idx, 1);
  786.                    localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  787.                    renderFavList();
  788.                });
  789.                els.favList.appendChild(div);
  790.            });
  791.        }
  792.  
  793.        els.favBtn.addEventListener('click', () => {
  794.            renderFavList();
  795.            els.favModal.style.display = 'flex';
  796.        });
  797.        els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  798.        els.addFavBtn.addEventListener('click', () => {
  799.            const p = els.prompt.value.trim();
  800.            if (!p) return alert("Prompt is empty!");
  801.            if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  802.            favoritePrompts.unshift(p);
  803.            localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts));
  804.            renderFavList();
  805.        });
  806.  
  807.        // ─── PROMPT BOX EXIF DRAG & DROP ──────────────────────────────────────────
  808.        els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.prompt.classList.add('prompt-drag-over'); });
  809.        els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.prompt.classList.remove('prompt-drag-over'); });
  810.        els.prompt.addEventListener('drop', async (e) => {
  811.            e.preventDefault(); e.stopPropagation();
  812.            els.prompt.classList.remove('prompt-drag-over');
  813.            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  814.                const file = e.dataTransfer.files[0];
  815.                const oldVal = els.prompt.value;
  816.                els.prompt.value = "Extracting prompt from EXIF...";
  817.                const extractedPrompt = await extractPromptFromImage(file);
  818.                if (extractedPrompt) {
  819.                    els.prompt.value = extractedPrompt;
  820.                    localStorage.setItem('xai_api_prompt', extractedPrompt);
  821.                } else {
  822.                    els.prompt.value = oldVal;
  823.                    alert("No prompt found in this image's EXIF data (or not a valid JPEG).");
  824.                }
  825.            }
  826.        });
  827.  
  828.        // ─── MASTER ACTION UI LOGIC ───────────────────────────────────────────────
  829.        function getMaxMedia() {
  830.            const val = els.action.value;
  831.            if (val === 'gen_image') return 5;
  832.            if (val === 'gen_video') return 7;
  833.            return 1;
  834.        }
  835.  
  836.        function updateActionUI() {
  837.            const val = els.action.value;
  838.  
  839.            if (val === 'gen_image') {
  840.                els.settingAr.style.display = 'block'; els.settingResImg.style.display = 'block'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'block'; els.settingDuration.style.display = 'none';
  841.            } else if (val === 'gen_video') {
  842.                els.settingAr.style.display = 'block'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'block'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'block';
  843.                els.duration.innerHTML = `<option value="5">5 Seconds</option><option value="8">8 Seconds</option><option value="10">10 Seconds</option><option value="12">12 Seconds</option><option value="15">15 Seconds</option>`;
  844.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 15) {
  845.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  846.                } else els.duration.value = "5";
  847.            } else if (val === 'edit_video') {
  848.                els.settingAr.style.display = 'none'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
  849.            } else if (val === 'extend_video') {
  850.                els.settingAr.style.display = 'none'; els.settingResImg.style.display = 'none'; els.settingResVid.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'block';
  851.                els.duration.innerHTML = `<option value="2">2s Extension</option><option value="4">4s Extension</option><option value="6">6s Extension</option><option value="8">8s Extension</option><option value="10">10s Extension</option>`;
  852.                if (localStorage.getItem('xai_api_gen_settings') && JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration <= 10) {
  853.                    els.duration.value = JSON.parse(localStorage.getItem('xai_api_gen_settings')).duration;
  854.                } else els.duration.value = "6";
  855.            }
  856.  
  857.            const max = getMaxMedia();
  858.            els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  859.  
  860.            let activeCount = 0;
  861.            referenceMedia.forEach(m => {
  862.                let valid = true;
  863.                if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  864.                if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  865.  
  866.                if (!valid) m.active = false;
  867.                else if (m.active) {
  868.                    activeCount++;
  869.                    if (activeCount > max) m.active = false;
  870.                }
  871.            });
  872.            renderRefList();
  873.        }
  874.  
  875.        els.action.addEventListener('change', updateActionUI);
  876.        updateActionUI();
  877.  
  878.        // ─── INSTANT EDIT BINDING HANDLER ─────────────────────────────────────────
  879.        updateUIForEditMedia = (mediaUrl, isVideo, fileName) => {
  880.            referenceMedia.forEach(m => m.active = false);
  881.  
  882.            referenceMedia.unshift({
  883.                id: Date.now() + Math.random(),
  884.                base64: mediaUrl,
  885.                isVideo: isVideo,
  886.                active: true,
  887.                thumb: isVideo ? null : mediaUrl,
  888.                fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png')
  889.            });
  890.  
  891.            els.action.value = isVideo ? 'edit_video' : 'gen_image';
  892.            updateActionUI();
  893.            updateGenSettingsMemory();
  894.            renderRefList();
  895.            saveRefs();
  896.        };
  897.  
  898.        // ─── BUILD PAYLOAD LOGIC ──────────────────────────────────────────────────
  899.        function buildPayloadData(dynamicPromptText) {
  900.            const action = els.action.value;
  901.            const payload = {
  902.                model: action === 'gen_image' ? "grok-imagine-image" : "grok-imagine-video",
  903.                prompt: dynamicPromptText,
  904.            };
  905.  
  906.            const ar = currentAr.toLowerCase();
  907.            const activeRefs = referenceMedia.filter(m => m.active);
  908.  
  909.            if (action === 'gen_image') {
  910.                payload.n = parseInt(els.n.value); payload.resolution = els.resImg.value; payload.response_format = "b64_json";
  911.                if (ar !== 'auto') payload.aspect_ratio = ar; else if (activeRefs.length > 0) payload.aspect_ratio = 'auto';
  912.  
  913.                if (activeRefs.length > 0) {
  914.                    if (activeRefs.length === 1) payload.image = { url: activeRefs[0].base64 };
  915.                    else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  916.                }
  917.            } else if (action === 'gen_video') {
  918.                payload.duration = parseInt(els.duration.value); payload.resolution = els.resVid.value;
  919.                if (ar !== 'auto') payload.aspect_ratio = ar;
  920.                if (activeRefs.length > 0) payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  921.            } else if (action === 'edit_video') {
  922.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  923.            } else if (action === 'extend_video') {
  924.                payload.duration = parseInt(els.duration.value);
  925.                if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  926.            }
  927.            return payload;
  928.        }
  929.  
  930.        // ─── CUSTOM PAYLOAD DEBUGGER LOGIC ────────────────────────────────────────
  931.        els.previewBtn.addEventListener('click', () => {
  932.            const dynamicPrompt = parseDynamicPrompt(els.prompt.value.trim());
  933.            fullPayloadMemory = buildPayloadData(dynamicPrompt);
  934.            const displayP = JSON.parse(JSON.stringify(fullPayloadMemory));
  935.            const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  936.  
  937.            if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => img.url = trunc); else displayP.image.url = trunc; }
  938.            if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => img.url = trunc);
  939.            if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => img.url = trunc);
  940.            if (displayP.video) displayP.video.url = trunc;
  941.  
  942.            const activeRefs = referenceMedia.filter(m => m.active);
  943.            let endpoint = '/v1/images/generations';
  944.            if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  945.            else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  946.            else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  947.            else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  948.  
  949.            els.payloadEndpoint.value = endpoint;
  950.            els.payloadCode.value = JSON.stringify(displayP, null, 2);
  951.            els.payloadModal.style.display = 'flex';
  952.        });
  953.  
  954.        els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  955.  
  956.        function injectBase64(editedObj, originalObj) {
  957.            if (!editedObj || typeof editedObj !== 'object') return;
  958.            for (let key in editedObj) {
  959.                if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') {
  960.                    if (originalObj && originalObj[key]) editedObj[key] = originalObj[key];
  961.                } else if (typeof editedObj[key] === 'object') { injectBase64(editedObj[key], originalObj ? originalObj[key] : null); }
  962.            }
  963.        }
  964.  
  965.        els.sendCustomBtn.addEventListener('click', async () => {
  966.            initAudio();
  967.            let customPayload;
  968.            try { customPayload = JSON.parse(els.payloadCode.value); }
  969.            catch(e) { return alert("Invalid JSON format in textarea!"); }
  970.  
  971.            injectBase64(customPayload, fullPayloadMemory);
  972.            const endpoint = els.payloadEndpoint.value.trim();
  973.            const isImage = customPayload.model === "grok-imagine-image";
  974.  
  975.            stealthIdentityReset();
  976.  
  977.            els.sendCustomBtn.disabled = true;
  978.            els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`;
  979.            isRequestCancelled = false;
  980.  
  981.            const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  982.  
  983.            els.sendCustomBtn.disabled = false;
  984.            els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`;
  985.            if (ok) notifyUser(false); else notifyUser(true);
  986.        });
  987.  
  988.        // ─── CSP-SAFE DELEGATED LIGHTBOX LOGIC ────────────────────────────────────
  989.        els.app.addEventListener('click', (e) => {
  990.            if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  991.                els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg';
  992.                els.lightbox.style.display = 'flex';
  993.            }
  994.        });
  995.        els.lightbox.addEventListener('click', (e) => {
  996.            if (e.target.closest('#xai-lightbox-dl')) return;
  997.            if (e.target.closest('.modal-box')) return;
  998.            els.lightbox.style.display = 'none';
  999.        });
  1000.        document.addEventListener('keydown', (e) => { if(e.key === 'Escape') { Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); } });
  1001.  
  1002.        // ─── FIXED FLOATING AR DROPDOWN LOGIC ─────────────────────────────────────
  1003.        function renderArOptions() {
  1004.            els.arOptionsCont.innerHTML = '';
  1005.            arData.forEach(ar => {
  1006.                const opt = document.createElement('div'); opt.className = 'ar-option';
  1007.                opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto)} <span>${ar.label}</span>`;
  1008.                opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1009.                els.arOptionsCont.appendChild(opt);
  1010.            });
  1011.        }
  1012.        function setAr(arObj) {
  1013.            currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1014.            els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto); els.arSelectedText.innerText = arObj.label;
  1015.        }
  1016.        renderArOptions();
  1017.        const initialAr = arData.find(a => a.label === currentAr) || arData[0]; setAr(initialAr);
  1018.  
  1019.        els.arSelectBox.addEventListener('click', (e) => {
  1020.            e.stopPropagation();
  1021.            if (els.arOptionsCont.style.display === 'block') { els.arOptionsCont.style.display = 'none'; return; }
  1022.            const rect = els.arSelectBox.getBoundingClientRect();
  1023.            els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px';
  1024.            els.arOptionsCont.style.display = 'block';
  1025.        });
  1026.        document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1027.  
  1028.        // ─── UNLIMITED MULTI-IMAGE DRAG/DROP WITH VIDEO THUMBNAILS ────────────────
  1029.        async function processFile(file) {
  1030.            const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1031.            if (!isVid && !isImg) return;
  1032.  
  1033.            if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1034.            else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1035.  
  1036.            const max = getMaxMedia();
  1037.            const activeCount = referenceMedia.filter(m => m.active).length;
  1038.  
  1039.            let thumbBase64 = null;
  1040.            if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1041.  
  1042.            const reader = new FileReader();
  1043.            reader.onload = (event) => {
  1044.                referenceMedia.push({
  1045.                    id: Date.now() + Math.random(),
  1046.                    base64: event.target.result,
  1047.                    isVideo: isVid,
  1048.                    active: activeCount < max,
  1049.                    thumb: thumbBase64,
  1050.                    fileName: file.name
  1051.                });
  1052.                renderRefList();
  1053.                if (isImg) setAr(arData[0]);
  1054.            };
  1055.            reader.readAsDataURL(file);
  1056.        }
  1057.  
  1058.        let draggedIndex = null;
  1059.        function renderRefList() {
  1060.            els.refList.innerHTML = '';
  1061.            referenceMedia.forEach((media, index) => {
  1062.                const item = document.createElement('div');
  1063.                item.className = 'ref-item';
  1064.                item.draggable = true;
  1065.  
  1066.                let thumbHtml = '';
  1067.                if (media.isVideo) {
  1068.                    if (media.thumb) {
  1069.                        thumbHtml = `
  1070.                            <div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;">
  1071.                                <img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}">
  1072.                                <div style="position: absolute; top: 4px; right: 4px; background: rgba(0,0,0,0.7); color: white; border-radius: 4px; padding: 2px 4px; font-size: 10px;">🎥</div>
  1073.                            </div>
  1074.                        `;
  1075.                    } else {
  1076.                        thumbHtml = `<div class="ref-thumb" style="display:flex; align-items:center; justify-content:center; flex-direction:column; background:#1e293b; color:#94a3b8; font-size:24px;" title="${media.fileName || 'Video'}">🎥<span style="font-size:9px; margin-top:4px; max-width:80px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${media.fileName || 'Video'}</span></div>`;
  1077.                    }
  1078.                } else {
  1079.                    thumbHtml = `<img src="${media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1080.                }
  1081.  
  1082.                item.innerHTML = `
  1083.                    <div class="ref-handle">☰</div>
  1084.                    ${thumbHtml}
  1085.                    <div class="ref-info">
  1086.                        <span style="font-size: 12px; color: #e2e8f0; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${media.fileName || ''}">
  1087.                            Ref ${index + 1} <span style="font-size:10px; color:#64748b; font-weight:normal;">${media.fileName ? '- ' + media.fileName : ''}</span>
  1088.                        </span>
  1089.                        <label class="ref-toggle-label">
  1090.                            <input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload
  1091.                        </label>
  1092.                        <button class="ref-del">Remove</button>
  1093.                    </div>
  1094.                `;
  1095.  
  1096.                if (!media.active) item.classList.add('inactive');
  1097.  
  1098.                item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1099.                    const max = getMaxMedia();
  1100.                    const currentlyActive = referenceMedia.filter(r => r.active).length;
  1101.  
  1102.                    if (e.target.checked && currentlyActive >= max) {
  1103.                        alert(`You can only have up to ${max} active references for this mode.`);
  1104.                        e.target.checked = false;
  1105.                        return;
  1106.                    }
  1107.                    media.active = e.target.checked;
  1108.                    if (media.active) item.classList.remove('inactive'); else item.classList.add('inactive');
  1109.                    saveRefs();
  1110.                });
  1111.  
  1112.                item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1113.                item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1114.                item.addEventListener('dragover', (e) => {
  1115.                    e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return;
  1116.                    const rect = item.getBoundingClientRect();
  1117.                    if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); }
  1118.                    else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); }
  1119.                });
  1120.                item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1121.                item.addEventListener('drop', (e) => {
  1122.                    e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom');
  1123.                    if (draggedIndex === null || draggedIndex === index) return;
  1124.                    const rect = item.getBoundingClientRect();
  1125.                    let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1;
  1126.                    if (draggedIndex < insertIndex) insertIndex--;
  1127.                    const [movedImage] = referenceMedia.splice(draggedIndex, 1);
  1128.                    referenceMedia.splice(insertIndex, 0, movedImage); renderRefList();
  1129.                });
  1130.  
  1131.                item.querySelector('.ref-del').addEventListener('click', () => { referenceMedia.splice(index, 1); renderRefList(); });
  1132.                els.refList.appendChild(item);
  1133.            });
  1134.            saveRefs();
  1135.        }
  1136.  
  1137.        els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1138.        els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1139.        document.addEventListener('paste', (e) => {
  1140.            if (e.target && (e.target.id === 'payload-code' || e.target.id === 'xai-api-prompt' || e.target.id === 'set-custom-css' || e.target.tagName === 'INPUT')) return;
  1141.            const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile());
  1142.        });
  1143.  
  1144.        els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1145.        els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1146.        els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1147.  
  1148.        // ─── CANCEL BUTTON LOGIC ─────────────────────────────────────────────────
  1149.        els.cancelBtn.addEventListener('click', () => {
  1150.            isRequestCancelled = true;
  1151.            if (currentAbortController) currentAbortController.abort();
  1152.            els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex';
  1153.            els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1154.            els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1155.        });
  1156.  
  1157.        // ─── MASTER GENERATION LOGIC ──────────────────────────────────────────────
  1158.        async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1159.            let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : '';
  1160.            statusEl.innerText = `${loopPrefix}Processing request...`;
  1161.            statusEl.className = "status-pulsing";
  1162.  
  1163.            currentAbortController = new AbortController();
  1164.  
  1165.            let attempts = 0; let success = false;
  1166.            while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1167.                try {
  1168.                    statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1169.  
  1170.                    const fullEndpoint = getApiUrl(endpoint);
  1171.                    const response = await fetch(fullEndpoint, {
  1172.                        method: 'POST',
  1173.                        headers: { 'Content-Type': 'application/json' },
  1174.                        body: JSON.stringify(payload),
  1175.                        signal: currentAbortController.signal
  1176.                    });
  1177.  
  1178.                    if (response.status === 429 || response.status === 503 || response.status === 500 || response.status === 502) {
  1179.                        attempts++;
  1180.                        statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`;
  1181.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1182.                        await sleep(delay);
  1183.                        continue;
  1184.                    }
  1185.  
  1186.                    if (!response.ok) {
  1187.                        let errMsg = `HTTP ${response.status}`;
  1188.                        try {
  1189.                            const errData = await response.json();
  1190.                            if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`;
  1191.                            else if (errData.detail) errMsg += `\n${JSON.stringify(errData.detail)}`;
  1192.                        } catch(e) {}
  1193.                        throw new Error(errMsg);
  1194.                    }
  1195.  
  1196.                    const data = await response.json();
  1197.  
  1198.                    if (isImageAction) {
  1199.                        if (data && data.data && Array.isArray(data.data)) {
  1200.                            success = true;
  1201.                            statusEl.innerText = `${loopPrefix}Processing final images...`;
  1202.                            statusEl.style.color = "#10b981";
  1203.                            statusEl.className = "";
  1204.  
  1205.                            await Promise.all(data.data.map((imgObj, index) =>
  1206.                                processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)
  1207.                            ));
  1208.  
  1209.                            statusEl.innerText = "Ready";
  1210.                            statusEl.style.color = "#64748b";
  1211.                        } else throw new Error("Invalid response format.");
  1212.                    } else {
  1213.                        const reqId = data.request_id;
  1214.                        if (!reqId) throw new Error("No Request ID returned.");
  1215.  
  1216.                        let videoReady = false;
  1217.                        let pollCount = 0;
  1218.                        const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1219.  
  1220.                        while (!videoReady && !isRequestCancelled) {
  1221.                            pollCount++;
  1222.                            if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue.");
  1223.                            await sleep(5000);
  1224.                            if (isRequestCancelled) break;
  1225.  
  1226.                            const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1227.                            if (!pollRes.ok) continue;
  1228.  
  1229.                            const pollData = await pollRes.json();
  1230.                            if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1231.  
  1232.                            const state = (pollData.status || pollData.state || 'processing').toLowerCase();
  1233.                            statusEl.innerText = `${loopPrefix}Polling video (Status: ${state})...[${pollCount}/${MAX_POLLS}]`;
  1234.  
  1235.                            if (state === 'done' || state === 'completed') {
  1236.                                videoReady = true;
  1237.                                success = true;
  1238.                                statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8";
  1239.                                renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1240.                            } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1241.                                if (pollData.video && pollData.video.url) {
  1242.                                    videoReady = true;
  1243.                                    success = true;
  1244.                                    statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`;
  1245.                                    statusEl.className = ""; statusEl.style.color = "#d97706";
  1246.                                    renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1247.                                } else {
  1248.                                    throw new Error(`Generation halted. Reason: ${state}`);
  1249.                                }
  1250.                            }
  1251.                        }
  1252.                    }
  1253.  
  1254.                } catch (err) {
  1255.                    if (err.name === 'AbortError' || isRequestCancelled) {
  1256.                        statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1257.                        return false;
  1258.                    } else if ((err.message.includes("Timeout: Video") || err.message.includes("Generation halted.")) && appSettings.autoRetryStuckVideo) {
  1259.                        attempts++;
  1260.                        if (attempts >= appSettings.retries) {
  1261.                            statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`;
  1262.                            statusEl.className = ""; statusEl.style.color = "#ef4444";
  1263.                            break;
  1264.                        }
  1265.                        statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`;
  1266.                        const delay = Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin;
  1267.                        await sleep(delay);
  1268.  
  1269.                        // Anti-caching injection: add a zero-width space to the prompt to force the server to evaluate a fresh generation.
  1270.                        if (payload.prompt) payload.prompt += "\u200B";
  1271.  
  1272.                        continue;
  1273.                    } else {
  1274.                        statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1275.                        break;
  1276.                    }
  1277.                }
  1278.            }
  1279.  
  1280.            if (!success && !isRequestCancelled) {
  1281.                if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:")) {
  1282.                    statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
  1283.                }
  1284.                statusEl.className = ""; statusEl.style.color = "#ef4444";
  1285.                return false;
  1286.            }
  1287.  
  1288.            return success;
  1289.        }
  1290.  
  1291.        els.btn.addEventListener('click', async () => {
  1292.            initAudio();
  1293.            const basePrompt = els.prompt.value.trim();
  1294.            if (!basePrompt) return alert("Please enter a prompt.");
  1295.  
  1296.            const oldImages = Array.from(els.currentImages.children);
  1297.            if (oldImages.length > 0) {
  1298.                if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1299.                oldImages.forEach(card => {
  1300.                    card.className = 'history-card';
  1301.                    const promptEl = card.querySelector('p');
  1302.                    promptEl.title = "Click to copy prompt";
  1303.                    promptEl.onclick = () => { els.prompt.value = promptEl.innerText; localStorage.setItem('xai_api_prompt', els.prompt.value); };
  1304.                    els.history.prepend(card);
  1305.                });
  1306.            }
  1307.  
  1308.            const action = els.action.value;
  1309.            const activeRefs = referenceMedia.filter(m => m.active);
  1310.            let endpoint = '/v1/images/generations';
  1311.            if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1312.            else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1313.            else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1314.            else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1315.  
  1316.            const isImage = action === 'gen_image';
  1317.            const totalLoops = parseInt(els.loops.value) || 1;
  1318.  
  1319.            stealthIdentityReset();
  1320.  
  1321.            els.btn.disabled = true;
  1322.            els.cancelBtn.style.display = 'flex';
  1323.            els.previewBtn.style.display = 'none';
  1324.            isRequestCancelled = false;
  1325.  
  1326.            let allSuccess = true;
  1327.            for (let i = 1; i <= totalLoops; i++) {
  1328.                if (isRequestCancelled) break;
  1329.  
  1330.                const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1331.                const payload = buildPayloadData(dynamicPrompt);
  1332.  
  1333.                els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1334.  
  1335.                const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1336.                if (!ok) {
  1337.                    allSuccess = false;
  1338.                    break;
  1339.                }
  1340.            }
  1341.  
  1342.            if (!isRequestCancelled) {
  1343.                els.cancelBtn.style.display = 'none';
  1344.                els.previewBtn.style.display = 'flex';
  1345.                els.btn.disabled = false;
  1346.                els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1347.  
  1348.                if (allSuccess) {
  1349.                    els.status.innerText = "All runs complete.";
  1350.                    els.status.className = "";
  1351.                    els.status.style.color = "#64748b";
  1352.                    notifyUser(false);
  1353.                } else {
  1354.                    notifyUser(true);
  1355.                }
  1356.            }
  1357.        });
  1358.  
  1359.        // ─── SESSION RESETTER ─────────────────────────────────────────────────────
  1360.        els.reset.addEventListener('click', () => {
  1361.            if (!confirm("Wipe cache? (This forces a page reload to clear front-end tokens). Your prompt and settings will be saved.")) return;
  1362.            localStorage.setItem('xai_api_prompt', els.prompt.value);
  1363.            const patterns =[/flushAfter/i, /imagine/i, /generation/i, /grok/i, /mixpanel|mp_/i, /distinct_id/i, /_rst/i, /limit/i, /credit/i];
  1364.            for (let i = localStorage.length - 1; i >= 0; i--) {
  1365.                const k = localStorage.key(i);
  1366.                if (k && !k.startsWith('xai_api_') && patterns.some(p => p.test(k))) localStorage.removeItem(k);
  1367.            }
  1368.            document.cookie.split(';').forEach(c => {
  1369.                const name = c.split('=')[0]?.trim();
  1370.                if (!name || !patterns.some(p => name.toLowerCase().includes(p.toLowerCase()))) return;['.x.ai', 'console.x.ai', ''].forEach(d => {['/', '/playground/imagine', ''].forEach(p => { document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${p}${d ? ';domain=' + d : ''}`; });
  1371.                });
  1372.            });
  1373.            const u = new URL(location.href);
  1374.            ['_r', '_rst'].forEach(k => u.searchParams.set(k, Date.now()));
  1375.            location.replace(u.toString());
  1376.        });
  1377.    }
  1378.  
  1379.    // ─── ASYNC PROCESSORS & RENDERERS ─────────────────────────────────────────
  1380.    async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1381.        if (!imgObj.b64_json) return;
  1382.        const mime = imgObj.mime_type || "image/png";
  1383.        const b64 = imgObj.b64_json;
  1384.        const pngDataUri = `data:${mime};base64,${b64}`;
  1385.  
  1386.        const finalPrompt = imgObj.revised_prompt || originalPrompt;
  1387.        let finalDataUri = pngDataUri;
  1388.        let filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.png`;
  1389.  
  1390.        if (!appSettings.saveAsPng) {
  1391.            finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt);
  1392.            filename = `Grok 2K - ${makeTimestamp()} - ${num}of${total}.jpg`;
  1393.        }
  1394.  
  1395.        const card = document.createElement('div');
  1396.        card.className = 'current-card';
  1397.        card.innerHTML = `
  1398.            <div class="img-wrapper">
  1399.                <img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen">
  1400.                <a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a>
  1401.                <button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button>
  1402.            </div>
  1403.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>
  1404.        `;
  1405.  
  1406.        const editBtn = card.querySelector('.overlay-edit-btn');
  1407.        editBtn.addEventListener('click', (e) => {
  1408.            e.preventDefault();
  1409.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename);
  1410.        });
  1411.  
  1412.        galleryEl.prepend(card);
  1413.    }
  1414.  
  1415.    function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1416.        const filename = `Grok Video - ${makeTimestamp()}.mp4`;
  1417.        const card = document.createElement('div');
  1418.        card.className = 'current-card';
  1419.        card.innerHTML = `
  1420.            <div class="img-wrapper">
  1421.                <video src="${videoUrl}" controls autoplay loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video>
  1422.                <a href="${videoUrl}" target="_blank" download="${filename}" class="overlay-btn overlay-dl-btn" style="z-index: 50;" title="Download MP4">${DOWNLOAD_ICON}</a>
  1423.                <button class="overlay-btn overlay-edit-btn" style="z-index: 50;" title="Edit this Video">${EDIT_ICON}</button>
  1424.            </div>
  1425.            <p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>
  1426.        `;
  1427.  
  1428.        const editBtn = card.querySelector('.overlay-edit-btn');
  1429.        editBtn.addEventListener('click', (e) => {
  1430.            e.preventDefault();
  1431.            if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename);
  1432.        });
  1433.  
  1434.        galleryEl.prepend(card);
  1435.    }
  1436.  
  1437.    if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); }
  1438.    else { initApp(); }
  1439.  
  1440. })();
Add Comment
Please, Sign In to add comment