DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge pull request #1112 from evan188199-tech/codex/feat-learner-account-presets
Bingxi Zhao (Frank)e06b366f697b
diff --cc deeptutor/api/routers/auth.pyindex 50295deae,38a2a96b4..eb9d85664--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@@ -348,6 -361,27 +361,33 @@@ async def require_adminreturn payload+ def _learning_surface_for_path(path: str) -> str:- if path.startswith("/api/v1/reading"):- return "reading"- if path.startswith(("/api/v1/chat", "/api/v1/question", "/api/v1/sessions")):- return "chat"++ normalized = "/" + str(path or "").lstrip("/")++ for root, surface in (++ ("/api/v1/reading", "reading"),++ ("/api/v1/chat", "chat"),++ ("/api/v1/question", "chat"),++ ("/api/v1/question-notebook", "chat"),++ ("/api/v1/sessions", "chat"),++ ):++ if normalized == root or normalized.startswith(f"{root}/"):++ return surface+ return ""+++ async def require_learning_surface(+ request: Request,+ _: TokenPayload | None = Depends(require_auth),+ ) -> None:+ """Second-stage default-deny guard for configured learning accounts."""+ from deeptutor.multi_user.learning_access import assert_learning_surface++ try:+ assert_learning_surface(_learning_surface_for_path(request.url.path))+ except PermissionError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc++def _local_admin_token_payload() -> TokenPayload:"""Synthetic admin payload used when AUTH_ENABLED=false.diff --cc deeptutor/api/routers/reading.pyindex 80d612414,0685f2649..d7199c385--- a/deeptutor/api/routers/reading.py+++ b/deeptutor/api/routers/reading.py@@@ -29,6 -29,10 +29,11 @@@ from fastapi.params import Filfrom fastapi.responses import FileResponse, Responsefrom pydantic import BaseModel, Field, model_validator+ from deeptutor.multi_user.learning_access import (+ assert_learning_material,++ assert_learning_material_mutation,+ current_learning_policy,+ )from deeptutor.reading import (ANNOTATION_COLORS,Annotation,@@@ -119,6 -125,29 +126,45 @@@ def _http_error(exc: Exception) -> HTTPreturn HTTPException(status_code=500, detail="The reader could not complete that request.")+ def _assigned_material_ids() -> set[str] | None:+ """Return the account allowlist, or ``None`` for unrestricted accounts."""+ policy = current_learning_policy()+ if policy is None:+ return None+ reading = policy.get("reading")+ if not isinstance(reading, dict):+ return {"*"}+ assigned = set(reading.get("material_ids") or [])+ return None if "*" in assigned else assigned+++ def _material_allowed(material_id: str) -> bool:+ assigned = _assigned_material_ids()+ return assigned is None or material_id in assigned+++ def _enforce_learning_materials(*material_ids: str) -> None:+ for material_id in material_ids:+ if material_id:+ assert_learning_material(material_id)++++def _workspace_payload(row: Any) -> dict[str, Any]:++ """Hide tabs that are no longer assigned to a learning account."""++ payload = row.to_dict()++ assigned = _assigned_material_ids()++ if assigned is None:++ return payload++ payload["tabs"] = [++ tab++ for tab in payload.get("tabs", [])++ if tab.get("material", {}).get("material_id") in assigned++ ]++ if payload.get("active_material_id") not in assigned:++ payload["active_material_id"] = None++ return payload++++# === Models ===================================================================@@@ -346,9 -376,9 +398,13 @@@ async def list_library_materialspayload["size_bytes"] = size_bytespayload["unit_count"] = unit_countmaterials.append(payload)-- # Counts describe the whole library, not the filtered page, so the-- # filter chips can show what they would reveal before being clicked.-- return {"materials": materials, "counts": catalog.library_counts()}++ # Counts describe every material this account may see, not only the++ # filtered page and never revoked or unassigned learner material.++ assigned = _assigned_material_ids()++ return {++ "materials": materials,++ "counts": catalog.library_counts(None if assigned is None else sorted(assigned)),++ }except Exception as exc:raise _http_error(exc) from exc@@@ -380,7 -410,7 +436,7 @@@ async def duplicate_check(payload: Duplif record is None and item.filename:record = catalog.find_ready_material_by_filename(item.filename, mime=item.mime)kind = "same_name"-- if record is None:++ if record is None or not _material_allowed(record.material_id):continuematches.append({@@@ -396,7 -426,7 +452,7 @@@except Exception: # noqa: BLE001 - a malformed URL is simply not a matchcontinuerecord = catalog.get_material(material_id)-- if record is None:++ if record is None or not _material_allowed(record.material_id):continuematches.append({@@@ -462,7 -497,7 +523,7 @@@ async def list_workspaces) -> dict[str, Any]:try:rows = _catalog().list_workspaces(search=search)-- return {"workspaces": [row.to_dict() for row in rows]}++ return {"workspaces": [_workspace_payload(row) for row in rows]}except Exception as exc:raise _http_error(exc) from exc@@@ -511,7 -547,7 +573,7 @@@ async def get_workspace(workspace_id: sif row is None:raise MaterialNotFound(f"reading workspace {workspace_id!r} not found")return {-- "workspace": row.to_dict(),++ "workspace": _workspace_payload(row),"sessions": [session.to_dict() for session in catalog.list_sessions(workspace_id)],}except Exception as exc:@@@ -944,6 -999,7 +1025,7 @@@ async def delete_material(material_id:record = catalog.get_material(material_id)removed_from = catalog.collections_for_material(material_id) if record else []try:- assert_learning_material(material_id)++ assert_learning_material_mutation(material_id)shared = record is not None and catalog.count_materials_for_content(record.content_id) > 1if shared and record is not None:# A sibling material still reads this content: drop this row anddiff --cc deeptutor/multi_user/grants.pyindex f859fee0e,ffa83893d..a384072f0--- a/deeptutor/multi_user/grants.py+++ b/deeptutor/multi_user/grants.py@@@ -53,6 -61,40 +61,42 @@@ def _normalize_tool_list(value: Any) -return [str(item).strip() for item in value if str(item).strip()]+ def _normalize_learning_policy(value: Any) -> dict[str, Any] | None:+ if value is None:+ return None+ if not isinstance(value, dict):+ return {}++ capabilities = _normalize_tool_list(value.get("allowed_capabilities")) or []+ has_reading = isinstance(value.get("reading"), dict)+ raw_reading = value.get("reading") if has_reading else {}+ material_ids = _normalize_tool_list(raw_reading.get("material_ids")) or (+ [] if has_reading else ["*"]+ )+ extensions = _normalize_tool_list(raw_reading.get("extensions")) or (- [] if has_reading else ["read_aloud", "guided_learn", "quiz"]++ []++ if has_reading++ else ["read_aloud", "guided_learning", "vocabulary", "quiz", "translation"]+ )+ # A policy without explicit surfaces/reading keeps the original learner+ # behavior while persisting the complete contract for API clients.+ surfaces = _normalize_tool_list(value.get("allowed_surfaces"))+ normalized = {+ "age_band": str(value.get("age_band") or "").strip(),+ "locked_persona": str(value.get("locked_persona") or "").strip(),+ "allowed_capabilities": capabilities,+ "default_capability": str(value.get("default_capability") or "chat").strip(),+ }+ if surfaces is not None:+ normalized["allowed_surfaces"] = surfaces+ normalized["reading"] = {+ "allow_upload": bool(raw_reading.get("allow_upload", True)),+ "material_ids": material_ids,+ "extensions": extensions,+ }+ return normalized++def grant_path(user_id: str) -> Path:ensure_system_dirs()return GRANTS_DIR / f"{user_id}.json"diff --cc deeptutor/multi_user/learning_access.pyindex 000000000,dacaae56f..2296d2a93mode 000000,100644..100644--- a/deeptutor/multi_user/learning_access.py+++ b/deeptutor/multi_user/learning_access.py@@@ -1,0 -1,105 +1,118 @@@+ """Learning-account policy resolution and turn enforcement."""++ from __future__ import annotations++ from copy import deepcopy+ from typing import Any++ from .context import get_current_user+ from .grants import load_grant+++ def learning_policy_for_user(user_id: str, *, is_admin: bool = False) -> dict[str, Any] | None:+ """Return the sanitized public policy for an account."""+ if is_admin:+ return None+ loaded = load_grant(user_id)+ policy = loaded.get("learning_policy")+ if policy is None:+ from .identity import get_user_by_id++ user = get_user_by_id(user_id)+ if user is not None and str(user[1].get("preset") or "standard") == "learner":+ from .grants import learner_grant++ policy = learner_grant(user_id).get("learning_policy")+ return deepcopy(policy) if isinstance(policy, dict) else None+++ def current_learning_policy() -> dict[str, Any] | None:+ user = get_current_user()+ return learning_policy_for_user(user.id, is_admin=user.is_admin)+++ def apply_learning_policy(payload: dict[str, Any]) -> dict[str, Any]:+ """Apply account policy before a turn is validated or persisted."""+ policy = current_learning_policy()+ if policy is None:+ return payload++ capability = str(payload.get("capability") or "chat")+ allowed = set(policy.get("allowed_capabilities") or [])+ if capability not in allowed:+ raise PermissionError(+ "This learning account cannot use this mode. Please choose an allowed learning mode."+ )+ return {+ **payload,+ "persona": str(policy.get("locked_persona") or ""),+ # Learners never inherit a broad tool surface from a stale session or a+ # crafted payload. Reading's context tools are mounted server-side from+ # the open material and remain available to the reading capability.+ "tools": [],+ "enabled_tools": [],+ "knowledge_bases": [],+ "kb_name": "",+ "enable_rag": False,+ "enable_web_search": False,+ "partner_id": None,+ "bot_id": None,+ }+++ def assert_learning_surface(surface: str) -> None:+ """Deny a server surface not explicitly exposed to a learning account."""+ policy = current_learning_policy()+ if policy is None:+ return+ if surface not in set(policy.get("allowed_surfaces") or ["chat", "reading"]):- raise PermissionError(f"This learning account cannot use the {surface} surface.")++ target = f"{surface} surface" if surface else "requested server surface"++ raise PermissionError(f"This learning account cannot use the {target}.")+++ def assert_learning_material(material_id: str, *, upload: bool = False) -> None:+ """Enforce upload and assigned-material policy in the authenticated scope."""+ policy = current_learning_policy()+ if policy is None:+ return+ has_reading = isinstance(policy.get("reading"), dict)+ reading = policy.get("reading") if has_reading else {}+ if upload:+ if has_reading and not bool(reading.get("allow_upload")):+ raise PermissionError("This learning account cannot upload reading materials.")+ return+ assigned = set(reading.get("material_ids") or (["*"] if not has_reading else []))+ if "*" not in assigned and str(material_id or "") not in assigned:+ raise PermissionError("This reading material is not assigned to this learning account.")++++def assert_learning_material_mutation(material_id: str) -> None:++ """Protect administrator-assigned material from learner-side deletion."""++ policy = current_learning_policy()++ if policy is None:++ return++ reading = policy.get("reading") if isinstance(policy.get("reading"), dict) else {}++ if not bool(reading.get("allow_upload")):++ raise PermissionError("This learning account cannot modify assigned reading materials.")++ assert_learning_material(material_id)+++++ def allowed_reading_extensions() -> set[str] | None:+ """None means unrestricted; a set is the learner extension allowlist."""+ policy = current_learning_policy()+ if policy is None:+ return None+ if not isinstance(policy.get("reading"), dict):- return {"read_aloud", "guided_learn", "quiz"}++ return {"read_aloud", "guided_learning", "vocabulary", "quiz", "translation"}+ return set(policy["reading"].get("extensions") or [])+++ __all__ = [+ "allowed_reading_extensions",+ "apply_learning_policy",+ "assert_learning_material",++ "assert_learning_material_mutation",+ "assert_learning_surface",+ "current_learning_policy",+ "learning_policy_for_user",+ ]diff --cc deeptutor/reading/catalog_store.pyindex 9c4ec8906,9c4ec8906..b247be414--- a/deeptutor/reading/catalog_store.py+++ b/deeptutor/reading/catalog_store.py@@@ -439,11 -439,11 +439,24 @@@ class ReadingCatalogStoreself._validate_id(material_id, "material")return self.collections_for_materials([material_id])[material_id]-- def library_counts(self) -> dict[str, object]:-- """Counts for the complete material library, independent of page filters."""++ def library_counts(++ self,++ material_ids: Sequence[str] | None = None,++ ) -> dict[str, object]:++ """Counts for the visible material library, independent of page filters."""++ params: list[str] = []++ where = ""++ if material_ids is not None:++ ids = tuple(dict.fromkeys(str(item) for item in material_ids if str(item)))++ if ids:++ placeholders = ",".join("?" for _ in ids)++ where = f"WHERE material_id IN ({placeholders})"++ params.extend(ids)++ else:++ where = "WHERE 0"with self._connect() as conn:row = conn.execute(-- """SELECT++ f"""SELECTCOUNT(*) AS all_count,COALESCE(SUM(NOT EXISTS (SELECT 1 FROM reading_workspace_materials wm@@@ -465,7 -465,7 +478,9 @@@WHEN render_mode NOT IN ('video', 'audio') AND source_kind = 'file'THEN 1 ELSE 0END), 0) AS document_count-- FROM reading_materials"""++ FROM reading_materials++ {where}""", # nosec B608 - only placeholder shape is interpolated++ params,).fetchone()assert row is not Nonereturn {diff --cc deeptutor/services/session/turn_runtime.pyindex b63a33f7f,1f7b4a30d..a3ea6b637--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@@ -1547,24 -1284,14 +1547,29 @@@ class TurnRuntimeManagerpreferences=preferences,)+ requested_capability = str(payload.get("capability") or "chat")+ capability_route = route_explicit_quiz_request(+ payload.get("content"),+ requested_capability,+ enabled=routing_enabled,+ )+ capability = (- capability_route.capability- if capability_route is not None- else requested_capability++ capability_route.capability if capability_route is not None else requested_capability+ )+ try:+ from deeptutor.multi_user.learning_access import apply_learning_policy+- payload = apply_learning_policy(payload)++ payload = apply_learning_policy({**payload, "capability": capability})+ except PermissionError as exc:+ raise RuntimeError(str(exc)) from exc+- capability = str(payload.get("capability") or "chat")+ workspace_mode_explicit = "workspace_mode" in payload+ workspace_mode = _workspace_mode(+ payload.get("workspace_mode")+ if workspace_mode_explicit+ else preferences.get("workspace_mode"),+ capability=capability,+ )try:from deeptutor.runtime.request_contracts import validate_capability_configdiff --cc tests/multi_user/test_account_presets.pyindex 000000000,c802d6882..e6bf95b9dmode 000000,100644..100644--- a/tests/multi_user/test_account_presets.py+++ b/tests/multi_user/test_account_presets.py@@@ -1,0 -1,230 +1,239 @@@+ """Account preset persistence, expansion, and admin HTTP behavior."""++ from __future__ import annotations++ from fastapi import FastAPI+ from fastapi.testclient import TestClient+ import pytest+++ @pytest.fixture+ def preset_client(mu_isolated_root, monkeypatch, as_user):+ import deeptutor.api.routers.auth as auth_router+ from deeptutor.api.routers.auth import require_admin+ from deeptutor.multi_user import router as multi_user_router+ from deeptutor.multi_user.identity import save_user+ from deeptutor.services.auth import TokenPayload++ admin = save_user("admin", "$2b$12$placeholder", role="admin")+ tokens = {"admin-token": TokenPayload(username="admin", role="admin", user_id=admin["id"])}+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", True)+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))++ app = FastAPI()+ app.include_router(auth_router.router, prefix="/api/v1/auth")+ app.include_router(multi_user_router.router, prefix="/api/v1/multi-user")+ app.dependency_overrides[require_admin] = lambda: tokens["admin-token"]+ return TestClient(app), admin, tokens+++ def test_legacy_and_new_standard_users_default_to_standard(seed_user):+ user = seed_user("legacy")+ assert user["preset"] == "standard"++++def test_learning_surface_routing_matches_complete_path_segments():++ from deeptutor.api.routers.auth import _learning_surface_for_path++++ assert _learning_surface_for_path("/api/v1/reading/materials") == "reading"++ assert _learning_surface_for_path("/api/v1/question-notebook/entries") == "chat"++ assert _learning_surface_for_path("/api/v1/reading-private") == ""++ assert _learning_surface_for_path("/api/v1/questions") == ""+++++ @pytest.mark.parametrize("preset", ["standard", "custom"])+ def test_non_learner_presets_do_not_install_a_learning_grant(preset_client, preset):+ client, _admin, _tokens = preset_client++ response = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": f"{preset}-user",+ "password": "reading-password-1",+ "preset": preset,+ },+ )++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["preset"] == preset+ from deeptutor.multi_user.grants import load_grant++ assert load_grant(body["user_id"])["learning_policy"] is None+++ def test_learner_preset_expands_to_a_conservative_grant(preset_client):+ from deeptutor.multi_user.grants import load_grant++ client, _admin, _tokens = preset_client++ response = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": "student",+ "password": "reading-password-1",+ "preset": "learner",+ },+ )++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["role"] == "user"+ assert body["preset"] == "learner"++ grant = load_grant(body["user_id"])+ assert grant["enabled_tools"] == []+ assert grant["mcp_tools"] == []+ assert grant["cli_apps"] == []+ assert grant["exec_enabled"] is False+ assert grant["learning_policy"] == {+ "age_band": "9-12",+ "locked_persona": "teacher",+ "allowed_capabilities": ["chat", "immersive_reading"],+ "default_capability": "immersive_reading",+ "allowed_surfaces": ["chat", "reading"],+ "reading": {+ "allow_upload": False,+ "material_ids": [],+ "extensions": [],+ },+ }+++ def test_learner_creation_rolls_back_when_grant_initialization_fails(preset_client, monkeypatch):+ from deeptutor.multi_user import grants+ from deeptutor.multi_user.identity import get_user++ client, _admin, _tokens = preset_client++ def fail_save_grant(*args, **kwargs):+ raise RuntimeError("grant store unavailable")++ monkeypatch.setattr(grants, "save_grant", fail_save_grant)+ response = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": "student",+ "password": "reading-password-1",+ "preset": "learner",+ },+ )++ assert response.status_code == 500+ assert response.json()["detail"] == "The learner preset could not be initialized."+ assert get_user("student") is None+++ def test_learner_accounts_cannot_disable_the_learning_policy(preset_client):+ client, _admin, _tokens = preset_client+ created = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": "student",+ "password": "reading-password-1",+ "preset": "learner",+ },+ ).json()++ response = client.put(+ f"/api/v1/multi-user/users/{created['user_id']}/grants",+ headers={"Authorization": "Bearer admin-token"},+ json={"grant": {"learning_policy": None}},+ )++ assert response.status_code == 400+ assert response.json()["detail"] == "Learner accounts must retain a learning policy."+++ @pytest.mark.parametrize("preset", ["learner", "custom"])+ def test_pocketbase_rejects_presets_it_cannot_enforce(preset_client, monkeypatch, preset):+ import deeptutor.api.routers.auth as auth_router++ client, _admin, _tokens = preset_client+ monkeypatch.setattr(auth_router, "POCKETBASE_ENABLED", True)+ response = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": "remote-student",+ "password": "reading-password-1",+ "preset": preset,+ },+ )++ assert response.status_code == 400+ assert "standard preset" in response.json()["detail"]+++ def test_auth_status_returns_the_effective_learning_policy(preset_client):+ client, _admin, tokens = preset_client+ created = client.post(+ "/api/v1/auth/users",+ headers={"Authorization": "Bearer admin-token"},+ json={+ "username": "student",+ "password": "reading-password-1",+ "preset": "learner",+ },+ ).json()+ from deeptutor.services.auth import TokenPayload++ tokens["learner-token"] = TokenPayload(+ username="student", role="user", user_id=created["user_id"]+ )+ response = client.get(+ "/api/v1/auth/status",+ headers={"Authorization": "Bearer learner-token"},+ )++ assert response.status_code == 200+ assert response.json()["learning_policy"]["default_capability"] == ("immersive_reading")+++ def test_assigning_a_material_copies_the_admin_material_once(+ preset_client, as_user, seed_user, tmp_path+ ):+ from deeptutor.multi_user.paths import get_path_service_for_scope, scope_for_user+ from deeptutor.reading import ReadingStore++ client, admin, _tokens = preset_client+ learner = seed_user("student")+ source = tmp_path / "lesson.txt"+ source.write_text("Assigned reading passage.", encoding="utf-8")+ with as_user(admin["id"], role="admin", username="admin"):+ material = ReadingStore().ingest(source)++ grant = {+ "enabled_tools": [],+ "mcp_tools": [],+ "cli_apps": [],+ "exec_enabled": False,+ "learning_policy": {+ "age_band": "9-12",+ "locked_persona": "teacher",+ "allowed_capabilities": ["chat", "immersive_reading"],+ "default_capability": "immersive_reading",+ "allowed_surfaces": ["chat", "reading"],+ "reading": {+ "allow_upload": False,+ "material_ids": [material.material_id],+ "extensions": [],+ },+ },+ }+ response = client.put(+ f"/api/v1/multi-user/users/{learner['id']}/grants",+ headers={"Authorization": "Bearer admin-token"},+ json={"grant": grant},+ )++ assert response.status_code == 200, response.text+ user_root = get_path_service_for_scope(+ scope_for_user(learner["id"], is_admin=False)+ ).get_workspace_feature_dir("reading")+ staged = user_root / material.material_id+ assert staged.is_dir()diff --cc tests/multi_user/test_learning_policy.pyindex 000000000,31c858ed4..0aa5ae61dmode 000000,100644..100644--- a/tests/multi_user/test_learning_policy.py+++ b/tests/multi_user/test_learning_policy.py@@@ -1,0 -1,166 +1,178 @@@+ """Server-side policy resolution for learning accounts."""++ from __future__ import annotations++ import pytest++ from deeptutor.multi_user.grants import normalize_grant, save_grant, validate_grant+ from deeptutor.multi_user.identity import set_preset+ from deeptutor.multi_user.learning_access import (+ allowed_reading_extensions,+ apply_learning_policy,+ assert_learning_material,+ assert_learning_surface,+ learning_policy_for_user,+ )+++ def _policy_grant(material_ids: list[str] | None = None, extensions: list[str] | None = None):+ return {+ "enabled_tools": [],+ "mcp_tools": [],+ "cli_apps": [],+ "exec_enabled": False,+ "learning_policy": {+ "age_band": "9-12",+ "locked_persona": "teacher",+ "allowed_capabilities": ["chat", "immersive_reading"],+ "default_capability": "immersive_reading",+ "allowed_surfaces": ["chat", "reading"],+ "reading": {+ "allow_upload": False,+ "material_ids": material_ids or [],+ "extensions": extensions or [],+ },+ },+ }+++ def _seed_learner(seed_user, name: str):+ seed_user("admin", role="admin")+ return seed_user(name)+++ def test_legacy_grants_remain_unrestricted(mu_isolated_root):+ grant = normalize_grant("u_legacy", {"version": 1})+ assert grant["learning_policy"] is None+ validate_grant(grant)+++ def test_learning_policy_validation_rejects_unsafe_values(mu_isolated_root):+ grant = normalize_grant(+ "u_student",+ _policy_grant(extensions=["not valid"]),+ )+ grant["learning_policy"]["allowed_capabilities"] = ["deep_research"]++ with pytest.raises(ValueError, match="unsupported values"):+ validate_grant(grant)+++ def test_apply_policy_keeps_allowed_modes_and_strips_the_turn_surface(+ mu_isolated_root, seed_user, as_user+ ):+ learner = _seed_learner(seed_user, "student")+ save_grant(learner["id"], _policy_grant())++ with as_user(learner["id"], username="student"):+ result = apply_learning_policy(+ {+ "capability": "immersive_reading",+ "persona": "friend",+ "tools": [{"name": "web_search"}],+ "enabled_tools": ["web_search"],+ "knowledge_bases": ["admin:kb:private"],+ "kb_name": "private",+ "enable_rag": True,+ "enable_web_search": True,+ "partner_id": "partner",+ "bot_id": "bot",+ }+ )++ assert result["persona"] == "teacher"+ assert result["tools"] == []+ assert result["enabled_tools"] == []+ assert result["knowledge_bases"] == []+ assert result["kb_name"] == ""+ assert result["enable_rag"] is False+ assert result["enable_web_search"] is False+ assert result["partner_id"] is None+ assert result["bot_id"] is None+++ def test_apply_policy_rejects_unallowed_capabilities(mu_isolated_root, seed_user, as_user):+ learner = _seed_learner(seed_user, "student")+ save_grant(learner["id"], _policy_grant())++ with as_user(learner["id"], username="student"):+ with pytest.raises(PermissionError, match="cannot use this mode"):+ apply_learning_policy({"capability": "deep_research"})+++ def test_surface_material_upload_and_extension_guards(mu_isolated_root, seed_user, as_user):+ learner = _seed_learner(seed_user, "student")+ grant = save_grant(+ learner["id"],+ _policy_grant(+ material_ids=["rm_allowed"],+ extensions=["read_aloud"],+ ),+ )++ with as_user(learner["id"], username="student"):+ assert_learning_surface("chat")+ assert_learning_surface("reading")+ with pytest.raises(PermissionError, match="knowledge surface"):+ assert_learning_surface("knowledge")++ assert_learning_material("rm_allowed")+ with pytest.raises(PermissionError, match="not assigned"):+ assert_learning_material("rm_private")+ with pytest.raises(PermissionError, match="cannot upload"):+ assert_learning_material("", upload=True)++ assert allowed_reading_extensions() == {"read_aloud"}+++ def test_policy_without_explicit_reading_keeps_legacy_access(mu_isolated_root, seed_user, as_user):+ learner = _seed_learner(seed_user, "legacy-learner")+ grant = save_grant(+ learner["id"],+ {+ "learning_policy": {+ "age_band": "9-12",+ "locked_persona": "teacher",+ "allowed_capabilities": ["chat", "immersive_reading"],+ "default_capability": "immersive_reading",+ }+ },+ )++ assert grant["learning_policy"]["reading"] == {+ "allow_upload": True,+ "material_ids": ["*"],- "extensions": ["read_aloud", "guided_learn", "quiz"],++ "extensions": [++ "read_aloud",++ "guided_learning",++ "vocabulary",++ "quiz",++ "translation",++ ],+ }+ with as_user(learner["id"], username="legacy-learner"):+ assert_learning_material("rm_anything")+ assert_learning_material("", upload=True)+ assert_learning_surface("reading")- assert allowed_reading_extensions() == {"read_aloud", "guided_learn", "quiz"}++ assert allowed_reading_extensions() == {++ "read_aloud",++ "guided_learning",++ "vocabulary",++ "quiz",++ "translation",++ }+++ def test_learner_preset_falls_back_to_the_conservative_policy(mu_isolated_root, seed_user):+ learner = _seed_learner(seed_user, "student")+ assert set_preset("student", "learner")++ policy = learning_policy_for_user(learner["id"], is_admin=False)++ assert policy is not None+ assert policy["default_capability"] == "immersive_reading"+ assert policy["reading"] == {+ "allow_upload": False,+ "material_ids": [],+ "extensions": [],+ }diff --cc tests/multi_user/test_learning_policy_http.pyindex 000000000,2fd66396d..4d8e21bc4mode 000000,100644..100644--- a/tests/multi_user/test_learning_policy_http.py+++ b/tests/multi_user/test_learning_policy_http.py@@@ -1,0 -1,149 +1,180 @@@+ """HTTP enforcement of learning-policy Reading boundaries."""++ from __future__ import annotations++ from pathlib import Path+ from types import SimpleNamespace++ from fastapi import Depends, FastAPI+ from fastapi.testclient import TestClient+ import pytest++ from deeptutor.api.routers import reading, reading_extensions+ from deeptutor.multi_user.context import reset_current_user, set_current_user+ from deeptutor.reading import ReadingStore+ from deeptutor.reading.extensions import (+ ReadingAction,+ ReadingExtensionManifest,+ ReadingExtensionRegistry,+ ReadingExtensionResult,+ )+++ def _extension(extension_id: str):+ return SimpleNamespace(+ manifest=ReadingExtensionManifest(+ id=extension_id,+ version="1.0.0",+ name=extension_id.title(),+ actions=[ReadingAction(id="open", label="Open")],+ result_types=["card"],+ ),+ run_action=lambda _action, _context: ReadingExtensionResult(type="card"),+ )+++ @pytest.fixture+ def learner_client(mu_isolated_root, seed_user, make_user, monkeypatch, tmp_path):+ learner = _seed_learner(seed_user)+ current_user = make_user(learner["id"], username="student")++ async def install_user():+ token = set_current_user(current_user)+ try:+ yield current_user+ finally:+ reset_current_user(token)++ registry = ReadingExtensionRegistry([_extension("read_aloud"), _extension("quiz")])+ monkeypatch.setattr(+ reading_extensions,+ "get_reading_extension_registry",+ lambda: registry,+ )++ app = FastAPI()+ dependencies = [Depends(install_user)]+ app.include_router(+ reading.router,+ prefix="/api/v1/reading",+ dependencies=dependencies,+ )+ app.include_router(+ reading_extensions.router,+ prefix="/api/v1/reading",+ dependencies=dependencies,+ )+ return TestClient(app), learner, current_user, tmp_path+++ def _seed_material(root: Path, name: str, text: str):+ source = root / name+ source.write_text(text, encoding="utf-8")+ return ReadingStore().ingest(source)+++ def _save_learner_grant(user_id: str, material_id: str):+ from deeptutor.multi_user.grants import save_grant++ save_grant(+ user_id,+ {+ "enabled_tools": [],+ "mcp_tools": [],+ "cli_apps": [],+ "exec_enabled": False,+ "learning_policy": {+ "age_band": "9-12",+ "locked_persona": "teacher",+ "allowed_capabilities": ["chat", "immersive_reading"],+ "default_capability": "immersive_reading",+ "allowed_surfaces": ["chat", "reading"],+ "reading": {+ "allow_upload": False,+ "material_ids": [material_id],+ "extensions": ["read_aloud"],+ },+ },+ },+ )+++ def _seed_learner(seed_user):+ seed_user("admin", role="admin")+ return seed_user("student")+++ def test_reading_upload_material_and_listing_follow_the_policy(learner_client, as_user):+ client, learner, current_user, tmp_path = learner_client+ with as_user(current_user.id, username="student"):++ from deeptutor.reading.catalog_store import ReadingCatalogStore+++ allowed = _seed_material(tmp_path, "allowed.txt", "Allowed passage.")+ private = _seed_material(tmp_path, "private.txt", "Private passage.")++ catalog = ReadingCatalogStore()++ catalog.register_manifest(allowed)++ catalog.register_manifest(private)++ workspace = catalog.create_workspace(++ "Mixed collection",++ [allowed.material_id, private.material_id],++ )+ _save_learner_grant(learner["id"], allowed.material_id)++ denied_upload = client.post(+ "/api/v1/reading/materials",+ files={"file": ("new.txt", b"new material", "text/plain")},+ )+ assert denied_upload.status_code == 403+ assert "cannot upload" in denied_upload.json()["detail"]++ rows = client.get("/api/v1/reading/materials").json()+ assert [row["material_id"] for row in rows] == [allowed.material_id]+ assert client.get(f"/api/v1/reading/materials/{allowed.material_id}").status_code == 200+ denied_material = client.get(f"/api/v1/reading/materials/{private.material_id}")+ assert denied_material.status_code == 403+ assert "not assigned" in denied_material.json()["detail"]+++ library = client.get("/api/v1/reading/library/materials").json()++ assert [row["material_id"] for row in library["materials"]] == [allowed.material_id]++ assert library["counts"]["all"] == 1++++ duplicate = client.post(++ "/api/v1/reading/library/duplicate-check",++ json={"files": [{"filename": "private.txt"}]},++ ).json()++ assert duplicate["matches"] == []++++ visible_workspace = client.get(f"/api/v1/reading/workspaces/{workspace.workspace_id}").json()[++ "workspace"++ ]++ assert [tab["material"]["material_id"] for tab in visible_workspace["tabs"]] == [++ allowed.material_id++ ]++++ denied_delete = client.delete(f"/api/v1/reading/materials/{allowed.material_id}")++ assert denied_delete.status_code == 403++ assert "cannot modify" in denied_delete.json()["detail"]++ assert client.get(f"/api/v1/reading/materials/{allowed.material_id}").status_code == 200++++ def test_reading_extensions_and_actions_follow_the_policy(learner_client, as_user):+ client, learner, current_user, tmp_path = learner_client+ with as_user(current_user.id, username="student"):+ material = _seed_material(tmp_path, "allowed.txt", "Allowed passage.")+ _save_learner_grant(learner["id"], material.material_id)++ rows = client.get("/api/v1/reading/extensions").json()+ assert [row["id"] for row in rows] == ["read_aloud"]++ allowed = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/read_aloud/actions/open",+ json={"locator": 1},+ )+ assert allowed.status_code == 200, allowed.text++ denied = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/quiz/actions/open",+ json={"locator": 1},+ )+ assert denied.status_code == 403+ assert "not allowed" in denied.json()["detail"]diff --cc web/locales/en/app.jsonindex 4a9ff9f0a,ddeb95294..71b5b1880--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -4277,77 -4120,21 +4277,94 @@@"Move out of More": "Move out of More","Reset sidebar order": "Reset sidebar order","Reset chat order": "Reset chat order",+ "Delete provider": "Delete provider",+ "Delete this provider?": "Delete this provider?",+ "This is your active {{service}} provider — deleting it switches to {{next}}.": "This is your active {{service}} provider — deleting it switches to {{next}}.",+ "This removes {{count}} model(s) and its saved credentials. This can't be undone.": "This removes {{count}} model(s) and its saved credentials. This can't be undone.",+ "nothing configured": "nothing configured",+ "Immersive Watching": "Immersive Watching",+ "Native YouTube learning": "Native YouTube learning",+ "Refresh provider": "Refresh provider",+ "Close video learning": "Close video learning",+ "Open a YouTube learning video": "Open a YouTube learning video",+ "Paste a watch, Shorts, Live, Embed, or youtu.be link.": "Paste a watch, Shorts, Live, Embed, or youtu.be link.",+ "YouTube URL": "https://youtu.be/…",+ "Use native YouTube for this video": "Use native YouTube for this video",+ "Use native YouTube": "Use native YouTube",+ "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.": "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.",+ "no captions": "no captions",+ "Retry captions": "Retry captions",+ "Explain here": "Explain here",+ "YouTube playback failed.": "YouTube playback failed.",+ "YouTube learning video": "YouTube learning video",+ "The configured Invidious stream could not be played.": "The configured Invidious stream could not be played.",+ "Settings could not be loaded.": "Settings could not be loaded.",+ "Saved. New and reopened videos use this provider immediately.": "Saved. New and reopened videos use this provider immediately.",+ "Settings could not be saved.": "Settings could not be saved.",+ "Testing Invidious…": "Testing Invidious…",+ "Invidious connected ({{message}}).": "Invidious connected ({{message}}).",+ "Invidious unavailable: {{message}}": "Invidious unavailable: {{message}}",+ "Video Learning": "Video Learning",+ "Choose native YouTube or a self-hosted Invidious instance. Provider changes do not rebuild learning materials or reset progress.": "Choose native YouTube or a self-hosted Invidious instance. Provider changes do not rebuild learning materials or reset progress.",+ "Official privacy-enhanced IFrame Player. No media is proxied or stored.": "Official privacy-enhanced IFrame Player. No media is proxied or stored.",+ "HTML5 playback through your configured Invidious instance.": "HTML5 playback through your configured Invidious instance.",+ "Native YouTube": "Native YouTube",+ "Self-hosted Invidious": "Self-hosted Invidious",+ "Invidious connection": "Invidious connection",+ "Backend API origin": "Backend API origin",+ "Invidious API URL": "http://127.0.0.1:3000",+ "Browser-facing origin (optional)": "Browser-facing origin (optional)",+ "Defaults to the API origin": "Defaults to the API origin",+ "YouTube transcript adapter": "YouTube transcript adapter",+ "Optional captions; playback remains available when the package or captions are unavailable.": "Optional captions; playback remains available when the package or captions are unavailable.",+ "youtube-transcript-api": "youtube-transcript-api",+ "The player provider is unavailable.": "The player provider is unavailable.",+ "This video could not be opened.": "This video could not be opened.",+ "Explain this part of the video": "Explain this part of the video",+ "YouTube Player API did not initialize.": "YouTube Player API did not initialize.",+ "YouTube Player API timed out.": "YouTube Player API timed out.",+ "YouTube Player API could not be loaded.": "YouTube Player API could not be loaded.",+ "Vector index": "Vector index",+ "Applies on the next full re-index": "Applies on the next full re-index",+ "Exact nearest-neighbor search. Best for small and medium knowledge bases.": "Exact nearest-neighbor search. Best for small and medium knowledge bases.",+ "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.": "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.",+ "HNSW graph degree": "HNSW graph degree",+ "HNSW construction candidates": "HNSW construction candidates",+ "HNSW search candidates": "HNSW search candidates",+ "Reranking": "Reranking",+ "Applies on the next query": "Applies on the next query",+ "Reranker model": "Reranker model",+ "Leave empty to disable. Example: BAAI/bge-reranker-base. Requires the optional rag-rerank extra.": "Leave empty to disable. Example: BAAI/bge-reranker-base. Requires the optional rag-rerank extra.",+ "Rerank candidates": "Rerank candidates",+ "Needs Review": "Needs Review",+ "All Sources": "All Sources",+ "Deep Question": "Deep Question",+ "Book": "Book",+ "All Materials": "All Materials",+ "Score Trend": "Score Trend",+ "All Trends": "All Trends",+ "First Attempt": "First Attempt",+ "Improved": "Improved",+ "Declined": "Declined",+ "Unchanged": "Unchanged",+ "Resolved": "Resolved",+ "Mark Resolved": "Mark Resolved",- "Reopen Review": "Reopen Review"++ "Reopen Review": "Reopen Review",+ "Account preset": "Account preset",+ "Learner": "Learner",+ "Preset: {{preset}}": "Preset: {{preset}}",+ "Chat and Immersive Reading only, with uploads and tools disabled until assigned.": "Chat and Immersive Reading only, with uploads and tools disabled until assigned.",+ "Create an ordinary account, then customize its assignments.": "Create an ordinary account, then customize its assignments.",+ "Create an ordinary account with the default workspace behavior.": "Create an ordinary account with the default workspace behavior.",+ "Learning policy": "Learning policy",+ "Enable learning policy": "Enable learning policy",+ "Teacher persona; Chat and Immersive Reading only": "Teacher persona; Chat and Immersive Reading only",+ "Age band": "Age band",+ "Teacher": "Teacher",+ "Modes": "Modes",+ "Chat · Immersive Reading": "Chat · Immersive Reading",+ "Assigned reading materials": "Assigned reading materials",+ "Upload books in Reading before assigning them.": "Upload books in Reading before assigning them.",+ "Allow learner uploads": "Allow learner uploads",+ "Reading extensions": "Reading extensions"}diff --cc web/locales/zh/app.jsonindex 779b35ec2,062a21ab5..7e92bac95--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -4277,77 -4120,21 +4277,94 @@@"Move out of More": "移出「更多」","Reset sidebar order": "恢复默认排列","Reset chat order": "恢复默认顺序",+ "Delete provider": "删除供应商",+ "Delete this provider?": "删除这个供应商?",+ "This is your active {{service}} provider — deleting it switches to {{next}}.": "这是当前使用中的 {{service}} 供应商,删除后会切换到 {{next}}。",+ "This removes {{count}} model(s) and its saved credentials. This can't be undone.": "这会删除 {{count}} 个模型及已保存的密钥,且不可撤销。",+ "nothing configured": "未配置",+ "Immersive Watching": "沉浸式观看",+ "Native YouTube learning": "原生 YouTube 学习",+ "Refresh provider": "刷新播放提供方",+ "Close video learning": "关闭视频学习",+ "Open a YouTube learning video": "打开 YouTube 学习视频",+ "Paste a watch, Shorts, Live, Embed, or youtu.be link.": "粘贴 watch、Shorts、Live、Embed 或 youtu.be 链接。",+ "YouTube URL": "https://youtu.be/…",+ "Use native YouTube for this video": "本次使用原生 YouTube",+ "Use native YouTube": "使用原生 YouTube",+ "Transcript learning is unavailable ({{reason}}). Playback still works, but Explain here is disabled.": "字幕学习不可用({{reason}})。视频仍可播放,但“解释此处”已禁用。",+ "no captions": "没有字幕",+ "Retry captions": "重试字幕",+ "Explain here": "解释此处",+ "YouTube playback failed.": "YouTube 播放失败。",+ "YouTube learning video": "YouTube 学习视频",+ "The configured Invidious stream could not be played.": "无法播放已配置的 Invidious 视频流。",+ "Settings could not be loaded.": "无法加载设置。",+ "Saved. New and reopened videos use this provider immediately.": "已保存。新打开或重新打开的视频会立即使用该提供方。",+ "Settings could not be saved.": "无法保存设置。",+ "Testing Invidious…": "正在测试 Invidious…",+ "Invidious connected ({{message}}).": "Invidious 已连接({{message}})。",+ "Invidious unavailable: {{message}}": "Invidious 不可用:{{message}}",+ "Video Learning": "视频学习",+ "Choose native YouTube or a self-hosted Invidious instance. Provider changes do not rebuild learning materials or reset progress.": "选择原生 YouTube 或自托管 Invidious。切换提供方不会重建学习材料或重置进度。",+ "Official privacy-enhanced IFrame Player. No media is proxied or stored.": "官方隐私增强型 IFrame Player;不代理或存储媒体。",+ "HTML5 playback through your configured Invidious instance.": "通过已配置的 Invidious 实例进行 HTML5 播放。",+ "Native YouTube": "原生 YouTube",+ "Self-hosted Invidious": "自托管 Invidious",+ "Invidious connection": "Invidious 连接",+ "Backend API origin": "后端 API 地址",+ "Invidious API URL": "http://127.0.0.1:3000",+ "Browser-facing origin (optional)": "浏览器访问地址(可选)",+ "Defaults to the API origin": "默认使用 API 地址",+ "YouTube transcript adapter": "YouTube 字幕适配器",+ "Optional captions; playback remains available when the package or captions are unavailable.": "字幕为可选能力;依赖包或字幕不可用时仍可播放视频。",+ "youtube-transcript-api": "youtube-transcript-api",+ "The player provider is unavailable.": "播放提供方不可用。",+ "This video could not be opened.": "无法打开此视频。",+ "Explain this part of the video": "解释视频的这一部分",+ "YouTube Player API did not initialize.": "YouTube Player API 未能初始化。",+ "YouTube Player API timed out.": "YouTube Player API 加载超时。",+ "YouTube Player API could not be loaded.": "无法加载 YouTube Player API。",+ "Vector index": "向量索引",+ "Applies on the next full re-index": "在下次完整重建索引时生效",+ "Exact nearest-neighbor search. Best for small and medium knowledge bases.": "精确最近邻搜索,适合中小型知识库。",+ "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.": "面向大型知识库的近似图搜索,规模更大时更快,但会有少量召回损失。",+ "HNSW graph degree": "HNSW 图连接度",+ "HNSW construction candidates": "HNSW 构建候选数",+ "HNSW search candidates": "HNSW 搜索候选数",+ "Reranking": "重排序",+ "Applies on the next query": "在下次查询时生效",+ "Reranker model": "重排序模型",+ "Leave empty to disable. Example: BAAI/bge-reranker-base. Requires the optional rag-rerank extra.": "留空表示禁用。示例:BAAI/bge-reranker-base。需要可选的 rag-rerank 依赖。",+ "Rerank candidates": "重排序候选数",+ "Needs Review": "待复习",+ "All Sources": "全部来源",+ "Deep Question": "深度提问",+ "Book": "书籍",+ "All Materials": "全部材料",+ "Score Trend": "得分趋势",+ "All Trends": "全部趋势",+ "First Attempt": "首次作答",+ "Improved": "已提升",+ "Declined": "已下降",+ "Unchanged": "无变化",+ "Resolved": "已解决",+ "Mark Resolved": "标记已解决",- "Reopen Review": "重新复习"++ "Reopen Review": "重新复习",+ "Account preset": "账户预设",+ "Learner": "学习者",+ "Preset: {{preset}}": "预设:{{preset}}",+ "Chat and Immersive Reading only, with uploads and tools disabled until assigned.": "仅可用 Chat 和沉浸阅读;上传与工具在分配前保持关闭。",+ "Create an ordinary account, then customize its assignments.": "创建普通账户,之后自定义可用资源。",+ "Create an ordinary account with the default workspace behavior.": "创建使用默认工作区行为的普通账户。",+ "Learning policy": "学习策略",+ "Enable learning policy": "启用学习策略",+ "Teacher persona; Chat and Immersive Reading only": "教师人格;仅可用 Chat 和沉浸阅读",+ "Age band": "年龄段",+ "Teacher": "教师",+ "Modes": "模式",+ "Chat · Immersive Reading": "Chat · 沉浸阅读",+ "Assigned reading materials": "已分配阅读材料",+ "Upload books in Reading before assigning them.": "请先在阅读区上传书籍,再分配给学习者。",+ "Allow learner uploads": "允许学习者上传",+ "Reading extensions": "阅读扩展"}