Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(mastery): complete v2 learning workflows

Bingxi Zhao (Frank)d57d2983ef10
diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.py
index 0b8e0d684..556bf27ad 100644
--- a/deeptutor/api/routers/mastery_path.py
+++ b/deeptutor/api/routers/mastery_path.py
@@ -19,6 +19,9 @@ from deeptutor.learning.models import (
KnowledgePoint,
KnowledgeType,
LearningModule,
+ LearningProgress,
+ MasteryInteraction,
+ MasteryTopic,
TopicMetadata,
TopicSource,
TopicSourceKind,
@@ -230,27 +233,62 @@ def _review_queue(progress) -> list[dict]:
]
-def _topic_payload(store: LearningStore, path_id: str) -> dict:
- progress = store.load(path_id)
- if progress is None:
- raise HTTPException(status_code=404, detail="Mastery topic not found")
- topic = store.get_topic(path_id)
- if topic is None: # pragma: no cover - a loaded path always synthesizes metadata
- raise HTTPException(status_code=404, detail="Mastery topic not found")
+def _next_step_payload(store: LearningStore, path_id: str, progress) -> dict:
+ interaction = (
+ store.get_active_interaction(path_id) if progress.pending_question is not None else None
+ )
+ return _next_step_from_interaction(progress, interaction)
+
+
+def _next_step_from_interaction(
+ progress: LearningProgress,
+ interaction: MasteryInteraction | None,
+) -> dict:
+ return learning_policy.next_objective(
+ progress,
+ pending_session_id=interaction.session_id if interaction is not None else "",
+ ).to_dict()
+
+
+def _topic_payload_from_snapshot(
+ progress: LearningProgress,
+ topic: MasteryTopic,
+ session_count: int,
+ active_interaction: MasteryInteraction | None,
+) -> dict:
+ path_id = progress.book_id
return {
"path_id": path_id,
"name": learning_policy.path_display_name(progress),
"metadata": topic.metadata.model_dump(mode="json"),
"sources": [source.model_dump(mode="json") for source in topic.sources],
"path_revision": progress.version,
- "next": learning_policy.next_objective(progress).to_dict(),
+ "next": _next_step_from_interaction(progress, active_interaction),
"map": learning_policy.map_summary(progress),
"reviews": _review_queue(progress),
- "session_count": len(store.list_session_ids(path_id)),
+ "session_count": session_count,
"updated_at": progress.updated_at,
}
+def _topic_payload(store: LearningStore, path_id: str) -> dict:
+ progress = store.load(path_id)
+ if progress is None:
+ raise HTTPException(status_code=404, detail="Mastery topic not found")
+ topic = store.get_topic(path_id, progress=progress)
+ if topic is None: # pragma: no cover - a loaded path always synthesizes metadata
+ raise HTTPException(status_code=404, detail="Mastery topic not found")
+ active_interaction = (
+ store.get_active_interaction(path_id) if progress.pending_question is not None else None
+ )
+ return _topic_payload_from_snapshot(
+ progress,
+ topic,
+ len(store.list_session_ids(path_id)),
+ active_interaction,
+ )
+
+
# ── Endpoints ────────────────────────────────────────────────────────────────
@@ -258,9 +296,11 @@ def _topic_payload(store: LearningStore, path_id: str) -> dict:
async def list_topics():
store = LearningStore()
topics = await asyncio.to_thread(
- lambda: [_topic_payload(store, path_id) for path_id in store.list_all()]
+ lambda: [
+ _topic_payload_from_snapshot(*snapshot)
+ for snapshot in store.list_topic_snapshots(status="active")
+ ]
)
- topics.sort(key=lambda item: item["updated_at"], reverse=True)
return {"topics": topics}
@@ -288,7 +328,7 @@ async def create_topic(body: ConfirmTopicRequest):
path_id = f"topic_{uuid.uuid4().hex}"
try:
- modules = materialize_modules(path_id, body.modules)
+ modules = materialize_modules(path_id, body.modules, strict=True)
except TopicGenerationError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
sources = _topic_sources(body.sources)
@@ -327,13 +367,27 @@ async def edit_topic_map(path_id: str, body: EditTopicMapRequest):
materialize_modules,
)
- try:
- modules = materialize_modules(path_id, body.modules)
- except TopicGenerationError as exc:
- raise HTTPException(status_code=422, detail=str(exc)) from exc
async with _exclusive_path_mutation(path_id):
+ store = LearningStore()
+ progress = await asyncio.to_thread(store.load, path_id)
+ if progress is None:
+ raise HTTPException(status_code=404, detail="Mastery topic not found")
+ existing_module_ids = {module.id for module in progress.modules}
+ existing_objective_ids = {
+ point.id for module in progress.modules for point in module.knowledge_points
+ }
+ try:
+ modules = materialize_modules(
+ path_id,
+ body.modules,
+ strict=True,
+ existing_module_ids=existing_module_ids,
+ existing_objective_ids=existing_objective_ids,
+ )
+ except TopicGenerationError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
await asyncio.to_thread(
- LearningService(LearningStore()).replace_modules_for_path,
+ LearningService(store).replace_modules_for_path,
path_id,
modules,
event_type="topic.map_edited",
@@ -380,24 +434,17 @@ async def list_topic_sessions(path_id: str):
from deeptutor.services.session import get_session_store
session_store = get_session_store()
+ active_interaction = await asyncio.to_thread(
+ learning_store.get_active_interaction,
+ path_id,
+ )
+ pending_session_id = active_interaction.session_id if active_interaction else ""
+ session_summaries = await session_store.get_session_summaries(session_ids)
sessions = []
- for session_id in session_ids:
- session = await session_store.get_session_with_messages(session_id)
- if session is None:
- continue
+ for session in session_summaries:
+ session_id = str(session.get("session_id") or session.get("id") or "")
preferences = 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()
- ),
- "",
- )
+ last_message = str(session.get("last_message") or "").strip()
sessions.append(
{
"session_id": session.get("session_id") or session.get("id") or session_id,
@@ -406,10 +453,13 @@ 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),
+ "message_count": int(session.get("message_count") or 0),
"last_message": last_message[:240],
"pinned": bool(preferences.get("pinned")),
"archived": bool(preferences.get("archived")),
+ "has_pending_question": bool(
+ pending_session_id and pending_session_id == session_id
+ ),
}
)
sessions.sort(key=lambda item: item["updated_at"], reverse=True)
@@ -508,7 +558,10 @@ async def mastery_topic_websocket(ws: WebSocket) -> None:
# Register before replay. A concurrent commit is therefore either
# present in this DB tail, queued on the subscription, or both;
# the cursor in ``forward`` removes the harmless overlap.
- subscription = mastery_topic_event_hub.subscribe(path_id)
+ subscription = mastery_topic_event_hub.subscribe(
+ path_id,
+ scope=store.event_scope,
+ )
events = await asyncio.to_thread(
store.list_events,
path_id,
@@ -562,7 +615,7 @@ async def get_progress_map(book_id: str):
"book_id": book_id,
"name": learning_policy.path_display_name(progress),
"path_revision": progress.version,
- "next": learning_policy.next_objective(progress).to_dict(),
+ "next": _next_step_payload(service.store, book_id, progress),
"map": learning_policy.map_summary(progress),
}
diff --git a/deeptutor/learning/event_hub.py b/deeptutor/learning/event_hub.py
index da756366e..2ec8b786f 100644
--- a/deeptutor/learning/event_hub.py
+++ b/deeptutor/learning/event_hub.py
@@ -24,10 +24,20 @@ class TopicSignal:
class TopicSubscription:
- def __init__(self, hub: "MasteryTopicEventHub", path_id: str) -> None:
+ def __init__(
+ self,
+ hub: "MasteryTopicEventHub",
+ path_id: str,
+ *,
+ scope: str,
+ ) -> None:
self._hub = hub
self.path_id = path_id
- self.queue: asyncio.Queue[TopicSignal] = asyncio.Queue()
+ self.scope = scope
+ # A wake-up is only a hint to replay SQLite. Keeping the newest signal
+ # is sufficient and prevents a slow/background tab from accumulating
+ # an unbounded in-memory queue.
+ self.queue: asyncio.Queue[TopicSignal] = asyncio.Queue(maxsize=1)
self.loop = asyncio.get_running_loop()
self._closed = False
self._hub._add(self)
@@ -45,26 +55,39 @@ class TopicSubscription:
class MasteryTopicEventHub:
def __init__(self) -> None:
self._lock = threading.RLock()
- self._subscriptions: dict[str, set[TopicSubscription]] = {}
+ self._subscriptions: dict[tuple[str, str], set[TopicSubscription]] = {}
self._sequence = itertools.count(1)
- def subscribe(self, path_id: str) -> TopicSubscription:
- return TopicSubscription(self, str(path_id))
+ @staticmethod
+ def _key(scope: str, path_id: str) -> tuple[str, str]:
+ return str(scope or "default"), str(path_id)
+
+ def subscribe(self, path_id: str, *, scope: str = "default") -> TopicSubscription:
+ return TopicSubscription(self, str(path_id), scope=str(scope or "default"))
def _add(self, subscription: TopicSubscription) -> None:
with self._lock:
- self._subscriptions.setdefault(subscription.path_id, set()).add(subscription)
+ key = self._key(subscription.scope, subscription.path_id)
+ self._subscriptions.setdefault(key, set()).add(subscription)
def _remove(self, subscription: TopicSubscription) -> None:
with self._lock:
- group = self._subscriptions.get(subscription.path_id)
+ key = self._key(subscription.scope, subscription.path_id)
+ group = self._subscriptions.get(key)
if not group:
return
group.discard(subscription)
if not group:
- self._subscriptions.pop(subscription.path_id, None)
-
- def publish(self, path_id: str, revision: int, reason: str = "topic.changed") -> None:
+ self._subscriptions.pop(key, None)
+
+ def publish(
+ self,
+ path_id: str,
+ revision: int,
+ reason: str = "topic.changed",
+ *,
+ scope: str = "default",
+ ) -> None:
with self._lock:
signal = TopicSignal(
path_id=str(path_id),
@@ -72,25 +95,40 @@ class MasteryTopicEventHub:
reason=str(reason or "topic.changed"),
sequence=next(self._sequence),
)
- subscriptions = list(self._subscriptions.get(signal.path_id, ()))
+ subscriptions = list(self._subscriptions.get(self._key(scope, signal.path_id), ()))
for subscription in subscriptions:
if subscription.loop.is_closed():
subscription.close()
continue
try:
subscription.loop.call_soon_threadsafe(
- subscription.queue.put_nowait,
+ self._deliver_latest,
+ subscription,
signal,
)
except RuntimeError:
subscription.close()
+ @staticmethod
+ def _deliver_latest(subscription: TopicSubscription, signal: TopicSignal) -> None:
+ if subscription._closed:
+ return
+ if subscription.queue.full():
+ subscription.queue.get_nowait()
+ subscription.queue.put_nowait(signal)
+
mastery_topic_event_hub = MasteryTopicEventHub()
-def publish_topic_signal(path_id: str, revision: int, reason: str = "topic.changed") -> None:
- mastery_topic_event_hub.publish(path_id, revision, reason)
+def publish_topic_signal(
+ path_id: str,
+ revision: int,
+ reason: str = "topic.changed",
+ *,
+ scope: str = "default",
+) -> None:
+ mastery_topic_event_hub.publish(path_id, revision, reason, scope=scope)
__all__ = [
diff --git a/deeptutor/learning/migration.py b/deeptutor/learning/migration.py
index dbfcd02bd..326b38ea0 100644
--- a/deeptutor/learning/migration.py
+++ b/deeptutor/learning/migration.py
@@ -11,6 +11,7 @@ It is a recovery surface for humans, not a runtime fallback.
from __future__ import annotations
+from contextlib import contextmanager
from datetime import datetime, timezone
import hashlib
import json
@@ -29,6 +30,8 @@ _V1_DB_NAME = "mastery.sqlite3"
_V2_DIR_NAME = "mastery"
_ARCHIVE_DIR_NAME = "archive"
_MANIFEST_NAME = "migration.json"
+_LOCK_NAME = ".mastery-v2-migration.lock"
+_STAGING_NAME = ".v1-migration-in-progress"
_COUNTED_TABLES = (
"mastery_paths",
"mastery_path_sessions",
@@ -101,78 +104,147 @@ def _unique_archive_dir(archive_root: Path) -> Path:
return candidate
+@contextmanager
+def _process_lock(root: Path):
+ """Serialize migration across app/server processes, not just threads."""
+
+ root.mkdir(parents=True, exist_ok=True)
+ lock_path = root / _LOCK_NAME
+ with lock_path.open("a+b") as handle:
+ if os.name == "nt": # pragma: no cover - exercised by Windows builds
+ import msvcrt
+
+ if handle.tell() == 0:
+ handle.write(b"\0")
+ handle.flush()
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
+ try:
+ yield
+ finally:
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def _copy_json_archive(source: Path, archive_json_root: Path) -> None:
+ """Archive a live JSON without overwriting an older lazy-import copy."""
+
+ archive_json_root.mkdir(parents=True, exist_ok=True)
+ target = archive_json_root / source.name
+ if target.exists() and _sha256(target) != _sha256(source):
+ target = archive_json_root / "live" / source.name
+ if not target.exists():
+ _copy_atomic(source, target)
+
+
+def _finish_staging_archive(archive_root: Path, staging: Path) -> None:
+ if not staging.exists():
+ return
+ final_dir = _unique_archive_dir(archive_root)
+ os.replace(staging, final_dir)
+
+
def prepare_mastery_v2_root(learning_root: Path) -> Path:
"""Return the V2 store root, archiving/copying a V1 workspace once.
- The V2 database itself is the idempotency marker. Once it exists this
- function returns immediately and does not enumerate, validate, or open any
- archive. A brand-new workspace creates only the V2 directory.
+ The migration owns a process lock and a deterministic staging archive.
+ Consequently a crash can leave both the source and target in place; the
+ next startup resumes idempotently instead of trusting a partially-created
+ V2 directory. Finalized archives are never enumerated or read.
"""
root = Path(learning_root)
v2_root = root / _V2_DIR_NAME
v2_db = v2_root / _V1_DB_NAME
- if v2_db.exists():
- return v2_root
with _migration_lock:
- if v2_db.exists():
- return v2_root
-
- root.mkdir(parents=True, exist_ok=True)
- legacy_db = root / _V1_DB_NAME
- legacy_json_dir = root / ".legacy"
- has_legacy_json = legacy_json_dir.is_dir() and any(
- path.is_file() for path in legacy_json_dir.rglob("*")
- )
- if not legacy_db.exists() and not has_legacy_json:
- v2_root.mkdir(parents=True, exist_ok=True)
+ with _process_lock(root):
+ legacy_db = root / _V1_DB_NAME
+ legacy_json_dir = root / ".legacy"
+ live_json = sorted(path for path in root.glob("*.json") if path.is_file())
+ has_legacy_json = legacy_json_dir.is_dir() and any(
+ path.is_file() for path in legacy_json_dir.rglob("*")
+ )
+ archive_root = root / _ARCHIVE_DIR_NAME
+ staging = archive_root / _STAGING_NAME
+ has_v1_artifacts = legacy_db.exists() or has_legacy_json or bool(live_json)
+
+ if not has_v1_artifacts and not staging.exists():
+ v2_root.mkdir(parents=True, exist_ok=True)
+ return v2_root
+
+ archive_root.mkdir(parents=True, exist_ok=True)
+ staging.mkdir(parents=True, exist_ok=True)
+ started_at = time.time()
+ archived_db = staging / _V1_DB_NAME
+
+ if legacy_db.exists() and not archived_db.exists():
+ _checkpoint_database(legacy_db)
+ _copy_atomic(legacy_db, archived_db)
+ if not v2_db.exists() and archived_db.exists():
+ _copy_atomic(archived_db, v2_db)
+ else:
+ v2_root.mkdir(parents=True, exist_ok=True)
+
+ archive_json_dir = staging / "legacy-json"
+ if has_legacy_json:
+ shutil.copytree(
+ legacy_json_dir,
+ archive_json_dir,
+ dirs_exist_ok=True,
+ )
+
+ # Import directly through the store boundary so migration never
+ # duplicates the schema or aggregate serialization rules. Each
+ # source is archived before it is read into V2 and remains live
+ # until every import and the manifest have committed.
+ if live_json:
+ from deeptutor.learning.storage import LearningStore
+
+ target_store = LearningStore(root=v2_root)
+ for source in live_json:
+ _copy_json_archive(source, archive_json_dir)
+ target_store.import_legacy_json(source, archive=False)
+
+ legacy_json_count = (
+ sum(1 for path in archive_json_dir.rglob("*") if path.is_file())
+ if archive_json_dir.exists()
+ else 0
+ )
+ manifest = {
+ "format_version": 2,
+ "migration": "mastery-path-v1-to-v2",
+ "migrated_at": started_at,
+ "source": str(root),
+ "target": str(v2_root),
+ "database_sha256": _sha256(archived_db) if archived_db.exists() else "",
+ "row_counts": _row_counts(archived_db) if archived_db.exists() else {},
+ "legacy_json_count": legacy_json_count,
+ }
+ atomic_write_text(
+ staging / _MANIFEST_NAME,
+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
+ )
+
+ # Archive + target + manifest are durable. Remove only the exact
+ # V1 artifacts, then atomically publish the completed archive.
+ legacy_db.unlink(missing_ok=True)
+ (root / f"{_V1_DB_NAME}-wal").unlink(missing_ok=True)
+ (root / f"{_V1_DB_NAME}-shm").unlink(missing_ok=True)
+ for source in live_json:
+ source.unlink(missing_ok=True)
+ if legacy_json_dir.exists():
+ shutil.rmtree(legacy_json_dir)
+ _finish_staging_archive(archive_root, staging)
return v2_root
- archive_root = root / _ARCHIVE_DIR_NAME
- archive_dir = _unique_archive_dir(archive_root)
- archive_dir.mkdir(parents=True, exist_ok=False)
- started_at = time.time()
-
- archived_db: Path | None = None
- if legacy_db.exists():
- _checkpoint_database(legacy_db)
- archived_db = archive_dir / _V1_DB_NAME
- _copy_atomic(legacy_db, archived_db)
- _copy_atomic(archived_db, v2_db)
- else:
- v2_root.mkdir(parents=True, exist_ok=True)
-
- legacy_json_count = 0
- 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())
-
- manifest = {
- "format_version": 2,
- "migration": "mastery-path-v1-to-v2",
- "migrated_at": started_at,
- "source": str(root),
- "target": str(v2_root),
- "database_sha256": _sha256(archived_db) if archived_db else "",
- "row_counts": _row_counts(archived_db) if archived_db else {},
- "legacy_json_count": legacy_json_count,
- }
- atomic_write_text(
- archive_dir / _MANIFEST_NAME,
- json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
- )
-
- # The archive and V2 copy are durable now. Remove only the exact V1
- # paths; the archive remains recoverable and is never consulted again.
- legacy_db.unlink(missing_ok=True)
- (root / f"{_V1_DB_NAME}-wal").unlink(missing_ok=True)
- (root / f"{_V1_DB_NAME}-shm").unlink(missing_ok=True)
- if legacy_json_dir.exists():
- shutil.rmtree(legacy_json_dir)
-
- return v2_root
-
__all__ = ["prepare_mastery_v2_root"]
diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.py
index e0fa65c1e..9e33e2b9d 100644
--- a/deeptutor/learning/policy.py
+++ b/deeptutor/learning/policy.py
@@ -165,6 +165,7 @@ class NextStep:
reason: str = ""
pending_prompt: str = ""
pending_question: PublicPendingQuestion | None = None
+ session_id: str = ""
def to_dict(self) -> dict:
return {
@@ -183,6 +184,7 @@ class NextStep:
"pending_question": (
self.pending_question.to_dict() if self.pending_question is not None else None
),
+ "session_id": self.session_id,
}
@@ -201,7 +203,12 @@ def _gate_kind(kp: KnowledgePoint) -> str:
return "qualitative" if kp.type in QUALITATIVE_TYPES else "quantitative"
-def next_objective(progress: LearningProgress, *, now: float | None = None) -> NextStep:
+def next_objective(
+ progress: LearningProgress,
+ *,
+ now: float | None = None,
+ pending_session_id: str = "",
+) -> NextStep:
"""Decide the next thing to work on. Order of precedence:
1. an outstanding posed question (grade it before moving on);
@@ -227,6 +234,7 @@ def next_objective(progress: LearningProgress, *, now: float | None = None) -> N
reason="A posed question is awaiting the learner's answer; grade it with mastery_grade.",
pending_prompt=pending.prompt,
pending_question=public_pending_question(pending),
+ session_id=str(pending_session_id or ""),
)
due = due_reviews(progress, now=now)
diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.py
index 0d2ff0e14..33470191b 100644
--- a/deeptutor/learning/service.py
+++ b/deeptutor/learning/service.py
@@ -674,12 +674,61 @@ class LearningService:
tx.progress.current_module_id = applied_modules[0].id
tx.progress.current_kp_index = 0
else:
+ current_kp_id = ""
+ for current_module in tx.progress.modules:
+ if current_module.id != tx.progress.current_module_id:
+ continue
+ if 0 <= tx.progress.current_kp_index < len(current_module.knowledge_points):
+ current_kp_id = current_module.knowledge_points[
+ tx.progress.current_kp_index
+ ].id
+ break
+ pending_kp_id = (
+ tx.progress.pending_question.knowledge_point_id
+ if tx.progress.pending_question is not None
+ else ""
+ )
+ active_interaction = tx.active_interaction()
+ active_kp_id = (
+ active_interaction.question.knowledge_point_id
+ if active_interaction is not None
+ else ""
+ )
+
self.replace_modules(tx.progress, applied_modules)
- tx.progress.pending_question = None
- tx.abandon_active_interactions()
- if applied_modules:
+ objective_locations = {
+ kp.id: (module.id, kp_index)
+ for module in applied_modules
+ for kp_index, kp in enumerate(module.knowledge_points)
+ }
+
+ if current_kp_id in objective_locations:
+ (
+ tx.progress.current_module_id,
+ tx.progress.current_kp_index,
+ ) = objective_locations[current_kp_id]
+ elif applied_modules:
tx.progress.current_module_id = applied_modules[0].id
tx.progress.current_kp_index = 0
+ else:
+ tx.progress.current_module_id = ""
+ tx.progress.current_kp_index = 0
+
+ if tx.progress.pending_question is not None:
+ if pending_kp_id not in objective_locations:
+ tx.progress.pending_question = None
+ else:
+ pending_module_id, _ = objective_locations[pending_kp_id]
+ tx.progress.pending_question.module_id = pending_module_id
+
+ if active_interaction is not None:
+ if active_kp_id not in objective_locations:
+ tx.abandon_active_interactions()
+ else:
+ active_module_id, _ = objective_locations[active_kp_id]
+ if active_interaction.question.module_id != active_module_id:
+ active_interaction.question.module_id = active_module_id
+ tx.put_interaction(active_interaction)
tx.touch()
tx.emit(
event_type,
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 2f5e9c2e7..8bc608022 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -334,6 +334,12 @@ class LearningStore:
def db_path(self) -> Path:
return Path(self._root) / self._DB_FILENAME
+ @property
+ def event_scope(self) -> str:
+ """Stable workspace identity used by the process-local wake-up hub."""
+
+ return str(Path(self._root).resolve())
+
def _path(self, book_id: str) -> Path:
"""Return the legacy JSON location after validating the public id."""
self._validate_id(book_id)
@@ -519,15 +525,30 @@ class LearningStore:
# removes any unarchived copy so it cannot resurrect the path.
pass
- def _import_legacy_if_needed(self, book_id: str) -> None:
- path_id = self._validate_id(book_id)
- legacy_path = self._path(path_id)
+ def import_legacy_json(self, legacy_path: Path, *, archive: bool = True) -> bool:
+ """Import one V1 JSON aggregate into this store exactly once.
+
+ ``legacy_path`` may live outside the store root. That small public
+ boundary lets the workspace migration merge still-live V1 JSON files
+ into an already-created V2 database without teaching the migration
+ module about the SQLite schema. The committed row always wins over a
+ duplicate JSON file. ``archive=False`` is reserved for callers that
+ have already made their own durable archive copy.
+
+ Returns ``True`` when this call inserted a new aggregate.
+ """
+
+ legacy_path = Path(legacy_path)
+ if legacy_path.suffix != ".json":
+ raise ValueError(f"Legacy mastery path must be a JSON file: {legacy_path}")
+ path_id = self._validate_id(legacy_path.stem)
if not legacy_path.exists():
- return
+ return False
with self._connect() as conn:
if conn.execute("SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)).fetchone():
- self._archive_legacy(legacy_path)
- return
+ if archive:
+ self._archive_legacy(legacy_path)
+ return False
try:
legacy_text = legacy_path.read_text(encoding="utf-8")
except FileNotFoundError:
@@ -539,7 +560,7 @@ class LearningStore:
"SELECT 1 FROM mastery_paths WHERE path_id = ?", (path_id,)
).fetchone()
if imported is not None:
- return
+ return False
raise
data = json.loads(legacy_text)
progress = LearningProgress.model_validate(data)
@@ -550,6 +571,7 @@ class LearningStore:
now = time.time()
revision = max(1, int(progress.version or 0))
payload = self._progress_payload(progress, revision, now)
+ inserted = False
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
try:
@@ -562,6 +584,7 @@ class LearningStore:
(path_id, payload, revision, progress.created_at, now),
)
if conn.execute("SELECT changes()").fetchone()[0]:
+ inserted = True
conn.execute(
"""
INSERT INTO mastery_events (
@@ -574,7 +597,13 @@ class LearningStore:
except Exception:
conn.rollback()
raise
- self._archive_legacy(legacy_path)
+ if archive:
+ self._archive_legacy(legacy_path)
+ return inserted
+
+ def _import_legacy_if_needed(self, book_id: str) -> None:
+ path_id = self._validate_id(book_id)
+ self.import_legacy_json(self._path(path_id))
def load(self, book_id: str) -> LearningProgress | None:
path_id = self._validate_id(book_id)
@@ -659,7 +688,12 @@ class LearningStore:
progress.updated_at = now
from deeptutor.learning.event_hub import publish_topic_signal
- publish_topic_signal(path_id, revision, event_type)
+ publish_topic_signal(
+ path_id,
+ revision,
+ event_type,
+ scope=self.event_scope,
+ )
@contextmanager
def transaction(
@@ -763,7 +797,12 @@ class LearningStore:
if committed_revision is not None:
from deeptutor.learning.event_hub import publish_topic_signal
- publish_topic_signal(path_id, committed_revision, committed_reason)
+ publish_topic_signal(
+ path_id,
+ committed_revision,
+ committed_reason,
+ scope=self.event_scope,
+ )
def mutate(
self,
@@ -798,7 +837,12 @@ class LearningStore:
archived.unlink(missing_ok=True)
from deeptutor.learning.event_hub import publish_topic_signal
- publish_topic_signal(path_id, 0, "topic.deleted")
+ publish_topic_signal(
+ path_id,
+ 0,
+ "topic.deleted",
+ scope=self.event_scope,
+ )
def exists(self, book_id: str) -> bool:
path_id = self._validate_id(book_id)
@@ -843,9 +887,17 @@ class LearningStore:
raise LearningStoreError(f"Failed to persist topic {path_id!r}")
return topic
- def get_topic(self, path_id: str) -> MasteryTopic | None:
+ def get_topic(
+ self,
+ path_id: str,
+ *,
+ progress: LearningProgress | None = None,
+ ) -> MasteryTopic | None:
path_id = self._validate_id(path_id)
- progress = self.load(path_id)
+ if progress is None:
+ progress = self.load(path_id)
+ elif progress.book_id != path_id:
+ raise ValueError("progress does not belong to the requested topic")
if progress is None:
return None
with self._connect() as conn:
@@ -859,6 +911,15 @@ class LearningStore:
""",
(path_id,),
).fetchall()
+ return self._topic_from_rows(path_id, progress, meta_row, source_rows)
+
+ def _topic_from_rows(
+ self,
+ path_id: str,
+ progress: LearningProgress,
+ meta_row: sqlite3.Row | None,
+ source_rows: list[sqlite3.Row],
+ ) -> MasteryTopic:
if meta_row is None:
metadata = TopicMetadata(
path_id=path_id,
@@ -893,6 +954,93 @@ class LearningStore:
]
return MasteryTopic(metadata=metadata, sources=sources)
+ def list_topic_snapshots(
+ self,
+ *,
+ status: str = "active",
+ ) -> list[
+ tuple[
+ LearningProgress,
+ MasteryTopic,
+ int,
+ MasteryInteraction | None,
+ ]
+ ]:
+ """Read the atlas in a constant number of bounded SQLite queries."""
+
+ with self._connect() as conn:
+ progress_rows = conn.execute(
+ """
+ SELECT p.* FROM mastery_paths p
+ JOIN mastery_topic_meta m ON m.path_id = p.path_id
+ WHERE m.status = ?
+ ORDER BY p.updated_at DESC
+ """,
+ (status,),
+ ).fetchall()
+ meta_rows = {
+ str(row["path_id"]): row
+ for row in conn.execute(
+ "SELECT * FROM mastery_topic_meta WHERE status = ?",
+ (status,),
+ ).fetchall()
+ }
+ source_rows: dict[str, list[sqlite3.Row]] = {}
+ for row in conn.execute(
+ """
+ SELECT s.* FROM mastery_topic_sources s
+ JOIN mastery_topic_meta m ON m.path_id = s.path_id
+ WHERE m.status = ?
+ ORDER BY s.path_id, s.position ASC, s.created_at ASC
+ """,
+ (status,),
+ ).fetchall():
+ source_rows.setdefault(str(row["path_id"]), []).append(row)
+ session_counts = {
+ str(row["path_id"]): int(row["session_count"])
+ for row in conn.execute(
+ """
+ SELECT b.path_id, COUNT(*) AS session_count
+ FROM mastery_path_sessions b
+ JOIN mastery_topic_meta m ON m.path_id = b.path_id
+ WHERE m.status = ?
+ GROUP BY b.path_id
+ """,
+ (status,),
+ ).fetchall()
+ }
+ placeholders = ",".join("?" for _ in _ACTIVE_INTERACTION_STATES)
+ active_rows = {
+ str(row["path_id"]): row
+ for row in conn.execute(
+ f"""
+ SELECT i.* FROM mastery_interactions i
+ JOIN mastery_topic_meta m ON m.path_id = i.path_id
+ WHERE m.status = ? AND i.status IN ({placeholders})
+ """, # nosec B608 - generated placeholders; values remain bound
+ (status, *_ACTIVE_INTERACTION_STATES),
+ ).fetchall()
+ }
+
+ snapshots = []
+ for progress_row in progress_rows:
+ path_id = str(progress_row["path_id"])
+ progress = self._progress_from_row(progress_row)
+ snapshots.append(
+ (
+ progress,
+ self._topic_from_rows(
+ path_id,
+ progress,
+ meta_rows.get(path_id),
+ source_rows.get(path_id, []),
+ ),
+ session_counts.get(path_id, 0),
+ LearningTransaction._interaction_from_row(active_rows.get(path_id)),
+ )
+ )
+ return snapshots
+
# ---- explicit path/session ownership ---------------------------------
def bind_session(self, path_id: str, session_id: str, *, owns_path: bool = False) -> None:
@@ -956,7 +1104,12 @@ class LearningStore:
raise
from deeptutor.learning.event_hub import publish_topic_signal
- publish_topic_signal(path_id, current_revision, "session.bound")
+ publish_topic_signal(
+ path_id,
+ current_revision,
+ "session.bound",
+ scope=self.event_scope,
+ )
def list_session_ids(self, path_id: str) -> list[str]:
path_id = self._validate_id(path_id)
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index 91353882c..3711598a8 100644
--- a/deeptutor/learning/tests/test_api_endpoints.py
+++ b/deeptutor/learning/tests/test_api_endpoints.py
@@ -8,7 +8,7 @@ from fastapi.testclient import TestClient
import pytest
from deeptutor.api.routers.mastery_path import router
-from deeptutor.learning.models import PendingQuestion
+from deeptutor.learning.models import PendingQuestion, QuizAttempt
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
@@ -120,6 +120,97 @@ class TestListProgress:
class TestTopicProductApi:
+ def test_edit_topic_map_preserves_reordered_evidence_by_entity_id(self, client, app):
+ created = client.post(
+ "/api/v1/learning/topics",
+ json={
+ "name": "Stable route",
+ "goal": "Keep evidence attached to concepts",
+ "sources": [],
+ "modules": [
+ {
+ "id": "draft-module",
+ "name": "Region",
+ "knowledge_points": [
+ {"id": "draft-a", "name": "First objective", "type": "concept"},
+ {"id": "draft-b", "name": "Second objective", "type": "concept"},
+ {"id": "draft-c", "name": "Third objective", "type": "concept"},
+ ],
+ }
+ ],
+ },
+ ).json()
+ path_id = created["path_id"]
+ points = created["map"]["modules"][0]["knowledge_points"]
+ first_id, deleted_id, third_id = [point["id"] for point in points]
+
+ store = LearningStore(root=app.state.learning_root)
+
+ def add_evidence(tx):
+ tx.progress.mastery_levels[first_id] = 0.2
+ tx.progress.mastery_levels[deleted_id] = 0.6
+ tx.progress.mastery_levels[third_id] = 0.9
+ tx.progress.quiz_attempts.extend(
+ [
+ QuizAttempt(
+ question_id="deleted-evidence",
+ knowledge_point_id=deleted_id,
+ is_correct=True,
+ ),
+ QuizAttempt(
+ question_id="third-evidence",
+ knowledge_point_id=third_id,
+ is_correct=False,
+ ),
+ ]
+ )
+ tx.touch()
+
+ store.mutate(path_id, add_evidence)
+
+ response = client.put(
+ f"/api/v1/learning/topics/{path_id}/map",
+ json={
+ "modules": [
+ {
+ "id": created["map"]["modules"][0]["id"],
+ "name": "Renamed region",
+ "knowledge_points": [
+ {"id": third_id, "name": "Third objective", "type": "concept"},
+ {"id": first_id, "name": "First objective", "type": "concept"},
+ ],
+ }
+ ]
+ },
+ )
+
+ assert response.status_code == 200
+ edited_points = response.json()["map"]["modules"][0]["knowledge_points"]
+ assert [point["id"] for point in edited_points] == [third_id, first_id]
+ progress = store.load(path_id)
+ assert progress is not None
+ assert progress.mastery_levels == {first_id: 0.2, third_id: 0.9}
+ assert [attempt.question_id for attempt in progress.quiz_attempts] == ["third-evidence"]
+
+ def test_edit_topic_map_rejects_empty_region_instead_of_silently_dropping_it(self, client):
+ created = client.post(
+ "/api/v1/learning/topics",
+ json={
+ "name": "Strict route",
+ "goal": "Reject disappearing edits",
+ "sources": [],
+ "modules": [_module_payload()],
+ },
+ ).json()
+
+ response = client.put(
+ f"/api/v1/learning/topics/{created['path_id']}/map",
+ json={"modules": [{"id": "m1", "name": "Empty", "knowledge_points": []}]},
+ )
+
+ assert response.status_code == 422
+ assert "at least one waypoint" in response.json()["detail"]
+
def test_topic_sessions_include_message_count_and_latest_preview(self, client, monkeypatch):
created = client.post(
"/api/v1/learning/topics",
@@ -133,19 +224,18 @@ class TestTopicProductApi:
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."},
- ],
- }
+ session_store.get_session_summaries.return_value = [
+ {
+ "session_id": "session-1",
+ "title": "Limits expedition",
+ "created_at": 10,
+ "updated_at": 20,
+ "status": "idle",
+ "preferences": {"pinned": True, "archived": False},
+ "message_count": 2,
+ "last_message": "Look at the local slope.",
+ }
+ ]
monkeypatch.setattr(
"deeptutor.services.session.get_session_store",
lambda: session_store,
@@ -166,8 +256,67 @@ class TestTopicProductApi:
"last_message": "Look at the local slope.",
"pinned": True,
"archived": False,
+ "has_pending_question": False,
}
]
+ session_store.get_session_summaries.assert_awaited_once_with(["session-1"])
+ session_store.get_session_with_messages.assert_not_awaited()
+
+ def test_pending_question_exposes_its_owning_session(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"]
+ kp_id = created["map"]["modules"][0]["knowledge_points"][0]["id"]
+ store = LearningStore(root=client.app.state.learning_root)
+ store.bind_session(path_id, "older-owner")
+ store.bind_session(path_id, "newer-session")
+ LearningService(store).register_question(
+ path_id,
+ PendingQuestion(
+ question_id="q1",
+ knowledge_point_id=kp_id,
+ module_id=created["map"]["modules"][0]["id"],
+ prompt="Explain the derivative",
+ expected_answer="rate of change",
+ ),
+ session_id="older-owner",
+ )
+ session_store = AsyncMock()
+ session_store.get_session_summaries.side_effect = lambda session_ids: [
+ {
+ "session_id": session_id,
+ "title": session_id,
+ "created_at": 1,
+ "updated_at": 2 if session_id == "newer-session" else 1,
+ "status": "idle",
+ "preferences": {},
+ "message_count": 0,
+ "last_message": "",
+ }
+ for session_id in session_ids
+ ]
+ monkeypatch.setattr(
+ "deeptutor.services.session.get_session_store",
+ lambda: session_store,
+ )
+
+ topic = client.get(f"/api/v1/learning/topics/{path_id}").json()
+ sessions = client.get(f"/api/v1/learning/topics/{path_id}/sessions").json()["sessions"]
+
+ assert topic["next"]["action"] == "answer_pending"
+ assert topic["next"]["session_id"] == "older-owner"
+ assert [item["session_id"] for item in sessions] == [
+ "newer-session",
+ "older-owner",
+ ]
+ assert [item["has_pending_question"] for item in sessions] == [False, True]
def test_generate_mixed_source_draft_without_persisting(self, client):
response_json = json.dumps(
@@ -244,6 +393,36 @@ class TestTopicProductApi:
listed = client.get("/api/v1/learning/topics").json()["topics"]
assert [item["path_id"] for item in listed] == [topic["path_id"]]
+ def test_topic_atlas_excludes_archived_topics(self, client, app):
+ active = client.post(
+ "/api/v1/learning/topics",
+ json={
+ "name": "Active route",
+ "goal": "Keep learning",
+ "sources": [],
+ "modules": [_module_payload("active-module", "active-point")],
+ },
+ ).json()
+ archived = client.post(
+ "/api/v1/learning/topics",
+ json={
+ "name": "Archived route",
+ "goal": "Hide this route",
+ "sources": [],
+ "modules": [_module_payload("archived-module", "archived-point")],
+ },
+ ).json()
+ store = LearningStore(root=app.state.learning_root)
+ archived_topic = store.get_topic(archived["path_id"])
+ assert archived_topic is not None
+ archived_topic.metadata.status = "archived"
+ store.put_topic(archived_topic.metadata, archived_topic.sources)
+
+ listed = client.get("/api/v1/learning/topics")
+
+ assert listed.status_code == 200
+ assert [item["path_id"] for item in listed.json()["topics"]] == [active["path_id"]]
+
def test_learner_override_advances_with_provenance(self, client):
created = client.post(
"/api/v1/learning/topics",
diff --git a/deeptutor/learning/tests/test_event_hub.py b/deeptutor/learning/tests/test_event_hub.py
index 6e567e90d..2673d4b08 100644
--- a/deeptutor/learning/tests/test_event_hub.py
+++ b/deeptutor/learning/tests/test_event_hub.py
@@ -37,3 +37,35 @@ async def test_topic_hub_isolated_by_path_and_unsubscribes_cleanly() -> None:
assert signal.path_id == "second"
assert signal.sequence >= 1
assert first.queue.empty()
+
+
+async def test_topic_hub_isolated_by_workspace_scope() -> None:
+ hub = MasteryTopicEventHub()
+ first = hub.subscribe("shared", scope="workspace-a")
+ second = hub.subscribe("shared", scope="workspace-b")
+ try:
+ hub.publish("shared", 3, scope="workspace-a")
+ signal = await asyncio.wait_for(first.get(), timeout=1)
+ finally:
+ first.close()
+ second.close()
+
+ assert signal.revision == 3
+ assert second.queue.empty()
+
+
+async def test_topic_hub_coalesces_slow_subscriber_to_latest_signal() -> None:
+ hub = MasteryTopicEventHub()
+ subscription = hub.subscribe("topic-one")
+ try:
+ for revision in range(1, 51):
+ hub.publish("topic-one", revision)
+ await asyncio.sleep(0)
+ signal = await asyncio.wait_for(subscription.get(), timeout=1)
+ finally:
+ subscription.close()
+
+ assert signal.revision == 50
+ assert subscription.queue.empty()
diff --git a/deeptutor/learning/tests/test_service_replace_merge.py b/deeptutor/learning/tests/test_service_replace_merge.py
index a0c47fa8d..b5d970d6f 100644
--- a/deeptutor/learning/tests/test_service_replace_merge.py
+++ b/deeptutor/learning/tests/test_service_replace_merge.py
@@ -17,6 +17,8 @@ from deeptutor.learning.models import (
KnowledgeType,
LearningModule,
LearningProgress,
+ MasteryInteraction,
+ PendingQuestion,
RepetitionState,
ReviewTask,
)
@@ -44,6 +46,78 @@ def _make_module(mod_id: str, kp_ids: list[str]) -> LearningModule:
class TestReplaceModules:
+ @staticmethod
+ def _pending(question_id: str = "q1", kp_id: str = "kp2") -> PendingQuestion:
+ return PendingQuestion(
+ question_id=question_id,
+ knowledge_point_id=kp_id,
+ module_id="m1",
+ prompt="Explain it",
+ expected_answer="Clearly",
+ )
+
+ def test_route_reorder_keeps_current_objective_and_pending_interaction(self, tmp_path: Path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ service.replace_modules_for_path(
+ "test", [_make_module("m1", ["kp1", "kp2"])], event_type="seed"
+ )
+
+ def prepare(tx):
+ tx.progress.current_module_id = "m1"
+ tx.progress.current_kp_index = 1
+ tx.progress.pending_question = self._pending()
+ tx.put_interaction(
+ MasteryInteraction(
+ interaction_id="q1",
+ path_id="test",
+ question=self._pending(),
+ session_id="session-1",
+ )
+ )
+ tx.touch()
+
+ store.mutate("test", prepare)
+
+ progress = service.replace_modules_for_path(
+ "test", [_make_module("m1", ["kp2", "kp1"])], event_type="topic.map_edited"
+ )
+
+ assert progress.current_module_id == "m1"
+ assert progress.current_kp_index == 0
+ assert progress.pending_question is not None
+ assert progress.pending_question.knowledge_point_id == "kp2"
+ assert store.get_active_interaction("test") is not None
+
+ def test_route_deletion_abandons_only_removed_pending_objective(self, tmp_path: Path):
+ store = LearningStore(root=tmp_path)
+ service = LearningService(store)
+ service.replace_modules_for_path("test", [_make_module("m1", ["kp1", "kp2"])])
+
+ def prepare(tx):
+ tx.progress.current_module_id = "m1"
+ tx.progress.current_kp_index = 1
+ tx.progress.pending_question = self._pending()
+ tx.put_interaction(
+ MasteryInteraction(
+ interaction_id="q1",
+ path_id="test",
+ question=self._pending(),
+ session_id="session-1",
+ )
+ )
+ tx.touch()
+
+ store.mutate("test", prepare)
+
+ progress = service.replace_modules_for_path(
+ "test", [_make_module("m1", ["kp1"])], event_type="topic.map_edited"
+ )
+
+ assert progress.current_kp_index == 0
+ assert progress.pending_question is None
+ assert store.get_active_interaction("test") is None
+
def test_append_to_empty_path_selects_first_module(self, tmp_path: Path):
store = LearningStore(root=tmp_path)
progress = LearningService(store).replace_modules_for_path(
diff --git a/deeptutor/learning/tests/test_storage.py b/deeptutor/learning/tests/test_storage.py
index e5660ef32..a314a1702 100644
--- a/deeptutor/learning/tests/test_storage.py
+++ b/deeptutor/learning/tests/test_storage.py
@@ -276,6 +276,35 @@ class TestTopicMetadata:
assert first.metadata.map_seed == second.metadata.map_seed
assert first.sources == []
+ def test_topic_snapshots_batch_active_topics_with_counts_and_sources(self, store):
+ for path_id in ("active-path", "archived-path"):
+ store.save(LearningProgress(book_id=path_id, name=path_id))
+ store.put_topic(
+ TopicMetadata(path_id="active-path", goal="Learn"),
+ [
+ TopicSource(
+ id="source-1",
+ kind=TopicSourceKind.BOOK,
+ label="Course book",
+ )
+ ],
+ )
+ store.put_topic(
+ TopicMetadata(path_id="archived-path", status="archived"),
+ [],
+ )
+ store.bind_session("active-path", "session-a")
+ store.bind_session("active-path", "session-b")
+
+ snapshots = store.list_topic_snapshots()
+
+ assert len(snapshots) == 1
+ progress, topic, session_count, active_interaction = snapshots[0]
+ assert progress.book_id == "active-path"
+ assert [source.label for source in topic.sources] == ["Course book"]
+ assert session_count == 2
+ assert active_interaction is None
+
class TestLegacyMigration:
def test_json_path_is_imported_and_archived_on_first_read(self, store, tmp_path):
diff --git a/deeptutor/learning/tests/test_topic_generation.py b/deeptutor/learning/tests/test_topic_generation.py
new file mode 100644
index 000000000..1e6232e1d
--- /dev/null
+++ b/deeptutor/learning/tests/test_topic_generation.py
@@ -0,0 +1,203 @@
+"""Route materialisation keeps product identity separate from display order."""
+
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+
+from deeptutor.learning.models import TopicSource, TopicSourceKind
+from deeptutor.learning.topic_generation import (
+ TopicGenerationError,
+ generate_topic_draft,
+ materialize_modules,
+)
+
+
+def _module(module_id: str, *points: tuple[str, str]) -> dict:
+ return {
+ "id": module_id,
+ "name": f"Region {module_id}",
+ "knowledge_points": [
+ {"id": point_id, "name": name, "type": "concept", "module_id": module_id}
+ for point_id, name in points
+ ],
+ }
+
+
+def test_edit_reorder_preserves_existing_module_and_objective_ids() -> None:
+ raw = [
+ _module("topic_m1", ("topic_m1_kp0", "Third objective")),
+ _module(
+ "topic_m0",
+ ("topic_m0_kp1", "Second objective"),
+ ("topic_m0_kp0", "First objective"),
+ ),
+ ]
+
+ modules = materialize_modules(
+ "topic",
+ raw,
+ strict=True,
+ existing_module_ids={"topic_m0", "topic_m1"},
+ existing_objective_ids={"topic_m0_kp0", "topic_m0_kp1", "topic_m1_kp0"},
+ )
+
+ assert [module.id for module in modules] == ["topic_m1", "topic_m0"]
+ assert [point.id for point in modules[1].knowledge_points] == [
+ "topic_m0_kp1",
+ "topic_m0_kp0",
+ ]
+ assert [module.order for module in modules] == [0, 1]
+
+
+def test_new_objective_never_reuses_an_existing_or_deleted_position_id() -> None:
+ raw = [
+ _module(
+ "topic_m0",
+ ("draft-new", "Brand new objective"),
+ ("topic_m0_kp0", "Existing objective"),
+ )
+ ]
+
+ modules = materialize_modules(
+ "topic",
+ raw,
+ strict=True,
+ existing_module_ids={"topic_m0"},
+ existing_objective_ids={"topic_m0_kp0", "topic_m0_kp1"},
+ )
+
+ ids = [point.id for point in modules[0].knowledge_points]
+ assert ids[1] == "topic_m0_kp0"
+ assert ids[0] not in {"topic_m0_kp0", "topic_m0_kp1"}
+ assert ids[0].startswith("topic_m0_kp_")
+
+
+ "raw, message",
+ [
+ ([{"id": "m", "name": "", "knowledge_points": []}], "region 1 needs a name"),
+ ([{"id": "m", "name": "Region", "knowledge_points": []}], "at least one waypoint"),
+ (
+ [
+ {
+ "id": "m",
+ "name": "Region",
+ "knowledge_points": [{"id": "kp", "name": "", "type": "concept"}],
+ }
+ ],
+ "waypoint 1 needs a name",
+ ),
+ ],
+)
+def test_strict_route_rejects_content_that_would_be_silently_dropped(
+ raw: list[dict], message: str
+) -> None:
+ with pytest.raises(TopicGenerationError, match=message):
+ materialize_modules("topic", raw, strict=True)
+
+
+async def test_selected_knowledge_base_is_retrieved_into_generation_prompt(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ rag_search = AsyncMock(
+ return_value={
+ "provider": "test-rag",
+ "sources": [
+ {
+ "title": "Mechanics notes",
+ "content": "Hamiltonian flow preserves symplectic structure.",
+ }
+ ],
+ }
+ )
+ complete = AsyncMock(
+ return_value=json.dumps(
+ {
+ "description": "Mechanics route",
+ "modules": [
+ {
+ "name": "Foundations",
+ "knowledge_points": [{"name": "Hamiltonian flow", "type": "concept"}],
+ }
+ ],
+ }
+ )
+ )
+ monkeypatch.setattr("deeptutor.tools.rag_tool.rag_search", rag_search)
+ monkeypatch.setattr("deeptutor.learning.topic_generation.complete", complete)
+
+ result = await generate_topic_draft(
+ name="Classical mechanics",
+ goal="Understand conserved geometric structure",
+ sources=[
+ TopicSource(
+ id="kb-source",
+ kind=TopicSourceKind.KNOWLEDGE_BASE,
+ source_id="mechanics-kb",
+ label="Mechanics KB",
+ )
+ ],
+ language="en",
+ )
+
+ rag_search.assert_awaited_once()
+ assert rag_search.await_args.args[:2] == (
+ "Classical mechanics\nUnderstand conserved geometric structure",
+ "mechanics-kb",
+ )
+ assert "Hamiltonian flow preserves" in complete.await_args.kwargs["prompt"]
+ assert result["sources"][0]["available"] is True
+ assert result["sources"][0]["metadata"]["grounded_for_route"] is True
+
+
+async def test_unavailable_knowledge_base_does_not_abort_other_sources(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "deeptutor.tools.rag_tool.rag_search",
+ AsyncMock(side_effect=RuntimeError("index offline")),
+ )
+ monkeypatch.setattr(
+ "deeptutor.learning.topic_generation.complete",
+ AsyncMock(
+ return_value=json.dumps(
+ {
+ "description": "Fallback route",
+ "modules": [
+ {
+ "name": "Goal region",
+ "knowledge_points": [{"name": "Core objective", "type": "concept"}],
+ }
+ ],
+ }
+ )
+ ),
+ )
+
+ result = await generate_topic_draft(
+ name="Fallback",
+ goal="Keep generating from the goal",
+ sources=[
+ TopicSource(
+ id="goal",
+ kind=TopicSourceKind.GOAL,
+ label="Goal",
+ excerpt="Keep generating from the goal",
+ ),
+ TopicSource(
+ id="offline",
+ kind=TopicSourceKind.KNOWLEDGE_BASE,
+ source_id="offline-kb",
+ label="Offline KB",
+ ),
+ ],
+ language="en",
+ )
+
+ assert result["modules"]
+ assert result["sources"][0]["available"] is True
+ assert result["sources"][1]["available"] is False
+ assert result["sources"][1]["metadata"]["unavailable_during_generation"] is True
diff --git a/deeptutor/learning/tests/test_v2_migration.py b/deeptutor/learning/tests/test_v2_migration.py
index 9d016ccf3..4fd6e095d 100644
--- a/deeptutor/learning/tests/test_v2_migration.py
+++ b/deeptutor/learning/tests/test_v2_migration.py
@@ -2,9 +2,13 @@ from __future__ import annotations
import hashlib
import json
+import multiprocessing
from pathlib import Path
import sqlite3
+import pytest
+
+import deeptutor.learning.migration as migration_module
from deeptutor.learning.migration import prepare_mastery_v2_root
from deeptutor.learning.models import LearningProgress, MasteryInteraction, PendingQuestion
from deeptutor.learning.storage import LearningStore
@@ -18,6 +22,10 @@ def _sha256(path: Path) -> str:
return digest.hexdigest()
+def _prepare_in_process(path: str) -> str:
+ return str(prepare_mastery_v2_root(Path(path)))
+
+
def test_workspace_v1_is_archived_then_copied_into_v2_store(tmp_path: Path) -> None:
learning_root = tmp_path / "learning"
old_store = LearningStore(root=learning_root)
@@ -103,3 +111,77 @@ def test_empty_workspace_uses_v2_directory_without_creating_archive(tmp_path: Pa
assert store.db_path == learning_root / "mastery" / "mastery.sqlite3"
assert not (learning_root / "archive").exists()
+
+
+def test_live_root_json_is_imported_and_archived(tmp_path: Path) -> None:
+ learning_root = tmp_path / "learning"
+ learning_root.mkdir(parents=True)
+ legacy_json = learning_root / "json-only.json"
+ legacy_json.write_text(
+ LearningProgress(book_id="json-only", name="JSON only").model_dump_json(),
+ encoding="utf-8",
+ )
+
+ v2_root = prepare_mastery_v2_root(learning_root)
+
+ assert LearningStore(root=v2_root).load("json-only").name == "JSON only"
+ assert not legacy_json.exists()
+ archive = next((learning_root / "archive").glob("v1-*"))
+ assert (archive / "legacy-json" / "json-only.json").exists()
+ manifest = json.loads((archive / "migration.json").read_text(encoding="utf-8"))
+ assert manifest["legacy_json_count"] == 1
+
+
+def test_late_root_json_is_reconciled_into_existing_v2_store(tmp_path: Path) -> None:
+ learning_root = tmp_path / "learning"
+ v2_root = prepare_mastery_v2_root(learning_root)
+ LearningStore(root=v2_root).save(LearningProgress(book_id="existing"))
+ late_json = learning_root / "late-topic.json"
+ late_json.write_text(
+ LearningProgress(book_id="late-topic", name="Recovered").model_dump_json(),
+ encoding="utf-8",
+ )
+
+ assert prepare_mastery_v2_root(learning_root) == v2_root
+ migrated = LearningStore(root=v2_root)
+ assert migrated.exists("existing") is True
+ assert migrated.load("late-topic").name == "Recovered"
+ assert not late_json.exists()
+
+
+def test_process_concurrent_initialization_creates_one_archive(tmp_path: Path) -> None:
+ learning_root = tmp_path / "learning"
+ old_store = LearningStore(root=learning_root)
+ old_store.save(LearningProgress(book_id="topic-one"))
+
+ context = multiprocessing.get_context("spawn")
+ with context.Pool(processes=3) as pool:
+ roots = pool.map(_prepare_in_process, [str(learning_root)] * 3)
+
+ assert roots == [str(learning_root / "mastery")] * 3
+ assert len(list((learning_root / "archive").glob("v1-*"))) == 1
+ assert LearningStore(root=learning_root / "mastery").exists("topic-one") is True
+
+
+def test_interrupted_finalization_resumes_from_staging(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ learning_root = tmp_path / "learning"
+ old_store = LearningStore(root=learning_root)
+ old_store.save(LearningProgress(book_id="topic-one"))
+
+ def interrupt(_archive_root: Path, _staging: Path) -> None:
+ raise RuntimeError("simulated shutdown")
+
+ monkeypatch.setattr(migration_module, "_finish_staging_archive", interrupt)
+ with pytest.raises(RuntimeError, match="simulated shutdown"):
+ prepare_mastery_v2_root(learning_root)
+
+ assert (learning_root / "archive" / ".v1-migration-in-progress").exists()
+ assert not (learning_root / "mastery.sqlite3").exists()
+ monkeypatch.undo()
+
+ v2_root = prepare_mastery_v2_root(learning_root)
+ assert not (learning_root / "archive" / ".v1-migration-in-progress").exists()
+ assert len(list((learning_root / "archive").glob("v1-*"))) == 1
+ assert LearningStore(root=v2_root).exists("topic-one") is True
diff --git a/deeptutor/learning/topic_generation.py b/deeptutor/learning/topic_generation.py
index a282476d5..c085dbe10 100644
--- a/deeptutor/learning/topic_generation.py
+++ b/deeptutor/learning/topic_generation.py
@@ -2,8 +2,10 @@
from __future__ import annotations
+import asyncio
import json
from typing import Any
+import uuid
from deeptutor.learning import prompts as learning_prompts
from deeptutor.learning.models import (
@@ -11,6 +13,7 @@ from deeptutor.learning.models import (
KnowledgeType,
LearningModule,
TopicSource,
+ TopicSourceKind,
)
from deeptutor.services.llm import complete
from deeptutor.utils.json_parser import parse_json_response
@@ -43,31 +46,189 @@ def _source_payload(sources: list[TopicSource]) -> list[dict[str, Any]]:
return payload
-def materialize_modules(path_id: str, raw_modules: list[dict[str, Any]]) -> list[LearningModule]:
+def _retrieved_context(result: dict[str, Any]) -> str:
+ blocks: list[str] = []
+ raw_sources = result.get("sources")
+ if isinstance(raw_sources, list):
+ for raw_source in raw_sources[:6]:
+ if not isinstance(raw_source, dict):
+ continue
+ title = str(raw_source.get("title") or raw_source.get("source") or "").strip()
+ content = str(
+ raw_source.get("content")
+ or raw_source.get("text")
+ or raw_source.get("snippet")
+ or ""
+ ).strip()
+ if content:
+ blocks.append(f"{title}\n{content}".strip())
+ # Some providers return one context block and only file-level source
+ # metadata. Include it when snippets alone do not provide useful grounding.
+ if sum(len(block) for block in blocks) < 500:
+ content = str(result.get("content") or result.get("answer") or "").strip()
+ if content:
+ blocks.append(content)
+ return "\n\n".join(blocks)[:_MAX_SOURCE_EXCERPT]
+
+
+async def _ground_knowledge_base_source(
+ source: TopicSource,
+ *,
+ query: str,
+) -> TopicSource:
+ grounded = source.model_copy(deep=True)
+ if (
+ grounded.kind != TopicSourceKind.KNOWLEDGE_BASE
+ or not grounded.available
+ or not grounded.source_id.strip()
+ ):
+ return grounded
+ try:
+ from deeptutor.tools.rag_tool import rag_search
+
+ result = await rag_search(query, grounded.source_id, top_k=4)
+ context = _retrieved_context(result if isinstance(result, dict) else {})
+ if not context:
+ raise ValueError("knowledge base returned no retrievable context")
+ grounded.excerpt = context
+ grounded.metadata = {
+ **grounded.metadata,
+ "grounded_for_route": True,
+ "retrieval_provider": str(result.get("provider") or ""),
+ }
+ except Exception:
+ # One unavailable source must not discard the user's other selected
+ # material or prevent a goal-only draft. Its degraded state is returned
+ # to the client and persisted when the user confirms the route.
+ grounded.available = False
+ grounded.metadata = {
+ **grounded.metadata,
+ "unavailable_during_generation": True,
+ }
+ return grounded
+
+
+async def ground_topic_sources(
+ *,
+ name: str,
+ goal: str,
+ sources: list[TopicSource],
+) -> list[TopicSource]:
+ query = f"{str(name or '').strip()}\n{str(goal or '').strip()}".strip()[:2_000]
+ return list(
+ await asyncio.gather(
+ *(
+ _ground_knowledge_base_source(source, query=query)
+ for source in sorted(sources, key=lambda item: item.position)[:_MAX_SOURCES]
+ )
+ )
+ )
+
+
+def _new_entity_id(prefix: str, reserved: set[str]) -> str:
+ """Allocate a durable id that cannot inherit evidence from a deleted row."""
+
+ while True:
+ candidate = f"{prefix}_{uuid.uuid4().hex[:12]}"
+ if candidate not in reserved:
+ reserved.add(candidate)
+ return candidate
+
+
+def materialize_modules(
+ path_id: str,
+ raw_modules: list[dict[str, Any]],
+ *,
+ strict: bool = False,
+ existing_module_ids: set[str] | None = None,
+ existing_objective_ids: set[str] | None = None,
+) -> list[LearningModule]:
+ """Validate and normalize a route while keeping existing entity identity.
+
+ Draft generation is intentionally forgiving because model JSON can contain
+ one malformed item among otherwise useful content. User-confirmed routes
+ use ``strict=True`` so saving can never report success after silently
+ dropping a region or waypoint.
+
+ Position is presentation state, not identity. Existing ids are accepted
+ only when the caller proves they belong to this topic; every new entity gets
+ a collision-proof id so a deleted objective's evidence can never be reused.
+ """
+
+ allowed_modules = set(existing_module_ids or ())
+ allowed_objectives = set(existing_objective_ids or ())
+ reserved_modules = set(allowed_modules)
+ reserved_objectives = set(allowed_objectives)
+ used_modules: set[str] = set()
+ used_objectives: set[str] = set()
modules: list[LearningModule] = []
for module_index, raw_module in enumerate(raw_modules[:8]):
if not isinstance(raw_module, dict):
+ if strict:
+ raise TopicGenerationError(f"Route region {module_index + 1} is invalid")
continue
module_name = str(raw_module.get("name") or "").strip()[:200]
if not module_name:
+ if strict:
+ raise TopicGenerationError(f"Route region {module_index + 1} needs a name")
continue
- module_id = f"{path_id}_m{module_index}"
+ requested_module_id = str(raw_module.get("id") or "").strip()
+ if requested_module_id in allowed_modules and requested_module_id not in used_modules:
+ module_id = requested_module_id
+ used_modules.add(module_id)
+ elif existing_module_ids is None:
+ module_id = f"{path_id}_m{module_index}"
+ reserved_modules.add(module_id)
+ else:
+ module_id = _new_entity_id(f"{path_id}_m", reserved_modules)
knowledge_points: list[KnowledgePoint] = []
raw_kps = raw_module.get("knowledge_points")
if not isinstance(raw_kps, list):
+ if strict:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} needs at least one waypoint"
+ )
continue
+ if strict and not raw_kps:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} needs at least one waypoint"
+ )
for kp_index, raw_kp in enumerate(raw_kps[:7]):
if not isinstance(raw_kp, dict):
+ if strict:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} waypoint {kp_index + 1} is invalid"
+ )
continue
name = str(raw_kp.get("name") or "").strip()[:200]
if len(name) < 2:
+ if strict:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} waypoint {kp_index + 1} needs a name"
+ )
continue
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
if kp_type not in _ALLOWED_TYPES:
+ if strict:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} waypoint {kp_index + 1} has an invalid type"
+ )
kp_type = "concept"
+ requested_objective_id = str(raw_kp.get("id") or "").strip()
+ if (
+ requested_objective_id in allowed_objectives
+ and requested_objective_id not in used_objectives
+ ):
+ objective_id = requested_objective_id
+ used_objectives.add(objective_id)
+ elif existing_objective_ids is None:
+ objective_id = f"{module_id}_kp{kp_index}"
+ reserved_objectives.add(objective_id)
+ else:
+ objective_id = _new_entity_id(f"{module_id}_kp", reserved_objectives)
knowledge_points.append(
KnowledgePoint(
- id=f"{module_id}_kp{kp_index}",
+ id=objective_id,
name=name,
type=KnowledgeType(kp_type),
module_id=module_id,
@@ -83,6 +244,10 @@ def materialize_modules(path_id: str, raw_modules: list[dict[str, Any]]) -> list
knowledge_points=knowledge_points,
)
)
+ elif strict:
+ raise TopicGenerationError(
+ f"Route region {module_index + 1} needs at least one waypoint"
+ )
if not modules:
raise TopicGenerationError("The generated route contains no usable objectives")
return modules
@@ -95,7 +260,12 @@ async def generate_topic_draft(
sources: list[TopicSource],
language: str,
) -> dict[str, Any]:
- source_json = json.dumps(_source_payload(sources), ensure_ascii=False)
+ grounded_sources = await ground_topic_sources(
+ name=name,
+ goal=goal,
+ sources=sources,
+ )
+ source_json = json.dumps(_source_payload(grounded_sources), ensure_ascii=False)
system_prompt, prompt = learning_prompts.topic_generation_prompts(
language,
name=str(name or "").strip()[:120],
@@ -113,7 +283,13 @@ async def generate_topic_draft(
return {
"description": str(data.get("description") or "").strip()[:500],
"modules": [module.model_dump(mode="json") for module in modules],
+ "sources": [source.model_dump(mode="json") for source in grounded_sources],
}
-__all__ = ["TopicGenerationError", "generate_topic_draft", "materialize_modules"]
+__all__ = [
+ "TopicGenerationError",
+ "generate_topic_draft",
+ "ground_topic_sources",
+ "materialize_modules",
+]
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index ae1b53a6e..2eaa430f7 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -253,6 +253,63 @@ class PocketBaseSessionStore:
logger.warning(f"list_sessions failed: {exc}")
return []
+ async def get_session_summaries(
+ self,
+ session_ids: list[str],
+ ) -> list[dict[str, Any]]:
+ """Return bounded metadata without loading complete chat transcripts."""
+
+ async def summarize(session_id: str) -> dict[str, Any] | None:
+ session = await self.get_session(session_id)
+ if session is None:
+ return None
+ message_summary, active_turn = await asyncio.gather(
+ self._get_message_summary(session_id),
+ self.get_active_turn(session_id),
+ )
+ session.update(message_summary)
+ if active_turn is not None:
+ session["status"] = active_turn.get("status") or "running"
+ session["active_turn_id"] = active_turn.get("id") or ""
+ return session
+
+ summaries = await asyncio.gather(
+ *(summarize(session_id) for session_id in dict.fromkeys(session_ids))
+ )
+ return [summary for summary in summaries if summary is not None]
+
+ async def _get_message_summary(self, session_id: str) -> dict[str, Any]:
+ """Fetch one preview row plus PocketBase's aggregate count."""
+
+ sid = _validate_id(session_id, "session_id")
+
+ def _get() -> dict[str, Any]:
+ result = (
+ _pb()
+ .collection("messages")
+ .get_list(
+ 1,
+ 1,
+ query_params={
+ "filter": f'session_id="{sid}" && role!="system"',
+ "sort": "-msg_created_at",
+ },
+ )
+ )
+ total = getattr(result, "total_items", getattr(result, "totalItems", None))
+ items = list(getattr(result, "items", ()) or ())
+ preview = self._message_record_to_dict(items[0]) if items else None
+ return {
+ "message_count": max(0, int(total if total is not None else len(items))),
+ "last_message": str((preview or {}).get("content") or ""),
+ }
+
+ try:
+ return await asyncio.to_thread(_get)
+ except Exception as exc:
+ logger.warning(f"get message summary failed: {exc}")
+ return {"message_count": 0, "last_message": ""}
+
async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:
sid = _validate_id(session_id, "session_id")
uid = _current_user_id()
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index 0d704214a..1f7d0b7eb 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -73,6 +73,11 @@ class SessionStoreProtocol(Protocol):
offset: int = 0,
) -> list[dict[str, Any]]: ...
+ async def get_session_summaries(
+ self,
+ session_ids: list[str],
+ ) -> list[dict[str, Any]]: ...
+
async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool: ...
async def update_session_preferences(
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 36696b1c6..97402182b 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -1413,7 +1413,7 @@ class SQLiteSessionStore:
s.compressed_summary,
s.summary_up_to_msg_id,
s.preferences_json,
- COUNT(m.id) AS message_count,
+ COUNT(CASE WHEN m.role != 'system' THEN 1 END) AS message_count,
COALESCE(
(SELECT t.status FROM turns t WHERE t.session_id = s.id
ORDER BY t.updated_at DESC LIMIT 1),
@@ -1431,7 +1431,8 @@ class SQLiteSessionStore:
) AS capability,
COALESCE(
(SELECT m2.content FROM messages m2
- WHERE m2.session_id = s.id AND TRIM(COALESCE(m2.content, '')) != ''
+ WHERE m2.session_id = s.id AND m2.role != 'system'
+ AND TRIM(COALESCE(m2.content, '')) != ''
ORDER BY m2.id DESC LIMIT 1),
''
) AS last_message
@@ -1456,13 +1457,31 @@ class SQLiteSessionStore:
self._SESSION_SUMMARY_SQL.format(where=where_sql),
(limit, offset),
).fetchall()
- sessions = []
- for row in rows:
- payload = dict(row)
- payload["session_id"] = payload["id"]
- payload["preferences"] = _json_loads(payload.pop("preferences_json", ""), {})
- sessions.append(payload)
- return sessions
+ return [self._session_summary_payload(row) for row in rows]
+
+ @staticmethod
+ def _session_summary_payload(row: sqlite3.Row) -> dict[str, Any]:
+ payload = dict(row)
+ payload["session_id"] = payload["id"]
+ payload["preferences"] = _json_loads(payload.pop("preferences_json", ""), {})
+ return payload
+
+ def _get_session_summaries_sync(
+ self,
+ session_ids: list[str],
+ ) -> list[dict[str, Any]]:
+ ids = list(dict.fromkeys(str(item or "").strip() for item in session_ids))
+ ids = [item for item in ids if item]
+ if not ids:
+ return []
+ placeholders = ",".join("?" for _ in ids)
+ where = f"WHERE s.id IN ({placeholders})"
+ with self._connect() as conn:
+ rows = conn.execute(
+ self._SESSION_SUMMARY_SQL.format(where=where),
+ (*ids, len(ids), 0),
+ ).fetchall()
+ return [self._session_summary_payload(row) for row in rows]
def _list_sessions_sync(
self,
@@ -1487,6 +1506,12 @@ class SQLiteSessionStore:
) -> list[dict[str, Any]]:
return await self._run(self._list_sessions_sync, limit, offset)
+ async def get_session_summaries(
+ self,
+ session_ids: list[str],
+ ) -> list[dict[str, Any]]:
+ return await self._run(self._get_session_summaries_sync, session_ids)
+
async def list_imported_sessions(
self,
limit: int = 50,
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 307785f6a..57d6e99c3 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -996,6 +996,40 @@ class TurnRuntimeManager:
f"path {path_id!r} is already active in session {exc.lease.session_id!r}"
) from exc
+ @staticmethod
+ async def _validate_mastery_session_topic(
+ *,
+ session_id: str,
+ requested_path_id: str,
+ remembered_path_id: str,
+ ) -> None:
+ """Reject a topic URL paired with an unrelated existing chat session.
+
+ A new session has no associations and may start any topic. Historical
+ sessions may resume any path they were durably bound to (including a
+ legitimate in-chat path switch), while the remembered preference
+ covers sessions created before explicit bindings were introduced.
+ """
+
+ from deeptutor.learning.storage import LearningStore
+
+ learning_store = LearningStore()
+ associations = await asyncio.to_thread(
+ learning_store.list_paths_for_session,
+ session_id,
+ )
+ known_path_ids = {str(item.get("path_id") or "") for item in associations}
+ remembered = str(remembered_path_id or "").strip()
+ if (
+ (known_path_ids or remembered)
+ and requested_path_id not in known_path_ids
+ and (not remembered or requested_path_id != remembered)
+ ):
+ raise RuntimeError(
+ "mastery_session_topic_mismatch: "
+ f"session {session_id!r} does not belong to path {requested_path_id!r}"
+ )
+
async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
capability = str(payload.get("capability") or "chat")
if not payload.get("language"):
@@ -1054,6 +1088,11 @@ class TurnRuntimeManager:
session_id=session["id"],
)
mastery_path_id = mastery_binding.path_id
+ await self._validate_mastery_session_topic(
+ session_id=session["id"],
+ requested_path_id=mastery_path_id,
+ remembered_path_id=_mastery_path_id(preferences.get("mastery_path_id")),
+ )
else:
mastery_path_id = configured_mastery_path_id
payload = {**payload, "mastery_path_id": mastery_path_id}
diff --git a/tests/services/session/test_pocketbase_isolation.py b/tests/services/session/test_pocketbase_isolation.py
index a49849dff..f2b1866db 100644
--- a/tests/services/session/test_pocketbase_isolation.py
+++ b/tests/services/session/test_pocketbase_isolation.py
@@ -43,8 +43,9 @@ class _Record:
class _Result:
- def __init__(self, items: list[_Record]) -> None:
+ def __init__(self, items: list[_Record], total_items: int) -> None:
self.items = items
+ self.total_items = total_items
class _Collection:
@@ -72,8 +73,15 @@ class _Collection:
def get_list(self, page: int, per_page: int, query_params: dict | None = None) -> _Result:
matched = self.get_full_list(query_params)
+ sort = str((query_params or {}).get("sort") or "")
+ if sort:
+ field = sort.lstrip("-")
+ matched.sort(
+ key=lambda record: getattr(record, field, 0),
+ reverse=sort.startswith("-"),
+ )
start = (page - 1) * per_page
- return _Result(matched[start : start + per_page])
+ return _Result(matched[start : start + per_page], len(matched))
def update(self, pb_id: str, data: dict) -> _Record:
record = next(r for r in self._rows if r.id == pb_id)
@@ -127,6 +135,19 @@ async def test_list_sessions_only_returns_own(fake_pb) -> None:
assert {s["session_id"] for s in alice_sessions} == {"s_a1", "s_a2"}
+async def test_session_summaries_count_messages_without_loading_transcripts(fake_pb) -> None:
+ store = PocketBaseSessionStore()
+ with as_user("alice"):
+ session = await store.create_session(title="summary", session_id="s_summary")
+ await store.add_message(session["id"], "user", "first")
+ await store.add_message(session["id"], "assistant", "latest")
+
+ [summary] = await store.get_session_summaries([session["id"]])
+
+ assert summary["message_count"] == 2
+ assert summary["last_message"] == "latest"
+
+
async def test_get_session_404s_for_other_user(fake_pb) -> None:
store = PocketBaseSessionStore()
with as_user("alice"):
diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py
index ddd4409b3..969e5fd40 100644
--- a/tests/services/session/test_sqlite_store.py
+++ b/tests/services/session/test_sqlite_store.py
@@ -76,6 +76,25 @@ def _make_items(*specs):
return items
+def test_get_session_summaries_batches_counts_and_latest_visible_message(
+ store: SQLiteSessionStore,
+) -> None:
+ first = asyncio.run(store.create_session(title="First", session_id="session-1"))
+ second = asyncio.run(store.create_session(title="Second", session_id="session-2"))
+ asyncio.run(store.add_message(first["id"], "system", "private setup"))
+ asyncio.run(store.add_message(first["id"], "user", "First question"))
+ asyncio.run(store.add_message(first["id"], "assistant", "Latest answer"))
+ asyncio.run(store.add_message(second["id"], "system", "system only"))
+
+ summaries = asyncio.run(store.get_session_summaries([first["id"], second["id"], first["id"]]))
+ by_id = {summary["session_id"]: summary for summary in summaries}
+
+ assert by_id[first["id"]]["message_count"] == 2
+ assert by_id[first["id"]]["last_message"] == "Latest answer"
+ assert by_id[second["id"]]["message_count"] == 0
+ assert by_id[second["id"]]["last_message"] == ""
+
+
# ── Notebook entries ──────────────────────────────────────────────
diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.py
index d2aa5842d..1d162ae14 100644
--- a/tests/services/session/test_turn_runtime_subscribe.py
+++ b/tests/services/session/test_turn_runtime_subscribe.py
@@ -422,6 +422,30 @@ async def test_mastery_path_allows_only_one_live_turn_across_sessions(
LearningStore().release_path_lease("shared", turn_id=first_turn["id"])
+async def test_mastery_turn_rejects_session_from_an_unrelated_topic(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ _isolate_learning_store(monkeypatch, tmp_path)
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ session = await store.ensure_session("session-1")
+ await store.update_session_preferences(
+ session["id"],
+ {"mastery_path_id": "topic-a"},
+ )
+ LearningStore().bind_session("topic-a", session["id"])
+
+ with pytest.raises(RuntimeError, match="mastery_session_topic_mismatch"):
+ await runtime.start_turn(_mastery_payload(session["id"], "topic-b"))
+
+ detail = await store.get_session(session["id"])
+ assert detail is not None
+ assert detail["preferences"]["mastery_path_id"] == "topic-a"
+ assert await store.get_active_turn(session["id"]) is None
+ assert LearningStore().list_paths_for_session(session["id"])[0]["path_id"] == "topic-a"
+
+
@pytest.mark.asyncio
async def test_mastery_turn_takes_over_a_path_parked_on_ask_user(
monkeypatch: pytest.MonkeyPatch, tmp_path
diff --git a/web/app/(utility)/space/learning/[pathId]/page.tsx b/web/app/(utility)/space/learning/[pathId]/page.tsx
index 9163dc8bd..057291fcb 100644
--- a/web/app/(utility)/space/learning/[pathId]/page.tsx
+++ b/web/app/(utility)/space/learning/[pathId]/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
@@ -19,6 +19,7 @@ import {
} from "lucide-react";
import { AdventureMap } from "@/components/space/learning/AdventureMap";
+import { ConfirmDialog } from "@/components/space/learning/ConfirmDialog";
import { EditTopicRouteDialog } from "@/components/space/learning/EditTopicRouteDialog";
import {
topicDisplayName,
@@ -46,6 +47,12 @@ const NEXT_LABELS: Record<string, { zh: string; en: string }> = {
complete: { zh: "整片疆域已经点亮", en: "The whole territory is illuminated" },
};
+const NEXT_CTA_LABELS: Record<string, { zh: string; en: string }> = {
+ review: { zh: "开始本次复习", en: "Start this review" },
+ answer_pending: { zh: "回到原会话作答", en: "Answer in the original session" },
+ complete: { zh: "继续自由探索", en: "Keep exploring" },
+};
+
export default function MasteryTopicPage() {
const params = useParams<{ pathId: string }>();
const pathId = String(params.pathId || "");
@@ -60,8 +67,27 @@ export default function MasteryTopicPage() {
const [error, setError] = useState<string | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [editorOpen, setEditorOpen] = useState(false);
+ const [confirmAction, setConfirmAction] = useState<"reset" | "delete" | null>(
+ null,
+ );
+ const [mutationBusy, setMutationBusy] = useState(false);
+ const editorTriggerRef = useRef<HTMLElement | null>(null);
+ const confirmTriggerRef = useRef<HTMLElement | null>(null);
const activity = useMasteryPathActivity(pathId || null);
+ const openEditor = (trigger: HTMLButtonElement) => {
+ editorTriggerRef.current = trigger;
+ setEditorOpen(true);
+ };
+
+ const openConfirmation = (
+ action: "reset" | "delete",
+ trigger: HTMLButtonElement,
+ ) => {
+ confirmTriggerRef.current = trigger;
+ setConfirmAction(action);
+ };
+
const loadTopic = useCallback(async () => {
try {
const next = await fetchMasteryTopic(pathId, { cache: "no-store" });
@@ -118,23 +144,24 @@ export default function MasteryTopicPage() {
};
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();
+ setMutationBusy(true);
+ try {
+ await redoProgress(pathId);
+ await refresh();
+ setConfirmAction(null);
+ } finally {
+ setMutationBusy(false);
+ }
};
const handleDelete = async () => {
- if (!window.confirm(tr("永久删除这个学习主题?", "Permanently delete this learning topic?"))) return;
- await deleteProgress(pathId);
- router.replace("/space/learning");
+ setMutationBusy(true);
+ try {
+ await deleteProgress(pathId);
+ router.replace("/space/learning");
+ } finally {
+ setMutationBusy(false);
+ }
};
if (loading && !topic) {
@@ -165,10 +192,19 @@ export default function MasteryTopicPage() {
const progress = topic.map.counts.total
? Math.round((topic.map.counts.mastered / topic.map.counts.total) * 100)
: 0;
+ const needsRouteRepair = topic.map.counts.total === 0;
+ const nextCta = NEXT_CTA_LABELS[topic.next.action];
+ const pendingSessionId =
+ topic.next.session_id ||
+ sessions.find((session) => session.has_pending_question)?.session_id;
+ const continuationSessionId =
+ topic.next.action === "answer_pending"
+ ? pendingSessionId
+ : sessions[0]?.session_id;
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="mx-auto max-w-[1440px] px-4 pb-48 pt-6 sm:px-7 sm:pb-7 lg:px-9 lg:py-8">
<div className="flex items-center justify-between gap-3">
<Link
href="/space/learning"
@@ -188,7 +224,7 @@ export default function MasteryTopicPage() {
</span>
<button
type="button"
- onClick={() => setEditorOpen(true)}
+ onClick={(event) => openEditor(event.currentTarget)}
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" />
@@ -202,14 +238,18 @@ export default function MasteryTopicPage() {
<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()}
+ onClick={(event) =>
+ openConfirmation("reset", event.currentTarget)
+ }
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()}
+ onClick={(event) =>
+ openConfirmation("delete", event.currentTarget)
+ }
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")}
@@ -262,47 +302,104 @@ export default function MasteryTopicPage() {
</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">
+ <section className="fixed bottom-3 left-4 right-4 z-20 flex flex-col gap-4 rounded-[22px] border border-[var(--border)] bg-[var(--card)]/95 p-4 shadow-lg backdrop-blur sm:static sm:mt-7 sm:flex-row sm:items-center sm:justify-between sm:bg-[var(--card)] sm:p-5 sm:shadow-sm">
<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" />}
+ {needsRouteRepair ? (
+ <PencilRuler className="h-4 w-4" />
+ ) : 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")}
+ {needsRouteRepair
+ ? tr("路线需要修复", "Route needs repair")
+ : 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}
+ {needsRouteRepair
+ ? tr(
+ "这是一张旧版空地图。添加至少一个区域和关卡后即可开始学习。",
+ "This migrated map has no runnable route. Add at least one region and waypoint to begin.",
+ )
+ : 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>
+ {needsRouteRepair ? (
+ <button
+ type="button"
+ onClick={(event) => openEditor(event.currentTarget)}
+ 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"
+ >
+ <PencilRuler className="h-4 w-4" />
+ {tr("修复路线", "Repair route")}
+ <ArrowRight className="h-3.5 w-3.5" />
+ </button>
+ ) : (
+ <Link
+ href={
+ continuationSessionId
+ ? `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(continuationSessionId)}`
+ : `/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" />
+ {nextCta
+ ? zh
+ ? nextCta.zh
+ : nextCta.en
+ : 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}
- />
+ {needsRouteRepair ? (
+ <section className="mastery-map-paper flex min-h-72 flex-col items-center justify-center rounded-[26px] border border-dashed border-black/15 p-8 text-center">
+ <PencilRuler className="h-9 w-9 text-[var(--mastery-route)]" />
+ <h2 className="mt-4 text-lg font-semibold">
+ {tr("先补画学习路线", "Chart the missing route")}
+ </h2>
+ <p className="mt-2 max-w-md text-sm leading-6 text-[var(--muted-foreground)]">
+ {tr(
+ "旧版主题已安全迁移,但没有可运行的区域或关卡。学习证据不会凭空生成;请先定义你真正要掌握的路线。",
+ "The legacy topic migrated safely, but it has no runnable regions or waypoints. Define the abilities you want to master before tutoring begins.",
+ )}
+ </p>
+ <button
+ type="button"
+ onClick={(event) => openEditor(event.currentTarget)}
+ className="mt-5 inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--mastery-ink)] px-4 text-sm font-medium text-[var(--mastery-paper-raised)]"
+ >
+ <PencilRuler className="h-4 w-4" />
+ {tr("添加区域和关卡", "Add regions and waypoints")}
+ </button>
+ </section>
+ ) : (
+ <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}
@@ -331,6 +428,7 @@ export default function MasteryTopicPage() {
<EditTopicRouteDialog
topic={topic}
tr={tr}
+ returnFocusRef={editorTriggerRef}
onClose={() => setEditorOpen(false)}
onSaved={(next) => {
setTopic(next);
@@ -340,6 +438,37 @@ export default function MasteryTopicPage() {
}}
/>
)}
+ {confirmAction === "reset" && (
+ <ConfirmDialog
+ title={tr("重置学习进度?", "Reset learning progress?")}
+ description={tr(
+ "区域和关卡会保留;掌握证据、待回答问题和复习计划会被清空。",
+ "Regions and waypoints stay. Mastery evidence, pending questions, and review schedules will be cleared.",
+ )}
+ confirmLabel={tr("确认重置", "Reset progress")}
+ cancelLabel={tr("取消", "Cancel")}
+ busy={mutationBusy}
+ returnFocusRef={confirmTriggerRef}
+ onConfirm={() => void handleReset()}
+ onClose={() => setConfirmAction(null)}
+ />
+ )}
+ {confirmAction === "delete" && (
+ <ConfirmDialog
+ title={tr("永久删除学习主题?", "Permanently delete this topic?")}
+ description={tr(
+ "地图、证据、复习计划和关联记录都会删除。此操作无法撤销。",
+ "The map, evidence, review schedule, and linked records will be deleted. This cannot be undone.",
+ )}
+ confirmLabel={tr("永久删除", "Delete permanently")}
+ cancelLabel={tr("取消", "Cancel")}
+ destructive
+ busy={mutationBusy}
+ returnFocusRef={confirmTriggerRef}
+ onConfirm={() => void handleDelete()}
+ onClose={() => setConfirmAction(null)}
+ />
+ )}
</main>
);
}
diff --git a/web/app/(utility)/space/learning/page.tsx b/web/app/(utility)/space/learning/page.tsx
index d493a8375..161300755 100644
--- a/web/app/(utility)/space/learning/page.tsx
+++ b/web/app/(utility)/space/learning/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
@@ -24,6 +24,7 @@ export default function MasteryPathPage() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [wizardOpen, setWizardOpen] = useState(false);
+ const wizardTriggerRef = useRef<HTMLElement | null>(null);
const loadTopics = useCallback(async () => {
setError(null);
@@ -51,7 +52,10 @@ export default function MasteryPathPage() {
loading={loading}
error={error}
tr={tr}
- onCreate={() => setWizardOpen(true)}
+ onCreate={(trigger) => {
+ wizardTriggerRef.current = trigger;
+ setWizardOpen(true);
+ }}
onRetry={() => {
setLoading(true);
void loadTopics();
@@ -60,6 +64,7 @@ export default function MasteryPathPage() {
{wizardOpen && (
<CreateTopicWizard
tr={tr}
+ returnFocusRef={wizardTriggerRef}
onClose={() => setWizardOpen(false)}
onCreated={(topic) => {
setWizardOpen(false);
diff --git a/web/components/space/learning/AdventureMap.tsx b/web/components/space/learning/AdventureMap.tsx
index f1860463b..bde6ffd71 100644
--- a/web/components/space/learning/AdventureMap.tsx
+++ b/web/components/space/learning/AdventureMap.tsx
@@ -23,7 +23,7 @@ import {
type ObjectiveReport,
} from "@/lib/learning-api";
-import type { Translate } from "./format";
+import { knowledgeTypeLabel, type Translate } from "./format";
import { ObjectiveDetail } from "./ObjectiveDetail";
interface Point {
@@ -167,36 +167,44 @@ export function AdventureMap({
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" : ""}`}
+ className="mastery-waypoint group absolute left-0 top-0 flex w-44 -translate-x-1/2 -translate-y-6 flex-col items-center outline-none"
>
- {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
+ className={`mastery-waypoint-icon flex h-12 w-12 items-center justify-center rounded-2xl border-2 shadow-md ${
+ 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" />
+ )}
+ </span>
+ <span
+ className={`mt-3 w-full 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 group-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>
</span>
</button>
{current && (
@@ -294,7 +302,7 @@ function ObjectiveDrawer({
<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>
+ <span>{knowledgeTypeLabel(report.type, tr)}</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" />
diff --git a/web/components/space/learning/ConfirmDialog.tsx b/web/components/space/learning/ConfirmDialog.tsx
new file mode 100644
index 000000000..0a6b82c5e
--- /dev/null
+++ b/web/components/space/learning/ConfirmDialog.tsx
@@ -0,0 +1,97 @@
+"use client";
+
+import type { RefObject } from "react";
+import { AlertTriangle, Loader2, X } from "lucide-react";
+
+import { useModalDialog } from "@/hooks/useModalDialog";
+
+export function ConfirmDialog({
+ title,
+ description,
+ confirmLabel,
+ cancelLabel,
+ destructive = false,
+ busy = false,
+ onConfirm,
+ onClose,
+ returnFocusRef,
+}: {
+ title: string;
+ description: string;
+ confirmLabel: string;
+ cancelLabel: string;
+ destructive?: boolean;
+ busy?: boolean;
+ onConfirm: () => void;
+ onClose: () => void;
+ returnFocusRef: RefObject<HTMLElement | null>;
+}) {
+ const dialogRef = useModalDialog(onClose, busy, returnFocusRef);
+ return (
+ <div className="fixed inset-0 z-[60] flex items-center justify-center bg-[var(--overlay)] p-5 backdrop-blur-[2px]">
+ <div
+ ref={dialogRef}
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="confirm-dialog-title"
+ aria-describedby="confirm-dialog-description"
+ tabIndex={-1}
+ className="w-full max-w-md rounded-[22px] border border-[var(--border)] bg-[var(--card)] p-5 shadow-2xl outline-none"
+ >
+ <div className="flex items-start gap-3">
+ <span
+ className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl ${
+ destructive
+ ? "bg-red-500/10 text-red-600"
+ : "bg-amber-500/10 text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ <AlertTriangle className="h-4 w-4" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <h2 id="confirm-dialog-title" className="text-base font-semibold">
+ {title}
+ </h2>
+ <p
+ id="confirm-dialog-description"
+ className="mt-1.5 text-sm leading-6 text-[var(--muted-foreground)]"
+ >
+ {description}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ disabled={busy}
+ aria-label={cancelLabel}
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--accent)] disabled:opacity-40"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+ <div className="mt-5 flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={onClose}
+ disabled={busy}
+ className="h-10 rounded-xl px-4 text-sm text-[var(--muted-foreground)] hover:bg-[var(--accent)] disabled:opacity-50"
+ >
+ {cancelLabel}
+ </button>
+ <button
+ type="button"
+ onClick={onConfirm}
+ disabled={busy}
+ data-modal-initial-focus
+ className={`inline-flex h-10 items-center gap-2 rounded-xl px-4 text-sm font-medium text-white disabled:opacity-50 ${
+ destructive ? "bg-red-600 hover:bg-red-700" : "bg-[var(--primary)]"
+ }`}
+ >
+ {busy && <Loader2 className="h-4 w-4 animate-spin" />}
+ {confirmLabel}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/space/learning/CreateTopicWizard.tsx b/web/components/space/learning/CreateTopicWizard.tsx
index b5b003abf..cc7134c76 100644
--- a/web/components/space/learning/CreateTopicWizard.tsx
+++ b/web/components/space/learning/CreateTopicWizard.tsx
@@ -1,162 +1,58 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useState, type RefObject } 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 { useModalDialog } from "@/hooks/useModalDialog";
+import {
+ hydrateTopicSource,
+ useTopicSourceLibrary,
+} from "@/hooks/useTopicSourceLibrary";
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 = ["🧭", "🏔️", "🌿", "🔭", "🧪", "🧠", "📐", "🌌"];
+import { RouteDraftEditor } from "./RouteDraftEditor";
+import { isRouteDraftValid } from "./route-draft";
+import { DestinationStep, SourcesStep } from "./TopicWizardSteps";
export function CreateTopicWizard({
tr,
onClose,
onCreated,
+ returnFocusRef,
}: {
tr: Translate;
onClose: () => void;
onCreated: (topic: MasteryTopic) => void;
+ returnFocusRef: RefObject<HTMLElement | null>;
}) {
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 { library, loading: libraryLoading, candidates } =
+ useTopicSourceLibrary(tr);
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 dialogRef = useModalDialog(onClose, busy, returnFocusRef);
const toggleSource = (key: string) => {
setSelected((previous) => {
@@ -167,76 +63,14 @@ export function CreateTopicWizard({
});
};
- 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 chosen = candidates.filter((candidate) =>
+ selected.has(candidate.key),
+ );
+ const hydrated = await Promise.all(chosen.map(hydrateTopicSource));
const nextSources: TopicSourceInput[] = [
{
kind: "goal",
@@ -250,14 +84,17 @@ export function CreateTopicWizard({
goal: goal.trim(),
sources: nextSources,
});
- setSources(nextSources);
+ setSources(nextDraft.sources ?? nextSources);
setDraft(nextDraft);
setStep(3);
} catch (reason) {
setError(
reason instanceof Error
? reason.message
- : tr("路线生成失败,请重试。", "Route generation failed. Please retry."),
+ : tr(
+ "路线生成失败,请重试。",
+ "Route generation failed. Please retry.",
+ ),
);
} finally {
setBusy(false);
@@ -265,7 +102,7 @@ export function CreateTopicWizard({
};
const confirm = async () => {
- if (!draft) return;
+ if (!draft || !isRouteDraftValid(draft)) return;
setBusy(true);
setError(null);
try {
@@ -291,15 +128,19 @@ export function CreateTopicWizard({
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]">
+ <div
+ ref={dialogRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="create-topic-title"
+ tabIndex={-1}
+ 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 outline-none 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)]">
@@ -325,7 +166,10 @@ export function CreateTopicWizard({
</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")}>
+ <ol
+ className="grid grid-cols-3 gap-2"
+ aria-label={tr("创建步骤", "Creation steps")}
+ >
{[
tr("目的地", "Destination"),
tr("补给", "Sources"),
@@ -349,7 +193,9 @@ export function CreateTopicWizard({
</span>
<span
className={`hidden text-xs sm:inline ${
- active ? "font-medium text-[var(--foreground)]" : "text-[var(--muted-foreground)]"
+ active
+ ? "font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)]"
}`}
>
{label}
@@ -419,18 +265,30 @@ export function CreateTopicWizard({
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")}
+ {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}
+ disabled={busy || !draft || !isRouteDraftValid(draft)}
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")}
+ {busy ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Check className="h-4 w-4" />
+ )}
+ {busy
+ ? tr("正在落图…", "Saving map…")
+ : tr("开启远征", "Start expedition")}
</button>
)}
</footer>
@@ -438,412 +296,3 @@ export function CreateTopicWizard({
</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.tsx
index 7d257aaee..d22334899 100644
--- a/web/components/space/learning/EditTopicRouteDialog.tsx
+++ b/web/components/space/learning/EditTopicRouteDialog.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useMemo, useState } from "react";
+import { useMemo, useState, type RefObject } from "react";
import { AlertTriangle, Check, Loader2, X } from "lucide-react";
+import { useModalDialog } from "@/hooks/useModalDialog";
import {
type MasteryTopic,
type ModuleInit,
@@ -10,8 +11,9 @@ import {
updateMasteryTopicMap,
} from "@/lib/learning-api";
-import { RouteDraftEditor } from "./CreateTopicWizard";
import type { Translate } from "./format";
+import { RouteDraftEditor } from "./RouteDraftEditor";
+import { isRouteDraftValid } from "./route-draft";
function topicDraft(topic: MasteryTopic): TopicDraft {
return {
@@ -37,18 +39,22 @@ export function EditTopicRouteDialog({
tr,
onClose,
onSaved,
+ returnFocusRef,
}: {
topic: MasteryTopic;
tr: Translate;
onClose: () => void;
onSaved: (topic: MasteryTopic) => void;
+ returnFocusRef: RefObject<HTMLElement | null>;
}) {
const original = useMemo(() => topicDraft(topic), [topic]);
const [draft, setDraft] = useState(original);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const dialogRef = useModalDialog(onClose, busy, returnFocusRef);
const save = async () => {
+ if (!isRouteDraftValid(draft)) return;
setBusy(true);
setError(null);
try {
@@ -62,12 +68,16 @@ export function EditTopicRouteDialog({
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]">
+ <div
+ ref={dialogRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="edit-route-title"
+ tabIndex={-1}
+ 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 outline-none 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)]">
@@ -116,7 +126,7 @@ export function EditTopicRouteDialog({
<button
type="button"
onClick={() => void save()}
- disabled={busy || !draft.modules.length}
+ disabled={busy || !isRouteDraftValid(draft)}
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" />}
diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsx
index 29b0b6dc0..5ffc550f2 100644
--- a/web/components/space/learning/MasteryStudy.tsx
+++ b/web/components/space/learning/MasteryStudy.tsx
@@ -27,9 +27,18 @@ 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 { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";
+import {
+ fetchMasteryTopic,
+ fetchMasteryTopicSessions,
+ type MasteryTopic,
+} from "@/lib/learning-api";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
import { useImeComposing } from "@/lib/use-ime-composing";
+import {
+ isMasteryDraftSessionReady,
+ type MasteryDraftRouteGuard,
+} from "@/lib/mastery-study-route";
import { topicDisplayName, type Translate } from "./format";
@@ -51,7 +60,11 @@ const STARTERS = [
},
] as const;
-function currentWaypoint(topic: MasteryTopic, fallback: string) {
+function currentWaypoint(
+ topic: MasteryTopic,
+ fallback: string,
+ tr: Translate,
+) {
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(
@@ -59,7 +72,7 @@ function currentWaypoint(topic: MasteryTopic, fallback: string) {
);
if (point) return point.name;
}
- return topic.map.complete ? "Journey complete" : fallback;
+ return topic.map.complete ? tr("旅程已完成", "Journey complete") : fallback;
}
export function MasteryStudy({
@@ -98,6 +111,8 @@ export function MasteryStudy({
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const initializedRouteRef = useRef("");
+ const draftRouteGuardRef = useRef<MasteryDraftRouteGuard | null>(null);
+ const activity = useMasteryPathActivity(pathId || null);
const { isComposingRef, onCompositionStart, onCompositionEnd } =
useImeComposing();
@@ -120,7 +135,7 @@ export function MasteryStudy({
return () => {
active = false;
};
- }, [pathId, tr]);
+ }, [activity.revision, pathId, tr]);
const knowledgeBases = useMemo(
() =>
@@ -150,13 +165,37 @@ export function MasteryStudy({
initializedRouteRef.current = routeKey;
if (!routeSessionId) {
+ draftRouteGuardRef.current = {
+ routeKey,
+ previousSessionId: state.sessionId,
+ };
newSession(sessionConfiguration);
return;
}
- const cached = showCachedSession(routeSessionId);
- if (cached) configureSession(sessionConfiguration, routeSessionId);
- void loadSession(routeSessionId, cached ? { revalidate: true } : undefined)
+ draftRouteGuardRef.current = null;
+
+ void fetchMasteryTopicSessions(pathId, { cache: "no-store" })
+ .then((topicSessions) => {
+ if (
+ !topicSessions.some(
+ (candidate) => candidate.session_id === routeSessionId,
+ )
+ ) {
+ throw new Error(
+ tr(
+ "这个会话不属于当前学习主题。请从本主题的会话营地重新进入。",
+ "This session belongs to a different learning topic. Open a session from this topic's camp instead.",
+ ),
+ );
+ }
+ const cached = showCachedSession(routeSessionId);
+ if (cached) configureSession(sessionConfiguration, routeSessionId);
+ return loadSession(
+ routeSessionId,
+ cached ? { revalidate: true } : undefined,
+ );
+ })
.then(() => {
configureSession(sessionConfiguration, routeSessionId);
setSessionResolution({ routeKey, error: null });
@@ -182,18 +221,37 @@ export function MasteryStudy({
routeSessionId,
sessionConfiguration,
showCachedSession,
+ state.sessionId,
topic,
tr,
]);
useEffect(() => {
- if (routeSessionId || !state.sessionId || state.masteryPathId !== pathId)
+ const newSessionId = state.sessionId;
+ if (
+ routeSessionId ||
+ !newSessionId ||
+ !isMasteryDraftSessionReady({
+ guard: draftRouteGuardRef.current,
+ routeKey: currentRouteKey,
+ sessionId: newSessionId,
+ masteryPathId: state.masteryPathId,
+ pathId,
+ })
+ )
return;
router.replace(
- `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(state.sessionId)}`,
+ `/space/learning/${encodeURIComponent(pathId)}/study/${encodeURIComponent(newSessionId)}`,
{ scroll: false },
);
- }, [pathId, routeSessionId, router, state.masteryPathId, state.sessionId]);
+ }, [
+ currentRouteKey,
+ pathId,
+ routeSessionId,
+ router,
+ state.masteryPathId,
+ state.sessionId,
+ ]);
const sessionError =
sessionResolution?.routeKey === currentRouteKey
@@ -201,8 +259,7 @@ export function MasteryStudy({
: null;
const sessionLoading = Boolean(
routeSessionId &&
- sessionResolution?.routeKey !== currentRouteKey &&
- state.sessionId !== routeSessionId,
+ sessionResolution?.routeKey !== currentRouteKey,
);
useEffect(() => {
@@ -222,11 +279,12 @@ export function MasteryStudy({
const submit = useCallback(
(value = draft) => {
const content = value.trim();
- if (!content || state.isStreaming || sessionLoading) return;
+ if (!content || state.isStreaming || sessionLoading || sessionError)
+ return;
sendMessage(content);
setDraft("");
},
- [draft, sendMessage, sessionLoading, state.isStreaming],
+ [draft, sendMessage, sessionError, sessionLoading, state.isStreaming],
);
const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
@@ -268,7 +326,7 @@ export function MasteryStudy({
}
const displayName = topicDisplayName(topic, tr);
- const waypoint = currentWaypoint(topic, displayName);
+ const waypoint = currentWaypoint(topic, displayName, tr);
const completed = topic.map.counts.mastered;
const total = topic.map.counts.total;
const progress = total ? Math.round((completed / total) * 100) : 0;
@@ -360,12 +418,12 @@ export function MasteryStudy({
<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 ? (
+ {sessionLoading ? (
<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 ? (
+ ) : sessionError ? (
<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">
@@ -440,53 +498,55 @@ export function MasteryStudy({
</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}”…`,
+ {!sessionError && (
+ <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>
)}
- 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>
- <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.tsx
index 78acf4329..8310befa8 100644
--- a/web/components/space/learning/ObjectiveDetail.tsx
+++ b/web/components/space/learning/ObjectiveDetail.tsx
@@ -125,6 +125,11 @@ export function ObjectiveDetail({
function GateBar({ report, tr }: { report: ObjectiveReport; tr: Translate }) {
const pct = Math.round(report.mastery * 100);
const thresholdPct = Math.round(report.threshold * 100);
+ const perfectButBelowGate =
+ report.gate === "quantitative" &&
+ report.attempts.length > 0 &&
+ report.correct_count === report.attempts.length &&
+ report.mastery < report.threshold;
return (
<div>
<div className="flex items-baseline justify-between text-xs">
@@ -161,6 +166,14 @@ function GateBar({ report, tr }: { report: ObjectiveReport; tr: Translate }) {
/>
)}
</div>
+ {perfectButBelowGate && (
+ <p className="mt-1.5 text-[11px] leading-4 text-[var(--muted-foreground)]">
+ {tr(
+ `虽然目前 ${report.correct_count}/${report.attempts.length} 全部答对,掌握分仍会结合证据数量、难度与近期稳定性计算;再完成一次有区分度的练习即可继续提高。`,
+ `Even with ${report.correct_count}/${report.attempts.length} correct so far, mastery also weighs evidence volume, difficulty, and recent consistency. One more discriminating practice can raise it further.`,
+ )}
+ </p>
+ )}
</div>
);
}
diff --git a/web/components/space/learning/RouteDraftEditor.tsx b/web/components/space/learning/RouteDraftEditor.tsx
new file mode 100644
index 000000000..110d983d6
--- /dev/null
+++ b/web/components/space/learning/RouteDraftEditor.tsx
@@ -0,0 +1,393 @@
+"use client";
+
+import {
+ ArrowDown,
+ ArrowUp,
+ Plus,
+ Trash2,
+ X,
+} from "lucide-react";
+
+import type { ModuleInit, TopicDraft } from "@/lib/learning-api";
+
+import type { Translate } from "./format";
+import {
+ moveRouteModule,
+ moveRouteWaypoint,
+ normalizeRouteModules,
+ routeDraftIssues,
+} from "./route-draft";
+
+let fallbackSequence = 0;
+
+function draftId(kind: "region" | "waypoint"): string {
+ const random = globalThis.crypto?.randomUUID?.();
+ return random
+ ? `draft_${kind}_${random}`
+ : `draft_${kind}_${Date.now()}_${fallbackSequence++}`;
+}
+
+export function RouteDraftEditor({
+ draft,
+ tr,
+ onChange,
+ compact = false,
+ showDescription = true,
+}: {
+ draft: TopicDraft;
+ tr: Translate;
+ onChange: (draft: TopicDraft) => void;
+ compact?: boolean;
+ showDescription?: boolean;
+}) {
+ const issues = routeDraftIssues(draft);
+ const updateModule = (index: number, module: ModuleInit) => {
+ const modules = [...draft.modules];
+ modules[index] = module;
+ onChange({ ...draft, modules: normalizeRouteModules(modules) });
+ };
+ const removeModule = (index: number) =>
+ onChange({
+ ...draft,
+ modules: normalizeRouteModules(
+ draft.modules.filter((_, moduleIndex) => moduleIndex !== index),
+ ),
+ });
+ const addModule = () => {
+ const index = draft.modules.length;
+ const moduleId = draftId("region");
+ onChange({
+ ...draft,
+ modules: normalizeRouteModules([
+ ...draft.modules,
+ {
+ id: moduleId,
+ name: tr(`新区域 ${index + 1}`, `New region ${index + 1}`),
+ order: index,
+ knowledge_points: [
+ {
+ id: draftId("waypoint"),
+ name: tr("新关卡", "New waypoint"),
+ type: "concept",
+ module_id: moduleId,
+ },
+ ],
+ },
+ ]),
+ });
+ };
+ const moduleHasIssue = (moduleIndex: number, code: string) =>
+ issues.some(
+ (issue) =>
+ "moduleIndex" in issue &&
+ issue.moduleIndex === moduleIndex &&
+ issue.code === code,
+ );
+ const waypointHasIssue = (moduleIndex: number, waypointIndex: number) =>
+ issues.some(
+ (issue) =>
+ issue.code === "blank_waypoint" &&
+ issue.moduleIndex === moduleIndex &&
+ issue.waypointIndex === waypointIndex,
+ );
+
+ 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 and waypoints define the abilities to master. Up/down controls make the full order editable by keyboard as well as pointer.",
+ )}
+ </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>
+ )}
+ {issues.some((issue) => issue.code === "no_regions") && (
+ <p role="alert" className="mt-4 text-xs font-medium text-red-600">
+ {tr("至少保留一个区域。", "Keep at least one region.")}
+ </p>
+ )}
+ <div className="mt-5 space-y-3">
+ {draft.modules.map((module, moduleIndex) => {
+ const blankRegion = moduleHasIssue(moduleIndex, "blank_region");
+ const emptyRegion = moduleHasIssue(moduleIndex, "no_waypoints");
+ return (
+ <div
+ key={module.id}
+ className={`rounded-2xl border bg-[var(--background)] p-3.5 ${
+ blankRegion || emptyRegion
+ ? "border-red-500/45"
+ : "border-[var(--border)]"
+ }`}
+ >
+ <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`,
+ )}
+ aria-invalid={blankRegion}
+ 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)] aria-[invalid=true]:border-red-500/50"
+ />
+ <OrderButtons
+ index={moduleIndex}
+ count={draft.modules.length}
+ upLabel={tr(
+ `将区域「${module.name || moduleIndex + 1}」上移`,
+ `Move region “${module.name || moduleIndex + 1}” up`,
+ )}
+ downLabel={tr(
+ `将区域「${module.name || moduleIndex + 1}」下移`,
+ `Move region “${module.name || moduleIndex + 1}” down`,
+ )}
+ onMove={(to) =>
+ onChange(moveRouteModule(draft, moduleIndex, to))
+ }
+ />
+ <button
+ type="button"
+ onClick={() => removeModule(moduleIndex)}
+ disabled={draft.modules.length === 1}
+ aria-label={tr(
+ `删除区域「${module.name || moduleIndex + 1}」`,
+ `Remove region “${module.name || moduleIndex + 1}”`,
+ )}
+ 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>
+ {blankRegion && (
+ <p className="ml-8 mt-1 text-[11px] text-red-600">
+ {tr("区域名称不能为空。", "Region name cannot be blank.")}
+ </p>
+ )}
+ <div className="mt-2 space-y-1.5 sm:pl-8">
+ {module.knowledge_points.map((point, pointIndex) => {
+ const blankWaypoint = waypointHasIssue(
+ moduleIndex,
+ pointIndex,
+ );
+ return (
+ <div
+ key={point.id}
+ className="flex flex-wrap items-center gap-1.5 sm:flex-nowrap sm:gap-2"
+ >
+ <span className="h-2 w-2 shrink-0 rounded-full border-2 border-[var(--primary)]/60" />
+ <input
+ aria-label={tr(
+ `区域 ${moduleIndex + 1} 的第 ${pointIndex + 1} 个关卡名称`,
+ `Waypoint ${pointIndex + 1} name in region ${moduleIndex + 1}`,
+ )}
+ aria-invalid={blankWaypoint}
+ 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-[12rem] flex-1 rounded-lg border border-transparent bg-transparent px-2 text-xs outline-none hover:border-[var(--border)] focus:border-[var(--ring)] aria-[invalid=true]:border-red-500/50"
+ />
+ <select
+ aria-label={tr(
+ `关卡「${point.name || pointIndex + 1}」类型`,
+ `Type for waypoint “${point.name || pointIndex + 1}”`,
+ )}
+ 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>
+ <OrderButtons
+ index={pointIndex}
+ count={module.knowledge_points.length}
+ upLabel={tr(
+ `将关卡「${point.name || pointIndex + 1}」上移`,
+ `Move waypoint “${point.name || pointIndex + 1}” up`,
+ )}
+ downLabel={tr(
+ `将关卡「${point.name || pointIndex + 1}」下移`,
+ `Move waypoint “${point.name || pointIndex + 1}” down`,
+ )}
+ onMove={(to) =>
+ onChange(
+ moveRouteWaypoint(
+ draft,
+ moduleIndex,
+ pointIndex,
+ to,
+ ),
+ )
+ }
+ />
+ <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(
+ `删除关卡「${point.name || pointIndex + 1}」`,
+ `Remove waypoint “${point.name || pointIndex + 1}”`,
+ )}
+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:text-red-600 disabled:opacity-25"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ {blankWaypoint && (
+ <p className="w-full pl-4 text-[11px] text-red-600">
+ {tr(
+ "关卡名称不能为空。",
+ "Waypoint name cannot be blank.",
+ )}
+ </p>
+ )}
+ </div>
+ );
+ })}
+ {emptyRegion && (
+ <p role="alert" className="text-[11px] text-red-600">
+ {tr(
+ "每个区域至少需要一个关卡。",
+ "Every region needs at least one waypoint.",
+ )}
+ </p>
+ )}
+ <button
+ type="button"
+ onClick={() =>
+ updateModule(moduleIndex, {
+ ...module,
+ knowledge_points: [
+ ...module.knowledge_points,
+ {
+ id: draftId("waypoint"),
+ 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>
+ );
+}
+
+function OrderButtons({
+ index,
+ count,
+ upLabel,
+ downLabel,
+ onMove,
+}: {
+ index: number;
+ count: number;
+ upLabel: string;
+ downLabel: string;
+ onMove: (index: number) => void;
+}) {
+ return (
+ <span className="inline-flex shrink-0 rounded-lg border border-[var(--border)] bg-[var(--card)]">
+ <button
+ type="button"
+ onClick={() => onMove(index - 1)}
+ disabled={index === 0}
+ aria-label={upLabel}
+ className="p-1.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-25"
+ >
+ <ArrowUp className="h-3 w-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onMove(index + 1)}
+ disabled={index === count - 1}
+ aria-label={downLabel}
+ className="border-l border-[var(--border)] p-1.5 text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-25"
+ >
+ <ArrowDown className="h-3 w-3" />
+ </button>
+ </span>
+ );
+}
diff --git a/web/components/space/learning/TopicAtlas.tsx b/web/components/space/learning/TopicAtlas.tsx
index 3eb022d96..8511dbfa9 100644
--- a/web/components/space/learning/TopicAtlas.tsx
+++ b/web/components/space/learning/TopicAtlas.tsx
@@ -1,10 +1,18 @@
"use client";
-import { AlertCircle, Compass, Plus, RefreshCw, Sparkles } from "lucide-react";
+import Link from "next/link";
+import {
+ AlertCircle,
+ ArrowRight,
+ Compass,
+ Plus,
+ RefreshCw,
+ Sparkles,
+} from "lucide-react";
import type { MasteryTopic } from "@/lib/learning-api";
-import type { Translate } from "./format";
+import { topicDisplayName, type Translate } from "./format";
import { TopicMapCard } from "./TopicMapCard";
export function TopicAtlas({
@@ -19,7 +27,7 @@ export function TopicAtlas({
loading: boolean;
error: string | null;
tr: Translate;
- onCreate: () => void;
+ onCreate: (trigger: HTMLButtonElement) => void;
onRetry: () => void;
}) {
const activeTopics = topics.filter((topic) => topic.metadata.status === "active");
@@ -27,6 +35,10 @@ export function TopicAtlas({
(count, topic) => count + topic.reviews.filter((review) => review.due).length,
0,
);
+ const dueTopics = activeTopics.filter((topic) =>
+ topic.reviews.some((review) => review.due),
+ );
+ const firstDueTopic = dueTopics[0];
return (
<main className="mastery-shell h-full overflow-y-auto [scrollbar-gutter:stable]">
@@ -49,7 +61,7 @@ export function TopicAtlas({
</div>
<button
type="button"
- onClick={onCreate}
+ onClick={(event) => onCreate(event.currentTarget)}
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" />
@@ -58,13 +70,16 @@ export function TopicAtlas({
</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)]">
+ <section className="mt-8 flex flex-col gap-3 rounded-2xl border border-amber-700/20 bg-amber-500/[0.07] px-4 py-3.5 text-sm text-[var(--foreground)] sm:flex-row sm:items-center">
<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="min-w-0 flex-1">
<div className="font-medium">
- {tr(`${dueCount} 个记忆信标已亮起`, `${dueCount} review beacons are glowing`)}
+ {tr(
+ `${dueCount} 个记忆信标已亮起,分布在 ${dueTopics.length} 个主题中`,
+ `${dueCount} review beacons are glowing across ${dueTopics.length} ${dueTopics.length === 1 ? "topic" : "topics"}`,
+ )}
</div>
<div className="mt-0.5 text-xs text-[var(--muted-foreground)]">
{tr(
@@ -73,6 +88,15 @@ export function TopicAtlas({
)}
</div>
</div>
+ {firstDueTopic && (
+ <Link
+ href={`/space/learning/${encodeURIComponent(firstDueTopic.path_id)}`}
+ className="inline-flex h-9 shrink-0 items-center justify-center gap-1.5 rounded-xl bg-amber-700 px-3.5 text-xs font-semibold text-white transition hover:-translate-y-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-600 focus-visible:ring-offset-2 dark:bg-amber-300 dark:text-amber-950"
+ >
+ {tr("开始复习", "Start review")}: {topicDisplayName(firstDueTopic, tr)}
+ <ArrowRight className="h-3.5 w-3.5" />
+ </Link>
+ )}
</section>
)}
@@ -143,7 +167,7 @@ export function TopicAtlas({
</p>
<button
type="button"
- onClick={onCreate}
+ onClick={(event) => onCreate(event.currentTarget)}
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" />
diff --git a/web/components/space/learning/TopicWizardSteps.tsx b/web/components/space/learning/TopicWizardSteps.tsx
new file mode 100644
index 000000000..e56815ed8
--- /dev/null
+++ b/web/components/space/learning/TopicWizardSteps.tsx
@@ -0,0 +1,250 @@
+"use client";
+
+import {
+ AlertCircle,
+ BookOpen,
+ Check,
+ Database,
+ Loader2,
+ Notebook,
+ Target,
+} from "lucide-react";
+
+import type {
+ SourceCandidate,
+ SourceLibrary,
+} from "@/hooks/useTopicSourceLibrary";
+
+import type { Translate } from "./format";
+
+const EMOJIS = ["🧭", "🏔️", "🌿", "🔭", "🧪", "🧠", "📐", "🌌"];
+
+export 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
+ data-modal-initial-focus
+ 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}
+ aria-label={tr(
+ `选择地图徽记 ${item}`,
+ `Choose map emblem ${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>
+ );
+}
+
+export 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")}
+ empty={tr("书架里还没有可用内容", "No books are available yet")}
+ items={library.books}
+ selected={selected}
+ onToggle={onToggle}
+ tr={tr}
+ />
+ <SourceSection
+ icon={Notebook}
+ title={tr("笔记本", "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}
+ disabled={!item.available}
+ className={`flex min-h-16 items-center gap-3 rounded-xl border p-3 text-left transition disabled:cursor-not-allowed disabled:opacity-55 ${
+ 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>
+ );
+}
diff --git a/web/components/space/learning/format.ts b/web/components/space/learning/format.ts
index d2de9e4ad..f3722cf47 100644
--- a/web/components/space/learning/format.ts
+++ b/web/components/space/learning/format.ts
@@ -2,6 +2,18 @@
export type Translate = (cn: string, en: string) => string;
+const KNOWLEDGE_TYPE_LABELS: Record<string, [string, string]> = {
+ concept: ["概念", "Concept"],
+ memory: ["记忆", "Memory"],
+ procedure: ["过程", "Procedure"],
+ design: ["设计", "Design"],
+};
+
+export function knowledgeTypeLabel(type: string, tr: Translate): string {
+ const label = KNOWLEDGE_TYPE_LABELS[type];
+ return label ? tr(label[0], label[1]) : type;
+}
+
/**
* Older paths did not require a human-readable title and sometimes stored the
* generated path id as the name. Keep a short trace suffix without exposing a
diff --git a/web/components/space/learning/mastery-theme.css b/web/components/space/learning/mastery-theme.css
index 1afd993c6..d217aabe0 100644
--- a/web/components/space/learning/mastery-theme.css
+++ b/web/components/space/learning/mastery-theme.css
@@ -63,19 +63,20 @@
box-shadow: 0 22px 55px rgba(66, 47, 29, 0.16);
}
-.mastery-waypoint {
+.mastery-waypoint-icon {
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:hover .mastery-waypoint-icon,
+.mastery-waypoint:focus-visible .mastery-waypoint-icon {
+ transform: scale(1.08);
+ box-shadow: 0 0 0 3px var(--mastery-paper-raised), 0 0 0 5px var(--mastery-route);
}
-.mastery-waypoint[data-current="true"] {
+.mastery-waypoint[data-current="true"] .mastery-waypoint-icon {
animation: mastery-pulse 2.4s ease-in-out infinite;
}
@@ -130,15 +131,15 @@
@media (prefers-reduced-motion: reduce) {
.mastery-map-card,
- .mastery-waypoint,
+ .mastery-waypoint-icon,
.mastery-campfire {
animation: none !important;
transition-duration: 0.01ms !important;
}
.mastery-map-card:hover,
- .mastery-waypoint:hover,
- .mastery-waypoint:focus-visible {
+ .mastery-waypoint:hover .mastery-waypoint-icon,
+ .mastery-waypoint:focus-visible .mastery-waypoint-icon {
transform: none;
}
}
diff --git a/web/components/space/learning/route-draft.ts b/web/components/space/learning/route-draft.ts
new file mode 100644
index 000000000..2e2156948
--- /dev/null
+++ b/web/components/space/learning/route-draft.ts
@@ -0,0 +1,91 @@
+import type { ModuleInit, TopicDraft } from "@/lib/learning-api";
+
+export type RouteDraftIssue =
+ | { code: "no_regions" }
+ | { code: "blank_region"; moduleIndex: number }
+ | { code: "no_waypoints"; moduleIndex: number }
+ | {
+ code: "blank_waypoint";
+ moduleIndex: number;
+ waypointIndex: number;
+ };
+
+function move<T>(items: T[], from: number, to: number): T[] {
+ if (
+ from === to ||
+ from < 0 ||
+ to < 0 ||
+ from >= items.length ||
+ to >= items.length
+ ) {
+ return items;
+ }
+ const next = [...items];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+}
+
+/** Keep positional fields coherent while stable entity ids travel with rows. */
+export function normalizeRouteModules(modules: ModuleInit[]): ModuleInit[] {
+ return modules.map((module, order) => ({
+ ...module,
+ order,
+ knowledge_points: module.knowledge_points.map((point) => ({
+ ...point,
+ module_id: module.id,
+ })),
+ }));
+}
+
+export function moveRouteModule(
+ draft: TopicDraft,
+ from: number,
+ to: number,
+): TopicDraft {
+ return {
+ ...draft,
+ modules: normalizeRouteModules(move(draft.modules, from, to)),
+ };
+}
+
+export function moveRouteWaypoint(
+ draft: TopicDraft,
+ moduleIndex: number,
+ from: number,
+ to: number,
+): TopicDraft {
+ const currentModule = draft.modules[moduleIndex];
+ if (!currentModule) return draft;
+ const modules = [...draft.modules];
+ modules[moduleIndex] = {
+ ...currentModule,
+ knowledge_points: move(currentModule.knowledge_points, from, to),
+ };
+ return { ...draft, modules: normalizeRouteModules(modules) };
+}
+
+export function routeDraftIssues(draft: TopicDraft): RouteDraftIssue[] {
+ if (draft.modules.length === 0) return [{ code: "no_regions" }];
+ const issues: RouteDraftIssue[] = [];
+ draft.modules.forEach((module, moduleIndex) => {
+ if (!module.name.trim()) issues.push({ code: "blank_region", moduleIndex });
+ if (module.knowledge_points.length === 0) {
+ issues.push({ code: "no_waypoints", moduleIndex });
+ }
+ module.knowledge_points.forEach((point, waypointIndex) => {
+ if (!point.name.trim()) {
+ issues.push({
+ code: "blank_waypoint",
+ moduleIndex,
+ waypointIndex,
+ });
+ }
+ });
+ });
+ return issues;
+}
+
+export function isRouteDraftValid(draft: TopicDraft): boolean {
+ return routeDraftIssues(draft).length === 0;
+}
diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsx
index e9bc3293f..33cfd876a 100644
--- a/web/context/AppShellContext.tsx
+++ b/web/context/AppShellContext.tsx
@@ -53,6 +53,7 @@ interface AppShellContextValue {
theme: Theme;
setTheme: (theme: Theme) => void;
language: AppLanguage;
+ languageReady: boolean;
setLanguage: (language: AppLanguage) => void;
activeSessionId: string | null;
setActiveSessionId: (sessionId: string | null) => void;
@@ -74,6 +75,7 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
});
// Always start with "en" to match SSR; hydrate from localStorage after mount
const [language, setLanguageState] = useState<AppLanguage>("en");
+ const [languageReady, setLanguageReady] = useState(false);
const [activeSessionId, setActiveSessionIdState] = useState<string | null>(
() => readStoredActiveSessionId(),
);
@@ -90,8 +92,6 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
// Hydrate client-only preferences after SSR-safe first render.
- // eslint-disable-next-line react-hooks/set-state-in-effect
- setLanguageState(readStoredLanguage());
setSidebarCollapsedState(readStoredSidebarCollapsed());
setCodeBlockThemeState(readStoredCodeBlockTheme());
setCodeBlockShowLineNumbersState(readStoredCodeBlockShowLineNumbers());
@@ -109,9 +109,21 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
// reader-facing output language are stored together and are gated by the
// same "has this browser chosen yet?" question, so splitting them into two
// bootstraps would only give them a chance to disagree.
- if (hasStoredLanguage()) return;
const controller = new AbortController();
+ let cancelled = false;
+ let fallbackTimer: ReturnType<typeof setTimeout> | undefined;
void (async () => {
+ if (hasStoredLanguage()) {
+ if (!cancelled) {
+ setLanguageState(readStoredLanguage());
+ setLanguageReady(true);
+ }
+ return;
+ }
+ fallbackTimer = setTimeout(() => {
+ controller.abort();
+ if (!cancelled) setLanguageReady(true);
+ }, 1_500);
try {
const response = await apiFetch(apiUrl("/api/v1/settings/ui"), {
signal: controller.signal,
@@ -135,12 +147,19 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
payload.language,
),
);
- setLanguageState(payload.language);
+ if (!cancelled) setLanguageState(payload.language);
} catch {
// Offline or unauthenticated: keep the local default.
+ } finally {
+ if (fallbackTimer) clearTimeout(fallbackTimer);
+ if (!cancelled) setLanguageReady(true);
}
})();
- return () => controller.abort();
+ return () => {
+ cancelled = true;
+ if (fallbackTimer) clearTimeout(fallbackTimer);
+ controller.abort();
+ };
}, []);
useEffect(() => {
@@ -241,6 +260,7 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
const setLanguage = useCallback((nextLanguage: AppLanguage) => {
writeStoredLanguage(nextLanguage);
setLanguageState(nextLanguage);
+ setLanguageReady(true);
}, []);
const setActiveSessionId = useCallback((sessionId: string | null) => {
@@ -274,6 +294,7 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
theme,
setTheme,
language,
+ languageReady,
setLanguage,
activeSessionId,
setActiveSessionId,
@@ -292,6 +313,7 @@ export function AppShellProvider({ children }: { children: React.ReactNode }) {
codeBlockTheme,
codeBlockWrapLongLines,
language,
+ languageReady,
setActiveSessionId,
setCodeBlockShowLineNumbers,
setCodeBlockTheme,
diff --git a/web/hooks/useModalDialog.ts b/web/hooks/useModalDialog.ts
new file mode 100644
index 000000000..abaf11820
--- /dev/null
+++ b/web/hooks/useModalDialog.ts
@@ -0,0 +1,86 @@
+"use client";
+
+import { useEffect, useRef, type RefObject } from "react";
+
+const FOCUSABLE = [
+ "button:not([disabled])",
+ "[href]",
+ "input:not([disabled])",
+ "select:not([disabled])",
+ "textarea:not([disabled])",
+ "[tabindex]:not([tabindex='-1'])",
+].join(",");
+
+/** Escape, focus trap, initial focus, and focus restoration for app dialogs. */
+export function useModalDialog(
+ onClose: () => void,
+ closeDisabled = false,
+ returnFocusRef?: RefObject<HTMLElement | null>,
+): RefObject<HTMLDivElement | null> {
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const closeRef = useRef(onClose);
+ const disabledRef = useRef(closeDisabled);
+
+ useEffect(() => {
+ closeRef.current = onClose;
+ }, [onClose]);
+
+ useEffect(() => {
+ disabledRef.current = closeDisabled;
+ }, [closeDisabled]);
+
+ useEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) return;
+ const previousFocus =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null;
+ const returnFocus = returnFocusRef?.current ?? previousFocus;
+ let disposed = false;
+ queueMicrotask(() => {
+ if (disposed) return;
+ const first =
+ dialog.querySelector<HTMLElement>("[data-modal-initial-focus]") ??
+ dialog.querySelector<HTMLElement>(FOCUSABLE);
+ (first ?? dialog).focus();
+ });
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ if (!disabledRef.current) {
+ event.preventDefault();
+ closeRef.current();
+ }
+ return;
+ }
+ if (event.key !== "Tab") return;
+ const focusable = Array.from(
+ dialog.querySelectorAll<HTMLElement>(FOCUSABLE),
+ ).filter((element) => element.offsetParent !== null);
+ if (focusable.length === 0) {
+ event.preventDefault();
+ dialog.focus();
+ return;
+ }
+ const first = focusable[0];
+ const last = focusable.at(-1) ?? first;
+ if (event.shiftKey && document.activeElement === first) {
+ event.preventDefault();
+ last.focus();
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault();
+ first.focus();
+ }
+ };
+
+ document.addEventListener("keydown", onKeyDown);
+ return () => {
+ disposed = true;
+ document.removeEventListener("keydown", onKeyDown);
+ if (returnFocus?.isConnected) returnFocus.focus();
+ };
+ }, [returnFocusRef]);
+
+ return dialogRef;
+}
diff --git a/web/hooks/useTopicSourceLibrary.ts b/web/hooks/useTopicSourceLibrary.ts
new file mode 100644
index 000000000..b30b26e83
--- /dev/null
+++ b/web/hooks/useTopicSourceLibrary.ts
@@ -0,0 +1,190 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+
+import { bookApi } from "@/lib/book-api";
+import { listKnowledgeBases } from "@/lib/knowledge-api";
+import type {
+ TopicSourceInput,
+ TopicSourceKind,
+} from "@/lib/learning-api";
+import { getNotebook, listNotebooks } from "@/lib/notebook-api";
+
+export type SourceCandidateKind = Exclude<
+ TopicSourceKind,
+ "goal" | "file" | "chat"
+>;
+
+export interface SourceCandidate {
+ key: string;
+ kind: SourceCandidateKind;
+ sourceId: string;
+ label: string;
+ detail: string;
+ available: boolean;
+}
+
+export interface SourceLibrary {
+ books: SourceCandidate[];
+ notebooks: SourceCandidate[];
+ knowledgeBases: SourceCandidate[];
+ failures: string[];
+}
+
+const EMPTY_LIBRARY: SourceLibrary = {
+ books: [],
+ notebooks: [],
+ knowledgeBases: [],
+ failures: [],
+};
+
+type Translate = (cn: string, en: string) => string;
+
+export function useTopicSourceLibrary(tr: Translate) {
+ const [library, setLibrary] = useState<SourceLibrary>(EMPTY_LIBRARY);
+ const [loading, setLoading] = useState(true);
+
+ 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,
+ });
+ setLoading(false);
+ });
+ return () => {
+ disposed = true;
+ };
+ }, [tr]);
+
+ const candidates = useMemo(
+ () => [...library.books, ...library.notebooks, ...library.knowledgeBases],
+ [library],
+ );
+ return { library, loading, candidates };
+}
+
+/** Resolve a selected source to bounded prompt context; failures stay visible. */
+export async function hydrateTopicSource(
+ 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 },
+ };
+ }
+}
diff --git a/web/i18n/I18nClientBridge.tsx b/web/i18n/I18nClientBridge.tsx
index e1dfb807e..bc6c2fbe5 100644
--- a/web/i18n/I18nClientBridge.tsx
+++ b/web/i18n/I18nClientBridge.tsx
@@ -4,7 +4,11 @@ import { useAppShell } from "@/context/AppShellContext";
import { I18nProvider } from "./I18nProvider";
export function I18nClientBridge({ children }: { children: React.ReactNode }) {
- const { language } = useAppShell();
+ const { language, languageReady } = useAppShell();
- return <I18nProvider language={language}>{children}</I18nProvider>;
+ return (
+ <I18nProvider language={language} enabled={languageReady}>
+ {children}
+ </I18nProvider>
+ );
}
diff --git a/web/i18n/I18nProvider.tsx b/web/i18n/I18nProvider.tsx
index bc5decd2f..c4d973df7 100644
--- a/web/i18n/I18nProvider.tsx
+++ b/web/i18n/I18nProvider.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import i18n from "i18next";
import {
@@ -21,26 +21,49 @@ initI18n();
export function I18nProvider({
language,
+ enabled = true,
children,
}: {
language: AppLanguage | string;
+ enabled?: boolean;
children: React.ReactNode;
}) {
+ const nextLang = normalizeLanguage(language);
+ const [readyLanguage, setReadyLanguage] = useState<AppLanguage | null>(
+ () =>
+ enabled &&
+ i18n.language === nextLang &&
+ i18n.hasResourceBundle(nextLang, "app")
+ ? nextLang
+ : null,
+ );
+
useEffect(() => {
let cancelled = false;
- const nextLang = normalizeLanguage(language);
- void ensureLanguage(nextLang).then(() => {
+ if (!enabled) return () => undefined;
+ void ensureLanguage(nextLang).then(async () => {
if (cancelled) return;
if (i18n.language !== nextLang) {
- i18n.changeLanguage(nextLang);
+ await i18n.changeLanguage(nextLang);
}
+ if (cancelled) return;
// Keep <html lang="..."> in sync for accessibility & Intl defaults.
document.documentElement.lang = nextLang;
+ setReadyLanguage(nextLang);
});
return () => {
cancelled = true;
};
- }, [language]);
+ }, [enabled, nextLang]);
+ if (!enabled || readyLanguage !== nextLang) {
+ return (
+ <div
+ aria-busy="true"
+ aria-hidden="true"
+ className="min-h-dvh bg-[var(--background)]"
+ />
+ );
+ }
return children;
}
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 5be55bd60..226850e7c 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -100,6 +100,8 @@ export interface NextStep {
reason: string;
/** The outstanding question's text, when `action` is `answer_pending`. */
pending_prompt: string;
+ /** Session that owns an outstanding question; empty for non-pending steps. */
+ session_id: string;
}
export interface MasteryMapResult {
@@ -387,6 +389,8 @@ export interface MasteryTopic {
export interface TopicDraft {
description: string;
modules: ModuleInit[];
+ /** Server-hydrated source states (for example KB retrieval availability). */
+ sources?: TopicSourceInput[];
}
export interface GenerateTopicInput {
@@ -412,6 +416,7 @@ export interface TopicSession {
last_message: string;
pinned: boolean;
archived: boolean;
+ has_pending_question: boolean;
}
async function masteryJson<T>(
diff --git a/web/lib/mastery-study-route.ts b/web/lib/mastery-study-route.ts
new file mode 100644
index 000000000..7e18f8da8
--- /dev/null
+++ b/web/lib/mastery-study-route.ts
@@ -0,0 +1,31 @@
+export interface MasteryDraftRouteGuard {
+ routeKey: string;
+ previousSessionId: string | null;
+}
+
+/**
+ * A draft route starts while UnifiedChatContext may still expose the session
+ * that was visible on the previous page. Only promote the URL after the
+ * backend has bound a different session to this draft.
+ */
+export function isMasteryDraftSessionReady({
+ guard,
+ routeKey,
+ sessionId,
+ masteryPathId,
+ pathId,
+}: {
+ guard: MasteryDraftRouteGuard | null;
+ routeKey: string;
+ sessionId: string | null;
+ masteryPathId: string | null;
+ pathId: string;
+}): boolean {
+ return Boolean(
+ guard &&
+ guard.routeKey === routeKey &&
+ sessionId &&
+ sessionId !== guard.previousSessionId &&
+ masteryPathId === pathId,
+ );
+}
diff --git a/web/tests/mastery-route-draft.test.ts b/web/tests/mastery-route-draft.test.ts
new file mode 100644
index 000000000..c51f4b5ab
--- /dev/null
+++ b/web/tests/mastery-route-draft.test.ts
@@ -0,0 +1,74 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import type { TopicDraft } from "../lib/learning-api";
+import {
+ isRouteDraftValid,
+ moveRouteModule,
+ moveRouteWaypoint,
+ routeDraftIssues,
+} from "../components/space/learning/route-draft";
+
+function draft(): TopicDraft {
+ return {
+ description: "A trail",
+ modules: [
+ {
+ id: "m1",
+ name: "First",
+ order: 0,
+ knowledge_points: [
+ { id: "kp1", name: "One", type: "concept", module_id: "m1" },
+ { id: "kp2", name: "Two", type: "procedure", module_id: "m1" },
+ ],
+ },
+ {
+ id: "m2",
+ name: "Second",
+ order: 1,
+ knowledge_points: [
+ { id: "kp3", name: "Three", type: "memory", module_id: "m2" },
+ ],
+ },
+ ],
+ };
+}
+
+test("route reorder carries stable ids while normalizing positional fields", () => {
+ const reorderedModules = moveRouteModule(draft(), 1, 0);
+ assert.deepEqual(
+ reorderedModules.modules.map((module) => [module.id, module.order]),
+ [
+ ["m2", 0],
+ ["m1", 1],
+ ],
+ );
+
+ const reorderedWaypoints = moveRouteWaypoint(draft(), 0, 1, 0);
+ assert.deepEqual(
+ reorderedWaypoints.modules[0].knowledge_points.map((point) => point.id),
+ ["kp2", "kp1"],
+ );
+ assert.ok(
+ reorderedWaypoints.modules[0].knowledge_points.every(
+ (point) => point.module_id === "m1",
+ ),
+ );
+});
+
+test("route validation catches every draft shape the API would reject", () => {
+ const invalid = draft();
+ invalid.modules[0].name = " ";
+ invalid.modules[0].knowledge_points[0].name = "";
+ invalid.modules[1].knowledge_points = [];
+
+ assert.equal(isRouteDraftValid(invalid), false);
+ assert.deepEqual(
+ routeDraftIssues(invalid).map((issue) => issue.code),
+ ["blank_region", "blank_waypoint", "no_waypoints"],
+ );
+ assert.equal(isRouteDraftValid(draft()), true);
+ assert.deepEqual(routeDraftIssues({ description: "", modules: [] }), [
+ { code: "no_regions" },
+ ]);
+});
diff --git a/web/tests/mastery-study-route.test.ts b/web/tests/mastery-study-route.test.ts
new file mode 100644
index 000000000..57ac88c42
--- /dev/null
+++ b/web/tests/mastery-study-route.test.ts
@@ -0,0 +1,51 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { isMasteryDraftSessionReady } from "../lib/mastery-study-route";
+
+const base = {
+ guard: {
+ routeKey: "topic-a:new",
+ previousSessionId: "session-old",
+ },
+ routeKey: "topic-a:new",
+ masteryPathId: "topic-a",
+ pathId: "topic-a",
+};
+
+test("a stale previous session cannot bounce a new-study route backwards", () => {
+ assert.equal(
+ isMasteryDraftSessionReady({ ...base, sessionId: "session-old" }),
+ false,
+ );
+});
+
+test("the backend-bound draft session is promoted into the route", () => {
+ assert.equal(
+ isMasteryDraftSessionReady({ ...base, sessionId: "session-new" }),
+ true,
+ );
+});
+
+test("a route or topic switch invalidates an older draft guard", () => {
+ assert.equal(
+ isMasteryDraftSessionReady({
+ ...base,
+ routeKey: "topic-b:new",
+ sessionId: "session-new",
+ }),
+ false,
+ );
+ assert.equal(
+ isMasteryDraftSessionReady({
+ ...base,
+ masteryPathId: "topic-b",
+ sessionId: "session-new",
+ }),
+ false,
+ );
+});
+
+test("an unbound draft stays on the sessionless study route", () => {
+ assert.equal(isMasteryDraftSessionReady({ ...base, sessionId: null }), false);
+});