Skip to content

~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.

refactor: delete dead main.js and detail.js (-1,027 lines) (#3185)

LearningCircuit690911f921c6
diff --git a/bearer.yml b/bearer.yml
index 7bb2ca0430..d13193e967 100644
--- a/bearer.yml
+++ b/bearer.yml
@@ -93,7 +93,7 @@ rule:
# Manual HTML sanitization alerts (javascript_lang_manual_html_sanitization)
# --------------------------------------------------------------------------
# SAFE TO SKIP: All 21 instances are intentional escapeHtml sanitization
- # functions (xss-protection.js, detail.js, etc.). Flagging the sanitizer
+ # functions (xss-protection.js, details.js, etc.). Flagging the sanitizer
# itself is circular — these functions ARE the security control. Deep search
# found zero partial/incomplete escaping patterns across the codebase.
- javascript_lang_manual_html_sanitization
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 0f71ba1532..0d75ce4551 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -832,6 +832,30 @@ def register_blueprints(app):
except ValueError:
pass
+ # Fall back to dist directory for Vite-built assets (fonts, etc.)
+ # Vite uses base: '/static/' so CSS references /static/fonts/...
+ # but the files live in static/dist/fonts/...
+ try:
+ validated_path = PathValidator.validate_safe_path(
+ path, dist_dir, allow_absolute=False, required_extensions=None
+ )
+
+ if validated_path and validated_path.exists():
+ response = make_response(
+ send_from_directory(str(dist_dir), path)
+ )
+ if _HASHED_FILENAME_RE.search(path):
+ response.headers["Cache-Control"] = (
+ "public, max-age=31536000, immutable"
+ )
+ else:
+ response.headers["Cache-Control"] = (
+ "public, max-age=0, must-revalidate"
+ )
+ return response
+ except ValueError:
+ pass
+
# Fall back to regular static folder
try:
validated_path = PathValidator.validate_safe_path(
diff --git a/src/local_deep_research/web/static/js/components/detail.js b/src/local_deep_research/web/static/js/components/detail.js
deleted file mode 100644
index af8e0c060c..0000000000
--- a/src/local_deep_research/web/static/js/components/detail.js
+++ /dev/null
@@ -1,747 +0,0 @@
-/**
- * Note: URLValidator is available globally via /static/js/security/url-validator.js
- * Research Details Component
- * Manages the display of research details and token metrics for a specific research
- */
-(function() {
- /**
- * Get chart colors from CSS variables for theme support
- */
- function getChartColors() {
- const style = getComputedStyle(document.documentElement);
- return {
- // Primary accent (for total/main data)
- accent: style.getPropertyValue('--accent-primary').trim() || '#6e4ff6',
- accentRgb: style.getPropertyValue('--accent-primary-rgb').trim() || '110, 79, 246',
- // Tertiary accent (for input tokens)
- tertiary: style.getPropertyValue('--accent-tertiary').trim() || '#40bfff',
- tertiaryRgb: style.getPropertyValue('--accent-tertiary-rgb').trim() || '64, 191, 255',
- // Error color (for output tokens)
- error: style.getPropertyValue('--error-color').trim() || '#fa5c7c',
- errorRgb: style.getPropertyValue('--error-color-rgb').trim() || '250, 92, 124',
- // Success color
- success: style.getPropertyValue('--success-color').trim() || '#0acf97',
- successRgb: style.getPropertyValue('--success-color-rgb').trim() || '10, 207, 151',
- // Text colors
- textPrimary: style.getPropertyValue('--text-primary').trim() || '#f5f5f5',
- textMuted: style.getPropertyValue('--text-muted').trim() || '#8a8aa0',
- // Background
- bgPrimary: style.getPropertyValue('--bg-primary').trim() || '#121212',
- };
- }
-
- // DOM Elements
- let queryElement = null;
- let statusElement = null;
- let modeElement = null;
- let progressBar = null;
- let progressPercentage = null;
- let pollInterval = null;
-
- // Token metrics elements
- let timelineChart = null;
-
- // Component state
- let currentResearchId = null;
- let isCompleted = false;
-
- /**
- * Initialize the research details component
- */
- async function initializeResearchDetails() {
- SafeLogger.log('Initializing research details component...');
-
- // Get research ID from URL
- currentResearchId = getResearchIdFromUrl();
-
- if (!currentResearchId) {
- SafeLogger.error('No research ID found in URL');
- if (window.ui && window.ui.showError) {
- window.ui.showError('No research ID found. Please return to the history page.');
- }
- return;
- }
-
- SafeLogger.log('Research ID:', currentResearchId);
-
- // Get DOM elements
- queryElement = document.getElementById('detail-query');
- statusElement = document.getElementById('detail-status');
- modeElement = document.getElementById('detail-mode');
- progressBar = document.getElementById('detail-progress-fill');
- progressPercentage = document.getElementById('detail-progress-percentage');
-
- SafeLogger.log('DOM elements found, setting up event listeners...');
-
- // Set up event listeners
- setupEventListeners();
-
- // Load initial research details
- await loadResearchDetails();
-
- // Start polling for updates (only if needed)
- startPolling();
-
- SafeLogger.log('Research details component initialized');
- }
-
- /**
- * Extract research ID from URL
- * @returns {string|null} Research ID or null if not found
- */
- function getResearchIdFromUrl() {
- return URLBuilder.extractResearchIdFromPattern('details');
- }
-
- /**
- * Set up event listeners
- */
- function setupEventListeners() {
- const viewResultsButton = document.getElementById('view-results-btn');
- if (viewResultsButton) {
- viewResultsButton.addEventListener('click', function() {
- // bearer:disable javascript_lang_open_redirect — URLBuilder produces /results/{id}
- window.location.href = URLBuilder.resultsPage(currentResearchId);
- });
- }
-
- const backButton = document.getElementById('back-to-history-from-details');
- if (backButton) {
- backButton.addEventListener('click', function() {
- window.location.href = URLS.PAGES.HISTORY;
- });
- }
- }
-
- /**
- * Load basic research details (for polling)
- */
- async function loadBasicResearchDetails() {
- SafeLogger.log('Loading basic research details...');
-
- try {
- const response = await fetch(URLBuilder.researchDetails(currentResearchId), {
- headers: {
- 'Accept': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error(`Failed to load research details: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- // Update UI with research details
- updateResearchInfo(data);
-
- // Check if research is in a terminal state
- isCompleted = data.status === 'completed' || data.status === 'failed' || data.status === 'suspended';
-
- } catch (error) {
- SafeLogger.error('Error loading basic research details:', error);
- }
- }
-
- /**
- * Load research details from API (full load including token metrics)
- */
- async function loadResearchDetails() {
- SafeLogger.log('Loading research details...');
-
- try {
- // Fetch research details
- const response = await fetch(URLBuilder.researchDetails(currentResearchId), {
- headers: {
- 'Accept': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error(`Failed to load research details: ${response.statusText}`);
- }
-
- const data = await response.json();
- SafeLogger.log('Research details loaded:', data);
-
- // Update UI with research details
- updateResearchInfo(data);
-
- // Check if research is in a terminal state
- isCompleted = data.status === 'completed' || data.status === 'failed' || data.status === 'suspended';
- if (isCompleted && pollInterval) {
- clearInterval(pollInterval);
- pollInterval = null;
- }
-
- // Load token metrics
- await loadTokenMetrics();
-
- // Load search metrics
- await loadSearchMetrics();
-
- } catch (error) {
- SafeLogger.error('Error loading research details:', error);
- if (window.ui && window.ui.showError) {
- window.ui.showError('Error loading research details: ' + error.message);
- }
- }
- }
-
- /**
- * Update research info display
- * @param {Object} data - Research data
- */
- function updateResearchInfo(data) {
- if (queryElement) {
- queryElement.textContent = data.query || 'N/A';
- }
-
- if (statusElement) {
- statusElement.textContent = data.status || 'N/A';
- statusElement.className = 'ldr-metadata-value ldr-status-' + (data.status || 'unknown').toLowerCase();
- }
-
- if (modeElement) {
- modeElement.textContent = data.mode || 'standard';
- }
-
- // Update progress
- const progress = data.progress_percentage || 0;
- if (progressBar) {
- progressBar.style.width = progress + '%';
- }
- if (progressPercentage) {
- progressPercentage.textContent = progress + '%';
- }
- }
-
- /**
- * Load search metrics for this research
- */
- async function loadSearchMetrics() {
- SafeLogger.log('Loading search metrics...');
-
- try {
- const response = await fetch(URLBuilder.build(URLS.METRICS_API.RESEARCH_SEARCH, currentResearchId), {
- headers: {
- 'Accept': 'application/json'
- }
- });
-
- if (!response.ok) {
- SafeLogger.log('No search metrics available for this research');
- return;
- }
-
- const data = await response.json();
-
- if (data.status === 'success' && data.metrics) {
- SafeLogger.log('Search metrics loaded:', data.metrics);
- displaySearchMetrics(data.metrics);
- displaySearchEnginePerformance(data.metrics.engine_stats || []);
- displaySearchTimeline(data.metrics.search_calls || []);
- }
-
- } catch (error) {
- SafeLogger.error('Error loading search metrics:', error);
- }
- }
-
- /**
- * Display search metrics summary
- * @param {Object} searchData - Search metrics data
- */
- function displaySearchMetrics(searchData) {
- const searchSummary = document.getElementById('search-summary');
- if (!searchSummary || !searchData) return;
-
- // Show the search analytics section
- const searchSection = document.getElementById('search-metrics-section');
- if (searchSection) {
- searchSection.style.display = 'block';
- }
-
- const totalSearches = searchData.total_searches || 0;
- const successRate = searchData.success_rate || 0;
- const avgResponseTime = (searchData.avg_response_time || 0) / 1000; // Convert ms to seconds
- const totalResults = searchData.total_results || 0;
-
- // Update individual metric elements
- const totalSearchesEl = document.getElementById('total-searches');
- const totalResultsEl = document.getElementById('total-search-results');
- const avgResponseTimeEl = document.getElementById('avg-search-response-time');
- const successRateEl = document.getElementById('search-success-rate');
-
- if (totalSearchesEl) totalSearchesEl.textContent = totalSearches;
- if (totalResultsEl) totalResultsEl.textContent = formatNumber(totalResults);
- if (avgResponseTimeEl) avgResponseTimeEl.textContent = avgResponseTime.toFixed(2) + 's';
- if (successRateEl) successRateEl.textContent = successRate.toFixed(1) + '%';
- }
-
- /**
- * Display search engine performance breakdown
- * @param {Array} enginePerformance - Search engine performance data
- */
- function displaySearchEnginePerformance(enginePerformance) {
- const engineContainer = document.getElementById('search-engine-performance');
- if (!engineContainer) return;
-
- if (!enginePerformance || enginePerformance.length === 0) {
- engineContainer.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No search engine data available</p>';
- return;
- }
-
- const engineHtml = enginePerformance.map(engine => `
- <div class="search-engine-item">
- <div class="engine-name">${escapeHtml(engine.engine)}</div>
- <div class="engine-stats">
- <span class="stat">${Number(engine.call_count) || 0} searches</span>
- <span class="stat">${engine.success_rate.toFixed(1)}% success</span>
- <span class="stat">${(engine.avg_response_time / 1000).toFixed(2)}s avg</span>
- <span class="stat">${formatNumber(engine.total_results)} results</span>
- </div>
- </div>
- `).join('');
-
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
- engineContainer.innerHTML = engineHtml;
- }
-
- /**
- * Display search timeline
- * @param {Array} searchTimeline - Search timeline data
- */
- function displaySearchTimeline(searchTimeline) {
- const timelineContainer = document.getElementById('search-timeline');
- if (!timelineContainer) return;
-
- if (!searchTimeline || searchTimeline.length === 0) {
- timelineContainer.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No search timeline data available</p>';
- return;
- }
-
- const timelineHtml = searchTimeline.map(search => {
- const timestamp = new Date(search.timestamp).toLocaleTimeString();
- const statusClass = search.success_status === 'success' ? 'success' : 'error';
- const statusText = search.success_status === 'success' ? 'Success' : 'Failed';
-
- return `
- <div class="timeline-item">
- <div class="timeline-time">${timestamp}</div>
- <div class="timeline-engine">${escapeHtml(search.engine)}</div>
- <div class="timeline-query">${escapeHtml(search.query)}</div>
- <div class="timeline-results">${formatNumber(search.results_count)} results</div>
- <div class="timeline-response">${(search.response_time_ms / 1000).toFixed(2)}s</div>
- <div class="timeline-status ${statusClass}">${statusText}</div>
- </div>
- `;
- }).join('');
-
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
- timelineContainer.innerHTML = timelineHtml;
- }
-
-
- /**
- * Start polling for updates (only if research is not completed)
- */
- function startPolling() {
- // Only poll if research is not completed
- if (!isCompleted) {
- SafeLogger.log('Starting polling for updates...');
-
- // Poll every 10 seconds (much less frequent)
- pollInterval = setInterval(async () => {
- if (!isCompleted) {
- // Only reload basic research info, not token metrics
- await loadBasicResearchDetails();
- } else {
- // Stop polling once completed
- if (pollInterval) {
- clearInterval(pollInterval);
- pollInterval = null;
- SafeLogger.log('Research completed, stopped polling');
- }
- }
- }, 10000);
- } else {
- SafeLogger.log('Research already completed, no polling needed');
- }
- }
-
- /**
- * Load token metrics for this research
- */
- async function loadTokenMetrics() {
- SafeLogger.log('Loading token metrics...');
-
- try {
- const response = await fetch(URLBuilder.build(URLS.METRICS_API.RESEARCH_TIMELINE, currentResearchId), {
- headers: {
- 'Accept': 'application/json'
- }
- });
-
- if (!response.ok) {
- SafeLogger.log('No token metrics available for this research');
- return;
- }
-
- const data = await response.json();
-
- if (data.status === 'success') {
- SafeLogger.log('Token metrics loaded:', data.metrics);
- displayTokenMetrics(data.metrics);
- }
-
- } catch (error) {
- SafeLogger.error('Error loading token metrics:', error);
- }
- }
-
- /**
- * Display token metrics on the page
- * @param {Object} metrics - Token metrics data
- */
- function displayTokenMetrics(metrics) {
- SafeLogger.log('Displaying token metrics with data:', metrics);
-
- // Show the metrics section
- const metricsSection = document.getElementById('token-metrics-section');
- if (metricsSection) {
- metricsSection.style.display = 'block';
- }
-
- // Update summary cards with safe data access
- const summary = metrics.summary || {};
- const totalTokensEl = document.getElementById('total-tokens');
- const totalPromptTokensEl = document.getElementById('total-prompt-tokens');
- const totalCompletionTokensEl = document.getElementById('total-completion-tokens');
- const totalCallsEl = document.getElementById('total-calls');
- const avgResponseTimeEl = document.getElementById('avg-response-time');
- const successRateEl = document.getElementById('success-rate');
-
- if (totalTokensEl) totalTokensEl.textContent = formatNumber(summary.total_tokens || 0);
- if (totalPromptTokensEl) totalPromptTokensEl.textContent = formatNumber(summary.total_prompt_tokens || 0);
- if (totalCompletionTokensEl) totalCompletionTokensEl.textContent = formatNumber(summary.total_completion_tokens || 0);
- if (totalCallsEl) totalCallsEl.textContent = formatNumber(summary.total_calls || 0);
- if (avgResponseTimeEl) avgResponseTimeEl.textContent = (summary.avg_response_time || 0) + 'ms';
- if (successRateEl) successRateEl.textContent = (summary.success_rate || 0) + '%';
-
- // Create timeline chart
- createTimelineChart(metrics.timeline);
-
- // Display phase breakdown
- displayPhaseBreakdown(metrics.phase_stats);
-
- // Display call stack traces
- displayCallStackTraces(metrics.timeline);
- }
-
- /**
- * Create timeline chart
- * @param {Array} timeline - Timeline data
- */
- function createTimelineChart(timeline) {
- const ctx = document.getElementById('timeline-chart');
- if (!ctx) return;
-
- // Handle empty timeline
- if (!timeline || timeline.length === 0) {
- SafeLogger.log('No timeline data available');
- ctx.getContext('2d').clearRect(0, 0, ctx.width, ctx.height);
-
- // Show a message in the chart area
- const chartContainer = ctx.parentElement;
- if (chartContainer) {
- chartContainer.innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-secondary);">No token usage timeline available for this research.<br>This research may have used search-only mode or meta search engine.</div>';
- }
- return;
- }
-
- // Prepare data
- const labels = timeline.map(item => {
- const date = new Date(item.timestamp);
- return date.toLocaleTimeString('en-US', {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit'
- });
- });
-
- const cumulativeTokens = timeline.map(item => item.cumulative_tokens);
- const cumulativePromptTokens = timeline.map(item => item.cumulative_prompt_tokens);
- const cumulativeCompletionTokens = timeline.map(item => item.cumulative_completion_tokens);
- const promptTokens = timeline.map(item => item.prompt_tokens);
- const completionTokens = timeline.map(item => item.completion_tokens);
-
- // Debug logging
- SafeLogger.log('Timeline data sample:', timeline.slice(0, 2));
- SafeLogger.log('Prompt tokens sample:', promptTokens.slice(0, 5));
- SafeLogger.log('Completion tokens sample:', completionTokens.slice(0, 5));
-
- // Destroy existing chart
- if (timelineChart) {
- timelineChart.destroy();
- }
-
- // Get theme-aware colors
- const colors = getChartColors();
-
- timelineChart = new Chart(ctx, {
- type: 'line',
- data: {
- labels: labels,
- datasets: [{
- label: 'Cumulative Total Tokens',
- data: cumulativeTokens,
- borderColor: colors.success,
- backgroundColor: `rgba(${colors.successRgb}, 0.1)`,
- borderWidth: 3,
- fill: true,
- tension: 0.1,
- pointRadius: 4,
- pointHoverRadius: 6,
- }, {
- label: 'Cumulative Input Tokens',
- data: cumulativePromptTokens,
- borderColor: colors.tertiary,
- backgroundColor: `rgba(${colors.tertiaryRgb}, 0.05)`,
- borderWidth: 2,
- fill: true,
- tension: 0.1,
- pointRadius: 2,
- pointHoverRadius: 4,
- }, {
- label: 'Cumulative Output Tokens',
- data: cumulativeCompletionTokens,
- borderColor: colors.error,
- backgroundColor: `rgba(${colors.errorRgb}, 0.05)`,
- borderWidth: 2,
- fill: true,
- tension: 0.1,
- pointRadius: 2,
- pointHoverRadius: 4,
- }, {
- label: 'Input Tokens per Call',
- data: promptTokens,
- borderColor: `rgba(${colors.tertiaryRgb}, 0.8)`,
- backgroundColor: `rgba(${colors.tertiaryRgb}, 0.1)`,
- borderWidth: 1,
- fill: false,
- tension: 0.1,
- pointRadius: 2,
- pointHoverRadius: 4,
- yAxisID: 'y1',
- borderDash: [5, 5],
- }, {
- label: 'Output Tokens per Call',
- data: completionTokens,
- borderColor: `rgba(${colors.errorRgb}, 0.8)`,
- backgroundColor: `rgba(${colors.errorRgb}, 0.1)`,
- borderWidth: 1,
- fill: false,
- tension: 0.1,
- pointRadius: 2,
- pointHoverRadius: 4,
- yAxisID: 'y1',
- borderDash: [5, 5],
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- interaction: {
- intersect: false,
- mode: 'index'
- },
- scales: {
- x: {
- display: true,
- title: {
- display: true,
- text: 'Time'
- }
- },
- y: {
- type: 'linear',
- display: true,
- position: 'left',
- title: {
- display: true,
- text: 'Cumulative Tokens'
- },
- beginAtZero: true
- },
- y1: {
- type: 'linear',
- display: true,
- position: 'right',
- title: {
- display: true,
- text: 'Tokens per Call'
- },
- beginAtZero: true,
- grid: {
- drawOnChartArea: false,
- },
- }
- },
- plugins: {
- legend: {
- position: 'top'
- },
- tooltip: {
- callbacks: {
- title: function(context) {
- const index = context[0].dataIndex;
- const item = timeline[index];
- return `${item.research_phase || 'Unknown Phase'} - ${item.model_name || 'Unknown Model'}`;
- },
- label: function(context) {
- let label = context.dataset.label || '';
- if (label) {
- label += ': ';
- }
- label += formatNumber(context.parsed.y);
- return label;
- },
- afterBody: function(context) {
- const index = context[0].dataIndex;
- const item = timeline[index];
- return [
- `Response Time: ${item.response_time_ms || 0}ms`,
- `Status: ${item.success_status || 'unknown'}`,
- `Engine: ${item.search_engine_selected || 'N/A'}`
- ];
- }
- }
- }
- }
- }
- });
- }
-
- /**
- * Display phase breakdown
- * @param {Object} phaseStats - Phase statistics
- */
- function displayPhaseBreakdown(phaseStats) {
- const container = document.getElementById('phase-breakdown');
- if (!container) return;
-
- container.innerHTML = '';
-
- Object.keys(phaseStats).forEach(phase => {
- const stats = phaseStats[phase];
- const item = document.createElement('div');
- item.className = 'ldr-phase-stat-item';
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
- item.innerHTML = `
- <div class="ldr-phase-name">${escapeHtml(phase)}</div>
- <div class="ldr-phase-tokens">${formatNumber(stats.tokens)} tokens</div>
- <div class="ldr-phase-calls">${Number(stats.count) || 0} calls | ${Number(stats.avg_response_time) || 0}ms avg</div>
- `;
- container.appendChild(item);
- });
- }
-
- /**
- * Display call stack traces for LLM calls
- * @param {Array} timeline - Timeline data with call stack info
- */
- function displayCallStackTraces(timeline) {
- const container = document.getElementById('call-stack-traces');
- if (!container) return;
-
- container.innerHTML = '';
-
- // Filter timeline items that have call stack information
- const itemsWithCallStack = timeline.filter(item => item.call_stack || item.calling_function);
-
- if (itemsWithCallStack.length === 0) {
- container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No call stack traces available for this research</p>';
- return;
- }
-
- itemsWithCallStack.forEach((item, index) => {
- const trace = document.createElement('div');
- trace.style.marginBottom = '1rem';
- trace.style.padding = '0.75rem';
- trace.style.backgroundColor = 'var(--card-bg)';
- trace.style.borderRadius = '6px';
- trace.style.border = '1px solid var(--border-color)';
-
- // Format timestamp
- const timestamp = item.timestamp ? new Date(item.timestamp).toLocaleTimeString() : 'Unknown time';
-
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
- trace.innerHTML = `
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
- <div style="font-weight: 500; color: var(--text-primary);">
- ${escapeHtml(item.calling_function || 'Unknown Function')}
- </div>
- <div style="font-size: 0.875rem; color: var(--text-secondary);">
- ${timestamp} - ${Number(item.prompt_tokens) || 0} in + ${Number(item.completion_tokens) || 0} out = ${Number(item.tokens) || 0} tokens, ${Number(item.response_time_ms) || 0}ms
- </div>
- </div>
- <div style="font-family: 'Courier New', monospace; font-size: 0.75rem; background: var(--bg-tertiary); padding: 0.5rem; border-radius: 4px; color: var(--text-secondary); overflow-x: auto; margin-bottom: 0.5rem;">
- ${escapeHtml(item.call_stack || 'No stack trace available')}
- </div>
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.5rem; font-size: 0.875rem;">
- <div><strong>File:</strong> ${escapeHtml((item.calling_file || 'Unknown').split('/').pop())}</div>
- <div><strong>Phase:</strong> ${escapeHtml(item.research_phase || 'N/A')}</div>
- <div><strong>Model:</strong> ${escapeHtml(item.model_name || 'N/A')}</div>
- <div><strong>Status:</strong>
- <span style="color: ${item.success_status === 'success' ? 'green' : 'red'}">
- ${escapeHtml(item.success_status || 'Unknown')}
- </span>
- </div>
- </div>
- `;
- container.appendChild(trace);
- });
- }
-
- /**
- * Format large numbers with commas
- * @param {number} num - Number to format
- * @returns {string} Formatted number
- */
- function formatNumber(num) {
- return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
- }
-
- /**
- * Fallback HTML escape function (used if xss-protection.js fails to load).
- * NOTE: This declaration is safe because it is INSIDE an IIFE (function scope).
- * Do NOT move it to top-level scope — it would conflict with the global
- * escapeHtmlFallback in services/ui.js and crash the page.
- */
- // bearer:disable javascript_lang_manual_html_sanitization — intentional defense-in-depth XSS fallback
- const escapeHtmlFallback = (str) => String(str || '').replace(/[&<>"']/g, (m) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
-
- // Use global escapeHtml from xss-protection.js with fallback
- const escapeHtml = window.escapeHtml || escapeHtmlFallback;
-
- // Clean up on page unload
- window.addEventListener('beforeunload', function() {
- if (pollInterval) {
- clearInterval(pollInterval);
- }
- });
-
- // Initialize on DOM content loaded
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => {
- initializeResearchDetails().catch(e => SafeLogger.error('Failed to initialize research details', e));
- });
- } else {
- initializeResearchDetails().catch(e => SafeLogger.error('Failed to initialize research details', e));
- }
-})();
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index a4cb5c46bc..73cb1416ed 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -9,11 +9,13 @@
let researchId = null;
let metricsData = null;
let timelineChart = null;
+ let currentChartView = 'bars';
+ let lastTimelineData = null;
let searchChart = null;
// XSS protection: escape dynamic content before innerHTML interpolation
// bearer:disable javascript_lang_manual_html_sanitization
- const escapeHtmlFallback = (str) => String(str).replace(/[&<>"']/g, (m) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
+ const escapeHtmlFallback = (str) => String(str ?? '').replace(/[&<>"']/g, (m) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
const escapeHtml = window.escapeHtml || escapeHtmlFallback;
/**
@@ -31,6 +33,12 @@
// Text colors
textPrimary: style.getPropertyValue('--text-primary').trim() || '#f5f5f5',
textMuted: style.getPropertyValue('--text-muted').trim() || '#8a8aa0',
+ // Tertiary accent (for input tokens)
+ tertiary: style.getPropertyValue('--accent-tertiary').trim() || '#40bfff',
+ tertiaryRgb: style.getPropertyValue('--accent-tertiary-rgb').trim() || '64, 191, 255',
+ // Error color (for output tokens)
+ error: style.getPropertyValue('--error-color').trim() || '#fa5c7c',
+ errorRgb: style.getPropertyValue('--error-color-rgb').trim() || '250, 92, 124',
// Background
bgPrimary: style.getPropertyValue('--bg-primary').trim() || '#121212',
};
@@ -394,6 +402,7 @@
SafeLogger.log('Chart.js available:', typeof Chart !== 'undefined');
SafeLogger.log('Timeline data for chart:', timelineData);
createTimelineChart(timelineData);
+ displayCallStackTraces(timelineData.timeline);
}
if (searchData) {
@@ -589,217 +598,323 @@
document.getElementById('search-success-rate').textContent = `${successRate.toFixed(1)}%`;
// Display search engine breakdown
- if (!searchData.search_calls) return;
-
const container = document.getElementById('search-engine-breakdown');
- container.innerHTML = '';
+ if (container && searchData.search_calls) {
+ container.innerHTML = '';
+
+ searchData.search_calls.forEach(call => {
+ const item = document.createElement('div');
+ item.className = 'ldr-search-engine-item';
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
+ item.innerHTML = `
+ <div class="ldr-search-engine-info">
+ <div class="ldr-search-engine-name">${escapeHtml(call.engine || 'Unknown')}</div>
+ <div class="ldr-search-engine-query">${escapeHtml(call.query || 'No query')}</div>
+ </div>
+ <div class="ldr-search-engine-stats">
+ <div class="ldr-search-results">${formatNumber(call.results_count || 0)} results</div>
+ <div class="ldr-search-time">${((call.response_time_ms || 0) / 1000).toFixed(1)}s</div>
+ </div>
+ `;
+ container.appendChild(item);
+ });
+ }
+ // Display per-engine aggregated performance
+ displaySearchEnginePerformance(searchData.engine_stats || []);
+ // Display search timeline with timestamps and status
+ displaySearchTimeline(searchData.search_calls || []);
+ }
- searchData.search_calls.forEach(call => {
- const item = document.createElement('div');
- item.className = 'ldr-search-engine-item';
+ // Display search engine performance breakdown (aggregated by engine)
+ function displaySearchEnginePerformance(enginePerformance) {
+ const container = document.getElementById('search-engine-performance');
+ if (!container) return;
+ if (!enginePerformance || enginePerformance.length === 0) {
// bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
- item.innerHTML = `
+ container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No search engine data available</p>';
+ return;
+ }
+ const html = enginePerformance.map(engine => `
+ <div class="ldr-search-engine-item">
<div class="ldr-search-engine-info">
- <div class="ldr-search-engine-name">${escapeHtml(call.engine || 'Unknown')}</div>
- <div class="ldr-search-engine-query">${escapeHtml(call.query || 'No query')}</div>
+ <div class="ldr-search-engine-name">${escapeHtml(engine.engine || 'Unknown')}</div>
</div>
<div class="ldr-search-engine-stats">
- <div class="ldr-search-results">${formatNumber(call.results_count || 0)} results</div>
- <div class="ldr-search-time">${((call.response_time_ms || 0) / 1000).toFixed(1)}s</div>
+ <span>${engine.call_count ?? 0} searches</span>
+ <span>${(engine.success_rate ?? 0).toFixed(1)}% success</span>
+ <span>${((engine.avg_response_time ?? 0) / 1000).toFixed(2)}s avg</span>
+ <span>${formatNumber(engine.total_results ?? 0)} results</span>
+ </div>
+ </div>
+ `).join('');
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- audited: all values escaped via escapeHtml or numeric coercion
+ container.innerHTML = html;
+ }
+
+ // Display search timeline with timestamps and success/failure status
+ function displaySearchTimeline(searchTimeline) {
+ const container = document.getElementById('search-timeline');
+ if (!container) return;
+ if (!searchTimeline || searchTimeline.length === 0) {
+ // bearer:disable javascript_lang_dangerous_insert_html
+ container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No search timeline data available</p>';
+ return;
+ }
+ const html = searchTimeline.map(search => {
+ const parsedDate = search.timestamp ? new Date(search.timestamp) : null;
+ const timestamp = parsedDate && !isNaN(parsedDate) ? parsedDate.toLocaleTimeString() : '\u2014';
+ const statusClass = search.success_status === 'success' ? 'ldr-search-status-success' : 'ldr-search-status-error';
+ const statusText = search.success_status === 'success' ? 'Success' : 'Failed';
+ return `
+ <div class="ldr-search-timeline-item">
+ <div style="flex: 1;">
+ <div class="ldr-search-timeline-query">${escapeHtml(search.engine || 'Unknown')}</div>
+ <div class="ldr-search-timeline-meta">${timestamp} \u00b7 ${escapeHtml(search.query || 'N/A')}</div>
+ </div>
+ <div class="ldr-search-timeline-results">
+ ${formatNumber(search.results_count || 0)} results \u00b7 ${((search.response_time_ms ?? 0) / 1000).toFixed(2)}s
+ </div>
+ <span class="${statusClass}" style="margin-left: 0.75rem; font-weight: 600;">${statusText}</span>
</div>
`;
- container.appendChild(item);
- });
+ }).join('');
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- audited: all values escaped via escapeHtml, timestamps from toLocaleTimeString, status from hardcoded literals
+ container.innerHTML = html;
}
- // Create timeline chart
- function createTimelineChart(timelineData) {
- SafeLogger.log('createTimelineChart called with:', timelineData);
+ // Display call stack traces for LLM calls
+ function displayCallStackTraces(timeline) {
+ const container = document.getElementById('call-stack-traces');
+ if (!container) return;
- if (!timelineData || !timelineData.timeline) {
- SafeLogger.log('No timeline data for chart, timelineData:', timelineData);
- return;
+ const itemsWithCallStack = (timeline || []).filter(item => item.call_stack || item.calling_function);
+
+ // Show the card if we have data
+ const card = document.getElementById('call-stack-card');
+ if (card && itemsWithCallStack.length > 0) {
+ card.style.display = 'block';
}
- if (typeof Chart === 'undefined') {
- SafeLogger.error('Chart.js not loaded!');
+ if (itemsWithCallStack.length === 0) {
+ // bearer:disable javascript_lang_dangerous_insert_html
+ container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">No call stack traces available for this research</p>';
return;
}
+ container.innerHTML = '';
+ itemsWithCallStack.forEach(item => {
+ const trace = document.createElement('div');
+ trace.style.cssText = 'margin-bottom: 1rem; padding: 0.75rem; background: var(--card-bg); border-radius: 6px; border: 1px solid var(--border-color);';
+
+ const parsedDate = item.timestamp ? new Date(item.timestamp) : null;
+ const timestamp = parsedDate && !isNaN(parsedDate) ? parsedDate.toLocaleTimeString() : '\u2014';
+
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- audited: all values escaped via escapeHtml, timestamp from toLocaleTimeString, numerics coerced
+ trace.innerHTML = `
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
+ <div style="font-weight: 500; color: var(--text-primary);">
+ ${escapeHtml(item.calling_function || 'Unknown Function')}
+ </div>
+ <div style="font-size: 0.875rem; color: var(--text-secondary);">
+ ${timestamp} \u2014 ${item.prompt_tokens || 0} in + ${item.completion_tokens || 0} out = ${item.tokens || 0} tokens, ${item.response_time_ms || 0}ms
+ </div>
+ </div>
+ <div style="font-family: 'Courier New', monospace; font-size: 0.75rem; background: var(--bg-tertiary); padding: 0.5rem; border-radius: 4px; color: var(--text-secondary); overflow-x: auto; margin-bottom: 0.5rem;">
+ ${escapeHtml(item.call_stack || 'No stack trace available')}
+ </div>
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 0.5rem; font-size: 0.875rem;">
+ <div><strong>File:</strong> ${escapeHtml((item.calling_file || 'Unknown').split('/').pop())}</div>
+ <div><strong>Phase:</strong> ${escapeHtml(item.research_phase || 'N/A')}</div>
+ <div><strong>Model:</strong> ${escapeHtml(item.model_name || 'N/A')}</div>
+ <div><strong>Status:</strong>
+ <span style="color: ${item.success_status === 'success' ? 'var(--success-color)' : 'var(--error-color)'}">
+ ${escapeHtml(item.success_status || 'Unknown')}
+ </span>
+ </div>
+ </div>
+ `;
+ container.appendChild(trace);
+ });
+ }
+
+ // Create timeline chart with toggle support (bars vs cumulative line)
+ function createTimelineChart(timelineData, viewType) {
+ if (!timelineData || !timelineData.timeline) return;
+ if (typeof Chart === 'undefined') return;
+
const chartElement = document.getElementById('timeline-chart');
- if (!chartElement) {
- SafeLogger.error('Timeline chart element not found');
- return;
- }
+ if (!chartElement) return;
- SafeLogger.log('Creating timeline chart with', timelineData.timeline.length, 'data points');
+ lastTimelineData = timelineData;
+ const view = viewType || currentChartView;
try {
const ctx = chartElement.getContext('2d');
- SafeLogger.log('Canvas context obtained');
-
- // Destroy existing chart
if (timelineChart) {
timelineChart.destroy();
}
- // Prepare chart data with enhanced information
- const chartData = timelineData.timeline.map((item, index) => ({
- phase: item.research_phase || item.phase || `Step ${index + 1}`,
- tokens: item.tokens || 0,
- promptTokens: item.prompt_tokens || 0,
- completionTokens: item.completion_tokens || 0,
- timestamp: item.timestamp || item.created_at,
- responseTime: item.response_time_ms || 0
- }));
-
- const labels = chartData.map(item => item.phase);
- const totalTokens = chartData.map(item => item.tokens);
- const promptTokens = chartData.map(item => item.promptTokens);
- const completionTokens = chartData.map(item => item.completionTokens);
+ const timeline = timelineData.timeline;
+ const colors = getChartColors();
- SafeLogger.log('Enhanced chart data:', chartData);
+ // Shared tooltip callbacks
+ function tooltipTitle(tooltipItems) {
+ const item = timeline[tooltipItems[0].dataIndex];
+ return `${item.research_phase || 'Unknown Phase'} - ${item.model_name || 'Unknown Model'}`;
+ }
+ function tooltipAfterBody(tooltipItems) {
+ const item = timeline[tooltipItems[0].dataIndex];
+ const lines = [];
+ if (item.search_engine_selected) lines.push(`Engine: ${item.search_engine_selected}`);
+ if (item.success_status) lines.push(`Status: ${item.success_status}`);
+ if (item.response_time_ms > 0) lines.push(`Response time: ${(item.response_time_ms / 1000).toFixed(1)}s`);
+ if (item.timestamp) {
+ const d = new Date(item.timestamp);
+ if (!isNaN(d)) lines.push(`Time: ${d.toLocaleTimeString()}`);
+ }
+ return lines;
+ }
- // Get theme-aware colors
- const colors = getChartColors();
+ if (view === 'line') {
+ // Cumulative line chart with dual axes
+ const timeLabels = timeline.map(item => {
+ const d = item.timestamp ? new Date(item.timestamp) : null;
+ return d && !isNaN(d) ? d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '';
+ });
- timelineChart = new Chart(ctx, {
- type: 'bar',
- data: {
- labels: labels,
- datasets: [
- {
- label: 'Input Tokens',
- data: promptTokens,
- backgroundColor: `rgba(${colors.accentRgb}, 0.8)`,
- borderColor: colors.accent,
- borderWidth: 1,
- borderRadius: 4,
- borderSkipped: false,
- },
- {
- label: 'Output Tokens',
- data: completionTokens,
- backgroundColor: `rgba(${colors.successRgb}, 0.8)`,
+ timelineChart = new Chart(ctx, {
+ type: 'line',
+ data: {
+ labels: timeLabels,
+ datasets: [{
+ label: 'Cumulative Total Tokens',
+ data: timeline.map(item => item.cumulative_tokens),
borderColor: colors.success,
- borderWidth: 1,
- borderRadius: 4,
- borderSkipped: false,
- }
- ]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- animation: {
- duration: 1000,
- easing: 'easeInOutQuart'
+ backgroundColor: `rgba(${colors.successRgb}, 0.1)`,
+ borderWidth: 3, fill: true, tension: 0.1,
+ pointRadius: 3, pointHoverRadius: 5,
+ }, {
+ label: 'Cumulative Input Tokens',
+ data: timeline.map(item => item.cumulative_prompt_tokens),
+ borderColor: colors.tertiary,
+ backgroundColor: `rgba(${colors.tertiaryRgb}, 0.05)`,
+ borderWidth: 2, fill: true, tension: 0.1,
+ pointRadius: 2, pointHoverRadius: 4,
+ }, {
+ label: 'Cumulative Output Tokens',
+ data: timeline.map(item => item.cumulative_completion_tokens),
+ borderColor: colors.error,
+ backgroundColor: `rgba(${colors.errorRgb}, 0.05)`,
+ borderWidth: 2, fill: true, tension: 0.1,
+ pointRadius: 2, pointHoverRadius: 4,
+ }, {
+ label: 'Input Tokens per Call',
+ data: timeline.map(item => item.prompt_tokens),
+ borderColor: `rgba(${colors.tertiaryRgb}, 0.8)`,
+ borderWidth: 1, fill: false, tension: 0.1,
+ pointRadius: 2, pointHoverRadius: 4,
+ yAxisID: 'y1', borderDash: [5, 5],
+ }, {
+ label: 'Output Tokens per Call',
+ data: timeline.map(item => item.completion_tokens),
+ borderColor: `rgba(${colors.errorRgb}, 0.8)`,
+ borderWidth: 1, fill: false, tension: 0.1,
+ pointRadius: 2, pointHoverRadius: 4,
+ yAxisID: 'y1', borderDash: [5, 5],
+ }]
},
- interaction: {
- intersect: false,
- mode: 'index'
- },
- scales: {
- x: {
- stacked: true,
- grid: {
- display: false
- },
- ticks: {
- font: {
- size: 11
- },
- maxRotation: 45,
- minRotation: 0
- }
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ interaction: { intersect: false, mode: 'index' },
+ scales: {
+ x: { title: { display: true, text: 'Time' } },
+ y: { type: 'linear', position: 'left', beginAtZero: true,
+ title: { display: true, text: 'Cumulative Tokens' } },
+ y1: { type: 'linear', position: 'right', beginAtZero: true,
+ title: { display: true, text: 'Tokens per Call' },
+ grid: { drawOnChartArea: false } }
},
- y: {
- stacked: true,
- beginAtZero: true,
- grid: {
- color: 'rgba(0, 0, 0, 0.1)',
- drawBorder: false
- },
- ticks: {
- font: {
- size: 11
- },
- callback: function(value) {
- return formatNumber(value);
- }
- },
- title: {
- display: true,
- text: 'Tokens',
- font: {
- size: 12,
- weight: 'bold'
+ plugins: {
+ legend: { position: 'top' },
+ tooltip: {
+ callbacks: {
+ title: tooltipTitle,
+ label: function(context) {
+ return (context.dataset.label || '') + ': ' + formatNumber(context.parsed.y);
+ },
+ afterBody: tooltipAfterBody
}
}
}
+ }
+ });
+ } else {
+ // Stacked bar chart (default)
+ const chartData = timeline.map((item, index) => ({
+ phase: item.research_phase || item.phase || `Step ${index + 1}`,
+ tokens: item.tokens || 0,
+ promptTokens: item.prompt_tokens || 0,
+ completionTokens: item.completion_tokens || 0,
+ }));
+
+ timelineChart = new Chart(ctx, {
+ type: 'bar',
+ data: {
+ labels: chartData.map(item => item.phase),
+ datasets: [{
+ label: 'Input Tokens',
+ data: chartData.map(item => item.promptTokens),
+ backgroundColor: `rgba(${colors.accentRgb}, 0.8)`,
+ borderColor: colors.accent,
+ borderWidth: 1, borderRadius: 4, borderSkipped: false,
+ }, {
+ label: 'Output Tokens',
+ data: chartData.map(item => item.completionTokens),
+ backgroundColor: `rgba(${colors.successRgb}, 0.8)`,
+ borderColor: colors.success,
+ borderWidth: 1, borderRadius: 4, borderSkipped: false,
+ }]
},
- plugins: {
- legend: {
- display: true,
- position: 'top',
- align: 'end',
- labels: {
- usePointStyle: true,
- pointStyle: 'rect',
- font: {
- size: 11
- },
- padding: 15
- }
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ animation: { duration: 1000, easing: 'easeInOutQuart' },
+ interaction: { intersect: false, mode: 'index' },
+ scales: {
+ x: { stacked: true, grid: { display: false },
+ ticks: { font: { size: 11 }, maxRotation: 45 } },
+ y: { stacked: true, beginAtZero: true,
+ ticks: { callback: function(v) { return formatNumber(v); } },
+ title: { display: true, text: 'Tokens' } }
},
- tooltip: {
- backgroundColor: 'rgba(0, 0, 0, 0.8)',
- titleColor: 'white',
- bodyColor: 'white',
- borderColor: 'rgba(255, 255, 255, 0.1)',
- borderWidth: 1,
- cornerRadius: 8,
- displayColors: true,
- callbacks: {
- title: function(tooltipItems) {
- const index = tooltipItems[0].dataIndex;
- const phase = chartData[index].phase;
- return phase;
- },
- beforeBody: function(tooltipItems) {
- const index = tooltipItems[0].dataIndex;
- const data = chartData[index];
- const total = data.tokens;
- return [`Total: ${formatNumber(total)} tokens`];
- },
- afterBody: function(tooltipItems) {
- const index = tooltipItems[0].dataIndex;
- const data = chartData[index];
- const lines = [];
-
- if (data.responseTime > 0) {
- lines.push(`Response time: ${(data.responseTime / 1000).toFixed(1)}s`);
- }
-
- if (data.timestamp) {
- const time = new Date(data.timestamp).toLocaleTimeString();
- lines.push(`Time: ${time}`);
- }
-
- return lines;
+ plugins: {
+ legend: { display: true, position: 'top', align: 'end',
+ labels: { usePointStyle: true, pointStyle: 'rect', font: { size: 11 }, padding: 15 } },
+ tooltip: {
+ backgroundColor: 'rgba(0, 0, 0, 0.8)',
+ titleColor: 'white', bodyColor: 'white',
+ cornerRadius: 8, displayColors: true,
+ callbacks: {
+ title: tooltipTitle,
+ beforeBody: function(tooltipItems) {
+ const item = timeline[tooltipItems[0].dataIndex];
+ return [`Total: ${formatNumber(item.tokens || 0)} tokens`];
+ },
+ afterBody: tooltipAfterBody
}
}
}
}
- }
- });
+ });
+ }
- SafeLogger.log('Timeline chart created successfully');
+ SafeLogger.log('Timeline chart created successfully (view: ' + view + ')');
} catch (error) {
SafeLogger.error('Error creating timeline chart:', error);
- SafeLogger.error('Chart error details:', error.message, error.stack);
}
}
@@ -1247,6 +1362,24 @@
window.location.href = URLS.PAGES.HISTORY;
});
}
+
+ // Chart view toggle (bars ↔ cumulative line)
+ const barsBtn = document.getElementById('chart-view-bars');
+ const lineBtn = document.getElementById('chart-view-line');
+ if (barsBtn && lineBtn) {
+ barsBtn.addEventListener('click', () => {
+ currentChartView = 'bars';
+ barsBtn.classList.add('active');
+ lineBtn.classList.remove('active');
+ if (lastTimelineData) createTimelineChart(lastTimelineData, 'bars');
+ });
+ lineBtn.addEventListener('click', () => {
+ currentChartView = 'line';
+ lineBtn.classList.add('active');
+ barsBtn.classList.remove('active');
+ if (lastTimelineData) createTimelineChart(lastTimelineData, 'line');
+ });
+ }
});
})();
diff --git a/src/local_deep_research/web/static/js/main.js b/src/local_deep_research/web/static/js/main.js
deleted file mode 100644
index da84efec22..0000000000
--- a/src/local_deep_research/web/static/js/main.js
+++ /dev/null
@@ -1,201 +0,0 @@
-/**
- * Main JavaScript Entry Point
- * Loads appropriate components based on the current page
- */
-(function() {
- // Map of page identifiers to component scripts
- const pageComponents = {
- 'page-home': ['research.js'],
- 'page-progress': ['progress.js'],
- 'page-results': ['results.js'],
- 'page-detail': ['detail.js'],
- 'page-history': ['history.js'],
- 'page-settings': ['settings.js']
- };
-
- // Core services to always load
- const coreServices = [
- 'formatting.js',
- 'ui.js',
- 'api.js',
- 'socket.js'
- // 'audio.js' - Removed from here, loaded separately
- ];
-
- // Optional services to load when needed
- const optionalServices = {
- 'page-results': ['pdf.js'],
- 'page-detail': ['pdf.js']
- };
-
- /**
- * Initialize the application
- */
- function initializeApp() {
- // Detect current page
- const currentPage = detectCurrentPage();
-
- if (!currentPage) {
- SafeLogger.error('Cannot detect current page type');
- return;
- }
-
- SafeLogger.log('Current page detected:', currentPage);
-
- // IMPORTANT: Load audio.js first, before ANY other scripts
- loadAudioServiceFirst(() => {
- // Continue loading other scripts after audio service is loaded
- SafeLogger.log('Audio service script loaded, continuing with other scripts');
-
- // Load UI and formatting utils
- loadScripts('utils', coreServices.filter(s => s.includes('formatting') || s.includes('ui')));
-
- // Then load the rest
- loadScripts('services', coreServices.filter(s => s.includes('api') || s.includes('socket')));
-
- // Load optional services for this page
- if (optionalServices[currentPage]) {
- loadScripts('services', optionalServices[currentPage]);
- }
-
- // Load components for this page AFTER all services
- if (pageComponents[currentPage]) {
- loadScripts('components', pageComponents[currentPage]);
- }
-
- // Initialize tooltips and other global UI elements
- initializeGlobalUI();
- });
- }
-
- /**
- * Load audio service first and separately to ensure it's fully loaded before other scripts
- * @param {Function} callback - Function to call after audio service is loaded
- */
- function loadAudioServiceFirst(callback) {
- SafeLogger.log('Loading audio service script first...');
- const audioScript = document.createElement('script');
- audioScript.src = `/static/js/services/audio.js?t=${new Date().getTime()}`; // Add timestamp to avoid cache
- audioScript.async = false;
-
- // Set up callback for when script loads
- audioScript.onload = function() {
- SafeLogger.log('Audio service script loaded successfully');
-
- // Check if audio service is available in window object
- setTimeout(() => {
- if (window.audio) {
- SafeLogger.log('Audio service initialized in window object');
- } else {
- SafeLogger.warn('Audio service not available in window object after script load');
- }
-
- // Continue regardless
- callback();
- }, 100); // Small delay to ensure script executes
- };
-
- // Error handling
- audioScript.onerror = function() {
- SafeLogger.error('Failed to load audio service script');
- // Continue with other scripts even if audio fails
- callback();
- };
-
- // Add to document
- document.body.appendChild(audioScript);
- }
-
- /**
- * Detect the current page based on body class
- * @returns {string|null} The page identifier or null if not found
- */
- function detectCurrentPage() {
- const bodyClasses = document.body.classList;
-
- for (const pageId in pageComponents) {
- if (bodyClasses.contains(pageId)) {
- return pageId;
- }
- }
-
- // Check URL patterns as fallback
- const path = window.location.pathname;
-
- if (path === '/' || path === '/index' || path === '/home') {
- return 'page-home';
- } else if (path.includes('/progress')) {
- return 'page-progress';
- } else if (path.includes('/results')) {
- return 'page-results';
- } else if (path.includes('/details')) {
- return 'page-detail';
- } else if (path.includes('/history')) {
- return 'page-history';
- } else if (path.includes('/settings')) {
- return 'page-settings';
- }
-
- return null;
- }
-
- /**
- * Load scripts dynamically
- * @param {string} folder - The folder containing the scripts
- * @param {Array} scripts - Array of script filenames to load
- */
- function loadScripts(folder, scripts) {
- if (!scripts || !scripts.length) return;
-
- scripts.forEach(script => {
- const scriptElement = document.createElement('script');
- scriptElement.src = `/static/js/${folder}/${script}`;
- scriptElement.async = false; // Load in sequence
- document.body.appendChild(scriptElement);
- });
- }
-
- /**
- * Initialize global UI elements
- */
- function initializeGlobalUI() {
- // Initialize notifications if browser supports it
- if ("Notification" in window && Notification.permission === "default") {
- // Only ask for permission when user interacts with the page
- document.addEventListener('click', requestNotificationPermission, { once: true });
- }
-
- // Theme toggle is now handled by themeService (services/theme.js)
- // which provides multi-theme support, server sync, and user-scoped localStorage
-
- // Initialize mobile menu toggle
- const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
- const navMenu = document.getElementById('main-nav');
-
- if (mobileMenuToggle && navMenu) {
- mobileMenuToggle.addEventListener('click', function() {
- navMenu.classList.toggle('ldr-open');
- mobileMenuToggle.setAttribute(
- 'aria-expanded',
- navMenu.classList.contains('ldr-open') ? 'true' : 'false'
- );
- });
- }
- }
-
- /**
- * Request notification permission
- */
- function requestNotificationPermission() {
- if ("Notification" in window && Notification.permission === "default") {
- Notification.requestPermission();
- }
- }
-
- // Initialize when DOM is ready
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', initializeApp);
- } else {
- initializeApp();
- }
-})();
diff --git a/src/local_deep_research/web/static/js/security/xss-protection.js b/src/local_deep_research/web/static/js/security/xss-protection.js
index a6f8fed487..93832b92e8 100644
--- a/src/local_deep_research/web/static/js/security/xss-protection.js
+++ b/src/local_deep_research/web/static/js/security/xss-protection.js
@@ -21,7 +21,7 @@
* in the same global scope across <script> tags.
*
* Files wrapped in IIFEs (components/results.js, components/settings.js,
- * components/detail.js, components/fallback/ui.js) may safely define their
+ * components/details.js, components/fallback/ui.js) may safely define their
* own scoped fallback.
*
* The usage pattern is: `(window.escapeHtml || escapeHtmlFallback)(text)`
diff --git a/src/local_deep_research/web/templates/pages/details.html b/src/local_deep_research/web/templates/pages/details.html
index e8f3641f35..091834af36 100644
--- a/src/local_deep_research/web/templates/pages/details.html
+++ b/src/local_deep_research/web/templates/pages/details.html
@@ -8,26 +8,6 @@
margin-top: 2rem;
}
- .ldr-metric-card {
- background: var(--bg-secondary);
- padding: 1rem;
- border-radius: 8px;
- border: 1px solid var(--border-color);
- }
-
- .ldr-metric-label {
- font-size: 0.875rem;
- color: var(--text-secondary);
- margin-bottom: 0.5rem;
- opacity: 1 !important;
- }
-
- .ldr-metric-value {
- font-size: 1.5rem;
- font-weight: 600;
- color: var(--text-primary);
- }
-
.ldr-metrics-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
@@ -58,6 +38,32 @@
opacity: 1 !important;
}
+ .ldr-chart-toggle {
+ padding: 0.25rem 0.75rem;
+ font-size: 0.8rem;
+ border: 1px solid var(--border-color);
+ background: var(--card-bg);
+ color: var(--text-secondary);
+ cursor: pointer;
+ border-radius: 0.25rem;
+ transition: all 0.2s;
+ }
+
+ .ldr-chart-toggle:first-child {
+ border-radius: 0.25rem 0 0 0.25rem;
+ }
+
+ .ldr-chart-toggle:last-child {
+ border-radius: 0 0.25rem 0.25rem 0;
+ margin-left: -1px;
+ }
+
+ .ldr-chart-toggle.active {
+ background: var(--accent-primary);
+ color: white;
+ border-color: var(--accent-primary);
+ }
+
.ldr-chart-container {
position: relative;
height: 300px;
@@ -326,7 +332,7 @@
</div>
<div class="ldr-metadata-item">
<span class="ldr-metadata-label">Progress:</span>
- <div class="ldr-ldr-detail-progress-container">
+ <div class="ldr-detail-progress-container">
<div class="ldr-detail-progress-bar">
<div class="ldr-detail-progress-fill" id="detail-progress-fill"></div>
</div>
@@ -379,7 +385,13 @@
<div class="ldr-charts-grid">
<!-- Token Consumption Chart -->
<div>
- <h3><i class="fas fa-clock"></i> Token Consumption Over Time</h3>
+ <div style="display: flex; justify-content: space-between; align-items: center;">
+ <h3 style="margin: 0;"><i class="fas fa-clock"></i> Token Consumption Over Time</h3>
+ <div>
+ <button id="chart-view-bars" class="ldr-chart-toggle active">Bars</button>
+ <button id="chart-view-line" class="ldr-chart-toggle">Line</button>
+ </div>
+ </div>
<div class="ldr-chart-container" style="height: 250px;">
<canvas id="timeline-chart"></canvas>
</div>
@@ -402,15 +414,6 @@
</div>
</div>
- <!-- Call Stack Analysis -->
- <div style="margin-top: 2rem;" id="call-stack-section">
- <h3><i class="fas fa-code"></i> LLM Call Stack Analysis</h3>
- <div style="margin-top: 1rem;">
- <div id="call-stack-traces" style="max-height: 400px; overflow-y: auto;">
- <!-- Populated dynamically -->
- </div>
- </div>
- </div>
</div>
</div>
@@ -462,7 +465,7 @@
<!-- Search Engine Breakdown -->
<div style="margin-top: 2rem;">
- <h3><i class="fas fa-search"></i> Search Engine Performance</h3>
+ <h3><i class="fas fa-search"></i> Search Calls</h3>
<div id="search-engine-breakdown" style="margin-top: 1rem;">
<!-- Populated dynamically -->
</div>
@@ -478,50 +481,6 @@
</div>
</div>
- <!-- Link Analytics Section -->
- <div class="ldr-card ldr-metrics-section" id="link-analytics-section" style="display: none;">
- <div class="card-header">
- <h2><i class="fas fa-link"></i> Link & Domain Analytics</h2>
- </div>
- <div class="ldr-card-content">
- <!-- Link Metrics Summary -->
- <div class="ldr-metrics-grid" id="link-metrics-summary">
- <div class="ldr-metric-card">
- <div class="ldr-metric-label">Total Links</div>
- <div class="ldr-metric-value" id="total-links">0</div>
- </div>
- <div class="ldr-metric-card">
- <div class="ldr-metric-label">Unique Domains</div>
- <div class="ldr-metric-value" id="unique-domains">0</div>
- </div>
- <div class="ldr-metric-card">
- <div class="ldr-metric-label">Academic Sources</div>
- <div class="ldr-metric-value" id="academic-sources">0</div>
- </div>
- <div class="ldr-metric-card">
- <div class="ldr-metric-label">News Sources</div>
- <div class="ldr-metric-value" id="news-sources">0</div>
- </div>
- </div>
-
- <!-- Domain Distribution -->
- <div style="margin-top: 2rem;">
- <h3><i class="fas fa-globe"></i> Top Domains Used</h3>
- <div id="domain-list" style="max-height: 400px; overflow-y: auto;">
- <!-- Domain items will be populated here -->
- </div>
- </div>
-
- <!-- Recent Resources Sample -->
- <div style="margin-top: 2rem;">
- <h3><i class="fas fa-file-text"></i> Sample Resources</h3>
- <div id="resource-sample" style="max-height: 300px; overflow-y: auto;">
- <!-- Resource samples will be populated here -->
- </div>
- </div>
- </div>
- </div>
-
<!-- Context Overflow Section -->
<div class="ldr-card ldr-metrics-section" id="context-overflow-section" style="display: none; margin-top: 2rem;">
<div class="card-header">
@@ -591,13 +550,66 @@
</div>
</div>
+ <!-- Link Analytics Section -->
+ <div class="ldr-card ldr-metrics-section" id="link-analytics-section" style="display: none;">
+ <div class="card-header">
+ <h2><i class="fas fa-link"></i> Link & Domain Analytics</h2>
+ </div>
+ <div class="ldr-card-content">
+ <!-- Link Metrics Summary -->
+ <div class="ldr-metrics-grid" id="link-metrics-summary">
+ <div class="ldr-metric-card">
+ <div class="ldr-metric-label">Total Links</div>
+ <div class="ldr-metric-value" id="total-links">0</div>
+ </div>
+ <div class="ldr-metric-card">
+ <div class="ldr-metric-label">Unique Domains</div>
+ <div class="ldr-metric-value" id="unique-domains">0</div>
+ </div>
+ <div class="ldr-metric-card">
+ <div class="ldr-metric-label">Academic Sources</div>
+ <div class="ldr-metric-value" id="academic-sources">0</div>
+ </div>
+ <div class="ldr-metric-card">
+ <div class="ldr-metric-label">News Sources</div>
+ <div class="ldr-metric-value" id="news-sources">0</div>
+ </div>
+ </div>
+
+ <!-- Domain Distribution -->
+ <div style="margin-top: 2rem;">
+ <h3><i class="fas fa-globe"></i> Top Domains Used</h3>
+ <div id="domain-list" style="max-height: 400px; overflow-y: auto;">
+ <!-- Domain items will be populated here -->
+ </div>
+ </div>
+
+ <!-- Recent Resources Sample -->
+ <div style="margin-top: 2rem;">
+ <h3><i class="fas fa-file-text"></i> Sample Resources</h3>
+ <div id="resource-sample" style="max-height: 300px; overflow-y: auto;">
+ <!-- Resource samples will be populated here -->
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- LLM Call Stack Analysis -->
+ <div class="ldr-card ldr-metrics-section" id="call-stack-card" style="display: none; margin-top: 2rem;">
+ <div class="card-header">
+ <h2><i class="fas fa-code"></i> LLM Call Stack Analysis</h2>
+ </div>
+ <div class="ldr-card-content">
+ <div id="call-stack-traces" style="max-height: 600px; overflow-y: auto;">
+ <!-- Populated dynamically -->
+ </div>
+ </div>
+ </div>
+
</div> <!-- End details-content -->
</div>
{% endblock %}
-{% block templates %}
-{% endblock %}
-
{% block page_scripts %}
<script defer src="/static/js/components/details.js"></script>
{% endblock %}