From 93d1a80310362365e6cd9875d01bd304fee790fb Mon Sep 17 00:00:00 2001 From: XZH Date: Sun, 30 Aug 2026 17:15:01 -0700 Subject: [PATCH 1/3] feat(learner): add account-scoped learner profiles --- deeptutor/agents/chat/prompt_blocks.py | 3 ++ deeptutor/api/routers/auth.py | 44 ++++++++++++++++++- deeptutor/multi_user/identity.py | 16 +++++++ deeptutor/multi_user/learner_profile.py | 50 ++++++++++++++++++++++ deeptutor/services/session/turn_runtime.py | 10 +++++ tests/multi_user/test_learner_profile.py | 45 +++++++++++++++++++ 6 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 deeptutor/multi_user/learner_profile.py create mode 100644 tests/multi_user/test_learner_profile.py 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 50295deae..5df4e7999 100644 --- a/deeptutor/api/routers/auth.py +++ b/deeptutor/api/routers/auth.py @@ -18,7 +18,7 @@ from fastapi import ( status, ) from fastapi.responses import FileResponse, HTMLResponse -from pydantic import BaseModel, field_validator +from pydantic import BaseModel, Field, field_validator from deeptutor.services.config import load_auth_settings @@ -47,6 +47,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 @@ -156,6 +157,15 @@ class UserInfo(BaseModel): avatar: str = "" +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. @@ -755,6 +765,38 @@ 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": + 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.learner_profile import normalize_profile + + 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") + 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, diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py index 47e68484f..5e2a53f20 100644 --- a/deeptutor/multi_user/identity.py +++ b/deeptutor/multi_user/identity.py @@ -20,6 +20,7 @@ from .book_permission import ( normalize_book_permission, public_permission_dict, ) +from .learner_profile import normalize_profile from .models import Role from .paths import PROJECT_ROOT, SYSTEM_ROOT, migrate_legacy_multi_user_tree @@ -80,6 +81,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 @@ -238,6 +241,7 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[ "disabled": bool(existing.get("disabled", False)), "avatar": str(existing.get("avatar") or ""), "book_permission": canonical_book_permission(existing.get("book_permission")), + "learner_profile": normalize_profile(existing.get("learner_profile")), } users[username] = record _write_users(users) @@ -275,6 +279,18 @@ def get_user_by_id(user_id: str) -> tuple[str, dict[str, Any]] | None: return None +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": + 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/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py index e221419ee..b384b49fa 100644 --- a/deeptutor/services/session/turn_runtime.py +++ b/deeptutor/services/session/turn_runtime.py @@ -2464,6 +2464,15 @@ 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) + learner_profile_prompt = prompt_block( + account[1].get("learner_profile") if account else None + ) requested_persona = str(payload.get("persona") or "").strip() persona_context = "" if requested_persona: @@ -2795,6 +2804,7 @@ class TurnRuntimeManager: "book_references": book_references, "course_id": str(payload.get("course_id") or ""), "course_conventions": str(payload.get("course_conventions") or ""), + "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..56329bc0a --- /dev/null +++ b/tests/multi_user/test_learner_profile.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +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 From 545c3610d886f941f61eaecd056cab683f6a6fae Mon Sep 17 00:00:00 2001 From: XZH Date: Sun, 30 Aug 2026 17:20:15 -0700 Subject: [PATCH 2/3] feat(learner): expose learner profile controls --- web/app/(admin)/admin/users/page.tsx | 2 + .../components/LearnerProfileEditor.tsx | 98 +++++++++++++++++++ web/lib/admin-api.ts | 38 +++++++ web/locales/en/app.json | 6 ++ web/locales/zh/app.json | 6 ++ 5 files changed, 150 insertions(+) create mode 100644 web/features/multi-user/components/LearnerProfileEditor.tsx diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsx index 0a3901951..10eaf51cb 100644 --- a/web/app/(admin)/admin/users/page.tsx +++ b/web/app/(admin)/admin/users/page.tsx @@ -13,6 +13,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"; @@ -456,6 +457,7 @@ export default function AdminUsersPage() { + )} diff --git a/web/features/multi-user/components/LearnerProfileEditor.tsx b/web/features/multi-user/components/LearnerProfileEditor.tsx new file mode 100644 index 000000000..81815689a --- /dev/null +++ b/web/features/multi-user/components/LearnerProfileEditor.tsx @@ -0,0 +1,98 @@ +"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", +]; + +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 { + await setLearnerProfile(username, profile); + 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 193ea8296..65d95851f 100644 --- a/web/lib/admin-api.ts +++ b/web/lib/admin-api.ts @@ -15,6 +15,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 125449c60..859561aab 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -193,6 +193,12 @@ "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", + "Grade level": "Grade 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 d3171771f..d08c870bd 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -193,6 +193,12 @@ "Loading conversation": "加载对话中…", "Still loading…": "仍在加载中…", "Save": "保存", + "Learner Profile": "学习者档案", + "Adapt explanations to this learner": "根据该学习者调整讲解", + "Failed to load learner profile": "加载学习者档案失败", + "Failed to save learner profile": "保存学习者档案失败", + "Grade level": "年级", + "Explanation style": "讲解风格", "Cancel": "取消", "Error": "错误", "Success": "成功", From 0852479334b24315a4974405db25abd60758abc8 Mon Sep 17 00:00:00 2001 From: XZH Date: Sun, 30 Aug 2026 17:21:29 -0700 Subject: [PATCH 3/3] fix(auth): expose learner profile store helpers --- deeptutor/services/auth.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/deeptutor/services/auth.py b/deeptutor/services/auth.py index 7afdd7884..475a7972b 100644 --- a/deeptutor/services/auth.py +++ b/deeptutor/services/auth.py @@ -212,6 +212,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 # ---------------------------------------------------------------------------