DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(learning): add visual learning board (#1194)
evan188199-techdb24303eb06d
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 89efd5c10..6e6040ec2 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -653,6 +653,57 @@ async def get_progress_map(book_id: str):}[email protected]("/progress/{book_id}/board")+async def get_progress_board(book_id: str):+ """The visual learning board: every knowledge point as a card, enriched+ with its next review time and a deterministic grid position derived from+ the module order. A read-only projection of the same mastery data the+ tutor and the map view use."""+ _validate_book_id(book_id)+ service = get_learning_service()+ progress = service.get_or_create(book_id)+ summary = learning_policy.map_summary(progress)++ due_by_kp = {task.knowledge_point_id: task.due_at for task in progress.review_queue}++ cards: list[dict] = []+ modules: list[dict] = []+ for module in summary["modules"]:+ module_cards: list[dict] = []+ for index, kp in enumerate(module["knowledge_points"]):+ card = {+ "id": kp["id"],+ "name": kp["name"],+ "type": kp["type"],+ "module_id": module["id"],+ "module_name": module["name"],+ "status": kp["status"],+ "mastery_level": kp["mastery"],+ "next_review_at": due_by_kp.get(kp["id"]),+ "position": {"column": module["order"], "row": index},+ }+ cards.append(card)+ module_cards.append(card)+ modules.append(+ {+ "id": module["id"],+ "name": module["name"],+ "order": module["order"],+ "mastered": module["mastered"],+ "total": module["total"],+ "cards": module_cards,+ }+ )++ return {+ "book_id": book_id,+ "name": summary["name"],+ "path_revision": progress.version,+ "cards": cards,+ "modules": modules,+ }++@router.get("/progress/{book_id}/objectives/{kp_id}")async def get_objective_report(book_id: str, kp_id: str):"""The evidence behind one objective: attempts, schedule, errors, prompts.diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex f319ad520..f7f906473 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -683,6 +683,74 @@ class TestGetProgress:assert path_map["path_revision"] == progress["version"]+# -- GET /progress/{book_id}/board ----------------------------------------+++class TestProgressBoard:+ def test_board_empty(self, client):+ resp = client.get("/api/mastery-paths/progress/boardempty/board")+ assert resp.status_code == 200+ data = resp.json()+ assert data["book_id"] == "boardempty"+ assert data["cards"] == []+ assert data["modules"] == []++ def test_board_card_shape_and_position(self, client):+ client.post(+ "/api/mastery-paths/progress/boardbook/init-modules",+ json={+ "modules": [+ {+ "id": "m1",+ "name": "M1",+ "order": 0,+ "knowledge_points": [+ {"id": "kp1", "name": "KP1", "type": "concept", "module_id": "m1"},+ {"id": "kp2", "name": "KP2", "type": "procedure", "module_id": "m1"},+ ],+ },+ {+ "id": "m2",+ "name": "M2",+ "order": 1,+ "knowledge_points": [+ {"id": "kp3", "name": "KP3", "type": "memory", "module_id": "m2"},+ ],+ },+ ]+ },+ )+ resp = client.get("/api/mastery-paths/progress/boardbook/board")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data["cards"]) == 3+ assert len(data["modules"]) == 2++ first = data["cards"][0]+ assert first["id"] == "kp1"+ assert first["name"] == "KP1"+ assert first["type"] == "concept"+ assert first["module_id"] == "m1"+ assert first["module_name"] == "M1"+ assert first["status"] == "new"+ assert first["mastery_level"] == 0.0+ assert first["next_review_at"] is None+ assert first["position"] == {"column": 0, "row": 0}++ third = data["cards"][2]+ assert third["position"] == {"column": 1, "row": 0}++ module = data["modules"][0]+ assert module["name"] == "M1"+ assert module["mastered"] == 0+ assert module["total"] == 2+ assert len(module["cards"]) == 2++ def test_board_invalid_book_id_returns_400(self, client):+ resp = client.get("/api/mastery-paths/progress/a\\b/board")+ assert resp.status_code == 400++# -- DELETE /progress/{book_id} -------------------------------------------diff --git a/web/app/(utility)/mastery/[pathId]/page.tsx b/web/app/(utility)/mastery/[pathId]/page.tsxindex 5139fd680..8c9ef4e86 100644--- a/web/app/(utility)/mastery/[pathId]/page.tsx+++ b/web/app/(utility)/mastery/[pathId]/page.tsx@@ -9,6 +9,8 @@ import {ArrowRight,BookOpen,Compass,+ LayoutGrid,+ List,Loader2,MoreHorizontal,PencilRuler,@@ -21,6 +23,7 @@ import {import { ModuleOutline } from "@/components/space/learning/ModuleOutline";import { ConfirmDialog } from "@/components/space/learning/ConfirmDialog";import { EditTopicRouteDialog } from "@/components/space/learning/EditTopicRouteDialog";+import { LearningBoard } from "@/components/space/learning/LearningBoard";import {topicDisplayName,type Translate,@@ -33,12 +36,15 @@ import {deleteProgress,fetchMasteryTopic,fetchMasteryTopicSessions,+ fetchLearningBoard,redoProgress,renameProgress,setMasteryObjectiveOverride,type MasteryTopic,+ type BoardResult,type TopicSession,} from "@/lib/learning-api";+import { setPendingPrompt } from "@/lib/pending-prompt";const NEXT_LABELS: Record<string, { zh: string; en: string }> = {probe: {@@ -90,6 +96,10 @@ export default function MasteryTopicPage() {const [confirmAction, setConfirmAction] = useState<"reset" | "delete" | null>(null,);+ const [topicView, setTopicView] = useState<"outline" | "board">("outline");+ const [board, setBoard] = useState<BoardResult | null>(null);+ const [boardError, setBoardError] = useState(false);+ const [boardRequestNonce, setBoardRequestNonce] = useState(0);const [mutationBusy, setMutationBusy] = useState(false);const editorTriggerRef = useRef<HTMLElement | null>(null);const confirmTriggerRef = useRef<HTMLElement | null>(null);@@ -147,6 +157,23 @@ export default function MasteryTopicPage() {void loadSessions();}, [activity.revision, activity.signal, loadSessions]);+ useEffect(() => {+ if (topicView !== "board") return;+ const controller = new AbortController();+ setBoardError(false);+ fetchLearningBoard(pathId, {+ cache: "no-store",+ signal: controller.signal,+ })+ .then((result) => setBoard(result))+ .catch(() => {+ if (controller.signal.aborted) return;+ setBoard(null);+ setBoardError(true);+ });+ return () => controller.abort();+ }, [activity.revision, boardRequestNonce, pathId, topicView]);+useEffect(() => {if (!selectedId || !topic) return;const stillThere = topic.map.modules.some((module) =>@@ -223,6 +250,14 @@ export default function MasteryTopicPage() {}};+ const startBoardTutoring = (knowledgePointName: string) => {+ setPendingPrompt(+ `Please tutor me on: ${knowledgePointName}. Start with a quick check of what I already know, then guide me step by step.`,+ "mastery_path",+ );+ router.push(`/mastery/${encodeURIComponent(pathId)}/sessions`);+ };+if (loading && !topic) {return (<div className="mastery-shell flex h-full items-center justify-center text-[var(--muted-foreground)]">@@ -439,14 +474,66 @@ export default function MasteryTopicPage() {</section>) : (<div className="space-y-5">- <ModuleOutline- topic={topic}- revision={Math.max(topic.path_revision, activity.revision)}- selectedId={selectedId}- zh={zh}- onSelect={setSelectedId}- onOverride={handleOverride}- />+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(+ [+ ["outline", List, t("Outline")],+ ["board", LayoutGrid, t("Board")],+ ] as const+ ).map(([value, Icon, label]) => (+ <button+ key={value}+ type="button"+ onClick={() => setTopicView(value)}+ aria-pressed={topicView === value}+ className={`flex h-8 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium transition ${+ topicView === value+ ? "bg-[var(--background)] text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <Icon className="h-3.5 w-3.5" />+ {label}+ </button>+ ))}+ </div>+ {topicView === "board" && boardError && (+ <button+ type="button"+ onClick={() => setBoardRequestNonce((nonce) => nonce + 1)}+ className="text-xs font-medium text-[var(--primary)] hover:underline"+ >+ {t("Try again")}+ </button>+ )}+ </div>+ {topicView === "outline" ? (+ <ModuleOutline+ topic={topic}+ revision={Math.max(topic.path_revision, activity.revision)}+ selectedId={selectedId}+ zh={zh}+ onSelect={setSelectedId}+ onOverride={handleOverride}+ />+ ) : board ? (+ <LearningBoard+ pathId={pathId}+ modules={board.modules}+ revision={Math.max(topic.path_revision, activity.revision)}+ zh={zh}+ onStartTutoring={startBoardTutoring}+ />+ ) : boardError ? (+ <p className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 text-center text-sm text-[var(--muted-foreground)]">+ {t("The learning board could not be loaded")}+ </p>+ ) : (+ <div className="flex min-h-40 items-center justify-center rounded-xl border border-[var(--border)] bg-[var(--card)]">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ )}<ReviewTrailreviews={topic.reviews}zh={zh}diff --git a/web/components/space/learning/LearningBoard.tsx b/web/components/space/learning/LearningBoard.tsxnew file mode 100644index 000000000..4e1b5d826--- /dev/null+++ b/web/components/space/learning/LearningBoard.tsx@@ -0,0 +1,163 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ BookOpen,+ Circle,+ CircleCheck,+ CircleDot,+ Loader2,+ MessageSquare,+} from "lucide-react";++import {+ fetchObjectiveReport,+ type BoardModule,+ type ObjectiveReport,+ type ObjectiveStatus,+} from "@/lib/learning-api";++import { ObjectiveDetail } from "./ObjectiveDetail";+import { formatRelative, knowledgeTypeLabel } from "./format";++const STATUS_BORDER: Record<ObjectiveStatus, string> = {+ mastered: "border-green-500/50",+ learning: "border-yellow-500/50",+ new: "border-[var(--border)]",+};++const STATUS_ICON: Record<ObjectiveStatus, React.ReactNode> = {+ mastered: <CircleCheck className="h-3.5 w-3.5 text-green-500" />,+ learning: <CircleDot className="h-3.5 w-3.5 text-yellow-500" />,+ new: <Circle className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />,+};++/**+ * The topic as a board: modules become columns and objectives become cards.+ *+ * The projection is read-only; opening a card still reads the same evidence+ * trail as the outline and starts the same Mastery Study surface.+ */+export function LearningBoard({+ pathId,+ modules,+ revision,+ zh,+ onStartTutoring,+}: {+ pathId: string;+ modules: BoardModule[];+ revision: number;+ zh: boolean;+ onStartTutoring: (knowledgePointName: string) => void;+}) {+ const { t } = useTranslation();+ const [openId, setOpenId] = useState<string | null>(null);+ const [report, setReport] = useState<ObjectiveReport | null>(null);+ const [reportError, setReportError] = useState(false);+ const loaded = openId !== null && report?.id === openId;++ useEffect(() => {+ if (!openId) return;+ const controller = new AbortController();+ fetchObjectiveReport(pathId, openId, { signal: controller.signal })+ .then((result) => {+ setReport(result);+ setReportError(false);+ })+ .catch(() => {+ if (controller.signal.aborted) return;+ setReport(null);+ setReportError(true);+ });+ return () => controller.abort();+ }, [openId, pathId, revision]);++ const toggle = useCallback((id: string) => {+ setOpenId((current) => (current === id ? null : id));+ setReport(null);+ setReportError(false);+ }, []);++ return (+ <div className="flex gap-4 overflow-x-auto pb-2">+ {modules.map((module) => (+ <div+ key={module.id}+ className="flex w-64 shrink-0 flex-col gap-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 p-3"+ >+ <div className="flex items-center justify-between gap-2">+ <h3 className="min-w-0 truncate text-[13px] font-semibold text-[var(--foreground)]">+ {module.name}+ </h3>+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--muted-foreground)]">+ {module.mastered}/{module.total}+ </span>+ </div>++ {module.cards.map((card) => {+ const open = openId === card.id;+ return (+ <div key={card.id}>+ <button+ type="button"+ onClick={() => toggle(card.id)}+ aria-expanded={open}+ className={`w-full rounded-lg border bg-[var(--card)] p-3 text-left transition hover:bg-[var(--muted)]/60 ${STATUS_BORDER[card.status]}`}+ >+ <div className="flex items-start justify-between gap-2">+ <span className="text-[13px] leading-snug text-[var(--foreground)]">+ {card.name}+ </span>+ {STATUS_ICON[card.status]}+ </div>+ <div className="mt-2 flex items-center justify-between gap-2 text-[11px]">+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[var(--muted-foreground)]">+ {knowledgeTypeLabel(card.type, t)}+ </span>+ <span className="shrink-0 tabular-nums text-[var(--muted-foreground)]">+ {Math.round(card.mastery_level * 100)}%+ </span>+ </div>+ {card.next_review_at && (+ <div className="mt-1.5 flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]">+ <BookOpen className="h-3 w-3" />+ {t("Review")} {formatRelative(card.next_review_at, zh)}+ </div>+ )}+ </button>++ {open && (+ <div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-3">+ {loaded && report ? (+ <>+ <ObjectiveDetail report={report} zh={zh} />+ <button+ type="button"+ onClick={() => onStartTutoring(card.name)}+ className="mt-2 flex h-8 w-full items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 text-xs font-medium text-[var(--primary-foreground)] transition hover:opacity-90"+ >+ <MessageSquare className="h-3.5 w-3.5" />+ {t("Start tutoring")}+ </button>+ </>+ ) : reportError ? (+ <p className="py-3 text-center text-xs text-[var(--muted-foreground)]">+ {t("Evidence could not be loaded")}+ </p>+ ) : (+ <div className="flex items-center justify-center py-3 text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ ))}+ </div>+ );+}diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.tsindex 949131865..8bba4c0d5 100644--- a/web/lib/learning-api.ts+++ b/web/lib/learning-api.ts@@ -112,6 +112,37 @@ export interface MasteryMapResult {map: MasteryMap;}+// ── Visual learning board ─────────────────────────────────────────────────++export interface BoardCard {+ id: string;+ name: string;+ type: string;+ module_id: string;+ module_name: string;+ status: ObjectiveStatus;+ mastery_level: number;+ next_review_at: number | null;+ position: { column: number; row: number };+}++export interface BoardModule {+ id: string;+ name: string;+ order: number;+ mastered: number;+ total: number;+ cards: BoardCard[];+}++export interface BoardResult {+ book_id: string;+ name: string;+ path_revision: number;+ cards: BoardCard[];+ modules: BoardModule[];+}+export async function fetchMasteryMap(pathId: string,init?: RequestInit,@@ -124,6 +155,20 @@ export async function fetchMasteryMap(return res.json() as Promise<MasteryMapResult>;}+export async function fetchLearningBoard(+ pathId: string,+ init?: RequestInit,+): Promise<BoardResult> {+ const res = await apiFetch(+ apiUrl(+ `/api/mastery-paths/progress/${encodeURIComponent(pathId)}/board`,+ ),+ init,+ );+ if (!res.ok) throw new Error(`Failed to fetch learning board: ${res.status}`);+ return res.json() as Promise<BoardResult>;+}+/** Rename a path. An empty name restores the derived display name. */export async function renameProgress(pathId: string, name: string) {const res = await apiFetch(diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 68325b5e5..d7aa35643 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3487,6 +3487,9 @@"paused": "paused","Draft": "Draft","Outline": "Outline",+ "Board": "Board",+ "Start tutoring": "Start tutoring",+ "The learning board could not be loaded": "The learning board could not be loaded","Contents": "Contents","Document contents": "Document contents","Pages": "Pages",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex bec7faf7c..1e765a427 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3487,6 +3487,9 @@"paused": "已暂停","Draft": "草稿","Outline": "大纲",+ "Board": "看板",+ "Start tutoring": "开始辅导",+ "The learning board could not be loaded": "学习看板加载失败","Contents": "目录","Document contents": "文档目录","Pages": "页码",