Block 7.5: Practice quiz phase, auto-advance fix, cancel streaming safety

- Add PRACTICE_QUIZ stage between Feynman Check and Error Diagnosis
- Generate 5-10 practice questions per module, record attempts but don't gate mastery
- Fix auto-advance race: move stagesRef updates outside React setState callbacks
- Fix stale handleStreamEvent closure via ref pattern
- Fix PLAN stage permanent deadlock when modules not initialized
- Clear error state unconditionally on new stage_start
- Add cancelStreamingTurn to sidebar and chat page for proper cleanup
- Fix cancelStreamingTurn to handle missing turnId gracefully
- Keep empty page_ids refs for whole-book resolution in guided learning
This commit is contained in:
unknown
2026-05-16 11:33:45 +08:00
parent 6f3070f8d3
commit 80ccbe9dfb
9 changed files with 167 additions and 34 deletions

View File

@@ -74,9 +74,6 @@ def normalize_book_references(value: Any) -> list[NormalizedBookReference]:
seen_pages.add(page_id)
page_ids.append(page_id)
if not page_ids:
continue
if book_id in seen_books:
existing = next((ref for ref in refs if ref.book_id == book_id), None)
if existing is not None:

View File

@@ -39,6 +39,8 @@ from deeptutor.learning.prompts import (
MODULE_TEST_USER,
PLAN_SYSTEM,
PLAN_USER,
PRACTICE_QUIZ_SYSTEM,
PRACTICE_QUIZ_USER,
PRACTICE_SYSTEM,
PRACTICE_USER,
PRETEST_SYSTEM,
@@ -61,6 +63,7 @@ class GuidedLearningCapability(BaseCapability):
"pretest",
"explain",
"feynman_check",
"practice_quiz",
"practice",
"error_diagnosis",
"module_test",
@@ -322,12 +325,16 @@ class GuidedLearningCapability(BaseCapability):
) -> None:
async with stream.stage("plan", source=self.manifest.name):
if not progress.modules:
await stream.content("请先在 /learning 页面初始化学习模块,然后再开始引导学习。", source=self.manifest.name)
await stream.error(
"模块未初始化,请先在 /learning 页面创建学习模块。",
await stream.content(
"请先在 /learning 页面初始化学习模块,然后再开始引导学习。"
"当前尚未创建学习模块,系统将跳过学习计划,进入下一阶段。",
source=self.manifest.name,
metadata={"turn_terminal": True, "reason": "no_modules"},
)
# Advance stage so the state machine does not get permanently
# stuck on PLAN when modules are not initialized. Downstream
# stages (PRETEST, EXPLAIN, …) gracefully handle empty
# knowledge-point lists via the "_current_kp_name" fallback.
self._service.advance_stage(progress, LearningStage.PRETEST)
return
response = await self._call_llm(PLAN_SYSTEM, PLAN_USER)
await stream.content(response)
@@ -383,7 +390,7 @@ class GuidedLearningCapability(BaseCapability):
self._after_knowledge_point(progress)
self._service.advance_stage(progress, LearningStage.PRETEST)
else:
self._service.advance_stage(progress, LearningStage.PRACTICE)
self._service.advance_stage(progress, LearningStage.PRACTICE_QUIZ)
return
response = await self._call_llm(
@@ -400,7 +407,7 @@ class GuidedLearningCapability(BaseCapability):
self._after_knowledge_point(progress)
self._service.advance_stage(progress, LearningStage.PRETEST)
else:
self._service.advance_stage(progress, LearningStage.PRACTICE)
self._service.advance_stage(progress, LearningStage.PRACTICE_QUIZ)
else:
await stream.content(f"反馈:{result.get('feedback', '请重新学习')}", source=self.manifest.name)
self._service.advance_stage(progress, LearningStage.EXPLAIN)
@@ -422,6 +429,72 @@ class GuidedLearningCapability(BaseCapability):
progress.current_kp_index += 1
progress.updated_at = time.time()
# ── §5 Practice Quiz ──────────────────────────────────────────────────
async def _run_practice_quiz(
self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus
) -> None:
"""Post-Feynman practice quiz — consolidates all knowledge points in the current module."""
async with stream.stage("practice_quiz", source=self.manifest.name):
kps = self._current_knowledge_points(progress)
if not kps:
self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)
return
kp_names = ", ".join(kp.name for kp in kps)
prefix = f"{progress.current_module_id}_pquiz" if progress.current_module_id else "pquiz"
response = await self._call_llm(
PRACTICE_QUIZ_SYSTEM,
PRACTICE_QUIZ_USER.format(knowledge_points=kp_names),
)
data = self._safe_json_parse(response, default={"questions": []})
book_id = self._resolve_book_id(context)
answers = self._extract_answers(data, prefix)
self._store.save_question_answers(book_id, answers)
self._inject_question_ids(data, prefix)
questions = data.get("questions", [])
qids = data.get("question_ids", [])
correct_count = 0
default_kp_id = kps[0].id if kps else ""
for i, q in enumerate(questions):
qid = qids[i] if i < len(qids) else f"{prefix}_{i}"
await stream.content(
json.dumps({"question": self._strip_answer(q), "question_id": qid}, ensure_ascii=False),
source=self.manifest.name,
)
user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)
stored = self._store.load_question_answers(book_id)
expected = stored.get(qid, "")
is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()
if is_correct:
correct_count += 1
self._service.record_quiz_attempt(
progress,
QuizAttempt(
question_id=qid,
knowledge_point_id=default_kp_id,
module_id=progress.current_module_id or "",
is_correct=is_correct,
user_answer=user_answer,
error_type=None if is_correct else ErrorType.APPLICATION_ERROR,
),
)
total = len(questions)
if total > 0:
pct = correct_count / total * 100
summary = f"练习测验完成!正确 {correct_count}/{total} 题({pct:.0f}%)。"
if pct >= 70:
summary += " 表现不错,继续加油!"
else:
summary += " 建议回顾相关知识点。"
await stream.content(summary, source=self.manifest.name)
self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)
# ── §5 Per-module loop ───────────────────────────────────────────────
async def _run_practice(
@@ -546,6 +619,7 @@ class GuidedLearningCapability(BaseCapability):
LearningStage.PRETEST: _run_pretest,
LearningStage.EXPLAIN: _run_explain,
LearningStage.FEYNMAN_CHECK: _run_feynman_check,
LearningStage.PRACTICE_QUIZ: _run_practice_quiz,
LearningStage.PRACTICE: _run_practice,
LearningStage.ERROR_DIAGNOSIS: _run_error_diagnosis,
LearningStage.MODULE_TEST: _run_module_test,

View File

@@ -62,6 +62,7 @@ class LearningStage(str, Enum):
PRETEST = "pretest"
EXPLAIN = "explain"
FEYNMAN_CHECK = "feynman_check"
PRACTICE_QUIZ = "practice_quiz"
PRACTICE = "practice"
ERROR_DIAGNOSIS = "error_diagnosis"
MODULE_TEST = "module_test"

View File

@@ -72,6 +72,18 @@ FEYNMAN_SYSTEM = """判断学生是否能用费曼技巧解释清楚概念。
FEYNMAN_USER = "检验对概念的费曼解释:{knowledge_point}"
# ── Practice Quiz ──────────────────────────────────────────────────────
PRACTICE_QUIZ_SYSTEM = """你是一个出题专家。请为以下知识点生成综合练习测验。
要求:
1. 生成 5-10 道题,覆盖所有列出的知识点
2. 题型多样(选择、填空、简答)
3. 难度适中,侧重理解和应用
4. 每道题附带正确答案和简要解析
返回 JSON:{"questions": [{"question": "...", "answer": "...", "explanation": "...", "knowledge_point": "..."}]}"""
PRACTICE_QUIZ_USER = "为以下知识点生成综合练习测验:{knowledge_points}"
# ── Practice ───────────────────────────────────────────────────────────
PRACTICE_SYSTEM = """生成3-5道练习题,难度递进(识记→理解→应用→分析)。

View File

@@ -117,6 +117,17 @@ def test_normalize_book_references_merges_and_filters() -> None:
]
def test_normalize_book_references_keeps_empty_page_ids() -> None:
"""Empty page_ids means 'whole book' — ref must be kept for book_id resolution."""
refs = normalize_book_references(
[{"book_id": "book-1", "page_ids": []}]
)
assert len(refs) == 1
assert refs[0].book_id == "book-1"
assert refs[0].page_ids == []
def test_build_book_context_serializes_readable_page_content() -> None:
result = build_book_context(
[{"book_id": "book-1", "page_ids": ["page-1"]}],

View File

@@ -224,10 +224,10 @@ const CAPABILITIES: CapabilityDef[] = [
label: "Visualize",
description: "Generate SVG, Chart.js, or Mermaid visualizations",
icon: BarChart3,
allowedTools: [],
defaultTools: [],
},
];
allowedTools: [],
defaultTools: [],
},
];
interface KnowledgeBase {
name: string;
@@ -1188,8 +1188,9 @@ export default function ChatPage() {
}, []);
const handleNewChat = useCallback(() => {
cancelStreamingTurn();
router.push("/chat");
}, [router]);
}, [cancelStreamingTurn, router]);
const handleDownloadMarkdown = useCallback(() => {
if (!state.messages.length) return;

View File

@@ -30,6 +30,7 @@ const STAGE_LABELS: Record<string, string> = {
pretest: "Pretest",
explain: "Explain",
feynman_check: "Feynman Check",
practice_quiz: "Practice Quiz",
practice: "Practice",
error_diagnosis: "Error Diagnosis",
module_test: "Module Test",
@@ -80,6 +81,10 @@ export default function LearningBookPage() {
const fetchProgressRef = useRef(fetchProgress);
fetchProgressRef.current = fetchProgress;
// Use a ref for handleStreamEvent so the WebSocket onmessage handler
// always calls the latest version instead of a stale closure.
const handleStreamEventRef = useRef<(evt: StreamEvent) => void>(() => {});
const connect = useCallback(() => {
const ws = new WebSocket(wsUrl("/api/v1/ws"));
wsRef.current = ws;
@@ -100,7 +105,7 @@ export default function LearningBookPage() {
ws.onmessage = (event) => {
try {
const evt: StreamEvent = JSON.parse(event.data);
handleStreamEvent(evt);
handleStreamEventRef.current(evt);
} catch { /* ignore parse errors */ }
};
@@ -121,42 +126,59 @@ export default function LearningBookPage() {
if (evt.type === "stage_start") {
currentStageRef.current = evt.stage;
setCurrentStage(evt.stage);
// Clear recoverable errors on new turn
if (activeTurnRetryRef.current) {
setError(null);
activeTurnRetryRef.current = false;
}
// Clear errors on new stage — previous turn's error should not block the next turn
errorRef.current = false;
setError(null);
activeTurnRetryRef.current = false;
setStages(prev => {
const updated = [...prev];
const idx = updated.findIndex(s => s.stage === evt.stage);
if (idx >= 0) {
updated[idx] = { ...updated[idx], status: "active" };
updated[idx] = { ...updated[idx], status: "active", content: "" };
} else {
updated.push({ stage: evt.stage, status: "active", content: "" });
}
stagesRef.current = updated;
return updated;
});
// Update ref OUTSIDE setStages callback so it is always synchronous.
// This prevents a race where `done` reads a stale stagesRef before
// React processes the batched setState.
{
const idx = stagesRef.current.findIndex(s => s.stage === evt.stage);
if (idx >= 0) {
stagesRef.current = [...stagesRef.current];
stagesRef.current[idx] = { ...stagesRef.current[idx], status: "active", content: "" };
} else {
stagesRef.current = [...stagesRef.current, { stage: evt.stage, status: "active", content: "" }];
}
}
} else if (evt.type === "content") {
setStages(prev => prev.map(s =>
s.stage === currentStageRef.current ? { ...s, content: s.content + evt.content } : s
));
} else if (evt.type === "result" || evt.type === "stage_end") {
const endedStage = currentStageRef.current;
// Update ref OUTSIDE setStages callback so it is synchronous and
// visible to the `done` handler that may run in the very next message.
if (endedStage) {
stagesRef.current = stagesRef.current.map(s =>
s.stage === endedStage ? { ...s, status: "completed" as const } : s
);
}
setStages(prev => {
const updated = prev.map(s =>
s.stage === currentStageRef.current ? { ...s, status: "completed" as const } : s
s.stage === endedStage ? { ...s, status: "completed" as const } : s
);
stagesRef.current = updated;
return updated;
});
const endedStage = currentStageRef.current;
currentStageRef.current = "";
setCurrentStage("");
if (["plan", "diagnostic_phase1", "diagnostic_phase2", "review", "module_test"].includes(endedStage)) {
if (["plan", "diagnostic_phase1", "diagnostic_phase2", "practice_quiz", "review", "module_test"].includes(endedStage)) {
fetchProgressRef.current();
}
} else if (evt.type === "done") {
// Auto-advance after turn completes, skip if terminal completed stage exists or any error occurred
// Auto-advance after turn completes.
// Skip if: terminal "completed" stage exists, any error stage exists, or errorRef is set.
const hasCompletedTerminal = stagesRef.current.some(s => s.stage === "completed" && s.status === "completed");
const hasError = errorRef.current || stagesRef.current.some(s => s.status === "error" || s.stage === "error");
if (!hasCompletedTerminal && !hasError && wsRef.current?.readyState === WebSocket.OPEN) {
@@ -191,16 +213,24 @@ export default function LearningBookPage() {
activeTurnRetryRef.current = true;
}
setToast(t("guidedLearning.stageFailed"));
const stageToError = currentStageRef.current;
if (stageToError) {
stagesRef.current = stagesRef.current.map(s =>
s.stage === stageToError ? { ...s, status: "error" as const } : s
);
}
setStages(prev => {
const updated = prev.map(s =>
s.stage === currentStageRef.current ? { ...s, status: "error" as const } : s
s.stage === stageToError ? { ...s, status: "error" as const } : s
);
stagesRef.current = updated;
return updated;
});
}
};
// Keep the ref always pointing at the latest handleStreamEvent
handleStreamEventRef.current = handleStreamEvent;
useEffect(() => {
if (!toast) return;
const timer = setTimeout(() => setToast(""), 3500);

View File

@@ -19,6 +19,7 @@ export default function WorkspaceSidebar() {
const router = useRouter();
const {
newSession,
cancelStreamingTurn,
selectedSessionId,
sessionStatuses,
sidebarRefreshToken,
@@ -68,6 +69,7 @@ export default function WorkspaceSidebar() {
.map(({ session }) => session);
const handleNewChat = () => {
cancelStreamingTurn();
newSession();
router.push("/chat");
};
@@ -105,11 +107,12 @@ export default function WorkspaceSidebar() {
prev.filter((session) => session.session_id !== sessionId),
);
if (selectedSessionId === sessionId) {
cancelStreamingTurn();
newSession();
router.push("/chat");
}
},
[newSession, router, selectedSessionId, t],
[cancelStreamingTurn, newSession, router, selectedSessionId, t],
);
return (

View File

@@ -1128,15 +1128,19 @@ export function UnifiedChatProvider({
const key = currentState.selectedKey;
if (!key) return;
const session = currentState.sessions[key];
const turnId = session?.activeTurnId;
if (!session || !turnId) return;
if (!session) return;
const turnId = session.activeTurnId;
const runner = runnersRef.current.get(key);
if (runner?.client.connected) {
runner.client.send({ type: "cancel_turn", turn_id: turnId });
if (turnId) {
runner.client.send({ type: "cancel_turn", turn_id: turnId });
}
runner.client.disconnect();
runnersRef.current.delete(key);
}
dispatch({ type: "STREAM_END", key, status: "cancelled" });
if (session.isStreaming) {
dispatch({ type: "STREAM_END", key, status: "cancelled" });
}
}, []);
const regenerateLastMessage = useCallback(() => {