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): show the last completed sync's result counts in the status table (#8194)

Nico81b27f6dfc85
diff --git a/changelog.d/8194.feature.md b/changelog.d/8194.feature.md
new file mode 100644
index 0000000000..6873403552
--- /dev/null
+++ b/changelog.d/8194.feature.md
@@ -0,0 +1 @@
+The Zotero sync status table now shows what the last completed sync did (for example "3 imported, 1 skipped"), and labels those counts as the last completed sync's while a newer sync is running or has failed.
diff --git a/src/local_deep_research/database/migrations/versions/0043_add_zotero_sync_counts.py b/src/local_deep_research/database/migrations/versions/0043_add_zotero_sync_counts.py
new file mode 100644
index 0000000000..211ce2d2b2
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0043_add_zotero_sync_counts.py
@@ -0,0 +1,52 @@
+"""Store the last completed Zotero sync's result counts.
+
+Revision ID: 0043
+Revises: 0042
+
+Adds nullable count columns to zotero_sync_state. They hold the counts of the
+last sync that completed for that collection and stay NULL until one does, so
+existing rows need no backfill.
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "0043"
+down_revision = "0042"
+branch_labels = None
+depends_on = None
+
+_TABLE = "zotero_sync_state"
+_COUNT_COLUMNS = (
+ "last_imported_count",
+ "last_updated_count",
+ "last_removed_count",
+ "last_skipped_count",
+ "last_error_count",
+)
+
+
+def _existing_columns(inspector):
+ return {column["name"] for column in inspector.get_columns(_TABLE)}
+
+
+def upgrade():
+ inspector = sa.inspect(op.get_bind())
+ if not inspector.has_table(_TABLE):
+ return
+ existing = _existing_columns(inspector)
+ for name in _COUNT_COLUMNS:
+ if name not in existing:
+ op.add_column(_TABLE, sa.Column(name, sa.Integer(), nullable=True))
+
+
+def downgrade():
+ inspector = sa.inspect(op.get_bind())
+ if not inspector.has_table(_TABLE):
+ return
+ present = [n for n in _COUNT_COLUMNS if n in _existing_columns(inspector)]
+ if not present:
+ return
+ with op.batch_alter_table(_TABLE) as batch:
+ for name in present:
+ batch.drop_column(name)
diff --git a/src/local_deep_research/database/models/zotero.py b/src/local_deep_research/database/models/zotero.py
index be584fbd69..2a9407dfc1 100644
--- a/src/local_deep_research/database/models/zotero.py
+++ b/src/local_deep_research/database/models/zotero.py
@@ -83,6 +83,14 @@ class ZoteroSyncState(Base):
last_error = Column(Text, nullable=True)
item_count = Column(Integer, nullable=False, default=0)
+ # Counts from the last sync that completed for this collection. NULL until
+ # one completes; a later failed attempt leaves them unchanged.
+ last_imported_count = Column(Integer, nullable=True)
+ last_updated_count = Column(Integer, nullable=True)
+ last_removed_count = Column(Integer, nullable=True)
+ last_skipped_count = Column(Integer, nullable=True)
+ last_error_count = Column(Integer, nullable=True)
+
created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
updated_at = Column(
UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False
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 d1dc231ae7..659c4825dc 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -545,6 +545,15 @@ class ZoteroSyncService:
"last_status": r.last_status,
"last_error": r.last_error,
"item_count": r.item_count,
+ "last_run_counts": None
+ if r.last_imported_count is None
+ else {
+ "imported": r.last_imported_count,
+ "updated": r.last_updated_count,
+ "removed": r.last_removed_count,
+ "skipped": r.last_skipped_count,
+ "errors": r.last_error_count,
+ },
"last_synced_at": r.last_synced_at.isoformat()
if r.last_synced_at
else None,
@@ -904,6 +913,14 @@ class ZoteroSyncService:
.filter(ZoteroItemMap.document_id.isnot(None))
.count()
)
+ # Counts of this completed run. A later failed attempt keeps
+ # them (_mark_failed only touches last_status/last_error), so
+ # they always describe the run of last_synced_at.
+ state.last_imported_count = stats["imported"]
+ state.last_updated_count = stats["updated"]
+ state.last_removed_count = stats["removed"]
+ state.last_skipped_count = stats["skipped"]
+ state.last_error_count = stats["errors"]
session.commit()
except ZoteroError as exc:
stats["status"] = "failed"
diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.html
index a4b366ce7a..9de7a9e6ba 100644
--- a/src/local_deep_research/web/templates/pages/zotero.html
+++ b/src/local_deep_research/web/templates/pages/zotero.html
@@ -83,6 +83,7 @@ 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-counts { color: var(--text-secondary, #999); font-size: .78rem; margin-top: 3px; }
.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; }
@@ -484,6 +485,29 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
return `<span class="ldr-zotero-badge ldr-zotero-badge-${kind}">${esc(st || '—')}</span>`;
}
+ // Counts of the last COMPLETED sync (null until one completes). While a
+ // later attempt is failed or still running, label them so they are not
+ // read as that attempt's results.
+ function runCounts(counts, status) {
+ if (!counts) return '';
+ const labels = [
+ ['imported', 'imported'],
+ ['updated', 'updated'],
+ ['removed', 'removed'],
+ ['skipped', 'skipped'],
+ ];
+ const parts = labels
+ .filter(([key]) => Number(counts[key]) > 0)
+ .map(([key, label]) => `${esc(counts[key])} ${label}`);
+ const errors = Number(counts.errors);
+ if (errors > 0) {
+ parts.push(`${esc(counts.errors)} ${errors === 1 ? 'error' : 'errors'}`);
+ }
+ const summary = parts.length ? parts.join(', ') : 'no changes';
+ const prefix = status === 'completed' ? '' : 'Last completed sync: ';
+ return `<div class="ldr-zotero-counts">${prefix}${summary}</div>`;
+ }
+
function renderProgress(prog) {
const pel = $('zotero-progress');
if (!prog) { pel.hidden = true; pel.innerHTML = ''; return; }
@@ -530,7 +554,8 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
// still carry contained per-item failures worth surfacing.
const err = c.last_error
? `<div class="ldr-zotero-rowerr">${esc(c.last_error)}</div>` : '';
- return `<tr><td>${esc(name)}</td><td>${statusBadge(c.last_status)}${err}</td><td>${esc(c.item_count)}</td><td>${esc(when)}</td></tr>`;
+ const counts = runCounts(c.last_run_counts, st);
+ return `<tr><td>${esc(name)}</td><td>${statusBadge(c.last_status)}${counts}${err}</td><td>${esc(c.item_count)}</td><td>${esc(when)}</td></tr>`;
}).join('');
el.innerHTML = head + body + '</tbody></table>';
return anySyncing;
diff --git a/tests/database/test_migration_0043_zotero_sync_counts.py b/tests/database/test_migration_0043_zotero_sync_counts.py
new file mode 100644
index 0000000000..c3cb91cd8b
--- /dev/null
+++ b/tests/database/test_migration_0043_zotero_sync_counts.py
@@ -0,0 +1,60 @@
+"""Tests for migration 0043: Zotero sync result count columns."""
+
+from alembic import command
+from alembic.config import Config
+from alembic.script import ScriptDirectory
+from sqlalchemy import create_engine, inspect
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+ get_migrations_dir,
+ run_migrations,
+)
+
+COUNT_COLUMNS = {
+ "last_imported_count",
+ "last_updated_count",
+ "last_removed_count",
+ "last_skipped_count",
+ "last_error_count",
+}
+
+
+def _columns(engine):
+ return {
+ c["name"]: c for c in inspect(engine).get_columns("zotero_sync_state")
+ }
+
+
+def _run_alembic(engine, direction, target):
+ config = get_alembic_config(engine)
+ with engine.connect() as conn:
+ with conn.begin():
+ config.attributes["connection"] = conn
+ getattr(command, direction)(config, target)
+
+
+def test_0043_chains_after_0042():
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ assert script.get_revision("0043").down_revision == "0042"
+
+
+def test_upgrade_adds_nullable_count_columns(tmp_path):
+ engine = create_engine(f"sqlite:///{tmp_path / 't.db'}")
+ run_migrations(engine)
+ cols = _columns(engine)
+ assert COUNT_COLUMNS <= set(cols)
+ assert all(cols[name]["nullable"] for name in COUNT_COLUMNS)
+ engine.dispose()
+
+
+def test_downgrade_removes_count_columns(tmp_path):
+ engine = create_engine(f"sqlite:///{tmp_path / 't.db'}")
+ run_migrations(engine)
+ _run_alembic(engine, "downgrade", "0042")
+ assert not COUNT_COLUMNS & set(_columns(engine))
+ _run_alembic(engine, "upgrade", "0043")
+ assert COUNT_COLUMNS <= set(_columns(engine))
+ engine.dispose()
diff --git a/tests/js/pages/zotero-runtime.test.js b/tests/js/pages/zotero-runtime.test.js
index 306dda07fb..6e9af5db37 100644
--- a/tests/js/pages/zotero-runtime.test.js
+++ b/tests/js/pages/zotero-runtime.test.js
@@ -680,3 +680,75 @@ it('does not autosave collection changes before the saved config has loaded', as
expect.anything(),
);
});
+
+// Status table: counts of the last completed sync
+function statusOnlyFetch(collections) {
+ return vi.fn(url => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(jsonResponse(config()));
+ }
+ if (url === '/library/api/zotero/status') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections,
+ progress: null,
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+const LAST_RUN_COUNTS = {
+ imported: 1,
+ updated: 0,
+ removed: 0,
+ skipped: 2,
+ errors: 0,
+};
+
+async function renderedCounts(collection) {
+ loadPage(statusOnlyFetch([{
+ collection_key: 'AAAA1111',
+ item_count: 1,
+ last_synced_at: '2026-10-28T15:04:08+00:00',
+ last_error: null,
+ ...collection,
+ }]));
+ await vi.waitFor(() => {
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('AAAA1111');
+ });
+ return document.querySelector('#zotero-status .ldr-zotero-counts');
+}
+
+it('shows the non-zero counts of a completed sync under its badge', async () => {
+ const counts = await renderedCounts({
+ last_status: 'completed',
+ last_run_counts: LAST_RUN_COUNTS,
+ });
+
+ expect(counts.textContent).toBe('1 imported, 2 skipped');
+});
+
+it('labels the counts as the last completed run when a later attempt failed', async () => {
+ const counts = await renderedCounts({
+ last_status: 'failed',
+ last_error: 'Zotero request failed. Check the integration settings.',
+ last_run_counts: LAST_RUN_COUNTS,
+ });
+
+ expect(counts.textContent)
+ .toBe('Last completed sync: 1 imported, 2 skipped');
+ expect(document.querySelector('#zotero-status .ldr-zotero-rowerr').textContent)
+ .toContain('Zotero request failed');
+});
+
+it('shows no counts before any sync has completed', async () => {
+ const counts = await renderedCounts({
+ last_status: 'failed',
+ last_error: 'Zotero request failed. Check the integration settings.',
+ last_run_counts: null,
+ });
+
+ expect(counts).toBeNull();
+});
diff --git a/tests/research_library/zotero/test_sync_counts.py b/tests/research_library/zotero/test_sync_counts.py
new file mode 100644
index 0000000000..547db423c2
--- /dev/null
+++ b/tests/research_library/zotero/test_sync_counts.py
@@ -0,0 +1,171 @@
+"""Persisted result counts of the last completed Zotero sync (#4961, slice 5).
+
+``_sync_one`` stores the run's imported/updated/removed/skipped/errors counts
+on the ``ZoteroSyncState`` row when a sync completes. A later failed attempt
+keeps the counts of the last completed run, and they stay NULL until a sync
+has completed. ``get_status`` exposes them as ``last_run_counts``.
+"""
+
+import uuid
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import SourceType
+from local_deep_research.database.models.zotero import ZoteroSyncState
+from local_deep_research.research_library.zotero.client import (
+ ZoteroError,
+ ZoteroItem,
+)
+from local_deep_research.research_library.zotero.sync_service import (
+ ZoteroConfig,
+ ZoteroSyncService,
+)
+
+
+def db_session():
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ yield session
+ session.close()
+ engine.dispose()
+
+
+def service(db_session, monkeypatch, tmp_path):
+ """A sync service wired to the in-memory session, like the other
+ ``_sync_one`` tests in test_sync_service.py."""
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ svc = ZoteroSyncService("user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ return svc
+
+
+def cfg():
+ return ZoteroConfig(
+ enabled=True,
+ api_key="k",
+ library_id="1",
+ pdf_storage_mode="none",
+ import_items_without_pdf=True,
+ )
+
+
+def _item(key, version, title):
+ return ZoteroItem(
+ key=key,
+ version=version,
+ item_type="journalArticle",
+ data={"title": title},
+ )
+
+
+def _counts(state):
+ return (
+ state.last_imported_count,
+ state.last_updated_count,
+ state.last_removed_count,
+ state.last_skipped_count,
+ state.last_error_count,
+ )
+
+
+def test_completed_sync_stores_its_counts(db_session, service, cfg):
+ client = MagicMock()
+ client.get_children.return_value = [] # metadata-only ingest
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1, "B": 1}, 10),
+ ({"A": 2}, 20), # B removed, A bumped
+ ]
+ client.get_items.side_effect = [
+ [_item("A", 1, "Paper A"), _item("B", 1, "Paper B")],
+ [_item("A", 2, "Paper A")],
+ ]
+
+ service._sync_one(client, cfg, "")
+ state = db_session.query(ZoteroSyncState).one()
+ assert _counts(state) == (2, 0, 0, 0, 0)
+
+ # Each completed run replaces the counts with its own.
+ service._sync_one(client, cfg, "")
+ db_session.refresh(state)
+ assert _counts(state) == (0, 1, 1, 0, 0)
+
+
+def test_failed_sync_keeps_last_completed_counts(db_session, service, cfg):
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.side_effect = [
+ ({"A": 1}, 10),
+ ZoteroError("rate limited"),
+ ]
+ client.get_items.return_value = [_item("A", 1, "Paper A")]
+
+ assert service._sync_one(client, cfg, "")["status"] == "completed"
+ assert service._sync_one(client, cfg, "")["status"] == "failed"
+
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_status == "failed"
+ assert _counts(state) == (1, 0, 0, 0, 0)
+
+
+def test_counts_stay_null_until_a_sync_completes(db_session, service, cfg):
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = ZoteroError("rate limited")
+
+ assert service._sync_one(client, cfg, "")["status"] == "failed"
+
+ state = db_session.query(ZoteroSyncState).one()
+ assert state.last_status == "failed"
+ assert _counts(state) == (None, None, None, None, None)
+
+
+def test_get_status_exposes_last_run_counts(db_session, service, cfg):
+ client = MagicMock()
+ client.get_children.return_value = []
+ client.get_top_item_versions.return_value = ({"A": 1}, 10)
+ client.get_items.return_value = [_item("A", 1, "Paper A")]
+ service._sync_one(client, cfg, "")
+
+ (row,) = service.get_status()
+ assert row["last_run_counts"] == {
+ "imported": 1,
+ "updated": 0,
+ "removed": 0,
+ "skipped": 0,
+ "errors": 0,
+ }
+
+
+def test_get_status_reports_no_counts_before_a_completed_sync(
+ db_session, service, cfg
+):
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = ZoteroError("rate limited")
+ service._sync_one(client, cfg, "")
+
+ (row,) = service.get_status()
+ assert row["last_status"] == "failed"
+ assert row["last_run_counts"] is None