DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge pull request #1124 from evan188199-tech/codex/feat-learner-profile-controls
Bingxi Zhao (Frank)15c31267cc69
diff --cc deeptutor/api/routers/auth.pyindex f0f1885ce,5df4e7999..123c869c1--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@@ -192,9 -155,17 +193,18 @@@ class UserInfo(BaseModel)created_at: strdisabled: bool = Falseavatar: str = ""+ preset: AccountPreset = "standard"+ class LearnerProfileRequest(BaseModel):+ age: int | None = Field(default=None, ge=3, le=120)+ grade_level: str | None = Field(default=None, max_length=80)+ curriculum: str | None = Field(default=None, max_length=80)+ language: str | None = Field(default=None, max_length=80)+ reading_level: str | None = Field(default=None, max_length=80)+ explanation_style: str | None = Field(default=None, max_length=80)++# Markers settable through PUT /profile. Image markers ("img:<version>") are# managed exclusively by the upload endpoint so users cannot point their# avatar at a file that was never validated.@@@ -984,9 -765,41 +994,56 @@@ async def get_users(_: TokenPayload = Dreturn [UserInfo(**u) for u in list_users()]+ @router.get("/users/{username}/learner-profile")+ async def get_learner_profile(username: str, _: TokenPayload = Depends(require_admin)) -> dict:+ """Return the structured profile managed for an ordinary learner."""+ from deeptutor.multi_user.identity import get_user++ user = get_user(username)- if user is None or str(user.get("role") or "user") != "user":++ if (++ user is None++ or str(user.get("role") or "user") != "user"++ or str(user.get("preset") or "standard") != "learner"++ ):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ return {"learner_profile": user.get("learner_profile")}+++ @router.put("/users/{username}/learner-profile")+ async def put_learner_profile(+ username: str,+ body: LearnerProfileRequest,+ current: TokenPayload = Depends(require_admin),+ ) -> dict:++ from deeptutor.multi_user.identity import get_user+ from deeptutor.multi_user.learner_profile import normalize_profile+++ user = get_user(username)++ if (++ user is None++ or str(user.get("role") or "user") != "user"++ or str(user.get("preset") or "standard") != "learner"++ ):++ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ try:+ profile = normalize_profile(body.model_dump(exclude_none=True))+ except ValueError as exc:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)+ ) from exc+ updated = set_learner_profile(username, profile)- if updated is None:- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")++ log_admin_action(++ "learner_profile_update",++ target_user_id=str(user.get("id") or ""),++ summary={"fields": sorted(profile or {})},++ )+ logger.info("Admin '%s' updated learner profile for '%s'", current.username, username)+ return {"learner_profile": updated}++@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.diff --cc deeptutor/multi_user/identity.pyindex a470efc16,5e2a53f20..5669872fb--- a/deeptutor/multi_user/identity.py+++ b/deeptutor/multi_user/identity.py@@@ -21,7 -20,8 +21,8 @@@ from .book_permission importnormalize_book_permission,public_permission_dict,)+ from .learner_profile import normalize_profile-from .models import Role+from .models import AccountPreset, Rolefrom .paths import PROJECT_ROOT, SYSTEM_ROOT, migrate_legacy_multi_user_treelogger = logging.getLogger(__name__)@@@ -251,8 -240,8 +254,9 @@@ def save_user"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")),+ "learner_profile": normalize_profile(existing.get("learner_profile")),}users[username] = record_write_users(users)@@@ -291,6 -279,18 +295,30 @@@ def get_user_by_id(user_id: str) -> tupreturn None++def get_learner_profile(username: str) -> dict[str, Any] | None:++ """Return a learner account's structured profile, if present."""++ record = get_user(username)++ if record is None or str(record.get("preset") or "standard") != "learner":++ return None++ return normalize_profile(record.get("learner_profile"))+++++ def set_learner_profile(username: str, profile: dict[str, Any] | None) -> dict[str, Any] | None:+ """Atomically replace one ordinary user's structured learner profile."""+ with _USERS_WRITE_LOCK:+ users = load_users()+ record = users.get(username)- if record is None or str(record.get("role") or "user") != "user":++ if (++ record is None++ or str(record.get("role") or "user") != "user"++ or str(record.get("preset") or "standard") != "learner"++ ):+ return None+ record["learner_profile"] = normalize_profile(profile)+ _write_users(users)+ return record["learner_profile"]++def set_book_permission(username: str, permission: BookPermission) -> bool:"""Atomically replace one ordinary user's shared-book permission."""diff --cc deeptutor/services/session/turn_runtime.pyindex a3ea6b637,b384b49fa..e28c273d6--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@@ -2577,6 -2464,15 +2577,14 @@@ class TurnRuntimeManagerfrom deeptutor.services.skill.service import SkillService, render_skills_manifestcurrent_user = get_current_user()+ learner_profile_prompt = ""+ if not current_user.is_admin:+ from deeptutor.multi_user.identity import get_user_by_id+ from deeptutor.multi_user.learner_profile import prompt_block++ account = get_user_by_id(current_user.id)- learner_profile_prompt = prompt_block(- account[1].get("learner_profile") if account else None- )++ if account and str(account[1].get("preset") or "standard") == "learner":++ learner_profile_prompt = prompt_block(account[1].get("learner_profile"))requested_persona = str(payload.get("persona") or "").strip()persona_context = ""if requested_persona:@@@ -2910,7 -2804,7 +2918,8 @@@"book_references": book_references,"course_id": str(payload.get("course_id") or ""),"course_conventions": str(payload.get("course_conventions") or ""),+ "reading_references": reading_references,+ "learner_profile_prompt": learner_profile_prompt,"mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),"mastery_mode": workspace_mode == WORKSPACE_MODE_MASTERY,"mastery_path_lease_managed": mastery_lease_managed,diff --cc tests/multi_user/test_learner_profile.pyindex 000000000,56329bc0a..a98af18dbmode 000000,100644..100644--- a/tests/multi_user/test_learner_profile.py+++ b/tests/multi_user/test_learner_profile.py@@@ -1,0 -1,45 +1,96 @@@+ from __future__ import annotations+++from fastapi import FastAPI++from fastapi.testclient import TestClient+++ from deeptutor.multi_user.learner_profile import normalize_profile, prompt_block+++ def test_chat_prompt_assembler_emits_profile_as_its_own_block() -> None:+ from deeptutor.agents.chat.prompt_blocks import ChatPromptAssembler+ from deeptutor.core.context import UnifiedContext++ context = UnifiedContext(+ metadata={"learner_profile_prompt": prompt_block({"age": 8, "language": "zh-CN"})}+ )+ rendered = ChatPromptAssembler(prompts={}, language="en").system_prompt(+ context=context, tool_manifest=""+ )+ assert "## learner_profile" in rendered+ assert "Age: 8" in rendered+++ def test_profile_normalizes_optional_fields_and_keeps_age_independent() -> None:+ profile = normalize_profile({"age": 8, "grade_level": "primary_4", "language": "zh-CN"})+ assert profile == {+ "schema_version": 1,+ "age": 8,+ "grade_level": "primary_4",+ "language": "zh-CN",+ }+++ def test_profile_rejects_invalid_age_and_oversized_text() -> None:+ for value in ({"age": 2}, {"age": True}, {"grade_level": "x" * 81}):+ try:+ normalize_profile(value)+ except ValueError:+ pass+ else:+ raise AssertionError("invalid learner profile was accepted")+++ def test_prompt_block_is_empty_for_missing_profile_and_lists_trusted_values() -> None:+ assert prompt_block(None) == ""+ block = prompt_block({"age": 8, "grade_level": "primary_4"})+ assert "trusted learner profile" in block+ assert "Age: 8" in block+ assert "Grade level: primary_4" in block++++++def test_admin_profile_api_is_learner_only_and_can_clear_profile(++ mu_isolated_root, monkeypatch++) -> None:++ from deeptutor.api.routers import auth as auth_router++ from deeptutor.multi_user.identity import save_user++ from deeptutor.services.auth import TokenPayload, hash_password++++ admin = save_user("root", hash_password("root-password"), role="admin")++ learner = save_user("learner", hash_password("learner-password"), preset="learner")++ save_user("standard", hash_password("standard-password"))++ tokens = {"admin-token": TokenPayload(username="root", 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")++ client = TestClient(app)++ headers = {"Authorization": "Bearer admin-token"}++++ updated = client.put(++ "/api/v1/auth/users/learner/learner-profile",++ headers=headers,++ json={"age": 8, "language": "zh-CN"},++ )++ assert updated.status_code == 200++ assert updated.json()["learner_profile"]["age"] == 8++ assert (++ learner["id"]++ in (mu_isolated_root / "data" / "system" / "audit" / "usage.jsonl").read_text()++ )++++ cleared = client.put(++ "/api/v1/auth/users/learner/learner-profile",++ headers=headers,++ json={},++ )++ assert cleared.status_code == 200++ assert cleared.json()["learner_profile"] is None++ assert (++ client.get("/api/v1/auth/users/standard/learner-profile", headers=headers).status_code++ == 404++ )++++ from deeptutor.services.auth import get_learner_profile++++ assert get_learner_profile("learner") is Nonediff --cc web/app/(admin)/admin/users/page.tsxindex 46b50aef9,10eaf51cb..d151c5e7c--- a/web/app/(admin)/admin/users/page.tsx+++ b/web/app/(admin)/admin/users/page.tsx@@@ -464,12 -455,9 +465,15 @@@ 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} />- <LearnerProfileEditor username={user.username} />++ {user.preset === "learner" && (++ <LearnerProfileEditor username={user.username} />++ )}</td></tr>)}diff --cc web/features/multi-user/components/LearnerProfileEditor.tsxindex 000000000,81815689a..32e15773bmode 000000,100644..100644--- a/web/features/multi-user/components/LearnerProfileEditor.tsx+++ b/web/features/multi-user/components/LearnerProfileEditor.tsx@@@ -1,0 -1,98 +1,113 @@@+ "use client";++ import { useEffect, useState } from "react";+ import { Check, Loader2 } from "lucide-react";+ import { useTranslation } from "react-i18next";+ import {+ getLearnerProfile,+ setLearnerProfile,+ type LearnerProfile,+ } from "@/lib/admin-api";++ const fields: Array<keyof LearnerProfile> = [+ "age",+ "grade_level",+ "curriculum",+ "language",+ "reading_level",+ "explanation_style",+ ];+++const fieldLabels: Record<keyof LearnerProfile, string> = {++ age: "Age",++ grade_level: "Grade level",++ curriculum: "Curriculum",++ language: "Preferred language",++ reading_level: "Reading level",++ explanation_style: "Explanation style",++};+++ export function LearnerProfileEditor({ username }: { username: string }) {+ const { t } = useTranslation();+ const [profile, setProfile] = useState<LearnerProfile>({});+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [message, setMessage] = useState("");++ useEffect(() => {+ let active = true;+ void getLearnerProfile(username)+ .then((value) => {+ if (active) setProfile(value ?? {});+ })+ .catch(() => {+ if (active) setMessage(t("Failed to load learner profile"));+ })+ .finally(() => {+ if (active) setLoading(false);+ });+ return () => {+ active = false;+ };+ }, [t, username]);++ async function save() {+ setSaving(true);+ setMessage("");+ try {- await setLearnerProfile(username, profile);++ const updated = await setLearnerProfile(username, profile);++ setProfile(updated ?? {});+ setMessage(t("Saved"));+ } catch (error) {+ setMessage(error instanceof Error ? error.message : t("Failed to save learner profile"));+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="border-t border-[var(--border)] bg-[var(--background)]/40 px-5 py-4">+ <div className="mb-3 flex items-center justify-between gap-3">+ <div>+ <h3 className="text-sm font-medium text-[var(--foreground)]">{t("Learner Profile")}</h3>+ <p className="text-xs text-[var(--muted-foreground)]">{t("Adapt explanations to this learner")}</p>+ </div>+ <button+ type="button"+ onClick={() => void save()}+ disabled={loading || saving}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-xs text-[var(--foreground)] disabled:opacity-50"+ >+ {saving ? <Loader2 size={13} className="animate-spin" /> : <Check size={13} />}+ {t("Save")}+ </button>+ </div>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">+ {fields.map((field) => (+ <label key={field} className="text-xs text-[var(--muted-foreground)]">- {t(field === "grade_level" ? "Grade level" : field === "explanation_style" ? "Explanation style" : field.replaceAll("_", " "))}++ {t(fieldLabels[field])}+ <input+ value={profile[field] ?? ""}+ onChange={(event) =>+ setProfile((current) => ({+ ...current,- [field]: field === "age" ? (event.target.value ? Number(event.target.value) : undefined) : event.target.value,++ [field]:++ field === "age"++ ? event.target.value++ ? Number(event.target.value)++ : undefined++ : event.target.value || undefined,+ }))+ }+ type={field === "age" ? "number" : "text"}+ min={field === "age" ? 3 : undefined}+ max={field === "age" ? 120 : undefined}+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ ))}+ </div>+ {message && <p className="mt-2 text-xs text-[var(--muted-foreground)]">{message}</p>}+ </div>+ );+ }diff --cc web/locales/en/app.jsonindex 71b5b1880,859561aab..5838d8025--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -197,6 -193,12 +197,16 @@@"Loading conversation": "Loading conversation…","Still loading…": "Still loading…","Save": "Save",+ "Learner Profile": "Learner Profile",+ "Adapt explanations to this learner": "Adapt explanations to this learner",+ "Failed to load learner profile": "Failed to load learner profile",+ "Failed to save learner profile": "Failed to save learner profile",++ "Age": "Age",+ "Grade level": "Grade level",++ "Curriculum": "Curriculum",++ "Preferred language": "Preferred language",++ "Reading level": "Reading level",+ "Explanation style": "Explanation style","Cancel": "Cancel","Error": "Error","Success": "Success",diff --cc web/locales/zh/app.jsonindex 7e92bac95,d08c870bd..4d5ed25c2--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -197,6 -193,12 +197,16 @@@"Loading conversation": "加载对话中…","Still loading…": "仍在加载中…","Save": "保存",+ "Learner Profile": "学习者档案",+ "Adapt explanations to this learner": "根据该学习者调整讲解",+ "Failed to load learner profile": "加载学习者档案失败",+ "Failed to save learner profile": "保存学习者档案失败",++ "Age": "年龄",+ "Grade level": "年级",++ "Curriculum": "课程体系",++ "Preferred language": "偏好语言",++ "Reading level": "阅读水平",+ "Explanation style": "讲解风格","Cancel": "取消","Error": "错误","Success": "成功",