Skip to content

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

feat(assessment): unify persisted review records (#824)

XZH7a0f1f6a07f5
diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.py
index 6277b69ad..170761fd1 100644
--- a/deeptutor/api/routers/book.py
+++ b/deeptutor/api/routers/book.py
@@ -145,6 +145,23 @@ class QuizAttemptRequest(BaseModel):
is_correct: bool | None = None
+def _focus_check_question(
+ questions: list[dict[str, Any]], requested_id: str, block_id: str
+) -> tuple[str, dict[str, Any]] | None:
+ """Resolve the durable question behind a Focus-Check submission."""
+ for index, question in enumerate(questions):
+ if not isinstance(question, dict):
+ continue
+ question_id = str(question.get("question_id") or "").strip()
+ if requested_id and question_id == requested_id:
+ return question_id, question
+ if not requested_id and not question_id:
+ return f"{block_id}:{index + 1}", question
+ if requested_id:
+ return requested_id, {}
+ return None
+
+
class UpdateBlockRequest(BaseModel):
book_id: str
page_id: str
@@ -946,6 +963,17 @@ async def deep_dive(req: DeepDiveRequest) -> dict[str, Any]:
@router.post("/books/quiz-attempt")
async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:
resolved = _resolve_book_or_404(req.book_id)
+ book = resolved.engine.load_book(req.book_id)
+ page = next(
+ (item for item in resolved.engine.list_pages(req.book_id) if item.id == req.page_id), None
+ )
+ block = page.block_by_id(req.block_id) if page is not None else None
+ questions = (
+ [item for item in block.payload.get("questions", []) if isinstance(item, dict)]
+ if block is not None
+ else []
+ )
+ resolved_question = _focus_check_question(questions, req.question_id, req.block_id)
progress = progress_ops.record_attempt(
resolved.load_progress(req.book_id),
page_id=req.page_id,
@@ -960,6 +988,46 @@ async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:
},
)
resolved.learning.save_progress(progress)
+ if req.is_correct is not None and resolved_question is not None and book is not None:
+ question_id, question = resolved_question
+ try:
+ from deeptutor.services.session import get_sqlite_session_store
+
+ store = get_sqlite_session_store()
+ session_id = f"book_{req.book_id}"
+ if await store.get_session(session_id) is None:
+ await store.create_session(
+ session_id=session_id, title=book.title or "Immersive Reading"
+ )
+ await store.upsert_notebook_entries(
+ session_id,
+ [
+ {
+ "turn_id": req.block_id,
+ "question_id": question_id,
+ "question": str(question.get("question") or block.title or "Focus check"),
+ "question_type": str(question.get("question_type") or ""),
+ "options": question.get("options") or {},
+ "correct_answer": str(question.get("correct_answer") or ""),
+ "explanation": str(question.get("explanation") or ""),
+ "difficulty": str(question.get("difficulty") or ""),
+ "user_answer": req.user_answer,
+ "is_correct": bool(req.is_correct),
+ "source": "immersive_reading",
+ "material_id": req.book_id,
+ "material_title": book.title,
+ "section_id": req.page_id,
+ "section_title": page.title if page is not None else "",
+ }
+ ],
+ )
+ except Exception:
+ logger.warning(
+ "Failed to sync Focus-Check %s to question bank for book %s",
+ req.question_id,
+ req.book_id,
+ exc_info=True,
+ )
return {"progress": progress.model_dump(mode="json")}
diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.py
index ac045a0cd..ec0819983 100644
--- a/deeptutor/api/routers/question_notebook.py
+++ b/deeptutor/api/routers/question_notebook.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import base64 as _b64
import logging
+from typing import Literal
import uuid as _uuid
from fastapi import APIRouter, HTTPException, Query, Response
@@ -17,6 +18,8 @@ from deeptutor.services.storage import get_attachment_store
logger = logging.getLogger(__name__)
router = APIRouter()
+AssessmentSource = Literal["deep_question", "mastery_path", "immersive_reading"]
+ScoreTrend = Literal["new", "improved", "declined", "unchanged"]
# ── Models ────────────────────────────────────────────────────────
@@ -56,7 +59,14 @@ class NotebookEntryItem(BaseModel):
difficulty: str = ""
user_answer: str = ""
user_answer_images: list[AnswerImageItem] = []
+ source: AssessmentSource = "deep_question"
+ material_id: str = ""
+ material_title: str = ""
+ section_id: str = ""
+ section_title: str = ""
+ score_trend: ScoreTrend = "new"
is_correct: bool = False
+ resolved: bool = False
bookmarked: bool = False
followup_session_id: str = ""
ai_judgment: str = ""
@@ -74,6 +84,7 @@ class EntryUpdateRequest(BaseModel):
bookmarked: bool | None = None
followup_session_id: str | None = None
ai_judgment: str | None = None
+ resolved: bool | None = None
class CategoryCreateRequest(BaseModel):
@@ -103,10 +114,19 @@ class BulkCategoryRequest(BaseModel):
class QuestionBankStats(BaseModel):
total: int = 0
wrong: int = 0
+ unresolved: int = 0
bookmarked: int = 0
uncategorized: int = 0
+class QuestionBankMaterial(BaseModel):
+ source: str
+ material_id: str
+ material_title: str
+ entry_count: int
+ unresolved_count: int
+
+
class AnswerImageUpload(BaseModel):
"""One image attached to the learner's answer.
@@ -138,6 +158,11 @@ class UpsertEntryRequest(BaseModel):
# ``None`` means "don't touch any previously-stored images on update";
# an empty list explicitly clears them.
user_answer_images: list[AnswerImageUpload] | None = None
+ source: AssessmentSource = "deep_question"
+ material_id: str = ""
+ material_title: str = ""
+ section_id: str = ""
+ section_title: str = ""
is_correct: bool = False
@@ -231,6 +256,11 @@ async def list_entries(
),
bookmarked: bool | None = Query(default=None),
is_correct: bool | None = Query(default=None),
+ source: str = Query(default="", pattern="^(deep_question|mastery_path|immersive_reading)?$"),
+ material_id: str = Query(default="", max_length=500),
+ section_id: str = Query(default="", max_length=500),
+ resolved: bool | None = Query(default=None),
+ score_trend: str = Query(default="", pattern="^(new|improved|declined|unchanged)?$"),
search: str = Query(default="", max_length=200),
sort: str = Query(default="recent", pattern="^(recent|oldest)$"),
limit: int = Query(default=50, ge=1, le=200),
@@ -242,6 +272,11 @@ async def list_entries(
uncategorized=uncategorized,
bookmarked=bookmarked,
is_correct=is_correct,
+ source=source,
+ material_id=material_id,
+ section_id=section_id,
+ resolved=resolved,
+ score_trend=score_trend,
search=search,
sort=sort,
limit=limit,
@@ -352,6 +387,13 @@ async def question_bank_stats() -> QuestionBankStats:
return QuestionBankStats(**await store.question_bank_stats())
[email protected]("/materials", response_model=list[QuestionBankMaterial])
+async def list_question_bank_materials() -> list[QuestionBankMaterial]:
+ """Materials represented in the unified review history."""
+ store = get_sqlite_session_store()
+ return [QuestionBankMaterial(**item) for item in await store.list_question_bank_materials()]
+
+
# ── Category CRUD ────────────────────────────────────────────────
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 00214c052..262b6c484 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -243,6 +243,7 @@ async def _resolve_pending_choice(
async def _sync_mastery_attempt_to_question_bank(
*,
+ path_id: str,
session_id: str,
turn_id: str,
pending: PendingQuestion,
@@ -250,6 +251,8 @@ async def _sync_mastery_attempt_to_question_bank(
is_correct: bool,
choice_options: dict[str, str] | None = None,
correct_answer: str | None = None,
+ material_title: str = "",
+ section_title: str = "",
) -> None:
if not session_id:
return
@@ -266,6 +269,11 @@ async def _sync_mastery_attempt_to_question_bank(
"difficulty": pending.difficulty,
"user_answer": user_answer,
"is_correct": is_correct,
+ "source": "mastery_path",
+ "material_id": path_id,
+ "material_title": material_title,
+ "section_id": pending.knowledge_point_id,
+ "section_title": section_title,
}
try:
from deeptutor.services.session import get_sqlite_session_store
@@ -698,7 +706,9 @@ class MasteryGradeTool(BaseTool):
# Upsert on every call, including an idempotent replay: if the first
# best-effort sync timed out, a safe retry repairs the auxiliary
# question bank without duplicating the mastery attempt.
+ kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
await _sync_mastery_attempt_to_question_bank(
+ path_id=path_id,
session_id=interaction.session_id or _resolve_session_id(kwargs),
turn_id=interaction.turn_id or _resolve_turn_id(kwargs),
pending=pending,
@@ -708,8 +718,9 @@ class MasteryGradeTool(BaseTool):
is_correct=is_correct,
choice_options=choice_options,
correct_answer=expected_answer,
+ material_title=progress.name,
+ section_title=kp.title if kp else "",
)
- kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
mastered = bool(kp and is_mastered(progress, kp))
payload = {
"is_correct": is_correct,
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 36696b1c6..68f3e5898 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -59,6 +59,8 @@ def _json_loads(value: str | None, default: Any) -> Any:
# this id prefix as their discriminator (see ``SQLiteSessionStore._WHERE_*``).
_IMPORTED_ID_PREFIX = "imported_"
_ID_SAFE = re.compile(r"[^A-Za-z0-9_-]")
+ASSESSMENT_SOURCES = frozenset({"deep_question", "mastery_path", "immersive_reading"})
+SCORE_TRENDS = frozenset({"new", "improved", "declined", "unchanged"})
def make_imported_session_id(source: str, external_id: str) -> str:
@@ -118,6 +120,11 @@ class QuestionBankQuery:
uncategorized: bool = False
bookmarked: bool | None = None
is_correct: bool | None = None
+ source: str = ""
+ material_id: str = ""
+ section_id: str = ""
+ resolved: bool | None = None
+ score_trend: str = ""
search: str = ""
session_id: str | None = None
sort: str = "recent"
@@ -131,6 +138,15 @@ class QuestionBankQuery:
uncategorized=self.uncategorized and self.category_id is None,
bookmarked=self.bookmarked,
is_correct=self.is_correct,
+ source=(self.source or "").strip()
+ if (self.source or "").strip() in ASSESSMENT_SOURCES
+ else "",
+ material_id=(self.material_id or "").strip(),
+ section_id=(self.section_id or "").strip(),
+ resolved=self.resolved,
+ score_trend=(self.score_trend or "").strip()
+ if (self.score_trend or "").strip() in SCORE_TRENDS
+ else "",
search=(self.search or "").strip()[:200],
session_id=self.session_id,
sort="oldest" if self.sort == "oldest" else "recent",
@@ -250,7 +266,14 @@ class SQLiteSessionStore:
difficulty TEXT DEFAULT '',
user_answer TEXT DEFAULT '',
user_answer_images_json TEXT DEFAULT '[]',
+ source TEXT NOT NULL DEFAULT 'deep_question',
+ material_id TEXT NOT NULL DEFAULT '',
+ material_title TEXT NOT NULL DEFAULT '',
+ section_id TEXT NOT NULL DEFAULT '',
+ section_title TEXT NOT NULL DEFAULT '',
+ score_trend TEXT NOT NULL DEFAULT 'new',
is_correct INTEGER DEFAULT 0,
+ resolved INTEGER DEFAULT 0,
bookmarked INTEGER DEFAULT 0,
followup_session_id TEXT DEFAULT '',
ai_judgment TEXT DEFAULT '',
@@ -324,6 +347,7 @@ class SQLiteSessionStore:
self._migrate_notebook_entries_add_turn_id(conn)
self._migrate_notebook_entries_add_user_answer_images(conn)
self._migrate_notebook_entries_add_ai_judgment(conn)
+ self._migrate_notebook_entries_add_assessment_review(conn)
conn.commit()
@staticmethod
@@ -441,6 +465,33 @@ class SQLiteSessionStore:
if "ai_judgment" not in cols:
conn.execute("ALTER TABLE notebook_entries ADD COLUMN ai_judgment TEXT DEFAULT ''")
+ @staticmethod
+ def _migrate_notebook_entries_add_assessment_review(
+ conn: sqlite3.Connection,
+ ) -> None:
+ """Add provenance and review-state columns without rewriting history."""
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(notebook_entries)").fetchall()}
+ if not cols:
+ return
+ additions = {
+ "source": "TEXT NOT NULL DEFAULT 'deep_question'",
+ "material_id": "TEXT NOT NULL DEFAULT ''",
+ "material_title": "TEXT NOT NULL DEFAULT ''",
+ "section_id": "TEXT NOT NULL DEFAULT ''",
+ "section_title": "TEXT NOT NULL DEFAULT ''",
+ "score_trend": "TEXT NOT NULL DEFAULT 'new'",
+ "resolved": "INTEGER DEFAULT 0",
+ }
+ for name, definition in additions.items():
+ if name not in cols:
+ conn.execute(f"ALTER TABLE notebook_entries ADD COLUMN {name} {definition}")
+ conn.execute(
+ """
+ CREATE INDEX IF NOT EXISTS idx_notebook_entries_review
+ ON notebook_entries(source, material_id, resolved, created_at DESC)
+ """
+ )
+
async def _run(self, fn, *args):
async with self._lock:
return await asyncio.to_thread(fn, *args)
@@ -1575,18 +1626,61 @@ class SQLiteSessionStore:
# upsert that only changes ``is_correct``).
images_value = item.get("user_answer_images")
images_json = _json_dumps(images_value) if isinstance(images_value, list) else None
+ source = str(item.get("source") or "deep_question")
+ if source not in ASSESSMENT_SOURCES:
+ source = "deep_question"
+ is_correct = 1 if item.get("is_correct") else 0
+ existing = conn.execute(
+ """
+ SELECT is_correct FROM notebook_entries
+ WHERE session_id = ? AND turn_id = ? AND question_id = ?
+ """,
+ (session_id, turn_id, question_id),
+ ).fetchone()
+ previous = bool(existing["is_correct"]) if existing is not None else None
+ if previous is None or previous == bool(is_correct):
+ score_trend = "new" if previous is None else "unchanged"
+ else:
+ score_trend = "improved" if is_correct else "declined"
+ provenance = (
+ source,
+ str(item.get("material_id") or ""),
+ str(item.get("material_title") or ""),
+ str(item.get("section_id") or ""),
+ str(item.get("section_title") or ""),
+ score_trend,
+ )
if images_json is None:
conn.execute(
"""
INSERT INTO notebook_entries (
session_id, turn_id, question_id, question, question_type,
options_json, correct_answer, explanation, difficulty,
- user_answer, user_answer_images_json, is_correct,
- bookmarked, followup_session_id, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, 0, '', ?, ?)
+ user_answer, user_answer_images_json, source, material_id,
+ material_title, section_id, section_title, score_trend,
+ is_correct, resolved, bookmarked, followup_session_id,
+ created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)
ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET
+ question = excluded.question,
+ question_type = excluded.question_type,
+ options_json = excluded.options_json,
+ correct_answer = excluded.correct_answer,
+ explanation = excluded.explanation,
+ difficulty = excluded.difficulty,
user_answer = excluded.user_answer,
+ source = excluded.source,
+ material_id = excluded.material_id,
+ material_title = excluded.material_title,
+ section_id = excluded.section_id,
+ section_title = excluded.section_title,
+ score_trend = excluded.score_trend,
is_correct = excluded.is_correct,
+ resolved = CASE
+ WHEN excluded.is_correct = 1 THEN 1
+ WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0
+ ELSE notebook_entries.resolved
+ END,
updated_at = excluded.updated_at
""",
(
@@ -1600,7 +1694,9 @@ class SQLiteSessionStore:
item.get("explanation") or "",
item.get("difficulty") or "",
item.get("user_answer") or "",
- 1 if item.get("is_correct") else 0,
+ *provenance,
+ is_correct,
+ 1 if is_correct else 0,
now,
now,
),
@@ -1611,13 +1707,32 @@ class SQLiteSessionStore:
INSERT INTO notebook_entries (
session_id, turn_id, question_id, question, question_type,
options_json, correct_answer, explanation, difficulty,
- user_answer, user_answer_images_json, is_correct,
- bookmarked, followup_session_id, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)
+ user_answer, user_answer_images_json, source, material_id,
+ material_title, section_id, section_title, score_trend,
+ is_correct, resolved, bookmarked, followup_session_id,
+ created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '', ?, ?)
ON CONFLICT(session_id, turn_id, question_id) DO UPDATE SET
+ question = excluded.question,
+ question_type = excluded.question_type,
+ options_json = excluded.options_json,
+ correct_answer = excluded.correct_answer,
+ explanation = excluded.explanation,
+ difficulty = excluded.difficulty,
user_answer = excluded.user_answer,
+ source = excluded.source,
+ material_id = excluded.material_id,
+ material_title = excluded.material_title,
+ section_id = excluded.section_id,
+ section_title = excluded.section_title,
+ score_trend = excluded.score_trend,
user_answer_images_json = excluded.user_answer_images_json,
is_correct = excluded.is_correct,
+ resolved = CASE
+ WHEN excluded.is_correct = 1 THEN 1
+ WHEN excluded.is_correct = 0 AND notebook_entries.is_correct = 1 THEN 0
+ ELSE notebook_entries.resolved
+ END,
updated_at = excluded.updated_at
""",
(
@@ -1632,7 +1747,9 @@ class SQLiteSessionStore:
item.get("difficulty") or "",
item.get("user_answer") or "",
images_json,
- 1 if item.get("is_correct") else 0,
+ *provenance,
+ is_correct,
+ 1 if is_correct else 0,
now,
now,
),
@@ -1667,6 +1784,13 @@ class SQLiteSessionStore:
"user_answer": row["user_answer"] or "",
"user_answer_images": images,
"is_correct": bool(row["is_correct"]),
+ "source": (row["source"] or "deep_question") if "source" in keys else "deep_question",
+ "material_id": (row["material_id"] or "") if "material_id" in keys else "",
+ "material_title": (row["material_title"] or "") if "material_title" in keys else "",
+ "section_id": (row["section_id"] or "") if "section_id" in keys else "",
+ "section_title": (row["section_title"] or "") if "section_title" in keys else "",
+ "score_trend": (row["score_trend"] or "new") if "score_trend" in keys else "new",
+ "resolved": bool(row["resolved"]) if "resolved" in keys else bool(row["is_correct"]),
"bookmarked": bool(row["bookmarked"]),
"followup_session_id": row["followup_session_id"] or "",
"ai_judgment": (row["ai_judgment"] or "") if "ai_judgment" in keys else "",
@@ -1702,6 +1826,21 @@ class SQLiteSessionStore:
if query.is_correct is not None:
conditions.append("n.is_correct = ?")
params.append(1 if query.is_correct else 0)
+ if query.source:
+ conditions.append("n.source = ?")
+ params.append(query.source)
+ if query.material_id:
+ conditions.append("n.material_id = ?")
+ params.append(query.material_id)
+ if query.section_id:
+ conditions.append("n.section_id = ?")
+ params.append(query.section_id)
+ if query.resolved is not None:
+ conditions.append("n.resolved = ?")
+ params.append(1 if query.resolved else 0)
+ if query.score_trend:
+ conditions.append("n.score_trend = ?")
+ params.append(query.score_trend)
if query.session_id is not None:
conditions.append("n.session_id = ?")
params.append(query.session_id)
@@ -1753,7 +1892,9 @@ class SQLiteSessionStore:
n.id, n.session_id, COALESCE(s.title, '') AS session_title,
n.turn_id, n.question_id, n.question, n.question_type, n.options_json,
n.correct_answer, n.explanation, n.difficulty,
- n.user_answer, n.user_answer_images_json, n.is_correct, n.bookmarked,
+ n.user_answer, n.user_answer_images_json, n.source, n.material_id,
+ n.material_title, n.section_id, n.section_title, n.score_trend,
+ n.is_correct, n.resolved, n.bookmarked,
n.followup_session_id, n.ai_judgment, n.created_at, n.updated_at
FROM notebook_entries n
LEFT JOIN sessions s ON s.id = n.session_id{join_sql}
@@ -1788,6 +1929,11 @@ class SQLiteSessionStore:
offset: int = 0,
*,
session_id: str | None = None,
+ source: str = "",
+ material_id: str = "",
+ section_id: str = "",
+ resolved: bool | None = None,
+ score_trend: str = "",
search: str = "",
uncategorized: bool = False,
sort: str = "recent",
@@ -1800,6 +1946,11 @@ class SQLiteSessionStore:
uncategorized=uncategorized,
bookmarked=bookmarked,
is_correct=is_correct,
+ source=source,
+ material_id=material_id,
+ section_id=section_id,
+ resolved=resolved,
+ score_trend=score_trend,
search=search,
session_id=session_id,
sort=sort,
@@ -1815,6 +1966,7 @@ class SQLiteSessionStore:
SELECT
COUNT(*) AS total,
COALESCE(SUM(CASE WHEN is_correct = 0 THEN 1 ELSE 0 END), 0) AS wrong,
+ COALESCE(SUM(CASE WHEN is_correct = 0 AND resolved = 0 THEN 1 ELSE 0 END), 0) AS unresolved,
COALESCE(SUM(CASE WHEN bookmarked = 1 THEN 1 ELSE 0 END), 0) AS bookmarked,
COALESCE(SUM(
CASE WHEN NOT EXISTS (
@@ -1826,10 +1978,17 @@ class SQLiteSessionStore:
"""
).fetchone()
if row is None:
- return {"total": 0, "wrong": 0, "bookmarked": 0, "uncategorized": 0}
+ return {
+ "total": 0,
+ "wrong": 0,
+ "unresolved": 0,
+ "bookmarked": 0,
+ "uncategorized": 0,
+ }
return {
"total": int(row["total"]),
"wrong": int(row["wrong"]),
+ "unresolved": int(row["unresolved"]),
"bookmarked": int(row["bookmarked"]),
"uncategorized": int(row["uncategorized"]),
}
@@ -1852,6 +2011,28 @@ class SQLiteSessionStore:
"""Counts behind the bank's filter chips (and the agent's overview)."""
return await self._run(self._question_bank_stats_sync)
+ def _list_question_bank_materials_sync(self) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ rows = conn.execute(
+ """
+ SELECT
+ source,
+ material_id,
+ COALESCE(NULLIF(MAX(material_title), ''), material_id, 'Unnamed material') AS material_title,
+ COUNT(*) AS entry_count,
+ COALESCE(SUM(CASE WHEN is_correct = 0 AND resolved = 0 THEN 1 ELSE 0 END), 0) AS unresolved_count
+ FROM notebook_entries
+ WHERE material_id != ''
+ GROUP BY source, material_id
+ ORDER BY material_title COLLATE NOCASE
+ """
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+ async def list_question_bank_materials(self) -> list[dict[str, Any]]:
+ """Distinct materials for review filters, with wrong-review counts."""
+ return await self._run(self._list_question_bank_materials_sync)
+
def _get_notebook_entry_sync(self, entry_id: int) -> dict[str, Any] | None:
with self._connect() as conn:
row = conn.execute(
@@ -1926,6 +2107,7 @@ class SQLiteSessionStore:
"user_answer",
"is_correct",
"ai_judgment",
+ "resolved",
}
fields = {k: v for k, v in updates.items() if k in allowed}
if not fields:
@@ -1935,6 +2117,8 @@ class SQLiteSessionStore:
fields["bookmarked"] = 1 if fields["bookmarked"] else 0
if "is_correct" in fields:
fields["is_correct"] = 1 if fields["is_correct"] else 0
+ if "resolved" in fields:
+ fields["resolved"] = 1 if fields["resolved"] else 0
set_clause = ", ".join(f"{k} = ?" for k in fields)
values = list(fields.values()) + [entry_id]
with self._connect() as conn:
diff --git a/tests/api/test_book_quiz_attempt_notebook.py b/tests/api/test_book_quiz_attempt_notebook.py
new file mode 100644
index 000000000..31d7ff8fe
--- /dev/null
+++ b/tests/api/test_book_quiz_attempt_notebook.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from fastapi import FastAPI
+from starlette.testclient import TestClient
+
+from deeptutor.api.routers import book as book_router
+from deeptutor.book.models import Progress
+import deeptutor.services.session as session_package
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+
+class _FakeLearningStore:
+ def __init__(self) -> None:
+ self.saved: list[Progress] = []
+
+ def load_progress(self, book_id: str) -> Progress:
+ return Progress(book_id=book_id)
+
+ def save_progress(self, progress: Progress) -> None:
+ self.saved.append(progress)
+
+
+class _FakeResolvedBook:
+ def __init__(self) -> None:
+ question = {
+ "question_id": "q1",
+ "question": "Which chapter?",
+ "question_type": "choice",
+ "options": {"A": "One", "B": "Two"},
+ "correct_answer": "B",
+ "explanation": "The book has two chapters.",
+ "difficulty": "easy",
+ }
+ block = SimpleNamespace(
+ title="Focus check",
+ payload={"questions": [question]},
+ )
+ self.page = SimpleNamespace(
+ id="page-1",
+ title="Page 1",
+ chapter_id="",
+ block_by_id=lambda _: block,
+ )
+ self.book = SimpleNamespace(title="Compiled Book")
+ self.engine = SimpleNamespace(
+ load_book=lambda _: self.book,
+ list_pages=lambda _: [self.page],
+ )
+ self.learning = _FakeLearningStore()
+
+ def load_progress(self, book_id: str) -> Progress:
+ return self.learning.load_progress(book_id)
+
+
+def test_quiz_attempt_syncs_focus_check_to_question_bank(tmp_path, monkeypatch) -> None:
+ store = SQLiteSessionStore(db_path=tmp_path / "sessions.db")
+ resolved = _FakeResolvedBook()
+ monkeypatch.setattr(book_router, "_resolve_book_or_404", lambda _: resolved)
+ monkeypatch.setattr(session_package, "get_sqlite_session_store", lambda: store)
+
+ app = FastAPI()
+ app.include_router(book_router.router, prefix="/api/v1/book")
+
+ payload = {
+ "book_id": "book-1",
+ "page_id": "page-1",
+ "block_id": "block-1",
+ "question_id": "q1",
+ "user_answer": "A",
+ "is_correct": False,
+ }
+ with TestClient(app) as client:
+ response = client.post("/api/v1/book/books/quiz-attempt", json=payload)
+
+ assert response.status_code == 200
+ assert len(resolved.learning.saved) == 1
+ entries = asyncio.run(store.list_notebook_entries(source="immersive_reading"))
+ assert entries["total"] == 1
+ entry = entries["items"][0]
+ assert entry["session_id"] == "book_book-1"
+ assert entry["session_title"] == "Compiled Book"
+ assert entry["question"] == "Which chapter?"
+ assert entry["source"] == "immersive_reading"
+ assert entry["material_id"] == "book-1"
+ assert entry["material_title"] == "Compiled Book"
+ assert entry["section_id"] == "page-1"
+ assert entry["section_title"] == "Page 1"
+ assert entry["score_trend"] == "new"
+ assert entry["resolved"] is False
diff --git a/tests/api/test_question_bank_api.py b/tests/api/test_question_bank_api.py
index 38ec405e0..67742bd97 100644
--- a/tests/api/test_question_bank_api.py
+++ b/tests/api/test_question_bank_api.py
@@ -68,7 +68,13 @@ def _seed(client) -> list[int]:
def test_stats_reports_the_triage_counts(client):
_seed(client)
body = client.get(f"{PREFIX}/stats").json()
- assert body == {"total": 2, "wrong": 1, "bookmarked": 0, "uncategorized": 2}
+ assert body == {
+ "total": 2,
+ "wrong": 1,
+ "unresolved": 1,
+ "bookmarked": 0,
+ "uncategorized": 2,
+ }
def test_listing_carries_each_entry_categories(client):
@@ -92,6 +98,61 @@ def test_search_treats_wildcards_literally(client):
assert underscore["total"] == 1
+def test_review_provenance_filters_resolution_and_materials(client):
+ store: SQLiteSessionStore = client.store
+
+ async def run() -> None:
+ session_id = (await store.create_session(title="Sources"))["id"]
+ await store.upsert_notebook_entries(
+ session_id,
+ [
+ {
+ "turn_id": "t1",
+ "question_id": "q1",
+ "question": "Mastery?",
+ "is_correct": False,
+ "source": "mastery_path",
+ "material_id": "path-1",
+ "material_title": "Algebra",
+ "section_id": "kp-1",
+ },
+ {
+ "turn_id": "t1",
+ "question_id": "q2",
+ "question": "Reading?",
+ "is_correct": True,
+ "source": "immersive_reading",
+ "material_id": "book-1",
+ "material_title": "EPUB",
+ },
+ ],
+ )
+
+ asyncio.run(run())
+
+ mastery = client.get(
+ f"{PREFIX}/entries",
+ params={"source": "mastery_path", "material_id": "path-1", "resolved": "false"},
+ ).json()
+ assert [item["question_id"] for item in mastery["items"]] == ["q1"]
+
+ materials = client.get(f"{PREFIX}/materials").json()
+ assert [(item["material_id"], item["unresolved_count"]) for item in materials] == [
+ ("path-1", 1),
+ ("book-1", 0),
+ ]
+
+ entry_id = mastery["items"][0]["id"]
+ patched = client.patch(f"{PREFIX}/entries/{entry_id}", json={"resolved": True})
+ assert patched.status_code == 200
+ reopened = client.patch(f"{PREFIX}/entries/{entry_id}", json={"resolved": False})
+ assert reopened.status_code == 200
+ unresolved = client.get(
+ f"{PREFIX}/entries", params={"is_correct": "false", "resolved": "false"}
+ ).json()
+ assert [item["id"] for item in unresolved["items"]] == [entry_id]
+
+
def test_uncategorized_filter_is_the_inbox(client):
ids = _seed(client)
category_id = client.post(f"{PREFIX}/categories", json={"name": "Set A"}).json()["id"]
diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.py
index 0bdd120b1..9374584e2 100644
--- a/tests/capabilities/test_mastery_capability.py
+++ b/tests/capabilities/test_mastery_capability.py
@@ -234,6 +234,49 @@ async def test_choice_composer_option_label_still_commits(tmp_path, monkeypatch)
assert answered.user_answer == "选B"
+async def test_mastery_sync_carries_provenance_to_question_bank(tmp_path, monkeypatch) -> None:
+ from deeptutor.capabilities.mastery.tools import (
+ _sync_mastery_attempt_to_question_bank,
+ )
+ import deeptutor.services.session as session_package
+ from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+ store = SQLiteSessionStore(db_path=tmp_path / "sessions.db")
+ monkeypatch.setattr(session_package, "get_sqlite_session_store", lambda: store)
+ await store.create_session(session_id="session-1", title="Mastery")
+ pending = PendingQuestion(
+ question_id="stable-question",
+ knowledge_point_id="kp-1",
+ prompt="Which colour?",
+ question_type="choice",
+ expected_answer="B",
+ options=["A: red", "B: blue"],
+ )
+
+ await _sync_mastery_attempt_to_question_bank(
+ path_id="path-1",
+ session_id="session-1",
+ turn_id="turn-1",
+ pending=pending,
+ user_answer="A",
+ is_correct=False,
+ choice_options={"A": "red", "B": "blue"},
+ correct_answer="B",
+ material_title="Path A",
+ section_title="Primary colours",
+ )
+
+ entries = await store.list_notebook_entries(source="mastery_path")
+ assert entries["total"] == 1
+ entry = entries["items"][0]
+ assert entry["material_id"] == "path-1"
+ assert entry["material_title"] == "Path A"
+ assert entry["section_id"] == "kp-1"
+ assert entry["section_title"] == "Primary colours"
+ assert entry["resolved"] is False
+
+
@pytest.mark.asyncio
async def test_hooks_bind_to_the_open_interaction_not_the_card_id(tmp_path, monkeypatch):
"""A same-round mastery_quiz + ask_user leaves the model's id on the card.
diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py
index ddd4409b3..032cb1e46 100644
--- a/tests/services/session/test_sqlite_store.py
+++ b/tests/services/session/test_sqlite_store.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
from pathlib import Path
import sqlite3
+import time
import pytest
@@ -51,6 +52,77 @@ def test_sqlite_store_migrates_legacy_chat_history_db(tmp_path: Path) -> None:
service._user_data_dir = original_user_dir
+def test_store_migrates_legacy_notebook_review_columns(tmp_path: Path) -> None:
+ db_path = tmp_path / "legacy-notebook.db"
+ now = time.time()
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ title TEXT DEFAULT '',
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL,
+ compressed_summary TEXT DEFAULT '',
+ summary_up_to_msg_id INTEGER DEFAULT 0
+ )
+ """
+ )
+ conn.execute(
+ """
+ CREATE TABLE notebook_entries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT NOT NULL,
+ turn_id TEXT NOT NULL DEFAULT '',
+ question_id TEXT NOT NULL,
+ question TEXT NOT NULL,
+ question_type TEXT DEFAULT '',
+ options_json TEXT DEFAULT '{}',
+ correct_answer TEXT DEFAULT '',
+ explanation TEXT DEFAULT '',
+ difficulty TEXT DEFAULT '',
+ user_answer TEXT DEFAULT '',
+ user_answer_images_json TEXT DEFAULT '[]',
+ is_correct INTEGER DEFAULT 0,
+ bookmarked INTEGER DEFAULT 0,
+ followup_session_id TEXT DEFAULT '',
+ ai_judgment TEXT DEFAULT '',
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL,
+ UNIQUE(session_id, turn_id, question_id)
+ )
+ """
+ )
+ conn.execute(
+ """
+ INSERT INTO notebook_entries (
+ session_id,
+ turn_id,
+ question_id,
+ question,
+ is_correct,
+ created_at,
+ updated_at
+ ) VALUES ('session-1', '', 'q1', 'Legacy?', 0, ?, ?)
+ """,
+ (now, now),
+ )
+ conn.commit()
+
+ store = SQLiteSessionStore(db_path=db_path)
+ listing = asyncio.run(store.list_notebook_entries())
+
+ assert listing["total"] == 1
+ entry = listing["items"][0]
+ assert entry["source"] == "deep_question"
+ assert entry["score_trend"] == "new"
+ assert entry["resolved"] is False
+ assert all(not entry[key] for key in ("material_id", "section_id"))
+ with sqlite3.connect(db_path) as conn:
+ indexes = {row[1] for row in conn.execute("PRAGMA index_list(notebook_entries)")}
+ assert "idx_notebook_entries_review" in indexes
+
+
@pytest.fixture
def store(tmp_path: Path) -> SQLiteSessionStore:
return SQLiteSessionStore(db_path=tmp_path / "test.db")
@@ -166,6 +238,90 @@ def test_list_entries_filters_is_correct(store: SQLiteSessionStore) -> None:
assert wrong["items"][0]["question_id"] == "q1"
+def test_notebook_review_metadata_filters_and_transitions(
+ store: SQLiteSessionStore,
+) -> None:
+ session = asyncio.run(store.create_session(title="Sources"))
+ asyncio.run(
+ store.upsert_notebook_entries(
+ session["id"],
+ [
+ {
+ "question_id": "q1",
+ "question": "Mastery?",
+ "is_correct": False,
+ "source": "mastery_path",
+ "material_id": "path-1",
+ "material_title": "Algebra",
+ "section_id": "kp-1",
+ "section_title": "Equations",
+ },
+ {
+ "question_id": "q2",
+ "question": "Reading?",
+ "is_correct": True,
+ "source": "immersive_reading",
+ "material_id": "book-1",
+ "material_title": "EPUB",
+ "section_id": "page-1",
+ "section_title": "Page 1",
+ },
+ ],
+ )
+ )
+
+ mastery = asyncio.run(
+ store.list_notebook_entries(source="mastery_path", material_id="path-1", section_id="kp-1")
+ )
+ assert mastery["total"] == 1
+ entry = mastery["items"][0]
+ assert entry["score_trend"] == "new"
+ assert entry["resolved"] is False
+ assert asyncio.run(store.question_bank_stats())["unresolved"] == 1
+ assert asyncio.run(store.list_question_bank_materials()) == [
+ {
+ "source": "mastery_path",
+ "material_id": "path-1",
+ "material_title": "Algebra",
+ "entry_count": 1,
+ "unresolved_count": 1,
+ },
+ {
+ "source": "immersive_reading",
+ "material_id": "book-1",
+ "material_title": "EPUB",
+ "entry_count": 1,
+ "unresolved_count": 0,
+ },
+ ]
+
+ eid = entry["id"]
+ assert asyncio.run(store.update_notebook_entry(eid, {"resolved": True}))
+ resolved = asyncio.run(store.list_notebook_entries(resolved=True))
+ assert {item["id"] for item in resolved["items"]} == {eid, entry["id"] + 1}
+
+ retry = {
+ "question_id": "q1",
+ "question": "Mastery?",
+ "is_correct": True,
+ "source": "mastery_path",
+ "material_id": "path-1",
+ "section_id": "kp-1",
+ }
+ asyncio.run(store.upsert_notebook_entries(session["id"], [retry]))
+ improved = asyncio.run(store.list_notebook_entries(score_trend="improved"))["items"][0]
+ assert improved["resolved"] is True
+
+ retry["is_correct"] = False
+ asyncio.run(store.upsert_notebook_entries(session["id"], [retry]))
+ declined = asyncio.run(store.list_notebook_entries(score_trend="declined"))["items"][0]
+ assert declined["resolved"] is False
+
+ asyncio.run(store.upsert_notebook_entries(session["id"], [retry]))
+ unchanged = asyncio.run(store.list_notebook_entries(score_trend="unchanged"))["items"][0]
+ assert unchanged["resolved"] is False
+
+
def test_update_notebook_entry_bookmark_roundtrip(store: SQLiteSessionStore) -> None:
session = asyncio.run(store.create_session())
asyncio.run(store.upsert_notebook_entries(session["id"], _make_items(("q1", "Q?", False))))
diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
index f770f2b7e..6b09da077 100644
--- a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
@@ -92,10 +92,13 @@ export default function QuizBlock({
<div className="space-y-3">
{questions.map((q, idx) => (
<QuizQuestionCard
- key={q.question_id || idx}
+ key={q.question_id || `${block.id}:${idx + 1}`}
index={idx}
question={q}
- previous={lastAttempts.get(q.question_id || "")}
+ questionId={q.question_id || `${block.id}:${idx + 1}`}
+ previous={lastAttempts.get(
+ q.question_id || `${block.id}:${idx + 1}`,
+ )}
onAttempt={(args) => {
if (args.isCorrect === false) setGotSomethingWrong(true);
onAttempt?.(block, args);
@@ -131,11 +134,13 @@ export default function QuizBlock({
function QuizQuestionCard({
index,
question,
+ questionId,
previous,
onAttempt,
}: {
index: number;
question: QuizQuestion;
+ questionId: string;
previous?: QuizAttempt;
onAttempt?: (args: QuizAttemptArgs) => void;
}) {
@@ -165,11 +170,11 @@ function QuizQuestionCard({
// Choice questions grade themselves the moment the answer is revealed.
useEffect(() => {
if (!isChoice || !revealed || !selected || !onAttempt) return;
- const reportKey = `${question.question_id || index}:${selected}`;
+ const reportKey = `${questionId}:${selected}`;
if (reportedRef.current === reportKey) return;
reportedRef.current = reportKey;
onAttempt({
- questionId: question.question_id,
+ questionId,
userAnswer: selected,
isCorrect: selected.toUpperCase() === correctChoiceKey,
});
@@ -178,7 +183,7 @@ function QuizQuestionCard({
revealed,
selected,
onAttempt,
- question.question_id,
+ questionId,
correctChoiceKey,
index,
]);
@@ -186,7 +191,7 @@ function QuizQuestionCard({
const recordSelfGrade = (isCorrect: boolean) => {
setSelfGraded(isCorrect);
onAttempt?.({
- questionId: question.question_id,
+ questionId,
userAnswer: isCorrect ? "self:correct" : "self:incorrect",
isCorrect,
});
diff --git a/web/components/space/question-bank/BankScopeRail.tsx b/web/components/space/question-bank/BankScopeRail.tsx
index 8efedae23..97f92e400 100644
--- a/web/components/space/question-bank/BankScopeRail.tsx
+++ b/web/components/space/question-bank/BankScopeRail.tsx
@@ -1,7 +1,7 @@
"use client";
import { useTranslation } from "react-i18next";
-import { Bookmark, FolderOpen, Inbox, LayoutGrid, XCircle } from "lucide-react";
+import { Bookmark, CheckCircle2, FolderOpen, Inbox, LayoutGrid, XCircle } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import type { NotebookCategory, QuestionBankStats } from "@/lib/notebook-api";
import type { BankScope } from "./useQuestionBank";
@@ -14,13 +14,19 @@ interface BankScopeRailProps {
}
const STATUS_SCOPES: {
- kind: "all" | "wrong" | "bookmarked" | "uncategorized";
+ kind: "all" | "wrong" | "unresolved" | "bookmarked" | "uncategorized";
label: string;
icon: LucideIcon;
count: (stats: QuestionBankStats) => number;
}[] = [
{ kind: "all", label: "All", icon: LayoutGrid, count: (s) => s.total },
{ kind: "wrong", label: "Wrong Only", icon: XCircle, count: (s) => s.wrong },
+ {
+ kind: "unresolved",
+ label: "Needs Review",
+ icon: CheckCircle2,
+ count: (s) => s.unresolved,
+ },
{
kind: "bookmarked",
label: "Bookmarked",
diff --git a/web/components/space/question-bank/BankToolbar.tsx b/web/components/space/question-bank/BankToolbar.tsx
index aeb3ed116..e3c7a8f79 100644
--- a/web/components/space/question-bank/BankToolbar.tsx
+++ b/web/components/space/question-bank/BankToolbar.tsx
@@ -8,16 +8,20 @@ import {
Settings2,
X,
} from "lucide-react";
-import type { BankSort } from "./useQuestionBank";
+import type { AssessmentSource, QuestionBankMaterial, ScoreTrend } from "@/lib/notebook-api";
+import type { BankSort, ReviewFilters } from "./useQuestionBank";
interface BankToolbarProps {
search: string;
sort: BankSort;
refreshing: boolean;
managerOpen: boolean;
+ filters: ReviewFilters;
+ materials: QuestionBankMaterial[];
onSearchChange: (value: string) => void;
onSortChange: (sort: BankSort) => void;
onToggleManager: () => void;
+ onFiltersChange: (filters: ReviewFilters) => void;
}
/**
@@ -31,9 +35,12 @@ export default function BankToolbar({
sort,
refreshing,
managerOpen,
+ filters,
+ materials,
onSearchChange,
onSortChange,
onToggleManager,
+ onFiltersChange,
}: BankToolbarProps) {
const { t } = useTranslation();
@@ -73,6 +80,64 @@ export default function BankToolbar({
{sort === "recent" ? t("Newest first") : t("Oldest first")}
</button>
+ <select
+ value={filters.source}
+ onChange={(event) =>
+ onFiltersChange({
+ ...filters,
+ source: event.target.value as AssessmentSource | "",
+ materialId: "",
+ })
+ }
+ aria-label={t("Source")}
+ className="h-[34px] rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-[12px] text-[var(--foreground)] outline-none"
+ >
+ <option value="">{t("All Sources")}</option>
+ <option value="deep_question">{t("Deep Question")}</option>
+ <option value="mastery_path">{t("Mastery Path")}</option>
+ <option value="immersive_reading">{t("Immersive Reading")}</option>
+ </select>
+
+ <select
+ value={filters.materialId}
+ onChange={(event) =>
+ onFiltersChange({ ...filters, materialId: event.target.value })
+ }
+ aria-label={t("Material")}
+ disabled={materials.length === 0}
+ className="h-[34px] max-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-[12px] text-[var(--foreground)] outline-none disabled:opacity-50"
+ >
+ <option value="">{t("All Materials")}</option>
+ {materials
+ .filter((item) => !filters.source || item.source === filters.source)
+ .map((item) => (
+ <option
+ key={`${item.source}:${item.material_id}`}
+ value={item.material_id}
+ >
+ {item.material_title}
+ </option>
+ ))}
+ </select>
+
+ <select
+ value={filters.scoreTrend}
+ onChange={(event) =>
+ onFiltersChange({
+ ...filters,
+ scoreTrend: event.target.value as ScoreTrend | "",
+ })
+ }
+ aria-label={t("Score Trend")}
+ className="h-[34px] rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-[12px] text-[var(--foreground)] outline-none"
+ >
+ <option value="">{t("All Trends")}</option>
+ <option value="new">{t("First Attempt")}</option>
+ <option value="improved">{t("Improved")}</option>
+ <option value="declined">{t("Declined")}</option>
+ <option value="unchanged">{t("Unchanged")}</option>
+ </select>
+
<button
type="button"
onClick={onToggleManager}
diff --git a/web/components/space/question-bank/QuestionBankSection.tsx b/web/components/space/question-bank/QuestionBankSection.tsx
index 528277d5e..550056dde 100644
--- a/web/components/space/question-bank/QuestionBankSection.tsx
+++ b/web/components/space/question-bank/QuestionBankSection.tsx
@@ -78,8 +78,11 @@ export default function QuestionBankSection() {
sort={bank.sort}
refreshing={bank.refreshing}
managerOpen={managerOpen}
+ filters={bank.reviewFilters}
+ materials={bank.materials}
onSearchChange={bank.setSearchInput}
onSortChange={bank.setSort}
+ onFiltersChange={bank.setReviewFilters}
onToggleManager={() => setManagerOpen((open) => !open)}
/>
@@ -166,6 +169,7 @@ export default function QuestionBankSection() {
disabled={bank.pendingIds.has(entry.id)}
onToggleSelected={() => bank.toggleSelected(entry.id)}
onToggleBookmark={() => void bank.toggleBookmark(entry)}
+ onToggleResolved={() => void bank.toggleResolved(entry)}
onDelete={() => {
if (window.confirm(t("Delete this entry?")))
void bank.removeEntry(entry);
diff --git a/web/components/space/question-bank/QuestionCard.tsx b/web/components/space/question-bank/QuestionCard.tsx
index bd4085e27..fb6623fb6 100644
--- a/web/components/space/question-bank/QuestionCard.tsx
+++ b/web/components/space/question-bank/QuestionCard.tsx
@@ -3,7 +3,15 @@
import dynamic from "next/dynamic";
import Link from "next/link";
import { useTranslation } from "react-i18next";
-import { Bookmark, ExternalLink, MessageSquare, Trash2, X } from "lucide-react";
+import {
+ Bookmark,
+ CheckCheck,
+ ExternalLink,
+ MessageSquare,
+ RotateCcw,
+ Trash2,
+ X,
+} from "lucide-react";
import type { NotebookCategory, NotebookEntry } from "@/lib/notebook-api";
import CategoryMenu from "./CategoryMenu";
@@ -12,6 +20,19 @@ const MarkdownRenderer = dynamic(
{ ssr: false },
);
+const SOURCE_LABELS: Record<NotebookEntry["source"], string> = {
+ deep_question: "Deep Question",
+ mastery_path: "Mastery Path",
+ immersive_reading: "Immersive Reading",
+};
+
+const TREND_LABELS: Record<NotebookEntry["score_trend"], string> = {
+ new: "First Attempt",
+ improved: "Improved",
+ declined: "Declined",
+ unchanged: "Unchanged",
+};
+
interface QuestionCardProps {
entry: NotebookEntry;
categories: NotebookCategory[];
@@ -19,6 +40,7 @@ interface QuestionCardProps {
disabled: boolean;
onToggleSelected: () => void;
onToggleBookmark: () => void;
+ onToggleResolved: () => void;
onDelete: () => void;
onFile: (categoryId: number) => Promise<boolean>;
onUnfile: (categoryId: number) => Promise<boolean>;
@@ -89,6 +111,7 @@ export default function QuestionCard({
disabled,
onToggleSelected,
onToggleBookmark,
+ onToggleResolved,
onDelete,
onFile,
onUnfile,
@@ -148,6 +171,25 @@ export default function QuestionCard({
{entry.question_type}
</span>
)}
+ <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
+ {t(SOURCE_LABELS[entry.source] || "Deep Question")}
+ </span>
+ {entry.score_trend && (
+ <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
+ {t(TREND_LABELS[entry.score_trend] || "First Attempt")}
+ </span>
+ )}
+ {!entry.is_correct && (
+ <span
+ className={`rounded-md px-1.5 py-0.5 text-[10px] font-semibold ${
+ entry.resolved
+ ? "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400"
+ : "bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400"
+ }`}
+ >
+ {entry.resolved ? t("Resolved") : t("Needs Review")}
+ </span>
+ )}
</div>
<div className="text-[14px] font-medium text-[var(--foreground)]">
@@ -184,6 +226,25 @@ export default function QuestionCard({
fill={entry.bookmarked ? "currentColor" : "none"}
/>
</button>
+ {!entry.is_correct && (
+ <button
+ type="button"
+ onClick={onToggleResolved}
+ disabled={disabled}
+ title={entry.resolved ? t("Reopen Review") : t("Mark Resolved")}
+ className={`rounded-lg p-1.5 transition-colors disabled:opacity-40 ${
+ entry.resolved
+ ? "text-green-600 dark:text-green-400"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"
+ }`}
+ >
+ {entry.resolved ? (
+ <RotateCcw className="h-3.5 w-3.5" />
+ ) : (
+ <CheckCheck className="h-3.5 w-3.5" />
+ )}
+ </button>
+ )}
<button
type="button"
onClick={onDelete}
@@ -311,6 +372,25 @@ export default function QuestionCard({
<ExternalLink size={10} />
{entry.session_title || t("Original Session")}
</Link>
+ {entry.source === "immersive_reading" && entry.material_id && (
+ <Link
+ href={`/book?book=${encodeURIComponent(entry.material_id)}${
+ entry.section_id
+ ? `&page=${encodeURIComponent(entry.section_id)}`
+ : ""
+ }`}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ <ExternalLink size={10} />
+ {entry.section_title || entry.material_title || t("Material")}
+ </Link>
+ )}
+ {entry.source === "mastery_path" && entry.material_title && (
+ <span className="inline-flex items-center rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2 py-0.5 text-[var(--muted-foreground)]">
+ {entry.material_title}
+ {entry.section_title ? ` · ${entry.section_title}` : ""}
+ </span>
+ )}
{entry.followup_session_id && (
<Link
href={`/?session=${encodeURIComponent(entry.followup_session_id)}`}
diff --git a/web/components/space/question-bank/useQuestionBank.ts b/web/components/space/question-bank/useQuestionBank.ts
index 170d520ad..cbf754bf9 100644
--- a/web/components/space/question-bank/useQuestionBank.ts
+++ b/web/components/space/question-bank/useQuestionBank.ts
@@ -10,6 +10,7 @@ import {
deleteNotebookEntry,
getQuestionBankStats,
listCategories,
+ listQuestionBankMaterials,
listNotebookEntries,
removeEntryFromCategory,
renameCategory,
@@ -17,6 +18,9 @@ import {
type NotebookCategory,
type NotebookEntry,
type QuestionBankStats,
+ type QuestionBankMaterial,
+ type AssessmentSource,
+ type ScoreTrend,
} from "@/lib/notebook-api";
/**
@@ -28,7 +32,7 @@ import {
* uncategorized" representable when it is not a real thing.
*/
export type BankScope =
- | { kind: "all" | "wrong" | "bookmarked" | "uncategorized" }
+ | { kind: "all" | "wrong" | "unresolved" | "bookmarked" | "uncategorized" }
| { kind: "category"; categoryId: number };
export type BankSort = "recent" | "oldest";
@@ -39,12 +43,28 @@ const SEARCH_DEBOUNCE_MS = 250;
export const DEFAULT_SCOPE: BankScope = { kind: "all" };
-function scopeToFilter(scope: BankScope, search: string, sort: BankSort) {
+export interface ReviewFilters {
+ source: AssessmentSource | "";
+ materialId: string;
+ scoreTrend: ScoreTrend | "";
+}
+
+export function buildQuestionBankFilter(
+ scope: BankScope,
+ filters: ReviewFilters,
+ search: string,
+ sort: BankSort,
+) {
return {
category_id: scope.kind === "category" ? scope.categoryId : undefined,
uncategorized: scope.kind === "uncategorized" || undefined,
bookmarked: scope.kind === "bookmarked" ? true : undefined,
- is_correct: scope.kind === "wrong" ? false : undefined,
+ is_correct:
+ scope.kind === "wrong" || scope.kind === "unresolved" ? false : undefined,
+ source: filters.source || undefined,
+ material_id: filters.materialId || undefined,
+ resolved: scope.kind === "unresolved" ? false : undefined,
+ score_trend: filters.scoreTrend || undefined,
search: search || undefined,
sort,
limit: PAGE_SIZE,
@@ -56,7 +76,9 @@ export interface QuestionBankController {
total: number;
categories: NotebookCategory[];
stats: QuestionBankStats;
+ materials: QuestionBankMaterial[];
scope: BankScope;
+ reviewFilters: ReviewFilters;
sort: BankSort;
searchInput: string;
loading: boolean;
@@ -67,6 +89,7 @@ export interface QuestionBankController {
selectedIds: ReadonlySet<number>;
setScope: (scope: BankScope) => void;
+ setReviewFilters: (filters: ReviewFilters) => void;
setSort: (sort: BankSort) => void;
setSearchInput: (value: string) => void;
refresh: () => Promise<void>;
@@ -79,6 +102,7 @@ export interface QuestionBankController {
// once, as a toast, from inside the hook — the boolean is for the caller's
// own UI decisions (keep the menu open, keep the typed name).
toggleBookmark: (entry: NotebookEntry) => Promise<boolean>;
+ toggleResolved: (entry: NotebookEntry) => Promise<boolean>;
removeEntry: (entry: NotebookEntry) => Promise<boolean>;
fileEntries: (ids: number[], categoryId: number) => Promise<boolean>;
unfileEntries: (ids: number[], categoryId: number) => Promise<boolean>;
@@ -92,10 +116,17 @@ export interface QuestionBankController {
const EMPTY_STATS: QuestionBankStats = {
total: 0,
wrong: 0,
+ unresolved: 0,
bookmarked: 0,
uncategorized: 0,
};
+const EMPTY_FILTERS: ReviewFilters = {
+ source: "",
+ materialId: "",
+ scoreTrend: "",
+};
+
/**
* Owns every piece of question-bank state so the views stay presentational.
*
@@ -111,7 +142,10 @@ export function useQuestionBank(): QuestionBankController {
const [total, setTotal] = useState(0);
const [categories, setCategories] = useState<NotebookCategory[]>([]);
const [stats, setStats] = useState<QuestionBankStats>(EMPTY_STATS);
+ const [materials, setMaterials] = useState<QuestionBankMaterial[]>([]);
const [scope, setScopeState] = useState<BankScope>(DEFAULT_SCOPE);
+ const [reviewFilters, setReviewFiltersState] =
+ useState<ReviewFilters>(EMPTY_FILTERS);
const [sort, setSort] = useState<BankSort>("recent");
const [searchInput, setSearchInput] = useState("");
const [search, setSearch] = useState("");
@@ -142,7 +176,7 @@ export function useQuestionBank(): QuestionBankController {
setError(null);
try {
const response = await listNotebookEntries(
- scopeToFilter(scope, search, sort),
+ buildQuestionBankFilter(scope, reviewFilters, search, sort),
);
if (seq !== requestSeq.current) return;
setItems(response.items);
@@ -166,16 +200,18 @@ export function useQuestionBank(): QuestionBankController {
setRefreshing(false);
}
}
- }, [scope, search, sort]);
+ }, [scope, reviewFilters, search, sort]);
const loadMeta = useCallback(async () => {
- const [nextCategories, nextStats] = await Promise.allSettled([
+ const [nextCategories, nextStats, nextMaterials] = await Promise.allSettled([
listCategories(),
getQuestionBankStats(),
+ listQuestionBankMaterials(),
]);
if (nextCategories.status === "fulfilled")
setCategories(nextCategories.value);
if (nextStats.status === "fulfilled") setStats(nextStats.value);
+ if (nextMaterials.status === "fulfilled") setMaterials(nextMaterials.value);
}, []);
useEffect(() => {
@@ -193,6 +229,10 @@ export function useQuestionBank(): QuestionBankController {
setScopeState(next);
}, []);
+ const setReviewFilters = useCallback((next: ReviewFilters) => {
+ setReviewFiltersState(next);
+ }, []);
+
const refresh = useCallback(async () => {
await Promise.all([loadEntries(), loadMeta()]);
}, [loadEntries, loadMeta]);
@@ -264,6 +304,22 @@ export function useQuestionBank(): QuestionBankController {
[refresh, withPending],
);
+ const toggleResolved = useCallback(
+ async (entry: NotebookEntry) => {
+ const next = !entry.resolved;
+ return withPending([entry.id], async () => {
+ await updateNotebookEntry(entry.id, { resolved: next });
+ setItems((prev) =>
+ prev.map((item) =>
+ item.id === entry.id ? { ...item, resolved: next } : item,
+ ),
+ );
+ await refresh();
+ });
+ },
+ [refresh, withPending],
+ );
+
const removeEntry = useCallback(
async (entry: NotebookEntry) => {
return withPending([entry.id], async () => {
@@ -366,7 +422,9 @@ export function useQuestionBank(): QuestionBankController {
total,
categories,
stats,
+ materials,
scope,
+ reviewFilters,
sort,
searchInput,
loading,
@@ -375,6 +433,7 @@ export function useQuestionBank(): QuestionBankController {
pendingIds,
selectedIds,
setScope,
+ setReviewFilters,
setSort,
setSearchInput,
refresh,
@@ -382,6 +441,7 @@ export function useQuestionBank(): QuestionBankController {
selectAll,
clearSelection,
toggleBookmark,
+ toggleResolved,
removeEntry,
fileEntries,
unfileEntries,
@@ -395,7 +455,9 @@ export function useQuestionBank(): QuestionBankController {
total,
categories,
stats,
+ materials,
scope,
+ reviewFilters,
sort,
searchInput,
loading,
@@ -404,11 +466,13 @@ export function useQuestionBank(): QuestionBankController {
pendingIds,
selectedIds,
setScope,
+ setReviewFilters,
refresh,
toggleSelected,
selectAll,
clearSelection,
toggleBookmark,
+ toggleResolved,
removeEntry,
fileEntries,
unfileEntries,
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index 739105396..d62ce106f 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -208,7 +208,14 @@ export interface NotebookEntry {
difficulty: string;
user_answer: string;
user_answer_images?: NotebookAnswerImage[];
+ source: AssessmentSource;
+ material_id: string;
+ material_title: string;
+ section_id: string;
+ section_title: string;
+ score_trend: ScoreTrend;
is_correct: boolean;
+ resolved: boolean;
bookmarked: boolean;
followup_session_id: string;
/** Latest AI-judge text for this entry; empty when never run. */
@@ -225,6 +232,21 @@ export interface NotebookCategory {
entry_count: number;
}
+export type AssessmentSource =
+ | "deep_question"
+ | "mastery_path"
+ | "immersive_reading";
+
+export type ScoreTrend = "new" | "improved" | "declined" | "unchanged";
+
+export interface QuestionBankMaterial {
+ source: AssessmentSource;
+ material_id: string;
+ material_title: string;
+ entry_count: number;
+ unresolved_count: number;
+}
+
export interface NotebookEntryListResponse {
items: NotebookEntry[];
total: number;
@@ -254,6 +276,11 @@ export interface NotebookEntryFilter {
uncategorized?: boolean;
bookmarked?: boolean;
is_correct?: boolean;
+ source?: AssessmentSource;
+ material_id?: string;
+ section_id?: string;
+ resolved?: boolean;
+ score_trend?: ScoreTrend;
search?: string;
sort?: "recent" | "oldest";
limit?: number;
@@ -271,6 +298,12 @@ export async function listNotebookEntries(
params.set("bookmarked", String(filter.bookmarked));
if (filter.is_correct !== undefined)
params.set("is_correct", String(filter.is_correct));
+ if (filter.source) params.set("source", filter.source);
+ if (filter.material_id) params.set("material_id", filter.material_id);
+ if (filter.section_id) params.set("section_id", filter.section_id);
+ if (filter.resolved !== undefined)
+ params.set("resolved", String(filter.resolved));
+ if (filter.score_trend) params.set("score_trend", filter.score_trend);
if (filter.search) params.set("search", filter.search);
if (filter.sort) params.set("sort", filter.sort);
if (filter.limit !== undefined) params.set("limit", String(filter.limit));
@@ -322,6 +355,7 @@ export async function updateNotebookEntry(
bookmarked?: boolean;
followup_session_id?: string;
ai_judgment?: string;
+ resolved?: boolean;
},
): Promise<void> {
const response = await apiFetch(
@@ -362,6 +396,11 @@ export async function upsertNotebookEntry(data: {
*/
user_answer_images?: NotebookAnswerImageUpload[];
is_correct?: boolean;
+ source?: AssessmentSource;
+ material_id?: string;
+ material_title?: string;
+ section_id?: string;
+ section_title?: string;
}): Promise<NotebookEntry> {
const response = await apiFetch(
apiUrl("/api/v1/question-notebook/entries/upsert"),
@@ -442,6 +481,7 @@ export async function bulkLinkEntriesToCategory(
export interface QuestionBankStats {
total: number;
wrong: number;
+ unresolved: number;
bookmarked: number;
uncategorized: number;
}
@@ -453,6 +493,16 @@ export async function getQuestionBankStats(): Promise<QuestionBankStats> {
return expectJson<QuestionBankStats>(response);
}
+export async function listQuestionBankMaterials(): Promise<
+ QuestionBankMaterial[]
+> {
+ const response = await apiFetch(
+ apiUrl("/api/v1/question-notebook/materials"),
+ { cache: "no-store" },
+ );
+ return expectJson<QuestionBankMaterial[]>(response);
+}
+
export async function removeEntryFromCategory(
entryId: number,
categoryId: number,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 846e8a812..acdae218b 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3402,5 +3402,18 @@
"Tutor threads": "Tutor threads",
"Filter by archive status": "Filter by archive status",
"Active and archived": "Active and archived",
- "Loading conversations": "Loading conversations"
+ "Loading conversations": "Loading conversations",
+ "Needs Review": "Needs Review",
+ "All Sources": "All Sources",
+ "Deep Question": "Deep Question",
+ "All Materials": "All Materials",
+ "Score Trend": "Score Trend",
+ "All Trends": "All Trends",
+ "First Attempt": "First Attempt",
+ "Improved": "Improved",
+ "Declined": "Declined",
+ "Unchanged": "Unchanged",
+ "Resolved": "Resolved",
+ "Mark Resolved": "Mark Resolved",
+ "Reopen Review": "Reopen Review"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 1279f3d24..6ec5942b8 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3402,5 +3402,18 @@
"Tutor threads": "小老师追问",
"Filter by archive status": "按归档状态筛选",
"Active and archived": "进行中与已归档",
- "Loading conversations": "正在加载聊天"
+ "Loading conversations": "正在加载聊天",
+ "Needs Review": "待复习",
+ "All Sources": "全部来源",
+ "Deep Question": "深度提问",
+ "All Materials": "全部材料",
+ "Score Trend": "得分趋势",
+ "All Trends": "全部趋势",
+ "First Attempt": "首次作答",
+ "Improved": "已提升",
+ "Declined": "已下降",
+ "Unchanged": "无变化",
+ "Resolved": "已解决",
+ "Mark Resolved": "标记已解决",
+ "Reopen Review": "重新复习"
}
diff --git a/web/tests/question-bank-filter.test.ts b/web/tests/question-bank-filter.test.ts
new file mode 100644
index 000000000..e340ff17a
--- /dev/null
+++ b/web/tests/question-bank-filter.test.ts
@@ -0,0 +1,27 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { buildQuestionBankFilter } from "@/components/space/question-bank/useQuestionBank";
+
+test("the unresolved view combines wrong answers with review state", () => {
+ const filter = buildQuestionBankFilter(
+ { kind: "unresolved" },
+ { source: "mastery_path", materialId: "path-1", scoreTrend: "declined" },
+ "equation",
+ "oldest",
+ );
+
+ assert.deepEqual(filter, {
+ category_id: undefined,
+ uncategorized: undefined,
+ bookmarked: undefined,
+ is_correct: false,
+ source: "mastery_path",
+ material_id: "path-1",
+ resolved: false,
+ score_trend: "declined",
+ search: "equation",
+ sort: "oldest",
+ limit: 60,
+ });
+});