Files
DeepTutor/web/components/learning/ModuleTree.tsx
Bingxi Zhao (Frank) e3a351a488 refactor(guided-learning): post-merge hardening of #500
Security/correctness:
- Stop leaking diagnostic answers: persist a _sanitize_diagnostic() snapshot
  (drops top-level answers + inline answer keys) into progress.diagnostic,
  which is returned verbatim by the /progress endpoints. Grading is unaffected
  (authoritative answers live in LearningStore).
- _safe_json_parse + generate_from_notebook now use the shared fence-stripping
  parse_json_response instead of bare json.loads, so the common fenced/lightly
  -malformed LLM output is recovered instead of silently dropped / 500'd.

Decoupling:
- unified_ws change_module: move module lookup + PRETEST reset into
  LearningService.switch_module(); router keeps only the WS ordering
  (module_changed before cancel) and no longer imports learning.models.
- unified_ws check_active_turn: use new public TurnRuntimeManager
  .has_live_execution() instead of reaching into _lock/_executions.
- redo endpoint: LearningStore.clear_questions() instead of poking _questions_path.
- remove unused StreamEventType.USER_INPUT enum; document the WS message types.

Stability:
- LearningStore: question read-modify-write (save_question_answers/_meta),
  delete(), and clear_questions() now hold _cas_lock — consistent concurrency
  model; _atomic_write_text cleans up its temp file on failure.

Cleanliness/clarity:
- router: shared _validate_book_id() (9 endpoints) + _parse_modules()
  (init/replace); _classify_error drops unused expected_answer param.
- guided_learning: hoist logging/RAGService imports + module logger; move tuning
  constants to class top; ContextVar declared after imports.
- storage: hoist json import (7 inline copies removed).
- pocketbase_store: move _VALID_ID/_validate_id below the import block.
- rename misleading mastered_pct -> avg_mastery_pct (service + web consumers).

Frontend:
- learning [bookId] page uses lib fetchProgress (apiFetch -> auth redirect)
  instead of a raw credentials fetch; track/clear the retry + auto-advance
  timers on unmount; drop dead currentStage state + ModuleTree prop.
- learning-api: remove orphaned submitAnswer + AnswerRequest.
- CreateModuleDialog: use the static bookApi import; reset manualBookId to ''
  to match initial state; learning list page: stop shadowing the t() translator.

Conflict-resolution carryover: dropped the PR's incidental 300s factory timeout
(kept dev's stream runner).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-29 14:28:32 +08:00

135 lines
3.6 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import { ChevronRight, ChevronDown, Circle } from "lucide-react";
import { useTranslation } from "react-i18next";
interface KnowledgePoint {
id: string;
name: string;
type: string;
}
interface Module {
id: string;
name: string;
order: number;
knowledge_points: KnowledgePoint[];
pass_threshold: number;
}
interface ModuleTreeProps {
modules: Module[];
masteryLevels: Record<string, number>;
currentModuleId: string;
onModuleClick?: (moduleId: string) => void;
}
function masteryColor(mastery: number, threshold: number): string {
if (mastery >= threshold) return "text-green-500";
if (mastery > 0) return "text-yellow-500";
return "text-[var(--muted-foreground)]";
}
function ModuleNode({
module,
masteryLevels,
isCurrent,
onSelect,
}: {
module: Module;
masteryLevels: Record<string, number>;
isCurrent: boolean;
onSelect?: () => void;
}) {
const [expanded, setExpanded] = useState(isCurrent);
useEffect(() => {
if (!isCurrent) return;
const timer = setTimeout(() => setExpanded(true), 0);
return () => clearTimeout(timer);
}, [isCurrent]);
const total = module.knowledge_points.length;
const averageMastery = total > 0
? module.knowledge_points.reduce((sum, kp) => sum + (masteryLevels[kp.id] ?? 0), 0) / total
: 0;
const masteryPercent = Math.round(averageMastery * 100);
return (
<div>
<button
onClick={() => {
if (!isCurrent) onSelect?.();
setExpanded((prev) => !prev);
}}
className={`flex items-center gap-1.5 w-full px-2 py-1.5 text-left text-sm rounded-md transition-colors cursor-pointer ${
isCurrent
? "bg-[var(--primary)]/10 ring-1 ring-[var(--primary)]/30 text-[var(--primary)]"
: "text-[var(--foreground)] hover:bg-[var(--accent)]"
}`}
>
{expanded ? (
<ChevronDown className="w-3.5 h-3.5 shrink-0" />
) : (
<ChevronRight className="w-3.5 h-3.5 shrink-0" />
)}
<span className="truncate flex-1">{module.name}</span>
<span className="text-xs text-[var(--muted-foreground)] shrink-0">
{masteryPercent}%
</span>
</button>
{expanded && (
<div className="ml-4 border-l border-[var(--border)] pl-2">
{module.knowledge_points.map((kp) => {
const mastery = masteryLevels[kp.id] ?? 0;
return (
<div
key={kp.id}
className="flex items-center gap-1.5 px-2 py-1 text-sm text-[var(--muted-foreground)]"
>
<Circle
className={`w-2 h-2 shrink-0 fill-current ${masteryColor(mastery, module.pass_threshold)}`}
/>
<span className="truncate">{kp.name}</span>
</div>
);
})}
</div>
)}
</div>
);
}
export default function ModuleTree({
modules,
masteryLevels,
currentModuleId,
onModuleClick,
}: ModuleTreeProps) {
const { t } = useTranslation();
const sorted = [...modules].sort((a, b) => a.order - b.order);
if (sorted.length === 0) {
return (
<div className="text-sm text-[var(--muted-foreground)] px-2 py-1">
{t("guidedLearning.noModulesLoaded")}
</div>
);
}
return (
<div className="space-y-0.5">
{sorted.map((mod) => (
<ModuleNode
key={mod.id}
module={mod}
masteryLevels={masteryLevels}
isCurrent={mod.id === currentModuleId}
onSelect={() => onModuleClick?.(mod.id)}
/>
))}
</div>
);
}