Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name xAI Pro Studio Frontend by Grok (v40 - Quality Mode)
- // @namespace http://tampermonkey.net/
- // @version 40
- // @description Full-Screen UI by Grok | Quality Mode (Speed/Quality toggle) | EXIF Fix | Multi-Image | Auto-Retry | Export Settings | Video Warnings | Adaptive AR | Auto-Download | Extend Support | Anti-Throttling | Auto-Resume
- // @match https://console.x.ai/playground/image*
- // @match https://console.x.ai/team/*/image*
- // @match https://console.x.ai/playground/imagine*
- // @match https://console.x.ai/team/*/imagine*
- // @grant GM_xmlhttpRequest
- // @grant GM_cookie
- // @grant GM_download
- // @connect console.x.ai
- // @connect vidgen.x.ai
- // @connect *.x.ai
- // @run-at document-start
- // ==/UserScript==
- (function() {
- 'use strict';
- // ─── LOGGING & DEBUG ENGINE ───────────────────────────────────────────────
- const appLogs = [];
- const MAX_LOGS = 500;
- function stripHeavyData(val) {
- if (val === null || val === undefined) return val;
- if (typeof val === 'string') {
- if (val.startsWith('data:image') || val.startsWith('data:video') || val.length > 2000) {
- return `[TRUNCATED_DATA_LEN_${val.length}]`;
- }
- return val;
- }
- if (typeof val !== 'object') return val;
- if (Array.isArray(val)) return val.map(stripHeavyData);
- const copy = {};
- for (const k in val) {
- if (Object.prototype.hasOwnProperty.call(val, k)) {
- copy[k] = stripHeavyData(val[k]);
- }
- }
- return copy;
- }
- function addLog(level, msg, data = null) {
- try {
- const ts = new Date().toISOString().replace('T', ' ').substring(0, 23);
- const safeData = data ? stripHeavyData(data) : null;
- appLogs.push({ ts, level, msg, data: safeData });
- if (appLogs.length > MAX_LOGS) appLogs.shift();
- const consoleMsg = `[xAI Studio] [${level}] ${msg}`;
- if (level === 'ERROR') console.error(consoleMsg, safeData || '');
- else if (level === 'WARN') console.warn(consoleMsg, safeData || '');
- else console.log(consoleMsg, safeData || '');
- } catch(e) {}
- }
- function formatLogsForExport() {
- return appLogs.map(l => {
- let text = `[${l.ts}] [${l.level}] ${l.msg}`;
- if (l.data) {
- try { text += `\n${JSON.stringify(l.data, null, 2)}`; }
- catch(e) { text += `\n[Unserializable Data]`; }
- }
- return text;
- }).join('\n\n----------------------------------------\n\n');
- }
- addLog('INFO', 'Script started executing');
- // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
- const sleep = (ms) => new Promise(r => setTimeout(r, ms));
- function pad2(n) { return String(n).padStart(2, '0'); }
- function makeTimestamp() {
- const d = new Date();
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
- }
- function base64ToBlobUrl(b64) {
- if (!b64 || !b64.startsWith('data:')) return b64;
- try {
- const parts = b64.split(',');
- const mime = parts[0].match(/:(.*?);/)[1];
- const bstr = atob(parts[1]);
- let n = bstr.length;
- const u8arr = new Uint8Array(n);
- while (n--) u8arr[n] = bstr.charCodeAt(n);
- return URL.createObjectURL(new Blob([u8arr], { type: mime }));
- } catch(e) { return b64; }
- }
- 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>`;
- 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>`;
- const EXTEND_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="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>`;
- // ─── SETTINGS SCHEMA & MANAGER ───────────────────────────────────────────
- const SETTINGS_SCHEMA = {
- retries: { id: 'set-retries', type: 'number', default: 20 },
- delayMin: { id: 'set-delay-min', type: 'number', default: 2000 },
- delayMax: { id: 'set-delay-max', type: 'number', default: 4000 },
- rateLimitDelay: { id: 'set-rate-limit-delay', type: 'number', default: 20 },
- notifications: { id: 'set-notifications', type: 'checkbox', default: true },
- customCSS: { id: 'set-custom-css', type: 'text', default: "" },
- saveAsPng: { id: 'set-save-png', type: 'checkbox', default: false },
- apiBaseUrl: { id: 'set-api-base-url', type: 'text', default: "" },
- videoPollTimeout: { id: 'set-video-timeout', type: 'number', default: 300 },
- autoRetryStuckVideo: { id: 'set-auto-retry-video', type: 'checkbox', default: false },
- breakLoopOnFailure: { id: 'set-break-loop-on-failure', type:'checkbox', default: true },
- referenceARTrick: { id: 'set-reference-ar-trick', type: 'checkbox', default: true },
- maximumGreedMode: { id: 'set-maximum-greed-mode', type: 'checkbox', default: false },
- suppressEditWarning: { id: 'set-suppress-warning', type: 'checkbox', default: false },
- videoAutoplay: { id: 'set-video-autoplay', type: 'checkbox', default: true },
- videoMuted: { id: 'set-video-muted', type: 'checkbox', default: false },
- uiFontSize: { id: 'set-font-size', type: 'number', default: 13 },
- autoDownload: { id: 'set-auto-download', type: 'checkbox', default: false },
- antiThrottling: { id: 'set-anti-throttling', type: 'checkbox', default: true }
- };
- const SettingsManager = {
- load: function() {
- let stored = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
- let parsed = {};
- for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
- let val = stored[key] !== undefined ? stored[key] : config.default;
- if (config.type === 'number') val = parseInt(val) || config.default;
- parsed[key] = val;
- }
- parsed.delayMax = Math.max(parsed.delayMin, parsed.delayMax); // Enforce logic
- return parsed;
- },
- populateUI: function(currentSettings) {
- for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
- const el = document.getElementById(config.id);
- if (!el) continue;
- if (config.type === 'checkbox') el.checked = currentSettings[key];
- else el.value = currentSettings[key];
- }
- },
- saveFromUI: function() {
- let newSettings = {};
- for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
- const el = document.getElementById(config.id);
- if (!el) { newSettings[key] = config.default; continue; }
- if (config.type === 'checkbox') {
- newSettings[key] = el.checked;
- } else if (config.type === 'number') {
- newSettings[key] = parseInt(el.value) || config.default;
- } else {
- newSettings[key] = el.value.trim();
- }
- }
- newSettings.delayMax = Math.max(newSettings.delayMin, newSettings.delayMax);
- localStorage.setItem('xai_api_settings', JSON.stringify(newSettings));
- return newSettings;
- }
- };
- // Initialize global settings
- let appSettings = SettingsManager.load();
- let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
- function getApiUrl(path) {
- let base = appSettings.apiBaseUrl || '';
- if (base.endsWith('/')) base = base.slice(0, -1);
- if (!path.startsWith('/') && base) path = '/' + path;
- return base + path;
- }
- function parseDynamicPrompt(text) {
- if (!text) return text;
- let parsed = text; let prev;
- do {
- prev = parsed;
- parsed = parsed.replace(/\{([^{}]+)\}/g, (m, c) => { const o = c.split('|'); return o[Math.floor(Math.random() * o.length)]; });
- } while (parsed !== prev);
- parsed = parsed.replace(/@randomseed/gi, () => Math.floor(1000000000 + Math.random() * 9000000000).toString());
- return parsed.trim();
- }
- let sharedAudioCtx = null;
- let awakeOsc = null;
- let titleBlinkInterval = null;
- const originalTitle = document.title || "xAI Pro Studio";
- function initAudio() {
- if (!sharedAudioCtx) {
- try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
- }
- if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
- }
- function toggleKeepAwake(enable) {
- if (enable && !appSettings.antiThrottling) return;
- if (enable) {
- initAudio();
- if (sharedAudioCtx) {
- if (!awakeOsc) {
- try {
- awakeOsc = sharedAudioCtx.createOscillator();
- //Сделай звук активности вкладки типа 21 кГц -90 дБ.
- awakeOsc.frequency.value = 21000;
- awakeOsc.type = 'sine';
- const gain = sharedAudioCtx.createGain();
- //gain.gain.value = 0.001;
- gain.gain.value = 0.000031622776601683795; //Math.pow(10, -90/20);
- awakeOsc.connect(gain);
- gain.connect(sharedAudioCtx.destination);
- awakeOsc.start();
- } catch(e) {}
- }
- }
- } else {
- if (awakeOsc) {
- try { awakeOsc.stop(); awakeOsc.disconnect(); } catch(e) {}
- awakeOsc = null;
- }
- }
- }
- function notifyUser(isError = false) {
- if (!appSettings.notifications) return;
- initAudio();
- if (sharedAudioCtx) {
- try {
- const osc = sharedAudioCtx.createOscillator(); const gain = sharedAudioCtx.createGain();
- osc.connect(gain); gain.connect(sharedAudioCtx.destination);
- if (isError) {
- osc.type = 'sawtooth'; osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
- } else {
- osc.type = 'sine'; osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
- }
- gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
- osc.start(sharedAudioCtx.currentTime); osc.stop(sharedAudioCtx.currentTime + 0.5);
- } catch(e) {}
- }
- if (!document.hasFocus()) {
- if (titleBlinkInterval) clearInterval(titleBlinkInterval);
- let toggle = true;
- titleBlinkInterval = setInterval(() => { document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle; toggle = !toggle; }, 1000);
- const clearBlink = () => { clearInterval(titleBlinkInterval); document.title = originalTitle; window.removeEventListener('focus', clearBlink); };
- window.addEventListener('focus', clearBlink);
- }
- }
- // ─── NUCLEAR SESSION WIPE ENGINE ──────────────────────────────────────────
- async function nuclearSessionReset(remainingLoops = 0) {
- addLog('INFO', `Nuclear Reset triggered.`);
- // 1. Wipe EVERY single cookie (xAI, Cloudflare, Stripe, HttpOnly) for local domain
- if (typeof GM_cookie !== 'undefined') {
- await new Promise(resolve => {
- GM_cookie.list({ url: window.location.href }, (cookies, error) => {
- if (!error && cookies && cookies.length > 0) {
- let deletedCount = 0;
- cookies.forEach(c => {
- GM_cookie.delete({ url: window.location.href, name: c.name }, () => {
- deletedCount++;
- if (deletedCount === cookies.length) resolve();
- });
- });
- } else resolve();
- });
- });
- // Also wipe root domain .x.ai just in case
- await new Promise(resolve => {
- GM_cookie.list({ url: 'https://x.ai' }, (cookies, error) => {
- if (!error && cookies && cookies.length > 0) {
- let deletedCount = 0;
- cookies.forEach(c => {
- GM_cookie.delete({ url: 'https://x.ai', name: c.name }, () => {
- deletedCount++;
- if (deletedCount === cookies.length) resolve();
- });
- });
- } else resolve();
- });
- });
- }
- // 2. Clear Local and Session Storage (leaving our script's custom UI settings intact)
- for (let i = localStorage.length - 1; i >= 0; i--) {
- const k = localStorage.key(i);
- if (k && !k.startsWith('xai_api_')) localStorage.removeItem(k);
- }
- sessionStorage.clear();
- if ( appSettings.maximumGreedMode && remainingLoops > 0) {
- sessionStorage.setItem('xai_resume_loops', remainingLoops.toString());
- } else {
- // Requesting new cookies.
- await fetch('https://console.x.ai/playground/imagine');
- }
- }
- let piexifPromise = null;
- function loadPiexif() {
- if (piexifPromise) return piexifPromise;
- piexifPromise = new Promise((resolve, reject) => {
- const getPiexif = () => window.piexif || (typeof unsafeWindow !== 'undefined' ? unsafeWindow.piexif : null);
- let px = getPiexif();
- if (px) { resolve(px); return; }
- const script = document.createElement('script');
- script.src = 'https://cdnjs.cloudflare.com/ajax/libs/piexifjs/1.0.6/piexif.min.js';
- script.onload = () => {
- px = getPiexif();
- if (px) {
- resolve(px);
- } else {
- piexifPromise = null;
- reject(new Error("piexifjs loaded, but 'piexif' object not found in window context."));
- }
- };
- script.onerror = () => {
- piexifPromise = null;
- reject(new Error('Failed to load piexifjs script from CDN.'));
- };
- document.head.appendChild(script);
- });
- return piexifPromise;
- }
- function toUTF16LE(str) {
- const arr =[];
- for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF); }
- arr.push(0, 0); return arr;
- }
- function convertToJpegWithExif(base64PngUri, prompt) {
- console.log(prompt);
- return new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = async () => {
- const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height;
- const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0);
- let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
- if (prompt) {
- try {
- const piexif = await loadPiexif();
- const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
- exifObj['0th'][piexif.ImageIFD.ImageDescription] = unescape(encodeURIComponent(prompt));
- jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
- } catch (e) { addLog('ERROR', 'EXIF Injection Failed', e); }
- }
- resolve(jpegUri);
- };
- img.onerror = reject; img.src = base64PngUri;
- });
- }
- async function extractPromptFromImage(file) {
- if (!file || !file.type.includes('image')) return null;
- try {
- const piexif = await loadPiexif();
- return new Promise((resolve) => {
- const reader = new FileReader();
- reader.onload = (e) => {
- try {
- const exifData = piexif.load(e.target.result);
- let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
- if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
- if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(err) {} }
- if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
- const xpTitleArr = exifData['0th'][40091]; let str = '';
- for (let i = 0; i < xpTitleArr.length; i += 2) {
- const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
- if (charCode === 0) break;
- str += String.fromCharCode(charCode);
- }
- prompt = str;
- }
- resolve(prompt ? prompt.trim() : null);
- } catch (err) { resolve(null); }
- };
- reader.onerror = () => resolve(null);
- reader.readAsDataURL(file);
- });
- } catch (e) { return null; }
- }
- function generateVideoThumbnail(file) {
- return new Promise((resolve) => {
- const video = document.createElement('video'); video.preload = 'metadata'; video.muted = true; video.playsInline = true;
- const url = URL.createObjectURL(file); video.src = url; let isSeeked = false;
- video.onloadeddata = () => { video.currentTime = Math.min(0.5, video.duration / 2 || 0); file._w = video.videoWidth; file._h = video.videoHeight; };
- video.onseeked = () => {
- if (isSeeked) return; isSeeked = true;
- try {
- const canvas = document.createElement('canvas'); canvas.width = video.videoWidth || 140; canvas.height = video.videoHeight || 140;
- const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); resolve(canvas.toDataURL('image/jpeg', 0.8));
- } catch(e) { URL.revokeObjectURL(url); resolve(null); }
- };
- video.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
- setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
- });
- }
- function updateFontSize(size) {
- let el = document.getElementById('xai-custom-font-size');
- if (!el) { el = document.createElement('style'); el.id = 'xai-custom-font-size'; document.head.appendChild(el); }
- if (size === 13) { el.innerHTML = ''; return; }
- el.innerHTML = `
- #xai-pro-app textarea, #xai-pro-app #prompt-backdrop, #xai-pro-app select, #xai-pro-app input[type="text"], #xai-pro-app input[type="number"], #xai-pro-app .btn-primary, #xai-pro-app .btn-secondary, #xai-pro-app .ar-select-box, #xai-pro-app .action-select { font-size: ${size}px !important; }
- #xai-pro-app .ar-option, #xai-pro-app .fav-text, #xai-pro-app #xai-api-status { font-size: ${size - 1}px !important; }
- #xai-pro-app .panel-title, #xai-pro-app label, #xai-pro-app .toggle-btn, #xai-pro-app .slider-header, #xai-pro-app .history-card p, #xai-pro-app .warning-box, #xai-pro-app .ref-info span { font-size: ${size - 2}px !important; }
- #xai-pro-app .slider-ticks, #xai-pro-app .slider-ticks span, #xai-pro-app .ref-action-btn, #xai-pro-app .ref-toggle-label, #xai-pro-app .ref-thumb span, #xai-pro-app button[style*="font-size: 10px"] { font-size: ${size - 3}px !important; }
- #xai-pro-app .ref-handle { font-size: ${size + 1}px !important; }
- #xai-pro-app h3 { font-size: ${size + 2}px !important; }
- `;
- }
- // ─── DATA MAPS FOR UI SLIDERS ─────────────────────────────────────────────
- const MAPS = {
- batch: [1, 2, 3, 4, 5, 8, 10],
- durGen: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
- durExt: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- };
- const arData =[
- { label: 'Auto', w: 1, h: 1, isAuto: true },
- { label: 'By First Ref', w: 1, h: 1, isAuto: true, isRef: true },
- { label: '1:1', w: 1, h: 1 }, { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
- { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
- { 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 },
- { 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 }
- ];
- function createArIcon(w, h, isAuto, isRef) {
- if (isRef) return `<div style="width: 12px; height: 12px; border: 1px dashed #10b981; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 8px; color: #10b981; font-weight:bold;">R</div>`;
- 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>`;
- const scale = 12 / Math.max(w, h);
- 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>`;
- }
- // ─── UI INJECTION ─────────────────────────────────────────────────────────
- const UI_CSS = `
- ::-webkit-scrollbar { width: 6px; }
- ::-webkit-scrollbar-track { background: #0f172a; }
- ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
- @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
- .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; }
- .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
- .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
- #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; }
- #xai-pro-app * { box-sizing: border-box; }
- .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; }
- .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
- .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
- .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
- .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
- .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
- 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; }
- textarea, select, input[type="text"], input[type="number"] { width: 100%; }
- 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); }
- label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
- .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; }
- .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
- .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
- .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; }
- .btn-secondary:hover:not(:disabled) { background: #334155; border-color: #64748b; }
- .action-select { width: 100%; font-weight: 600; font-size: 13px; color: #f8fafc; background: transparent; border: none; outline: none; overflow-y: hidden; }
- .action-select option { padding: 8px 10px; margin-bottom: 4px; border-radius: 6px; cursor: pointer; transition: 0.1s; background: #0f172a; border: 1px solid #334155; }
- .action-select option:checked { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); border-color: #4f46e5; color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
- .action-select option:hover:not(:checked) { background: #334155; }
- .slider-block { display: flex; flex-direction: column; margin-bottom: 12px; }
- .toggle-btn { background: #0f172a; border: 1px solid #334155; color: #94a3b8; padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }
- .toggle-btn.active { background: linear-gradient(180deg, #10b981 0%, #059669 100%); color: #fff; border-color: #047857; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
- .slider-header { display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 6px; font-weight: 600; color: #94a3b8; }
- .slider-header span { color: #f8fafc; }
- .slider-ticks { position: relative; height: 14px; width: 100%; font-size: 10px; color: #64748b; margin-top: 4px; padding: 0; }
- .slider-ticks span { position: absolute; transform: translateX(-50%); text-align: center; white-space: nowrap; line-height: 1; }
- input[type=range] { -webkit-appearance: none; width: 100%; background: transparent; margin: 4px 0; outline: none; transform: scaleY(1.6); }
- input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
- input[type=range]::-moz-range-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
- input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; margin-top: -5px; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
- input[type=range]::-moz-range-thumb { height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; border: none; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
- input[type=range]:focus::-webkit-slider-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
- input[type=range]:focus::-moz-range-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
- .ar-select-box { background: #1e293b; border: 1px solid #475569; border-radius: 6px; padding: 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; color: #f8fafc; font-size: 13px; }
- #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: 265px; overflow-y: auto; display: none; z-index: 99999999; grid-template-columns: 1fr 1fr; }
- .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
- .ar-option:hover { background: #334155; color: #f8fafc; }
- .img-wrapper { position: relative; display: block; }
- .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
- .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; }
- .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
- .overlay-dl-btn { right: 6px; }
- .overlay-edit-btn { right: 40px; color: #10b981; }
- .overlay-extend-btn { right: 74px; color: #3b82f6; }
- .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; }
- .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
- .ref-item:active { cursor: grabbing; }
- .ref-item.dragging { opacity: 0.4; }
- .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
- .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
- .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
- .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
- .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
- .ref-btn-group { display: flex; gap: 4px; width: 100%; margin-top: auto; }
- .ref-action-btn { flex: 1; border-radius: 4px; padding: 4px 0; cursor: pointer; font-size: 10px; transition: 0.2s; font-weight: bold; text-align: center; }
- .ref-insert { background: #0f766e; color: #ccfbf1; border: 1px solid #115e59; }
- .ref-insert:hover { background: #115e59; color: #f0fdfa; }
- .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
- .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
- .drag-over-top { border-top: 2px solid #22c55e !important; }
- .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
- .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
- .history-card .overlay-btn { width: 24px; height: 24px; top: 4px; border-radius: 4px; }
- .history-card .overlay-dl-btn { right: 4px; }
- .history-card .overlay-edit-btn { right: 32px; }
- .history-card .overlay-extend-btn { right: 60px; }
- .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
- .history-card p:hover { background: #1e293b; color: #e2e8f0; }
- .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; transition: all 0.3s ease; }
- .current-card.downloaded { border-color: #10b981 !important; box-shadow: 0 0 10px rgba(16,185,129,0.3) !important; }
- .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
- .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); }
- .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; overflow-y: auto; }
- .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
- .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; }
- .fav-text:hover { color: #10b981; }
- #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
- #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
- #logs-btn { position: fixed; top: 10px; right: 45px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
- #logs-btn:hover { transform: scale(1.15); opacity: 1; }
- #xai-lightbox { cursor: zoom-out; }
- #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
- #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); }
- .prompt-container { position: relative; width: 100%; height: 100px; min-height: 70px; margin-bottom: 10px; resize: vertical; overflow: hidden; border: 1px solid #334155; border-radius: 6px; background: #0f172a; transition: 0.2s; box-sizing: border-box; font-family: 'Inter', -apple-system, sans-serif; }
- .prompt-container:focus-within { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
- .prompt-container.prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
- #prompt-backdrop { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding: 8px; font-size: 13px; font-family: inherit; white-space: pre-wrap; word-wrap: break-word; overflow-y: auto; color: transparent; z-index: 1; opacity: 0; box-sizing: border-box; pointer-events: none; }
- .prompt-tag { pointer-events: auto; }
- #xai-api-prompt { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; resize: none; background: transparent; border: none; box-shadow: none; outline: none; padding: 8px; font-size: 13px; font-family: inherit; color: #f8fafc; box-sizing: border-box; margin: 0; }
- #xai-api-prompt:focus { background: transparent; border: none; box-shadow: none; }
- .warning-box { border-radius: 6px; padding: 6px 10px; font-size: 11px; margin-bottom: 8px; font-weight: 500; display: block; }
- .warning-red { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
- .warning-yellow { background: #422006; color: #fcd34d; border: 1px solid #78350f; }
- `;
- const UI_HTML = `
- <div id="xai-pro-app">
- <div id="settings-btn" title="Studio Settings">⚙️</div>
- <div id="logs-btn" title="Debug Logs">🐛</div>
- <!-- LEFT COLUMN -->
- <div class="col-left">
- <div class="panel" style="flex-shrink: 0;">
- <div style="display: flex; background: transparent; border-radius: 0 0 6px 6px; margin-bottom: 6px; padding: 10px; padding-bottom: 0;">
- <select id="master-action" size="4" class="action-select">
- <option value="gen_image" selected>🖼️ Generate Image</option>
- <option value="gen_video">🎥 Generate Video</option>
- <option value="edit_video">✂️ Edit Video</option>
- <option value="extend_video">➡️ Extend Video</option>
- </select>
- </div>
- <div style="padding: 10px; display: flex; flex-direction: column; overflow-y: auto;">
- <div id="setting-ar" class="slider-block">
- <div class="slider-header"><label style="margin:0;">Aspect Ratio</label></div>
- <div class="ar-select-box" id="ar-select-box">
- <div id="ar-selected-icon"></div>
- <span id="ar-selected-text">Auto</span>
- </div>
- </div>
- <div id="setting-high-res" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
- <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;">High Resolution</label></div>
- <button id="high-res-btn" class="toggle-btn active">ON (2K / 720p)</button>
- </div>
- <div id="setting-quality" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
- <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="Quality = grok-imagine-image-quality (better realism & text). Speed = grok-imagine-image">Quality Mode</label></div>
- <button id="quality-btn" class="toggle-btn">OFF (Speed)</button>
- </div>
- <div id="setting-batch" class="slider-block">
- <div class="slider-header"><label style="margin:0;">Batch Size</label> <span id="val-batch">1 Image</span></div>
- <input type="range" id="xai-api-n" min="0" max="6" value="0">
- <div class="slider-ticks" id="ticks-batch"></div>
- </div>
- <div id="setting-duration" class="slider-block" style="display: none;">
- <div class="slider-header"><label style="margin:0;">Duration</label> <span id="val-duration">5 Seconds</span></div>
- <input type="range" id="xai-api-duration" min="0" max="14" value="4">
- <div class="slider-ticks" id="ticks-duration"></div>
- </div>
- <div id="setting-loops" class="slider-block">
- <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="How many consecutive API calls to perform in a row">Loops</label></div>
- <div style="display: flex; gap: 10px; align-items: center; margin-top: 4px;">
- <input type="range" id="slider-loops" min="1" max="20" value="1" style="flex: 1; margin:0;">
- <input type="number" id="xai-api-loops" value="1" min="1" max="100" style="width: 50px; height: 26px; padding: 2px 4px; text-align: center; border-radius: 4px; border: 1px solid #334155; background: #1e293b; color: #f8fafc;">
- </div>
- </div>
- </div>
- </div>
- <div class="panel" style="flex: 1; min-height: 0;">
- <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
- <span>Previous Results</span>
- <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
- </div>
- <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
- <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
- </div>
- </div>
- </div>
- <!-- CENTER COLUMN -->
- <div class="col-center">
- <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
- <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
- <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>
- </div>
- <div class="panel" style="flex-shrink: 0; padding: 12px;">
- <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
- <span style="display: flex; align-items: center; gap: 8px;">
- <span>Prompt</span>
- <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
- </span>
- <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
- </label>
- <div id="warnings-container" style="display: flex; flex-direction: column; gap: 0px;"></div>
- <div class="prompt-container">
- <div id="prompt-backdrop"></div>
- <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed"></textarea>
- </div>
- <div style="display: flex; align-items: center; justify-content: space-between;">
- <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
- <div style="display: flex; gap: 8px;">
- <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
- <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
- <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
- </div>
- </div>
- </div>
- </div>
- <!-- RIGHT COLUMN -->
- <div class="col-right" id="col-right-dropzone">
- <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
- <div class="panel-title" id="ref-panel-title">Reference Media</div>
- <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
- <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);">
- <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
- <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
- </div>
- <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
- <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
- <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
- </div>
- </div>
- </div>
- <div id="ar-options-container"></div>
- <!-- MODALS -->
- <div id="xai-lightbox" class="modal-overlay">
- <div id="xai-lightbox-wrapper">
- <img id="xai-lightbox-img" src="">
- <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>
- </div>
- </div>
- <div id="tag-preview-box" style="position: fixed; display: none; z-index: 99999999; background: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); pointer-events: none;">
- <img id="tag-preview-img" style="max-width: 150px; max-height: 150px; border-radius: 4px; display: block; object-fit: cover;">
- </div>
- <!-- LOGS MODAL -->
- <div id="xai-logs-modal" class="modal-overlay">
- <div class="modal-box" style="width: 800px; max-width: 95vw; height: 80vh;">
- <div style="display: flex; justify-content: space-between; align-items: center;">
- <h3 style="margin:0; font-size: 15px; color: #f8fafc;">🐛 Debug Logs</h3>
- <button id="close-logs-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
- </div>
- <textarea id="logs-textarea" readonly style="flex: 1; width: 100%; background: #0f172a; color: #e2e8f0; font-family: monospace; font-size: 11px; border: 1px solid #334155; border-radius: 6px; padding: 10px; resize: none; white-space: pre;"></textarea>
- <div style="display: flex; gap: 8px;">
- <button id="copy-logs-btn" class="btn-primary" style="flex: 1;">📋 Copy Logs to Clipboard</button>
- <button id="clear-logs-btn" class="btn-secondary" style="flex: 1; color: #ef4444; border-color: #ef4444;">🗑️ Clear Logs</button>
- </div>
- </div>
- </div>
- <!-- SETTINGS MODAL -->
- <div id="xai-settings-modal" class="modal-overlay">
- <div class="modal-box" style="width: 500px;">
- <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
- <div style="display:flex; gap:10px;">
- <div style="flex:1;"><label>Max Retries</label><input type="number" id="set-retries" min="1" max="100"></div>
- <div style="flex:1;"><label>Delay Min (ms)</label><input type="number" id="set-delay-min" min="500" step="500"></div>
- <div style="flex:1;"><label>Delay Max (ms)</label><input type="number" id="set-delay-max" min="1000" step="500"></div>
- </div>
- <div><label>API Base URL (Leave empty for default console.x.ai)</label><input type="text" id="set-api-base-url" placeholder="e.g., https://api.proxy.com"></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;"><label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-save-png" style="width: 16px; height: 16px;"><label for="set-save-png" style="margin: 0; cursor: pointer;">Save as Original PNG (Disable JPEG / EXIF Prompt)</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-download" style="width: 16px; height: 16px;"><label for="set-auto-download" style="margin: 0; cursor: pointer;">Auto-Download Generated Media</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-anti-throttling" style="width: 16px; height: 16px;"><label for="set-anti-throttling" style="margin: 0; cursor: pointer;">Prevent Background Throttling (Plays silent audio)</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-retry-video" style="width: 16px; height: 16px;"><label for="set-auto-retry-video" style="margin: 0; cursor: pointer;">Auto-Retry Stuck Videos (Timeout / Moderated)</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-break-loop-on-failure" style="width: 16px; height: 16px;"><label for="set-break-loop-on-failure" style="margin: 0; cursor: pointer;">Break loops if one iteration fails entirely.</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-reference-ar-trick" style="width: 16px; height: 16px;"><label for="set-reference-ar-trick" style="margin: 0; cursor: pointer;">Single reference aspect ratio fix hack.</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-maximum-greed-mode" style="width: 16px; height: 16px;"><label for="set-maximum-greed-mode" style="margin: 0; cursor: pointer;">MAXIUMUM GREED mode: reload tab on rate limit instead of waiting</label></div>
- <div style="display:flex; gap:10px; margin-top: 4px;">
- <div style="flex:1;"><label>Video Poll Timeout (s)</label><input type="number" id="set-video-timeout" min="10" step="10"></div>
- <div style="flex:1;"><label title="When 'Rate limit exceeded' occurs">Rate Limit Delay (s)</label><input type="number" id="set-rate-limit-delay" min="1" step="1"></div>
- <div style="flex:1;"><label>Base Font Size (px)</label><input type="number" id="set-font-size" min="10" max="24"></div>
- </div>
- <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;"></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-suppress-warning" style="width: 16px; height: 16px;"><label for="set-suppress-warning" style="margin: 0; cursor: pointer; color: #fcd34d;">Suppress yellow ">8s video edit" warning</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-autoplay" style="width: 16px; height: 16px;"><label for="set-video-autoplay" style="margin: 0; cursor: pointer;">Autoplay generated videos in gallery</label></div>
- <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-muted" style="width: 16px; height: 16px;"><label for="set-video-muted" style="margin: 0; cursor: pointer;">Start generated videos muted</label></div>
- <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;">
- <label>Custom CSS Overrides</label>
- <textarea id="set-custom-css" style="font-family: monospace; height: 60px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
- </div>
- <div style="display: flex; gap: 8px; margin-top: 5px; border-top: 1px solid #334155; padding-top: 10px;">
- <button id="export-data-btn" class="btn-secondary" style="flex:1;">📤 Export Data</button>
- <button id="import-data-btn" class="btn-secondary" style="flex:1;">📥 Import Data</button>
- <input type="file" id="import-data-file" accept=".json" style="display: none;">
- </div>
- <div style="display: flex; gap: 8px; margin-top: 5px;">
- <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
- <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
- </div>
- </div>
- </div>
- <!-- FAVORITES MODAL -->
- <div id="xai-fav-modal" class="modal-overlay">
- <div class="modal-box" style="width: 550px;">
- <div style="display: flex; justify-content: space-between; align-items: center;">
- <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
- <button id="close-fav-btn" style="background: none; border: none; color: #ef4444; font-size: 20px; cursor: pointer; font-weight: bold; line-height: 1;">×</button>
- </div>
- <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
- <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
- </div>
- </div>
- <!-- PAYLOAD MODAL -->
- <div id="xai-payload-modal" class="modal-overlay">
- <div class="modal-box" style="width: 550px;">
- <div style="display: flex; justify-content: space-between; align-items: center;">
- <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
- <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>
- </div>
- <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
- <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>
- <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>
- <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
- </div>
- </div>
- </div>
- `;
- // ─── DOM ELEMENT CACHE ───────────────────────────────────────────────────
- const els = {};
- function initializeDOM() {
- Object.assign(els, {
- app: document.getElementById('xai-pro-app'),
- prompt: document.getElementById('xai-api-prompt'),
- promptBackdrop: document.getElementById('prompt-backdrop'),
- warningsContainer: document.getElementById('warnings-container'),
- promptContainer: document.querySelector('.prompt-container'),
- action: document.getElementById('master-action'),
- highResBtn: document.getElementById('high-res-btn'),
- qualityBtn: document.getElementById('quality-btn'),
- settingQuality: document.getElementById('setting-quality'),
- n: document.getElementById('xai-api-n'),
- duration: document.getElementById('xai-api-duration'),
- loopsSlider: document.getElementById('slider-loops'),
- loopsNum: document.getElementById('xai-api-loops'),
- settingAr: document.getElementById('setting-ar'),
- settingHighRes: document.getElementById('setting-high-res'),
- settingBatch: document.getElementById('setting-batch'),
- settingDuration: document.getElementById('setting-duration'),
- fileInput: document.getElementById('xai-api-file'),
- dropzone: document.getElementById('col-right-dropzone'),
- uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
- refList: document.getElementById('xai-ref-list'),
- refTitle: document.getElementById('ref-panel-title'),
- btn: document.getElementById('xai-api-generate'),
- previewBtn: document.getElementById('xai-preview-btn'),
- cancelBtn: document.getElementById('xai-cancel-btn'),
- status: document.getElementById('xai-api-status'),
- history: document.getElementById('xai-history'),
- currentImages: document.getElementById('xai-current-images'),
- reset: document.getElementById('xai-reset-btn'),
- arSelectBox: document.getElementById('ar-select-box'),
- arOptionsCont: document.getElementById('ar-options-container'),
- arSelectedIcon: document.getElementById('ar-selected-icon'),
- arSelectedText: document.getElementById('ar-selected-text'),
- lightbox: document.getElementById('xai-lightbox'),
- lightboxImg: document.getElementById('xai-lightbox-img'),
- lightboxDl: document.getElementById('xai-lightbox-dl'),
- previewBox: document.getElementById('tag-preview-box'),
- previewImg: document.getElementById('tag-preview-img'),
- payloadModal: document.getElementById('xai-payload-modal'),
- payloadEndpoint: document.getElementById('payload-endpoint'),
- payloadCode: document.getElementById('payload-code'),
- closePayloadBtn: document.getElementById('close-payload-btn'),
- sendCustomBtn: document.getElementById('send-custom-payload-btn'),
- customStatus: document.getElementById('custom-payload-status'),
- settingsBtn: document.getElementById('settings-btn'),
- settingsModal: document.getElementById('xai-settings-modal'),
- closeSettingsBtn: document.getElementById('close-settings-btn'),
- saveSettingsBtn: document.getElementById('save-settings-btn'),
- exportDataBtn: document.getElementById('export-data-btn'),
- importDataBtn: document.getElementById('import-data-btn'),
- importDataFile: document.getElementById('import-data-file'),
- favBtn: document.getElementById('fav-prompts-btn'),
- favModal: document.getElementById('xai-fav-modal'),
- closeFavBtn: document.getElementById('close-fav-btn'),
- addFavBtn: document.getElementById('add-current-fav-btn'),
- favList: document.getElementById('fav-list'),
- logsBtn: document.getElementById('logs-btn'),
- logsModal: document.getElementById('xai-logs-modal'),
- closeLogsBtn: document.getElementById('close-logs-btn'),
- copyLogsBtn: document.getElementById('copy-logs-btn'),
- clearLogsBtn: document.getElementById('clear-logs-btn'),
- logsTextarea: document.getElementById('logs-textarea')
- });
- }
- // ─── INITIALIZATION ───────────────────────────────────────────────────────
- let updateUIForEditMedia = null;
- let activeDurationMap = MAPS.durGen;
- const initApp = () => {
- if (!document.body) return setTimeout(initApp, 50);
- const hideNode = (node) => {
- if (node.nodeType === 1 && node.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(node.tagName)) {
- node.style.display = 'none';
- }
- };
- Array.from(document.body.children).forEach(hideNode);
- new MutationObserver((mutations) => {
- mutations.forEach(m => m.addedNodes.forEach(hideNode));
- }).observe(document.body, { childList: true });
- if (!document.getElementById('xai-pro-app')) {
- const style = document.createElement('style'); style.innerHTML = UI_CSS; document.head.appendChild(style);
- const customStyle = document.createElement('style'); customStyle.id = 'xai-custom-css-block'; customStyle.innerHTML = appSettings.customCSS; document.head.appendChild(customStyle);
- document.body.insertAdjacentHTML('beforeend', UI_HTML);
- updateFontSize(appSettings.uiFontSize);
- initializeDOM();
- bindLogic();
- }
- };
- let referenceMedia =[];
- let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
- let fullPayloadMemory = {};
- let currentAbortController = null;
- let isRequestCancelled = false;
- // ─── INDEXEDDB MANAGER ───────────────────────────────────────────────────
- const DB_NAME = 'xAIProStudioDB';
- const STORE_NAME = 'refsStore';
- const DBManager = {
- init: function() {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(DB_NAME, 1);
- request.onupgradeneeded = (e) => {
- const db = e.target.result;
- if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
- };
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error);
- });
- },
- setRefs: async function(data) {
- const db = await this.init();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([STORE_NAME], 'readwrite');
- const store = transaction.objectStore(STORE_NAME);
- const request = store.put(data, 'refs');
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error);
- });
- },
- getRefs: async function() {
- const db = await this.init();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([STORE_NAME], 'readonly');
- const store = transaction.objectStore(STORE_NAME);
- const request = store.get('refs');
- request.onsuccess = () => resolve(request.result || null);
- request.onerror = () => reject(request.error);
- });
- }
- };
- let saveRefsTimeout = null;
- function saveRefs(immediate = false) {
- const executeSave = async () => {
- try {
- const cleanRefs = referenceMedia.map(m => {
- const copy = { ...m };
- delete copy.blobUrl; // Do not save session-bound URLs
- return copy;
- });
- await DBManager.setRefs(cleanRefs);
- } catch(e) { addLog('ERROR', 'Failed to save refs to IDB', e); }
- };
- if (saveRefsTimeout) clearTimeout(saveRefsTimeout);
- // Return the promise if immediate, so we can await it during critical reloads
- if (immediate) return executeSave();
- else saveRefsTimeout = setTimeout(executeSave, 400);
- }
- function findMapIndex(arr, val) {
- let idx = arr.findIndex(item => (item.v || item).toString() === val.toString());
- return idx !== -1 ? idx : 0;
- }
- function drawTicks(containerId, map, colorFn) {
- const cont = document.getElementById(containerId);
- if (!cont) return;
- cont.innerHTML = map.map((item, index) => {
- let val = item.v || item; let label = item.t || val;
- let color = colorFn ? colorFn(val) : '#64748b';
- let percent = map.length > 1 ? (index / (map.length - 1)) * 100 : 50;
- let offset = 8 - (percent / 100) * 16;
- return `<span style="color:${color}; left:calc(${percent}% + ${offset}px);">${label}</span>`;
- }).join('');
- }
- function getDurationColor(val) {
- const v = parseInt(val);
- if (v <= 8) return '#f8fafc';
- if (v <= 10) return '#94a3b8';
- return '#ef4444';
- }
- function syncSlider(sliderEl, textEl, mapArr, formatFn) {
- const val = mapArr[sliderEl.value];
- textEl.innerText = formatFn ? formatFn(val) : (val.l || val);
- }
- // ─── SHARED UI HELPERS ───────────────────────────────────────────────────
- let isHighRes = true; // Moved to global scope
- let isQuality = localStorage.getItem('xai_api_quality') === 'true';
- let genSettingsTimeout = null;
- function updateGenSettingsMemory() {
- if (genSettingsTimeout) clearTimeout(genSettingsTimeout);
- genSettingsTimeout = setTimeout(() => {
- localStorage.setItem('xai_api_gen_settings', JSON.stringify({
- action: els.action.value, isHighRes: isHighRes, isQuality: isQuality,
- n: MAPS.batch[els.n.value], duration: activeDurationMap[els.duration.value], loops: els.loopsNum.value
- }));
- }, 300);
- }
- function updateWarnings() {
- els.warningsContainer.innerHTML = ''; let html = '';
- if (/--[a-zA-Z0-9_-]+=/.test(els.prompt.value)) html += `<div class="warning-box warning-red">⚠️ A gentle reminder that --parameter=value has never been shown to do anything at all, including --seed and --sid, but you do you!</div>`;
- const action = els.action.value; const duration = activeDurationMap[els.duration.value] || 0; const activeRefs = referenceMedia.filter(m => m.active).length;
- if (action === 'gen_video') {
- if (activeRefs > 0 && duration > 10) {
- const currentAr = localStorage.getItem('xai_api_ar');
- if ( currentAr != 'Auto' && currentAr != 'By First Ref' ) {
- html += `<div class="warning-box warning-red">⚠️ Warning: videos longer than 10 seconds seem to stretch the reference to the desired aspect ratio instead of properly resizing them. You might get better results with auto.</div>`;
- }
- if ( activeRefs > 1 ) {
- html += `<div class="warning-box warning-red">⚠️ Warning: only the first reference is going to be used for videos longer than 10 seconds.</div>`;
- }
- }
- if (duration > 8 && !appSettings.suppressEditWarning) html += `<div class="warning-box warning-yellow">⚠️ Note: edit won't work on videos longer than 8s like the one you are about to generate. You can suppress this warning in options.</div>`;
- }
- els.warningsContainer.innerHTML = html;
- }
- function syncPromptBackdrop() {
- const val = els.prompt.value; updateWarnings();
- let html = val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
- const activeRefs = referenceMedia.filter(m => m.active);
- html = html.replace(/<IMAGE_(\d+)>/g, (match, idxStr) => { const idx = parseInt(idxStr); return activeRefs[idx] ? `<span class="prompt-tag" data-idx="${idx}">${match}</span>` : match; });
- els.promptBackdrop.innerHTML = html.replace(/\n/g, '<br>') + '<br>';
- els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
- }
- function setPromptVal(val) {
- els.prompt.focus();
- els.prompt.setSelectionRange(0, els.prompt.value.length);
- document.execCommand('insertText', false, val);
- localStorage.setItem('xai_api_prompt', val);
- syncPromptBackdrop();
- }
- // ─── MODALS & AUXILIARY UI SETUP ─────────────────────────────────────────
- function renderFavList() {
- els.favList.innerHTML = '';
- if (favoritePrompts.length === 0) { els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>'; return; }
- favoritePrompts.forEach((promptText, idx) => {
- const div = document.createElement('div'); div.className = 'fav-item'; div.innerHTML = `<div class="fav-text" title="${promptText.replace(/"/g, '"')}">${promptText}</div><button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>`;
- div.querySelector('.fav-text').addEventListener('click', () => { setPromptVal(promptText); els.favModal.style.display = 'none'; });
- div.querySelector('button').addEventListener('click', () => { favoritePrompts.splice(idx, 1); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList(); });
- els.favList.appendChild(div);
- });
- }
- function setupModalsAndAuxUI() {
- // --- Logs Modal ---
- els.logsBtn.addEventListener('click', () => { els.logsTextarea.value = formatLogsForExport(); els.logsModal.style.display = 'flex'; els.logsTextarea.scrollTop = els.logsTextarea.scrollHeight; });
- els.closeLogsBtn.addEventListener('click', () => els.logsModal.style.display = 'none');
- els.copyLogsBtn.addEventListener('click', () => { els.logsTextarea.select(); document.execCommand('copy'); alert('Logs copied to clipboard!'); });
- els.clearLogsBtn.addEventListener('click', () => { if (confirm("Clear all logs?")) { appLogs.length = 0; els.logsTextarea.value = ''; } });
- // --- Settings Modal (from Block 1) ---
- els.settingsBtn.addEventListener('click', () => { SettingsManager.populateUI(appSettings); els.settingsModal.style.display = 'flex'; });
- els.saveSettingsBtn.addEventListener('click', () => { appSettings = SettingsManager.saveFromUI(); document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS; updateFontSize(appSettings.uiFontSize); updateWarnings(); els.settingsModal.style.display = 'none'; });
- els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
- // --- Export / Import ---
- els.exportDataBtn.addEventListener('click', () => {
- const blob = new Blob([JSON.stringify({settings: appSettings, refs: referenceMedia}, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `xAI_Pro_Studio_Backup_${makeTimestamp()}.json`; a.click(); URL.revokeObjectURL(url);
- });
- els.importDataBtn.addEventListener('click', () => els.importDataFile.click());
- els.importDataFile.addEventListener('change', (e) => {
- const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
- reader.onload = async (evt) => {
- try {
- const parsed = JSON.parse(evt.target.result);
- if (parsed.settings) { appSettings = { ...appSettings, ...parsed.settings }; localStorage.setItem('xai_api_settings', JSON.stringify(appSettings)); }
- if (parsed.refs && Array.isArray(parsed.refs)) {
- referenceMedia = parsed.refs;
- await saveRefs(true);
- }
- alert("Import successful! Page will reload."); location.reload();
- } catch(err) { alert("Failed to parse the JSON file."); }
- }; reader.readAsText(file); e.target.value = '';
- });
- // --- Favorites Modal ---
- els.favBtn.addEventListener('click', () => { renderFavList(); els.favModal.style.display = 'flex'; });
- els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
- els.addFavBtn.addEventListener('click', () => {
- const p = els.prompt.value.trim(); if (!p) return alert("Prompt is empty!"); if (favoritePrompts.includes(p)) return alert("Already in favorites!");
- favoritePrompts.unshift(p); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList();
- });
- // --- Lightbox & Global Esc Key ---
- els.app.addEventListener('click', (e) => {
- if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
- els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg'; els.lightbox.style.display = 'flex';
- els.lightboxDl.onclick = () => { if(e.target.closest('.current-card')) e.target.closest('.current-card').classList.add('downloaded'); };
- }
- });
- els.lightbox.addEventListener('click', (e) => { if (!e.target.closest('#xai-lightbox-dl') && !e.target.closest('.modal-box')) els.lightbox.style.display = 'none'; });
- document.addEventListener('keydown', (e) => { if(e.key === 'Escape') Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); });
- }
- // ─── PROMPT & ASPECT RATIO SETUP ─────────────────────────────────────────
- function setupPromptListeners() {
- if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
- let promptSaveTimeout = null;
- els.prompt.addEventListener('input', () => {
- if (promptSaveTimeout) clearTimeout(promptSaveTimeout);
- promptSaveTimeout = setTimeout(() => localStorage.setItem('xai_api_prompt', els.prompt.value), 400);
- syncPromptBackdrop();
- });
- els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
- let hidePreviewTimeout;
- els.prompt.addEventListener('mousemove', (e) => {
- if (e.buttons !== 0) { els.previewBox.style.display = 'none'; return; }
- els.prompt.style.pointerEvents = 'none'; const el = document.elementFromPoint(e.clientX, e.clientY); els.prompt.style.pointerEvents = 'auto';
- if (el && el.classList.contains('prompt-tag')) {
- const idx = el.getAttribute('data-idx'); const media = referenceMedia.filter(m => m.active)[parseInt(idx)];
- if (media) {
- els.previewBox.style.display = 'block';
- els.previewImg.src = media.thumb || media.blobUrl || media.base64;
- let tx = e.clientX + 15; let ty = e.clientY + 15;
- if (tx + 160 > window.innerWidth) tx = e.clientX - 165; if (ty + 160 > window.innerHeight) ty = e.clientY - 165;
- els.previewBox.style.left = tx + 'px'; els.previewBox.style.top = ty + 'px';
- clearTimeout(hidePreviewTimeout);
- }
- } else hidePreviewTimeout = setTimeout(() => els.previewBox.style.display = 'none', 50);
- });
- els.prompt.addEventListener('mouseleave', () => els.previewBox.style.display = 'none');
- els.prompt.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- if (!els.btn.disabled) {
- els.btn.click();
- }
- }
- });
- els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
- els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
- els.prompt.addEventListener('drop', async (e) => {
- e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over');
- if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
- const file = e.dataTransfer.files[0]; const oldVal = els.prompt.value; setPromptVal("Extracting prompt from EXIF...");
- const extractedPrompt = await extractPromptFromImage(file);
- if (extractedPrompt) setPromptVal(extractedPrompt); else { setPromptVal(oldVal); alert("No prompt found in this image's EXIF data."); }
- }
- });
- }
- function setupAspectRatioUI() {
- function renderArOptions() {
- els.arOptionsCont.innerHTML = '';
- arData.forEach(ar => {
- const opt = document.createElement('div'); opt.className = 'ar-option';
- opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto, ar.isRef)} <span>${ar.label}</span>`;
- opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
- els.arOptionsCont.appendChild(opt);
- });
- }
- function setAr(arObj) {
- currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
- els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto, arObj.isRef); els.arSelectedText.innerText = arObj.label;
- }
- renderArOptions();
- const initialAr = arData.find(a => a.label === currentAr) || arData[0];
- setAr(initialAr);
- els.arSelectBox.addEventListener('click', (e) => {
- e.stopPropagation(); if (els.arOptionsCont.style.display === 'grid') { els.arOptionsCont.style.display = 'none'; return; }
- const rect = els.arSelectBox.getBoundingClientRect(); els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px'; els.arOptionsCont.style.display = 'grid';
- });
- document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
- }
- // ─── MEDIA & ACTION UI SETUP ─────────────────────────────────────────────
- function getMaxMedia() {
- const val = els.action.value;
- return val === 'gen_image' ? 5 : (val === 'gen_video' ? 7 : 1);
- }
- function updateActionUI() {
- const val = els.action.value;
- if (val === 'gen_image') {
- els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingQuality.style.display = 'flex'; els.settingBatch.style.display = 'flex'; els.settingDuration.style.display = 'none';
- } else if (val === 'gen_video') {
- els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingQuality.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
- activeDurationMap = MAPS.durGen; els.duration.max = activeDurationMap.length - 1;
- drawTicks('ticks-duration', activeDurationMap, getDurationColor);
- syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
- } else if (val === 'edit_video') {
- els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingQuality.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
- } else if (val === 'extend_video') {
- els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingQuality.style.display = 'none'; els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
- activeDurationMap = MAPS.durExt; els.duration.max = activeDurationMap.length - 1;
- drawTicks('ticks-duration', activeDurationMap, getDurationColor);
- syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
- }
- const max = getMaxMedia(); els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
- let activeCount = 0;
- referenceMedia.forEach(m => {
- let valid = true;
- if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
- if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
- if (!valid) m.active = false; else if (m.active) { activeCount++; if (activeCount > max) m.active = false; }
- });
- renderRefList(); updateWarnings();
- }
- let draggedIndex = null;
- function updateRefActiveStates() {
- const actionVal = els.action.value;
- const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
- const activeRefs = referenceMedia.filter(m => m.active);
- const refNodes = Array.from(els.refList.children);
- referenceMedia.forEach((media, index) => {
- const item = refNodes[index];
- if (!item) return;
- // Update grayscale/opacity
- if (media.active) item.classList.remove('inactive');
- else item.classList.add('inactive');
- // Update Insert Button Text & Status
- if (!media.isVideo) {
- const insertBtn = item.querySelector('.ref-insert');
- if (insertBtn) {
- if (disableInsert) {
- insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'grayscale(1)'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Not available in this mode"; insertBtn.innerHTML = `➕ <IMAGE_X>`;
- } else if (!media.active) {
- insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Check 'Use in Payload' first"; insertBtn.innerHTML = `➕ <IMAGE_?>`;
- } else {
- const dynamicIndex = activeRefs.indexOf(media);
- insertBtn.disabled = false; insertBtn.style.opacity = '1'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'pointer'; insertBtn.title = "Insert into prompt"; insertBtn.innerHTML = `➕ <IMAGE_${dynamicIndex}>`;
- }
- }
- }
- });
- }
- function renderRefList() {
- els.refList.innerHTML = '';
- referenceMedia.forEach((media, index) => {
- const item = document.createElement('div'); item.className = 'ref-item'; item.draggable = true;
- const activeRefs = referenceMedia.filter(m => m.active); const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
- const actionVal = els.action.value; const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
- let thumbHtml = '';
- if (media.isVideo) {
- if (media.thumb) thumbHtml = `<div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;"><img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}"><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></div>`;
- else 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>`;
- } else thumbHtml = `<img src="${media.blobUrl || media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
- let insertBtnHtml = '';
- if (!media.isVideo) {
- if (disableInsert) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; filter: grayscale(1); cursor: not-allowed;" title="Not available in this mode">➕ <IMAGE_X></button>`;
- else if (!media.active) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; cursor: not-allowed;" title="Check 'Use in Payload' first">➕ <IMAGE_?></button>`;
- else insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ <IMAGE_${dynamicIndex}></button>`;
- }
- item.innerHTML = `<div class="ref-handle">☰</div>${thumbHtml}<div class="ref-info"><span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span><label class="ref-toggle-label"><input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload</label><div class="ref-btn-group">${insertBtnHtml}<button class="ref-action-btn ref-del">Remove</button></div></div>`;
- const insertBtn = item.querySelector('.ref-insert');
- if (insertBtn) {
- insertBtn.addEventListener('click', (e) => {
- if (!media.active || insertBtn.disabled) return;
- const currentAction = els.action.value; if (currentAction === 'edit_video' || currentAction === 'extend_video') { e.preventDefault(); return alert("<IMAGE_X> tags not supported here."); }
- const dynIdx = referenceMedia.filter(m => m.active).indexOf(media);
- const promptEl = els.prompt; const tag = `<IMAGE_${dynIdx}>`; const startPos = promptEl.selectionStart; const endPos = promptEl.selectionEnd;
- setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
- promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length; promptEl.focus();
- });
- }
- if (!media.active) item.classList.add('inactive');
- item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
- const max = getMaxMedia(); const currentlyActive = referenceMedia.filter(r => r.active).length;
- if (e.target.checked && currentlyActive >= max) { alert(`Up to ${max} active references allowed.`); e.target.checked = false; return; }
- media.active = e.target.checked;
- saveRefs();
- updateRefActiveStates();
- syncPromptBackdrop();
- updateWarnings();
- });
- item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
- item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
- item.addEventListener('dragover', (e) => { e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); } else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); } });
- item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
- item.addEventListener('drop', (e) => { e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom'); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1; if (draggedIndex < insertIndex) insertIndex--; const [movedImage] = referenceMedia.splice(draggedIndex, 1); referenceMedia.splice(insertIndex, 0, movedImage); renderRefList(); syncPromptBackdrop(); });
- item.querySelector('.ref-del').addEventListener('click', () => {
- const removed = referenceMedia.splice(index, 1)[0];
- if (removed && removed.blobUrl) URL.revokeObjectURL(removed.blobUrl);
- renderRefList(); syncPromptBackdrop(); updateWarnings();
- });
- els.refList.appendChild(item);
- });
- saveRefs();
- }
- async function processFile(file) {
- const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
- if (!isVid && !isImg) return;
- if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
- else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
- const max = getMaxMedia(); const activeCount = referenceMedia.filter(m => m.active).length;
- let thumbBase64 = null; if (isVid) thumbBase64 = await generateVideoThumbnail(file);
- const blobUrl = URL.createObjectURL(file);
- const reader = new FileReader();
- reader.onload = async (event) => {
- const b64 = event.target.result;
- let w = 0, h = 0;
- if (isVid && file._w && file._h) { w = file._w; h = file._h; }
- else if (isImg) {
- try {
- const dims = await new Promise(r => { const i = new Image(); i.onload = () => r({w: i.width, h: i.height}); i.onerror = () => r({w: 0, h: 0}); i.src = blobUrl; });
- w = dims.w; h = dims.h;
- } catch(e) {}
- }
- referenceMedia.push({ id: Date.now() + Math.random(), base64: b64, blobUrl: blobUrl, isVideo: isVid, active: activeCount < max, thumb: thumbBase64, fileName: file.name, w, h });
- renderRefList();
- };
- reader.readAsDataURL(file);
- }
- function setupMediaAndActionUI() {
- drawTicks('ticks-batch', MAPS.batch);
- (async () => {
- try {
- let storedRefs = await DBManager.getRefs();
- // One-time migration from old localStorage to IndexedDB
- if (!storedRefs) {
- const legacyRefs = localStorage.getItem('xai_api_refs');
- if (legacyRefs) {
- storedRefs = JSON.parse(legacyRefs);
- localStorage.removeItem('xai_api_refs'); // Clean up the bloat!
- }
- }
- if (Array.isArray(storedRefs)) {
- referenceMedia = storedRefs;
- referenceMedia.forEach(m => {
- if (m.base64) m.blobUrl = base64ToBlobUrl(m.base64);
- });
- // Refresh the UI now that data has arrived
- updateActionUI();
- renderRefList();
- }
- } catch(e) {}
- })();
- els.highResBtn.addEventListener('click', () => {
- isHighRes = !isHighRes;
- els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
- els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
- updateGenSettingsMemory();
- });
- function updateQualityBtn() {
- if (!els.qualityBtn) return;
- els.qualityBtn.className = isQuality ? 'toggle-btn active' : 'toggle-btn';
- els.qualityBtn.innerText = isQuality ? 'ON (Quality)' : 'OFF (Speed)';
- }
- updateQualityBtn();
- if (els.qualityBtn) {
- els.qualityBtn.addEventListener('click', () => {
- isQuality = !isQuality;
- localStorage.setItem('xai_api_quality', isQuality);
- updateQualityBtn();
- updateGenSettingsMemory();
- });
- }
- els.n.addEventListener('input', () => { syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images')); updateGenSettingsMemory(); });
- els.duration.addEventListener('input', () => { syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds'); updateGenSettingsMemory(); updateWarnings(); });
- els.loopsSlider.addEventListener('input', e => { els.loopsNum.value = e.target.value; updateGenSettingsMemory(); });
- els.loopsNum.addEventListener('input', e => { let v = parseInt(e.target.value) || 1; els.loopsSlider.value = Math.min(v, 20); updateGenSettingsMemory(); });
- els.action.addEventListener('change', () => { updateActionUI(); updateGenSettingsMemory(); });
- try {
- const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
- if (storedGen.action) els.action.value = storedGen.action;
- updateActionUI();
- if (typeof storedGen.isHighRes !== 'undefined') isHighRes = storedGen.isHighRes;
- else if (storedGen.resImg === '1k' || storedGen.resVid === '480p') isHighRes = false;
- if (typeof storedGen.isQuality !== 'undefined') isQuality = !!storedGen.isQuality;
- els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
- els.highResBtn.innerText = isHighRes ? 'ON (2K / 720p)' : 'OFF (1K / 480p)';
- updateQualityBtn();
- if (storedGen.n) els.n.value = findMapIndex(MAPS.batch, storedGen.n);
- if (storedGen.duration) { let idx = activeDurationMap.indexOf(parseInt(storedGen.duration)); els.duration.value = idx !== -1 ? idx : 0; }
- if (storedGen.loops) { els.loopsNum.value = storedGen.loops; els.loopsSlider.value = Math.min(storedGen.loops, 20); }
- syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images'));
- syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
- } catch(e) {}
- updateUIForEditMedia = (mediaUrl, isVideo, fileName, actionOverride) => {
- referenceMedia.forEach(m => m.active = false);
- const blobUrl = base64ToBlobUrl(mediaUrl);
- referenceMedia.unshift({ id: Date.now() + Math.random(), base64: mediaUrl, blobUrl: blobUrl, isVideo: isVideo, active: true, thumb: isVideo ? null : blobUrl, fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png'), w:0, h:0 });
- };
- els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
- els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
- document.addEventListener('paste', (e) => { if (e.target && (e.target.id === 'payload-code' || e.target.id === 'xai-api-prompt' || e.target.id === 'set-custom-css' || e.target.tagName === 'INPUT' && e.target.type !== 'range')) return; const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile()); });
- els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
- els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
- els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
- }
- // ─── GENERATION & API CORE LOGIC ─────────────────────────────────────────
- function getMediaDimensions(base64, isVideo) {
- return new Promise(resolve => {
- if (isVideo) {
- const vid = document.createElement('video'); vid.onloadedmetadata = () => resolve({w: vid.videoWidth, h: vid.videoHeight}); vid.onerror = () => resolve({w: 0, h: 0}); vid.src = base64;
- } else {
- const img = new Image(); img.onload = () => resolve({w: img.width, h: img.height}); img.onerror = () => resolve({w: 0, h: 0}); img.src = base64;
- }
- });
- }
- async function buildPayloadData(dynamicPromptText) {
- const action = els.action.value;
- let modelName = "grok-imagine-video";
- if (action === 'gen_image') {
- modelName = isQuality ? "grok-imagine-image-quality" : "grok-imagine-image";
- }
- // Video kept as grok-imagine-video (leave for now; 1.5 exists but may need different params)
- const payload = { model: modelName, prompt: dynamicPromptText };
- let ar = currentAr.toLowerCase(); const activeRefs = referenceMedia.filter(m => m.active);
- if (currentAr === 'By First Ref') {
- if (activeRefs.length > 0) {
- let ref = activeRefs[0];
- if (!ref.w || !ref.h) { const dims = await getMediaDimensions(ref.base64, ref.isVideo); ref.w = dims.w; ref.h = dims.h; saveRefs(); }
- if (ref.w && ref.h) {
- const targetRatio = ref.w / ref.h; let bestMatch = '1:1'; let minDiff = Infinity;
- arData.forEach(a => {
- if (a.isAuto || a.isRef) return;
- const r = a.w / a.h; const diff = Math.abs(r - targetRatio);
- if (diff < minDiff) { minDiff = diff; bestMatch = a.label; }
- });
- ar = bestMatch.toLowerCase(); addLog('INFO', 'Calculated AR by First Ref', { targetRatio, selectedAr: ar });
- } else ar = 'auto';
- } else ar = 'auto';
- }
- if (action === 'gen_image') {
- payload.n = MAPS.batch[els.n.value]; payload.resolution = isHighRes ? "2k" : "1k"; payload.response_format = "b64_json";
- if (ar !== 'auto') payload.aspect_ratio = ar;
- if (activeRefs.length > 0) {
- if (activeRefs.length === 1) {
- if (appSettings.referenceARTrick && ar != 'auto') payload.images = [{ type: "image_url", url: activeRefs[0].base64 }, { type: "image_url", url: activeRefs[0].base64 }];
- else payload.image = { url: activeRefs[0].base64 };
- }
- else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
- }
- } else if (action === 'gen_video') {
- payload.duration = activeDurationMap[els.duration.value]; payload.resolution = isHighRes ? "720p" : "480p";
- if (ar !== 'auto') payload.aspect_ratio = ar;
- if ( activeRefs.length > 0 ) {
- if ( payload.duration > 10 ) {
- payload.image = { url: activeRefs[0].base64 }; //Only the first one
- //delete payload.aspect_ratio; //Seems to just stretch and distort otherwise.
- } else {
- payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
- }
- }
- } else if (action === 'edit_video') {
- if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
- } else if (action === 'extend_video') {
- payload.duration = activeDurationMap[els.duration.value];
- if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
- }
- return payload;
- }
- function injectBase64(editedObj, originalObj) {
- if (!editedObj || typeof editedObj !== 'object') return;
- for (let key in editedObj) {
- if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') { if (originalObj && originalObj[key]) editedObj[key] = originalObj[key]; }
- else if (typeof editedObj[key] === 'object') injectBase64(editedObj[key], originalObj ? originalObj[key] : null);
- }
- }
- async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
- let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : ''; statusEl.innerText = `${loopPrefix}Processing request...`; statusEl.className = "status-pulsing";
- addLog('INFO', `Starting generation loop ${currentLoop}/${totalLoops}`, { endpoint, isImageAction });
- currentAbortController = new AbortController(); let attempts = 0; let success = false; let rateLimitFails = 0;
- try {
- while (attempts < appSettings.retries && !success && !isRequestCancelled) {
- try {
- statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
- const fullEndpoint = getApiUrl(endpoint);
- addLog('NETWORK_REQ', `POST ${fullEndpoint}`, payload);
- const response = await fetch(fullEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: currentAbortController.signal });
- if (response.status === 503 || response.status === 500 || response.status === 502) { attempts++; statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`; addLog('WARN', `Gateway error ${response.status}. Retrying.`); await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue; }
- if (response.status === 401 || response.status === 403) {
- statusEl.innerText = `${loopPrefix}Session Expired (${response.status}). Requesting new cookies...`; statusEl.className = ""; statusEl.style.color = "#d97706";
- await nuclearSessionReset(); await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue;
- }
- if (!response.ok) {
- let errMsg = `HTTP ${response.status}`; let errData = null;
- try { errData = await response.json(); addLog('NETWORK_ERR', `Response error JSON`, { status: response.status, data: errData });
- if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`; else if (errData.error && typeof errData.error === 'string') errMsg += `\n${errData.error}`;
- if (errData.code) errMsg += `\nCode: ${errData.code}`; if (errData.detail) errMsg += `\n${typeof errData.detail === 'string' ? errData.detail : JSON.stringify(errData.detail)}`;
- } catch(e) { addLog('NETWORK_ERR', `Failed to parse error response`, { status: response.status }); }
- throw new Error(errMsg);
- }
- const data = await response.json(); addLog('NETWORK_RES', `Successful response`, data);
- if (isImageAction) {
- if (data && data.data && Array.isArray(data.data)) {
- success = true; statusEl.innerText = `${loopPrefix}Processing final images...`; statusEl.style.color = "#10b981"; statusEl.className = "";
- await Promise.all(data.data.map((imgObj, index) => processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)));
- statusEl.innerText = "Ready"; statusEl.style.color = "#64748b";
- } else throw new Error("Invalid response format.");
- } else {
- const reqId = data.request_id; if (!reqId) throw new Error(data.error ? (data.error.message || JSON.stringify(data.error)) : "No Request ID returned.");
- let videoReady = false; let pollCount = 0; const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
- while (!videoReady && !isRequestCancelled) {
- pollCount++; if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue."); await sleep(5000); if (isRequestCancelled) break;
- addLog('POLL_REQ', `Polling video ID: ${reqId}`, { pollCount, MAX_POLLS });
- const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
- if (!pollRes.ok) {
- if (pollRes.status === 401 || pollRes.status === 403) {
- addLog('POLL_WARN', `Poll got 401/403. Cross-tab wipe likely. Restoring...`); statusEl.innerText = `${loopPrefix}Polling interrupted (401). Restoring session...`;
- try { await fetch('https://console.x.ai/playground/imagine', { credentials: 'include', cache: 'no-store' }); } catch(e) {} await sleep(3000); continue;
- }
- if (pollRes.status >= 400 && pollRes.status < 500) {
- let errData; try { errData = await pollRes.json(); } catch(e) {} addLog('POLL_ERR', `Poll failed HTTP ${pollRes.status}`, errData);
- if (pollRes.status === 404) throw new Error("video lost (404). Session wiped by another tab.");
- if (errData && errData.error) throw new Error(typeof errData.error.message === 'string' ? errData.error.message : JSON.stringify(errData.error));
- }
- continue;
- }
- const pollData = await pollRes.json(); addLog('POLL_RES', `Poll Result`, pollData);
- if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
- const state = (pollData.status || pollData.state || 'processing').toLowerCase(); let progressText = typeof pollData.progress === 'number' ? ` ${pollData.progress}%` : "";
- statusEl.innerText = `${loopPrefix}Polling video (Status: ${state}${progressText})...[${pollCount}/${MAX_POLLS}]`;
- if (state === 'done' || state === 'completed') {
- videoReady = true; success = true; statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
- } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
- if (pollData.video && pollData.video.url) {
- videoReady = true; success = true; statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`; statusEl.className = ""; statusEl.style.color = "#d97706"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
- addLog('WARN', `Video flagged but recovered`, pollData);
- } else throw new Error(`Generation halted. Reason: ${state}`);
- }
- }
- }
- } catch (err) {
- const errStr = err.message.toLowerCase(); addLog('ERROR', `Generation logic exception`, { message: err.message });
- if (err.name === 'AbortError' || isRequestCancelled) { statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444"; return false; }
- let isLongRateLimit = false; let isShortRateLimit = false;
- if (errStr.includes("requests per second (actual/limit)")) {
- const secMatch = errStr.match(/requests per second \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/); const minMatch = errStr.match(/requests per minute \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/);
- if (minMatch && minMatch[1] === minMatch[2]) isLongRateLimit = true; else if (secMatch && secMatch[1] === secMatch[2]) isShortRateLimit = true; else isLongRateLimit = true;
- } else if (errStr.includes("rate limit") || errStr.includes("resource has been exhausted") || errStr.includes("http 429") || errStr.includes("http 422")) isLongRateLimit = true;
- if (isShortRateLimit || isLongRateLimit) {
- if (appSettings.maximumGreedMode) {
- statusEl.innerText = `${loopPrefix}Rate Limit Hit (429). Refreshing tab...`; statusEl.className = ""; statusEl.style.color = "#ef4444";
- await nuclearSessionReset(totalLoops - currentLoop + 1); const u = new URL(window.location.href.split('?')[0]); u.searchParams.set('_rst', Date.now()); window.location.replace(u.toString()); await sleep(10000);
- } else {
- statusEl.innerText = `${loopPrefix}Rate Limit Hit (429). Resetting cookies...`; await nuclearSessionReset();
- if (isShortRateLimit) {
- attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after per-second rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
- await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
- } else {
- attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
- let delaySeconds = parseInt(appSettings.rateLimitDelay) || 60; let countdown = delaySeconds;
- if ((rateLimitFails++) < 1) { await sleep(1000); continue; }
- rateLimitFails = 0; toggleKeepAwake(true);
- while(countdown > 0 && !isRequestCancelled) { statusEl.innerText = `${loopPrefix}Rate Limit Hit. Retrying in ${countdown}s... [${attempts}/${appSettings.retries}]`; await sleep(1000); countdown--; }
- toggleKeepAwake(false);
- }
- if (isRequestCancelled) return false; continue;
- }
- } else if (errStr.includes("video lost") || ((errStr.includes("timeout: video") || errStr.includes("generation halted.") || errStr.includes("video rejected")) && appSettings.autoRetryStuckVideo)) {
- attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
- statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`; await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
- if (payload.prompt) payload.prompt += "\u200B"; continue;
- } else { statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
- }
- }
- } finally { toggleKeepAwake(false); }
- if (!success && !isRequestCancelled) {
- if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:") && !statusEl.innerText.includes("Reloading")) statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
- statusEl.className = ""; statusEl.style.color = "#ef4444"; addLog('ERROR', 'Generation loop failed completely'); return false;
- }
- return success;
- }
- function setupGenerationUI() {
- els.previewBtn.addEventListener('click', async () => {
- els.previewBtn.disabled = true; els.previewBtn.innerHTML = `<div class="loading-spinner" style="border-top-color:#64748b; width:12px; height:12px;"></div>`;
- fullPayloadMemory = await buildPayloadData(parseDynamicPrompt(els.prompt.value.trim()));
- const displayP = JSON.parse(JSON.stringify(fullPayloadMemory)); const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
- if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => (img.url = trunc)); else displayP.image.url = trunc; }
- if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => (img.url = trunc));
- if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => (img.url = trunc));
- if (displayP.video) displayP.video.url = trunc;
- const activeRefs = referenceMedia.filter(m => m.active); let endpoint = '/v1/images/generations';
- if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
- else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
- else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
- else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
- els.payloadEndpoint.value = endpoint; els.payloadCode.value = JSON.stringify(displayP, null, 2); els.payloadModal.style.display = 'flex';
- els.previewBtn.innerHTML = `🔍 Payload`; els.previewBtn.disabled = false;
- });
- els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
- els.sendCustomBtn.addEventListener('click', async () => {
- initAudio(); let customPayload; try { customPayload = JSON.parse(els.payloadCode.value); } catch(e) { return alert("Invalid JSON format in textarea!"); }
- injectBase64(customPayload, fullPayloadMemory);
- const endpoint = els.payloadEndpoint.value.trim();
- const isImage = customPayload.model && String(customPayload.model).includes("image");
- els.sendCustomBtn.disabled = true; els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`; isRequestCancelled = false;
- const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
- els.sendCustomBtn.disabled = false; els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`; if (ok) notifyUser(false); else notifyUser(true);
- });
- els.cancelBtn.addEventListener('click', () => {
- isRequestCancelled = true; if (currentAbortController) currentAbortController.abort(); toggleKeepAwake(false);
- els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
- els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
- });
- els.btn.addEventListener('click', async () => {
- initAudio(); const basePrompt = els.prompt.value.trim(); if (!basePrompt) return alert("Please enter a prompt.");
- addLog('UI', 'Generate button clicked', { basePrompt });
- const oldImages = Array.from(els.currentImages.children);
- if (oldImages.length > 0) {
- if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
- oldImages.forEach(card => { card.className = 'history-card'; const promptEl = card.querySelector('p'); promptEl.title = "Click to copy prompt"; promptEl.onclick = () => setPromptVal(promptEl.innerText); els.history.prepend(card); });
- }
- const action = els.action.value; const activeRefs = referenceMedia.filter(m => m.active);
- let endpoint = '/v1/images/generations';
- if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
- else if (action === 'gen_video') endpoint = '/v1/videos/generations';
- else if (action === 'edit_video') endpoint = '/v1/videos/edits';
- else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
- const isImage = action === 'gen_image'; const totalLoops = parseInt(els.loopsNum.value) || 1;
- els.btn.disabled = true; els.cancelBtn.style.display = 'flex'; els.previewBtn.style.display = 'none'; isRequestCancelled = false;
- let allSuccess = true;
- for (let i = 1; i <= totalLoops; i++) {
- if (isRequestCancelled) break; const dynamicPrompt = parseDynamicPrompt(basePrompt);
- els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Building...</div>`;
- const payload = await buildPayloadData(dynamicPrompt);
- els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
- const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
- if (!ok) { allSuccess = false; if (appSettings.breakLoopOnFailure) break; }
- }
- if (!isRequestCancelled) {
- els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
- if (allSuccess) { els.status.innerText = "All runs complete."; els.status.className = ""; els.status.style.color = "#64748b"; notifyUser(false); addLog('INFO', 'All generation loops completed successfully'); }
- else { notifyUser(true); addLog('ERROR', 'Generation sequence ended with errors'); }
- }
- });
- els.reset.addEventListener('click', () => {
- if (!confirm("Wipe cache? Your prompt and settings will be saved.")) return;
- localStorage.setItem('xai_api_prompt', els.prompt.value); nuclearSessionReset();
- });
- }
- function checkAutoResume() {
- const resumeLoops = sessionStorage.getItem('xai_resume_loops');
- if (resumeLoops) {
- sessionStorage.removeItem('xai_resume_loops'); const loops = parseInt(resumeLoops);
- if (loops > 0) {
- els.loopsNum.value = loops; els.loopsSlider.value = Math.min(loops, 20); updateGenSettingsMemory();
- els.status.innerText = `Auto-resuming ${loops} runs...`; els.status.className = "status-pulsing";
- setTimeout(() => { if (!els.btn.disabled) els.btn.click(); }, 2500);
- }
- }
- }
- function bindLogic() {
- setupModalsAndAuxUI(); // Initializes modals, logs, exports, and lightbox
- setupPromptListeners();
- setupAspectRatioUI();
- setupMediaAndActionUI();
- setupGenerationUI();
- checkAutoResume();
- }
- async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
- if (!imgObj.b64_json) return;
- const mime = imgObj.mime_type || "image/png"; const b64 = imgObj.b64_json; const pngDataUri = `data:${mime};base64,${b64}`;
- const finalPrompt = imgObj.revised_prompt || originalPrompt; let finalDataUri = pngDataUri;
- const qTag = isQuality ? 'Quality' : 'Speed';
- const resTag = isHighRes ? '2K' : '1K';
- let filename = `Grok ${qTag} ${resTag} - ${makeTimestamp()} - ${num}of${total}.png`;
- if (!appSettings.saveAsPng) { finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt); filename = `Grok ${qTag} ${resTag} - ${makeTimestamp()} - ${num}of${total}.jpg`; }
- const card = document.createElement('div'); card.className = 'current-card';
- card.innerHTML = `<div class="img-wrapper"><img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen"><a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a><button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>`;
- card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename, 'gen_image'); });
- const dlBtn = card.querySelector('.overlay-dl-btn');
- dlBtn.addEventListener('click', () => { card.classList.add('downloaded'); });
- galleryEl.prepend(card);
- if (appSettings.autoDownload) {
- //setTimeout(() => dlBtn.click(), 500);
- setTimeout(() => {
- GM_download({ url: finalDataUri, name: filename, saveAs: false });
- card.classList.add('downloaded');
- }, 500);
- }
- }
- function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
- const filename = `Grok Video - ${makeTimestamp()}.mp4`; const auto = appSettings.videoAutoplay ? "autoplay" : ""; const muted = appSettings.videoMuted ? "muted" : "";
- const card = document.createElement('div'); card.className = 'current-card';
- card.innerHTML = `<div class="img-wrapper"><video src="${videoUrl}" controls ${auto} ${muted} loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video><button class="overlay-btn overlay-dl-btn force-dl" data-url="${videoUrl}" data-filename="${filename}" style="z-index: 50; right: 6px;" title="Download MP4">${DOWNLOAD_ICON}</button><button class="overlay-btn overlay-edit-btn" style="z-index: 50; right: 40px;" title="Edit this Video">${EDIT_ICON}</button><button class="overlay-btn overlay-extend-btn" style="z-index: 50; right: 74px;" title="Extend this Video">${EXTEND_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>`;
- card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'edit_video'); });
- card.querySelector('.overlay-extend-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'extend_video'); });
- const dlBtn = card.querySelector('.overlay-dl-btn');
- dlBtn.addEventListener('click', (e) => {
- e.preventDefault(); const url = dlBtn.getAttribute('data-url'); const fname = dlBtn.getAttribute('data-filename'); const originalIcon = dlBtn.innerHTML;
- dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>'; dlBtn.style.pointerEvents = 'none'; card.classList.add('downloaded');
- if (typeof GM_xmlhttpRequest !== "undefined") {
- GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'blob', onload: function(response) {
- if (response.status >= 200 && response.status < 300) {
- const blobUrl = URL.createObjectURL(response.response); const a = document.createElement('a'); a.style.display = 'none'; a.href = blobUrl; a.download = fname; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
- } else window.open(url, '_blank');
- dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto';
- }, onerror: function() { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; } });
- } else { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; }
- });
- galleryEl.prepend(card);
- if (appSettings.autoDownload) {
- //setTimeout(() => dlBtn.click(), 500);
- setTimeout(() => {
- GM_download({ url: videoUrl, name: filename, saveAs: false });
- card.classList.add('downloaded');
- }, 500);
- }
- }
- if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); } else { initApp(); }
- })();
Add Comment
Please, Sign In to add comment