Spaces:
Sleeping
Sleeping
Commit ·
add3f25
1
Parent(s): 10f6669
Fix message sending by adding safe storage fallbacks and resilient event listeners
Browse files1481 unmodified lines148214831484148514861487148819 unmodified lines150815091510151115121513151415151516151715181519152015215 unmodified lines152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315646 unmodified lines15711572157315741575157615771578157915801581158215831584158515861587158849 unmodified lines163816391640164116421643164431 unmodified lines167616771678167916801681168291 unmodified lines17741775177617771778177917801781170 unmodified lines195219531954195519561957195819591960196119621963196450 unmodified lines20152016201720182019202018 unmodified lines20392040204120422043204420452046204720482049205020512052205320542055205620572058205920604 unmodified lines2065206620672068206920702071207220732074207520762077207820792080208120824 unmodified lines2087208820892090209120921481 unmodified linesclass="input-field"id="messageInput"placeholder="Ask about tickets, bugs, or debugging..."onkeypress="handleKeyPress(event)"/><input type="file" id="imageInput" accept="image/*" style="display:none" /><div class="attach-indicator" id="attachIndicator"></div>19 unmodified lines</div><script>let conversationHistory = [];const chatStateKey = 'tandion_chat_state';const clientIdKey = 'tandion_client_id';let clientId = localStorage.getItem(clientIdKey);if (!clientId) {const fallbackId = 'client_' + Math.random().toString(36).slice(2);clientId = (crypto && crypto.randomUUID) ? crypto.randomUUID() : fallbackId;localStorage.setItem(clientIdKey, clientId);}let queryCount = 0;let sessionStart = Date.now();5 unmodified lineslet pendingImagePreviewUrl = null;function isReloadNavigation() {const navEntries = performance.getEntriesByType && performance.getEntriesByType('navigation');if (navEntries && navEntries.length > 0) {return navEntries[0].type === 'reload';}return performance.navigation && performance.navigation.type === 1;}function saveChatState() {const payload = {conversationHistory,queryCount,sessionStart,};sessionStorage.setItem(chatStateKey, JSON.stringify(payload));}function loadChatState() {if (isReloadNavigation()) {sessionStorage.removeItem(chatStateKey);return;}const raw = sessionStorage.getItem(chatStateKey);if (!raw) return;try {const state = JSON.parse(raw);conversationHistory = Array.isArray(state.conversationHistory) ? state.conversationHistory : [];queryCount = Number.isFinite(state.queryCount) ? state.queryCount : 0;sessionStart = Number.isFinite(state.sessionStart) ? state.sessionStart : Date.now();document.getElementById('queryCount').textContent = queryCount;const chatArea = document.getElementById('chatArea');const welcome = document.getElementById('welcomeCard');6 unmodified linesaddMessage(msg.content || '', isUser, msg.model_used || null, msg.image_url || null);});} catch (e) {sessionStorage.removeItem(chatStateKey);}}// Update session timesetInterval(() => {const mins = Math.floor((Date.now() - sessionStart) / 60000);document.getElementById('sessionTime').textContent = mins + 'm';}, 60000);function handleKeyPress(event) {if (event.key === 'Enter') sendMessage();}function updateAttachIndicator() {49 unmodified linesif (!dataUrl || !dataUrl.startsWith('data:image/')) return false;const parts = dataUrl.split(',');if (parts.length < 2) return false;const mimeMatch = parts[0].match(/^data:(image\/[a-zA-Z0-9.+-]+);base64$/);pendingImageBase64 = parts[1] || null;pendingImageMime = (mimeMatch && mimeMatch[1]) ? mimeMatch[1] : 'image/png';pendingImagePreviewUrl = dataUrl;31 unmodified lines// 3) HTML path with inline data URL imageconst html = clipboard.getData && clipboard.getData('text/html');if (html) {const dataUrlMatch = html.match(/src=["'](data:image\/[a-zA-Z0-9.+-]+;base64,[^"']+)["']/i);if (dataUrlMatch && setPendingImageFromDataUrl(dataUrlMatch[1])) {return true;}91 unmodified linesbubble.appendChild(txt);}} else {marked.setOptions({ gfm: true, breaks: true });bubble.innerHTML = marked.parse(text);// Wrap tables in scrollable containerconst tables = bubble.querySelectorAll('table');170 unmodified lines}accumulatedText += event.text;marked.setOptions({ gfm: true, breaks: true });assistantBubble.innerHTML = marked.parse(accumulatedText) + '<span class="typing-cursor">▌</span>';chatArea.scrollTop = chatArea.scrollHeight;} else if (event.type === 'done') {if (assistantBubble) {marked.setOptions({ gfm: true, breaks: true });assistantBubble.innerHTML = marked.parse(accumulatedText);// Wrap tables in scrollable containerconst tables = assistantBubble.querySelectorAll('table');50 unmodified lines}}} else {// Fallback to JSON response if not SSEconst data = await response.json();if (typing && typing.parentNode) typing.remove();18 unmodified linesif (typing && typing.parentNode) typing.remove();if (error.name === 'AbortError') {if (assistantBubble) {marked.setOptions({ gfm: true, breaks: true });assistantBubble.innerHTML = marked.parse(accumulatedText) + ' *(stopped)*';} else {addMessage('⏹️ Response stopped by user.', false);}} else {addMessage('Connection error. Please try again: ' + error.message, false);}}// Hide stop button and reset statestopBtn.classList.remove('visible');isGenerating = false;currentAbortController = null;sendBtn.disabled = false;input.focus();}function stopResponse() {4 unmodified lines}}// Initial status checkdocument.getElementById('imageInput').addEventListener('change', event => {const file = event.target.files && event.target.files[0];if (!file) return;setPendingImageFromFile(file, 'Attached image');});document.getElementById('messageInput').addEventListener('paste', event => {if (tryExtractImageFromClipboard(event)) {event.preventDefault();}});// Support paste when focus is outside the input (common with screenshots / copy as image).document.addEventListener('paste', event => {4 unmodified lines}});loadChatState();refreshStatus();setInterval(refreshStatus, 4000);1481 unmodified lines148214831484148514861487148819 unmodified lines150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415755 unmodified lines158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616276 unmodified lines163416351636163716381639164016411642164316441645164616471648164916501651165216531654165549 unmodified lines170517061707170817091710171131 unmodified lines174317441745174617471748174991 unmodified lines1841184218431844184518461847170 unmodified lines2018201920202021202220232024202520262027202850 unmodified lines2079208020812082208320842085208620872088208920902091209220932094209518 unmodified lines2114211521162117211821192120212121222123212421252126212721282129213021312132213321344 unmodified lines21392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221634 unmodified lines216821692170217121722173217421752176217721782179218021811481 unmodified linesclass="input-field"id="messageInput"placeholder="Ask about tickets, bugs, or debugging..."onkeydown="handleKeyPress(event)"/><input type="file" id="imageInput" accept="image/*" style="display:none" /><div class="attach-indicator" id="attachIndicator"></div>19 unmodified lines</div><script>// Safe storage helpers with in-memory fallback for iframe / cross-origin / privacy environments (Brave Shields, Safari, etc.)const memoryStorage = {};function safeGetItem(type, key) {try {const storage = type === 'local' ? window.localStorage : window.sessionStorage;if (storage) return storage.getItem(key);} catch (e) {// Storage blocked or restricted by browser}return memoryStorage[key] || null;}function safeSetItem(type, key, value) {try {const storage = type === 'local' ? window.localStorage : window.sessionStorage;if (storage) {storage.setItem(key, value);return;}} catch (e) {// Storage blocked}memoryStorage[key] = String(value);}function safeRemoveItem(type, key) {try {const storage = type === 'local' ? window.localStorage : window.sessionStorage;if (storage) {storage.removeItem(key);return;}} catch (e) {// Storage blocked}delete memoryStorage[key];}// Resilient markdown renderer with fallbackfunction renderMarkdown(text) {if (!text) return '';if (window.marked && typeof window.marked.parse === 'function') {try {window.marked.setOptions({ gfm: true, breaks: true });return window.marked.parse(text);} catch (e) {console.warn('Markdown parsing error:', e);}}const div = document.createElement('div');div.textContent = text;return div.innerHTML.replace(/\n/g, '<br>');}let conversationHistory = [];const chatStateKey = 'tandion_chat_state';const clientIdKey = 'tandion_client_id';let clientId = safeGetItem('local', clientIdKey);if (!clientId) {const fallbackId = 'client_' + Math.random().toString(36).slice(2);clientId = (window.crypto && window.crypto.randomUUID) ? window.crypto.randomUUID() : fallbackId;safeSetItem('local', clientIdKey, clientId);}let queryCount = 0;let sessionStart = Date.now();5 unmodified lineslet pendingImagePreviewUrl = null;function isReloadNavigation() {try {const navEntries = performance.getEntriesByType && performance.getEntriesByType('navigation');if (navEntries && navEntries.length > 0) {return navEntries[0].type === 'reload';}return performance.navigation && performance.navigation.type === 1;} catch (e) {return false;}}function saveChatState() {try {const payload = {conversationHistory,queryCount,sessionStart,};safeSetItem('session', chatStateKey, JSON.stringify(payload));} catch (e) {console.warn('saveChatState error:', e);}}function loadChatState() {try {if (isReloadNavigation()) {safeRemoveItem('session', chatStateKey);return;}const raw = safeGetItem('session', chatStateKey);if (!raw) return;const state = JSON.parse(raw);conversationHistory = Array.isArray(state.conversationHistory) ? state.conversationHistory : [];queryCount = Number.isFinite(state.queryCount) ? state.queryCount : 0;sessionStart = Number.isFinite(state.sessionStart) ? state.sessionStart : Date.now();const countEl = document.getElementById('queryCount');if (countEl) countEl.textContent = queryCount;const chatArea = document.getElementById('chatArea');const welcome = document.getElementById('welcomeCard');6 unmodified linesaddMessage(msg.content || '', isUser, msg.model_used || null, msg.image_url || null);});} catch (e) {safeRemoveItem('session', chatStateKey);}}// Update session timesetInterval(() => {const mins = Math.floor((Date.now() - sessionStart) / 60000);const timeEl = document.getElementById('sessionTime');if (timeEl) timeEl.textContent = mins + 'm';}, 60000);function handleKeyPress(event) {if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();sendMessage();}}function updateAttachIndicator() {49 unmodified linesif (!dataUrl || !dataUrl.startsWith('data:image/')) return false;const parts = dataUrl.split(',');if (parts.length < 2) return false;const mimeMatch = parts[0].match(/^data:(image\\/[a-zA-Z0-9.+-]+);base64$/);pendingImageBase64 = parts[1] || null;pendingImageMime = (mimeMatch && mimeMatch[1]) ? mimeMatch[1] : 'image/png';pendingImagePreviewUrl = dataUrl;31 unmodified lines// 3) HTML path with inline data URL imageconst html = clipboard.getData && clipboard.getData('text/html');if (html) {const dataUrlMatch = html.match(/src=["'](data:image\\/[a-zA-Z0-9.+-]+;base64,[^"']+)["']/i);if (dataUrlMatch && setPendingImageFromDataUrl(dataUrlMatch[1])) {return true;}91 unmodified linesbubble.appendChild(txt);}} else {bubble.innerHTML = renderMarkdown(text);// Wrap tables in scrollable containerconst tables = bubble.querySelectorAll('table');170 unmodified lines}accumulatedText += event.text;assistantBubble.innerHTML = renderMarkdown(accumulatedText) + '<span class="typing-cursor">▌</span>';chatArea.scrollTop = chatArea.scrollHeight;} else if (event.type === 'done') {if (assistantBubble) {assistantBubble.innerHTML = renderMarkdown(accumulatedText);// Wrap tables in scrollable containerconst tables = assistantBubble.querySelectorAll('table');50 unmodified lines}}} else {if (!response.ok) {if (typing && typing.parentNode) typing.remove();let errMsg = `Server returned status ${response.status}`;try {const errData = await response.json();if (errData && errData.error) errMsg = errData.error;} catch (_) {}addMessage('Error: ' + errMsg, false);return;}// Fallback to JSON response if not SSEconst data = await response.json();if (typing && typing.parentNode) typing.remove();18 unmodified linesif (typing && typing.parentNode) typing.remove();if (error.name === 'AbortError') {if (assistantBubble) {assistantBubble.innerHTML = renderMarkdown(accumulatedText) + ' *(stopped)*';} else {addMessage('⏹️ Response stopped by user.', false);}} else {addMessage('Connection error. Please try again: ' + error.message, false);}} finally {// Hide stop button and reset state unconditionallystopBtn.classList.remove('visible');isGenerating = false;currentAbortController = null;sendBtn.disabled = false;input.focus();}}function stopResponse() {4 unmodified lines}}// Initial setup and event listenersconst imageInputEl = document.getElementById('imageInput');if (imageInputEl) {imageInputEl.addEventListener('change', event => {const file = event.target.files && event.target.files[0];if (!file) return;setPendingImageFromFile(file, 'Attached image');});}const msgInputEl = document.getElementById('messageInput');if (msgInputEl) {msgInputEl.addEventListener('keydown', handleKeyPress);msgInputEl.addEventListener('paste', event => {if (tryExtractImageFromClipboard(event)) {event.preventDefault();}});}// Support paste when focus is outside the input (common with screenshots / copy as image).document.addEventListener('paste', event => {4 unmodified lines}});// Expose functions to window for inline onclick/onkeydown handlerswindow.sendMessage = sendMessage;window.handleKeyPress = handleKeyPress;window.quickAction = quickAction;window.clearChat = clearChat;window.stopResponse = stopResponse;window.clearPendingImage = clearPendingImage;loadChatState();refreshStatus();setInterval(refreshStatus, 4000);
web_ui.py+142-53