DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: user profile page with avatar (icons + image upload)
Ilia Avdeev7901368bb257
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.pyindex a03afd778..6f3136e46 100644--- a/deeptutor/api/routers/auth.py+++ b/deeptutor/api/routers/auth.py@@ -1,18 +1,22 @@-"""Auth router — login, logout, status, registration, and user-management endpoints."""+"""Auth router — login, logout, status, registration, profile, and user-management endpoints."""from contextvars import Token as _CtxTokenimport logging+import refrom fastapi import (APIRouter,Cookie,Depends,+ File,Header,HTTPException,Response,+ UploadFile,WebSocket,status,)+from fastapi.responses import FileResponsefrom pydantic import BaseModel, field_validatorfrom deeptutor.services.config import load_auth_settings@@ -37,9 +41,11 @@ from deeptutor.services.auth import (create_token,decode_token,delete_user,+ get_user_info,is_first_user,list_users,register_pb,+ set_avatar,set_role,)@@ -115,16 +121,43 @@ class AuthStatusResponse(BaseModel):username: str | None = Nonerole: str | None = Noneis_admin: bool = False+ avatar: str = ""class UserInfo(BaseModel):- """Single user record returned by the GET /users endpoint."""+ """Single user record returned by the GET /users and /profile endpoints."""id: str = ""username: strrole: strcreated_at: strdisabled: bool = False+ avatar: str = ""+++# 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.+_ICON_MARKER_RE = re.compile(r"^icon:[a-z0-9-]{1,32}:[a-z0-9-]{1,32}$")++# User ids are generated as "u_<uuid hex>" (plus the "local-admin" /+# "env-admin" sentinels); reject anything else before it reaches the+# filesystem layer.+_USER_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")+++class UpdateProfileRequest(BaseModel):+ """Payload for the PUT /profile endpoint."""++ avatar: str++ @field_validator("avatar")+ @classmethod+ def avatar_valid(cls, v: str) -> str:+ v = v.strip()+ if v and not _ICON_MARKER_RE.match(v):+ raise ValueError("Avatar must be empty or 'icon:<name>:<color>'")+ return v# ---------------------------------------------------------------------------@@ -334,6 +367,11 @@ async def auth_status(token = _extract_token(authorization, dt_token)payload = decode_token(token) if token else None+ avatar = ""+ if payload is not None:+ info = get_user_info(payload.username)+ if info:+ avatar = str(info.get("avatar") or "")return AuthStatusResponse(enabled=True,authenticated=payload is not None,@@ -341,6 +379,7 @@ async def auth_status(username=payload.username if payload else None,role=payload.role if payload else None,is_admin=payload.role == "admin" if payload else False,+ avatar=avatar,)@@ -492,6 +531,179 @@ async def check_is_first_user() -> dict:return {"is_first_user": is_first_user() if AUTH_ENABLED else False}+# ---------------------------------------------------------------------------+# Profile endpoints (any authenticated user, self-service)+# ---------------------------------------------------------------------------++_AVATAR_MAX_BYTES = 1 * 1024 * 1024+_AVATAR_MEDIA_TYPES = {"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}+++def _sniff_image(data: bytes) -> str | None:+ """Detect a supported raster image format from its magic bytes.++ The uploaded filename and Content-Type are attacker-controlled, so the+ stored extension (and the media type served back) is derived from the+ bytes alone. SVG is deliberately unsupported — serving user-supplied SVG+ is a stored-XSS vector.+ """+ if data[:8] == b"\x89PNG\r\n\x1a\n":+ return "png"+ if data[:3] == b"\xff\xd8\xff":+ return "jpg"+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":+ return "webp"+ return None+++def _require_profile_identity(payload: TokenPayload | None) -> TokenPayload:+ """Shared guard for the self-service profile endpoints."""+ if not AUTH_ENABLED or payload is None:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Auth is disabled — profiles are not available.",+ )+ return payload++[email protected]("/profile", response_model=UserInfo)+async def get_profile(+ payload: TokenPayload | None = Depends(require_auth),+) -> UserInfo:+ """Return the current user's own account info."""+ current = _require_profile_identity(payload)+ info = get_user_info(current.username)+ if info is None:+ # PocketBase-backed identities have no local record; fall back to the+ # token claims so the profile page still renders.+ return UserInfo(+ id=current.user_id,+ username=current.username,+ role=current.role,+ created_at="",+ )+ return UserInfo(**info)++[email protected]("/profile")+async def update_profile(+ body: UpdateProfileRequest,+ payload: TokenPayload | None = Depends(require_auth),+) -> dict:+ """Update the current user's own avatar marker (icon choice or reset).++ Only the validated ``icon:<name>:<color>`` form (or empty string) is+ accepted here; ``img:`` markers are owned by the upload endpoint.+ """+ current = _require_profile_identity(payload)+ if not set_avatar(current.username, body.avatar):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ # The marker no longer references an uploaded image, so drop the file.+ from deeptutor.multi_user.identity import delete_avatar_file++ if current.user_id and _USER_ID_RE.match(current.user_id):+ delete_avatar_file(current.user_id)+ return {"ok": True, "avatar": body.avatar}++[email protected]("/profile/avatar")+async def upload_avatar(+ file: UploadFile = File(...),+ payload: TokenPayload | None = Depends(require_auth),+) -> dict:+ """Upload an avatar image for the current user.++ The client is expected to crop/resize before uploading; the server only+ enforces a size cap and validates the format by magic bytes. Not available+ in PocketBase mode (those identities have no local user record).+ """+ current = _require_profile_identity(payload)+ if POCKETBASE_ENABLED:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Avatar upload is not available in PocketBase mode.",+ )+ if not current.user_id or not _USER_ID_RE.match(current.user_id):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="Cannot store an avatar for this account.",+ )+ info = get_user_info(current.username)+ if info is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")++ data = await file.read(_AVATAR_MAX_BYTES + 1)+ if len(data) > _AVATAR_MAX_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail="Avatar image is too large (max 1 MB).",+ )+ ext = _sniff_image(data)+ if ext is None:+ raise HTTPException(+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,+ detail="Avatar must be a PNG, JPEG or WebP image.",+ )++ from deeptutor.multi_user.identity import save_avatar_file++ # Bump the version embedded in the marker so clients cache-bust the URL.+ previous = str(info.get("avatar") or "")+ version = 1+ if previous.startswith("img:"):+ try:+ version = int(previous.split(":", 1)[1]) + 1+ except ValueError:+ version = 1+ marker = f"img:{version}"++ save_avatar_file(current.user_id, data, ext)+ if not set_avatar(current.username, marker):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ logger.info(f"User '{current.username}' uploaded a new avatar ({ext}, {len(data)} bytes)")+ return {"ok": True, "avatar": marker}++[email protected]("/profile/avatar")+async def remove_avatar(+ payload: TokenPayload | None = Depends(require_auth),+) -> dict:+ """Remove the current user's uploaded avatar image and reset the marker."""+ current = _require_profile_identity(payload)+ from deeptutor.multi_user.identity import delete_avatar_file++ if current.user_id and _USER_ID_RE.match(current.user_id):+ delete_avatar_file(current.user_id)+ set_avatar(current.username, "")+ return {"ok": True, "avatar": ""}++[email protected]("/avatar/{user_id}")+async def get_avatar_image(+ user_id: str,+ _: TokenPayload | None = Depends(require_auth),+) -> FileResponse:+ """Serve a stored avatar image. Any authenticated user may view avatars+ (they appear in the admin table and next to the viewer's own profile)."""+ if not _USER_ID_RE.match(user_id):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Avatar not found")++ from deeptutor.multi_user.identity import get_avatar_file++ target = get_avatar_file(user_id)+ if target is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Avatar not found")++ media_type = _AVATAR_MEDIA_TYPES.get(target.suffix.lstrip("."), "application/octet-stream")+ headers = {+ # Private user content; the marker version in the URL handles busting.+ "Cache-Control": "private, max-age=86400",+ "X-Content-Type-Options": "nosniff",+ "Content-Disposition": "inline",+ }+ return FileResponse(path=str(target), media_type=media_type, headers=headers)++# ---------------------------------------------------------------------------# Admin-only endpoints# ---------------------------------------------------------------------------@@ -579,10 +791,19 @@ async def remove_user(detail="You cannot delete your own account",)+ # Capture the id before the record disappears so the avatar file can go too.+ info = get_user_info(username)+removed = delete_user(username)if not removed:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ user_id = str(info.get("id") or "") if info else ""+ if user_id and _USER_ID_RE.match(user_id):+ from deeptutor.multi_user.identity import delete_avatar_file++ delete_avatar_file(user_id)+logger.info(f"Admin '{current.username if current else 'local'}' deleted user '{username}'")return {"ok": True}diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.pyindex 440c3abc8..989c76518 100644--- a/deeptutor/multi_user/identity.py+++ b/deeptutor/multi_user/identity.py@@ -51,6 +51,7 @@ def _canonical_record("role": default_role,"created_at": utc_now(),"disabled": False,+ "avatar": "",}if not isinstance(value, dict):return None@@ -66,6 +67,7 @@ def _canonical_record("role": role,"created_at": str(value.get("created_at") or utc_now()),"disabled": bool(value.get("disabled", False)),+ "avatar": str(value.get("avatar") or ""),}@@ -181,6 +183,7 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict["role": effective_role,"created_at": str(existing.get("created_at") or utc_now()),"disabled": bool(existing.get("disabled", False)),+ "avatar": str(existing.get("avatar") or ""),}users[username] = record_write_users(users)@@ -198,6 +201,7 @@ def list_user_info( # nosec B107 - empty defaults mean "no env fallback supplie"role": record.get("role", "user"),"created_at": record.get("created_at", ""),"disabled": bool(record.get("disabled", False)),+ "avatar": str(record.get("avatar") or ""),}for username, record in load_users(env_username, env_password_hash).items()]@@ -225,6 +229,64 @@ def delete_user(username: str) -> bool:return True+def set_avatar(username: str, avatar: str) -> bool:+ """Update the avatar marker for an existing user. Returns True on success."""+ if not USERS_FILE.exists():+ return False+ with _USERS_WRITE_LOCK:+ users = load_users()+ if username not in users:+ return False+ users[username]["avatar"] = avatar+ _write_users(users)+ return True+++# ---------------------------------------------------------------------------+# Avatar image files — stored next to the user store, keyed by user id+# ---------------------------------------------------------------------------++# Extensions are derived from server-side content sniffing, never from the+# uploaded filename, so this list is also the full set of files we may serve.+AVATAR_EXTENSIONS = ("png", "jpg", "webp")+++def _avatar_dir() -> Path:+ # Resolved lazily so tests that monkeypatch AUTH_DIR keep avatars isolated.+ return AUTH_DIR / "avatars"+++def get_avatar_file(user_id: str) -> Path | None:+ """Return the stored avatar image for ``user_id``, or None."""+ for ext in AVATAR_EXTENSIONS:+ candidate = _avatar_dir() / f"{user_id}.{ext}"+ if candidate.is_file():+ return candidate+ return None+++def save_avatar_file(user_id: str, data: bytes, ext: str) -> Path:+ """Atomically persist an avatar image, replacing any previous one."""+ if ext not in AVATAR_EXTENSIONS:+ raise ValueError(f"Unsupported avatar extension: {ext!r}")+ directory = _avatar_dir()+ directory.mkdir(parents=True, exist_ok=True)+ target = directory / f"{user_id}.{ext}"+ tmp = directory / f"{user_id}.{ext}.tmp"+ tmp.write_bytes(data)+ tmp.replace(target)+ # A re-upload may change the extension; drop stale siblings.+ for other in AVATAR_EXTENSIONS:+ if other != ext:+ (directory / f"{user_id}.{other}").unlink(missing_ok=True)+ return target+++def delete_avatar_file(user_id: str) -> None:+ for ext in AVATAR_EXTENSIONS:+ (_avatar_dir() / f"{user_id}.{ext}").unlink(missing_ok=True)++def set_role(username: str, role: Role) -> bool:if role not in {"admin", "user"}:raise ValueError("role must be 'admin' or 'user'")diff --git a/deeptutor/multi_user/models.py b/deeptutor/multi_user/models.pyindex 052ce5b75..417866526 100644--- a/deeptutor/multi_user/models.py+++ b/deeptutor/multi_user/models.py@@ -17,6 +17,10 @@ class UserRecord:role: Role = "user"created_at: str = ""disabled: bool = False+ # Avatar marker: "" (deterministic fallback), "icon:<name>:<color>" for a+ # picked icon, or "img:<version>" when the user uploaded an image (the+ # version is bumped on every upload so clients can cache-bust).+ avatar: str = ""def public_dict(self) -> dict[str, Any]:return {@@ -25,6 +29,7 @@ class UserRecord:"role": self.role,"created_at": self.created_at,"disabled": self.disabled,+ "avatar": self.avatar,}diff --git a/deeptutor/services/auth.py b/deeptutor/services/auth.pyindex cdb2e7ddd..7afdd7884 100644--- a/deeptutor/services/auth.py+++ b/deeptutor/services/auth.py@@ -111,6 +111,7 @@ def _make_user_record(hashed: str, role: str = "user", created_at: str = "") ->"role": role,"created_at": created_at or datetime.now(timezone.utc).isoformat(),"disabled": False,+ "avatar": "",}@@ -188,6 +189,29 @@ def set_role(username: str, role: str) -> bool:return True+def set_avatar(username: str, avatar: str) -> bool:+ """+ Update the avatar marker for an existing user. Returns True on success.++ The marker is either '' (deterministic fallback), 'icon:<name>:<color>',+ or 'img:<version>' (managed by the avatar upload endpoint).+ """+ from deeptutor.multi_user.identity import set_avatar as _set_avatar++ if not _set_avatar(username, avatar):+ return False+ logger.info("User '%s' avatar updated", username)+ return True+++def get_user_info(username: str) -> dict | None:+ """Return the public info dict for a single user, or None if unknown."""+ for item in list_users():+ if item.get("username") == username:+ return item+ return None++# ---------------------------------------------------------------------------# JWT# ---------------------------------------------------------------------------diff --git a/web/app/(utility)/profile/page.tsx b/web/app/(utility)/profile/page.tsxnew file mode 100644index 000000000..7182ca076--- /dev/null+++ b/web/app/(utility)/profile/page.tsx@@ -0,0 +1,406 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { createElement } from "react";+import { ArrowLeft, ImageUp, LogOut, ShieldCheck, Trash2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { AUTH_ENABLED, fetchAuthStatus, logout } from "@/lib/auth";+import {+ getProfile,+ removeAvatarImage,+ setAvatarMarker,+ uploadAvatarImage,+ type ProfileInfo,+} from "@/lib/profile-api";+import {+ AVATAR_COLOR_NAMES,+ AVATAR_COLORS,+ AVATAR_ICON_NAMES,+ AVATAR_ICONS,+ fallbackAvatarFor,+ UserAvatar,+} from "@/components/UserAvatar";+import { parseAvatarMarker } from "@/lib/avatar";+import { formatDate, type Language } from "@/lib/datetime";++const AVATAR_OUTPUT_SIZE = 256;+// Decoding a huge photo just to throw away most pixels wastes memory; the+// server enforces its own 1 MB cap on the (much smaller) cropped result.+const MAX_SOURCE_BYTES = 20 * 1024 * 1024;++/** Center-crop to a square and downscale; canvas re-encode also strips EXIF. */+async function cropToSquareBlob(file: File): Promise<Blob> {+ let source: CanvasImageSource;+ let width: number;+ let height: number;+ try {+ const bitmap = await createImageBitmap(file);+ source = bitmap;+ width = bitmap.width;+ height = bitmap.height;+ } catch {+ // Older Safari: fall back to decoding via an <img> element.+ const url = URL.createObjectURL(file);+ try {+ const image = await new Promise<HTMLImageElement>((resolve, reject) => {+ const el = new Image();+ el.onload = () => resolve(el);+ el.onerror = () => reject(new Error("Could not decode image"));+ el.src = url;+ });+ source = image;+ width = image.naturalWidth;+ height = image.naturalHeight;+ } finally {+ URL.revokeObjectURL(url);+ }+ }+ if (!width || !height) throw new Error("Could not decode image");++ const side = Math.min(width, height);+ const canvas = document.createElement("canvas");+ canvas.width = AVATAR_OUTPUT_SIZE;+ canvas.height = AVATAR_OUTPUT_SIZE;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("Could not decode image");+ ctx.drawImage(+ source,+ (width - side) / 2,+ (height - side) / 2,+ side,+ side,+ 0,+ 0,+ AVATAR_OUTPUT_SIZE,+ AVATAR_OUTPUT_SIZE,+ );+ // Release the decoder/GPU memory now instead of waiting for GC.+ if (typeof ImageBitmap !== "undefined" && source instanceof ImageBitmap) {+ source.close();+ }++ const toBlob = (type: string, quality?: number) =>+ new Promise<Blob | null>((resolve) =>+ canvas.toBlob(resolve, type, quality),+ );+ // WebP keeps avatars tiny; browsers without a WebP encoder return null.+ const blob =+ (await toBlob("image/webp", 0.85)) ?? (await toBlob("image/png"));+ if (!blob) throw new Error("Could not encode image");+ return blob;+}++export default function ProfilePage() {+ const router = useRouter();+ const { t, i18n } = useTranslation();+ const [profile, setProfile] = useState<ProfileInfo | null>(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ if (!AUTH_ENABLED) {+ router.replace("/");+ return;+ }+ let cancelled = false;+ (async () => {+ const status = await fetchAuthStatus();+ if (cancelled) return;+ if (!status?.authenticated) {+ router.replace("/login");+ return;+ }+ try {+ const info = await getProfile();+ if (!cancelled) setProfile(info);+ } catch {+ if (!cancelled) setError(t("Failed to load profile"));+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [router, t]);++ const applyMarker = useCallback(async (marker: string) => {+ setBusy(true);+ setError(null);+ try {+ const saved = await setAvatarMarker(marker);+ setProfile((prev) => (prev ? { ...prev, avatar: saved } : prev));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ }, []);++ const handleUpload = useCallback(+ async (file: File) => {+ setBusy(true);+ setError(null);+ try {+ if (file.size > MAX_SOURCE_BYTES) {+ throw new Error(t("Image is too large"));+ }+ const blob = await cropToSquareBlob(file);+ const marker = await uploadAvatarImage(blob);+ setProfile((prev) => (prev ? { ...prev, avatar: marker } : prev));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ if (fileInputRef.current) fileInputRef.current.value = "";+ }+ },+ [t],+ );++ const handleRemoveImage = useCallback(async () => {+ setBusy(true);+ setError(null);+ try {+ await removeAvatarImage();+ setProfile((prev) => (prev ? { ...prev, avatar: "" } : prev));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ }, []);++ const handleSignOut = useCallback(async () => {+ await logout();+ router.replace("/login");+ }, [router]);++ if (!AUTH_ENABLED) return null;++ const descriptor = parseAvatarMarker(profile?.avatar);+ const hasImage = descriptor.kind === "image";+ const fallback = fallbackAvatarFor(profile?.username ?? "");+ const selectedIcon =+ descriptor.kind === "icon"+ ? descriptor.icon+ : hasImage+ ? null+ : fallback.icon;+ const selectedColor =+ descriptor.kind === "icon"+ ? descriptor.color+ : hasImage+ ? null+ : fallback.color;+ const isAdmin = profile?.role === "admin";+ const lang: Language = i18n.language?.startsWith("zh") ? "zh" : "en";+ const joinedDate = profile?.created_at ? new Date(profile.created_at) : null;+ const joined =+ joinedDate && !Number.isNaN(joinedDate.getTime())+ ? formatDate(joinedDate, lang)+ : null;++ return (+ <div className="h-screen overflow-y-auto bg-[var(--background)] px-4 py-10 [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-2xl">+ {/* Header */}+ <div className="mb-8 flex items-center gap-4">+ <Link+ href="/"+ className="flex items-center gap-1.5 text-sm text-[var(--muted-foreground)] hover:text-[var(--foreground)] transition-colors"+ >+ <ArrowLeft size={15} />+ {t("Back")}+ </Link>+ <div className="flex-1">+ <h1 className="text-xl font-semibold text-[var(--foreground)]">+ {t("My profile")}+ </h1>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t("View your account and personalize your avatar")}+ </p>+ </div>+ </div>++ {error && (+ <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600 dark:text-red-400">+ {error}+ </div>+ )}++ {loading ? (+ <div className="flex items-center justify-center rounded-2xl border border-[var(--border)] bg-[var(--card)] py-16 text-sm text-[var(--muted-foreground)] shadow-sm">+ {t("Loading…")}+ </div>+ ) : !profile ? null : (+ <>+ {/* Account card */}+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm">+ <div className="flex items-center gap-5">+ <UserAvatar+ username={profile.username}+ userId={profile.id}+ avatar={profile.avatar}+ role={profile.role}+ size={72}+ />+ <div className="min-w-0">+ <div className="flex items-center gap-2.5">+ <span className="truncate text-lg font-semibold text-[var(--foreground)]">+ {profile.username}+ </span>+ <span+ className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${+ isAdmin+ ? "bg-amber-500/15 text-amber-600 dark:text-amber-400"+ : "bg-[var(--muted)]/70 text-[var(--muted-foreground)]"+ }`}+ >+ {isAdmin && <ShieldCheck size={11} strokeWidth={2} />}+ {isAdmin ? t("Administrator") : t("User")}+ </span>+ </div>+ {joined && (+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ {t("Joined")}: {joined}+ </p>+ )}+ </div>+ </div>+ </div>++ {/* Avatar card */}+ <div className="mt-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm">+ <h2 className="text-sm font-semibold text-[var(--foreground)]">+ {t("Avatar")}+ </h2>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t("Upload a picture or pick an icon")}+ </p>++ <div className="mt-4 flex flex-wrap items-center gap-2.5">+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="hidden"+ onChange={(event) => {+ const file = event.target.files?.[0];+ if (file) void handleUpload(file);+ }}+ />+ <button+ onClick={() => fileInputRef.current?.click()}+ disabled={busy}+ className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm+ border border-[var(--border)] text-[var(--foreground)]+ hover:bg-[var(--background)]/60 disabled:opacity-50 transition-colors"+ >+ <ImageUp size={14} />+ {t("Upload image")}+ </button>+ {hasImage && (+ <button+ onClick={() => void handleRemoveImage()}+ disabled={busy}+ className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm+ border border-[var(--border)] text-[var(--muted-foreground)]+ hover:text-red-500 disabled:opacity-50 transition-colors"+ >+ <Trash2 size={14} />+ {t("Remove photo")}+ </button>+ )}+ </div>++ {/* Icon grid */}+ <div className="mt-5">+ <p className="mb-2 text-xs font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Or pick an icon")}+ </p>+ <div className="flex flex-wrap gap-2">+ {AVATAR_ICON_NAMES.map((name) => {+ const active = !hasImage && name === selectedIcon;+ const color = selectedColor ?? fallback.color;+ return (+ <button+ key={name}+ onClick={() =>+ void applyMarker(`icon:${name}:${color}`)+ }+ disabled={busy}+ aria-label={name}+ aria-pressed={active}+ className={`flex h-10 w-10 items-center justify-center rounded-full text-white transition-all disabled:opacity-50 ${+ active+ ? "ring-2 ring-[var(--foreground)] ring-offset-2 ring-offset-[var(--card)]"+ : "opacity-75 hover:opacity-100"+ }`}+ style={{ backgroundColor: AVATAR_COLORS[color] }}+ >+ {createElement(AVATAR_ICONS[name], {+ size: 18,+ strokeWidth: 1.8,+ })}+ </button>+ );+ })}+ </div>+ <p className="mb-2 mt-4 text-xs font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Color")}+ </p>+ <div className="flex flex-wrap gap-2">+ {AVATAR_COLOR_NAMES.map((name) => {+ const active = !hasImage && name === selectedColor;+ const icon = selectedIcon ?? fallback.icon;+ return (+ <button+ key={name}+ onClick={() => void applyMarker(`icon:${icon}:${name}`)}+ disabled={busy}+ aria-label={name}+ aria-pressed={active}+ className={`h-7 w-7 rounded-full transition-all disabled:opacity-50 ${+ active+ ? "ring-2 ring-[var(--foreground)] ring-offset-2 ring-offset-[var(--card)]"+ : "opacity-75 hover:opacity-100"+ }`}+ style={{ backgroundColor: AVATAR_COLORS[name] }}+ />+ );+ })}+ </div>+ </div>+ </div>++ {/* Sign out card */}+ <div className="mt-4 flex items-center justify-between rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-sm">+ <div>+ <h2 className="text-sm font-semibold text-[var(--foreground)]">+ {t("Sign out")}+ </h2>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t("End your session on this device")}+ </p>+ </div>+ <button+ onClick={() => void handleSignOut()}+ className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm+ border border-red-500/40 text-red-600 dark:text-red-400+ hover:bg-red-500/10 transition-colors"+ >+ <LogOut size={14} />+ {t("Sign out")}+ </button>+ </div>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/web/components/UserAvatar.tsx b/web/components/UserAvatar.tsxnew file mode 100644index 000000000..26b87b65c--- /dev/null+++ b/web/components/UserAvatar.tsx@@ -0,0 +1,179 @@+"use client";++import { createElement, useState } from "react";+import {+ Cherry,+ Cloud,+ Compass,+ Cookie,+ Droplet,+ Feather,+ Flame,+ Heart,+ Leaf,+ Lightbulb,+ Moon,+ Music,+ Shield,+ Sparkles,+ Sprout,+ Star,+ Sun,+ type LucideIcon,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ AVATAR_COLOR_NAMES,+ AVATAR_COLORS,+ AVATAR_ICON_NAMES,+ fallbackAvatarFor,+ parseAvatarMarker,+} from "@/lib/avatar";+import { avatarImageUrl } from "@/lib/profile-api";++/**+ * User avatars. Marker parsing and the deterministic fallback live in+ * lib/avatar.ts (pure, unit-tested); this component maps icon names to+ * lucide components and renders the marker.+ *+ * Admins get an amber ring at every size plus a small shield badge once the+ * avatar is large enough for it to stay legible (>= 40px).+ */++// Must cover every name in AVATAR_ICON_NAMES (lib/avatar.ts).+export const AVATAR_ICONS: Record<string, LucideIcon> = {+ sparkles: Sparkles,+ sprout: Sprout,+ leaf: Leaf,+ feather: Feather,+ cloud: Cloud,+ droplet: Droplet,+ sun: Sun,+ moon: Moon,+ flame: Flame,+ star: Star,+ heart: Heart,+ lightbulb: Lightbulb,+ compass: Compass,+ cherry: Cherry,+ cookie: Cookie,+ music: Music,+};++// Re-exported so picker UIs only need one import site.+export {+ AVATAR_COLOR_NAMES,+ AVATAR_COLORS,+ AVATAR_ICON_NAMES,+ fallbackAvatarFor,+};++const ADMIN_RING_COLOR = "#e0a83c";++interface UserAvatarProps {+ username: string;+ /** Needed to resolve "img:" markers to an image URL. */+ userId?: string;+ /** Avatar marker; empty/undefined renders the deterministic fallback. */+ avatar?: string;+ /** Admins get the amber ring (and a shield badge at size >= 40). */+ role?: string;+ size?: number;+ className?: string;+}++export function UserAvatar({+ username,+ userId,+ avatar = "",+ role,+ size = 28,+ className,+}: UserAvatarProps) {+ const { t } = useTranslation();+ const [imageBroken, setImageBroken] = useState(false);+ // A re-upload changes the marker version; give the new URL a fresh chance.+ // Render-time reset (instead of an effect) per react.dev's "adjusting+ // state when a prop changes" guidance.+ const imageKey = `${userId ?? ""}:${avatar}`;+ const [lastImageKey, setLastImageKey] = useState(imageKey);+ if (imageKey !== lastImageKey) {+ setLastImageKey(imageKey);+ setImageBroken(false);+ }++ const isAdmin = role === "admin";+ const showBadge = isAdmin && size >= 40;+ const descriptor = parseAvatarMarker(avatar);+ const isImage =+ descriptor.kind === "image" && Boolean(userId) && !imageBroken;++ let iconName: string;+ let colorName: string;+ if (descriptor.kind === "icon") {+ iconName = descriptor.icon;+ colorName = descriptor.color;+ } else {+ const fallback = fallbackAvatarFor(username);+ iconName = fallback.icon;+ colorName = fallback.color;+ }++ const ringStyle = isAdmin+ ? {+ outline: `${Math.max(1.5, size / 18)}px solid ${ADMIN_RING_COLOR}`,+ outlineOffset: `${Math.max(1, size / 28)}px`,+ }+ : undefined;+ const adminLabel = t("Administrator");++ return (+ <span+ className={`relative inline-flex shrink-0 ${className ?? ""}`}+ style={{ width: size, height: size }}+ title={isAdmin ? `${username} — ${adminLabel}` : username}+ aria-label={isAdmin ? `${username} (${adminLabel})` : username}+ >+ {isImage ? (+ /* Dynamic backend URL with cookie auth; next/image cannot optimize it. */+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={avatarImageUrl(userId as string, avatar)}+ alt=""+ width={size}+ height={size}+ onError={() => setImageBroken(true)}+ className="h-full w-full rounded-full object-cover"+ style={ringStyle}+ />+ ) : (+ <span+ className="flex h-full w-full items-center justify-center rounded-full text-white"+ style={{ backgroundColor: AVATAR_COLORS[colorName], ...ringStyle }}+ >+ {createElement(AVATAR_ICONS[iconName] ?? Sparkles, {+ size: Math.round(size * 0.55),+ strokeWidth: 1.8,+ })}+ </span>+ )}+ {showBadge && (+ <span+ className="absolute flex items-center justify-center rounded-full"+ style={{+ right: -size / 14,+ bottom: -size / 14,+ width: Math.round(size * 0.38),+ height: Math.round(size * 0.38),+ backgroundColor: "#f7ecd4",+ border: "2px solid var(--background)",+ color: "#8a5d0b",+ }}+ aria-hidden+ >+ <Shield size={Math.round(size * 0.2)} strokeWidth={2.2} />+ </span>+ )}+ </span>+ );+}diff --git a/web/components/auth/ProfileLink.tsx b/web/components/auth/ProfileLink.tsxnew file mode 100644index 000000000..c5d2e926d--- /dev/null+++ b/web/components/auth/ProfileLink.tsx@@ -0,0 +1,71 @@+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import { useTranslation } from "react-i18next";+import { fetchAuthStatus, AUTH_ENABLED, type AuthStatus } from "@/lib/auth";+import { UserAvatar } from "@/components/UserAvatar";++interface ProfileLinkProps {+ collapsed?: boolean;+}++export function ProfileLink({ collapsed = false }: ProfileLinkProps) {+ const pathname = usePathname();+ const { t } = useTranslation();+ const [status, setStatus] = useState<AuthStatus | null>(null);++ useEffect(() => {+ if (!AUTH_ENABLED) return;+ fetchAuthStatus().then((next) => {+ if (next?.authenticated) setStatus(next);+ });+ }, []);++ if (!AUTH_ENABLED || !status?.username) return null;++ const active = pathname.startsWith("/profile");+ const avatar = (+ <UserAvatar+ username={status.username}+ userId={status.user_id}+ avatar={status.avatar}+ size={collapsed ? 18 : 16}+ />+ );++ if (collapsed) {+ return (+ <Link+ href="/profile"+ className={`rounded-lg p-2 transition-colors+ ${+ active+ ? "bg-[var(--primary)]/10 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"+ }`}+ aria-label={t("My profile")}+ title={`${t("My profile")} — ${status.username}`}+ >+ {avatar}+ </Link>+ );+ }++ return (+ <Link+ href="/profile"+ className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-[13.5px] transition-colors+ ${+ active+ ? "bg-[var(--primary)]/10 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"+ }`}+ title={t("My profile")}+ >+ {avatar}+ <span className="truncate">{status.username}</span>+ </Link>+ );+}diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsxindex 8d19d48de..c5ad6a267 100644--- a/web/components/sidebar/UtilitySidebar.tsx+++ b/web/components/sidebar/UtilitySidebar.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import { SidebarShell } from "@/components/sidebar/SidebarShell";import { LogoutButton } from "@/components/auth/LogoutButton";import { AdminLink } from "@/components/auth/AdminLink";+import { ProfileLink } from "@/components/auth/ProfileLink";import { useAppShell } from "@/context/AppShellContext";import {deleteSession,@@ -92,6 +93,7 @@ export default function UtilitySidebar() {onDeleteSession={handleDeleteSession}footerSlot={(collapsed) => (<>+ <ProfileLink collapsed={collapsed} /><AdminLink collapsed={collapsed} /><LogoutButton collapsed={collapsed} /></>diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsxindex 32282a0a9..304f22671 100644--- a/web/components/sidebar/WorkspaceSidebar.tsx+++ b/web/components/sidebar/WorkspaceSidebar.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import { SidebarShell } from "@/components/sidebar/SidebarShell";import { LogoutButton } from "@/components/auth/LogoutButton";import { AdminLink } from "@/components/auth/AdminLink";+import { ProfileLink } from "@/components/auth/ProfileLink";import { useUnifiedChat } from "@/context/UnifiedChatContext";import {deleteSession,@@ -134,6 +135,7 @@ export default function WorkspaceSidebar() {onDeleteSession={handleDeleteSession}footerSlot={(collapsed) => (<>+ <ProfileLink collapsed={collapsed} /><AdminLink collapsed={collapsed} /><LogoutButton collapsed={collapsed} /></>diff --git a/web/lib/admin-api.ts b/web/lib/admin-api.tsindex 5672d0a6d..22f282291 100644--- a/web/lib/admin-api.ts+++ b/web/lib/admin-api.ts@@ -6,6 +6,8 @@ export interface UserRecord {role: "admin" | "user";created_at: string;disabled?: boolean;+ /** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */+ avatar?: string;}export async function listUsers(): Promise<UserRecord[]> {diff --git a/web/lib/auth.ts b/web/lib/auth.tsindex 5abc16c99..24a7ae307 100644--- a/web/lib/auth.ts+++ b/web/lib/auth.ts@@ -17,6 +17,8 @@ export interface AuthStatus {username?: string;role?: string;is_admin?: boolean;+ /** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */+ avatar?: string;}/**diff --git a/web/lib/avatar.ts b/web/lib/avatar.tsnew file mode 100644index 000000000..9929c7b99--- /dev/null+++ b/web/lib/avatar.ts@@ -0,0 +1,102 @@+/**+ * Pure avatar logic — marker parsing and the deterministic fallback.+ *+ * The marker format (persisted in the user record) is:+ * "" — deterministic icon+color derived from the username+ * "icon:<name>:<color>" — an explicitly picked icon and color (keys below)+ * "img:<version>" — an uploaded image served from /api/v1/auth/avatar+ *+ * Kept free of React/lucide imports so node unit tests can pin the behavior;+ * the UserAvatar component maps icon names to lucide components on top.+ */++// Same curated icon set as SessionAvatar, so the app keeps one visual voice.+// Order matters: the fallback hash indexes into this list, so reordering or+// removing entries silently reassigns every user's fallback avatar.+export const AVATAR_ICON_NAMES: readonly string[] = [+ "sparkles",+ "sprout",+ "leaf",+ "feather",+ "cloud",+ "droplet",+ "sun",+ "moon",+ "flame",+ "star",+ "heart",+ "lightbulb",+ "compass",+ "cherry",+ "cookie",+ "music",+];++// Fixed hexes (not theme variables) so a user's chosen color reads the same+// across Light/Dark/Snow/Glass themes; all carry white icons at 4.5:1+.+export const AVATAR_COLORS: Record<string, string> = {+ violet: "#7c5fd3",+ blue: "#3f7cc8",+ teal: "#2a9d8f",+ green: "#4f9d4f",+ amber: "#c98a2d",+ rose: "#d05c7c",+ slate: "#6b7a8c",+ pink: "#bb5fb2",+};++export const AVATAR_COLOR_NAMES = Object.keys(AVATAR_COLORS);++// Cheap, stable FNV-1a hash (same as SessionAvatar) so a username always maps+// to the same fallback icon/color without anything persisted.+function hashString(input: string): number {+ let h = 2166136261;+ for (let i = 0; i < input.length; i++) {+ h ^= input.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++export function fallbackAvatarFor(username: string): {+ icon: string;+ color: string;+} {+ const hash = hashString(username || "user");+ return {+ icon: AVATAR_ICON_NAMES[hash % AVATAR_ICON_NAMES.length],+ // ">>>" not ">>": a signed shift of a hash >= 2^31 yields a negative+ // index, which would silently drop the background color entirely.+ color: AVATAR_COLOR_NAMES[(hash >>> 4) % AVATAR_COLOR_NAMES.length],+ };+}++export type AvatarDescriptor =+ | { kind: "image"; version: string }+ | { kind: "icon"; icon: string; color: string }+ | { kind: "fallback" };++const ICON_MARKER_RE = /^icon:([a-z0-9-]+):([a-z0-9-]+)$/;++/**+ * Classify an avatar marker. Unknown icon/color names (e.g. from a stale or+ * hand-edited user record) degrade to the deterministic fallback instead of+ * rendering a broken avatar.+ */+export function parseAvatarMarker(+ marker: string | null | undefined,+): AvatarDescriptor {+ const value = (marker ?? "").trim();+ if (value.startsWith("img:")) {+ return { kind: "image", version: value.slice(4) };+ }+ const match = ICON_MARKER_RE.exec(value);+ if (+ match &&+ AVATAR_ICON_NAMES.includes(match[1]) &&+ AVATAR_COLORS[match[2]]+ ) {+ return { kind: "icon", icon: match[1], color: match[2] };+ }+ return { kind: "fallback" };+}diff --git a/web/lib/profile-api.ts b/web/lib/profile-api.tsnew file mode 100644index 000000000..22abc6f02--- /dev/null+++ b/web/lib/profile-api.ts@@ -0,0 +1,80 @@+import { apiFetch, apiUrl } from "@/lib/api";++export interface ProfileInfo {+ id: string;+ username: string;+ role: "admin" | "user";+ created_at: string;+ disabled?: boolean;+ /** Avatar marker: "", "icon:<name>:<color>", or "img:<version>". */+ avatar?: string;+}++function extractDetail(data: unknown, fallback: string): string {+ if (typeof data === "object" && data !== null && "detail" in data) {+ const detail = (data as { detail: unknown }).detail;+ if (typeof detail === "string") return detail;+ }+ return fallback;+}++/** Fetch the signed-in user's own profile. */+export async function getProfile(): Promise<ProfileInfo> {+ const res = await apiFetch(apiUrl("/api/v1/auth/profile"));+ if (!res.ok) throw new Error("Failed to fetch profile");+ return res.json();+}++/**+ * Persist an icon-based avatar choice ("icon:<name>:<color>") or reset to the+ * deterministic fallback (""). Uploaded-image markers are managed by+ * `uploadAvatarImage`.+ */+export async function setAvatarMarker(avatar: string): Promise<string> {+ const res = await apiFetch(apiUrl("/api/v1/auth/profile"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ avatar }),+ });+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw new Error(extractDetail(data, "Failed to update avatar"));+ }+ const data = await res.json();+ return String(data.avatar ?? avatar);+}++/** Upload an avatar image (already cropped/resized client-side). */+export async function uploadAvatarImage(blob: Blob): Promise<string> {+ const form = new FormData();+ form.append("file", blob, "avatar");+ const res = await apiFetch(apiUrl("/api/v1/auth/profile/avatar"), {+ method: "PUT",+ body: form,+ });+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw new Error(extractDetail(data, "Failed to upload avatar"));+ }+ const data = await res.json();+ return String(data.avatar ?? "");+}++/** Remove the uploaded avatar image and reset the marker. */+export async function removeAvatarImage(): Promise<void> {+ const res = await apiFetch(apiUrl("/api/v1/auth/profile/avatar"), {+ method: "DELETE",+ });+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw new Error(extractDetail(data, "Failed to remove avatar"));+ }+}++/** Build the image URL for an "img:<version>" marker (version cache-busts). */+export function avatarImageUrl(userId: string, marker: string): string {+ const version = marker.startsWith("img:") ? marker.slice(4) : "0";+ return apiUrl(+ `/api/v1/auth/avatar/${encodeURIComponent(userId)}?v=${encodeURIComponent(version)}`,+ );+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ac09ad892..acf946182 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2358,5 +2358,18 @@"Partner": "Partner","Edited — your version becomes this partner's soul. The original template is untouched.": "Edited — your version becomes this partner's soul. The original template is untouched.","Mastery-based tutoring with a hard gate": "Mastery-based tutoring with a hard gate",- "Mastery Path tooltip": "Mastery-based learning with a hard gate"+ "Mastery Path tooltip": "Mastery-based learning with a hard gate",+ "My profile": "My profile",+ "View your account and personalize your avatar": "View your account and personalize your avatar",+ "Administrator": "Administrator",+ "Joined": "Joined",+ "Avatar": "Avatar",+ "Upload a picture or pick an icon": "Upload a picture or pick an icon",+ "Upload image": "Upload image",+ "Remove photo": "Remove photo",+ "Or pick an icon": "Or pick an icon",+ "Sign out": "Sign out",+ "End your session on this device": "End your session on this device",+ "Failed to load profile": "Failed to load profile",+ "Image is too large": "Image is too large"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 8ebb5ca14..5c0d729fa 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2358,5 +2358,18 @@"Partner": "伙伴","Edited — your version becomes this partner's soul. The original template is untouched.": "已编辑——你的版本将成为这个伙伴的 soul,原模板保持不变。","Mastery-based tutoring with a hard gate": "掌握式辅导:硬门槛 + 间隔复习",- "Mastery Path tooltip": "掌握式学习:硬门槛与间隔复习"+ "Mastery Path tooltip": "掌握式学习:硬门槛与间隔复习",+ "My profile": "个人资料",+ "View your account and personalize your avatar": "查看账户信息并个性化你的头像",+ "Administrator": "管理员",+ "Joined": "注册时间",+ "Avatar": "头像",+ "Upload a picture or pick an icon": "上传图片或选择一个图标",+ "Upload image": "上传图片",+ "Remove photo": "移除照片",+ "Or pick an icon": "或选择一个图标",+ "Sign out": "退出登录",+ "End your session on this device": "结束此设备上的会话",+ "Failed to load profile": "加载个人资料失败",+ "Image is too large": "图片过大"}