DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(web-source): add durable sync scheduling
XZH90b99187d139
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 9b1760769..f6a5c4edf 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -203,6 +203,20 @@ async def lifespan(app: FastAPI):await get_sync_service().stop()+ async def _start_web_source_sync() -> None:+ from deeptutor.services.web_source.scheduler import (+ start_web_source_sync_scheduler,+ )++ await start_web_source_sync_scheduler()++ async def _stop_web_source_sync() -> None:+ from deeptutor.services.web_source.scheduler import (+ stop_web_source_sync_scheduler,+ )++ await stop_web_source_sync_scheduler()+from deeptutor.runtime.coordination import BackgroundCommandKindasync def _handle_background_command(command) -> None:@@ -268,8 +282,18 @@ async def lifespan(app: FastAPI):background_supervisor = BackgroundLeaderSupervisor(application_container.coordinator,application_container.worker_id,- start_callbacks=[_start_partners, _start_cron, _start_github_sync],- stop_callbacks=[_stop_partners, _stop_cron, _stop_github_sync],+ start_callbacks=[+ _start_partners,+ _start_cron,+ _start_github_sync,+ _start_web_source_sync,+ ],+ stop_callbacks=[+ _stop_partners,+ _stop_cron,+ _stop_github_sync,+ _stop_web_source_sync,+ ],recovery_callback=application_container.recover_once,control_callback=_handle_background_command,renew_interval_seconds=application_container.settings.renew_interval_seconds,diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 794385ace..03d8c4549 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -88,6 +88,7 @@ from deeptutor.services.rag.pipelines.ima.config import (ImaCredentials,get_account_credentials,)+from deeptutor.services.web_source.scheduler import get_web_source_sync_schedulerfrom deeptutor.utils.document_extractor import (MAX_EXTRACTED_CHARS_PER_DOC,DocumentExtractionError,@@ -4042,6 +4043,8 @@ class WebSourceInfo(BaseModel):max_depth: int = 3max_pages: int = 200enabled: bool = True+ auto_sync_enabled: bool = True+ sync_interval_hours: int = Field(default=24, ge=1, le=168)page_count: int = 0last_synced_at: str = ""last_sync_status: str = "pending"@@ -4050,6 +4053,23 @@ class WebSourceInfo(BaseModel):navigation: dict | None = None+class WebSourceScheduleUpdate(BaseModel):+ auto_sync_enabled: bool+ sync_interval_hours: int = Field(default=24, ge=1, le=168)+++class WebSourceSyncJobInfo(BaseModel):+ owner_id: str+ kb_name: str+ source_id: str+ state: str+ next_run_at: int+ last_run_at: int | None = None+ attempt: int = 0+ error: str | None = None+ cancel_requested: bool = False++@contextmanagerdef _knowledge_source_errors(kb_name: str, *, validation_status: int = 404):"""Translate source-service failures without duplicating route ladders."""@@ -4132,6 +4152,8 @@ async def add_web_source(kb_name: str, request: AddWebSourceRequest):info = manager.add_web_source(resolved_name, request.url, request.max_depth, request.max_pages)+ scheduler = get_web_source_sync_scheduler()+ scheduler.repo.ensure_source((get_current_user().id, resolved_name, str(info["id"])))return WebSourceInfo(**info)@@ -4148,9 +4170,99 @@ async def remove_web_source(kb_name: str, source_id: str):manager, resolved_name, _ = _writable_kb(kb_name)if not manager.remove_web_source(resolved_name, source_id):raise HTTPException(status_code=404, detail=f"Source '{source_id}' not found")+ await get_web_source_sync_scheduler().request_cancel(+ get_current_user().id, resolved_name, source_id+ )+ get_web_source_sync_scheduler().repo.delete(+ (get_current_user().id, resolved_name, source_id)+ )return {"message": "Removed", "source_id": source_id}+ "/knowledge-bases/{kb_name}/web-source-sync",+ response_model=list[WebSourceSyncJobInfo],+)+async def get_web_source_sync_jobs(kb_name: str):+ with _knowledge_source_errors(kb_name):+ manager, resolved_name, _ = _writable_kb(kb_name)+ scheduler = get_web_source_sync_scheduler()+ jobs = scheduler.repo.list_jobs(get_current_user().id, resolved_name)+ return [WebSourceSyncJobInfo(**job.public_dict()) for job in jobs]+++ "/knowledge-bases/{kb_name}/web-source/{source_id}/schedule",+ response_model=WebSourceInfo,+)+async def update_web_source_schedule(+ kb_name: str,+ source_id: str,+ request: WebSourceScheduleUpdate,+):+ with _knowledge_source_errors(kb_name, validation_status=400):+ manager, resolved_name, _ = _writable_kb(kb_name)+ info = manager.update_web_source_schedule(+ resolved_name,+ source_id,+ auto_sync_enabled=request.auto_sync_enabled,+ sync_interval_hours=request.sync_interval_hours,+ )+ scheduler = get_web_source_sync_scheduler()+ job_key = (get_current_user().id, resolved_name, source_id)+ if request.auto_sync_enabled:+ scheduler.repo.ensure_source(job_key)+ else:+ await scheduler.request_cancel(*job_key)+ scheduler.repo.delete(job_key)+ return WebSourceInfo(**info)+++ "/knowledge-bases/{kb_name}/web-source/{source_id}/cancel",+)+async def cancel_web_source_sync(kb_name: str, source_id: str):+ with _knowledge_source_errors(kb_name):+ manager, resolved_name, _ = _writable_kb(kb_name)+ if not any(item.get("id") == source_id for item in manager.get_web_sources(resolved_name)):+ raise HTTPException(status_code=404, detail=f"Source '{source_id}' not found")+ cancelled = await get_web_source_sync_scheduler().request_cancel(+ get_current_user().id, resolved_name, source_id+ )+ if not cancelled:+ raise HTTPException(status_code=409, detail="Synchronization job cannot be cancelled")+ return {"message": "Cancellation requested", "source_id": source_id}+++ "/knowledge-bases/{kb_name}/web-source/{source_id}/retry",+)+async def retry_web_source_sync(kb_name: str, source_id: str):+ with _knowledge_source_errors(kb_name):+ manager, resolved_name, _ = _writable_kb(kb_name)+ source = next(+ (+ item+ for item in manager.get_web_sources(resolved_name)+ if item.get("id") == source_id+ ),+ None,+ )+ if source is None:+ raise HTTPException(status_code=404, detail=f"Source '{source_id}' not found")+ if not source.get("enabled", True) or not source.get("auto_sync_enabled", True):+ raise HTTPException(+ status_code=409,+ detail="Enable the source and automatic synchronization before retrying",+ )+ retried = await get_web_source_sync_scheduler().retry(+ get_current_user().id, resolved_name, source_id+ )+ if not retried:+ raise HTTPException(status_code=404, detail="Synchronization job not found")+ return {"message": "Retry scheduled", "source_id": source_id}++@router.post("/knowledge-bases/{kb_name}/sync-web")async def sync_web_sources(kb_name: str):"""Run one bounded crawl-and-sync pass for every enabled web source."""diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 8f75fa616..94d83d750 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -2079,6 +2079,8 @@ class KnowledgeBaseManager:"max_depth": max_depth,"max_pages": max_pages,"enabled": True,+ "auto_sync_enabled": True,+ "sync_interval_hours": 24,"page_hashes": {},"page_count": 0,"last_synced_at": "",@@ -2126,6 +2128,29 @@ class KnowledgeBaseManager:atomic_write_json(metadata_file, metadata)return+ def update_web_source_schedule(+ self,+ kb_name: str,+ source_id: str,+ *,+ auto_sync_enabled: bool,+ sync_interval_hours: int,+ ) -> dict:+ """Persist the reviewable schedule fields for one web source."""+ source = next(+ (item for item in self.get_web_sources(kb_name) if item.get("id") == source_id),+ None,+ )+ if source is None:+ raise ValueError(f"Source '{source_id}' not found")+ self.update_web_source_state(+ kb_name,+ source_id,+ auto_sync_enabled=auto_sync_enabled,+ sync_interval_hours=sync_interval_hours,+ )+ return next(item for item in self.get_web_sources(kb_name) if item.get("id") == source_id)+def get_all_web_sources(self) -> list[tuple[str, dict]]:"""Scan every KB and return (kb_name, source_dict) pairs."""result = []diff --git a/deeptutor/services/web_source/repository.py b/deeptutor/services/web_source/repository.pynew file mode 100644index 000000000..c1e8be855--- /dev/null+++ b/deeptutor/services/web_source/repository.py@@ -0,0 +1,418 @@+"""Durable scheduling state for web-source synchronization."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+import sqlite3+import time+from typing import Any+++@dataclass(slots=True)+class WebSourceSyncJob:+ """One durable row per account-scoped knowledge-base source."""++ owner_id: str+ kb_name: str+ source_id: str+ next_run_at_ms: int+ updated_at_ms: int+ state: str = "pending"+ last_run_at_ms: int | None = None+ attempt: int = 0+ error: str | None = None+ cancel_requested: bool = False+ runner_id: str = ""+ lease_until_ms: int | None = None++ @classmethod+ def from_row(cls, row: sqlite3.Row) -> "WebSourceSyncJob":+ return cls(+ owner_id=str(row["owner_id"]),+ kb_name=str(row["kb_name"]),+ source_id=str(row["source_id"]),+ state=str(row["state"]),+ next_run_at_ms=int(row["next_run_at_ms"]),+ last_run_at_ms=(+ int(row["last_run_at_ms"]) if row["last_run_at_ms"] is not None else None+ ),+ attempt=int(row["attempt"]),+ error=str(row["error"]) if row["error"] is not None else None,+ cancel_requested=bool(row["cancel_requested"]),+ runner_id=str(row["runner_id"]),+ lease_until_ms=(+ int(row["lease_until_ms"]) if row["lease_until_ms"] is not None else None+ ),+ updated_at_ms=int(row["updated_at_ms"]),+ )++ def public_dict(self) -> dict[str, Any]:+ return {+ "owner_id": self.owner_id,+ "kb_name": self.kb_name,+ "source_id": self.source_id,+ "state": self.state,+ "next_run_at": self.next_run_at_ms,+ "last_run_at": self.last_run_at_ms,+ "attempt": self.attempt,+ "error": self.error,+ "cancel_requested": self.cancel_requested,+ }+++class SQLiteWebSourceSyncRepository:+ """WAL-backed job state shared by API requests and the scheduler."""++ def __init__(self, path: Path) -> None:+ self.path = Path(path).expanduser().resolve()+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self._initialize()++ def _connect(self) -> sqlite3.Connection:+ connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)+ connection.execute("PRAGMA journal_mode=WAL")+ connection.execute("PRAGMA busy_timeout=30000")+ connection.execute("PRAGMA synchronous=NORMAL")+ connection.row_factory = sqlite3.Row+ return connection++ def _initialize(self) -> None:+ with self._connect() as connection:+ connection.execute(+ """+ CREATE TABLE IF NOT EXISTS web_source_sync_jobs (+ owner_id TEXT NOT NULL,+ kb_name TEXT NOT NULL,+ source_id TEXT NOT NULL,+ state TEXT NOT NULL,+ next_run_at_ms INTEGER NOT NULL,+ last_run_at_ms INTEGER,+ attempt INTEGER NOT NULL DEFAULT 0,+ error TEXT,+ cancel_requested INTEGER NOT NULL DEFAULT 0,+ runner_id TEXT NOT NULL DEFAULT '',+ lease_until_ms INTEGER,+ updated_at_ms INTEGER NOT NULL,+ PRIMARY KEY (owner_id, kb_name, source_id)+ )+ """+ )+ connection.execute(+ "CREATE INDEX IF NOT EXISTS idx_web_source_sync_due "+ "ON web_source_sync_jobs(next_run_at_ms, state)"+ )++ @staticmethod+ def key(job: WebSourceSyncJob) -> tuple[str, str, str]:+ return job.owner_id, job.kb_name, job.source_id++ def _now_ms(self) -> int:+ return int(time.time() * 1000)++ def reconcile_sources(self, source_keys: set[tuple[str, str, str]]) -> None:+ """Create missing rows and remove jobs whose source no longer exists."""+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute("BEGIN IMMEDIATE")+ try:+ rows = connection.execute(+ "SELECT owner_id, kb_name, source_id FROM web_source_sync_jobs"+ ).fetchall()+ existing = {+ (str(row["owner_id"]), str(row["kb_name"]), str(row["source_id"]))+ for row in rows+ }+ for owner_id, kb_name, source_id in source_keys - existing:+ connection.execute(+ """+ INSERT OR IGNORE INTO web_source_sync_jobs+ (owner_id, kb_name, source_id, state, next_run_at_ms,+ updated_at_ms)+ VALUES (?, ?, ?, 'pending', ?, ?)+ """,+ (owner_id, kb_name, source_id, now, now),+ )+ for owner_id, kb_name, source_id in existing - source_keys:+ connection.execute(+ """+ DELETE FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (owner_id, kb_name, source_id),+ )+ connection.execute("COMMIT")+ except Exception:+ connection.execute("ROLLBACK")+ raise++ def ensure_source(self, source_key: tuple[str, str, str]) -> WebSourceSyncJob:+ """Create a due job for one source without touching unrelated rows."""+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute(+ """+ INSERT OR IGNORE INTO web_source_sync_jobs+ (owner_id, kb_name, source_id, state, next_run_at_ms,+ updated_at_ms)+ VALUES (?, ?, ?, 'pending', ?, ?)+ """,+ (*source_key, now, now),+ )+ job = self.get(source_key)+ if job is None:+ raise RuntimeError("Web source synchronization job could not be created")+ return job++ def recover_interrupted(self, runner_id: str) -> None:+ """Mark jobs left running by a prior process or expired lease as retryable."""+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET state='interrupted',+ error='Synchronization was interrupted by a restart',+ runner_id='',+ lease_until_ms=NULL,+ next_run_at_ms=?,+ updated_at_ms=?+ WHERE state='running' AND runner_id<>?+ AND (lease_until_ms IS NULL OR lease_until_ms<=?)+ """,+ (now, now, runner_id, now),+ )++ def list_jobs(self, owner_id: str, kb_name: str) -> list[WebSourceSyncJob]:+ with self._connect() as connection:+ rows = connection.execute(+ """+ SELECT * FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=?+ ORDER BY next_run_at_ms, source_id+ """,+ (owner_id, kb_name),+ ).fetchall()+ return [WebSourceSyncJob.from_row(row) for row in rows]++ def due_jobs(self, now_ms: int | None = None) -> list[WebSourceSyncJob]:+ now = self._now_ms() if now_ms is None else now_ms+ with self._connect() as connection:+ rows = connection.execute(+ """+ SELECT * FROM web_source_sync_jobs+ WHERE state IN ('pending', 'interrupted', 'error')+ AND next_run_at_ms<=?+ ORDER BY next_run_at_ms, owner_id, kb_name, source_id+ """,+ (now,),+ ).fetchall()+ return [WebSourceSyncJob.from_row(row) for row in rows]++ def claim(+ self,+ job: WebSourceSyncJob,+ *,+ runner_id: str,+ lease_until_ms: int,+ ) -> WebSourceSyncJob | None:+ """Claim one job only when its durable state still matches."""+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute("BEGIN IMMEDIATE")+ try:+ row = connection.execute(+ """+ SELECT * FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ self.key(job),+ ).fetchone()+ if row is None:+ connection.execute("COMMIT")+ return None+ current = WebSourceSyncJob.from_row(row)+ runnable = current.state in {"pending", "interrupted", "cancelled", "error"}+ lease_expired = (+ current.state == "running"+ and current.lease_until_ms is not None+ and current.lease_until_ms <= now+ )+ if not (runnable or lease_expired):+ connection.execute("COMMIT")+ return None+ connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET state='running', runner_id=?, lease_until_ms=?,+ cancel_requested=0, updated_at_ms=?+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (runner_id, lease_until_ms, now, *self.key(job)),+ )+ connection.execute("COMMIT")+ current.state = "running"+ current.runner_id = runner_id+ current.lease_until_ms = lease_until_ms+ current.cancel_requested = False+ return current+ except Exception:+ connection.execute("ROLLBACK")+ raise++ def _update(+ self,+ job: WebSourceSyncJob,+ **fields: Any,+ ) -> None:+ assignments = list(fields)+ if not assignments:+ return+ fields["updated_at_ms"] = self._now_ms()+ assignments.append("updated_at_ms")+ values = list(fields.values())+ set_sql = ", ".join(f"{name}=?" for name in assignments)+ with self._connect() as connection:+ connection.execute(+ f"""+ UPDATE web_source_sync_jobs+ SET {set_sql}+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (*values, *self.key(job)),+ )++ def mark_success(self, job: WebSourceSyncJob, next_run_at_ms: int) -> None:+ self._update(+ job,+ state="pending",+ next_run_at_ms=next_run_at_ms,+ last_run_at_ms=self._now_ms(),+ attempt=0,+ error=None,+ cancel_requested=False,+ runner_id="",+ lease_until_ms=None,+ )++ def mark_failure(+ self,+ job: WebSourceSyncJob,+ *,+ error: str,+ next_run_at_ms: int,+ ) -> None:+ self._update(+ job,+ state="error",+ next_run_at_ms=next_run_at_ms,+ last_run_at_ms=self._now_ms(),+ attempt=job.attempt + 1,+ error=error[:2000],+ cancel_requested=False,+ runner_id="",+ lease_until_ms=None,+ )++ def mark_cancelled(self, job: WebSourceSyncJob, next_run_at_ms: int | None = None) -> None:+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET state='cancelled', cancel_requested=0, runner_id='',+ lease_until_ms=NULL, last_run_at_ms=?, updated_at_ms=?,+ next_run_at_ms=COALESCE(?, next_run_at_ms)+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (now, now, next_run_at_ms, *self.key(job)),+ )++ def request_cancel(self, job_key: tuple[str, str, str]) -> bool:+ now = self._now_ms()+ with self._connect() as connection:+ connection.execute("BEGIN IMMEDIATE")+ try:+ row = connection.execute(+ """+ SELECT state FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ job_key,+ ).fetchone()+ if row is None:+ connection.execute("COMMIT")+ return False+ state = str(row["state"])+ if state not in {"pending", "running", "interrupted", "error"}:+ connection.execute("COMMIT")+ return False+ cancel_requested = 1 if state == "running" else 0+ if state == "pending":+ connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET state='cancelled', cancel_requested=0, runner_id='',+ lease_until_ms=NULL, updated_at_ms=?+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (now, *job_key),+ )+ else:+ connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET cancel_requested=?, updated_at_ms=?+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (cancel_requested, now, *job_key),+ )+ connection.execute("COMMIT")+ return True+ except Exception:+ connection.execute("ROLLBACK")+ raise++ def delete(self, job_key: tuple[str, str, str]) -> bool:+ """Remove a job after its source has been deleted."""+ with self._connect() as connection:+ cursor = connection.execute(+ """+ DELETE FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ job_key,+ )+ return int(cursor.rowcount or 0) > 0++ def retry(self, job_key: tuple[str, str, str]) -> WebSourceSyncJob | None:+ now = self._now_ms()+ with self._connect() as connection:+ cursor = connection.execute(+ """+ UPDATE web_source_sync_jobs+ SET state='pending', next_run_at_ms=?, attempt=0, error=NULL,+ cancel_requested=0, runner_id='', lease_until_ms=NULL,+ updated_at_ms=?+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ (now, now, *job_key),+ )+ changed = int(cursor.rowcount or 0) > 0+ if not changed:+ return None+ return self.get(job_key)++ def get(self, job_key: tuple[str, str, str]) -> WebSourceSyncJob | None:+ with self._connect() as connection:+ row = connection.execute(+ """+ SELECT * FROM web_source_sync_jobs+ WHERE owner_id=? AND kb_name=? AND source_id=?+ """,+ job_key,+ ).fetchone()+ return WebSourceSyncJob.from_row(row) if row else None+++__all__ = ["SQLiteWebSourceSyncRepository", "WebSourceSyncJob"]diff --git a/deeptutor/services/web_source/scheduler.py b/deeptutor/services/web_source/scheduler.pynew file mode 100644index 000000000..84172c585--- /dev/null+++ b/deeptutor/services/web_source/scheduler.py@@ -0,0 +1,308 @@+"""Durable background scheduler for account-scoped web sources."""++from __future__ import annotations++import asyncio+from collections.abc import Callable+import logging+import time+from typing import Any+import uuid++from deeptutor.services.web_source.repository import (+ SQLiteWebSourceSyncRepository,+ WebSourceSyncJob,+)++logger = logging.getLogger(__name__)++WEB_SYNC_MIN_INTERVAL_HOURS = 1+WEB_SYNC_MAX_INTERVAL_HOURS = 168+WEB_SYNC_INTERVAL_HOURS = 24+WEB_SYNC_CHECK_SECONDS = 15+WEB_SYNC_LEASE_HOURS = 6+WEB_SYNC_MAX_CONCURRENCY = 2+++def _now_ms() -> int:+ return int(time.time() * 1000)+++def _hours_ms(hours: int) -> int:+ return hours * 60 * 60 * 1000+++def default_repository() -> SQLiteWebSourceSyncRepository:+ from deeptutor.multi_user.paths import SYSTEM_ROOT++ return SQLiteWebSourceSyncRepository(SYSTEM_ROOT / "web-source-sync.sqlite")+++def normalize_sync_interval(value: Any) -> int:+ try:+ interval = int(value)+ except (TypeError, ValueError):+ return WEB_SYNC_INTERVAL_HOURS+ return max(WEB_SYNC_MIN_INTERVAL_HOURS, min(WEB_SYNC_MAX_INTERVAL_HOURS, interval))+++class WebSourceSyncScheduler:+ """Run due web-source jobs while preserving state across restarts."""++ def __init__(+ self,+ *,+ repository: SQLiteWebSourceSyncRepository | None = None,+ manager_factory: Callable[[], Any] | None = None,+ check_interval_s: float = WEB_SYNC_CHECK_SECONDS,+ max_concurrency: int = WEB_SYNC_MAX_CONCURRENCY,+ ) -> None:+ self._repository = repository+ self._manager_factory = manager_factory+ self._check_interval_s = check_interval_s+ self._max_concurrency = max_concurrency+ self._runner_id = f"web-sync-{uuid.uuid4().hex}"+ self._task: asyncio.Task[None] | None = None+ self._running = False+ self._run_tasks: dict[tuple[str, str, str], asyncio.Task[None]] = {}+ self._sources: dict[tuple[str, str, str], dict[str, Any]] = {}++ @property+ def repo(self) -> SQLiteWebSourceSyncRepository:+ if self._repository is None:+ self._repository = default_repository()+ return self._repository++ def _make_manager(self) -> Any:+ if self._manager_factory is not None:+ return self._manager_factory()+ from deeptutor.knowledge.manager import KnowledgeBaseManager+ from deeptutor.multi_user.knowledge_access import current_kb_base_dir++ return KnowledgeBaseManager(base_dir=str(current_kb_base_dir()))++ async def start(self) -> None:+ if self._running:+ return+ self._running = True+ self.repo.recover_interrupted(self._runner_id)+ self._task = asyncio.create_task(self._loop(), name="web-source-sync:scheduler")+ logger.info("Web source sync scheduler started")++ async def stop(self) -> None:+ self._running = False+ if self._task and not self._task.done():+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ self._task = None+ if self._run_tasks:+ for task in self._run_tasks.values():+ task.cancel()+ await asyncio.gather(*self._run_tasks.values(), return_exceptions=True)+ self._run_tasks.clear()++ async def _loop(self) -> None:+ while self._running:+ try:+ await self._synchronize_sources()+ self._start_due_jobs()+ except Exception:+ logger.exception("Web source scheduler cycle failed")+ await asyncio.sleep(self._check_interval_s)++ def _manager_for_owner(self, owner_id: str) -> Any:+ from deeptutor.multi_user.context import reset_current_user, set_current_user+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.multi_user.paths import (+ LOCAL_ADMIN_ID,+ ensure_scope_workspace,+ local_admin_user,+ scope_for_user,+ )++ user = (+ local_admin_user()+ if owner_id == LOCAL_ADMIN_ID+ else CurrentUser(+ id=owner_id,+ username=owner_id,+ role="user",+ scope=scope_for_user(owner_id, is_admin=False),+ )+ )+ if user.scope.kind == "user":+ ensure_scope_workspace(user.scope)+ token = set_current_user(user)+ try:+ return self._make_manager()+ finally:+ reset_current_user(token)++ async def _synchronize_sources(self) -> None:+ from deeptutor.multi_user.paths import LOCAL_ADMIN_ID, USERS_ROOT++ manager = self._manager_for_owner(LOCAL_ADMIN_ID)+ owner_ids = [LOCAL_ADMIN_ID, *(path.name for path in USERS_ROOT.glob("*") if path.is_dir())]+ # The first manager call above also validates the configured admin path.+ del manager+ source_keys: set[tuple[str, str, str]] = set()+ sources: dict[tuple[str, str, str], dict[str, Any]] = {}+ for owner_id in owner_ids:+ try:+ owner_manager = await asyncio.to_thread(self._manager_for_owner, owner_id)+ for kb_name, source in owner_manager.get_all_web_sources():+ if not source.get("enabled", True):+ continue+ if not source.get("auto_sync_enabled", True):+ continue+ source_id = str(source.get("id") or "")+ kb_key = str(kb_name)+ if not source_id or not kb_key:+ continue+ key = owner_id, kb_key, source_id+ source_keys.add(key)+ sources[key] = dict(source)+ except Exception:+ logger.exception("Failed to enumerate web sources for owner %s", owner_id)+ self._sources = sources+ await asyncio.to_thread(self.repo.reconcile_sources, source_keys)++ def _start_due_jobs(self) -> None:+ for job in self.repo.due_jobs():+ key = self.repo.key(job)+ if key in self._run_tasks:+ continue+ if len(self._run_tasks) >= self._max_concurrency:+ return+ task = asyncio.create_task(self._run_job(job), name=f"web-source-sync:{key[2]}")+ self._run_tasks[key] = task+ task.add_done_callback(lambda _task, item=key: self._run_tasks.pop(item, None))++ async def _run_job(self, scheduled: WebSourceSyncJob) -> None:+ from deeptutor.multi_user.context import reset_current_user, set_current_user+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.multi_user.paths import (+ LOCAL_ADMIN_ID,+ ensure_scope_workspace,+ local_admin_user,+ scope_for_user,+ )+ from deeptutor.services.web_source.sync import sync_source++ key = self.repo.key(scheduled)+ lease_until = _now_ms() + _hours_ms(WEB_SYNC_LEASE_HOURS)+ claimed = await asyncio.to_thread(+ self.repo.claim,+ scheduled,+ runner_id=self._runner_id,+ lease_until_ms=lease_until,+ )+ if claimed is None:+ return+ source = self._sources.get(key)+ if source is None:+ self.repo.mark_cancelled(claimed)+ return++ user = (+ local_admin_user()+ if claimed.owner_id == LOCAL_ADMIN_ID+ else CurrentUser(+ id=claimed.owner_id,+ username=claimed.owner_id,+ role="user",+ scope=scope_for_user(claimed.owner_id, is_admin=False),+ )+ )+ if user.scope.kind == "user":+ ensure_scope_workspace(user.scope)+ token = set_current_user(user)+ try:+ current = await asyncio.to_thread(self.repo.get, key)+ if current is not None and current.cancel_requested:+ self.repo.mark_cancelled(current)+ return+ result = await sync_source(+ kb_name=claimed.kb_name,+ source=source,+ base_dir=str(self._make_manager().base_dir),+ max_depth=source.get("max_depth"),+ max_pages=source.get("max_pages"),+ )+ current = await asyncio.to_thread(self.repo.get, key)+ if current is not None and current.cancel_requested:+ self.repo.mark_cancelled(current)+ return+ if result.ok:+ interval = normalize_sync_interval(source.get("sync_interval_hours"))+ self.repo.mark_success(claimed, _now_ms() + _hours_ms(interval))+ else:+ self._mark_failure(claimed, source, result.error or "Web synchronization failed")+ except asyncio.CancelledError:+ self.repo.mark_cancelled(claimed, _now_ms())+ raise+ except Exception as exc:+ logger.exception("Scheduled web source sync failed for %s", source.get("url"))+ self._mark_failure(claimed, source, str(exc))+ finally:+ reset_current_user(token)++ def _mark_failure(+ self,+ job: WebSourceSyncJob,+ source: dict[str, Any],+ error: str,+ ) -> None:+ interval = normalize_sync_interval(source.get("sync_interval_hours"))+ backoff = min(interval, WEB_SYNC_MIN_INTERVAL_HOURS * max(1, job.attempt + 1))+ self.repo.mark_failure(+ job,+ error=error,+ next_run_at_ms=_now_ms() + _hours_ms(backoff),+ )++ async def request_cancel(self, owner_id: str, kb_name: str, source_id: str) -> bool:+ key = owner_id, kb_name, source_id+ if not await asyncio.to_thread(self.repo.request_cancel, key):+ return False+ task = self._run_tasks.get(key)+ if task is not None and not task.done():+ task.cancel()+ return True++ async def retry(self, owner_id: str, kb_name: str, source_id: str) -> bool:+ job = await asyncio.to_thread(self.repo.retry, (owner_id, kb_name, source_id))+ return job is not None+++_scheduler: WebSourceSyncScheduler | None = None+++def get_web_source_sync_scheduler() -> WebSourceSyncScheduler:+ global _scheduler+ if _scheduler is None:+ _scheduler = WebSourceSyncScheduler()+ return _scheduler+++async def start_web_source_sync_scheduler() -> None:+ await get_web_source_sync_scheduler().start()+++async def stop_web_source_sync_scheduler() -> None:+ await get_web_source_sync_scheduler().stop()+++__all__ = [+ "WEB_SYNC_INTERVAL_HOURS",+ "WEB_SYNC_MAX_INTERVAL_HOURS",+ "WEB_SYNC_MIN_INTERVAL_HOURS",+ "WebSourceSyncScheduler",+ "get_web_source_sync_scheduler",+ "normalize_sync_interval",+ "start_web_source_sync_scheduler",+ "stop_web_source_sync_scheduler",+]diff --git a/tests/api/test_web_source_schedule_api.py b/tests/api/test_web_source_schedule_api.pynew file mode 100644index 000000000..5395825e1--- /dev/null+++ b/tests/api/test_web_source_schedule_api.py@@ -0,0 +1,101 @@+from __future__ import annotations++from pathlib import Path++import pytest++fastapi = pytest.importorskip("fastapi")+TestClient = pytest.importorskip("fastapi.testclient").TestClient++from deeptutor.knowledge.manager import KnowledgeBaseManager+import deeptutor.services.config as config_package+from deeptutor.services.config import loader as config_loader+from deeptutor.services.web_source import scheduler as scheduler_module+from deeptutor.services.web_source.repository import (+ SQLiteWebSourceSyncRepository,+)+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ from fastapi import FastAPI++ runtime_home = tmp_path / "runtime"+ settings_dir = runtime_home / "data" / "user" / "settings"+ settings_dir.mkdir(parents=True)+ (settings_dir / "main.yaml").write_text("system:\n language: en\n", encoding="utf-8")+ monkeypatch.setenv("DEEPTUTOR_HOME", str(runtime_home))+ monkeypatch.setattr(config_package, "PROJECT_ROOT", runtime_home)+ monkeypatch.setattr(config_loader, "PROJECT_ROOT", runtime_home)++ from deeptutor.api.routers import knowledge as knowledge_router++ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ (manager.base_dir / "kb").mkdir(parents=True)+ (manager.base_dir / "kb" / "metadata.json").write_text("{}", encoding="utf-8")+ manager.register_knowledge_base("kb")++ def writable(kb_name: str):+ assert kb_name == "kb"+ return manager, "kb", manager.base_dir++ monkeypatch.setattr(knowledge_router, "_writable_kb", writable)+ scheduler = scheduler_module.WebSourceSyncScheduler(+ repository=SQLiteWebSourceSyncRepository(tmp_path / "web-source-sync.sqlite")+ )+ monkeypatch.setattr(scheduler_module, "_scheduler", scheduler)+ app = FastAPI()+ app.include_router(knowledge_router.router, prefix="/api")+ return TestClient(app), manager+++def test_schedule_defaults_update_and_delete_cleanup(client) -> None:+ test_client, manager = client+ source = manager.add_web_source("kb", "https://example.com/docs/")+ scheduler_module._scheduler.repo.ensure_source(("local-admin", "kb", source["id"]))++ created = test_client.post(+ "/api/knowledge-bases/kb/web-source",+ json={"url": "https://another.example.com/docs/"},+ )+ assert created.status_code == 200+ assert created.json()["auto_sync_enabled"] is True+ assert created.json()["sync_interval_hours"] == 24++ jobs = test_client.get("/api/knowledge-bases/kb/web-source-sync")+ assert jobs.status_code == 200+ assert {item["source_id"] for item in jobs.json()} == {+ source["id"],+ created.json()["id"],+ }++ updated = test_client.put(+ f"/api/knowledge-bases/kb/web-source/{source['id']}/schedule",+ json={"auto_sync_enabled": False, "sync_interval_hours": 6},+ )+ assert updated.status_code == 200+ assert updated.json()["auto_sync_enabled"] is False+ assert updated.json()["sync_interval_hours"] == 6+ scheduled_ids = {+ item["source_id"]+ for item in test_client.get("/api/knowledge-bases/kb/web-source-sync").json()+ }+ assert scheduled_ids == {created.json()["id"]}++ removed = test_client.delete(f"/api/knowledge-bases/kb/web-source/{source['id']}")+ assert removed.status_code == 200+ job_ids = {+ item["source_id"]+ for item in test_client.get("/api/knowledge-bases/kb/web-source-sync").json()+ }+ assert source["id"] not in job_ids+++def test_schedule_rejects_out_of_range_interval(client) -> None:+ test_client, manager = client+ source = manager.add_web_source("kb", "https://example.com/docs/")+ response = test_client.put(+ f"/api/knowledge-bases/kb/web-source/{source['id']}/schedule",+ json={"auto_sync_enabled": True, "sync_interval_hours": 0},+ )+ assert response.status_code == 422diff --git a/tests/services/web_source/test_sync_scheduler.py b/tests/services/web_source/test_sync_scheduler.pynew file mode 100644index 000000000..71348a3b1--- /dev/null+++ b/tests/services/web_source/test_sync_scheduler.py@@ -0,0 +1,149 @@+from __future__ import annotations++import asyncio+from pathlib import Path+import time+from unittest.mock import AsyncMock, patch++import pytest++from deeptutor.knowledge.manager import KnowledgeBaseManager+from deeptutor.services.web_source.repository import (+ SQLiteWebSourceSyncRepository,+ WebSourceSyncJob,+)+from deeptutor.services.web_source.scheduler import WebSourceSyncScheduler+from deeptutor.services.web_source.sync import WebSyncResult+++def test_repository_creates_reconciles_and_recovers(tmp_path: Path) -> None:+ repository = SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite")+ key = "local-admin", "kb", "abc"+ repository.reconcile_sources({key})+ assert repository.list_jobs("local-admin", "kb")[0].state == "pending"++ job = repository.get(key)+ assert job is not None+ claimed = repository.claim(job, runner_id="runner-a", lease_until_ms=10_000)+ assert claimed is not None and claimed.state == "running"++ repository.recover_interrupted("runner-b")+ recovered = repository.get(key)+ assert recovered is not None+ assert recovered.state == "interrupted"+ assert recovered.runner_id == ""++ repository.reconcile_sources(set())+ assert repository.get(key) is None+++def test_repository_recover_preserves_active_lease(tmp_path: Path) -> None:+ repository = SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite")+ key = "local-admin", "kb", "abc"+ repository.reconcile_sources({key})+ job = repository.get(key)+ assert job is not None++ claimed = repository.claim(+ job,+ runner_id="runner-a",+ lease_until_ms=int(time.time() * 1000) + 3_600_000,+ )+ assert claimed is not None+ repository.recover_interrupted("runner-b")++ active = repository.get(key)+ assert active is not None+ assert active.state == "running"+++def test_repository_cancel_and_retry(tmp_path: Path) -> None:+ repository = SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite")+ key = "local-admin", "kb", "abc"+ repository.reconcile_sources({key})++ assert repository.request_cancel(key) is True+ assert repository.get(key).state == "cancelled" # type: ignore[union-attr]++ retried = repository.retry(key)+ assert retried is not None and retried.state == "pending"+++async def test_scheduler_marks_success_and_schedules_next_run(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ (manager.base_dir / "kb").mkdir()+ (manager.base_dir / "kb" / "metadata.json").write_text("{}", encoding="utf-8")+ manager.register_knowledge_base("kb")+ source = manager.add_web_source("kb", "https://example.com/docs/")+ source["sync_interval_hours"] = 2++ repository = SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite")+ scheduler = WebSourceSyncScheduler(+ repository=repository,+ manager_factory=lambda: manager,+ )+ await scheduler._synchronize_sources()+ job = repository.list_jobs("local-admin", "kb")[0]++ sync = AsyncMock(return_value=WebSyncResult(ok=True))+ with patch("deeptutor.services.web_source.sync.sync_source", sync):+ await scheduler._run_job(job)++ persisted = repository.get((job.owner_id, job.kb_name, job.source_id))+ assert persisted is not None+ assert persisted.state == "pending"+ assert persisted.attempt == 0+ assert persisted.next_run_at_ms > persisted.last_run_at_ms # type: ignore[operator]+ sync.assert_awaited_once()+++async def test_scheduler_cancelled_run_is_not_marked_successful(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ (manager.base_dir / "kb").mkdir()+ (manager.base_dir / "kb" / "metadata.json").write_text("{}", encoding="utf-8")+ manager.register_knowledge_base("kb")+ manager.add_web_source("kb", "https://example.com/docs/")++ repository = SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite")+ scheduler = WebSourceSyncScheduler(+ repository=repository,+ manager_factory=lambda: manager,+ )+ await scheduler._synchronize_sources()+ job = repository.list_jobs("local-admin", "kb")[0]++ sync = AsyncMock(side_effect=asyncio.CancelledError)+ with patch("deeptutor.services.web_source.sync.sync_source", sync):+ with pytest.raises(asyncio.CancelledError):+ await scheduler._run_job(job)++ persisted = repository.get((job.owner_id, job.kb_name, job.source_id))+ assert persisted is not None+ assert persisted.state == "cancelled"+++async def test_scheduler_ignores_manual_and_disabled_sources(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ (manager.base_dir / "kb").mkdir()+ (manager.base_dir / "kb" / "metadata.json").write_text("{}", encoding="utf-8")+ manager.register_knowledge_base("kb")+ automatic = manager.add_web_source("kb", "https://auto.example.com/docs/")+ manager.add_web_source("kb", "https://disabled.example.com/docs/")+ manager.update_web_source_state(+ "kb",+ manager.get_web_sources("kb")[1]["id"],+ auto_sync_enabled=False,+ )++ scheduler = WebSourceSyncScheduler(+ repository=SQLiteWebSourceSyncRepository(tmp_path / "jobs.sqlite"),+ manager_factory=lambda: manager,+ )+ await scheduler._synchronize_sources()++ assert [job.source_id for job in scheduler.repo.list_jobs("local-admin", "kb")] == [+ automatic["id"]+ ]diff --git a/web/components/knowledge/KbWebSourcesSection.tsx b/web/components/knowledge/KbWebSourcesSection.tsxindex 4ab77f9c7..1198eaff2 100644--- a/web/components/knowledge/KbWebSourcesSection.tsx+++ b/web/components/knowledge/KbWebSourcesSection.tsx@@ -2,13 +2,26 @@import { useCallback, useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { Globe, Loader2, Plus, RefreshCw, Trash2 } from "lucide-react";import {+ Ban,+ Globe,+ Loader2,+ Plus,+ RefreshCw,+ RotateCcw,+ Trash2,+} from "lucide-react";+import {+ cancelWebSourceSync,addWebSource,listWebSources,removeWebSource,+ retryWebSourceSync,syncWebSources,+ updateWebSourceSchedule,+ listWebSourceSyncJobs,type WebSource,+ type WebSourceSyncJob,} from "@/features/knowledge/api/sources";import { formatKnowledgeTimestamp } from "@/lib/knowledge-helpers";@@ -21,6 +34,7 @@ export default function KbWebSourcesSection({}: KbWebSourcesSectionProps) {const { t } = useTranslation();const [sources, setSources] = useState<WebSource[]>([]);+ const [jobs, setJobs] = useState<WebSourceSyncJob[]>([]);const [loading, setLoading] = useState(true);const [showForm, setShowForm] = useState(false);const [syncing, setSyncing] = useState(false);@@ -29,12 +43,21 @@ export default function KbWebSourcesSection({const [urlInput, setUrlInput] = useState("");const [maxDepth, setMaxDepth] = useState(3);const [submitting, setSubmitting] = useState(false);+ const [busySource, setBusySource] = useState<string | null>(null);+ const [intervalInputs, setIntervalInputs] = useState<Record<string, number>>(+ {},+ );const refresh = useCallback(async () => {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 15_000);try {- setSources(await listWebSources(kbName, { signal: controller.signal }));+ const [nextSources, nextJobs] = await Promise.all([+ listWebSources(kbName, { signal: controller.signal }),+ listWebSourceSyncJobs(kbName, { signal: controller.signal }),+ ]);+ setSources(nextSources);+ setJobs(nextJobs);setError(null);} catch (err) {if (err instanceof DOMException && err.name === "AbortError") {@@ -52,6 +75,15 @@ export default function KbWebSourcesSection({void refresh();}, [refresh]);+ useEffect(() => {+ const hasActiveJob = jobs.some(+ (job) => job.state === "running" || job.state === "pending",+ );+ if (!hasActiveJob) return;+ const timer = setInterval(() => void refresh(), 5_000);+ return () => clearInterval(timer);+ }, [jobs, refresh]);+const handleAdd = async () => {const url = urlInput.trim();if (!url) return;@@ -93,6 +125,34 @@ export default function KbWebSourcesSection({}};+ const withSourceAction = async (id: string, action: () => Promise<void>) => {+ setBusySource(id);+ setError(null);+ try {+ await action();+ await refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusySource(null);+ }+ };++ const handleScheduleChange = (+ source: WebSource,+ autoSyncEnabled: boolean,+ syncIntervalHours: number,+ ) => {+ const interval = Math.min(168, Math.max(1, syncIntervalHours || 24));+ setIntervalInputs((current) => ({ ...current, [source.id]: interval }));+ return withSourceAction(source.id, async () => {+ await updateWebSourceSchedule(kbName, source.id, {+ auto_sync_enabled: autoSyncEnabled,+ sync_interval_hours: interval,+ });+ });+ };+if (loading) {return (<div className="flex flex-col items-center justify-center gap-2 py-10">@@ -226,6 +286,28 @@ export default function KbWebSourcesSection({<WebSourceCardkey={src.id}source={src}+ job={jobs.find((job) => job.source_id === src.id)}+ busy={busySource === src.id}+ intervalValue={intervalInputs[src.id] ?? src.sync_interval_hours}+ onIntervalInput={(hours) =>+ setIntervalInputs((current) => ({+ ...current,+ [src.id]: hours,+ }))+ }+ onScheduleChange={(autoSync, hours) =>+ void handleScheduleChange(src, autoSync, hours)+ }+ onCancel={() =>+ void withSourceAction(src.id, () =>+ cancelWebSourceSync(kbName, src.id),+ )+ }+ onRetry={() =>+ void withSourceAction(src.id, () =>+ retryWebSourceSync(kbName, src.id),+ )+ }onRemove={() => void handleRemove(src.id)}/>))}@@ -237,9 +319,23 @@ export default function KbWebSourcesSection({function WebSourceCard({source,+ job,+ busy,+ intervalValue,+ onIntervalInput,+ onScheduleChange,+ onCancel,+ onRetry,onRemove,}: {source: WebSource;+ job?: WebSourceSyncJob;+ busy: boolean;+ intervalValue: number;+ onIntervalInput: (hours: number) => void;+ onScheduleChange: (enabled: boolean, interval: number) => void;+ onCancel: () => void;+ onRetry: () => void;onRemove: () => void;}) {const { t } = useTranslation();@@ -250,6 +346,18 @@ function WebSourceCard({? "text-red-600 dark:text-red-400": "text-[var(--muted-foreground)]";const lastSync = formatKnowledgeTimestamp(source.last_synced_at);+ const jobColor =+ job?.state === "running"+ ? "text-blue-600 dark:text-blue-400"+ : job?.state === "error" || job?.state === "interrupted"+ ? "text-red-600 dark:text-red-400"+ : job?.state === "cancelled"+ ? "text-amber-600 dark:text-amber-400"+ : "text-[var(--muted-foreground)]";+ const nextRun =+ job?.state === "pending" && job.next_run_at+ ? new Date(job.next_run_at).toLocaleString()+ : "";return (<div className="flex items-start justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">@@ -277,21 +385,92 @@ function WebSourceCard({{t("Synced")}: {lastSync}</span>)}+ {job && (+ <span className={jobColor}>+ {t("Schedule")}: {t(job.state === "interrupted" ? "Interrupted" : job.state)}+ </span>+ )}+ {nextRun && <span>{t("Next run")}: {nextRun}</span>}+ {job?.cancel_requested && <span>{t("Cancelling…")}</span>}+ </div>+ <div className="mt-2 flex flex-wrap items-center gap-3">+ <label className="inline-flex items-center gap-1.5 text-[11px]">+ <input+ type="checkbox"+ checked={source.auto_sync_enabled}+ disabled={busy}+ onChange={(event) =>+ onScheduleChange(event.target.checked, intervalValue)+ }+ aria-label={t("Automatic sync")}+ />+ {t("Automatic sync")}+ </label>+ <label className="inline-flex items-center gap-1.5 text-[11px]">+ <span>{t("Interval hours")}</span>+ <input+ type="number"+ min={1}+ max={168}+ value={intervalValue}+ disabled={busy || !source.auto_sync_enabled}+ onChange={(event) => onIntervalInput(Number(event.target.value) || 24)}+ onBlur={(event) =>+ onScheduleChange(+ source.auto_sync_enabled,+ Number(event.target.value) || 24,+ )+ }+ className="w-16 rounded-md border border-[var(--border)] bg-[var(--card)] px-1.5 py-1 text-[11px] text-[var(--foreground)] outline-none focus:border-[var(--primary)] disabled:opacity-50"+ aria-label={t("Interval hours")}+ />+ </label></div>{source.last_sync_error && (<p className="mt-1 text-[11px] text-red-600 dark:text-red-400">{source.last_sync_error}</p>)}+ {job?.error && (+ <p className="mt-1 text-[11px] text-red-600 dark:text-red-400">+ {job.error}+ </p>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {job?.state === "running" || job?.state === "pending" ? (+ <button+ type="button"+ onClick={onCancel}+ disabled={busy}+ title={t("Cancel sync")}+ aria-label={t("Cancel sync")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-600 disabled:opacity-50"+ >+ <Ban className="h-3.5 w-3.5" />+ </button>+ ) : (+ <button+ type="button"+ onClick={onRetry}+ disabled={busy || !source.enabled || !source.auto_sync_enabled}+ title={t("Retry sync")}+ aria-label={t("Retry sync")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-50"+ >+ <RotateCcw className="h-3.5 w-3.5" />+ </button>+ )}+ <button+ type="button"+ onClick={onRemove}+ title={t("Remove source")}+ aria-label={t("Remove source")}+ className="shrink-0 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-600"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button></div>- <button- type="button"- onClick={onRemove}- title={t("Remove source")}- className="shrink-0 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-600"- >- <Trash2 className="h-3.5 w-3.5" />- </button></div>);}diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.tsindex bb5bf400d..92ec3b247 100644--- a/web/features/knowledge/api/client.ts+++ b/web/features/knowledge/api/client.ts@@ -1397,6 +1397,8 @@ export interface WebSource {max_depth: number;max_pages: number;enabled: boolean;+ auto_sync_enabled: boolean;+ sync_interval_hours: number;page_count: number;last_synced_at: string;last_sync_status: string;@@ -1428,6 +1430,23 @@ export interface WebSyncResult {results: WebSyncSourceResult[];}+export interface WebSourceSyncJob {+ owner_id: string;+ kb_name: string;+ source_id: string;+ state: string;+ next_run_at: number;+ last_run_at?: number | null;+ attempt: number;+ error?: string | null;+ cancel_requested: boolean;+}++export interface WebSourceSchedulePayload {+ auto_sync_enabled: boolean;+ sync_interval_hours: number;+}+export async function listWebSources(kbName: string,options?: { signal?: AbortSignal },@@ -1487,6 +1506,82 @@ export async function removeWebSource(invalidateKnowledgeCaches();}+export async function listWebSourceSyncJobs(+ kbName: string,+ options?: { signal?: AbortSignal },+): Promise<WebSourceSyncJob[]> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/web-source-sync`,+ ),+ { signal: options?.signal },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to list sync jobs (${res.status})`),+ );+ }+ return (await res.json()) as WebSourceSyncJob[];+}++export async function updateWebSourceSchedule(+ kbName: string,+ sourceId: string,+ payload: WebSourceSchedulePayload,+): Promise<WebSource> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/web-source/${encodeURIComponent(sourceId)}/schedule`,+ ),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to update sync schedule (${res.status})`),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as WebSource;+}++export async function cancelWebSourceSync(+ kbName: string,+ sourceId: string,+): Promise<void> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/web-source/${encodeURIComponent(sourceId)}/cancel`,+ ),+ { method: "POST" },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to cancel sync (${res.status})`),+ );+ }+}++export async function retryWebSourceSync(+ kbName: string,+ sourceId: string,+): Promise<void> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/web-source/${encodeURIComponent(sourceId)}/retry`,+ ),+ { method: "POST" },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to retry sync (${res.status})`),+ );+ }+}+export async function syncWebSources(kbName: string): Promise<WebSyncResult> {const res = await apiFetch(apiUrl(`/api/knowledge-bases/${encodeURIComponent(kbName)}/sync-web`),diff --git a/web/features/knowledge/api/sources.ts b/web/features/knowledge/api/sources.tsindex b6803ed77..126d56739 100644--- a/web/features/knowledge/api/sources.ts+++ b/web/features/knowledge/api/sources.ts@@ -1,12 +1,16 @@export {addGitHubSource,addWebSource,+ cancelWebSourceSync,listGitHubSources,listWebSources,+ listWebSourceSyncJobs,removeGitHubSource,removeWebSource,+ retryWebSourceSync,syncGitHubSources,syncWebSources,+ updateWebSourceSchedule,} from "./client";export type {@@ -15,6 +19,8 @@ export type {GitHubSource,GitHubSyncResult,WebSource,+ WebSourceSchedulePayload,+ WebSourceSyncJob,WebSyncResult,WebSyncSourceResult,} from "../model/types";diff --git a/web/features/knowledge/model/types.ts b/web/features/knowledge/model/types.tsindex eb495bed3..08c637627 100644--- a/web/features/knowledge/model/types.ts+++ b/web/features/knowledge/model/types.ts@@ -26,6 +26,8 @@ export type {PreflightCheck,RagProviderSummary,WebSource,+ WebSourceSchedulePayload,+ WebSourceSyncJob,WebSyncResult,WebSyncSourceResult,WeKnoraProbe,diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ea72027d8..9b7708b3f 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -784,6 +784,14 @@"Parsed Dir": "Parsed Dir","Max": "Max","Depth": "Depth",+ "Schedule": "Schedule",+ "Next run": "Next run",+ "Automatic sync": "Automatic sync",+ "Interval hours": "Interval hours",+ "Cancel sync": "Cancel sync",+ "Retry sync": "Retry sync",+ "Interrupted": "Interrupted",+ "Cancelling…": "Cancelling…","Sub-topics": "Sub-topics","Iterations": "Iterations","Study Notes": "Study Notes",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 702df3f39..368b60506 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -813,6 +813,14 @@"Parsed Dir": "解析目录","Max": "上限","Depth": "深度",+ "Schedule": "调度",+ "Next run": "下次运行",+ "Automatic sync": "自动同步",+ "Interval hours": "间隔小时数",+ "Cancel sync": "取消同步",+ "Retry sync": "重试同步",+ "Interrupted": "已中断",+ "Cancelling…": "正在取消…","Sub-topics": "子主题数","Iterations": "迭代次数","Study Notes": "学习笔记",