DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(book): add a learning-capture inbox (#926)
evan188199-tech15527bbdabb7
diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.pyindex 66dc1799e..de8bf08e7 100644--- a/deeptutor/api/routers/book.py+++ b/deeptutor/api/routers/book.py@@ -9,10 +9,12 @@ create / confirm / compile / read / delete + a per-book event stream.from __future__ import annotationsimport asyncio+import hashlibimport logging+import timefrom typing import Any-from fastapi import APIRouter, HTTPException, Response, WebSocket, WebSocketDisconnect+from fastapi import APIRouter, HTTPException, Query, Response, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel, Fieldfrom deeptutor.api.utils.http_headers import content_disposition@@ -24,7 +26,8 @@ from deeptutor.book import ()from deeptutor.book.estimate import chapter_basisfrom deeptutor.book.export import export_filename, render_book_markdown-from deeptutor.book.models import ContentType+from deeptutor.book.models import ContentType, LearningCapture, LearningCaptureStatus+from deeptutor.book.storage import get_book_storagefrom deeptutor.book.streaming import SOURCE as BOOK_SOURCEfrom deeptutor.core.stream_bus import StreamBus@@ -156,6 +159,136 @@ class ResumeBookRequest(BaseModel):book_id: str+def _normalize_capture_text(value: str) -> str:+ return " ".join((value or "").strip().split())+++def _build_capture_hash(book_id: str, page_id: str, block_id: str, locator: str, text: str) -> str:+ payload = "|".join(+ [+ book_id,+ page_id,+ block_id,+ locator,+ _normalize_capture_text(text),+ ],+ ).encode("utf-8")+ return hashlib.sha256(payload).hexdigest()+++def _coerce_capture_status(raw: str | None) -> LearningCaptureStatus | None:+ if raw is None:+ return None+ try:+ return LearningCaptureStatus(raw)+ except ValueError as exc:+ raise HTTPException(+ status_code=400,+ detail=f"Invalid capture status: {raw}",+ ) from exc+++_CAPTURE_TRANSITIONS: dict[LearningCaptureStatus, set[LearningCaptureStatus]] = {+ LearningCaptureStatus.CAPTURED: {+ LearningCaptureStatus.CAPTURED,+ LearningCaptureStatus.DRAFTED,+ LearningCaptureStatus.PENDING_CONFIRMATION,+ LearningCaptureStatus.APPROVED,+ LearningCaptureStatus.REJECTED,+ },+ LearningCaptureStatus.DRAFTED: {+ LearningCaptureStatus.DRAFTED,+ LearningCaptureStatus.PENDING_CONFIRMATION,+ LearningCaptureStatus.APPROVED,+ LearningCaptureStatus.REJECTED,+ },+ LearningCaptureStatus.PENDING_CONFIRMATION: {+ LearningCaptureStatus.PENDING_CONFIRMATION,+ LearningCaptureStatus.APPROVED,+ LearningCaptureStatus.REJECTED,+ },+ LearningCaptureStatus.APPROVED: {+ LearningCaptureStatus.APPROVED,+ LearningCaptureStatus.DELIVERED,+ },+ LearningCaptureStatus.DELIVERED: {+ LearningCaptureStatus.DELIVERED,+ LearningCaptureStatus.IMPORTED,+ },+ LearningCaptureStatus.IMPORTED: {LearningCaptureStatus.IMPORTED},+ LearningCaptureStatus.REJECTED: {LearningCaptureStatus.REJECTED},+}+++def _is_capture_transition_allowed(+ current: LearningCaptureStatus,+ requested: LearningCaptureStatus,+) -> bool:+ return requested in _CAPTURE_TRANSITIONS.get(current, set())+++def _derive_capture_title_values(book_id: str, page_id: str, block_id: str) -> tuple[str, str, str]:+ engine = get_book_engine()+ book = engine.load_book(book_id)+ if book is None:+ raise HTTPException(status_code=404, detail="Book not found")+ page = engine.load_page(book_id, page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")++ spine = engine.load_spine(book_id)+ chapter_title = page.title+ if spine is not None and page.chapter_id:+ for chapter in spine.chapters:+ if chapter.id == page.chapter_id:+ chapter_title = chapter.title+ break++ base_locator = f"/book/{book_id}/pages/{page_id}"+ source_locator = f"{base_locator}/block/{block_id}" if block_id else base_locator+ return book.title, chapter_title, source_locator+++def _find_capture_duplicate(+ storage: Any,+ book_id: str,+ page_id: str,+ content_hash: str,+) -> LearningCapture | None:+ for capture in storage.load_learning_captures(book_id):+ if capture.page_id != page_id:+ continue+ if capture.content_hash != content_hash:+ continue+ if capture.status == LearningCaptureStatus.REJECTED:+ continue+ return capture+ return None+++class LearningCaptureCreateRequest(BaseModel):+ page_id: str+ block_id: str = ""+ source_text: str+ context_before: str = ""+ context_after: str = ""+ source_locator: str = ""+ book_title: str = ""+ chapter_title: str = ""+ user_note: str = ""+ status: str | None = None+++class LearningCaptureUpdateRequest(BaseModel):+ status: str | None = None+ user_note: str | None = None+ rejected_reason: str | None = None+++def _capture_payload(capture: LearningCapture) -> dict[str, object]:+ return capture.model_dump(mode="json")++# ─────────────────────────────────────────────────────────────────────────────# REST endpoints# ─────────────────────────────────────────────────────────────────────────────@@ -196,6 +329,121 @@ async def list_books() -> dict[str, Any]:return {"books": await asyncio.to_thread(_collect)}[email protected]("/books/{book_id}/learning-captures")+async def list_learning_captures(+ book_id: str,+ status: str | None = Query(default=None),+) -> dict[str, Any]:+ engine = get_book_engine()+ if engine.load_book(book_id) is None:+ raise HTTPException(status_code=404, detail="Book not found")++ parsed_status = _coerce_capture_status(status) if status is not None else None+ storage = get_book_storage()+ captures = storage.load_learning_captures(book_id, status=parsed_status)+ return {"captures": [_capture_payload(capture) for capture in captures]}++[email protected]("/books/{book_id}/learning-captures")+async def create_learning_capture(+ book_id: str,+ req: LearningCaptureCreateRequest,+) -> dict[str, Any]:+ engine = get_book_engine()+ if engine.load_book(book_id) is None:+ raise HTTPException(status_code=404, detail="Book not found")++ page = engine.load_page(book_id, req.page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")++ source_text = _normalize_capture_text(req.source_text)+ if not source_text:+ raise HTTPException(status_code=400, detail="source_text is required")++ book_title, chapter_title, default_source_locator = _derive_capture_title_values(+ book_id=book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ )++ source_locator = req.source_locator.strip() or default_source_locator+ status = _coerce_capture_status(req.status) or LearningCaptureStatus.CAPTURED++ content_hash = _build_capture_hash(+ book_id,+ req.page_id,+ req.block_id,+ source_locator,+ source_text,+ )++ storage = get_book_storage()+ duplicate = _find_capture_duplicate(storage, book_id, req.page_id, content_hash)+ if duplicate is not None:+ return {"capture": _capture_payload(duplicate)}++ capture = LearningCapture(+ book_id=book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ source_text=source_text,+ context_before=_normalize_capture_text(req.context_before),+ context_after=_normalize_capture_text(req.context_after),+ source_locator=source_locator,+ book_title=req.book_title or book_title,+ chapter_title=req.chapter_title or chapter_title,+ user_note=req.user_note.strip(),+ content_hash=content_hash,+ status=status,+ )+ storage.upsert_learning_capture(capture)+ return {"capture": _capture_payload(capture)}++[email protected]("/books/{book_id}/learning-captures/{capture_id}")+async def update_learning_capture(+ book_id: str,+ capture_id: str,+ req: LearningCaptureUpdateRequest,+) -> dict[str, Any]:+ storage = get_book_storage()+ capture = storage.load_learning_capture(book_id, capture_id)+ if capture is None:+ raise HTTPException(status_code=404, detail="Learning capture not found")++ requested_status = _coerce_capture_status(req.status) if req.status is not None else None+ if requested_status is not None and not _is_capture_transition_allowed(+ capture.status,+ requested_status,+ ):+ raise HTTPException(+ status_code=400,+ detail=(f"Invalid state transition: {capture.status} -> {requested_status}"),+ )++ changed = False+ updated = capture.model_copy(deep=True)++ if requested_status is not None and requested_status != capture.status:+ updated.status = requested_status+ changed = True+ if req.user_note is not None and req.user_note != capture.user_note:+ updated.user_note = req.user_note+ changed = True+ if req.rejected_reason is not None and req.rejected_reason != capture.rejected_reason:+ updated.rejected_reason = req.rejected_reason+ changed = True++ if not changed:+ return {"capture": _capture_payload(capture)}++ updated.version = capture.version + 1+ updated.updated_at = time.time()+ storage.upsert_learning_capture(updated)+ return {"capture": _capture_payload(updated)}++def _page_summary(page) -> dict[str, Any]:"""Page metadata without block payloads.diff --git a/deeptutor/book/models.py b/deeptutor/book/models.pyindex 3edf333ef..c4a6dcb13 100644--- a/deeptutor/book/models.py+++ b/deeptutor/book/models.py@@ -285,6 +285,57 @@ class ConceptGraph(BaseModel):return any(e.src == src and e.dst == dst for e in self.edges)+# ─────────────────────────────────────────────────────────────────────────────+# Learning captures (Book reader annotations)+# ─────────────────────────────────────────────────────────────────────────────+++class LearningCaptureStatus(str, Enum):+ """Lifecycle state for one captured reading segment.++ ``captured`` is the first persisted state after user action.+ ``drafted`` is explicit editing or normalization.+ ``pending_confirmation`` enters UI review.+ ``approved`` is user-reviewed and ready for export.+ ``delivered`` means export task is created.+ ``imported`` means export task was imported/acknowledged in MN4.+ ``rejected`` is a terminal, user-declined state.+ """++ CAPTURED = "captured"+ DRAFTED = "drafted"+ PENDING_CONFIRMATION = "pending_confirmation"+ APPROVED = "approved"+ DELIVERED = "delivered"+ IMPORTED = "imported"+ REJECTED = "rejected"+++class LearningCapture(BaseModel):+ """One captured reading segment for manual review before MN4 writeback."""++ model_config = ConfigDict(extra="ignore")++ id: str = Field(default_factory=lambda: _new_id("lc"))+ book_id: str+ page_id: str+ block_id: str = ""+ capture_type: str = "selection"+ source_text: str = ""+ context_before: str = ""+ context_after: str = ""+ source_locator: str = "" # book/page/anchor for later traceability+ book_title: str = ""+ chapter_title: str = ""+ user_note: str = ""+ content_hash: str = ""+ status: LearningCaptureStatus = LearningCaptureStatus.CAPTURED+ version: int = 1+ rejected_reason: str = ""+ created_at: float = Field(default_factory=_now)+ updated_at: float = Field(default_factory=_now)++class Spine(BaseModel):"""Full chapter tree of a book."""@@ -506,6 +557,8 @@ __all__ = ["SourceChunk","ExplorationReport","Block",+ "LearningCaptureStatus",+ "LearningCapture","Page","PageLink","QuizAttempt",diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.pyindex 5c62bb418..8b89e3394 100644--- a/deeptutor/book/storage.py+++ b/deeptutor/book/storage.py@@ -11,6 +11,7 @@ Layout (relative to ``data/user/workspace/book/``)::├── spine.json # Spine├── progress.json # Progress├── inputs.json # Captured BookInputs+ ├── learning_captures.json # Captured learning items├── log.md # Append-only operation log├── pages/│ └── {page_id}.json@@ -32,7 +33,16 @@ from typing import Anyfrom deeptutor.services.file_io import atomic_write_text as _atomic_write_textfrom deeptutor.services.path_service import get_path_service-from .models import Book, BookInputs, ExplorationReport, Page, Progress, Spine+from .models import (+ Book,+ BookInputs,+ ExplorationReport,+ LearningCapture,+ LearningCaptureStatus,+ Page,+ Progress,+ Spine,+)logger = logging.getLogger(__name__)@@ -196,6 +206,61 @@ class BookStorage:progress.model_dump(mode="json"),)+ # ── Learning Captures ───────────────────────────────────────────────++ def get_learning_captures_path(self, book_id: str) -> Path:+ return self.path_service.get_book_learning_captures_file(_safe_book_id(book_id))++ def _sort_captures(self, captures: list[LearningCapture]) -> list[LearningCapture]:+ return sorted(captures, key=lambda c: c.updated_at, reverse=True)++ def load_learning_captures(+ self, book_id: str, *, status: LearningCaptureStatus | None = None+ ) -> list[LearningCapture]:+ data = _read_json(self.get_learning_captures_path(book_id))+ if not isinstance(data, list):+ return []++ captures: list[LearningCapture] = []+ for raw in data:+ if not isinstance(raw, dict):+ continue+ try:+ capture = LearningCapture.model_validate(raw)+ except Exception as exc:+ logger.warning("Failed to validate LearningCapture for %s: %s", book_id, exc)+ continue+ if status is not None and capture.status != status:+ continue+ captures.append(capture)++ return self._sort_captures(captures)++ def load_learning_capture(self, book_id: str, capture_id: str) -> LearningCapture | None:+ for capture in self.load_learning_captures(book_id):+ if capture.id == capture_id:+ return capture+ return None++ def save_learning_captures(self, book_id: str, captures: list[LearningCapture]) -> None:+ self.ensure_book_root(book_id)+ _atomic_write_json(+ self.get_learning_captures_path(book_id),+ [capture.model_dump(mode="json") for capture in self._sort_captures(captures)],+ )++ def upsert_learning_capture(self, capture: LearningCapture) -> None:+ captures = self.load_learning_captures(capture.book_id)+ updated = False+ for idx, existing in enumerate(captures):+ if existing.id == capture.id:+ captures[idx] = capture+ updated = True+ break+ if not updated:+ captures.append(capture)+ self.save_learning_captures(capture.book_id, captures)+def load_progress(self, book_id: str) -> Progress | None:data = _read_json(self.path_service.get_book_progress_file(book_id))if data is None:diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex 1597f1f4d..56708fd95 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -368,6 +368,9 @@ class PathService:def get_book_page_file(self, book_id: str, page_id: str) -> Path:return self.get_book_pages_dir(book_id) / f"{page_id}.json"+ def get_book_learning_captures_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "learning_captures.json"+def get_book_assets_dir(self, book_id: str) -> Path:return self.get_book_root(book_id) / "assets"diff --git a/tests/api/test_book_learning_captures.py b/tests/api/test_book_learning_captures.pynew file mode 100644index 000000000..362dd8d7c--- /dev/null+++ b/tests/api/test_book_learning_captures.py@@ -0,0 +1,224 @@+from __future__ import annotations++from fastapi import FastAPI+from starlette.testclient import TestClient++from deeptutor.api.routers import book as book_router+from deeptutor.book.models import (+ Book,+ ContentType,+ LearningCapture,+ Page,+ PageStatus,+)+import deeptutor.book.storage as storage_module+from deeptutor.services.path_service import PathService+++class _StubBookEngine:+ def __init__(self, storage: storage_module.BookStorage) -> None:+ self.storage = storage++ def load_book(self, book_id: str) -> Book | None:+ return self.storage.load_book(book_id)++ def load_page(self, book_id: str, page_id: str) -> Page | None:+ return self.storage.load_page(book_id, page_id)++ def load_spine(self, book_id: str):+ return self.storage.load_spine(book_id)+++def _new_client(tmp_path, monkeypatch) -> tuple[TestClient, storage_module.BookStorage]:+ service = PathService(workspace_root=tmp_path / "data")+ monkeypatch.setattr(storage_module, "get_path_service", lambda: service)+ storage_module._storages.clear()+ storage = storage_module.get_book_storage()++ monkeypatch.setattr(+ book_router,+ "get_book_engine",+ lambda: _StubBookEngine(storage),+ )++ app = FastAPI()+ app.include_router(book_router.router, prefix="/api/v1/book")+ return TestClient(app), storage+++def test_learning_capture_list_returns_empty_for_new_book(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_list"++ storage.save_book(Book(id=book_id, title="Book"))+ response = client.get(f"/api/v1/book/books/{book_id}/learning-captures")++ assert response.status_code == 200+ assert response.json() == {"captures": []}+++def test_learning_capture_create_deduplicates_by_content_hash(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_create"++ storage.save_book(Book(id=book_id, title="Book"))+ storage.save_page(+ Page(+ id="pg_1",+ book_id=book_id,+ title="Page",+ learning_objectives=[],+ content_type=ContentType.THEORY,+ status=PageStatus.READY,+ )+ )++ payload = {+ "page_id": "pg_1",+ "block_id": "",+ "source_text": " A repeated selection ",+ }++ first = client.post(f"/api/v1/book/books/{book_id}/learning-captures", json=payload)+ assert first.status_code == 200+ first_id = first.json()["capture"]["id"]++ second = client.post(+ f"/api/v1/book/books/{book_id}/learning-captures",+ json=payload,+ )+ assert second.status_code == 200+ assert second.json()["capture"]["id"] == first_id+ assert second.json()["capture"]["source_text"] == "A repeated selection"+++def test_learning_capture_create_requires_source_text(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_bad"++ storage.save_book(Book(id=book_id, title="Book"))+ storage.save_page(+ Page(+ id="pg_1",+ book_id=book_id,+ title="Page",+ learning_objectives=[],+ content_type=ContentType.THEORY,+ status=PageStatus.READY,+ )+ )++ response = client.post(+ f"/api/v1/book/books/{book_id}/learning-captures",+ json={+ "page_id": "pg_1",+ "source_text": " ",+ "block_id": "",+ },+ )+ assert response.status_code == 400+ assert "source_text is required" in response.json()["detail"]+++def test_learning_capture_patch_allows_legal_transition(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_update"++ storage.save_book(Book(id=book_id, title="Book"))+ storage.save_page(+ Page(+ id="pg_1",+ book_id=book_id,+ title="Page",+ learning_objectives=[],+ content_type=ContentType.THEORY,+ status=PageStatus.READY,+ )+ )++ capture = LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="source",+ content_hash="hash1",+ )+ storage.upsert_learning_capture(capture)++ response = client.patch(+ f"/api/v1/book/books/{book_id}/learning-captures/{capture.id}",+ json={"status": "approved"},+ )+ assert response.status_code == 200+ assert response.json()["capture"]["status"] == "approved"+++def test_learning_capture_patch_blocks_invalid_transition(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_bad_transition"++ storage.save_book(Book(id=book_id, title="Book"))+ storage.save_page(+ Page(+ id="pg_1",+ book_id=book_id,+ title="Page",+ learning_objectives=[],+ content_type=ContentType.THEORY,+ status=PageStatus.READY,+ )+ )+ capture = LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="source",+ content_hash="hash1",+ status="captured",+ )+ storage.upsert_learning_capture(capture)++ response = client.patch(+ f"/api/v1/book/books/{book_id}/learning-captures/{capture.id}",+ json={"status": "imported"},+ )+ assert response.status_code == 400+++def test_learning_capture_list_supports_status_filter(tmp_path, monkeypatch) -> None:+ client, storage = _new_client(tmp_path, monkeypatch)+ book_id = "bk_capture_api_filter"++ storage.save_book(Book(id=book_id, title="Book"))+ storage.save_page(+ Page(+ id="pg_1",+ book_id=book_id,+ title="Page",+ learning_objectives=[],+ content_type=ContentType.THEORY,+ status=PageStatus.READY,+ )+ )+ storage.upsert_learning_capture(+ LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="one",+ content_hash="h1",+ status="captured",+ )+ )+ storage.upsert_learning_capture(+ LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="two",+ content_hash="h2",+ status="approved",+ )+ )++ response = client.get(f"/api/v1/book/books/{book_id}/learning-captures?status=approved")+ assert response.status_code == 200+ payload = response.json()["captures"]+ assert len(payload) == 1+ assert payload[0]["status"] == "approved"diff --git a/tests/book/test_learning_capture_storage.py b/tests/book/test_learning_capture_storage.pynew file mode 100644index 000000000..aeede7de3--- /dev/null+++ b/tests/book/test_learning_capture_storage.py@@ -0,0 +1,122 @@+from __future__ import annotations++from pathlib import Path++from deeptutor.book.models import LearningCapture, LearningCaptureStatus+import deeptutor.book.storage as storage_module+from deeptutor.services.path_service import PathService+++def _build_storage(tmp_path: Path, monkeypatch) -> storage_module.BookStorage:+ service = PathService(workspace_root=tmp_path / "data")+ storage_module._storages.clear()+ monkeypatch.setattr(storage_module, "get_path_service", lambda: service)+ return storage_module.get_book_storage()+++def test_learning_captures_load_save_sorting(tmp_path: Path, monkeypatch) -> None:+ storage = _build_storage(tmp_path, monkeypatch)+ book_id = "bk_capture_sort"++ first = LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="first",+ content_hash="h1",+ updated_at=1,+ )+ second = LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="second",+ content_hash="h2",+ updated_at=5,+ )+ third = LearningCapture(+ book_id=book_id,+ page_id="pg_2",+ source_text="third",+ content_hash="h3",+ updated_at=3,+ )++ storage.upsert_learning_capture(first)+ storage.upsert_learning_capture(second)+ storage.upsert_learning_capture(third)++ captures = storage.load_learning_captures(book_id)+ assert [capture.id for capture in captures] == [second.id, third.id, first.id]++ updated = first.model_copy()+ updated.updated_at = 10+ updated.user_note = "updated note"+ storage.upsert_learning_capture(updated)++ captures = storage.load_learning_captures(book_id)+ assert captures[0].id == first.id+ assert captures[0].user_note == "updated note"+++def test_learning_captures_filter_by_status(tmp_path: Path, monkeypatch) -> None:+ storage = _build_storage(tmp_path, monkeypatch)+ book_id = "bk_capture_filter"+ storage.upsert_learning_capture(+ LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="one",+ content_hash="h1",+ status=LearningCaptureStatus.CAPTURED,+ )+ )+ storage.upsert_learning_capture(+ LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="two",+ content_hash="h2",+ status=LearningCaptureStatus.APPROVED,+ )+ )+ storage.upsert_learning_capture(+ LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="three",+ content_hash="h3",+ status=LearningCaptureStatus.REJECTED,+ )+ )++ assert [+ capture.status+ for capture in storage.load_learning_captures(+ book_id,+ status=LearningCaptureStatus.APPROVED,+ )+ ] == [LearningCaptureStatus.APPROVED]++ assert {+ capture.status+ for capture in storage.load_learning_captures(+ book_id,+ status=LearningCaptureStatus.REJECTED,+ )+ } == {LearningCaptureStatus.REJECTED}+++def test_learning_capture_load_by_id(tmp_path: Path, monkeypatch) -> None:+ storage = _build_storage(tmp_path, monkeypatch)+ book_id = "bk_capture_lookup"+ capture = LearningCapture(+ book_id=book_id,+ page_id="pg_1",+ source_text="lookup me",+ content_hash="h1",+ )+ storage.upsert_learning_capture(capture)++ loaded = storage.load_learning_capture(book_id, capture.id)+ assert loaded is not None+ assert loaded.id == capture.id+ assert loaded.source_text == "lookup me"diff --git a/web/app/(workspace)/book/components/LearningCapturePanel.tsx b/web/app/(workspace)/book/components/LearningCapturePanel.tsxnew file mode 100644index 000000000..e57af2cc9--- /dev/null+++ b/web/app/(workspace)/book/components/LearningCapturePanel.tsx@@ -0,0 +1,135 @@+"use client";++import { Check, ListFilter, X } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";++import type { LearningCapture } from "@/lib/book-types";++interface LearningCapturePanelProps {+ captures: LearningCapture[];+ loading: boolean;+ onApprove: (capture: LearningCapture) => Promise<void> | void;+ onReject: (capture: LearningCapture) => Promise<void> | void;+}++const reviewableStatuses = new Set<LearningCapture["status"]>([+ "captured",+ "drafted",+ "pending_confirmation",+]);++function statusText(status: LearningCapture["status"], t: (key: string, values?: any) => string) {+ const map: Record<string, string> = {+ captured: t("Captured"),+ drafted: t("Drafted"),+ pending_confirmation: t("Pending confirmation"),+ approved: t("Approved"),+ delivered: t("Delivered"),+ imported: t("Imported"),+ rejected: t("Rejected"),+ };+ return map[status] || status;+}++export default function LearningCapturePanel({+ captures,+ loading,+ onApprove,+ onReject,+}: LearningCapturePanelProps) {+ const { t } = useTranslation();+ const [showAll, setShowAll] = useState(false);++ const filteredCaptures = useMemo(() => {+ if (showAll) return captures;+ return captures.filter((capture) => reviewableStatuses.has(capture.status));+ }, [captures, showAll]);++ return (+ <section className="mx-auto w-full max-w-[78ch] space-y-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4">+ <div className="flex items-center justify-between gap-2">+ <h2 className="text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Learning capture inbox")}+ </h2>+ <div className="flex items-center gap-2">+ <span className="rounded-full bg-[var(--muted)] px-2 py-0.5 text-xs text-[var(--muted-foreground)]">+ {filteredCaptures.length}+ </span>+ <button+ type="button"+ onClick={() => setShowAll((current) => !current)}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-[10px] text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]"+ title={+ showAll ? t("Show only reviewable captures") : t("Show all captures")+ }+ >+ <ListFilter className="h-3.5 w-3.5" />+ {showAll ? t("Review") : t("All")}+ </button>+ </div>+ </div>++ {loading && filteredCaptures.length === 0 ? (+ <div className="text-xs text-[var(--muted-foreground)]">{t("Loading captures…")}</div>+ ) : filteredCaptures.length === 0 ? (+ <div className="text-xs text-[var(--muted-foreground)]">+ {showAll+ ? t("No captures yet.")+ : t("No captures awaiting review.")}+ </div>+ ) : (+ <div className="max-h-52 space-y-2 overflow-y-auto pr-1">+ {filteredCaptures.map((capture) => {+ const reviewable = reviewableStatuses.has(capture.status);+ return (+ <article+ key={capture.id}+ className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-2"+ >+ <div className="mb-1 flex items-start justify-between gap-2 text-[11px]">+ <span className="rounded-md bg-[var(--muted)] px-2 py-0.5 text-[10px] text-[var(--muted-foreground)]">+ {statusText(capture.status, t)}+ </span>+ <span className="text-[10px] text-[var(--muted-foreground)]">+ {capture.chapter_title || t("Unknown chapter")}+ </span>+ </div>+ <p className="whitespace-pre-wrap text-sm text-[var(--foreground)]">+ {capture.source_text}+ </p>+ {capture.user_note ? (+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">+ {t("Note")}: {capture.user_note}+ </p>+ ) : null}+ <div className="mt-2 flex items-center gap-2">+ {reviewable && (+ <>+ <button+ type="button"+ onClick={() => void onApprove(capture)}+ className="inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-2 py-1 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90"+ >+ <Check className="h-3.5 w-3.5" />+ {t("Approve")}+ </button>+ <button+ type="button"+ onClick={() => void onReject(capture)}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ >+ <X className="h-3.5 w-3.5" />+ {t("Reject")}+ </button>+ </>+ )}+ </div>+ </article>+ );+ })}+ </div>+ )}+ </section>+ );+}diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsxindex 9784a1a0f..88c0274bd 100644--- a/web/app/(workspace)/book/components/PageReader.tsx+++ b/web/app/(workspace)/book/components/PageReader.tsx@@ -1,10 +1,11 @@"use client";-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {Bookmark,BookmarkCheck,Loader2,+ Pencil,RefreshCcw,Plus,ChevronDown,@@ -59,6 +60,15 @@ export interface PageReaderProps {onNavigate?: (pageId: string) => void;bookmarked?: boolean;onToggleBookmark?: () => void;++ onCaptureSelection?: (payload: {+ page_id: string;+ block_id: string;+ source_text: string;+ context_before?: string;+ context_after?: string;+ source_locator?: string;+ }) => Promise<void> | void;}export default function PageReader({@@ -85,6 +95,7 @@ export default function PageReader({onNavigate,bookmarked = false,onToggleBookmark,+ onCaptureSelection,}: PageReaderProps) {const { t } = useTranslation();const [showInsertMenu, setShowInsertMenu] = useState(false);@@ -130,6 +141,61 @@ export default function PageReader({return () => scrollContainer.removeEventListener("scroll", handler);}, [scrollContainer, userToggled]);+ const normalizeText = useCallback((value: string): string => {+ return (value || "").replace(/\s+/g, " ").trim();+ }, []);++ const captureSelection = useCallback(() => {+ if (!onCaptureSelection || !page) {+ return;+ }+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) {+ window.alert(t("Please select some text before saving."));+ return;+ }++ const sourceText = normalizeText(selection.toString());+ if (!sourceText) {+ window.alert(t("Selected text is empty."));+ return;+ }++ const anchor = selection.anchorNode;+ const anchorEl =+ anchor && anchor.nodeType === Node.TEXT_NODE+ ? anchor.parentElement+ : (anchor as HTMLElement | null);+ const blockEl = anchorEl?.closest?.("[data-block-id]") as HTMLElement | null;+ const blockId = blockEl?.getAttribute("data-block-id") || "";++ const rawContext = blockEl?.textContent || selection.toString();+ const contextText = rawContext || "";+ const normalizedContext = normalizeText(contextText);+ const sourceStart = normalizedContext.indexOf(sourceText);+ const sourceEnd = sourceStart >= 0 ? sourceStart + sourceText.length : -1;+ const beforeStart = sourceStart >= 0 ? Math.max(0, sourceStart - 120) : 0;+ const afterEnd =+ sourceEnd >= 0 ? Math.min(normalizedContext.length, sourceEnd + 120) : 0;+ const contextBefore =+ sourceStart >= 0 ? normalizedContext.slice(beforeStart, sourceStart) : "";+ const contextAfter = sourceEnd >= 0 ? normalizedContext.slice(sourceEnd, afterEnd) : "";++ const sourceLocator = blockId+ ? `/book/${page.book_id}/pages/${page.id}/blocks/${blockId}`+ : `/book/${page.book_id}/pages/${page.id}`;++ void onCaptureSelection({+ page_id: page.id,+ block_id: blockId,+ source_text: sourceText,+ context_before: contextBefore,+ context_after: contextAfter,+ source_locator: sourceLocator,+ });+ selection.removeAllRanges();+ }, [onCaptureSelection, normalizeText, page, t]);+useEffect(() => {if (!onNavigate) return;const handler = (event: KeyboardEvent) => {@@ -165,6 +231,8 @@ export default function PageReader({const collapseTip = t("Collapse header");const failedBlocks = page.blocks.filter((block) => block.status === "error");const hasFailedBlocks = failedBlocks.length > 0;+ const canCaptureSelection =+ !!onCaptureSelection && !loading && page.blocks.length > 0;return (// The outer container is `relative` so the floating outline nav can@@ -395,6 +463,16 @@ export default function PageReader({))}</div>)}+ {canCaptureSelection && (+ <button+ type="button"+ onClick={captureSelection}+ className="inline-flex items-center justify-center rounded-full border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/50 hover:text-[var(--primary)]"+ >+ <Pencil className="mr-1.5 h-3.5 w-3.5" />+ {t("Save selection")}+ </button>+ )}</div>)}</article>diff --git a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsxindex 006b850b7..bc4cbc3cc 100644--- a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx+++ b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx@@ -261,7 +261,7 @@ export default function BlockRenderer({const showBridge = bridgeText.length > 0;return (- <div className="group relative">+ <div className="group relative" data-block-id={block.id}>{showBridge && (<div className="mb-3 text-[var(--foreground)]"><MarkdownRenderer content={bridgeText} variant="prose" />diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsxindex 2318f3654..fc015d398 100644--- a/web/app/(workspace)/book/page.tsx+++ b/web/app/(workspace)/book/page.tsx@@ -24,6 +24,7 @@ import type {BookProposal,Page,Spine,+ LearningCapture,} from "@/lib/book-types";import {RESET_BOOK_PROGRESS,@@ -46,6 +47,7 @@ import BookPausedBanner from "./components/BookPausedBanner";import BookProgressTimeline from "./components/BookProgressTimeline";import BookSidebar from "./components/BookSidebar";import PageReader from "./components/PageReader";+import LearningCapturePanel from "./components/LearningCapturePanel";import SpineEditor from "./components/SpineEditor";import type { QuizAttemptArgs } from "./components/blocks/QuizBlock";@@ -140,6 +142,9 @@ function BookPageInner() {const [supplementingBlockId, setSupplementingBlockId] = useState<string | null>(null);+ const [learningCaptures, setLearningCaptures] = useState<LearningCapture[]>([]);+ const [loadingLearningCaptures, setLoadingLearningCaptures] =+ useState(false);// Phase 5 — live BookEngine progress timeline state.const [progress, dispatchProgress] = useReducer(@@ -215,6 +220,26 @@ function BookPageInner() {[selectedBookId, mergePage],);+ const refreshLearningCaptures = useCallback(+ async (bookId: string) => {+ setLoadingLearningCaptures(true);+ try {+ const { captures } = await bookApi.listLearningCaptures(bookId);+ setLearningCaptures(captures);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ notify(t("Could not load learning captures: {{message}}", { message: msg }), {+ tone: "error",+ durationMs: 6000,+ });+ setLearningCaptures([]);+ } finally {+ setLoadingLearningCaptures(false);+ }+ },+ [t],+ );+// Debounced per page, so a burst of block events costs one fetch.const pageRefreshTimers = useRef(new Map<string, ReturnType<typeof setTimeout>>(),@@ -401,6 +426,14 @@ function BookPageInner() {void handleSelectBook(requestedBookId, requestedPageId);}, [requestedBookId, requestedPageId, selectedBookId, handleSelectBook]);+ useEffect(() => {+ if (view !== "reader" || !selectedBookId) {+ if (!selectedBookId) setLearningCaptures([]);+ return;+ }+ void refreshLearningCaptures(selectedBookId);+ }, [view, selectedBookId, refreshLearningCaptures]);+const handleDeleteBook = async (id: string) =>guard("Delete book", async () => {// The library card already requires a second click to confirm.@@ -766,6 +799,65 @@ function BookPageInner() {}};+ const refreshCapturesSorted = useCallback((captures: LearningCapture[]) => {+ return [...captures].sort((a, b) => b.updated_at - a.updated_at);+ }, []);++ const applyCapturePatch = useCallback((capture: LearningCapture) => {+ setLearningCaptures((current) =>+ refreshCapturesSorted(+ current.some((item) => item.id === capture.id)+ ? current.map((item) => (item.id === capture.id ? capture : item))+ : [capture, ...current],+ ),+ );+ }, [refreshCapturesSorted]);++ const handleCaptureSelection = async (payload: {+ page_id: string;+ block_id: string;+ source_text: string;+ context_before?: string;+ context_after?: string;+ source_locator?: string;+ }) => {+ if (!detail) return;+ const result = await bookApi.createLearningCapture(detail.book.id, {+ ...payload,+ book_title: detail.book.title,+ chapter_title: selectedPage?.title || "",+ });+ applyCapturePatch(result.capture);+ };++ const handleApproveCapture = async (capture: LearningCapture) => {+ if (!detail) return;+ const result = await bookApi.updateLearningCapture(+ detail.book.id,+ capture.id,+ { status: "approved" },+ );+ applyCapturePatch(result.capture);+ notify(t("Capture approved"), {+ tone: "success",+ durationMs: 3000,+ });+ };++ const handleRejectCapture = async (capture: LearningCapture) => {+ if (!detail) return;+ const result = await bookApi.updateLearningCapture(+ detail.book.id,+ capture.id,+ { status: "rejected" },+ );+ applyCapturePatch(result.capture);+ notify(t("Capture rejected"), {+ tone: "info",+ durationMs: 3000,+ });+ };+const handlePageChatSession = async (sessionId: string) =>guard("Link chat session", async () => {if (!detail || !selectedPage || !sessionId) return;@@ -873,52 +965,71 @@ function BookPageInner() {}}/><div className="min-h-0 flex-1">- <PageReader- page={selectedPage}- bookId={detail?.book.id}- bookLanguage={detail?.book.language}- loading={- !!compilingPageId && compilingPageId === selectedPage?.id- }- onRegenerateBlock={(block) =>- void handleRegenerateBlock(block)- }- onDeleteBlock={(block) => void handleDeleteBlock(block)}- onMoveBlock={(block, dir) => void handleMoveBlock(block, dir)}- onChangeBlockType={(block, t) =>- void handleChangeBlockType(block, t)- }- onInsertBlock={(t) => handleInsertBlock(t)}- onDeepDive={(topic, blockId) =>- handleDeepDive(topic, blockId)- }- onOpenPage={(pageId) => handleSelectPage(pageId)}- onQuizAttempt={(block, args) =>- void handleQuizAttempt(block, args)- }- onRequestSupplement={(block) =>- void handleRequestSupplement(block)- }- supplementingBlockId={supplementingBlockId}- onUpdateBody={handleUpdateBody}- attempts={detail?.progress.quiz_attempts}- previousPage={pageNeighbours.previous}- nextPage={pageNeighbours.next}- onNavigate={handleSelectPage}- bookmarked={- !!selectedPage &&- !!detail?.progress.bookmarked_page_ids.includes(- selectedPage.id,- )- }- onToggleBookmark={() => void handleToggleBookmark()}- pendingDeepDiveTopic={pendingDeepDiveTopic}- onRecompile={- selectedPage- ? () => void compilePage(selectedPage.id, true)- : undefined- }- />+ <div className="min-h-0 flex-1 overflow-hidden">+ <PageReader+ page={selectedPage}+ bookId={detail?.book.id}+ bookLanguage={detail?.book.language}+ loading={+ !!compilingPageId && compilingPageId === selectedPage?.id+ }+ onRegenerateBlock={(block) =>+ void handleRegenerateBlock(block)+ }+ onDeleteBlock={(block) => void handleDeleteBlock(block)}+ onMoveBlock={(block, dir) => void handleMoveBlock(block, dir)}+ onChangeBlockType={(block, t) =>+ void handleChangeBlockType(block, t)+ }+ onInsertBlock={(t) => handleInsertBlock(t)}+ onDeepDive={(topic, blockId) =>+ handleDeepDive(topic, blockId)+ }+ onOpenPage={(pageId) => handleSelectPage(pageId)}+ onQuizAttempt={(block, args) =>+ void handleQuizAttempt(block, args)+ }+ onRequestSupplement={(block) =>+ void handleRequestSupplement(block)+ }+ supplementingBlockId={supplementingBlockId}+ onUpdateBody={handleUpdateBody}+ attempts={detail?.progress.quiz_attempts}+ previousPage={pageNeighbours.previous}+ nextPage={pageNeighbours.next}+ onNavigate={handleSelectPage}+ bookmarked={+ !!selectedPage &&+ !!detail?.progress.bookmarked_page_ids.includes(+ selectedPage.id,+ )+ }+ onToggleBookmark={() => void handleToggleBookmark()}+ pendingDeepDiveTopic={pendingDeepDiveTopic}+ onRecompile={+ selectedPage+ ? () => void compilePage(selectedPage.id, true)+ : undefined+ }+ onCaptureSelection={(payload) =>+ void guard("Save selection", () =>+ handleCaptureSelection(payload),+ )+ }+ />+ </div>+ <div className="border-t border-[var(--border)]">+ <LearningCapturePanel+ captures={learningCaptures}+ loading={loadingLearningCaptures}+ onApprove={(capture) =>+ void guard("Approve capture", () => handleApproveCapture(capture))+ }+ onReject={(capture) =>+ void guard("Reject capture", () => handleRejectCapture(capture))+ }+ />+ </div></div></div>)}diff --git a/web/lib/book-api.ts b/web/lib/book-api.tsindex 6ceec6506..595a6e21a 100644--- a/web/lib/book-api.ts+++ b/web/lib/book-api.ts@@ -7,6 +7,8 @@ import type {Book,BookDepth,BookDetail,+ LearningCapture,+ LearningCaptureStatus,BookProposal,Page,Progress,@@ -317,6 +319,55 @@ export const bookApi = {}>(`/books/${encodeURIComponent(book_id)}/refresh-fingerprints`, {method: "POST",}),++ listLearningCaptures: (+ book_id: string,+ status?: LearningCaptureStatus,+ ) =>+ request<{ captures: LearningCapture[] }>(+ `/books/${encodeURIComponent(+ book_id,+ )}/learning-captures${status ? `?status=${encodeURIComponent(status)}` : ""}`,+ ),++ createLearningCapture: (+ book_id: string,+ payload: {+ page_id: string;+ block_id: string;+ source_text: string;+ context_before?: string;+ context_after?: string;+ source_locator?: string;+ book_title?: string;+ chapter_title?: string;+ user_note?: string;+ status?: LearningCaptureStatus;+ },+ ) =>+ request<{ capture: LearningCapture }>(`/books/${encodeURIComponent(book_id)}/learning-captures`, {+ method: "POST",+ body: JSON.stringify(payload),+ }),++ updateLearningCapture: (+ book_id: string,+ capture_id: string,+ payload: {+ status?: LearningCaptureStatus;+ user_note?: string;+ rejected_reason?: string;+ },+ ) =>+ request<{ capture: LearningCapture }>(+ `/books/${encodeURIComponent(book_id)}/learning-captures/${encodeURIComponent(+ capture_id,+ )}`,+ {+ method: "PATCH",+ body: JSON.stringify(payload),+ },+ ),};export interface LegacyChatSession {diff --git a/web/lib/book-types.ts b/web/lib/book-types.tsindex 2249a7c68..a020bfef6 100644--- a/web/lib/book-types.ts+++ b/web/lib/book-types.ts@@ -188,6 +188,36 @@ export interface QuizAttempt {timestamp: number;}+export type LearningCaptureStatus =+ | "captured"+ | "drafted"+ | "pending_confirmation"+ | "approved"+ | "delivered"+ | "imported"+ | "rejected";++export interface LearningCapture {+ id: string;+ book_id: string;+ page_id: string;+ block_id: string;+ capture_type: string;+ source_text: string;+ context_before: string;+ context_after: string;+ source_locator: string;+ book_title: string;+ chapter_title: string;+ user_note: string;+ content_hash: string;+ status: LearningCaptureStatus;+ version: number;+ rejected_reason: string;+ created_at: number;+ updated_at: number;+}+export interface Progress {book_id: string;current_page_id: string;