Merge pull request #1112 from evan188199-tech/codex/feat-learner-account-presets

# Conflicts:
#	deeptutor/services/session/turn_runtime.py
#	web/locales/en/app.json
#	web/locales/zh/app.json
This commit is contained in:
Bingxi Zhao (Frank)
2026-08-31 20:21:34 +08:00
23 changed files with 1629 additions and 40 deletions
+5 -2
View File
@@ -406,9 +406,12 @@ app.include_router(outputs.router, prefix="/api/outputs", tags=["outputs"])
# All other routers require a valid session when AUTH_ENABLED=true.
# require_auth is a no-op when AUTH_ENABLED=false, so this is safe for local use.
from deeptutor.api.routers.auth import require_admin, require_auth # noqa: E402
from deeptutor.api.routers.auth import ( # noqa: E402
require_admin,
require_learning_surface,
)
_auth = [Depends(require_auth)]
_auth = [Depends(require_learning_surface)]
# Partner data is anchored at the admin workspace (data/partners) and shared
# process-wide, so management is admin-gated in multi-user deployments
# (single-user local runs are implicitly admin — no behaviour change there).
+81 -3
View File
@@ -30,6 +30,8 @@ _SECURE = bool(load_auth_settings()["cookie_secure"])
_SAMESITE = "none" if _SECURE else "lax"
from deeptutor.multi_user.context import set_current_user, user_from_token_payload
from deeptutor.multi_user.learning_access import learning_policy_for_user
from deeptutor.multi_user.models import AccountPreset
from deeptutor.multi_user.paths import local_admin_user
from deeptutor.services.auth import (
AUTH_ENABLED,
@@ -133,6 +135,15 @@ class SetRoleRequest(BaseModel):
return v
class AdminCreateUserRequest(RegisterRequest):
"""Admin user-creation payload.
A preset configures an ordinary account; it never becomes a third role.
"""
preset: AccountPreset = "standard"
class AuthStatusResponse(BaseModel):
"""Response body for the GET /status endpoint."""
@@ -143,6 +154,7 @@ class AuthStatusResponse(BaseModel):
role: str | None = None
is_admin: bool = False
avatar: str = ""
learning_policy: dict | None = None
class UserInfo(BaseModel):
@@ -154,6 +166,7 @@ class UserInfo(BaseModel):
created_at: str
disabled: bool = False
avatar: str = ""
preset: AccountPreset = "standard"
# Markers settable through PUT /profile. Image markers ("img:<version>") are
@@ -348,6 +361,33 @@ async def require_admin(
return payload
def _learning_surface_for_path(path: str) -> str:
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.
@@ -418,10 +458,15 @@ async def auth_status(
token = _extract_token(authorization, dt_token)
payload = decode_token(token) if token else None
avatar = ""
learning_policy = None
if payload is not None:
info = get_user_info(payload.username)
if info:
avatar = str(info.get("avatar") or "")
learning_policy = learning_policy_for_user(
payload.user_id,
is_admin=payload.role == "admin",
)
return AuthStatusResponse(
enabled=True,
authenticated=payload is not None,
@@ -430,6 +475,7 @@ async def auth_status(
role=payload.role if payload else None,
is_admin=payload.role == "admin" if payload else False,
avatar=avatar,
learning_policy=learning_policy,
)
@@ -757,7 +803,7 @@ async def get_users(_: TokenPayload = Depends(require_admin)) -> list[UserInfo]:
@router.post("/users", status_code=status.HTTP_201_CREATED)
async def admin_create_user(
body: RegisterRequest,
body: AdminCreateUserRequest,
current: TokenPayload = Depends(require_admin),
) -> dict:
"""Admin-only: create a new user account.
@@ -773,6 +819,11 @@ async def admin_create_user(
)
if POCKETBASE_ENABLED:
if body.preset != "standard":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Only the standard preset is available in PocketBase mode.",
)
result = register_pb(username=body.username, email=body.username, password=body.password)
if not result:
raise HTTPException(
@@ -789,6 +840,7 @@ async def admin_create_user(
"username": body.username,
"role": "user",
"is_admin": False,
"preset": "standard",
}
existing = {u["username"] for u in list_users()}
@@ -798,17 +850,42 @@ async def admin_create_user(
detail="Username already taken",
)
add_user(body.username, body.password)
add_user(body.username, body.password, preset=body.preset)
user_id = ""
role = "user"
preset = "standard"
for item in list_users():
if item.get("username") == body.username:
user_id = str(item.get("id") or "")
role = str(item.get("role") or "user")
preset = str(item.get("preset") or "standard")
break
if preset == "learner":
from deeptutor.multi_user.grants import learner_grant, save_grant
try:
save_grant(user_id, learner_grant(user_id))
except Exception as exc:
rolled_back = False
try:
rolled_back = delete_user(body.username)
except Exception:
logger.exception(
"Failed to roll back user '%s' after learner grant initialization failed",
body.username,
)
if not rolled_back:
logger.error(
"Learner account '%s' may remain after grant initialization failed",
body.username,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="The learner preset could not be initialized.",
) from exc
logger.info(
f"Admin '{current.username if current else 'local'}' created user '{body.username}' "
f"(role={role!r})"
f"(role={role!r}, preset={preset!r})"
)
return {
"ok": True,
@@ -816,6 +893,7 @@ async def admin_create_user(
"username": body.username,
"role": role,
"is_admin": role == "admin",
"preset": preset,
}
+99 -9
View File
@@ -29,6 +29,11 @@ from fastapi.params import File
from fastapi.responses import FileResponse, Response
from 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,
@@ -109,6 +114,8 @@ def _http_error(exc: Exception) -> HTTPException:
locator, unsupported format, no extractable text). A 500 is reserved for
failures that are genuinely ours.
"""
if isinstance(exc, PermissionError):
return HTTPException(status_code=403, detail=str(exc))
if isinstance(exc, MaterialNotFound):
return HTTPException(status_code=404, detail=str(exc))
if isinstance(exc, ReadingUpgradeConflict):
@@ -119,6 +126,45 @@ def _http_error(exc: Exception) -> HTTPException:
return 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 ===================================================================
@@ -336,7 +382,13 @@ async def list_library_materials(
for manifest in store.list_materials():
if catalog.get_material(manifest.material_id) is None:
catalog.register_manifest(manifest)
rows = catalog.list_materials(search=search, status=status, library_filter=library_filter)
rows = [
row
for row in catalog.list_materials(
search=search, status=status, library_filter=library_filter
)
if _material_allowed(row.material_id)
]
membership = catalog.collections_for_materials([row.material_id for row in rows])
materials: list[dict[str, Any]] = []
for row in rows:
@@ -346,9 +398,13 @@ async def list_library_materials(
payload["size_bytes"] = size_bytes
payload["unit_count"] = unit_count
materials.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 +436,7 @@ async def duplicate_check(payload: DuplicateCheckRequest) -> dict[str, Any]:
if 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):
continue
matches.append(
{
@@ -396,7 +452,7 @@ async def duplicate_check(payload: DuplicateCheckRequest) -> dict[str, Any]:
except Exception: # noqa: BLE001 - a malformed URL is simply not a match
continue
record = catalog.get_material(material_id)
if record is None:
if record is None or not _material_allowed(record.material_id):
continue
matches.append(
{
@@ -416,6 +472,10 @@ async def import_urls(
payload: UrlImportRequest, background_tasks: BackgroundTasks
) -> dict[str, Any]:
"""Queue safe webpage, YouTube, or Bilibili imports into a workspace."""
try:
assert_learning_material("", upload=True)
except PermissionError as exc:
raise _http_error(exc) from exc
service = _ingestion()
try:
materials = [service.queue_url(url) for url in payload.urls]
@@ -446,6 +506,7 @@ async def import_urls(
async def retry_import(material_id: str, background_tasks: BackgroundTasks) -> dict[str, Any]:
service = _ingestion()
try:
assert_learning_material(material_id)
material = service.catalog.get_material(material_id)
if material is None:
raise MaterialNotFound(f"material {material_id!r} not found")
@@ -462,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
@@ -493,6 +554,7 @@ async def list_workspace_index() -> dict[str, Any]:
@router.post("/workspaces", status_code=201)
async def create_workspace(payload: WorkspaceCreateRequest) -> dict[str, Any]:
try:
_enforce_learning_materials(*payload.material_ids)
row = _catalog().create_workspace(
payload.title,
payload.material_ids,
@@ -511,7 +573,7 @@ async def get_workspace(workspace_id: str) -> dict[str, Any]:
if 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:
@@ -581,6 +643,7 @@ async def add_workspace_material(
workspace_id: str, payload: WorkspaceMaterialRequest
) -> dict[str, Any]:
try:
assert_learning_material(payload.material_id)
row = _catalog().add_material(
workspace_id, payload.material_id, make_active=payload.make_active
)
@@ -594,6 +657,7 @@ async def reorder_workspace_materials(
workspace_id: str, payload: WorkspaceReorderRequest
) -> dict[str, Any]:
try:
_enforce_learning_materials(*payload.material_ids)
row = _catalog().reorder_materials(workspace_id, payload.material_ids)
return {"workspace": row.to_dict()}
except Exception as exc:
@@ -603,6 +667,7 @@ async def reorder_workspace_materials(
@router.put("/workspaces/{workspace_id}/materials/{material_id}/active")
async def activate_workspace_material(workspace_id: str, material_id: str) -> dict[str, Any]:
try:
assert_learning_material(material_id)
row = _catalog().set_active_material(workspace_id, material_id)
return {"workspace": row.to_dict()}
except Exception as exc:
@@ -612,6 +677,7 @@ async def activate_workspace_material(workspace_id: str, material_id: str) -> di
@router.delete("/workspaces/{workspace_id}/materials/{material_id}")
async def remove_workspace_material(workspace_id: str, material_id: str) -> dict[str, Any]:
try:
assert_learning_material(material_id)
row = _catalog().remove_material(workspace_id, material_id)
return {"workspace": row.to_dict()}
except Exception as exc:
@@ -665,6 +731,8 @@ async def create_reading_session(
catalog = _catalog()
try:
if payload.active_material_id:
assert_learning_material(payload.active_material_id)
workspace = catalog.get_workspace(workspace_id)
if workspace is None:
raise MaterialNotFound(f"reading workspace {workspace_id!r} not found")
@@ -759,6 +827,7 @@ async def organize_reading_notes(
workspace_id: str, payload: OrganizeNotesRequest
) -> dict[str, Any]:
try:
_enforce_learning_materials(*payload.material_ids)
catalog = _catalog()
notes = await asyncio.to_thread(
organize_workspace_notes,
@@ -777,6 +846,7 @@ async def capture_reading_to_notebook(
workspace_id: str, payload: NotebookCaptureRequest
) -> dict[str, Any]:
try:
_enforce_learning_materials(*payload.material_ids)
catalog = _catalog()
result = await asyncio.to_thread(
send_workspace_to_notebook,
@@ -810,7 +880,11 @@ async def supported_formats() -> SupportedFormats:
async def list_materials() -> list[MaterialInfo]:
store = _store()
try:
return [_info(store, manifest) for manifest in store.list_materials()]
return [
_info(store, manifest)
for manifest in store.list_materials()
if _material_allowed(manifest.material_id)
]
except Exception as exc:
raise _http_error(exc) from exc
@@ -825,6 +899,10 @@ async def upload_material(
The upload is streamed to a temp file with a running size check, so an
oversized file is rejected before it is fully buffered rather than after.
"""
try:
assert_learning_material("", upload=True)
except PermissionError as exc:
raise _http_error(exc) from exc
filename = (file.filename or "").strip()
if not filename:
raise HTTPException(status_code=400, detail="The upload has no filename.")
@@ -886,6 +964,7 @@ async def upload_material(
async def get_material(material_id: str) -> MaterialDetail:
store = _store()
try:
assert_learning_material(material_id)
return _detail(store, store.manifest(material_id))
except Exception as exc:
raise _http_error(exc) from exc
@@ -896,6 +975,7 @@ async def epub_pairing_candidates(material_id: str) -> list[dict[str, Any]]:
from deeptutor.reading.epub_bilingual import recommend_epub_candidates
try:
assert_learning_material(material_id)
return await asyncio.to_thread(recommend_epub_candidates, _store(), material_id)
except Exception as exc:
raise _http_error(exc) from exc
@@ -913,6 +993,7 @@ async def create_epub_pairing(payload: EpubPairingRequest) -> dict[str, Any]:
from deeptutor.reading.epub_bilingual import create_epub_pairing
try:
_enforce_learning_materials(payload.english_material_id, payload.chinese_material_id)
pairing = await asyncio.to_thread(
create_epub_pairing,
_store(),
@@ -944,6 +1025,7 @@ async def delete_material(material_id: str) -> dict[str, Any]:
record = catalog.get_material(material_id)
removed_from = catalog.collections_for_material(material_id) if record else []
try:
assert_learning_material_mutation(material_id)
shared = record is not None and catalog.count_materials_for_content(record.content_id) > 1
if shared and record is not None:
# A sibling material still reads this content: drop this row and
@@ -972,6 +1054,7 @@ async def get_unit(material_id: str, locator: int) -> UnitText:
"""One unit's text — the reader's text view, and the only view for non-PDFs."""
store = _store()
try:
assert_learning_material(material_id)
manifest = store.manifest(material_id)
return UnitText(
locator=locator,
@@ -1019,6 +1102,7 @@ async def get_raw(material_id: str) -> FileResponse:
"""The original bytes, for the faithful viewer. Serves Range requests."""
store = _store()
try:
assert_learning_material(material_id)
manifest = store.manifest(material_id)
path = store.raw_path(material_id)
except Exception as exc:
@@ -1068,6 +1152,7 @@ async def get_snapshot_asset(material_id: str, asset_name: str) -> FileResponse:
async def list_annotations(material_id: str) -> list[AnnotationInfo]:
store = _store()
try:
assert_learning_material(material_id)
return [_annotation_info(row) for row in store.annotations(material_id)]
except Exception as exc:
raise _http_error(exc) from exc
@@ -1078,6 +1163,7 @@ async def get_position(material_id: str) -> PositionInfo:
"""Return the user's last durable viewport for this material."""
store = _store()
try:
assert_learning_material(material_id)
return PositionInfo(**store.position(material_id).to_dict())
except Exception as exc:
raise _http_error(exc) from exc
@@ -1088,6 +1174,7 @@ async def save_position(material_id: str, payload: PositionPayload) -> PositionI
"""Persist a validated numeric locator plus an optional renderer anchor."""
store = _store()
try:
assert_learning_material(material_id)
saved = store.save_position(
material_id,
ReadingPosition(
@@ -1106,6 +1193,7 @@ async def save_annotation(material_id: str, payload: AnnotationPayload) -> Annot
"""Create or update one annotation (id absent = create)."""
store = _store()
try:
assert_learning_material(material_id)
saved = store.save_annotation(material_id, payload.to_annotation())
except Exception as exc:
raise _http_error(exc) from exc
@@ -1116,6 +1204,7 @@ async def save_annotation(material_id: str, payload: AnnotationPayload) -> Annot
async def delete_annotation(material_id: str, annotation_id: str) -> dict[str, Any]:
store = _store()
try:
assert_learning_material(material_id)
removed = store.delete_annotation(material_id, annotation_id)
except Exception as exc:
raise _http_error(exc) from exc
@@ -1137,6 +1226,7 @@ async def export(
"""
store = _store()
try:
assert_learning_material(material_id)
result = export_material(store, material_id, fmt=fmt)
except Exception as exc:
raise _http_error(exc) from exc
+19 -1
View File
@@ -10,6 +10,10 @@ from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field, ValidationError
from deeptutor.multi_user.learning_access import (
allowed_reading_extensions,
assert_learning_material,
)
from deeptutor.reading import ReadingStore
from deeptutor.reading.extensions import (
ReadingContext,
@@ -38,7 +42,12 @@ def _verified_selection(candidate: str, unit_text: str) -> str:
@router.get("/extensions")
async def list_extensions() -> list[dict[str, Any]]:
return [extension.manifest.model_dump() for extension in get_reading_extension_registry().all()]
allowed = allowed_reading_extensions()
return [
extension.manifest.model_dump()
for extension in get_reading_extension_registry().all()
if allowed is None or extension.manifest.id in allowed
]
@router.post("/materials/{material_id}/extensions/{extension_id}/actions/{action}")
@@ -48,6 +57,15 @@ async def run_extension_action(
action: str,
payload: ActionPayload,
) -> dict[str, Any]:
try:
assert_learning_material(material_id)
except PermissionError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
allowed = allowed_reading_extensions()
if allowed is not None and extension_id not in allowed:
raise HTTPException(status_code=403, detail="This reading extension is not allowed.")
registry = get_reading_extension_registry()
extension = registry.get(extension_id)
if extension is None:
+120
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from copy import deepcopy
import json
from pathlib import Path
import re
from typing import Any
from .identity import get_user_by_id
@@ -12,6 +13,12 @@ from .paths import SYSTEM_ROOT, ensure_system_dirs
GRANTS_DIR = SYSTEM_ROOT / "grants"
LEARNING_CAPABILITIES = {"chat", "immersive_reading"}
LEARNING_AGE_BANDS = {"6-8", "9-12", "13-15"}
LEARNING_PERSONAS = {"teacher"}
LEARNING_SURFACES = {"chat", "reading"}
_EXTENSION_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
def empty_grant(user_id: str) -> dict[str, Any]:
return {
@@ -42,6 +49,7 @@ def empty_grant(user_id: str) -> dict[str, Any]:
"mcp_tools": None,
"cli_apps": None,
"exec_enabled": None,
"learning_policy": None,
}
@@ -53,6 +61,42 @@ def _normalize_tool_list(value: Any) -> list[str] | None:
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_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"
@@ -85,9 +129,35 @@ def normalize_grant(user_id: str, payload: dict[str, Any] | None) -> dict[str, A
base[key] = _normalize_tool_list(payload.get(key))
exec_enabled = payload.get("exec_enabled")
base["exec_enabled"] = bool(exec_enabled) if isinstance(exec_enabled, bool) else None
base["learning_policy"] = _normalize_learning_policy(payload.get("learning_policy"))
return base
def learner_grant(user_id: str) -> dict[str, Any]:
"""Return the conservative server-enforced expansion of the learner preset."""
return normalize_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": [],
"extensions": [],
},
},
},
)
def load_grant(user_id: str) -> dict[str, Any]:
path = grant_path(user_id)
if not path.exists():
@@ -132,6 +202,56 @@ def validate_grant(grant: dict[str, Any]) -> None:
walk(child, f"{trail}[{index}]")
walk(grant)
policy = grant.get("learning_policy")
if policy is None:
return
if not isinstance(policy, dict):
raise ValueError("learning_policy must be an object or null")
if policy.get("age_band") not in LEARNING_AGE_BANDS:
raise ValueError(
f"learning_policy.age_band must be one of: {', '.join(sorted(LEARNING_AGE_BANDS))}"
)
if policy.get("locked_persona") not in LEARNING_PERSONAS:
raise ValueError(
f"learning_policy.locked_persona must be one of: {', '.join(sorted(LEARNING_PERSONAS))}"
)
capabilities = policy.get("allowed_capabilities")
if not isinstance(capabilities, list) or not capabilities:
raise ValueError("learning_policy.allowed_capabilities cannot be empty")
capability_set = set(capabilities)
unknown = capability_set - LEARNING_CAPABILITIES
if unknown:
raise ValueError(
"learning_policy.allowed_capabilities contains unsupported values: "
f"{', '.join(sorted(unknown))}"
)
if policy.get("default_capability") not in capability_set:
raise ValueError("learning_policy.default_capability must be allowed")
surfaces = policy.get("allowed_surfaces", ["chat", "reading"])
if not isinstance(surfaces, list) or not surfaces:
raise ValueError("learning_policy.allowed_surfaces cannot be empty")
unknown_surfaces = set(surfaces) - LEARNING_SURFACES
if unknown_surfaces:
raise ValueError(
"learning_policy.allowed_surfaces contains unsupported values: "
f"{', '.join(sorted(unknown_surfaces))}"
)
reading = policy.get("reading", {})
if not isinstance(reading, dict):
raise ValueError("learning_policy.reading must be an object")
material_ids = reading.get("material_ids") or []
if not isinstance(material_ids, list):
raise ValueError("learning_policy.reading.material_ids must be an array")
invalid_extensions = sorted(
extension
for extension in set(reading.get("extensions") or [])
if not _EXTENSION_ID_RE.fullmatch(str(extension))
)
if invalid_extensions:
raise ValueError(
"learning_policy.reading.extensions contains invalid ids: "
f"{', '.join(invalid_extensions)}"
)
def public_grant(user_id: str) -> dict[str, Any]:
+32 -2
View File
@@ -20,7 +20,7 @@ from .book_permission import (
normalize_book_permission,
public_permission_dict,
)
from .models import Role
from .models import AccountPreset, Role
from .paths import PROJECT_ROOT, SYSTEM_ROOT, migrate_legacy_multi_user_tree
logger = logging.getLogger(__name__)
@@ -70,6 +70,9 @@ def _canonical_record(
role = str(value.get("role") or default_role)
if role not in {"admin", "user"}:
role = default_role
preset = str(value.get("preset") or "standard")
if preset not in {"standard", "learner", "custom"}:
preset = "standard"
record = {
"id": str(value.get("id") or new_user_id()),
"hash": hashed,
@@ -77,6 +80,7 @@ def _canonical_record(
"created_at": str(value.get("created_at") or utc_now()),
"disabled": bool(value.get("disabled", False)),
"avatar": str(value.get("avatar") or ""),
"preset": preset,
}
if "book_permission" in value:
record["book_permission"] = canonical_book_permission(value.get("book_permission"))
@@ -163,6 +167,7 @@ def _env_admin_record(password_hash: str) -> dict[str, Any]:
"created_at": "",
"disabled": False,
"avatar": "",
"preset": "standard",
}
@@ -213,7 +218,12 @@ def load_users( # nosec B107 - empty defaults mean "no env fallback supplied".
return canonical
def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[str, Any]:
def save_user(
username: str,
hashed_password: str,
role: Role = "user",
preset: AccountPreset = "standard",
) -> dict[str, Any]:
USERS_FILE.parent.mkdir(parents=True, exist_ok=True)
# Read-modify-write must be atomic so concurrent first-time registrations
# cannot each see an empty store and each promote themselves to admin.
@@ -230,6 +240,9 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[
account_exists = bool(users) or (bool(env_username) and env_username != username)
effective_role: Role = role if account_exists else "admin"
existing = users.get(username) or {}
effective_preset = str(existing.get("preset") or preset or "standard")
if effective_preset not in {"standard", "learner", "custom"}:
effective_preset = preset
record = {
"id": str(existing.get("id") or new_user_id()),
"hash": hashed_password,
@@ -237,6 +250,7 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[
"created_at": str(existing.get("created_at") or utc_now()),
"disabled": bool(existing.get("disabled", False)),
"avatar": str(existing.get("avatar") or ""),
"preset": effective_preset,
"book_permission": canonical_book_permission(existing.get("book_permission")),
}
users[username] = record
@@ -256,6 +270,7 @@ def list_user_info( # nosec B107 - empty defaults mean "no env fallback supplie
"created_at": record.get("created_at", ""),
"disabled": bool(record.get("disabled", False)),
"avatar": str(record.get("avatar") or ""),
"preset": str(record.get("preset") or "standard"),
"book_permission": public_permission_dict(
normalize_book_permission(record.get("book_permission"))
),
@@ -404,6 +419,21 @@ def set_role(username: str, role: Role) -> bool:
return True
def set_preset(username: str, preset: AccountPreset) -> bool:
"""Update an account's configuration preset without changing its role."""
if preset not in {"standard", "learner", "custom"}:
raise ValueError("preset must be 'standard', 'learner', or 'custom'")
if not USERS_FILE.exists():
return False
with _USERS_WRITE_LOCK:
users = load_users()
if username not in users:
return False
users[username]["preset"] = preset
_write_users(users)
return True
def load_or_create_auth_secret() -> str:
migrate_legacy_multi_user_tree()
_migrate_secret()
+118
View File
@@ -0,0 +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"]):
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_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",
]
+7
View File
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any, Literal
Role = Literal["admin", "user"]
AccountPreset = Literal["standard", "learner", "custom"]
ScopeKind = Literal["admin", "user"]
@@ -22,6 +23,11 @@ class UserRecord:
# version is bumped on every upload so clients can cache-bust).
avatar: str = ""
# Account presets describe how a normal ``user`` is configured. They are
# deliberately not a third identity role: admins remain admins and every
# preset remains an ordinary account.
preset: AccountPreset = "standard"
def public_dict(self) -> dict[str, Any]:
return {
"id": self.id,
@@ -30,6 +36,7 @@ class UserRecord:
"created_at": self.created_at,
"disabled": self.disabled,
"avatar": self.avatar,
"preset": self.preset,
}
+78 -4
View File
@@ -3,24 +3,30 @@
from __future__ import annotations
import asyncio
import os
from pathlib import Path
import shutil
from typing import Any
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field, StrictBool
from deeptutor.api.routers.auth import require_admin
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.reading import ReadingStore
from deeptutor.reading.extensions import get_reading_extension_registry
from deeptutor.services.config.model_catalog import ModelCatalogService
from deeptutor.services.skill.service import SkillService
from .audit import log_admin_action
from .book_permission import BookDefaultLevel, BookPermission, BookPermissionLevel
from .context import get_current_user
from .grants import load_grant, save_grant
from .grants import load_grant, normalize_grant, save_grant, validate_grant
from .identity import get_user_by_id, list_user_info, set_book_permission
from .knowledge_access import admin_kb_base_dir
from .model_access import is_owner_bound
from .paths import get_admin_path_service
from .paths import get_admin_path_service, get_path_service_for_scope, scope_for_user
router = APIRouter()
@@ -117,6 +123,60 @@ def _admin_partner_summary() -> list[dict[str, Any]]:
]
def _reading_root(service: Any) -> Path:
return service.get_workspace_feature_dir("reading")
def _admin_reading_summary() -> list[dict[str, Any]]:
store = ReadingStore(_reading_root(get_admin_path_service()))
return [manifest.to_dict() for manifest in store.list_materials()]
def _stage_assigned_materials(user_id: str, grant: dict[str, Any]) -> None:
"""Copy newly assigned admin books without touching learner-owned state."""
policy = grant.get("learning_policy")
reading = policy.get("reading") if isinstance(policy, dict) else None
if not isinstance(reading, dict):
return
material_ids = set(reading.get("material_ids") or [])
material_ids.discard("*")
if not material_ids:
return
admin_root = _reading_root(get_admin_path_service())
admin_store = ReadingStore(admin_root)
user_service = get_path_service_for_scope(scope_for_user(user_id, is_admin=False))
target_root = _reading_root(user_service)
target_root.mkdir(parents=True, exist_ok=True)
for material_id in sorted(material_ids):
try:
admin_store.manifest(material_id)
except Exception as exc:
raise ValueError(f"Unknown admin reading material: {material_id}") from exc
target = target_root / material_id
if target.exists():
continue
stage = target_root / f".{material_id}.{uuid.uuid4().hex[:8]}.staging"
try:
shutil.copytree(admin_root / material_id, stage)
os.replace(stage, target)
finally:
shutil.rmtree(stage, ignore_errors=True)
def _validate_reading_policy(grant: dict[str, Any]) -> None:
policy = grant.get("learning_policy")
reading = policy.get("reading") if isinstance(policy, dict) else None
if not isinstance(reading, dict):
return
allowed_extensions = {
extension.manifest.id for extension in get_reading_extension_registry().all()
}
unknown = sorted(set(reading.get("extensions") or []) - allowed_extensions)
if unknown:
raise ValueError(f"Unknown reading extensions: {', '.join(unknown)}")
def _require_assignable_user(user_id: str) -> tuple[str, dict[str, Any]]:
user_record = get_user_by_id(user_id)
if user_record is None:
@@ -142,6 +202,10 @@ async def admin_resources(_: object = Depends(require_admin)) -> dict[str, Any]:
"knowledge_bases": _admin_kb_summary(),
"skills": _admin_skill_summary(),
"partners": _admin_partner_summary(),
"reading_materials": _admin_reading_summary(),
"reading_extensions": [
extension.manifest.model_dump() for extension in get_reading_extension_registry().all()
],
"tools": tool_options["tools"],
"mcp_tools": tool_options["mcp_tools"],
}
@@ -166,9 +230,18 @@ async def put_user_grants(
payload: GrantPayload,
_: object = Depends(require_admin),
) -> dict[str, Any]:
_require_assignable_user(user_id)
user_record = _require_assignable_user(user_id)
try:
grant = save_grant(user_id, payload.grant)
grant = normalize_grant(user_id, payload.grant)
if (
str(user_record[1].get("preset") or "standard") == "learner"
and grant.get("learning_policy") is None
):
raise ValueError("Learner accounts must retain a learning policy.")
validate_grant(grant)
_validate_reading_policy(grant)
_stage_assigned_materials(user_id, grant)
grant = save_grant(user_id, grant)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
log_admin_action(
@@ -184,6 +257,7 @@ async def put_user_grants(
None if grant.get("mcp_tools") is None else len(grant.get("mcp_tools") or [])
),
"exec_enabled": grant.get("exec_enabled"),
"learning_policy": grant.get("learning_policy"),
},
)
return {"grant": grant}
+19 -4
View File
@@ -439,11 +439,24 @@ class ReadingCatalogStore:
self._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"""SELECT
COUNT(*) AS all_count,
COALESCE(SUM(NOT EXISTS (
SELECT 1 FROM reading_workspace_materials wm
@@ -465,7 +478,9 @@ class ReadingCatalogStore:
WHEN render_mode NOT IN ('video', 'audio') AND source_kind = 'file'
THEN 1 ELSE 0
END), 0) AS document_count
FROM reading_materials"""
FROM reading_materials
{where}""", # nosec B608 - only placeholder shape is interpolated
params,
).fetchone()
assert row is not None
return {
+26 -4
View File
@@ -28,6 +28,7 @@ from datetime import datetime, timedelta, timezone
import logging
from typing import Any
from deeptutor.multi_user.models import AccountPreset, Role
from deeptutor.services.config import load_auth_settings, load_integrations_settings
logger = logging.getLogger(__name__)
@@ -101,7 +102,12 @@ def verify_password(plain: str, hashed: str) -> bool:
# ---------------------------------------------------------------------------
def _make_user_record(hashed: str, role: str = "user", created_at: str = "") -> dict[str, Any]:
def _make_user_record(
hashed: str,
role: str = "user",
created_at: str = "",
preset: str = "standard",
) -> dict[str, Any]:
"""Build a canonical user record dict for legacy callers/tests."""
from deeptutor.multi_user.identity import new_user_id
@@ -112,6 +118,7 @@ def _make_user_record(hashed: str, role: str = "user", created_at: str = "") ->
"created_at": created_at or datetime.now(timezone.utc).isoformat(),
"disabled": False,
"avatar": "",
"preset": preset,
}
@@ -136,7 +143,12 @@ def is_first_user() -> bool:
return len(_load_users()) == 0
def add_user(username: str, plain_password: str, role: str = "user") -> None:
def add_user(
username: str,
plain_password: str,
role: Role = "user",
preset: AccountPreset = "standard",
) -> None:
"""
Add or update a user in data/user/auth_users.json.
@@ -148,8 +160,18 @@ def add_user(username: str, plain_password: str, role: str = "user") -> None:
"""
from deeptutor.multi_user.identity import save_user
record = save_user(username, hash_password(plain_password), role=role) # type: ignore[arg-type]
logger.info("User '%s' saved with role=%r", username, record.get("role", "user"))
record = save_user(
username,
hash_password(plain_password),
role=role,
preset=preset,
)
logger.info(
"User '%s' saved with role=%r preset=%r",
username,
record.get("role", "user"),
record.get("preset", "standard"),
)
def list_users() -> list[dict]:
+8 -3
View File
@@ -1554,10 +1554,15 @@ class TurnRuntimeManager:
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, "capability": capability})
except PermissionError as exc:
raise RuntimeError(str(exc)) from exc
workspace_mode_explicit = "workspace_mode" in payload
workspace_mode = _workspace_mode(
payload.get("workspace_mode")
+239
View File
@@ -0,0 +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()
+178
View File
@@ -0,0 +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_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_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": [],
}
@@ -0,0 +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"]
+57 -2
View File
@@ -10,6 +10,7 @@ import {
setUserRole,
createUser,
type UserRecord,
type AccountPreset,
} from "@/lib/admin-api";
import { GrantEditor } from "@/features/multi-user/components/GrantEditor";
import { BookPermissionEditor } from "@/features/multi-user/components/BookPermissionEditor";
@@ -63,6 +64,7 @@ export default function AdminUsersPage() {
const [confirmBusy, setConfirmBusy] = useState(false);
const [createUsername, setCreateUsername] = useState("");
const [createPassword, setCreatePassword] = useState("");
const [createPreset, setCreatePreset] = useState<AccountPreset>("standard");
const [createSubmitting, setCreateSubmitting] = useState(false);
const [createError, setCreateError] = useState("");
@@ -97,6 +99,7 @@ export default function AdminUsersPage() {
function openCreateDialog() {
setCreateUsername("");
setCreatePassword("");
setCreatePreset("standard");
setCreateError("");
setShowCreateDialog(true);
}
@@ -121,7 +124,7 @@ export default function AdminUsersPage() {
}
setCreateSubmitting(true);
try {
await createUser(username, createPassword);
await createUser(username, createPassword, createPreset);
setShowCreateDialog(false);
await load();
} catch (e) {
@@ -384,6 +387,13 @@ export default function AdminUsersPage() {
)}
{isAdmin ? t("Admin") : t("User")}
</span>
{!isAdmin && user.preset && (
<span className="mt-1 block text-[11px] text-[var(--muted-foreground)]">
{t("Preset: {{preset}}", {
preset: t(user.preset === "learner" ? "Learner" : user.preset === "custom" ? "Custom" : "Standard"),
})}
</span>
)}
</td>
<td className="px-5 py-3.5 text-[var(--muted-foreground)]">
{formatDate(user.created_at, lang)}
@@ -454,7 +464,11 @@ export default function AdminUsersPage() {
{canManageAssignments && expandedUserId === user.id && (
<tr>
<td colSpan={4} className="p-0">
<GrantEditor key={user.id} userId={user.id} />
<GrantEditor
key={user.id}
userId={user.id}
lockLearningPolicy={user.preset === "learner"}
/>
<BookPermissionEditor userId={user.id} />
</td>
</tr>
@@ -594,6 +608,47 @@ export default function AdminUsersPage() {
/>
</label>
<fieldset className="mb-4">
<legend className="mb-1.5 block text-xs text-[var(--muted-foreground)]">
{t("Account preset")}
</legend>
<div
className="grid grid-cols-3 gap-1 rounded-lg bg-[var(--muted)]/50 p-1"
role="group"
aria-label={t("Account preset")}
>
{(["standard", "learner", "custom"] as const).map((preset) => (
<button
key={preset}
type="button"
disabled={createSubmitting}
aria-pressed={createPreset === preset}
onClick={() => setCreatePreset(preset)}
className={`rounded-md px-2 py-1.5 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-45 ${
createPreset === preset
? "bg-[var(--card)] text-[var(--foreground)] shadow-sm"
: "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
{t(
preset === "learner"
? "Learner"
: preset === "custom"
? "Custom"
: "Standard",
)}
</button>
))}
</div>
<p className="mt-1.5 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
{createPreset === "learner"
? t("Chat and Immersive Reading only, with uploads and tools disabled until assigned.")
: createPreset === "custom"
? t("Create an ordinary account, then customize its assignments.")
: t("Create an ordinary account with the default workspace behavior.")}
</p>
</fieldset>
{createError && (
<p className="mb-3 text-xs text-red-500">{createError}</p>
)}
@@ -1,11 +1,18 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { AlertCircle, CheckCircle2, Loader2, Save } from "lucide-react";
import {
AlertCircle,
CheckCircle2,
GraduationCap,
Loader2,
Save,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import McpToolGroups from "@/components/common/McpToolGroups";
import { toggleToolName as toggleName } from "@/lib/mcp-tool-groups";
import { fetchAdminResources, fetchUserGrant, saveUserGrant } from "../api";
import type { GrantPayload, MultiUserResources } from "../types";
import type { GrantPayload, LearningPolicy, MultiUserResources } from "../types";
type SaveState = "idle" | "saving" | "saved" | "error";
@@ -20,6 +27,24 @@ function emptyGrant(userId: string): GrantPayload {
enabled_tools: null,
mcp_tools: null,
exec_enabled: null,
learning_policy: null,
};
}
const LEARNING_AGE_BANDS = ["6-8", "9-12", "13-15"] as const;
function conservativeLearningPolicy(): LearningPolicy {
return {
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: [],
},
};
}
@@ -128,7 +153,14 @@ function ModeSwitch({
);
}
export function GrantEditor({ userId }: { userId: string }) {
export function GrantEditor({
userId,
lockLearningPolicy = false,
}: {
userId: string;
lockLearningPolicy?: boolean;
}) {
const { t } = useTranslation();
const [resources, setResources] = useState<MultiUserResources | null>(null);
const [grant, setGrant] = useState<GrantPayload>(() => emptyGrant(userId));
const [loading, setLoading] = useState(true);
@@ -274,6 +306,64 @@ export function GrantEditor({ userId }: { userId: string }) {
setGrant((current) => ({ ...current, [key]: value }));
}
function enableLearningPolicy() {
setGrant((current) => ({
...current,
learning_policy: conservativeLearningPolicy(),
}));
}
function disableLearningPolicy() {
setGrant((current) => ({ ...current, learning_policy: null }));
}
function setLearningAgeBand(ageBand: LearningPolicy["age_band"]) {
setGrant((current) =>
current.learning_policy
? {
...current,
learning_policy: { ...current.learning_policy, age_band: ageBand },
}
: current,
);
}
function updateReadingPolicy(
update: (reading: LearningPolicy["reading"]) => LearningPolicy["reading"],
) {
setGrant((current) => {
if (!current.learning_policy) return current;
const reading = current.learning_policy.reading;
return {
...current,
learning_policy: {
...current.learning_policy,
allowed_surfaces:
current.learning_policy.allowed_surfaces ?? ["chat", "reading"],
reading: update(reading),
},
};
});
}
function toggleReadingMaterial(materialId: string) {
updateReadingPolicy((reading) => ({
...reading,
material_ids: reading.material_ids.includes(materialId)
? reading.material_ids.filter((id) => id !== materialId)
: [...reading.material_ids, materialId],
}));
}
function toggleReadingExtension(extensionId: string) {
updateReadingPolicy((reading) => ({
...reading,
extensions: reading.extensions.includes(extensionId)
? reading.extensions.filter((id) => id !== extensionId)
: [...reading.extensions, extensionId],
}));
}
// Named apart from the imported `toggleName` helper it wraps, and narrowed to
// the one key that still uses it: MCP rows go through McpToolGroups now.
function toggleGrantTool(key: "enabled_tools", name: string) {
@@ -377,6 +467,142 @@ export function GrantEditor({ userId }: { userId: string }) {
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-5 [scrollbar-gutter:stable]">
<div className="grid gap-5 md:grid-cols-3">
<section className="min-w-0 md:col-span-3">
<SectionTitle>{t("Learning policy")}</SectionTitle>
<div className="rounded-lg border border-[var(--border)]/60 p-3">
<CheckRow
label={t("Enable learning policy")}
description={t("Teacher persona; Chat and Immersive Reading only")}
checked={Boolean(grant.learning_policy)}
disabled={controlsDisabled || lockLearningPolicy}
onToggle={() =>
grant.learning_policy
? disableLearningPolicy()
: enableLearningPolicy()
}
/>
{grant.learning_policy && (
<div className="mt-3 grid gap-3 sm:grid-cols-3">
<label className="text-xs text-[var(--foreground)]">
<span className="mb-1 block text-[11px] text-[var(--muted-foreground)]">
{t("Age band")}
</span>
<select
value={grant.learning_policy.age_band}
disabled={controlsDisabled}
onChange={(event) =>
setLearningAgeBand(
event.target.value as LearningPolicy["age_band"],
)
}
className="h-8 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2"
>
{LEARNING_AGE_BANDS.map((band) => (
<option key={band} value={band}>
{band}
</option>
))}
</select>
</label>
<label className="text-xs text-[var(--foreground)]">
<span className="mb-1 block text-[11px] text-[var(--muted-foreground)]">
{t("Persona")}
</span>
<select
value={grant.learning_policy.locked_persona}
disabled
className="h-8 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2"
>
<option value="teacher">{t("Teacher")}</option>
</select>
</label>
<div className="text-xs">
<span className="mb-1 block text-[11px] text-[var(--muted-foreground)]">
{t("Modes")}
</span>
<div className="flex h-8 items-center gap-1.5">
<GraduationCap
size={14}
className="text-[var(--muted-foreground)]"
/>
<span>{t("Chat · Immersive Reading")}</span>
</div>
</div>
<div className="grid gap-3 sm:col-span-3 lg:grid-cols-2">
<div>
<div className="mb-1 text-[11px] text-[var(--muted-foreground)]">
{t("Assigned reading materials")}
</div>
<div className="grid gap-1 sm:grid-cols-2">
{(resources?.reading_materials ?? []).map((material) => (
<CheckRow
key={material.material_id}
label={material.title || material.filename}
description={material.filename}
checked={Boolean(
grant.learning_policy?.reading.material_ids.includes(
material.material_id,
),
)}
disabled={controlsDisabled}
onToggle={() =>
toggleReadingMaterial(material.material_id)
}
/>
))}
{(resources?.reading_materials ?? []).length === 0 ? (
<p className="text-[11px] leading-relaxed text-[var(--muted-foreground)]">
{t(
"Upload books in Reading before assigning them.",
)}
</p>
) : null}
</div>
<label className="mt-2 flex items-center gap-2 text-xs">
<input
type="checkbox"
checked={grant.learning_policy.reading.allow_upload}
disabled={controlsDisabled}
onChange={(event) =>
updateReadingPolicy((reading) => ({
...reading,
allow_upload: event.target.checked,
}))
}
/>
{t("Allow learner uploads")}
</label>
</div>
<div>
<div className="mb-1 text-[11px] text-[var(--muted-foreground)]">
{t("Reading extensions")}
</div>
<div className="grid gap-1 sm:grid-cols-2">
{(resources?.reading_extensions ?? []).map(
(extension) => (
<CheckRow
key={extension.id}
label={extension.name}
description={`${extension.id} · ${extension.version}`}
checked={Boolean(
grant.learning_policy?.reading.extensions.includes(
extension.id,
),
)}
disabled={controlsDisabled}
onToggle={() =>
toggleReadingExtension(extension.id)
}
/>
),
)}
</div>
</div>
</div>
</div>
)}
</div>
</section>
<section className="min-w-0">
<SectionTitle>Models</SectionTitle>
<div className="space-y-1.5 text-xs">
+25
View File
@@ -14,6 +14,20 @@ export type GrantPayload = {
mcp_tools: string[] | null;
/** null = follow deployment exec policy, false = always disabled. */
exec_enabled: boolean | null;
learning_policy: LearningPolicy | null;
};
export type LearningPolicy = {
age_band: "6-8" | "9-12" | "13-15";
locked_persona: "teacher";
allowed_capabilities: Array<"chat" | "immersive_reading">;
default_capability: "chat" | "immersive_reading";
allowed_surfaces: Array<"chat" | "reading">;
reading: {
allow_upload: boolean;
material_ids: string[];
extensions: string[];
};
};
export type ToolOption = { name: string; description?: string };
@@ -43,6 +57,17 @@ export type MultiUserResources = {
}>;
skills: Array<{ name: string; description?: string; tags?: string[] }>;
partners: Array<{ partner_id: string; name: string; description?: string }>;
reading_materials: Array<{
material_id: string;
title: string;
filename: string;
render_mode: string;
}>;
reading_extensions: Array<{
id: string;
name: string;
version: string;
}>;
tools: ToolOption[];
mcp_tools: McpToolOption[];
};
+6 -1
View File
@@ -1,5 +1,7 @@
import { apiFetch, apiUrl } from "@/lib/api";
export type AccountPreset = "standard" | "learner" | "custom";
export interface UserRecord {
id: string;
username: string;
@@ -8,6 +10,7 @@ export interface UserRecord {
disabled?: boolean;
/** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */
avatar?: string;
preset?: AccountPreset;
book_permission?: {
create: boolean;
default: "none" | "read";
@@ -57,16 +60,18 @@ export interface CreatedUser {
username: string;
role: "admin" | "user";
is_admin: boolean;
preset: AccountPreset;
}
export async function createUser(
username: string,
password: string,
preset: AccountPreset = "standard",
): Promise<CreatedUser> {
const res = await apiFetch(apiUrl("/api/v1/auth/users"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
body: JSON.stringify({ username, password, preset }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
+12
View File
@@ -16,6 +16,18 @@ export interface AuthStatus {
is_admin?: boolean;
/** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */
avatar?: string;
learning_policy?: {
age_band: string;
locked_persona: string;
allowed_capabilities: string[];
default_capability: string;
allowed_surfaces?: string[];
reading?: {
allow_upload: boolean;
material_ids: string[];
extensions: string[];
};
} | null;
}
/**
+18 -1
View File
@@ -4349,5 +4349,22 @@
"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"
}
+18 -1
View File
@@ -4349,5 +4349,22 @@
"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": "阅读扩展"
}
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import test from "node:test";
const adminApi = readFileSync(path.resolve(process.cwd(), "lib/admin-api.ts"), "utf8");
const usersPage = readFileSync(
path.resolve(process.cwd(), "app/(admin)/admin/users/page.tsx"),
"utf8",
);
const grantEditor = readFileSync(
path.resolve(process.cwd(), "features/multi-user/components/GrantEditor.tsx"),
"utf8",
);
const en = JSON.parse(
readFileSync(path.resolve(process.cwd(), "locales/en/app.json"), "utf8"),
) as Record<string, string>;
const zh = JSON.parse(
readFileSync(path.resolve(process.cwd(), "locales/zh/app.json"), "utf8"),
) as Record<string, string>;
test("admin user creation sends the selected preset", () => {
assert.match(adminApi, /export type AccountPreset = "standard" \| "learner" \| "custom"/);
assert.match(adminApi, /body: JSON\.stringify\(\{ username, password, preset \}\)/);
assert.match(usersPage, /\["standard", "learner", "custom"\] as const/);
assert.match(usersPage, /aria-pressed=\{createPreset === preset\}/);
});
test("grant editing exposes the server-enforced learning policy controls", () => {
assert.match(grantEditor, /learning_policy: conservativeLearningPolicy\(\)/);
assert.match(grantEditor, /allowed_surfaces: \["chat", "reading"\]/);
assert.match(grantEditor, /toggleReadingMaterial/);
assert.match(grantEditor, /toggleReadingExtension/);
assert.match(grantEditor, /checked=\{grant\.learning_policy\.reading\.allow_upload\}/);
});
test("account preset copy is present in both supported locales", () => {
const keys = [
"Account preset",
"Learner",
"Preset: {{preset}}",
"Learning policy",
"Enable learning policy",
"Age band",
"Assigned reading materials",
"Allow learner uploads",
"Reading extensions",
];
for (const key of keys) {
assert.ok(key in en, `missing English key: ${key}`);
assert.ok(key in zh, `missing Chinese key: ${key}`);
assert.notEqual(en[key], "");
assert.notEqual(zh[key], "");
}
});