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.

feat: add pagination to document listing endpoint

LearningCircuit216055548cf5
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index bc47e4574a..1fa138257b 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -444,11 +444,22 @@ def configure_rag():
@rag_bp.route("/api/rag/documents", methods=["GET"])
@login_required
def get_documents():
- """Get all library text documents with their RAG status."""
+ """Get library text documents with their RAG status (paginated)."""
from ...database.models.library import LibraryTextDocument
from ...database.session_context import get_user_db_session
try:
+ # Get pagination parameters
+ page = request.args.get("page", 1, type=int)
+ per_page = request.args.get("per_page", 50, type=int)
+ filter_type = request.args.get(
+ "filter", "all"
+ ) # all, indexed, unindexed
+
+ # Validate pagination parameters
+ page = max(1, page)
+ per_page = min(max(10, per_page), 100) # Limit between 10-100
+
# Close current thread's session to force fresh connection
from ...database.thread_local_session import cleanup_current_thread
@@ -456,7 +467,25 @@ def get_documents():
username = session["username"]
with get_user_db_session(username) as db_session:
- text_docs = db_session.query(LibraryTextDocument).all()
+ # Build base query
+ query = db_session.query(LibraryTextDocument)
+
+ # Apply filters
+ if filter_type == "indexed":
+ query = query.filter(LibraryTextDocument.rag_indexed.is_(True))
+ elif filter_type == "unindexed":
+ query = query.filter(LibraryTextDocument.rag_indexed.is_(False))
+
+ # Get total count before pagination
+ total_count = query.count()
+
+ # Apply pagination
+ text_docs = (
+ query.order_by(LibraryTextDocument.created_at.desc())
+ .limit(per_page)
+ .offset((page - 1) * per_page)
+ .all()
+ )
documents = [
{
@@ -472,7 +501,18 @@ def get_documents():
for doc in text_docs
]
- return jsonify({"success": True, "documents": documents})
+ return jsonify(
+ {
+ "success": True,
+ "documents": documents,
+ "pagination": {
+ "page": page,
+ "per_page": per_page,
+ "total": total_count,
+ "pages": (total_count + per_page - 1) // per_page,
+ },
+ }
+ )
except Exception as e:
logger.exception("Error getting documents")
return jsonify({"success": False, "error": str(e)}), 500
diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.js
index 34a5f0a4c0..16c08c2583 100644
--- a/src/local_deep_research/web/static/js/rag_manager.js
+++ b/src/local_deep_research/web/static/js/rag_manager.js
@@ -24,6 +24,9 @@ async function safeFetch(url, options = {}) {
// Store all documents for filtering
let allDocuments = [];
let currentFilter = 'all';
+let currentPage = 1;
+let totalPages = 1;
+const perPage = 50;
/**
* Initialize the page
@@ -628,18 +631,23 @@ function showError(message) {
}
/**
- * Load documents list
+ * Load documents list with pagination
*/
-async function loadDocuments() {
+async function loadDocuments(page = 1) {
const documentsContainer = document.getElementById('documents-list');
try {
- const response = await safeFetch('/library/api/rag/documents');
+ const response = await safeFetch(
+ `/library/api/rag/documents?page=${page}&per_page=${perPage}&filter=${currentFilter}`
+ );
const data = await response.json();
if (data.success) {
allDocuments = data.documents;
+ currentPage = data.pagination.page;
+ totalPages = data.pagination.pages;
renderDocuments();
+ renderPagination(data.pagination);
} else {
documentsContainer.innerHTML = `
<div class="ldr-alert ldr-alert-danger">
@@ -657,21 +665,102 @@ async function loadDocuments() {
}
}
+/**
+ * Render pagination controls
+ */
+function renderPagination(pagination) {
+ let paginationContainer = document.getElementById('pagination-container');
+
+ // Create container if it doesn't exist
+ if (!paginationContainer) {
+ paginationContainer = document.createElement('div');
+ paginationContainer.id = 'pagination-container';
+ paginationContainer.style.marginTop = '20px';
+ paginationContainer.style.textAlign = 'center';
+
+ const documentsSection = document.querySelector('.ldr-documents-section');
+ if (documentsSection) {
+ documentsSection.appendChild(paginationContainer);
+ }
+ }
+
+ if (pagination.pages <= 1) {
+ paginationContainer.innerHTML = '';
+ return;
+ }
+
+ const { page, pages, total } = pagination;
+
+ let paginationHTML = '<div class="ldr-pagination">';
+
+ // Previous button
+ paginationHTML += `
+ <button class="ldr-btn ldr-btn-sm"
+ onclick="loadDocuments(${page - 1})"
+ ${page <= 1 ? 'disabled' : ''}>
+ &laquo; Previous
+ </button>
+ `;
+
+ // Page numbers
+ const maxPageButtons = 5;
+ let startPage = Math.max(1, page - Math.floor(maxPageButtons / 2));
+ let endPage = Math.min(pages, startPage + maxPageButtons - 1);
+
+ if (endPage - startPage < maxPageButtons - 1) {
+ startPage = Math.max(1, endPage - maxPageButtons + 1);
+ }
+
+ if (startPage > 1) {
+ paginationHTML += `
+ <button class="ldr-btn ldr-btn-sm" onclick="loadDocuments(1)">1</button>
+ `;
+ if (startPage > 2) {
+ paginationHTML += '<span style="padding: 0 10px;">...</span>';
+ }
+ }
+
+ for (let i = startPage; i <= endPage; i++) {
+ paginationHTML += `
+ <button class="ldr-btn ldr-btn-sm ${i === page ? 'ldr-active' : ''}"
+ onclick="loadDocuments(${i})">
+ ${i}
+ </button>
+ `;
+ }
+
+ if (endPage < pages) {
+ if (endPage < pages - 1) {
+ paginationHTML += '<span style="padding: 0 10px;">...</span>';
+ }
+ paginationHTML += `
+ <button class="ldr-btn ldr-btn-sm" onclick="loadDocuments(${pages})">${pages}</button>
+ `;
+ }
+
+ // Next button
+ paginationHTML += `
+ <button class="ldr-btn ldr-btn-sm"
+ onclick="loadDocuments(${page + 1})"
+ ${page >= pages ? 'disabled' : ''}>
+ Next &raquo;
+ </button>
+ `;
+
+ paginationHTML += `</div>`;
+ paginationHTML += `<div style="margin-top: 10px; color: #666;">Showing ${allDocuments.length} of ${total} documents</div>`;
+
+ paginationContainer.innerHTML = paginationHTML;
+}
+
/**
* Render documents based on current filter
*/
function renderDocuments() {
const documentsContainer = document.getElementById('documents-list');
- // Filter documents
- let filteredDocs = allDocuments;
- if (currentFilter === 'indexed') {
- filteredDocs = allDocuments.filter(doc => doc.rag_indexed);
- } else if (currentFilter === 'unindexed') {
- filteredDocs = allDocuments.filter(doc => !doc.rag_indexed);
- }
-
- if (filteredDocs.length === 0) {
+ // Documents are already filtered by backend
+ if (allDocuments.length === 0) {
documentsContainer.innerHTML = `
<div class="ldr-alert ldr-alert-info">
No documents found for this filter.
@@ -681,7 +770,7 @@ function renderDocuments() {
}
// Render documents
- documentsContainer.innerHTML = filteredDocs.map(doc => `
+ documentsContainer.innerHTML = allDocuments.map(doc => `
<div class="ldr-document-item">
<div class="ldr-document-info">
<div class="ldr-document-title">${escapeHtml(doc.title)}</div>
@@ -722,8 +811,8 @@ function filterDocuments(filter) {
});
event.target.classList.add('ldr-active');
- // Re-render documents
- renderDocuments();
+ // Reload documents from page 1 with new filter
+ loadDocuments(1);
}
/**