DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge remote-tracking branch 'origin/main' into multi-user
Bingxi Zhao (Frank)5c31f0dee6ab
diff --cc assets/releases/ver1-3-7.mdindex 000000000,2287bd360..3b92a5d11mode 000000,100644..100644--- a/assets/releases/ver1-3-7.md+++ b/assets/releases/ver1-3-7.md@@@ -1,0 -1,64 +1,64 @@@+ # DeepTutor v1.3.7 Release Notes++ **Release Date:** 2026.05.04++ v1.3.7 focuses on thinking-model compatibility, clearer knowledge-base index+ history, and safer Co-Writer editing. It keeps provider-specific reasoning+ output under control while making index activity easier to understand in the UI.++ ## Highlights++ ### Thinking-Model and Gateway Compatibility++ - **Reasoning output stays separate** - OpenAI-compatible and TutorBot providers+ keep `reasoning_content` out of visible answer text, and streaming avoids+ replaying internal scratchpad as final content.+ - **DeepSeek thinking can be configured from `.env`** - `LLM_REASONING_EFFORT`+ is documented and applied through the resolver path. Use `minimal` to disable+ DeepSeek thinking, or `high` / `max` to enable it.+ - **Custom gateway headers are preserved** - chat and explicit LLM calls inherit+ profile `extra_headers`, fixing gateways that require custom headers such as+ a `User-Agent` override.+ - **Structured generation is more tolerant** - book blocks and question ideation+ now handle fenced, repaired, list-shaped, or otherwise imperfect JSON outputs+ more reliably.++ ### Knowledge Index Visibility++ - **Index activity is recorded** - create, upload, and re-index flows now store+ `last_indexed_at`, indexed document count, and the index action in knowledge+ metadata.+ - **Progress payloads describe real index changes** - backend status updates can+ distinguish metadata-only completion from an actual vector-index update.+ - **The Knowledge UI shows index history** - detail, settings, and index-version+ panels display the latest index time and document count when available.++ ### Co-Writer Editing Safety++ - **Clear and template actions ask first** - replacing a non-empty draft now+ opens a confirmation dialog before the editor is cleared or overwritten.+ - **Undo is more dependable** - pending typing snapshots are committed before+ toolbar edits, and editor shortcuts support Ctrl/Cmd+Z, Shift+Cmd+Z, and+ Ctrl/Cmd+Y.+ - **Toolbar controls are clearer** - destructive and template actions now have+ distinct tones, focus states, labels, and accessible tooltips.-+++ ## Tests++ - Added OpenAI-compatible provider tests to keep `reasoning_content` separate+ from visible response content in both service and TutorBot paths.+ - Expanded LLM factory tests for inherited `extra_headers`, inherited+ `reasoning_effort`, and reasoning-only streaming behavior.+ - Added knowledge manager coverage for recording `last_indexed_*` metadata only+ when the index actually changes.++ ## Upgrade Notes++ - Set `LLM_REASONING_EFFORT` in `.env` if you need global thinking control.+ Leave it empty to let DeepTutor auto-detect behavior from the active model.+ - Knowledge-base metadata may now include `last_indexed_at`,+ `last_indexed_count`, and `last_indexed_action`.+ - Co-Writer clear/template actions are recoverable through undo until the user+ leaves the current draft.++ **Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.6...v1.3.7diff --cc deeptutor/api/routers/auth.pyindex 4b91a02dc,000000000..36c809e51mode 100644,000000..100644--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@@ -1,371 -1,0 +1,371 @@@+"""Auth router — login, logout, status, registration, and user-management endpoints."""+++import logging+import os++from fastapi import APIRouter, Cookie, Depends, HTTPException, Response, status+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer+from pydantic import BaseModel, field_validator++# SameSite=None lets the cookie work when the browser accesses the frontend via+# 127.0.0.1 and the backend via localhost (different origins on the same machine).+# Browsers require Secure=True for SameSite=None, but that needs HTTPS — so in+# local dev we fall back to SameSite=Lax and tell users to use localhost:// URLs.+_SECURE = os.getenv("AUTH_COOKIE_SECURE", "false").lower() == "true"+_SAMESITE = "none" if _SECURE else "lax"+- from deeptutor.logging import get_logger+from deeptutor.services.auth import (+ AUTH_ENABLED,+ POCKETBASE_ENABLED,+ TOKEN_EXPIRE_HOURS,+ TokenPayload,+ add_user,+ authenticate,+ authenticate_pb,+ create_token,+ decode_token,+ delete_user,+ is_first_user,+ list_users,+ register_pb,+ set_role,+)+- logger = get_logger("Auth")++logger = logging.getLogger(__name__)++router = APIRouter()+_bearer = HTTPBearer(auto_error=False)++_COOKIE_NAME = "dt_token"+_COOKIE_MAX_AGE = TOKEN_EXPIRE_HOURS * 3600+++# ---------------------------------------------------------------------------+# Schemas+# ---------------------------------------------------------------------------+++class LoginRequest(BaseModel):+ """Payload for the POST /login endpoint."""++ username: str+ password: str+++class RegisterRequest(BaseModel):+ """Payload for the POST /register endpoint."""++ username: str+ password: str++ @field_validator("username")+ @classmethod+ def username_valid(cls, v: str) -> str:+ import re++ v = v.strip()+ if not v:+ raise ValueError("Email cannot be empty")+ # Accept standard email addresses (used by PocketBase mode) or plain+ # usernames (used by the built-in SQLite/JSON auth mode).+ email_re = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")+ plain_re = re.compile(r"^[A-Za-z0-9_\-.]{3,64}$")+ if not email_re.match(v) and not plain_re.match(v):+ raise ValueError("Enter a valid email address")+ return v++ @field_validator("password")+ @classmethod+ def password_valid(cls, v: str) -> str:+ if len(v) < 8:+ raise ValueError("Password must be at least 8 characters")+ return v+++class SetRoleRequest(BaseModel):+ """Payload for the PUT /users/{username}/role endpoint."""++ role: str++ @field_validator("role")+ @classmethod+ def role_valid(cls, v: str) -> str:+ if v not in ("admin", "user"):+ raise ValueError("Role must be 'admin' or 'user'")+ return v+++class AuthStatusResponse(BaseModel):+ """Response body for the GET /status endpoint."""++ enabled: bool+ authenticated: bool+ username: str | None = None+ role: str | None = None+++class UserInfo(BaseModel):+ """Single user record returned by the GET /users endpoint."""++ username: str+ role: str+ created_at: str+++# ---------------------------------------------------------------------------+# Shared helper — extract token from cookie or Bearer header+# ---------------------------------------------------------------------------+++def _extract_token(+ credentials: HTTPAuthorizationCredentials | None,+ dt_token: str | None,+) -> str | None:+ if credentials:+ return credentials.credentials+ return dt_token+++# ---------------------------------------------------------------------------+# Dependencies — reusable auth guards for other routers+# ---------------------------------------------------------------------------+++def require_auth(+ credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),+ dt_token: str | None = Cookie(default=None),+) -> TokenPayload | None:+ """+ FastAPI dependency that enforces authentication when AUTH_ENABLED=true.++ Accepts the JWT from either:+ - Authorization: Bearer <token> header+ - dt_token cookie++ Returns the authenticated TokenPayload, or None if auth is disabled.+ Raises HTTP 401 if auth is enabled but the token is missing or invalid.+ """+ if not AUTH_ENABLED:+ return None++ token = _extract_token(credentials, dt_token)++ if not token:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Not authenticated",+ headers={"WWW-Authenticate": "Bearer"},+ )++ payload = decode_token(token)+ if not payload:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Invalid or expired token",+ headers={"WWW-Authenticate": "Bearer"},+ )++ return payload+++def require_admin(+ payload: TokenPayload | None = Depends(require_auth),+) -> TokenPayload:+ """+ FastAPI dependency that requires the caller to be an admin.++ Raises HTTP 403 if the authenticated user is not an admin.+ When AUTH_ENABLED=false, all requests are treated as admin.+ """+ if not AUTH_ENABLED:+ from deeptutor.services.auth import TokenPayload as TP++ return TP(username="local", role="admin")++ if payload is None or payload.role != "admin":+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Admin access required",+ )+ return payload+++# ---------------------------------------------------------------------------+# Public endpoints (no auth required)+# ---------------------------------------------------------------------------++[email protected]("/status", response_model=AuthStatusResponse)+async def auth_status(+ credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),+ dt_token: str | None = Cookie(default=None),+) -> AuthStatusResponse:+ """Return whether auth is enabled and whether the current request is authenticated."""+ if not AUTH_ENABLED:+ return AuthStatusResponse(enabled=False, authenticated=True, role="admin")++ token = _extract_token(credentials, dt_token)+ payload = decode_token(token) if token else None+ return AuthStatusResponse(+ enabled=True,+ authenticated=payload is not None,+ username=payload.username if payload else None,+ role=payload.role if payload else None,+ )++[email protected]("/login")+async def login(body: LoginRequest, response: Response) -> dict:+ """Validate credentials and set a JWT cookie."""+ if not AUTH_ENABLED:+ return {"ok": True, "message": "Auth is disabled — no login required."}++ if POCKETBASE_ENABLED:+ # PocketBase mode: email = username field for backwards-compat with the+ # existing LoginRequest schema; users can pass their email as "username".+ pb_result = authenticate_pb(body.username, body.password)+ if not pb_result:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Incorrect email or password",+ )+ payload, pb_token = pb_result+ response.set_cookie(+ key=_COOKIE_NAME,+ value=pb_token,+ httponly=True,+ samesite=_SAMESITE,+ max_age=_COOKIE_MAX_AGE,+ secure=_SECURE,+ )+ logger.info(f"User '{payload.username}' logged in via PocketBase (role={payload.role!r})")+ return {"ok": True, "username": payload.username, "role": payload.role}++ # Standard JWT + bcrypt mode+ result = authenticate(body.username, body.password)+ if not result:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Incorrect username or password",+ )++ token = create_token(result.username, result.role)+ response.set_cookie(+ key=_COOKIE_NAME,+ value=token,+ httponly=True,+ samesite=_SAMESITE,+ max_age=_COOKIE_MAX_AGE,+ secure=_SECURE,+ )++ logger.info(f"User '{result.username}' logged in (role={result.role!r})")+ return {"ok": True, "username": result.username, "role": result.role}++[email protected]("/logout")+async def logout(response: Response) -> dict:+ """Clear the JWT cookie."""+ response.delete_cookie(key=_COOKIE_NAME, samesite=_SAMESITE)+ return {"ok": True}++[email protected]("/register", status_code=status.HTTP_201_CREATED)+async def register(body: RegisterRequest) -> dict:+ """+ Create a new user account.++ In PocketBase mode, the username is also used as the email address.+ In standard mode, the first user to register is automatically granted admin.++ Only available when AUTH_ENABLED=true.+ """+ if not AUTH_ENABLED:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Auth is disabled — registration is not available.",+ )++ if POCKETBASE_ENABLED:+ result = register_pb(username=body.username, email=body.username, password=body.password)+ if not result:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="Registration failed — username or email may already be taken.",+ )+ logger.info(f"New user registered via PocketBase: '{body.username}'")+ return {"ok": True, "username": body.username, "role": "user", "is_first_user": False}++ # Standard mode+ first = is_first_user()+ existing = {u["username"] for u in list_users()}+ if body.username in existing:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="Username already taken",+ )++ add_user(body.username, body.password)+ role = "admin" if first else "user"+ logger.info(f"New user registered: '{body.username}' (role={role!r})")+ return {"ok": True, "username": body.username, "role": role, "is_first_user": first}++[email protected]("/is_first_user")+async def check_is_first_user() -> dict:+ """Return whether the user store is empty (used by the register UI)."""+ return {"is_first_user": is_first_user() if AUTH_ENABLED else False}+++# ---------------------------------------------------------------------------+# Admin-only endpoints+# ---------------------------------------------------------------------------++[email protected]("/users", response_model=list[UserInfo])+async def get_users(_: TokenPayload = Depends(require_admin)) -> list[UserInfo]:+ """List all registered users. Requires admin role."""+ return [UserInfo(**u) for u in list_users()]++[email protected]("/users/{username}", status_code=status.HTTP_200_OK)+async def remove_user(+ username: str,+ current: TokenPayload = Depends(require_admin),+) -> dict:+ """Delete a user. Admins cannot delete their own account."""+ if current and username == current.username:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="You cannot delete your own account",+ )++ removed = delete_user(username)+ if not removed:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")++ logger.info(f"Admin '{current.username if current else 'local'}' deleted user '{username}'")+ return {"ok": True}++[email protected]("/users/{username}/role", status_code=status.HTTP_200_OK)+async def update_user_role(+ username: str,+ body: SetRoleRequest,+ current: TokenPayload = Depends(require_admin),+) -> dict:+ """Change a user's role. Admins cannot change their own role."""+ if current and username == current.username:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="You cannot change your own role",+ )++ updated = set_role(username, body.role)+ if not updated:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")++ logger.info(+ f"Admin '{current.username if current else 'local'}' set '{username}' role to {body.role!r}"+ )+ return {"ok": True, "username": username, "role": body.role}diff --cc deeptutor/knowledge/manager.pyindex 104f47d2c,740b4e4ea..77578462b--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@@ -16,11 -17,10 +17,10 @@@ import staimport sysfrom typing import Any- from deeptutor.logging import get_logger-from deeptutor.services.rag.factory import DEFAULT_PROVIDER+from deeptutor.services.rag.factory import DEFAULT_PROVIDER, normalize_provider_namefrom deeptutor.services.rag.file_routing import FileTypeRouter- logger = get_logger("KnowledgeBaseManager")+ logger = logging.getLogger(__name__)# Cross-platform file locking@@@ -300,9 -345,26 +384,27 @@@ class KnowledgeBaseManagerfp = _get_embedding_fingerprint()if fp:kb_config["embedding_model"], kb_config["embedding_dim"] = fp+ # Record the active signature + the on-disk version registry so+ # the UI can render version chips without recomputing.+ try:+ from deeptutor.services.rag.embedding_signature import (+ signature_from_embedding_config,+ )+ from deeptutor.services.rag.index_versioning import (+ list_kb_versions,+ )++ sig = signature_from_embedding_config()+ if sig is not None:+ kb_config["embedding_signature"] = sig.hash()+ kb_dir = self.base_dir / name+ if kb_dir.is_dir():+ kb_config["index_versions"] = list_kb_versions(kb_dir)+ except Exception: # pragma: no cover - best-effort metadata+ passself._save_config()+ self._sync_kb_to_pb(name, kb_config)def get_kb_status(self, name: str) -> dict | None:"""Get status and progress for a knowledge base."""diff --cc deeptutor/services/auth.pyindex 89930532b,000000000..7ee3d7371mode 100644,000000..100644--- a/deeptutor/services/auth.py+++ b/deeptutor/services/auth.py@@@ -1,404 -1,0 +1,403 @@@+"""+Authentication service for DeepTutor.++Disabled by default (AUTH_ENABLED=false) so localhost users are unaffected.+When enabled, guards all API routes with JWT bearer tokens.++Quick setup (single user via env vars):+ 1. Set AUTH_ENABLED=true in .env+ 2. Set AUTH_USERNAME=<your username>+ 3. Generate a password hash:+ python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"+ Paste the output into AUTH_PASSWORD_HASH=<hash>+ 4. Set AUTH_SECRET to a long random string++Multi-user setup (recommended):+ Enable AUTH_ENABLED=true and leave AUTH_USERNAME/AUTH_PASSWORD_HASH empty.+ Navigate to /register in the browser. The first user to register is granted+ admin privileges and can manage other users from /admin/users.++ Users are stored in data/user/auth_users.json:+ {+ "alice": {"hash": "$2b$12$...", "role": "admin", "created_at": "2026-..."},+ "bob": {"hash": "$2b$12$...", "role": "user", "created_at": "2026-..."}+ }+"""++from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+import json++import logging+import os+from pathlib import Path+import secrets+- from deeptutor.logging import get_logger-- logger = get_logger("Auth")++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Configuration — read once at import time+# ---------------------------------------------------------------------------++AUTH_ENABLED: bool = os.getenv("AUTH_ENABLED", "false").lower() == "true"+AUTH_USERNAME: str = os.getenv("AUTH_USERNAME", "admin")+AUTH_PASSWORD_HASH: str = os.getenv("AUTH_PASSWORD_HASH", "")+AUTH_SECRET: str = os.getenv("AUTH_SECRET", "")+TOKEN_EXPIRE_HOURS: int = int(os.getenv("AUTH_TOKEN_EXPIRE_HOURS", "24"))++# PocketBase auth mode — active when POCKETBASE_URL is set AND AUTH_ENABLED=true.+# When enabled, login/register proxy to PocketBase and token validation uses+# PocketBase's auth-refresh endpoint (cached in memory — no static secret needed).+POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")+POCKETBASE_ENABLED: bool = bool(POCKETBASE_URL) and AUTH_ENABLED++_ALGORITHM = "HS256"+_USERS_FILE = Path("data/user/auth_users.json")++if AUTH_ENABLED and not POCKETBASE_ENABLED and not AUTH_SECRET:+ logger.warning(+ "AUTH_ENABLED=true but AUTH_SECRET is not set. "+ "A temporary secret will be generated — tokens will be invalidated on restart. "+ "Set AUTH_SECRET in .env to a stable random value."+ )+ AUTH_SECRET = secrets.token_hex(32)+++# ---------------------------------------------------------------------------+# Token payload+# ---------------------------------------------------------------------------+++@dataclass+class TokenPayload:+ """Decoded JWT payload."""++ username: str+ role: str+++# ---------------------------------------------------------------------------+# Password hashing — uses bcrypt directly (passlib is unmaintained for bcrypt 4+)+# ---------------------------------------------------------------------------+++def hash_password(plain: str) -> str:+ """Hash a plaintext password. Use this to generate password hashes."""+ import bcrypt++ return bcrypt.hashpw(plain.encode(), bcrypt.gensalt()).decode()+++def verify_password(plain: str, hashed: str) -> bool:+ """Verify a plaintext password against a stored bcrypt hash."""+ import bcrypt++ try:+ return bcrypt.checkpw(plain.encode(), hashed.encode())+ except Exception:+ return False+++# ---------------------------------------------------------------------------+# User store — JSON file takes priority over env vars+# ---------------------------------------------------------------------------+++def _make_user_record(hashed: str, role: str = "user", created_at: str = "") -> dict:+ """Build a canonical user record dict."""+ return {+ "hash": hashed,+ "role": role,+ "created_at": created_at or datetime.now(timezone.utc).isoformat(),+ }+++def _load_users() -> dict[str, dict]:+ """+ Load the user store, migrating old flat format if needed.++ Priority:+ 1. data/user/auth_users.json — multi-user file+ 2. AUTH_USERNAME + AUTH_PASSWORD_HASH env vars — single-user fallback++ Old format: {"alice": "$2b$12$..."}+ New format: {"alice": {"hash": "...", "role": "admin", "created_at": "..."}}+ """+ if _USERS_FILE.exists():+ try:+ data = json.loads(_USERS_FILE.read_text())+ if not isinstance(data, dict):+ logger.warning("auth_users.json is not a JSON object — falling back to env vars")+ data = {}++ migrated = False+ users: dict[str, dict] = {}+ for username, value in data.items():+ if isinstance(value, str):+ # Migrate old flat hash string — first user in old file gets admin+ role = "admin" if not users else "user"+ users[username] = _make_user_record(value, role=role)+ migrated = True+ elif isinstance(value, dict):+ users[username] = value+ else:+ logger.warning(f"Skipping malformed user entry: {username!r}")++ if migrated:+ _USERS_FILE.write_text(json.dumps(users, indent=2))+ logger.info("Migrated auth_users.json to new schema with role/created_at fields")++ return users+ except Exception as exc:+ logger.warning(f"Failed to read auth_users.json: {exc} — falling back to env vars")++ # Env-var single-user fallback — always treated as admin+ if AUTH_USERNAME and AUTH_PASSWORD_HASH:+ return {AUTH_USERNAME: _make_user_record(AUTH_PASSWORD_HASH, role="admin", created_at="")}++ return {}+++def is_first_user() -> bool:+ """Return True when no users exist yet (first registration will become admin)."""+ return len(_load_users()) == 0+++def add_user(username: str, plain_password: str, role: str = "user") -> None:+ """+ Add or update a user in data/user/auth_users.json.++ The role defaults to 'user'. Pass role='admin' to elevate. When the store+ is empty the first user is automatically promoted to 'admin' regardless of+ the role argument.++ Creates the file (and parent directories) if they don't exist.+ """+ _USERS_FILE.parent.mkdir(parents=True, exist_ok=True)++ users: dict[str, dict] = {}+ if _USERS_FILE.exists():+ try:+ users = json.loads(_USERS_FILE.read_text())+ except Exception:+ pass++ effective_role = "admin" if not users else role+ users[username] = _make_user_record(hash_password(plain_password), role=effective_role)+ _USERS_FILE.write_text(json.dumps(users, indent=2))+ logger.info(f"User '{username}' saved to {_USERS_FILE} with role={effective_role!r}")+++def list_users() -> list[dict]:+ """Return a list of user info dicts (username, role, created_at) — no hashes."""+ users = _load_users()+ return [+ {+ "username": username,+ "role": record.get("role", "user"),+ "created_at": record.get("created_at", ""),+ }+ for username, record in users.items()+ ]+++def delete_user(username: str) -> bool:+ """+ Remove a user from the store. Returns True if the user existed.++ Note: env-var-only users cannot be deleted via this function.+ """+ if not _USERS_FILE.exists():+ return False++ try:+ users: dict[str, dict] = json.loads(_USERS_FILE.read_text())+ except Exception:+ return False++ if username not in users:+ return False++ del users[username]+ _USERS_FILE.write_text(json.dumps(users, indent=2))+ logger.info(f"User '{username}' deleted from {_USERS_FILE}")+ return True+++def set_role(username: str, role: str) -> bool:+ """+ Change the role for an existing user. Returns True on success.++ Valid roles: 'admin', 'user'.+ """+ if role not in ("admin", "user"):+ raise ValueError(f"Invalid role: {role!r}. Must be 'admin' or 'user'.")++ if not _USERS_FILE.exists():+ return False++ try:+ users: dict[str, dict] = json.loads(_USERS_FILE.read_text())+ except Exception:+ return False++ if username not in users:+ return False++ users[username]["role"] = role+ _USERS_FILE.write_text(json.dumps(users, indent=2))+ logger.info(f"User '{username}' role updated to {role!r}")+ return True+++# ---------------------------------------------------------------------------+# JWT+# ---------------------------------------------------------------------------+++def create_token(username: str, role: str = "user") -> str:+ """Create a signed JWT for the given username and role."""+ from jose import jwt++ payload = {+ "sub": username,+ "role": role,+ "exp": datetime.now(timezone.utc) + timedelta(hours=TOKEN_EXPIRE_HOURS),+ "iat": datetime.now(timezone.utc),+ }+ return jwt.encode(payload, AUTH_SECRET, algorithm=_ALGORITHM)+++def decode_token(token: str) -> TokenPayload | None:+ """+ Validate a token and return a TokenPayload, or None if invalid.++ - PocketBase mode: calls PocketBase's auth-refresh endpoint (cached in+ memory for 60 s, so only the first request per token per minute makes+ a network call). No static JWT secret required.+ - Standard mode: local in-memory jwt.decode() using AUTH_SECRET — zero+ network calls, same as before.+ """+ if not token:+ return None++ if POCKETBASE_ENABLED:+ from deeptutor.services.pocketbase_client import validate_pb_token++ payload = validate_pb_token(token)+ if payload is None:+ return None+ return TokenPayload(+ username=payload["username"],+ role=payload.get("role", "user"),+ )++ # Standard JWT + bcrypt mode+ from jose import JWTError, jwt++ if not AUTH_SECRET:+ return None++ try:+ payload = jwt.decode(token, AUTH_SECRET, algorithms=[_ALGORITHM])+ username = payload.get("sub")+ if not username:+ return None+ return TokenPayload(username=username, role=payload.get("role", "user"))+ except JWTError:+ return None+++# ---------------------------------------------------------------------------+# PocketBase auth helpers+# ---------------------------------------------------------------------------+++def authenticate_pb(username: str, password: str) -> tuple[TokenPayload, str] | None:+ """+ Authenticate against PocketBase and return (TokenPayload, raw_pb_token).++ Only called when POCKETBASE_ENABLED=True.+ Returns None on failure.+ The raw token is the PocketBase JWT string to be stored in the cookie.++ PocketBase requires an email address; plain usernames are mapped to+ <username>@deeptutor.local to match the email used at registration.+ """+ try:+ from deeptutor.services.pocketbase_client import get_pb_client++ pb = get_pb_client()+ result = pb.collection("users").auth_with_password(username, password)+ token: str = result.token+ record = result.record+ username = (+ getattr(record, "email", None)+ or getattr(record, "name", None)+ or getattr(record, "id", "unknown")+ )+ # PocketBase has no built-in "role" field by default; treat all as "user".+ # Admins authenticated via PocketBase admin panel use a separate endpoint.+ role = getattr(record, "role", "user") or "user"+ return TokenPayload(username=str(username), role=str(role)), token+ except Exception as exc:+ logger.warning(f"PocketBase authentication failed: {exc}")+ return None+++def register_pb(username: str, email: str, password: str) -> dict | None:+ """+ Create a new user in PocketBase.++ Returns the created user record dict or None on failure.+ """+ try:+ from deeptutor.services.pocketbase_client import get_pb_client++ pb = get_pb_client()+ record = pb.collection("users").create(+ {+ "username": username,+ "email": email,+ "password": password,+ "passwordConfirm": password,+ }+ )+ return {"id": record.id, "username": username, "email": email}+ except Exception as exc:+ logger.warning(f"PocketBase registration failed: {exc}")+ return None+++# ---------------------------------------------------------------------------+# Main auth entry point+# ---------------------------------------------------------------------------+++def authenticate(username: str, password: str) -> TokenPayload | None:+ """+ Validate credentials. Returns a TokenPayload on success, None on failure.++ When AUTH_ENABLED=false, always returns a dummy admin payload so that+ callers don't need to special-case the disabled state.+ """+ if not AUTH_ENABLED:+ return TokenPayload(username=username or "local", role="admin")++ users = _load_users()+ if not users:+ logger.warning(+ "No users configured — login will always fail. "+ "Navigate to /register to create your first account."+ )+ return None++ record = users.get(username)+ if not record:+ return None++ hashed = record.get("hash", "") if isinstance(record, dict) else record+ if not verify_password(password, hashed):+ return None++ role = record.get("role", "user") if isinstance(record, dict) else "user"+ return TokenPayload(username=username, role=role)diff --cc deeptutor/services/memory/service.pyindex 8d6e2e956,e573a4e62..199a517a4--- a/deeptutor/services/memory/service.py+++ b/deeptutor/services/memory/service.py@@@ -16,9 -18,10 +18,10 @@@ from pathlib import Patimport refrom typing import Literal+ from deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.llm import stream as llm_streamfrom deeptutor.services.path_service import PathService, get_path_service-from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store+from deeptutor.services.session.protocol import SessionStoreProtocolMemoryFile = Literal["summary", "profile"]MEMORY_FILES: list[MemoryFile] = ["summary", "profile"]@@@ -52,12 -57,11 +57,13 @@@ class MemoryServicedef __init__(self,path_service: PathService | None = None,- store: SQLiteSessionStore | None = None,+ store: SessionStoreProtocol | None = None,) -> None:+ from deeptutor.services.session import get_session_store+self._path_service = path_service or get_path_service()- self._store = store or get_sqlite_session_store()+ self._store = store or get_session_store()+ self._refresh_lock = asyncio.Lock()self._migrate_legacy()@propertydiff --cc deeptutor/services/pocketbase_client.pyindex 76bc26d48,000000000..80cd62c57mode 100644,000000..100644--- a/deeptutor/services/pocketbase_client.py+++ b/deeptutor/services/pocketbase_client.py@@@ -1,177 -1,0 +1,176 @@@+"""+PocketBase client singleton.++Only initialised when POCKETBASE_URL is present in the environment.+All other code checks ``is_pocketbase_enabled()`` before calling+``get_pb_client()`` to avoid import-time failures when PocketBase is+not configured.++Token validation uses PocketBase's auth-refresh endpoint rather than+local JWT decoding (PocketBase does not expose a static JWT secret).+Results are cached in memory for 60 seconds so only the first request+per token per minute incurs a network call (~5–10 ms); all subsequent+requests within the TTL are resolved in < 1 ms from the local cache.++Usage:+ from deeptutor.services.pocketbase_client import get_pb_client, is_pocketbase_enabled++ if is_pocketbase_enabled():+ pb = get_pb_client()+ result = pb.collection("sessions").get_list(1, 50)+"""++from __future__ import annotations+++import logging+import os+import time+from typing import Any+- from deeptutor.logging import get_logger-- logger = get_logger("PocketBase")++logger = logging.getLogger(__name__)++_POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")+_ADMIN_EMAIL: str = os.getenv("POCKETBASE_ADMIN_EMAIL", "")+_ADMIN_PASSWORD: str = os.getenv("POCKETBASE_ADMIN_PASSWORD", "")++_client = None+_client_initialised = False++# Token validation cache: token -> (payload_dict, expires_at)+_TOKEN_CACHE: dict[str, tuple[dict[str, Any], float]] = {}+_TOKEN_CACHE_TTL: float = 60.0 # seconds+++def is_pocketbase_enabled() -> bool:+ """Return True when POCKETBASE_URL is configured."""+ return bool(_POCKETBASE_URL)+++def get_pb_client():+ """+ Return an admin-authenticated PocketBase SDK client (cached singleton).++ Raises RuntimeError if POCKETBASE_URL is not set.+ Raises on authentication failure.+ """+ global _client, _client_initialised++ if not is_pocketbase_enabled():+ raise RuntimeError("PocketBase is not configured. Set POCKETBASE_URL in .env to enable it.")++ if _client_initialised:+ return _client++ try:+ from pocketbase import PocketBase # type: ignore[import]+ except ImportError as exc:+ raise RuntimeError(+ "The 'pocketbase' package is not installed. Run: pip install pocketbase"+ ) from exc++ pb = PocketBase(_POCKETBASE_URL)++ if _ADMIN_EMAIL and _ADMIN_PASSWORD:+ try:+ pb.admins.auth_with_password(_ADMIN_EMAIL, _ADMIN_PASSWORD)+ logger.info(f"PocketBase admin authenticated at {_POCKETBASE_URL}")+ except Exception as exc:+ logger.error(+ f"PocketBase admin authentication failed: {exc}. "+ "Check POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD."+ )+ raise+ else:+ logger.warning(+ "POCKETBASE_ADMIN_EMAIL / POCKETBASE_ADMIN_PASSWORD not set. "+ "The backend will connect to PocketBase without admin privileges. "+ "Collection management (scripts/pb_setup.py) will not work."+ )++ _client = pb+ _client_initialised = True+ return _client+++def validate_pb_token(token: str) -> dict[str, Any] | None:+ """+ Validate a PocketBase user token and return the user payload dict.++ Uses PocketBase's /api/collections/users/auth-refresh endpoint.+ Results are cached for ``_TOKEN_CACHE_TTL`` seconds so only the+ first call per token per minute makes a network round-trip.++ Returns a dict with at least ``username`` and ``role`` keys, or+ None if the token is invalid / expired.+ """+ if not is_pocketbase_enabled():+ return None++ now = time.monotonic()++ # Cache hit+ cached = _TOKEN_CACHE.get(token)+ if cached is not None:+ payload, expires_at = cached+ if now < expires_at:+ return payload+ del _TOKEN_CACHE[token]++ # Cache miss — call PocketBase+ try:+ from pocketbase import PocketBase # type: ignore[import]++ pb = PocketBase(_POCKETBASE_URL)+ # Inject the user token so auth_refresh validates it+ pb.auth_store.save(token, None)+ result = pb.collection("users").auth_refresh()++ record = result.record+ username = (+ getattr(record, "email", None)+ or getattr(record, "name", None)+ or getattr(record, "username", None)+ or getattr(record, "id", "unknown")+ )+ role = str(getattr(record, "role", "user") or "user")++ payload = {"username": str(username), "role": role}+ _TOKEN_CACHE[token] = (payload, now + _TOKEN_CACHE_TTL)+ return payload++ except Exception as exc:+ logger.debug(f"PocketBase token validation failed: {exc}")+ return None+++async def ping_pocketbase() -> bool:+ """+ Async health check called during FastAPI lifespan startup.++ Returns True if PocketBase is reachable, False otherwise.+ Logs a clear warning (not an exception) so the server still starts+ when PocketBase is configured but temporarily unavailable.+ """+ if not is_pocketbase_enabled():+ return False++ try:+ import httpx++ async with httpx.AsyncClient(timeout=5.0) as client:+ resp = await client.get(f"{_POCKETBASE_URL}/api/health")+ if resp.status_code == 200:+ logger.info(f"PocketBase health check passed at {_POCKETBASE_URL}")+ return True+ logger.warning(+ f"PocketBase health check returned HTTP {resp.status_code} at {_POCKETBASE_URL}. "+ "Sessions will fail until PocketBase is healthy."+ )+ return False+ except Exception as exc:+ logger.warning(+ f"PocketBase is unreachable at {_POCKETBASE_URL} ({exc}). "+ "Sessions and auth will fall back to SQLite until PocketBase is available. "+ "Check that the pocketbase container is running and POCKETBASE_URL is correct."+ )+ return Falsediff --cc deeptutor/services/session/pocketbase_store.pyindex 896213768,000000000..a8a6eb547mode 100644,000000..100644--- a/deeptutor/services/session/pocketbase_store.py+++ b/deeptutor/services/session/pocketbase_store.py@@@ -1,616 -1,0 +1,616 @@@+"""+PocketBase-backed session store.++Implements SessionStoreProtocol using PocketBase collections for all durable+storage. The key performance design:++- All methods except ``append_turn_event`` make direct PocketBase HTTP calls.+ These are called at most a handful of times per turn (create, get, update+ status, add message) and the ~5–10 ms overhead is acceptable.++- ``append_turn_event`` returns immediately without writing to PocketBase.+ The existing ``_mirror_event_to_workspace`` in turn_runtime.py already+ appends every event to a local ``events.jsonl`` file. When+ ``update_turn_status`` finalises a turn it reads that file and batch-posts+ all events to PocketBase ``turn_events`` in a single request, trading+ real-time durability for ~40× lower per-event latency during streaming.+"""++from __future__ import annotations++import asyncio+import json++import logging+from pathlib import Path+import time+from typing import Any+import uuid+- from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_service+- logger = get_logger("PocketBaseStore")++logger = logging.getLogger(__name__)+++def _json_loads(value: Any, default: Any) -> Any:+ if not value:+ return default+ if isinstance(value, (dict, list)):+ return value+ try:+ return json.loads(value)+ except Exception:+ return default+++def _pb():+ """Return the shared PocketBase client."""+ from deeptutor.services.pocketbase_client import get_pb_client++ return get_pb_client()+++def _to_float(value: Any, default: float = 0.0) -> float:+ try:+ return float(value) if value is not None else default+ except (TypeError, ValueError):+ return default+++class PocketBaseSessionStore:+ """PocketBase-backed implementation of SessionStoreProtocol."""++ # ------------------------------------------------------------------+ # Sessions+ # ------------------------------------------------------------------++ async def create_session(+ self,+ title: str | None = None,+ session_id: str | None = None,+ ) -> dict[str, Any]:+ now = time.time()+ resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"+ resolved_title = (title or "New conversation").strip() or "New conversation"++ def _create():+ return (+ _pb()+ .collection("sessions")+ .create(+ {+ "session_id": resolved_id,+ "title": resolved_title[:100],+ "compressed_summary": "",+ "summary_up_to_msg_id": 0,+ "preferences_json": {},+ "capability": "",+ "status": "idle",+ }+ )+ )++ record = await asyncio.to_thread(_create)+ return self._session_record_to_dict(record, resolved_id, resolved_title, now)++ async def get_session(self, session_id: str) -> dict[str, Any] | None:+ def _get():+ try:+ records = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ return records[0] if records else None+ except Exception:+ return None++ record = await asyncio.to_thread(_get)+ if record is None:+ return None+ return self._session_record_to_dict(record)++ async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]:+ if session_id:+ session = await self.get_session(session_id)+ if session is not None:+ return session+ return await self.create_session()++ def _session_record_to_dict(+ self,+ record: Any,+ session_id: str | None = None,+ title: str | None = None,+ now: float | None = None,+ ) -> dict[str, Any]:+ sid = session_id or getattr(record, "session_id", getattr(record, "id", ""))+ t = title or getattr(record, "title", "New conversation") or "New conversation"+ created = _to_float(getattr(record, "created", None)) or now or time.time()+ updated = _to_float(getattr(record, "updated", None)) or now or time.time()+ preferences_raw = getattr(record, "preferences_json", None)+ return {+ "id": sid,+ "session_id": sid,+ "title": t,+ "created_at": created,+ "updated_at": updated,+ "compressed_summary": getattr(record, "compressed_summary", "") or "",+ "summary_up_to_msg_id": int(getattr(record, "summary_up_to_msg_id", 0) or 0),+ "preferences": _json_loads(preferences_raw, {}),+ "capability": getattr(record, "capability", "") or "",+ "status": getattr(record, "status", "idle") or "idle",+ "active_turn_id": "",+ }++ async def update_session_title(self, session_id: str, title: str) -> bool:+ def _update():+ records = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if not records:+ return False+ _pb().collection("sessions").update(+ records[0].id, {"title": (title.strip() or "New conversation")[:100]}+ )+ return True++ try:+ return await asyncio.to_thread(_update)+ except Exception as exc:+ logger.warning(f"update_session_title failed: {exc}")+ return False++ async def delete_session(self, session_id: str) -> bool:+ def _delete():+ records = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if not records:+ return False+ _pb().collection("sessions").delete(records[0].id)+ return True++ try:+ return await asyncio.to_thread(_delete)+ except Exception as exc:+ logger.warning(f"delete_session failed: {exc}")+ return False++ async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:+ page = (offset // limit) + 1++ def _list():+ return (+ _pb()+ .collection("sessions")+ .get_list(+ page,+ limit,+ query_params={"sort": "-updated"},+ )+ )++ try:+ result = await asyncio.to_thread(_list)+ return [self._session_record_to_dict(r) for r in result.items]+ except Exception as exc:+ logger.warning(f"list_sessions failed: {exc}")+ return []++ async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:+ def _update():+ records = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if not records:+ return False+ _pb().collection("sessions").update(+ records[0].id,+ {+ "compressed_summary": summary,+ "summary_up_to_msg_id": max(0, int(up_to_msg_id)),+ },+ )+ return True++ try:+ return await asyncio.to_thread(_update)+ except Exception as exc:+ logger.warning(f"update_summary failed: {exc}")+ return False++ async def update_session_preferences(+ self, session_id: str, preferences: dict[str, Any]+ ) -> bool:+ async def _merge():+ session = await self.get_session(session_id)+ if session is None:+ return False+ merged = {**session.get("preferences", {}), **(preferences or {})}++ def _update():+ records = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if not records:+ return False+ _pb().collection("sessions").update(records[0].id, {"preferences_json": merged})+ return True++ return await asyncio.to_thread(_update)++ try:+ return await _merge()+ except Exception as exc:+ logger.warning(f"update_session_preferences failed: {exc}")+ return False++ async def get_session_with_messages(self, session_id: str) -> dict[str, Any] | None:+ session = await self.get_session(session_id)+ if session is None:+ return None+ session["messages"] = await self.get_messages(session_id)+ session["active_turns"] = await self.list_active_turns(session_id)+ return session++ # ------------------------------------------------------------------+ # Messages+ # ------------------------------------------------------------------++ async def add_message(+ self,+ session_id: str,+ role: str,+ content: str,+ capability: str = "",+ events: list[dict[str, Any]] | None = None,+ attachments: list[dict[str, Any]] | None = None,+ ) -> int:+ now = time.time()++ def _add():+ record = (+ _pb()+ .collection("messages")+ .create(+ {+ "session_id": session_id,+ "role": role,+ "content": content or "",+ "capability": capability or "",+ "events_json": events or [],+ "attachments_json": attachments or [],+ "msg_created_at": now,+ }+ )+ )+ # Update session title if still default+ sessions = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if sessions and sessions[0].title == "New conversation" and role == "user":+ trimmed = (content or "").strip()+ if trimmed:+ new_title = trimmed[:50] + ("..." if len(trimmed) > 50 else "")+ _pb().collection("sessions").update(sessions[0].id, {"title": new_title})+ return record++ try:+ record = await asyncio.to_thread(_add)+ # Return a synthetic integer id using epoch ms+ return int(now * 1000)+ except Exception as exc:+ logger.warning(f"add_message failed: {exc}")+ return 0++ async def get_messages(self, session_id: str) -> list[dict[str, Any]]:+ def _get():+ return (+ _pb()+ .collection("messages")+ .get_full_list(+ query_params={+ "filter": f'session_id="{session_id}"',+ "sort": "msg_created_at",+ }+ )+ )++ try:+ records = await asyncio.to_thread(_get)+ return [self._message_record_to_dict(r) for r in records]+ except Exception as exc:+ logger.warning(f"get_messages failed: {exc}")+ return []++ async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:+ messages = await self.get_messages(session_id)+ return [+ {"id": m["id"], "role": m["role"], "content": m["content"] or ""}+ for m in messages+ if m["role"] in ("user", "assistant", "system")+ ]++ def _message_record_to_dict(self, record: Any) -> dict[str, Any]:+ return {+ "id": getattr(record, "id", ""),+ "session_id": getattr(record, "session_id", ""),+ "role": getattr(record, "role", ""),+ "content": getattr(record, "content", "") or "",+ "capability": getattr(record, "capability", "") or "",+ "events": _json_loads(getattr(record, "events_json", None), []),+ "attachments": _json_loads(getattr(record, "attachments_json", None), []),+ "created_at": _to_float(getattr(record, "msg_created_at", None)),+ }++ # ------------------------------------------------------------------+ # Turns+ # ------------------------------------------------------------------++ async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]:+ now = time.time()+ turn_id = f"turn_{int(now * 1000)}_{uuid.uuid4().hex[:10]}"++ def _create():+ # Guard: ensure session exists+ sessions = (+ _pb()+ .collection("sessions")+ .get_full_list(query_params={"filter": f'session_id="{session_id}"'})+ )+ if not sessions:+ raise ValueError(f"Session not found: {session_id}")+ # Guard: no duplicate active turns+ active = (+ _pb()+ .collection("turns")+ .get_full_list(+ query_params={"filter": f'session_id="{session_id}" && status="running"'}+ )+ )+ if active:+ raise RuntimeError(f"Session already has an active turn: {active[0].turn_id}")+ return (+ _pb()+ .collection("turns")+ .create(+ {+ "turn_id": turn_id,+ "session_id": session_id,+ "capability": capability or "",+ "status": "running",+ "error": "",+ "turn_created_at": now,+ "turn_updated_at": now,+ "finished_at": None,+ }+ )+ )++ await asyncio.to_thread(_create)+ return {+ "id": turn_id,+ "turn_id": turn_id,+ "session_id": session_id,+ "capability": capability or "",+ "status": "running",+ "error": "",+ "created_at": now,+ "updated_at": now,+ "finished_at": None,+ "last_seq": 0,+ }++ async def get_turn(self, turn_id: str) -> dict[str, Any] | None:+ def _get():+ records = (+ _pb()+ .collection("turns")+ .get_full_list(query_params={"filter": f'turn_id="{turn_id}"'})+ )+ return records[0] if records else None++ record = await asyncio.to_thread(_get)+ return self._turn_record_to_dict(record) if record else None++ async def get_active_turn(self, session_id: str) -> dict[str, Any] | None:+ def _get():+ records = (+ _pb()+ .collection("turns")+ .get_full_list(+ query_params={+ "filter": f'session_id="{session_id}" && status="running"',+ "sort": "-turn_updated_at",+ }+ )+ )+ return records[0] if records else None++ record = await asyncio.to_thread(_get)+ return self._turn_record_to_dict(record) if record else None++ async def list_active_turns(self, session_id: str) -> list[dict[str, Any]]:+ def _list():+ return (+ _pb()+ .collection("turns")+ .get_full_list(+ query_params={+ "filter": f'session_id="{session_id}" && status="running"',+ "sort": "-turn_updated_at",+ }+ )+ )++ try:+ records = await asyncio.to_thread(_list)+ return [self._turn_record_to_dict(r) for r in records]+ except Exception:+ return []++ async def update_turn_status(self, turn_id: str, status: str, error: str = "") -> bool:+ now = time.time()+ finished_at = now if status in {"completed", "failed", "cancelled"} else None++ def _update():+ records = (+ _pb()+ .collection("turns")+ .get_full_list(query_params={"filter": f'turn_id="{turn_id}"'})+ )+ if not records:+ return False+ _pb().collection("turns").update(+ records[0].id,+ {+ "status": status,+ "error": error or "",+ "turn_updated_at": now,+ "finished_at": finished_at,+ },+ )+ return True++ try:+ updated = await asyncio.to_thread(_update)+ except Exception as exc:+ logger.warning(f"update_turn_status failed: {exc}")+ return False++ # Batch-flush turn events from local JSONL buffer to PocketBase on finalisation+ if updated and finished_at is not None:+ await self._flush_turn_events(turn_id)++ return updated++ async def _flush_turn_events(self, turn_id: str) -> None:+ """+ Read the local events.jsonl write-ahead buffer and batch-POST all+ events to PocketBase turn_events collection in a single background call.+ """+ try:+ path_service = get_path_service()+ # The JSONL file is written by _mirror_event_to_workspace; we look+ # across all capability workspaces since we only have the turn_id.+ workspace_root = path_service.get_user_root()+ jsonl_files: list[Path] = list(workspace_root.rglob(f"{turn_id}/events.jsonl"))++ if not jsonl_files:+ return++ events: list[dict[str, Any]] = []+ for jsonl_path in jsonl_files:+ try:+ for line in jsonl_path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line:+ events.append(json.loads(line))+ except Exception as exc:+ logger.debug(f"Could not read events.jsonl at {jsonl_path}: {exc}")++ if not events:+ return++ def _batch_create():+ pb = _pb()+ for event in events:+ try:+ pb.collection("turn_events").create(+ {+ "turn_id": turn_id,+ "session_id": event.get("session_id", ""),+ "seq": int(event.get("seq", 0)),+ "type": event.get("type", ""),+ "source": event.get("source", ""),+ "stage": event.get("stage", ""),+ "content": str(event.get("content", ""))[:10000],+ "metadata_json": event.get("metadata", {}),+ "event_timestamp": float(event.get("timestamp", 0)),+ }+ )+ except Exception as exc:+ logger.debug(f"turn_events batch item failed: {exc}")++ await asyncio.to_thread(_batch_create)+ logger.debug(f"Flushed {len(events)} turn events for {turn_id} to PocketBase")++ except Exception as exc:+ logger.warning(f"_flush_turn_events failed for {turn_id}: {exc}")++ def _turn_record_to_dict(self, record: Any) -> dict[str, Any]:+ turn_id = getattr(record, "turn_id", getattr(record, "id", ""))+ return {+ "id": turn_id,+ "turn_id": turn_id,+ "session_id": getattr(record, "session_id", ""),+ "capability": getattr(record, "capability", "") or "",+ "status": getattr(record, "status", "running") or "running",+ "error": getattr(record, "error", "") or "",+ "created_at": _to_float(getattr(record, "turn_created_at", None)),+ "updated_at": _to_float(getattr(record, "turn_updated_at", None)),+ "finished_at": _to_float(getattr(record, "finished_at", None)) or None,+ "last_seq": 0,+ }++ # ------------------------------------------------------------------+ # Turn events — write-ahead only; batch flush handled in update_turn_status+ # ------------------------------------------------------------------++ async def append_turn_event(self, turn_id: str, event: dict[str, Any]) -> dict[str, Any]:+ """+ Assign a monotonic seq number and return the annotated payload.++ Does NOT write to PocketBase immediately — the caller's+ _mirror_event_to_workspace already appends to events.jsonl, which+ is flushed to PocketBase in bulk when the turn is finalised.+ """+ payload = dict(event)+ payload.setdefault("turn_id", turn_id)+ # Assign seq if not provided; use timestamp-based counter as fallback.+ if not payload.get("seq"):+ payload["seq"] = int(time.time() * 1000) % 1_000_000+ return payload++ async def get_turn_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]:+ """Retrieve persisted turn events from PocketBase (post-turn replay)."""++ def _get():+ filter_str = f'turn_id="{turn_id}"'+ if after_seq > 0:+ filter_str += f" && seq > {after_seq}"+ return (+ _pb()+ .collection("turn_events")+ .get_full_list(query_params={"filter": filter_str, "sort": "seq"})+ )++ try:+ records = await asyncio.to_thread(_get)+ return [+ {+ "type": getattr(r, "type", ""),+ "source": getattr(r, "source", ""),+ "stage": getattr(r, "stage", ""),+ "content": getattr(r, "content", "") or "",+ "metadata": _json_loads(getattr(r, "metadata_json", None), {}),+ "session_id": getattr(r, "session_id", ""),+ "turn_id": turn_id,+ "seq": int(getattr(r, "seq", 0)),+ "timestamp": _to_float(getattr(r, "event_timestamp", None)),+ }+ for r in records+ ]+ except Exception as exc:+ logger.warning(f"get_turn_events failed: {exc}")+ return []diff --cc deeptutor/services/session/turn_runtime.pyindex e28c4d99e,b0473f0f2..5491cb047--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@@ -14,10 -15,15 +15,15 @@@ from typing import TYPE_CHECKING, Any,from deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.path_service import get_path_service-from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store+from deeptutor.services.session.protocol import SessionStoreProtocol+ if TYPE_CHECKING:+ from deeptutor.services.llm.config import LLMConfig+logger = logging.getLogger(__name__)+ MemoryReference = Literal["summary", "profile"]+def _should_capture_assistant_content(event: StreamEvent) -> bool:if event.type != StreamEventType.CONTENT:diff --cc pyproject.tomlindex ee40f92af,607a89f23..0e8335a59--- a/pyproject.toml+++ b/pyproject.toml@@@ -45,22 -66,59 +66,62 @@@ server ="uvicorn[standard]>=0.24.0","websockets>=12.0","python-multipart>=0.0.6",- "python-jose[cryptography]>=3.3.0",+ "bcrypt>=4.0.0",++ "python-jose[cryptography]>=3.3.0",++ "pocketbase>=0.12.0",+ "loguru>=0.7.3,<1.0.0",+ "json-repair>=0.57.0,<1.0.0",+ ]++ # TutorBot agent engine + channel SDKs. Mirrors requirements/tutorbot.txt.+ tutorbot = [+ "deeptutor[server]",+ "croniter>=6.0.0,<7.0.0",+ "tiktoken>=0.12.0,<1.0.0",+ "chardet>=3.0.2,<6.0.0",+ "mcp>=1.26.0,<2.0.0",+ "readability-lxml>=0.8.4,<1.0.0",+ "python-telegram-bot[socks]>=22.6,<23.0",+ "lark-oapi>=1.5.0,<2.0.0",+ "dingtalk-stream>=0.24.0,<1.0.0",+ "slack-sdk>=3.39.0,<4.0.0",+ "slackify-markdown>=0.2.0,<1.0.0",+ "qq-botpy>=1.2.0,<2.0.0",+ "python-socketio>=5.16.0,<6.0.0",+ "msgpack>=1.1.0,<2.0.0",+ "python-socks[asyncio]>=2.8.0,<3.0.0",+ "socksio>=1.0.0,<2.0.0",+ "websocket-client>=1.9.0,<2.0.0",]++ # Matrix (Element) channel for TutorBot. Mirrors requirements/matrix.txt.+ # Kept as a separate extra because matrix-nio[e2e] requires libolm (native dep).+ matrix = [+ "matrix-nio[e2e]>=0.25.2,<1.0.0",+ "mistune>=3.0.0,<4.0.0",+ "nh3>=0.2.18,<1.0.0",+ ]++ # Math Animator addon (Manim). Mirrors requirements/math-animator.txt.+ # System prerequisites (installed outside pip): LaTeX, pkg-config, cairo, cmake, ffmpeg.math-animator = ["manim>=0.19.0"]++ # Dev/test tooling. Mirrors requirements/dev.txt.+ dev = [+ "deeptutor[server]",+ "pytest>=7.0.0",+ "pytest-asyncio>=0.23.0",+ "pre-commit>=3.0.0",+ "safety<3.0.0",+ "bandit>=1.8.0",+ ]++ # Everything: server + tutorbot + matrix + math-animator + dev tools.all = [- "anthropic>=0.30.0",- "dashscope>=1.14.0",- "perplexityai>=0.1.0",- "oauth-cli-kit>=0.2.0; python_version >= '3.11'",- "python-jose[cryptography]>=3.3.0",- "bcrypt>=4.0.0",- "fastapi>=0.100.0",- "uvicorn[standard]>=0.24.0",- "websockets>=12.0",- "python-multipart>=0.0.6",- "manim>=0.19.0",+ "deeptutor[tutorbot]",+ "deeptutor[matrix]",+ "deeptutor[math-animator]",+ "deeptutor[dev]",][tool.setuptools]diff --cc requirements/server.txtindex 9be59c5a2,49af1ad65..aeeeb46b7--- a/requirements/server.txt+++ b/requirements/server.txt@@@ -12,10 -15,6 +15,14 @@@ uvicorn[standard]>=0.24.websockets>=12.0python-multipart>=0.0.6+# --- Authentication ---+bcrypt>=4.0.0+python-jose[cryptography]>=3.3.0++# --- PocketBase (optional sidecar backend) ---+# Only used when POCKETBASE_URL is set in the environment.+pocketbase>=0.12.0+++ # --- LLM provider runtime (unconditionally imported by provider_core) ---+ loguru>=0.7.3,<1.0.0+ json-repair>=0.57.0,<1.0.0diff --cc web/.env.localindex 243c69999,a114876c2..3de3737c9--- a/web/.env.local+++ b/web/.env.local@@@ -1,3 -1,2 +1,3 @@@- # Auto-generated by start_web.py — do not edit manually+ # Auto-generated by start_web.py - do not edit manuallyNEXT_PUBLIC_API_BASE=http://localhost:8001+NEXT_PUBLIC_AUTH_ENABLED=falsediff --cc web/app/(utility)/settings/page.tsxindex 8703a5aec,18b4ba3d5..aca9c84a1--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@@ -658,8 -921,11 +935,11 @@@ function SettingsPageContent()}setLogs(`Preparing ${activeService} diagnostics...\n`);setTestRunning(activeService);+ if (activeService === "embedding") {+ setEmbeddingCapabilities(null);+ }try {- const response = await fetch(+ const response = await apiFetch(apiUrl(`/api/v1/settings/tests/${activeService}/start`),{method: "POST",diff --cc web/app/(workspace)/agents/page.tsxindex 8da93ff6b,28b098803..baae2d7d3--- a/web/app/(workspace)/agents/page.tsx+++ b/web/app/(workspace)/agents/page.tsx@@@ -21,7 -21,14 +21,14 @@@ importimport { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";import dynamic from "next/dynamic";-import { apiUrl } from "@/lib/api";+import { apiFetch, apiUrl } from "@/lib/api";+ import ModelSelector from "@/components/chat/home/ModelSelector";+ import {+ listLLMOptions,+ sameLLMSelection,+ type LLMOption,+ } from "@/lib/llm-options";+ import type { LLMSelection } from "@/lib/unified-ws";const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"),@@@ -911,7 -956,61 +957,61 @@@ function BotsTab(} finally {setCreating(false);}- }, [botId, formName, formDesc, formSoul, formModel, onReload, onToast, t]);+ }, [+ botId,+ formName,+ formDesc,+ formSoul,+ formLLMSelection,+ onReload,+ onToast,+ t,+ ]);++ const updateBotModel = useCallback(+ async (bid: string, selection: LLMSelection | null) => {+ setUpdatingModelBot(bid);+ try {- const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), {++ const res = await apiFetch(apiUrl(`/api/v1/tutorbot/${bid}`), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ llm_selection: selection,+ ...(selection ? {} : { model: "" }),+ }),+ });+ if (res.ok) {+ onToast(t("Model saved"));+ await onReload();+ } else {+ const err = (await res.json().catch(() => ({}))) as {+ detail?: string;+ };+ onToast(err.detail ?? t("Failed to save model"));+ }+ } catch {+ onToast(t("Failed to save model"));+ } finally {+ setUpdatingModelBot(null);+ }+ },+ [onReload, onToast, t],+ );++ const modelLabelFor = useCallback(+ (bot: BotInfo) => {+ const selected = bot.llm_selection+ ? llmOptions.find((option) =>+ sameLLMSelection(option, bot.llm_selection),+ )+ : null;+ if (selected) return selected.model_name || selected.model;+ if (bot.llm_selection) return t("Selected model");+ if (bot.model) return bot.model;+ return t("System default");+ },+ [llmOptions, t],+ );const startBot = useCallback(async (bid: string) => {@@@ -1313,124 -1435,132 +1436,130 @@@ function ProfilesTab([applySoulSelection, hasChanges],);- const saveFile = useCallback(async (- mode: "file_only" | "update_template" | "new_template",- createTemplateName?: string,- ) => {- if (!selectedBot) return false;- setSaving(true);- try {- if (activeFile === "SOUL.md") {- const content = editor.trim();- if (!content) {- onToast(t("SOUL.md is empty"));- return false;- }- if (mode === "update_template") {- if (!sourceSoulTemplate) {- onToast(t("No template selected to update"));+ const saveFile = useCallback(+ async (+ mode: "file_only" | "update_template" | "new_template",+ createTemplateName?: string,+ ) => {+ if (!selectedBot) return false;+ setSaving(true);+ try {+ if (activeFile === "SOUL.md") {+ const content = editor.trim();+ if (!content) {+ onToast(t("SOUL.md is empty"));return false;}- const tplRes = await apiFetch(- apiUrl(`/api/v1/tutorbot/souls/${sourceSoulTemplate.id}`),- {- method: "PUT",+ if (mode === "update_template") {+ if (!sourceSoulTemplate) {+ onToast(t("No template selected to update"));+ return false;+ }- const tplRes = await fetch(++ const tplRes = await apiFetch(+ apiUrl(`/api/v1/tutorbot/souls/${sourceSoulTemplate.id}`),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: sourceSoulTemplate.name,+ content: editor,+ }),+ },+ );+ if (!tplRes.ok) {+ onToast(t("Failed to update soul template"));+ return false;+ }+ await onReloadSouls();+ setSelectedSoulId(sourceSoulTemplate.id);+ setSourceSoulId(sourceSoulTemplate.id);+ } else if (mode === "new_template") {+ const rawName = (createTemplateName ?? "").trim();+ if (!rawName) {+ onToast(t("Template name is required"));+ return false;+ }+ const baseId = rawName+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");+ if (!baseId) {+ onToast(t("Please choose a name with letters or numbers"));+ return false;+ }+ const existing = new Set(souls.map((s) => s.id));+ let soulId = baseId;+ let n = 2;+ while (existing.has(soulId)) {+ soulId = `${baseId}-${n}`;+ n += 1;+ }- const tplRes = await fetch(apiUrl("/api/v1/tutorbot/souls"), {++ const tplRes = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {+ method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({- name: sourceSoulTemplate.name,+ id: soulId,+ name: rawName,content: editor,}),- },- );- if (!tplRes.ok) {- onToast(t("Failed to update soul template"));- return false;- }- await onReloadSouls();- setSelectedSoulId(sourceSoulTemplate.id);- setSourceSoulId(sourceSoulTemplate.id);- } else if (mode === "new_template") {- const rawName = (createTemplateName ?? "").trim();- if (!rawName) {- onToast(t("Template name is required"));- return false;- }- const baseId = rawName- .toLowerCase()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-|-$/g, "");- if (!baseId) {- onToast(t("Please choose a name with letters or numbers"));- return false;- }- const existing = new Set(souls.map((s) => s.id));- let soulId = baseId;- let n = 2;- while (existing.has(soulId)) {- soulId = `${baseId}-${n}`;- n += 1;- }- const tplRes = await apiFetch(apiUrl("/api/v1/tutorbot/souls"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- id: soulId,- name: rawName,- content: editor,- }),- });- if (tplRes.status === 409) {- onToast(t("A soul with this id already exists, try another name"));- return false;+ });+ if (tplRes.status === 409) {- onToast(- t("A soul with this id already exists, try another name"),- );++ onToast(t("A soul with this id already exists, try another name"));+ return false;+ }+ if (!tplRes.ok) {+ onToast(t("Failed to save soul template"));+ return false;+ }+ await onReloadSouls();+ setSelectedSoulId(soulId);+ setSourceSoulId(soulId);}- if (!tplRes.ok) {- onToast(t("Failed to save soul template"));- return false;- }- await onReloadSouls();- setSelectedSoulId(soulId);- setSourceSoulId(soulId);}- }- const res = await apiFetch(- apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`),- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: editor }),- },- );- if (res.ok) {- setFiles((prev) => ({ ...prev, [activeFile]: editor }));- if (activeFile === "SOUL.md") {- const personaRes = await apiFetch(apiUrl(`/api/v1/tutorbot/${selectedBot}`), {- method: "PATCH",- const res = await fetch(++ const res = await apiFetch(+ apiUrl(`/api/v1/tutorbot/${selectedBot}/files/${activeFile}`),+ {+ method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ persona: editor }),- });- if (!personaRes.ok) {- onToast(t("SOUL.md saved, but persona sync failed"));- return false;+ body: JSON.stringify({ content: editor }),+ },+ );+ if (res.ok) {+ setFiles((prev) => ({ ...prev, [activeFile]: editor }));+ if (activeFile === "SOUL.md") {- const personaRes = await fetch(++ const personaRes = await apiFetch(+ apiUrl(`/api/v1/tutorbot/${selectedBot}`),+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ persona: editor }),+ },+ );+ if (!personaRes.ok) {+ onToast(t("SOUL.md saved, but persona sync failed"));+ return false;+ }}+ onToast(`${activeFile} saved`);+ return true;}- onToast(`${activeFile} saved`);- return true;+ return false;+ } finally {+ setSaving(false);}- return false;- } finally {- setSaving(false);- }- }, [- selectedBot,- activeFile,- editor,- onToast,- onReloadSouls,- sourceSoulTemplate,- souls,- t,- ]);+ },+ [+ selectedBot,+ activeFile,+ editor,+ onToast,+ onReloadSouls,+ sourceSoulTemplate,+ souls,+ t,+ ],+ );const handleSaveClick = useCallback(() => {if (activeFile !== "SOUL.md") {diff --cc web/lib/llm-options.tsindex 000000000,d5f1c4dbf..e7de6cff7mode 000000,100644..100644--- a/web/lib/llm-options.ts+++ b/web/lib/llm-options.ts@@@ -1,0 -1,42 +1,42 @@@-import { apiUrl } from "@/lib/api";++import { apiFetch, apiUrl } from "@/lib/api";+ import type { LLMSelection } from "@/lib/unified-ws";++ export interface LLMOption extends LLMSelection {+ profile_name: string;+ model_name: string;+ model: string;+ provider: string;+ context_window?: number;+ is_active_default: boolean;+ }++ export interface LLMOptionsResponse {+ active: LLMSelection | null;+ options: LLMOption[];+ }++ export function llmSelectionKey(selection: LLMSelection | null | undefined) {+ if (!selection?.profile_id || !selection.model_id) return "";+ return `${selection.profile_id}:${selection.model_id}`;+ }++ export function sameLLMSelection(+ a: LLMSelection | null | undefined,+ b: LLMSelection | null | undefined,+ ) {+ return llmSelectionKey(a) === llmSelectionKey(b);+ }++ export async function listLLMOptions(): Promise<LLMOptionsResponse> {- const response = await fetch(apiUrl("/api/v1/settings/llm-options"), {++ const response = await apiFetch(apiUrl("/api/v1/settings/llm-options"), {+ cache: "no-store",+ });+ if (!response.ok) {+ throw new Error(`Failed to load LLM options: ${response.status}`);+ }+ const data = (await response.json()) as LLMOptionsResponse;+ return {+ active: data.active ?? null,+ options: Array.isArray(data.options) ? data.options : [],+ };+ }