DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(mastery): ship atlas and guided study journeys
Bingxi Zhao (Frank)1b5ad913d4ab
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 8842f01be..0b8e0d684 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -215,9 +215,7 @@ def _topic_sources(items: list[TopicSourceRequest]) -> list[TopicSource]:def _review_queue(progress) -> list[dict]:- names = {- kp.id: kp.name for module in progress.modules for kp in module.knowledge_points- }+ names = {kp.id: kp.name for module in progress.modules for kp in module.knowledge_points}return [{"id": task.id,@@ -384,10 +382,22 @@ async def list_topic_sessions(path_id: str):session_store = get_session_store()sessions = []for session_id in session_ids:- session = await session_store.get_session(session_id)+ session = await session_store.get_session_with_messages(session_id)if session is None:continuepreferences = session.get("preferences") or {}+ messages = session.get("messages") or []+ visible_messages = [+ message for message in messages if str(message.get("role") or "") != "system"+ ]+ last_message = next(+ (+ str(message.get("content") or "").strip()+ for message in reversed(visible_messages)+ if str(message.get("content") or "").strip()+ ),+ "",+ )sessions.append({"session_id": session.get("session_id") or session.get("id") or session_id,@@ -396,6 +406,8 @@ async def list_topic_sessions(path_id: str):"updated_at": session.get("updated_at") or 0,"status": session.get("status") or "idle","active_turn_id": session.get("active_turn_id") or "",+ "message_count": len(visible_messages),+ "last_message": last_message[:240],"pinned": bool(preferences.get("pinned")),"archived": bool(preferences.get("archived")),}diff --git a/deeptutor/learning/event_hub.py b/deeptutor/learning/event_hub.pyindex e06bc00a4..da756366e 100644--- a/deeptutor/learning/event_hub.py+++ b/deeptutor/learning/event_hub.py@@ -100,4 +100,3 @@ __all__ = ["mastery_topic_event_hub","publish_topic_signal",]-diff --git a/deeptutor/learning/migration.py b/deeptutor/learning/migration.pyindex ccd4b15b0..dbfcd02bd 100644--- a/deeptutor/learning/migration.py+++ b/deeptutor/learning/migration.py@@ -147,9 +147,7 @@ def prepare_mastery_v2_root(learning_root: Path) -> Path:if has_legacy_json:archived_json_dir = archive_dir / "legacy-json"shutil.copytree(legacy_json_dir, archived_json_dir)- legacy_json_count = sum(- 1 for path in archived_json_dir.rglob("*") if path.is_file()- )+ legacy_json_count = sum(1 for path in archived_json_dir.rglob("*") if path.is_file())manifest = {"format_version": 2,@@ -178,4 +176,3 @@ def prepare_mastery_v2_root(learning_root: Path) -> Path:__all__ = ["prepare_mastery_v2_root"]-diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.pyindex 76dab6760..9dd0f32e3 100644--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@ -333,9 +333,7 @@ class LearningProgress(BaseModel):# A learner may explicitly claim prior mastery. Policy exposes this as a# separate provenance (``mastery_source=learner``); assessed mastery and# its evidence remain untouched and can take over later.- learner_mastery_overrides: dict[str, LearnerMasteryOverride] = Field(- default_factory=dict- )+ learner_mastery_overrides: dict[str, LearnerMasteryOverride] = Field(default_factory=dict)# A single outstanding question; grading reads its expected answer so the# model never has to recall it across turns.pending_question: PendingQuestion | None = Nonediff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex a379cfe98..91353882c 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -120,6 +120,55 @@ class TestListProgress:class TestTopicProductApi:+ def test_topic_sessions_include_message_count_and_latest_preview(self, client, monkeypatch):+ created = client.post(+ "/api/v1/learning/topics",+ json={+ "name": "Calculus",+ "goal": "Understand rates of change",+ "sources": [],+ "modules": [_module_payload("m1", "kp1")],+ },+ ).json()+ path_id = created["path_id"]+ LearningStore(root=client.app.state.learning_root).bind_session(path_id, "session-1")+ session_store = AsyncMock()+ session_store.get_session_with_messages.return_value = {+ "session_id": "session-1",+ "title": "Limits expedition",+ "created_at": 10,+ "updated_at": 20,+ "status": "idle",+ "preferences": {"pinned": True, "archived": False},+ "messages": [+ {"role": "system", "content": "hidden"},+ {"role": "user", "content": "Why is this limit finite?"},+ {"role": "assistant", "content": "Look at the local slope."},+ ],+ }+ monkeypatch.setattr(+ "deeptutor.services.session.get_session_store",+ lambda: session_store,+ )++ response = client.get(f"/api/v1/learning/topics/{path_id}/sessions")++ assert response.status_code == 200+ assert response.json()["sessions"] == [+ {+ "session_id": "session-1",+ "title": "Limits expedition",+ "created_at": 10,+ "updated_at": 20,+ "status": "idle",+ "active_turn_id": "",+ "message_count": 2,+ "last_message": "Look at the local slope.",+ "pinned": True,+ "archived": False,+ }+ ]+def test_generate_mixed_source_draft_without_persisting(self, client):response_json = json.dumps({@@ -233,9 +282,7 @@ class TestTopicProductApi:kp_id = created["map"]["modules"][0]["knowledge_points"][0]["id"]with client.websocket_connect("/api/v1/learning/ws") as socket:- socket.send_json(- {"type": "subscribe", "path_id": path_id, "after_revision": 0}- )+ socket.send_json({"type": "subscribe", "path_id": path_id, "after_revision": 0})subscribed = socket.receive_json()assert subscribed["type"] == "subscribed"assert subscribed["events"]@@ -277,9 +324,7 @@ class TestTopicProductApi:# A cursor beyond the durable head is clamped instead of causing# every subsequent revision to be silently ignored.- socket.send_json(- {"type": "subscribe", "path_id": path_id, "after_revision": 999_999}- )+ socket.send_json({"type": "subscribe", "path_id": path_id, "after_revision": 999_999})subscribed = socket.receive_json()assert subscribed["type"] == "subscribed"assert subscribed["revision"] == created["path_revision"]@@ -292,9 +337,7 @@ class TestTopicProductApi:assert response.status_code == 200pushed = socket.receive_json()assert pushed["revision"] == response.json()["path_revision"]- assert [event["event_type"] for event in pushed["events"]] == [- "mastery.overridden"- ]+ assert [event["event_type"] for event in pushed["events"]] == ["mastery.overridden"]# -- POST /progress/{book_id}/init-modules --------------------------------diff --git a/deeptutor/learning/tests/test_event_hub.py b/deeptutor/learning/tests/test_event_hub.pyindex 28b633e53..6e567e90d 100644--- a/deeptutor/learning/tests/test_event_hub.py+++ b/deeptutor/learning/tests/test_event_hub.py@@ -37,4 +37,3 @@ async def test_topic_hub_isolated_by_path_and_unsubscribes_cleanly() -> None:assert signal.path_id == "second"assert signal.sequence >= 1assert first.queue.empty()-diff --git a/deeptutor/learning/tests/test_v2_migration.py b/deeptutor/learning/tests/test_v2_migration.pyindex 7844587f0..46fde37f0 100644--- a/deeptutor/learning/tests/test_v2_migration.py+++ b/deeptutor/learning/tests/test_v2_migration.py@@ -96,4 +96,3 @@ def test_empty_workspace_uses_v2_directory_without_creating_archive(tmp_path: Paassert store.db_path == learning_root / "mastery" / "mastery.sqlite3"assert not (learning_root / "archive").exists()-diff --git a/deeptutor/learning/topic_generation.py b/deeptutor/learning/topic_generation.pyindex bee684c47..a282476d5 100644--- a/deeptutor/learning/topic_generation.py+++ b/deeptutor/learning/topic_generation.py@@ -117,4 +117,3 @@ async def generate_topic_draft(__all__ = ["TopicGenerationError", "generate_topic_draft", "materialize_modules"]-diff --git a/web/app/(utility)/space/learning/[pathId]/page.tsx b/web/app/(utility)/space/learning/[pathId]/page.tsxnew file mode 100644index 000000000..ea148dffe--- /dev/null+++ b/web/app/(utility)/space/learning/[pathId]/page.tsx@@ -0,0 +1,341 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { useParams, useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";+import {+ ArrowLeft,+ ArrowRight,+ BookOpen,+ Compass,+ Loader2,+ MoreHorizontal,+ PencilRuler,+ Radio,+ RotateCcw,+ Sparkles,+ Trash2,+} from "lucide-react";++import { AdventureMap } from "@/components/space/learning/AdventureMap";+import { EditTopicRouteDialog } from "@/components/space/learning/EditTopicRouteDialog";+import type { Translate } from "@/components/space/learning/format";+import { ReviewTrail } from "@/components/space/learning/ReviewTrail";+import { SessionCamp } from "@/components/space/learning/SessionCamp";+import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";+import {+ deleteProgress,+ fetchMasteryTopic,+ fetchMasteryTopicSessions,+ redoProgress,+ setMasteryObjectiveOverride,+ type MasteryTopic,+ type TopicSession,+} from "@/lib/learning-api";++const NEXT_LABELS: Record<string, { zh: string; en: string }> = {+ probe: { zh: "先用一道探查题看看你是否已经掌握", en: "Start with a probe and test out if you already know it" },+ practice: { zh: "继续练习,直到稳定越过掌握门槛", en: "Practice until you reliably clear the mastery gate" },+ assess: { zh: "用自己的话讲清楚这个概念", en: "Explain this clearly in your own words" },+ review: { zh: "复习这个记忆信标", en: "Revisit this memory beacon" },+ answer_pending: { zh: "完成导师正在等待的回答", en: "Complete the answer your tutor is waiting for" },+ complete: { zh: "整片疆域已经点亮", en: "The whole territory is illuminated" },+};++export default function MasteryTopicPage() {+ const params = useParams<{ pathId: string }>();+ const pathId = String(params.pathId || "");+ const router = useRouter();+ const { i18n } = useTranslation();+ const zh = Boolean(i18n.language?.toLowerCase().startsWith("zh"));+ const tr: Translate = useCallback((cn, en) => (zh ? cn : en), [zh]);+ const [topic, setTopic] = useState<MasteryTopic | null>(null);+ const [sessions, setSessions] = useState<TopicSession[]>([]);+ const [loading, setLoading] = useState(true);+ const [sessionsLoading, setSessionsLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [editorOpen, setEditorOpen] = useState(false);+ const activity = useMasteryPathActivity(pathId || null);++ const loadTopic = useCallback(async () => {+ try {+ const next = await fetchMasteryTopic(pathId, { cache: "no-store" });+ setTopic(next);+ setError(null);+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : tr("地图读取失败", "The map could not be loaded"),+ );+ } finally {+ setLoading(false);+ }+ }, [pathId, tr]);++ const loadSessions = useCallback(async () => {+ try {+ setSessions(await fetchMasteryTopicSessions(pathId, { cache: "no-store" }));+ } catch {+ setSessions([]);+ } finally {+ setSessionsLoading(false);+ }+ }, [pathId]);++ useEffect(() => {+ void loadTopic();+ }, [activity.revision, loadTopic]);++ useEffect(() => {+ void loadSessions();+ }, [activity.revision, activity.signal, loadSessions]);++ const sourceLabels = useMemo(+ () => topic?.sources.filter((source) => source.kind !== "goal").slice(0, 5) ?? [],+ [topic],+ );++ const refresh = async () => {+ await Promise.all([loadTopic(), loadSessions()]);+ activity.refresh();+ };++ const handleOverride = async (objectiveId: string, mastered: boolean, note: string) => {+ const result = await setMasteryObjectiveOverride(pathId, objectiveId, mastered, note);+ setTopic((previous) =>+ previous+ ? { ...previous, map: result.map, path_revision: result.path_revision }+ : previous,+ );+ await loadTopic();+ };++ const handleReset = async () => {+ if (+ !window.confirm(+ tr(+ "重置这张地图上的学习进度?区域和关卡会保留,掌握证据与复习计划会清空。",+ "Reset learning progress on this map? Regions and waypoints remain, while mastery evidence and reviews are cleared.",+ ),+ )+ )+ return;+ await redoProgress(pathId);+ await refresh();+ };++ const handleDelete = async () => {+ if (!window.confirm(tr("永久删除这个学习主题?", "Permanently delete this learning topic?"))) return;+ await deleteProgress(pathId);+ router.replace("/space/learning");+ };++ if (loading && !topic) {+ return (+ <div className="mastery-shell flex h-full items-center justify-center text-[var(--muted-foreground)]">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ );+ }++ if (!topic) {+ return (+ <div className="mastery-shell flex h-full flex-col items-center justify-center px-6 text-center">+ <Compass className="h-10 w-10 text-[var(--muted-foreground)] opacity-40" />+ <h1 className="mt-4 text-lg font-semibold">{tr("找不到这张地图", "This map could not be found")}</h1>+ <p className="mt-2 text-sm text-[var(--muted-foreground)]">{error}</p>+ <Link href="/space/learning" className="mt-5 text-sm font-medium text-[var(--primary)] hover:underline">+ {tr("返回地图集", "Return to atlas")}+ </Link>+ </div>+ );+ }++ const nextCopy = NEXT_LABELS[topic.next.action] ?? {+ zh: topic.next.reason,+ en: topic.next.reason,+ };+ const progress = topic.map.counts.total+ ? Math.round((topic.map.counts.mastered / topic.map.counts.total) * 100)+ : 0;++ return (+ <main className="mastery-shell h-full overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-[1440px] px-4 py-6 sm:px-7 lg:px-9 lg:py-8">+ <div className="flex items-center justify-between gap-3">+ <Link+ href="/space/learning"+ className="inline-flex items-center gap-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ {tr("地图集", "Mastery Atlas")}+ </Link>+ <div className="flex items-center gap-2">+ <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-[10px] font-medium text-[var(--muted-foreground)]">+ <span+ className={`h-1.5 w-1.5 rounded-full ${+ activity.connection === "live" ? "bg-emerald-500" : "bg-amber-500"+ }`}+ />+ {activity.connection === "live" ? tr("实时同步", "Live") : tr("正在重连", "Reconnecting")}+ </span>+ <button+ type="button"+ onClick={() => setEditorOpen(true)}+ className="inline-flex h-9 items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 text-xs font-medium hover:bg-[var(--accent)]"+ >+ <PencilRuler className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">{tr("编辑路线", "Edit route")}</span>+ </button>+ <details className="relative">+ <summary className="flex h-9 w-9 cursor-pointer list-none items-center justify-center rounded-xl border border-[var(--border)] bg-[var(--card)] hover:bg-[var(--accent)]">+ <MoreHorizontal className="h-4 w-4" />+ <span className="sr-only">{tr("更多操作", "More actions")}</span>+ </summary>+ <div className="absolute right-0 z-20 mt-2 w-44 rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 text-xs shadow-xl">+ <button+ type="button"+ onClick={() => void handleReset()}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left hover:bg-[var(--accent)]"+ >+ <RotateCcw className="h-3.5 w-3.5" /> {tr("重置进度", "Reset progress")}+ </button>+ <button+ type="button"+ onClick={() => void handleDelete()}+ className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-red-600 hover:bg-red-500/10"+ >+ <Trash2 className="h-3.5 w-3.5" /> {tr("删除主题", "Delete topic")}+ </button>+ </div>+ </details>+ </div>+ </div>++ <header className="mt-6 flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">+ <div className="min-w-0">+ <div className="flex items-center gap-3">+ <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-[var(--border)] bg-[var(--card)] text-2xl shadow-sm">+ {topic.metadata.emoji}+ </span>+ <div className="min-w-0">+ <h1 className="truncate text-3xl font-semibold tracking-[-0.035em] text-[var(--foreground)] sm:text-[36px]">+ {topic.name}+ </h1>+ <p className="mt-1 max-w-3xl text-sm text-[var(--muted-foreground)]">+ {topic.metadata.description || topic.metadata.goal}+ </p>+ </div>+ </div>+ {sourceLabels.length > 0 && (+ <div className="mt-4 flex flex-wrap items-center gap-2 pl-0 sm:pl-[60px]">+ {sourceLabels.map((source) => (+ <span+ key={source.id}+ className="inline-flex items-center gap-1.5 rounded-full bg-[var(--muted)] px-2.5 py-1 text-[10px] text-[var(--muted-foreground)]"+ >+ <BookOpen className="h-3 w-3" /> {source.label}+ </span>+ ))}+ </div>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 shadow-sm">+ <div>+ <div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--muted-foreground)]">+ {tr("疆域完成度", "Territory complete")}+ </div>+ <div className="mt-0.5 text-xl font-semibold text-[var(--foreground)]">{progress}%</div>+ </div>+ <div className="h-10 w-px bg-[var(--border)]" />+ <div className="text-xs text-[var(--muted-foreground)]">+ <div>{topic.map.counts.mastered}/{topic.map.counts.total} {tr("关卡", "waypoints")}</div>+ <div className="mt-1">{topic.map.modules.length} {tr("片区域", "regions")}</div>+ </div>+ </div>+ </header>++ <section className="mt-7 flex flex-col gap-4 rounded-[22px] border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm sm:flex-row sm:items-center sm:justify-between sm:p-5">+ <div className="flex items-start gap-3">+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--primary)]/10 text-[var(--primary)]">+ {topic.next.action === "complete" ? <Sparkles className="h-4 w-4" /> : <Compass className="h-4 w-4" />}+ </span>+ <div>+ <div className="text-[10px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ {tr("下一段路", "Next on the trail")}+ </div>+ <div className="mt-1 text-sm font-semibold text-[var(--foreground)]">+ {topic.next.knowledge_point_name || tr("完成庆祝", "Celebrate completion")}+ </div>+ <p className="mt-1 text-xs leading-5 text-[var(--muted-foreground)]">+ {zh ? nextCopy.zh : nextCopy.en}+ </p>+ </div>+ </div>+ <Link+ href={+ sessions[0]+ ? `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(sessions[0].session_id)}`+ : `/space/learning/${encodeURIComponent(pathId)}/study`+ }+ className="inline-flex h-10 shrink-0 items-center justify-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] transition hover:-translate-y-0.5"+ >+ <Radio className="h-4 w-4" />+ {topic.session_count > 0 ? tr("继续远征", "Continue expedition") : tr("开始第一关", "Begin first waypoint")}+ <ArrowRight className="h-3.5 w-3.5" />+ </Link>+ </section>++ <div className="mt-6 grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">+ <AdventureMap+ topic={topic}+ revision={Math.max(topic.path_revision, activity.revision)}+ selectedId={selectedId}+ tr={tr}+ zh={zh}+ onSelect={setSelectedId}+ onOverride={handleOverride}+ />+ <div className="space-y-5 lg:sticky lg:top-6">+ <SessionCamp+ pathId={pathId}+ sessions={sessions}+ loading={sessionsLoading}+ tr={tr}+ zh={zh}+ />+ <ReviewTrail+ reviews={topic.reviews}+ tr={tr}+ zh={zh}+ onSelect={(objectiveId) => {+ setSelectedId(objectiveId);+ document.getElementById("mastery-map-start")?.scrollIntoView({+ behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches+ ? "auto"+ : "smooth",+ });+ }}+ />+ </div>+ </div>+ </div>+ {editorOpen && (+ <EditTopicRouteDialog+ topic={topic}+ tr={tr}+ onClose={() => setEditorOpen(false)}+ onSaved={(next) => {+ setTopic(next);+ setSelectedId(null);+ setEditorOpen(false);+ activity.refresh();+ }}+ />+ )}+ </main>+ );+}diff --git a/web/app/(utility)/space/learning/[pathId]/study/[[...sessionId]]/page.tsx b/web/app/(utility)/space/learning/[pathId]/study/[[...sessionId]]/page.tsxnew file mode 100644index 000000000..6a37e3fd6--- /dev/null+++ b/web/app/(utility)/space/learning/[pathId]/study/[[...sessionId]]/page.tsx@@ -0,0 +1,19 @@+"use client";++import { useParams } from "next/navigation";++import { MasteryStudy } from "@/components/space/learning/MasteryStudy";++export default function MasteryStudyPage() {+ const params = useParams<{ pathId: string; sessionId?: string[] }>();+ const routeSessionId = Array.isArray(params.sessionId)+ ? params.sessionId[0]+ : undefined;++ return (+ <MasteryStudy+ pathId={String(params.pathId || "")}+ routeSessionId={routeSessionId}+ />+ );+}diff --git a/web/app/(utility)/space/learning/layout.tsx b/web/app/(utility)/space/learning/layout.tsxnew file mode 100644index 000000000..082339721--- /dev/null+++ b/web/app/(utility)/space/learning/layout.tsx@@ -0,0 +1,9 @@+import { UnifiedChatProvider } from "@/context/UnifiedChatContext";++import "@/components/space/learning/mastery-theme.css";++export default function MasteryLayout({+ children,+}: Readonly<{ children: React.ReactNode }>) {+ return <UnifiedChatProvider>{children}</UnifiedChatProvider>;+}diff --git a/web/app/(utility)/space/learning/page.tsx b/web/app/(utility)/space/learning/page.tsxindex f02524584..d493a8375 100644--- a/web/app/(utility)/space/learning/page.tsx+++ b/web/app/(utility)/space/learning/page.tsx@@ -1,477 +1,72 @@"use client";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";-import {- GraduationCap,- Loader2,- RotateCcw,- Trash2,- MessageSquare,-} from "lucide-react";+import { CreateTopicWizard } from "@/components/space/learning/CreateTopicWizard";+import type { Translate } from "@/components/space/learning/format";+import { TopicAtlas } from "@/components/space/learning/TopicAtlas";import {- fetchAllProgress,- fetchMasteryMap,- deleteProgress,- redoProgress,- renameProgress,- skipPendingQuestion,- type ProgressSummary,- type MasteryMapResult,+ fetchMasteryTopics,+ type MasteryTopic,} from "@/lib/learning-api";-import { newMasteryPathChatUrl } from "@/lib/chat-launch-intent";-import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";-import { ActivityTimeline } from "@/components/space/learning/ActivityTimeline";-import { PathMap } from "@/components/space/learning/PathMap";-import { PathTitle } from "@/components/space/learning/PathTitle";-import { formatRelative } from "@/components/space/learning/format";-/**- * Mastery Path dashboard — the persistent "screen" of the mastery experience.- *- * The tutoring itself runs on the chat agent loop (pick "Mastery Path" mode in- * Chat); this page is the map of where the learner stands, and it follows- * along live: the engine's event feed is polled for anything past the revision- * already on screen, and every read here re-runs when the path moves. So a- * learner can keep this open beside a tutoring conversation and watch the gate- * clear. "Continue" starts a focused chat while retaining the selected path.- */export default function MasteryPathPage() {- const { i18n } = useTranslation();- const zh = !!i18n.language?.toLowerCase().startsWith("zh");- const tr = useCallback((cn: string, en: string) => (zh ? cn : en), [zh]);const router = useRouter();+ const { i18n } = useTranslation();+ const zh = Boolean(i18n.language?.toLowerCase().startsWith("zh"));+ const tr: Translate = useCallback(+ (cn: string, en: string) => (zh ? cn : en),+ [zh],+ );+ const [topics, setTopics] = useState<MasteryTopic[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [wizardOpen, setWizardOpen] = useState(false);- const [paths, setPaths] = useState<ProgressSummary[]>([]);- const [selected, setSelected] = useState<string | null>(null);- const [detail, setDetail] = useState<MasteryMapResult | null>(null);- const [loadingList, setLoadingList] = useState(true);- const [loadingDetail, setLoadingDetail] = useState(false);- const [tab, setTab] = useState<"map" | "activity">("map");-- const { events, revision, refresh } = useMasteryPathActivity(selected);-- const loadList = useCallback(async () => {+ const loadTopics = useCallback(async () => {+ setError(null);try {- const result = await fetchAllProgress();- const withContent = result.summaries- .filter((s) => s.kp_count > 0)- .sort((a, b) => b.updated_at - a.updated_at);- setPaths(withContent);- setSelected((prev) => prev ?? withContent[0]?.book_id ?? null);- } catch {- setPaths([]);+ setTopics(await fetchMasteryTopics({ cache: "no-store" }));+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : tr("暂时无法读取地图。", "The atlas could not be loaded."),+ );} finally {- setLoadingList(false);+ setLoading(false);}- }, []);-- /* The list carries per-path mastery, so it is as live as the map. */- useEffect(() => {- void loadList();- }, [loadList, revision]);+ }, [tr]);- /* Re-read the map whenever the path advances — `revision` is that signal. */useEffect(() => {- if (!selected) {- setDetail(null);- return;- }- const controller = new AbortController();- setLoadingDetail(- (wasLoading) => wasLoading || detail?.book_id !== selected,- );- fetchMasteryMap(selected, { signal: controller.signal })- .then(setDetail)- .catch(() => {- if (!controller.signal.aborted) setDetail(null);- })- .finally(() => setLoadingDetail(false));- return () => controller.abort();- // `detail` is read only to decide whether to show a spinner; depending on- // it would refetch the map every time the map arrives.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [selected, revision]);-- /* Objective id → name, so the activity feed reads in the learner's terms. */- const objectiveNames = useMemo(() => {- const names: Record<string, string> = {};- for (const group of detail?.map.modules ?? [])- for (const kp of group.knowledge_points) names[kp.id] = kp.name;- return names;- }, [detail]);-- /* Mutations refresh through the same path as the tutor's own changes. */- const afterMutation = useCallback(async () => {- await loadList();- refresh();- }, [loadList, refresh]);-- const handleDelete = useCallback(- async (pathId: string) => {- if (- !window.confirm(- tr("确定删除这条精通之路?", "Delete this mastery path?"),- )- )- return;- await deleteProgress(pathId);- setSelected(null);- await afterMutation();- },- [afterMutation, tr],- );-- const handleRedo = useCallback(- async (pathId: string) => {- if (- !window.confirm(- tr(- "重置进度?知识点保留,但掌握度与复习计划清空。",- "Reset progress? Objectives are kept, but mastery and reviews are cleared.",- ),- )- )- return;- await redoProgress(pathId);- await afterMutation();- },- [afterMutation, tr],- );-- const handleRename = useCallback(- async (pathId: string, name: string) => {- const { name: applied } = await renameProgress(pathId, name);- // Show it at once. Everything else on this page refreshes by noticing a- // new revision in the event feed, which is right for changes made by a- // tutoring turn elsewhere and wrong for an edit made right here: the- // title would stay stale for up to one poll interval.- setDetail((previous) =>- previous && previous.book_id === pathId- ? {- ...previous,- name: applied,- map: { ...previous.map, name: applied },- }- : previous,- );- await afterMutation();- },- [afterMutation],- );-- const handleSkipQuestion = useCallback(- async (pathId: string) => {- if (- !window.confirm(- tr(- "跳过这道待回答的题目?已掌握的进度都会保留。",- "Skip the question awaiting an answer? Mastery already earned is kept.",- ),- )- )- return;- await skipPendingQuestion(pathId);- await afterMutation();- },- [afterMutation, tr],- );+ void loadTopics();+ }, [loadTopics]);return (- <div className="flex h-full">- {/* Path list */}- <aside className="flex w-64 shrink-0 flex-col border-r border-[var(--border)]">- <header className="border-b border-[var(--border)] px-4 py-3">- <div className="flex items-center gap-2 text-[var(--foreground)]">- <GraduationCap className="h-4 w-4" />- <h1 className="text-sm font-semibold">- {tr("精通之路", "Mastery Path")}- </h1>- </div>- <p className="mt-1 text-xs text-[var(--muted-foreground)]">- {tr(- "掌握式学习:硬门槛 + 间隔复习",- "Mastery-based learning: hard gate + spaced review",- )}- </p>- </header>- <div className="flex-1 space-y-1 overflow-y-auto p-2">- {loadingList ? (- <div className="flex items-center justify-center py-8 text-[var(--muted-foreground)]">- <Loader2 className="h-4 w-4 animate-spin" />- </div>- ) : paths.length === 0 ? (- <p className="px-2 py-3 text-xs leading-relaxed text-[var(--muted-foreground)]">- {tr(- "还没有精通之路。去「对话」选择 Mastery Path 模式,让导师根据你的材料建一条。",- "No paths yet. Open Chat, pick Mastery Path mode, and ask the tutor to build one from your materials.",- )}- </p>- ) : (- paths.map((path) => (- <button- key={path.book_id}- onClick={() => setSelected(path.book_id)}- className={`w-full cursor-pointer rounded-md px-3 py-2 text-left transition-colors ${- selected === path.book_id- ? "bg-[var(--primary)]/10 ring-1 ring-[var(--primary)]/30"- : "hover:bg-[var(--accent)]"- }`}- >- <div className="truncate text-sm text-[var(--foreground)]">- {path.name}- </div>- <div className="mt-0.5 text-xs text-[var(--muted-foreground)]">- {path.kp_count} {tr("个知识点", "objectives")} ·{" "}- {path.avg_mastery_pct}%- </div>- </button>- ))- )}- </div>- <footer className="border-t border-[var(--border)] p-2">- <button- onClick={() => router.push("/home")}- className="flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] transition-opacity hover:opacity-90"- >- <MessageSquare className="h-3.5 w-3.5" />- {tr("新建(在对话中)", "New (in Chat)")}- </button>- </footer>- </aside>-- {/* Selected path */}- <section className="flex-1 overflow-y-auto">- {loadingDetail && !detail ? (- <div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">- <Loader2 className="h-5 w-5 animate-spin" />- </div>- ) : !detail || !selected ? (- <div className="flex h-full flex-col items-center justify-center px-6 text-center text-[var(--muted-foreground)]">- <GraduationCap className="mb-3 h-10 w-10 opacity-40" />- <p className="max-w-sm text-sm leading-relaxed">- {tr(- "选择一条精通之路查看进度地图,或在「对话」里用 Mastery Path 模式开始。",- "Select a path to see its progress map, or start one in Chat with Mastery Path mode.",- )}- </p>- </div>- ) : (- <PathView- pathId={selected}- result={detail}- onRename={(name) => handleRename(selected, name)}- revision={revision}- events={events}- objectiveNames={objectiveNames}- tab={tab}- onTabChange={setTab}- zh={zh}- tr={tr}- onContinue={() => router.push(newMasteryPathChatUrl(selected))}- onSkipQuestion={() => handleSkipQuestion(selected)}- onRedo={() => handleRedo(selected)}- onDelete={() => handleDelete(selected)}- />- )}- </section>- </div>- );-}--const ACTION_LABEL: Record<string, { cn: string; en: string }> = {- probe: { cn: "先探查是否已掌握", en: "Probe — test out first" },- practice: { cn: "练习直到达标", en: "Practice until the gate clears" },- assess: { cn: "用自己的话解释", en: "Explain it in your own words" },- review: { cn: "到期复习", en: "Due for review" },- answer_pending: {- cn: "有待回答的问题",- en: "A question is awaiting your answer",- },- complete: { cn: "已全部掌握 🎉", en: "All mastered 🎉" },-};--function PathView({- pathId,- result,- revision,- events,- objectiveNames,- tab,- onTabChange,- zh,- tr,- onContinue,- onRename,- onSkipQuestion,- onRedo,- onDelete,-}: {- pathId: string;- result: MasteryMapResult;- revision: number;- events: React.ComponentProps<typeof ActivityTimeline>["events"];- objectiveNames: Record<string, string>;- tab: "map" | "activity";- onTabChange: (tab: "map" | "activity") => void;- zh: boolean;- tr: (cn: string, en: string) => string;- onContinue: () => void;- onRename: (name: string) => Promise<void>;- onSkipQuestion: () => void;- onRedo: () => void;- onDelete: () => void;-}) {- const { map, next } = result;- const pct = map.counts.total- ? Math.round((map.counts.mastered / map.counts.total) * 100)- : 0;- const action = ACTION_LABEL[next.action] ?? {- cn: next.reason,- en: next.reason,- };- const lastEvent = events.length ? events[events.length - 1] : null;-- return (- <div className="mx-auto max-w-2xl px-6 py-5">- {/* Header: progress + actions */}- <div className="flex items-start justify-between gap-4">- <div className="min-w-0 flex-1">- {/* Keyed by path: an open editor belongs to the path it was- opened on, and its draft must not follow a switch. */}- <PathTitle- key={pathId}- name={result.name}- onRename={onRename}- tr={tr}- />- <div className="mt-1 flex items-center gap-2 text-sm text-[var(--muted-foreground)]">- <span>- {map.counts.mastered}/{map.counts.total}{" "}- {tr("已掌握", "mastered")}- </span>- {map.due_reviews > 0 && (- <span className="text-yellow-600">- · {map.due_reviews} {tr("项待复习", "due for review")}- </span>- )}- {lastEvent && (- <span>- · {tr("最近更新 ", "updated ")}- {formatRelative(lastEvent.created_at, zh)}- </span>- )}- </div>- <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--accent)]">- <div- className="h-full bg-green-500 transition-all"- style={{ width: `${pct}%` }}- />- </div>- </div>- <div className="flex shrink-0 items-center gap-1.5">- <button- onClick={onRedo}- title={tr("重置进度", "Reset progress")}- className="cursor-pointer rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--accent)]"- >- <RotateCcw className="h-4 w-4" />- </button>- <button- onClick={onDelete}- title={tr("删除", "Delete")}- className="cursor-pointer rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-red-500/10 hover:text-red-500"- >- <Trash2 className="h-4 w-4" />- </button>- </div>- </div>-- {/* Next step */}- <div className="mt-4 rounded-lg border border-[var(--border)] p-3">- <div className="text-xs text-[var(--muted-foreground)]">- {tr("接下来", "Next")}- </div>- <div className="mt-0.5 text-sm font-medium text-[var(--foreground)]">- {next.action === "complete"- ? tr(action.cn, action.en)- : `${next.knowledge_point_name} — ${tr(action.cn, action.en)}`}- </div>- {next.pending_prompt && (- <p className="mt-1 text-xs text-[var(--muted-foreground)]">- {next.pending_prompt}- </p>- )}- <div className="mt-1.5 flex items-center gap-3">- <button- onClick={onContinue}- className="cursor-pointer text-xs text-[var(--primary)] hover:underline"- >- {tr("在对话中继续辅导 →", "Continue tutoring in Chat →")}- </button>- {/* Only reachable escape from a question whose conversation is gone;- unlike Reset it keeps every mastery level already earned. */}- {next.action === "answer_pending" && (- <button- onClick={onSkipQuestion}- className="cursor-pointer text-xs text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:underline"- >- {tr("跳过这道题", "Skip this question")}- </button>- )}- </div>- </div>-- {/* Map / activity */}- <div className="mt-5 flex items-center gap-4 border-b border-[var(--border)]">- {(- [- ["map", tr("地图", "Map")],- ["activity", tr("活动", "Activity")],- ] as const- ).map(([value, label]) => (- <button- key={value}- onClick={() => onTabChange(value)}- className={`-mb-px cursor-pointer border-b-2 pb-1.5 text-xs transition-colors ${- tab === value- ? "border-[var(--primary)] text-[var(--foreground)]"- : "border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {label}- {value === "activity" && events.length > 0 && (- <span className="ml-1 text-[var(--muted-foreground)]">- {events.length}- </span>- )}- </button>- ))}- </div>-- <div className="mt-4">- {tab === "map" ? (- /* Keyed by path: switching paths must drop whichever objective was- open, since its id belongs to the path that is going away. */- <PathMap- key={pathId}- pathId={pathId}- map={map}- revision={revision}- tr={tr}- zh={zh}- />- ) : (- <ActivityTimeline- events={events}- objectiveNames={objectiveNames}- tr={tr}- zh={zh}- />- )}- </div>- </div>+ <>+ <TopicAtlas+ topics={topics}+ loading={loading}+ error={error}+ tr={tr}+ onCreate={() => setWizardOpen(true)}+ onRetry={() => {+ setLoading(true);+ void loadTopics();+ }}+ />+ {wizardOpen && (+ <CreateTopicWizard+ tr={tr}+ onClose={() => setWizardOpen(false)}+ onCreated={(topic) => {+ setWizardOpen(false);+ router.push(`/space/learning/${encodeURIComponent(topic.path_id)}`);+ }}+ />+ )}+ </>);}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 24aa5108c..344e079ad 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -45,7 +45,6 @@ import {shouldSurfaceLoadFailure,} from "@/lib/session-load";import StarterSuggestions from "@/components/chat/home/StarterSuggestions";-import MasteryPathStrip from "@/components/chat/home/MasteryPathStrip";// Imported eagerly so the drawer shell is always mounted off-screen —// clicking a chip becomes a single CSS class flip, no chunk fetch + double// render. The heavy renderers inside still load lazily.@@ -313,17 +312,6 @@ const CAPABILITIES: CapabilityDef[] = [allowedTools: [],defaultTools: [],},- {- value: "mastery_path",- label: "Mastery Path",- description: "Mastery-based tutoring with a hard gate",- icon: GraduationCap,- // The mastery tools (status/quiz/grade/assess/build) auto-mount server-side- // when this capability is active; rag auto-mounts when a KB is attached.- // These are only the extra optional tools the tutor may also reach for.- allowedTools: ["web_search", "code_execution"],- defaultTools: [],- },{value: "immersive_reading",label: "Immersive Reading",@@ -413,7 +401,6 @@ export default function ChatPage() {setCapability,setKBs,setLLMSelection,- setMasteryPathId,setPersonaSelection,sendMessage,cancelStreamingTurn,@@ -1347,7 +1334,16 @@ export default function ChatPage() {useEffect(() => {if (typeof window === "undefined") return;const intent = readChatLaunchIntent(window.location.search);- if (intent.masteryPathId) setMasteryPathId(intent.masteryPathId);+ // Mastery Path now owns a dedicated product surface. Preserve old launch+ // links by forwarding them to the topic map instead of silently exposing+ // the retired generic-chat mode. Historical /home/:session transcripts+ // remain readable because they carry no launch query.+ if (intent.masteryPathId) {+ router.replace(+ `/space/learning/${encodeURIComponent(intent.masteryPathId)}`,+ );+ return;+ }if (intent.capability !== null) handleSelectCapability(intent.capability);else if (intent.tools.length) {const valid = intent.tools.filter((t): t is ToolName =>@@ -2424,14 +2420,6 @@ export default function ChatPage() {</div>)}- {/* Anchors the conversation to the path it is advancing. Only when- the mastery capability is actually driving this turn — a stale- path id on a plain chat would be a lie. */}- {state.activeCapability === "mastery_path" &&- state.masteryPathId && (- <MasteryPathStrip pathId={state.masteryPathId} />- )}-<ChatComposercomposerRef={composerRef}capMenuRef={capMenuRef}diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsxindex 15fc5cf2e..661f18776 100644--- a/web/components/chat/home/AskUserOptions.tsx+++ b/web/components/chat/home/AskUserOptions.tsx@@ -1,6 +1,13 @@"use client";-import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";+import {+ CheckCircle2,+ ChevronDown,+ ChevronLeft,+ ChevronRight,+ Flag,+ Sparkles,+} from "lucide-react";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";@@ -459,6 +466,7 @@ function normaliseAskUserPayload(raw: unknown): AskUserPayload | null {}const LETTERS = "ABCDEFGH"; // matches MAX_OPTIONS=8+type AskUserSurfaceVariant = "default" | "mastery";/*** Render the ``ask_user`` card.@@ -474,6 +482,7 @@ export const AskUserOptions = memo(function AskUserOptions({onSubmit,collapsible,defaultCollapsed,+ variant = "default",}: {data: AskUserCardData;onSubmit: (payload: {@@ -488,6 +497,8 @@ export const AskUserOptions = memo(function AskUserOptions({collapsible?: boolean;/** Only honoured when ``collapsible`` is true. */defaultCollapsed?: boolean;+ /** The mastery study surface presents the prompt as a map checkpoint. */+ variant?: AskUserSurfaceVariant;}) {if (data.resolved) {return (@@ -495,11 +506,18 @@ export const AskUserOptions = memo(function AskUserOptions({payload={data.payload}answers={data.answers ?? []}collapsible={collapsible ?? true}- defaultCollapsed={defaultCollapsed ?? true}+ defaultCollapsed={defaultCollapsed ?? variant !== "mastery"}+ variant={variant}/>);}- return <InteractiveAskUserCard payload={data.payload} onSubmit={onSubmit} />;+ return (+ <InteractiveAskUserCard+ payload={data.payload}+ onSubmit={onSubmit}+ variant={variant}+ />+ );});AskUserOptions.displayName = "AskUserOptions";@@ -508,12 +526,14 @@ AskUserOptions.displayName = "AskUserOptions";const InteractiveAskUserCard = memo(function InteractiveAskUserCard({payload,onSubmit,+ variant,}: {payload: AskUserPayload;onSubmit: (payload: {text?: string;answers?: Array<{ questionId: string; text: string }>;}) => void;+ variant: AskUserSurfaceVariant;}) {const { t } = useTranslation();const totalQuestions = payload.questions.length;@@ -628,13 +648,41 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({}, []);return (- <div className="mt-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_14px_rgba(0,0,0,0.04)]">+ <div+ className={+ variant === "mastery"+ ? "mastery-map-paper relative mt-4 overflow-hidden rounded-[22px] border-2 border-[color-mix(in_srgb,var(--mastery-route)_35%,transparent)] p-5 shadow-[0_14px_40px_rgba(71,52,36,0.12)]"+ : "mt-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_14px_rgba(0,0,0,0.04)]"+ }+ >+ {variant === "mastery" ? (+ <div className="pointer-events-none absolute right-5 top-4 rotate-6 rounded-full border border-[var(--mastery-ink)]/15 px-3 py-1 text-[9px] font-black uppercase tracking-[0.22em] text-[var(--mastery-ink)]/30">+ {t("Knowledge check")}+ </div>+ ) : null}<div className="flex items-start gap-3">- <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--foreground)_8%,transparent)] text-[12px] font-semibold text-[var(--foreground)]/70">- ?+ <div+ className={+ variant === "mastery"+ ? "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--mastery-route)] text-white shadow-sm"+ : "flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--foreground)_8%,transparent)] text-[12px] font-semibold text-[var(--foreground)]/70"+ }+ >+ {variant === "mastery" ? <Flag size={18} /> : "?"}</div><div className="flex-1">- <div className="text-[13px] font-medium leading-snug text-[var(--foreground)]">+ {variant === "mastery" ? (+ <div className="mb-1 flex items-center gap-1.5 text-[10px] font-black uppercase tracking-[0.18em] text-[var(--mastery-route)]">+ <Sparkles size={12} /> {t("Waypoint challenge")}+ </div>+ ) : null}+ <div+ className={+ variant === "mastery"+ ? "max-w-[80%] text-[15px] font-semibold leading-snug text-[var(--mastery-ink)]"+ : "text-[13px] font-medium leading-snug text-[var(--foreground)]"+ }+ >{payload.intro || t("Please answer to continue.")}</div><div className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">@@ -663,7 +711,9 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({className={"flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11.5px] font-medium transition-all " +(isActive- ? "border-[var(--foreground)]/35 bg-[color-mix(in_srgb,var(--foreground)_5%,transparent)] text-[var(--foreground)]"+ ? variant === "mastery"+ ? "border-[var(--mastery-route)]/50 bg-[var(--mastery-route)]/10 text-[var(--mastery-route)]"+ : "border-[var(--foreground)]/35 bg-[color-mix(in_srgb,var(--foreground)_5%,transparent)] text-[var(--foreground)]": "border-[var(--border)] bg-transparent text-[var(--muted-foreground)] hover:border-[var(--foreground)]/25 hover:text-[var(--foreground)]") +" disabled:cursor-not-allowed disabled:opacity-60"}@@ -697,6 +747,7 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({onPickOption={(label) => pickOption(activeQuestion, label)}onSelectCustom={() => selectCustom(activeQuestion)}onCustomTextChange={(text) => updateCustomText(activeQuestion.id, text)}+ variant={variant}/><div className="mt-3 flex items-center justify-between gap-2 border-t border-[var(--border)]/60 pt-3">@@ -736,7 +787,11 @@ const InteractiveAskUserCard = memo(function InteractiveAskUserCard({type="button"onClick={handleSubmit}disabled={submitted}- className="rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ className={+ variant === "mastery"+ ? "rounded-xl bg-[var(--mastery-route)] px-4 py-2 text-[12px] font-bold text-white shadow-sm transition-transform hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-40"+ : "rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ }>{totalQuestions > 1 ? t("Submit answers") : t("Submit")}</button>@@ -756,6 +811,7 @@ const QuestionBody = memo(function QuestionBody({onPickOption,onSelectCustom,onCustomTextChange,+ variant,}: {question: AskUserQuestion;pickedLabels: string[];@@ -765,6 +821,7 @@ const QuestionBody = memo(function QuestionBody({onPickOption: (label: string) => void;onSelectCustom: () => void;onCustomTextChange: (text: string) => void;+ variant: AskUserSurfaceVariant;}) {const { t } = useTranslation();const textareaRef = useRef<HTMLTextAreaElement>(null);@@ -777,7 +834,13 @@ const QuestionBody = memo(function QuestionBody({return (<>- <div className="mt-3 text-[14px] font-medium leading-snug text-[var(--foreground)]">+ <div+ className={+ variant === "mastery"+ ? "mt-4 text-[16px] font-bold leading-snug text-[var(--mastery-ink)]"+ : "mt-3 text-[14px] font-medium leading-snug text-[var(--foreground)]"+ }+ >{question.prompt}{question.multi_select ? (<span className="ml-1.5 text-[11px] font-normal text-[var(--muted-foreground)]">@@ -800,9 +863,15 @@ const QuestionBody = memo(function QuestionBody({onClick={() => !locked && onPickOption(option.label)}disabled={locked}className={- "group flex w-full items-center gap-3 rounded-xl border px-3 py-2 text-left transition-all " ++ `group flex w-full items-center gap-3 border text-left transition-all ${+ variant === "mastery"+ ? "rounded-2xl px-4 py-3"+ : "rounded-xl px-3 py-2"+ } ` +(isPicked- ? "border-[var(--primary)]/70 bg-[color-mix(in_srgb,var(--primary)_7%,var(--card))] text-[var(--foreground)]"+ ? variant === "mastery"+ ? "border-[var(--mastery-route)] bg-[var(--mastery-route)]/10 text-[var(--mastery-ink)] shadow-[inset_4px_0_0_var(--mastery-route)]"+ : "border-[var(--primary)]/70 bg-[color-mix(in_srgb,var(--primary)_7%,var(--card))] text-[var(--foreground)]": "border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] hover:border-[var(--foreground)]/30 hover:bg-[color-mix(in_srgb,var(--foreground)_3%,var(--card))]") +" disabled:cursor-not-allowed disabled:opacity-60"}@@ -886,11 +955,13 @@ const ResolvedAskUserCard = memo(function ResolvedAskUserCard({answers,collapsible,defaultCollapsed,+ variant,}: {payload: AskUserPayload;answers: AskUserAnswer[];collapsible: boolean;defaultCollapsed: boolean;+ variant: AskUserSurfaceVariant;}) {const { t } = useTranslation();// Null means "follow defaultCollapsed"; once the user toggles, their@@ -919,7 +990,13 @@ const ResolvedAskUserCard = memo(function ResolvedAskUserCard({// Match the look-and-feel of ``ResearchOutlineEditor`` so the two// collapsible cards stack consistently in the merged research bubble.return (- <div className="my-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)] shadow-sm">+ <div+ className={+ variant === "mastery"+ ? "mastery-map-paper my-3 overflow-hidden rounded-[20px] border border-[var(--mastery-complete)]/35 shadow-sm"+ : "my-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)] shadow-sm"+ }+ ><buttontype="button"disabled={!collapsible}@@ -939,8 +1016,22 @@ const ResolvedAskUserCard = memo(function ResolvedAskUserCard({}`}/>)}- <h3 className="text-[13px] font-semibold text-[var(--foreground)]">- {t("Your answers")}+ {variant === "mastery" ? (+ <CheckCircle2+ size={15}+ className="text-[var(--mastery-complete)]"+ />+ ) : null}+ <h3+ className={+ variant === "mastery"+ ? "text-[13px] font-bold text-[var(--mastery-ink)]"+ : "text-[13px] font-semibold text-[var(--foreground)]"+ }+ >+ {variant === "mastery"+ ? t("Checkpoint complete")+ : t("Your answers")}</h3>{collapsible && collapsed && (<span className="text-[11px] text-[var(--muted-foreground)]/45">diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex f27b0c811..c75cf87e0 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -78,6 +78,8 @@ const MathAnimatorViewer = dynamic(const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {ssr: false,});++export type ChatSurfaceVariant = "default" | "mastery";const ResearchOutlineEditor = dynamic(() => import("@/components/research/ResearchOutlineEditor"),{ ssr: false },@@ -291,6 +293,7 @@ const AssistantMessage = memo(function AssistantMessage({onConfirmOutline,onSubmitUserReply,researchRequestSnapshot,+ variant = "default",}: {msg: { content: string; capability?: string; events?: StreamEvent[] };isStreaming?: boolean;@@ -298,6 +301,7 @@ const AssistantMessage = memo(function AssistantMessage({sessionId?: string | null;language?: string;researchRequestSnapshot?: MessageRequestSnapshot | null;+ variant?: ChatSurfaceVariant;onConfirmOutline?: (outline: Array<{ title: string; overview: string }>,topic: string,@@ -454,6 +458,7 @@ const AssistantMessage = memo(function AssistantMessage({}}collapsible={researchInProgress}defaultCollapsed={researchInProgress}+ variant={variant}/>) : null}<ResearchOutlineEditor@@ -532,6 +537,7 @@ const AssistantMessage = memo(function AssistantMessage({if (!onSubmitUserReply) return;onSubmitUserReply(reply);}}+ variant={variant}/>),)@@ -549,6 +555,7 @@ const AssistantMessage = memo(function AssistantMessage({if (!onSubmitUserReply) return;onSubmitUserReply(reply);}}+ variant={variant}/>) : null}{/* Credential hand-off sits below whichever body branch rendered: it@@ -1196,6 +1203,7 @@ export const ChatMessageList = memo(function ChatMessageList({onSwitchBranch,availableKbNames,onSubmitUserReply,+ variant = "default",}: {messages: ChatMessageItem[];isStreaming: boolean;@@ -1233,6 +1241,8 @@ export const ChatMessageList = memo(function ChatMessageList({) => void;/** Names of KBs confirmed to exist. Omitted when the KB list is unavailable. */availableKbNames?: Set<string>;+ /** Mastery uses a tactile challenge-card treatment for ask_user turns. */+ variant?: ChatSurfaceVariant;}) {const { t } = useTranslation();// Visible path: when no branching has happened the result is identical@@ -1483,6 +1493,7 @@ export const ChatMessageList = memo(function ChatMessageList({researchRequestSnapshot={pairedUserMessage?.requestSnapshot ?? null}+ variant={variant}/></InlineFileCardProvider><GeneratedFileCardsdiff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex f3fe5836e..4549bc4f1 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -20,6 +20,7 @@ import {PanelLeftClose,PanelLeftOpen,PenLine,+ Route,Settings,type LucideIcon,} from "lucide-react";@@ -86,6 +87,13 @@ const PRIMARY_NAV: NavEntry[] = [tooltipKey: "Book tooltip",requires: "llm",},+ {+ href: "/space/learning",+ label: "Mastery Path",+ icon: Route,+ tooltipKey: "Learn through a living mastery map",+ requires: "llm",+ },{href: "/space",label: "Learning Space",@@ -119,6 +127,16 @@ const GITHUB_REPO_URL = "https://github.com/HKUDS/DeepTutor";const DOCS_URL = "https://deeptutor.info/";const RECENTS_COLLAPSED_KEY = "deeptutor.sidebar.recentsCollapsed";+function isNavActive(pathname: string, href: string) {+ if (href === "/space") {+ return (+ (pathname === "/space" || pathname.startsWith("/space/")) &&+ !pathname.startsWith("/space/learning")+ );+ }+ return pathname === href || pathname.startsWith(`${href}/`);+}+interface SidebarShellProps {sessions?: SessionSummary[];activeSessionId?: string | null;@@ -252,7 +270,7 @@ export function SidebarShell({{/* Primary nav */}<nav className="mt-1 flex w-full flex-col items-center gap-1 px-1.5">{PRIMARY_NAV.map((item) => {- const active = pathname.startsWith(item.href);+ const active = isNavActive(pathname, item.href);const locked = navLocked(item);const description = locked? lockedTooltip@@ -312,7 +330,7 @@ export function SidebarShell({<div className="flex w-full flex-col items-center gap-1 px-1.5"><div className="my-1 h-px w-7 bg-[var(--border)]/40" />{SECONDARY_NAV.map((item) => {- const active = pathname.startsWith(item.href);+ const active = isNavActive(pathname, item.href);return (<Linkkey={item.href}@@ -392,7 +410,7 @@ export function SidebarShell({<nav className="px-2 pt-1"><div className="space-y-px">{PRIMARY_NAV.map((item) => {- const active = pathname.startsWith(item.href);+ const active = isNavActive(pathname, item.href);const locked = navLocked(item);if (locked) {return (@@ -517,7 +535,7 @@ export function SidebarShell({{/* Secondary nav + footer */}<div className="border-t border-[var(--border)]/40 px-2 py-2">{SECONDARY_NAV.map((item) => {- const active = pathname.startsWith(item.href);+ const active = isNavActive(pathname, item.href);return (<Linkkey={item.href}diff --git a/web/components/space/learning/AdventureMap.tsx b/web/components/space/learning/AdventureMap.tsxnew file mode 100644index 000000000..f1860463b--- /dev/null+++ b/web/components/space/learning/AdventureMap.tsx@@ -0,0 +1,385 @@+"use client";++import { useEffect, useState } from "react";+import {+ BookOpenCheck,+ Check,+ Circle,+ CircleDot,+ Compass,+ Flag,+ Leaf,+ Loader2,+ LockKeyhole,+ Mountain,+ Sparkles,+ Undo2,+} from "lucide-react";++import {+ fetchObjectiveReport,+ type MapKnowledgePoint,+ type MasteryTopic,+ type ObjectiveReport,+} from "@/lib/learning-api";++import type { Translate } from "./format";+import { ObjectiveDetail } from "./ObjectiveDetail";++interface Point {+ x: number;+ y: number;+}++function routePoints(seed: number, count: number): Point[] {+ const total = Math.max(1, count);+ return Array.from({ length: total }, (_, index) => {+ const band = index % 4;+ const baseX = [22, 48, 76, 55][band];+ const wobble = ((seed >>> ((index % 5) * 4)) & 7) - 3;+ return {+ x: Math.max(13, Math.min(87, baseX + wobble * 2.1)),+ y: 18 + (index / Math.max(1, total - 1)) * 66,+ };+ });+}++function routeD(points: Point[]): string {+ if (!points.length) return "";+ return points+ .map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`)+ .join(" ");+}++function statusLabel(point: MapKnowledgePoint, tr: Translate) {+ if (point.mastery_source === "learner") return tr("学习者确认", "Learner confirmed");+ if (point.status === "mastered") return tr("已掌握", "Mastered");+ if (point.status === "learning") return tr("学习中", "In progress");+ return tr("未探索", "Unexplored");+}++export function AdventureMap({+ topic,+ revision,+ selectedId,+ tr,+ zh,+ onSelect,+ onOverride,+}: {+ topic: MasteryTopic;+ revision: number;+ selectedId: string | null;+ tr: Translate;+ zh: boolean;+ onSelect: (id: string | null) => void;+ onOverride: (objectiveId: string, mastered: boolean, note: string) => Promise<void>;+}) {+ const nextId = topic.next.knowledge_point_id;++ return (+ <section id="mastery-map-start" aria-label={tr("精通路线地图", "Mastery route map")}>+ <div className="space-y-5">+ {topic.map.modules.map((module, moduleIndex) => {+ const points = routePoints(+ topic.metadata.map_seed + moduleIndex * 7919,+ module.knowledge_points.length,+ );+ const firstIncomplete = module.knowledge_points.findIndex(+ (point) => point.status !== "mastered",+ );+ const travelledCount =+ firstIncomplete === -1 ? points.length : Math.max(1, firstIncomplete + 1);+ return (+ <article+ key={module.id}+ className="mastery-map-paper relative overflow-hidden rounded-[26px] border border-black/10"+ >+ <header className="relative z-[3] flex items-center justify-between border-b border-black/10 bg-[var(--mastery-paper-raised)]/80 px-5 py-4">+ <div>+ <div className="text-[10px] font-semibold uppercase tracking-[0.18em] opacity-55">+ {tr(`区域 ${moduleIndex + 1}`, `Region ${moduleIndex + 1}`)}+ </div>+ <h2 className="mt-1 text-base font-semibold tracking-tight">{module.name}</h2>+ </div>+ <div className="flex items-center gap-2 text-xs opacity-65">+ {module.mastered === module.total ? (+ <BookOpenCheck className="h-4 w-4 text-emerald-700 dark:text-emerald-300" />+ ) : (+ <Compass className="h-4 w-4" />+ )}+ {module.mastered}/{module.total}+ </div>+ </header>+ <div+ className="mastery-map-grid relative min-h-[360px]"+ style={{ height: Math.max(360, module.knowledge_points.length * 92) }}+ >+ <svg+ aria-hidden="true"+ viewBox="0 0 100 100"+ preserveAspectRatio="none"+ className="absolute inset-0 z-[1] h-full w-full"+ >+ <path+ d="M -15 20 C 10 2, 26 33, 50 13 S 85 9, 115 26"+ fill="none"+ stroke="var(--mastery-moss)"+ strokeOpacity=".13"+ strokeWidth="12"+ />+ <path+ d="M -10 78 C 20 58, 38 96, 65 68 S 94 59, 112 82"+ fill="none"+ stroke="var(--mastery-water)"+ strokeOpacity=".16"+ strokeWidth="14"+ />+ <path d={routeD(points)} className="mastery-route-line" />+ <path+ d={routeD(points.slice(0, travelledCount))}+ className="mastery-route-travelled"+ />+ </svg>+ <Mountain+ aria-hidden="true"+ className="absolute right-[8%] top-[8%] z-[1] h-16 w-16 opacity-15"+ strokeWidth={1}+ />+ <Leaf+ aria-hidden="true"+ className="absolute bottom-[10%] left-[8%] z-[1] h-12 w-12 text-[var(--mastery-moss)] opacity-20"+ strokeWidth={1.2}+ />+ {points.map((position, pointIndex) => {+ const point = module.knowledge_points[pointIndex];+ const current = point.id === nextId;+ const selected = point.id === selectedId;+ return (+ <div+ key={point.id}+ className="absolute z-[2]"+ style={{ left: `${position.x}%`, top: `${position.y}%` }}+ >+ <button+ type="button"+ data-current={current ? "true" : "false"}+ onClick={() => onSelect(selected ? null : point.id)}+ aria-pressed={selected}+ aria-label={`${point.name} — ${statusLabel(point, tr)}`}+ className={`mastery-waypoint absolute left-0 top-0 flex h-12 w-12 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-2xl border-2 shadow-md outline-none focus-visible:ring-2 focus-visible:ring-[var(--mastery-route)] focus-visible:ring-offset-2 ${+ point.status === "mastered"+ ? "border-[var(--mastery-moss)] bg-[var(--mastery-moss)] text-white"+ : point.status === "learning"+ ? "border-[var(--mastery-gold)] bg-[var(--mastery-paper-raised)] text-[var(--mastery-gold)]"+ : "border-[var(--mastery-route)]/45 bg-[var(--mastery-paper-raised)] text-[var(--mastery-route)]"+ } ${selected ? "ring-2 ring-[var(--mastery-route)] ring-offset-2" : ""}`}+ >+ {point.mastery_source === "learner" ? (+ <Sparkles className="h-5 w-5" />+ ) : point.status === "mastered" ? (+ <Check className="h-5 w-5" />+ ) : point.status === "learning" ? (+ <CircleDot className="h-5 w-5" />+ ) : (+ <Circle className="h-5 w-5" />+ )}+ </button>+ <button+ type="button"+ onClick={() => onSelect(selected ? null : point.id)}+ className={`absolute left-0 top-9 w-44 -translate-x-1/2 rounded-xl border px-2.5 py-2 text-center shadow-sm transition ${+ selected+ ? "border-[var(--mastery-route)] bg-[var(--mastery-paper-raised)]"+ : "border-black/10 bg-[var(--mastery-paper-raised)]/90 hover:bg-[var(--mastery-paper-raised)]"+ }`}+ >+ <span className="line-clamp-2 text-xs font-medium leading-4">{point.name}</span>+ <span className="mt-1 block text-[9px] font-semibold uppercase tracking-[0.12em] opacity-55">+ {statusLabel(point, tr)}+ </span>+ </button>+ {current && (+ <Flag+ aria-hidden="true"+ className="absolute -right-9 -top-10 h-6 w-6 text-[var(--mastery-gold)]"+ strokeWidth={1.8}+ />+ )}+ </div>+ );+ })}+ </div>+ </article>+ );+ })}+ </div>++ {selectedId && (+ <ObjectiveDrawer+ key={selectedId}+ pathId={topic.path_id}+ objectiveId={selectedId}+ revision={revision}+ tr={tr}+ zh={zh}+ onClose={() => onSelect(null)}+ onOverride={onOverride}+ />+ )}+ </section>+ );+}++function ObjectiveDrawer({+ pathId,+ objectiveId,+ revision,+ tr,+ zh,+ onClose,+ onOverride,+}: {+ pathId: string;+ objectiveId: string;+ revision: number;+ tr: Translate;+ zh: boolean;+ onClose: () => void;+ onOverride: (objectiveId: string, mastered: boolean, note: string) => Promise<void>;+}) {+ const [report, setReport] = useState<ObjectiveReport | null>(null);+ const [noteOpen, setNoteOpen] = useState(false);+ const [note, setNote] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ const controller = new AbortController();+ fetchObjectiveReport(pathId, objectiveId, { signal: controller.signal })+ .then(setReport)+ .catch(() => {+ if (!controller.signal.aborted) setError(tr("证据读取失败", "Evidence could not be loaded"));+ });+ return () => controller.abort();+ }, [objectiveId, pathId, revision, tr]);++ const applyOverride = async (mastered: boolean) => {+ setBusy(true);+ setError(null);+ try {+ await onOverride(objectiveId, mastered, note);+ setNoteOpen(false);+ } catch (reason) {+ setError(reason instanceof Error ? reason.message : tr("更新失败", "Update failed"));+ } finally {+ setBusy(false);+ }+ };++ return (+ <aside className="mt-5 rounded-[22px] border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">+ {!report ? (+ <div className="flex min-h-32 items-center justify-center text-[var(--muted-foreground)]">+ {error ? error : <Loader2 className="h-5 w-5 animate-spin" />}+ </div>+ ) : (+ <>+ <div className="flex items-start justify-between gap-4">+ <div>+ <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-[var(--primary)]">+ {tr("关卡证据", "Waypoint evidence")}+ </div>+ <h3 className="mt-1 text-lg font-semibold text-[var(--foreground)]">{report.name}</h3>+ <div className="mt-1 flex items-center gap-2 text-xs text-[var(--muted-foreground)]">+ <span>{report.module_name}</span>+ <span>·</span>+ <span>{report.type}</span>+ {report.mastery_source === "learner" && (+ <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-amber-700 dark:text-amber-300">+ <Sparkles className="h-3 w-3" />+ {tr("由你确认", "Learner confirmed")}+ </span>+ )}+ </div>+ </div>+ <button+ type="button"+ onClick={onClose}+ className="rounded-lg px-2 py-1 text-xs text-[var(--muted-foreground)] hover:bg-[var(--accent)]"+ >+ {tr("收起", "Close")}+ </button>+ </div>+ <ObjectiveDetail report={report} tr={tr} zh={zh} />++ {!report.assessed_mastered && (+ <div className="mt-5 border-t border-[var(--border)] pt-4">+ {report.mastery_source === "learner" ? (+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="text-xs leading-5 text-[var(--muted-foreground)]">+ {tr(+ "这条路线已按你的确认放行,但测评证据仍保持原样。",+ "The route advances on your confirmation while assessed evidence remains unchanged.",+ )}+ </div>+ <button+ type="button"+ onClick={() => void applyOverride(false)}+ disabled={busy}+ className="inline-flex h-9 items-center gap-2 rounded-xl border border-[var(--border)] px-3 text-xs font-medium hover:bg-[var(--accent)] disabled:opacity-50"+ >+ {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Undo2 className="h-3.5 w-3.5" />}+ {tr("回到正常测评", "Return to assessment")}+ </button>+ </div>+ ) : noteOpen ? (+ <div>+ <label className="text-xs font-medium text-[var(--foreground)]">+ {tr("可选:为什么跳过这个关卡?", "Optional: why are you skipping this waypoint?")}+ <textarea+ autoFocus+ value={note}+ onChange={(event) => setNote(event.target.value)}+ rows={2}+ maxLength={500}+ className="mt-2 w-full resize-none rounded-xl border border-[var(--input)] bg-[var(--background)] p-3 text-xs outline-none focus:border-[var(--ring)]"+ />+ </label>+ <div className="mt-2 flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setNoteOpen(false)}+ className="h-9 rounded-xl px-3 text-xs text-[var(--muted-foreground)] hover:bg-[var(--accent)]"+ >+ {tr("取消", "Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void applyOverride(true)}+ disabled={busy}+ className="inline-flex h-9 items-center gap-2 rounded-xl bg-[var(--primary)] px-3 text-xs font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {tr("确认已掌握", "Confirm mastery")}+ </button>+ </div>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => setNoteOpen(true)}+ className="inline-flex h-9 items-center gap-2 rounded-xl border border-[var(--border)] px-3 text-xs font-medium hover:bg-[var(--accent)]"+ >+ <LockKeyhole className="h-3.5 w-3.5" />+ {tr("我已经掌握,直接放行", "I already know this — advance")}+ </button>+ )}+ {error && <p className="mt-2 text-xs text-red-600">{error}</p>}+ </div>+ )}+ </>+ )}+ </aside>+ );+}diff --git a/web/components/space/learning/CreateTopicWizard.tsx b/web/components/space/learning/CreateTopicWizard.tsxnew file mode 100644index 000000000..b5b003abf--- /dev/null+++ b/web/components/space/learning/CreateTopicWizard.tsx@@ -0,0 +1,849 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import {+ AlertCircle,+ ArrowLeft,+ ArrowRight,+ BookOpen,+ Check,+ Database,+ Loader2,+ Notebook,+ Plus,+ Sparkles,+ Target,+ Trash2,+ X,+} from "lucide-react";++import { bookApi } from "@/lib/book-api";+import { listKnowledgeBases } from "@/lib/knowledge-api";+import {+ createMasteryTopic,+ generateMasteryTopicDraft,+ type CreateTopicInput,+ type MasteryTopic,+ type ModuleInit,+ type TopicDraft,+ type TopicSourceInput,+ type TopicSourceKind,+} from "@/lib/learning-api";+import { getNotebook, listNotebooks } from "@/lib/notebook-api";++import type { Translate } from "./format";++interface SourceCandidate {+ key: string;+ kind: Exclude<TopicSourceKind, "goal" | "file" | "chat">;+ sourceId: string;+ label: string;+ detail: string;+ available: boolean;+}++interface SourceLibrary {+ books: SourceCandidate[];+ notebooks: SourceCandidate[];+ knowledgeBases: SourceCandidate[];+ failures: string[];+}++const EMPTY_LIBRARY: SourceLibrary = {+ books: [],+ notebooks: [],+ knowledgeBases: [],+ failures: [],+};++const EMOJIS = ["🧭", "🏔️", "🌿", "🔭", "🧪", "🧠", "📐", "🌌"];++export function CreateTopicWizard({+ tr,+ onClose,+ onCreated,+}: {+ tr: Translate;+ onClose: () => void;+ onCreated: (topic: MasteryTopic) => void;+}) {+ const [step, setStep] = useState(1);+ const [name, setName] = useState("");+ const [goal, setGoal] = useState("");+ const [emoji, setEmoji] = useState("🧭");+ const [library, setLibrary] = useState<SourceLibrary>(EMPTY_LIBRARY);+ const [libraryLoading, setLibraryLoading] = useState(true);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [draft, setDraft] = useState<TopicDraft | null>(null);+ const [sources, setSources] = useState<TopicSourceInput[]>([]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let disposed = false;+ Promise.allSettled([bookApi.list(), listNotebooks(), listKnowledgeBases()]).then(+ ([booksResult, notebooksResult, knowledgeResult]) => {+ if (disposed) return;+ const failures: string[] = [];+ if (booksResult.status === "rejected") failures.push(tr("书架", "Books"));+ if (notebooksResult.status === "rejected")+ failures.push(tr("笔记本", "Notebooks"));+ if (knowledgeResult.status === "rejected")+ failures.push(tr("知识库", "Knowledge bases"));+ setLibrary({+ books:+ booksResult.status === "fulfilled"+ ? booksResult.value.books.map((book) => ({+ key: `book:${book.id}`,+ kind: "book" as const,+ sourceId: book.id,+ label: book.title,+ detail: tr(+ `${book.chapter_count} 章 · ${book.status}`,+ `${book.chapter_count} chapters · ${book.status}`,+ ),+ available: book.status !== "error",+ }))+ : [],+ notebooks:+ notebooksResult.status === "fulfilled"+ ? notebooksResult.value.map((notebook) => ({+ key: `notebook:${notebook.id}`,+ kind: "notebook" as const,+ sourceId: notebook.id,+ label: notebook.name,+ detail: tr(+ `${notebook.record_count ?? 0} 条记录`,+ `${notebook.record_count ?? 0} records`,+ ),+ available: !notebook.unreadable,+ }))+ : [],+ knowledgeBases:+ knowledgeResult.status === "fulfilled"+ ? knowledgeResult.value.map((knowledgeBase) => ({+ key: `knowledge_base:${knowledgeBase.id || knowledgeBase.name}`,+ kind: "knowledge_base" as const,+ sourceId: knowledgeBase.name,+ label: knowledgeBase.name,+ detail:+ knowledgeBase.provenance_label ||+ tr(+ knowledgeBase.status === "ready" ? "可检索" : "索引状态未知",+ knowledgeBase.status === "ready" ? "Ready to retrieve" : "Index status unknown",+ ),+ available: knowledgeBase.available !== false,+ }))+ : [],+ failures,+ });+ setLibraryLoading(false);+ },+ );+ return () => {+ disposed = true;+ };+ }, [tr]);++ useEffect(() => {+ const closeOnEscape = (event: KeyboardEvent) => {+ if (event.key === "Escape" && !busy) onClose();+ };+ window.addEventListener("keydown", closeOnEscape);+ return () => window.removeEventListener("keydown", closeOnEscape);+ }, [busy, onClose]);++ const candidates = useMemo(+ () => [...library.books, ...library.notebooks, ...library.knowledgeBases],+ [library],+ );++ const toggleSource = (key: string) => {+ setSelected((previous) => {+ const next = new Set(previous);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+ };++ const hydrateSource = useCallback(+ async (candidate: SourceCandidate): Promise<TopicSourceInput> => {+ try {+ if (candidate.kind === "book") {+ const { spine } = await bookApi.getSpine(candidate.sourceId);+ return {+ kind: "book",+ source_id: candidate.sourceId,+ label: candidate.label,+ excerpt: spine.chapters+ .map(+ (chapter) =>+ `${chapter.title}: ${[+ ...chapter.learning_objectives,+ chapter.summary,+ ]+ .filter(Boolean)+ .join("; ")}`,+ )+ .join("\n")+ .slice(0, 8_000),+ available: true,+ metadata: { chapter_count: spine.chapters.length },+ };+ }+ if (candidate.kind === "notebook") {+ const notebook = await getNotebook(candidate.sourceId);+ return {+ kind: "notebook",+ source_id: candidate.sourceId,+ label: candidate.label,+ excerpt: notebook.records+ .slice(0, 16)+ .map(+ (record) =>+ `${record.title}\n${record.summary || record.user_query || ""}\n${record.output || ""}`,+ )+ .join("\n\n")+ .slice(0, 8_000),+ available: true,+ metadata: { record_count: notebook.records.length },+ };+ }+ return {+ kind: "knowledge_base",+ source_id: candidate.sourceId,+ label: candidate.label,+ excerpt: candidate.detail,+ available: candidate.available,+ };+ } catch {+ return {+ kind: candidate.kind,+ source_id: candidate.sourceId,+ label: candidate.label,+ excerpt: "",+ available: false,+ metadata: { unavailable_during_generation: true },+ };+ }+ },+ [],+ );++ const generate = async () => {+ setBusy(true);+ setError(null);+ try {+ const chosen = candidates.filter((candidate) => selected.has(candidate.key));+ const hydrated = await Promise.all(chosen.map(hydrateSource));+ const nextSources: TopicSourceInput[] = [+ {+ kind: "goal",+ label: tr("学习目标", "Learning destination"),+ excerpt: goal.trim(),+ },+ ...hydrated,+ ];+ const nextDraft = await generateMasteryTopicDraft({+ name: name.trim(),+ goal: goal.trim(),+ sources: nextSources,+ });+ setSources(nextSources);+ setDraft(nextDraft);+ setStep(3);+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : tr("路线生成失败,请重试。", "Route generation failed. Please retry."),+ );+ } finally {+ setBusy(false);+ }+ };++ const confirm = async () => {+ if (!draft) return;+ setBusy(true);+ setError(null);+ try {+ const payload: CreateTopicInput = {+ name: name.trim(),+ goal: goal.trim(),+ description: draft.description.trim(),+ emoji,+ sources,+ modules: draft.modules,+ };+ onCreated(await createMasteryTopic(payload));+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : tr("创建失败,请重试。", "Creation failed. Please retry."),+ );+ } finally {+ setBusy(false);+ }+ };++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="create-topic-title"+ className="fixed inset-0 z-50 flex items-end justify-center bg-[var(--overlay)] p-0 backdrop-blur-[2px] sm:items-center sm:p-6"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget && !busy) onClose();+ }}+ >+ <div className="flex max-h-[94dvh] w-full max-w-3xl flex-col overflow-hidden rounded-t-[26px] border border-[var(--border)] bg-[var(--card)] shadow-2xl sm:max-h-[88dvh] sm:rounded-[26px]">+ <header className="flex items-start justify-between border-b border-[var(--border)] px-5 py-4 sm:px-7 sm:py-5">+ <div>+ <div className="flex items-center gap-2 text-xs font-medium text-[var(--primary)]">+ <Sparkles className="h-3.5 w-3.5" />+ {tr("新远征", "New expedition")}+ </div>+ <h2+ id="create-topic-title"+ className="mt-1 text-xl font-semibold tracking-tight text-[var(--foreground)]"+ >+ {tr("绘制一条精通路线", "Chart a mastery route")}+ </h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ disabled={busy}+ aria-label={tr("关闭", "Close")}+ className="rounded-lg p-2 text-[var(--muted-foreground)] hover:bg-[var(--accent)] disabled:opacity-40"+ >+ <X className="h-4 w-4" />+ </button>+ </header>++ <div className="border-b border-[var(--border)] px-5 py-3 sm:px-7">+ <ol className="grid grid-cols-3 gap-2" aria-label={tr("创建步骤", "Creation steps")}>+ {[+ tr("目的地", "Destination"),+ tr("补给", "Sources"),+ tr("路线", "Route"),+ ].map((label, index) => {+ const number = index + 1;+ const active = number === step;+ const done = number < step;+ return (+ <li key={label} className="flex items-center gap-2">+ <span+ className={`flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-semibold ${+ active+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"+ : done+ ? "bg-emerald-600 text-white"+ : "bg-[var(--muted)] text-[var(--muted-foreground)]"+ }`}+ >+ {done ? <Check className="h-3 w-3" /> : number}+ </span>+ <span+ className={`hidden text-xs sm:inline ${+ active ? "font-medium text-[var(--foreground)]" : "text-[var(--muted-foreground)]"+ }`}+ >+ {label}+ </span>+ </li>+ );+ })}+ </ol>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-6 sm:px-7">+ {step === 1 && (+ <DestinationStep+ name={name}+ goal={goal}+ emoji={emoji}+ tr={tr}+ onName={setName}+ onGoal={setGoal}+ onEmoji={setEmoji}+ />+ )}+ {step === 2 && (+ <SourcesStep+ library={library}+ loading={libraryLoading}+ selected={selected}+ tr={tr}+ onToggle={toggleSource}+ />+ )}+ {step === 3 && draft && (+ <RouteDraftEditor draft={draft} tr={tr} onChange={setDraft} />+ )}+ {error && (+ <div className="mt-5 flex items-start gap-2 rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3 text-xs leading-5 text-red-700 dark:text-red-300">+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {error}+ </div>+ )}+ </div>++ <footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-4 sm:px-7">+ <button+ type="button"+ onClick={() => setStep((current) => Math.max(1, current - 1))}+ disabled={step === 1 || busy}+ className="inline-flex h-10 items-center gap-2 rounded-xl px-3 text-sm text-[var(--muted-foreground)] hover:bg-[var(--accent)] disabled:invisible"+ >+ <ArrowLeft className="h-4 w-4" />+ {tr("上一步", "Back")}+ </button>+ {step === 1 ? (+ <button+ type="button"+ onClick={() => setStep(2)}+ disabled={!name.trim() || !goal.trim()}+ className="inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {tr("选择补给", "Choose sources")}+ <ArrowRight className="h-4 w-4" />+ </button>+ ) : step === 2 ? (+ <button+ type="button"+ onClick={() => void generate()}+ disabled={busy}+ className="inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />}+ {busy ? tr("正在绘图…", "Charting…") : tr("生成路线", "Generate route")}+ </button>+ ) : (+ <button+ type="button"+ onClick={() => void confirm()}+ disabled={busy || !draft?.modules.length}+ className="inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}+ {busy ? tr("正在落图…", "Saving map…") : tr("开启远征", "Start expedition")}+ </button>+ )}+ </footer>+ </div>+ </div>+ );+}++function DestinationStep({+ name,+ goal,+ emoji,+ tr,+ onName,+ onGoal,+ onEmoji,+}: {+ name: string;+ goal: string;+ emoji: string;+ tr: Translate;+ onName: (value: string) => void;+ onGoal: (value: string) => void;+ onEmoji: (value: string) => void;+}) {+ return (+ <div className="mx-auto max-w-xl">+ <div className="mb-6 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--primary)]/10 text-[var(--primary)]">+ <Target className="h-5 w-5" />+ </div>+ <h3 className="text-lg font-semibold text-[var(--foreground)]">+ {tr("你想抵达哪里?", "Where do you want to arrive?")}+ </h3>+ <p className="mt-1 text-sm leading-6 text-[var(--muted-foreground)]">+ {tr(+ "目标越具体,地图上的关卡就越贴近你真正想获得的能力。",+ "The more specific the destination, the closer each waypoint will be to the ability you actually want.",+ )}+ </p>+ <label className="mt-6 block text-xs font-medium text-[var(--foreground)]">+ {tr("主题名称", "Topic name")}+ <input+ autoFocus+ value={name}+ onChange={(event) => onName(event.target.value)}+ maxLength={120}+ placeholder={tr("例如:线性代数", "e.g. Linear algebra")}+ className="mt-2 h-11 w-full rounded-xl border border-[var(--input)] bg-[var(--background)] px-3.5 text-sm outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/15"+ />+ </label>+ <label className="mt-5 block text-xs font-medium text-[var(--foreground)]">+ {tr("学习目的地", "Learning destination")}+ <textarea+ value={goal}+ onChange={(event) => onGoal(event.target.value)}+ maxLength={2000}+ rows={5}+ placeholder={tr(+ "我希望能从几何直觉出发,理解向量空间、线性变换,并能独立解决特征值问题。",+ "I want to build geometric intuition for vector spaces and transformations, then solve eigenvalue problems independently.",+ )}+ className="mt-2 w-full resize-none rounded-xl border border-[var(--input)] bg-[var(--background)] px-3.5 py-3 text-sm leading-6 outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/15"+ />+ </label>+ <fieldset className="mt-5">+ <legend className="text-xs font-medium text-[var(--foreground)]">+ {tr("地图徽记", "Map emblem")}+ </legend>+ <div className="mt-2 flex flex-wrap gap-2">+ {EMOJIS.map((item) => (+ <button+ key={item}+ type="button"+ onClick={() => onEmoji(item)}+ aria-pressed={emoji === item}+ className={`flex h-10 w-10 items-center justify-center rounded-xl border text-lg transition ${+ emoji === item+ ? "border-[var(--primary)] bg-[var(--primary)]/10 shadow-sm"+ : "border-[var(--border)] hover:bg-[var(--accent)]"+ }`}+ >+ {item}+ </button>+ ))}+ </div>+ </fieldset>+ </div>+ );+}++function SourcesStep({+ library,+ loading,+ selected,+ tr,+ onToggle,+}: {+ library: SourceLibrary;+ loading: boolean;+ selected: Set<string>;+ tr: Translate;+ onToggle: (key: string) => void;+}) {+ return (+ <div>+ <h3 className="text-lg font-semibold text-[var(--foreground)]">+ {tr("带上哪些学习补给?", "Which learning supplies should come along?")}+ </h3>+ <p className="mt-1 text-sm leading-6 text-[var(--muted-foreground)]">+ {tr(+ "可混合多个来源。目标本身始终会作为第一份材料,其他来源会让路线更贴近你的上下文。",+ "Mix as many sources as useful. Your destination is always included; the rest grounds the route in your own context.",+ )}+ </p>+ {loading ? (+ <div className="flex items-center justify-center py-20 text-[var(--muted-foreground)]">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ ) : (+ <div className="mt-6 space-y-6">+ <SourceSection+ icon={BookOpen}+ title={tr("Books", "Books")}+ empty={tr("书架里还没有可用内容", "No books are available yet")}+ items={library.books}+ selected={selected}+ onToggle={onToggle}+ tr={tr}+ />+ <SourceSection+ icon={Notebook}+ title={tr("Notebooks", "Notebooks")}+ empty={tr("还没有保存过笔记", "No saved notebooks yet")}+ items={library.notebooks}+ selected={selected}+ onToggle={onToggle}+ tr={tr}+ />+ <SourceSection+ icon={Database}+ title={tr("知识库", "Knowledge bases")}+ empty={tr("还没有可检索的知识库", "No retrievable knowledge bases yet")}+ items={library.knowledgeBases}+ selected={selected}+ onToggle={onToggle}+ tr={tr}+ />+ {library.failures.length > 0 && (+ <p className="flex items-center gap-2 text-xs text-amber-700 dark:text-amber-300">+ <AlertCircle className="h-3.5 w-3.5" />+ {tr(+ `${library.failures.join("、")} 暂时无法读取;仍可只用现有来源生成。`,+ `${library.failures.join(", ")} could not be loaded; you can still generate from the available sources.`,+ )}+ </p>+ )}+ </div>+ )}+ </div>+ );+}++function SourceSection({+ icon: Icon,+ title,+ empty,+ items,+ selected,+ onToggle,+ tr,+}: {+ icon: typeof BookOpen;+ title: string;+ empty: string;+ items: SourceCandidate[];+ selected: Set<string>;+ onToggle: (key: string) => void;+ tr: Translate;+}) {+ return (+ <section>+ <div className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.13em] text-[var(--muted-foreground)]">+ <Icon className="h-3.5 w-3.5" /> {title}+ </div>+ {items.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border)] px-3 py-4 text-xs text-[var(--muted-foreground)]">+ {empty}+ </div>+ ) : (+ <div className="grid gap-2 sm:grid-cols-2">+ {items.map((item) => {+ const active = selected.has(item.key);+ return (+ <button+ key={item.key}+ type="button"+ onClick={() => onToggle(item.key)}+ aria-pressed={active}+ className={`flex min-h-16 items-center gap-3 rounded-xl border p-3 text-left transition ${+ active+ ? "border-[var(--primary)] bg-[var(--primary)]/[0.06]"+ : "border-[var(--border)] hover:bg-[var(--accent)]/60"+ }`}+ >+ <span+ className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-md border ${+ active+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--input)]"+ }`}+ >+ {active && <Check className="h-3 w-3" />}+ </span>+ <span className="min-w-0">+ <span className="block truncate text-sm font-medium text-[var(--foreground)]">+ {item.label}+ </span>+ <span className="mt-0.5 block truncate text-xs text-[var(--muted-foreground)]">+ {item.available ? item.detail : tr("当前不可用", "Currently unavailable")}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ )}+ </section>+ );+}++export function RouteDraftEditor({+ draft,+ tr,+ onChange,+ compact = false,+ showDescription = true,+}: {+ draft: TopicDraft;+ tr: Translate;+ onChange: (draft: TopicDraft) => void;+ compact?: boolean;+ showDescription?: boolean;+}) {+ const updateModule = (index: number, module: ModuleInit) => {+ const modules = [...draft.modules];+ modules[index] = module;+ onChange({ ...draft, modules });+ };+ const removeModule = (index: number) =>+ onChange({+ ...draft,+ modules: draft.modules.filter((_, moduleIndex) => moduleIndex !== index),+ });+ const addModule = () => {+ const index = draft.modules.length;+ const id = `draft_m${Date.now()}`;+ onChange({+ ...draft,+ modules: [+ ...draft.modules,+ {+ id,+ name: tr(`新区域 ${index + 1}`, `New region ${index + 1}`),+ order: index,+ knowledge_points: [],+ },+ ],+ });+ };++ return (+ <div>+ {!compact && (+ <>+ <h3 className="text-lg font-semibold text-[var(--foreground)]">+ {tr("检查并调整路线", "Inspect and tune the route")}+ </h3>+ <p className="mt-1 text-sm leading-6 text-[var(--muted-foreground)]">+ {tr(+ "区域决定学习阶段,关卡决定每次导师要帮助你真正掌握的能力。现在改好,以后也能继续编辑。",+ "Regions define learning phases; waypoints define the abilities your tutor must help you truly master. Tune it now—you can edit it later too.",+ )}+ </p>+ </>+ )}+ {showDescription && (+ <label className={`${compact ? "" : "mt-5"} block text-xs font-medium text-[var(--foreground)]`}>+ {tr("地图简介", "Map description")}+ <textarea+ value={draft.description}+ onChange={(event) => onChange({ ...draft, description: event.target.value })}+ maxLength={500}+ rows={compact ? 2 : 3}+ className="mt-2 w-full resize-none rounded-xl border border-[var(--input)] bg-[var(--background)] px-3 py-2.5 text-sm leading-5 outline-none focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/15"+ />+ </label>+ )}+ <div className="mt-5 space-y-3">+ {draft.modules.map((module, moduleIndex) => (+ <div key={module.id} className="rounded-2xl border border-[var(--border)] bg-[var(--background)] p-3.5">+ <div className="flex items-center gap-2">+ <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg bg-[var(--primary)]/10 text-[11px] font-semibold text-[var(--primary)]">+ {moduleIndex + 1}+ </span>+ <input+ aria-label={tr(`第 ${moduleIndex + 1} 个区域名称`, `Region ${moduleIndex + 1} name`)}+ value={module.name}+ onChange={(event) =>+ updateModule(moduleIndex, { ...module, name: event.target.value })+ }+ maxLength={200}+ className="h-9 min-w-0 flex-1 rounded-lg border border-transparent bg-transparent px-2 text-sm font-semibold outline-none hover:border-[var(--border)] focus:border-[var(--ring)]"+ />+ <button+ type="button"+ onClick={() => removeModule(moduleIndex)}+ disabled={draft.modules.length === 1}+ aria-label={tr("删除区域", "Remove region")}+ className="rounded-lg p-2 text-[var(--muted-foreground)] hover:bg-red-500/10 hover:text-red-600 disabled:opacity-30"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div>+ <div className="mt-2 space-y-1.5 pl-8">+ {module.knowledge_points.map((point, pointIndex) => (+ <div key={point.id} className="flex items-center gap-2">+ <span className="h-2 w-2 shrink-0 rounded-full border-2 border-[var(--primary)]/60" />+ <input+ aria-label={tr("关卡名称", "Waypoint name")}+ value={point.name}+ onChange={(event) => {+ const knowledgePoints = [...module.knowledge_points];+ knowledgePoints[pointIndex] = { ...point, name: event.target.value };+ updateModule(moduleIndex, {+ ...module,+ knowledge_points: knowledgePoints,+ });+ }}+ maxLength={200}+ className="h-8 min-w-0 flex-1 rounded-lg border border-transparent bg-transparent px-2 text-xs outline-none hover:border-[var(--border)] focus:border-[var(--ring)]"+ />+ <select+ aria-label={tr("关卡类型", "Waypoint type")}+ value={point.type}+ onChange={(event) => {+ const knowledgePoints = [...module.knowledge_points];+ knowledgePoints[pointIndex] = { ...point, type: event.target.value };+ updateModule(moduleIndex, {+ ...module,+ knowledge_points: knowledgePoints,+ });+ }}+ className="h-8 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-[11px] text-[var(--muted-foreground)] outline-none"+ >+ <option value="concept">{tr("概念", "Concept")}</option>+ <option value="memory">{tr("记忆", "Memory")}</option>+ <option value="procedure">{tr("过程", "Procedure")}</option>+ <option value="design">{tr("设计", "Design")}</option>+ </select>+ <button+ type="button"+ onClick={() =>+ updateModule(moduleIndex, {+ ...module,+ knowledge_points: module.knowledge_points.filter(+ (_, index) => index !== pointIndex,+ ),+ })+ }+ disabled={module.knowledge_points.length === 1}+ aria-label={tr("删除关卡", "Remove waypoint")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:text-red-600 disabled:opacity-25"+ >+ <X className="h-3 w-3" />+ </button>+ </div>+ ))}+ <button+ type="button"+ onClick={() => {+ const id = `${module.id}_kp${Date.now()}`;+ updateModule(moduleIndex, {+ ...module,+ knowledge_points: [+ ...module.knowledge_points,+ {+ id,+ name: tr("新关卡", "New waypoint"),+ type: "concept",+ module_id: module.id,+ },+ ],+ });+ }}+ className="mt-1 inline-flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs text-[var(--primary)] hover:bg-[var(--primary)]/[0.06]"+ >+ <Plus className="h-3 w-3" />+ {tr("添加关卡", "Add waypoint")}+ </button>+ </div>+ </div>+ ))}+ </div>+ {draft.modules.length < 8 && (+ <button+ type="button"+ onClick={addModule}+ className="mt-3 inline-flex h-9 items-center gap-2 rounded-xl border border-dashed border-[var(--border)] px-3 text-xs text-[var(--muted-foreground)] hover:border-[var(--primary)]/50 hover:text-[var(--foreground)]"+ >+ <Plus className="h-3.5 w-3.5" />+ {tr("添加区域", "Add region")}+ </button>+ )}+ </div>+ );+}diff --git a/web/components/space/learning/EditTopicRouteDialog.tsx b/web/components/space/learning/EditTopicRouteDialog.tsxnew file mode 100644index 000000000..7d257aaee--- /dev/null+++ b/web/components/space/learning/EditTopicRouteDialog.tsx@@ -0,0 +1,129 @@+"use client";++import { useMemo, useState } from "react";+import { AlertTriangle, Check, Loader2, X } from "lucide-react";++import {+ type MasteryTopic,+ type ModuleInit,+ type TopicDraft,+ updateMasteryTopicMap,+} from "@/lib/learning-api";++import { RouteDraftEditor } from "./CreateTopicWizard";+import type { Translate } from "./format";++function topicDraft(topic: MasteryTopic): TopicDraft {+ return {+ description: topic.metadata.description,+ modules: topic.map.modules.map(+ (module): ModuleInit => ({+ id: module.id,+ name: module.name,+ order: module.order,+ knowledge_points: module.knowledge_points.map((point) => ({+ id: point.id,+ name: point.name,+ type: point.type,+ module_id: module.id,+ })),+ }),+ ),+ };+}++export function EditTopicRouteDialog({+ topic,+ tr,+ onClose,+ onSaved,+}: {+ topic: MasteryTopic;+ tr: Translate;+ onClose: () => void;+ onSaved: (topic: MasteryTopic) => void;+}) {+ const original = useMemo(() => topicDraft(topic), [topic]);+ const [draft, setDraft] = useState(original);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const save = async () => {+ setBusy(true);+ setError(null);+ try {+ onSaved(await updateMasteryTopicMap(topic.path_id, draft.modules));+ } catch (reason) {+ setError(reason instanceof Error ? reason.message : tr("保存失败", "Save failed"));+ } finally {+ setBusy(false);+ }+ };++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="edit-route-title"+ className="fixed inset-0 z-50 flex items-end justify-center bg-[var(--overlay)] p-0 backdrop-blur-[2px] sm:items-center sm:p-6"+ >+ <div className="flex max-h-[92dvh] w-full max-w-3xl flex-col overflow-hidden rounded-t-[26px] border border-[var(--border)] bg-[var(--card)] shadow-2xl sm:rounded-[26px]">+ <header className="flex items-start justify-between border-b border-[var(--border)] px-5 py-4 sm:px-7">+ <div>+ <div className="text-[10px] font-semibold uppercase tracking-[0.18em] text-[var(--primary)]">+ {tr("地图工坊", "Map workshop")}+ </div>+ <h2 id="edit-route-title" className="mt-1 text-xl font-semibold tracking-tight">+ {tr("编辑学习路线", "Edit learning route")}+ </h2>+ </div>+ <button+ type="button"+ onClick={onClose}+ disabled={busy}+ aria-label={tr("关闭", "Close")}+ className="rounded-lg p-2 text-[var(--muted-foreground)] hover:bg-[var(--accent)]"+ >+ <X className="h-4 w-4" />+ </button>+ </header>+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-5 sm:px-7">+ <div className="mb-5 flex items-start gap-2.5 rounded-xl border border-amber-600/20 bg-amber-500/[0.06] p-3 text-xs leading-5 text-[var(--muted-foreground)]">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />+ {tr(+ "只修改名称会保留原关卡证据;删除关卡会同时移除它的掌握度、复习计划和学习者放行记录。保存前请确认路线结构。",+ "Renaming preserves existing evidence. Removing a waypoint also removes its mastery, review schedule, and learner override. Confirm the route structure before saving.",+ )}+ </div>+ <RouteDraftEditor+ draft={draft}+ tr={tr}+ onChange={setDraft}+ compact+ showDescription={false}+ />+ {error && <p className="mt-4 text-xs text-red-600">{error}</p>}+ </div>+ <footer className="flex justify-end gap-2 border-t border-[var(--border)] px-5 py-4 sm:px-7">+ <button+ type="button"+ onClick={onClose}+ disabled={busy}+ className="h-10 rounded-xl px-4 text-sm text-[var(--muted-foreground)] hover:bg-[var(--accent)]"+ >+ {tr("取消", "Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void save()}+ disabled={busy || !draft.modules.length}+ className="inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}+ {tr("保存路线", "Save route")}+ </button>+ </footer>+ </div>+ </div>+ );+}diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsxnew file mode 100644index 000000000..7d4f3cf6a--- /dev/null+++ b/web/components/space/learning/MasteryStudy.tsx@@ -0,0 +1,493 @@+"use client";++import Link from "next/link";+import { useRouter } from "next/navigation";+import {+ ArrowLeft,+ ArrowUp,+ CheckCircle2,+ Compass,+ Flag,+ Loader2,+ Map,+ MessageCircle,+ Route,+ Square,+ Sparkles,+} from "lucide-react";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type KeyboardEvent,+} from "react";+import { useTranslation } from "react-i18next";++import { ChatMessageList } from "@/components/chat/home/ChatMessages";+import { useUnifiedChat, type SessionConfiguration } from "@/context/UnifiedChatContext";+import { fetchMasteryTopic, type MasteryTopic } from "@/lib/learning-api";+import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";+import { useImeComposing } from "@/lib/use-ime-composing";++import type { Translate } from "./format";++const STARTERS = [+ {+ icon: Compass,+ zh: "先用一道探查题看看我已经会了什么",+ en: "Start with a quick probe to see what I already know",+ },+ {+ icon: Sparkles,+ zh: "从直觉和一个具体例子开始教我",+ en: "Teach me from intuition and one concrete example",+ },+ {+ icon: Flag,+ zh: "直接给我一个有挑战性的关卡",+ en: "Give me a challenging waypoint right away",+ },+] as const;++function currentWaypoint(topic: MasteryTopic) {+ if (topic.next.knowledge_point_name) return topic.next.knowledge_point_name;+ for (const region of topic.map.modules) {+ const point = region.knowledge_points.find(+ (item) => item.status !== "mastered",+ );+ if (point) return point.name;+ }+ return topic.map.complete ? "Journey complete" : topic.name;+}++export function MasteryStudy({+ pathId,+ routeSessionId,+}: {+ pathId: string;+ routeSessionId?: string;+}) {+ const router = useRouter();+ const { i18n } = useTranslation();+ const zh = Boolean(i18n.language?.toLowerCase().startsWith("zh"));+ const tr: Translate = useCallback((cn, en) => (zh ? cn : en), [zh]);+ const {+ state,+ newSession,+ configureSession,+ loadSession,+ showCachedSession,+ sendMessage,+ cancelStreamingTurn,+ submitUserReply,+ regenerateLastMessage,+ deleteTurn,+ editMessage,+ switchBranch,+ } = useUnifiedChat();+ const [topic, setTopic] = useState<MasteryTopic | null>(null);+ const [topicError, setTopicError] = useState<string | null>(null);+ const currentRouteKey = `${pathId}:${routeSessionId || "new"}`;+ const [sessionResolution, setSessionResolution] = useState<{+ routeKey: string;+ error: string | null;+ } | null>(null);+ const [draft, setDraft] = useState("");+ const messagesEndRef = useRef<HTMLDivElement>(null);+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const initializedRouteRef = useRef("");+ const { isComposingRef, onCompositionStart, onCompositionEnd } =+ useImeComposing();++ useEffect(() => {+ let active = true;+ // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the route-owned request state before fetching.+ setTopicError(null);+ void fetchMasteryTopic(pathId, { cache: "no-store" })+ .then((result) => {+ if (active) setTopic(result);+ })+ .catch((reason: unknown) => {+ if (!active) return;+ setTopicError(+ reason instanceof Error+ ? reason.message+ : tr("学习地图读取失败", "The learning map could not be loaded"),+ );+ });+ return () => {+ active = false;+ };+ }, [pathId, tr]);++ const knowledgeBases = useMemo(+ () =>+ topic?.sources+ .filter(+ (source) =>+ source.kind === "knowledge_base" &&+ source.available &&+ source.source_id,+ )+ .map((source) => source.source_id) ?? [],+ [topic],+ );+ const sessionConfiguration = useMemo<SessionConfiguration>(+ () => ({+ capability: "mastery_path",+ masteryPathId: pathId,+ knowledgeBases,+ }),+ [knowledgeBases, pathId],+ );++ useEffect(() => {+ if (!topic) return;+ const routeKey = currentRouteKey;+ if (initializedRouteRef.current === routeKey) return;+ initializedRouteRef.current = routeKey;++ if (!routeSessionId) {+ newSession(sessionConfiguration);+ return;+ }++ const cached = showCachedSession(routeSessionId);+ if (cached) configureSession(sessionConfiguration, routeSessionId);+ void loadSession(routeSessionId, cached ? { revalidate: true } : undefined)+ .then(() => {+ configureSession(sessionConfiguration, routeSessionId);+ setSessionResolution({ routeKey, error: null });+ })+ .catch((reason: unknown) => {+ setSessionResolution({+ routeKey,+ error:+ reason instanceof Error+ ? reason.message+ : tr(+ "这个学习会话无法打开",+ "This learning session could not be opened",+ ),+ });+ });+ }, [+ configureSession,+ currentRouteKey,+ loadSession,+ newSession,+ pathId,+ routeSessionId,+ sessionConfiguration,+ showCachedSession,+ topic,+ tr,+ ]);++ useEffect(() => {+ if (routeSessionId || !state.sessionId || state.masteryPathId !== pathId)+ return;+ router.replace(+ `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(state.sessionId)}`,+ { scroll: false },+ );+ }, [pathId, routeSessionId, router, state.masteryPathId, state.sessionId]);++ const sessionError =+ sessionResolution?.routeKey === currentRouteKey+ ? sessionResolution.error+ : null;+ const sessionLoading = Boolean(+ routeSessionId &&+ sessionResolution?.routeKey !== currentRouteKey &&+ state.sessionId !== routeSessionId,+ );++ useEffect(() => {+ messagesEndRef.current?.scrollIntoView({+ behavior: state.isStreaming ? "instant" : "smooth",+ block: "end",+ });+ }, [state.isStreaming, state.messages]);++ useEffect(() => {+ const area = textareaRef.current;+ if (!area) return;+ area.style.height = "0px";+ area.style.height = `${Math.min(160, Math.max(48, area.scrollHeight))}px`;+ }, [draft]);++ const submit = useCallback(+ (value = draft) => {+ const content = value.trim();+ if (!content || state.isStreaming || sessionLoading) return;+ sendMessage(content);+ setDraft("");+ },+ [draft, sendMessage, sessionLoading, state.isStreaming],+ );++ const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (!shouldSubmitOnEnter(event, isComposingRef.current)) return;+ event.preventDefault();+ submit();+ };++ const copyAssistantMessage = useCallback(async (content: string) => {+ if (content.trim()) await navigator.clipboard.writeText(content);+ }, []);++ if (!topic && !topicError) {+ return (+ <div className="mastery-shell flex h-full items-center justify-center text-[var(--muted-foreground)]">+ <Loader2 className="h-5 w-5 animate-spin" />+ </div>+ );+ }++ if (!topic) {+ return (+ <div className="mastery-shell flex h-full flex-col items-center justify-center px-6 text-center">+ <Map className="h-10 w-10 text-[var(--muted-foreground)] opacity-40" />+ <h1 className="mt-4 text-lg font-semibold">+ {tr("找不到这张学习地图", "This learning map could not be found")}+ </h1>+ <p className="mt-2 text-sm text-[var(--muted-foreground)]">+ {topicError}+ </p>+ <Link+ href="/space/learning"+ className="mt-5 text-sm font-medium text-[var(--primary)] hover:underline"+ >+ {tr("返回地图集", "Return to atlas")}+ </Link>+ </div>+ );+ }++ const waypoint = currentWaypoint(topic);+ const completed = topic.map.counts.mastered;+ const total = topic.map.counts.total;+ const progress = total ? Math.round((completed / total) * 100) : 0;+ const hasMessages = state.messages.length > 0;++ return (+ <main className="mastery-shell flex h-full min-h-0 flex-col overflow-hidden">+ <header className="flex h-[68px] shrink-0 items-center gap-3 border-b border-[var(--border)] bg-[var(--background)]/95 px-4 backdrop-blur sm:px-6">+ <Link+ href={`/space/learning/${encodeURIComponent(pathId)}`}+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-[var(--border)] bg-[var(--card)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ aria-label={tr("返回主题地图", "Back to topic map")}+ >+ <ArrowLeft className="h-4 w-4" />+ </Link>+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-[var(--mastery-paper)] text-xl shadow-sm">+ {topic.metadata.emoji}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <h1 className="truncate text-sm font-semibold text-[var(--foreground)]">+ {topic.name}+ </h1>+ <span className="hidden rounded-full bg-[var(--mastery-route)]/10 px-2 py-0.5 text-[9px] font-bold uppercase tracking-[0.13em] text-[var(--mastery-route)] sm:inline">+ {tr("半引导学习", "Guided trail")}+ </span>+ </div>+ <p className="mt-0.5 flex items-center gap-1.5 truncate text-[11px] text-[var(--muted-foreground)]">+ <Flag className="h-3 w-3 text-[var(--mastery-gold)]" /> {waypoint}+ </p>+ </div>+ <div className="hidden items-center gap-3 sm:flex">+ <div className="h-1.5 w-24 overflow-hidden rounded-full bg-[var(--muted)]">+ <div+ className="h-full rounded-full bg-[var(--mastery-moss)] transition-[width]"+ style={{ width: `${progress}%` }}+ />+ </div>+ <span className="text-[11px] font-semibold tabular-nums text-[var(--muted-foreground)]">+ {completed}/{total}+ </span>+ </div>+ </header>++ <div className="flex min-h-0 flex-1">+ <aside className="hidden w-[264px] shrink-0 overflow-y-auto border-r border-[var(--border)] bg-[var(--card)]/40 p-4 xl:block">+ <div className="mastery-map-paper relative overflow-hidden rounded-[22px] border border-black/10 p-4">+ <div className="relative z-[1]">+ <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.17em] opacity-55">+ <Route className="h-3.5 w-3.5" /> {tr("随身路线", "Trail map")}+ </div>+ <div className="mt-4 space-y-4">+ {topic.map.modules.map((region, moduleIndex) => (+ <div key={region.id}>+ <div className="flex items-center gap-2 text-xs font-bold text-[var(--mastery-ink)]">+ <span className="flex h-5 w-5 items-center justify-center rounded-lg bg-[var(--mastery-route)]/10 text-[9px] text-[var(--mastery-route)]">+ {moduleIndex + 1}+ </span>+ <span className="truncate">{region.name}</span>+ </div>+ <div className="ml-2.5 mt-2 space-y-2 border-l border-dashed border-[var(--mastery-ink)]/20 pl-3">+ {region.knowledge_points.map((point) => (+ <div+ key={point.id}+ className={`flex items-start gap-2 text-[11px] leading-4 ${+ point.name === waypoint+ ? "font-semibold text-[var(--mastery-route)]"+ : "text-[var(--mastery-ink)]/60"+ }`}+ >+ {point.status === "mastered" ? (+ <CheckCircle2 className="mt-0.5 h-3 w-3 shrink-0 text-[var(--mastery-moss)]" />+ ) : point.name === waypoint ? (+ <Flag className="mt-0.5 h-3 w-3 shrink-0 text-[var(--mastery-gold)]" />+ ) : (+ <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-30" />+ )}+ <span>{point.name}</span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ </aside>++ <section className="flex min-w-0 flex-1 flex-col bg-[var(--background)]">+ <div className="min-h-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto w-full max-w-[900px] px-4 pb-8 pt-7 sm:px-7">+ {sessionLoading && !hasMessages ? (+ <div className="flex min-h-[45vh] flex-col items-center justify-center text-sm text-[var(--muted-foreground)]">+ <Loader2 className="mb-3 h-5 w-5 animate-spin" />+ {tr("正在回到这段旅程…", "Returning to this learning journey…")}+ </div>+ ) : sessionError && !hasMessages ? (+ <div className="mx-auto mt-20 max-w-md rounded-[22px] border border-red-500/20 bg-red-500/5 p-6 text-center">+ <MessageCircle className="mx-auto h-8 w-8 text-red-500/60" />+ <h2 className="mt-3 text-sm font-semibold">+ {tr("会话没有成功打开", "The session did not open")}+ </h2>+ <p className="mt-2 text-xs leading-5 text-[var(--muted-foreground)]">+ {sessionError}+ </p>+ <Link+ href={`/space/learning/${encodeURIComponent(pathId)}/study`}+ className="mt-4 inline-flex rounded-xl bg-[var(--primary)] px-3 py-2 text-xs font-medium text-[var(--primary-foreground)]"+ >+ {tr("开启新会话", "Start a new session")}+ </Link>+ </div>+ ) : !hasMessages ? (+ <div className="mx-auto flex min-h-[54vh] max-w-2xl flex-col items-center justify-center text-center">+ <div className="mastery-map-paper relative flex h-16 w-16 items-center justify-center overflow-hidden rounded-[24px] border border-black/10 text-3xl shadow-sm">+ <span className="relative z-[1]">{topic.metadata.emoji}</span>+ </div>+ <div className="mt-5 text-[10px] font-bold uppercase tracking-[0.2em] text-[var(--mastery-route)]">+ {tr("下一处路标", "Your next waypoint")}+ </div>+ <h2 className="mt-2 text-2xl font-semibold tracking-[-0.025em] text-[var(--foreground)]">+ {waypoint}+ </h2>+ <p className="mt-2 max-w-xl text-sm leading-6 text-[var(--muted-foreground)]">+ {tr(+ "导师会根据你的回答调整路线;你可以从探查、讲解或挑战任意一种方式出发。",+ "Your tutor will adapt the route to your answers. Begin with a probe, an intuitive explanation, or a challenge.",+ )}+ </p>+ <div className="mt-7 grid w-full gap-2 sm:grid-cols-3">+ {STARTERS.map((starter) => {+ const Icon = starter.icon;+ const label = zh ? starter.zh : starter.en;+ return (+ <button+ key={starter.en}+ type="button"+ onClick={() => submit(label)}+ disabled={state.isStreaming || sessionLoading}+ className="group rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 text-left shadow-sm transition hover:-translate-y-0.5 hover:border-[var(--mastery-route)]/35 hover:shadow-md disabled:opacity-50"+ >+ <Icon className="h-4 w-4 text-[var(--mastery-route)]" />+ <span className="mt-3 block text-xs font-medium leading-5 text-[var(--foreground)]">+ {label}+ </span>+ </button>+ );+ })}+ </div>+ </div>+ ) : (+ <ChatMessageList+ messages={state.messages}+ isStreaming={state.isStreaming}+ sessionId={state.sessionId}+ language={state.language}+ onCopyAssistantMessage={copyAssistantMessage}+ onRegenerateMessage={regenerateLastMessage}+ onDeleteTurn={deleteTurn}+ selectedBranches={state.selectedBranches}+ onEditMessage={editMessage}+ onSwitchBranch={switchBranch}+ onSubmitUserReply={submitUserReply}+ availableKbNames={new Set(knowledgeBases)}+ variant="mastery"+ />+ )}+ <div ref={messagesEndRef} className="h-px" />+ </div>+ </div>++ <div className="shrink-0 border-t border-[var(--border)] bg-[var(--background)]/95 px-3 pb-3 pt-3 backdrop-blur sm:px-6 sm:pb-5">+ <div className="mx-auto max-w-[900px]">+ <div className="relative rounded-[22px] border border-[var(--border)] bg-[var(--card)] p-2 shadow-[0_12px_36px_rgba(0,0,0,0.08)] focus-within:border-[var(--mastery-route)]/40">+ <textarea+ ref={textareaRef}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={handleKeyDown}+ onCompositionStart={onCompositionStart}+ onCompositionEnd={onCompositionEnd}+ disabled={sessionLoading}+ rows={1}+ placeholder={tr(+ `问导师关于「${waypoint}」的问题…`,+ `Ask your tutor about “${waypoint}”…`,+ )}+ className="block min-h-12 w-full resize-none bg-transparent px-3 py-2.5 pr-14 text-sm leading-6 text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/70 disabled:opacity-50"+ />+ {state.isStreaming ? (+ <button+ type="button"+ onClick={cancelStreamingTurn}+ className="absolute bottom-3 right-3 flex h-8 w-8 items-center justify-center rounded-xl bg-[var(--foreground)] text-[var(--background)]"+ aria-label={tr("停止回答", "Stop response")}+ >+ <Square className="h-3.5 w-3.5 fill-current" />+ </button>+ ) : (+ <button+ type="button"+ onClick={() => submit()}+ disabled={!draft.trim() || sessionLoading}+ className="absolute bottom-3 right-3 flex h-8 w-8 items-center justify-center rounded-xl bg-[var(--mastery-route)] text-white transition hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-30"+ aria-label={tr("发送", "Send")}+ >+ <ArrowUp className="h-4 w-4" />+ </button>+ )}+ </div>+ <p className="mt-2 text-center text-[10px] text-[var(--muted-foreground)]/65">+ {tr(+ "导师会用可验证的关卡证据更新地图;你始终可以手动覆盖掌握状态。",+ "The tutor updates your map with verifiable checkpoint evidence; you can always override mastery yourself.",+ )}+ </p>+ </div>+ </div>+ </section>+ </div>+ </main>+ );+}diff --git a/web/components/space/learning/ObjectiveDetail.tsx b/web/components/space/learning/ObjectiveDetail.tsxindex 65346f157..78acf4329 100644--- a/web/components/space/learning/ObjectiveDetail.tsx+++ b/web/components/space/learning/ObjectiveDetail.tsx@@ -113,7 +113,7 @@ export function ObjectiveDetail({<p className="text-xs text-[var(--muted-foreground)]">{tr("还没有作答记录。在对话里继续辅导后,这里会出现题目、你的回答和判分。",- "No attempts yet. Once you tutor this in Chat, the questions, your answers, and the grading show up here.",+ "No attempts yet. Once you work through this waypoint, its questions, your answers, and the grading evidence will appear here.",)}</p>)}diff --git a/web/components/space/learning/ReviewTrail.tsx b/web/components/space/learning/ReviewTrail.tsxnew file mode 100644index 000000000..7b86346b7--- /dev/null+++ b/web/components/space/learning/ReviewTrail.tsx@@ -0,0 +1,68 @@+"use client";++import { ArrowRight, BellRing, CheckCircle2, Clock3 } from "lucide-react";++import type { TopicReview } from "@/lib/learning-api";++import { formatRelative, type Translate } from "./format";++export function ReviewTrail({+ reviews,+ tr,+ zh,+ onSelect,+}: {+ reviews: TopicReview[];+ tr: Translate;+ zh: boolean;+ onSelect: (objectiveId: string) => void;+}) {+ return (+ <section className="rounded-[22px] border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-amber-500/10 text-amber-700 dark:text-amber-300">+ <BellRing className="h-4 w-4" />+ </span>+ <div>+ <h2 className="text-sm font-semibold text-[var(--foreground)]">+ {tr("复习小径", "Review trail")}+ </h2>+ <p className="text-[11px] text-[var(--muted-foreground)]">+ {tr("按记忆节奏重新点亮信标", "Relight beacons on your memory rhythm")}+ </p>+ </div>+ </div>+ <span className="text-xs text-[var(--muted-foreground)]">{reviews.length}</span>+ </div>+ {reviews.length === 0 ? (+ <div className="mt-4 flex items-start gap-2 rounded-xl bg-[var(--muted)]/55 p-3 text-xs leading-5 text-[var(--muted-foreground)]">+ <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600" />+ {tr("今天没有待复习的关卡。继续前进,系统会在合适的时候带你回来。", "Nothing is due today. Keep moving; the trail will bring you back at the right time.")}+ </div>+ ) : (+ <div className="mt-3 space-y-1.5">+ {reviews.slice(0, 5).map((review) => (+ <button+ key={review.id}+ type="button"+ onClick={() => onSelect(review.knowledge_point_id)}+ className="group flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left hover:bg-[var(--accent)]/70"+ >+ <Clock3 className={`h-3.5 w-3.5 shrink-0 ${review.due ? "text-amber-600" : "text-[var(--muted-foreground)]"}`} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs font-medium text-[var(--foreground)]">+ {review.knowledge_point_name}+ </span>+ <span className="text-[10px] text-[var(--muted-foreground)]">+ {review.due ? tr("现在可复习", "Ready now") : formatRelative(review.due_at, zh)}+ </span>+ </span>+ <ArrowRight className="h-3 w-3 text-[var(--muted-foreground)] transition-transform group-hover:translate-x-0.5" />+ </button>+ ))}+ </div>+ )}+ </section>+ );+}diff --git a/web/components/space/learning/SessionCamp.tsx b/web/components/space/learning/SessionCamp.tsxnew file mode 100644index 000000000..c439ad6d4--- /dev/null+++ b/web/components/space/learning/SessionCamp.tsx@@ -0,0 +1,137 @@+"use client";++import { useRouter } from "next/navigation";+import {+ ArrowRight,+ Flame,+ Loader2,+ MessageCircle,+ Plus,+ Radio,+} from "lucide-react";++import type { TopicSession } from "@/lib/learning-api";++import { formatRelative, type Translate } from "./format";++export function SessionCamp({+ pathId,+ sessions,+ loading,+ tr,+ zh,+}: {+ pathId: string;+ sessions: TopicSession[];+ loading: boolean;+ tr: Translate;+ zh: boolean;+}) {+ const router = useRouter();+ const openStudy = (sessionId?: string) =>+ router.push(+ sessionId+ ? `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(sessionId)}`+ : `/space/learning/${encodeURIComponent(pathId)}/study`,+ );++ return (+ <aside className="overflow-hidden rounded-[22px] border border-[var(--border)] bg-[var(--card)] shadow-sm">+ <div className="mastery-map-paper relative overflow-hidden border-b border-black/10 px-5 py-5">+ <div className="relative z-[1] flex items-start justify-between gap-3">+ <div>+ <div className="flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.18em] opacity-60">+ <Flame className="mastery-campfire h-3.5 w-3.5 text-orange-700 dark:text-orange-300" />+ {tr("会话营地", "Session camp")}+ </div>+ <h2 className="mt-1.5 text-lg font-semibold">{tr("你的学习旅程", "Your learning journeys")}</h2>+ </div>+ <button+ type="button"+ onClick={() => openStudy()}+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-[var(--mastery-ink)] text-[var(--mastery-paper-raised)] shadow-sm transition hover:-translate-y-0.5"+ aria-label={tr("新建学习会话", "Start a new learning session")}+ >+ <Plus className="h-4 w-4" />+ </button>+ </div>+ </div>+ <div className="p-3">+ {loading ? (+ <div className="flex min-h-28 items-center justify-center text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ ) : sessions.length === 0 ? (+ <div className="px-3 py-6 text-center">+ <MessageCircle className="mx-auto h-7 w-7 text-[var(--muted-foreground)] opacity-45" />+ <p className="mt-3 text-sm font-medium text-[var(--foreground)]">+ {tr("营地还没有篝火", "No campfire stories yet")}+ </p>+ <p className="mx-auto mt-1 max-w-xs text-xs leading-5 text-[var(--muted-foreground)]">+ {tr(+ "开启第一次辅导。以后每次都可以回到同一段旅程,或从新视角出发。",+ "Start your first tutoring journey. Later, resume this exact thread or begin again from a fresh angle.",+ )}+ </p>+ <button+ type="button"+ onClick={() => openStudy()}+ className="mt-4 inline-flex h-9 items-center gap-2 rounded-xl bg-[var(--primary)] px-3.5 text-xs font-medium text-[var(--primary-foreground)]"+ >+ <Plus className="h-3.5 w-3.5" />+ {tr("开始学习", "Begin learning")}+ </button>+ </div>+ ) : (+ <div className="space-y-1.5">+ {sessions.map((session) => {+ const running = session.status === "running" || Boolean(session.active_turn_id);+ return (+ <button+ key={session.session_id}+ type="button"+ onClick={() => openStudy(session.session_id)}+ className="group flex w-full items-center gap-3 rounded-xl p-3 text-left transition hover:bg-[var(--accent)]/70"+ >+ <span+ className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${+ running+ ? "bg-emerald-500/12 text-emerald-700 dark:text-emerald-300"+ : "bg-[var(--muted)] text-[var(--muted-foreground)]"+ }`}+ >+ {running ? <Radio className="h-4 w-4 animate-pulse" /> : <MessageCircle className="h-4 w-4" />}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-[var(--foreground)]">+ {session.title || tr("未命名旅程", "Untitled journey")}+ </span>+ <span className="mt-0.5 block truncate text-[11px] text-[var(--muted-foreground)]">+ {running+ ? tr("导师正在回应", "Tutor is responding")+ : `${session.message_count} ${tr("条消息", "messages")} · ${formatRelative(session.updated_at, zh)}`}+ </span>+ {session.last_message && (+ <span className="mt-1 block truncate text-[11px] text-[var(--muted-foreground)]/75">+ {session.last_message}+ </span>+ )}+ </span>+ <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)] transition-transform group-hover:translate-x-0.5" />+ </button>+ );+ })}+ <button+ type="button"+ onClick={() => openStudy()}+ className="mt-2 flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-[var(--border)] py-2.5 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"+ >+ <Plus className="h-3.5 w-3.5" />+ {tr("从新视角开启会话", "Start from a fresh angle")}+ </button>+ </div>+ )}+ </div>+ </aside>+ );+}diff --git a/web/components/space/learning/TopicAtlas.tsx b/web/components/space/learning/TopicAtlas.tsxnew file mode 100644index 000000000..3eb022d96--- /dev/null+++ b/web/components/space/learning/TopicAtlas.tsx@@ -0,0 +1,157 @@+"use client";++import { AlertCircle, Compass, Plus, RefreshCw, Sparkles } from "lucide-react";++import type { MasteryTopic } from "@/lib/learning-api";++import type { Translate } from "./format";+import { TopicMapCard } from "./TopicMapCard";++export function TopicAtlas({+ topics,+ loading,+ error,+ tr,+ onCreate,+ onRetry,+}: {+ topics: MasteryTopic[];+ loading: boolean;+ error: string | null;+ tr: Translate;+ onCreate: () => void;+ onRetry: () => void;+}) {+ const activeTopics = topics.filter((topic) => topic.metadata.status === "active");+ const dueCount = activeTopics.reduce(+ (count, topic) => count + topic.reviews.filter((review) => review.due).length,+ 0,+ );++ return (+ <main className="mastery-shell h-full overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-7xl px-5 py-8 sm:px-8 lg:px-10 lg:py-10">+ <header className="flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">+ <div>+ <div className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.2em] text-[var(--primary)]">+ <Compass className="h-4 w-4" />+ {tr("学习疆域", "Learning territories")}+ </div>+ <h1 className="text-3xl font-semibold tracking-[-0.035em] text-[var(--foreground)] sm:text-[38px]">+ {tr("你的精通地图", "Your Mastery Atlas")}+ </h1>+ <p className="mt-3 max-w-2xl text-sm leading-6 text-[var(--muted-foreground)]">+ {tr(+ "每个主题都是一片可探索的疆域。沿路线闯过知识关卡,回到营地继续任意一次学习旅程。",+ "Each topic is a territory to explore. Clear its knowledge waypoints, then return to camp and resume any learning journey.",+ )}+ </p>+ </div>+ <button+ type="button"+ onClick={onCreate}+ className="inline-flex h-11 shrink-0 items-center justify-center gap-2 rounded-xl bg-[var(--primary)] px-5 text-sm font-medium text-[var(--primary-foreground)] shadow-sm transition hover:-translate-y-0.5 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:ring-offset-2"+ >+ <Plus className="h-4 w-4" />+ {tr("开启新主题", "Chart a new topic")}+ </button>+ </header>++ {dueCount > 0 && (+ <section className="mt-8 flex items-center gap-3 rounded-2xl border border-amber-700/20 bg-amber-500/[0.07] px-4 py-3.5 text-sm text-[var(--foreground)]">+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-amber-500/15 text-amber-700 dark:text-amber-300">+ <Sparkles className="h-4 w-4" />+ </span>+ <div>+ <div className="font-medium">+ {tr(`${dueCount} 个记忆信标已亮起`, `${dueCount} review beacons are glowing`)}+ </div>+ <div className="mt-0.5 text-xs text-[var(--muted-foreground)]">+ {tr(+ "进入对应地图即可开始短复习,不会打断当前主线。",+ "Open their maps for a short review without losing your main route.",+ )}+ </div>+ </div>+ </section>+ )}++ {error && (+ <div className="mt-8 flex items-center justify-between gap-4 rounded-2xl border border-red-500/20 bg-red-500/[0.06] p-4 text-sm">+ <span className="flex items-center gap-2 text-red-700 dark:text-red-300">+ <AlertCircle className="h-4 w-4" /> {error}+ </span>+ <button+ type="button"+ onClick={onRetry}+ className="inline-flex items-center gap-1.5 font-medium text-[var(--foreground)] hover:underline"+ >+ <RefreshCw className="h-3.5 w-3.5" />+ {tr("重试", "Retry")}+ </button>+ </div>+ )}++ {loading ? (+ <div className="mt-9 grid gap-6 md:grid-cols-2 xl:grid-cols-3">+ {Array.from({ length: 6 }, (_, index) => (+ <div+ key={index}+ className="h-[360px] animate-pulse rounded-[22px] border border-[var(--border)] bg-[var(--muted)]/60"+ />+ ))}+ </div>+ ) : activeTopics.length > 0 ? (+ <section+ aria-label={tr("正在学习的主题", "Active learning topics")}+ className="mt-9 grid gap-6 md:grid-cols-2 xl:grid-cols-3"+ >+ {activeTopics.map((topic) => (+ <TopicMapCard key={topic.path_id} topic={topic} tr={tr} />+ ))}+ </section>+ ) : !error ? (+ <section className="mastery-map-paper relative mx-auto mt-12 max-w-3xl overflow-hidden rounded-[28px] border border-black/10 px-6 py-16 text-center sm:px-12">+ <svg+ aria-hidden="true"+ viewBox="0 0 700 280"+ className="absolute inset-0 h-full w-full opacity-25"+ >+ <path+ d="M -40 210 C 90 40, 180 270, 320 115 S 550 240, 760 40"+ className="mastery-route-line"+ />+ <path+ d="M 50 40 C 150 -10, 210 90, 320 35 S 520 50, 650 10"+ fill="none"+ stroke="var(--mastery-moss)"+ strokeWidth="35"+ strokeOpacity=".2"+ />+ </svg>+ <div className="relative z-[1] mx-auto flex h-16 w-16 items-center justify-center rounded-[22px] border border-black/10 bg-[var(--mastery-paper-raised)] shadow-sm">+ <Compass className="h-7 w-7 text-[var(--mastery-route)]" />+ </div>+ <h2 className="relative z-[1] mt-6 text-2xl font-semibold tracking-tight">+ {tr("地图仍是一张空白纸", "Your atlas is still uncharted")}+ </h2>+ <p className="relative z-[1] mx-auto mt-3 max-w-lg text-sm leading-6 opacity-70">+ {tr(+ "告诉 DeepTutor 你想抵达哪里,再混合你的书、笔记和知识库,我们会为你绘制第一条真正可走的路线。",+ "Tell DeepTutor where you want to arrive, mix in your books, notes, and knowledge bases, and we’ll chart your first traversable route.",+ )}+ </p>+ <button+ type="button"+ onClick={onCreate}+ className="relative z-[1] mt-7 inline-flex h-11 items-center gap-2 rounded-xl bg-[var(--mastery-ink)] px-5 text-sm font-medium text-[var(--mastery-paper-raised)] transition hover:-translate-y-0.5"+ >+ <Plus className="h-4 w-4" />+ {tr("绘制第一张地图", "Chart the first map")}+ </button>+ </section>+ ) : null}+ </div>+ </main>+ );+}diff --git a/web/components/space/learning/TopicMapCard.tsx b/web/components/space/learning/TopicMapCard.tsxnew file mode 100644index 000000000..ea800bdfe--- /dev/null+++ b/web/components/space/learning/TopicMapCard.tsx@@ -0,0 +1,177 @@+"use client";++import Link from "next/link";+import {+ BookOpen,+ CircleCheck,+ Flag,+ Mountain,+ Sparkles,+ TentTree,+} from "lucide-react";++import type { MasteryTopic } from "@/lib/learning-api";++import type { Translate } from "./format";++const ACCENTS = ["#6f7f58", "#567e7a", "#9a6b4d", "#76688a", "#8a7650"];++function miniPoints(seed: number, count: number) {+ const bounded = Math.max(2, Math.min(7, count));+ return Array.from({ length: bounded }, (_, index) => {+ const progress = index / (bounded - 1);+ const wobble = ((seed >>> ((index % 4) * 5)) & 15) - 7;+ return {+ x: 10 + progress * 80,+ y: 52 - Math.sin(progress * Math.PI) * 28 + wobble * 0.75,+ };+ });+}++function routePath(points: Array<{ x: number; y: number }>) {+ return points+ .map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`)+ .join(" ");+}++export function TopicMapCard({+ topic,+ tr,+}: {+ topic: MasteryTopic;+ tr: Translate;+}) {+ const { map, metadata } = topic;+ const total = map.counts.total;+ const mastered = map.counts.mastered;+ const progress = total ? mastered / total : 0;+ const points = miniPoints(metadata.map_seed, total || 4);+ const travelled = Math.max(0, Math.min(points.length - 1, Math.floor(progress * points.length)));+ const accent = ACCENTS[metadata.map_seed % ACCENTS.length];+ const due = topic.reviews.filter((review) => review.due).length;++ return (+ <Link+ href={`/space/learning/${encodeURIComponent(topic.path_id)}`}+ aria-label={tr(+ `打开 ${topic.name},已完成 ${mastered}/${total} 个关卡`,+ `Open ${topic.name}, ${mastered} of ${total} waypoints complete`,+ )}+ className="mastery-map-card group block overflow-hidden rounded-[22px] border border-[var(--border)] bg-[var(--card)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)]"+ >+ <div className="mastery-map-paper relative h-52 overflow-hidden border-b border-black/10">+ <svg+ aria-hidden="true"+ viewBox="0 0 100 66"+ preserveAspectRatio="none"+ className="absolute inset-0 z-[1] h-full w-full"+ >+ <path+ d="M -8 18 C 18 2, 29 31, 54 13 S 86 7, 112 24"+ fill="none"+ stroke={accent}+ strokeOpacity=".2"+ strokeWidth="7"+ />+ <path+ d="M -5 59 C 22 40, 37 66, 62 49 S 91 37, 108 54"+ fill="none"+ stroke="var(--mastery-water)"+ strokeOpacity=".18"+ strokeWidth="10"+ />+ <path d={routePath(points)} className="mastery-route-line" />+ {travelled > 0 && (+ <path+ d={routePath(points.slice(0, travelled + 1))}+ className="mastery-route-travelled"+ />+ )}+ {points.map((point, index) => {+ const complete = index <= travelled && mastered > 0;+ return (+ <g key={`${point.x}-${point.y}`}>+ <circle+ cx={point.x}+ cy={point.y}+ r={index === travelled && !map.complete ? 3.2 : 2.45}+ fill={complete ? "var(--mastery-moss)" : "var(--mastery-paper-raised)"}+ stroke={complete ? "var(--mastery-moss)" : "var(--mastery-route)"}+ strokeWidth="1"+ />+ {complete && (+ <path+ d={`M ${point.x - 1.1} ${point.y} l .7 .8 l 1.5 -1.8`}+ fill="none"+ stroke="white"+ strokeWidth=".65"+ />+ )}+ </g>+ );+ })}+ </svg>++ <div className="absolute left-5 top-5 z-[2] flex h-11 w-11 items-center justify-center rounded-2xl border border-black/10 bg-[var(--mastery-paper-raised)] text-2xl shadow-sm">+ {metadata.emoji}+ </div>+ <Mountain+ aria-hidden="true"+ className="absolute right-6 top-7 z-[2] h-11 w-11 opacity-30"+ style={{ color: accent }}+ strokeWidth={1.2}+ />+ <TentTree+ aria-hidden="true"+ className="absolute bottom-5 left-7 z-[2] h-8 w-8 text-[var(--mastery-moss)] opacity-70"+ strokeWidth={1.4}+ />+ <Flag+ aria-hidden="true"+ className="absolute bottom-6 right-7 z-[2] h-8 w-8 text-[var(--mastery-route)] opacity-80"+ strokeWidth={1.5}+ />+ {due > 0 && (+ <div className="absolute right-4 top-4 z-[3] flex items-center gap-1 rounded-full border border-amber-700/20 bg-amber-50/90 px-2 py-1 text-[10px] font-semibold text-amber-800 shadow-sm dark:bg-amber-950/80 dark:text-amber-200">+ <Sparkles className="h-3 w-3" />+ {due} {tr("待复习", "due")}+ </div>+ )}+ </div>++ <div className="p-5">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h2 className="truncate text-[17px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">+ {topic.name}+ </h2>+ <p className="mt-1 line-clamp-2 min-h-10 text-[13px] leading-5 text-[var(--muted-foreground)]">+ {metadata.description || metadata.goal}+ </p>+ </div>+ {map.complete && (+ <CircleCheck className="mt-0.5 h-5 w-5 shrink-0 text-emerald-600" />+ )}+ </div>+ <div className="mt-4 flex items-center justify-between text-xs text-[var(--muted-foreground)]">+ <span className="inline-flex items-center gap-1.5">+ <BookOpen className="h-3.5 w-3.5" />+ {map.modules.length} {tr("片区域", "regions")}+ </span>+ <span>+ {mastered}/{total} {tr("关卡", "waypoints")}+ </span>+ <span>+ {topic.session_count} {tr("次旅程", "sessions")}+ </span>+ </div>+ <div className="mt-3 h-1 overflow-hidden rounded-full bg-[var(--muted)]">+ <div+ className="h-full rounded-full transition-[width] duration-500"+ style={{ width: `${Math.round(progress * 100)}%`, backgroundColor: accent }}+ />+ </div>+ </div>+ </Link>+ );+}diff --git a/web/components/space/learning/mastery-theme.css b/web/components/space/learning/mastery-theme.cssnew file mode 100644index 000000000..1afd993c6--- /dev/null+++ b/web/components/space/learning/mastery-theme.css@@ -0,0 +1,144 @@+.mastery-shell {+ --mastery-ink: #2b342f;+ --mastery-paper: #f3ead7;+ --mastery-paper-raised: #fbf6ea;+ --mastery-route: #8c5d3b;+ --mastery-moss: #58725e;+ --mastery-complete: #58725e;+ --mastery-water: #6c8b91;+ --mastery-gold: #b77b2f;+ background: var(--background);+}++.mastery-map-paper {+ background-color: var(--mastery-paper);+ color: var(--mastery-ink);+ box-shadow:+ 0 1px 0 rgba(255, 255, 255, 0.65) inset,+ 0 18px 45px rgba(74, 54, 34, 0.1);+}++.mastery-map-paper::after {+ content: "";+ position: absolute;+ inset: 0;+ pointer-events: none;+ opacity: 0.22;+ mix-blend-mode: multiply;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='90' height='90' viewBox='0 0 90 90'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.75' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.08'/%3E%3C/svg%3E");+}++.mastery-map-grid {+ background-image:+ linear-gradient(rgba(91, 88, 71, 0.07) 1px, transparent 1px),+ linear-gradient(90deg, rgba(91, 88, 71, 0.07) 1px, transparent 1px);+ background-size: 28px 28px;+}++.mastery-route-line {+ fill: none;+ stroke: var(--mastery-route);+ stroke-width: 2.4;+ stroke-linecap: round;+ stroke-dasharray: 1 8;+}++.mastery-route-travelled {+ fill: none;+ stroke: var(--mastery-moss);+ stroke-width: 3.4;+ stroke-linecap: round;+}++.mastery-map-card {+ transform: translateZ(0);+ transition:+ transform 220ms ease,+ box-shadow 220ms ease,+ border-color 220ms ease;+}++.mastery-map-card:hover {+ transform: translateY(-3px) rotate(-0.15deg);+ box-shadow: 0 22px 55px rgba(66, 47, 29, 0.16);+}++.mastery-waypoint {+ transition:+ transform 160ms ease,+ box-shadow 160ms ease,+ border-color 160ms ease;+}++.mastery-waypoint:hover,+.mastery-waypoint:focus-visible {+ transform: translate(-50%, -50%) scale(1.08);+}++.mastery-waypoint[data-current="true"] {+ animation: mastery-pulse 2.4s ease-in-out infinite;+}++.mastery-campfire {+ animation: mastery-fire 1.8s ease-in-out infinite alternate;+ transform-origin: center bottom;+}++@keyframes mastery-pulse {+ 0%,+ 100% {+ box-shadow: 0 0 0 4px rgba(183, 123, 47, 0.18);+ }+ 50% {+ box-shadow: 0 0 0 9px rgba(183, 123, 47, 0.05);+ }+}++@keyframes mastery-fire {+ from {+ transform: scaleY(0.94) rotate(-1deg);+ }+ to {+ transform: scaleY(1.04) rotate(1deg);+ }+}++.dark .mastery-shell,+.theme-glass .mastery-shell {+ --mastery-ink: #e8e3d7;+ --mastery-paper: #202823;+ --mastery-paper-raised: #28312b;+ --mastery-route: #cf9569;+ --mastery-moss: #8ba58f;+ --mastery-complete: #8ba58f;+ --mastery-water: #7e9da4;+ --mastery-gold: #d5a052;+}++.dark .mastery-map-paper,+.theme-glass .mastery-map-paper {+ box-shadow:+ 0 1px 0 rgba(255, 255, 255, 0.05) inset,+ 0 18px 45px rgba(0, 0, 0, 0.25);+}++.dark .mastery-map-paper::after,+.theme-glass .mastery-map-paper::after {+ mix-blend-mode: screen;+ opacity: 0.08;+}++@media (prefers-reduced-motion: reduce) {+ .mastery-map-card,+ .mastery-waypoint,+ .mastery-campfire {+ animation: none !important;+ transition-duration: 0.01ms !important;+ }++ .mastery-map-card:hover,+ .mastery-waypoint:hover,+ .mastery-waypoint:focus-visible {+ transform: none;+ }+}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex d459a9a9b..f621f4ad9 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -106,6 +106,13 @@ export interface ChatState {selectedBranches: Record<string, number>;}+export interface SessionConfiguration {+ capability?: string | null;+ knowledgeBases?: string[];+ masteryPathId?: string | null;+ enabledTools?: string[];+}+interface SessionStatusSnapshot {sessionId: string;status: SessionRuntimeStatus;@@ -247,7 +254,16 @@ type Action =assistantMessageId?: number | null;}| { type: "DELETE_TURN"; key: string; messageId: number }- | { type: "NEW_SESSION"; key: string }+ | {+ type: "NEW_SESSION";+ key: string;+ configuration?: SessionConfiguration;+ }+ | {+ type: "CONFIGURE_SESSION";+ key?: string;+ configuration: SessionConfiguration;+ }| { type: "ENSURE_DRAFT_SESSION"; key: string }| {type: "SET_SELECTED_BRANCH";@@ -313,12 +329,43 @@ function updateSelectedSession(};}+function applySessionConfiguration(+ session: SessionEntry,+ configuration?: SessionConfiguration,+): SessionEntry {+ if (!configuration) return session;+ return {+ ...session,+ activeCapability:+ configuration.capability !== undefined+ ? configuration.capability+ : session.activeCapability,+ knowledgeBases:+ configuration.knowledgeBases !== undefined+ ? [...configuration.knowledgeBases]+ : session.knowledgeBases,+ masteryPathId:+ configuration.masteryPathId !== undefined+ ? configuration.masteryPathId+ : session.masteryPathId,+ enabledTools:+ configuration.enabledTools !== undefined+ ? [...configuration.enabledTools]+ : session.enabledTools,+ updatedAt: Date.now(),+ };+}+/** Add an empty session under ``key`` and make it the selected one. */-function selectFreshDraft(state: ProviderState, key: string): ProviderState {+function selectFreshDraft(+ state: ProviderState,+ key: string,+ configuration?: SessionConfiguration,+): ProviderState {const MAX_CACHED_SESSIONS = 20;const nextSessions = {...state.sessions,- [key]: createSessionEntry(key),+ [key]: applySessionConfiguration(createSessionEntry(key), configuration),};const keys = Object.keys(nextSessions);if (keys.length > MAX_CACHED_SESSIONS) {@@ -798,7 +845,20 @@ function reducer(state: ProviderState, action: Action): ProviderState {sidebarRefreshToken: state.sidebarRefreshToken + 1,};case "NEW_SESSION":- return selectFreshDraft(state, action.key);+ return selectFreshDraft(state, action.key, action.configuration);+ case "CONFIGURE_SESSION": {+ const key = action.key || state.selectedKey;+ if (!key) return state;+ const session = state.sessions[key];+ if (!session) return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [key]: applySessionConfiguration(session, action.configuration),+ },+ };+ }// Idempotent variant of NEW_SESSION: guarantees there is *a* selected// session without discarding one a page already selected and configured.// The check belongs here rather than in the caller because a mount effect@@ -872,7 +932,14 @@ interface ChatContextValue {/** Switch which sibling is currently visible at a branch point. */switchBranch: (parentMessageId: number | null, childId: number) => void;renameSessionTitle: (title: string) => Promise<void>;- newSession: () => void;+ newSession: (configuration?: SessionConfiguration) => void;+ /** Apply route-owned preferences to an explicit loaded session (or the+ * selected draft). Dispatching by key keeps this safe immediately after+ * LOAD_SESSION, before React has committed a new context render. */+ configureSession: (+ configuration: SessionConfiguration,+ sessionKey?: string,+ ) => void;/** Fetch a session and apply it. Pass ``revalidate`` when the session is* already on screen (see ``showCachedSession``): the snapshot is then* dropped rather than applied if a turn started meanwhile. */@@ -1913,10 +1980,21 @@ export function UnifiedChatProvider({});}, []);- const newSession = useCallback(() => {- dispatch({ type: "NEW_SESSION", key: makeDraftKey() });+ const newSession = useCallback((configuration?: SessionConfiguration) => {+ dispatch({ type: "NEW_SESSION", key: makeDraftKey(), configuration });}, [makeDraftKey]);+ const configureSession = useCallback(+ (configuration: SessionConfiguration, sessionKey?: string) => {+ dispatch({+ type: "CONFIGURE_SESSION",+ key: sessionKey,+ configuration,+ });+ },+ [],+ );+const editMessage = useCallback(async (messageId: number, newContent: string) => {const trimmed = newContent.trim();@@ -2049,6 +2127,7 @@ export function UnifiedChatProvider({switchBranch,renameSessionTitle,newSession,+ configureSession,loadSession,showCachedSession,selectedSessionId: derivedState.sessionId,@@ -2073,6 +2152,7 @@ export function UnifiedChatProvider({switchBranch,renameSessionTitle,newSession,+ configureSession,loadSession,showCachedSession,sessionStatuses,diff --git a/web/lib/chat-launch-intent.ts b/web/lib/chat-launch-intent.tsindex bc768e1a0..03831570c 100644--- a/web/lib/chat-launch-intent.ts+++ b/web/lib/chat-launch-intent.ts@@ -1,11 +1,9 @@/*** The `/home` launch-URL contract — both ends in one place.*- * Other surfaces (the Mastery Path dashboard, capability shortcuts) open a- * chat by navigating to `/home` with query parameters that say how the- * composer should be set up before the learner types anything. Building and- * reading that URL are two halves of one contract, so they live together and- * are covered by a round-trip test.+ * Capability shortcuts can open `/home` with query parameters that set up the+ * composer before the learner types. Mastery Path formerly used this contract;+ * its parser remains for forwarding old links to the dedicated product.** Parsing is deliberately dependency-free: tool names are returned verbatim* and validated by the caller against its own tool registry.@@ -39,11 +37,7 @@ export function readChatLaunchIntent(search: string): ChatLaunchIntent {};}-/** Build a fresh chat URL associated with existing persistent mastery state. */+/** Open a topic on the dedicated Mastery Path product surface. */export function newMasteryPathChatUrl(masteryPathId: string): string {- const params = new URLSearchParams({- capability: "mastery_path",- mastery_path_id: masteryPathId,- });- return `/home?${params.toString()}`;+ return `/space/learning/${encodeURIComponent(masteryPathId)}`;}diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.tsindex 115c9c5a1..0cf9c7878 100644--- a/web/lib/learning-api.ts+++ b/web/lib/learning-api.ts@@ -408,6 +408,8 @@ export interface TopicSession {updated_at: number;status: string;active_turn_id: string;+ message_count: number;+ last_message: string;pinned: boolean;archived: boolean;}diff --git a/web/tests/chat-launch-intent.test.ts b/web/tests/chat-launch-intent.test.tsindex 18853d8e0..20ff81d27 100644--- a/web/tests/chat-launch-intent.test.ts+++ b/web/tests/chat-launch-intent.test.ts@@ -6,16 +6,17 @@ import {readChatLaunchIntent,} from "../lib/chat-launch-intent";-test("continuing a mastery path opens a fresh associated chat", () => {+test("continuing a mastery path opens its dedicated topic surface", () => {assert.equal(newMasteryPathChatUrl("calculus/path 1"),- "/home?capability=mastery_path&mastery_path_id=calculus%2Fpath+1",+ "/space/learning/calculus%2Fpath%201",);});-test("the mastery continue URL round-trips into a launch intent", () => {- const url = newMasteryPathChatUrl("calculus/path 1");- const intent = readChatLaunchIntent(url.slice(url.indexOf("?")));+test("legacy mastery chat links still parse for forwarding", () => {+ const intent = readChatLaunchIntent(+ "?capability=mastery_path&mastery_path_id=calculus%2Fpath+1",+ );assert.equal(intent.capability, "mastery_path");assert.equal(intent.masteryPathId, "calculus/path 1");assert.deepEqual(intent.tools, []);