DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: decouple mastery paths from chat sessions (#810)
Bingxi Zhao (Frank)a8e03347cbf1
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.pyindex 3da7ef46f..288361cdf 100644--- a/deeptutor/api/routers/unified_ws.py+++ b/deeptutor/api/routers/unified_ws.py@@ -18,7 +18,8 @@ Supported client message ``type`` values:brand-new turn. Replaces the trailing assistant message (if any) andreuses the session's stored capability/tools/preferences. Optional``overrides`` field accepts ``capability``, ``tools``, ``knowledge_bases``,- ``language``, ``config``, ``notebook_references``, ``history_references``.+ ``language``, ``config``, ``notebook_references``, ``history_references``,+ ``mastery_path_id``.Errors: ``regenerate_busy`` (another turn is running) and``nothing_to_regenerate`` (no prior user message).- ``check_active_turn`` — report whether the session has a live running turn;diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 169ca1282..f3c6f2f8e 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -194,6 +194,11 @@ def _string_list(value: Any) -> list[str]:return [item for item in value if isinstance(item, str) and item]+def _mastery_path_id(value: Any) -> str:+ """Normalize the optional session-to-mastery-path association."""+ return str(value or "").strip()++def _llm_selection_dict(value: Any) -> dict[str, str] | None:from deeptutor.services.model_selection import LLMSelection@@ -236,6 +241,9 @@ def _request_snapshot_metadata(snapshot["questionNotebookReferences"] = question_notebook_referencesif book_references:snapshot["bookReferences"] = book_references+ mastery_path_id = _mastery_path_id(payload.get("mastery_path_id"))+ if mastery_path_id:+ snapshot["masteryPathId"] = mastery_path_idif persona:snapshot["persona"] = personaif memory_references:@@ -708,6 +716,16 @@ class TurnRuntimeManager:}session = await self.store.ensure_session(payload.get("session_id"))preferences = session.get("preferences") or {}+ # A mastery path has a longer lifetime than any one conversation.+ # Persist the explicit association on the session, and restore it on+ # later turns whose frontend payload omits the field.+ mastery_path_explicit = "mastery_path_id" in payload+ mastery_path_id = _mastery_path_id(+ payload.get("mastery_path_id")+ if mastery_path_explicit+ else preferences.get("mastery_path_id")+ )+ payload = {**payload, "mastery_path_id": mastery_path_id}# Persona is a session-level preference (mirrors llm_selection): an# explicit ``persona`` key in the payload — including an empty string,# which means "Default" / no persona — wins and is persisted below; an@@ -819,6 +837,9 @@ class TurnRuntimeManager:if persona_explicit:# Persist explicit set AND explicit clear ("" = back to Default).preference_update["persona"] = persona_pref+ if mastery_path_explicit:+ # Like persona, an explicit empty string clears the association.+ preference_update["mastery_path_id"] = mastery_path_idawait self.store.update_session_preferences(session["id"], preference_update)turn = await self.store.create_turn(session["id"], capability=capability)execution = _TurnExecution(@@ -932,6 +953,11 @@ class TurnRuntimeManager:if overrides.get("llm_selection") is not Noneelse snapshot.get("llmSelection") or preferences.get("llm_selection"))+ mastery_path_id = _mastery_path_id(+ overrides.get("mastery_path_id")+ if "mastery_path_id" in overrides+ else snapshot.get("masteryPathId") or preferences.get("mastery_path_id")+ )payload: dict[str, Any] = {"session_id": session_id,@@ -956,6 +982,7 @@ class TurnRuntimeManager:if overrides.get("book_references") is not Noneelse snapshot.get("bookReferences") or []),+ "mastery_path_id": mastery_path_id,"config": config,}if llm_selection:@@ -1649,6 +1676,7 @@ class TurnRuntimeManager:"history_references": history_references,"question_notebook_references": question_notebook_references,"book_references": book_references,+ "mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),"book_context": book_context,"book_context_warnings": book_context_result.warnings,"memory_references": memory_references,diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex 29049f493..c8923ff07 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -177,6 +177,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages("persona": "socratic","memory_references": ["summary"],"book_references": [{"book_id": "book-1", "page_ids": ["page-1"]}],+ "mastery_path_id": "path-1","config": {},})@@ -210,6 +211,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(assert detail["messages"][0]["metadata"]["request_snapshot"]["bookReferences"] == [{"book_id": "book-1", "page_ids": ["page-1"]}]+ assert detail["messages"][0]["metadata"]["request_snapshot"]["masteryPathId"] == "path-1"# Chat capability now routes attached sources through the manifest +# ``read_source`` tool instead of inlining ``[Book Context]`` into the# user message. The raw user message stays raw; the book payload@@ -227,6 +229,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(assert captured["metadata"] and captured["metadata"]["book_references"] == [{"book_id": "book-1", "page_ids": ["page-1"]}]+ assert captured["metadata"]["mastery_path_id"] == "path-1"assert detail["messages"][1]["content"] == "Hello Frank"assert detail["preferences"] == {"capability": "chat",@@ -236,6 +239,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(# Explicit persona in the payload is persisted as a session-level# preference (survives reloads; later turns fall back to it)."persona": "socratic",+ "mastery_path_id": "path-1",}persisted_turn = await store.get_turn(turn["id"])diff --git a/tests/services/session/test_regenerate.py b/tests/services/session/test_regenerate.pyindex e45083e1c..ce3ed4c0a 100644--- a/tests/services/session/test_regenerate.py+++ b/tests/services/session/test_regenerate.py@@ -224,6 +224,19 @@ class TestRegenerateLastTurn:{"book_id": "book-1", "page_ids": ["page-1"]}]+ def test_replays_mastery_path_from_request_snapshot(self, store: SQLiteSessionStore) -> None:+ sid, _, _ = _seed_session(+ store,+ user_metadata={"request_snapshot": {"masteryPathId": "path-1"}},+ )+ runtime = TurnRuntimeManager(store=store)+ recorder = _FakeStartTurnRecorder()++ with patch.object(runtime, "start_turn", new=recorder):+ asyncio.run(runtime.regenerate_last_turn(sid))++ assert recorder.calls[0]["mastery_path_id"] == "path-1"+def test_user_tail_is_kept_and_no_delete(self, store: SQLiteSessionStore) -> None:sid, user_id, _ = _seed_session(store, assistant_content=None)runtime = TurnRuntimeManager(store=store)diff --git a/web/app/(utility)/space/learning/page.tsx b/web/app/(utility)/space/learning/page.tsxindex 7821371d4..543f2f6f2 100644--- a/web/app/(utility)/space/learning/page.tsx+++ b/web/app/(utility)/space/learning/page.tsx@@ -23,6 +23,7 @@ import {type MasteryMapResult,type ObjectiveStatus,} from "@/lib/learning-api";+import { newMasteryPathChatUrl } from "@/lib/mastery-path-navigation";/*** Mastery Path dashboard — the persistent "screen" of the mastery experience.@@ -31,8 +32,8 @@ import {* Chat); this page is the map of where the learner stands. It reads the* gate-accurate snapshot from ``/progress/{id}/map`` (per-type status computed* by ``deeptutor.learning.policy``) so the colours here agree with the gate the- * tutor enforces. A path is keyed by its chat session, so "Continue" reopens- * that session in mastery mode.+ * tutor enforces. A path and a conversation have independent identities, so+ * "Continue" starts a focused chat while retaining the selected path state.*/export default function MasteryPathPage() {const { i18n } = useTranslation();@@ -206,7 +207,7 @@ export default function MasteryPathPage() {zh={!!zh}tr={tr}onContinue={() =>- selected && router.push(`/home/${encodeURIComponent(selected)}`)+ selected && router.push(newMasteryPathChatUrl(selected))}onRedo={() => selected && handleRedo(selected)}onDelete={() => selected && handleDelete(selected)}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex f57a2db27..a25bb55f4 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -353,6 +353,7 @@ export default function ChatPage() {setCapability,setKBs,setLLMSelection,+ setMasteryPathId,setPersonaSelection,sendMessage,cancelStreamingTurn,@@ -1120,12 +1121,14 @@ export default function ChatPage() {setCapabilityConfigs(loadCapabilityPlaygroundConfigs());}, []);- /* URL query params (capability, tool) */+ /* URL query params (capability, tool, persistent mastery path) */useEffect(() => {if (typeof window === "undefined") return;const p = new URLSearchParams(window.location.search);const qc = p.get("capability");const qt = p.getAll("tool");+ const masteryPathId = p.get("mastery_path_id")?.trim();+ if (masteryPathId) setMasteryPathId(masteryPathId);if (qc !== null) handleSelectCapability(qc || "");else if (qt.length) {const valid = qt.filter((t): t is ToolName =>diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 263cbd247..e89450aa2 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -90,6 +90,8 @@ export interface ChatState {activeCapability: string | null;knowledgeBases: string[];llmSelection: LLMSelection | null;+ /** Persistent mastery state associated with this conversation. */+ masteryPathId: string | null;/** Session-level persona preference; "" = Default (no persona). Applies* to every following message until changed (persisted on the session). */personaSelection: string;@@ -140,6 +142,7 @@ export interface MessageRequestSnapshot {historyReferences?: HistoryReferencePayload;questionNotebookReferences?: QuestionNotebookReferencePayload;bookReferences?: BookReferencePayload[];+ masteryPathId?: string;persona?: string;memoryReferences?: MemoryReferencePayload;llmSelection?: LLMSelection | null;@@ -188,6 +191,7 @@ interface SessionSnapshot {capability?: string | null;knowledgeBases?: string[];llmSelection?: LLMSelection | null;+ masteryPathId?: string | null;personaSelection?: string;language?: string;selectedBranches?: Record<string, number>;@@ -198,6 +202,7 @@ type Action =| { type: "SET_CAPABILITY"; cap: string | null }| { type: "SET_KB"; kbs: string[] }| { type: "SET_LLM_SELECTION"; selection: LLMSelection | null }+ | { type: "SET_MASTERY_PATH_ID"; masteryPathId: string | null }| { type: "SET_PERSONA_SELECTION"; persona: string }| { type: "SET_LANGUAGE"; lang: string }| {@@ -263,6 +268,7 @@ function createSessionEntry(activeCapability: null,knowledgeBases: [],llmSelection: null,+ masteryPathId: null,personaSelection: "",messages: [],isStreaming: false,@@ -332,6 +338,11 @@ function reducer(state: ProviderState, action: Action): ProviderState {...session,llmSelection: action.selection,}));+ case "SET_MASTERY_PATH_ID":+ return updateSelectedSession(state, (session) => ({+ ...session,+ masteryPathId: action.masteryPathId,+ }));case "SET_PERSONA_SELECTION":return updateSelectedSession(state, (session) => ({...session,@@ -608,6 +619,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {action.llmSelection !== undefined? action.llmSelection: existing.llmSelection,+ masteryPathId:+ action.masteryPathId !== undefined+ ? action.masteryPathId+ : existing.masteryPathId,personaSelection:action.personaSelection !== undefined? action.personaSelection@@ -788,6 +803,7 @@ interface ChatContextValue {setCapability: (cap: string | null) => void;setKBs: (kbs: string[]) => void;setLLMSelection: (selection: LLMSelection | null) => void;+ setMasteryPathId: (masteryPathId: string | null) => void;setPersonaSelection: (persona: string) => void;setLanguage: (lang: string) => void;sendMessage: (@@ -967,6 +983,10 @@ function hydrateRequestSnapshot(const memoryReferences = asMemoryReferences(stored.memoryReferences);const bookReferences = normalizeBookReferences(stored.bookReferences);const llmSelection = asLLMSelection(stored.llmSelection);+ const masteryPathId =+ typeof (stored.masteryPathId ?? stored.mastery_path_id) === "string"+ ? String(stored.masteryPathId ?? stored.mastery_path_id).trim()+ : "";if (config && Object.keys(config).length) snapshot.config = config;if (notebookReferences.length)@@ -979,6 +999,7 @@ function hydrateRequestSnapshot(if (persona) snapshot.persona = persona;if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;if (llmSelection) snapshot.llmSelection = llmSelection;+ if (masteryPathId) snapshot.masteryPathId = masteryPathId;return snapshot;}@@ -1358,6 +1379,10 @@ export function UnifiedChatProvider({? session.preferences.knowledge_bases: [],llmSelection: asLLMSelection(session.preferences?.llm_selection),+ masteryPathId:+ typeof session.preferences?.mastery_path_id === "string"+ ? session.preferences.mastery_path_id+ : null,personaSelection:typeof session.preferences?.persona === "string"? session.preferences.persona@@ -1511,6 +1536,8 @@ export function UnifiedChatProvider({replaySnapshot && "llmSelection" in replaySnapshot? (replaySnapshot.llmSelection ?? null): session.llmSelection;+ const effectiveMasteryPathId =+ replaySnapshot?.masteryPathId ?? session.masteryPathId;const effectiveLanguage =replaySnapshot?.language ?? readStoredResponseLanguage();// Persona resolution: replay snapshot wins; then an explicit per-call@@ -1566,6 +1593,9 @@ export function UnifiedChatProvider({...(effectiveBookReferences?.length? { bookReferences: effectiveBookReferences }: {}),+ ...(effectiveMasteryPathId+ ? { masteryPathId: effectiveMasteryPathId }+ : {}),...(effectivePersona ? { persona: effectivePersona } : {}),...(effectiveMemoryReferences?.length? { memoryReferences: [...effectiveMemoryReferences] }@@ -1634,6 +1664,9 @@ export function UnifiedChatProvider({...(effectiveBookReferences?.length? { book_references: effectiveBookReferences }: {}),+ ...(effectiveMasteryPathId+ ? { mastery_path_id: effectiveMasteryPathId }+ : {}),// Always sent (possibly ""): an explicit key is the backend's signal// to persist the value into session.preferences — "" clears back to// Default. Omitting the key would make the backend fall back to the@@ -1760,6 +1793,7 @@ export function UnifiedChatProvider({activeCapability: current.activeCapability,knowledgeBases: current.knowledgeBases,llmSelection: current.llmSelection,+ masteryPathId: current.masteryPathId,personaSelection: current.personaSelection,messages: current.messages,isStreaming: current.isStreaming,@@ -1799,6 +1833,11 @@ export function UnifiedChatProvider({dispatch({ type: "SET_LLM_SELECTION", selection });}, []);+ const setMasteryPathId = useCallback((masteryPathId: string | null) => {+ const normalized = masteryPathId?.trim() || null;+ dispatch({ type: "SET_MASTERY_PATH_ID", masteryPathId: normalized });+ }, []);+const setPersonaSelection = useCallback((persona: string) => {dispatch({ type: "SET_PERSONA_SELECTION", persona });}, []);@@ -1948,6 +1987,7 @@ export function UnifiedChatProvider({setCapability,setKBs,setLLMSelection,+ setMasteryPathId,setPersonaSelection,setLanguage,sendMessage,@@ -1971,6 +2011,7 @@ export function UnifiedChatProvider({setCapability,setKBs,setLLMSelection,+ setMasteryPathId,setPersonaSelection,setLanguage,sendMessage,diff --git a/web/lib/mastery-path-navigation.ts b/web/lib/mastery-path-navigation.tsnew file mode 100644index 000000000..5cfd7ab2c--- /dev/null+++ b/web/lib/mastery-path-navigation.ts@@ -0,0 +1,8 @@+/** Build a fresh chat URL associated with existing persistent mastery state. */+export function newMasteryPathChatUrl(masteryPathId: string): string {+ const params = new URLSearchParams({+ capability: "mastery_path",+ mastery_path_id: masteryPathId,+ });+ return `/home?${params.toString()}`;+}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex dd464f82a..724a5d5ea 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -27,6 +27,22 @@ export interface SessionMessage {parent_message_id?: number | null;}+export interface SessionPreferences {+ capability?: string;+ tools?: string[];+ knowledge_bases?: string[];+ language?: string;+ llm_selection?: LLMSelection | null;+ /** Persistent mastery state associated with this conversation. */+ mastery_path_id?: string;+ /** Session-level persona preference; "" / absent = Default (no persona). */+ persona?: string;+ /** Edit-branching: maps a parent_message_id → the child id currently+ * shown at that branch point. Missing keys default to the latest+ * sibling (most recently created child). */+ selected_branches?: Record<string, number>;+}+export interface SessionSummary {id: string;session_id: string;@@ -43,19 +59,7 @@ export interface SessionSummary {| "cancelled"| "rejected";active_turn_id?: string;- preferences?: {- capability?: string;- tools?: string[];- knowledge_bases?: string[];- language?: string;- llm_selection?: LLMSelection | null;- /** Session-level persona preference; "" / absent = Default (no persona). */- persona?: string;- /** Edit-branching: maps a parent_message_id → the child id currently- * shown at that branch point. Missing keys default to the latest- * sibling (most recently created child). */- selected_branches?: Record<string, number>;- };+ preferences?: SessionPreferences;}export interface ActiveTurnSummary {@@ -87,19 +91,7 @@ export interface SessionDetail {active_turn_id?: string;compressed_summary?: string;summary_up_to_msg_id?: number;- preferences?: {- capability?: string;- tools?: string[];- knowledge_bases?: string[];- language?: string;- llm_selection?: LLMSelection | null;- /** Session-level persona preference; "" / absent = Default (no persona). */- persona?: string;- /** Edit-branching: maps a parent_message_id → the child id currently- * shown at that branch point. Missing keys default to the latest- * sibling (most recently created child). */- selected_branches?: Record<string, number>;- };+ preferences?: SessionPreferences;messages: SessionMessage[];active_turns?: ActiveTurnSummary[];}diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 681a3b353..7652de9d4 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -75,6 +75,8 @@ export interface StartTurnMessage {book_id: string;page_ids: string[];}[];+ /** Persistent mastery state to use independently of this chat session. */+ mastery_path_id?: string;persona?: string;llm_selection?: LLMSelection | null;/** Edit-branching: when present (even as ``null``) the new user messagediff --git a/web/tests/mastery-path-navigation.test.ts b/web/tests/mastery-path-navigation.test.tsnew file mode 100644index 000000000..93e2bfbc2--- /dev/null+++ b/web/tests/mastery-path-navigation.test.ts@@ -0,0 +1,11 @@+import test from "node:test";+import assert from "node:assert/strict";++import { newMasteryPathChatUrl } from "../lib/mastery-path-navigation";++test("continuing a mastery path opens a fresh associated chat", () => {+ assert.equal(+ newMasteryPathChatUrl("calculus/path 1"),+ "/home?capability=mastery_path&mastery_path_id=calculus%2Fpath+1",+ );+});