Skip to content

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

Block 7: /book integration — Start Learning button in BookLibrary

whfcdc1b73ed88a
diff --git a/deeptutor/api/routers/guided_learning.py b/deeptutor/api/routers/guided_learning.py
index 165ffde53..29d3bbfa7 100644
--- a/deeptutor/api/routers/guided_learning.py
+++ b/deeptutor/api/routers/guided_learning.py
@@ -68,6 +68,15 @@ class InitModulesRequest(BaseModel):
modules: list[dict] # list of LearningModule-compatible dicts
+class ChapterImport(BaseModel):
+ title: str
+ knowledge_points: list[str] = []
+
+
+class ImportFromBookRequest(BaseModel):
+ chapters: list[ChapterImport]
+
+
# ── Endpoints ────────────────────────────────────────────────────────────────
@@ -190,6 +199,32 @@ async def init_modules(book_id: str, body: InitModulesRequest):
return {"status": "ok", "module_count": len(modules)}
[email protected]("/progress/{book_id}/import-from-book")
+async def import_from_book(book_id: str, body: ImportFromBookRequest):
+ if not book_id or ".." in book_id or "/" in book_id or "\\" in book_id or ":" in book_id:
+ raise HTTPException(status_code=400, detail="Invalid book_id")
+ service = get_learning_service()
+ progress = service.get_or_create(book_id)
+ modules = []
+ for i, ch in enumerate(body.chapters):
+ kps = [
+ KnowledgePoint(id=f"{book_id}_ch{i}_kp{j}", name=kp_name, type="concept", module_id=f"{book_id}_ch{i}")
+ for j, kp_name in enumerate(ch.knowledge_points)
+ ]
+ modules.append(LearningModule(
+ id=f"{book_id}_ch{i}",
+ name=ch.title or f"Chapter {i+1}",
+ order=i,
+ pass_threshold=0.7,
+ knowledge_points=kps,
+ ))
+ service.init_modules(progress, modules)
+ progress.current_module_id = modules[0].id if modules else ""
+ progress.current_kp_index = 0
+ service.save(progress)
+ return {"status": "ok", "module_count": len(modules)}
+
+
@router.delete("/progress/{book_id}")
async def delete_progress(book_id: str):
if not book_id or ".." in book_id or "/" in book_id or "\\" in book_id or ":" in book_id:
diff --git a/web/app/(workspace)/book/components/BookLibrary.tsx b/web/app/(workspace)/book/components/BookLibrary.tsx
index 3d6d3da33..31571718a 100644
--- a/web/app/(workspace)/book/components/BookLibrary.tsx
+++ b/web/app/(workspace)/book/components/BookLibrary.tsx
@@ -5,6 +5,7 @@ import {
BookOpen,
Clock3,
FileText,
+ GraduationCap,
Layers,
Library,
Loader2,
@@ -137,6 +138,7 @@ export interface BookLibraryProps {
onNewBook: () => void;
onSelectBook: (id: string) => void;
onDeleteBook: (id: string) => void;
+ onLearn?: (book: Book) => void;
}
export default function BookLibrary({
@@ -145,6 +147,7 @@ export default function BookLibrary({
onNewBook,
onSelectBook,
onDeleteBook,
+ onLearn,
}: BookLibraryProps) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
@@ -416,6 +419,16 @@ export default function BookLibrary({
{relativeTime(book.updated_at, t) || "—"}
</span>
</div>
+ {onLearn && book.status === "ready" && (
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onLearn(book); }}
+ className="mt-2 inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
+ >
+ <GraduationCap size={13} />
+ {t("Start learning")}
+ </button>
+ )}
</div>
</div>
);
diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsx
index e37caf1ce..c56575258 100644
--- a/web/app/(workspace)/book/page.tsx
+++ b/web/app/(workspace)/book/page.tsx
@@ -9,7 +9,7 @@ import {
useRef,
useState,
} from "react";
-import { useSearchParams } from "next/navigation";
+import { useSearchParams, useRouter } from "next/navigation";
import { Loader2, MessageSquare } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -30,6 +30,8 @@ import {
reduceBookEvent,
} from "@/lib/book-progress";
+import { fetchAllProgress, importFromBook } from "@/lib/learning-api";
+
import BookChatPanel from "./components/BookChatPanel";
import BookCreator from "./components/BookCreator";
import BookHealthBanner from "./components/BookHealthBanner";
@@ -65,6 +67,7 @@ function BookLoadingText() {
function BookPageInner() {
const { t } = useTranslation();
+ const router = useRouter();
const [books, setBooks] = useState<Book[]>([]);
const [loadingBooks, setLoadingBooks] = useState(false);
const [view, setView] = useState<View>("list");
@@ -230,6 +233,26 @@ function BookPageInner() {
await refreshBooks();
};
+ const handleLearn = useCallback(async (book: Book) => {
+ try {
+ const allProgress = await fetchAllProgress();
+ const existing = allProgress.find((p: { book_id: string }) => p.book_id === book.id);
+ if (existing && existing.modules_count > 0) {
+ router.push(`/learning/${book.id}`);
+ return;
+ }
+ const data = await bookApi.get(book.id);
+ const chapters = (data.spine?.chapters ?? []).map((ch: { title: string; learning_objectives: string[] }) => ({
+ title: ch.title,
+ knowledge_points: ch.learning_objectives ?? [],
+ }));
+ await importFromBook(book.id, chapters);
+ router.push(`/learning/${book.id}`);
+ } catch {
+ // silent — navigation won't happen on failure
+ }
+ }, [router]);
+
const handleRebuildBook = async () => {
if (!detail) return;
if (
@@ -473,6 +496,7 @@ function BookPageInner() {
onNewBook={handleNewBook}
onSelectBook={(id) => void handleSelectBook(id)}
onDeleteBook={(id) => void handleDeleteBook(id)}
+ onLearn={(book) => void handleLearn(book)}
/>
)}
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 06384672e..5e00ce510 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -68,3 +68,13 @@ export async function redoProgress(bookId: string) {
if (!res.ok) throw new Error(`Failed to redo progress: ${res.status}`);
return res.json();
}
+
+export async function importFromBook(bookId: string, chapters: { title: string; knowledge_points: string[] }[]) {
+ const res = await apiFetch(apiUrl(`/api/v1/learning/progress/${encodeURIComponent(bookId)}/import-from-book`), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ chapters }),
+ });
+ if (!res.ok) throw new Error(`Failed to import from book: ${res.status}`);
+ return res.json();
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ea458727b..91013ae5c 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1649,6 +1649,8 @@
"guidedLearning.stage.module_test": "Module Test",
"guidedLearning.stage.review": "Review",
"guidedLearning.stage.completed": "Completed",
+ "Start learning": "Start learning",
+ "guidedLearning.alreadyHasProgress": "You already have learning progress for this book. Continuing...",
"knowledgeType.memory": "Rote Memory",
"knowledgeType.concept": "Conceptual",
"knowledgeType.procedure": "Procedural",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 27dcd8bea..2f79e18f6 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1649,6 +1649,8 @@
"guidedLearning.stage.module_test": "模块测试",
"guidedLearning.stage.review": "复习",
"guidedLearning.stage.completed": "已完成",
+ "Start learning": "开始学习",
+ "guidedLearning.alreadyHasProgress": "该书已有学习进度,将直接继续学习。",
"knowledgeType.memory": "记忆型",
"knowledgeType.concept": "概念型",
"knowledgeType.procedure": "程序型",