diff --git "a/search.html" "b/search.html" --- "a/search.html" +++ "b/search.html" @@ -37,14 +37,8 @@ window.pauseMarqueeTemporarily = function() {}; - - - `; - }; - - // ▶ "Play Code" button on a code block - runs it in a sandboxed preview - window.playHtmlCode = function(btn, langType = 'html') { - try { - let codeBody = btn.parentElement && btn.parentElement.nextElementSibling; - if (!codeBody || !codeBody.classList || !codeBody.classList.contains('code-body')) { - const box = btn.closest('.code-box'); - codeBody = box ? box.querySelector('.code-body') : null; - } - const rawCode = codeBody ? codeBody.textContent : ""; - if (!rawCode || !rawCode.trim()) { showToast("❌ No code found to run."); return; } - - window.__lastPlayedHtml = langType === 'python' ? window.buildPythonEnvironment(rawCode) : rawCode; - - const frame = document.getElementById('htmlPlayFrame'); - if (frame) frame.srcdoc = window.__lastPlayedHtml; - document.getElementById('htmlPlayModal').style.display = 'flex'; - } catch (e) { - console.error("playHtmlCode failed:", e); - showToast("❌ Couldn't run this snippet."); - } - }; - - function closeHtmlPlayModal() { - document.getElementById('htmlPlayModal').style.display = 'none'; - const frame = document.getElementById('htmlPlayFrame'); - if (frame) frame.srcdoc = "about:blank"; - } - function openHtmlPreviewInNewTab() { - const html = window.__lastPlayedHtml || ""; - const blob = new Blob([html], { type: 'text/html' }); - const url = URL.createObjectURL(blob); - window.open(url, '_blank'); - setTimeout(() => URL.revokeObjectURL(url), 60000); - } - - const renderer = new marked.Renderer(); - renderer.code = function(code, language) { - let safeCode = code.replace(/&/g, '&').replace(//g, '>').trim(); - const lang = (language || "").toLowerCase().trim(); - const looksRunnableHtml = /<\/?(html|body|div|button|script|style|p|h[1-6]|form|input|table|ul|li|span|a|img|section)\b/i.test(code); - const isPython = lang === 'python' || lang === 'py'; - - let playBtnStr = ''; - if (lang === 'html' || lang === 'htm' || looksRunnableHtml) { - playBtnStr = ``; - } else if (isPython) { - playBtnStr = ``; - } - - return `
${playBtnStr}
${safeCode}
`; - }; - marked.setOptions({ renderer: renderer }); - function copyCodeEngine(btn) { navigator.clipboard.writeText(btn.parentElement.nextElementSibling.innerText); btn.innerText = "✅ Copied"; btn.style.background = "#10b981"; setTimeout(() => { btn.innerText = "📋 Copy"; btn.style.background = "var(--input-bg)"; }, 2000); showToast("Code Copied!"); } - -// ========================================================================== - // 🔊 GOOGLE GEMINI CACHED AUDIO ENGINE (CLEAN VERSION - NO FAKE HIGHLIGHTS) - // ========================================================================== - let stdAudioCtx = null; - let stdScheduledNodes = []; - let stdCachedPCM = new Float32Array(0); - let stdIsFullyDownloaded = false; - let stdAbortController = null; - let stdPlayOffset = 0; // seconds - let stdAudioStartTime = 0; // context time - let stdIsPlaying = false; - - let stdTotalDuration = 0; - let stdBufferedDuration = 0; - let stdCurrentTextId = ""; - let stdTickInterval = null; - let stdPlaybackRate = 1.0; - let stdIsBuffering = false; - - let ttsTextChunks = []; - let currentTtsChunkIndex = 0; - let isFetchingChunk = false; - let stdNextChunkStartTime = 0; - - window.__ttsCache = window.__ttsCache || {}; - - function formatTime(secs) { - if (isNaN(secs) || secs < 0) return "0:00"; - let m = Math.floor(secs / 60); - let s = Math.floor(secs % 60); - return `${m}:${s < 10 ? '0' : ''}${s}`; - } - - function cleanTextForGoogleTTS(targetElement) { - const clone = targetElement.cloneNode(true); - clone.querySelectorAll('button, .code-box, pre, .msg-actions-outer, .quick-suggestions-wrap, .inline-source-badge, .inline-cite, svg, .mermaid, .ai-file-card-box, [id^="sug_"]').forEach(el => el.remove()); - let text = clone.innerText || clone.textContent || ""; - return text - .replace(/\|\|SUGGESTIONS:[\s\S]*?(?:\|\||$)/g, '') - .replace(/<(?:quiz_data|pdf_data|file_data|map_data|svg_data)[\s\S]*?<\/(?:quiz_data|pdf_data|file_data|map_data|svg_data)>/gi, '') - .replace(/https?:\/\/[^\s\)\>]+/g, '') - .replace(/[\*\_\#`%~]+/g, ' ') - .replace(/\s+/g, ' ') - .trim(); - } - - function splitTextIntoChunks(text, maxLength = 260) { - const cleaned = String(text || '').replace(/\r\n/g, '\n').trim(); - if (!cleaned) return []; - // Split on sentence boundaries (. ! ? । or newline) without ever dropping unpunctuated mid-paragraph text! - const rawParts = cleaned - .split(/(?<=[.!?।])\s+|\n+/g) - .map(s => s.trim()) - .filter(Boolean); - - const pieces = []; - for (const part of rawParts) { - if (part.length <= maxLength) { - pieces.push(part); - } else { - // Further split long sentences on commas/semicolons/dashes or word boundaries so Gemini TTS never truncates a long sentence - const subParts = part.split(/(?<=[,;:\u2014\-])\s+/g); - let subAcc = ""; - for (const sp of subParts) { - if (sp.length > maxLength) { - if (subAcc) { pieces.push(subAcc.trim()); subAcc = ""; } - const words = sp.split(/\s+/); - let wAcc = ""; - for (const w of words) { - if ((wAcc + " " + w).trim().length > maxLength) { - if (wAcc) pieces.push(wAcc.trim()); - wAcc = w; - } else { - wAcc = (wAcc + " " + w).trim(); - } - } - if (wAcc) subAcc = wAcc; - } else if ((subAcc + " " + sp).trim().length > maxLength) { - if (subAcc) pieces.push(subAcc.trim()); - subAcc = sp; - } else { - subAcc = (subAcc + " " + sp).trim(); - } - } - if (subAcc) pieces.push(subAcc.trim()); - } - } - - const chunks = []; - let currentChunk = ""; - for (const piece of pieces) { - if (!currentChunk) { - currentChunk = piece; - } else if ((currentChunk + " " + piece).length <= maxLength) { - currentChunk += " " + piece; - } else { - chunks.push(currentChunk.trim()); - currentChunk = piece; - } - } - if (currentChunk) chunks.push(currentChunk.trim()); - return chunks.length ? chunks : [cleaned]; - } - - window.playAudio = async function(btn) { - const textId = btn.getAttribute('data-target'); - const textEl = document.getElementById(textId); - if (!textEl) return; - - stopAudio(); - - document.getElementById("appTopbar").classList.add("hidden"); - document.getElementById("appInputArea").classList.add("hidden"); - document.getElementById("premiumAudioPlayer").style.display = "flex"; - - const playBtn = document.getElementById("premiumAudioToggle"); - playBtn.innerText = "⏳"; - - stdPlaybackRate = parseFloat(document.getElementById("audioSpeed").value || 1.0); - stdCurrentTextId = textId; - stdScheduledNodes = []; - stdPlayOffset = 0; - - let cleanText = cleanTextForGoogleTTS(textEl); - if (!cleanText) { showToast("❌ No readable text."); stopAudio(); return; } - - // 🚀 ESTIMATE TOTAL DURATION - let rawCharCount = cleanText.length; - stdTotalDuration = Math.max(2, rawCharCount / 17); // Fixed accurate time estimate - - stdAudioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 24000 }); - if (stdAudioCtx.state === 'suspended') await stdAudioCtx.resume(); - stdAudioStartTime = stdAudioCtx.currentTime; - stdIsPlaying = true; - stdIsBuffering = true; - - clearInterval(stdTickInterval); - stdTickInterval = setInterval(syncStandardAudioTick, 50); - - if (window.__ttsCache[textId] && window.__ttsCache[textId].isFullyDownloaded) { - stdCachedPCM = window.__ttsCache[textId].pcmData; - stdBufferedDuration = window.__ttsCache[textId].duration; - stdTotalDuration = stdBufferedDuration; - stdIsFullyDownloaded = true; - stdIsBuffering = false; - playBtn.innerHTML = "⏸"; - playFromBuffer(0); - } else { - ttsTextChunks = splitTextIntoChunks(cleanText, 260); - currentTtsChunkIndex = 0; - stdCachedPCM = new Float32Array(0); - stdBufferedDuration = 0; - stdIsFullyDownloaded = false; - stdNextChunkStartTime = stdAudioCtx.currentTime + 0.1; - stdAbortController = new AbortController(); - fetchNextTtsChunk(); - } - }; - - // 🚀 FETCHES ALL PARAGRAPH CHUNKS BACK-TO-BACK SEAMLESSLY WITHOUT SKIPPING - async function fetchNextTtsChunk() { - if (currentTtsChunkIndex >= ttsTextChunks.length || isFetchingChunk || stdIsFullyDownloaded) { - if (currentTtsChunkIndex >= ttsTextChunks.length) { - stdIsFullyDownloaded = true; - stdTotalDuration = Math.max(stdBufferedDuration, 0.5); - window.__ttsCache[stdCurrentTextId] = { - pcmData: stdCachedPCM, - isFullyDownloaded: true, - duration: stdBufferedDuration - }; - } - return; - } - - isFetchingChunk = true; - if (stdCachedPCM.length === 0) { - stdIsBuffering = true; - document.getElementById("premiumAudioToggle").innerHTML = `⚙️`; - } - - let textToSpeak = ttsTextChunks[currentTtsChunkIndex]; - - try { - let audioBytes = null; - for (let attempt = 0; attempt < 3 && !audioBytes; attempt++) { - try { - const response = await fetch(API_BASE + "/api/gemini-tts", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ text: textToSpeak }), - signal: stdAbortController.signal - }); - if (!response.ok) throw new Error("TTS Chunk Failed"); - const buf = new Uint8Array(await response.arrayBuffer()); - if (buf.length < 200 && attempt < 2) throw new Error("empty audio"); - audioBytes = buf; - } catch (e) { - if (e.name === 'AbortError') throw e; - await new Promise(r => setTimeout(r, 400)); - } - } - if (!audioBytes) throw new Error("TTS chunk " + (currentTtsChunkIndex + 1) + " failed"); - - if (stdIsBuffering) { - stdIsBuffering = false; - document.getElementById("premiumAudioToggle").innerText = "⏸"; - } - - const numSamples = Math.floor(audioBytes.length / 2); - if (numSamples > 0) { - const aligned = audioBytes.buffer.slice(audioBytes.byteOffset, audioBytes.byteOffset + numSamples * 2); - const pcm16View = new Int16Array(aligned); - const float32Data = new Float32Array(numSamples); - for (let i = 0; i < numSamples; i++) float32Data[i] = pcm16View[i] / 32768.0; - - const prevSamples = stdCachedPCM.length; - let newCache = new Float32Array(prevSamples + float32Data.length); - newCache.set(stdCachedPCM); - newCache.set(float32Data, prevSamples); - stdCachedPCM = newCache; - stdBufferedDuration = stdCachedPCM.length / 24000; - if (stdBufferedDuration > stdTotalDuration) stdTotalDuration = stdBufferedDuration; - - if (stdIsPlaying && stdAudioCtx) { - const audioBuffer = stdAudioCtx.createBuffer(1, numSamples, 24000); - audioBuffer.getChannelData(0).set(float32Data); - const sourceNode = stdAudioCtx.createBufferSource(); - sourceNode.buffer = audioBuffer; - sourceNode.playbackRate.value = stdPlaybackRate; - sourceNode.connect(stdAudioCtx.destination); - const playbackTime = Math.max(stdAudioCtx.currentTime + 0.02, stdNextChunkStartTime); - if (prevSamples === 0) { - stdPlayOffset = 0; - stdAudioStartTime = playbackTime; - } - sourceNode.start(playbackTime); - stdScheduledNodes.push(sourceNode); - stdNextChunkStartTime = playbackTime + (audioBuffer.duration / stdPlaybackRate); - } - } - - currentTtsChunkIndex++; - isFetchingChunk = false; - - if (currentTtsChunkIndex >= ttsTextChunks.length) { - stdIsFullyDownloaded = true; - stdTotalDuration = Math.max(stdBufferedDuration, 0.5); - window.__ttsCache[stdCurrentTextId] = { - pcmData: stdCachedPCM, - isFullyDownloaded: true, - duration: stdBufferedDuration - }; - } else if (!stdAbortController || !stdAbortController.signal.aborted) { - // Immediately prefetch the next sentence/paragraph chunk so there is zero gap or cut-off! - setTimeout(fetchNextTtsChunk, 15); - } - } catch(err) { - isFetchingChunk = false; - if (err.name !== 'AbortError') { showToast("❌ Stream Interrupted. " + err.message); } - } - } - - function playFromBuffer(offsetSeconds) { - stdScheduledNodes.forEach(node => { try { node.stop(); } catch(e){} }); - stdScheduledNodes = []; - - if (stdCachedPCM.length === 0) return; - - const sampleOffset = Math.floor(offsetSeconds * 24000); - if (sampleOffset >= stdCachedPCM.length) return; - - const float32Data = stdCachedPCM.slice(sampleOffset); - const audioBuffer = stdAudioCtx.createBuffer(1, float32Data.length, 24000); - audioBuffer.getChannelData(0).set(float32Data); - - const sourceNode = stdAudioCtx.createBufferSource(); - sourceNode.buffer = audioBuffer; - sourceNode.playbackRate.value = stdPlaybackRate; - sourceNode.connect(stdAudioCtx.destination); - - sourceNode.start(stdAudioCtx.currentTime); - stdScheduledNodes.push(sourceNode); - - stdPlayOffset = offsetSeconds; - stdAudioStartTime = stdAudioCtx.currentTime; - - // Recalculate where new chunks should inject - stdNextChunkStartTime = stdAudioCtx.currentTime + (audioBuffer.duration / stdPlaybackRate); - } - - window.toggleAudio = function() { - const btn = document.getElementById("premiumAudioToggle"); - if (!stdAudioCtx || stdIsBuffering) return; - - if (stdAudioCtx.state === 'running') { - stdAudioCtx.suspend(); - stdIsPlaying = false; - btn.innerHTML = "▶"; - } else if (stdAudioCtx.state === 'suspended') { - stdAudioCtx.resume(); - stdIsPlaying = true; - btn.innerHTML = "⏸"; - } - }; - - window.changeAudioSpeed = function() { - stdPlaybackRate = parseFloat(document.getElementById("audioSpeed").value || 1.0); - stdScheduledNodes.forEach(node => { - try { node.playbackRate.value = stdPlaybackRate; } catch(e){} - }); - }; - - window.seekAudio = function(e) { - if (!stdAudioCtx) return; - const bar = document.getElementById("audioProgressBar"); - const rect = bar.getBoundingClientRect(); - const percent = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); - - const targetTime = percent * stdTotalDuration; - - if (targetTime > stdBufferedDuration && !stdIsFullyDownloaded) { - // User scrubbed ahead into undownloaded territory! - stdIsBuffering = true; - document.getElementById("premiumAudioToggle").innerHTML = `⚙️`; - - stdScheduledNodes.forEach(node => { try { node.stop(); } catch(e){} }); - stdScheduledNodes = []; - stdPlayOffset = targetTime; - - let checkInt = setInterval(() => { - if (!stdIsBuffering) { clearInterval(checkInt); return; } - if (stdBufferedDuration > targetTime || stdIsFullyDownloaded) { - clearInterval(checkInt); - stdIsBuffering = false; - document.getElementById("premiumAudioToggle").innerHTML = stdIsPlaying ? "⏸" : "▶"; - if (stdIsPlaying) playFromBuffer(targetTime); - } - }, 100); - } else { - let actualTarget = Math.min(targetTime, stdBufferedDuration); - if (stdIsPlaying) { - playFromBuffer(actualTarget); - } else { - stdPlayOffset = actualTarget; - stdAudioStartTime = stdAudioCtx.currentTime; - } - } - document.getElementById("audioProgressFill").style.width = (percent * 100) + "%"; - }; - - window.stopAudio = function() { - if (stdAbortController) stdAbortController.abort(); - if (stdAudioCtx) { try { stdAudioCtx.close(); } catch(e){} stdAudioCtx = null; } - clearInterval(stdTickInterval); - stdIsPlaying = false; - document.getElementById("premiumAudioPlayer").style.display = "none"; - document.getElementById("appTopbar").classList.remove("hidden"); - document.getElementById("appInputArea").classList.remove("hidden"); - - document.querySelectorAll('.tts-word-highlight').forEach(el => { - el.style.backgroundColor = "transparent"; - el.style.color = "inherit"; - }); - }; - - function syncStandardAudioTick() { - if (!stdAudioCtx || !stdIsPlaying || stdIsBuffering) return; - - const currentRealTime = stdAudioCtx.currentTime - stdAudioStartTime; - let currentAudioTime = stdPlayOffset + (currentRealTime * stdPlaybackRate); - if (currentAudioTime > stdBufferedDuration) currentAudioTime = Math.max(stdBufferedDuration, 0); - - if (!stdIsFullyDownloaded && !isFetchingChunk) { - if ((stdBufferedDuration - currentAudioTime) < 45) fetchNextTtsChunk(); - } - - const duration = Math.max(stdTotalDuration, 0.1); - let progress = currentAudioTime / duration; - if (progress > 1) progress = 1; - - document.getElementById("audioCurrentTime").innerText = formatTime(currentAudioTime); - document.getElementById("audioTotalTime").innerText = formatTime(duration); - document.getElementById("audioProgressFill").style.width = (progress * 100) + "%"; - - if (stdIsFullyDownloaded && stdAudioCtx.currentTime >= stdNextChunkStartTime - 0.03) { // really finished playing the LAST scheduled chunk - stopAudio(); - document.getElementById("premiumAudioToggle").innerText = "▶"; - } - } - - function copyText(btn) { navigator.clipboard.writeText(document.getElementById(btn.getAttribute('data-target')).innerText); btn.innerHTML = "✅"; setTimeout(() => btn.innerHTML = "📋", 1500); showToast("Text Copied!"); } - - // 🎛️ Single source of truth for the icon-only action row under every AI - // message (outside the bubble). Used by both the live response flow and - // restoreSession so they never drift out of sync with each other. - function buildMsgActionsBar(lId, textId, hasSources, tutorButtonHtml, hasThinking) { - hidePreviousFeedbackButtons(); // only the newest message shows like/unlike - const showBrain = (hasThinking !== undefined) - ? Boolean(hasThinking) - : Boolean(window.__getThoughts && window.__getThoughts(lId) && String(window.__getThoughts(lId)).trim()); - return ` -
- - - - ${showBrain ? `` : ''} - ${hasSources ? `` : ''} - ${tutorButtonHtml || ''} - - - - - - -
`; - } - - // Only the latest AI message shows like/unlike - hide the feedback - // group (not the whole action bar, copy/listen/delete stay) on all others. - function hidePreviousFeedbackButtons() { - document.querySelectorAll('.feedback-group').forEach(el => el.style.display = 'none'); - } - -// 🧠 Dynamically calls the AI to EXPLAIN its thought process for the specific answer - window.openThinkingModal = async function(loadId) { - const msgNode = document.getElementById(loadId); - if (!msgNode) return; - - // 1. Extract which API provider was used - let providerText = "Gemini API"; - const headerNode = msgNode.querySelector('div[style*="font-size:10px"]'); - if (headerNode) { - const fullText = headerNode.innerText || ""; - const match = fullText.match(/(?:VIA|SECURED VIA)\s+([^(]+(?:\([^)]+\))?)/i); - if (match && match[1]) providerText = match[1].trim(); - else providerText = fullText.replace(/✨\s*(?:SECURED\s*)?VIA\s*/i, '').trim() || "Gemini API"; - } - - // 2. Extract the User's Question and AI's Answer from the chat history - const userNode = msgNode.previousElementSibling; - let questionText = "User Question"; - if (userNode && userNode.classList.contains('chat-user')) { - let clone = userNode.cloneNode(true); - clone.querySelectorAll('.msg-actions-outer, .user-attachment-badge, img').forEach(el => el.remove()); - questionText = clone.innerText.trim(); - } - - let answerText = "AI Answer"; - const textEl = document.getElementById('txt_' + loadId); - if (textEl) answerText = textEl.innerText.trim(); - - // 3. Render the exact UI layout you requested - let modalOverlay = document.getElementById('thinkingStepsModal'); - if (!modalOverlay) { - modalOverlay = document.createElement('div'); - modalOverlay.id = 'thinkingStepsModal'; - modalOverlay.className = 'modal-overlay'; - modalOverlay.style.zIndex = '9999999'; - document.body.appendChild(modalOverlay); - } - - modalOverlay.innerHTML = ` - - `; - modalOverlay.style.display = 'flex'; - - // Click outside to close - modalOverlay.onclick = function(e) { - if (e.target === modalOverlay) modalOverlay.remove(); - }; - - // 4. Show the REAL thinking captured while the answer was generated (no extra API call) - const __t = window.__getThoughts(loadId); - document.getElementById('dynamicThinkingContent').innerHTML = __t - ? window.__fmtThoughts(__t) - : 'No thinking summary came back for this answer. Greetings and tiny questions skip thinking. If it happens on real questions, make sure you restarted the updated server.js.'; - }; - // 🗑️ Removes this AI response AND the user question right before it, from - // both the screen and saved local history. - window.__deletedMsgIds = new Set(); // 🚀 Global Ghost-Buster - window.deleteMessage = function(lId, skipConfirm = false) { - const aiNode = document.getElementById(lId); - if (!aiNode) return; - if (!skipConfirm && !confirm("Delete this question and its answer?")) return; - - window.__deletedMsgIds.add(lId); // 🚀 Mark as permanently deleted - - const userNode = aiNode.previousElementSibling; - let userActionsNode = null; - let userMsgNode = userNode; - if (userNode && userNode.classList && userNode.classList.contains('msg-actions-outer')) { - userActionsNode = userNode; - userMsgNode = userNode.previousElementSibling; - } - - try { - if (Array.isArray(appHistory)) { - appHistory.forEach(session => { - if (!Array.isArray(session.interactions)) return; - session.interactions = session.interactions.filter(it => it.id !== lId); - }); - appHistory = appHistory.filter(session => Array.isArray(session.interactions) && session.interactions.length > 0); - saveHistorySafe(); - } - } catch (e) {} - - aiNode.remove(); - if (userActionsNode) userActionsNode.remove(); - if (userMsgNode && userMsgNode.classList && userMsgNode.classList.contains('chat-user')) userMsgNode.remove(); - if (!window.__quietDelete) showToast("🗑️ Deleted"); - // If the chat is now completely empty, show the start/welcome screen again. - const chatHistoryEl = document.getElementById("searchChatHistory"); - if (chatHistoryEl && !chatHistoryEl.querySelector('.chat-msg')) { - chatHistoryEl.innerHTML = `
✨ SYSTEM ONLINE
Ready for new questions.
`; - } - } - - // 👍👎 Sends feedback via WhatsApp using the existing /api/feedback route. - // Both buttons disappear for this message right after one is clicked. - async function sendMessageFeedback(lId, type) { - const group = document.getElementById('feedbackGroup_' + lId); - if (group) group.innerHTML = `${type === 'like' ? '👍' : '👎'} Thanks!`; - - const textEl = document.getElementById('txt_' + lId); - const snippet = textEl ? textEl.innerText.slice(0, 400) : ""; - const feedbackMsg = `${type === 'like' ? '👍 Liked' : '👎 Disliked'} a response:\n\n${snippet}`; - - try { - await fetch(API_BASE + '/api/feedback', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message: feedbackMsg }) - }); - } catch (e) { /* best-effort - still thank the user below */ } - showToast("🙏 Thanks for your feedback!"); - } - - let currentFullscreenImage = ""; - function openFullImage(src) { - currentFullscreenImage = src; - document.getElementById('fullImageSrc').src = src; - document.getElementById('fullImageViewer').style.display = 'flex'; - resetImageZoom(); - setupImageZoomHandlers(); - } - - // 📥 Cross-origin images (e.g. from Google Search results) were only - // ever "downloading" as an open-in-new-tab, because browsers ignore - // the download attribute on cross-origin links. Fetch as a blob - // instead so it actually saves - falling back to opening it if the - // source site blocks the fetch (CORS). - async function downloadFullImage() { - const src = currentFullscreenImage; - if (!src) return; - if (src.startsWith('data:')) { - const a = document.createElement("a"); - a.href = src; a.download = `DEEP_SEARCH_${Date.now()}.png`; - document.body.appendChild(a); a.click(); document.body.removeChild(a); - showToast("📥 Download Started!"); - return; - } - showToast("📥 Preparing download..."); - try { - const response = await fetch(src); - if (!response.ok) throw new Error("fetch failed"); - const blob = await response.blob(); - const blobUrl = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = blobUrl; a.download = `DEEP_SEARCH_${Date.now()}.jpg`; - document.body.appendChild(a); a.click(); document.body.removeChild(a); - setTimeout(() => URL.revokeObjectURL(blobUrl), 30000); - showToast("📥 Download Started!"); - } catch (e) { - showToast("⚠️ This site blocks direct downloads - opening the image, use 'Save Image As'."); - window.open(src, '_blank'); - } - } - - // 🔍 Zoom: scroll wheel, double-click/double-tap, and pinch (touch) - let __imgZoomScale = 1; - function resetImageZoom() { - __imgZoomScale = 1; - const img = document.getElementById('fullImageSrc'); - if (img) { img.style.transform = 'scale(1)'; img.style.transition = 'transform 0.2s ease'; img.style.cursor = 'zoom-in'; } - } - function setupImageZoomHandlers() { - const img = document.getElementById('fullImageSrc'); - if (!img || img.dataset.zoomBound === '1') return; - img.dataset.zoomBound = '1'; - - img.addEventListener('wheel', (e) => { - e.preventDefault(); - __imgZoomScale = Math.min(5, Math.max(1, __imgZoomScale + (e.deltaY < 0 ? 0.3 : -0.3))); - img.style.transform = `scale(${__imgZoomScale})`; - img.style.cursor = __imgZoomScale > 1 ? 'zoom-out' : 'zoom-in'; - }, { passive: false }); - - img.addEventListener('dblclick', () => { - __imgZoomScale = __imgZoomScale > 1 ? 1 : 2.5; - img.style.transform = `scale(${__imgZoomScale})`; - img.style.cursor = __imgZoomScale > 1 ? 'zoom-out' : 'zoom-in'; - }); - - let lastTouchDist = null; - img.addEventListener('touchmove', (e) => { - if (e.touches.length === 2) { - e.preventDefault(); - const dx = e.touches[0].clientX - e.touches[1].clientX; - const dy = e.touches[0].clientY - e.touches[1].clientY; - const dist = Math.hypot(dx, dy); - if (lastTouchDist) { - __imgZoomScale = Math.min(5, Math.max(1, __imgZoomScale + (dist - lastTouchDist) * 0.01)); - img.style.transform = `scale(${__imgZoomScale})`; - } - lastTouchDist = dist; - } - }, { passive: false }); - img.addEventListener('touchend', (e) => { if (e.touches.length < 2) lastTouchDist = null; }); - } - - // 🖼️ "View All Images" gallery - every image compared during a Google - // Search image generation, not just the one Gemini picked as best. - window.__imageGalleries = window.__imageGalleries || {}; - window.openImageGallery = function(galleryId) { - const urls = window.__imageGalleries[galleryId] || []; - const grid = document.getElementById('imageGalleryGrid'); - const title = document.getElementById('imageGalleryTitle'); - if (!grid) return; - if (title) title.innerText = `🖼️ All ${urls.length} Images Found`; - grid.innerHTML = urls.map(url => { - const safeUrl = String(url).replace(/"/g, '"'); - return `
- -
`; - }).join(''); - document.getElementById('imageGalleryModal').style.display = 'flex'; - }; - - function togglePhotoMode() { isPhotoMode = !isPhotoMode; document.getElementById("photoModeChip").style.display = isPhotoMode ? "flex" : "none"; document.getElementById("photoModeMenuBtn").innerText = isPhotoMode ? "🎨 Turn Off Photo Gen" : "🎨 Turn On Photo Gen"; if(isPhotoMode) { isYoutubeMode = false; document.getElementById("ytModeChip").style.display = "none"; showToast("Photo Gen Ready"); } closePlusMenu(); } - function toggleYoutubeMode() { isYoutubeMode = !isYoutubeMode; document.getElementById("ytModeChip").style.display = isYoutubeMode ? "flex" : "none"; if(isYoutubeMode) { isPhotoMode = false; document.getElementById("photoModeChip").style.display = "none"; showToast("YouTube Mode Ready"); } closePlusMenu(); } - function toggleFocus() { const topBar = document.getElementById('appTopbar'); const inputArea = document.getElementById('appInputArea'); const exitBtn = document.getElementById('exitFocusBtn'); const isFocus = topBar.style.display !== 'none'; topBar.style.display = isFocus ? 'none' : 'flex'; inputArea.style.transform = isFocus ? 'translateY(200%)' : 'translateY(0)'; exitBtn.style.display = isFocus ? 'flex' : 'none'; document.getElementById('settingsModal').style.display = 'none'; showToast(isFocus ? "Focus Mode ON" : "Focus Mode OFF"); } -function clearSearchChat() { - document.getElementById("searchChatHistory").innerHTML = `
✨ SYSTEM ONLINE
Memory Cleared. Ready for new questions.
`; - documentMemory = ""; - webUrls = []; - uploadedImagesList = []; - updateImageUI(); - clearAttachment(true); - document.getElementById('settingsModal').style.display = 'none'; - - // 🚨 FIX: Wipe the old PTI token here too! - currentPti = null; - currentSessionId = Date.now(); - window.history.replaceState({}, document.title, window.location.pathname); - - showToast("Memory Wiped Clean."); - } - - async function openCamera() { closePlusMenu(); document.getElementById('cameraModal').style.display='flex'; try { if(camStream) camStream.getTracks().forEach(t => t.stop()); camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: camFacing, width: {ideal: 1920}, height: {ideal: 1080} } }); document.getElementById("cameraVideo").srcObject = camStream; setTimeout(async () => { const track = camStream.getVideoTracks()[0]; if (track.getCapabilities().torch && camFacing === "environment") { isFlash = true; await track.applyConstraints({ advanced: [{ torch: true }] }); document.getElementById('flashBtn').innerText = "💡"; } }, 500); } catch(e) { alert("Camera Error."); document.getElementById('cameraModal').style.display='none'; } } - function closeCamera() { document.getElementById('cameraModal').style.display='none'; if(camStream) camStream.getTracks().forEach(t=>t.stop()); isFlash=false; } - async function switchCamera() { camFacing = camFacing === "environment" ? "user" : "environment"; await openCamera(); } - async function toggleFlash() { if(!camStream) return; const track = camStream.getVideoTracks()[0]; if(track.getCapabilities().torch) { isFlash = !isFlash; await track.applyConstraints({ advanced: [{ torch: isFlash }] }); document.getElementById('flashBtn').innerText = isFlash ? "💡" : "🔦"; } } - function takePhoto() { if(uploadedImagesList.length >= 20) return showToast("❌ Max 20 images allowed!"); const v = document.getElementById("cameraVideo"), c = document.getElementById("captureCanvas"); c.width = v.videoWidth; c.height = v.videoHeight; c.getContext("2d").drawImage(v, 0, 0, c.width, c.height); uploadedImagesList.push(c.toDataURL("image/jpeg", 0.7)); documentMemory = ""; updateImageUI(); closeCamera(); showToast("Photo Added!"); } - - function openWebImport() { closePlusMenu(); document.getElementById('webImportModal').style.display = 'flex'; } - function saveWebUrls() { let text = document.getElementById('webUrlInput').value.trim(); if (text) { webUrls = [text]; document.getElementById("attachmentChip").style.display = "flex"; document.getElementById("attachName").innerText = `🌐 URL Linked`; windowUploadedFileName = "🌐 Web Link"; } document.getElementById('webImportModal').style.display = 'none'; document.getElementById('webUrlInput').value = ''; } - - // ========================================================================== - // 📎 MULTI-DOCUMENT ATTACHMENT ENGINE - // Rewritten to: support several files at once, raise the PDF cap from a hard - // 25 pages to 200, use type-aware size ceilings instead of one blanket 7.5MB - // rule, show live per-page progress, and let you pick a page range or preview - // exactly what got extracted before you ask your question. - // ========================================================================== - let attachedDocsList = []; // [{ name, content, pages, pageTexts, fromPage, toPage }] - const MAX_ATTACHED_DOCS = 5; - const DOC_MEMORY_CHAR_CAP = 200000; // kept in sync with the substring cap in handleTextSearch - - function rebuildDocumentMemory() { - const docParts = attachedDocsList.map(d => - `\n\n===== 📄 FILE: ${d.name} =====\n` + - (d.aiSummary ? `[GEMINI SCAN SUMMARY]\n${d.aiSummary}\n[/GEMINI SCAN SUMMARY]\n\n` : "") + - d.content); - const imgParts = []; - (uploadedImagesList || []).forEach(img => { - const ins = window.__imageInsights && window.__imageInsights.get(img); - if (ins) imgParts.push(`\n\n===== 🖼️ IMAGE: ${ins.name} =====\n[GEMINI IMAGE SCAN]\n${ins.text}`); - }); - documentMemory = docParts.concat(imgParts).join('\n').trim(); - } - - function refreshAttachmentChipUI() { - const chip = document.getElementById("attachmentChip"); - const nameEl = document.getElementById("attachName"); - if (attachedDocsList.length === 0) { if(!webUrls.length) chip.style.display = "none"; return; } - chip.style.display = "flex"; - nameEl.innerText = attachedDocsList.length === 1 ? truncName(attachedDocsList[0].name, 30) : `${attachedDocsList.length} files attached`; - nameEl.title = attachedDocsList.map(d => d.name).join(", "); - windowUploadedFileName = attachedDocsList.map(d => d.name).join(", "); - } - - function setPdfProgress(text) { - setDocDetail(String(text || "").replace(/^⏳\s*/, "")); - } - - // 📥 Drag-and-drop: dragging any file over the page shows an overlay; - // dropping it attaches it the same way the file picker does. - let __dragCounter = 0; - window.addEventListener('dragenter', (e) => { - if (!e.dataTransfer || !e.dataTransfer.types || !e.dataTransfer.types.includes('Files')) return; - e.preventDefault(); - __dragCounter++; - const overlay = document.getElementById('dragDropOverlay'); - if (overlay) overlay.style.display = 'flex'; - }); - window.addEventListener('dragover', (e) => { - if (!e.dataTransfer || !e.dataTransfer.types || !e.dataTransfer.types.includes('Files')) return; - e.preventDefault(); - }); - window.addEventListener('dragleave', (e) => { - __dragCounter = Math.max(0, __dragCounter - 1); - if (__dragCounter === 0) { - const overlay = document.getElementById('dragDropOverlay'); - if (overlay) overlay.style.display = 'none'; - } - }); - window.addEventListener('drop', async (e) => { - if (!e.dataTransfer || !e.dataTransfer.files || e.dataTransfer.files.length === 0) return; - e.preventDefault(); - __dragCounter = 0; - const overlay = document.getElementById('dragDropOverlay'); - if (overlay) overlay.style.display = 'none'; - if (e.__dropHandled) return; // the document-level drop handler already took these files (it handles images + files) - window.enqueueFiles(Array.from(e.dataTransfer.files)); - }); - - async function handleFileUpload(e) { - const files = Array.from(e.target.files || []); - if (files.length === 0) return; - closePlusMenu(); - window.enqueueFiles(files); // processed one-by-one, status shown for each - e.target.value = ""; - } - - - // Pulls plain text out of .docx / .pptx / .xlsx (they are ZIPs of XML) - async function extractOfficeText(file) { - const zip = await JSZip.loadAsync(file); - const ext = file.name.toLowerCase().split('.').pop(); - const parseXml = (str) => new DOMParser().parseFromString(str, "application/xml"); - const paras = (xmlStr, pTag, tTag) => { - const doc = parseXml(xmlStr); - return Array.from(doc.getElementsByTagName(pTag)).map(p => - Array.from(p.getElementsByTagName(tTag)).map(t => t.textContent).join('') - ).filter(Boolean).join('\n'); - }; - if (ext === 'docx') { - const f = zip.file('word/document.xml'); - if (!f) throw new Error("Not a valid .docx file"); - return paras(await f.async('string'), 'w:p', 'w:t'); - } - if (ext === 'pptx') { - const names = Object.keys(zip.files).filter(n => /^ppt\/slides\/slide\d+\.xml$/.test(n)) - .sort((a, b) => parseInt(a.match(/(\d+)\.xml/)[1]) - parseInt(b.match(/(\d+)\.xml/)[1])); - if (!names.length) throw new Error("Not a valid .pptx file"); - const out = []; - for (let i = 0; i < names.length; i++) { - out.push(`--- Slide ${i + 1} ---\n` + paras(await zip.file(names[i]).async('string'), 'a:p', 'a:t')); - } - return out.join('\n\n'); - } - // xlsx - const shared = []; - const ss = zip.file('xl/sharedStrings.xml'); - if (ss) { - Array.from(parseXml(await ss.async('string')).getElementsByTagName('si')).forEach(si => { - shared.push(Array.from(si.getElementsByTagName('t')).map(t => t.textContent).join('')); - }); - } - const sheets = Object.keys(zip.files).filter(n => /^xl\/worksheets\/sheet\d+\.xml$/.test(n)) - .sort((a, b) => parseInt(a.match(/(\d+)\.xml/)[1]) - parseInt(b.match(/(\d+)\.xml/)[1])); - if (!sheets.length) throw new Error("Not a valid .xlsx file"); - const out = []; - for (let i = 0; i < sheets.length; i++) { - const doc = parseXml(await zip.file(sheets[i]).async('string')); - const rows = Array.from(doc.getElementsByTagName('row')).map(r => - Array.from(r.getElementsByTagName('c')).map(c => { - const t = c.getAttribute('t'); - const v = c.getElementsByTagName('v')[0]; - if (t === 's' && v) return shared[parseInt(v.textContent)] || ''; - if (t === 'inlineStr') return Array.from(c.getElementsByTagName('t')).map(x => x.textContent).join(''); - return v ? v.textContent : ''; - }).join(' | ') - ).filter(r => r.replace(/[\s|]/g, '')); - out.push(`--- Sheet ${i + 1} ---\n` + rows.join('\n')); - } - return out.join('\n\n'); - } - - function processOneUploadedFile(file) { - return new Promise((resolve) => { - const isImage = file.type.startsWith('image/'); - const isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'); - // Type-aware ceilings: a PDF only ever contributes extracted TEXT downstream, so it - // can safely be far larger than an image, which gets embedded whole as base64. - const sizeCapMB = isImage ? 10 : (isPdf ? 40 : 8); - if (file.size > sizeCapMB * 1024 * 1024) { - showToast(`❌ "${truncName(file.name, 30)}" is too large. Max ${sizeCapMB}MB for this file type.`, "error"); - return resolve(); - } - - if (isImage) { - if (uploadedImagesList.length >= 20) { showToast("❌ Max 20 images!", "error"); return resolve(); } - const r = new FileReader(); - r.onload = (ev) => { uploadedImagesList.push(ev.target.result); updateImageUI(); showToast(`Image added: ${truncName(file.name, 30)}`, "success"); resolve(); }; - r.onerror = () => { showToast(`❌ Could not read ${truncName(file.name, 30)}`, "error"); resolve(); }; - r.readAsDataURL(file); - } - else if (file.name.toLowerCase().endsWith('.zip')) { - if(typeof JSZip === 'undefined') { showToast("❌ ZIP Engine not loaded", "error"); return resolve(); } - setPdfProgress(`⏳ Extracting ${truncName(file.name, 30)}...`); - JSZip.loadAsync(file).then(zip => { - const fileNames = Object.keys(zip.files).filter(name => !zip.files[name].dir); - if (fileNames.length > 5) { - showToast(`❌ ZIP contains ${fileNames.length} files. Max 5 allowed.`, "error"); - return resolve(); - } - let readPromises = fileNames.map(name => { - return zip.files[name].async("string").then(content => { - attachedDocsList.push({ name: name, content: content.trim(), pages: null, pageTexts: null }); - }); - }); - Promise.all(readPromises).then(() => { - rebuildDocumentMemory(); refreshAttachmentChipUI(); - showToast(`✅ Extracted ${fileNames.length} files from ZIP`, "success"); - resolve(); - }); - }).catch(() => { showToast(`❌ Failed to extract ${truncName(file.name, 30)}`, "error"); resolve(); }); - return; - } - else if (isPdf) { - processPdfFile(file, resolve); - } - else if (/\.(docx|pptx|xlsx)$/i.test(file.name)) { - if (attachedDocsList.length >= MAX_ATTACHED_DOCS) { showToast(`❌ Max ${MAX_ATTACHED_DOCS} documents attached at once.`, "error"); return resolve(); } - if (typeof JSZip === 'undefined') { showToast("❌ ZIP/Office engine not loaded", "error"); return resolve(); } - setPdfProgress(`Reading ${truncName(file.name, 30)}...`); - extractOfficeText(file).then(text => { - if (!text || !text.trim()) throw new Error("No readable text found in " + truncName(file.name, 30)); - attachedDocsList.push({ name: file.name, content: text.trim(), pages: null, pageTexts: null }); - rebuildDocumentMemory(); refreshAttachmentChipUI(); - showToast(`✅ ${truncName(file.name, 30)} attached`, "success"); - }).catch(err => showToast("❌ " + err.message, "error")).finally(() => resolve()); - } - else if (/\.(doc|xls|ppt)$/i.test(file.name)) { - showToast(`❌ Old ${file.name.split('.').pop().toUpperCase()} format can't be read. Save it as .docx/.xlsx/.pptx and try again.`, "error"); - return resolve(); - } - else { - if (attachedDocsList.length >= MAX_ATTACHED_DOCS) { showToast(`❌ Max ${MAX_ATTACHED_DOCS} documents attached at once.`, "error"); return resolve(); } - setPdfProgress(`⏳ Reading ${truncName(file.name, 30)}...`); - const r = new FileReader(); - r.onload = (ev) => { - // KEEP THE REAL TEXT. This line used to be .replace(/\s+/g, ' ') which turned every uploaded file (HTML, JS, Python...) - // into ONE giant line: a // comment then swallowed the rest of the code, edits broke, and the AI imitated the one-line style. - const content = String(ev.target.result || "").replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').replace(/\s+$/, ''); - attachedDocsList.push({ name: file.name, content, pages: null, pageTexts: null }); - rebuildDocumentMemory(); refreshAttachmentChipUI(); - showToast(`✅ ${truncName(file.name, 30)} attached`, "success"); - resolve(); - }; - r.onerror = () => { showToast(`❌ Could not read ${truncName(file.name, 30)}`, "error"); resolve(); }; - r.readAsText(file); - } - }); - } - - function processPdfFile(file, resolve) { - if (attachedDocsList.length >= MAX_ATTACHED_DOCS) { showToast(`❌ Max ${MAX_ATTACHED_DOCS} documents attached at once.`, "error"); return resolve(); } - setPdfProgress(`⏳ Opening ${truncName(file.name, 30)}...`); - const r = new FileReader(); - r.onload = async function() { - try { - const typedarray = new Uint8Array(this.result); - const pdf = await pdfjsLib.getDocument(typedarray).promise; - - // 📄 Raised from a hard 25-page wall to 200 — full textbooks/chapters now work. - if (pdf.numPages > 200) { - throw new Error(`"${truncName(file.name, 30)}" is ${pdf.numPages} pages. Max 200 pages per PDF.`); - } - - const pageTexts = []; - for (let i = 1; i <= pdf.numPages; i++) { - const p = await pdf.getPage(i); - const c = await p.getTextContent(); - pageTexts.push(c.items.map(item => item.str).join(' ').replace(/\s+/g, ' ').trim()); - if (i % 5 === 0 || i === pdf.numPages) setPdfProgress(`⏳ Reading page ${i}/${pdf.numPages}...`); - } - - let fullText = pageTexts.join('\n').trim(); - let ocrUsed = false; - if (!fullText) { - if (!AI_SCAN.enabled) throw new Error(`No readable text found inside "${truncName(file.name, 30)}" (scanned image PDF).`); - fullText = await ocrPdfWithGemini(pdf); // scanned PDF -> Gemini reads the pages - ocrUsed = true; - } - - attachedDocsList.push({ name: file.name, content: fullText, pages: ocrUsed ? null : pdf.numPages, pageTexts: ocrUsed ? null : pageTexts, fromPage: 1, toPage: pdf.numPages }); - rebuildDocumentMemory(); refreshAttachmentChipUI(); - - if (documentMemory.length > DOC_MEMORY_CHAR_CAP) { - showToast(`✅ ${truncName(file.name, 30)} processed (${pdf.numPages} pages). It's long — only part fits each question. Tap the attachment to pick a page range.`, "info", 6000); - } else { - showToast(`✅ ${truncName(file.name, 30)} processed (${pdf.numPages} pages)`, "success"); - } - } catch(err) { - showToast("❌ " + err.message, "error"); - } finally { - resolve(); - } - }; - r.onerror = () => { showToast(`❌ Could not read ${truncName(file.name, 30)}`, "error"); resolve(); }; - r.readAsArrayBuffer(file); - } - - function updateImageUI() { const container = document.getElementById("multiImagePreview"); if(!container) return; if(uploadedImagesList.length === 0) { container.style.display = "none"; return; } container.style.display = "flex"; container.innerHTML = uploadedImagesList.map((img, i) => `
`).join(''); } - function removeImage(index) { const gone = uploadedImagesList.splice(index, 1)[0]; if (window.__imageInsights) window.__imageInsights.delete(gone); rebuildDocumentMemory(); updateImageUI(); } - - // 🛠️ FIX: this used to fire "Attachment Cleared" unconditionally — including after every - // single message send, whether or not anything was ever attached. Now it only announces - // itself when there was actually something to clear, and internal/automatic calls (after - // sending, on New Chat) pass silent=true so they never pop a toast at all. - function clearAttachment(silent) { - try { window.__forgetFileSigs && window.__forgetFileSigs(); } catch (e) {} - const hadSomething = attachedDocsList.length > 0 || (webUrls && webUrls.length > 0) || !!windowUploadedFileName || !!forwardedMessageText; - attachedDocsList = []; - documentMemory = ""; - webUrls = []; - windowUploadedFileName = ""; - document.getElementById("attachmentChip").style.display = "none"; - closeAttachmentManager(); - clearForwardedMessage(); // 🚀 Clears the forwarded message chip too - if (hadSomething && !silent) showToast("Attachment Cleared", "info"); - } - - // ---- Attachment Manager: multi-file list, per-file remove, PDF page range, text preview ---- - function openAttachmentManager() { - if (attachedDocsList.length === 0 && webUrls.length === 0) return; - renderAttachmentManager(); - document.getElementById('attachManagerModal').style.display = 'flex'; - } - function closeAttachmentManager() { - const m = document.getElementById('attachManagerModal'); - if (m) m.style.display = 'none'; - } - function renderAttachmentManager() { - const wrap = document.getElementById('attachManagerList'); - if (!wrap) return; - let html = ""; - attachedDocsList.forEach((d, i) => { - const chars = d.content.length; - const rangeControl = (d.pages && d.pages > 1) ? ( - '
' + - 'Pages:' + - '' + - 'to' + - '' + - 'of ' + (d.pages || 1) + '' + - '' + - '
') : ''; - html += ` -
-
-
-
📄 ${truncName(d.name, 30)}
-
${chars.toLocaleString()} characters${d.pages ? ` · ${d.pages} pages` : ''}
-
- -
- ${d.aiSummary ? `
✨ GEMINI SCAN
${String(d.aiSummary).replace(/` : ''} - ${rangeControl} - - -
`; - }); - if (webUrls.length > 0) { - html += `
-
🌐 ${webUrls[0]}
-
`; - } - const totalChars = documentMemory.length; - const overCap = totalChars > DOC_MEMORY_CHAR_CAP; - if (attachedDocsList.length > 0) { - html += `
- ${totalChars.toLocaleString()} total characters attached${overCap ? ` — only the first ${DOC_MEMORY_CHAR_CAP.toLocaleString()} will be sent with each question. Narrow a page range above if needed.` : ''} -
`; - } - wrap.innerHTML = html || `
Nothing attached.
`; - } - function togglePreviewDoc(i) { - const el = document.getElementById('preview_' + i); - if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none'; - } - function removeAttachedDoc(i) { - try { window.__forgetFileSigs && window.__forgetFileSigs(); } catch (e) {} - attachedDocsList.splice(i, 1); - rebuildDocumentMemory(); refreshAttachmentChipUI(); renderAttachmentManager(); - if (attachedDocsList.length === 0 && webUrls.length === 0) closeAttachmentManager(); - showToast("File removed", "info"); - } - function applyPdfPageRange(i) { - const d = attachedDocsList[i]; - if (!d || !d.pageTexts) return; - let from = parseInt(document.getElementById('pgFrom_' + i).value) || 1; - let to = parseInt(document.getElementById('pgTo_' + i).value) || d.pages; - from = Math.max(1, Math.min(from, d.pages)); - to = Math.max(from, Math.min(to, d.pages)); - d.fromPage = from; d.toPage = to; - d.content = d.pageTexts.slice(from - 1, to).join('\n').trim(); - rebuildDocumentMemory(); refreshAttachmentChipUI(); renderAttachmentManager(); - showToast(`Using pages ${from}–${to} of ${d.name}`, "success"); - } - - document.getElementById("searchInput").addEventListener("keypress", function(e) { if(e.key === "Enter" && !e.shiftKey) { e.preventDefault(); runMainSearch(); } }); - - function openNotesModal() { closePlusMenu(); document.getElementById('notesModal').style.display = 'flex'; } - async function generateNotes() { const b = document.getElementById("noteBookName").value.trim(); const c = document.getElementById("noteChapter").value.trim(); if(!b || !c) return showToast("Enter both book and chapter details."); document.getElementById('notesModal').style.display = 'none'; document.getElementById('searchInput').value = `Create highly detailed, structured study notes for the book/subject "${b}", focusing specifically on the chapter/topic: "${c}". Provide definitions, important concepts, and key bullet points. STRICT RULE: ONLY include formulas, equations, or math symbols if "${b}" is explicitly a Mathematics, Physics, Chemistry, or Science subject.`; runMainSearch(); } - - function runInsaneTypewriter(targetElement, fullHtml, callback) { - let tempDiv = document.createElement('div'); tempDiv.innerHTML = fullHtml; let nodes = Array.from(tempDiv.childNodes); targetElement.innerHTML = ""; let nodeIndex = 0; - function typeNextNode() { - if (nodeIndex >= nodes.length) { if(callback) callback(); return; } - let currentNode = nodes[nodeIndex].cloneNode(true); - if (currentNode.nodeType === Node.TEXT_NODE) { - let text = currentNode.textContent; let span = document.createElement('span'); targetElement.appendChild(span); let charIndex = 0; - let interval = setInterval(() => { if (charIndex >= text.length) { clearInterval(interval); nodeIndex++; typeNextNode(); } else { span.textContent += text.substring(charIndex, charIndex + 1); charIndex += 1; } }, 14); - } else { targetElement.appendChild(currentNode); nodeIndex++; typeNextNode(); } - } typeNextNode(); - } - - window.sendQuickReply = function(btn) { document.getElementById("searchInput").value = btn.innerText; btn.parentElement.remove(); resizeInputBox(); runMainSearch(); } - function checkDailyImageLimit() { const today = new Date().toDateString(); let usage = JSON.parse(localStorage.getItem('geminiImgUsage') || '{"count": 0, "date": ""}'); if (usage.date !== today) usage = { count: 0, date: today }; if (usage.count >= 15) { showToast("❌ Daily limit of 15 Image Generations reached. Try again tomorrow!"); return false; } usage.count++; localStorage.setItem('geminiImgUsage', JSON.stringify(usage)); return true; } -// 🛡️ AUTO-LINK VERIFIER & FIXER ENGINE - async function autoVerifyAndFixLinks(textId, originalPrompt, rawText) { - // 1. कोड ब्लॉक्स को इग्नोर करें (ताकि API कोड या स्क्रिप्ट्स चेक न हों) - let textWithoutCode = rawText.replace(/```[\s\S]*?```/g, ''); - - // 2. सिर्फ http/https वाले वेबसाइट लिंक निकालें (ईमेल को इग्नोर करें) - let urls = textWithoutCode.match(/https?:\/\/[^\s\)"'<>]+/g); - if (!urls) return; - - // 3. डुप्लीकेट और लोकलहोस्ट को फिल्टर करें - urls = [...new Set(urls)].filter(u => !u.includes('api.') && !u.includes('localhost') && !u.includes('127.0.0.1')); - - for (let url of urls) { - try { - // सर्वर से DNS चेक करवाएं - let checkRes = await fetch(API_BASE + '/api/verify-url', { - method: 'POST', - headers: {'Content-Type': 'application/json'}, - body: JSON.stringify({ url: url }) - }); - let checkData = await checkRes.json(); - - if (!checkData.valid) { - showToast(`⚠️ Dead link detected: ${url}. Searching for real URL...`); - - let textNode = document.getElementById(textId); - if(!textNode) continue; - - // UI में लिंक की जगह 'Fixing' का एनीमेशन दिखाएं - let originalHtml = textNode.innerHTML; - let safeUrlRegex = new RegExp(url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); - textNode.innerHTML = originalHtml.replace(safeUrlRegex, `⚠️ Auto-fixing dead link...`); - - // 🚀 1 ATTEMPT: GEMINI 2.5 FLASH SEARCH GROUNDING - let fixRes = await fetch(API_BASE + "/api/gemini-text", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - userPrompt: `The AI previously generated a fake or dead link: "${url}" for the topic: "${originalPrompt}". Using Google Search, find the ACTUAL, working, official website URL for this entity. REPLY WITH ONLY THE RAW, WORKING URL (e.g. https://www.example.com). NOTHING ELSE. No markdown. If you absolutely cannot find it, reply with "NOT_FOUND".`, - useSearch: true, // Forces performFreeLiveSearch (Gemini 2.5 Flash Grounding) - model: "API 1" - }) - }); - - let fixData = await fixRes.json(); - let fixedUrl = fixData.text ? fixData.text.replace(/```[a-zA-Z]*/g, '').replace(/```/g, '').trim() : "NOT_FOUND"; - - // नया लिंक मिलने पर उसे दोबारा चेक करें - if (fixedUrl.startsWith('http') && !fixedUrl.includes('NOT_FOUND')) { - let verifyAgain = await fetch(API_BASE + '/api/verify-url', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ url: fixedUrl }) }); - let verifyData = await verifyAgain.json(); - - if (verifyData.valid) { - // 🟢 नया लिंक एकदम सही है! - textNode.innerHTML = originalHtml.replace(safeUrlRegex, `${fixedUrl} ✅ (Auto-Fixed)`); - showToast(`✅ Fake link replaced with real one!`); - } else { - // 🔴 नया लिंक भी गलत निकला (Give up) - textNode.innerHTML = originalHtml.replace(safeUrlRegex, `${url} (⚠️ Website Not Found)`); - } - } else { - // 🔴 कोई वेबसाइट नहीं मिली (Give up) - textNode.innerHTML = originalHtml.replace(safeUrlRegex, `${url} (⚠️ Website Not Found)`); - } - } - } catch(e) { console.error("Link check failed", e); } - } - } -window.handleImageEditingMode = function(promptText, sourceImageBase64, loadId) { - const chatBox = document.getElementById("searchChatHistory"); - const __introLine = (window.__toolIntroLines && window.__toolIntroLines[loadId]) || ""; - const __introHtml = __introLine ? `
✨ ${String(__introLine).replace(/` : ""; - const innerBubbleHtml = ` -
- ${__introHtml} -
🖌️ AI IMAGE EDITOR STUDIO
-
-
-
🪄
- Applying edits to your image... -
This takes about 10-15 seconds.
-
-
`; - const existingEl = document.getElementById(loadId); - if (existingEl) { - existingEl.innerHTML = innerBubbleHtml; - } else { - chatBox.insertAdjacentHTML('beforeend', `
${innerBubbleHtml}
`); - } - - const scrollArea = document.getElementById("searchScrollArea"); - if(scrollArea) scrollArea.scrollTo({top: scrollArea.scrollHeight, behavior: 'smooth'}); - - const img = new Image(); - img.crossOrigin = "anonymous"; - img.onload = async function() { - const canvas = document.createElement("canvas"); - - // 🚀 THE FIX: Shrink to 256x256 to bypass the local TLS socket crash - canvas.width = 256; - canvas.height = 256; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#ffffff"; - ctx.fillRect(0, 0, 256, 256); - ctx.drawImage(img, 0, 0, 256, 256); - - // 🚀 THE FIX: Drop quality from 0.9 to 0.7 to make the payload tiny - let resizedBase64 = canvas.toDataURL("image/jpeg", 0.7); - let rawBase64 = resizedBase64.split(',')[1]; - - try { - const response = await window.apiFetch(API_BASE + "/api/edit-image", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ prompt: promptText, image: rawBase64 }) - }); - - const data = await response.json(); - if (!response.ok) throw new Error(data.error || "Failed to edit image."); - - const editedImage = data.image; - const __doneIntro = (window.__toolIntroLines && window.__toolIntroLines[loadId]) ? `
✨ ${String(window.__toolIntroLines[loadId]).replace(/` : ""; - let htmlAns = ` - ${__doneIntro} -
✨ EDIT SUCCESSFUL
-

I have successfully applied your requested changes:
"${promptText}"

- - -
- - 📥 Download -
- `; - - const __sugHtmlEd = (window.getPendingToolSuggestionsHtml && window.getPendingToolSuggestionsHtml(loadId)) || ""; - document.getElementById(loadId).innerHTML = `
${htmlAns}${__sugHtmlEd}
`; - saveInteractionToLocalForage(promptText, htmlAns + __sugHtmlEd, [editedImage], "Cloudflare Edit", [], null, loadId); - - } catch(e) { - document.getElementById(loadId).innerHTML = `
❌ Edit Failed: ${e.message}
`; - } - - uploadedImagesList = []; - if (typeof updateImageUI === "function") updateImageUI(); - if (typeof clearAttachment === "function") clearAttachment(); - - isProcessing = false; - document.getElementById("sendSearchBtn").innerHTML = window.SEND_ICON; - }; - img.src = sourceImageBase64; -}; - -async function runMainSearch() { - if(isProcessing) { - if (window.chatAbortController) { - window.chatAbortController.abort(); // 🛑 KILL THE STREAM - window.chatAbortController = null; - } - isProcessing = false; - window.setSendBtn("idle"); - showToast("🛑 Generation Stopped"); - return; - } - if (window.__imgPdfMode) { return window.runImageToPdf(); } - if (window.__pdfCompMode) { return window.runPdfCompress(); } - if (window.__editImgMode) { return window.runEditImage(); } - window.chatAbortController = new AbortController(); - - // 🚀 Ensure PTI ID is active and attached to URL before dispatching request - ensurePtiUrlState(); - - const inp = document.getElementById("searchInput"); - let q = inp.value.trim(); - if (window.__docQueue && window.__docQueue.busy) { window.__sendWhenReady = true; window.setSendBtn("loading"); showToast("Files are loading — your message will send automatically"); return; } - if (!q && uploadedImagesList.length === 0 && !documentMemory && webUrls.length === 0) return; - window.__lastDocsSnapshot = attachedDocsList.map(d => ({ name: d.name, content: d.content })); - window.__codeFiles = window.__codeFiles || {}; - attachedDocsList.forEach(d => { if (/\.(js|ts|jsx|tsx|html|css|py|java|c|cpp|cs|go|rs|php|rb|json|sql|sh|md|txt)$/i.test(d.name)) window.__codeFiles[d.name] = d.content; }); - // PDFs / Word / Excel ... of THIS conversation (extracted text, read-only for the agent) - attachedDocsList.forEach(d => { if (!/\.(js|ts|jsx|tsx|html|css|py|java|c|cpp|cs|go|rs|php|rb|json|sql|sh|md|txt)$/i.test(d.name) && typeof d.content === 'string' && d.content) window.__convDocs[d.name] = d.content.slice(0, 120000); }); - try { window.__touchConv(); window.__saveConvStore(); } catch (e) {} - { const __n = attachedDocsList.map(d => d.name).concat(uploadedImagesList.length ? [uploadedImagesList.length + " image(s)"] : []); - window.__pendingFileLabel = __n.length ? ("📄 Processing " + __n.slice(0, 2).join(", ") + (__n.length > 2 ? " +" + (__n.length - 2) : "") + "...") : ""; setTimeout(() => { window.__pendingFileLabel = ""; }, 8000); } - if (q && uploadedImagesList.length === 0 && !documentMemory && await window.tryWeatherCard(q)) { window.setSendBtn("idle"); isProcessing = false; return; } -// 🎨 AUTO-IMAGE DETECTOR (Only active when Auto Tool Chooser is enabled and no image is attached) - const isSolveOrQuestionPrompt = /\b(solve|solve\s+all|answer|explain|read|translate|summarize|summary|calculate|find|what|why|how|who|which|question|questions|mcq|quiz|notes|homework|page|book|chapter|check|hal|batao|samjhao|padho)\b|हल|सॉल्व|बताओ|समझाओ|पढ़ो|प्रश्न|उत्तर/i.test(q); - const imageCmdMatch = (window.__autoToolChooserEnabled !== false && uploadedImagesList.length === 0 && !isSolveOrQuestionPrompt) - ? q.match(/^(?:make|create|generate|draw|show me)\s+(?:an?|some)?\s*(?:image|picture|photo|drawing|art)\s+(?:of|about|for)?\s*(.*)$/i) - : null; - if (imageCmdMatch) { - isPhotoMode = true; - document.getElementById("photoModeChip").style.display = "flex"; - const menuBtn = document.getElementById("photoModeMenuBtn"); - if(menuBtn) menuBtn.innerText = "🎨 Turn Off Photo Gen"; - isYoutubeMode = false; - document.getElementById("ytModeChip").style.display = "none"; - } - -// 🖌️ AUTO-IMAGE EDIT DETECTOR (Only active when Auto Tool Chooser is enabled AND prompt is an explicit visual photo-edit command, NEVER on solve/read/explain!) - const editCmdMatch = (window.__autoToolChooserEnabled !== false && !isSolveOrQuestionPrompt) - ? q.match(/\b(?:edit\s+(?:this\s+|the\s+)?(?:image|photo|picture|pic)|remove\s+(?:the\s+)?background|change\s+(?:the\s+)?background|blur\s+(?:the\s+)?background|make\s+(?:it|this\s+image|this\s+photo)\s+black\s+and\s+white|recolor|colorize|retouch)\b/i) - : null; - - if (editCmdMatch && !isYoutubeMode && !imageCmdMatch && !isPhotoMode && !window.__editImgMode) { - let targetImage = null; - if (uploadedImagesList.length > 0) { - targetImage = uploadedImagesList[0]; - } else { - for (let i = 0; i < appHistory.length; i++) { - const session = appHistory[i]; - if (session && session.interactions) { - for (let j = session.interactions.length - 1; j >= 0; j--) { - const inter = session.interactions[j]; - if (inter.images && inter.images.length > 0 && !inter.images[0].includes('LOCAL_IMAGE_ONLY')) { - targetImage = inter.images[0]; - break; - } - } - } - if (targetImage) break; - } - } - - isProcessing = true; - window.setSendBtn("stop"); - const loadId = "load_" + Date.now(); - let safeUserText = q.replace(/&/g, "&").replace(//g, ">"); - - const chatBox = document.getElementById("searchChatHistory"); - if (document.getElementById("welcomeMessage")) document.getElementById("welcomeMessage").style.display = "none"; - - chatBox.insertAdjacentHTML('beforeend', `
${safeUserText}
${buildUserActionsBar(loadId, q)}
`); - inp.value = ""; resizeInputBox(); - const scrollArea = document.getElementById("searchScrollArea"); - if(scrollArea) scrollArea.scrollTo({top: scrollArea.scrollHeight, behavior: 'smooth'}); - - if (!targetImage) { - chatBox.insertAdjacentHTML('beforeend', `
I'd love to edit that for you! However, I couldn't find an image in our recent chat. Please upload an image first by clicking the ➕ icon, then tell me how to edit it.
`); - isProcessing = false; - document.getElementById("sendSearchBtn").innerHTML = window.SEND_ICON; - return; - } - - if (typeof handleImageEditingMode === "function") { - handleImageEditingMode(q, targetImage, loadId); - } - return; - } - // 0. 🌐 Check for a spoken/typed language-switch command ("talk in english", etc.) - const SUPPORTED_LANGUAGES = ["hindi", "english", "french", "spanish", "german", "japanese", "chinese", "arabic", "portuguese", "russian", "bengali", "tamil", "telugu", "marathi"]; - let langCmdMatch = q.match(/^(?:please\s+)?(?:talk|speak|reply|respond|answer)\s+(?:to me\s+)?in\s+([a-zA-Z]+)\s*$/i) || q.match(/^change\s+(?:the\s+)?language\s+to\s+([a-zA-Z]+)\s*$/i); - if (langCmdMatch) { - inp.value = ""; resizeInputBox(); - const requested = langCmdMatch[1].trim(); - const requestedLower = requested.toLowerCase(); - const chatBox = document.getElementById("searchChatHistory"); - if (document.getElementById("welcomeMessage")) document.getElementById("welcomeMessage").style.display = "none"; - const loadId = "lang_" + Date.now(); - chatBox.insertAdjacentHTML('beforeend', `
${q}
${buildUserActionsBar(loadId, q)}
`); - let responseHtml; - if (SUPPORTED_LANGUAGES.includes(requestedLower)) { - const properName = requested.charAt(0).toUpperCase() + requestedLower.slice(1); - const langSelect = document.getElementById('appLang'); - if (langSelect) { - const optionExists = Array.from(langSelect.options).some(o => o.value.toLowerCase() === requestedLower); - if (optionExists) { langSelect.value = properName; localStorage.setItem('suite_app_language', properName); } - } - responseHtml = `

✅ Changed language to ${properName}. I'll reply in ${properName} from now on - you can change this anytime in Settings.

`; - } else { - responseHtml = `

😕 Sorry, ${requested} isn't supported yet. Supported languages: ${SUPPORTED_LANGUAGES.map(l => l.charAt(0).toUpperCase() + l.slice(1)).join(", ")}.

`; - } - chatBox.insertAdjacentHTML('beforeend', `
${responseHtml}
${buildMsgActionsBar(loadId, loadId, false)}`); - saveInteractionToLocalForage(q, responseHtml, [], "Settings Engine", [], null, loadId); - return; - } - - // 0.5 📄 Source Mode: require an attached source (checking this session's - // earlier messages too, not just the current one), or ask permission - - // via an in-chat message + button, not a native popup - to fall back to - // a live web search (Firecrawl) instead. - if (searchModeState === 'source') { - if (window.__forceAiModeOnce) { - window.__forceAiModeOnce = false; - isSearchMode = true; - window.__lastSearchWasSourceModeFallback = true; - } else { - const hasAttachedSourceNow = uploadedImagesList.length > 0 || !!documentMemory || webUrls.length > 0; - if (hasAttachedSourceNow) { - window.__sessionHasProvidedSource = true; - isSearchMode = false; // answer strictly from the attached source, no extra web search - window.__lastSearchWasSourceModeFallback = false; - } else if (window.__sessionHasProvidedSource) { - // A source was given earlier this session (e.g. an image a few - // messages back) - still treat it as available for this follow-up. - isSearchMode = false; - window.__lastSearchWasSourceModeFallback = false; - } else { - const chatBox = document.getElementById("searchChatHistory"); - if (document.getElementById("welcomeMessage")) document.getElementById("welcomeMessage").style.display = "none"; - const permLoadId = "srcperm_" + Date.now(); - chatBox.insertAdjacentHTML('beforeend', `
${q}
${buildUserActionsBar(permLoadId, q)}
`); - chatBox.insertAdjacentHTML('beforeend', ` -
-
-

🔍 The answer isn't found in your sources - no file or link is attached.

-
- -
-
-
${buildMsgActionsBar(permLoadId, permLoadId, false)}`); - window.__pendingSourceModeQuestion = window.__pendingSourceModeQuestion || {}; - window.__pendingSourceModeQuestion[permLoadId] = q; - const scrollArea = document.getElementById("searchScrollArea"); - if (scrollArea) scrollArea.scrollTo({ top: scrollArea.scrollHeight, behavior: 'smooth' }); - inp.value = ""; - resizeInputBox(); - return; - } - } - } else { - window.__lastSearchWasSourceModeFallback = false; - } - - // 1. 📍 Check for Geolocation Requests Locally - let locationTriggers = /what is my location|where am i|mera location kya hai|my position/i.test(q); - if (locationTriggers) { - inp.value = ""; - resizeInputBox(); - const friendlyName = localStorage.getItem("suite_location_friendly_cache") || (verifiedGeoCoordinates && !verifiedGeoCoordinates.startsWith("Latitude") ? verifiedGeoCoordinates : "your area"); - const chatBox = document.getElementById("searchChatHistory"); - if (document.getElementById("welcomeMessage")) document.getElementById("welcomeMessage").style.display = "none"; - - const loadId = "loc_" + Date.now(); -chatBox.insertAdjacentHTML('beforeend', `
${q}
${buildUserActionsBar(loadId, q)}
`); - - let locResponseHtml = ` -
📍 LOCATION
-

You're currently in ${friendlyName}.

- `; - - chatBox.insertAdjacentHTML('beforeend', `
${locResponseHtml}
${buildMsgActionsBar(loadId, loadId, false)}`); - saveInteractionToLocalForage(q, locResponseHtml, [], "Local Sensor Engine", [], null, loadId); - return; - } - - // 1.5 📴 No internet -> don't try (and don't spend quota): show the notice, tap it to get the prompt + files back - if (!navigator.onLine) { window.__handleOfflineSend(q, inp); return; } - - // 2. 🛡️ Check and Enforce Quota Tiers Before Running - try { - verifyDailyQuotaResetTimestamps(); - - let currentHardwareTotal = parseInt(localStorage.getItem("suite_device_hardware_pool") || "0"); - if (currentHardwareTotal + 1 > 500) { - alert("❌ CRITICAL QUOTA EXHAUSTED: This device has used all 500 allowed allocation tokens. All operations are locked."); - return; - } - - if (!currentUserProfile) { - let currentAnonTotal = parseInt(localStorage.getItem("suite_anon_session_pool") || "0"); - if (currentAnonTotal + 1 > 20) { - alert("🔒 TIER LOCKED: Anonymous usage limit (20 messages) reached on this machine. Please sign in to authenticate more requests."); - return; - } - localStorage.setItem("suite_anon_session_pool", (currentAnonTotal + 1).toString()); - } - - localStorage.setItem("suite_device_hardware_pool", (currentHardwareTotal + 1).toString()); - calculateAndInjectLiveUsageMetrics(); - - } catch(quotaError) { - console.error("Quota engine error:", quotaError); - return; - } - - // 3. Continue Normal Core Request Lifecycle execution - isProcessing = true; - window.setSendBtn("stop"); - const chatBox = document.getElementById("searchChatHistory"); - if (document.getElementById("welcomeMessage")) document.getElementById("welcomeMessage").style.display = "none"; - - let currentImagesToSave = [...uploadedImagesList]; - let userImgs = uploadedImagesList.map(img => ``).join(''); - - let attachHtml = ""; - let currentFileNameForHistory = null; - if (windowUploadedFileName) { - attachHtml = `
📄 Attached: ${windowUploadedFileName}

`; - currentFileNameForHistory = windowUploadedFileName; - } - -const loadId = "load_" + Date.now(); - window.__activeLoadId = loadId; - window.__snapshotForRetry(loadId, q); // 🔁 remembers prompt + files so Retry can resend them - // 🚀 FIXED: Securely escape HTML brackets before putting them on the screen! - let safeUserText = q.replace(/&/g, "&").replace(//g, ">").replace(/\n/g, '
'); - - let userHtml = `
${attachHtml}${userImgs}${userImgs?'
':''}${safeUserText}
${buildUserActionsBar(loadId, q)}
`; - chatBox.insertAdjacentHTML('beforeend', userHtml); - inp.value = ""; - resizeInputBox(); - uploadedImagesList = []; - updateImageUI(); - if (typeof window.syncInputButtons === "function") window.syncInputButtons(); - - const scrollArea = document.getElementById("searchScrollArea"); - if(scrollArea) scrollArea.scrollTo({top: scrollArea.scrollHeight, behavior: 'smooth'}); - - const thinkKind = isYoutubeMode ? 'default' : (currentImagesToSave.length > 0 ? 'image' : (isSearchMode ? 'search' : 'default')); - chatBox.insertAdjacentHTML('beforeend', `
${buildThinkingBubbleHtml(loadId, thinkKind)}
`); - startThinkingCycle(loadId, thinkKind); - - try { - if (isYoutubeMode) { await handleYoutubeAppSearch(q, loadId); toggleYoutubeMode(); } - else if (isPhotoMode) { await handlePhotoGeneration(q, loadId, currentImagesToSave); if(isPhotoMode) togglePhotoMode(); } - else { await handleTextSearch(q, loadId, currentImagesToSave, currentFileNameForHistory); } - } catch(e) { - if (e && (e.name === 'AbortError' || /aborted/i.test(e.message || '')) || (window.chatAbortController && window.chatAbortController.signal && window.chatAbortController.signal.aborted)) { - stopThinkingCycle(loadId); - const host = document.getElementById(loadId); - const line = '
STOPPED
'; - if (host) { - if (host.querySelector('.rainbow-thinking-bubble')) host.innerHTML = '
' + line + '
'; - else if (!host.querySelector('.stopped-line')) (host.querySelector('.bubble') || host).insertAdjacentHTML('beforeend', line); - } - } else { - window.showFailureBubble(loadId, e); - } - } - - isProcessing = false; - document.getElementById("sendSearchBtn").innerHTML = window.SEND_ICON; - uploadedImagesList = []; - updateImageUI(); - clearAttachment(); -} - let ytVideosStore = []; let ytCurrentIndex = 0; - async function handleYoutubeAppSearch(query, loadId) { - document.getElementById(loadId).innerHTML = `
SEARCHING YOUTUBE...
`; - try { - const res = await fetch(API_BASE + "/api/youtube-search", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ topic: query }) }); - const data = await res.json(); - - // FIXED: Now looking for data.items instead of data.results - if (!data.items || data.items.length === 0) throw new Error("No videos found."); - - ytVideosStore = data.items; let top5List = ytVideosStore.slice(0, 5); - let htmlAns = `
▶️ YOUTUBE RESULTS
`; - - // FIXED: Mapping v.id, v.thumb, and v.duration directly to match the server output - top5List.forEach(v => { htmlAns += `
${v.title}
📺 ${v.author} • ⏱️ ${v.duration}
`; }); - - htmlAns += `
`; - document.getElementById(loadId).innerHTML = `
${htmlAns}
`; - saveInteractionToLocalForage(query, htmlAns, [], "YouTube Mode", [], null, loadId); - } catch (error) { document.getElementById(loadId).innerHTML = `
❌ YouTube Error: ${error.message}
`; } - } - - function openYtFullList() { - ytCurrentIndex = 15; const list = document.getElementById("ytResultsList"); - - // FIXED: v.id, v.thumb, v.duration - list.innerHTML = ytVideosStore.slice(0, ytCurrentIndex).map(v => `
${v.title}
📺 ${v.author} • ⏱️ ${v.duration}
`).join(''); - - document.getElementById("ytResultsModal").style.display = "flex"; document.getElementById("ytLoadMoreBtn").style.display = (ytVideosStore.length > ytCurrentIndex) ? "block" : "none"; - } - - function loadMoreYt() { - const list = document.getElementById("ytResultsList"); let nextBatch = ytVideosStore.slice(ytCurrentIndex, ytCurrentIndex + 10); - - // FIXED: v.id, v.thumb, v.duration - list.insertAdjacentHTML('beforeend', nextBatch.map(v => `
${v.title}
📺 ${v.author} • ⏱️ ${v.duration}
`).join('')); - - ytCurrentIndex += 10; if (ytCurrentIndex >= ytVideosStore.length) document.getElementById("ytLoadMoreBtn").style.display = "none"; - } - - let currentActiveVid = ""; - function openYtSelector(vidId) { currentActiveVid = vidId; document.getElementById("ytActionModal").style.display = "flex"; } - function closeYtModal(e, force = false) { if (force || e.target === document.getElementById('ytResultsModal')) { document.getElementById('ytResultsModal').style.display='none'; } } - function openYtExternal() { document.getElementById("ytActionModal").style.display = "none"; window.open(`https://www.youtube.com/watch?v=${currentActiveVid}`, "_blank"); } - function playYtInApp() { document.getElementById("ytActionModal").style.display = "none"; document.getElementById("ytResultsModal").style.display = "none"; document.getElementById("ytIframe").src = `https://www.youtube.com/embed/${currentActiveVid}?autoplay=1`; document.getElementById("ytPlayerFullscreen").style.display = "flex"; if (screen.orientation && screen.orientation.lock) { screen.orientation.lock("landscape").catch(e=>{}); } } - function closeYtFullscreen() { document.getElementById("ytPlayerFullscreen").style.display = "none"; document.getElementById("ytIframe").src = ""; if (screen.orientation && screen.orientation.unlock) { screen.orientation.unlock(); } } - - // 🔢 Wraps LaTeX the model forgot to delimit with $ / $$, without - // touching anything already correctly wrapped. - function autoWrapUnwrappedLatex(text) { - const LATEX_CMD = /\\(?:frac|sqrt|times|cdot|pi|theta|alpha|beta|gamma|Rightarrow|Leftrightarrow|left|right|div|pm|infty|sum|int|neq|leq|geq|approx)\b/; - // Split on existing math segments so they're left completely untouched. - const parts = text.split(/(\$\$[\s\S]*?\$\$|\$[^\$\n]*?\$)/g); - return parts.map((part, i) => { - if (i % 2 === 1) return part; // already-delimited math - if (!LATEX_CMD.test(part)) return part; // nothing to wrap here - return part.replace( - /(\\(?:frac|sqrt|times|cdot|pi|theta|alpha|beta|gamma|Rightarrow|Leftrightarrow|left|right|div|pm|infty|sum|int|neq|leq|geq|approx)(?:\{[^{}]*\}(?:\{[^{}]*\})?)?(?:\s*[=×÷+\-*/^]\s*(?:\d+(?:\.\d+)?|[a-zA-Z]\b|\\(?:frac|sqrt|times|cdot|pi|theta)(?:\{[^{}]*\}(?:\{[^{}]*\})?)?))*)/g, - (m) => `$${m.trim()}$` - ); - }).join(''); - } - - // ============================================================================ - // �� QUIZ SYSTEM (rebuilt): safe JSON parsing, math support, hints, results - // ============================================================================ - window.__quizStore = window.__quizStore || {}; - window.__quizState = { id: null, items: [], idx: 0, answers: [], hints: [], selected: -1, timed: false, timer: null, remaining: 0 }; - function saveQuizStore() { - try { if (window.localforage) localforage.setItem('aiQuizStore', window.__quizStore); } catch (e) {} - } - document.addEventListener('DOMContentLoaded', function() { - try { if (window.localforage) localforage.getItem('aiQuizStore').then(function(d) { if (d) window.__quizStore = Object.assign({}, d, window.__quizStore); }).catch(function() {}); } catch (e) {} - }); - - // Fixes JSON that models often break: single-backslash LaTeX (\frac, \sqrt, \pi), raw newlines, trailing commas, cut-off output - window.parseQuizJson = function(inner) { - let t = String(inner || '').replace(/```[a-zA-Z]*/g, '').replace(/```/g, '').trim(); - const a = t.indexOf('['); if (a === -1) return null; - const b = t.lastIndexOf(']'); - const body = b > a ? t.slice(a, b + 1) : t.slice(a); - const fixSlashes = x => x.replace(/\\(["\\\/]|u[0-9a-fA-F]{4}|[bfnrt](?![A-Za-z]))|\\/g, (m, ok) => ok ? m : '\\\\'); - const noCtl = x => x.replace(/[\u0000-\u001F]+/g, ' '); - const noTrail = x => x.replace(/,\s*([\]}])/g, '$1'); - const salvage = (t.lastIndexOf('}') > a) ? t.slice(a, t.lastIndexOf('}') + 1) + ']' : null; - const cands = [body, noTrail(noCtl(fixSlashes(body)))]; - if (salvage) cands.push(noTrail(noCtl(fixSlashes(salvage)))); - for (const c of cands) { - try { const arr = JSON.parse(c); const items = window.normalizeQuizItems(arr); if (items.length) return items; } catch (e) {} - } - return null; - }; - window.normalizeQuizItems = function(arr) { - if (!Array.isArray(arr)) return []; - const out = []; - arr.forEach(function(it) { - if (!it || typeof it !== 'object') return; - const q = String(it.q != null ? it.q : (it.question != null ? it.question : '')).trim(); - let opts = it.options != null ? it.options : (it.choices != null ? it.choices : it.answers); - if (opts && !Array.isArray(opts) && typeof opts === 'object') opts = Object.values(opts); - if (!q || !Array.isArray(opts) || opts.length < 2) return; - opts = opts.map(o => String(o && typeof o === 'object' ? (o.text != null ? o.text : (o.label != null ? o.label : JSON.stringify(o))) : o).trim()); - let c = it.correct != null ? it.correct : (it.answer != null ? it.answer : (it.correctIndex != null ? it.correctIndex : it.correct_answer)); - let ci = -1; - if (typeof c === 'number') ci = c; - else if (typeof c === 'string') { - const s = c.trim(); - if (/^\d+$/.test(s)) ci = parseInt(s, 10); - else if (/^[A-Da-d][\).:]?$/.test(s)) ci = s.toUpperCase().charCodeAt(0) - 65; - else ci = opts.findIndex(o => o.toLowerCase() === s.toLowerCase()); - } - if (!(ci >= 0 && ci < opts.length)) return; - let hint = String(it.hint != null ? it.hint : '').trim(); - if (!hint) { // model forgot the hint -> build a 50/50 style one - const wrong = opts.map((o, i) => i).filter(i => i !== ci); - hint = 'It is NOT option ' + String.fromCharCode(65 + wrong[0]) + '.'; - } - out.push({ q: q, options: opts, correct: ci, exp: String(it.exp != null ? it.exp : (it.explanation != null ? it.explanation : '')).trim(), hint: hint, isMath: !!it.isMath || /\$|\\frac|\\sqrt|\\int|\\sum/.test(q) }); - }); - return out; - }; - window.inspectQuizPayload = function(rawText) { - const re = /([\s\S]*?)(?:<\/quiz_data\s*>|$)/gi; let m, found = 0, good = 0; - while ((m = re.exec(String(rawText || ''))) !== null) { found++; if (window.parseQuizJson(m[1])) good++; if (m[0].length === 0) re.lastIndex++; } - return { found: found, good: good, bad: found > 0 && good === 0 }; - }; - // Live streaming: never show the JSON while it is being typed - window.stripLiveQuiz = function(text) { - return String(text).replace(/(?:```[a-zA-Z]*\s*)?[\s\S]*?(?:<\/quiz_data\s*>|$)(?:\s*```)?/gi, - '\n\n
📝 Preparing your quiz...
\n\n'); - }; - - // Text (with $math$) -> safe HTML. Math is protected from markdown, then typeset by MathJax. - window.quizRich = function(text, inline) { - const store = []; let t = String(text == null ? '' : text); - t = t.replace(/\$\$([\s\S]+?)\$\$|\$([^$\n]+?)\$|\\\(([\s\S]+?)\\\)|\\\[([\s\S]+?)\\\]/g, function(m) { store.push(m); return '@@QMATH' + (store.length - 1) + '@@'; }); - t = window.__escHtml(t).replace(/"/g, '"').replace(/'/g, "'"); - let html; try { html = inline ? marked.parseInline(t) : marked.parse(t); } catch (e) { html = t; } - return html.replace(/@@QMATH(\d+)@@/g, function(m, i) { return store[i].replace(/&/g, '&').replace(//g, '>'); }); - }; - window.quizTypeset = function(el) { - try { if (window.MathJax && typeof MathJax.typesetPromise === 'function') { if (typeof MathJax.typesetClear === 'function') MathJax.typesetClear([el]); MathJax.typesetPromise([el]).catch(function() {}); } } catch (e) {} - }; - - function interceptAndRenderQuizPayload(rawText, containerElementId) { - return String(rawText).replace(/(?:```[a-zA-Z]*\s*)?([\s\S]*?)(?:<\/quiz_data\s*>|$)(?:\s*```)?/gi, function(m, inner) { - const items = window.parseQuizJson(inner); - if (!items || !items.length) return ''; // broken block: never show raw code - const id = 'quiz_' + Date.now() + Math.floor(Math.random() * 10000); - window.__quizStore[id] = items; window.__quizLastId = id; saveQuizStore(); - return `
📝
Your quiz is ready!
${items.length} questions · 💡 hints available
`; - }); - } - - function openQuizGUIOverlay(quizId) { - const id = quizId || window.__quizLastId; - const items = id && window.__quizStore[id]; - if (!items || !items.length) { showToast("⚠️ This quiz isn't saved on this device anymore. Ask again to regenerate it."); return; } - const S = window.__quizState; clearInterval(S.timer); - S.id = id; S.items = items; S.idx = 0; S.answers = []; S.hints = items.map(() => false); S.selected = -1; - document.getElementById("quizTopTitle").innerText = "📝 Quiz"; - document.getElementById("quizGlobalProgress").innerText = items.length + " questions"; - document.getElementById("quizSetupFrame").style.display = "block"; - document.getElementById("quizGameplayFrame").style.display = "none"; - document.getElementById("quizDashboardFrame").style.display = "none"; - document.getElementById("quizAppOverlay").style.display = "flex"; - } - - function initializeQuizGameplay(enableTimerFlag) { - window.__quizState.timed = !!enableTimerFlag; - document.getElementById("quizSetupFrame").style.display = "none"; - document.getElementById("quizGameplayFrame").style.display = "block"; - renderActiveQuizQuestionCard(); - } - - function renderActiveQuizQuestionCard() { - const S = window.__quizState; clearInterval(S.timer); - const item = S.items[S.idx]; S.selected = -1; - document.getElementById("quizTopTitle").innerText = "📝 Quiz"; - document.getElementById("quizGlobalProgress").innerText = `Question ${S.idx + 1} of ${S.items.length}`; - const qBody = document.getElementById("quizQuestionBody"); - qBody.innerHTML = window.quizRich(item.q, false); - document.getElementById("quizNextStepBtn").style.display = "none"; - - const grid = document.getElementById("quizOptionsGrid"); grid.innerHTML = ""; - item.options.forEach(function(opt, idx) { - grid.insertAdjacentHTML('beforeend', ``); - }); - - // hint UI - const hb = document.getElementById("quizHintBtn"), box = document.getElementById("quizHintBox"); - hb.disabled = false; hb.style.opacity = "1"; hb.innerText = "💡 Hint"; - box.style.display = "none"; box.innerHTML = ""; - window.__updateHintCounter(); - - window.quizTypeset(document.getElementById("quizGameplayFrame")); - - if (S.timed) { - document.getElementById("quizTimerWrapper").style.display = "block"; - S.remaining = item.isMath ? 120 : 45; const total = S.remaining; - const meter = document.getElementById("quizTimerMeter"); - meter.style.width = "100%"; meter.style.backgroundColor = "#3b82f6"; - S.timer = setInterval(function() { - S.remaining--; const pct = (S.remaining / total) * 100; - meter.style.width = pct + "%"; if (pct < 30) meter.style.backgroundColor = "#ef4444"; - if (S.remaining <= 0) { clearInterval(S.timer); showToast("⏱️ Time's up!"); S.answers[S.idx] = -1; advanceQuizStepSequence(); } - }, 1000); - } else { document.getElementById("quizTimerWrapper").style.display = "none"; } - } - - window.__updateHintCounter = function() { - const n = window.__quizState.hints.filter(Boolean).length; - const c = document.getElementById("quizHintCounter"); if (c) c.innerText = "Hints used: " + n; - }; - window.showQuizHint = function() { - const S = window.__quizState; const item = S.items[S.idx]; if (!item) return; - S.hints[S.idx] = true; // counted once per question, however many taps - const box = document.getElementById("quizHintBox"); - box.innerHTML = "💡 " + window.quizRich(item.hint, true); box.style.display = "block"; - const hb = document.getElementById("quizHintBtn"); hb.disabled = true; hb.style.opacity = "0.55"; hb.innerText = "💡 Hint shown"; - window.__updateHintCounter(); window.quizTypeset(box); - }; - - function handleQuizOptionSelection(elementNode, indexPosition) { - const S = window.__quizState; - document.querySelectorAll("#quizOptionsGrid .quiz-option-node").forEach(btn => btn.classList.remove("selected-active")); - elementNode.classList.add("selected-active"); - S.selected = indexPosition; - const nextBtn = document.getElementById("quizNextStepBtn"); - nextBtn.style.display = "block"; - nextBtn.innerText = (S.idx === S.items.length - 1) ? "Finish Quiz 🏁" : "Next Question ➡️"; - nextBtn.onclick = function() { clearInterval(S.timer); S.answers[S.idx] = S.selected; advanceQuizStepSequence(); }; - } - - function advanceQuizStepSequence() { - const S = window.__quizState; S.idx++; - if (S.idx < S.items.length) renderActiveQuizQuestionCard(); else renderQuizPerformanceSummaryDashboard(); - } - - function renderQuizPerformanceSummaryDashboard() { - const S = window.__quizState; clearInterval(S.timer); - document.getElementById("quizGameplayFrame").style.display = "none"; - document.getElementById("quizDashboardFrame").style.display = "block"; - document.getElementById("quizTopTitle").innerText = "📝 Quiz Results"; - let correctCount = 0; - const list = document.getElementById("quizDashboardReviewList"); list.innerHTML = ""; - S.items.forEach(function(item, idx) { - const u = (S.answers[idx] == null) ? -1 : S.answers[idx]; - const ok = u === item.correct; if (ok) correctCount++; - const userText = u === -1 ? "⏱️ No answer" : window.quizRich(item.options[u], true); - const usedHint = !!S.hints[idx]; - list.insertAdjacentHTML('beforeend', ` -
-
${idx + 1}. ${window.quizRich(item.q, true)}${usedHint ? ' 💡 hint used' : ''}
-
🙋 Your answer: ${userText}
- ${!ok ? `
✅ Correct answer: ${window.quizRich(item.options[item.correct], true)}
` : ''} - ${item.exp ? `
Explanation: ${window.quizRich(item.exp, true)}
` : ''} -
`); - }); - const total = S.items.length, pct = Math.round((correctCount / total) * 100) || 0, hintsUsed = S.hints.filter(Boolean).length; - document.getElementById("quizGlobalProgress").innerText = `Score ${correctCount}/${total}`; - document.getElementById("quizFinalScoreTitle").innerText = `You scored ${correctCount} / ${total}`; - document.getElementById("quizFinalPercentTitle").innerText = `Accuracy: ${pct}%`; - document.getElementById("quizFinalHintsTitle").innerText = `💡 Total hints used: ${hintsUsed} of ${total}`; - window.quizTypeset(document.getElementById("quizDashboardFrame")); - } - - function exitQuizGUIAndReturnToChat(force) { - const gp = document.getElementById("quizGameplayFrame"); - if (force !== true && gp && gp.style.display !== "none" && !confirm("Leave the quiz? Your progress will be lost.")) return; - clearInterval(window.__quizState.timer); - document.getElementById("quizAppOverlay").style.display = "none"; - } - - -async function handlePhotoGeneration(promptText, loadId, savedImages) { - const __introLine = (window.__toolIntroLines && window.__toolIntroLines[loadId]) || ""; - const __introHtml = __introLine ? `
${String(__introLine).replace(/` : ""; - const __actBar = (typeof buildMsgActionsBar === "function") ? buildMsgActionsBar(loadId, "txt_" + loadId, false) : ""; - document.getElementById(loadId).innerHTML = ` -
-
- ${__introHtml} -

🎨 How would you like to get this image?

-
- - - -
-
-
${__actBar}`; - window.__pendingPhotoGenPrompts = window.__pendingPhotoGenPrompts || {}; - window.__pendingPhotoGenPrompts[loadId] = promptText; - window.__pendingPhotoGenImages = window.__pendingPhotoGenImages || {}; - window.__pendingPhotoGenImages[loadId] = (savedImages || []).filter(x => typeof x === 'string' && x.startsWith('data:image')).slice(0, 2); -} - -window.cancelPhotoGen = function(loadId) { - const __actBar = (typeof buildMsgActionsBar === "function") ? buildMsgActionsBar(loadId, "txt_" + loadId, false) : ""; - document.getElementById(loadId).innerHTML = `
🚫 Image generation cancelled.
${__actBar}`; - isProcessing = false; - document.getElementById("sendSearchBtn").innerHTML = window.SEND_ICON; -}; - -// 🎨/🔍 Handles the Cloudflare-generate vs Google-search choice, then clearly -// labels the result with whichever method actually produced it. -window.resolvePhotoGenChoice = async function(loadId, method) { - const promptText = window.__pendingPhotoGenPrompts ? window.__pendingPhotoGenPrompts[loadId] : null; - if (!promptText) return; - const bubble = document.querySelector(`#${loadId} .bubble`); - if (bubble) { - var __introLoading = (window.__toolIntroLines && window.__toolIntroLines[loadId]) ? `
${String(window.__toolIntroLines[loadId]).replace(/&/g,"&").replace(//g,">")}
` : ""; - bubble.innerHTML = ` - ${__introLoading} -
${method === 'cloudflare' ? '🎨 GENERATING NEW IMAGE' : '🔍 SEARCHING GOOGLE'}
- ${window.pgLoadingHtml(loadId, method === 'cloudflare' ? '🎨 Painting masterpiece...' : '🔍 Searching & comparing...')}`; - } - - const __actBar = (typeof buildMsgActionsBar === "function") ? buildMsgActionsBar(loadId, "txt_" + loadId, false) : ""; - try { - if (typeof validateAndIncrementRequestCounter === "function") { - await validateAndIncrementRequestCounter(method === 'cloudflare' ? 20 : 15); - } - if (method === 'cloudflare') { - let genPrompt = (window.__pendingPhotoGenDetailedPrompts && window.__pendingPhotoGenDetailedPrompts[loadId]) || promptText, usedHints = ""; - const refImgs = (window.__pendingPhotoGenImages && window.__pendingPhotoGenImages[loadId]) || []; - if (refImgs.length) { - const lbl = document.getElementById('pgcap_' + loadId); if (lbl) lbl.textContent = "🔎 Sending your photo to Cloudflare for hints..."; - try { - const small = await window.eiShrink(refImgs[0], 768, 0.8); - const hr = await window.apiFetch(API_BASE + "/api/image-hints", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ image: small, prompt: promptText }) }); - const hd = await hr.json().catch(() => null); - if (hr.ok && hd && hd.hints) { usedHints = hd.hints.trim(); genPrompt = (promptText + ". Use this reference as guidance: " + usedHints).slice(0, 1800); } - } catch (e) { console.warn("Hints skipped:", e.message); } - if (lbl) lbl.textContent = "🎨 Painting Masterpiece..."; - } - const response = await window.apiFetch(API_BASE + "/api/cloudflare-image", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: genPrompt }) }); - let data = null; - try { data = await response.json(); } catch (e) { data = null; } - if (!response.ok || !data || !data.image) { - throw new Error((data && data.error) || `Image service busy (status ${response.status}). Please try again.`); - } - await window.pgPreload(data.image); - const __introLine = (window.__toolIntroLines && window.__toolIntroLines[loadId]) || ""; - const __introHtml = __introLine ? `
${String(__introLine).replace(/` : ""; - let htmlAns = `${__introHtml} -
🎨 NEW IMAGE GENERATED VIA CLOUDFLARE
${usedHints ? `
🔎 Hints from your photo: ${usedHints.replace(/` : ""} - ${window.pgFrame(data.image)}`; - const __sugHtmlCf = (window.getPendingToolSuggestionsHtml && window.getPendingToolSuggestionsHtml(loadId)) || ""; - document.getElementById(loadId).innerHTML = `
${htmlAns}
${__sugHtmlCf}
${__actBar}`; - saveInteractionToLocalForage(promptText, htmlAns + __sugHtmlCf, [], "Cloudflare (Image)", [], null, loadId); - } else { - const gSearchPrompt = (window.sanitizeSearchQueryNo2024 ? window.sanitizeSearchQueryNo2024((window.__pendingPhotoGenSearchQueries && window.__pendingPhotoGenSearchQueries[loadId]) || promptText, promptText) : promptText); - const response = await fetch(API_BASE + "/api/image-search-select", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: gSearchPrompt }) }); - let data = null; try { data = await response.json(); } catch (e) { data = null; } - if (!response.ok || !data) throw new Error((data && data.error) || "Image search service returned an unexpected reply. Please try again."); - const galleryId = "gallery_" + loadId; - if (Array.isArray(data.allImageUrls)) window.__imageGalleries = Object.assign(window.__imageGalleries || {}, { [galleryId]: data.allImageUrls }); - let viewAllBtn = (Array.isArray(data.allImageUrls) && data.allImageUrls.length > 1) - ? `` : ''; - await window.pgPreload(data.bestImageUrl); - const __introLine = (window.__toolIntroLines && window.__toolIntroLines[loadId]) || ""; - const __introHtml = __introLine ? `
${String(__introLine).replace(/` : ""; - let htmlAns = `${__introHtml} -
🔍 FOUND VIA GOOGLE SEARCH (${data.totalCompared} Images Compared)
-

Reason: ${data.reason}

- ${window.pgFrame(data.bestImageUrl)} - - ${viewAllBtn}`; - const __sugHtmlGs = (window.getPendingToolSuggestionsHtml && window.getPendingToolSuggestionsHtml(loadId)) || ""; - document.getElementById(loadId).innerHTML = `
${htmlAns}
${__sugHtmlGs}
${__actBar}`; - saveInteractionToLocalForage(promptText, htmlAns + __sugHtmlGs, [], "Google Search (Image)", [], null, loadId); - } - } catch (error) { - document.getElementById(loadId).innerHTML = `
❌ Image Error: ${error.message}
${__actBar}`; - } -}; - - // 🌊 Consumes the real SSE stream: renders text progressively as Gemini - // actually generates it, and shows the real website logos the instant - // Firecrawl finds them - nothing here is simulated. Throws on any - // failure so the caller falls back to the standard request. - async function handleTextSearchStreaming(payload, loadId, prompt, savedImages, attachedFileName) { - const response = await fetch(API_BASE + "/api/smart-search-stream", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), - signal: window.chatAbortController.signal // 🛑 Attach Abort Signal - }); - if (!response.ok || !response.body) throw new Error("Streaming unavailable"); - window.__tkStep(loadId, "Stream connected"); - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - let accumulatedText = ""; - let providerUsed = null; - let gotAnyChunk = false; - let finalWebSources = []; // 🚀 STORE SOURCES FOR FINAL RENDER - let thoughtText = ""; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - let parts = buffer.split('\n\n'); - buffer = parts.pop(); - for (const line of parts) { - const dataLine = line.split('\n').find(l => l.startsWith('data:')); - if (!dataLine) continue; - let evt; - try { evt = JSON.parse(dataLine.slice(5).trim()); } catch (e) { continue; } - - if (evt.type === 'status') { - if (!gotAnyChunk) updateThinkingStatusText(loadId, evt.text); - } else if (evt.type === 'thought') { - thoughtText += evt.text; - } else if (evt.type === 'search_sources') { - finalWebSources = evt.sources; // 🚀 SAVE SOURCES - window.__didWebSearchByLoadId = window.__didWebSearchByLoadId || {}; - window.__didWebSearchByLoadId[loadId] = true; - // 🚫 DO NOT WIPE TEXT IF IT ALREADY STARTED STREAMING - if (!gotAnyChunk) { - startWebsiteLogoAnimation(loadId, evt.sources); - } - } else if (evt.type === 'chunk') { - gotAnyChunk = true; - accumulatedText += evt.text; - renderLiveStreamingText(loadId, accumulatedText); - } else if (evt.type === 'done') { - providerUsed = evt.provider; - if (evt.fullText) accumulatedText = evt.fullText; - } else if (evt.type === 'error') { - throw new Error(evt.message || "Stream error"); - } - } - } - - if (!accumulatedText.trim()) throw new Error("Empty stream response."); - stopWebsiteLogoAnimation(loadId); - // 🚀 PASS FINAL WEB SOURCES TO SHOW AT THE BOTTOM OF THE CHAT - window.__saveThoughts(loadId, thoughtText); - renderSearchPayloadResult({ text: accumulatedText, provider: providerUsed || "GEMINI", webSources: finalWebSources }, loadId, prompt, savedImages, attachedFileName); - } - - // Live progressive rendering while chunks are still arriving. Re-parses - // the growing text each time - simple and safe; the final renderSearchPayloadResult - // call replaces this with the fully correct structural render once done. - // 🚀 LIVE STREAMING GLOBALS - // 🚀 LIVE STREAMING GLOBALS - window.__liveCodeContent = ""; - window.__liveFileName = "File"; - window.__isViewingLiveCode = false; - - window.openLiveCodeViewer = function() { - let fName = window.__liveFileName || "Code File"; - if (fName.toLowerCase().endsWith('.pdf')) return; - - window.__isViewingLiveCode = true; - - if (window.innerWidth > 900) { - // DESKTOP: Stream directly into the Artifact Pane with hidden buttons - if (!document.getElementById('liveArtifactCodeContent')) { - const actionsHtml = ` - ⚡ Generating... - - - - `; - const contentHtml = `
`; - window.openInArtifact(`💻 ${fName}`, contentHtml, actionsHtml); - } - const lcNode = document.getElementById('liveArtifactCodeContent'); - if (lcNode) lcNode.innerText = window.__liveCodeContent; - } else { - // MOBILE: Use the actual Code View Modal with hidden buttons - document.getElementById('codeViewTitle').innerText = "Writing " + fName; - document.getElementById('codeViewContent').innerText = window.__liveCodeContent || ""; - - // Hide normal buttons during generation - document.querySelectorAll('#codeViewModal .action-btn').forEach(b => b.style.display = 'none'); - - let genInd = document.getElementById('mobileGenInd'); - if (!genInd) { - const toolbar = document.querySelector('#codeViewModal > div:nth-child(2)'); - if (toolbar) toolbar.insertAdjacentHTML('afterbegin', `⚡ Generating...`); - } else { - genInd.style.display = 'flex'; - } - document.getElementById('codeViewModal').style.display = 'flex'; - } - }; - - function renderLiveStreamingText(loadId, text) { - stopWebsiteLogoAnimation(loadId); - const host = document.getElementById(loadId); - if (!host) return; - - // 🚀 BROWSER REPAINT FIX: Separate the Text from the Shimmer Box! - let bubble = host.querySelector('.bubble'); - if (!bubble) { - host.innerHTML = `
`; - } - let textEl = document.getElementById('txt_' + loadId); - let shimmerEl = document.getElementById('shimmer_' + loadId); - - let cleanLiveText = window.stripLiveQuiz(window.hidePartialTag(text.replace(/\|\|SUGGESTIONS:\s*\[.*?\]\|\|/gs, '').trim())); - - // Extract the tag and file name - const blockMatch = cleanLiveText.match(/(?:```[a-zA-Z0-9_+-]*\s*)?<(pdf_data|file_data|map_data|svg_data)([^>]*)>([\s\S]*?)(?:<\/\1>|$)(?:\s*```)?/i); - - if (blockMatch) { - const hideStartIndex = blockMatch.index; - const tag = blockMatch[1].toLowerCase(); - const rawLiveAttr = blockMatch[2] || ""; - const extractedLiveName = tag === "file_data" && window.extractCleanFileDataName - ? window.extractCleanFileDataName(rawLiveAttr, blockMatch[3] || "", "", cleanLiveText.slice(0, hideStartIndex)) - : ((rawLiveAttr.match(/(?:name|filename|file|path|title)\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s"'>]+))/i) || [])[1] || ""); - window.__liveFileName = extractedLiveName || (tag.includes("pdf") ? "Document.pdf" : (tag.includes("map") ? "Flowchart" : (tag.includes("svg") ? "Vector Diagram.svg" : "Code File"))); - window.__liveCodeContent = (blockMatch[3] || "").replace(/```[a-zA-Z]*/g, '').replace(/```/g, ''); - if (tag === "pdf_data") { const __lp = window.livePdfInfo(blockMatch[3], blockMatch[2]); window.__liveFileName = __lp.name + ".pdf"; window.__liveCodeContent = __lp.code; } - - // ✅ Show the text written BEFORE the code block starts - textEl.style.display = 'block'; - let textPart = cleanLiveText.substring(0, hideStartIndex); - - // Keep AI formatting active for the text - if (typeof window.parseAIFormatting === "function") { - textPart = window.parseAIFormatting(textPart); - } - - // Render the text safely above the shiny box - try { - textEl.innerHTML = marked.parse(textPart); - } catch (e) { - textEl.innerText = textPart; - } - - // 🌟 THE GLITCH FIX: ONLY draw the box if it doesn't exist yet! - // This stops the animation from resetting every millisecond. - if (shimmerEl.innerHTML === "") { - let icon = tag.includes("pdf") ? "📄" : (tag.includes("map") ? "🗺️" : "💻"); - shimmerEl.innerHTML = ` - -
-
- ${icon} - Creating ${window.__liveFileName} - Tap to watch live... -
`; - - // 🚀 AUTO-OPEN ARTIFACT PANE ON DESKTOP - if (window.innerWidth > 900) { - window.openLiveCodeViewer(); - } - } else { - // Just update the title cleanly without touching the animation - const titleEl = document.getElementById('shimmerTitle_' + loadId); - if (titleEl) titleEl.innerText = "Creating " + window.__liveFileName; - } - - // AUTO-SCROLL LIVE VIEWER - // AUTO-SCROLL LIVE VIEWER - if (window.__isViewingLiveCode) { - if (window.innerWidth > 900) { - const artNode = document.getElementById('liveArtifactCodeContent'); - const artBox = document.getElementById('artifactContent').firstElementChild; - if (artNode && artBox) { - artNode.innerText = window.__liveCodeContent; - artBox.scrollTop = artBox.scrollHeight; - } - } else { - const lcNode = document.getElementById('codeViewContent'); - const lcBox = lcNode.closest('div'); - if (lcNode && lcBox) { - lcNode.innerText = window.__liveCodeContent; - lcBox.scrollTop = lcBox.scrollHeight; - } - } - } - } else { - textEl.style.display = 'block'; - shimmerEl.innerHTML = ""; // Clear the box if the AI is just typing normal chat text - - cleanLiveText = window.__liveFenceFix(cleanLiveText); - - if (typeof window.parseAIFormatting === "function") { - cleanLiveText = window.parseAIFormatting(cleanLiveText); - } - - try { textEl.innerHTML = marked.parse(cleanLiveText); } catch (e) { textEl.innerText = cleanLiveText; } - } - } - - function updateThinkingStatusText(loadId, text) { - const el = document.getElementById('thinkstatus_' + loadId); - if (el) el.innerText = text; - } - - // 🖼️ Real website-logo cycling animation - uses the ACTUAL domains - // Firecrawl found (never a hardcoded/simulated list). Shows one at a - // time for 2 seconds, looping through all of them until the answer - // starts streaming in. - window.__websiteLogoIntervals = window.__websiteLogoIntervals || {}; - function startWebsiteLogoAnimation(loadId, sources) { - const host = document.getElementById(loadId); - const domains = (sources || []).map(s => s.domain).filter(Boolean); - if (!host || domains.length === 0) return; - stopThinkingCycle(loadId); - - host.innerHTML = - '
' + - '
🔎 Searching...
' + - '
' + - '' + - '' + (domains[0] || '') + '' + - '
' + - '
' + - '
'; - - let i = 0; - clearInterval(window.__websiteLogoIntervals[loadId]); - window.__websiteLogoIntervals[loadId] = setInterval(() => { - const img = document.getElementById('logoAnim_' + loadId); - const label = document.getElementById('logoAnimLabel_' + loadId); - if (!img) { clearInterval(window.__websiteLogoIntervals[loadId]); delete window.__websiteLogoIntervals[loadId]; return; } - i = (i + 1) % domains.length; - img.style.animation = 'none'; - void img.offsetWidth; // restart the CSS animation - img.style.display = 'block'; // reset display if previous icon failed - img.src = `https://www.google.com/s2/favicons?domain=${domains[i]}&sz=64`; - img.style.animation = 'logoFadeIn 0.4s ease'; - if (label) label.innerText = domains[i]; - }, 2000); - } - function stopWebsiteLogoAnimation(loadId) { - if (window.__websiteLogoIntervals[loadId]) { clearInterval(window.__websiteLogoIntervals[loadId]); delete window.__websiteLogoIntervals[loadId]; } - } - - async function handleTextSearch(prompt, loadId, savedImages, attachedFileName) { - try { - if (typeof validateAndIncrementRequestCounter === "function") { - await validateAndIncrementRequestCounter(selectedModel === '3.6' ? 10 : 1); - } - } catch(e) { - const node = document.getElementById(loadId); - if(node) node.remove(); - isProcessing = false; - document.getElementById("sendSearchBtn").innerHTML = window.SEND_ICON; - return; - } - - const lang = document.getElementById("appLang").value; - const customRules = document.getElementById("aiInstructions").value.trim(); - let isMathQ = /math|solve|calculate|equation|find the value|त्रिज्या|व्यास|formula|[0-9]+[\+\-\*\/\^]/i.test(prompt); - - // 🎯 Quiz question-count enforcement - without this the model tends to - // generate a random smaller number (2/3/4) even when N was requested. - const __fmtNeg = window.__negatesFormat(prompt); - const isQuizRequest = !__fmtNeg.quiz && /\bquiz(?:zes)?\b|\bmcqs?\b|multiple[- ]choice|test me|\bobjective\b|क्विज/i.test(prompt); - let requestedQuizCount = null; - if (isQuizRequest) { - const countMatch = prompt.match(/(\d+)\s*(?:questions?|mcqs?|quiz)/i) || prompt.match(/(?:quiz|test|mcqs?)\s*(?:of|with|for)?\s*(\d+)/i); - requestedQuizCount = countMatch ? parseInt(countMatch[1]) : 10; // sensible default if a quiz is asked for without a number - } - window.__lastRequestedQuizCount = requestedQuizCount; - - let activeUserNameString = "User"; - if (currentUserProfile && currentUserProfile.given_name) { - activeUserNameString = currentUserProfile.given_name; - } else if (currentUserProfile && currentUserProfile.name) { - activeUserNameString = currentUserProfile.name.split(" ")[0]; - } - - let sysPrompt = `You are the ultimate educational AI Tutor. - -🚨 GEOLOCATION INTELLIGENCE MANDATE: -- The verified tracking coordinates of the user are: "${verifiedGeoCoordinates || 'Unknown India Grid Location'}". WRITE PLACE NAME DONT WRITE LONGITUDE AND LATITUDE. WRITE ONLY IF USER ASKED. - -🚨 USER ENGAGEMENT PERSONALIZATION MANDATE: -- The logged-in user's name is currently verified as: "${activeUserNameString}". Address them naturally. - -🚨 GREETINGS & CHAT RETENTION LIMIT (CRITICAL): -- NEVER repeat "Namaste", "Welcome", or any other introductory greeting phrases. Get straight to the answer. - -🚨 HIGH-PRIORITY LANGUAGE & MATH STRUCTURE RULES: -1. STRICT LANGUAGE MANDATE: Answer 100% in the user's selected language from Settings: "${lang}". NEVER write in Hinglish (Romanized Hindi). If "${lang}" is Hindi, write 100% in pure Devanagari script (हिंदी देवनागरी लिपि में लिखें, Hinglish में कभी न लिखें). If "${lang}" is English, write 100% in pure English. For any other selected language, write 100% in "${lang}". -2. 🚫 ZERO TEXT OR HINDI CHARACTERS INSIDE MATH BLOCKS ($ or $$). ONLY pure numbers and operators. -3. 📏 LABELED LAYOUT STRUCTURE: Always print the descriptive label ABOVE the math calculation. -4. ➡️ MANDATORY STEP TRANSITIONS: Use '\\Rightarrow ' for multiple steps. -5. 📄 SHOW EVERY FRACTIONAL STEP: Use LaTeX fraction (\\frac{numerator}{denominator}). -6. ✖️ EXPLICIT MULTIPLICATION SIGN: Use '\\times '. -7. 👑 ABSOLUTE LATEX FORMATTING: Wrap major blocks in $$ and inline in $. -8. 🚨 CRITICAL NUMBER FORMATTING: NEVER place spaces, commas, or empty gaps inside a number in LaTeX. -9. ${requestedQuizCount ? `QUIZ REQUESTED: The user wants EXACTLY ${requestedQuizCount} quiz questions. You MUST generate EXACTLY ${requestedQuizCount} questions in the JSON array. Use EXACTLY this JSON format: [{"q": "Question text?", "options": ["Opt 1", "Opt 2", "Opt 3", "Opt 4"], "correct": 0, "exp": "Short explanation", "hint": "A short clue that points toward the answer WITHOUT giving it away"}]. The 'correct' field MUST be the integer index (0-3) of the correct option. EVERY question MUST have a non-empty "hint". Put ONLY valid JSON inside [...] at the very bottom (no code fences, no comments, no trailing commas). Write maths inside $...$ LaTeX and use a DOUBLE backslash for every LaTeX command inside the JSON strings.` : `ONLY GENERATE QUIZ IF EXPLICITLY ASKED. If asked, use format [{"q":"..","options":[".."],"correct":0,"exp":"..","hint":".."}] inside .`} -10. GIVE MATH EQUATION IF ASKED. dont give any math formula until the topic or subject requires math formula. -11. WHEN USER GIVES GREETING, SPEAK CASUALLY DONT WRITE ANY LOCATION OR ANYTHING. -12. CRITICAL FORMATTING: NEVER write the Question and Answer on the same line. Put the Question on one line, and the Answer on a completely NEW line below it. -13. 🚨 CRITICAL MULTI-IMAGE RULE: The user has attached MULTIPLE images. You MUST process EVERY SINGLE IMAGE. Extract and solve ALL questions from Image 1, then ALL questions from Image 2, etc. If you skip ANY question from the second image, you fail. NEVER summarize. List and solve every single item you see. -14. STRICT NO-HALLUCINATION: NEVER change or rewrite the user's math question. If they ask "2+2", solve "2+2". Do not alter signs or numbers.5. GRAMMAR & LISTS (SWIPEABLE TABLES): If asked for word roots, grammar, persons, tenses, or list comparisons, YOU MUST output a Markdown table so it renders as a swipeable table. -16. COMPLEX FRACTIONS: If the user types "2 fraction 3" or similar, interpret it as 2/3 (fractions). -17. SVG GENERATION: If asked to draw math/diagrams using SVG, you MUST generate valid SVG code and wrap it EXACTLY in .... Example: .... Write a normal explanation outside this tag. -18. SUGGESTIONS: At the very end, provide exactly 3 concise, ACTIONABLE prompts the user can click to ask you next, wrapped like this: ||SUGGESTIONS: ["Explain force in detail", "Give an example of this", "Show me the formula"]||. DO NOT ask conversational questions to the user.19. PDF GENERATION (STRICT FORMAT): When the user asks for a PDF / document / notes file, output EXACTLY ONE block: Short Plain Title|||
full HTML body
. RULES: (a) The title is plain text only - max 8 words, NO HTML tags, NO quotes, NO .pdf. (b) Write ||| exactly once, right after the title. (c) After ||| write the COMPLETE finished document as HTML BODY content only (h1/h2/p/ul/table with inline styles) - no , , , - - - - - - - - - - - - - - - - - - - - -
-
- - ✂️ Crop photo - -
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + }; + + function syncStandardAudioTick() { + if (!stdAudioCtx || !stdIsPlaying || stdIsBuffering) return; + + const currentRealTime = stdAudioCtx.currentTime - stdAudio \ No newline at end of file