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(zotero): import & auto-sync Zotero collections into the library (#4723)

LearningCircuita9bc2f30740a
diff --git a/changelog.d/4723.feature.md b/changelog.d/4723.feature.md
new file mode 100644
index 0000000000..91ae4bcbe3
--- /dev/null
+++ b/changelog.d/4723.feature.md
@@ -0,0 +1 @@
+**New Zotero integration: import a Zotero library or collection into your document library, with optional background auto-sync.** Add your Zotero API key, library type/ID and (optionally) a collection key under **Settings → Zotero**, then use the new **Library → Zotero** page to test the connection, list collections, and **Sync now**. Imported papers are stored, text-extracted and RAG-indexed like any other library document, so they become searchable during research via the collection search engine — no separate search engine to configure. Sync is incremental (new, changed and removed items are reconciled), and items without an attached PDF are imported as metadata/abstract text by default (toggle off to import PDFs only). Enable **Auto-Sync** to refresh in the background on a configurable interval.
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index 2cbcab8e12..8d506f684a 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -95,6 +95,12 @@ def seed_source_types(username: str, password: str = None) -> None:
"description": "Sources discovered during research with content for semantic search",
"icon": "link",
},
+ {
+ "name": "zotero",
+ "display_name": "Zotero",
+ "description": "Documents imported from a Zotero library or collection",
+ "icon": "book",
+ },
]
try:
diff --git a/src/local_deep_research/database/migrations/versions/0020_add_zotero_tables.py b/src/local_deep_research/database/migrations/versions/0020_add_zotero_tables.py
new file mode 100644
index 0000000000..5116f5dc6f
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0020_add_zotero_tables.py
@@ -0,0 +1,174 @@
+"""Add Zotero integration tables.
+
+Creates the two tables that back the Zotero import / auto-sync feature in
+each user's encrypted per-user database:
+
+ - zotero_sync_state: one row per configured (library, collection) pair,
+ tracking the LDR collection it maps to and the Zotero library version
+ reached by the last successful sync (informational high-water mark).
+ - zotero_item_map: maps an individual Zotero item to the LDR document it
+ was imported as, plus the item's Zotero version (for change/removal
+ detection via full version-map reconciliation; see the model docstring).
+
+Both tables are new, so there is no data migration. The schema source of
+truth is the SQLAlchemy models in database/models/zotero.py; this migration
+exists because per-user databases are built purely from the Alembic chain
+(see database/initialize.py).
+
+Revision ID: 0020
+Revises: 0019
+Create Date: 2026-06-20
+"""
+
+from alembic import op
+import sqlalchemy as sa
+from loguru import logger
+from sqlalchemy import inspect
+from sqlalchemy_utc import UtcDateTime
+
+# revision identifiers, used by Alembic.
+revision = "0020"
+down_revision = "0019"
+branch_labels = None
+depends_on = None
+
+
+# (index_name, table_name, [columns]) — created idempotently after the
+# tables exist. Unique constraints are defined inline in create_table.
+ZOTERO_INDEXES = [
+ (
+ "ix_zotero_sync_state_ldr_collection_id",
+ "zotero_sync_state",
+ ["ldr_collection_id"],
+ ),
+ (
+ "ix_zotero_item_map_ldr_collection_id",
+ "zotero_item_map",
+ ["ldr_collection_id"],
+ ),
+ (
+ "ix_zotero_item_map_zotero_item_key",
+ "zotero_item_map",
+ ["zotero_item_key"],
+ ),
+ (
+ "ix_zotero_item_map_document_id",
+ "zotero_item_map",
+ ["document_id"],
+ ),
+]
+
+
+def _index_exists(index_name: str, table_name: str) -> bool:
+ bind = op.get_bind()
+ inspector = inspect(bind)
+ if not inspector.has_table(table_name):
+ return False
+ return any(
+ idx["name"] == index_name for idx in inspector.get_indexes(table_name)
+ )
+
+
+def upgrade():
+ bind = op.get_bind()
+ inspector = inspect(bind)
+
+ if not inspector.has_table("zotero_sync_state"):
+ op.create_table(
+ "zotero_sync_state",
+ sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
+ sa.Column("library_type", sa.String(10), nullable=False),
+ sa.Column("library_id", sa.String(64), nullable=False),
+ sa.Column(
+ "collection_key",
+ sa.String(16),
+ nullable=False,
+ server_default="",
+ ),
+ sa.Column(
+ "ldr_collection_id",
+ sa.String(36),
+ sa.ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column(
+ "last_version",
+ sa.Integer(),
+ nullable=False,
+ server_default="0",
+ ),
+ sa.Column("last_synced_at", UtcDateTime(), nullable=True),
+ sa.Column(
+ "last_status",
+ sa.String(20),
+ nullable=False,
+ server_default="pending",
+ ),
+ sa.Column("last_error", sa.Text(), nullable=True),
+ sa.Column(
+ "item_count", sa.Integer(), nullable=False, server_default="0"
+ ),
+ sa.Column("created_at", UtcDateTime(), nullable=False),
+ sa.Column("updated_at", UtcDateTime(), nullable=False),
+ sa.UniqueConstraint(
+ "library_type",
+ "library_id",
+ "collection_key",
+ name="uq_zotero_sync_state_library_collection",
+ ),
+ )
+ logger.info("0020: created zotero_sync_state")
+
+ if not inspector.has_table("zotero_item_map"):
+ op.create_table(
+ "zotero_item_map",
+ sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
+ sa.Column(
+ "ldr_collection_id",
+ sa.String(36),
+ sa.ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("zotero_item_key", sa.String(16), nullable=False),
+ sa.Column(
+ "zotero_version",
+ sa.Integer(),
+ nullable=False,
+ server_default="0",
+ ),
+ sa.Column(
+ "document_id",
+ sa.String(36),
+ sa.ForeignKey("documents.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ sa.Column(
+ "has_pdf",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.false(),
+ ),
+ sa.Column("last_synced_at", UtcDateTime(), nullable=True),
+ sa.Column("created_at", UtcDateTime(), nullable=False),
+ sa.Column("updated_at", UtcDateTime(), nullable=False),
+ sa.UniqueConstraint(
+ "ldr_collection_id",
+ "zotero_item_key",
+ name="uq_zotero_item_map_collection_item",
+ ),
+ )
+ logger.info("0020: created zotero_item_map")
+
+ for index_name, table_name, columns in ZOTERO_INDEXES:
+ if not _index_exists(index_name, table_name):
+ op.create_index(index_name, table_name, columns)
+
+
+def downgrade():
+ bind = op.get_bind()
+ inspector = inspect(bind)
+
+ if inspector.has_table("zotero_item_map"):
+ op.drop_table("zotero_item_map")
+ if inspector.has_table("zotero_sync_state"):
+ op.drop_table("zotero_sync_state")
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index 586267928c..243d9461c5 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -90,6 +90,12 @@ from .file_integrity import (
FileVerificationFailure,
)
+# Import Zotero integration models
+from .zotero import (
+ ZoteroSyncState,
+ ZoteroItemMap,
+)
+
# Import Domain Classification model
from ...domain_classifier.models import DomainClassification
@@ -187,6 +193,9 @@ __all__ = [
"ChatProgressStep",
"ChatRole",
"ChatSessionStatus",
+ # Zotero Integration Models
+ "ZoteroSyncState",
+ "ZoteroItemMap",
# Domain Classification
"DomainClassification",
]
diff --git a/src/local_deep_research/database/models/zotero.py b/src/local_deep_research/database/models/zotero.py
new file mode 100644
index 0000000000..4eec467ea5
--- /dev/null
+++ b/src/local_deep_research/database/models/zotero.py
@@ -0,0 +1,145 @@
+"""
+Zotero integration models.
+
+These tables live in each user's encrypted per-user database and track the
+state needed to sync a Zotero library/collection into the document library:
+
+- ``ZoteroSyncState``: one row per configured (library, collection) pair. It
+ remembers which LDR :class:`Collection` the Zotero collection maps to and
+ the Zotero *library version* reached by the last successful sync
+ (``last_version`` — informational / shown in the status UI; see below).
+- ``ZoteroItemMap``: maps an individual Zotero item to the LDR
+ :class:`Document` it was imported as, plus the item's Zotero version. This
+ enables skipping unchanged items, re-importing changed ones, and detecting
+ items removed from the collection so they can be removed locally.
+
+Sync compares the *full* current ``{itemKey: version}`` map of the
+collection's top-level items against ``ZoteroItemMap`` — additions/changes by
+version, removals by absence. This deliberately does NOT use a ``?since=``
+delta: a delta (or the library-level ``/deleted`` feed) would not catch items
+*removed from the collection* but still present in the library, whereas the
+full-map comparison does.
+
+"""
+
+from sqlalchemy import (
+ Boolean,
+ Column,
+ ForeignKey,
+ Integer,
+ String,
+ Text,
+ UniqueConstraint,
+)
+from sqlalchemy_utc import UtcDateTime, utcnow
+
+from .base import Base
+
+
+class ZoteroSyncState(Base):
+ """Per-collection sync bookkeeping for the Zotero integration."""
+
+ __tablename__ = "zotero_sync_state"
+ __table_args__ = (
+ UniqueConstraint(
+ "library_type",
+ "library_id",
+ "collection_key",
+ name="uq_zotero_sync_state_library_collection",
+ ),
+ )
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ # Zotero library identity
+ library_type = Column(String(10), nullable=False) # 'user' | 'group'
+ library_id = Column(String(64), nullable=False)
+ # Empty string means "the entire library" (no specific collection).
+ # Stored as "" rather than NULL so the UNIQUE constraint is effective on
+ # SQLite (which treats NULLs as distinct).
+ collection_key = Column(String(16), nullable=False, default="")
+
+ # LDR collection these items are imported into
+ ldr_collection_id = Column(
+ String(36),
+ ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ index=True,
+ )
+
+ # Zotero library version reached by the last successful sync.
+ # Informational (surfaced in the status UI) — NOT used as a ``?since=``
+ # cursor; each sync fetches the full current version map (see module
+ # docstring for why). 0 means "never synced".
+ last_version = Column(Integer, nullable=False, default=0)
+
+ last_synced_at = Column(UtcDateTime, nullable=True)
+ last_status = Column(
+ String(20), nullable=False, default="pending"
+ ) # pending | syncing | completed | failed
+ last_error = Column(Text, nullable=True)
+ item_count = Column(Integer, nullable=False, default=0)
+
+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ updated_at = Column(
+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False
+ )
+
+ def __repr__(self) -> str:
+ return (
+ f"<ZoteroSyncState(library={self.library_type}:{self.library_id}, "
+ f"collection={self.collection_key or 'ALL'}, "
+ f"version={self.last_version})>"
+ )
+
+
+class ZoteroItemMap(Base):
+ """Maps a single Zotero item to the LDR document it was imported as."""
+
+ __tablename__ = "zotero_item_map"
+ __table_args__ = (
+ UniqueConstraint(
+ "ldr_collection_id",
+ "zotero_item_key",
+ name="uq_zotero_item_map_collection_item",
+ ),
+ )
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ ldr_collection_id = Column(
+ String(36),
+ ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ index=True,
+ )
+ # The Zotero (parent) item key this row tracks.
+ zotero_item_key = Column(String(16), nullable=False, index=True)
+ # Zotero item version at last import — used for change detection.
+ zotero_version = Column(Integer, nullable=False, default=0)
+
+ # The LDR document this item was imported as. SET NULL on document
+ # deletion so a removed document doesn't dangle. A null document_id marks
+ # an item deliberately not imported (skipped, or its document was deleted
+ # locally); the sync service re-imports it only when the item's Zotero
+ # version changes. A non-null document_id whose Document row went missing
+ # IS re-imported on the next sync.
+ document_id = Column(
+ String(36),
+ ForeignKey("documents.id", ondelete="SET NULL"),
+ nullable=True,
+ index=True,
+ )
+ has_pdf = Column(Boolean, nullable=False, default=False)
+
+ last_synced_at = Column(UtcDateTime, nullable=True)
+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ updated_at = Column(
+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False
+ )
+
+ def __repr__(self) -> str:
+ return (
+ f"<ZoteroItemMap(item={self.zotero_item_key}, "
+ f"document={self.document_id}, version={self.zotero_version})>"
+ )
diff --git a/src/local_deep_research/defaults/settings_zotero.json b/src/local_deep_research/defaults/settings_zotero.json
new file mode 100644
index 0000000000..c0e8c9b3f0
--- /dev/null
+++ b/src/local_deep_research/defaults/settings_zotero.json
@@ -0,0 +1,177 @@
+{
+ "zotero.enabled": {
+ "category": "zotero",
+ "description": "Enable the Zotero integration. When on, you can import papers from a Zotero collection into your library and (optionally) keep them in sync.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Enable Zotero Integration",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.use_local_api": {
+ "category": "zotero",
+ "description": "Sync from the Zotero desktop app running on this machine (local API at localhost:23119) instead of the cloud Web API. No API key needed, and it can read locally-stored / linked-file attachments the cloud API can't. Requires Zotero 7+ with the local API enabled in its preferences, and Zotero running during sync. Caution on shared/multi-user hosts: the desktop app's local API is unauthenticated, so any user or process on the server able to reach localhost:23119 can read that Zotero library.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Use Local Zotero (desktop app)",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.api_key": {
+ "category": "zotero",
+ "description": "Your Zotero API key. Create one at https://www.zotero.org/settings/keys (it needs read access to the library you want to import). Not needed if 'Use Local Zotero' is enabled.",
+ "editable": true,
+ "env_var": "LDR_ZOTERO_API_KEY",
+ "max_value": null,
+ "min_value": null,
+ "name": "Zotero API Key",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
+ "zotero.library_type": {
+ "category": "zotero",
+ "description": "Whether to read from your personal user library or a shared group library.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Library Type",
+ "options": [
+ {"value": "user", "label": "Personal (user) library"},
+ {"value": "group", "label": "Group library"}
+ ],
+ "step": null,
+ "type": "APP",
+ "ui_element": "select",
+ "value": "user",
+ "visible": true
+ },
+ "zotero.library_id": {
+ "category": "zotero",
+ "description": "Numeric library ID. For a personal library this is your userID (see https://www.zotero.org/settings/keys). For a group library it is the group's numeric ID.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Library ID",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.collection_keys": {
+ "category": "zotero",
+ "description": "Comma-separated Zotero collection keys to import (e.g. ABCD1234). Leave empty to import the entire library. Use the 'List collections' button on the Zotero page to find keys.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Collection Keys",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.import_tags": {
+ "category": "zotero",
+ "description": "Only import items tagged with ALL of these comma-separated Zotero tags (case-insensitive). Leave empty to import everything. This filters what is imported; changing it does not remove items already imported.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Only These Tags",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.import_items_without_pdf": {
+ "category": "zotero",
+ "description": "Also import items that have no attached PDF, using their title/abstract/metadata as a text-only document so they remain searchable. Turn off to import only items with a downloadable PDF. Not retroactive: items skipped while this was off are picked up only when they next change in Zotero.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Items Without a PDF",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "zotero.import_annotations": {
+ "category": "zotero",
+ "description": "Also import your Zotero PDF annotations (highlights + comments) and child notes, appended to the document's searchable text. Adds extra API calls per item, so it's off by default. Note: annotation/note edits that don't change the parent item are picked up only when the item itself changes.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Annotations & Notes",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.pdf_storage_mode": {
+ "category": "zotero",
+ "description": "How to store imported PDFs. 'database' keeps the PDF inside your encrypted database; 'none' stores only the extracted text (smaller, but the original PDF is not retained).",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "PDF Storage Mode",
+ "options": [
+ {"value": "database", "label": "Store PDF in encrypted database"},
+ {"value": "none", "label": "Text only (don't keep the PDF)"}
+ ],
+ "step": null,
+ "type": "APP",
+ "ui_element": "select",
+ "value": "database",
+ "visible": true
+ },
+ "zotero.auto_sync_enabled": {
+ "category": "zotero",
+ "description": "Periodically re-sync the configured collections in the background (downloads new items, updates changed ones, and removes items deleted in Zotero). Requires the Zotero integration to be enabled.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Auto-Sync in Background",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.sync_interval_minutes": {
+ "category": "zotero",
+ "description": "How often the background auto-sync runs (minutes).",
+ "editable": true,
+ "max_value": 10080,
+ "min_value": 15,
+ "name": "Auto-Sync Interval (minutes)",
+ "options": null,
+ "step": 15,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 360,
+ "visible": true
+ }
+}
diff --git a/src/local_deep_research/research_library/__init__.py b/src/local_deep_research/research_library/__init__.py
index 42562f0890..9d72faca30 100644
--- a/src/local_deep_research/research_library/__init__.py
+++ b/src/local_deep_research/research_library/__init__.py
@@ -13,6 +13,7 @@ from .services.library_service import LibraryService
from .services.library_rag_service import LibraryRAGService
from .routes.library_routes import library_bp
from .routes.rag_routes import rag_bp
+from .routes.zotero_routes import zotero_bp
from .deletion.routes import delete_bp
from .search import search_bp
@@ -22,6 +23,7 @@ __all__ = [
"LibraryRAGService",
"library_bp",
"rag_bp",
+ "zotero_bp",
"delete_bp",
"search_bp",
]
diff --git a/src/local_deep_research/research_library/routes/zotero_routes.py b/src/local_deep_research/research_library/routes/zotero_routes.py
new file mode 100644
index 0000000000..629cd9ff14
--- /dev/null
+++ b/src/local_deep_research/research_library/routes/zotero_routes.py
@@ -0,0 +1,196 @@
+"""
+Web routes for the Zotero integration.
+
+Exposes a small page plus JSON endpoints to test the connection, list the
+user's Zotero collections, trigger a manual sync, and read sync status.
+Credentials and options live in user settings (category ``zotero``); these
+routes never accept or return the API key.
+"""
+
+import threading
+
+from flask import Blueprint, current_app, jsonify, render_template, session
+from loguru import logger
+
+from ...database.session_passwords import session_password_store
+from ...database.thread_local_session import thread_cleanup
+from ...web.auth.decorators import login_required
+from ..utils import handle_api_error
+from ..zotero import ZoteroSyncService
+
+zotero_bp = Blueprint("zotero", __name__, url_prefix="/library")
+
+
+def _db_password() -> str | None:
+ """Resolve the current session's database password."""
+ return session_password_store.get_session_password(
+ session["username"], session.get("session_id")
+ )
+
+
+def _session_expired_response():
+ """401 for a logged-in session whose cached DB password has expired.
+
+ Every endpoint below opens the user's encrypted database, so without the
+ password the request cannot succeed — tell the client to re-authenticate
+ instead of failing with a generic 500.
+ """
+ return jsonify(
+ {
+ "success": False,
+ "error": "Session expired — please sign in again.",
+ }
+ ), 401
+
+
+@zotero_bp.route("/zotero")
+@login_required
+def zotero_page():
+ """Render the Zotero integration page."""
+ return render_template("pages/zotero.html", active_page="zotero")
+
+
+@zotero_bp.route("/api/zotero/config", methods=["GET"])
+@login_required
+def get_config():
+ """Return a non-secret summary of the Zotero configuration."""
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+ try:
+ cfg = ZoteroSyncService(session["username"], password).get_config()
+ return jsonify(
+ {
+ "success": True,
+ "enabled": cfg.enabled,
+ "configured": cfg.is_configured,
+ "library_type": cfg.library_type,
+ "library_id": cfg.library_id,
+ "collection_keys": cfg.collection_keys,
+ "import_tags": cfg.import_tags,
+ "import_items_without_pdf": cfg.import_items_without_pdf,
+ "import_annotations": cfg.import_annotations,
+ "pdf_storage_mode": cfg.pdf_storage_mode,
+ "auto_sync_enabled": cfg.auto_sync_enabled,
+ "sync_interval_minutes": cfg.sync_interval_minutes,
+ "use_local_api": cfg.use_local_api,
+ "has_api_key": bool(cfg.api_key),
+ }
+ )
+ except Exception as e:
+ return handle_api_error("getting Zotero config", e)
+
+
+@zotero_bp.route("/api/zotero/test", methods=["POST"])
+@login_required
+def test_connection():
+ """Validate the configured Zotero credentials."""
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+ try:
+ result = ZoteroSyncService(
+ session["username"], password
+ ).test_connection()
+ return jsonify(result), (200 if result.get("success") else 400)
+ except Exception as e:
+ return handle_api_error("testing Zotero connection", e)
+
+
+@zotero_bp.route("/api/zotero/collections", methods=["GET"])
+@login_required
+def list_collections():
+ """List the user's Zotero collections (key + name)."""
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+ try:
+ collections = ZoteroSyncService(
+ session["username"], password
+ ).list_collections()
+ return jsonify({"success": True, "collections": collections})
+ except Exception as e:
+ return handle_api_error("listing Zotero collections", e)
+
+
+@zotero_bp.route("/api/zotero/groups", methods=["GET"])
+@login_required
+def list_groups():
+ """List the groups the configured API key can access (id + name)."""
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+ try:
+ groups = ZoteroSyncService(session["username"], password).list_groups()
+ return jsonify({"success": True, "groups": groups})
+ except Exception as e:
+ return handle_api_error("listing Zotero groups", e)
+
+
+@zotero_bp.route("/api/zotero/sync", methods=["POST"])
+@login_required
+def sync_now():
+ """Trigger a background sync of the configured collections.
+
+ Runs in a daemon thread (with an app context) using the current
+ session's password, and returns immediately. Progress is observable via
+ the ``/api/zotero/status`` endpoint.
+ """
+ username = session["username"]
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+
+ cfg = ZoteroSyncService(username, password).get_config()
+ if not cfg.is_configured:
+ return jsonify(
+ {
+ "success": False,
+ "error": "Zotero is not enabled/configured. Set your API key "
+ "and library ID in Settings first.",
+ }
+ ), 400
+
+ # Fast feedback if a sync (manual OR scheduled) is already in flight.
+ # The authoritative guard is the per-user lock inside sync_all(), which
+ # serialises both entry points; this is just a best-effort early exit.
+ if ZoteroSyncService.is_user_syncing(username):
+ return jsonify(
+ {
+ "success": True,
+ "message": "A Zotero sync is already running.",
+ "already_running": True,
+ }
+ )
+
+ app = current_app._get_current_object()
+
+ def _run():
+ # thread_cleanup() releases the thread-local DB session + cached
+ # credentials when this daemon thread exits — without it each manual
+ # sync would strand a pooled connection and the plaintext password.
+ with app.app_context(), thread_cleanup():
+ try:
+ result = ZoteroSyncService(username, password).sync_all()
+ logger.info(f"Zotero manual sync finished: {result}")
+ except Exception:
+ logger.exception("Zotero manual sync failed")
+
+ threading.Thread(
+ target=_run, name=f"zotero-sync-{username}", daemon=True
+ ).start()
+ return jsonify({"success": True, "message": "Zotero sync started."})
+
+
+@zotero_bp.route("/api/zotero/status", methods=["GET"])
+@login_required
+def get_status():
+ """Return stored sync state for all configured collections."""
+ password = _db_password() # gitleaks:allow
+ if not password:
+ return _session_expired_response()
+ try:
+ status = ZoteroSyncService(session["username"], password).get_status()
+ return jsonify({"success": True, "collections": status})
+ except Exception as e:
+ return handle_api_error("getting Zotero status", e)
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index 4b21d44d1a..04bac31942 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -1300,6 +1300,20 @@ class LibraryRAGService:
source_id=document_id,
)
+ # _delete_chunks_from_db is DB-only — also drop the document's
+ # vectors from the FAISS index, otherwise they (and their
+ # persisted text) keep surfacing in search until a full
+ # reindex. Best-effort: a FAISS hiccup must not fail the DB
+ # removal that already succeeded.
+ try:
+ self.remove_documents_from_index(
+ [document_id], collection_id
+ )
+ except Exception:
+ logger.warning(
+ "Could not remove document vectors from FAISS index"
+ )
+
# Update DocumentCollection RAG status
doc_collection.indexed = False
doc_collection.chunk_count = 0
@@ -1735,3 +1749,93 @@ class LibraryRAGService:
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
+
+ def remove_documents_from_index(
+ self, document_ids: List[str], collection_id: str
+ ) -> int:
+ """Delete given documents' vectors from a collection's FAISS index.
+
+ FAISS-only: the DB chunk rows are removed separately by the caller.
+ This closes the gap where deleting a document's DB chunks left its
+ vectors (and their persisted text) in the FAISS docstore, so the
+ document kept surfacing in semantic search until a full reindex.
+
+ Matching is by docstore metadata (``document_id`` for library docs,
+ ``source_id`` for uploads). Returns the number of vectors removed.
+ No-ops (returns 0) when the collection has no current FAISS index.
+ """
+ from ...database.models.library import RAGIndex
+ from ...database.session_context import get_user_db_session
+
+ wanted = {d for d in document_ids if d}
+ if not wanted:
+ return 0
+
+ collection_name = f"collection_{collection_id}"
+ # Don't create an index just to delete from it — only act if one
+ # already exists for this collection.
+ with get_user_db_session(self.username, self.db_password) as session:
+ has_index = (
+ session.query(RAGIndex.id)
+ .filter_by(collection_name=collection_name, is_current=True)
+ .first()
+ is not None
+ )
+ if not has_index:
+ return 0
+
+ try:
+ if self.faiss_index is None:
+ self.faiss_index = self.load_or_create_faiss_index(
+ collection_id
+ )
+ docstore = getattr(self.faiss_index, "docstore", None)
+ store = getattr(docstore, "_dict", None)
+ if not store:
+ return 0
+
+ vector_ids = [
+ vid
+ for vid, doc in store.items()
+ if (
+ (getattr(doc, "metadata", None) or {}).get("document_id")
+ in wanted
+ or (getattr(doc, "metadata", None) or {}).get("source_id")
+ in wanted
+ )
+ ]
+ if not vector_ids or not hasattr(self.faiss_index, "delete"):
+ return 0
+
+ index_path = (
+ Path(self.rag_index_record.index_path)
+ if self.rag_index_record
+ else None
+ )
+ # delete + save under the per-index lock (see #4197).
+ if index_path:
+ with _get_faiss_write_lock(self.username, str(index_path)):
+ self.faiss_index.delete(vector_ids)
+ self.faiss_index.save_local(
+ str(index_path.parent),
+ index_name=index_path.stem,
+ )
+ self.integrity_manager.record_file(
+ index_path,
+ related_entity_type="rag_index",
+ related_entity_id=self.rag_index_record.id,
+ )
+ else:
+ self.faiss_index.delete(vector_ids)
+
+ logger.info(
+ f"Removed {len(vector_ids)} vectors for "
+ f"{len(wanted)} document(s) from {collection_name}"
+ )
+ return len(vector_ids)
+ except Exception:
+ logger.warning(
+ "Could not remove document vectors from FAISS index for "
+ f"{collection_name}"
+ )
+ return 0
diff --git a/src/local_deep_research/research_library/zotero/__init__.py b/src/local_deep_research/research_library/zotero/__init__.py
new file mode 100644
index 0000000000..fa85f15045
--- /dev/null
+++ b/src/local_deep_research/research_library/zotero/__init__.py
@@ -0,0 +1,22 @@
+"""Zotero integration for the Research Library.
+
+Imports papers from a Zotero library/collection into the LDR document
+library (where they are stored, text-extracted and RAG-indexed like any
+other library document) and supports incremental background auto-sync.
+"""
+
+from .client import (
+ ZoteroClient,
+ ZoteroError,
+ ZoteroAuthError,
+ ZoteroTransientError,
+)
+from .sync_service import ZoteroSyncService
+
+__all__ = [
+ "ZoteroClient",
+ "ZoteroError",
+ "ZoteroAuthError",
+ "ZoteroTransientError",
+ "ZoteroSyncService",
+]
diff --git a/src/local_deep_research/research_library/zotero/client.py b/src/local_deep_research/research_library/zotero/client.py
new file mode 100644
index 0000000000..9f5f39b5e8
--- /dev/null
+++ b/src/local_deep_research/research_library/zotero/client.py
@@ -0,0 +1,770 @@
+"""
+Thin client for the Zotero Web API (https://www.zotero.org/support/dev/web_api/v3).
+
+Uses the project's :class:`SafeSession` so every request is SSRF-validated
+and response sizes are bounded, rather than pulling in ``pyzotero`` (which
+would bypass those protections). Only the small slice of the API needed for
+import / incremental sync is implemented:
+
+- list collections (for the UI picker)
+- list item *versions* for a collection or the whole library
+- fetch full item data for a batch of keys
+- fetch an item's child attachments
+- download an attachment's file bytes
+
+The sync service uses the ``/items/top?format=versions`` endpoint, which
+returns the FULL ``{itemKey: version}`` map of the current top-level items.
+Reconciling that map against its mapping table lets the sync detect additions,
+metadata changes (version bump) and removals (key gone) — and, unlike a
+``?since=`` delta, removals *from the collection* too. Full item data is then
+fetched only for the keys that actually changed. Pure attachment edits that
+don't bump the parent item's version are not detected by this approach —
+acceptable for v1.
+"""
+
+import re
+import time
+from dataclasses import dataclass, field
+from html import unescape
+from typing import Dict, List, Optional, Tuple
+from urllib.parse import quote
+
+import requests
+from loguru import logger
+
+from ...security import SafeSession
+
+
+def _html_to_text(html: str) -> str:
+ """Minimal HTML→text for Zotero note bodies (which are stored as HTML)."""
+ if not html:
+ return ""
+ # Turn block-ish tags into newlines, drop the rest, unescape entities.
+ text = re.sub(r"(?i)<(br|/p|/div|/li|/h[1-6])\s*>", "\n", html)
+ text = re.sub(r"<[^>]+>", "", text)
+ text = unescape(text)
+ # Collapse runs of blank lines / trailing spaces.
+ lines = [ln.strip() for ln in text.splitlines()]
+ return "\n".join(ln for ln in lines if ln).strip()
+
+
+ZOTERO_API_BASE = "https://api.zotero.org"
+# Zotero 7 desktop's read-only local API (no API key; can serve local files).
+ZOTERO_LOCAL_API_BASE = "http://localhost:23119/api"
+ZOTERO_API_VERSION = "3"
+
+# Zotero caps multi-key item requests at 50 keys.
+_MAX_KEYS_PER_REQUEST = 50
+# Pagination page size for list endpoints.
+_PAGE_LIMIT = 100
+# Hard cap on paginated requests per call. Bounds memory and guards against a
+# server that returns full pages forever (ignoring `start`) — without it the
+# while-True paginators below could loop unbounded. 10k pages * 100 = 1M items.
+_MAX_PAGES = 10_000
+# Cap retries on transient errors / explicit Backoff|Retry-After headers.
+_MAX_RETRIES = 4
+_MAX_BACKOFF_SECONDS = 60
+
+
+class ZoteroError(Exception):
+ """Base error for Zotero API interactions."""
+
+
+class ZoteroAuthError(ZoteroError):
+ """Raised on authentication / authorization failures (HTTP 403)."""
+
+
+class ZoteroTransientError(ZoteroError):
+ """Raised when a request fails for a transient reason (network error, or
+ HTTP 429/5xx) after retries are exhausted.
+
+ Distinct from a plain :class:`ZoteroError` so per-item callers
+ (``download_attachment`` / ``get_attachment_fulltext``) can tell a genuine
+ "this item has no file / no indexed text" (404 → ``None``) apart from a
+ temporary failure. A transient failure must NOT be recorded as "no PDF",
+ otherwise a single rate-limit blip during a bulk sync would permanently
+ downgrade the item to metadata-only until its Zotero version next changes.
+ """
+
+
+@dataclass
+class ZoteroAttachment:
+ """A child attachment of a Zotero item."""
+
+ key: str
+ version: int
+ content_type: Optional[str]
+ link_mode: Optional[str]
+ filename: Optional[str]
+ title: Optional[str]
+
+ @property
+ def is_downloadable_pdf(self) -> bool:
+ """True if this is a stored PDF we can fetch via the API.
+
+ ``linked_file`` attachments point at a file on the user's local disk
+ and are not retrievable through the Web API.
+ """
+ return (self.content_type or "").lower() == "application/pdf" and (
+ self.link_mode or ""
+ ) in ("imported_file", "imported_url")
+
+
+@dataclass
+class ZoteroItem:
+ """A top-level Zotero item plus its (lazily attached) children."""
+
+ key: str
+ version: int
+ item_type: str
+ data: Dict = field(default_factory=dict)
+ attachments: List[ZoteroAttachment] = field(default_factory=list)
+
+ @property
+ def title(self) -> str:
+ return (self.data.get("title") or "").strip()
+
+ def best_pdf_attachment(self) -> Optional[ZoteroAttachment]:
+ """Return the first downloadable PDF attachment, if any."""
+ for att in self.attachments:
+ if att.is_downloadable_pdf:
+ return att
+ return None
+
+
+def _sleep_for_backoff(headers, attempt: int) -> None:
+ """Honor Zotero ``Backoff`` / ``Retry-After`` headers (capped)."""
+ raw = headers.get("Backoff") or headers.get("Retry-After")
+ delay: float
+ if raw:
+ try:
+ delay = float(raw)
+ except (TypeError, ValueError):
+ delay = 2.0 * attempt
+ else:
+ delay = min(2.0 * attempt, _MAX_BACKOFF_SECONDS)
+ delay = min(max(delay, 0.0), _MAX_BACKOFF_SECONDS)
+ if delay > 0:
+ logger.debug(f"Zotero: backing off {delay:.1f}s (attempt {attempt})")
+ time.sleep(delay)
+
+
+class ZoteroClient:
+ """Minimal Zotero Web API client scoped to one library."""
+
+ def __init__(
+ self,
+ api_key: str,
+ library_type: str,
+ library_id: str,
+ timeout: int = 30,
+ local: bool = False,
+ ):
+ """Initialize the client.
+
+ Args:
+ api_key: Zotero API key with read access (not needed when local).
+ library_type: ``"user"`` or ``"group"``.
+ library_id: Numeric user or group id.
+ timeout: Per-request timeout in seconds.
+ local: Talk to the desktop Zotero local API on localhost:23119
+ (no API key; can serve local/linked files) instead of the
+ cloud Web API.
+ """
+ if library_type not in ("user", "group"):
+ raise ValueError(f"Invalid library_type: {library_type!r}")
+ if not api_key and not local:
+ raise ValueError("Zotero API key is required")
+ if not str(library_id).strip():
+ raise ValueError("Zotero library_id is required")
+
+ self.api_key = api_key
+ self.library_type = library_type
+ self.library_id = str(library_id).strip()
+ self.timeout = timeout
+ self.local = local
+ self._base = ZOTERO_LOCAL_API_BASE if local else ZOTERO_API_BASE
+ self._prefix = (
+ f"/{'users' if library_type == 'user' else 'groups'}"
+ f"/{quote(self.library_id, safe='')}"
+ )
+ # The local API is on the loopback interface; allow it explicitly.
+ self.session = SafeSession(allow_localhost=local)
+ headers = {"Zotero-API-Version": ZOTERO_API_VERSION}
+ # The local desktop API needs no key and is reached over plaintext HTTP
+ # on the loopback; never attach the key there (it would put a real
+ # credential on the wire for no benefit).
+ if api_key and not local:
+ headers["Zotero-API-Key"] = self.api_key
+ self.session.headers.update(headers)
+
+ # -- lifecycle ---------------------------------------------------------
+
+ def close(self) -> None:
+ if getattr(self, "session", None) is not None:
+ try:
+ self.session.close()
+ except Exception:
+ logger.debug("Error closing Zotero session", exc_info=True)
+ finally:
+ self.session = None # type: ignore[assignment]
+
+ def __enter__(self) -> "ZoteroClient":
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
+ self.close()
+ return False
+
+ # -- low-level request -------------------------------------------------
+
+ def _request(
+ self,
+ path: str,
+ params: Optional[Dict] = None,
+ *,
+ stream: bool = False,
+ allow_redirects: bool = True,
+ prefixed: bool = True,
+ ):
+ """Perform a GET against the Zotero API with retry/backoff.
+
+ ``path`` is appended to the library prefix (e.g. ``/collections``)
+ unless ``prefixed=False`` (for non-library endpoints like
+ ``/keys/current`` or ``/users/{id}/groups``).
+ Returns the ``requests.Response``. Raises :class:`ZoteroAuthError`
+ on 403 and :class:`ZoteroError` on other non-2xx responses.
+
+ When ``allow_redirects=False``, a 3xx response is returned as-is
+ (not raised) so the caller can follow the redirect itself — used by
+ ``download_attachment`` to avoid forwarding the API key header to the
+ storage host.
+ """
+ prefix = self._prefix if prefixed else ""
+ url = f"{self._base}{prefix}{path}"
+ last_exc: Optional[Exception] = None
+ for attempt in range(1, _MAX_RETRIES + 1):
+ try:
+ response = self.session.get(
+ url,
+ params=params,
+ timeout=self.timeout,
+ stream=stream,
+ allow_redirects=allow_redirects,
+ )
+ except (
+ requests.exceptions.Timeout,
+ requests.exceptions.ConnectionError,
+ ) as exc:
+ # Transient network errors — worth retrying.
+ last_exc = exc
+ logger.warning(
+ f"Zotero request error (attempt {attempt}): "
+ f"{type(exc).__name__}"
+ )
+ if attempt == _MAX_RETRIES:
+ raise ZoteroTransientError(
+ f"Zotero request failed: {type(exc).__name__}"
+ ) from exc
+ time.sleep(min(2.0 * attempt, _MAX_BACKOFF_SECONDS))
+ continue
+ except Exception as exc:
+ # Non-transient (e.g. SafeSession SSRF/oversize ValueError, or
+ # a malformed-URL error) — do NOT retry; fail fast.
+ raise ZoteroError(
+ f"Zotero request failed: {type(exc).__name__}"
+ ) from exc
+
+ status = response.status_code
+ if status == 403:
+ raise ZoteroAuthError(
+ "Zotero rejected the API key (HTTP 403). Check the key "
+ "and that it has read access to this library."
+ )
+ if status == 404:
+ raise ZoteroError(
+ "Zotero resource not found (HTTP 404). Check the library "
+ "id / collection key."
+ )
+ if status in (429, 500, 502, 503, 504):
+ logger.warning(
+ f"Zotero transient HTTP {status} (attempt {attempt})"
+ )
+ if attempt == _MAX_RETRIES:
+ raise ZoteroTransientError(
+ f"Zotero request failed after {attempt} attempts "
+ f"(HTTP {status})"
+ )
+ _sleep_for_backoff(response.headers, attempt)
+ continue
+ # When the caller manages redirects itself, hand back the 3xx.
+ if not allow_redirects and 300 <= status < 400:
+ return response
+ if not (200 <= status < 300):
+ raise ZoteroError(f"Zotero request failed (HTTP {status})")
+
+ # Honor a Backoff header even on success (server under load).
+ if response.headers.get("Backoff"):
+ _sleep_for_backoff(response.headers, attempt)
+ return response
+
+ # Unreachable, but keeps type-checkers happy.
+ raise ZoteroError(
+ f"Zotero request failed: {type(last_exc).__name__ if last_exc else 'unknown'}"
+ )
+
+ @staticmethod
+ def _library_version(response) -> int:
+ try:
+ return int(response.headers.get("Last-Modified-Version", "0"))
+ except (TypeError, ValueError):
+ return 0
+
+ # -- public API --------------------------------------------------------
+
+ def test_connection(self) -> int:
+ """Validate credentials by reading the library version.
+
+ Returns the current library version. Raises on failure.
+ """
+ response = self._request(
+ "/items/top", params={"format": "versions", "limit": 1}
+ )
+ return self._library_version(response)
+
+ def get_collections(self) -> List[Dict]:
+ """List all collections in the library (paginated).
+
+ Returns a list of ``{"key", "name", "parentCollection"}`` dicts.
+ """
+ collections: List[Dict] = []
+ start = 0
+ pages = 0
+ while True:
+ pages += 1
+ if pages > _MAX_PAGES:
+ raise ZoteroError(
+ f"Zotero: pagination exceeded safety cap ({_MAX_PAGES} "
+ "pages) — aborting to avoid a runaway loop"
+ )
+ response = self._request(
+ "/collections",
+ params={
+ "format": "json",
+ "limit": _PAGE_LIMIT,
+ "start": start,
+ },
+ )
+ page = response.json()
+ if not page:
+ break
+ for entry in page:
+ data = entry.get("data", {})
+ collections.append(
+ {
+ "key": entry.get("key"),
+ "name": data.get("name", ""),
+ "parentCollection": data.get("parentCollection", False),
+ }
+ )
+ if len(page) < _PAGE_LIMIT:
+ break
+ start += _PAGE_LIMIT
+ return collections
+
+ def get_groups(self) -> List[Dict]:
+ """List the groups this API key can access (id + name + type).
+
+ Resolves the key's owner via ``/keys/current`` then reads
+ ``/users/{userID}/groups`` — both non-library-scoped endpoints. Lets
+ the UI offer a group picker instead of making the user hunt for a
+ numeric group id on zotero.org.
+ """
+ if self.local:
+ # The local API has no key endpoint / auth; group discovery isn't
+ # applicable.
+ return []
+ info = self._request("/keys/current", prefixed=False).json()
+ user_id = info.get("userID") if isinstance(info, dict) else None
+ if not user_id:
+ return []
+
+ groups: List[Dict] = []
+ start = 0
+ pages = 0
+ while True:
+ pages += 1
+ if pages > _MAX_PAGES:
+ raise ZoteroError(
+ f"Zotero: pagination exceeded safety cap ({_MAX_PAGES} "
+ "pages) — aborting to avoid a runaway loop"
+ )
+ response = self._request(
+ f"/users/{quote(str(user_id), safe='')}/groups",
+ params={
+ "format": "json",
+ "limit": _PAGE_LIMIT,
+ "start": start,
+ },
+ prefixed=False,
+ )
+ page = response.json()
+ if not page:
+ break
+ for entry in page:
+ data = entry.get("data", {})
+ groups.append(
+ {
+ "id": str(entry.get("id") or data.get("id") or ""),
+ "name": data.get("name", ""),
+ "type": data.get("type", ""),
+ }
+ )
+ if len(page) < _PAGE_LIMIT:
+ break
+ start += _PAGE_LIMIT
+ return groups
+
+ def get_collection_name(self, collection_key: str) -> Optional[str]:
+ """Return a single collection's display name, or None if missing."""
+ try:
+ response = self._request(
+ f"/collections/{quote(collection_key, safe='')}",
+ params={"format": "json"},
+ )
+ except ZoteroError:
+ return None
+ data = response.json().get("data", {})
+ return data.get("name")
+
+ def get_top_item_versions(
+ self,
+ collection_key: Optional[str] = None, # gitleaks:allow
+ ) -> Tuple[Dict[str, int], int]:
+ """Get ``{itemKey: version}`` for current top-level items.
+
+ Scoped to ``collection_key`` when given, else the whole library.
+ Also returns the library version (from ``Last-Modified-Version``).
+
+ This is the FULL current set (not a ``?since=`` delta) on purpose: the
+ sync service reconciles it against its mapping table to detect both
+ deletions AND items removed from the collection (which a library-level
+ ``/deleted`` feed would miss). To make that reconciliation safe, this
+ method raises if the paginated result is INCOMPLETE relative to the
+ ``Total-Results`` header — otherwise a truncated response would look
+ like a batch of deletions to the caller.
+ """
+ if collection_key:
+ path = f"/collections/{quote(collection_key, safe='')}/items/top"
+ else:
+ path = "/items/top"
+
+ versions: Dict[str, int] = {}
+ library_version = 0
+ start = 0
+ pages = 0
+ expected_total: Optional[int] = None
+ while True:
+ pages += 1
+ if pages > _MAX_PAGES:
+ raise ZoteroError(
+ f"Zotero: pagination exceeded safety cap ({_MAX_PAGES} "
+ "pages) — aborting to avoid a runaway loop"
+ )
+ response = self._request(
+ path,
+ params={
+ "format": "versions",
+ "limit": _PAGE_LIMIT,
+ "start": start,
+ },
+ )
+ library_version = max(
+ library_version, self._library_version(response)
+ )
+ # Total-Results is the authoritative item count; capture it once.
+ if expected_total is None:
+ total = response.headers.get("Total-Results")
+ try:
+ expected_total = int(total) if total is not None else None
+ except (TypeError, ValueError):
+ expected_total = None
+ page = response.json() or {}
+ # ``format=versions`` returns a JSON object {key: version}.
+ for key, version in page.items():
+ try:
+ versions[key] = int(version)
+ except (TypeError, ValueError):
+ versions[key] = 0
+ # A short page is the authoritative end-of-data signal for both
+ # list and object (``format=versions``) responses.
+ if len(page) < _PAGE_LIMIT:
+ break
+ # When Total-Results is known, stop one round-trip early. Do NOT
+ # fall back to len(versions) when the header is absent — that makes
+ # the check a tautology and would stop after a single full page.
+ if expected_total is not None and len(versions) >= expected_total:
+ break
+ start += _PAGE_LIMIT
+
+ # Completeness guard: if the server told us how many items exist and we
+ # ended up with fewer (a truncated / short-circuited page), refuse to
+ # return a partial set — the caller treats "absent" keys as deletions,
+ # so a partial map would silently delete real documents.
+ if expected_total is not None and len(versions) < expected_total:
+ raise ZoteroError(
+ "Zotero returned an incomplete version map "
+ f"({len(versions)}/{expected_total} items); aborting so "
+ "missing items are not mistaken for deletions"
+ )
+ return versions, library_version
+
+ def get_items(self, item_keys: List[str]) -> List[ZoteroItem]:
+ """Fetch full data for the given top-level item keys (batched)."""
+ items: List[ZoteroItem] = []
+ for batch_start in range(0, len(item_keys), _MAX_KEYS_PER_REQUEST):
+ batch = item_keys[batch_start : batch_start + _MAX_KEYS_PER_REQUEST]
+ if not batch:
+ continue
+ response = self._request(
+ "/items",
+ params={
+ "format": "json",
+ "itemKey": ",".join(batch),
+ "limit": _MAX_KEYS_PER_REQUEST,
+ },
+ )
+ for entry in response.json() or []:
+ data = entry.get("data", {})
+ items.append(
+ ZoteroItem(
+ key=entry.get("key"),
+ version=int(entry.get("version", 0) or 0),
+ item_type=data.get("itemType", ""),
+ data=data,
+ )
+ )
+ return items
+
+ def _get_children_raw(self, item_key: str) -> List[Dict]:
+ """Fetch all raw child entries of an item/attachment (paginated)."""
+ entries: List[Dict] = []
+ start = 0
+ pages = 0
+ while True:
+ pages += 1
+ if pages > _MAX_PAGES:
+ raise ZoteroError(
+ f"Zotero: pagination exceeded safety cap ({_MAX_PAGES} "
+ "pages) — aborting to avoid a runaway loop"
+ )
+ response = self._request(
+ f"/items/{quote(item_key, safe='')}/children",
+ params={
+ "format": "json",
+ "limit": _PAGE_LIMIT,
+ "start": start,
+ },
+ )
+ page = response.json() or []
+ entries.extend(page)
+ if len(page) < _PAGE_LIMIT:
+ break
+ start += _PAGE_LIMIT
+ return entries
+
+ def get_children(self, item_key: str) -> List[ZoteroAttachment]:
+ """Fetch an item's child attachments."""
+ attachments: List[ZoteroAttachment] = []
+ for entry in self._get_children_raw(item_key):
+ data = entry.get("data", {})
+ if data.get("itemType") != "attachment":
+ continue
+ attachments.append(
+ ZoteroAttachment(
+ key=entry.get("key"),
+ version=int(entry.get("version", 0) or 0),
+ content_type=data.get("contentType"),
+ link_mode=data.get("linkMode"),
+ filename=data.get("filename"),
+ title=data.get("title"),
+ )
+ )
+ return attachments
+
+ def get_notes(self, item_key: str) -> List[str]:
+ """Return the plain text of an item's child notes (HTML stripped)."""
+ notes: List[str] = []
+ for entry in self._get_children_raw(item_key):
+ data = entry.get("data", {})
+ if data.get("itemType") != "note":
+ continue
+ text = _html_to_text(data.get("note") or "")
+ if text:
+ notes.append(text)
+ return notes
+
+ def get_annotations(self, attachment_key: str) -> List[str]:
+ """Return an attachment's annotations as text (highlight + comment).
+
+ Image/area annotations carry no text (only position), so they're
+ skipped.
+ """
+ out: List[str] = []
+ for entry in self._get_children_raw(attachment_key):
+ data = entry.get("data", {})
+ if data.get("itemType") != "annotation":
+ continue
+ parts = []
+ highlighted = (data.get("annotationText") or "").strip()
+ comment = (data.get("annotationComment") or "").strip()
+ if highlighted:
+ parts.append(highlighted)
+ if comment:
+ parts.append(f"[note] {comment}")
+ if parts:
+ out.append(" — ".join(parts))
+ return out
+
+ def download_attachment(self, attachment_key: str) -> Optional[bytes]:
+ """Download an attachment's file bytes, or None on failure.
+
+ Zotero's ``/items/{key}/file`` endpoint typically answers with a 302
+ to the actual storage location (Zotero's S3, or a WebDAV/external host
+ for self-hosted storage). We must NOT follow that redirect with the
+ authenticated session: ``requests`` only strips the standard
+ ``Authorization`` header on a cross-host redirect, so our custom
+ ``Zotero-API-Key`` header would otherwise be forwarded verbatim to the
+ storage host — a credential leak. Instead we fetch with
+ ``allow_redirects=False`` and follow the ``Location`` ourselves using a
+ fresh, credential-free :class:`SafeSession` (which still SSRF-validates
+ the target).
+ """
+ try:
+ response = self._request(
+ f"/items/{quote(attachment_key, safe='')}/file",
+ allow_redirects=False,
+ )
+ except ZoteroTransientError:
+ # Temporary (429/5xx/network): let the caller skip this item and
+ # retry next sync rather than silently import it metadata-only.
+ raise
+ except ZoteroError:
+ logger.warning(
+ f"Zotero: could not download attachment {attachment_key}"
+ )
+ return None
+
+ if 300 <= response.status_code < 400:
+ location = (response.headers.get("Location") or "").strip()
+ if not location:
+ logger.warning(
+ f"Zotero: attachment {attachment_key} redirect had no "
+ "Location header"
+ )
+ return None
+ if location.lower().startswith("file:"):
+ # The local API redirects to a file:// path on disk. Only honor
+ # it in local mode (never follow a file:// redirect from the
+ # cloud API).
+ if not self.local:
+ logger.warning(
+ "Zotero: ignoring file:// redirect from the cloud API"
+ )
+ return None
+ return self._read_local_file(location)
+ return self._fetch_file_unauthenticated(location)
+
+ # Some configurations serve the file directly (200, no redirect).
+ content = response.content
+ return content or None
+
+ @staticmethod
+ def _read_local_file(file_url: str) -> Optional[bytes]:
+ """Read bytes from a ``file://`` URL (local API attachment on disk).
+
+ Only PDF content is honored: the redirect target comes from whatever
+ answers on the local API port, so restricting reads to files with a
+ PDF magic number keeps this from acting as a generic local-file
+ disclosure primitive (defense in depth — the sync layer discards
+ non-PDF bodies anyway).
+ """
+ from urllib.parse import urlparse
+ from urllib.request import url2pathname
+
+ try:
+ path = url2pathname(urlparse(file_url).path)
+ with open(path, "rb") as fh:
+ data = fh.read()
+ except OSError:
+ logger.warning("Zotero: could not read local attachment file")
+ return None
+ if not data:
+ return None
+ if b"%PDF" not in data[:1024]:
+ logger.warning("Zotero: local attachment is not a PDF; ignoring it")
+ return None
+ return data
+
+ def _fetch_file_unauthenticated(self, url: str) -> Optional[bytes]:
+ """Fetch a storage URL with a fresh session that carries no Zotero
+ credentials. SafeSession SSRF-validates the URL (and any further
+ redirects).
+
+ Raises :class:`ZoteroTransientError` on a transient failure (network
+ error or HTTP 429/5xx from the storage host) so the caller retries next
+ sync rather than importing the item metadata-only; returns None only
+ for a genuine "no file here" (other non-2xx / empty body).
+ """
+ try:
+ with SafeSession() as session:
+ response = session.get(url, timeout=self.timeout)
+ except (
+ requests.exceptions.Timeout,
+ requests.exceptions.ConnectionError,
+ ) as exc:
+ raise ZoteroTransientError(
+ f"Zotero storage fetch failed: {type(exc).__name__}"
+ ) from exc
+ except Exception as exc:
+ logger.warning(
+ f"Zotero: storage download failed ({type(exc).__name__})"
+ )
+ return None
+ if response.status_code in (429, 500, 502, 503, 504):
+ raise ZoteroTransientError(
+ f"Zotero storage returned HTTP {response.status_code}"
+ )
+ if not (200 <= response.status_code < 300):
+ logger.warning(
+ f"Zotero: storage download returned HTTP {response.status_code}"
+ )
+ return None
+ content = response.content
+ return content or None
+
+ def get_attachment_fulltext(self, attachment_key: str) -> Optional[str]:
+ """Return Zotero's already-extracted full text for an attachment.
+
+ Uses ``GET /items/{key}/fulltext``; returns None when Zotero has no
+ indexed text for it (HTTP 404) or the content is empty. Lets the sync
+ skip downloading + re-parsing the PDF in text-only mode.
+ """
+ try:
+ response = self._request(
+ f"/items/{quote(attachment_key, safe='')}/fulltext"
+ )
+ except ZoteroTransientError:
+ # Temporary failure — don't conflate with "no indexed text"; let
+ # the caller retry next sync.
+ raise
+ except ZoteroError:
+ return None
+ try:
+ data = response.json()
+ except Exception:
+ return None
+ if not isinstance(data, dict):
+ return None
+ content = data.get("content")
+ return content or None
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
new file mode 100644
index 0000000000..c2f2d1feb4
--- /dev/null
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -0,0 +1,1499 @@
+"""
+Zotero sync service.
+
+Imports items from a Zotero library/collection into the LDR document library
+and keeps them in sync. Items become :class:`Document` rows (with extracted
+text, optional encrypted PDF blob, and RAG auto-indexing) inside a dedicated
+:class:`Collection`, exactly like uploads/research downloads — so they are
+searchable during research with no extra plumbing.
+
+Sync algorithm (per collection), using cheap version maps:
+
+1. Ask Zotero for ``{itemKey: version}`` of current top-level items.
+2. Map keys not present anymore -> remove the local document.
+3. Map keys that are new, version-bumped, or whose local document went
+ missing -> (re)fetch full data, download the best PDF (or import
+ metadata-only), and upsert the document + mapping row.
+4. Persist the library version as the new high-water mark.
+
+Known limitations (v1):
+
+- With MULTIPLE synced collections, an item moved from collection A to B is
+ removed by A's sync before B has imported it: the document is deleted and
+ re-created under a new id once B next syncs successfully (briefly absent
+ from the library if B's sync fails first). Whole-library (single-target)
+ configs are unaffected.
+- Toggling ``import_items_without_pdf`` (or the tag filter) is not
+ retroactive: items skipped under the old setting are reconsidered only
+ when they next change in Zotero.
+"""
+
+import hashlib
+import os
+import re
+import threading
+import uuid
+from dataclasses import dataclass, field
+from datetime import date, datetime, UTC
+from pathlib import Path
+from typing import Dict, List, Optional, Tuple
+
+from loguru import logger
+
+from ...constants import FILE_PATH_TEXT_ONLY
+from ...config.paths import get_library_directory
+from ...database.library_init import get_source_type_id
+from ...database.models.library import (
+ Collection,
+ Document,
+ DocumentBlob,
+ DocumentCollection,
+ DocumentStatus,
+)
+from ...database.models.zotero import ZoteroItemMap, ZoteroSyncState
+from ...database.session_context import get_user_db_session, safe_rollback
+from ...security import (
+ sanitize_error_for_client,
+ sanitize_filename,
+ UnsafeFilenameError,
+)
+from ...settings.manager import SettingsManager
+from ..deletion.utils.cascade_helper import CascadeHelper
+from ..services.pdf_storage_manager import (
+ DEFAULT_MAX_PDF_SIZE_MB,
+ PDFStorageManager,
+)
+from ..utils import ensure_in_collection
+from .client import (
+ ZoteroClient,
+ ZoteroError,
+ ZoteroItem,
+ ZoteroTransientError,
+)
+
+
+@dataclass
+class ZoteroConfig:
+ """Snapshot of the user's Zotero settings."""
+
+ enabled: bool = False
+ api_key: str = ""
+ library_type: str = "user"
+ library_id: str = ""
+ collection_keys: List[str] = field(default_factory=list)
+ import_tags: List[str] = field(default_factory=list)
+ import_items_without_pdf: bool = True
+ import_annotations: bool = False
+ pdf_storage_mode: str = "database"
+ auto_sync_enabled: bool = False
+ sync_interval_minutes: int = 360
+ use_local_api: bool = False
+
+ @property
+ def is_configured(self) -> bool:
+ # Local API mode needs no API key (it talks to the running desktop
+ # Zotero on localhost); the web API needs one.
+ has_auth = self.use_local_api or bool(self.api_key)
+ return bool(self.enabled and has_auth and self.library_id)
+
+ @property
+ def targets(self) -> List[str]:
+ """Collection keys to sync; ``[""]`` means the whole library."""
+ return self.collection_keys or [""]
+
+
+# Per-user sync locks. A single non-blocking lock per username serialises ALL
+# sync entry points (the manual "Sync now" daemon thread AND the scheduled
+# auto-sync job), so two concurrent runs can't write the same per-user
+# SQLCipher DB and race on the ZoteroItemMap unique constraint.
+_user_sync_locks: dict[str, threading.Lock] = {}
+_user_sync_locks_guard = threading.Lock()
+
+
+def _get_user_sync_lock(username: str) -> threading.Lock:
+ with _user_sync_locks_guard:
+ lock = _user_sync_locks.get(username)
+ if lock is None:
+ lock = threading.Lock()
+ _user_sync_locks[username] = lock
+ return lock
+
+
+class ZoteroSyncService:
+ """Service that imports / syncs Zotero items into the library."""
+
+ def __init__(
+ self,
+ username: str,
+ password: Optional[str] = None, # gitleaks:allow
+ ):
+ self.username = username
+ self.password = password # gitleaks:allow
+
+ # -- settings ----------------------------------------------------------
+
+ def get_config(self) -> ZoteroConfig:
+ """Read the user's Zotero settings from their encrypted database."""
+ with get_user_db_session(self.username, self.password) as session:
+ sm = SettingsManager(session)
+ raw_keys = sm.get_setting("zotero.collection_keys", "") or ""
+ collection_keys = [
+ k.strip() for k in str(raw_keys).split(",") if k.strip()
+ ]
+ raw_tags = sm.get_setting("zotero.import_tags", "") or ""
+ import_tags = [
+ t.strip() for t in str(raw_tags).split(",") if t.strip()
+ ]
+ try:
+ interval = int(
+ sm.get_setting("zotero.sync_interval_minutes", 360) or 360
+ )
+ except (TypeError, ValueError):
+ interval = 360
+ return ZoteroConfig(
+ enabled=sm.get_bool_setting("zotero.enabled", False),
+ api_key=str(sm.get_setting("zotero.api_key", "") or "").strip(),
+ library_type=str(
+ sm.get_setting("zotero.library_type", "user") or "user"
+ ).strip(),
+ library_id=str(
+ sm.get_setting("zotero.library_id", "") or ""
+ ).strip(),
+ collection_keys=collection_keys,
+ import_tags=import_tags,
+ import_items_without_pdf=sm.get_bool_setting(
+ "zotero.import_items_without_pdf", True
+ ),
+ import_annotations=sm.get_bool_setting(
+ "zotero.import_annotations", False
+ ),
+ pdf_storage_mode=str(
+ sm.get_setting("zotero.pdf_storage_mode", "database")
+ or "database"
+ ).strip(),
+ auto_sync_enabled=sm.get_bool_setting(
+ "zotero.auto_sync_enabled", False
+ ),
+ sync_interval_minutes=interval,
+ use_local_api=sm.get_bool_setting(
+ "zotero.use_local_api", False
+ ),
+ )
+
+ def _make_client(self, cfg: ZoteroConfig) -> ZoteroClient:
+ return ZoteroClient(
+ api_key=cfg.api_key,
+ library_type=cfg.library_type,
+ library_id=cfg.library_id,
+ local=cfg.use_local_api,
+ )
+
+ def _library_root(self) -> str:
+ with get_user_db_session(self.username, self.password) as session:
+ sm = SettingsManager(session)
+ storage_path = sm.get_setting(
+ "research_library.storage_path", str(get_library_directory())
+ )
+ return str(
+ Path(os.path.expandvars(storage_path)).expanduser().resolve()
+ )
+
+ # -- public operations -------------------------------------------------
+
+ def test_connection(self) -> Dict:
+ """Validate credentials. Returns ``{success, library_version, ...}``."""
+ cfg = self.get_config()
+ if not cfg.library_id or (not cfg.use_local_api and not cfg.api_key):
+ return {
+ "success": False,
+ "error": "Zotero library ID (and an API key, unless using the "
+ "local API) are required.",
+ }
+ try:
+ with self._make_client(cfg) as client:
+ version = client.test_connection()
+ collections = client.get_collections()
+ return {
+ "success": True,
+ "library_version": version,
+ "collection_count": len(collections),
+ }
+ except ZoteroError as exc:
+ return {
+ "success": False,
+ "error": sanitize_error_for_client(str(exc)),
+ }
+
+ def list_collections(self) -> List[Dict]:
+ """List Zotero collections (for the UI picker)."""
+ cfg = self.get_config()
+ with self._make_client(cfg) as client:
+ return client.get_collections()
+
+ def list_groups(self) -> List[Dict]:
+ """List the groups the configured API key can access (UI picker)."""
+ cfg = self.get_config()
+ with self._make_client(cfg) as client:
+ return client.get_groups()
+
+ @classmethod
+ def is_user_syncing(cls, username: str) -> bool:
+ """True if a sync is currently in progress for this user."""
+ lock = _user_sync_locks.get(username)
+ return bool(lock and lock.locked())
+
+ def sync_all(self) -> Dict:
+ """Sync every configured collection (or the whole library).
+
+ Serialised per user: if a sync (manual or scheduled) is already
+ running for this user, returns immediately rather than starting a
+ second concurrent writer against the same encrypted DB.
+ """
+ cfg = self.get_config()
+ if not cfg.is_configured:
+ return {
+ "success": False,
+ "error": "Zotero is not enabled/configured.",
+ }
+
+ lock = _get_user_sync_lock(self.username)
+ if not lock.acquire(blocking=False):
+ logger.info(
+ f"Zotero: a sync is already running for {self.username}; "
+ "skipping this run"
+ )
+ return {
+ "success": True,
+ "already_running": True,
+ "imported": 0,
+ "updated": 0,
+ "removed": 0,
+ "skipped": 0,
+ "errors": 0,
+ "collections": [],
+ }
+
+ totals = {
+ "imported": 0,
+ "updated": 0,
+ "removed": 0,
+ "skipped": 0,
+ "errors": 0,
+ "collections": [],
+ }
+ try:
+ with self._make_client(cfg) as client:
+ for collection_key in cfg.targets:
+ stats = self._sync_one(client, cfg, collection_key)
+ totals["imported"] += stats.get("imported", 0)
+ totals["updated"] += stats.get("updated", 0)
+ totals["removed"] += stats.get("removed", 0)
+ totals["skipped"] += stats.get("skipped", 0)
+ totals["errors"] += stats.get("errors", 0)
+ totals["collections"].append(stats)
+ finally:
+ lock.release()
+ totals["success"] = all(
+ c.get("status") != "failed" for c in totals["collections"]
+ )
+ return totals
+
+ def get_status(self) -> List[Dict]:
+ """Return the stored sync state for all configured collections."""
+ with get_user_db_session(self.username, self.password) as session:
+ rows = session.query(ZoteroSyncState).all()
+ return [
+ {
+ "library_type": r.library_type,
+ "library_id": r.library_id,
+ "collection_key": r.collection_key or None,
+ "ldr_collection_id": r.ldr_collection_id,
+ "last_version": r.last_version,
+ "last_status": r.last_status,
+ "last_error": r.last_error,
+ "item_count": r.item_count,
+ "last_synced_at": r.last_synced_at.isoformat()
+ if r.last_synced_at
+ else None,
+ }
+ for r in rows
+ ]
+
+ # -- per-collection sync ----------------------------------------------
+
+ def _sync_one(
+ self, client: ZoteroClient, cfg: ZoteroConfig, collection_key: str
+ ) -> Dict:
+ """Sync a single collection (``""`` = whole library)."""
+ stats = {
+ "collection_key": collection_key or None,
+ "imported": 0,
+ "updated": 0,
+ "removed": 0,
+ # Deliberate skips (tag filter, no-PDF import disabled).
+ "skipped": 0,
+ # Contained per-item failures (rolled back, retried next sync).
+ # Kept separate from "skipped" so they can be SURFACED: a sync
+ # that completes with errors must not look identical to a clean
+ # one.
+ "errors": 0,
+ "status": "completed",
+ }
+ new_or_updated_doc_ids: List[str] = []
+ # Docs whose content changed in place: their stale FAISS vectors must be
+ # purged before the re-index rebuilds them (see _ingest_item).
+ reindexed_doc_ids: List[str] = []
+ # Prior documents orphaned when an in-place edit dedups onto a different
+ # existing doc: their stale vectors are purged like a removal.
+ released_doc_ids: List[str] = []
+ # Each id is appended only AFTER its own removal committed, so the
+ # finally-block vector purge never touches a rolled-back removal.
+ removed_doc_ids: List[str] = []
+ ldr_collection_id: Optional[str] = None
+ try:
+ with get_user_db_session(self.username, self.password) as session:
+ ldr_collection_id = self._ensure_ldr_collection(
+ session, client, cfg, collection_key
+ )
+ state = self._get_or_create_state(
+ session, cfg, collection_key, ldr_collection_id
+ )
+ state.last_status = "syncing"
+ session.commit()
+
+ remote_versions, library_version = client.get_top_item_versions(
+ collection_key or None
+ )
+ rows = (
+ session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=ldr_collection_id)
+ .all()
+ )
+ mapped = {r.zotero_item_key: r for r in rows}
+ remote_keys = set(remote_versions)
+
+ source_type_id = get_source_type_id(
+ self.username, "zotero", self.password
+ )
+
+ # 1) Removals — but NEVER read an empty remote set as "delete
+ # everything". A truncated/transient empty response would
+ # otherwise wipe the whole collection (docs + blobs + chunks).
+ if remote_keys or not mapped:
+ for key in set(mapped) - remote_keys:
+ # Per-item transaction: one document whose cascade
+ # fails must not abort the whole batch (or the sync).
+ # Its removal rolls back cleanly — the map row
+ # survives, so it is re-detected and retried next
+ # sync — while every other removal proceeds.
+ try:
+ rid = self._remove_item(
+ session, mapped[key], source_type_id
+ )
+ session.commit()
+ except Exception:
+ safe_rollback(session, "zotero removal")
+ logger.exception(
+ f"Zotero: failed to remove item {key}"
+ )
+ stats["errors"] += 1
+ continue
+ if rid:
+ removed_doc_ids.append(rid)
+ stats["removed"] += 1
+ else:
+ logger.warning(
+ f"Zotero: empty item set for "
+ f"{collection_key or 'ALL'} while {len(mapped)} items "
+ "are mapped — skipping removals to avoid mass-deletion"
+ )
+
+ # 2) Additions / changes. Reprocess a key when it is new, its
+ # version changed, or its previously-imported document went
+ # missing. We intentionally do NOT reprocess solely because
+ # document_id is None: that is the case for deliberately
+ # skipped (no-PDF, import-disabled) items, which would
+ # otherwise be re-fetched on every sync forever.
+ to_process = [
+ key
+ for key, version in remote_versions.items()
+ if key not in mapped
+ or mapped[key].zotero_version != version
+ or (
+ mapped[key].document_id is not None
+ and not self._document_exists(
+ session, mapped[key].document_id
+ )
+ )
+ ]
+
+ pdf_storage = PDFStorageManager(
+ library_root=self._library_root(),
+ storage_mode=cfg.pdf_storage_mode,
+ max_pdf_size_mb=DEFAULT_MAX_PDF_SIZE_MB,
+ )
+
+ returned_keys: set = set()
+ for item in client.get_items(to_process):
+ returned_keys.add(item.key)
+ if item.data.get("parentItem") or item.item_type in (
+ "attachment",
+ "note",
+ ):
+ # A child/note that slipped into /top: record its
+ # version so it isn't re-fetched every sync.
+ self._touch_map_version(
+ session,
+ ldr_collection_id,
+ item.key,
+ item.version,
+ )
+ continue
+ if cfg.import_tags and not self._item_has_tags(
+ item, cfg.import_tags
+ ):
+ # Doesn't match the tag filter — record the version so
+ # it isn't re-fetched every sync. Additive filter: we
+ # do NOT remove items imported before the filter was
+ # set (removals come only from the version-map diff).
+ self._touch_map_version(
+ session,
+ ldr_collection_id,
+ item.key,
+ item.version,
+ )
+ stats["skipped"] += 1
+ continue
+ # The document this item currently maps to (if any) before
+ # ingest may repoint it onto a DIFFERENT existing doc via
+ # content-hash dedup.
+ prior_row = mapped.get(item.key)
+ prior_doc_id = prior_row.document_id if prior_row else None
+ try:
+ doc_id, action, reindexed = self._ingest_item(
+ session,
+ client,
+ cfg,
+ item,
+ ldr_collection_id,
+ source_type_id,
+ pdf_storage,
+ )
+ except ZoteroTransientError:
+ # A rate-limit / 5xx (from a PDF/full-text fetch inside
+ # _ingest_item) will hit every remaining item too. Abort
+ # the batch and let the outer handler mark the sync
+ # failed so it retries next run, rather than hammering
+ # items 2..N against the limit and burning the budget.
+ safe_rollback(session, "zotero ingest")
+ raise
+ except Exception:
+ safe_rollback(session, "zotero ingest")
+ logger.exception(
+ f"Zotero: failed to ingest item {item.key}"
+ )
+ # Don't record a version — let it retry next sync.
+ stats["errors"] += 1
+ continue
+
+ # Map upsert + (on a dedup remap) release of the orphaned
+ # prior doc, in ONE transaction: committing the repoint on
+ # its own first would strand the prior doc forever if the
+ # release then failed — the item's new version would
+ # already be recorded, so no later sync would retry it.
+ # Per-item isolation: a failure rolls this item back
+ # cleanly (ingest included; retried next sync since its
+ # version was not recorded) without aborting the batch.
+ try:
+ self._upsert_map(
+ session, ldr_collection_id, item, doc_id
+ )
+ released = None
+ if (
+ prior_row
+ and prior_doc_id
+ and prior_doc_id != doc_id
+ ):
+ released = self._release_document(
+ session,
+ prior_doc_id,
+ ldr_collection_id,
+ prior_row.id,
+ source_type_id,
+ )
+ session.commit()
+ except Exception:
+ safe_rollback(session, "zotero map update")
+ logger.exception(
+ f"Zotero: failed to record mapping for item "
+ f"{item.key}"
+ )
+ stats["errors"] += 1
+ continue
+ if released:
+ released_doc_ids.append(released)
+
+ if action == "imported":
+ stats["imported"] += 1
+ new_or_updated_doc_ids.append(doc_id)
+ elif action == "updated":
+ stats["updated"] += 1
+ new_or_updated_doc_ids.append(doc_id)
+ if reindexed:
+ reindexed_doc_ids.append(doc_id)
+ else:
+ stats["skipped"] += 1
+
+ # Keys we asked for but Zotero didn't return (trashed,
+ # permission-changed, etc.): record their version so they
+ # aren't re-requested on every subsequent sync.
+ for key in set(to_process) - returned_keys:
+ self._touch_map_version(
+ session,
+ ldr_collection_id,
+ key,
+ remote_versions.get(key, 0),
+ )
+ session.commit()
+
+ # 3) Persist high-water mark. Contained per-item failures
+ # must stay visible: a run that skipped items because their
+ # removal/ingest kept failing would otherwise look identical
+ # to a clean one (green badge, last_error wiped) while the
+ # same items silently fail on every sync.
+ state.last_version = library_version
+ state.last_status = "completed"
+ state.last_error = (
+ f"{stats['errors']} item(s) failed and will be retried "
+ "next sync (see server log)"
+ if stats["errors"]
+ else None
+ )
+ state.last_synced_at = datetime.now(UTC)
+ state.item_count = (
+ session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=ldr_collection_id)
+ .filter(ZoteroItemMap.document_id.isnot(None))
+ .count()
+ )
+ session.commit()
+ except ZoteroError as exc:
+ stats["status"] = "failed"
+ stats["error"] = sanitize_error_for_client(str(exc))
+ self._mark_failed(cfg, collection_key, stats["error"])
+ return stats
+ except Exception as exc:
+ stats["status"] = "failed"
+ stats["error"] = sanitize_error_for_client(str(exc))
+ logger.exception(
+ f"Zotero: sync failed for collection {collection_key or 'ALL'}"
+ )
+ self._mark_failed(cfg, collection_key, stats["error"])
+ return stats
+ finally:
+ # Purge stale FAISS vectors for DURABLY-COMMITTED removals and
+ # in-place content updates — even when the sync later fails partway
+ # through the additions phase. Those docs' DB chunks are already
+ # gone, so skipping this on the failure path would strand ORPHANED
+ # vectors that keep surfacing in semantic search and are never
+ # re-detected by a future sync (the map row was deleted). Runs
+ # before the auto-index below, so an edited doc's old vectors are
+ # cleared first. _cleanup_removed_vectors is best-effort and no-ops
+ # when the collection was never RAG-indexed.
+ #
+ # Every id in these lists was appended only AFTER its own per-item
+ # commit, so each is durable — a rolled-back removal/update never
+ # reaches here and cannot lose a still-valid doc's vectors.
+ if ldr_collection_id and self.password:
+ if reindexed_doc_ids:
+ self._cleanup_removed_vectors(
+ reindexed_doc_ids, ldr_collection_id
+ )
+ if released_doc_ids:
+ self._cleanup_removed_vectors(
+ released_doc_ids, ldr_collection_id
+ )
+ if removed_doc_ids:
+ self._cleanup_removed_vectors(
+ removed_doc_ids, ldr_collection_id
+ )
+
+ # Auto-index outside the sync transaction (best-effort, async).
+ # Deliberately in the finally, ON FAILURE PATHS TOO: every id in
+ # new_or_updated_doc_ids was committed per-item, and a sync that
+ # fails on item N must not leave items 1..N-1 permanently
+ # unindexed — their versions already match, so no future sync
+ # reprocesses them, and the background reconciler only runs when
+ # the document-scheduler settings are enabled.
+ if new_or_updated_doc_ids and ldr_collection_id and self.password:
+ try:
+ from ..routes.rag_routes import trigger_auto_index
+
+ trigger_auto_index(
+ new_or_updated_doc_ids,
+ ldr_collection_id,
+ self.username,
+ self.password,
+ )
+ except Exception:
+ logger.exception("Zotero: failed to trigger auto-indexing")
+
+ return stats
+
+ def _cleanup_removed_vectors(
+ self, document_ids: List[str], ldr_collection_id: str
+ ) -> None:
+ """Remove the given documents' vectors from the collection's FAISS
+ index. No-op if the collection was never RAG-indexed. Best-effort —
+ never raises (it runs inside a ``finally`` where a propagating exception
+ would mask the real sync error), so the imports live inside the try."""
+ try:
+ from ...database.models.library import RAGIndex
+ from ..services.library_rag_service import LibraryRAGService
+
+ collection_name = f"collection_{ldr_collection_id}"
+ with get_user_db_session(self.username, self.password) as session:
+ rag_index = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name, is_current=True)
+ .first()
+ )
+ if not rag_index:
+ return # collection isn't indexed — nothing to clean
+ embedding_model = rag_index.embedding_model
+ embedding_provider = (
+ rag_index.embedding_model_type.value
+ if rag_index.embedding_model_type
+ else None
+ )
+ chunk_size = rag_index.chunk_size
+ chunk_overlap = rag_index.chunk_overlap
+
+ with LibraryRAGService(
+ username=self.username,
+ embedding_model=embedding_model,
+ embedding_provider=embedding_provider,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ db_password=self.password,
+ ) as rag_service:
+ removed = rag_service.remove_documents_from_index(
+ document_ids, ldr_collection_id
+ )
+ logger.info(
+ f"Zotero: cleared {removed} FAISS vectors for "
+ f"{len(document_ids)} document(s) in {collection_name}"
+ )
+ except Exception:
+ logger.warning(
+ "Zotero: failed to clear FAISS vectors for removed documents"
+ )
+
+ def _mark_failed(
+ self, cfg: ZoteroConfig, collection_key: str, error: str
+ ) -> None:
+ """Best-effort: record a failed status on the sync-state row."""
+ ck = collection_key or ""
+ try:
+ with get_user_db_session(self.username, self.password) as session:
+ state = (
+ session.query(ZoteroSyncState)
+ .filter_by(
+ library_type=cfg.library_type,
+ library_id=cfg.library_id,
+ collection_key=ck,
+ )
+ .first()
+ )
+ if state:
+ state.last_status = "failed"
+ state.last_error = error[:2000]
+ session.commit()
+ except Exception:
+ logger.debug("Zotero: could not record failed state", exc_info=True)
+
+ # -- LDR collection / state helpers -----------------------------------
+
+ def _ensure_ldr_collection(
+ self,
+ session,
+ client: ZoteroClient,
+ cfg: ZoteroConfig,
+ collection_key: str,
+ ) -> str:
+ """Find or create the LDR collection backing this Zotero collection."""
+ ck = collection_key or ""
+ state = (
+ session.query(ZoteroSyncState)
+ .filter_by(
+ library_type=cfg.library_type,
+ library_id=cfg.library_id,
+ collection_key=ck,
+ )
+ .first()
+ )
+ if state:
+ existing = (
+ session.query(Collection)
+ .filter_by(id=state.ldr_collection_id)
+ .first()
+ )
+ if existing:
+ return existing.id
+
+ # Determine a friendly name.
+ if collection_key:
+ name = client.get_collection_name(collection_key) or collection_key
+ display = f"Zotero: {name}"
+ description = (
+ f"Imported from Zotero collection '{name}' ({collection_key})."
+ )
+ else:
+ display = "Zotero Library"
+ description = "Imported from the entire Zotero library."
+
+ collection_id = str(uuid.uuid4())
+ session.add(
+ Collection(
+ id=collection_id,
+ name=display,
+ description=description,
+ collection_type="zotero",
+ is_default=False,
+ )
+ )
+ session.flush()
+ return collection_id
+
+ def _get_or_create_state(
+ self,
+ session,
+ cfg: ZoteroConfig,
+ collection_key: str,
+ ldr_collection_id: str,
+ ) -> ZoteroSyncState:
+ ck = collection_key or ""
+ state = (
+ session.query(ZoteroSyncState)
+ .filter_by(
+ library_type=cfg.library_type,
+ library_id=cfg.library_id,
+ collection_key=ck,
+ )
+ .first()
+ )
+ if state:
+ # Keep the collection pointer fresh in case it was recreated.
+ state.ldr_collection_id = ldr_collection_id
+ return state
+ state = ZoteroSyncState(
+ library_type=cfg.library_type,
+ library_id=cfg.library_id,
+ collection_key=ck,
+ ldr_collection_id=ldr_collection_id,
+ last_version=0,
+ last_status="pending",
+ )
+ session.add(state)
+ session.flush()
+ return state
+
+ # -- item ingestion ----------------------------------------------------
+
+ def _ingest_item(
+ self,
+ session,
+ client: ZoteroClient,
+ cfg: ZoteroConfig,
+ item: ZoteroItem,
+ ldr_collection_id: str,
+ source_type_id: str,
+ pdf_storage: PDFStorageManager,
+ ) -> Tuple[Optional[str], str, bool]:
+ """Create or update the LDR document for a Zotero item.
+
+ Returns ``(document_id, action, reindexed_in_place)`` where action is
+ ``"imported"`` | ``"updated"`` | ``"skipped"``. ``reindexed_in_place``
+ is True only when an existing document's content changed and its stale
+ RAG chunks were purged here — the caller must then clear the matching
+ FAISS vectors before the re-index rebuilds them.
+ """
+ item.attachments = client.get_children(item.key)
+ pdf_att = item.best_pdf_attachment()
+
+ pdf_bytes = None
+ zotero_fulltext = None
+ if pdf_att:
+ # In text-only mode we don't keep the PDF, so prefer Zotero's
+ # already-extracted full text and skip the download + local parse
+ # entirely. Falls back to downloading if Zotero has no indexed
+ # text for the attachment.
+ if cfg.pdf_storage_mode == "none":
+ zotero_fulltext = client.get_attachment_fulltext(pdf_att.key)
+ if not zotero_fulltext:
+ pdf_bytes = client.download_attachment(pdf_att.key)
+ # Validate the downloaded body really is a PDF. The /file
+ # endpoint can redirect to an HTML error page; without this
+ # we'd store that as file_type="pdf" and extract garbage.
+ if pdf_bytes is not None and b"%PDF" not in pdf_bytes[:1024]:
+ logger.warning(
+ f"Zotero: attachment {pdf_att.key} did not return PDF "
+ "content; treating item as having no PDF"
+ )
+ pdf_bytes = None
+
+ if pdf_bytes:
+ content = pdf_bytes
+ file_type = "pdf"
+ mime_type = "application/pdf"
+ text, extraction_method = self._safe_extract_text(pdf_bytes, item)
+ elif zotero_fulltext:
+ from ...text_processing import remove_surrogates
+
+ text = remove_surrogates(zotero_fulltext)
+ content = text.encode("utf-8", errors="ignore")
+ file_type = "pdf" # it is a PDF paper; we just reused Zotero's text
+ mime_type = "application/pdf"
+ extraction_method = "zotero_fulltext"
+ else:
+ if not cfg.import_items_without_pdf:
+ return None, "skipped", False
+ text = self._metadata_text(item)
+ content = text.encode("utf-8", errors="ignore")
+ file_type = "text"
+ mime_type = "text/plain"
+ extraction_method = "metadata"
+
+ # Optionally append the user's annotations (highlights/comments) and
+ # child notes to the searchable text. Kept out of the content hash so
+ # it doesn't perturb dedup of the primary document.
+ if cfg.import_annotations:
+ extra = self._collect_annotations_text(client, item)
+ if extra:
+ text = f"{text}\n\n{extra}" if text else extra
+
+ doc_hash = hashlib.sha256(content).hexdigest()
+
+ # The document this item currently maps to (if any) — needed both to
+ # detect an in-place content change and, on unchanged content, to
+ # decide whether the searchable text may be refreshed safely.
+ prior = (
+ session.query(ZoteroItemMap)
+ .filter_by(
+ ldr_collection_id=ldr_collection_id, zotero_item_key=item.key
+ )
+ .first()
+ )
+ # -1 matches no row (Integer PK starts at 1) so the "any OTHER
+ # mapping?" exclusion below stays correct when there is no prior row.
+ prior_mapping_id = prior.id if prior else -1
+
+ # Dedup: an identical document (same bytes) may already exist.
+ # document_hash is globally UNIQUE, so this can match a document from
+ # a different source (a manual upload or research download). Only
+ # rewrite metadata on documents WE own (Zotero source); for a foreign
+ # document just add the collection link — never clobber the user's
+ # title/tags or take ownership of it.
+ existing = (
+ session.query(Document).filter_by(document_hash=doc_hash).first()
+ )
+ if existing:
+ if existing.source_type_id == source_type_id:
+ # Deliberately gated on ownership only (NOT exclusivity):
+ # metadata edits must keep propagating to a doc shared across
+ # two synced collections. For byte-identical twin ITEMS this
+ # means last-synced-twin-wins on title/tags — an accepted
+ # trade-off for content that is by definition the same paper.
+ self._apply_metadata(existing, item)
+ ensure_in_collection(session, existing.id, ldr_collection_id)
+ # The content bytes are unchanged, but the searchable text may
+ # not be: annotations/notes are appended AFTER hashing (so they
+ # don't perturb dedup), and a previously failed PDF extraction
+ # may have fallen back to metadata text. Refresh it — but only on
+ # a document this item exclusively owns; rewriting a shared or
+ # foreign doc's text would change what its other references
+ # surface.
+ if (text or "") != (
+ existing.text_content or ""
+ ) and self._exclusive_to_mapping(
+ session,
+ existing,
+ prior_mapping_id,
+ ldr_collection_id,
+ source_type_id,
+ ):
+ existing.text_content = text
+ existing.character_count = len(text) if text else 0
+ existing.word_count = len(text.split()) if text else 0
+ existing.extraction_method = extraction_method
+ self._purge_collection_chunks(
+ session, existing.id, ldr_collection_id
+ )
+ return existing.id, "updated", True
+ # Content is byte-identical (matched by hash), so the existing
+ # chunks/vectors are still valid — no purge needed.
+ return existing.id, "updated", False
+
+ # Is this a re-import of an item we already mapped (content changed)?
+ doc = None
+ if prior and prior.document_id:
+ doc = (
+ session.query(Document).filter_by(id=prior.document_id).first()
+ )
+ # An in-place rewrite is only safe on a document this item
+ # exclusively owns. A dedup-adopted user upload, a byte-identical
+ # twin's shared doc, or a doc linked into another collection must
+ # never be mutated under its other references — fork a fresh
+ # Document instead; the caller's remap logic then releases this
+ # item's claim on the old one (_release_document keeps shared and
+ # foreign documents intact).
+ if doc is not None and not self._exclusive_to_mapping(
+ session,
+ doc,
+ prior_mapping_id,
+ ldr_collection_id,
+ source_type_id,
+ ):
+ doc = None
+
+ created = doc is None
+ if doc is None:
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=source_type_id,
+ )
+ session.add(doc)
+
+ store_pdf_in_db = (
+ cfg.pdf_storage_mode == "database" and file_type == "pdf"
+ )
+
+ doc.document_hash = doc_hash
+ doc.filename = self._filename_for(item, file_type)
+ doc.file_size = len(content)
+ doc.file_type = file_type
+ doc.mime_type = mime_type
+ doc.text_content = text
+ doc.character_count = len(text) if text else 0
+ doc.word_count = len(text.split()) if text else 0
+ doc.extraction_method = extraction_method
+ doc.extraction_source = "zotero"
+ doc.status = DocumentStatus.COMPLETED
+ doc.processed_at = datetime.now(UTC)
+ doc.storage_mode = "database" if store_pdf_in_db else "none"
+ doc.file_path = None if store_pdf_in_db else FILE_PATH_TEXT_ONLY
+ self._apply_metadata(doc, item)
+ session.flush()
+
+ if store_pdf_in_db:
+ try:
+ pdf_storage.save_pdf(
+ pdf_content=content,
+ document=doc,
+ session=session,
+ filename=doc.filename,
+ )
+ except Exception:
+ logger.exception(
+ f"Zotero: failed to store PDF blob for {item.key}"
+ )
+ # The blob write failed, so there is no PDF to serve. Leave the
+ # doc searchable via its extracted text but downgrade it to
+ # text-only, otherwise ZoteroItemMap.has_pdf (keyed off
+ # file_type=="pdf") would advertise a PDF that load_pdf() — which
+ # looks up the missing blob by document_id — can never return.
+ doc.file_type = "text"
+ doc.mime_type = "text/plain"
+ doc.storage_mode = "none"
+ doc.file_path = FILE_PATH_TEXT_ONLY
+ # On a re-sync a stale blob from a previous import may linger;
+ # drop it so load_pdf() can't serve an outdated PDF for what is
+ # now a text-only doc.
+ session.query(DocumentBlob).filter_by(
+ document_id=doc.id
+ ).delete(synchronize_session=False)
+ elif not created:
+ # Re-sync of an item previously imported WITH a database-stored
+ # PDF that now has no usable PDF (removed in Zotero, or the
+ # re-downloaded body failed the %PDF check). The doc is being
+ # marked text-only (storage_mode="none"), so drop the stale
+ # encrypted blob — otherwise PDFStorageManager.load_pdf(), which
+ # keys off document_id and ignores file_type, would keep serving
+ # the orphaned PDF.
+ removed = (
+ session.query(DocumentBlob)
+ .filter_by(document_id=doc.id)
+ .delete(synchronize_session=False)
+ )
+ if removed:
+ logger.info(
+ f"Zotero: removed stale PDF blob for {item.key} "
+ "(item no longer has a usable PDF)"
+ )
+
+ ensure_in_collection(session, doc.id, ldr_collection_id)
+ # On an in-place content change the document's previous RAG chunks are
+ # now stale: chunking is content-derived and _store_chunks_to_db dedups
+ # by chunk hash, so a re-index would ADD the new chunks while the old
+ # ones linger and keep surfacing outdated text in search. Purge this
+ # collection's chunks for the doc now (atomic with the content update)
+ # and force a re-index by clearing the indexed flag; the caller clears
+ # the matching FAISS vectors before that re-index runs.
+ if not created:
+ self._purge_collection_chunks(session, doc.id, ldr_collection_id)
+
+ return doc.id, ("imported" if created else "updated"), (not created)
+
+ @staticmethod
+ def _exclusive_to_mapping(
+ session,
+ doc: Document,
+ mapping_id,
+ coll_id: str,
+ source_type_id: str,
+ ) -> bool:
+ """True when ``doc`` belongs to this item mapping alone: Zotero owns
+ it, no OTHER :class:`ZoteroItemMap` row points at it, and it isn't
+ linked into any other collection. Only such a document may be
+ rewritten in place — anything else (a dedup-adopted user upload, a
+ byte-identical twin's shared doc, a doc the user linked into another
+ collection) would be corrupted under its other references.
+ """
+ if doc.source_type_id != source_type_id:
+ return False
+ shared_mapping = (
+ session.query(ZoteroItemMap.id)
+ .filter(
+ ZoteroItemMap.document_id == doc.id,
+ ZoteroItemMap.id != mapping_id,
+ )
+ .first()
+ is not None
+ )
+ if shared_mapping:
+ return False
+ linked_elsewhere = (
+ session.query(DocumentCollection.document_id)
+ .filter(
+ DocumentCollection.document_id == doc.id,
+ DocumentCollection.collection_id != coll_id,
+ )
+ .first()
+ is not None
+ )
+ return not linked_elsewhere
+
+ @staticmethod
+ def _purge_collection_chunks(session, doc_id: str, coll_id: str) -> None:
+ """Purge a doc's RAG chunks for this collection and clear the link's
+ indexed flag, forcing a re-index after an in-place text change.
+
+ Raises on failure so the whole per-item transaction rolls back (the
+ item retries next sync) — swallowing here would let the caller purge
+ FAISS vectors for chunks that still exist.
+ """
+ CascadeHelper.delete_document_chunks(
+ session, doc_id, collection_name=f"collection_{coll_id}"
+ )
+ link = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ )
+ if link:
+ link.indexed = False
+
+ def _collect_annotations_text(
+ self, client: ZoteroClient, item: ZoteroItem
+ ) -> str:
+ """Gather the item's PDF annotations + child notes as one text block.
+
+ Best-effort: a failure fetching either must not break ingestion.
+ """
+ from ...text_processing import remove_surrogates
+
+ annotations: List[str] = []
+ for att in item.attachments or []:
+ try:
+ annotations.extend(client.get_annotations(att.key))
+ except Exception:
+ logger.debug(
+ f"Zotero: could not fetch annotations for {att.key}",
+ exc_info=True,
+ )
+ try:
+ notes = client.get_notes(item.key)
+ except Exception:
+ logger.debug(
+ f"Zotero: could not fetch notes for {item.key}", exc_info=True
+ )
+ notes = []
+
+ sections: List[str] = []
+ if annotations:
+ sections.append(
+ "Annotations:\n" + "\n".join(f"- {a}" for a in annotations)
+ )
+ if notes:
+ sections.append("Notes:\n" + "\n\n".join(notes))
+ return remove_surrogates("\n\n".join(sections)) if sections else ""
+
+ def _safe_extract_text(
+ self, pdf_bytes: bytes, item: ZoteroItem
+ ) -> Tuple[Optional[str], str]:
+ """Extract text from PDF bytes; returns ``(text, extraction_method)``.
+
+ Falls back to metadata text (method ``"metadata"``) when extraction
+ fails or yields nothing, so the document is still searchable — the
+ method string keeps downstream consumers from assuming real PDF text
+ when only the fallback was stored.
+ """
+ from ...document_loaders import extract_text_from_bytes
+ from ...text_processing import remove_surrogates
+
+ try:
+ text = extract_text_from_bytes(pdf_bytes, ".pdf", item.key)
+ except Exception:
+ logger.debug(
+ f"Zotero: PDF text extraction failed for {item.key}",
+ exc_info=True,
+ )
+ text = None
+ if not text:
+ # Fall back to metadata so the document is still searchable.
+ return self._metadata_text(item), "metadata"
+ return remove_surrogates(text), "pdf_extraction"
+
+ # -- metadata helpers --------------------------------------------------
+
+ def _apply_metadata(self, doc: Document, item: ZoteroItem) -> None:
+ data = item.data
+ doc.title = (data.get("title") or doc.filename or item.key)[:5000]
+ authors = self._authors(item)
+ if authors:
+ doc.authors = authors
+ doi = (data.get("DOI") or "").strip()
+ if doi:
+ doc.doi = doi[:255]
+ isbn = (data.get("ISBN") or "").strip()
+ if isbn:
+ doc.isbn = isbn[:20]
+ published = self._parse_date(data.get("date"))
+ if published:
+ doc.published_date = published
+ tags = [
+ t.get("tag")
+ for t in data.get("tags", [])
+ if isinstance(t, dict) and t.get("tag")
+ ]
+ if tags:
+ doc.tags = tags
+ url = self._source_url(item)
+ if url:
+ doc.original_url = url
+
+ @staticmethod
+ def _item_has_tags(item: ZoteroItem, required: List[str]) -> bool:
+ """True if the item carries ALL required tags (case-insensitive)."""
+ item_tags = {
+ (t.get("tag") or "").strip().lower()
+ for t in item.data.get("tags", []) or []
+ if isinstance(t, dict)
+ }
+ return all(r.strip().lower() in item_tags for r in required)
+
+ @staticmethod
+ def _authors(item: ZoteroItem) -> List[str]:
+ names: List[str] = []
+ for creator in item.data.get("creators", []) or []:
+ if not isinstance(creator, dict):
+ continue
+ if creator.get("name"):
+ names.append(creator["name"].strip())
+ else:
+ full = " ".join(
+ p
+ for p in (
+ creator.get("firstName", ""),
+ creator.get("lastName", ""),
+ )
+ if p
+ ).strip()
+ if full:
+ names.append(full)
+ return names
+
+ @staticmethod
+ def _source_url(item: ZoteroItem) -> Optional[str]:
+ data = item.data
+ if data.get("url"):
+ return str(data["url"]).strip()
+ doi = (data.get("DOI") or "").strip()
+ if doi:
+ return f"https://doi.org/{doi}"
+ return None
+
+ @staticmethod
+ def _parse_date(raw) -> Optional[date]:
+ """Best-effort parse of Zotero's freeform date field."""
+ if not raw:
+ return None
+ text = str(raw).strip()
+ # Try full ISO first.
+ for fmt in ("%Y-%m-%d", "%Y-%m"):
+ try:
+ return datetime.strptime(text[: len(fmt) + 2], fmt).date()
+ except ValueError:
+ continue
+ match = re.search(r"(\d{4})", text)
+ if match:
+ year = int(match.group(1))
+ if 1000 <= year <= 9999:
+ return date(year, 1, 1)
+ return None
+
+ def _metadata_text(self, item: ZoteroItem) -> str:
+ data = item.data
+ parts: List[str] = []
+ if data.get("title"):
+ parts.append(f"Title: {data['title']}")
+ authors = self._authors(item)
+ if authors:
+ parts.append(f"Authors: {', '.join(authors)}")
+ if data.get("date"):
+ parts.append(f"Date: {data['date']}")
+ if data.get("publicationTitle"):
+ parts.append(f"Publication: {data['publicationTitle']}")
+ if data.get("DOI"):
+ parts.append(f"DOI: {data['DOI']}")
+ if data.get("url"):
+ parts.append(f"URL: {data['url']}")
+ tags = [
+ t.get("tag")
+ for t in data.get("tags", [])
+ if isinstance(t, dict) and t.get("tag")
+ ]
+ if tags:
+ parts.append(f"Tags: {', '.join(tags)}")
+ if data.get("abstractNote"):
+ parts.append(f"\nAbstract:\n{data['abstractNote']}")
+
+ from ...text_processing import remove_surrogates
+
+ return remove_surrogates("\n".join(parts)) if parts else item.key
+
+ @staticmethod
+ def _filename_for(item: ZoteroItem, file_type: str) -> str:
+ title = (item.data.get("title") or "").strip()
+ candidate = f"{title[:120]}.{file_type}" if title else None
+ if candidate:
+ try:
+ return sanitize_filename(candidate)
+ except UnsafeFilenameError:
+ pass
+ return f"{item.key}.{file_type}"
+
+ # -- mapping / removal -------------------------------------------------
+
+ def _upsert_map(
+ self,
+ session,
+ ldr_collection_id: str,
+ item: ZoteroItem,
+ document_id: Optional[str],
+ ) -> None:
+ row = (
+ session.query(ZoteroItemMap)
+ .filter_by(
+ ldr_collection_id=ldr_collection_id,
+ zotero_item_key=item.key,
+ )
+ .first()
+ )
+ has_pdf = bool(
+ document_id
+ and (
+ session.query(Document)
+ .filter_by(id=document_id, file_type="pdf")
+ .first()
+ )
+ )
+ if row:
+ row.zotero_version = item.version
+ row.document_id = document_id
+ row.has_pdf = has_pdf
+ row.last_synced_at = datetime.now(UTC)
+ else:
+ session.add(
+ ZoteroItemMap(
+ ldr_collection_id=ldr_collection_id,
+ zotero_item_key=item.key,
+ zotero_version=item.version,
+ document_id=document_id,
+ has_pdf=has_pdf,
+ last_synced_at=datetime.now(UTC),
+ )
+ )
+
+ def _touch_map_version(
+ self,
+ session,
+ ldr_collection_id: str,
+ zotero_item_key: str,
+ version: int,
+ ) -> None:
+ """Record a key's version without importing a document.
+
+ Used for keys we deliberately don't import (a child/note that slipped
+ into the top-level list, or a key Zotero didn't return) so the
+ version-changed predicate doesn't re-queue them on every sync. Does
+ not touch ``document_id`` (stays None / unchanged).
+ """
+ ik = zotero_item_key
+ row = (
+ session.query(ZoteroItemMap)
+ .filter_by(
+ ldr_collection_id=ldr_collection_id,
+ zotero_item_key=ik,
+ )
+ .first()
+ )
+ if row:
+ row.zotero_version = version
+ row.last_synced_at = datetime.now(UTC)
+ else:
+ session.add(
+ ZoteroItemMap(
+ ldr_collection_id=ldr_collection_id,
+ zotero_item_key=ik,
+ zotero_version=version,
+ document_id=None,
+ has_pdf=False,
+ last_synced_at=datetime.now(UTC),
+ )
+ )
+
+ def _remove_item(
+ self, session, row: ZoteroItemMap, source_type_id: str
+ ) -> Optional[str]:
+ """Remove an item that no longer exists in Zotero.
+
+ The document is only hard-deleted when nothing else references it AND
+ it is a Zotero-owned document. Because dedup is global by content hash,
+ one Document can be shared by multiple collections / Zotero mappings, or
+ can be a user upload / research download that Zotero merely adopted via
+ dedup; in those cases we must only drop *this* collection's link and the
+ mapping row, never destroy a shared or foreign-owned document (and its
+ blob/chunks) out from under the other references / the user.
+
+ Returns the RELEASED document_id (so the caller can clear its FAISS
+ vectors for this collection after the transaction), or None when the
+ document is kept — either it has no document, or a byte-identical twin
+ still maps to it in this collection (in which case its vectors must NOT
+ be purged, or the surviving twin would vanish from search).
+ """
+ released = self._release_document(
+ session,
+ row.document_id,
+ row.ldr_collection_id,
+ row.id,
+ source_type_id,
+ )
+ session.delete(row)
+ return released
+
+ def _release_document(
+ self,
+ session,
+ doc_id: Optional[str],
+ coll_id: str,
+ keep_mapping_id,
+ source_type_id: str,
+ ) -> Optional[str]:
+ """Release a document from this collection: drop its collection link and
+ RAG chunks, hard-deleting the document only when nothing else references
+ it AND Zotero owns it. Never destroys a shared or foreign-owned document
+ (dedup is global by content hash, so one Document may be shared across
+ collections/mappings, or be a user upload Zotero merely adopted).
+
+ ``keep_mapping_id`` is the ZoteroItemMap row that is going away or being
+ repointed — excluded from the "is it shared?" check. Used both when an
+ item is removed (:meth:`_remove_item`) and when an in-place edit dedups
+ onto a *different* existing document, orphaning the item's prior doc.
+ Returns ``doc_id`` so the caller can clear its FAISS vectors after the
+ transaction.
+ """
+ if not doc_id:
+ return None
+ # Another item in THIS collection still maps to the doc (byte-identical
+ # dedup): it must stay linked + indexed here, so there is nothing to
+ # release and no vectors to purge.
+ if (
+ session.query(ZoteroItemMap)
+ .filter(
+ ZoteroItemMap.document_id == doc_id,
+ ZoteroItemMap.id != keep_mapping_id,
+ ZoteroItemMap.ldr_collection_id == coll_id,
+ )
+ .first()
+ is not None
+ ):
+ return None
+ doc_owned_by_zotero = (
+ session.query(Document.id)
+ .filter_by(id=doc_id, source_type_id=source_type_id)
+ .first()
+ is not None
+ )
+ referenced_elsewhere = (
+ session.query(ZoteroItemMap)
+ .filter(
+ ZoteroItemMap.document_id == doc_id,
+ ZoteroItemMap.id != keep_mapping_id,
+ )
+ .first()
+ is not None
+ ) or (
+ session.query(DocumentCollection)
+ .filter(
+ DocumentCollection.document_id == doc_id,
+ DocumentCollection.collection_id != coll_id,
+ )
+ .first()
+ is not None
+ )
+ # A cascade failure below must PROPAGATE so the whole release (and the
+ # map change it shares a transaction with) rolls back and the item is
+ # retried next sync. Swallowing it would commit a half-release — the
+ # map row gone but the doc/chunks still present — and the caller would
+ # then purge FAISS vectors for a document that still exists.
+ if referenced_elsewhere or not doc_owned_by_zotero:
+ # Keep the document (shared with another collection/mapping, or a
+ # user upload / research download Zotero only adopted via
+ # content-hash dedup — never Zotero's to destroy), but drop this
+ # collection's link AND its RAG chunks so it stops surfacing here.
+ # The caller clears this collection's FAISS vectors for the returned
+ # doc_id after the transaction.
+ CascadeHelper.delete_document_chunks(
+ session, doc_id, collection_name=f"collection_{coll_id}"
+ )
+ session.query(DocumentCollection).filter_by(
+ document_id=doc_id, collection_id=coll_id
+ ).delete(synchronize_session=False)
+ else:
+ doc = session.query(Document).filter_by(id=doc_id).first()
+ if doc:
+ # DocumentChunk has no FK cascade — delete RAG chunks
+ # explicitly before removing the document.
+ CascadeHelper.delete_document_chunks(session, doc.id)
+ CascadeHelper.delete_document_completely(session, doc.id)
+ return doc_id
+
+ @staticmethod
+ def _document_exists(session, document_id: Optional[str]) -> bool:
+ if not document_id:
+ return False
+ return (
+ session.query(Document.id).filter_by(id=document_id).first()
+ is not None
+ )
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 689b928fcd..8c336a2beb 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -530,6 +530,38 @@ class BackgroundJobScheduler:
self._schedule_document_processing(username)
return True
+ def reschedule_zotero_jobs(self, username: str) -> bool:
+ """(Re)schedule the Zotero auto-sync job for an ACTIVE user against
+ their current settings.
+
+ Call this after a ``zotero.*`` setting changes (e.g. toggling
+ ``auto_sync_enabled`` or changing ``sync_interval_minutes``) so the
+ change takes effect on the next tick instead of only after the user logs
+ out and back in — otherwise ``_schedule_zotero_sync`` runs only via the
+ login path (``update_user_info`` -> ``_schedule_user_subscriptions``).
+ ``_schedule_zotero_sync`` already removes any existing job and no-ops
+ when auto-sync is disabled, so this both creates and tears down as
+ needed and is idempotent (``replace_existing=True``).
+
+ Relies on the caller having invalidated settings caches first so
+ ``get_config()`` re-reads fresh settings. Returns ``True`` if a
+ reschedule was performed, ``False`` for a user the scheduler isn't
+ tracking (built from current settings on their next login) or when the
+ scheduler isn't running.
+ """
+ if not self.is_running:
+ return False
+ with self.lock:
+ if username not in self.user_sessions:
+ logger.debug(
+ f"[ZOTERO_SCHEDULER] reschedule_zotero_jobs: {username} "
+ "not an active scheduler session; skipping"
+ )
+ return False
+ self.user_sessions[username]["last_activity"] = datetime.now(UTC)
+ self._schedule_zotero_sync(username)
+ return True
+
def _schedule_user_subscriptions(self, username: str):
"""Schedule all active subscriptions for a user."""
logger.info(f"_schedule_user_subscriptions called for {username}")
@@ -662,6 +694,9 @@ class BackgroundJobScheduler:
# Add document processing for this user
self._schedule_document_processing(username)
+ # Add Zotero auto-sync for this user (no-op unless enabled)
+ self._schedule_zotero_sync(username)
+
def _schedule_document_processing(self, username: str):
"""Schedule document processing for a user."""
logger.info(
@@ -1639,6 +1674,134 @@ class BackgroundJobScheduler:
)
return False
+ # -- Zotero auto-sync -------------------------------------------------
+
+ def _schedule_zotero_sync(self, username: str):
+ """Schedule (or refresh) the Zotero auto-sync job for a user.
+
+ No-op unless the user has enabled the Zotero integration *and*
+ background auto-sync. Any existing job is removed first so toggling
+ the setting off actually unschedules it.
+ """
+ # Pre-declared so the except handler can pass it to redact_secrets
+ # even if retrieve()/get_config() raises — get_config() opens the
+ # encrypted DB, so an error message could embed the SQLCipher key.
+ password = None
+ try:
+ session_info = self.user_sessions.get(username)
+ if not session_info:
+ return
+
+ job_id = f"{username}_zotero_sync"
+
+ def _drop_existing_job():
+ try:
+ self.scheduler.remove_job(job_id)
+ session_info["scheduled_jobs"].discard(job_id)
+ except JobLookupError:
+ pass
+
+ password = self._credential_store.retrieve(username)
+ if not password:
+ # Expired credentials: the job could never run anyway, and
+ # disabling auto-sync in this state must still unschedule it —
+ # otherwise it keeps ticking (and logging a warning) until
+ # logout.
+ _drop_existing_job()
+ return
+
+ from ..research_library.zotero import ZoteroSyncService
+
+ cfg = ZoteroSyncService(username, password).get_config()
+
+ # Remove only AFTER the config read succeeded: a transient error
+ # from the encrypted-DB read must leave a healthy existing job in
+ # place (it would otherwise stay gone until the next login).
+ # Accepted trade-off: if that error races a just-disabled toggle,
+ # the stale job stays scheduled — but it is inert, because
+ # _sync_user_zotero re-checks the config at every tick and no-ops
+ # when auto-sync is disabled.
+ _drop_existing_job()
+
+ if not (cfg.is_configured and cfg.auto_sync_enabled):
+ logger.debug(
+ f"[ZOTERO_SCHEDULER] Auto-sync not enabled for {username}"
+ )
+ return
+
+ interval_minutes = max(15, int(cfg.sync_interval_minutes or 360))
+ self.scheduler.add_job(
+ func=self._wrap_job(self._sync_user_zotero),
+ args=[username],
+ trigger="interval",
+ minutes=interval_minutes,
+ id=job_id,
+ name=f"Zotero Sync for {username}",
+ jitter=60,
+ max_instances=1,
+ replace_existing=True,
+ )
+ session_info["scheduled_jobs"].add(job_id)
+ logger.info(
+ f"[ZOTERO_SCHEDULER] Scheduled Zotero sync for {username} "
+ f"every {interval_minutes} minutes"
+ )
+ except Exception as e:
+ safe_msg = redact_secrets(str(e), password)
+ logger.warning(
+ f"[ZOTERO_SCHEDULER] Error scheduling Zotero sync for "
+ f"{username}: {safe_msg}"
+ )
+
+ @thread_cleanup
+ def _sync_user_zotero(self, username: str):
+ """Background job: run a Zotero sync for a user."""
+ password = None
+ try:
+ session_info = self.user_sessions.get(username)
+ if not session_info:
+ return
+
+ password = self._credential_store.retrieve(username)
+ if not password:
+ logger.warning(
+ f"[ZOTERO_SCHEDULER] Credentials expired for {username}"
+ )
+ return
+
+ from ..research_library.zotero import ZoteroSyncService
+
+ service = ZoteroSyncService(username, password)
+ cfg = service.get_config()
+ if not (cfg.is_configured and cfg.auto_sync_enabled):
+ logger.debug(
+ f"[ZOTERO_SCHEDULER] Auto-sync not enabled for {username}"
+ )
+ return
+
+ logger.info(
+ f"[ZOTERO_SCHEDULER] Running Zotero sync for {username}"
+ )
+ result = service.sync_all()
+ logger.info(
+ f"[ZOTERO_SCHEDULER] Zotero sync for {username}: "
+ f"imported={result.get('imported')}, "
+ f"updated={result.get('updated')}, "
+ f"removed={result.get('removed')}, "
+ f"skipped={result.get('skipped')}, "
+ f"errors={result.get('errors')}"
+ )
+ except Exception as e:
+ # ``password`` was retrieved above and passed into the sync
+ # service (which opens the encrypted DB). Drop the traceback
+ # chain and redact str(e) so the SQLCipher master password
+ # cannot leak under loguru ``diagnose=True``.
+ safe_msg = redact_secrets(str(e), password)
+ logger.warning(
+ f"[ZOTERO_SCHEDULER] Error syncing Zotero for {username}: "
+ f"{safe_msg}"
+ )
+
@thread_cleanup
def _check_user_overdue_subscriptions(self, username: str):
"""Check and immediately run any overdue subscriptions for a user."""
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 8388b4930e..6e54509cc0 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -722,6 +722,12 @@ def register_blueprints(app):
app.register_blueprint(rag_bp) # Already has url_prefix='/library'
logger.info("RAG Management routes registered successfully")
+ # Register Zotero integration blueprint
+ from ..research_library import zotero_bp
+
+ app.register_blueprint(zotero_bp) # Already has url_prefix='/library'
+ logger.info("Zotero integration routes registered successfully")
+
# Register Deletion Management blueprint
app.register_blueprint(delete_bp) # Already has url_prefix='/library/api'
logger.info("Deletion Management routes registered successfully")
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 458c1b7f62..e007f0e942 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -82,6 +82,7 @@ from ..services.settings_service import (
create_or_update_setting,
invalidate_settings_caches,
reschedule_document_jobs_if_needed,
+ reschedule_zotero_jobs_if_needed,
set_setting,
)
from ..utils.route_decorators import with_user_session
@@ -171,6 +172,7 @@ ALLOWED_SETTING_PREFIXES = frozenset(
"search.",
"ui.",
"web.",
+ "zotero.",
}
)
BLOCKED_SETTING_PREFIXES = frozenset(
@@ -753,6 +755,9 @@ def save_all_settings(
reschedule_document_jobs_if_needed(
session["username"], updated_settings + created_settings
)
+ reschedule_zotero_jobs_if_needed(
+ session["username"], updated_settings + created_settings
+ )
return jsonify(response_data)
except Exception:
@@ -1170,6 +1175,7 @@ def api_update_setting(key, db_session: Optional[Session] = None):
# A document_scheduler.* toggle (e.g. sweep_library_collections
# or generate_rag) must take effect without a re-login.
reschedule_document_jobs_if_needed(session["username"], [key])
+ reschedule_zotero_jobs_if_needed(session["username"], [key])
return jsonify(response_data)
return jsonify({"error": f"Failed to update setting {key}"}), 500
@@ -1214,6 +1220,7 @@ def api_update_setting(key, db_session: Optional[Session] = None):
if db_setting:
invalidate_settings_caches(session["username"])
reschedule_document_jobs_if_needed(session["username"], [key])
+ reschedule_zotero_jobs_if_needed(session["username"], [key])
return (
jsonify(
{
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index 23ae4684d2..46bb7cd503 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -127,6 +127,38 @@ def reschedule_document_jobs_if_needed(username, changed_keys):
)
+def reschedule_zotero_jobs_if_needed(username, changed_keys):
+ """Reschedule a user's Zotero auto-sync job after a settings change.
+
+ Mirrors :func:`reschedule_document_jobs_if_needed` for ``zotero.*`` keys.
+ Without it, toggling ``zotero.auto_sync_enabled`` (or changing
+ ``zotero.sync_interval_minutes``) would not create/refresh the interval job
+ until the user logged out and back in — the schedule is otherwise only built
+ on the login path. Call AFTER ``invalidate_settings_caches`` so the
+ scheduler re-reads fresh settings. Only reschedules when a ``zotero.`` key
+ actually changed. Best-effort and silent when the scheduler isn't running
+ (e.g. tests, CLI).
+
+ Args:
+ username: The user whose Zotero job should be re-evaluated.
+ changed_keys: Iterable of setting keys written by the request.
+ """
+ if not username or not changed_keys:
+ return
+ if not any(str(key).startswith("zotero.") for key in changed_keys):
+ return
+ try:
+ from ...scheduler.background import get_background_job_scheduler
+
+ scheduler = get_background_job_scheduler()
+ scheduler.reschedule_zotero_jobs(username)
+ except Exception:
+ logger.debug(
+ "Could not reschedule Zotero jobs after settings change",
+ exc_info=True,
+ )
+
+
def validate_setting(
setting: Setting, value: Any
) -> tuple[bool, Optional[str]]:
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index 49abc4fabe..1e1fe13567 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -50,6 +50,12 @@
<span class="ldr-nav-text">Downloads</span>
</a>
</li>
+ <li {% if active_page == 'zotero' %}class="active ldr-sidebar-item--nested"{% else %}class="ldr-sidebar-item--nested"{% endif %} data-page="zotero">
+ <a href="{{ url_for('zotero.zotero_page') }}" title="Zotero" aria-label="Zotero">
+ <i aria-hidden="true" class="fas fa-book"></i>
+ <span class="ldr-nav-text">Zotero</span>
+ </a>
+ </li>
</ul>
</div>
diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.html
new file mode 100644
index 0000000000..f1a986ea18
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/zotero.html
@@ -0,0 +1,523 @@
+{% extends "base.html" %}
+
+{% block title %}Zotero - Local Deep Research{% endblock %}
+
+{% block extra_head %}
+<style>
+.ldr-zotero-wrap { max-width: 960px; margin: 0 auto; padding: 20px; }
+.ldr-zotero-card {
+ background: var(--card-bg);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 20px;
+ color: var(--text-primary);
+}
+.ldr-zotero-card h2 { margin-top: 0; font-size: 1.1rem; }
+.ldr-zotero-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
+.ldr-zotero-actions button {
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
+ border: 1px solid var(--border-color); background: var(--card-bg);
+ color: var(--text-primary);
+}
+.ldr-zotero-actions button.ldr-zotero-primary {
+ background: var(--primary-color, #6e4ff6); color: #fff; border-color: transparent;
+}
+.ldr-zotero-actions button:disabled { opacity: .5; cursor: not-allowed; }
+.ldr-zotero-msg { margin-top: 12px; font-size: .9rem; min-height: 1.2em; }
+.ldr-zotero-msg.ldr-zotero-ok { color: #1faa59; }
+.ldr-zotero-msg.ldr-zotero-err { color: #e5484d; }
+
+/* Editable config form */
+.ldr-zotero-form { display: flex; flex-direction: column; gap: 16px; }
+.ldr-zotero-fieldset { border: 1px solid var(--border-color); border-radius: 6px; padding: 14px 16px 16px; margin: 0; }
+.ldr-zotero-fieldset legend { padding: 0 6px; font-size: .78rem; text-transform: uppercase; letter-spacing: .04em; color: var(--text-secondary, #999); }
+.ldr-zotero-field { margin-bottom: 14px; }
+.ldr-zotero-field:last-child { margin-bottom: 0; }
+.ldr-zotero-field > label { display: block; font-size: .85rem; margin-bottom: 5px; }
+.ldr-zotero-hint { font-size: .78rem; color: var(--text-secondary, #999); margin-top: 5px; }
+.ldr-zotero-input, .ldr-zotero-select {
+ width: 100%; box-sizing: border-box; padding: 8px 10px; border-radius: 6px;
+ border: 1px solid var(--border-color); background: var(--input-bg, var(--card-bg));
+ color: var(--text-primary); font-size: .9rem;
+}
+.ldr-zotero-input:disabled { opacity: .5; }
+.ldr-zotero-check { display: flex; align-items: center; gap: 9px; font-size: .9rem; cursor: pointer; }
+.ldr-zotero-check input { width: 16px; height: 16px; flex: 0 0 auto; }
+.ldr-zotero-row { display: grid; grid-template-columns: 170px 1fr; gap: 12px; }
+.ldr-zotero-save-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
+.ldr-zotero-save-msg { font-size: .85rem; }
+.ldr-zotero-save-msg.ldr-zotero-ok { color: #1faa59; }
+.ldr-zotero-save-msg.ldr-zotero-err { color: #e5484d; }
+#zotero-save { padding: 8px 20px; border-radius: 6px; border: 1px solid transparent; background: var(--primary-color, #6e4ff6); color: #fff; cursor: pointer; }
+#zotero-save:disabled { opacity: .5; cursor: not-allowed; }
+
+table.ldr-zotero-table { width: 100%; border-collapse: collapse; font-size: .88rem; }
+table.ldr-zotero-table th, table.ldr-zotero-table td {
+ text-align: left; padding: 8px; border-bottom: 1px solid var(--border-color);
+}
+/* Click/Enter-to-add key chips in the picker tables — real buttons so they
+ are keyboard- and screen-reader-operable, styled to look like inline code. */
+.ldr-zotero-keybtn {
+ font-family: monospace; font-size: inherit; cursor: pointer;
+ color: var(--primary-color, #6e4ff6); background: none; border: none; padding: 0;
+}
+.ldr-zotero-keybtn:hover, .ldr-zotero-keybtn:focus-visible { text-decoration: underline; }
+.ldr-zotero-empty { color: var(--text-secondary, #999); font-size: .9rem; }
+@media (max-width: 520px) {
+ .ldr-zotero-row { grid-template-columns: 1fr; }
+ .ldr-zotero-actions button { flex: 1 1 auto; }
+}
+/* Sync-status badges + inline error */
+.ldr-zotero-badge { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: .78rem; font-weight: 500; }
+.ldr-zotero-badge-ok { background: rgba(31, 170, 89, .15); color: #1faa59; }
+.ldr-zotero-badge-err { background: rgba(229, 72, 77, .15); color: #e5484d; }
+.ldr-zotero-badge-run { background: rgba(110, 79, 246, .15); color: var(--primary-color, #6e4ff6); }
+.ldr-zotero-badge-muted { background: var(--border-color); color: var(--text-secondary, #999); }
+.ldr-zotero-rowerr { color: #e5484d; font-size: .78rem; margin-top: 3px; word-break: break-word; }
+.ldr-zotero-linkbtn { font: inherit; font-size: .8rem; font-weight: 400; margin-left: 10px; background: none; border: none; color: var(--primary-color, #6e4ff6); cursor: pointer; }
+.ldr-zotero-linkbtn:hover, .ldr-zotero-linkbtn:focus-visible { text-decoration: underline; }
+</style>
+{% endblock %}
+
+{% block content %}
+<div class="ldr-zotero-wrap">
+ <h1><i class="fas fa-book"></i> Zotero</h1>
+ <p class="ldr-zotero-empty">
+ Import papers from a Zotero library or collection into your document
+ library — they are stored, text-extracted and indexed so you can use
+ them as a search source during research. Configure and sync it all from
+ this page.
+ </p>
+
+ <div class="ldr-zotero-card">
+ <h2>Configuration</h2>
+ <form id="zotero-config-form" class="ldr-zotero-form" autocomplete="off">
+ <fieldset class="ldr-zotero-fieldset">
+ <legend>Connection</legend>
+ <div class="ldr-zotero-field">
+ <label class="ldr-zotero-check">
+ <input type="checkbox" id="zt-enabled"> Enable Zotero integration
+ </label>
+ </div>
+ <div class="ldr-zotero-field">
+ <label class="ldr-zotero-check">
+ <input type="checkbox" id="zt-local"> Use the local desktop app API (localhost:23119)
+ </label>
+ <div class="ldr-zotero-hint">Reads from the running Zotero desktop app — no API key needed.</div>
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-library-type">Library</label>
+ <div class="ldr-zotero-row">
+ <select id="zt-library-type" class="ldr-zotero-select" aria-label="Library type">
+ <option value="user">User</option>
+ <option value="group">Group</option>
+ </select>
+ <input type="text" id="zt-library-id" class="ldr-zotero-input" aria-label="Library ID (numeric)" placeholder="Library ID (numeric)">
+ </div>
+ <div class="ldr-zotero-hint">Your numeric user ID (Settings → Feeds/API on zotero.org) or a group ID. Use “List groups” below to find group IDs.</div>
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-api-key">API key</label>
+ <input type="password" id="zt-api-key" class="ldr-zotero-input" autocomplete="new-password" placeholder="Zotero API key">
+ <div class="ldr-zotero-hint" id="zt-api-key-hint">Create one at zotero.org → Settings → Security → Applications.</div>
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-collections">Collections</label>
+ <input type="text" id="zt-collections" class="ldr-zotero-input" placeholder="Collection keys, comma-separated (blank = entire library)">
+ <div class="ldr-zotero-hint">Use “List collections” below to add keys.</div>
+ </div>
+ </fieldset>
+
+ <fieldset class="ldr-zotero-fieldset">
+ <legend>Import options</legend>
+ <div class="ldr-zotero-field">
+ <label class="ldr-zotero-check">
+ <input type="checkbox" id="zt-without-pdf"> Import items without a PDF (metadata / abstract as text)
+ </label>
+ </div>
+ <div class="ldr-zotero-field">
+ <label class="ldr-zotero-check">
+ <input type="checkbox" id="zt-annotations"> Import annotations &amp; notes into the searchable text
+ </label>
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-tags">Only import items tagged (optional)</label>
+ <input type="text" id="zt-tags" class="ldr-zotero-input" placeholder="Tags, comma-separated (blank = all items)">
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-pdf-storage">PDF storage</label>
+ <select id="zt-pdf-storage" class="ldr-zotero-select">
+ <option value="database">Store the PDF in the library (database)</option>
+ <option value="none">Text only — don’t keep the PDF</option>
+ </select>
+ </div>
+ </fieldset>
+
+ <fieldset class="ldr-zotero-fieldset">
+ <legend>Auto-sync</legend>
+ <div class="ldr-zotero-field">
+ <label class="ldr-zotero-check">
+ <input type="checkbox" id="zt-auto-sync"> Automatically sync in the background
+ </label>
+ </div>
+ <div class="ldr-zotero-field">
+ <label for="zt-interval">Interval (minutes)</label>
+ <div class="ldr-zotero-row">
+ <input type="number" id="zt-interval" class="ldr-zotero-input" min="15" max="10080" step="15" value="360">
+ <div class="ldr-zotero-hint" style="align-self:center;margin-top:0;">How often to check Zotero for changes (only when auto-sync is on).</div>
+ </div>
+ </div>
+ </fieldset>
+
+ <div class="ldr-zotero-save-row">
+ <button type="submit" id="zotero-save" class="ldr-zotero-primary">Save settings</button>
+ <span id="zotero-save-msg" class="ldr-zotero-save-msg" role="status" aria-live="polite"></span>
+ </div>
+ </form>
+
+ <div class="ldr-zotero-actions">
+ <button id="zotero-test">Test connection</button>
+ <!-- Start gated; loadConfig() enables these once the saved config is valid. -->
+ <button id="zotero-groups" disabled>List groups</button>
+ <button id="zotero-list" disabled>List collections</button>
+ <button id="zotero-sync" class="ldr-zotero-primary" disabled>Sync now</button>
+ </div>
+ <div id="zotero-msg" class="ldr-zotero-msg" role="status" aria-live="polite"></div>
+ </div>
+
+ <div class="ldr-zotero-card ldr-zotero-collections" id="zotero-groups-card" style="display:none;">
+ <h2>Zotero groups</h2>
+ <p class="ldr-zotero-empty">Click a group to set Library Type = Group and fill its ID above.</p>
+ <table class="ldr-zotero-table">
+ <thead><tr><th>Name</th><th>Group ID</th></tr></thead>
+ <tbody id="zotero-groups-body"></tbody>
+ </table>
+ </div>
+
+ <div class="ldr-zotero-card ldr-zotero-collections" id="zotero-collections-card" style="display:none;">
+ <h2>Zotero collections</h2>
+ <p class="ldr-zotero-empty">Click a key to add it to the Collections field above.</p>
+ <table class="ldr-zotero-table">
+ <thead><tr><th>Name</th><th>Key</th></tr></thead>
+ <tbody id="zotero-collections-body"></tbody>
+ </table>
+ </div>
+
+ <div class="ldr-zotero-card">
+ <h2>Sync status
+ <button type="button" id="zotero-refresh" class="ldr-zotero-linkbtn" title="Refresh sync status"><i class="fas fa-rotate-right"></i> Refresh</button>
+ </h2>
+ <div id="zotero-status">
+ <div class="ldr-zotero-empty">No syncs yet.</div>
+ </div>
+ </div>
+</div>
+
+<script>
+(function () {
+ const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
+ const msg = document.getElementById('zotero-msg');
+ const saveMsg = document.getElementById('zotero-save-msg');
+ const $ = (id) => document.getElementById(id);
+
+ function setMsg(text, ok) {
+ msg.textContent = text || '';
+ msg.className = 'ldr-zotero-msg ' + (ok === true ? 'ldr-zotero-ok' : ok === false ? 'ldr-zotero-err' : '');
+ }
+ function setSaveMsg(text, ok) {
+ saveMsg.textContent = text || '';
+ saveMsg.className = 'ldr-zotero-save-msg ' + (ok === true ? 'ldr-zotero-ok' : ok === false ? 'ldr-zotero-err' : '');
+ }
+
+ async function getJSON(url) {
+ const r = await fetch(url, { headers: { 'Accept': 'application/json' } });
+ return r.json();
+ }
+ async function postJSON(url) {
+ const r = await fetch(url, {
+ method: 'POST',
+ headers: { 'Accept': 'application/json', 'X-CSRFToken': csrf },
+ });
+ return r.json();
+ }
+
+ // Escape any dynamic value before inserting into innerHTML. Zotero
+ // collection names/keys and user-entered settings are untrusted input.
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (ch) => (
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]
+ ));
+
+ // ---- Config form ----------------------------------------------------
+
+ function updateLocalModeUI() {
+ // In local-API mode no key is needed; dim the field to make that clear.
+ const local = $('zt-local').checked;
+ $('zt-api-key').disabled = local;
+ $('zt-api-key-hint').textContent = local
+ ? 'Not needed in local-API mode.'
+ : 'Create one at zotero.org → Settings → Security → Applications.';
+ }
+
+ function updateAutoSyncUI() {
+ // The interval only applies when background auto-sync is enabled.
+ $('zt-interval').disabled = !$('zt-auto-sync').checked;
+ }
+
+ function gateActions(configured) {
+ // The Test/List/Sync buttons act on SAVED settings, so gate them until
+ // the stored config is usable; Test connection stays available.
+ ['zotero-list', 'zotero-groups', 'zotero-sync'].forEach((id) => {
+ const b = $(id);
+ if (!b) return;
+ b.disabled = !configured;
+ b.title = configured ? '' : 'Save valid Zotero settings first';
+ });
+ }
+
+ function fillForm(c) {
+ $('zt-enabled').checked = !!c.enabled;
+ $('zt-local').checked = !!c.use_local_api;
+ $('zt-library-type').value = c.library_type || 'user';
+ $('zt-library-id').value = c.library_id || '';
+ $('zt-collections').value = (c.collection_keys || []).join(', ');
+ $('zt-api-key').value = ''; // write-only: never populate the secret
+ $('zt-api-key').placeholder = c.has_api_key
+ ? '•••••••• saved — leave blank to keep' : 'Zotero API key';
+ $('zt-without-pdf').checked = !!c.import_items_without_pdf;
+ $('zt-annotations').checked = !!c.import_annotations;
+ $('zt-tags').value = (c.import_tags || []).join(', ');
+ $('zt-pdf-storage').value = c.pdf_storage_mode || 'database';
+ $('zt-auto-sync').checked = !!c.auto_sync_enabled;
+ $('zt-interval').value = c.sync_interval_minutes || 360;
+ updateLocalModeUI();
+ updateAutoSyncUI();
+ gateActions(!!c.configured);
+ }
+
+ function collectPayload() {
+ const payload = {
+ 'zotero.enabled': $('zt-enabled').checked,
+ 'zotero.use_local_api': $('zt-local').checked,
+ 'zotero.library_type': $('zt-library-type').value,
+ 'zotero.library_id': $('zt-library-id').value.trim(),
+ 'zotero.collection_keys': $('zt-collections').value.trim(),
+ 'zotero.import_items_without_pdf': $('zt-without-pdf').checked,
+ 'zotero.import_annotations': $('zt-annotations').checked,
+ 'zotero.import_tags': $('zt-tags').value.trim(),
+ 'zotero.pdf_storage_mode': $('zt-pdf-storage').value,
+ 'zotero.auto_sync_enabled': $('zt-auto-sync').checked,
+ 'zotero.sync_interval_minutes': parseInt($('zt-interval').value, 10) || 360,
+ };
+ // Only send the API key when the user actually typed one — an empty
+ // value would be a no-op server-side anyway, but skipping it avoids
+ // ever transmitting a blank over the wire.
+ const key = $('zt-api-key').value;
+ if (key) payload['zotero.api_key'] = key;
+ return payload;
+ }
+
+ async function loadConfig() {
+ const c = await getJSON('/library/api/zotero/config');
+ if (!c.success) { setSaveMsg(c.error || 'Could not load current settings.', false); return; }
+ fillForm(c);
+ }
+
+ $('zt-local').addEventListener('change', updateLocalModeUI);
+ $('zt-auto-sync').addEventListener('change', updateAutoSyncUI);
+
+ $('zotero-config-form').addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const btn = $('zotero-save');
+ btn.disabled = true;
+ setSaveMsg('Saving…');
+ try {
+ const r = await fetch('/settings/save_all_settings', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrf },
+ body: JSON.stringify(collectPayload()),
+ });
+ const data = await r.json().catch(() => ({}));
+ if (r.ok && data.status === 'success') {
+ setSaveMsg('Saved.', true);
+ // Refresh only the derived state (action gating + key placeholder);
+ // do NOT re-fill the inputs — that would clobber anything the user
+ // typed during the save round-trip.
+ try {
+ const c2 = await getJSON('/library/api/zotero/config');
+ if (c2.success) {
+ gateActions(!!c2.configured);
+ $('zt-api-key').placeholder = c2.has_api_key
+ ? '•••••••• saved — leave blank to keep' : 'Zotero API key';
+ }
+ } catch (e) { /* non-fatal: settings were saved regardless */ }
+ } else {
+ // save_all_settings returns errors as objects: {key, name, error}.
+ const errList = (data.errors || []).map(
+ (e) => (e && typeof e === 'object') ? `${e.name || e.key || ''}: ${e.error || ''}` : String(e)
+ );
+ const err = errList.join('; ') || data.message || 'Could not save settings.';
+ setSaveMsg(err, false);
+ }
+ } catch (e) {
+ setSaveMsg('Could not save settings.', false);
+ } finally {
+ btn.disabled = false;
+ }
+ });
+
+ // ---- Sync status ----------------------------------------------------
+
+ function statusBadge(st) {
+ const s = String(st ?? '').toLowerCase();
+ const kind = s === 'completed' ? 'ok' : s === 'failed' ? 'err'
+ : s === 'syncing' ? 'run' : 'muted';
+ return `<span class="ldr-zotero-badge ldr-zotero-badge-${kind}">${esc(st || '—')}</span>`;
+ }
+
+ async function loadStatus() {
+ // Returns true while any collection is still syncing. Must never reject:
+ // it is polled on an interval while a sync runs, and a rejection there
+ // would stall the Sync button's restore loop.
+ const el = $('zotero-status');
+ try {
+ const s = await getJSON('/library/api/zotero/status');
+ if (!s.success || !s.collections || !s.collections.length) {
+ el.innerHTML = '<div class="ldr-zotero-empty">No syncs yet.</div>';
+ return false;
+ }
+ let anySyncing = false;
+ const head = '<table class="ldr-zotero-table"><thead><tr><th>Collection</th><th>Status</th><th>Items</th><th>Last sync</th></tr></thead><tbody>';
+ const body = s.collections.map(c => {
+ const st = String(c.last_status ?? '').toLowerCase();
+ if (st === 'syncing') anySyncing = true;
+ const when = c.last_synced_at ? new Date(c.last_synced_at).toLocaleString() : '—';
+ const name = c.collection_key || 'Entire library';
+ // Show last_error whenever present: a "completed" run can
+ // still carry contained per-item failures worth surfacing.
+ const err = c.last_error
+ ? `<div class="ldr-zotero-rowerr">${esc(c.last_error)}</div>` : '';
+ return `<tr><td>${esc(name)}</td><td>${statusBadge(c.last_status)}${err}</td><td>${esc(c.item_count)}</td><td>${esc(when)}</td></tr>`;
+ }).join('');
+ el.innerHTML = head + body + '</tbody></table>';
+ return anySyncing;
+ } catch (e) {
+ // Transient error — keep the previous content and let polling continue.
+ return false;
+ }
+ }
+
+ // ---- Actions --------------------------------------------------------
+
+ $('zotero-test').addEventListener('click', async () => {
+ const b = $('zotero-test');
+ b.disabled = true;
+ setMsg('Testing…');
+ try {
+ const r = await postJSON('/library/api/zotero/test');
+ if (r.success) setMsg(`Connected. Library version ${r.library_version}, ${r.collection_count} collections.`, true);
+ else setMsg(r.error || 'Connection failed.', false);
+ } catch (e) { setMsg('Connection failed.', false); }
+ finally { b.disabled = false; }
+ });
+
+ $('zotero-list').addEventListener('click', async () => {
+ const listBtn = $('zotero-list');
+ if (listBtn.disabled) return;
+ listBtn.disabled = true;
+ setMsg('Loading collections…');
+ try {
+ const r = await getJSON('/library/api/zotero/collections');
+ if (!r.success) { setMsg(r.error || 'Failed to list collections.', false); return; }
+ const body = $('zotero-collections-body');
+ body.innerHTML = (r.collections || []).map(c =>
+ `<tr><td>${esc(c.name) || '(untitled)'}</td><td><button type="button" class="ldr-zotero-keybtn" title="Add to Collections" data-key="${esc(c.key)}">${esc(c.key)}</button></td></tr>`
+ ).join('') || '<tr><td colspan="2" class="ldr-zotero-empty">No collections found.</td></tr>';
+ const card = $('zotero-collections-card');
+ card.style.display = '';
+ card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ body.querySelectorAll('.ldr-zotero-keybtn').forEach(btn => {
+ btn.addEventListener('click', () => {
+ // Add the clicked key to the Collections field (dedup).
+ const field = $('zt-collections');
+ const keys = field.value.split(',').map(k => k.trim()).filter(Boolean);
+ if (!keys.includes(btn.dataset.key)) keys.push(btn.dataset.key);
+ field.value = keys.join(', ');
+ setSaveMsg('Added collection ' + btn.dataset.key + ' — click Save settings to apply.', true);
+ });
+ });
+ setMsg(`Found ${(r.collections || []).length} collections.`, true);
+ } catch (e) { setMsg('Failed to list collections.', false); }
+ finally { listBtn.disabled = false; }
+ });
+
+ $('zotero-groups').addEventListener('click', async () => {
+ const groupsBtn = $('zotero-groups');
+ if (groupsBtn.disabled) return;
+ groupsBtn.disabled = true;
+ setMsg('Loading groups…');
+ try {
+ const r = await getJSON('/library/api/zotero/groups');
+ if (!r.success) { setMsg(r.error || 'Failed to list groups.', false); return; }
+ const body = $('zotero-groups-body');
+ body.innerHTML = (r.groups || []).map(g =>
+ `<tr><td>${esc(g.name) || '(untitled)'}</td><td><button type="button" class="ldr-zotero-keybtn" title="Use this group" data-key="${esc(g.id)}">${esc(g.id)}</button></td></tr>`
+ ).join('') || '<tr><td colspan="2" class="ldr-zotero-empty">No groups found.</td></tr>';
+ const card = $('zotero-groups-card');
+ card.style.display = '';
+ card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ body.querySelectorAll('.ldr-zotero-keybtn').forEach(btn => {
+ btn.addEventListener('click', () => {
+ // Point the library at this group.
+ $('zt-library-type').value = 'group';
+ $('zt-library-id').value = btn.dataset.key;
+ setSaveMsg('Set library to group ' + btn.dataset.key + ' — click Save settings to apply.', true);
+ });
+ });
+ setMsg(`Found ${(r.groups || []).length} groups.`, true);
+ } catch (e) { setMsg('Failed to list groups.', false); }
+ finally { groupsBtn.disabled = false; }
+ });
+
+ $('zotero-sync').addEventListener('click', async () => {
+ const btn = $('zotero-sync');
+ if (btn.disabled) return;
+ const orig = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = 'Syncing…';
+ const restore = () => { btn.disabled = false; btn.textContent = orig; };
+ setMsg('Starting sync…');
+ try {
+ const r = await postJSON('/library/api/zotero/sync');
+ if (r.success) {
+ setMsg('Sync started in the background. Status updates below.', true);
+ // Poll until the sync actually finishes (not a fixed window):
+ // stop once a seen "syncing" clears, if none appears within the
+ // grace window, or after a hard cap — so a large-library sync
+ // isn't cut off and the button doesn't restore prematurely.
+ let elapsed = 0, sawSyncing = false;
+ const STEP = 5000, GRACE = 20000, MAX = 15 * 60 * 1000;
+ const t = setInterval(async () => {
+ const syncing = await loadStatus();
+ if (syncing) sawSyncing = true;
+ elapsed += STEP;
+ if ((sawSyncing && !syncing) || (!sawSyncing && elapsed >= GRACE) || elapsed >= MAX) {
+ clearInterval(t);
+ restore();
+ if (sawSyncing && !syncing) setMsg('Sync finished.', true);
+ }
+ }, STEP);
+ } else {
+ setMsg(r.error || 'Could not start sync.', false);
+ restore();
+ }
+ } catch (e) { setMsg('Could not start sync.', false); restore(); }
+ });
+
+ $('zotero-refresh').addEventListener('click', () => { loadStatus(); });
+
+ loadConfig().catch(() => setSaveMsg('Could not load current settings.', false));
+ loadStatus();
+})();
+</script>
+{% endblock %}
diff --git a/tests/database/test_library_init.py b/tests/database/test_library_init.py
index b256d86103..5ba27f3953 100644
--- a/tests/database/test_library_init.py
+++ b/tests/database/test_library_init.py
@@ -43,9 +43,10 @@ class TestSeedSourceTypes:
seed_source_types("testuser", "testpass")
- # Should have queried for each type and added 5 new ones
- # (research_download, user_upload, manual_entry, research_report, research_source)
- assert mock_session.add.call_count == 5
+ # Should have queried for each type and added 6 new ones
+ # (research_download, user_upload, manual_entry, research_report,
+ # research_source, zotero)
+ assert mock_session.add.call_count == 6
mock_session.commit.assert_called_once()
@patch("local_deep_research.database.library_init.get_user_db_session")
diff --git a/tests/database/test_migration_0018_remove_mcp_strategy.py b/tests/database/test_migration_0018_remove_mcp_strategy.py
index af98a14c2d..3d890b7bce 100644
--- a/tests/database/test_migration_0018_remove_mcp_strategy.py
+++ b/tests/database/test_migration_0018_remove_mcp_strategy.py
@@ -368,7 +368,7 @@ class TestMigration0018HeadAlignment:
rev_0018 = script.get_revision("0018")
assert rev_0018.down_revision == "0017"
- # NOTE: the head-alignment guard (assert head == latest) now lives in the
- # newest migration's test file — see TestMigration0019HeadAlignment in
- # test_migration_0019_retire_both_egress_scope.py. 0018 is no longer the
- # head, so asserting it here would break every future migration.
+ # NOTE: the head-alignment guard (assert head == latest) always lives in
+ # the newest migration's test file — currently
+ # test_migration_0020_add_zotero_tables.py. 0018 is no longer the head,
+ # so asserting it here would break every future migration.
diff --git a/tests/database/test_migration_0019_retire_both_egress_scope.py b/tests/database/test_migration_0019_retire_both_egress_scope.py
index a8f296cfb3..af095b5cd1 100644
--- a/tests/database/test_migration_0019_retire_both_egress_scope.py
+++ b/tests/database/test_migration_0019_retire_both_egress_scope.py
@@ -144,9 +144,7 @@ class TestMigration0019HeadAlignment:
rev_0019 = script.get_revision("0019")
assert rev_0019.down_revision == "0018"
- def test_head_revision_is_0019(self):
- from local_deep_research.database.alembic_runner import (
- get_head_revision,
- )
-
- assert get_head_revision() == "0019"
+ # NOTE: the head-alignment guard (assert head == latest) moved to the
+ # newest migration's test file — test_migration_0020_add_zotero_tables.py.
+ # 0019 is no longer the head, so asserting it here would break every
+ # future migration.
diff --git a/tests/database/test_migration_0020_add_zotero_tables.py b/tests/database/test_migration_0020_add_zotero_tables.py
new file mode 100644
index 0000000000..6e611ed301
--- /dev/null
+++ b/tests/database/test_migration_0020_add_zotero_tables.py
@@ -0,0 +1,163 @@
+"""Tests for migration 0020: add the Zotero integration tables.
+
+Verifies the migration chains correctly after 0019 and is the current head,
+and that the upgrade creates the two Zotero tables. Also holds the
+head-alignment guard (0020 is the newest migration); when a later migration
+is added, move this guard to that migration's test file.
+"""
+
+import pytest
+from alembic import command
+from alembic.config import Config
+from alembic.script import ScriptDirectory
+from sqlalchemy import create_engine, inspect, text
+from sqlalchemy.exc import IntegrityError
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+ get_head_revision,
+ get_migrations_dir,
+ run_migrations,
+)
+
+
+def test_0020_chains_after_0019():
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ rev = script.get_revision("0020")
+ assert rev.down_revision == "0019"
+
+
+def test_head_revision_is_0020():
+ # 0020 (add zotero tables) is the newest migration. If you add a later
+ # migration, move this guard to its test file.
+ assert get_head_revision() == "0020"
+
+
+def test_upgrade_creates_zotero_tables(tmp_path):
+ engine = create_engine(f"sqlite:///{tmp_path / 'test_0020.db'}")
+ run_migrations(engine) # up to head (includes 0020)
+ tables = set(inspect(engine).get_table_names())
+ assert "zotero_sync_state" in tables
+ assert "zotero_item_map" in tables
+ engine.dispose()
+
+
+def _migrated_engine(tmp_path, name="test_0020.db"):
+ engine = create_engine(f"sqlite:///{tmp_path / name}")
+ run_migrations(engine)
+ return engine
+
+
+def _run_alembic(engine, direction, target):
+ """Run an alembic upgrade/downgrade, wiring the connection into the config
+ the way alembic_runner.run_migrations does (this project's env.py requires
+ config.attributes['connection'])."""
+ config = get_alembic_config(engine)
+ with engine.connect() as conn:
+ with conn.begin():
+ config.attributes["connection"] = conn
+ getattr(command, direction)(config, target)
+
+
+def test_upgrade_creates_unique_constraints(tmp_path):
+ # Production per-user DBs are built PURELY from the Alembic chain (not
+ # create_all), and the sync service relies on these UNIQUE constraints as
+ # its race backstop. Assert the migration actually shipped them.
+ engine = _migrated_engine(tmp_path)
+ insp = inspect(engine)
+
+ item_uqs = insp.get_unique_constraints("zotero_item_map")
+ assert any(
+ set(uq["column_names"]) == {"ldr_collection_id", "zotero_item_key"}
+ for uq in item_uqs
+ ), item_uqs
+
+ state_uqs = insp.get_unique_constraints("zotero_sync_state")
+ assert any(
+ set(uq["column_names"])
+ == {"library_type", "library_id", "collection_key"}
+ for uq in state_uqs
+ ), state_uqs
+ engine.dispose()
+
+
+def test_upgrade_creates_expected_indexes(tmp_path):
+ engine = _migrated_engine(tmp_path)
+ insp = inspect(engine)
+ item_indexes = {ix["name"] for ix in insp.get_indexes("zotero_item_map")}
+ state_indexes = {ix["name"] for ix in insp.get_indexes("zotero_sync_state")}
+ assert "ix_zotero_item_map_ldr_collection_id" in item_indexes
+ assert "ix_zotero_item_map_zotero_item_key" in item_indexes
+ assert "ix_zotero_item_map_document_id" in item_indexes
+ assert "ix_zotero_sync_state_ldr_collection_id" in state_indexes
+ engine.dispose()
+
+
+def test_upgrade_foreign_keys(tmp_path):
+ engine = _migrated_engine(tmp_path)
+ insp = inspect(engine)
+ fks = {
+ fk["constrained_columns"][0]: fk
+ for fk in insp.get_foreign_keys("zotero_item_map")
+ }
+ assert fks["ldr_collection_id"]["referred_table"] == "collections"
+ assert fks["document_id"]["referred_table"] == "documents"
+ # ondelete: CASCADE for the owning collection, SET NULL for the document
+ # (the sync service treats a null document as "needs re-import").
+ assert (
+ fks["ldr_collection_id"].get("options", {}).get("ondelete", "").upper()
+ == "CASCADE"
+ )
+ assert (
+ fks["document_id"].get("options", {}).get("ondelete", "").upper()
+ == "SET NULL"
+ )
+ engine.dispose()
+
+
+def test_item_map_unique_constraint_is_enforced(tmp_path):
+ # Behavioral proof (against the migration-built schema) that a duplicate
+ # (ldr_collection_id, zotero_item_key) is rejected.
+ engine = _migrated_engine(tmp_path)
+ ts = "2020-01-01 00:00:00"
+ insert = text(
+ "INSERT INTO zotero_item_map "
+ "(ldr_collection_id, zotero_item_key, zotero_version, has_pdf, "
+ "created_at, updated_at) "
+ "VALUES ('c1', 'K1', :v, 0, :ts, :ts)"
+ )
+ with engine.begin() as conn:
+ conn.execute(insert, {"v": 1, "ts": ts})
+ with pytest.raises(IntegrityError):
+ with engine.begin() as conn:
+ conn.execute(insert, {"v": 2, "ts": ts})
+ engine.dispose()
+
+
+def test_downgrade_then_upgrade_roundtrip(tmp_path):
+ engine = _migrated_engine(tmp_path)
+
+ # Downgrade removes both tables...
+ _run_alembic(engine, "downgrade", "0019")
+ tables = set(inspect(engine).get_table_names())
+ assert "zotero_sync_state" not in tables
+ assert "zotero_item_map" not in tables
+
+ # ...and re-upgrading recreates them (exercises the has_table guards).
+ _run_alembic(engine, "upgrade", "0020")
+ tables = set(inspect(engine).get_table_names())
+ assert "zotero_sync_state" in tables
+ assert "zotero_item_map" in tables
+ engine.dispose()
+
+
+def test_upgrade_is_idempotent(tmp_path):
+ # Running the migration runner a second time must not error.
+ engine = _migrated_engine(tmp_path)
+ run_migrations(engine)
+ tables = set(inspect(engine).get_table_names())
+ assert "zotero_sync_state" in tables
+ assert "zotero_item_map" in tables
+ engine.dispose()
diff --git a/tests/database/test_schema_stability.py b/tests/database/test_schema_stability.py
index 1fbbcd3340..58ca8b303a 100644
--- a/tests/database/test_schema_stability.py
+++ b/tests/database/test_schema_stability.py
@@ -90,6 +90,9 @@ EXPECTED_TABLES = {
"chat_sessions",
"chat_messages",
"chat_progress_steps",
+ # Zotero
+ "zotero_sync_state",
+ "zotero_item_map",
}
diff --git a/tests/research_library/zotero/__init__.py b/tests/research_library/zotero/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/research_library/zotero/test_client.py b/tests/research_library/zotero/test_client.py
new file mode 100644
index 0000000000..c3cad1f7b6
--- /dev/null
+++ b/tests/research_library/zotero/test_client.py
@@ -0,0 +1,532 @@
+"""Unit tests for the Zotero Web API client.
+
+The client's HTTP layer (``SafeSession``) is replaced with a mock so these
+tests exercise pagination, parsing, batching, retry and error handling
+without any network access.
+"""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from local_deep_research.research_library.zotero.client import (
+ ZoteroAuthError,
+ ZoteroClient,
+ ZoteroError,
+ ZoteroTransientError,
+)
+
+
+class FakeResponse:
+ def __init__(
+ self, status_code=200, json_data=None, headers=None, content=b""
+ ):
+ self.status_code = status_code
+ self._json = json_data
+ self._has_json = json_data is not None
+ self.headers = headers or {}
+ self.content = content
+
+ def json(self):
+ # Mirror requests.Response: calling .json() on a non-JSON / empty body
+ # raises rather than silently returning {}.
+ if not self._has_json:
+ raise ValueError("No JSON object could be decoded")
+ return self._json
+
+
+def make_client():
+ client = ZoteroClient(
+ api_key="KEY", library_type="user", library_id="12345"
+ )
+ client.session = MagicMock()
+ return client
+
+
+def test_init_validates_inputs():
+ with pytest.raises(ValueError):
+ ZoteroClient(api_key="", library_type="user", library_id="1")
+ with pytest.raises(ValueError):
+ ZoteroClient(api_key="k", library_type="bogus", library_id="1")
+ with pytest.raises(ValueError):
+ ZoteroClient(api_key="k", library_type="user", library_id="")
+
+
+def test_prefix_user_vs_group():
+ u = ZoteroClient(api_key="k", library_type="user", library_id="7")
+ g = ZoteroClient(api_key="k", library_type="group", library_id="9")
+ assert u._prefix == "/users/7"
+ assert g._prefix == "/groups/9"
+
+
+def test_local_mode_no_key_required_and_base_url():
+ # Local mode: API key optional, base points at the desktop local API.
+ c = ZoteroClient(
+ api_key="", library_type="user", library_id="7", local=True
+ )
+ assert c._base == "http://localhost:23119/api"
+ assert "Zotero-API-Key" not in c.session.headers
+ # Cloud mode still requires a key.
+ with pytest.raises(ValueError):
+ ZoteroClient(api_key="", library_type="user", library_id="7")
+
+
+def test_local_download_reads_file_url(tmp_path):
+ f = tmp_path / "paper.pdf"
+ f.write_bytes(b"%PDF-local-bytes")
+ client = ZoteroClient(
+ api_key="", library_type="user", library_id="7", local=True
+ )
+ client.session = MagicMock()
+ client.session.get.return_value = FakeResponse(
+ 302, headers={"Location": f.as_uri()}
+ )
+ assert client.download_attachment("ATT1") == b"%PDF-local-bytes"
+
+
+def test_local_download_rejects_non_pdf_file(tmp_path):
+ """A file:// redirect target without a PDF magic number is not returned —
+ the local API port is unauthenticated, so this must not become a generic
+ local-file disclosure primitive."""
+ f = tmp_path / "secrets.txt"
+ f.write_bytes(b"root:x:0:0:than which nothing less pdf-like exists")
+ client = ZoteroClient(
+ api_key="", library_type="user", library_id="7", local=True
+ )
+ client.session = MagicMock()
+ client.session.get.return_value = FakeResponse(
+ 302, headers={"Location": f.as_uri()}
+ )
+ assert client.download_attachment("ATT1") is None
+
+
+def test_cloud_mode_ignores_file_redirect():
+ client = make_client() # cloud mode
+ client.session.get.return_value = FakeResponse(
+ 302, headers={"Location": "file:///etc/passwd"}
+ )
+ assert client.download_attachment("ATT1") is None
+
+
+def test_get_groups_empty_in_local_mode():
+ client = ZoteroClient(
+ api_key="", library_type="user", library_id="7", local=True
+ )
+ client.session = MagicMock()
+ assert client.get_groups() == []
+ client.session.get.assert_not_called()
+
+
+def test_test_connection_returns_library_version():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200, json_data={}, headers={"Last-Modified-Version": "42"}
+ )
+ assert client.test_connection() == 42
+
+
+def test_get_collections_paginates():
+ client = make_client()
+
+ def page(n, count):
+ return FakeResponse(
+ 200,
+ json_data=[
+ {"key": f"K{n}_{i}", "data": {"name": f"C{n}_{i}"}}
+ for i in range(count)
+ ],
+ )
+
+ # First page full (100), second page short (5) -> stop.
+ client.session.get.side_effect = [page(1, 100), page(2, 5)]
+ collections = client.get_collections()
+ assert len(collections) == 105
+ assert collections[0]["key"] == "K1_0"
+ assert collections[0]["name"] == "C1_0"
+
+
+def test_get_top_item_versions_parses_object_and_library_version():
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(
+ 200,
+ json_data={"AAA": 3, "BBB": 7},
+ headers={"Last-Modified-Version": "7", "Total-Results": "2"},
+ )
+ ]
+ versions, library_version = client.get_top_item_versions("COLLKEY")
+ assert versions == {"AAA": 3, "BBB": 7}
+ assert library_version == 7
+ # Scoped to the collection path.
+ called_url = client.session.get.call_args_list[0].args[0]
+ assert "/collections/COLLKEY/items/top" in called_url
+
+
+def test_get_items_batches_over_50():
+ client = make_client()
+ keys = [f"K{i:03d}" for i in range(60)]
+ client.session.get.side_effect = [
+ FakeResponse(
+ 200,
+ json_data=[
+ {"key": k, "version": 1, "data": {"itemType": "journalArticle"}}
+ for k in keys[:50]
+ ],
+ ),
+ FakeResponse(
+ 200,
+ json_data=[
+ {"key": k, "version": 1, "data": {"itemType": "journalArticle"}}
+ for k in keys[50:]
+ ],
+ ),
+ ]
+ items = client.get_items(keys)
+ assert len(items) == 60
+ assert client.session.get.call_count == 2
+ # First batch carries exactly 50 keys.
+ first_params = client.session.get.call_args_list[0].kwargs["params"]
+ assert len(first_params["itemKey"].split(",")) == 50
+
+
+def test_get_children_filters_non_attachments():
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(
+ 200,
+ json_data=[
+ {
+ "key": "ATT1",
+ "version": 5,
+ "data": {
+ "itemType": "attachment",
+ "contentType": "application/pdf",
+ "linkMode": "imported_file",
+ "filename": "paper.pdf",
+ "title": "Full Text",
+ },
+ },
+ {
+ "key": "NOTE1",
+ "version": 6,
+ "data": {"itemType": "note"},
+ },
+ ],
+ )
+ ]
+ children = client.get_children("PARENT")
+ assert len(children) == 1
+ att = children[0]
+ assert att.key == "ATT1"
+ assert att.is_downloadable_pdf is True
+
+
+def test_get_notes_strips_html():
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(
+ 200,
+ json_data=[
+ {
+ "key": "NOTE1",
+ "data": {
+ "itemType": "note",
+ "note": "<p>First &amp; second</p><p>line two</p>",
+ },
+ },
+ {"key": "ATT", "data": {"itemType": "attachment"}},
+ ],
+ )
+ ]
+ notes = client.get_notes("ITEM")
+ assert notes == ["First & second\nline two"]
+
+
+def test_get_annotations_combines_text_and_comment():
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(
+ 200,
+ json_data=[
+ {
+ "key": "ANN1",
+ "data": {
+ "itemType": "annotation",
+ "annotationText": "important passage",
+ "annotationComment": "my thought",
+ },
+ },
+ {
+ "key": "ANN2",
+ "data": {
+ "itemType": "annotation",
+ "annotationType": "image", # no text -> skipped
+ },
+ },
+ ],
+ )
+ ]
+ anns = client.get_annotations("ATT")
+ assert anns == ["important passage — [note] my thought"]
+
+
+def test_download_attachment_returns_bytes():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(200, content=b"%PDF-1.7 x")
+ assert client.download_attachment("ATT1") == b"%PDF-1.7 x"
+
+
+def test_403_raises_auth_error():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(403)
+ with pytest.raises(ZoteroAuthError):
+ client.test_connection()
+
+
+def test_404_raises_zotero_error():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(404)
+ with pytest.raises(ZoteroError):
+ client.get_collections()
+
+
+def test_retry_on_429_then_success(monkeypatch):
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.time.sleep",
+ lambda *_a, **_k: None,
+ )
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(429, headers={"Backoff": "0"}),
+ FakeResponse(200, json_data=[], headers={"Last-Modified-Version": "1"}),
+ ]
+ # get_collections should retry past the 429 and succeed (empty list).
+ assert client.get_collections() == []
+ assert client.session.get.call_count == 2
+
+
+def test_transient_error_raised_after_retry_exhaustion(monkeypatch):
+ # 429 on every attempt exhausts the retries and must raise the *transient*
+ # subclass, not a bare ZoteroError — so per-item callers can tell it apart
+ # from a genuine "no file".
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.time.sleep",
+ lambda *_a, **_k: None,
+ )
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(429, headers={"Backoff": "0"}) for _ in range(4)
+ ]
+ with pytest.raises(ZoteroTransientError):
+ client.get_collections()
+ assert client.session.get.call_count == 4
+
+
+def test_download_attachment_reraises_transient_error(monkeypatch):
+ # A rate-limit blip on the /file request must propagate (so the sync skips
+ # the item and retries next run) rather than be swallowed to None, which
+ # would silently import the paper metadata-only forever.
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.time.sleep",
+ lambda *_a, **_k: None,
+ )
+ client = make_client()
+ client.session.get.side_effect = [FakeResponse(503) for _ in range(4)]
+ with pytest.raises(ZoteroTransientError):
+ client.download_attachment("ATT1")
+
+
+def test_download_attachment_returns_none_on_404():
+ # A genuine "this attachment has no downloadable file" (404) is NOT
+ # transient — return None so the item imports metadata-only.
+ client = make_client()
+ client.session.get.return_value = FakeResponse(404)
+ assert client.download_attachment("ATT1") is None
+
+
+def test_get_attachment_fulltext_reraises_transient_error(monkeypatch):
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.time.sleep",
+ lambda *_a, **_k: None,
+ )
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(429, headers={"Backoff": "0"}) for _ in range(4)
+ ]
+ with pytest.raises(ZoteroTransientError):
+ client.get_attachment_fulltext("ATT1")
+
+
+def test_local_mode_omits_key_header_even_when_configured():
+ # Security: the desktop local API is plaintext HTTP on loopback and needs
+ # no key. Even if the user has an API key set, it must never be attached to
+ # local-mode requests.
+ c = ZoteroClient(
+ api_key="SECRETKEY", library_type="user", library_id="7", local=True
+ )
+ assert "Zotero-API-Key" not in c.session.headers
+ # Cloud mode DOES attach it.
+ c2 = ZoteroClient(api_key="SECRETKEY", library_type="user", library_id="7")
+ assert c2.session.headers.get("Zotero-API-Key") == "SECRETKEY"
+
+
+def test_non_transient_error_is_not_retried():
+ # SafeSession raises ValueError on SSRF / oversized body. That is not a
+ # transient error and must NOT be retried 4x.
+ client = make_client()
+ client.session.get.side_effect = ValueError("possible SSRF")
+ with pytest.raises(ZoteroError):
+ client.get_collections()
+ assert client.session.get.call_count == 1
+
+
+def test_top_item_versions_paginates_without_total_results_header():
+ # Regression: when Total-Results is absent and the first page is exactly
+ # full, the loop must NOT stop early (which would silently drop items and
+ # the sync would treat them as deletions).
+ client = make_client()
+ full_page = {f"K{i:03d}": 1 for i in range(100)} # exactly _PAGE_LIMIT
+ short_page = {"K100": 1, "K101": 1, "K102": 1}
+ client.session.get.side_effect = [
+ FakeResponse(200, json_data=full_page, headers={}), # no Total-Results
+ FakeResponse(200, json_data=short_page, headers={}),
+ ]
+ versions, _ = client.get_top_item_versions(None)
+ assert len(versions) == 103
+ assert client.session.get.call_count == 2
+
+
+def test_download_attachment_does_not_leak_key_on_redirect(monkeypatch):
+ # The /file endpoint 302-redirects to storage. We must follow that with a
+ # fresh credential-free session, never the authenticated one.
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 302, headers={"Location": "https://files.example.com/abc"}
+ )
+
+ clean = MagicMock()
+ clean.get.return_value = FakeResponse(200, content=b"PDFBYTES")
+ clean.__enter__ = MagicMock(return_value=clean)
+ clean.__exit__ = MagicMock(return_value=False)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.SafeSession",
+ lambda *a, **k: clean,
+ )
+
+ result = client.download_attachment("ATT1")
+ assert result == b"PDFBYTES"
+ # Initial request used allow_redirects=False on the AUTHENTICATED session.
+ assert client.session.get.call_args.kwargs.get("allow_redirects") is False
+ # The redirect target was fetched by a DIFFERENT (credential-free) session.
+ assert clean.get.call_args.args[0] == "https://files.example.com/abc"
+ assert clean is not client.session
+
+
+def test_download_attachment_direct_200_no_redirect():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(200, content=b"DIRECT")
+ assert client.download_attachment("ATT1") == b"DIRECT"
+
+
+def test_download_attachment_reraises_transient_from_storage(monkeypatch):
+ # A transient failure (5xx) fetching the REDIRECTED storage URL must
+ # propagate so the sync retries next run, not be swallowed to None (which
+ # would import the paper metadata-only forever).
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 302, headers={"Location": "https://files.example.com/abc"}
+ )
+ clean = MagicMock()
+ clean.get.return_value = FakeResponse(503)
+ clean.__enter__ = MagicMock(return_value=clean)
+ clean.__exit__ = MagicMock(return_value=False)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client.SafeSession",
+ lambda *a, **k: clean,
+ )
+ with pytest.raises(ZoteroTransientError):
+ client.download_attachment("ATT1")
+
+
+def test_get_groups_resolves_user_then_lists():
+ client = make_client()
+ client.session.get.side_effect = [
+ FakeResponse(200, json_data={"userID": 99, "username": "x"}),
+ FakeResponse(
+ 200,
+ json_data=[{"id": 123, "data": {"name": "Lab", "type": "Private"}}],
+ ),
+ ]
+ groups = client.get_groups()
+ assert groups == [{"id": "123", "name": "Lab", "type": "Private"}]
+ # First call hits the non-prefixed /keys/current endpoint.
+ assert (
+ client.session.get.call_args_list[0].args[0].endswith("/keys/current")
+ )
+ # Second call hits /users/99/groups (also non-prefixed).
+ assert "/users/99/groups" in client.session.get.call_args_list[1].args[0]
+
+
+def test_get_groups_empty_when_no_user():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(200, json_data={})
+ assert client.get_groups() == []
+
+
+def test_get_attachment_fulltext_returns_content():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200, json_data={"content": "hello world", "indexedChars": 11}
+ )
+ assert client.get_attachment_fulltext("ATT1") == "hello world"
+
+
+def test_get_attachment_fulltext_none_when_not_indexed():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(404) # no indexed text
+ assert client.get_attachment_fulltext("ATT1") is None
+
+
+def test_get_attachment_fulltext_none_when_empty():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200, json_data={"content": ""}
+ )
+ assert client.get_attachment_fulltext("ATT1") is None
+
+
+def test_top_item_versions_raises_on_incomplete_map():
+ # Total-Results says 5 items exist, but the (short) page returns only 2.
+ # Returning that partial map would make the sync treat 3 items as
+ # deletions — so the client must raise instead.
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200, json_data={"A": 1, "B": 1}, headers={"Total-Results": "5"}
+ )
+ with pytest.raises(ZoteroError):
+ client.get_top_item_versions(None)
+
+
+def test_top_item_versions_complete_map_ok():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200,
+ json_data={"A": 1, "B": 2},
+ headers={"Total-Results": "2", "Last-Modified-Version": "9"},
+ )
+ versions, lib = client.get_top_item_versions(None)
+ assert versions == {"A": 1, "B": 2}
+ assert lib == 9
+
+
+def test_pagination_has_a_hard_safety_cap(monkeypatch):
+ # A server that returns a FULL page forever (ignores `start`, no
+ # Total-Results) must not loop unbounded — the page cap aborts it.
+ monkeypatch.setattr(
+ "local_deep_research.research_library.zotero.client._MAX_PAGES", 2
+ )
+ client = make_client()
+ full = [{"key": f"K{i}", "data": {"name": "n"}} for i in range(100)]
+ client.session.get.return_value = FakeResponse(200, json_data=full)
+ with pytest.raises(ZoteroError):
+ client.get_collections()
diff --git a/tests/research_library/zotero/test_client_integration.py b/tests/research_library/zotero/test_client_integration.py
new file mode 100644
index 0000000000..330f5a27e1
--- /dev/null
+++ b/tests/research_library/zotero/test_client_integration.py
@@ -0,0 +1,213 @@
+"""Live integration tests for the Zotero Web API client.
+
+The unit tests in ``test_client.py`` mock the HTTP layer, so they only verify
+the client against our *assumptions* about the API. These tests hit the REAL
+Zotero Web API (``api.zotero.org``) to confirm those assumptions still hold and
+the client works end-to-end.
+
+Marked ``@pytest.mark.integration`` — skipped in CI mock mode; run with::
+
+ LDR_TESTING_WITH_MOCKS=false pytest \
+ tests/research_library/zotero/test_client_integration.py -v
+
+Two tiers:
+
+* **Contract (no credentials).** Read a real *public* Zotero group and assert
+ the live response shapes + headers are exactly what the client parses. Needs
+ only network access; catches a Zotero-side API change. Skips (never fails) if
+ the public group or the API is unreachable.
+* **Full client (needs a key).** Set ``ZOTERO_TEST_API_KEY`` (read-only is
+ enough) to exercise the real client end-to-end against your own library.
+ Optionally set ``ZOTERO_TEST_LIBRARY_TYPE`` / ``ZOTERO_TEST_LIBRARY_ID`` to
+ target a specific library instead of the key owner's user library.
+"""
+
+import os
+
+import pytest
+import requests
+
+from local_deep_research.research_library.zotero.client import (
+ ZOTERO_API_BASE,
+ ZOTERO_API_VERSION,
+ ZoteroClient,
+ ZoteroItem,
+)
+from local_deep_research.security import SafeSession
+
+pytestmark = pytest.mark.integration
+
+# A stable, read-only PUBLIC Zotero group for the no-credential contract checks
+# (overridable in case it ever goes away).
+_PUBLIC_GROUP_ID = os.environ.get("ZOTERO_TEST_PUBLIC_GROUP", "4507109")
+_API_KEY = os.environ.get("ZOTERO_TEST_API_KEY")
+
+
+def _get(path, params=None):
+ """GET a public (no-key) Zotero endpoint through the project's SafeSession
+ — the same HTTP layer the client uses. Returns the response, or ``None`` if
+ unreachable so callers can SKIP rather than fail on a network blip."""
+ url = f"{ZOTERO_API_BASE}{path}"
+ try:
+ with SafeSession() as session:
+ session.headers.update({"Zotero-API-Version": ZOTERO_API_VERSION})
+ return session.get(url, params=params, timeout=30)
+ except (
+ requests.exceptions.Timeout,
+ requests.exceptions.ConnectionError,
+ ):
+ return None
+
+
+def _public_group_or_skip(path, params=None):
+ r = _get(f"/groups/{_PUBLIC_GROUP_ID}{path}", params=params)
+ if r is None or r.status_code != 200:
+ pytest.skip(
+ f"public Zotero group {_PUBLIC_GROUP_ID} unavailable "
+ f"(HTTP {getattr(r, 'status_code', 'n/a')})"
+ )
+ return r
+
+
+# --- Tier 1: contract against the live API (no credentials) -----------------
+
+
+def test_live_api_reachable_and_speaks_v3():
+ r = _get("/itemTypes") # stable, no-auth schema endpoint
+ if r is None:
+ pytest.skip("Zotero API unreachable from this environment")
+ assert r.status_code == 200
+ assert r.headers.get("Zotero-API-Version") == ZOTERO_API_VERSION
+ assert isinstance(r.json(), list)
+
+
+def test_live_items_shape_matches_client_parsing():
+ # get_items reads entry['key'], entry['version'], entry['data']['itemType'].
+ # The paginators read the Total-Results / Last-Modified-Version headers.
+ r = _public_group_or_skip("/items/top", {"format": "json", "limit": 3})
+ assert "Total-Results" in r.headers
+ assert "Last-Modified-Version" in r.headers
+ entries = r.json()
+ assert isinstance(entries, list) and entries
+ for entry in entries:
+ assert isinstance(entry.get("key"), str) and entry["key"]
+ assert isinstance(entry.get("version"), int)
+ data = entry.get("data")
+ assert isinstance(data, dict)
+ assert isinstance(data.get("itemType"), str) and data["itemType"]
+
+
+def test_live_versions_shape_is_key_to_int():
+ # get_top_item_versions parses format=versions as {itemKey: intVersion}.
+ r = _public_group_or_skip("/items/top", {"format": "versions", "limit": 5})
+ obj = r.json()
+ assert isinstance(obj, dict) and obj
+ for key, version in obj.items():
+ assert isinstance(key, str) and key
+ assert int(version) >= 0 # client coerces the same way
+
+
+def test_live_collections_shape_matches_client_parsing():
+ # get_collections reads entry['key'] and entry['data']['name'].
+ r = _public_group_or_skip("/collections", {"format": "json", "limit": 1})
+ entries = r.json()
+ assert isinstance(entries, list)
+ for entry in entries:
+ assert isinstance(entry.get("key"), str) and entry["key"]
+ assert isinstance(entry.get("data", {}).get("name"), str)
+
+
+def test_live_bad_key_is_rejected_403():
+ # The client maps 403 -> ZoteroAuthError; confirm the live API really does
+ # reject an invalid key with 403 (even for otherwise-public content).
+ r = _get(
+ f"/groups/{_PUBLIC_GROUP_ID}/items/top",
+ params={"limit": 1},
+ )
+ if r is None:
+ pytest.skip("Zotero API unreachable")
+ # (no key on _get -> 200; re-request WITH a bogus key -> 403)
+ try:
+ with SafeSession() as session:
+ session.headers.update(
+ {
+ "Zotero-API-Version": ZOTERO_API_VERSION,
+ "Zotero-API-Key": "bogus_invalid_key_for_test",
+ }
+ )
+ bad = session.get(
+ f"{ZOTERO_API_BASE}/groups/{_PUBLIC_GROUP_ID}/items/top",
+ params={"limit": 1},
+ timeout=30,
+ )
+ except (
+ requests.exceptions.Timeout,
+ requests.exceptions.ConnectionError,
+ ):
+ pytest.skip("Zotero API unreachable")
+ assert bad.status_code == 403
+
+
+# --- Tier 2: full client end-to-end (needs a real API key) ------------------
+
+_needs_key = pytest.mark.skipif(
+ not _API_KEY,
+ reason="set ZOTERO_TEST_API_KEY to run the full-client live tests",
+)
+
+
+def _live_client():
+ """Build a read-only client for the key owner's user library (default) or
+ the library named by ``ZOTERO_TEST_LIBRARY_TYPE`` / ``_ID``."""
+ lib_type = os.environ.get("ZOTERO_TEST_LIBRARY_TYPE")
+ lib_id = os.environ.get("ZOTERO_TEST_LIBRARY_ID")
+ if not lib_id:
+ # Resolve the key owner's numeric userID via /keys/current.
+ probe = ZoteroClient(
+ api_key=_API_KEY, library_type="user", library_id="1"
+ )
+ try:
+ info = probe._request("/keys/current", prefixed=False).json()
+ finally:
+ probe.close()
+ lib_id = str(info.get("userID") or "")
+ lib_type = "user"
+ assert lib_id, "Zotero /keys/current returned no userID"
+ return ZoteroClient(
+ api_key=_API_KEY,
+ library_type=lib_type or "user",
+ library_id=lib_id,
+ )
+
+
+@_needs_key
+def test_full_client_connection_and_listing():
+ client = _live_client()
+ try:
+ version = client.test_connection()
+ assert isinstance(version, int) and version >= 0
+ assert isinstance(client.get_collections(), list)
+ versions, lib = client.get_top_item_versions()
+ assert isinstance(versions, dict)
+ assert isinstance(lib, int)
+ finally:
+ client.close()
+
+
+@_needs_key
+def test_full_client_item_and_children_roundtrip():
+ client = _live_client()
+ try:
+ versions, _ = client.get_top_item_versions()
+ if not versions:
+ pytest.skip("target Zotero library has no top-level items")
+ keys = list(versions)[:3]
+ items = client.get_items(keys)
+ assert {it.key for it in items} == set(keys)
+ for it in items:
+ assert isinstance(it, ZoteroItem)
+ assert it.item_type and isinstance(it.data, dict)
+ # Children of the first item (may be empty) — must round-trip, not raise.
+ assert isinstance(client.get_children(keys[0]), list)
+ finally:
+ client.close()
diff --git a/tests/research_library/zotero/test_faiss_cleanup.py b/tests/research_library/zotero/test_faiss_cleanup.py
new file mode 100644
index 0000000000..086442fae2
--- /dev/null
+++ b/tests/research_library/zotero/test_faiss_cleanup.py
@@ -0,0 +1,125 @@
+"""Tests for FAISS vector removal on document removal.
+
+These exercise ``LibraryRAGService.remove_documents_from_index`` (the new
+primitive the Zotero removal path uses) without a real FAISS index or
+embedding model: the index is a stub and the RAGIndex existence check is
+stubbed via the session.
+"""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+
+
+class _Doc:
+ def __init__(self, metadata):
+ self.metadata = metadata
+
+
+class _FakeDocstore:
+ def __init__(self, store):
+ self._dict = store
+
+
+class _FakeIndex:
+ def __init__(self, store):
+ self.docstore = _FakeDocstore(store)
+ self.deleted = []
+
+ def delete(self, ids):
+ self.deleted.extend(ids)
+
+
+def _svc_with_index(store):
+ # Build the service without running __init__ (no embeddings needed).
+ svc = LibraryRAGService.__new__(LibraryRAGService)
+ # The db_password setter propagates to these — set them first.
+ svc.embedding_manager = None
+ svc.integrity_manager = None
+ svc.username = "u"
+ svc.db_password = "pw" # gitleaks:allow
+ svc.faiss_index = _FakeIndex(store)
+ svc.rag_index_record = None # -> in-memory delete branch (no save_local)
+ return svc
+
+
+def _patch_has_index(monkeypatch, exists: bool):
+ @contextmanager
+ def fake_session(*_a, **_k):
+ sess = MagicMock()
+ sess.query.return_value.filter_by.return_value.first.return_value = (
+ object() if exists else None
+ )
+ yield sess
+
+ monkeypatch.setattr(
+ "local_deep_research.database.session_context.get_user_db_session",
+ fake_session,
+ )
+
+
+def test_remove_documents_from_index_selects_by_metadata(monkeypatch):
+ store = {
+ "c_1": _Doc({"document_id": "D1"}),
+ "c_2": _Doc({"document_id": "D1"}),
+ "c_3": _Doc({"source_id": "D2"}), # different doc
+ "c_4": _Doc({}), # unrelated
+ }
+ _patch_has_index(monkeypatch, True)
+ svc = _svc_with_index(store)
+
+ removed = svc.remove_documents_from_index(["D1"], "COLL")
+ assert removed == 2
+ assert set(svc.faiss_index.deleted) == {"c_1", "c_2"}
+
+
+def test_remove_documents_from_index_matches_source_id_too(monkeypatch):
+ store = {"c_3": _Doc({"source_id": "D2"})}
+ _patch_has_index(monkeypatch, True)
+ svc = _svc_with_index(store)
+ assert svc.remove_documents_from_index(["D2"], "COLL") == 1
+ assert svc.faiss_index.deleted == ["c_3"]
+
+
+def test_remove_documents_from_index_noop_without_index(monkeypatch):
+ _patch_has_index(monkeypatch, False)
+ svc = _svc_with_index({"c_1": _Doc({"document_id": "D1"})})
+ assert svc.remove_documents_from_index(["D1"], "COLL") == 0
+ assert svc.faiss_index.deleted == []
+
+
+def test_remove_documents_from_index_empty_ids(monkeypatch):
+ # No DB hit, no index touched.
+ svc = _svc_with_index({"c_1": _Doc({"document_id": "D1"})})
+ assert svc.remove_documents_from_index([], "COLL") == 0
+ assert svc.faiss_index.deleted == []
+
+
+def test_remove_document_from_rag_also_clears_vectors(monkeypatch):
+ # The general UI removal path must clear FAISS vectors too, not just DB
+ # chunks — it delegates to the new primitive.
+ svc = LibraryRAGService.__new__(LibraryRAGService)
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager._delete_chunks_from_db.return_value = 3
+ svc.integrity_manager = None
+ svc.username = "u"
+ svc._db_password = "pw" # gitleaks:allow
+ svc.remove_documents_from_index = MagicMock(return_value=2)
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield MagicMock() # DocumentCollection/Collection lookups -> truthy
+
+ monkeypatch.setattr(
+ "local_deep_research.research_library.services."
+ "library_rag_service.get_user_db_session",
+ fake_session,
+ )
+
+ result = svc.remove_document_from_rag("DOC1", "COLL1")
+ assert result["status"] == "success"
+ svc.embedding_manager._delete_chunks_from_db.assert_called_once()
+ svc.remove_documents_from_index.assert_called_once_with(["DOC1"], "COLL1")
diff --git a/tests/research_library/zotero/test_scheduler.py b/tests/research_library/zotero/test_scheduler.py
new file mode 100644
index 0000000000..b7a26df22d
--- /dev/null
+++ b/tests/research_library/zotero/test_scheduler.py
@@ -0,0 +1,129 @@
+"""Tests for the Zotero hooks on the BackgroundJobScheduler.
+
+The APScheduler instance and credential store are mocked, and
+ZoteroSyncService.get_config is stubbed, so these tests verify only the
+scheduling logic (enable/disable, interval clamp, reschedule gating).
+"""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from local_deep_research.research_library.zotero import ZoteroSyncService
+from local_deep_research.research_library.zotero.sync_service import (
+ ZoteroConfig,
+)
+from local_deep_research.scheduler.background import BackgroundJobScheduler
+
+
+def sched(monkeypatch):
+ s = BackgroundJobScheduler() # singleton; attrs restored by monkeypatch
+ monkeypatch.setattr(s, "scheduler", MagicMock())
+ monkeypatch.setattr(s, "is_running", True)
+ monkeypatch.setattr(s, "user_sessions", {"u": {"scheduled_jobs": set()}})
+ cred = MagicMock()
+ cred.retrieve.return_value = "pw" # gitleaks:allow
+ monkeypatch.setattr(s, "_credential_store", cred)
+ return s
+
+
+def _stub_config(monkeypatch, **kw):
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="1", **kw)
+ monkeypatch.setattr(ZoteroSyncService, "get_config", lambda self: cfg)
+ return cfg
+
+
+def test_schedule_enabled_adds_job(sched, monkeypatch):
+ _stub_config(monkeypatch, auto_sync_enabled=True, sync_interval_minutes=120)
+ sched._schedule_zotero_sync("u")
+ assert sched.scheduler.add_job.called
+ kwargs = sched.scheduler.add_job.call_args.kwargs
+ assert kwargs["id"] == "u_zotero_sync"
+ assert kwargs["minutes"] == 120
+ assert "u_zotero_sync" in sched.user_sessions["u"]["scheduled_jobs"]
+
+
+def test_schedule_clamps_interval_to_15(sched, monkeypatch):
+ _stub_config(monkeypatch, auto_sync_enabled=True, sync_interval_minutes=5)
+ sched._schedule_zotero_sync("u")
+ assert sched.scheduler.add_job.call_args.kwargs["minutes"] == 15
+
+
+def test_schedule_disabled_unschedules_and_skips_add(sched, monkeypatch):
+ _stub_config(monkeypatch, auto_sync_enabled=False)
+ sched._schedule_zotero_sync("u")
+ assert sched.scheduler.remove_job.called # tries to unschedule
+ assert not sched.scheduler.add_job.called
+
+
+def test_schedule_unschedules_even_when_credentials_expired(sched, monkeypatch):
+ """Disabling auto-sync after the cached credentials expired must still
+ remove the old interval job — it would otherwise keep ticking (and
+ logging a credentials warning) until logout."""
+ sched._credential_store.retrieve.return_value = None
+ sched._schedule_zotero_sync("u")
+ assert sched.scheduler.remove_job.called
+ assert not sched.scheduler.add_job.called
+
+
+def test_schedule_keeps_existing_job_when_config_read_fails(sched, monkeypatch):
+ """A transient error reading the config (encrypted-DB open) must NOT
+ remove a healthy existing job — it would stay gone until the next
+ login."""
+
+ def boom(self):
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(ZoteroSyncService, "get_config", boom)
+ sched._schedule_zotero_sync("u")
+ assert not sched.scheduler.remove_job.called
+ assert not sched.scheduler.add_job.called
+
+
+# --- reschedule on a settings change (no relogin required) ------------------
+
+
+def test_reschedule_zotero_jobs_active_user_creates_job(sched, monkeypatch):
+ _stub_config(monkeypatch, auto_sync_enabled=True, sync_interval_minutes=90)
+ assert sched.reschedule_zotero_jobs("u") is True
+ assert sched.scheduler.add_job.call_args.kwargs["id"] == "u_zotero_sync"
+ assert sched.scheduler.add_job.call_args.kwargs["minutes"] == 90
+
+
+def test_reschedule_zotero_jobs_disabled_tears_down(sched, monkeypatch):
+ _stub_config(monkeypatch, auto_sync_enabled=False)
+ assert sched.reschedule_zotero_jobs("u") is True
+ assert sched.scheduler.remove_job.called # existing job removed
+ assert not sched.scheduler.add_job.called # disabled -> not re-added
+
+
+def test_reschedule_zotero_jobs_untracked_user(sched):
+ assert sched.reschedule_zotero_jobs("stranger") is False
+ assert not sched.scheduler.add_job.called
+
+
+def test_reschedule_zotero_jobs_not_running(sched, monkeypatch):
+ monkeypatch.setattr(sched, "is_running", False)
+ assert sched.reschedule_zotero_jobs("u") is False
+
+
+def test_reschedule_if_needed_fires_only_on_zotero_keys(monkeypatch):
+ from local_deep_research.web.services.settings_service import (
+ reschedule_zotero_jobs_if_needed,
+ )
+
+ called = []
+ fake_sched = MagicMock()
+ fake_sched.reschedule_zotero_jobs.side_effect = lambda u: called.append(u)
+ monkeypatch.setattr(
+ "local_deep_research.scheduler.background.get_background_job_scheduler",
+ lambda: fake_sched,
+ )
+
+ reschedule_zotero_jobs_if_needed("u", ["llm.provider", "search.tool"])
+ assert called == [] # no zotero.* key -> no reschedule
+ reschedule_zotero_jobs_if_needed("u", ["zotero.auto_sync_enabled"])
+ assert called == ["u"]
+ reschedule_zotero_jobs_if_needed("", ["zotero.enabled"]) # no username
+ assert called == ["u"] # unchanged
diff --git a/tests/research_library/zotero/test_sync_service.py b/tests/research_library/zotero/test_sync_service.py
new file mode 100644
index 0000000000..e17194357e
--- /dev/null
+++ b/tests/research_library/zotero/test_sync_service.py
@@ -0,0 +1,2420 @@
+"""Unit tests for the Zotero sync service.
+
+The pure metadata helpers are tested directly. Document ingestion is tested
+against an in-memory SQLite database by calling ``_ingest_item`` with a fake
+client and a real ORM session — no encrypted DB / network required.
+"""
+
+import hashlib
+import uuid
+from contextlib import contextmanager
+from datetime import date, datetime, UTC
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentCollection,
+ DocumentStatus,
+ SourceType,
+)
+from local_deep_research.database.models.zotero import (
+ ZoteroItemMap,
+ ZoteroSyncState,
+)
+from local_deep_research.research_library.zotero.client import (
+ ZoteroAttachment,
+ ZoteroItem,
+)
+from local_deep_research.research_library.zotero.sync_service import (
+ ZoteroConfig,
+ ZoteroSyncService,
+)
+
+
+# ---------------------------------------------------------------------------
+# Pure helpers
+# ---------------------------------------------------------------------------
+
+
+def test_config_targets_and_configured():
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="1")
+ assert cfg.is_configured is True
+ assert cfg.targets == [""] # whole library when no keys
+ cfg2 = ZoteroConfig(
+ enabled=True, api_key="k", library_id="1", collection_keys=["A", "B"]
+ )
+ assert cfg2.targets == ["A", "B"]
+ assert (
+ ZoteroConfig(enabled=False, api_key="k", library_id="1").is_configured
+ is False
+ )
+
+
+def test_parse_date():
+ p = ZoteroSyncService._parse_date
+ assert p("2020-05-01") == date(2020, 5, 1)
+ assert p("2020-05") == date(2020, 5, 1)
+ assert p("2019") == date(2019, 1, 1)
+ assert p("May 2018") == date(2018, 1, 1)
+ assert p("") is None
+ assert p(None) is None
+ assert p("no-year-here") is None
+
+
+def test_authors():
+ item = ZoteroItem(
+ key="K",
+ version=1,
+ item_type="journalArticle",
+ data={
+ "creators": [
+ {"firstName": "Ada", "lastName": "Lovelace"},
+ {"name": "OpenAI"},
+ {"lastName": "Onlylast"},
+ ]
+ },
+ )
+ assert ZoteroSyncService._authors(item) == [
+ "Ada Lovelace",
+ "OpenAI",
+ "Onlylast",
+ ]
+
+
+def test_source_url_prefers_url_then_doi():
+ svc = ZoteroSyncService
+ with_url = ZoteroItem("K", 1, "x", {"url": "http://e.com", "DOI": "10.1/x"})
+ assert svc._source_url(with_url) == "http://e.com"
+ with_doi = ZoteroItem("K", 1, "x", {"DOI": "10.1/x"})
+ assert svc._source_url(with_doi) == "https://doi.org/10.1/x"
+ assert svc._source_url(ZoteroItem("K", 1, "x", {})) is None
+
+
+def test_filename_for_uses_title_then_key():
+ item = ZoteroItem("ABCD1234", 1, "x", {"title": "A Nice Title"})
+ assert ZoteroSyncService._filename_for(item, "pdf").endswith(".pdf")
+ blank = ZoteroItem("ABCD1234", 1, "x", {})
+ assert ZoteroSyncService._filename_for(blank, "text") == "ABCD1234.text"
+
+
+# ---------------------------------------------------------------------------
+# Ingestion against an in-memory database
+# ---------------------------------------------------------------------------
+
+
+def db_session():
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ session = Session()
+ yield session
+ session.close()
+ engine.dispose()
+
+
+def seeded(db_session):
+ source_type_id = str(uuid.uuid4())
+ collection_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(
+ id=source_type_id,
+ name="zotero",
+ display_name="Zotero",
+ )
+ )
+ db_session.add(
+ Collection(
+ id=collection_id,
+ name="Zotero: Test",
+ collection_type="zotero",
+ is_default=False,
+ )
+ )
+ db_session.commit()
+ return source_type_id, collection_id
+
+
+def _pdf_item(key="ITEM0001", title="A Paper"):
+ return ZoteroItem(
+ key=key,
+ version=3,
+ item_type="journalArticle",
+ data={"title": title, "DOI": "10.1234/x", "date": "2021"},
+ )
+
+
+def _fake_client(pdf_bytes=None, fulltext=None):
+ client = MagicMock()
+ # Default: no Zotero-side extracted full text (so tests exercise the
+ # download path unless they opt in).
+ client.get_attachment_fulltext.return_value = fulltext
+ if pdf_bytes is not None or fulltext is not None:
+ att = ZoteroAttachment(
+ key="ATT1",
+ version=2,
+ content_type="application/pdf",
+ link_mode="imported_file",
+ filename="paper.pdf",
+ title="Full Text",
+ )
+ client.get_children.return_value = [att]
+ client.download_attachment.return_value = pdf_bytes
+ else:
+ client.get_children.return_value = []
+ return client
+
+
+def test_ingest_pdf_item_creates_document(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 not-a-real-pdf")
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "pdf"
+ assert doc.title == "A Paper"
+ assert doc.doi == "10.1234/x"
+ assert doc.published_date == date(2021, 1, 1)
+ link = (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=collection_id)
+ .one()
+ )
+ assert link is not None
+
+
+def test_resync_pdf_to_text_removes_stale_blob(db_session, seeded):
+ """Regression: an item imported with a database-stored PDF that later has
+ no usable PDF must have its orphaned DocumentBlob deleted on re-sync.
+
+ Otherwise the doc is marked text-only (storage_mode="none") while a stale
+ encrypted PDF blob lingers, and PDFStorageManager.load_pdf() (which keys
+ off document_id and ignores file_type) would keep serving it.
+ """
+ from local_deep_research.database.models.library import DocumentBlob
+
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ item = _pdf_item(key="ITEMBLOB1")
+ cfg = ZoteroConfig(
+ pdf_storage_mode="database", import_items_without_pdf=True
+ )
+
+ # First sync: a valid PDF in database mode -> document stored as PDF.
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 body"),
+ cfg,
+ item,
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ assert action == "imported"
+ assert (
+ db_session.query(Document).filter_by(id=doc_id).one().storage_mode
+ == "database"
+ )
+
+ # Simulate the blob the real PDFStorageManager would have written (the
+ # test injects a MagicMock storage) and the item mapping the sync loop
+ # records, so the re-sync reuses this document.
+ db_session.add(
+ DocumentBlob(document_id=doc_id, pdf_binary=b"%PDF-1.7 body")
+ )
+ db_session.add(
+ ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key=item.key,
+ zotero_version=3,
+ document_id=doc_id,
+ )
+ )
+ db_session.commit()
+ assert (
+ db_session.query(DocumentBlob).filter_by(document_id=doc_id).count()
+ == 1
+ )
+
+ # Re-sync: same item, PDF now gone -> reuse doc, downgrade to text-only.
+ doc_id2, action2, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=None),
+ cfg,
+ item,
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id
+ assert action2 == "updated"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "text"
+ assert doc.storage_mode == "none"
+ # The stale encrypted PDF blob must be gone.
+ assert (
+ db_session.query(DocumentBlob).filter_by(document_id=doc_id).count()
+ == 0
+ )
+
+
+def test_ingest_metadata_only_when_enabled(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=None)
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(title="No PDF Here"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "text"
+ assert "No PDF Here" in (doc.text_content or "")
+
+
+def test_ingest_metadata_only_skipped_when_disabled(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=False)
+ client = _fake_client(pdf_bytes=None)
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert doc_id is None
+ assert action == "skipped"
+ assert db_session.query(Document).count() == 0
+
+
+def test_ingest_dedup_identical_content(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"%PDF-same-bytes")
+
+ doc_id1, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="A"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ doc_id2, action2, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="A"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id1 == doc_id2
+ assert action2 == "updated"
+ assert db_session.query(Document).count() == 1
+
+
+def test_upsert_and_remove_map(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"%PDF-x")
+ item = _pdf_item(key="ITEMX")
+
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ item,
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, item, doc_id)
+ db_session.commit()
+
+ row = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=collection_id, zotero_item_key="ITEMX")
+ .one()
+ )
+ assert row.document_id == doc_id
+ assert row.zotero_version == 3
+ assert row.has_pdf is True
+
+ # Removal deletes both the map row and the document.
+ svc._remove_item(db_session, row, source_type_id)
+ db_session.commit()
+ assert (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=collection_id, zotero_item_key="ITEMX")
+ .first()
+ is None
+ )
+ assert db_session.query(Document).filter_by(id=doc_id).first() is None
+
+
+def test_ingest_does_not_overwrite_foreign_document(db_session, seeded):
+ """A byte-identical doc from another source must not be mutated/owned."""
+ source_type_id, collection_id = seeded
+ foreign_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(
+ id=foreign_type_id,
+ name="user_upload",
+ display_name="User Upload",
+ )
+ )
+ shared = b"%PDF-1.7 SHARED-BYTES"
+ foreign = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=foreign_type_id,
+ document_hash=hashlib.sha256(shared).hexdigest(),
+ file_size=len(shared),
+ file_type="pdf",
+ title="User Title",
+ tags=["mine"],
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(foreign)
+ db_session.commit()
+
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=shared)
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(title="Zotero Title"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id == foreign.id
+ assert action == "updated"
+ db_session.refresh(foreign)
+ assert foreign.title == "User Title" # NOT overwritten
+ assert foreign.tags == ["mine"]
+ # Linked into the Zotero collection, but no duplicate created.
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=foreign.id, collection_id=collection_id)
+ .first()
+ is not None
+ )
+ assert db_session.query(Document).count() == 1
+
+
+def test_remove_item_keeps_document_shared_with_another_collection(
+ db_session, seeded
+):
+ """Removing an item must not destroy a document referenced elsewhere."""
+ from local_deep_research.research_library.utils import (
+ ensure_in_collection,
+ )
+
+ source_type_id, collection_id = seeded
+ coll2 = str(uuid.uuid4())
+ db_session.add(
+ Collection(
+ id=coll2,
+ name="Zotero: Other",
+ collection_type="zotero",
+ is_default=False,
+ )
+ )
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=source_type_id,
+ document_hash="shared-hash",
+ file_size=1,
+ file_type="pdf",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ # Capture the id as a plain string: after the full delete below, the ORM
+ # instance is stale and touching doc.id raises ObjectDeletedError.
+ doc_id = doc.id
+ ensure_in_collection(db_session, doc_id, collection_id)
+ ensure_in_collection(db_session, doc_id, coll2)
+ row1 = ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="K",
+ zotero_version=1,
+ document_id=doc_id,
+ )
+ row2 = ZoteroItemMap(
+ ldr_collection_id=coll2,
+ zotero_item_key="K",
+ zotero_version=1,
+ document_id=doc_id,
+ )
+ db_session.add_all([row1, row2])
+ db_session.commit()
+
+ svc = ZoteroSyncService("user", None)
+
+ # Remove from collection 1 — shared, so only the link + map row go.
+ svc._remove_item(db_session, row1, source_type_id)
+ db_session.commit()
+ assert db_session.query(Document).filter_by(id=doc_id).first() is not None
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=collection_id)
+ .first()
+ is None
+ )
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=coll2)
+ .first()
+ is not None
+ )
+
+ # Remove from the last collection — now unshared, so the doc is deleted.
+ svc._remove_item(db_session, row2, source_type_id)
+ db_session.commit()
+ assert db_session.query(Document).filter_by(id=doc_id).first() is None
+
+
+def test_sync_one_imports_then_reconciles(db_session, monkeypatch, tmp_path):
+ """End-to-end _sync_one: import, then a second pass that removes one item
+ and updates another, advancing the stored library version."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session # shared, never closed/committed by the CM
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = [] # metadata-only ingest
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1, "B": 1}, 10),
+ ({"A": 2}, 20), # B removed, A bumped
+ ]
+ client.get_items.side_effect = [
+ [item("A", 1, "Paper A"), item("B", 1, "Paper B")],
+ [item("A", 2, "Paper A")],
+ ]
+
+ stats1 = svc._sync_one(client, cfg, "")
+ assert stats1["status"] == "completed"
+ assert stats1["imported"] == 2
+ assert db_session.query(Document).count() == 2
+ coll = db_session.query(Collection).filter_by(name="Zotero Library").one()
+ assert (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=coll.id)
+ .count()
+ == 2
+ )
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_version == 10
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["removed"] == 1
+ assert stats2["updated"] == 1
+ assert stats2["imported"] == 0
+ assert db_session.query(Document).count() == 1 # B gone
+ a_row = db_session.query(ZoteroItemMap).filter_by(zotero_item_key="A").one()
+ assert a_row.zotero_version == 2
+ db_session.refresh(state)
+ assert state.last_version == 20
+
+
+def test_sync_one_cleans_removed_vectors_even_when_additions_fail(
+ db_session, monkeypatch, tmp_path
+):
+ """Regression: a removal commits, then the additions phase fails (a Zotero
+ 5xx from get_items). The removed doc's FAISS vectors MUST still be purged
+ (now in a finally) — otherwise they orphan into ghost search hits, and no
+ future sync re-detects them because the map row is already deleted."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+ from local_deep_research.research_library.zotero.client import (
+ ZoteroTransientError,
+ )
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ # Don't run the real auto-indexer on the (successful) first sync.
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", lambda *a, **k: None)
+
+ # A truthy password so the cleanup guard (`and self.password`) is reached.
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cleanup = (
+ MagicMock()
+ ) # spy: collection isn't RAG-indexed, so only assert calls
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", cleanup)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1, "B": 1}, 10),
+ ({"A": 2}, 20), # B removed, A bumped
+ ]
+ client.get_items.side_effect = [
+ [item("A", 1, "Paper A"), item("B", 1, "Paper B")],
+ ZoteroTransientError(
+ "boom"
+ ), # additions fail AFTER B's removal commits
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ b_doc_id = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="B")
+ .one()
+ .document_id
+ )
+ assert b_doc_id is not None
+ cleanup.reset_mock()
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["status"] == "failed"
+ assert stats2["removed"] == 1
+ # Removal is durably committed even though the sync then failed.
+ assert (
+ db_session.query(ZoteroItemMap).filter_by(zotero_item_key="B").count()
+ == 0
+ )
+ # THE FIX: the removed doc's vectors are cleaned on the failure path too.
+ cleaned = [c.args[0] for c in cleanup.call_args_list]
+ assert any(b_doc_id in ids for ids in cleaned), (
+ "removed doc's FAISS vectors were not cleaned on the additions-failure "
+ "path — they would orphan into ghost search hits"
+ )
+
+
+def test_sync_one_keeps_vectors_when_removal_commit_fails(
+ db_session, monkeypatch, tmp_path
+):
+ """Guard against the INVERSE leak the finally could cause: if a removal's
+ per-item commit fails (rolled back), the document still exists, so its
+ FAISS vectors must NOT be purged — and the failure stays contained to
+ that item (the sync itself completes and the removal retries next run)."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", lambda *a, **k: None)
+
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cleanup = MagicMock()
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", cleanup)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1, "B": 1}, 10),
+ ({"A": 1}, 20), # B removed
+ ]
+ client.get_items.side_effect = [
+ [item("A", 1, "Paper A"), item("B", 1, "Paper B")],
+ [], # second sync has nothing to (re)process
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ cleanup.reset_mock()
+
+ # Arm the batch commit that runs right after a removal is staged to fail.
+ orig_remove = svc._remove_item
+ orig_commit = db_session.commit
+ armed = {"v": False}
+
+ def spy_remove(session, row, stid):
+ rid = orig_remove(session, row, stid)
+ armed["v"] = True # the next commit is the removals batch commit
+ return rid
+
+ def guarded_commit():
+ if armed["v"]:
+ armed["v"] = False
+ raise RuntimeError("removals commit boom")
+ return orig_commit()
+
+ monkeypatch.setattr(svc, "_remove_item", spy_remove)
+ monkeypatch.setattr(db_session, "commit", guarded_commit)
+
+ stats2 = svc._sync_one(client, cfg, "")
+ # The failure is contained to B's removal: the sync completes, nothing
+ # is reported removed, and B stays mapped so next sync retries it.
+ assert stats2["status"] == "completed"
+ assert stats2["removed"] == 0
+ assert stats2["errors"] == 1
+ assert stats2["skipped"] == 0
+ assert (
+ db_session.query(ZoteroItemMap).filter_by(zotero_item_key="B").first()
+ is not None
+ )
+ # The removal rolled back, so the document still exists and the finally
+ # must NOT purge its vectors — otherwise a rolled-back removal would
+ # delete a still-valid document's vectors (the inverse leak).
+ cleanup.assert_not_called()
+
+
+def test_sync_one_aborts_batch_on_transient_ingest_error(
+ db_session, monkeypatch, tmp_path
+):
+ """A rate-limit / 5xx during item ingest must ABORT the sync (so it retries
+ next run) rather than skip the item and keep hammering the rest of the
+ batch against the rate limit."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ from local_deep_research.research_library.zotero.client import (
+ ZoteroTransientError,
+ )
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ calls = {"n": 0}
+
+ def boom(*_a, **_k):
+ calls["n"] += 1
+ raise ZoteroTransientError("429")
+
+ monkeypatch.setattr(svc, "_ingest_item", boom)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key):
+ return ZoteroItem(
+ key=key, version=1, item_type="journalArticle", data={"title": key}
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [({"A": 1, "B": 1}, 10)]
+ client.get_items.side_effect = [[item("A"), item("B")]]
+
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["status"] == "failed"
+ assert stats["imported"] == 0
+ # Aborted after the FIRST item's transient error — B was never attempted.
+ assert calls["n"] == 1
+
+
+def test_sync_one_releases_orphaned_doc_on_dedup_remap(
+ db_session, monkeypatch, tmp_path
+):
+ """When an edited item's new content dedups onto a DIFFERENT existing doc,
+ the item's prior document is released (not left as a stale orphan) and its
+ FAISS vectors are purged."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", lambda *a, **k: None)
+
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cleanup = MagicMock()
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", cleanup)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"K": 1, "M": 1}, 10),
+ ({"K": 2, "M": 1}, 20), # K edited, M unchanged
+ ]
+ client.get_items.side_effect = [
+ [item("K", 1, "Original K"), item("M", 1, "Shared Paper")],
+ [item("K", 2, "Shared Paper")], # K's new content == M's -> dedup
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ assert db_session.query(Document).count() == 2
+
+ def doc_of(key):
+ return (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key=key)
+ .one()
+ .document_id
+ )
+
+ d1, d2 = doc_of("K"), doc_of("M")
+ assert d1 != d2
+ cleanup.reset_mock()
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ # K now maps to M's doc; the orphaned prior doc D1 is gone...
+ assert doc_of("K") == d2
+ assert db_session.query(Document).filter_by(id=d1).first() is None
+ assert db_session.query(Document).count() == 1
+ # ...and its stale FAISS vectors were purged.
+ cleaned = [c.args[0] for c in cleanup.call_args_list]
+ assert any(d1 in ids for ids in cleaned), (
+ "orphaned prior document's vectors were not cleaned on dedup remap"
+ )
+
+
+def test_remove_item_keeps_doc_used_by_twin_in_same_collection(
+ db_session, seeded
+):
+ """Two byte-identical items in the SAME collection share one document via
+ dedup. Removing one must NOT drop the shared link/doc — the twin needs it."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client() # metadata-only
+
+ def meta_item(key):
+ return ZoteroItem(
+ key=key,
+ version=1,
+ item_type="journalArticle",
+ data={"title": "Dup"},
+ )
+
+ for key in ("K", "J"):
+ did, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ meta_item(key),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, meta_item(key), did)
+ db_session.commit()
+
+ assert db_session.query(Document).count() == 1 # K & J deduped
+
+ k_row = db_session.query(ZoteroItemMap).filter_by(zotero_item_key="K").one()
+ j_doc = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="J")
+ .one()
+ .document_id
+ )
+ # Returns None (nothing released), so the sync loop does NOT purge the
+ # surviving twin's FAISS vectors.
+ assert svc._remove_item(db_session, k_row, source_type_id) is None
+ db_session.commit()
+
+ # J's document + its collection link survive.
+ assert db_session.query(Document).filter_by(id=j_doc).first() is not None
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=j_doc, collection_id=collection_id)
+ .count()
+ == 1
+ )
+
+
+def test_item_has_tags_matches_all_case_insensitive():
+ item = ZoteroItem(
+ key="K",
+ version=1,
+ item_type="journalArticle",
+ data={"tags": [{"tag": "ML"}, {"tag": "Robotics"}]},
+ )
+ has = ZoteroSyncService._item_has_tags
+ assert has(item, ["ml"]) is True
+ assert has(item, ["ML", "robotics"]) is True # all required, any case
+ assert has(item, ["ml", "biology"]) is False # missing one
+ blank = ZoteroItem("K", 1, "x", {})
+ assert has(blank, ["ml"]) is False
+
+
+def test_sync_one_tag_filter_skips_nonmatching(
+ db_session, monkeypatch, tmp_path
+):
+ """With import_tags set, items lacking the tag are skipped (not imported)
+ and recorded so they aren't re-fetched."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ import_tags=["keep"],
+ )
+
+ def item(key, tags):
+ return ZoteroItem(
+ key=key,
+ version=1,
+ item_type="journalArticle",
+ data={"title": key, "tags": [{"tag": t} for t in tags]},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_attachment_fulltext.return_value = None
+ client.get_top_item_versions.side_effect = [({"A": 1, "B": 1}, 10)]
+ client.get_items.side_effect = [[item("A", ["keep"]), item("B", ["other"])]]
+
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["imported"] == 1 # only A (tagged "keep")
+ assert stats["skipped"] == 1 # B filtered out
+ assert db_session.query(Document).count() == 1
+ # B is recorded (version) so it won't be re-fetched next time.
+ b_row = db_session.query(ZoteroItemMap).filter_by(zotero_item_key="B").one()
+ assert b_row.document_id is None
+
+
+def test_ingest_appends_annotations_when_enabled(db_session, seeded):
+ """With import_annotations on, annotations + notes are appended to the
+ document's searchable text."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ import_annotations=True,
+ )
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 body")
+ client.get_annotations.return_value = ["highlight one", "highlight two"]
+ client.get_notes.return_value = ["a standalone note"]
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert "highlight one" in doc.text_content
+ assert "highlight two" in doc.text_content
+ assert "a standalone note" in doc.text_content
+ client.get_annotations.assert_called() # fetched per attachment
+
+
+def test_ingest_skips_annotations_when_disabled(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 body")
+
+ svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ client.get_annotations.assert_not_called()
+ client.get_notes.assert_not_called()
+
+
+def test_ingest_uses_zotero_fulltext_in_text_mode(db_session, seeded):
+ """In text-only mode, Zotero's extracted full text is used and the PDF is
+ NOT downloaded."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(
+ pdf_bytes=b"%PDF-should-not-be-used",
+ fulltext="EXTRACTED BY ZOTERO",
+ )
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "pdf"
+ assert doc.text_content == "EXTRACTED BY ZOTERO"
+ client.download_attachment.assert_not_called() # skipped the download
+
+
+def test_ingest_downloads_when_no_zotero_fulltext(db_session, seeded):
+ """Falls back to downloading when Zotero has no indexed text."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 body", fulltext=None)
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ assert action == "imported"
+ client.download_attachment.assert_called_once()
+
+
+def test_ingest_rejects_non_pdf_body(db_session, seeded):
+ """A /file response that isn't a PDF must not be stored as one."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=b"<html>403 Forbidden</html>")
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(title="HTML Trap"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "text" # fell back to metadata, NOT stored as pdf
+
+
+def test_ingest_non_pdf_body_skipped_when_import_disabled(db_session, seeded):
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=False)
+ client = _fake_client(pdf_bytes=b"<html>not a pdf</html>")
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert doc_id is None
+ assert action == "skipped"
+ assert db_session.query(Document).count() == 0
+
+
+def test_remove_item_deletes_rag_chunks(db_session, seeded):
+ """The unshared hard-delete path must also remove the doc's RAG chunks."""
+ from local_deep_research.database.models.library import DocumentChunk
+ from local_deep_research.research_library.utils import (
+ ensure_in_collection,
+ )
+
+ source_type_id, collection_id = seeded
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=source_type_id,
+ document_hash="chunk-hash",
+ file_size=1,
+ file_type="pdf",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ doc_id = doc.id
+ ensure_in_collection(db_session, doc_id, collection_id)
+ db_session.add(
+ DocumentChunk(
+ source_id=doc_id,
+ source_type="document",
+ collection_name=f"collection_{collection_id}",
+ chunk_index=0,
+ chunk_text="hello",
+ chunk_hash="ch",
+ start_char=0,
+ end_char=5,
+ word_count=1,
+ embedding_id="emb-0",
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type="sentence_transformers",
+ )
+ )
+ row = ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="K",
+ zotero_version=1,
+ document_id=doc_id,
+ )
+ db_session.add(row)
+ db_session.commit()
+ assert db_session.query(DocumentChunk).count() == 1
+
+ svc = ZoteroSyncService("user", None)
+ svc._remove_item(db_session, row, source_type_id)
+ db_session.commit()
+ assert db_session.query(Document).filter_by(id=doc_id).first() is None
+ assert db_session.query(DocumentChunk).count() == 0 # chunks cleaned up
+
+
+def test_remove_item_keeps_foreign_owned_document(db_session, seeded):
+ """A document Zotero only *adopted* via content-hash dedup (a user upload
+ or research download owned by a different source type) must NOT be
+ hard-deleted when its Zotero item disappears — even when nothing else
+ references it. Zotero only owns the collection link + mapping row."""
+ from local_deep_research.research_library.utils import (
+ ensure_in_collection,
+ )
+
+ zotero_source_type_id, collection_id = seeded
+ # A different (non-Zotero) source type owns the document.
+ foreign_source_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(
+ id=foreign_source_id,
+ name="user_uploads",
+ display_name="User Uploads",
+ )
+ )
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=foreign_source_id, # NOT Zotero's
+ document_hash="user-upload-hash",
+ file_size=1,
+ file_type="pdf",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ doc_id = doc.id
+ ensure_in_collection(db_session, doc_id, collection_id)
+ row = ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="K",
+ zotero_version=1,
+ document_id=doc_id,
+ )
+ db_session.add(row)
+ db_session.commit()
+
+ svc = ZoteroSyncService("user", None)
+ returned = svc._remove_item(db_session, row, zotero_source_type_id)
+ db_session.commit()
+
+ # The user's document survives; only this collection's link + the map row go.
+ assert returned == doc_id
+ assert db_session.query(Document).filter_by(id=doc_id).first() is not None
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=collection_id)
+ .first()
+ is None
+ )
+ assert db_session.query(ZoteroItemMap).filter_by(id=row.id).first() is None
+
+
+def test_ingest_update_purges_stale_chunks(db_session, seeded):
+ """When a mapped item's content changes, _ingest_item must purge the doc's
+ stale RAG chunks (and flag a re-index) so outdated text stops surfacing in
+ search instead of accumulating alongside the new chunks."""
+ from local_deep_research.database.models.library import DocumentChunk
+
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = _fake_client(pdf_bytes=None) # metadata-only
+
+ # First ingest (fresh import).
+ doc_id, action, reindexed = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="UPD1", title="Original Title"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ assert action == "imported"
+ assert reindexed is False
+
+ # Simulate the sync loop's mapping + an indexed chunk for this doc.
+ db_session.add(
+ ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="UPD1",
+ zotero_version=3,
+ document_id=doc_id,
+ )
+ )
+ db_session.add(
+ DocumentChunk(
+ source_id=doc_id,
+ source_type="document",
+ collection_name=f"collection_{collection_id}",
+ chunk_index=0,
+ chunk_text="original title stale text",
+ chunk_hash="stale-chunk",
+ start_char=0,
+ end_char=25,
+ word_count=4,
+ embedding_id="emb-stale",
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type="sentence_transformers",
+ )
+ )
+ db_session.commit()
+ assert db_session.query(DocumentChunk).count() == 1
+
+ # Re-ingest the SAME item key with changed content (new title -> new hash).
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="UPD1", title="Completely Different Title"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id # same document, updated in place
+ assert action2 == "updated"
+ assert reindexed2 is True # caller must clear the FAISS vectors
+ # The stale chunk is gone (re-index will rebuild from current content).
+ assert db_session.query(DocumentChunk).count() == 0
+ # The collection link is flagged for re-index.
+ link = (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=collection_id)
+ .one()
+ )
+ assert link.indexed is False
+
+
+def test_ingest_save_pdf_failure_downgrades_to_text_only(db_session, seeded):
+ """If storing the PDF blob fails, the doc must be downgraded to text-only so
+ ZoteroItemMap.has_pdf (keyed off file_type) doesn't advertise a PDF that
+ load_pdf() can never return."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ pdf_storage_mode="database", import_items_without_pdf=True
+ )
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 realish body")
+
+ failing_storage = MagicMock()
+ failing_storage.save_pdf.side_effect = Exception("disk full")
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="PDFFAIL1"),
+ collection_id,
+ source_type_id,
+ failing_storage,
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ # Downgraded to a consistent text-only document (no phantom PDF).
+ assert doc.file_type == "text"
+ assert doc.storage_mode == "none"
+ # Extracted text is preserved so the item is still searchable.
+ assert doc.text_content
+
+
+def test_sync_one_empty_remote_map_skips_removals(
+ db_session, monkeypatch, tmp_path
+):
+ """Mass-deletion guard: if the remote version map comes back EMPTY while
+ items are still mapped locally (a truncated/transient response), _sync_one
+ must NOT delete anything."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": key},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ # First sync imports A + B; second sync returns an EMPTY map.
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1, "B": 1}, 10),
+ ({}, 20),
+ ]
+ client.get_items.side_effect = [
+ [item("A", 1), item("B", 1)],
+ [],
+ ]
+
+ svc._sync_one(client, cfg, "")
+ assert db_session.query(Document).count() == 2
+
+ stats2 = svc._sync_one(client, cfg, "")
+ # Guard fired: nothing removed, both documents survive.
+ assert stats2["removed"] == 0
+ assert db_session.query(Document).count() == 2
+ coll = db_session.query(Collection).filter_by(name="Zotero Library").one()
+ assert (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=coll.id)
+ .count()
+ == 2
+ )
+
+
+def test_sync_one_marks_state_failed_on_version_fetch_error(
+ db_session, monkeypatch, tmp_path
+):
+ """A ZoteroError while fetching the version map must fail the collection
+ sync AND persist last_status='failed' + last_error on the state row."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ from local_deep_research.research_library.zotero.client import ZoteroError
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_id="1", pdf_storage_mode="none"
+ )
+
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = ZoteroError("rate limited")
+
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["status"] == "failed"
+ assert stats["error"]
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_status == "failed"
+ assert state.last_error
+
+
+def test_sync_one_skipped_no_pdf_item_not_reprocessed(
+ db_session, monkeypatch, tmp_path
+):
+ """Regression: a no-PDF item with import disabled is mapped (doc_id None)
+ and must NOT be re-fetched on the next sync when its version is unchanged."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=False, # no-PDF items are skipped
+ )
+
+ def item(key, ver):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": key},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = [] # no PDF -> skipped
+ client.get_top_item_versions.side_effect = [({"A": 1}, 10), ({"A": 1}, 10)]
+ client.get_items.side_effect = [[item("A", 1)], []]
+
+ stats1 = svc._sync_one(client, cfg, "")
+ assert stats1["skipped"] == 1
+ assert stats1["imported"] == 0
+ row = db_session.query(ZoteroItemMap).filter_by(zotero_item_key="A").one()
+ assert row.document_id is None
+
+ # Second sync: version unchanged -> A must NOT be reprocessed.
+ svc._sync_one(client, cfg, "")
+ assert client.get_items.call_args_list[1].args[0] == []
+
+
+def test_sync_all_skips_when_already_running(monkeypatch):
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="1")
+ monkeypatch.setattr(ZoteroSyncService, "get_config", lambda self: cfg)
+
+ svc = ZoteroSyncService("user", None)
+ lock = svc_mod._get_user_sync_lock("user")
+ assert lock.acquire(blocking=False)
+ try:
+ assert ZoteroSyncService.is_user_syncing("user") is True
+ result = svc.sync_all()
+ assert result.get("already_running") is True
+ assert result["imported"] == 0
+ finally:
+ lock.release()
+ assert ZoteroSyncService.is_user_syncing("user") is False
+
+
+def test_sync_one_omitted_key_not_refetched(db_session, monkeypatch, tmp_path):
+ """A key present in the version map but NOT returned by get_items (e.g.
+ trashed/permission-changed) must have its version recorded so it isn't
+ re-requested on every subsequent sync."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_id="1", pdf_storage_mode="none"
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ # "A" is in the version map both syncs, but get_items never returns it.
+ client.get_top_item_versions.side_effect = [({"A": 1}, 10), ({"A": 1}, 10)]
+ client.get_items.side_effect = [[], []]
+
+ svc._sync_one(client, cfg, "")
+ row = db_session.query(ZoteroItemMap).filter_by(zotero_item_key="A").one()
+ assert row.zotero_version == 1
+ assert row.document_id is None
+
+ # Second sync: version unchanged + already recorded -> not re-requested.
+ svc._sync_one(client, cfg, "")
+ assert client.get_items.call_args_list[1].args[0] == []
+
+
+def test_remove_item_returns_affected_doc_id(db_session, seeded):
+ """_remove_item returns the document id so the caller can clear its
+ FAISS vectors after the transaction."""
+ source_type_id, collection_id = seeded
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=source_type_id,
+ document_hash="ret-hash",
+ file_size=1,
+ file_type="pdf",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ doc_id = doc.id
+ row = ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="K",
+ zotero_version=1,
+ document_id=doc_id,
+ )
+ db_session.add(row)
+ db_session.commit()
+
+ svc = ZoteroSyncService("user", None)
+ assert svc._remove_item(db_session, row, source_type_id) == doc_id
+
+
+# ---------------------------------------------------------------------------
+# In-place rewrite safety: adopted, shared, and cross-collection documents
+# ---------------------------------------------------------------------------
+
+
+def _seed_foreign_upload(db_session, content: bytes):
+ """A user-uploaded document (foreign source type) with a stored PDF blob."""
+ from local_deep_research.database.models.library import DocumentBlob
+
+ foreign_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(
+ id=foreign_type_id,
+ name="user_upload",
+ display_name="User Upload",
+ )
+ )
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=foreign_type_id,
+ document_hash=hashlib.sha256(content).hexdigest(),
+ file_size=len(content),
+ file_type="pdf",
+ title="User Title",
+ tags=["mine"],
+ text_content="the user's own extracted text",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ db_session.add(DocumentBlob(document_id=doc.id, pdf_binary=content))
+ db_session.commit()
+ return doc
+
+
+def test_ingest_change_never_rewrites_adopted_foreign_document(
+ db_session, seeded
+):
+ """An item that dedup-adopted a user upload must FORK on a later content
+ change — never rewrite the user's document or delete its PDF blob."""
+ from local_deep_research.database.models.library import DocumentBlob
+
+ source_type_id, collection_id = seeded
+ original = b"%PDF-1.7 THE-USERS-BYTES"
+ foreign = _seed_foreign_upload(db_session, original)
+ foreign_id = foreign.id
+
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+
+ # Step 1: first contact — byte-identical, so the item adopts the upload.
+ client = _fake_client(pdf_bytes=original)
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="ADOPT1"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert doc_id == foreign_id
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="ADOPT1"), doc_id)
+ db_session.commit()
+
+ # Step 2: the PDF is replaced in Zotero — content now differs.
+ client2 = _fake_client(pdf_bytes=b"%PDF-1.7 REPLACED-IN-ZOTERO")
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ client2,
+ cfg,
+ _pdf_item(key="ADOPT1", title="Zotero Title"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ # A NEW zotero-owned document was created; the upload is untouched.
+ assert doc_id2 != foreign_id
+ assert action2 == "imported"
+ assert reindexed2 is False # nothing was rewritten in place
+ db_session.refresh(foreign)
+ assert foreign.title == "User Title"
+ assert foreign.tags == ["mine"]
+ assert foreign.text_content == "the user's own extracted text"
+ assert (
+ db_session.query(DocumentBlob).filter_by(document_id=foreign_id).count()
+ == 1
+ )
+ new_doc = db_session.query(Document).filter_by(id=doc_id2).one()
+ assert new_doc.source_type_id == source_type_id
+
+
+def test_ingest_change_forks_instead_of_rewriting_shared_twin_doc(
+ db_session, seeded
+):
+ """Two byte-identical items share one document. Editing ONE of them must
+ fork a new document — the twin keeps serving the original content."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ shared = b"%PDF-1.7 TWIN-BYTES"
+
+ client = _fake_client(pdf_bytes=shared)
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="TWINA"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="TWINA"), doc_id)
+ doc_id_b, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="TWINB"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert doc_id_b == doc_id # deduped onto the same doc
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="TWINB"), doc_id)
+ db_session.commit()
+ original_text = (
+ db_session.query(Document).filter_by(id=doc_id).one().text_content
+ )
+
+ # Edit TWINA's content in Zotero.
+ client2 = _fake_client(pdf_bytes=b"%PDF-1.7 TWIN-A-EDITED")
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ client2,
+ cfg,
+ _pdf_item(key="TWINA", title="Edited"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 != doc_id # forked, not rewritten
+ assert action2 == "imported"
+ assert reindexed2 is False
+ # The shared doc still carries the ORIGINAL content for TWINB.
+ shared_doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert shared_doc.text_content == original_text
+ twin_b_row = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=collection_id, zotero_item_key="TWINB")
+ .one()
+ )
+ assert twin_b_row.document_id == doc_id
+ # Releasing TWINA's claim on the old doc keeps it (twin still maps to it).
+ twin_a_row = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(ldr_collection_id=collection_id, zotero_item_key="TWINA")
+ .one()
+ )
+ assert (
+ svc._release_document(
+ db_session, doc_id, collection_id, twin_a_row.id, source_type_id
+ )
+ is None
+ )
+ db_session.commit()
+ assert db_session.query(Document).filter_by(id=doc_id).first() is not None
+
+
+def test_ingest_change_forks_when_doc_linked_to_another_collection(
+ db_session, seeded
+):
+ """A zotero-owned doc the user also linked into ANOTHER collection must not
+ be rewritten in place — the other collection's chunks would go stale."""
+ from local_deep_research.research_library.utils import (
+ ensure_in_collection,
+ )
+
+ source_type_id, collection_id = seeded
+ other_coll = str(uuid.uuid4())
+ db_session.add(
+ Collection(
+ id=other_coll,
+ name="My Manual Collection",
+ collection_type="manual",
+ is_default=False,
+ )
+ )
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+
+ client = _fake_client(pdf_bytes=b"%PDF-1.7 LINKED-BYTES")
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="LINK1"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="LINK1"), doc_id)
+ ensure_in_collection(db_session, doc_id, other_coll)
+ db_session.commit()
+ original_text = (
+ db_session.query(Document).filter_by(id=doc_id).one().text_content
+ )
+
+ client2 = _fake_client(pdf_bytes=b"%PDF-1.7 LINKED-BYTES-EDITED")
+ doc_id2, action2, _ = svc._ingest_item(
+ db_session,
+ client2,
+ cfg,
+ _pdf_item(key="LINK1"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 != doc_id
+ assert action2 == "imported"
+ old_doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert old_doc.text_content == original_text # other collection intact
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=other_coll)
+ .first()
+ is not None
+ )
+
+
+# ---------------------------------------------------------------------------
+# Annotation/text refresh on unchanged content bytes
+# ---------------------------------------------------------------------------
+
+
+def test_ingest_refreshes_annotations_on_unchanged_pdf(db_session, seeded):
+ """New annotations must reach the document even when the PDF bytes (and
+ thus the content hash) are unchanged, flagging a re-index."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ import_annotations=True,
+ )
+ pdf = b"%PDF-1.7 ANNOTATED"
+
+ client = _fake_client(pdf_bytes=pdf)
+ client.get_annotations.return_value = ["first highlight"]
+ client.get_notes.return_value = []
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="ANN1"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="ANN1"), doc_id)
+ db_session.commit()
+
+ # Same PDF bytes, new annotation.
+ client2 = _fake_client(pdf_bytes=pdf)
+ client2.get_annotations.return_value = [
+ "first highlight",
+ "second highlight",
+ ]
+ client2.get_notes.return_value = []
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ client2,
+ cfg,
+ _pdf_item(key="ANN1"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id
+ assert action2 == "updated"
+ assert reindexed2 is True # caller must clear stale FAISS vectors
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert "second highlight" in doc.text_content
+ link = (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=collection_id)
+ .one()
+ )
+ assert link.indexed is False # re-index forced
+
+
+def test_ingest_skips_text_refresh_on_shared_doc(db_session, seeded):
+ """Annotation refresh must NOT rewrite a document shared with a twin
+ mapping — one item's annotations would overwrite what the other item
+ surfaces."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ import_annotations=True,
+ )
+ pdf = b"%PDF-1.7 SHARED-ANNOTATED"
+
+ client = _fake_client(pdf_bytes=pdf)
+ client.get_annotations.return_value = []
+ client.get_notes.return_value = []
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _pdf_item(key="SHRA"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="SHRA"), doc_id)
+ svc._upsert_map(db_session, collection_id, _pdf_item(key="SHRB"), doc_id)
+ db_session.commit()
+ original_text = (
+ db_session.query(Document).filter_by(id=doc_id).one().text_content
+ )
+
+ client2 = _fake_client(pdf_bytes=pdf)
+ client2.get_annotations.return_value = ["only A's highlight"]
+ client2.get_notes.return_value = []
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ client2,
+ cfg,
+ _pdf_item(key="SHRA"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id
+ assert action2 == "updated"
+ assert reindexed2 is False
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.text_content == original_text # untouched
+
+
+# ---------------------------------------------------------------------------
+# Release failures must propagate (no half-committed releases)
+# ---------------------------------------------------------------------------
+
+
+def test_release_document_propagates_cascade_failure(
+ db_session, seeded, monkeypatch
+):
+ """A chunk-cascade failure during release must raise so the surrounding
+ transaction rolls back — swallowing it would let the caller purge FAISS
+ vectors for a document whose chunks still exist."""
+ from local_deep_research.research_library.zotero import (
+ sync_service as svc_mod,
+ )
+
+ source_type_id, collection_id = seeded
+ doc = Document(
+ id=str(uuid.uuid4()),
+ source_type_id=source_type_id,
+ document_hash="cascade-fail-hash",
+ file_size=1,
+ file_type="pdf",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ db_session.add(doc)
+ db_session.flush()
+ row = ZoteroItemMap(
+ ldr_collection_id=collection_id,
+ zotero_item_key="CASC",
+ zotero_version=1,
+ document_id=doc.id,
+ )
+ db_session.add(row)
+ db_session.commit()
+
+ def boom(*_a, **_k):
+ raise RuntimeError("cascade failed")
+
+ monkeypatch.setattr(
+ svc_mod.CascadeHelper, "delete_document_chunks", staticmethod(boom)
+ )
+ svc = ZoteroSyncService("user", None)
+ with pytest.raises(RuntimeError, match="cascade failed"):
+ svc._release_document(
+ db_session, doc.id, collection_id, row.id, source_type_id
+ )
+
+
+def test_extraction_method_reflects_actual_text_source(db_session, seeded):
+ """extraction_method must say where the text really came from: local PDF
+ extraction, Zotero's fulltext index, or the metadata fallback."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+
+ # No PDF at all -> metadata.
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(),
+ cfg,
+ _pdf_item(key="EXM1", title="Meta Only"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert (
+ db_session.query(Document).filter_by(id=doc_id).one().extraction_method
+ == "metadata"
+ )
+
+ # Zotero-side fulltext -> zotero_fulltext.
+ doc_id2, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-x", fulltext="ZOTERO TEXT"),
+ cfg,
+ _pdf_item(key="EXM2", title="Fulltext"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ assert (
+ db_session.query(Document).filter_by(id=doc_id2).one().extraction_method
+ == "zotero_fulltext"
+ )
+
+ # PDF bytes that fail local extraction -> metadata fallback, NOT
+ # "pdf_extraction".
+ doc_id3, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 not-a-real-pdf EXM3"),
+ cfg,
+ _pdf_item(key="EXM3", title="Broken PDF"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+ doc3 = db_session.query(Document).filter_by(id=doc_id3).one()
+ assert doc3.file_type == "pdf"
+ assert doc3.extraction_method == "metadata"
+
+
+def test_sync_one_isolates_removal_cascade_failure(
+ db_session, monkeypatch, tmp_path
+):
+ """One document whose delete-cascade fails must not abort the removals
+ batch: the other removals complete (and get their vectors purged), the
+ failing item stays mapped for a retry next sync, and the sync itself
+ completes."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", lambda *a, **k: None)
+
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cleanup = MagicMock()
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", cleanup)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"S": 1, "A": 1, "B": 1}, 10),
+ ({"S": 1}, 20), # A and B removed
+ ]
+ client.get_items.side_effect = [
+ [item("S", 1, "Survivor"), item("A", 1, "Paper A"), item("B", 1, "B")],
+ [],
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ cleanup.reset_mock()
+
+ def doc_of(key):
+ return (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key=key)
+ .one()
+ .document_id
+ )
+
+ a_doc, b_doc = doc_of("A"), doc_of("B")
+
+ orig_cascade = svc_mod.CascadeHelper.delete_document_chunks
+
+ def guarded(session, document_id, collection_name=None):
+ if document_id == b_doc:
+ raise RuntimeError("cascade boom")
+ return orig_cascade(
+ session, document_id, collection_name=collection_name
+ )
+
+ monkeypatch.setattr(
+ svc_mod.CascadeHelper,
+ "delete_document_chunks",
+ staticmethod(guarded),
+ )
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["status"] == "completed"
+ assert stats2["removed"] == 1 # A
+ assert stats2["errors"] == 1 # B, contained
+ # The contained failure is surfaced on the persisted sync state.
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_status == "completed"
+ assert "1 item(s) failed" in (state.last_error or "")
+ # A is fully removed and its vectors purged.
+ assert db_session.query(Document).filter_by(id=a_doc).first() is None
+ cleaned = [c.args[0] for c in cleanup.call_args_list]
+ assert any(a_doc in ids for ids in cleaned)
+ # B rolled back cleanly: doc + map row intact, vectors untouched.
+ assert db_session.query(Document).filter_by(id=b_doc).first() is not None
+ assert (
+ db_session.query(ZoteroItemMap).filter_by(zotero_item_key="B").first()
+ is not None
+ )
+ assert not any(b_doc in ids for ids in cleaned)
+
+
+def test_sync_one_isolates_remap_release_failure(
+ db_session, monkeypatch, tmp_path
+):
+ """A failing release during a dedup remap must roll back the whole item
+ (map still points at the prior doc, version not advanced -> retried next
+ sync) without failing the sync or purging any vectors."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", lambda *a, **k: None)
+
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ cleanup = MagicMock()
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", cleanup)
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"K": 1, "M": 1}, 10),
+ ({"K": 2, "M": 1}, 20), # K edited
+ ]
+ client.get_items.side_effect = [
+ [item("K", 1, "Original K"), item("M", 1, "Shared Paper")],
+ [item("K", 2, "Shared Paper")], # K's new content == M's -> remap
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+
+ def row_of(key):
+ return (
+ db_session.query(ZoteroItemMap).filter_by(zotero_item_key=key).one()
+ )
+
+ d1 = row_of("K").document_id
+ cleanup.reset_mock()
+
+ orig_cascade = svc_mod.CascadeHelper.delete_document_chunks
+
+ def guarded(session, document_id, collection_name=None):
+ if document_id == d1:
+ raise RuntimeError("cascade boom")
+ return orig_cascade(
+ session, document_id, collection_name=collection_name
+ )
+
+ monkeypatch.setattr(
+ svc_mod.CascadeHelper,
+ "delete_document_chunks",
+ staticmethod(guarded),
+ )
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["status"] == "completed"
+ assert stats2["errors"] == 1
+ assert stats2["updated"] == 0
+ # Whole item rolled back: still mapped to the prior doc at the OLD
+ # version, so the next sync retries the remap.
+ row = row_of("K")
+ assert row.document_id == d1
+ assert row.zotero_version == 1
+ assert db_session.query(Document).filter_by(id=d1).first() is not None
+ cleanup.assert_not_called()
+
+
+def test_sync_one_indexes_committed_docs_even_when_sync_fails(
+ db_session, monkeypatch, tmp_path
+):
+ """Items committed before a mid-batch failure must still get their RAG
+ auto-index triggered — their versions already match, so no future sync
+ reprocesses them, and without the trigger they stay invisible to
+ semantic search."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ import local_deep_research.research_library.routes.rag_routes as rag_mod
+ from local_deep_research.research_library.zotero.client import (
+ ZoteroTransientError,
+ )
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ auto_index = MagicMock()
+ monkeypatch.setattr(rag_mod, "trigger_auto_index", auto_index)
+
+ svc = ZoteroSyncService("user", "pw")
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ monkeypatch.setattr(svc, "_cleanup_removed_vectors", MagicMock())
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+
+ def children(key):
+ if key == "B":
+ raise ZoteroTransientError("rate limited")
+ return []
+
+ client.get_children.side_effect = children
+ client.get_top_item_versions.return_value = ({"A": 1, "B": 1}, 10)
+ client.get_items.return_value = [
+ item("A", 1, "Paper A"),
+ item("B", 1, "Paper B"),
+ ]
+
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["status"] == "failed" # the transient error aborts the batch
+ assert stats["imported"] == 1 # but A was committed first
+
+ a_doc = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="A")
+ .one()
+ .document_id
+ )
+ # A's committed document still gets its auto-index triggered.
+ auto_index.assert_called_once()
+ assert auto_index.call_args.args[0] == [a_doc]
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 7359e53113..3ed0791037 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -8411,5 +8411,192 @@
"ui_element": "checkbox",
"value": true,
"visible": false
+ },
+ "zotero.api_key": {
+ "category": "zotero",
+ "description": "Your Zotero API key. Create one at https://www.zotero.org/settings/keys (it needs read access to the library you want to import). Not needed if 'Use Local Zotero' is enabled.",
+ "editable": true,
+ "env_var": "LDR_ZOTERO_API_KEY",
+ "max_value": null,
+ "min_value": null,
+ "name": "Zotero API Key",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
+ "zotero.auto_sync_enabled": {
+ "category": "zotero",
+ "description": "Periodically re-sync the configured collections in the background (downloads new items, updates changed ones, and removes items deleted in Zotero). Requires the Zotero integration to be enabled.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Auto-Sync in Background",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.collection_keys": {
+ "category": "zotero",
+ "description": "Comma-separated Zotero collection keys to import (e.g. ABCD1234). Leave empty to import the entire library. Use the 'List collections' button on the Zotero page to find keys.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Collection Keys",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.enabled": {
+ "category": "zotero",
+ "description": "Enable the Zotero integration. When on, you can import papers from a Zotero collection into your library and (optionally) keep them in sync.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Enable Zotero Integration",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.import_annotations": {
+ "category": "zotero",
+ "description": "Also import your Zotero PDF annotations (highlights + comments) and child notes, appended to the document's searchable text. Adds extra API calls per item, so it's off by default. Note: annotation/note edits that don't change the parent item are picked up only when the item itself changes.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Annotations & Notes",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "zotero.import_items_without_pdf": {
+ "category": "zotero",
+ "description": "Also import items that have no attached PDF, using their title/abstract/metadata as a text-only document so they remain searchable. Turn off to import only items with a downloadable PDF. Not retroactive: items skipped while this was off are picked up only when they next change in Zotero.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Items Without a PDF",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "zotero.import_tags": {
+ "category": "zotero",
+ "description": "Only import items tagged with ALL of these comma-separated Zotero tags (case-insensitive). Leave empty to import everything. This filters what is imported; changing it does not remove items already imported.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Import Only These Tags",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.library_id": {
+ "category": "zotero",
+ "description": "Numeric library ID. For a personal library this is your userID (see https://www.zotero.org/settings/keys). For a group library it is the group's numeric ID.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Library ID",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "text",
+ "value": "",
+ "visible": true
+ },
+ "zotero.library_type": {
+ "category": "zotero",
+ "description": "Whether to read from your personal user library or a shared group library.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Library Type",
+ "options": [
+ {
+ "label": "Personal (user) library",
+ "value": "user"
+ },
+ {
+ "label": "Group library",
+ "value": "group"
+ }
+ ],
+ "step": null,
+ "type": "APP",
+ "ui_element": "select",
+ "value": "user",
+ "visible": true
+ },
+ "zotero.pdf_storage_mode": {
+ "category": "zotero",
+ "description": "How to store imported PDFs. 'database' keeps the PDF inside your encrypted database; 'none' stores only the extracted text (smaller, but the original PDF is not retained).",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "PDF Storage Mode",
+ "options": [
+ {
+ "label": "Store PDF in encrypted database",
+ "value": "database"
+ },
+ {
+ "label": "Text only (don't keep the PDF)",
+ "value": "none"
+ }
+ ],
+ "step": null,
+ "type": "APP",
+ "ui_element": "select",
+ "value": "database",
+ "visible": true
+ },
+ "zotero.sync_interval_minutes": {
+ "category": "zotero",
+ "description": "How often the background auto-sync runs (minutes).",
+ "editable": true,
+ "max_value": 10080,
+ "min_value": 15,
+ "name": "Auto-Sync Interval (minutes)",
+ "options": null,
+ "step": 15,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 360,
+ "visible": true
+ },
+ "zotero.use_local_api": {
+ "category": "zotero",
+ "description": "Sync from the Zotero desktop app running on this machine (local API at localhost:23119) instead of the cloud Web API. No API key needed, and it can read locally-stored / linked-file attachments the cloud API can't. Requires Zotero 7+ with the local API enabled in its preferences, and Zotero running during sync. Caution on shared/multi-user hosts: the desktop app's local API is unauthenticated, so any user or process on the server able to reach localhost:23119 can read that Zotero library.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Use Local Zotero (desktop app)",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
}
}
diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.js
index c232092ff1..b212bb1236 100644
--- a/tests/ui_tests/run_all_tests.js
+++ b/tests/ui_tests/run_all_tests.js
@@ -273,7 +273,7 @@ const tests = [
},
// =====================================================================
- // Shard: library (4 tests)
+ // Shard: library (5 tests)
// =====================================================================
{
name: 'Library Collections CI Tests',
@@ -299,6 +299,12 @@ const tests = [
shard: 'library',
description: 'Tests download manager: stats, filters, selection cycle, collections API'
},
+ {
+ name: 'Zotero Integration CI Tests',
+ file: 'test_zotero_integration_ci.js',
+ shard: 'library',
+ description: 'Tests Zotero page structure, config/status APIs, API-key non-leak contract, unconfigured negative paths'
+ },
// =====================================================================
// Shard: history-news (3 tests)
diff --git a/tests/ui_tests/test_zotero_integration_ci.js b/tests/ui_tests/test_zotero_integration_ci.js
new file mode 100644
index 0000000000..b6582d61ca
--- /dev/null
+++ b/tests/ui_tests/test_zotero_integration_ci.js
@@ -0,0 +1,540 @@
+#!/usr/bin/env node
+/**
+ * Zotero Integration UI Tests
+ *
+ * Tests the Zotero integration page (/library/zotero): the inline
+ * configuration form (edit + save settings directly on the page), the
+ * config/status JSON endpoints, the security contract (the API key is never
+ * returned to or pre-filled in the browser), the unconfigured negative paths,
+ * and an end-to-end save round-trip.
+ *
+ * Design note — NO external network calls to api.zotero.org: a fresh CI user
+ * has no Zotero credentials, so this suite only exercises endpoints that
+ * short-circuit before reaching api.zotero.org:
+ * - /config, /status -> read local settings / DB only
+ * - /test (unconfigured) -> returns {success:false} without a request
+ * - /sync (unconfigured) -> returns 400 without a request
+ * The save round-trip uses local-API mode (localhost, no key) and never
+ * triggers a sync, and it restores the unconfigured state afterwards.
+ * "List collections" / "List groups" would hit api.zotero.org, so we assert
+ * they exist but never click them.
+ *
+ * Run: node test_zotero_integration_ci.js
+ */
+const { setupTest, teardownTest, TestResults, log, navigateTo, withTimeout } = require('./test_lib');
+
+const zoteroUrl = (baseUrl) => `${baseUrl}/library/zotero`;
+
+async function waitForForm(page) {
+ await page.waitForSelector('#zotero-config-form', { timeout: 15000 });
+ // loadConfig() populates the fields; wait until the library-type select
+ // has been initialised so we know the config fetch resolved.
+ await page
+ .waitForFunction(() => document.getElementById('zt-library-type')?.value?.length > 0, { timeout: 15000 })
+ .catch(() => {});
+}
+
+// ============================================================================
+// Zotero Page Structure Tests
+// ============================================================================
+const ZoteroPageTests = {
+ async zoteroPageLoads(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(() => {
+ const heading = document.querySelector('.ldr-zotero-wrap h1');
+ return {
+ hasWrap: !!document.querySelector('.ldr-zotero-wrap'),
+ headingText: heading?.textContent?.trim(),
+ hasForm: !!document.getElementById('zotero-config-form'),
+ hasStatusCard: !!document.getElementById('zotero-status'),
+ };
+ });
+
+ const passed = result.hasWrap && /zotero/i.test(result.headingText || '') && result.hasForm && result.hasStatusCard;
+ return {
+ passed,
+ message: passed
+ ? `Zotero page loaded (heading "${result.headingText}", config form + status card present)`
+ : `Zotero page missing structure (wrap=${result.hasWrap}, heading="${result.headingText}", form=${result.hasForm}, status=${result.hasStatusCard})`,
+ };
+ },
+
+ async actionAndSaveButtonsPresent(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(() => {
+ const ids = ['zotero-save', 'zotero-test', 'zotero-groups', 'zotero-list', 'zotero-sync'];
+ const found = {};
+ for (const id of ids) found[id] = !!document.getElementById(id);
+ return { found, syncIsPrimary: document.getElementById('zotero-sync')?.classList.contains('ldr-zotero-primary') };
+ });
+
+ const missing = Object.entries(result.found).filter(([, v]) => !v).map(([k]) => k);
+ const passed = missing.length === 0;
+ return {
+ passed,
+ message: passed
+ ? `Save + all 4 action buttons present (sync primary=${result.syncIsPrimary})`
+ : `Missing buttons: ${missing.join(', ')}`,
+ };
+ },
+
+ async configFormRenders(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+
+ const result = await page.evaluate(() => {
+ const ids = ['zt-enabled', 'zt-local', 'zt-library-type', 'zt-library-id', 'zt-api-key',
+ 'zt-collections', 'zt-without-pdf', 'zt-annotations', 'zt-tags', 'zt-pdf-storage',
+ 'zt-auto-sync', 'zt-interval'];
+ const missing = ids.filter((id) => !document.getElementById(id));
+ return {
+ missing,
+ libraryType: document.getElementById('zt-library-type')?.value,
+ // A fresh user default: import-without-pdf is on.
+ withoutPdf: document.getElementById('zt-without-pdf')?.checked,
+ intervalHasValue: (document.getElementById('zt-interval')?.value || '').length > 0,
+ };
+ });
+
+ const passed = result.missing.length === 0 && !!result.libraryType && result.intervalHasValue;
+ return {
+ passed,
+ message: passed
+ ? `Config form renders + populates (library type="${result.libraryType}", import-without-pdf=${result.withoutPdf})`
+ : `Config form incomplete (missing=[${result.missing}], libraryType="${result.libraryType}")`,
+ };
+ },
+
+ async apiKeyFieldWriteOnly(page, baseUrl) {
+ // Security: the API key input must be a password field that is NEVER
+ // pre-filled with the stored secret (the config endpoint doesn't return
+ // it, and the form must not reconstruct it).
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+
+ const result = await page.evaluate(() => {
+ const el = document.getElementById('zt-api-key');
+ return { type: el?.type, value: el?.value, autocomplete: el?.getAttribute('autocomplete') };
+ });
+
+ const passed = result.type === 'password' && result.value === '';
+ return {
+ passed,
+ message: passed
+ ? `API key field is write-only (type=password, empty, autocomplete="${result.autocomplete}")`
+ : `API key field leaks/exposes (type=${result.type}, valueLen=${(result.value || '').length})`,
+ };
+ },
+
+ async intervalInputMatchesBackendConstraints(page, baseUrl) {
+ // Regression guard: the interval input's min/max/step must match the
+ // zotero.sync_interval_minutes setting (15 / 10080 / 15). A mismatch
+ // (e.g. min=60 step=30) makes HTML5 validation block saving whenever a
+ // backend-valid value like 45 is present.
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+
+ const attrs = await page.evaluate(() => {
+ const el = document.getElementById('zt-interval');
+ return { min: el?.getAttribute('min'), max: el?.getAttribute('max'), step: el?.getAttribute('step') };
+ });
+
+ const passed = attrs.min === '15' && attrs.max === '10080' && attrs.step === '15';
+ return {
+ passed,
+ message: passed
+ ? 'Interval input constraints match the backend (min=15, max=10080, step=15)'
+ : `Interval input constraints mismatch backend (${JSON.stringify(attrs)}; expected min=15,max=10080,step=15)`,
+ };
+ },
+
+ async formAccessibility(page, baseUrl) {
+ // Every form control needs an accessible name (label[for], aria-label,
+ // or a wrapping label), and the status regions must be aria-live so
+ // screen readers announce "Saved." / errors.
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+
+ const result = await page.evaluate(() => {
+ const hasName = (id) => {
+ const el = document.getElementById(id);
+ if (!el) return false;
+ if (el.getAttribute('aria-label')) return true;
+ if (document.querySelector(`label[for="${id}"]`)) return true;
+ if (el.closest('label')) return true;
+ return false;
+ };
+ const isLive = (id) => {
+ const el = document.getElementById(id);
+ return !!el && (el.getAttribute('aria-live') === 'polite' || el.getAttribute('role') === 'status');
+ };
+ const controls = ['zt-enabled', 'zt-local', 'zt-library-type', 'zt-library-id', 'zt-api-key',
+ 'zt-collections', 'zt-without-pdf', 'zt-annotations', 'zt-tags', 'zt-pdf-storage',
+ 'zt-auto-sync', 'zt-interval'];
+ return {
+ unnamed: controls.filter((id) => !hasName(id)),
+ msgLive: isLive('zotero-msg'),
+ saveMsgLive: isLive('zotero-save-msg'),
+ };
+ });
+
+ const passed = result.unnamed.length === 0 && result.msgLive && result.saveMsgLive;
+ return {
+ passed,
+ message: passed
+ ? 'All form controls have accessible names; status regions are aria-live'
+ : `A11y gaps (unnamed=[${result.unnamed}], msgLive=${result.msgLive}, saveMsgLive=${result.saveMsgLive})`,
+ };
+ },
+
+ async pickerCardsHiddenInitially(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(() => {
+ const isHidden = (id) => {
+ const el = document.getElementById(id);
+ return !el || getComputedStyle(el).display === 'none';
+ };
+ return {
+ hasGroups: !!document.getElementById('zotero-groups-card'),
+ hasCollections: !!document.getElementById('zotero-collections-card'),
+ groupsHidden: isHidden('zotero-groups-card'),
+ collectionsHidden: isHidden('zotero-collections-card'),
+ };
+ });
+
+ const passed = result.hasGroups && result.hasCollections && result.groupsHidden && result.collectionsHidden;
+ return {
+ passed,
+ message: passed
+ ? 'Groups + collections picker cards exist and are hidden until their buttons are clicked'
+ : `Picker card visibility wrong (${JSON.stringify(result)})`,
+ };
+ },
+
+ async noConsoleErrors(page, baseUrl) {
+ const errors = [];
+ const handler = (msg) => {
+ if (msg.type() === 'error') errors.push(msg.text());
+ };
+ page.on('console', handler);
+ try {
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+ } finally {
+ page.off('console', handler);
+ }
+
+ const critical = errors.filter((e) => !/favicon|net::ERR_ABORTED|ResizeObserver/i.test(e));
+ const passed = critical.length === 0;
+ return {
+ passed,
+ message: passed ? 'No critical console errors during Zotero page load' : `Console errors: ${critical.slice(0, 3).join(' | ')}`,
+ };
+ },
+};
+
+// ============================================================================
+// Zotero API Contract Tests
+// ============================================================================
+const ZoteroApiTests = {
+ async configApiContract(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(async () => {
+ const res = await fetch('/library/api/zotero/config', { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
+ const data = await res.json().catch(() => ({}));
+ return { status: res.status, data };
+ });
+
+ const d = result.data || {};
+ const expectedKeys = ['enabled', 'configured', 'has_api_key', 'library_type', 'auto_sync_enabled'];
+ const missingKeys = expectedKeys.filter((k) => !(k in d));
+ const leaksSecret = 'api_key' in d || 'apiKey' in d;
+ const passed = result.status === 200 && d.success === true && missingKeys.length === 0 && !leaksSecret;
+ return {
+ passed,
+ message: passed
+ ? `Config API returns non-secret summary (has_api_key=${d.has_api_key}, no raw api_key field)`
+ : `Config API contract failed (status=${result.status}, success=${d.success}, missingKeys=[${missingKeys}], leaksSecret=${leaksSecret})`,
+ };
+ },
+
+ async statusApiResponds(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(async () => {
+ const res = await fetch('/library/api/zotero/status', { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
+ const data = await res.json().catch(() => ({}));
+ return { status: res.status, data };
+ });
+
+ const d = result.data || {};
+ const passed = result.status === 200 && d.success === true && Array.isArray(d.collections);
+ return {
+ passed,
+ message: passed
+ ? `Status API responds (collections=${d.collections.length} — table exists, no 500)`
+ : `Status API failed (status=${result.status}, ${JSON.stringify(d)})`,
+ };
+ },
+
+ async testConnectionUnconfigured(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(async () => {
+ const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
+ const res = await fetch('/library/api/zotero/test', {
+ method: 'POST', headers: { Accept: 'application/json', 'X-CSRFToken': csrf }, credentials: 'same-origin',
+ });
+ const data = await res.json().catch(() => ({}));
+ return { status: res.status, data };
+ });
+
+ const d = result.data || {};
+ const passed = d.success === false && typeof d.error === 'string' && /library|api key/i.test(d.error);
+ return {
+ passed,
+ message: passed ? `Test-connection cleanly rejects unconfigured user ("${d.error}")` : `Unexpected response (status=${result.status}, ${JSON.stringify(d)})`,
+ };
+ },
+
+ async syncUnconfiguredRejected(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(async () => {
+ const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
+ const res = await fetch('/library/api/zotero/sync', {
+ method: 'POST', headers: { Accept: 'application/json', 'X-CSRFToken': csrf }, credentials: 'same-origin',
+ });
+ const data = await res.json().catch(() => ({}));
+ return { status: res.status, data };
+ });
+
+ const d = result.data || {};
+ const passed = result.status === 400 && d.success === false && /not enabled|not configured/i.test(d.error || '');
+ return {
+ passed,
+ message: passed
+ ? 'Sync endpoint rejects unconfigured user with 400 (no background thread / external call)'
+ : `Unexpected sync response (status=${result.status}, ${JSON.stringify(d)})`,
+ };
+ },
+
+ async syncPostRequiresCsrf(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+
+ const result = await page.evaluate(async () => {
+ const res = await fetch('/library/api/zotero/sync', { method: 'POST', headers: { Accept: 'application/json' }, credentials: 'same-origin' });
+ return { status: res.status };
+ });
+
+ const passed = result.status === 400 || result.status === 403;
+ return {
+ passed,
+ message: passed ? `Sync POST without CSRF token is rejected (status ${result.status})` : `CSRF not enforced on sync POST (status ${result.status})`,
+ };
+ },
+};
+
+// ============================================================================
+// Config Form Behaviour Tests
+// ============================================================================
+const ZoteroFormTests = {
+ async actionButtonsGatedWhenUnconfigured(page, baseUrl) {
+ // Actions operate on SAVED settings, so until Zotero is configured the
+ // List/Groups/Sync buttons are disabled; Test connection stays enabled.
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+ await page.waitForFunction(() => document.getElementById('zotero-sync')?.disabled === true, { timeout: 10000 }).catch(() => {});
+
+ const state = await page.evaluate(() => {
+ const dis = (id) => document.getElementById(id)?.disabled;
+ return { sync: dis('zotero-sync'), list: dis('zotero-list'), groups: dis('zotero-groups'), test: dis('zotero-test') };
+ });
+
+ const passed = state.sync === true && state.list === true && state.groups === true && state.test === false;
+ return {
+ passed,
+ message: passed ? 'Unconfigured: List/Groups/Sync disabled, Test connection enabled' : `Unexpected gating: ${JSON.stringify(state)}`,
+ };
+ },
+
+ async testButtonShowsError(page, baseUrl) {
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await page.waitForSelector('#zotero-test', { timeout: 10000 });
+ await page.click('#zotero-test');
+
+ try {
+ await page.waitForFunction(
+ () => {
+ const m = document.getElementById('zotero-msg');
+ return m && m.classList.contains('ldr-zotero-err') && m.textContent.trim().length > 0;
+ },
+ { timeout: 10000 },
+ );
+ } catch {
+ const msg = await page.evaluate(() => document.getElementById('zotero-msg')?.textContent);
+ return { passed: false, message: `Test button did not surface an error (msg="${msg}")` };
+ }
+
+ const text = await page.evaluate(() => document.getElementById('zotero-msg')?.textContent?.trim());
+ return { passed: true, message: `Test button wired: shows credential error for unconfigured user ("${text}")` };
+ },
+
+ async saveSettingsRoundTrip(page, baseUrl) {
+ // End-to-end: edit the form, Save, and confirm it persisted via the
+ // config API and re-gated the actions. Uses local-API mode (no key, no
+ // external call) and restores the unconfigured state afterwards so it
+ // doesn't pollute other tests.
+ await navigateTo(page, zoteroUrl(baseUrl));
+ await waitForForm(page);
+
+ const TEST_ID = '9999999';
+ // 45 is backend-valid (min 15, step 15) but was BLOCKED by the old form
+ // (min=60, step=30) — persisting it proves the constraint fix.
+ const TEST_INTERVAL = 45;
+ await page.evaluate((id, interval) => {
+ document.getElementById('zt-enabled').checked = true;
+ const local = document.getElementById('zt-local');
+ local.checked = true;
+ local.dispatchEvent(new Event('change'));
+ document.getElementById('zt-library-id').value = id;
+ document.getElementById('zt-auto-sync').checked = true;
+ document.getElementById('zt-interval').value = String(interval);
+ }, TEST_ID, TEST_INTERVAL);
+
+ await page.click('#zotero-save');
+ await page
+ .waitForFunction(() => /saved/i.test(document.getElementById('zotero-save-msg')?.textContent || ''), { timeout: 10000 })
+ .catch(() => {});
+
+ const outcome = await page.evaluate(async () => {
+ const saveMsg = document.getElementById('zotero-save-msg')?.textContent?.trim();
+ const res = await fetch('/library/api/zotero/config', { headers: { Accept: 'application/json' } });
+ const cfg = await res.json().catch(() => ({}));
+ const syncDisabled = document.getElementById('zotero-sync')?.disabled;
+ return { saveMsg, cfg, syncDisabled };
+ });
+
+ const c = outcome.cfg || {};
+ const persisted = c.enabled === true && c.use_local_api === true && c.library_id === TEST_ID
+ && c.configured === true && c.sync_interval_minutes === TEST_INTERVAL;
+ // Configuring via local API should enable the Sync button.
+ const passed = /saved/i.test(outcome.saveMsg || '') && persisted && outcome.syncDisabled === false;
+ const message = passed
+ ? `Save round-trip works: settings persisted (enabled, local API, library ${TEST_ID}, interval ${TEST_INTERVAL}) and Sync enabled`
+ : `Save round-trip failed (msg="${outcome.saveMsg}", enabled=${c.enabled}, local=${c.use_local_api}, id=${c.library_id}, interval=${c.sync_interval_minutes}, configured=${c.configured}, syncDisabled=${outcome.syncDisabled})`;
+
+ // Best-effort restore: put the user back to unconfigured.
+ await page
+ .evaluate(async () => {
+ const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
+ await fetch('/settings/save_all_settings', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf },
+ body: JSON.stringify({
+ 'zotero.enabled': false,
+ 'zotero.use_local_api': false,
+ 'zotero.library_id': '',
+ 'zotero.auto_sync_enabled': false,
+ }),
+ });
+ })
+ .catch(() => {});
+
+ return { passed, message };
+ },
+};
+
+// ============================================================================
+// Sidebar Navigation Test
+// ============================================================================
+const ZoteroNavTests = {
+ async sidebarHasZoteroLink(page, baseUrl) {
+ await navigateTo(page, `${baseUrl}/library`);
+
+ const result = await page.evaluate(() => {
+ const link = document.querySelector('a[href*="/library/zotero"]');
+ return { found: !!link, text: link?.textContent?.trim(), nested: !!link?.closest('.ldr-sidebar-item--nested') };
+ });
+
+ return {
+ passed: result.found,
+ message: result.found ? `Sidebar has Zotero link ("${result.text}", nested under Library=${result.nested})` : 'No Zotero link found in sidebar',
+ };
+ },
+};
+
+// ============================================================================
+// Main Test Runner
+// ============================================================================
+async function main() {
+ log.section('Zotero Integration Tests');
+
+ const ctx = await setupTest({ authenticate: true });
+ const results = new TestResults('Zotero Integration Tests');
+ const { page } = ctx;
+ const { baseUrl } = ctx.config;
+
+ const subTestTimeout = ctx.config.isCI ? 60000 : 30000;
+ async function run(category, name, testFn) {
+ try {
+ const result = await withTimeout(testFn(page, baseUrl), subTestTimeout, `${category}/${name}`);
+ if (result.skipped) {
+ results.skip(category, name, result.message);
+ } else {
+ results.add(category, name, result.passed, result.message);
+ }
+ } catch (error) {
+ results.add(category, name, false, `Error: ${error.message}`);
+ }
+ }
+
+ try {
+ log.section('Zotero Page');
+ await run('Page', 'Zotero Page Loads', (p, u) => ZoteroPageTests.zoteroPageLoads(p, u));
+ await run('Page', 'Action + Save Buttons Present', (p, u) => ZoteroPageTests.actionAndSaveButtonsPresent(p, u));
+ await run('Page', 'Config Form Renders', (p, u) => ZoteroPageTests.configFormRenders(p, u));
+ await run('Page', 'API Key Field Write-Only', (p, u) => ZoteroPageTests.apiKeyFieldWriteOnly(p, u));
+ await run('Page', 'Interval Input Matches Backend Constraints', (p, u) => ZoteroPageTests.intervalInputMatchesBackendConstraints(p, u));
+ await run('Page', 'Form Accessibility (names + aria-live)', (p, u) => ZoteroPageTests.formAccessibility(p, u));
+ await run('Page', 'Picker Cards Hidden Initially', (p, u) => ZoteroPageTests.pickerCardsHiddenInitially(p, u));
+ await run('Page', 'No Console Errors', (p, u) => ZoteroPageTests.noConsoleErrors(p, u));
+
+ log.section('Zotero APIs');
+ await run('API', 'Config API Contract (no secret leak)', (p, u) => ZoteroApiTests.configApiContract(p, u));
+ await run('API', 'Status API Responds', (p, u) => ZoteroApiTests.statusApiResponds(p, u));
+ await run('API', 'Test Connection Unconfigured', (p, u) => ZoteroApiTests.testConnectionUnconfigured(p, u));
+ await run('API', 'Sync Unconfigured Rejected', (p, u) => ZoteroApiTests.syncUnconfiguredRejected(p, u));
+ await run('API', 'Sync POST Requires CSRF', (p, u) => ZoteroApiTests.syncPostRequiresCsrf(p, u));
+
+ log.section('Zotero Config Form');
+ await run('Form', 'Action Buttons Gated When Unconfigured', (p, u) => ZoteroFormTests.actionButtonsGatedWhenUnconfigured(p, u));
+ await run('Form', 'Test Button Shows Error', (p, u) => ZoteroFormTests.testButtonShowsError(p, u));
+ // Mutates + restores config — keep LAST so earlier "unconfigured" tests are unaffected.
+ await run('Form', 'Save Settings Round-Trip', (p, u) => ZoteroFormTests.saveSettingsRoundTrip(p, u));
+
+ log.section('Zotero Navigation');
+ await run('Nav', 'Sidebar Has Zotero Link', (p, u) => ZoteroNavTests.sidebarHasZoteroLink(p, u));
+ } catch (error) {
+ log.error(`Fatal error: ${error.message}`);
+ console.error(error.stack);
+ } finally {
+ results.print();
+ results.save();
+ await teardownTest(ctx);
+ process.exit(results.exitCode());
+ }
+}
+
+if (require.main === module) {
+ main().catch((error) => {
+ console.error('Test runner failed:', error);
+ process.exit(1);
+ });
+}
+
+module.exports = { ZoteroPageTests, ZoteroApiTests, ZoteroFormTests, ZoteroNavTests };