diff --git a/deeptutor/agents/chat/prompt_blocks.py b/deeptutor/agents/chat/prompt_blocks.py index e9ef56afc..4bd329c49 100644 --- a/deeptutor/agents/chat/prompt_blocks.py +++ b/deeptutor/agents/chat/prompt_blocks.py @@ -88,6 +88,9 @@ class ChatPromptAssembler: course_conventions = str((context.metadata or {}).get("course_conventions") or "") if course_conventions: blocks.append(PromptBlock("course_conventions", course_conventions)) + learner_profile = str((context.metadata or {}).get("learner_profile_prompt") or "") + if learner_profile: + blocks.append(PromptBlock("learner_profile", learner_profile)) if context.persona_context: blocks.append(PromptBlock("persona_style", context.persona_context)) partner_policy = self._partner_turn_policy(context) diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py index f0f1885ce..123c869c1 100644 --- a/deeptutor/api/routers/auth.py +++ b/deeptutor/api/routers/auth.py @@ -59,6 +59,7 @@ from deeptutor.services.auth import ( list_users, register_pb, set_avatar, + set_learner_profile, set_role, ) from deeptutor.services.codex_auth.contracts import CodexAuthError @@ -195,6 +196,15 @@ class UserInfo(BaseModel): 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:") are # managed exclusively by the upload endpoint so users cannot point their # avatar at a file that was never validated. @@ -984,6 +994,53 @@ async def get_users(_: TokenPayload = Depends(require_admin)) -> list[UserInfo]: return [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" + 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) + 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: AdminCreateUserRequest, diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py index a470efc16..5669872fb 100644 --- a/deeptutor/multi_user/identity.py +++ b/deeptutor/multi_user/identity.py @@ -21,6 +21,7 @@ from .book_permission import ( normalize_book_permission, public_permission_dict, ) +from .learner_profile import normalize_profile from .models import AccountPreset, Role from .paths import PROJECT_ROOT, SYSTEM_ROOT, migrate_legacy_multi_user_tree @@ -85,6 +86,8 @@ def _canonical_record( } if "book_permission" in value: record["book_permission"] = canonical_book_permission(value.get("book_permission")) + if "learner_profile" in value: + record["learner_profile"] = normalize_profile(value.get("learner_profile")) return record @@ -253,6 +256,7 @@ def save_user( "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 +295,30 @@ def get_user_by_id(user_id: str) -> tuple[str, dict[str, Any]] | None: return 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" + 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 --git a/deeptutor/multi_user/learner_profile.py b/deeptutor/multi_user/learner_profile.py new file mode 100644 index 000000000..7732b76d0 --- /dev/null +++ b/deeptutor/multi_user/learner_profile.py @@ -0,0 +1,50 @@ +"""Validated, account-scoped learner profile helpers.""" + +from __future__ import annotations + +from typing import Any + +_FIELDS = ("age", "grade_level", "curriculum", "language", "reading_level", "explanation_style") +_MAX_TEXT = 80 + + +def normalize_profile(value: Any) -> dict[str, Any] | None: + if value is None: + return None + if not isinstance(value, dict): + raise ValueError("learner_profile must be an object") + result: dict[str, Any] = {"schema_version": 1} + age = value.get("age") + if age is not None: + if isinstance(age, bool) or not isinstance(age, int) or not 3 <= age <= 120: + raise ValueError("learner_profile.age must be between 3 and 120") + result["age"] = age + for field in _FIELDS[1:]: + raw = value.get(field) + if raw is not None: + text = str(raw).strip() + if not text or len(text) > _MAX_TEXT: + raise ValueError(f"learner_profile.{field} must be 1-{_MAX_TEXT} characters") + result[field] = text + if len(result) == 1: + return None + return result + + +def prompt_block(profile: dict[str, Any] | None) -> str: + normalized = normalize_profile(profile) + if not normalized: + return "" + labels = { + "age": "Age", + "grade_level": "Grade level", + "curriculum": "Curriculum", + "language": "Preferred language", + "reading_level": "Reading level", + "explanation_style": "Explanation style", + } + lines = [ + "Use this trusted learner profile to adapt explanations, prerequisites, examples, and checks for understanding." + ] + lines.extend(f"- {labels[key]}: {normalized[key]}" for key in labels if key in normalized) + return "\n".join(lines) diff --git a/deeptutor/services/auth.py b/deeptutor/services/auth.py index da5427fb4..291859be6 100644 --- a/deeptutor/services/auth.py +++ b/deeptutor/services/auth.py @@ -236,6 +236,20 @@ def get_user_info(username: str) -> dict | None: return None +def get_learner_profile(username: str) -> dict[str, Any] | None: + """Return the structured learner profile for an existing account.""" + from deeptutor.multi_user.identity import get_learner_profile as _get_profile + + return _get_profile(username) + + +def set_learner_profile(username: str, profile: dict[str, Any] | None) -> dict[str, Any] | None: + """Replace the structured learner profile for an existing account.""" + from deeptutor.multi_user.identity import set_learner_profile as _set_profile + + return _set_profile(username, profile) + + # --------------------------------------------------------------------------- # JWT # --------------------------------------------------------------------------- diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py index a3ea6b637..e28c273d6 100644 --- a/deeptutor/services/session/turn_runtime.py +++ b/deeptutor/services/session/turn_runtime.py @@ -2577,6 +2577,14 @@ class TurnRuntimeManager: from deeptutor.services.skill.service import SkillService, render_skills_manifest current_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) + 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: @@ -2911,6 +2919,7 @@ class TurnRuntimeManager: "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 --git a/tests/multi_user/test_learner_profile.py b/tests/multi_user/test_learner_profile.py new file mode 100644 index 000000000..a98af18db --- /dev/null +++ b/tests/multi_user/test_learner_profile.py @@ -0,0 +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 None diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsx index 46b50aef9..d151c5e7c 100644 --- a/web/app/(admin)/admin/users/page.tsx +++ b/web/app/(admin)/admin/users/page.tsx @@ -14,6 +14,7 @@ import { } from "@/lib/admin-api"; import { GrantEditor } from "@/features/multi-user/components/GrantEditor"; import { BookPermissionEditor } from "@/features/multi-user/components/BookPermissionEditor"; +import { LearnerProfileEditor } from "@/features/multi-user/components/LearnerProfileEditor"; import { UserAvatar } from "@/components/UserAvatar"; import { ConfirmDialog } from "@/components/ui/ConfirmDialog"; import { filterUsersByQuery } from "@/lib/admin-users"; @@ -470,6 +471,9 @@ export default function AdminUsersPage() { lockLearningPolicy={user.preset === "learner"} /> + {user.preset === "learner" && ( + + )} )} diff --git a/web/features/multi-user/components/LearnerProfileEditor.tsx b/web/features/multi-user/components/LearnerProfileEditor.tsx new file mode 100644 index 000000000..32e15773b --- /dev/null +++ b/web/features/multi-user/components/LearnerProfileEditor.tsx @@ -0,0 +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 = [ + "age", + "grade_level", + "curriculum", + "language", + "reading_level", + "explanation_style", +]; + +const fieldLabels: Record = { + 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({}); + 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 { + 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 ( +
+
+
+

{t("Learner Profile")}

+

{t("Adapt explanations to this learner")}

+
+ +
+
+ {fields.map((field) => ( + + ))} +
+ {message &&

{message}

} +
+ ); +} diff --git a/web/lib/admin-api.ts b/web/lib/admin-api.ts index 9520f7bed..e2fb39795 100644 --- a/web/lib/admin-api.ts +++ b/web/lib/admin-api.ts @@ -18,6 +18,44 @@ export interface UserRecord { }; } +export interface LearnerProfile { + age?: number; + grade_level?: string; + curriculum?: string; + language?: string; + reading_level?: string; + explanation_style?: string; +} + +export async function getLearnerProfile(username: string): Promise { + const res = await apiFetch( + apiUrl(`/api/v1/auth/users/${encodeURIComponent(username)}/learner-profile`), + ); + if (!res.ok) throw new Error("Failed to fetch learner profile"); + const data = (await res.json()) as { learner_profile?: LearnerProfile | null }; + return data.learner_profile ?? null; +} + +export async function setLearnerProfile( + username: string, + profile: LearnerProfile, +): Promise { + const res = await apiFetch( + apiUrl(`/api/v1/auth/users/${encodeURIComponent(username)}/learner-profile`), + { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(profile), + }, + ); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.detail ?? "Failed to save learner profile"); + } + const data = (await res.json()) as { learner_profile?: LearnerProfile | null }; + return data.learner_profile ?? null; +} + export async function listUsers(): Promise { const res = await apiFetch(apiUrl("/api/v1/auth/users")); if (!res.ok) throw new Error("Failed to fetch users"); diff --git a/web/locales/en/app.json b/web/locales/en/app.json index 71b5b1880..5838d8025 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -197,6 +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 --git a/web/locales/zh/app.json b/web/locales/zh/app.json index 7e92bac95..4d5ed25c2 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -197,6 +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": "成功",