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 standalone PDF attachments; clearer config errors (#4960)

LearningCircuit67f0fb8ff6c0
diff --git a/changelog.d/4960.feature.md b/changelog.d/4960.feature.md
new file mode 100644
index 0000000000..18adaad077
--- /dev/null
+++ b/changelog.d/4960.feature.md
@@ -0,0 +1,8 @@
+Zotero integration polish from first real-world testing: standalone PDF
+attachments (PDFs added without a parent item) now import as documents;
+the library ID is auto-detected from the API key (usernames resolve
+too); manual syncs re-examine previously skipped items; imports appear
+in the main Library view; a live progress bar tracks syncs; the config
+page autosaves with essentials-first layout and runs the connection
+test on saving a key; friendlier defaults (text-only PDF storage,
+integration enabled once a key is set) and actionable error messages.
diff --git a/src/local_deep_research/defaults/settings_zotero.json b/src/local_deep_research/defaults/settings_zotero.json
index c0e8c9b3f0..3a4763c3ad 100644
--- a/src/local_deep_research/defaults/settings_zotero.json
+++ b/src/local_deep_research/defaults/settings_zotero.json
@@ -1,7 +1,7 @@
{
"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.",
+ "description": "Enable the Zotero integration (on by default; nothing runs until an API key is configured). Turn off to pause all Zotero syncing without removing your credentials.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -10,7 +10,7 @@
"step": null,
"type": "APP",
"ui_element": "checkbox",
- "value": false,
+ "value": true,
"visible": true
},
"zotero.use_local_api": {
@@ -61,7 +61,7 @@
},
"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.",
+ "description": "Numeric library ID. Optional for personal libraries — it is detected automatically from the API key (a pasted username is resolved too). Required for group libraries: the group's numeric ID (use the group picker, or the number in the group's URL).",
"editable": true,
"max_value": null,
"min_value": null,
@@ -103,7 +103,7 @@
},
"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.",
+ "description": "Import items that have no attached PDF, using only their title/abstract/metadata as a text-only document. Off by default and generally discouraged: without full text, research over these documents is shallow — prefer attaching the PDF in Zotero. If enabled later, applies to already-skipped items on the next manual Sync now.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -112,7 +112,7 @@
"step": null,
"type": "APP",
"ui_element": "checkbox",
- "value": true,
+ "value": false,
"visible": true
},
"zotero.import_annotations": {
@@ -131,7 +131,7 @@
},
"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).",
+ "description": "How to store imported PDFs. 'none' (default) stores only the extracted, indexed text — all that research needs, and much smaller. 'database' additionally keeps the full PDF inside your encrypted database so you can open the original.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -143,7 +143,7 @@
"step": null,
"type": "APP",
"ui_element": "select",
- "value": "database",
+ "value": "none",
"visible": true
},
"zotero.auto_sync_enabled": {
diff --git a/src/local_deep_research/research_library/routes/zotero_routes.py b/src/local_deep_research/research_library/routes/zotero_routes.py
index 629cd9ff14..7f08676fbd 100644
--- a/src/local_deep_research/research_library/routes/zotero_routes.py
+++ b/src/local_deep_research/research_library/routes/zotero_routes.py
@@ -14,9 +14,15 @@ from loguru import logger
from ...database.session_passwords import session_password_store
from ...database.thread_local_session import thread_cleanup
+from ...security import sanitize_error_for_client
from ...web.auth.decorators import login_required
from ..utils import handle_api_error
-from ..zotero import ZoteroSyncService
+from ..zotero import (
+ ZoteroAuthError,
+ ZoteroError,
+ ZoteroSyncService,
+ ZoteroTransientError,
+)
zotero_bp = Blueprint("zotero", __name__, url_prefix="/library")
@@ -28,6 +34,15 @@ def _db_password() -> str | None:
)
+def _zotero_error_status(exc: ZoteroError) -> int:
+ """Map a Zotero client error to the matching HTTP status."""
+ if isinstance(exc, ZoteroAuthError):
+ return 401
+ if isinstance(exc, ZoteroTransientError):
+ return 503
+ return 400
+
+
def _session_expired_response():
"""401 for a logged-in session whose cached DB password has expired.
@@ -109,6 +124,13 @@ def list_collections():
session["username"], password
).list_collections()
return jsonify({"success": True, "collections": collections})
+ except ZoteroError as e:
+ # Zotero-side rejections carry actionable, static messages (bad
+ # library ID, revoked key, …) — surface them instead of a 500,
+ # with a status code matching the failure class.
+ return jsonify(
+ {"success": False, "error": sanitize_error_for_client(str(e))}
+ ), _zotero_error_status(e)
except Exception as e:
return handle_api_error("listing Zotero collections", e)
@@ -123,6 +145,10 @@ def list_groups():
try:
groups = ZoteroSyncService(session["username"], password).list_groups()
return jsonify({"success": True, "groups": groups})
+ except ZoteroError as e:
+ return jsonify(
+ {"success": False, "error": sanitize_error_for_client(str(e))}
+ ), _zotero_error_status(e)
except Exception as e:
return handle_api_error("listing Zotero groups", e)
@@ -171,7 +197,12 @@ def sync_now():
# sync would strand a pooled connection and the plaintext password.
with app.app_context(), thread_cleanup():
try:
- result = ZoteroSyncService(username, password).sync_all()
+ # Manual syncs re-examine previously skipped items so
+ # settings changes apply without waiting for the items to
+ # change in Zotero (scheduled syncs stay cheap).
+ result = ZoteroSyncService(username, password).sync_all(
+ reprocess_skipped=True
+ )
logger.info(f"Zotero manual sync finished: {result}")
except Exception:
logger.exception("Zotero manual sync failed")
@@ -191,6 +222,16 @@ def get_status():
return _session_expired_response()
try:
status = ZoteroSyncService(session["username"], password).get_status()
- return jsonify({"success": True, "collections": status})
+ return jsonify(
+ {
+ "success": True,
+ "collections": status,
+ # Live counters while a sync runs (None when idle) — lets
+ # the page render a real progress bar during long imports.
+ "progress": ZoteroSyncService.get_sync_progress(
+ session["username"]
+ ),
+ }
+ )
except Exception as e:
return handle_api_error("getting Zotero status", e)
diff --git a/src/local_deep_research/research_library/zotero/client.py b/src/local_deep_research/research_library/zotero/client.py
index 9f5f39b5e8..9d95b4415a 100644
--- a/src/local_deep_research/research_library/zotero/client.py
+++ b/src/local_deep_research/research_library/zotero/client.py
@@ -131,6 +131,37 @@ class ZoteroItem:
return att
return None
+ @property
+ def is_standalone_pdf_attachment(self) -> bool:
+ """A top-level stored PDF with no bibliographic parent.
+
+ This is what Zotero creates when a PDF is dropped straight into the
+ library without "Retrieve Metadata" / "Create Parent Item" — very
+ common in real libraries. It carries no metadata beyond a filename,
+ but the PDF itself is fully retrievable, so it is importable as its
+ own document. ``linked_file`` attachments are excluded (the Web API
+ cannot serve them).
+ """
+ return (
+ self.item_type == "attachment"
+ and not self.data.get("parentItem")
+ and (self.data.get("contentType") or "").lower()
+ == "application/pdf"
+ and (self.data.get("linkMode") or "").lower()
+ in ("imported_file", "imported_url")
+ )
+
+ def as_attachment(self) -> ZoteroAttachment:
+ """View this standalone attachment item as its own attachment."""
+ return ZoteroAttachment(
+ key=self.key,
+ version=self.version,
+ content_type=self.data.get("contentType"),
+ link_mode=self.data.get("linkMode"),
+ filename=self.data.get("filename"),
+ title=self.data.get("title") or self.data.get("filename"),
+ )
+
def _sleep_for_backoff(headers, attempt: int) -> None:
"""Honor Zotero ``Backoff`` / ``Retry-After`` headers (capped)."""
@@ -300,6 +331,15 @@ class ZoteroClient:
# When the caller manages redirects itself, hand back the 3xx.
if not allow_redirects and 300 <= status < 400:
return response
+ if status == 400:
+ # The most common cause by far: a username (or other
+ # non-numeric value) in the library-ID setting.
+ raise ZoteroError(
+ "Zotero rejected the request (HTTP 400). This usually "
+ "means the library ID is not the NUMERIC userID / group "
+ "ID from zotero.org/settings/keys (e.g. a username was "
+ "entered instead)."
+ )
if not (200 <= status < 300):
raise ZoteroError(f"Zotero request failed (HTTP {status})")
@@ -332,6 +372,21 @@ class ZoteroClient:
)
return self._library_version(response)
+ def get_current_key_info(self) -> Dict:
+ """Return ``/keys/current``: the key's owner ``userID`` + access map.
+
+ Cloud API only (the local API has no key); returns ``{}`` in local
+ mode or when the response isn't JSON. Used to resolve the numeric
+ userID when the user pasted a username into the library-ID field.
+ """
+ if self.local:
+ return {}
+ response = self._request("/keys/current", prefixed=False)
+ try:
+ return response.json() or {}
+ except ValueError:
+ return {}
+
def get_collections(self) -> List[Dict]:
"""List all collections in the library (paginated).
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index c2f2d1feb4..494dd3ba52 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -23,9 +23,10 @@ Known limitations (v1):
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.
+- Toggling ``import_items_without_pdf`` (or the tag filter) does not apply
+ to already-skipped items on SCHEDULED syncs — run a manual "Sync now"
+ (which re-examines skipped items), or wait for the items to change in
+ Zotero.
"""
import hashlib
@@ -76,15 +77,21 @@ from .client import (
class ZoteroConfig:
"""Snapshot of the user's Zotero settings."""
- enabled: bool = False
+ # On by default — inert until an API key is configured; the toggle is an
+ # opt-out kill-switch, not a required opt-in step.
+ enabled: bool = True
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
+ # Off by default: metadata/abstract-only documents carry no full text,
+ # which is what LDR's research actually needs.
+ import_items_without_pdf: bool = False
import_annotations: bool = False
- pdf_storage_mode: str = "database"
+ # Text-only by default: the extracted text is what research uses, and it
+ # keeps the encrypted DB small. "database" additionally keeps the PDF.
+ pdf_storage_mode: str = "none"
auto_sync_enabled: bool = False
sync_interval_minutes: int = 360
use_local_api: bool = False
@@ -92,9 +99,15 @@ class ZoteroConfig:
@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.
+ # Zotero on localhost); the web API needs one. A library ID is only
+ # required for GROUP libraries: a personal library is identified by
+ # the key itself (resolved via /keys/current), and the local API
+ # addresses the current desktop user as user 0.
has_auth = self.use_local_api or bool(self.api_key)
- return bool(self.enabled and has_auth and self.library_id)
+ needs_id = self.library_type == "group"
+ return bool(
+ self.enabled and has_auth and (self.library_id or not needs_id)
+ )
@property
def targets(self) -> List[str]:
@@ -109,6 +122,13 @@ class ZoteroConfig:
_user_sync_locks: dict[str, threading.Lock] = {}
_user_sync_locks_guard = threading.Lock()
+# Live progress of the currently running sync, per user — read by the status
+# endpoint while a sync runs so the UI can show a real progress bar.
+# In-memory on purpose: progress is transient, and both sync entry points
+# (manual daemon thread, scheduler job) run in this process.
+_user_sync_progress: dict[str, Dict] = {}
+_user_sync_progress_guard = threading.Lock()
+
def _get_user_sync_lock(username: str) -> threading.Lock:
with _user_sync_locks_guard:
@@ -129,6 +149,9 @@ class ZoteroSyncService:
):
self.username = username
self.password = password # gitleaks:allow
+ # Cached /keys/current lookup ("" = resolution failed) so one service
+ # instance resolves the key's userID at most once.
+ self._resolved_user_id: Optional[str] = None
# -- settings ----------------------------------------------------------
@@ -151,7 +174,7 @@ class ZoteroSyncService:
except (TypeError, ValueError):
interval = 360
return ZoteroConfig(
- enabled=sm.get_bool_setting("zotero.enabled", False),
+ enabled=sm.get_bool_setting("zotero.enabled", True),
api_key=str(sm.get_setting("zotero.api_key", "") or "").strip(),
library_type=str(
sm.get_setting("zotero.library_type", "user") or "user"
@@ -162,14 +185,13 @@ class ZoteroSyncService:
collection_keys=collection_keys,
import_tags=import_tags,
import_items_without_pdf=sm.get_bool_setting(
- "zotero.import_items_without_pdf", True
+ "zotero.import_items_without_pdf", False
),
import_annotations=sm.get_bool_setting(
"zotero.import_annotations", False
),
pdf_storage_mode=str(
- sm.get_setting("zotero.pdf_storage_mode", "database")
- or "database"
+ sm.get_setting("zotero.pdf_storage_mode", "none") or "none"
).strip(),
auto_sync_enabled=sm.get_bool_setting(
"zotero.auto_sync_enabled", False
@@ -188,6 +210,66 @@ class ZoteroSyncService:
local=cfg.use_local_api,
)
+ def _resolve_library_id(self, cfg: ZoteroConfig) -> Optional[str]:
+ """Normalize ``cfg.library_id`` in place; returns an error or None.
+
+ A personal library needs no manually entered ID: the API key
+ identifies its owner, so an empty or non-numeric value (a username,
+ say) is resolved to the numeric userID via ``/keys/current``. Local
+ mode addresses the desktop's current user as ``0``. Only group
+ libraries must carry an explicit numeric group ID.
+
+ Called by the operational entry points (test/list/sync) — NOT by
+ :meth:`get_config`, which must stay network-free (the config
+ endpoint reads it on every page load).
+ """
+ lid = cfg.library_id
+ if cfg.library_type == "group":
+ if not lid.isdigit():
+ return (
+ "Zotero group libraries need the numeric group ID — use "
+ "the group picker, or the number in the group's URL on "
+ "zotero.org."
+ )
+ return None
+ if cfg.use_local_api:
+ if not lid:
+ # The local API addresses the desktop's current user as 0.
+ cfg.library_id = "0"
+ return None
+ if lid.isdigit():
+ return None
+ # Personal library with an empty or non-numeric ID (e.g. a username):
+ # the key knows its owner — resolve and use the real userID.
+ if self._resolved_user_id is None:
+ try:
+ probe = ZoteroClient(
+ api_key=cfg.api_key, library_type="user", library_id="0"
+ )
+ with probe:
+ user_id = probe.get_current_key_info().get("userID")
+ self._resolved_user_id = str(user_id) if user_id else ""
+ except ZoteroError:
+ logger.debug(
+ "Zotero: could not resolve the key's userID via "
+ "/keys/current",
+ exc_info=True,
+ )
+ self._resolved_user_id = ""
+ if self._resolved_user_id:
+ if lid:
+ logger.info(
+ f"Zotero: library ID {lid!r} is not numeric — using the "
+ f"API key's userID {self._resolved_user_id} instead"
+ )
+ cfg.library_id = self._resolved_user_id
+ return None
+ return (
+ "Could not determine the Zotero userID from the API key — check "
+ "the key, or enter the numeric userID shown at "
+ "zotero.org/settings/keys."
+ )
+
def _library_root(self) -> str:
with get_user_db_session(self.username, self.password) as session:
sm = SettingsManager(session)
@@ -203,12 +285,15 @@ class ZoteroSyncService:
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):
+ if 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.",
+ "error": "A Zotero API key is required (unless using the "
+ "local API).",
}
+ resolve_error = self._resolve_library_id(cfg)
+ if resolve_error:
+ return {"success": False, "error": resolve_error}
try:
with self._make_client(cfg) as client:
version = client.test_connection()
@@ -227,12 +312,18 @@ class ZoteroSyncService:
def list_collections(self) -> List[Dict]:
"""List Zotero collections (for the UI picker)."""
cfg = self.get_config()
+ resolve_error = self._resolve_library_id(cfg)
+ if resolve_error:
+ raise ZoteroError(resolve_error)
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()
+ resolve_error = self._resolve_library_id(cfg)
+ if resolve_error:
+ raise ZoteroError(resolve_error)
with self._make_client(cfg) as client:
return client.get_groups()
@@ -242,12 +333,36 @@ class ZoteroSyncService:
lock = _user_sync_locks.get(username)
return bool(lock and lock.locked())
- def sync_all(self) -> Dict:
+ @classmethod
+ def get_sync_progress(cls, username: str) -> Optional[Dict]:
+ """Live progress of the user's running sync, or None when idle."""
+ if not cls.is_user_syncing(username):
+ return None
+ with _user_sync_progress_guard:
+ progress = _user_sync_progress.get(username)
+ return dict(progress) if progress else None
+
+ def _set_progress(self, **fields) -> None:
+ with _user_sync_progress_guard:
+ _user_sync_progress.setdefault(self.username, {}).update(fields)
+
+ def _clear_progress(self) -> None:
+ with _user_sync_progress_guard:
+ _user_sync_progress.pop(self.username, None)
+
+ def sync_all(self, reprocess_skipped: bool = False) -> 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.
+
+ ``reprocess_skipped`` re-examines items previously recorded without
+ a document (skipped strays, no-PDF items, tag-filter misses) even
+ though their Zotero version is unchanged. Manual "Sync now" sets it
+ so settings changes and newly importable item shapes apply without
+ waiting for the item to change in Zotero; scheduled syncs keep the
+ cheap version-diff.
"""
cfg = self.get_config()
if not cfg.is_configured:
@@ -255,6 +370,12 @@ class ZoteroSyncService:
"success": False,
"error": "Zotero is not enabled/configured.",
}
+ # Resolve BEFORE the per-collection loop so the sync-state rows are
+ # always keyed on the real numeric library ID, whatever the setting
+ # holds (empty for personal libraries, or even a pasted username).
+ resolve_error = self._resolve_library_id(cfg)
+ if resolve_error:
+ return {"success": False, "error": resolve_error}
lock = _get_user_sync_lock(self.username)
if not lock.acquire(blocking=False):
@@ -282,9 +403,15 @@ class ZoteroSyncService:
"collections": [],
}
try:
+ self._set_progress(phase="starting", done=0, total=None)
with self._make_client(cfg) as client:
for collection_key in cfg.targets:
- stats = self._sync_one(client, cfg, collection_key)
+ stats = self._sync_one(
+ client,
+ cfg,
+ collection_key,
+ reprocess_skipped=reprocess_skipped,
+ )
totals["imported"] += stats.get("imported", 0)
totals["updated"] += stats.get("updated", 0)
totals["removed"] += stats.get("removed", 0)
@@ -292,6 +419,7 @@ class ZoteroSyncService:
totals["errors"] += stats.get("errors", 0)
totals["collections"].append(stats)
finally:
+ self._clear_progress()
lock.release()
totals["success"] = all(
c.get("status") != "failed" for c in totals["collections"]
@@ -322,7 +450,11 @@ class ZoteroSyncService:
# -- per-collection sync ----------------------------------------------
def _sync_one(
- self, client: ZoteroClient, cfg: ZoteroConfig, collection_key: str
+ self,
+ client: ZoteroClient,
+ cfg: ZoteroConfig,
+ collection_key: str,
+ reprocess_skipped: bool = False,
) -> Dict:
"""Sync a single collection (``""`` = whole library)."""
stats = {
@@ -349,7 +481,12 @@ class ZoteroSyncService:
# 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] = []
+ # Subset of removed/released docs whose Document row was HARD-deleted:
+ # their vectors must also leave the default Library collection's index
+ # (a kept/foreign doc's default-collection vectors stay valid).
+ hard_deleted_doc_ids: List[str] = []
ldr_collection_id: Optional[str] = None
+ default_collection_id: Optional[str] = None
try:
with get_user_db_session(self.username, self.password) as session:
ldr_collection_id = self._ensure_ldr_collection(
@@ -361,6 +498,13 @@ class ZoteroSyncService:
state.last_status = "syncing"
session.commit()
+ self._set_progress(
+ phase="checking",
+ collection_key=collection_key or None, # gitleaks:allow
+ done=0,
+ total=None,
+ current=None,
+ )
remote_versions, library_version = client.get_top_item_versions(
collection_key or None
)
@@ -376,11 +520,28 @@ class ZoteroSyncService:
self.username, "zotero", self.password
)
+ # The default "Library" collection shows ALL documents, so
+ # imports are linked into it too (like uploads and research
+ # downloads). That membership is AMBIENT: the ownership /
+ # removal logic below ignores it when deciding whether a
+ # document is shared.
+ default_row = (
+ session.query(Collection.id)
+ .filter_by(is_default=True)
+ .first()
+ )
+ default_collection_id = default_row[0] if default_row else None
+
# 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).
+ to_remove = set(mapped) - remote_keys
+ if to_remove and (remote_keys or not mapped):
+ self._set_progress(
+ phase="removing", done=0, total=len(to_remove)
+ )
if remote_keys or not mapped:
- for key in set(mapped) - remote_keys:
+ for removal_index, key in enumerate(to_remove, start=1):
# 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
@@ -388,7 +549,10 @@ class ZoteroSyncService:
# sync — while every other removal proceeds.
try:
rid = self._remove_item(
- session, mapped[key], source_type_id
+ session,
+ mapped[key],
+ source_type_id,
+ default_collection_id,
)
session.commit()
except Exception:
@@ -400,7 +564,10 @@ class ZoteroSyncService:
continue
if rid:
removed_doc_ids.append(rid)
+ if not self._document_exists(session, rid):
+ hard_deleted_doc_ids.append(rid)
stats["removed"] += 1
+ self._set_progress(done=removal_index)
else:
logger.warning(
f"Zotero: empty item set for "
@@ -410,15 +577,19 @@ class ZoteroSyncService:
# 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.
+ # missing. On a scheduled sync we intentionally do NOT
+ # reprocess solely because document_id is None: that is the
+ # case for deliberately skipped (no-PDF, import-disabled,
+ # stray) items, which would otherwise be re-fetched on every
+ # sync forever. A manual sync (reprocess_skipped) re-examines
+ # them so settings changes and newly importable shapes take
+ # effect without waiting for the item to change in Zotero.
to_process = [
key
for key, version in remote_versions.items()
if key not in mapped
or mapped[key].zotero_version != version
+ or (reprocess_skipped and mapped[key].document_id is None)
or (
mapped[key].document_id is not None
and not self._document_exists(
@@ -433,21 +604,41 @@ class ZoteroSyncService:
max_pdf_size_mb=DEFAULT_MAX_PDF_SIZE_MB,
)
+ self._set_progress(
+ phase="importing",
+ done=0,
+ total=len(to_process),
+ current=None,
+ )
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",
+ self._set_progress(
+ done=len(returned_keys),
+ current=(item.data.get("title") or item.key)[:120],
+ )
+ # A top-level stored PDF with no bibliographic parent (a
+ # PDF dropped straight into Zotero) IS importable — it
+ # falls through to ingestion as its own document. Other
+ # attachment/note strays are not.
+ if not item.is_standalone_pdf_attachment and (
+ 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.
+ # Record the version so it isn't re-fetched every
+ # sync. A child that slipped into /top is plumbing
+ # (not counted); a genuine top-level stray (a note,
+ # or a non-PDF / linked-file attachment) counts as
+ # skipped so the sync result doesn't silently read
+ # as "nothing found".
self._touch_map_version(
session,
ldr_collection_id,
item.key,
item.version,
)
+ if not item.data.get("parentItem"):
+ stats["skipped"] += 1
continue
if cfg.import_tags and not self._item_has_tags(
item, cfg.import_tags
@@ -478,6 +669,7 @@ class ZoteroSyncService:
ldr_collection_id,
source_type_id,
pdf_storage,
+ default_collection_id,
)
except ZoteroTransientError:
# A rate-limit / 5xx (from a PDF/full-text fetch inside
@@ -520,6 +712,7 @@ class ZoteroSyncService:
ldr_collection_id,
prior_row.id,
source_type_id,
+ default_collection_id,
)
session.commit()
except Exception:
@@ -532,6 +725,8 @@ class ZoteroSyncService:
continue
if released:
released_doc_ids.append(released)
+ if not self._document_exists(session, released):
+ hard_deleted_doc_ids.append(released)
if action == "imported":
stats["imported"] += 1
@@ -617,6 +812,24 @@ class ZoteroSyncService:
self._cleanup_removed_vectors(
removed_doc_ids, ldr_collection_id
)
+ # The default Library collection carries every synced doc too
+ # (ambient membership), so its index needs the same care:
+ # in-place updates invalidate its copy of the vectors, and a
+ # hard-deleted document must not linger as dead hits there.
+ # Kept/foreign releases are deliberately NOT purged from it —
+ # their default-collection vectors are still valid.
+ if (
+ default_collection_id
+ and default_collection_id != ldr_collection_id
+ ):
+ if reindexed_doc_ids:
+ self._cleanup_removed_vectors(
+ reindexed_doc_ids, default_collection_id
+ )
+ if hard_deleted_doc_ids:
+ self._cleanup_removed_vectors(
+ hard_deleted_doc_ids, default_collection_id
+ )
# Auto-index outside the sync transaction (best-effort, async).
# Deliberately in the finally, ON FAILURE PATHS TOO: every id in
@@ -635,6 +848,17 @@ class ZoteroSyncService:
self.username,
self.password,
)
+ # Keep the default Library collection's index fresh too.
+ if (
+ default_collection_id
+ and default_collection_id != ldr_collection_id
+ ):
+ trigger_auto_index(
+ new_or_updated_doc_ids,
+ default_collection_id,
+ self.username,
+ self.password,
+ )
except Exception:
logger.exception("Zotero: failed to trigger auto-indexing")
@@ -809,6 +1033,7 @@ class ZoteroSyncService:
ldr_collection_id: str,
source_type_id: str,
pdf_storage: PDFStorageManager,
+ default_collection_id: Optional[str] = None,
) -> Tuple[Optional[str], str, bool]:
"""Create or update the LDR document for a Zotero item.
@@ -818,7 +1043,12 @@ class ZoteroSyncService:
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)
+ if item.is_standalone_pdf_attachment:
+ # A PDF dropped into Zotero with no bibliographic parent: the
+ # item IS its own attachment (it has no children to fetch).
+ item.attachments = [item.as_attachment()]
+ else:
+ item.attachments = client.get_children(item.key)
pdf_att = item.best_pdf_attachment()
pdf_bytes = None
@@ -906,6 +1136,11 @@ class ZoteroSyncService:
# 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)
+ if default_collection_id:
+ # The default "Library" collection lists all documents.
+ ensure_in_collection(
+ session, existing.id, default_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
@@ -921,13 +1156,17 @@ class ZoteroSyncService:
prior_mapping_id,
ldr_collection_id,
source_type_id,
+ default_collection_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
+ session,
+ existing.id,
+ ldr_collection_id,
+ default_collection_id,
)
return existing.id, "updated", True
# Content is byte-identical (matched by hash), so the existing
@@ -953,6 +1192,7 @@ class ZoteroSyncService:
prior_mapping_id,
ldr_collection_id,
source_type_id,
+ default_collection_id,
):
doc = None
@@ -1032,6 +1272,9 @@ class ZoteroSyncService:
)
ensure_in_collection(session, doc.id, ldr_collection_id)
+ if default_collection_id:
+ # The default "Library" collection lists all documents.
+ ensure_in_collection(session, doc.id, default_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
@@ -1040,7 +1283,9 @@ class ZoteroSyncService:
# 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)
+ self._purge_collection_chunks(
+ session, doc.id, ldr_collection_id, default_collection_id
+ )
return doc.id, ("imported" if created else "updated"), (not created)
@@ -1051,6 +1296,7 @@ class ZoteroSyncService:
mapping_id,
coll_id: str,
source_type_id: str,
+ default_collection_id: Optional[str] = None,
) -> 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
@@ -1058,6 +1304,10 @@ class ZoteroSyncService:
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.
+
+ Membership in the default "Library" collection is AMBIENT (every
+ import is linked there so the main library view lists it) and does
+ not count as another reference.
"""
if doc.source_type_id != source_type_id:
return False
@@ -1072,11 +1322,14 @@ class ZoteroSyncService:
)
if shared_mapping:
return False
+ ambient = {coll_id}
+ if default_collection_id:
+ ambient.add(default_collection_id)
linked_elsewhere = (
session.query(DocumentCollection.document_id)
.filter(
DocumentCollection.document_id == doc.id,
- DocumentCollection.collection_id != coll_id,
+ DocumentCollection.collection_id.notin_(ambient),
)
.first()
is not None
@@ -1084,24 +1337,35 @@ class ZoteroSyncService:
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.
+ def _purge_collection_chunks(
+ session,
+ doc_id: str,
+ coll_id: str,
+ default_collection_id: Optional[str] = None,
+ ) -> None:
+ """Purge a doc's RAG chunks and clear the link's indexed flag, forcing
+ a re-index after an in-place text change — for this collection AND
+ (when given) the default Library collection, whose ambient copy of
+ the chunks is derived from the same now-changed text.
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
+ targets = [coll_id]
+ if default_collection_id and default_collection_id != coll_id:
+ targets.append(default_collection_id)
+ for cid in targets:
+ CascadeHelper.delete_document_chunks(
+ session, doc_id, collection_name=f"collection_{cid}"
+ )
+ link = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=cid)
+ .first()
+ )
+ if link:
+ link.indexed = False
def _collect_annotations_text(
self, client: ZoteroClient, item: ZoteroItem
@@ -1285,6 +1549,10 @@ class ZoteroSyncService:
@staticmethod
def _filename_for(item: ZoteroItem, file_type: str) -> str:
title = (item.data.get("title") or "").strip()
+ # Standalone attachments carry the filename as their title — don't
+ # produce "paper.pdf.pdf".
+ if title.lower().endswith(f".{file_type}".lower()):
+ title = title[: -(len(file_type) + 1)]
candidate = f"{title[:120]}.{file_type}" if title else None
if candidate:
try:
@@ -1374,7 +1642,11 @@ class ZoteroSyncService:
)
def _remove_item(
- self, session, row: ZoteroItemMap, source_type_id: str
+ self,
+ session,
+ row: ZoteroItemMap,
+ source_type_id: str,
+ default_collection_id: Optional[str] = None,
) -> Optional[str]:
"""Remove an item that no longer exists in Zotero.
@@ -1398,6 +1670,7 @@ class ZoteroSyncService:
row.ldr_collection_id,
row.id,
source_type_id,
+ default_collection_id,
)
session.delete(row)
return released
@@ -1409,6 +1682,7 @@ class ZoteroSyncService:
coll_id: str,
keep_mapping_id,
source_type_id: str,
+ default_collection_id: Optional[str] = None,
) -> Optional[str]:
"""Release a document from this collection: drop its collection link and
RAG chunks, hard-deleting the document only when nothing else references
@@ -1454,10 +1728,17 @@ class ZoteroSyncService:
.first()
is not None
) or (
+ # Membership in the default "Library" collection is ambient
+ # (every import is linked there) — it must not keep a removed
+ # item's document alive.
session.query(DocumentCollection)
.filter(
DocumentCollection.document_id == doc_id,
- DocumentCollection.collection_id != coll_id,
+ DocumentCollection.collection_id.notin_(
+ {coll_id, default_collection_id}
+ if default_collection_id
+ else {coll_id}
+ ),
)
.first()
is not None
diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.html
index f1a986ea18..8d45f1a597 100644
--- a/src/local_deep_research/web/templates/pages/zotero.html
+++ b/src/local_deep_research/web/templates/pages/zotero.html
@@ -45,12 +45,6 @@
.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 {
@@ -75,6 +69,14 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
.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-hint-inline { align-self: center; margin-top: 0; }
+.ldr-zotero-advanced { margin: 14px 0 4px; border: 1px solid var(--border-color); border-radius: 8px; padding: 4px 14px; }
+.ldr-zotero-advanced summary { cursor: pointer; font-size: .9rem; color: var(--text-secondary, #999); padding: 8px 0; user-select: none; }
+.ldr-zotero-advanced[open] summary { margin-bottom: 6px; }
+.ldr-zotero-progress { margin: 0 0 10px; }
+.ldr-zotero-progress-label { font-size: .8rem; color: var(--text-secondary, #999); margin-bottom: 4px; word-break: break-word; }
+.ldr-zotero-progress-track { height: 8px; border-radius: 999px; background: var(--border-color); overflow: hidden; }
+.ldr-zotero-progress-fill { height: 100%; border-radius: 999px; background: var(--primary-color, #6e4ff6); width: 0%; transition: width .4s ease; }
.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>
@@ -95,10 +97,42 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
<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 for="zt-api-key">API key</label>
+ <div class="ldr-zotero-row">
+ <input type="password" id="zt-api-key" class="ldr-zotero-input" autocomplete="new-password" placeholder="Zotero API key">
+ <button type="button" id="zotero-test">Test connection</button>
+ </div>
+ <div class="ldr-zotero-hint" id="zt-api-key-hint">Create one at zotero.org → Settings → Security → Applications. That’s all you need — your library is detected from the key. Saving runs the connection test automatically.</div>
+ </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="none">Text only — extract &amp; index the text, don’t keep the PDF (default)</option>
+ <option value="database">Also store the full PDF in the encrypted library</option>
+ </select>
+ </div>
+ <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 ldr-zotero-hint-inline">How often to check Zotero for changes (only when auto-sync is on).</div>
+ </div>
+ </div>
+ </fieldset>
+
+ <details id="zt-advanced" class="ldr-zotero-advanced">
+ <summary>Advanced options — the defaults suit most libraries</summary>
<div class="ldr-zotero-field">
<label class="ldr-zotero-check">
<input type="checkbox" id="zt-enabled"> Enable Zotero integration
</label>
+ <div class="ldr-zotero-hint">On by default — untick to pause all Zotero syncing without removing your credentials.</div>
</div>
<div class="ldr-zotero-field">
<label class="ldr-zotero-check">
@@ -113,71 +147,35 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
<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)">
+ <input type="text" id="zt-library-id" class="ldr-zotero-input" aria-label="Library ID (auto-detected for personal libraries)" placeholder="Library ID (leave blank for personal libraries)">
</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 class="ldr-zotero-hint">Personal libraries are detected from the API key. For a group library, use “List groups” below to find its ID.</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 class="ldr-zotero-hint">Use “List collections” below to add keys. Remember to Save — Sync uses the saved value.</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>
+ <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 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
+ <input type="checkbox" id="zt-without-pdf"> Import items that have no PDF (not recommended)
</label>
+ <div class="ldr-zotero-hint">Creates title/abstract-only documents with no full text — research over them is shallow. Prefer attaching the PDF in Zotero.</div>
</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>
+ </details>
- <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>
@@ -208,6 +206,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
<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-progress" class="ldr-zotero-progress" hidden></div>
<div id="zotero-status">
<div class="ldr-zotero-empty">No syncs yet.</div>
</div>
@@ -218,7 +217,6 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
(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) {
@@ -226,8 +224,13 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
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' : '');
+ // App-wide green/red banner (ui.js), matching the rest of the app;
+ // falls back to the inline message area if the service is absent.
+ if (window.ui && window.ui.showMessage) {
+ window.ui.showMessage(text, ok === false ? 'error' : 'success', ok === false ? 6000 : 4000);
+ } else {
+ setMsg(text, ok !== false);
+ }
}
async function getJSON(url) {
@@ -256,7 +259,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
$('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.';
+ : 'Create one at zotero.org → Settings → Security → Applications. That’s all you need — your library is detected from the key. Saving runs the connection test automatically.';
}
function updateAutoSyncUI() {
@@ -287,9 +290,21 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
$('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-pdf-storage').value = c.pdf_storage_mode || 'none';
$('zt-auto-sync').checked = !!c.auto_sync_enabled;
$('zt-interval').value = c.sync_interval_minutes || 360;
+ // If any advanced setting deviates from its default, open the
+ // section — an invisible active filter (e.g. collections) or a
+ // disabled integration would otherwise silently shape what Sync
+ // does.
+ const advancedActive = !c.enabled
+ || !!c.use_local_api
+ || (c.library_type || 'user') !== 'user'
+ || (c.collection_keys || []).length > 0
+ || (c.import_tags || []).length > 0
+ || !!c.import_items_without_pdf
+ || !!c.import_annotations;
+ if (advancedActive) $('zt-advanced').open = true;
updateLocalModeUI();
updateAutoSyncUI();
gateActions(!!c.configured);
@@ -312,43 +327,72 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
// 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;
+ const key = $('zt-api-key').value.trim();
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; }
+ if (!c.success) {
+ configLoadState = 'failed';
+ setSaveMsg(c.error || 'Could not load current settings.', false);
+ return;
+ }
fillForm(c);
+ configLoadState = 'ready';
+ // Readiness marker for the UI tests (and a truthful "the form now
+ // shows your saved settings" signal).
+ $('zotero-config-form').dataset.configLoaded = '1';
+ // Show what the key can reach without requiring button clicks.
+ if (c.configured) autoLoadPickers();
}
$('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…');
+ // ---- Autosave (app-wide pattern: change -> save -> green banner) ----
+
+ let saving = false, resaveQueued = false;
+ // 'pending' until fillForm() ran, 'ready' after, 'failed' on a terminal
+ // load error — guards autosave so DOM defaults never overwrite the
+ // user's real settings (and reschedule background jobs off them).
+ let configLoadState = 'pending';
+ async function autosave() {
+ if (configLoadState !== 'ready') {
+ setSaveMsg(configLoadState === 'failed'
+ ? 'Your saved settings could not be loaded, so changes are not being saved — reload the page and try again.'
+ : 'Still loading your saved settings — that change was not saved. Please redo it once the form shows your current values.', false);
+ return;
+ }
+ if (saving) { resaveQueued = true; return; }
+ saving = true;
try {
+ const payload = collectPayload();
+ const sentKey = !!payload['zotero.api_key'];
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()),
+ body: JSON.stringify(payload),
});
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.
+ setSaveMsg('Zotero settings saved.', true);
+ // Refresh only the derived state (action gating + key
+ // placeholder); do NOT re-fill the inputs — that would
+ // clobber anything typed during the save round-trip.
try {
const c2 = await getJSON('/library/api/zotero/config');
if (c2.success) {
gateActions(!!c2.configured);
+ if (sentKey) $('zt-api-key').value = '';
$('zt-api-key').placeholder = c2.has_api_key
? '•••••••• saved — leave blank to keep' : 'Zotero API key';
+ // A newly saved key proves itself right away.
+ if (sentKey && c2.configured) {
+ runConnectionTest();
+ autoLoadPickers();
+ }
}
} catch (e) { /* non-fatal: settings were saved regardless */ }
} else {
@@ -356,15 +400,23 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
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);
+ setSaveMsg(errList.join('; ') || data.message || 'Could not save settings.', false);
}
} catch (e) {
setSaveMsg('Could not save settings.', false);
} finally {
- btn.disabled = false;
+ saving = false;
+ if (resaveQueued) { resaveQueued = false; autosave(); }
}
+ }
+
+ // Every field saves on change; Enter in a text field saves too.
+ ['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'].forEach((id) => {
+ $(id).addEventListener('change', () => { autosave(); });
});
+ $('zotero-config-form').addEventListener('submit', (e) => { e.preventDefault(); autosave(); });
// ---- Sync status ----------------------------------------------------
@@ -375,6 +427,24 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
return `<span class="ldr-zotero-badge ldr-zotero-badge-${kind}">${esc(st || '—')}</span>`;
}
+ function renderProgress(prog) {
+ const pel = $('zotero-progress');
+ if (!prog) { pel.hidden = true; pel.innerHTML = ''; return; }
+ const phases = { starting: 'Starting', checking: 'Checking for changes', removing: 'Removing', importing: 'Importing' };
+ const label = phases[prog.phase] || 'Syncing';
+ if (prog.total) {
+ const done = prog.done || 0;
+ const pct = Math.min(100, Math.round(done / prog.total * 100));
+ const cur = prog.current ? ` — ${esc(prog.current)}` : '';
+ pel.innerHTML = `<div class="ldr-zotero-progress-label">${label} ${done}/${prog.total}${cur}</div>` +
+ '<div class="ldr-zotero-progress-track"><div class="ldr-zotero-progress-fill"></div></div>';
+ pel.querySelector('.ldr-zotero-progress-fill').style.width = pct + '%';
+ } else {
+ pel.innerHTML = `<div class="ldr-zotero-progress-label">${label}…</div>`;
+ }
+ pel.hidden = false;
+ }
+
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
@@ -382,6 +452,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
const el = $('zotero-status');
try {
const s = await getJSON('/library/api/zotero/status');
+ renderProgress(s && s.progress);
if (!s.success || !s.collections || !s.collections.length) {
el.innerHTML = '<div class="ldr-zotero-empty">No syncs yet.</div>';
return false;
@@ -409,7 +480,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
// ---- Actions --------------------------------------------------------
- $('zotero-test').addEventListener('click', async () => {
+ async function runConnectionTest() {
const b = $('zotero-test');
b.disabled = true;
setMsg('Testing…');
@@ -419,23 +490,30 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
else setMsg(r.error || 'Connection failed.', false);
} catch (e) { setMsg('Connection failed.', false); }
finally { b.disabled = false; }
- });
+ }
- $('zotero-list').addEventListener('click', async () => {
+ $('zotero-test').addEventListener('click', () => { runConnectionTest(); });
+
+ async function loadCollectionsList(interactive) {
+ // interactive=true: user clicked the button (messages + scroll).
+ // interactive=false: silent auto-load — populate the card if there
+ // is anything to show, never nag on failure.
const listBtn = $('zotero-list');
- if (listBtn.disabled) return;
- listBtn.disabled = true;
- setMsg('Loading collections…');
+ if (interactive) { 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; }
+ if (!r.success) {
+ if (interactive) setMsg(r.error || 'Failed to list collections.', false);
+ return;
+ }
+ const items = r.collections || [];
const body = $('zotero-collections-body');
- body.innerHTML = (r.collections || []).map(c =>
+ body.innerHTML = items.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' });
+ if (interactive || items.length) card.style.display = '';
+ if (interactive) 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).
@@ -443,40 +521,65 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
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);
+ $('zt-advanced').open = true; // the field lives in Advanced
+ autosave();
});
});
- setMsg(`Found ${(r.collections || []).length} collections.`, true);
- } catch (e) { setMsg('Failed to list collections.', false); }
- finally { listBtn.disabled = false; }
- });
+ if (interactive) setMsg(`Found ${items.length} collections.`, true);
+ } catch (e) {
+ if (interactive) setMsg('Failed to list collections.', false);
+ } finally {
+ if (interactive) listBtn.disabled = false;
+ }
+ }
- $('zotero-groups').addEventListener('click', async () => {
+ async function loadGroupsList(interactive) {
const groupsBtn = $('zotero-groups');
- if (groupsBtn.disabled) return;
- groupsBtn.disabled = true;
- setMsg('Loading groups…');
+ if (interactive) { 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; }
+ if (!r.success) {
+ if (interactive) setMsg(r.error || 'Failed to list groups.', false);
+ return;
+ }
+ const items = r.groups || [];
const body = $('zotero-groups-body');
- body.innerHTML = (r.groups || []).map(g =>
+ body.innerHTML = items.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' });
+ if (interactive || items.length) card.style.display = '';
+ if (interactive) 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);
+ $('zt-advanced').open = true; // the field lives in Advanced
+ autosave();
});
});
- setMsg(`Found ${(r.groups || []).length} groups.`, true);
- } catch (e) { setMsg('Failed to list groups.', false); }
- finally { groupsBtn.disabled = false; }
+ if (interactive) setMsg(`Found ${items.length} groups.`, true);
+ } catch (e) {
+ if (interactive) setMsg('Failed to list groups.', false);
+ } finally {
+ if (interactive) groupsBtn.disabled = false;
+ }
+ }
+
+ function autoLoadPickers() {
+ // Fire-and-forget: show what's available (collections to filter by,
+ // groups the key can reach) without requiring button clicks.
+ loadCollectionsList(false);
+ loadGroupsList(false);
+ }
+
+ $('zotero-list').addEventListener('click', () => {
+ if (!$('zotero-list').disabled) loadCollectionsList(true);
+ });
+
+ $('zotero-groups').addEventListener('click', () => {
+ if (!$('zotero-groups').disabled) loadGroupsList(true);
});
$('zotero-sync').addEventListener('click', async () => {
@@ -485,8 +588,12 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
const orig = btn.textContent;
btn.disabled = true;
btn.textContent = 'Syncing…';
- const restore = () => { btn.disabled = false; btn.textContent = orig; };
+ const restore = () => { btn.disabled = false; btn.textContent = orig; renderProgress(null); };
setMsg('Starting sync…');
+ // Immediate feedback: show the progress element right away rather
+ // than waiting for the first status poll to catch the sync (a small
+ // sync can finish between polls).
+ renderProgress({ phase: 'starting' });
try {
const r = await postJSON('/library/api/zotero/sync');
if (r.success) {
@@ -495,8 +602,9 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
// 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.
+ // Fast cadence: the poll also drives the progress bar.
let elapsed = 0, sawSyncing = false;
- const STEP = 5000, GRACE = 20000, MAX = 15 * 60 * 1000;
+ const STEP = 1500, GRACE = 20000, MAX = 15 * 60 * 1000;
const t = setInterval(async () => {
const syncing = await loadStatus();
if (syncing) sawSyncing = true;
@@ -505,6 +613,8 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
clearInterval(t);
restore();
if (sawSyncing && !syncing) setMsg('Sync finished.', true);
+ // Collections may have changed Zotero-side.
+ loadCollectionsList(false);
}
}, STEP);
} else {
@@ -516,7 +626,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
$('zotero-refresh').addEventListener('click', () => { loadStatus(); });
- loadConfig().catch(() => setSaveMsg('Could not load current settings.', false));
+ loadConfig().catch(() => { configLoadState = 'failed'; setSaveMsg('Could not load current settings.', false); });
loadStatus();
})();
</script>
diff --git a/tests/research_library/zotero/test_client.py b/tests/research_library/zotero/test_client.py
index c3cad1f7b6..89cad7f87e 100644
--- a/tests/research_library/zotero/test_client.py
+++ b/tests/research_library/zotero/test_client.py
@@ -13,6 +13,7 @@ from local_deep_research.research_library.zotero.client import (
ZoteroAuthError,
ZoteroClient,
ZoteroError,
+ ZoteroItem,
ZoteroTransientError,
)
@@ -530,3 +531,89 @@ def test_pagination_has_a_hard_safety_cap(monkeypatch):
client.session.get.return_value = FakeResponse(200, json_data=full)
with pytest.raises(ZoteroError):
client.get_collections()
+
+
+# ---------------------------------------------------------------------------
+# Standalone PDF attachments (a PDF dropped into Zotero with no parent item)
+# ---------------------------------------------------------------------------
+
+
+def _standalone_data(**overrides):
+ data = {
+ "title": "paper.pdf",
+ "filename": "paper.pdf",
+ "contentType": "application/pdf",
+ "linkMode": "imported_file",
+ }
+ data.update(overrides)
+ return data
+
+
+def test_is_standalone_pdf_attachment():
+ yes = ZoteroItem("K1", 3, "attachment", _standalone_data())
+ assert yes.is_standalone_pdf_attachment is True
+
+ # linked_file points at the user's local disk — not servable by the API.
+ linked = ZoteroItem(
+ "K2", 3, "attachment", _standalone_data(linkMode="linked_file")
+ )
+ assert linked.is_standalone_pdf_attachment is False
+
+ # A child attachment has a parent — the parent is what gets imported.
+ child = ZoteroItem(
+ "K3", 3, "attachment", _standalone_data(parentItem="PARENT01")
+ )
+ assert child.is_standalone_pdf_attachment is False
+
+ non_pdf = ZoteroItem(
+ "K4", 3, "attachment", _standalone_data(contentType="text/html")
+ )
+ assert non_pdf.is_standalone_pdf_attachment is False
+
+ note = ZoteroItem("K5", 3, "note", {})
+ assert note.is_standalone_pdf_attachment is False
+
+
+def test_as_attachment_maps_item_fields():
+ item = ZoteroItem("KEY9", 7, "attachment", _standalone_data())
+ att = item.as_attachment()
+ assert att.key == "KEY9"
+ assert att.version == 7
+ assert att.content_type == "application/pdf"
+ assert att.link_mode == "imported_file"
+ assert att.filename == "paper.pdf"
+ assert att.is_downloadable_pdf is True
+
+
+# ---------------------------------------------------------------------------
+# /keys/current + clearer HTTP 400
+# ---------------------------------------------------------------------------
+
+
+def test_get_current_key_info():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(
+ 200, json_data={"userID": 20971466, "username": "someone"}
+ )
+ info = client.get_current_key_info()
+ assert info["userID"] == 20971466
+ # Non-prefixed endpoint: the library prefix must NOT be in the URL.
+ url = client.session.get.call_args.args[0]
+ assert url.endswith("/keys/current")
+ assert "/users/" not in url
+
+
+def test_get_current_key_info_local_mode_is_empty():
+ client = ZoteroClient(
+ api_key="", library_type="user", library_id="0", local=True
+ )
+ client.session = MagicMock()
+ assert client.get_current_key_info() == {}
+ client.session.get.assert_not_called()
+
+
+def test_request_400_mentions_numeric_library_id():
+ client = make_client()
+ client.session.get.return_value = FakeResponse(400)
+ with pytest.raises(ZoteroError, match="NUMERIC"):
+ client.test_connection()
diff --git a/tests/research_library/zotero/test_sync_service.py b/tests/research_library/zotero/test_sync_service.py
index e17194357e..5908349eb8 100644
--- a/tests/research_library/zotero/test_sync_service.py
+++ b/tests/research_library/zotero/test_sync_service.py
@@ -2418,3 +2418,761 @@ def test_sync_one_indexes_committed_docs_even_when_sync_fails(
# A's committed document still gets its auto-index triggered.
auto_index.assert_called_once()
assert auto_index.call_args.args[0] == [a_doc]
+
+
+# ---------------------------------------------------------------------------
+# Standalone PDF attachments (PDFs dropped into Zotero with no parent item)
+# ---------------------------------------------------------------------------
+
+
+def _standalone_pdf_item(key="STAND001", filename="dropped.pdf", **overrides):
+ data = {
+ "title": filename,
+ "filename": filename,
+ "contentType": "application/pdf",
+ "linkMode": "imported_file",
+ }
+ data.update(overrides)
+ return ZoteroItem(key=key, version=4, item_type="attachment", data=data)
+
+
+def test_ingest_standalone_pdf_attachment(db_session, seeded):
+ """A top-level PDF attachment with no parent is imported as its own
+ document: the item itself is the attachment (no children fetch)."""
+ source_type_id, collection_id = seeded
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none", import_items_without_pdf=True)
+ client = MagicMock()
+ client.get_attachment_fulltext.return_value = None
+ client.download_attachment.return_value = b"%PDF-1.7 dropped-pdf-bytes"
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ client,
+ cfg,
+ _standalone_pdf_item(),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ client.get_children.assert_not_called() # the item IS the attachment
+ client.download_attachment.assert_called_once_with("STAND001")
+ doc = db_session.query(Document).filter_by(id=doc_id).one()
+ assert doc.file_type == "pdf"
+ assert doc.title == "dropped.pdf"
+
+
+def test_sync_one_imports_standalone_pdf_skips_other_strays(
+ db_session, monkeypatch, tmp_path
+):
+ """Sync level: a standalone PDF imports; a standalone note and a
+ linked-file attachment are version-touched and counted as skipped; a
+ child that slipped into /top is touched silently."""
+ 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))
+ 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,
+ )
+
+ standalone = _standalone_pdf_item(key="SPDF0001")
+ note = ZoteroItem("NOTE0001", 2, "note", {})
+ linked = _standalone_pdf_item(key="LINK0001", linkMode="linked_file")
+ child = ZoteroItem(
+ "CHLD0001",
+ 2,
+ "attachment",
+ {"parentItem": "PARENT01", "contentType": "application/pdf"},
+ )
+
+ client = MagicMock()
+ client.get_attachment_fulltext.return_value = None
+ client.download_attachment.return_value = b"%PDF-1.7 standalone"
+ client.get_children.return_value = []
+ client.get_top_item_versions.return_value = (
+ {"SPDF0001": 4, "NOTE0001": 2, "LINK0001": 4, "CHLD0001": 2},
+ 10,
+ )
+ client.get_items.return_value = [standalone, note, linked, child]
+
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["status"] == "completed"
+ assert stats["imported"] == 1 # the standalone PDF
+ assert stats["skipped"] == 2 # note + linked-file (visible)
+ assert stats["errors"] == 0
+
+ def row(key):
+ return (
+ db_session.query(ZoteroItemMap).filter_by(zotero_item_key=key).one()
+ )
+
+ assert row("SPDF0001").document_id is not None
+ # Strays are version-touched so they aren't re-fetched every sync.
+ for key in ("NOTE0001", "LINK0001", "CHLD0001"):
+ assert row(key).document_id is None
+ doc = (
+ db_session.query(Document)
+ .filter_by(id=row("SPDF0001").document_id)
+ .one()
+ )
+ assert doc.file_type == "pdf"
+
+
+def _probe_client(monkeypatch, key_info):
+ """Patch the /keys/current probe client used by _resolve_library_id."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ probe = MagicMock()
+ probe.__enter__ = lambda s: s
+ probe.__exit__ = lambda s, *a: False
+ probe.get_current_key_info.return_value = key_info
+ monkeypatch.setattr(svc_mod, "ZoteroClient", MagicMock(return_value=probe))
+ return probe
+
+
+def test_resolve_library_id_accepts_username_and_blank(monkeypatch):
+ """Personal libraries need no manually entered ID: a blank field or a
+ pasted username is resolved to the key's numeric userID."""
+ svc = ZoteroSyncService("user", None)
+ _probe_client(monkeypatch, {"userID": 20971466})
+
+ for entered in ("cat-fox", ""):
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_type="user",
+ library_id=entered,
+ )
+ assert svc._resolve_library_id(cfg) is None
+ assert cfg.library_id == "20971466"
+
+ # A numeric ID passes through untouched (no probe needed).
+ cfg = ZoteroConfig(enabled=True, api_key="k", library_id="42")
+ assert svc._resolve_library_id(cfg) is None
+ assert cfg.library_id == "42"
+
+
+def test_resolve_library_id_group_requires_numeric():
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_type="group", library_id="my-group"
+ )
+ err = svc._resolve_library_id(cfg)
+ assert err is not None and "group" in err.lower()
+ ok = ZoteroConfig(
+ enabled=True, api_key="k", library_type="group", library_id="99"
+ )
+ assert svc._resolve_library_id(ok) is None
+
+
+def test_resolve_library_id_local_defaults_to_zero():
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(enabled=True, use_local_api=True, library_id="")
+ assert svc._resolve_library_id(cfg) is None
+ assert cfg.library_id == "0"
+
+
+def test_resolve_library_id_failure_gives_actionable_error(monkeypatch):
+ """If /keys/current can't resolve a userID the error says what to do."""
+ svc = ZoteroSyncService("user", None)
+ _probe_client(monkeypatch, {})
+ cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_type="user", library_id=""
+ )
+ err = svc._resolve_library_id(cfg)
+ assert err is not None
+ assert "userID" in err
+
+
+def test_connection_resolves_username_in_library_id(monkeypatch):
+ """test_connection works even when the user pasted their username: the
+ key's userID is resolved and used transparently."""
+ cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_type="user", library_id="cat-fox"
+ )
+ monkeypatch.setattr(ZoteroSyncService, "get_config", lambda self: cfg)
+ _probe_client(monkeypatch, {"userID": 20971466})
+
+ svc = ZoteroSyncService("user", None)
+ fake_client = MagicMock()
+ fake_client.__enter__ = lambda s: s
+ fake_client.__exit__ = lambda s, *a: False
+ fake_client.test_connection.return_value = 7
+ fake_client.get_collections.return_value = []
+ monkeypatch.setattr(svc, "_make_client", lambda c: fake_client)
+
+ result = svc.test_connection()
+ assert result["success"] is True
+ assert cfg.library_id == "20971466"
+
+
+def test_config_configured_without_library_id_for_user_library():
+ """A personal cloud library is configured with just key+enabled; a group
+ library still requires an explicit ID."""
+ user_cfg = ZoteroConfig(enabled=True, api_key="k", library_id="")
+ assert user_cfg.is_configured is True
+ group_cfg = ZoteroConfig(
+ enabled=True, api_key="k", library_type="group", library_id=""
+ )
+ assert group_cfg.is_configured is False
+ local_cfg = ZoteroConfig(enabled=True, use_local_api=True, library_id="")
+ assert local_cfg.is_configured is True
+
+
+def test_manual_sync_reprocesses_previously_skipped_items(
+ db_session, monkeypatch, tmp_path
+):
+ """An item version-touched as a stray by an earlier sync (document_id
+ None, version unchanged) is re-examined by a manual sync — so upgrades
+ and settings changes take effect — while a scheduled sync still skips
+ it."""
+ 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))
+ 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,
+ )
+
+ standalone = _standalone_pdf_item(key="OLDSKIP1")
+ client = MagicMock()
+ client.get_attachment_fulltext.return_value = None
+ client.download_attachment.return_value = b"%PDF-1.7 finally-imported"
+ client.get_children.return_value = []
+ client.get_top_item_versions.return_value = ({"OLDSKIP1": 4}, 10)
+ # Faithful to the real client: only requested keys are returned.
+ client.get_items.side_effect = lambda keys: (
+ [standalone] if "OLDSKIP1" in keys else []
+ )
+
+ # Simulate the pre-upgrade state: the item was version-touched with no
+ # document by an earlier sync of THIS collection. The state row must
+ # exist too, or _sync_one would mint a fresh collection id and never
+ # see the map row.
+ ldr_collection_id = svc._ensure_ldr_collection(db_session, client, cfg, "")
+ svc._get_or_create_state(db_session, cfg, "", ldr_collection_id)
+ db_session.add(
+ ZoteroItemMap(
+ ldr_collection_id=ldr_collection_id,
+ zotero_item_key="OLDSKIP1",
+ zotero_version=4, # matches remote -> normally not reprocessed
+ document_id=None,
+ )
+ )
+ db_session.commit()
+
+ # Scheduled (default): the stamped item stays skipped.
+ stats = svc._sync_one(client, cfg, "")
+ assert stats["imported"] == 0
+ client.get_items.assert_called_with([])
+
+ # Manual: it is re-fetched and now imports.
+ stats2 = svc._sync_one(client, cfg, "", reprocess_skipped=True)
+ assert stats2["imported"] == 1
+ row = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="OLDSKIP1")
+ .one()
+ )
+ assert row.document_id is not None
+
+
+def test_sync_progress_lifecycle():
+ """Progress is only visible while the user's sync lock is held, and
+ clears cleanly."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ svc = ZoteroSyncService("progress-user", None)
+ assert ZoteroSyncService.get_sync_progress("progress-user") is None
+
+ lock = svc_mod._get_user_sync_lock("progress-user")
+ assert lock.acquire(blocking=False)
+ try:
+ svc._set_progress(phase="importing", done=3, total=10, current="Paper")
+ prog = ZoteroSyncService.get_sync_progress("progress-user")
+ assert prog == {
+ "phase": "importing",
+ "done": 3,
+ "total": 10,
+ "current": "Paper",
+ }
+ svc._set_progress(done=4)
+ assert ZoteroSyncService.get_sync_progress("progress-user")["done"] == 4
+ svc._clear_progress()
+ assert ZoteroSyncService.get_sync_progress("progress-user") is None
+ finally:
+ lock.release()
+
+
+# ---------------------------------------------------------------------------
+# Default "Library" collection: ambient membership
+# ---------------------------------------------------------------------------
+
+
+def _seed_default_collection(db_session):
+ default_id = str(uuid.uuid4())
+ db_session.add(
+ Collection(
+ id=default_id,
+ name="Library",
+ collection_type="library",
+ is_default=True,
+ )
+ )
+ db_session.commit()
+ return default_id
+
+
+def test_ingest_links_default_library_collection(db_session, seeded):
+ """Imports are linked into the default Library collection too, so the
+ main library view lists them (like uploads and research downloads)."""
+ source_type_id, collection_id = seeded
+ default_id = _seed_default_collection(db_session)
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none")
+
+ doc_id, action, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 default-linked"),
+ cfg,
+ _pdf_item(key="DEFL0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ db_session.commit()
+
+ assert action == "imported"
+ for cid in (collection_id, default_id):
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=cid)
+ .first()
+ is not None
+ )
+
+
+def test_default_membership_does_not_block_in_place_update(db_session, seeded):
+ """Ambient default-collection membership must not make a document look
+ 'shared': a content edit still updates in place instead of forking."""
+ source_type_id, collection_id = seeded
+ default_id = _seed_default_collection(db_session)
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none")
+
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 v1-bytes"),
+ cfg,
+ _pdf_item(key="DEFU0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ svc._upsert_map(
+ db_session, collection_id, _pdf_item(key="DEFU0001"), doc_id
+ )
+ db_session.commit()
+
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 v2-bytes"),
+ cfg,
+ _pdf_item(key="DEFU0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id # updated in place, not forked
+ assert action2 == "updated"
+ assert reindexed2 is True
+
+
+def test_remove_item_deletes_doc_despite_default_membership(db_session, seeded):
+ """Ambient default-collection membership must not keep a removed item's
+ document alive."""
+ source_type_id, collection_id = seeded
+ default_id = _seed_default_collection(db_session)
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none")
+
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 removable"),
+ cfg,
+ _pdf_item(key="DEFR0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ svc._upsert_map(
+ db_session, collection_id, _pdf_item(key="DEFR0001"), doc_id
+ )
+ db_session.commit()
+ row = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="DEFR0001")
+ .one()
+ )
+
+ released = svc._remove_item(
+ db_session, row, source_type_id, default_collection_id=default_id
+ )
+ db_session.commit()
+
+ assert released == doc_id
+ assert db_session.query(Document).filter_by(id=doc_id).first() is None
+ assert (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ == 0
+ )
+
+
+def test_in_place_update_purges_default_collection_chunks(db_session, seeded):
+ """An in-place content change must also purge the default Library
+ collection's chunks and clear its indexed flag — its ambient copy is
+ derived from the same now-changed text."""
+ from local_deep_research.database.models.library import DocumentChunk
+
+ source_type_id, collection_id = seeded
+ default_id = _seed_default_collection(db_session)
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(pdf_storage_mode="none")
+
+ doc_id, _, _ = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 amb-v1"),
+ cfg,
+ _pdf_item(key="AMBP0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ svc._upsert_map(
+ db_session, collection_id, _pdf_item(key="AMBP0001"), doc_id
+ )
+ # Simulate the default collection having indexed the doc.
+ db_session.add(
+ DocumentChunk(
+ source_id=doc_id,
+ source_type="document",
+ collection_name=f"collection_{default_id}",
+ chunk_index=0,
+ chunk_text="stale ambient text",
+ chunk_hash="amb-stale",
+ start_char=0,
+ end_char=18,
+ word_count=3,
+ embedding_id="emb-amb",
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type="sentence_transformers",
+ )
+ )
+ link = (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=default_id)
+ .one()
+ )
+ link.indexed = True
+ db_session.commit()
+
+ doc_id2, action2, reindexed2 = svc._ingest_item(
+ db_session,
+ _fake_client(pdf_bytes=b"%PDF-1.7 amb-v2-changed"),
+ cfg,
+ _pdf_item(key="AMBP0001"),
+ collection_id,
+ source_type_id,
+ MagicMock(),
+ default_collection_id=default_id,
+ )
+ db_session.commit()
+
+ assert doc_id2 == doc_id and action2 == "updated" and reindexed2 is True
+ assert (
+ db_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, collection_name=f"collection_{default_id}")
+ .count()
+ == 0
+ )
+ db_session.refresh(link)
+ assert link.indexed is False
+
+
+def test_sync_one_purges_default_vectors_for_hard_deleted_docs(
+ db_session, monkeypatch, tmp_path
+):
+ """A hard-deleted document's FAISS vectors must leave the default
+ Library collection's index too — not just the Zotero collection's."""
+ 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")
+ )
+ default_id = _seed_default_collection(db_session)
+
+ @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",
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ # Each item needs its own downloadable PDF with DISTINCT bytes —
+ # identical bytes would dedup both items onto one shared document and
+ # the twin would (correctly) keep it alive.
+ client = MagicMock()
+ client.get_attachment_fulltext.return_value = None
+ client.get_children.side_effect = lambda key: [
+ ZoteroAttachment(
+ key=f"A{key}",
+ version=1,
+ content_type="application/pdf",
+ link_mode="imported_file",
+ filename=f"{key}.pdf",
+ title=key,
+ )
+ ]
+ client.download_attachment.side_effect = lambda att_key: (
+ f"%PDF-1.7 {att_key}".encode()
+ )
+ client.get_top_item_versions.side_effect = [
+ ({"HD1": 1, "KEEP1": 1}, 10),
+ # KEEP1 survives so the remote set is non-empty and the
+ # mass-deletion guard lets the removal of HD1 proceed.
+ ({"KEEP1": 1}, 20),
+ ]
+ client.get_items.side_effect = [
+ [item("HD1", 1, "Doomed"), item("KEEP1", 1, "Keeper")],
+ [],
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ doc_id = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="HD1")
+ .one()
+ .document_id
+ )
+ cleanup.reset_mock()
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["removed"] == 1
+ assert db_session.query(Document).filter_by(id=doc_id).first() is None
+ # Vectors purged from BOTH the zotero collection and the default one.
+ calls = [(c.args[0], c.args[1]) for c in cleanup.call_args_list]
+ purged_collections = {cid for ids, cid in calls if doc_id in ids}
+ assert default_id in purged_collections
+ assert len(purged_collections) == 2
+
+
+def test_filename_for_avoids_double_extension():
+ item = ZoteroItem(
+ "K",
+ 1,
+ "attachment",
+ {"title": "dropped.pdf", "filename": "dropped.pdf"},
+ )
+ assert ZoteroSyncService._filename_for(item, "pdf") == "dropped.pdf"
+ upper = ZoteroItem("K", 1, "attachment", {"title": "PAPER.PDF"})
+ assert ZoteroSyncService._filename_for(upper, "pdf") == "PAPER.pdf"
+
+
+def test_resolve_library_id_group_error_wins_over_local_default():
+ """Local mode with a group library and no ID must surface the clear
+ group-ID error, not silently address the desktop user 0."""
+ svc = ZoteroSyncService("user", None)
+ cfg = ZoteroConfig(
+ enabled=True, use_local_api=True, library_type="group", library_id=""
+ )
+ err = svc._resolve_library_id(cfg)
+ assert err is not None and "group" in err.lower()
+
+
+def test_default_purge_spares_kept_docs_in_mixed_removal_sync(
+ db_session, monkeypatch, tmp_path
+):
+ """One sync removes two items: an owned doc (hard-deleted) and a
+ dedup-adopted foreign doc (released but kept). Only the hard-deleted
+ doc's vectors may leave the default Library collection's index."""
+ 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")
+ )
+ default_id = _seed_default_collection(db_session)
+ foreign_bytes = b"%PDF-1.7 AFOREIGN-shared"
+ foreign = _seed_foreign_upload(db_session, foreign_bytes)
+ foreign_id = foreign.id
+
+ @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"
+ )
+
+ def item(key, ver, title):
+ return ZoteroItem(
+ key=key,
+ version=ver,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+ client = MagicMock()
+ client.get_attachment_fulltext.return_value = None
+ client.get_children.side_effect = lambda key: [
+ ZoteroAttachment(
+ key=f"A{key}",
+ version=1,
+ content_type="application/pdf",
+ link_mode="imported_file",
+ filename=f"{key}.pdf",
+ title=key,
+ )
+ ]
+ # AFOREIGN's bytes match the user upload -> dedup adoption; AOWNED gets
+ # its own distinct bytes.
+ client.download_attachment.side_effect = lambda att_key: (
+ foreign_bytes
+ if att_key == "AFOREIGN"
+ else f"%PDF-1.7 {att_key}-own".encode()
+ )
+ client.get_top_item_versions.side_effect = [
+ ({"OWNED": 1, "FOREIGN": 1, "KEEP": 1}, 10),
+ ({"KEEP": 1}, 20), # both removed; KEEP survives past the guard
+ ]
+ client.get_items.side_effect = [
+ [
+ item("OWNED", 1, "Owned"),
+ item("FOREIGN", 1, "F"),
+ item("KEEP", 1, "K"),
+ ],
+ [],
+ ]
+
+ assert svc._sync_one(client, cfg, "")["status"] == "completed"
+ owned_doc = (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="OWNED")
+ .one()
+ .document_id
+ )
+ assert (
+ db_session.query(ZoteroItemMap)
+ .filter_by(zotero_item_key="FOREIGN")
+ .one()
+ .document_id
+ == foreign_id
+ )
+ cleanup.reset_mock()
+
+ stats2 = svc._sync_one(client, cfg, "")
+ assert stats2["removed"] == 2
+ # Hard-deleted vs kept:
+ assert db_session.query(Document).filter_by(id=owned_doc).first() is None
+ assert (
+ db_session.query(Document).filter_by(id=foreign_id).first() is not None
+ )
+ default_purged = set()
+ for c in cleanup.call_args_list:
+ ids, cid = c.args[0], c.args[1]
+ if cid == default_id:
+ default_purged.update(ids)
+ assert owned_doc in default_purged
+ assert foreign_id not in default_purged # kept doc stays searchable
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 3ed0791037..749982fce8 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -8457,7 +8457,7 @@
},
"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.",
+ "description": "Enable the Zotero integration (on by default; nothing runs until an API key is configured). Turn off to pause all Zotero syncing without removing your credentials.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8466,7 +8466,7 @@
"step": null,
"type": "APP",
"ui_element": "checkbox",
- "value": false,
+ "value": true,
"visible": true
},
"zotero.import_annotations": {
@@ -8485,7 +8485,7 @@
},
"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.",
+ "description": "Import items that have no attached PDF, using only their title/abstract/metadata as a text-only document. Off by default and generally discouraged: without full text, research over these documents is shallow — prefer attaching the PDF in Zotero. If enabled later, applies to already-skipped items on the next manual Sync now.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8494,7 +8494,7 @@
"step": null,
"type": "APP",
"ui_element": "checkbox",
- "value": true,
+ "value": false,
"visible": true
},
"zotero.import_tags": {
@@ -8513,7 +8513,7 @@
},
"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.",
+ "description": "Numeric library ID. Optional for personal libraries — it is detected automatically from the API key (a pasted username is resolved too). Required for group libraries: the group's numeric ID (use the group picker, or the number in the group's URL).",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8550,7 +8550,7 @@
},
"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).",
+ "description": "How to store imported PDFs. 'none' (default) stores only the extracted, indexed text — all that research needs, and much smaller. 'database' additionally keeps the full PDF inside your encrypted database so you can open the original.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8568,7 +8568,7 @@
"step": null,
"type": "APP",
"ui_element": "select",
- "value": "database",
+ "value": "none",
"visible": true
},
"zotero.sync_interval_minutes": {
diff --git a/tests/ui_tests/test_zotero_integration_ci.js b/tests/ui_tests/test_zotero_integration_ci.js
index b6582d61ca..a1317ff4c9 100644
--- a/tests/ui_tests/test_zotero_integration_ci.js
+++ b/tests/ui_tests/test_zotero_integration_ci.js
@@ -27,10 +27,11 @@ 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.
+ // loadConfig() sets data-config-loaded once the saved settings populated
+ // the form (autosave is gated on the same signal) — a real readiness
+ // marker, unlike a select value that is truthy from DOM-parse time.
await page
- .waitForFunction(() => document.getElementById('zt-library-type')?.value?.length > 0, { timeout: 15000 })
+ .waitForFunction(() => document.getElementById('zotero-config-form')?.dataset?.configLoaded === '1', { timeout: 15000 })
.catch(() => {});
}
@@ -64,7 +65,7 @@ const ZoteroPageTests = {
await navigateTo(page, zoteroUrl(baseUrl));
const result = await page.evaluate(() => {
- const ids = ['zotero-save', 'zotero-test', 'zotero-groups', 'zotero-list', 'zotero-sync'];
+ const ids = ['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') };
@@ -92,7 +93,7 @@ const ZoteroPageTests = {
return {
missing,
libraryType: document.getElementById('zt-library-type')?.value,
- // A fresh user default: import-without-pdf is on.
+ // Fresh-user default: import-without-pdf is OFF (title/abstract-only docs are discouraged).
withoutPdf: document.getElementById('zt-without-pdf')?.checked,
intervalHasValue: (document.getElementById('zt-interval')?.value || '').length > 0,
};
@@ -176,11 +177,10 @@ const ZoteroPageTests = {
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;
+ const passed = result.unnamed.length === 0 && result.msgLive;
return {
passed,
message: passed
@@ -397,36 +397,46 @@ const ZoteroFormTests = {
// (min=60, step=30) — persisting it proves the constraint fix.
const TEST_INTERVAL = 45;
await page.evaluate((id, interval) => {
+ // Autosave listens on 'change' — set every field first, then fire
+ // ONE change event so a single save captures the whole payload
+ // (collectPayload always sends the full form).
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);
+ local.dispatchEvent(new Event('change'));
}, TEST_ID, TEST_INTERVAL);
- await page.click('#zotero-save');
+ // Autosave persists in the background — poll the config API until it
+ // reflects the change (or times out).
await page
- .waitForFunction(() => /saved/i.test(document.getElementById('zotero-save-msg')?.textContent || ''), { timeout: 10000 })
+ .waitForFunction(async (id) => {
+ const res = await fetch('/library/api/zotero/config', { headers: { Accept: 'application/json' } });
+ const cfg = await res.json().catch(() => ({}));
+ // Persisted AND the page finished its own post-save refresh
+ // (gateActions enables Sync once configured).
+ return cfg && cfg.library_id === id && cfg.use_local_api === true
+ && document.getElementById('zotero-sync')?.disabled === false;
+ }, { timeout: 10000, polling: 500 }, TEST_ID)
.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 };
+ return { 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 passed = 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})`;
+ ? `Autosave round-trip works: settings persisted (enabled, local API, library ${TEST_ID}, interval ${TEST_INTERVAL}) and Sync enabled`
+ : `Autosave round-trip failed (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