~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: Enhance frontend service layer with improved API, PDF, socket, and UI functionality
hashedviking4a3ed5fc6426
diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.jsindex 1aac503c5a..6db40ef7d2 100644--- a/src/local_deep_research/web/static/js/services/api.js+++ b/src/local_deep_research/web/static/js/services/api.js@@ -76,7 +76,7 @@ async function startResearch(query, mode) {* @returns {Promise<Object>} The research status*/async function getResearchStatus(researchId) {- return fetchWithErrorHandling(`/research/api/research/${researchId}`);+ return fetchWithErrorHandling(`/research/api/status/${researchId}`);}/**@@ -85,7 +85,7 @@ async function getResearchStatus(researchId) {* @returns {Promise<Object>} The research details*/async function getResearchDetails(researchId) {- return fetchWithErrorHandling(`/research/api/research/${researchId}/details`);+ return fetchWithErrorHandling(`/research/api/details/${researchId}`);}/**@@ -94,7 +94,7 @@ async function getResearchDetails(researchId) {* @returns {Promise<Object>} The research logs*/async function getResearchLogs(researchId) {- return fetchWithErrorHandling(`/research/api/research/${researchId}/logs`);+ return fetchWithErrorHandling(`/research/api/logs/${researchId}`);}/**@@ -120,7 +120,7 @@ async function getReport(researchId) {* @returns {Promise<Object>} The termination response*/async function terminateResearch(researchId) {- return postJSON(`/research/api/research/${researchId}/terminate`, {});+ return postJSON(`/research/api/terminate/${researchId}`, {});}/**@@ -129,7 +129,7 @@ async function terminateResearch(researchId) {* @returns {Promise<Object>} The deletion response*/async function deleteResearch(researchId) {- return fetchWithErrorHandling(`/research/api/research/${researchId}/delete`, {+ return fetchWithErrorHandling(`/research/api/delete/${researchId}`, {method: 'DELETE'});}@@ -211,7 +211,7 @@ async function saveLlmConfig(config) {* @returns {Promise<Object>} The markdown content*/async function getMarkdownExport(researchId) {- return fetchWithErrorHandling(`/research/api/research/${researchId}/markdown`);+ return fetchWithErrorHandling(`/research/api/markdown/${researchId}`);}// Export the API functionsdiff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsindex 7daa24fa39..cc6c6c9669 100644--- a/src/local_deep_research/web/static/js/services/pdf.js+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -5,17 +5,25 @@/*** Generate a PDF from the research content- * @param {string} title - The research title/query- * @param {string} content - The markdown content of the research+ * @param {string|any} title - The research title/query+ * @param {string|any} content - The markdown content of the research* @param {Object} metadata - Additional metadata for the PDF* @returns {Promise<Blob>} A promise resolving to the generated PDF blob*/async function generatePdf(title, content, metadata = {}) {// Check if necessary libraries are loaded- if (typeof jspdf === 'undefined' || typeof html2canvas === 'undefined') {- throw new Error('PDF generation libraries not loaded');+ if (typeof jspdf === 'undefined') {+ throw new Error('PDF generation libraries not loaded (jsPDF missing)');}+ if (typeof html2canvas === 'undefined') {+ throw new Error('PDF generation libraries not loaded (html2canvas missing)');+ }++ // Ensure title and content are strings+ title = String(title || 'Research Report');+ content = String(content || '');+// Create a temporary container to render the markdownconst tempContainer = document.createElement('div');tempContainer.style.position = 'absolute';@@ -32,6 +40,7 @@ async function generatePdf(title, content, metadata = {}) {color: #333;line-height: 1.5;padding: 20px;+ background-color: #ffffff;}.pdf-content h1 {font-size: 24px;@@ -125,6 +134,8 @@ async function generatePdf(title, content, metadata = {}) {<p>Generated: ${new Date().toLocaleString()}</p>${metadata.mode ? `<p>Mode: ${metadata.mode}</p>` : ''}${metadata.iterations ? `<p>Search iterations: ${metadata.iterations}</p>` : ''}+ ${metadata.id ? `<p>Research ID: ${metadata.id}</p>` : ''}+ ${metadata.timestamp ? `<p>Research Date: ${new Date(metadata.timestamp).toLocaleString()}</p>` : ''}</div><div class="pdf-body">${window.marked ? window.marked.parse(content) : content}@@ -138,76 +149,422 @@ async function generatePdf(title, content, metadata = {}) {document.body.appendChild(tempContainer);try {+ console.log("Starting PDF generation...");++ // Use the jsPDF library from the window object+ const { jsPDF } = window.jspdf;+// Create a new PDF document- const pdf = new jspdf.jsPDF({- orientation: 'portrait',- unit: 'pt',- format: 'letter'- });+ const pdf = new jsPDF('p', 'pt', 'letter');+ const pdfWidth = pdf.internal.pageSize.getWidth();+ const pdfHeight = pdf.internal.pageSize.getHeight();+ const margin = 40;+ const contentWidth = pdfWidth - 2 * margin;// Function to add page with header- const addPageWithHeader = (pageNum, totalPages) => {- pdf.setFont('helvetica', 'normal');+ const addPageWithHeader = (pageNum) => {+ if (pageNum > 1) {+ pdf.addPage();+ }pdf.setFontSize(8);pdf.setTextColor(100, 100, 100);- pdf.text(`Page ${pageNum} of ${totalPages || '?'}`, 40, 20);- pdf.text(`Generated: ${new Date().toLocaleString()}`, 450, 20, { align: 'right' });+ pdf.text(`Deep Research - ${title} - Page ${pageNum}`, margin, pdfHeight - 20);};- // Convert each page to image and add to PDF- // Get the computed width and height- const width = tempContainer.offsetWidth;- const height = tempContainer.offsetHeight;+ // Process each element with a more optimized approach+ const contentDiv = tempContainer.querySelector('.pdf-body');+ if (!contentDiv) {+ throw new Error('PDF body container not found');+ }- // Calculate how many pages we need- const pdfWidth = pdf.internal.pageSize.getWidth();- const pdfHeight = pdf.internal.pageSize.getHeight() - 40; // Account for margins- const totalPages = Math.ceil(height / pdfHeight);+ // Create a more efficient PDF generation approach that keeps text selectable+ const elements = Array.from(contentDiv.children);+ let currentY = margin;+ let pageNum = 1;- // Convert to canvas in chunks for each page- for (let i = 0; i < totalPages; i++) {- // If not the first page, add a new page- if (i > 0) {- pdf.addPage();- }-- // Add header to each page- addPageWithHeader(i + 1, totalPages);-- // Setup the page- const yPosition = i * pdfHeight;-- // Create canvas with the specific part of the content- const canvas = await html2canvas(tempContainer, {- y: yPosition,- height: Math.min(pdfHeight, height - yPosition),- windowHeight: Math.min(pdfHeight, height - yPosition) + 100,- scale: 1.5 // Higher quality- });+ // Add the first page with header+ addPageWithHeader(pageNum);++ // Process each element+ for (const element of elements) {+ // Skip style element+ if (element.tagName === 'STYLE') continue;- // Add to PDF- const imgData = canvas.toDataURL('image/png');- pdf.addImage(imgData, 'PNG', 30, 30, pdfWidth - 60, 0);+ try {+ // Simple text content - handled directly by jsPDF for better text selection+ if ((element.tagName === 'P' || element.tagName === 'DIV' || element.tagName === 'H1' ||+ element.tagName === 'H2' || element.tagName === 'H3') &&+ !element.querySelector('img, canvas, svg, table') &&+ !element.innerHTML.includes('<')) {++ pdf.setFont('helvetica', element.tagName.startsWith('H') ? 'bold' : 'normal');+ pdf.setFontSize(element.tagName === 'H1' ? 18 : (element.tagName === 'H2' ? 16 : (element.tagName === 'H3' ? 14 : 11)));+ pdf.setTextColor(0, 0, 0);++ const text = element.textContent.trim();+ if (!text) continue; // Skip empty text++ const textLines = pdf.splitTextToSize(text, contentWidth);++ // Check if we need a new page+ if (currentY + (textLines.length * 14) > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.text(textLines, margin, currentY + 12);+ currentY += (textLines.length * 14) + 10;+ }+ // List elements - handle bullets and numbering+ else if (element.tagName === 'UL' || element.tagName === 'OL') {+ const listItems = Array.from(element.querySelectorAll('li'));+ for (let i = 0; i < listItems.length; i++) {+ const item = listItems[i];+ const itemText = item.textContent.trim();+ if (!itemText) continue;++ pdf.setFont('helvetica', 'normal');+ pdf.setFontSize(11);+ pdf.setTextColor(0, 0, 0);++ const bulletPoint = element.tagName === 'UL' ? '•' : `${i + 1}.`;+ const textWithBullet = `${bulletPoint} ${itemText}`;+ const textLines = pdf.splitTextToSize(textWithBullet, contentWidth - 10);++ // Check if we need a new page+ if (currentY + (textLines.length * 14) > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.text(textLines, margin, currentY + 12);+ currentY += (textLines.length * 14) + 5;+ }+ currentY += 5; // Add some space after the list+ }+ // Tables - render with proper cells+ else if (element.tagName === 'TABLE') {+ const rows = Array.from(element.querySelectorAll('tr'));+ if (rows.length === 0) continue;++ // Get header cells+ const headerCells = Array.from(rows[0].querySelectorAll('th, td'));+ const colCount = headerCells.length || 1;+ const colWidth = contentWidth / colCount;++ // Start table at current position+ let tableY = currentY;++ // Check if we need a new page+ if (tableY + 20 > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ tableY = margin;+ }++ // Draw header background+ pdf.setFillColor(240, 240, 240);+ pdf.rect(margin, tableY, contentWidth, 20, 'F');++ // Draw header text+ pdf.setFont("helvetica", "bold");+ pdf.setFontSize(10);+ pdf.setTextColor(0, 0, 0);++ headerCells.forEach((cell, index) => {+ const text = cell.textContent.trim();+ const x = margin + (index * colWidth) + 5;+ pdf.text(text, x, tableY + 13);+ });++ // Draw horizontal line after header+ pdf.setDrawColor(200, 200, 200);+ pdf.setLineWidth(0.5);+ pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);++ tableY += 20;++ // Draw table rows+ pdf.setFont("helvetica", "normal");+ for (let i = 1; i < rows.length; i++) {+ // Check if we need a new page+ if (tableY + 20 > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ tableY = margin;++ // Redraw header on new page+ pdf.setFillColor(240, 240, 240);+ pdf.rect(margin, tableY, contentWidth, 20, 'F');++ pdf.setFont("helvetica", "bold");+ headerCells.forEach((cell, index) => {+ const text = cell.textContent.trim();+ const x = margin + (index * colWidth) + 5;+ pdf.text(text, x, tableY + 13);+ });++ pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);+ tableY += 20;+ pdf.setFont("helvetica", "normal");+ }++ // Get cells for this row+ const cells = Array.from(rows[i].querySelectorAll('td, th'));++ // Draw cell content+ cells.forEach((cell, index) => {+ const text = cell.textContent.trim();+ if (!text) return;++ const x = margin + (index * colWidth) + 5;+ pdf.text(text, x, tableY + 13);+ });++ // Draw horizontal line after row+ pdf.line(margin, tableY + 20, margin + contentWidth, tableY + 20);+ tableY += 20;+ }++ // Draw vertical lines+ for (let i = 0; i <= colCount; i++) {+ const x = margin + (i * colWidth);+ pdf.line(x, currentY, x, tableY);+ }++ // Update current position to after the table+ currentY = tableY + 10;+ }+ // Code blocks - render with monospace font and background+ else if (element.tagName === 'PRE' || element.querySelector('pre')) {+ const preElement = element.tagName === 'PRE' ? element : element.querySelector('pre');+ const codeText = preElement.textContent.trim();+ if (!codeText) continue;++ pdf.setFont("courier", "normal"); // Use monospace font for code+ pdf.setFontSize(9);+ pdf.setTextColor(0, 0, 0);++ // Split code into lines, respecting line breaks+ const codeLines = codeText.split(/\r?\n/);+ const wrappedLines = [];++ codeLines.forEach(line => {+ // Wrap long lines+ const wrappedLine = pdf.splitTextToSize(line, contentWidth - 20);+ wrappedLines.push(...wrappedLine);+ });++ // Calculate code block height+ const lineHeight = 12;+ const codeHeight = wrappedLines.length * lineHeight + 20; // 10px padding top and bottom++ // Check if we need a new page+ if (currentY + codeHeight > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ // Draw code block background+ pdf.setFillColor(245, 245, 245);+ pdf.rect(margin, currentY, contentWidth, codeHeight, 'F');++ // Draw code content+ pdf.setTextColor(0, 0, 0);+ wrappedLines.forEach((line, index) => {+ pdf.text(line, margin + 10, currentY + 15 + (index * lineHeight));+ });++ // Update position+ currentY += codeHeight + 10;+ }+ // Images - render as images+ else if (element.tagName === 'IMG' || element.querySelector('img')) {+ const imgElement = element.tagName === 'IMG' ? element : element.querySelector('img');++ if (!imgElement || !imgElement.src) continue;++ try {+ // Create a new image to get dimensions+ const img = new Image();+ img.src = imgElement.src;++ // Calculate dimensions+ const imgWidth = contentWidth;+ const imgHeight = img.height * (contentWidth / img.width);++ // Check if we need a new page+ if (currentY + imgHeight > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ // Add image to PDF+ pdf.addImage(img.src, 'JPEG', margin, currentY, imgWidth, imgHeight);+ currentY += imgHeight + 10;+ } catch (imgError) {+ console.error('Error adding image:', imgError);+ pdf.text("[Image could not be rendered]", margin, currentY + 12);+ currentY += 20;+ }+ }+ // Fallback for moderately complex elements - try to extract text first before using canvas+ else {+ // Try to extract text content and render it directly first+ const textContent = element.textContent.trim();++ if (textContent) {+ pdf.setFont('helvetica', 'normal');+ pdf.setFontSize(11);+ pdf.setTextColor(0, 0, 0);++ const textLines = pdf.splitTextToSize(textContent, contentWidth);++ // Check if we need a new page+ if (currentY + (textLines.length * 14) > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.text(textLines, margin, currentY + 12);+ currentY += (textLines.length * 14) + 10;+ } else {+ // Only use html2canvas as a last resort for elements with no text content+ try {+ const canvas = await html2canvas(element, {+ scale: 2,+ useCORS: true,+ logging: false,+ backgroundColor: '#FFFFFF'+ });++ const imgData = canvas.toDataURL('image/png');+ const imgWidth = contentWidth;+ const imgHeight = (canvas.height * contentWidth) / canvas.width;++ if (currentY + imgHeight > pdfHeight - margin) {+ pageNum++;+ addPageWithHeader(pageNum);+ currentY = margin;+ }++ pdf.addImage(imgData, 'PNG', margin, currentY, imgWidth, imgHeight);+ currentY += imgHeight + 10;+ } catch (canvasError) {+ console.error('Error rendering complex element:', canvasError);+ pdf.text("[Content could not be rendered]", margin, currentY + 12);+ currentY += 20;+ }+ }+ }+ } catch (elementError) {+ console.error('Error processing element:', elementError);+ pdf.text("[Error rendering content]", margin, currentY + 12);+ currentY += 20;+ }}// Generate the PDF blobconst blob = pdf.output('blob');+ console.log("PDF generation completed successfully");return blob;+ } catch (error) {+ console.error('Error in PDF generation:', error);+ throw error;} finally {// Clean up- document.body.removeChild(tempContainer);+ if (document.body.contains(tempContainer)) {+ document.body.removeChild(tempContainer);+ }}}/*** Generate and download a PDF from research content- * @param {string} title - The research title/query- * @param {string} content - The markdown content of the research+ * @param {Object|string} titleOrData - Either the research title or the entire research data object+ * @param {string|null} content - The markdown content of the research, or research ID if first param is data object* @param {Object} metadata - Additional metadata for the PDF* @returns {Promise<void>} A promise that resolves when the PDF has been downloaded*/-async function downloadPdf(title, content, metadata = {}) {+async function downloadPdf(titleOrData, content, metadata = {}) {try {+ console.log("Starting PDF download process...");++ let title, pdfContent, pdfMetadata;++ // Determine if we're being passed a research data object or direct parameters+ if (typeof titleOrData === 'object' && titleOrData !== null) {+ // We were passed a research data object+ const researchData = titleOrData;+ const researchId = content; // Second parameter is research ID in this case++ console.log("Processing research data object", { researchId });++ // Extract title from research data+ title = researchData.query || researchData.title || researchData.prompt || `Research ${researchId}`;++ // Extract content - try all possible locations based on how data might be structured+ if (researchData.markdown) {+ pdfContent = researchData.markdown;+ } else if (researchData.content) {+ pdfContent = researchData.content;+ } else if (researchData.text) {+ pdfContent = researchData.text;+ } else if (researchData.summary) {+ pdfContent = researchData.summary;+ } else if (researchData.results && Array.isArray(researchData.results)) {+ pdfContent = researchData.results.join('\n\n');+ } else if (researchData.report) {+ pdfContent = researchData.report;+ } else if (researchData.research && researchData.research.content) {+ pdfContent = researchData.research.content;+ } else if (researchData.html) {+ // If we have HTML, convert it to a reasonable markdown-like format+ pdfContent = researchData.html+ .replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')+ .replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')+ .replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')+ .replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')+ .replace(/<li[^>]*>(.*?)<\/li>/gi, '- $1\n')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<(?:.|\n)*?>/gm, '') // Remove remaining HTML tags+ .replace(/ /gi, ' ')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/&/gi, '&')+ .replace(/"/gi, '"')+ .replace(/'/gi, "'")+ .replace(/\n{3,}/g, '\n\n'); // Normalize excessive newlines+ } else {+ // Last resort: stringify the entire object+ console.warn("Could not find content in research data, using JSON stringification");+ pdfContent = JSON.stringify(researchData, null, 2);+ }++ // Extract metadata+ pdfMetadata = {+ mode: researchData.mode,+ iterations: researchData.iterations,+ timestamp: researchData.timestamp || researchData.created_at || new Date().toISOString(),+ id: researchId+ };+ } else {+ // We were passed direct parameters+ title = titleOrData || 'Research Report';+ pdfContent = content || '';+ pdfMetadata = metadata || {};+ }++ // Ensure title is a string+ title = String(title || 'Research Report');++ console.log("PDF parameters prepared", { titleLength: title.length, contentLength: pdfContent?.length });+// Show loading indicatorconst loadingIndicator = document.createElement('div');loadingIndicator.className = 'loading-indicator';@@ -224,7 +581,7 @@ async function downloadPdf(title, content, metadata = {}) {document.body.appendChild(loadingIndicator);// Generate the PDF- const blob = await generatePdf(title, content, metadata);+ const blob = await generatePdf(title, pdfContent, pdfMetadata);// Create a download linkconst url = URL.createObjectURL(blob);@@ -232,7 +589,7 @@ async function downloadPdf(title, content, metadata = {}) {downloadLink.href = url;// Generate a filename based on the title- const safeTitle = title.replace(/[^a-z0-9]/gi, '_').toLowerCase();+ const safeTitle = title.replace(/[^a-z0-9]/gi, '_').toLowerCase().substring(0, 30);downloadLink.download = `${safeTitle}_research.pdf`;// Trigger the download@@ -242,9 +599,13 @@ async function downloadPdf(title, content, metadata = {}) {// Clean updocument.body.removeChild(downloadLink);URL.revokeObjectURL(url);++ console.log("PDF download process completed");+ return true;} catch (error) {console.error('Error generating PDF:', error);- alert('Error generating PDF: ' + error.message);+ alert('Error generating PDF: ' + (error.message || 'Unknown error'));+ throw error;} finally {// Remove loading indicatorconst loadingIndicator = document.querySelector('.loading-indicator');diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex 0b3c0e2a40..ad2f23d81d 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -7,10 +7,15 @@ window.socket = (function() {let socket = null;let researchEventHandlers = {};let reconnectCallback = null;+ let connectionAttempts = 0;+ const MAX_CONNECTION_ATTEMPTS = 3;// Keep track of the research we're currently subscribed tolet currentResearchId = null;+ // Track if we're using polling fallback+ let usingPolling = false;+/*** Initialize the Socket.IO connection*/@@ -25,17 +30,21 @@ window.socket = (function() {// Create a new socket instancetry {+ // Use polling only to avoid WebSocket issuessocket = io(baseUrl, {path: '/research/socket.io',reconnection: true,reconnectionDelay: 1000,- reconnectionAttempts: 5+ reconnectionAttempts: 5,+ transports: ['polling'] // Use only polling to avoid WebSocket issues});setupSocketEvents();- console.log('Socket.IO initialized');+ console.log('Socket.IO initialized with polling only strategy');} catch (error) {console.error('Error initializing Socket.IO:', error);+ // Set a flag that we're not connected - will use polling for updates+ usingPolling = true;}return socket;@@ -47,6 +56,8 @@ window.socket = (function() {function setupSocketEvents() {socket.on('connect', () => {console.log('Socket connected');+ connectionAttempts = 0;+ usingPolling = false;// Re-subscribe to current research if anyif (currentResearchId) {@@ -59,12 +70,33 @@ window.socket = (function() {}});+ socket.on('connect_error', (error) => {+ console.warn('Socket connection error:', error);+ connectionAttempts++;++ if (connectionAttempts >= MAX_CONNECTION_ATTEMPTS) {+ console.warn(`Failed to connect after ${MAX_CONNECTION_ATTEMPTS} attempts, falling back to polling`);+ usingPolling = true;++ // If we can't establish a socket connection, use polling for any active research+ if (currentResearchId && typeof window.pollResearchStatus === 'function') {+ window.pollResearchStatus(currentResearchId);+ }+ }+ });+socket.on('disconnect', (reason) => {console.log('Socket disconnected:', reason);++ // Fall back to polling on disconnect+ if (currentResearchId) {+ fallbackToPolling(currentResearchId);+ }});socket.on('reconnect', (attemptNumber) => {console.log('Socket reconnected after', attemptNumber, 'attempts');+ connectionAttempts = 0;});socket.on('reconnect_attempt', (attemptNumber) => {@@ -73,15 +105,21 @@ window.socket = (function() {socket.on('error', (error) => {console.error('Socket error:', error);++ // Fall back to polling on any error+ if (currentResearchId) {+ fallbackToPolling(currentResearchId);+ }});}/*** Subscribe to research events* @param {string} researchId - The research ID to subscribe to+ * @param {function} callback - Optional callback for progress updates*/- function subscribeToResearch(researchId) {- if (!socket) {+ function subscribeToResearch(researchId, callback) {+ if (!socket && !usingPolling) {console.warn('Socket not initialized, initializing now');initializeSocket();}@@ -96,29 +134,327 @@ window.socket = (function() {// Remember the current research IDcurrentResearchId = researchId;- // Join the research room- socket.emit('join', { research_id: researchId });+ // Add the callback if provided+ if (callback && typeof callback === 'function') {+ addResearchEventHandler(researchId, callback);+ }++ // If we have a socket connection, join the research room+ if (socket && socket.connected) {+ try {+ socket.emit('join', { research_id: researchId });++ // Setup direct event handler for progress updates+ socket.on(`progress_${researchId}`, (data) => {+ handleProgressUpdate(researchId, data);+ });+ } catch (error) {+ console.error('Error subscribing to research:', error);+ fallbackToPolling(researchId);+ }+ } else {+ // If no socket connection, use polling+ fallbackToPolling(researchId);+ }+ }++ /**+ * Handle progress updates from research+ * @param {string} researchId - The research ID this update is for+ * @param {Object} data - The progress data+ */+ function handleProgressUpdate(researchId, data) {+ console.log('Progress update for research', researchId, ':', data);- // Setup direct event handler for progress updates- socket.on(`progress_${researchId}`, (data) => {- console.log('Progress update:', data);+ // Call all registered event handlers for this research+ if (researchEventHandlers[researchId]) {+ researchEventHandlers[researchId].forEach(handler => {+ try {+ handler(data);+ } catch (error) {+ console.error('Error in progress update handler:', error);+ }+ });+ }++ // Initialize message tracking if not exists+ window._processedSocketMessages = window._processedSocketMessages || new Map();++ // Process logs from progress_log if available+ if (data.progress_log && typeof data.progress_log === 'string') {+ try {+ const progressLogs = JSON.parse(data.progress_log);+ if (Array.isArray(progressLogs) && progressLogs.length > 0) {+ console.log(`Socket received ${progressLogs.length} logs in progress_log`);++ // Process each log entry+ progressLogs.forEach(logItem => {+ // Skip if no message or time+ if (!logItem.message || !logItem.time) return;++ // Generate a unique key for this message+ const messageKey = `${logItem.time}-${logItem.message}`;++ // Skip if we've seen this exact message before+ if (window._processedSocketMessages.has(messageKey)) {+ console.log('Skipping duplicate socket message:', logItem.message);+ return;+ }++ // Record that we've processed this message+ window._processedSocketMessages.set(messageKey, Date.now());++ // Determine log type based on metadata+ let logType = 'info';+ if (logItem.metadata) {+ if (logItem.metadata.phase === 'iteration_complete' ||+ logItem.metadata.phase === 'report_complete' ||+ logItem.metadata.phase === 'complete' ||+ logItem.metadata.phase === 'search_complete' ||+ logItem.metadata.is_milestone === true ||+ logItem.metadata.type === 'milestone') {+ logType = 'milestone';+ } else if (logItem.metadata.phase === 'error' ||+ logItem.metadata.type === 'error') {+ logType = 'error';+ }+ }++ // Also check for keywords in the message for better milestone detection+ if (logType !== 'milestone' && logItem.message) {+ const msg = logItem.message.toLowerCase();+ if (msg.includes('complete') ||+ msg.includes('finished') ||+ msg.includes('starting phase') ||+ msg.includes('generated report')) {+ logType = 'milestone';+ } else if (msg.includes('error') || msg.includes('failed')) {+ logType = 'error';+ }+ }++ // Send to log panel+ if (typeof window.addConsoleLog === 'function') {+ // Use the main console log function if available+ window.addConsoleLog(logItem.message, logType, logItem.metadata);+ } else if (typeof window._socketAddLogEntry === 'function') {+ // Fallback to the direct connector if needed+ const logEntry = {+ time: logItem.time,+ message: logItem.message,+ type: logType,+ metadata: logItem.metadata || {}+ };+ window._socketAddLogEntry(logEntry);+ } else {+ console.warn('No log handler function available for log:', logItem);+ }+ });++ // Clean up old entries from message tracking (keep only last 5 minutes)+ const now = Date.now();+ for (const [key, timestamp] of window._processedSocketMessages.entries()) {+ if (now - timestamp > 5 * 60 * 1000) { // 5 minutes+ window._processedSocketMessages.delete(key);+ }+ }+ }+ } catch (error) {+ console.error('Error processing progress_log:', error);+ }+ }++ // If the event contains log data, add it to the console+ if (data.log_entry) {+ console.log('Adding log entry from socket event:', data.log_entry);++ // Make sure global tracking is initialized+ window._processedSocketMessages = window._processedSocketMessages || new Map();++ // Generate a message key+ const messageKey = `${data.log_entry.time || new Date().toISOString()}-${data.log_entry.message}`;++ // Skip if we've seen this message before+ if (window._processedSocketMessages.has(messageKey)) {+ console.log('Skipping duplicate individual log entry:', data.log_entry.message);+ return;+ }++ // Record that we've processed this message+ window._processedSocketMessages.set(messageKey, Date.now());++ if (typeof window.addConsoleLog === 'function') {+ window.addConsoleLog(+ data.log_entry.message,+ data.log_entry.type ||+ (data.log_entry.metadata && data.log_entry.metadata.type) ||+ 'info',+ data.log_entry.metadata+ );+ } else if (typeof window._socketAddLogEntry === 'function') {+ window._socketAddLogEntry(data.log_entry);+ } else {+ console.warn('No log handler function available for direct log entry');+ }+ } else if (data.message && typeof window.addConsoleLog === 'function') {+ // Use the message field if no specific log entry+ console.log('Adding message from socket event:', data.message);- // Call all registered handlers for this research- if (researchEventHandlers[researchId]) {- researchEventHandlers[researchId].forEach(callback => {+ // Skip duplicate general messages too+ const messageKey = `${new Date().toISOString()}-${data.message}`;+ if (window._processedSocketMessages.has(messageKey)) {+ console.log('Skipping duplicate message:', data.message);+ return;+ }++ // Record this message+ window._processedSocketMessages.set(messageKey, Date.now());++ window.addConsoleLog(data.message, determineLogLevel(data.status));+ }+ }++ /**+ * Determine log level based on status+ * @param {string} status - The research status+ * @returns {string} Log level (info, milestone, error, etc)+ */+ function determineLogLevel(status) {+ if (!status) return 'info';++ if (status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'error') {+ return 'milestone';+ }++ if (status === 'error' || status.includes('error')) {+ return 'error';+ }++ return 'info';+ }++ /**+ * Add a log entry to the console log container+ * @param {Object} logEntry - The log entry data+ */+ function addLogEntry(logEntry) {+ // If the logpanel's log function is available, use it+ if (typeof window._socketAddLogEntry === 'function') {+ console.log('Using logpanel\'s _socketAddLogEntry for log:', logEntry.message);+ window._socketAddLogEntry(logEntry);+ return;+ }++ // If window.addConsoleLog is available, use it+ if (typeof window.addConsoleLog === 'function') {+ console.log('Using window.addConsoleLog for log:', logEntry.message);+ let logLevel = 'info';+ if (logEntry.type) {+ logLevel = logEntry.type;+ } else if (logEntry.metadata && logEntry.metadata.type) {+ logLevel = logEntry.metadata.type;+ }+ window.addConsoleLog(logEntry.message, logLevel, logEntry.metadata);+ return;+ }++ // Fallback implementation if none of the above is available+ console.log('Using socket.js fallback log implementation for:', logEntry.message);+ const consoleLogContainer = document.getElementById('console-log-container');+ if (!consoleLogContainer) return;++ // Clear empty message if present+ const emptyMessage = consoleLogContainer.querySelector('.empty-log-message');+ if (emptyMessage) {+ emptyMessage.remove();+ }++ // Get the log template+ const template = document.getElementById('console-log-entry-template');+ if (!template) {+ console.error('Console log entry template not found');+ return;+ }++ // Create a new log entry from the template+ const entry = document.importNode(template.content, true);++ // Determine the log level+ let logLevel = 'info';+ if (logEntry.metadata && logEntry.metadata.type) {+ logLevel = logEntry.metadata.type;+ } else if (logEntry.metadata && logEntry.metadata.phase) {+ if (logEntry.metadata.phase === 'complete' ||+ logEntry.metadata.phase === 'iteration_complete' ||+ logEntry.metadata.phase === 'report_complete') {+ logLevel = 'milestone';+ }+ }++ // Format the timestamp+ const timestamp = new Date(logEntry.time);+ const timeStr = timestamp.toLocaleTimeString();++ // Set content+ entry.querySelector('.log-timestamp').textContent = timeStr;+ entry.querySelector('.log-badge').textContent = logLevel.charAt(0).toUpperCase() + logLevel.slice(1);+ entry.querySelector('.log-badge').className = `log-badge ${logLevel}`;+ entry.querySelector('.log-message').textContent = logEntry.message;++ // Add to container (at the beginning for newest first)+ consoleLogContainer.insertBefore(entry, consoleLogContainer.firstChild);++ // Update log count+ const logIndicator = document.getElementById('log-indicator');+ if (logIndicator) {+ const currentCount = parseInt(logIndicator.textContent) || 0;+ logIndicator.textContent = currentCount + 1;+ }+ }++ /**+ * Fall back to polling for research updates+ * @param {string} researchId - The research ID+ */+ function fallbackToPolling(researchId) {+ console.log('Falling back to polling for research', researchId);+ usingPolling = true;++ // Start polling if the global polling function exists+ if (typeof window.pollResearchStatus === 'function') {+ window.pollResearchStatus(researchId);+ } else {+ // Define a simple polling function if it doesn't exist+ window.pollResearchStatus = function(id) {+ if (!window.api || !window.api.getResearchStatus) {+ console.error('API service not available for polling');+ return;+ }++ const pollInterval = setInterval(async () => {try {- callback(data);+ const data = await window.api.getResearchStatus(id);+ if (data) {+ handleProgressUpdate(id, data);++ // Stop polling if the research is complete+ if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ clearInterval(pollInterval);+ }+ }} catch (error) {- console.error('Error in research event handler:', error);+ console.error('Error polling research status:', error);}- });- }+ }, 3000);++ // Store the interval ID for later cleanup+ window.pollIntervals = window.pollIntervals || {};+ window.pollIntervals[id] = pollInterval;+ };- // If the event contains log data, add it to the console- if (data.log && window.addConsoleLog) {- window.addConsoleLog(data.log.message, data.log.type || 'info');- }- });+ // Start polling for this research+ window.pollResearchStatus(researchId);+ }}/**@@ -126,20 +462,37 @@ window.socket = (function() {* @param {string} researchId - The research ID to unsubscribe from*/function unsubscribeFromResearch(researchId) {- if (!socket) return;+ if (!researchId) return;console.log('Unsubscribing from research:', researchId);- // Leave the research room- socket.emit('leave', { research_id: researchId });+ // Clear any polling intervals+ if (window.pollIntervals && window.pollIntervals[researchId]) {+ clearInterval(window.pollIntervals[researchId]);+ delete window.pollIntervals[researchId];+ }- // Remove the event handler- socket.off(`progress_${researchId}`);+ // If we have a socket connection, leave the research room+ if (socket && socket.connected) {+ try {+ // Leave the research room+ socket.emit('leave', { research_id: researchId });++ // Remove the event handler+ socket.off(`progress_${researchId}`);+ } catch (error) {+ console.error('Error unsubscribing from research:', error);+ }+ }// Clear handlersif (researchId === currentResearchId) {currentResearchId = null;- researchEventHandlers[researchId] = [];+ }++ // Clear event handlers+ if (researchEventHandlers[researchId]) {+ delete researchEventHandlers[researchId];}}@@ -159,8 +512,10 @@ window.socket = (function() {researchEventHandlers[researchId] = [];}- // Add the handler- researchEventHandlers[researchId].push(callback);+ // Add the handler if it's not already in the array+ if (!researchEventHandlers[researchId].includes(callback)) {+ researchEventHandlers[researchId].push(callback);+ }}/**@@ -171,12 +526,17 @@ window.socket = (function() {function removeResearchEventHandler(researchId, callback) {if (!researchId || !researchEventHandlers[researchId]) return;- // Find the handler index- const index = researchEventHandlers[researchId].indexOf(callback);-- // Remove if found- if (index !== -1) {- researchEventHandlers[researchId].splice(index, 1);+ if (callback) {+ // Find the handler index+ const index = researchEventHandlers[researchId].indexOf(callback);++ // Remove if found+ if (index !== -1) {+ researchEventHandlers[researchId].splice(index, 1);+ }+ } else {+ // Remove all handlers for this research+ delete researchEventHandlers[researchId];}}@@ -192,21 +552,43 @@ window.socket = (function() {* Disconnect the socket*/function disconnectSocket() {+ // Clear any polling intervals+ if (window.pollIntervals) {+ Object.keys(window.pollIntervals).forEach(id => {+ clearInterval(window.pollIntervals[id]);+ });+ window.pollIntervals = {};+ }+if (socket) {- socket.disconnect();+ try {+ socket.disconnect();+ } catch (error) {+ console.error('Error disconnecting socket:', error);+ }socket = null;- researchEventHandlers = {};- reconnectCallback = null;- currentResearchId = null;}++ researchEventHandlers = {};+ reconnectCallback = null;+ currentResearchId = null;+ connectionAttempts = 0;+ usingPolling = false;}/**- * Filter log messages by type+ * Filter logs by type* @param {string} type - The log type to filter by ('all', 'info', 'error', 'milestone')*/function filterLogsByType(type) {- console.log('Filtering logs by type:', type);+ // If the logpanel's filter function is available, use it+ if (typeof window.filterLogsByType === 'function') {+ console.log('Using logpanel\'s filterLogsByType for filter:', type);+ window.filterLogsByType(type);+ return;+ }++ console.log('Using socket.js filtering implementation for:', type);// Update button UIconst buttons = document.querySelectorAll('.filter-buttons .small-btn');@@ -222,6 +604,17 @@ window.socket = (function() {const logEntries = document.querySelectorAll('.console-log-entry');logEntries.forEach(entry => {+ // Use dataset for type if available (new way)+ if (entry.dataset && entry.dataset.logType) {+ if (type === 'all' || entry.dataset.logType === type) {+ entry.style.display = '';+ } else {+ entry.style.display = 'none';+ }+ return;+ }++ // Fallback to badge content (old way)const badge = entry.querySelector('.log-badge');const logType = badge ? badge.textContent.toLowerCase() : 'info';@@ -246,11 +639,28 @@ window.socket = (function() {}}- // Initialize socket on load- initializeSocket();+ /**+ * Check if socket is connected+ * @returns {boolean} True if connected+ */+ function isConnected() {+ return socket && socket.connected;+ }++ /**+ * Check if we're using polling fallback+ * @returns {boolean} True if using polling+ */+ function isUsingPolling() {+ return usingPolling;+ }++ // Initialize socket on load with a small delay to ensure document is ready+ setTimeout(initializeSocket, 100);- // Expose the log filtering function globally+ // Expose functions globallywindow.filterLogsByType = filterLogsByType;+ window._socketAddLogEntry = addLogEntry; // Expose the addLogEntry function// Public APIreturn {@@ -259,6 +669,154 @@ window.socket = (function() {unsubscribeFromResearch,onReconnect: setReconnectCallback,disconnect: disconnectSocket,- getSocketInstance: () => socket+ getSocketInstance: () => socket,+ isConnected,+ isUsingPolling+ };+})();++/**+ * Register global functions for filtering logs - ONLY if they don't already exist+ */+if (!window.filterLogsByType) {+ window.filterLogsByType = function(type) {+ console.log('Filter logs by type (socket.js fallback):', type);+ // If the socket object exists and has the function+ if (window.socket && typeof window.socket.filterLogsByType === 'function') {+ window.socket.filterLogsByType(type);+ return;+ }++ // Otherwise do basic filtering+ const logEntries = document.querySelectorAll('.console-log-entry');+ logEntries.forEach(entry => {+ // Try using dataset first (new way)+ if (entry.dataset && entry.dataset.logType) {+ if (type === 'all' || entry.dataset.logType === type.toLowerCase()) {+ entry.style.display = '';+ } else {+ entry.style.display = 'none';+ }+ return;+ }++ // Fallback to badge (old way)+ const badge = entry.querySelector('.log-badge');+ const logType = badge ? badge.textContent.toLowerCase() : 'info';++ if (type === 'all' || logType === type.toLowerCase()) {+ entry.style.display = '';+ } else {+ entry.style.display = 'none';+ }+ });+ };+}++/**+ * Function to add a log entry to the console - Only create if it doesn't exist+ * @param {string} message - Log message+ * @param {string} level - Log level (info, milestone, error)+ * @param {Object} metadata - Optional metadata+ */+if (!window.addConsoleLog) {+ window.addConsoleLog = function(message, level = 'info', metadata = null) {+ console.log(`Adding console log (socket.js fallback): ${message} (${level})`);++ // Create a log entry object+ const logEntry = {+ time: new Date().toISOString(),+ message: message,+ type: level,+ metadata: metadata || { type: level }+ };++ // Try to use the log panel's direct function first+ if (window.logPanel && typeof window.logPanel.addLog === 'function') {+ console.log('Using logPanel.addLog to add log entry');+ window.logPanel.addLog(message, level, metadata);+ return;+ }++ // Then try the socket's connector function+ if (window._socketAddLogEntry) {+ console.log('Using _socketAddLogEntry to add log entry');+ window._socketAddLogEntry(logEntry);+ return;+ }++ console.warn('LogPanel functions not available, using fallback implementation');++ // FALLBACK IMPLEMENTATION+ const consoleLogContainer = document.getElementById('console-log-container');+ if (!consoleLogContainer) {+ console.warn('Console log container not found, log will be lost');+ return;+ }++ // Clear empty message if present+ const emptyMessage = consoleLogContainer.querySelector('.empty-log-message');+ if (emptyMessage) {+ emptyMessage.remove();+ }++ // Get or create a new log entry+ const template = document.getElementById('console-log-entry-template');+ let entry;++ if (template) {+ entry = document.importNode(template.content, true);++ // Set content+ entry.querySelector('.log-timestamp').textContent = new Date().toLocaleTimeString();+ entry.querySelector('.log-badge').textContent = level.charAt(0).toUpperCase() + level.slice(1);+ entry.querySelector('.log-badge').className = `log-badge ${level}`;+ entry.querySelector('.log-message').textContent = message;++ // Add data attribute for filtering+ const logEntry = entry.querySelector('.console-log-entry');+ if (logEntry) {+ logEntry.dataset.logType = level.toLowerCase();+ logEntry.classList.add(`log-${level.toLowerCase()}`);+ }+ } else {+ // Create a simple log entry without template+ entry = document.createElement('div');+ entry.className = 'console-log-entry';+ entry.dataset.logType = level.toLowerCase();+ entry.classList.add(`log-${level.toLowerCase()}`);++ // Create log content+ entry.innerHTML = `+ <span class="log-timestamp">${new Date().toLocaleTimeString()}</span>+ <span class="log-badge ${level}">${level.charAt(0).toUpperCase() + level.slice(1)}</span>+ <span class="log-message">${message}</span>+ `;+ }++ // Add to container (at the beginning for newest first)+ consoleLogContainer.insertBefore(entry, consoleLogContainer.firstChild);++ // Update log count+ const logIndicator = document.getElementById('log-indicator');+ if (logIndicator) {+ const currentCount = parseInt(logIndicator.textContent) || 0;+ logIndicator.textContent = currentCount + 1;+ }++ // Show log panel if hidden+ const logPanelToggle = document.getElementById('log-panel-toggle');+ const logPanelContent = document.getElementById('log-panel-content');++ if (logPanelContent && logPanelContent.classList.contains('collapsed') && logPanelToggle) {+ // Auto-expand after a few logs+ if (!window._logAutoExpandTimer) {+ window._logAutoExpandTimer = setTimeout(() => {+ console.log('Auto-expanding log panel due to accumulated logs');+ logPanelToggle.click();+ window._logAutoExpandTimer = null;+ }, 500);+ }+ }};-})();\ No newline at end of file+}\ No newline at end of filediff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 6588c29510..8ba933dd20 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -157,23 +157,75 @@ function showMessage(message, type = 'success', duration = 3000) {* @returns {string} The rendered HTML*/function renderMarkdown(markdown) {- if (!markdown) return '';+ if (!markdown) {+ return '<div class="alert alert-warning">No content available</div>';+ }try {- if (window.marked) {- // Add a wrapper for proper styling- return `<div class="markdown-content">${window.marked.parse(markdown)}</div>`;+ // Use marked library if available+ if (typeof marked !== 'undefined') {+ // Configure marked options+ marked.setOptions({+ breaks: true,+ gfm: true,+ headerIds: true,+ smartLists: true,+ smartypants: true,+ highlight: function(code, language) {+ // Use Prism for syntax highlighting if available+ if (typeof Prism !== 'undefined' && Prism.languages[language]) {+ return Prism.highlight(code, Prism.languages[language], language);+ }+ return code;+ }+ });++ // Parse markdown and return HTML+ const html = marked.parse(markdown);++ // Process any special elements like image references+ const processedHtml = processSpecialMarkdown(html);++ return `<div class="markdown-content">${processedHtml}</div>`;} else {- // Fallback if marked is not available- console.warn('Marked library not available for rendering markdown');- return `<pre>${markdown}</pre>`;+ // Basic fallback if marked is not available+ console.warn('Marked library not available. Using basic formatting.');+ const basic = markdown+ .replace(/\n\n/g, '<br><br>')+ .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')+ .replace(/\*(.*?)\*/g, '<em>$1</em>')+ .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>');++ return `<div class="markdown-content">${basic}</div>`;}} catch (error) {console.error('Error rendering markdown:', error);- return `<pre>${markdown}</pre>`;+ return `<div class="alert alert-danger">Error rendering content: ${error.message}</div>`;}}+/**+ * Process special markdown elements+ * @param {string} html - HTML content to process+ * @returns {string} - Processed HTML+ */+function processSpecialMarkdown(html) {+ // Process image references+ return html.replace(/\!\[ref:([^\]]+)\]/g, (match, ref) => {+ // Check if this is a reference to a generated image+ if (ref.startsWith('image-')) {+ return `<div class="generated-image" data-image-id="${ref}">+ <img src="/research/static/img/generated/${ref}.png"+ alt="Generated image ${ref}"+ class="img-fluid"+ loading="lazy" />+ <div class="image-caption">Generated image (${ref})</div>+ </div>`;+ }+ return match;+ });+}+/*** Create a dynamic favicon* @param {string} emoji - The emoji to use for the favicon@@ -214,46 +266,65 @@ function createDynamicFavicon(emoji = '⚡') {}/**- * Update favicon to indicate status- * @param {string} status - Status to indicate (active, complete, error)+ * Update favicon based on status+ * @param {string} status - The research status*/function updateFavicon(status) {try {- const faviconLink = document.querySelector('link[rel="icon"]') ||- document.querySelector('link[rel="shortcut icon"]');+ // Find favicon link or create it if it doesn't exist+ let link = document.querySelector("link[rel='icon']") ||+ document.querySelector("link[rel='shortcut icon']");- if (!faviconLink) {- console.warn('Favicon link not found');- return;+ if (!link) {+ console.log('Favicon link not found, creating a new one');+ link = document.createElement('link');+ link.rel = 'icon';+ link.type = 'image/x-icon';+ document.head.appendChild(link);}- let iconPath;- switch (status) {- case 'active':- case 'in_progress':- iconPath = '/research/static/img/favicon-active.ico';- break;- case 'completed':- case 'complete':- iconPath = '/research/static/img/favicon-complete.ico';- break;- case 'failed':- case 'error':- iconPath = '/research/static/img/favicon-error.ico';- break;- case 'cancelled':- case 'cancel':- iconPath = '/research/static/img/favicon-cancel.ico';- break;- default:- iconPath = '/research/static/img/favicon.ico';+ // Create dynamic favicon using canvas+ const canvas = document.createElement('canvas');+ canvas.width = 32;+ canvas.height = 32;+ const ctx = canvas.getContext('2d');++ // Background color based on status+ let bgColor = '#007bff'; // Default blue++ if (status === 'completed') {+ bgColor = '#28a745'; // Success green+ } else if (status === 'failed' || status === 'error') {+ bgColor = '#dc3545'; // Error red+ } else if (status === 'cancelled') {+ bgColor = '#6c757d'; // Gray}- // Add cache busting parameter to force reload- faviconLink.href = iconPath + '?v=' + new Date().getTime();+ // Draw circle background+ ctx.fillStyle = bgColor;+ ctx.beginPath();+ ctx.arc(16, 16, 16, 0, 2 * Math.PI);+ ctx.fill();++ // Draw inner circle+ ctx.fillStyle = '#ffffff';+ ctx.beginPath();+ ctx.arc(16, 16, 10, 0, 2 * Math.PI);+ ctx.fill();++ // Draw letter R+ ctx.fillStyle = bgColor;+ ctx.font = 'bold 16px Arial';+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillText('R', 16, 16);++ // Set the favicon to the canvas data URL+ link.href = canvas.toDataURL('image/png');+console.log('Updated favicon to:', status);} catch (error) {- console.error('Failed to update favicon:', error);+ console.error('Error updating favicon:', error);}}