~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: batched file uploads with improved drag-and-drop UX
LearningCircuit9531f9929deb
diff --git a/src/local_deep_research/security/file_upload_validator.py b/src/local_deep_research/security/file_upload_validator.pyindex a9a33bfdb6..a2aa2d8657 100644--- a/src/local_deep_research/security/file_upload_validator.py+++ b/src/local_deep_research/security/file_upload_validator.py@@ -20,7 +20,7 @@ class FileUploadValidator:# Security constantsMAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB per file- MAX_FILES_PER_REQUEST = 100 # Maximum number of files in single request+ MAX_FILES_PER_REQUEST = 200 # Maximum number of files in single requestPDF_MAGIC_BYTES = b"%PDF" # PDF file signatureALLOWED_MIME_TYPES = {"application/pdf"}diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex d7386fc1b7..e3332591d9 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -64,24 +64,101 @@ document.addEventListener('DOMContentLoaded', function() {dropZone.addEventListener('dragleave', handleDragLeave);dropZone.addEventListener('drop', handleDrop);}++ // IMMEDIATE document-level drag detection+ // Fires instantly when ANY file drag enters the window+ let dragCounter = 0;++ document.addEventListener('dragenter', (e) => {+ e.preventDefault();+ dragCounter++;+ if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {+ const dropZone = document.getElementById('drop-zone');+ if (dropZone) {+ dropZone.classList.add('ldr-drag-over');+ // Scroll drop zone into view if not visible+ if (!isElementInViewport(dropZone)) {+ dropZone.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }+ }+ }+ }, { capture: true });++ document.addEventListener('dragleave', (e) => {+ e.preventDefault();+ dragCounter--;+ // Only remove class when truly leaving the document+ if (dragCounter <= 0) {+ dragCounter = 0;+ const dropZone = document.getElementById('drop-zone');+ if (dropZone) {+ dropZone.classList.remove('ldr-drag-over');+ }+ }+ }, { capture: true });++ document.addEventListener('drop', (e) => {+ dragCounter = 0;+ const dropZone = document.getElementById('drop-zone');+ if (dropZone) {+ dropZone.classList.remove('ldr-drag-over');+ }+ }, { capture: true });++ // Prevent default for dragover on document to allow drop+ document.addEventListener('dragover', (e) => {+ e.preventDefault();+ }, { capture: true });});/**- * Handle drag over event+ * Check if element is in viewport+ */+function isElementInViewport(el) {+ const rect = el.getBoundingClientRect();+ return (+ rect.top >= 0 &&+ rect.left >= 0 &&+ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&+ rect.right <= (window.innerWidth || document.documentElement.clientWidth)+ );+}++// Throttle drag events for better performance+let dragOverTimeout = null;++/**+ * Handle drag over event (throttled)*/function handleDragOver(e) {e.preventDefault();e.stopPropagation();- e.currentTarget.classList.add('ldr-drag-over');++ // Only update class if not already set (avoid repeated DOM updates)+ if (!e.currentTarget.classList.contains('ldr-drag-over')) {+ e.currentTarget.classList.add('ldr-drag-over');+ }++ // Clear any pending drag leave+ if (dragOverTimeout) {+ clearTimeout(dragOverTimeout);+ dragOverTimeout = null;+ }}/**- * Handle drag leave event+ * Handle drag leave event (debounced)*/function handleDragLeave(e) {e.preventDefault();e.stopPropagation();- e.currentTarget.classList.remove('ldr-drag-over');++ const target = e.currentTarget;++ // Debounce the class removal to avoid flickering+ dragOverTimeout = setTimeout(() => {+ target.classList.remove('ldr-drag-over');+ }, 50);}/**@@ -132,31 +209,27 @@ function handleFiles(files) {* Show selected files preview*/function showSelectedFiles(files) {- console.log('👀 showSelectedFiles called with:', files.length, 'files');+ console.log(`👀 Showing preview for ${files.length} files`);const selectedFilesDiv = document.getElementById('selected-files');const fileList = document.getElementById('file-list');- console.log('👀 UI elements found:', {- selectedFilesDiv: !!selectedFilesDiv,- fileList: !!fileList- });// Clear existing file listfileList.innerHTML = '';- // Add each file to list- Array.from(files).forEach((file, index) => {- console.log(`👀 Processing file ${index + 1}:`, file.name, file.size);+ // Add each file to list (batch DOM updates)+ const fragment = document.createDocumentFragment();+ Array.from(files).forEach((file) => {const li = document.createElement('li');const fileSize = (file.size / 1024 / 1024).toFixed(2) + ' MB';li.innerHTML = `<i class="fas fa-file"></i><span>${escapeHtml(file.name)} (${fileSize})</span>`;- fileList.appendChild(li);+ fragment.appendChild(li);});+ fileList.appendChild(fragment);selectedFilesDiv.style.display = 'block';- console.log('👀 Selected files preview shown');}/**@@ -167,176 +240,338 @@ function hideSelectedFiles() {selectedFilesDiv.style.display = 'none';}+// Configuration for batched uploads+const BATCH_SIZE = 15; // Files per batch - balance between efficiency and memory+/**- * Handle file upload+ * Handle file upload - uses batched uploads for large file sets*/async function handleUploadFiles(e) {- console.log('🚀 UPLOAD BUTTON CLICKED - handleUploadFiles called');e.preventDefault();- console.log('✅ Form submission prevented');-- // Use globally stored files instead of file input- console.log('📁 Using stored files:', selectedFiles.length, 'files');- console.log('📁 Stored file names:', selectedFiles.map(f => f.name));-- // Also check file input state for debugging- const fileInput = document.getElementById('files-input');- console.log('🔍 File input state for comparison:', {- inputFiles: fileInput.files.length,- storedFiles: selectedFiles.length,- inputValue: fileInput.value- });if (selectedFiles.length === 0) {- console.log('❌ No files selected - showing error');showError('Please select at least one file to upload.');return;}- console.log('🔧 Building FormData...');- const formData = new FormData();- for (let file of selectedFiles) {- console.log(`📎 Adding file: ${file.name} (${file.size} bytes)`);- formData.append('files', file);- }-- // Add PDF storage mode selectionconst pdfStorageMode = document.querySelector('input[name="pdf_storage"]:checked')?.value || 'none';- formData.append('pdf_storage', pdfStorageMode);- console.log(`📦 PDF storage mode: ${pdfStorageMode}`);-- const progressDiv = document.getElementById('upload-progress');- const resultsDiv = document.getElementById('upload-results');const submitBtn = e.target.querySelector('button[type="submit"]');- console.log('🎯 UI elements found:', {- progressDiv: !!progressDiv,- resultsDiv: !!resultsDiv,- submitBtn: !!submitBtn- });+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');+ const uploadUrl = URLBuilder.build(URLS.LIBRARY_API.COLLECTION_UPLOAD, COLLECTION_ID);++ // Decide: batch upload for large sets, single upload for small sets+ const useBatchedUpload = selectedFiles.length > BATCH_SIZE;try {- console.log('⏳ Showing progress UI...');submitBtn.disabled = true;submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';- // Show clean progress display- showCleanProgress(selectedFiles);-- console.log('🔐 Getting CSRF token...');- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');- console.log('🔑 CSRF token found:', !!csrfToken);-- console.log('🌐 Building upload URL...');- const uploadUrl = URLBuilder.build(URLS.LIBRARY_API.COLLECTION_UPLOAD, COLLECTION_ID);- console.log('📡 Upload URL:', uploadUrl);- console.log('🆔 COLLECTION_ID:', COLLECTION_ID);-- console.log('🚀 Starting fetch request...');- const response = await safeFetch(uploadUrl, {- method: 'POST',- headers: {- 'X-CSRFToken': csrfToken- },- body: formData- });-- console.log('📨 Response status:', response.status);- console.log('📨 Response content-type:', response.headers.get('content-type'));-- // Check if response is OK- if (!response.ok) {- const errorText = await response.text();- console.error('❌ Server error response:', errorText);- throw new Error(`Server returned ${response.status}: ${errorText.substring(0, 100)}`);- }-- // Check if response is JSON- const contentType = response.headers.get('content-type');- if (!contentType || !contentType.includes('application/json')) {- const responseText = await response.text();- console.error('❌ Non-JSON response:', responseText);- throw new Error(`Expected JSON but got: ${contentType}. Response: ${responseText.substring(0, 100)}`);- }-- const data = await response.json();- console.log('✅ Parsed JSON data:', data);-- if (data.success) {- updateProgressComplete(data);- setTimeout(() => {- showUploadResults(data);- // Reset form and clear stored files- document.getElementById('upload-files-form').reset();- selectedFiles = []; // Clear stored files- hideSelectedFiles();- }, 500);+ if (useBatchedUpload) {+ // Batched upload for large file sets+ await handleBatchedUpload(selectedFiles, pdfStorageMode, csrfToken, uploadUrl);} else {- showError(data.error || 'Upload failed');+ // Single upload for small file sets+ await handleSingleUpload(selectedFiles, pdfStorageMode, csrfToken, uploadUrl);}} catch (error) {console.error('Error uploading files:', error);- // Check if this is a network error likely caused by timeout or payload too large- if (error.message.includes('NetworkError') || error.message.includes('Failed to fetch') || error.name === 'AbortError') {- const fileCount = selectedFiles.length;- const totalSize = selectedFiles.reduce((sum, f) => sum + f.size, 0);- const totalSizeMB = (totalSize / (1024 * 1024)).toFixed(1);- showError(- `<strong>Upload interrupted</strong><br><br>` +- `The upload of ${fileCount} files (${totalSizeMB} MB) was interrupted - likely due to timeout or size limits.<br><br>` +- `<strong>Note:</strong> Some files may have been uploaded successfully. Check the collection to see which files made it.<br><br>` +- `<strong>Tip:</strong> For large batches, upload 10-20 files at a time to avoid timeouts.`- );- } else {- showError('Upload failed: ' + error.message);- }+ showError('Upload failed: ' + error.message);} finally {submitBtn.disabled = false;submitBtn.innerHTML = '<i class="fas fa-upload"></i> 🚀 Upload Files';}}+/**+ * Handle batched upload - uploads files in smaller chunks+ */+async function handleBatchedUpload(files, pdfStorageMode, csrfToken, uploadUrl) {+ const totalFiles = files.length;+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);+ const batches = [];++ // Split files into batches+ for (let i = 0; i < files.length; i += BATCH_SIZE) {+ batches.push(files.slice(i, i + BATCH_SIZE));+ }++ console.log(`📦 Uploading ${totalFiles} files in ${batches.length} batches`);++ // Show batched progress UI+ showBatchedProgress(files, batches.length);++ // Track results across all batches+ const allUploaded = [];+ const allErrors = [];+ let uploadedBytes = 0;++ for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {+ const batch = batches[batchIndex];+ const batchSize = batch.reduce((sum, f) => sum + f.size, 0);++ updateBatchProgress(batchIndex + 1, batches.length, uploadedBytes, totalSize);++ try {+ const result = await uploadBatch(batch, pdfStorageMode, csrfToken, uploadUrl, (loaded) => {+ // Progress within this batch+ const currentProgress = uploadedBytes + loaded;+ const percent = Math.round((currentProgress / totalSize) * 100);+ updateBatchProgressBytes(percent, currentProgress, totalSize);+ });++ if (result.uploaded) allUploaded.push(...result.uploaded);+ if (result.errors) allErrors.push(...result.errors);++ uploadedBytes += batchSize;++ } catch (error) {+ console.error(`Batch ${batchIndex + 1} failed:`, error);+ // Mark all files in failed batch as errors+ batch.forEach(file => {+ allErrors.push({ filename: file.name, error: error.message });+ });+ }+ }++ // Show combined results+ const combinedResult = {+ success: true,+ uploaded: allUploaded,+ errors: allErrors,+ summary: { successful: allUploaded.length, failed: allErrors.length }+ };++ updateProgressComplete(combinedResult);+ setTimeout(() => {+ showUploadResults(combinedResult);+ document.getElementById('upload-files-form').reset();+ selectedFiles = [];+ hideSelectedFiles();+ }, 500);+}++/**+ * Upload a single batch of files+ */+function uploadBatch(files, pdfStorageMode, csrfToken, uploadUrl, onProgress) {+ return new Promise((resolve, reject) => {+ const formData = new FormData();+ for (let file of files) {+ formData.append('files', file);+ }+ formData.append('pdf_storage', pdfStorageMode);++ const xhr = new XMLHttpRequest();++ xhr.upload.onprogress = function(e) {+ if (e.lengthComputable && onProgress) {+ onProgress(e.loaded);+ }+ };++ xhr.onload = function() {+ if (xhr.status >= 200 && xhr.status < 300) {+ try {+ resolve(JSON.parse(xhr.responseText));+ } catch (e) {+ reject(new Error('Invalid JSON response'));+ }+ } else {+ reject(new Error(`Server returned ${xhr.status}`));+ }+ };++ xhr.onerror = function() {+ reject(new Error('Network error'));+ };++ xhr.ontimeout = function() {+ reject(new Error('Request timeout'));+ };++ xhr.open('POST', uploadUrl);+ xhr.setRequestHeader('X-CSRFToken', csrfToken);+ xhr.timeout = 300000; // 5 min per batch+ xhr.send(formData);+ });+}++/**+ * Handle single upload (original behavior for small file sets)+ */+async function handleSingleUpload(files, pdfStorageMode, csrfToken, uploadUrl) {+ const formData = new FormData();+ for (let file of files) {+ formData.append('files', file);+ }+ formData.append('pdf_storage', pdfStorageMode);++ showCleanProgress(files);++ const data = await new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();++ xhr.upload.onprogress = function(e) {+ if (e.lengthComputable) {+ const percentComplete = Math.round((e.loaded / e.total) * 100);+ const loadedMB = (e.loaded / (1024 * 1024)).toFixed(1);+ const totalMB = (e.total / (1024 * 1024)).toFixed(1);+ updateUploadProgress(percentComplete, loadedMB, totalMB);+ }+ };++ xhr.onload = function() {+ if (xhr.status >= 200 && xhr.status < 300) {+ try {+ resolve(JSON.parse(xhr.responseText));+ } catch (e) {+ reject(new Error('Invalid JSON response'));+ }+ } else {+ reject(new Error(`Server returned ${xhr.status}: ${xhr.responseText.substring(0, 100)}`));+ }+ };++ xhr.onerror = () => reject(new Error('NetworkError: Upload failed'));+ xhr.ontimeout = () => reject(new Error('Request timeout'));++ xhr.open('POST', uploadUrl);+ xhr.setRequestHeader('X-CSRFToken', csrfToken);+ xhr.timeout = 600000;+ xhr.send(formData);+ });++ if (data.success) {+ updateProgressComplete(data);+ setTimeout(() => {+ showUploadResults(data);+ document.getElementById('upload-files-form').reset();+ selectedFiles = [];+ hideSelectedFiles();+ }, 500);+ } else {+ showError(data.error || 'Upload failed');+ }+}++/**+ * Show batched upload progress UI+ */+function showBatchedProgress(files, totalBatches) {+ const progressDiv = document.getElementById('upload-progress');+ const totalFiles = files.length;+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);+ const totalSizeMB = (totalSize / (1024 * 1024)).toFixed(1);++ progressDiv.innerHTML = `+ <div style="padding: 1.5rem; background: #f8f9fa; border-radius: 8px;">+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">+ <h3 style="margin: 0; font-size: 1.1rem; color: #333;">+ <i class="fas fa-cloud-upload-alt" style="color: #667eea;"></i>+ Uploading ${totalFiles} Files+ </h3>+ <span id="progress-summary" style="font-weight: 600; color: #667eea;">+ 0% (0 / ${totalSizeMB} MB)+ </span>+ </div>++ <div style="background: #e9ecef; border-radius: 8px; height: 12px; overflow: hidden; margin-bottom: 1rem;">+ <div id="progress-bar-fill" style="background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); height: 100%; width: 0%; transition: width 0.2s ease;"></div>+ </div>++ <div id="progress-details" style="font-size: 0.9rem; color: #6c757d; margin-bottom: 0.5rem; text-align: center;">+ Preparing batched upload (${totalBatches} batches)...+ </div>++ <div id="batch-info" style="font-size: 0.85rem; color: #667eea; text-align: center;">+ Batch 1 of ${totalBatches}+ </div>+ </div>+ `;+ progressDiv.style.display = 'block';+}++/**+ * Update batched upload progress+ */+function updateBatchProgress(currentBatch, totalBatches, uploadedBytes, totalBytes) {+ const batchInfo = document.getElementById('batch-info');+ const progressDetails = document.getElementById('progress-details');++ if (batchInfo) {+ batchInfo.textContent = `Batch ${currentBatch} of ${totalBatches}`;+ }+ if (progressDetails) {+ progressDetails.textContent = `Uploading batch ${currentBatch}...`;+ }+}++/**+ * Update progress bar with byte-level accuracy+ */+function updateBatchProgressBytes(percent, uploadedBytes, totalBytes) {+ const progressBarFill = document.getElementById('progress-bar-fill');+ const progressSummary = document.getElementById('progress-summary');++ const uploadedMB = (uploadedBytes / (1024 * 1024)).toFixed(1);+ const totalMB = (totalBytes / (1024 * 1024)).toFixed(1);++ if (progressBarFill) {+ progressBarFill.style.width = percent + '%';+ }+ if (progressSummary) {+ progressSummary.textContent = `${percent}% (${uploadedMB} / ${totalMB} MB)`;+ }+}+/*** Show clean progress display with file list*/function showCleanProgress(files) {const progressDiv = document.getElementById('upload-progress');const totalFiles = files.length;+ const totalSize = files.reduce((sum, f) => sum + f.size, 0);+ const totalSizeMB = (totalSize / (1024 * 1024)).toFixed(1);let html = `<div style="padding: 1.5rem; background: #f8f9fa; border-radius: 8px;"><div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;"><h3 style="margin: 0; font-size: 1.1rem; color: #333;"><i class="fas fa-cloud-upload-alt" style="color: #667eea;"></i>- Uploading Files+ Uploading ${totalFiles} Files</h3><span id="progress-summary" style="font-weight: 600; color: #667eea;">- Processing ${totalFiles} file${totalFiles !== 1 ? 's' : ''}...+ 0% (0 / ${totalSizeMB} MB)</span></div>- <div style="background: #e9ecef; border-radius: 8px; height: 8px; overflow: hidden; margin-bottom: 1rem;">- <div id="progress-bar-fill" style="background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); height: 100%; width: 0%; transition: width 0.3s ease;"></div>+ <div style="background: #e9ecef; border-radius: 8px; height: 12px; overflow: hidden; margin-bottom: 1rem;">+ <div id="progress-bar-fill" style="background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); height: 100%; width: 0%; transition: width 0.2s ease;"></div>+ </div>++ <div id="progress-details" style="font-size: 0.9rem; color: #6c757d; margin-bottom: 1rem; text-align: center;">+ Starting upload...</div>- <div id="file-progress-list" style="max-height: 300px; overflow-y: auto;">+ <details style="margin-top: 1rem;">+ <summary style="cursor: pointer; color: #667eea; font-weight: 500;">Show file list (${totalFiles} files)</summary>+ <div id="file-progress-list" style="max-height: 300px; overflow-y: auto; margin-top: 0.5rem;">`;files.forEach((file, index) => {const fileSize = (file.size / 1024 / 1024).toFixed(2);html += `- <div id="file-${index}" style="display: flex; align-items: center; padding: 0.75rem; background: white; border-radius: 6px; margin-bottom: 0.5rem; border: 1px solid #dee2e6;">- <i class="fas fa-spinner fa-spin" style="color: #667eea; margin-right: 0.75rem; width: 16px;"></i>- <div style="flex: 1;">- <div style="font-weight: 500; color: #333; margin-bottom: 0.25rem;">${escapeHtml(file.name)}</div>- <div style="font-size: 0.85rem; color: #6c757d;">${fileSize} MB</div>- </div>- <span style="font-size: 0.85rem; color: #667eea; font-weight: 500;">Uploading...</span>+ <div id="file-${index}" style="display: flex; align-items: center; padding: 0.5rem; background: white; border-radius: 4px; margin-bottom: 0.25rem; border: 1px solid #dee2e6; font-size: 0.85rem;">+ <i class="fas fa-file-pdf" style="color: #e74c3c; margin-right: 0.5rem; width: 14px;"></i>+ <span style="flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${escapeHtml(file.name)}</span>+ <span style="color: #6c757d; margin-left: 0.5rem;">${fileSize} MB</span></div>`;});html += `- </div>+ </div>+ </details></div>`;@@ -344,60 +579,60 @@ function showCleanProgress(files) {progressDiv.style.display = 'block';}+/**+ * Update upload progress display+ */+function updateUploadProgress(percent, loadedMB, totalMB) {+ const progressBarFill = document.getElementById('progress-bar-fill');+ const progressSummary = document.getElementById('progress-summary');+ const progressDetails = document.getElementById('progress-details');++ if (progressBarFill) {+ progressBarFill.style.width = percent + '%';+ }++ if (progressSummary) {+ progressSummary.textContent = `${percent}% (${loadedMB} / ${totalMB} MB)`;+ }++ if (progressDetails) {+ if (percent < 100) {+ progressDetails.textContent = `Uploading... ${loadedMB} MB of ${totalMB} MB transferred`;+ } else {+ progressDetails.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing files on server...';+ }+ }+}+/*** Update progress to show completion*/function updateProgressComplete(data) {const progressBarFill = document.getElementById('progress-bar-fill');const progressSummary = document.getElementById('progress-summary');+ const progressDetails = document.getElementById('progress-details');if (progressBarFill) {progressBarFill.style.width = '100%';+ progressBarFill.style.background = '#27ae60';}+ // Server returns data.uploaded and data.errors (not uploaded_files/failed_files)+ const successCount = data.uploaded ? data.uploaded.length : (data.summary?.successful || 0);+ const failedCount = data.errors ? data.errors.length : (data.summary?.failed || 0);+if (progressSummary) {- const successCount = data.uploaded_files ? data.uploaded_files.length : 0;- const failedCount = data.failed_files ? data.failed_files.length : 0;progressSummary.textContent = `✓ ${successCount} uploaded${failedCount > 0 ? `, ${failedCount} failed` : ''}`;progressSummary.style.color = failedCount > 0 ? '#f39c12' : '#27ae60';}- // Update individual file status- if (data.uploaded_files) {- data.uploaded_files.forEach((file, index) => {- const fileDiv = document.getElementById(`file-${index}`);- if (fileDiv) {- const icon = fileDiv.querySelector('i');- const status = fileDiv.querySelector('span:last-child');- icon.className = 'fas fa-check-circle';- icon.style.color = '#27ae60';- status.textContent = 'Complete';- status.style.color = '#27ae60';- fileDiv.style.borderColor = '#27ae60';- fileDiv.style.background = '#f0fff4';- }- });- }-- if (data.failed_files) {- data.failed_files.forEach((file, index) => {- const fileDiv = document.getElementById(`file-${index}`);- if (fileDiv) {- const icon = fileDiv.querySelector('i');- const status = fileDiv.querySelector('span:last-child');- icon.className = 'fas fa-exclamation-circle';- icon.style.color = '#e74c3c';- status.textContent = 'Failed';- status.style.color = '#e74c3c';- fileDiv.style.borderColor = '#e74c3c';- fileDiv.style.background = '#fff5f5';- }- });+ if (progressDetails) {+ progressDetails.innerHTML = `<i class="fas fa-check-circle" style="color: #27ae60;"></i> Upload complete!`;}}/**- * Show upload results+ * Show upload results with clear breakdown*/function showUploadResults(data) {const progressDiv = document.getElementById('upload-progress');@@ -406,32 +641,102 @@ function showUploadResults(data) {// Hide progress displayprogressDiv.style.display = 'none';- let html = '<div class="alert" style="background: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">';- html += '<h4 style="margin: 0 0 0.5rem 0;"><i class="fas fa-check-circle"></i> Upload Complete!</h4>';+ // Server returns data.uploaded and data.errors+ const uploadedFiles = data.uploaded || [];+ const failedFiles = data.errors || [];- if (data.uploaded_files && data.uploaded_files.length > 0) {- html += '<p><strong>Successfully uploaded:</strong></p><ul>';- data.uploaded_files.forEach(file => {- html += `<li>✅ ${escapeHtml(file.name)} (${(file.size / 1024 / 1024).toFixed(2)} MB)</li>`;- });- html += '</ul>';+ // Categorize by status+ const newUploads = uploadedFiles.filter(f => f.status === 'uploaded');+ const addedToCollection = uploadedFiles.filter(f => f.status === 'added_to_collection' || f.status === 'added_to_collection_pdf_upgraded');+ const alreadyInCollection = uploadedFiles.filter(f => f.status === 'already_in_collection' || f.status === 'pdf_upgraded');++ const actualNewCount = newUploads.length + addedToCollection.length;+ const skippedCount = alreadyInCollection.length;++ let html = '<div style="padding: 1.5rem; background: #f8f9fa; border-radius: 8px;">';++ // Summary header+ html += '<h3 style="margin: 0 0 1rem 0; color: #333;"><i class="fas fa-check-circle" style="color: #28a745;"></i> Upload Complete!</h3>';++ // Stats grid+ html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">';++ if (actualNewCount > 0) {+ html += `<div style="background: #d4edda; padding: 1rem; border-radius: 8px; text-align: center;">+ <div style="font-size: 1.5rem; font-weight: 700; color: #155724;">${actualNewCount}</div>+ <div style="font-size: 0.85rem; color: #155724;">New Files Added</div>+ </div>`;}- if (data.failed_files && data.failed_files.length > 0) {- html += '<p><strong>Failed to upload:</strong></p><ul>';- data.failed_files.forEach(file => {- html += `<li>❌ ${escapeHtml(file.name)}: ${escapeHtml(file.error)}</li>`;- });- html += '</ul>';+ if (skippedCount > 0) {+ html += `<div style="background: #fff3cd; padding: 1rem; border-radius: 8px; text-align: center;">+ <div style="font-size: 1.5rem; font-weight: 700; color: #856404;">${skippedCount}</div>+ <div style="font-size: 0.85rem; color: #856404;">Already Existed</div>+ </div>`;+ }++ if (failedFiles.length > 0) {+ html += `<div style="background: #f8d7da; padding: 1rem; border-radius: 8px; text-align: center;">+ <div style="font-size: 1.5rem; font-weight: 700; color: #721c24;">${failedFiles.length}</div>+ <div style="font-size: 0.85rem; color: #721c24;">Failed</div>+ </div>`;+ }++ html += '</div>';++ // Details sections+ if (newUploads.length > 0) {+ html += `<details style="margin-bottom: 0.5rem;">+ <summary style="cursor: pointer; color: #28a745; font-weight: 500;">+ ✅ New uploads (${newUploads.length})+ </summary>+ <ul style="margin: 0.5rem 0 0 1rem; padding: 0; list-style: none;">+ ${newUploads.map(f => `<li style="padding: 0.25rem 0;">📄 ${escapeHtml(f.filename)}</li>`).join('')}+ </ul>+ </details>`;+ }++ if (addedToCollection.length > 0) {+ html += `<details style="margin-bottom: 0.5rem;">+ <summary style="cursor: pointer; color: #17a2b8; font-weight: 500;">+ 📁 Added to collection (already in library) (${addedToCollection.length})+ </summary>+ <ul style="margin: 0.5rem 0 0 1rem; padding: 0; list-style: none;">+ ${addedToCollection.map(f => `<li style="padding: 0.25rem 0;">📄 ${escapeHtml(f.filename)}</li>`).join('')}+ </ul>+ </details>`;+ }++ if (alreadyInCollection.length > 0) {+ html += `<details style="margin-bottom: 0.5rem;">+ <summary style="cursor: pointer; color: #856404; font-weight: 500;">+ ⏭️ Skipped - already in collection (${alreadyInCollection.length})+ </summary>+ <ul style="margin: 0.5rem 0 0 1rem; padding: 0; list-style: none;">+ ${alreadyInCollection.map(f => `<li style="padding: 0.25rem 0;">📄 ${escapeHtml(f.filename)}</li>`).join('')}+ </ul>+ </details>`;+ }++ if (failedFiles.length > 0) {+ html += `<details open style="margin-bottom: 0.5rem;">+ <summary style="cursor: pointer; color: #dc3545; font-weight: 500;">+ ❌ Failed (${failedFiles.length})+ </summary>+ <ul style="margin: 0.5rem 0 0 1rem; padding: 0; list-style: none;">+ ${failedFiles.map(f => `<li style="padding: 0.25rem 0; color: #721c24;">📄 ${escapeHtml(f.filename)}: ${escapeHtml(f.error)}</li>`).join('')}+ </ul>+ </details>`;}- html += '<div style="margin-top: 1rem;">';- html += `<a href="/library/collections/${COLLECTION_ID}" class="ldr-btn-collections ldr-btn-collections-primary">`;- html += '<i class="fas fa-folder-open"></i> View Collection';- html += '</a>';- html += '<button onclick="location.reload()" class="ldr-btn-collections ldr-btn-collections-secondary" style="margin-left: 1rem;">';- html += '<i class="fas fa-plus"></i> Upload More Files';- html += '</button>';+ // Action buttons+ html += '<div style="margin-top: 1.5rem; display: flex; gap: 1rem; flex-wrap: wrap;">';+ html += `<a href="/library/collections/${COLLECTION_ID}" class="ldr-btn-collections ldr-btn-collections-primary">+ <i class="fas fa-folder-open"></i> View Collection+ </a>`;+ html += `<button onclick="location.reload()" class="ldr-btn-collections ldr-btn-collections-secondary">+ <i class="fas fa-plus"></i> Upload More Files+ </button>`;html += '</div>';html += '</div>';diff --git a/tests/pdf_tests/test_file_validator.py b/tests/pdf_tests/test_file_validator.pyindex 30517a2b1b..10fd98636f 100644--- a/tests/pdf_tests/test_file_validator.py+++ b/tests/pdf_tests/test_file_validator.py@@ -274,9 +274,9 @@ class TestConstants:expected = 50 * 1024 * 1024assert FileUploadValidator.MAX_FILE_SIZE == expected- def test_max_files_is_100(self):- """Verify MAX_FILES_PER_REQUEST is 100."""- assert FileUploadValidator.MAX_FILES_PER_REQUEST == 100+ def test_max_files_is_200(self):+ """Verify MAX_FILES_PER_REQUEST is 200."""+ assert FileUploadValidator.MAX_FILES_PER_REQUEST == 200def test_pdf_magic_bytes(self):"""Verify PDF magic bytes."""diff --git a/tests/security/test_file_upload_validator.py b/tests/security/test_file_upload_validator.pyindex 5f79aeab40..fabfcfdac3 100644--- a/tests/security/test_file_upload_validator.py+++ b/tests/security/test_file_upload_validator.py@@ -21,7 +21,7 @@ class TestFileUploadValidatorConstants:def test_max_files_per_request_defined(self):"""MAX_FILES_PER_REQUEST is defined and reasonable."""assert FileUploadValidator.MAX_FILES_PER_REQUEST > 0- assert FileUploadValidator.MAX_FILES_PER_REQUEST == 100+ assert FileUploadValidator.MAX_FILES_PER_REQUEST == 200def test_pdf_magic_bytes_correct(self):"""PDF_MAGIC_BYTES is correct."""