DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): add server-owned quiz star rewards (#1656)
XZHcd474bc8244e
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.pyindex b19380eb4..d90df1436 100644--- a/deeptutor/api/routers/reading.py+++ b/deeptutor/api/routers/reading.py@@ -456,6 +456,11 @@ async def list_library_materials(if _material_allowed(row.material_id)]membership = catalog.collections_for_materials([row.material_id for row in rows])+ from deeptutor.services.session import get_sqlite_session_store++ reward_totals = await get_sqlite_session_store().reading_quiz_reward_totals(+ [row.material_id for row in rows]+ )materials: list[dict[str, Any]] = []for row in rows:payload = row.to_dict()@@ -463,6 +468,7 @@ async def list_library_materials(size_bytes, unit_count = _content_facts(store, row)payload["size_bytes"] = size_bytespayload["unit_count"] = unit_count+ payload["quiz_stars"] = reward_totals.get(row.material_id, 0)materials.append(payload)# Counts describe every material this account may see, not only the# filtered page and never revoked or unassigned learner material.diff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.pyindex e9fbcee22..1ce80b2ee 100644--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@ -288,6 +288,12 @@ def _material_title(material_id: str) -> str:return str(getattr(manifest, "title", "") or getattr(manifest, "filename", "") or "")+def _assert_quiz_extension_allowed() -> None:+ allowed = allowed_reading_extensions()+ if allowed is not None and "quiz" not in allowed:+ raise HTTPException(status_code=403, detail="This reading extension is not allowed.")++async def _persist_reading_quiz_pending(material_id: str, locator: int, payload: dict[str, Any]) -> None:@@ -308,6 +314,7 @@ async def _persist_reading_quiz_pending(async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) -> dict[str, Any]:try:assert_learning_material(material_id)+ _assert_quiz_extension_allowed()except PermissionError as exc:raise HTTPException(status_code=403, detail=str(exc)) from exc@@ -321,7 +328,8 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->store = get_sqlite_session_store()question_ids = [item.question_id.strip() for item in payload.answers]- pending = await store.get_reading_quiz_pending(material_id, payload.locator, question_ids)+ pending_quiz = await store.get_reading_quiz_pending(material_id, payload.locator)+ pending = {qid: pending_quiz[qid] for qid in question_ids if qid in pending_quiz}missing = [qid for qid in question_ids if qid not in pending]if missing:raise HTTPException(status_code=409, detail="This reading quiz has expired.")@@ -408,7 +416,33 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->"result": result,})- return {"answers": graded}+ response: dict[str, Any] = {"answers": graded}+ current_question_ids = list(pending_quiz)+ best_results = await store.best_reading_quiz_results(+ material_id, payload.locator, current_question_ids+ )+ if current_question_ids and all(+ best_results.get(qid, {}).get("attempted") for qid in current_question_ids+ ):+ stars = max(1, sum(bool(best_results[qid].get("correct")) for qid in current_question_ids))+ response["reward"] = await store.upsert_reading_quiz_reward(+ material_id, payload.locator, stars+ )+ return response++[email protected]("/materials/{material_id}/quiz/rewards")+async def list_quiz_rewards(material_id: str) -> dict[str, Any]:+ try:+ assert_learning_material(material_id)+ _assert_quiz_extension_allowed()+ except PermissionError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc++ from deeptutor.services.session import get_sqlite_session_store++ rewards = await get_sqlite_session_store().list_reading_quiz_rewards(material_id)+ return {"rewards": rewards, "total_stars": sum(row["stars"] for row in rewards)}__all__ = ["router"]diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex a559e2aaa..7e9f12b74 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -429,6 +429,14 @@ class SQLiteSessionStore:PRIMARY KEY (material_id, locator, question_id));+ CREATE TABLE IF NOT EXISTS reading_quiz_rewards (+ material_id TEXT NOT NULL,+ locator INTEGER NOT NULL,+ stars INTEGER NOT NULL,+ updated_at REAL NOT NULL,+ PRIMARY KEY (material_id, locator)+ );+CREATE TABLE IF NOT EXISTS notebook_categories (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL UNIQUE,@@ -811,6 +819,17 @@ class SQLiteSessionStore:)""")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS reading_quiz_rewards (+ material_id TEXT NOT NULL,+ locator INTEGER NOT NULL,+ stars INTEGER NOT NULL,+ updated_at REAL NOT NULL,+ PRIMARY KEY (material_id, locator)+ )+ """+ )@staticmethoddef _migrate_notebook_entry_origins(conn: sqlite3.Connection) -> None:@@ -3498,6 +3517,142 @@ class SQLiteSessionStore:None if question_ids is None else tuple(question_ids),)+ def _best_reading_quiz_results_sync(+ self, material_id: str, locator: int, question_ids: Sequence[str]+ ) -> dict[str, dict[str, bool]]:+ material = str(material_id or "").strip()+ section = str(int(locator))+ wanted = list(dict.fromkeys(str(qid).strip() for qid in question_ids if str(qid).strip()))+ if not material or not wanted:+ return {}+ placeholders = ",".join("?" for _ in wanted)+ with self._connect() as conn:+ query = f"""+ SELECT question_id, assessment_json FROM assessment_attempts+ WHERE source = 'immersive_reading'+ AND question_id IN ({placeholders})+ """ # nosec B608 - fixed SQL columns with bound values+ rows = conn.execute(+ query,+ tuple(wanted),+ ).fetchall()+ results: dict[str, dict[str, bool]] = {}+ for row in rows:+ value = _json_loads(str(row["assessment_json"]), {})+ if not isinstance(value, dict):+ continue+ if str(value.get("material_id") or "") != material:+ continue+ if str(value.get("section_id") or "") != section:+ continue+ question_id = str(row["question_id"])+ correct = str(value.get("result") or "") == "correct"+ current = results.setdefault(question_id, {"attempted": True, "correct": False})+ current["correct"] = current["correct"] or correct+ return results++ async def best_reading_quiz_results(+ self, material_id: str, locator: int, question_ids: Sequence[str]+ ) -> dict[str, dict[str, bool]]:+ """Return the best immutable result for each current quiz question."""+ return await self._run(+ self._best_reading_quiz_results_sync,+ material_id,+ locator,+ tuple(question_ids),+ )++ def _upsert_reading_quiz_reward_sync(+ self, material_id: str, locator: int, stars: int+ ) -> dict[str, Any]:+ material = str(material_id or "").strip()+ normalized_locator = int(locator)+ normalized_stars = max(1, int(stars))+ if not material:+ raise ValueError("material_id is required")+ now = time.time()+ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute(+ "SELECT stars FROM reading_quiz_rewards WHERE material_id = ? AND locator = ?",+ (material, normalized_locator),+ ).fetchone()+ previous = int(row["stars"]) if row is not None else 0+ awarded = normalized_stars > previous+ conn.execute(+ """+ INSERT INTO reading_quiz_rewards (+ material_id, locator, stars, updated_at+ ) VALUES (?, ?, ?, ?)+ ON CONFLICT(material_id, locator) DO UPDATE SET+ stars = excluded.stars,+ updated_at = excluded.updated_at+ WHERE excluded.stars > reading_quiz_rewards.stars+ """,+ (material, normalized_locator, normalized_stars, now),+ )+ conn.commit()+ return {+ "locator": normalized_locator,+ "stars": max(normalized_stars, previous),+ "updated_at": now,+ "awarded": awarded,+ }++ async def upsert_reading_quiz_reward(+ self, material_id: str, locator: int, stars: int+ ) -> dict[str, Any]:+ """Raise, never lower, a chapter's server-owned star watermark."""+ return await self._run(self._upsert_reading_quiz_reward_sync, material_id, locator, stars)++ def _list_reading_quiz_rewards_sync(self, material_id: str) -> list[dict[str, Any]]:+ material = str(material_id or "").strip()+ if not material:+ return []+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT locator, stars, updated_at FROM reading_quiz_rewards "+ "WHERE material_id = ? ORDER BY locator",+ (material,),+ ).fetchall()+ return [+ {+ "locator": int(row["locator"]),+ "stars": int(row["stars"]),+ "updated_at": float(row["updated_at"]),+ }+ for row in rows+ ]++ async def list_reading_quiz_rewards(self, material_id: str) -> list[dict[str, Any]]:+ return await self._run(self._list_reading_quiz_rewards_sync, material_id)++ def _reading_quiz_reward_totals_sync(self, material_ids: Sequence[str]) -> dict[str, int]:+ wanted = list(+ dict.fromkeys(+ str(material_id).strip() for material_id in material_ids if str(material_id).strip()+ )+ )+ if not wanted:+ return {}+ placeholders = ",".join("?" for _ in wanted)+ with self._connect() as conn:+ query = f"""+ SELECT material_id, SUM(stars) AS stars+ FROM reading_quiz_rewards+ WHERE material_id IN ({placeholders})+ GROUP BY material_id+ """ # nosec B608 - fixed SQL columns with bound values+ rows = conn.execute(+ query,+ tuple(wanted),+ ).fetchall()+ return {str(row["material_id"]): int(row["stars"]) for row in rows}++ async def reading_quiz_reward_totals(self, material_ids: Sequence[str]) -> dict[str, int]:+ """Return total reward stars for a library page in one query."""+ return await self._run(self._reading_quiz_reward_totals_sync, tuple(material_ids))+@staticmethoddef _serialize_notebook_entry(row: sqlite3.Row) -> dict[str, Any]:keys = set(row.keys())diff --git a/tests/api/test_reading_quiz_answers.py b/tests/api/test_reading_quiz_answers.pyindex b07139329..46509cadd 100644--- a/tests/api/test_reading_quiz_answers.py+++ b/tests/api/test_reading_quiz_answers.py@@ -96,6 +96,15 @@ def _payload(**overrides) -> dict:return values+def _submit(client: TestClient, payload: dict) -> dict:+ response = client.post(+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",+ json=payload,+ )+ assert response.status_code == 200, response.text+ return response.json()++def test_focus_check_entries_land_in_unified_list(store: SQLiteSessionStore,) -> None:@@ -168,14 +177,101 @@ def test_grading_uses_server_key_not_client_submission(store: SQLiteSessionStoreasyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))payload = _payload(answers=_answers(("q_1", 1)))with TestClient(_build_app(store)) as client:- resp = client.post(- f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",- json=payload,+ body = _submit(client, payload)+ assert body["answers"] == [{"question_id": "q_1", "is_correct": True, "result": "correct"}]+ assert "reward" not in body+ assert asyncio.run(store.list_reading_quiz_rewards(MATERIAL_ID)) == []+++def test_complete_quiz_awards_completion_and_correctness_stars(+ store: SQLiteSessionStore,+) -> None:+ asyncio.run(store.create_session(title="Reading", session_id="reading-session"))+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))+ with TestClient(_build_app(store)) as client:+ first = _submit(client, _payload(answers=_answers(("q_1", 1))))+ assert "reward" not in first++ completed = _submit(+ client,+ _payload(answers=_answers(("q_2", 0)), submission_id="retry-q2"),)- assert resp.status_code == 200- assert resp.json()["answers"] == [- {"question_id": "q_1", "is_correct": True, "result": "correct"}- ]+ assert completed["reward"]["stars"] == 1+ assert completed["reward"]["awarded"] is True++ improved = _submit(+ client,+ _payload(answers=_answers(("q_2", 1)), submission_id="retry-q2-correct"),+ )+ assert improved["reward"]["stars"] == 2+ assert improved["reward"]["awarded"] is True++ lower = _submit(+ client,+ _payload(answers=_answers(("q_2", 0)), submission_id="retry-q2-again"),+ )+ assert lower["reward"]["stars"] == 2+ assert lower["reward"]["awarded"] is False++ rewards = client.get(f"/api/reading/materials/{MATERIAL_ID}/quiz/rewards").json()+ assert rewards == {+ "rewards": [+ {"locator": LOCATOR, "stars": 2, "updated_at": rewards["rewards"][0]["updated_at"]}+ ],+ "total_stars": 2,+ }+++def test_regenerated_quiz_does_not_remove_a_previous_reward(+ store: SQLiteSessionStore,+) -> None:+ asyncio.run(store.create_session(title="Reading", session_id="reading-session"))+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))+ with TestClient(_build_app(store)) as client:+ _submit(client, _payload(submission_id="first"))+ _submit(+ client,+ _payload(answers=_answers(("q_2", 1)), submission_id="first-q2-correct"),+ )++ questions = _quiz_questions()+ for index, question in enumerate(questions):+ question["id"] = f"new:{index}"+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, questions))+ partial = _submit(+ client,+ _payload(answers=_answers(("new:0", 0)), submission_id="new-first"),+ )+ assert "reward" not in partial+ rewards = client.get(f"/api/reading/materials/{MATERIAL_ID}/quiz/rewards").json()+ assert rewards["total_stars"] == 2+++def test_quiz_rewards_require_material_and_extension_access(+ store: SQLiteSessionStore,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asyncio.run(store.upsert_reading_quiz_reward(MATERIAL_ID, LOCATOR, 2))+ with TestClient(_build_app(store)) as client:+ assert client.get(f"/api/reading/materials/{MATERIAL_ID}/quiz/rewards").status_code == 200++ monkeypatch.setattr(+ "deeptutor.api.routers.reading_extensions.assert_learning_material",+ lambda material_id: (_ for _ in ()).throw(PermissionError("not assigned")),+ )+ with TestClient(_build_app(store)) as client:+ assert client.get(f"/api/reading/materials/{MATERIAL_ID}/quiz/rewards").status_code == 403++ monkeypatch.setattr(+ "deeptutor.api.routers.reading_extensions.assert_learning_material",+ lambda material_id: None,+ )+ monkeypatch.setattr(+ "deeptutor.api.routers.reading_extensions.allowed_reading_extensions",+ lambda: {"read_aloud"},+ )+ with TestClient(_build_app(store)) as client:+ assert client.get(f"/api/reading/materials/{MATERIAL_ID}/quiz/rewards").status_code == 403def test_repeat_submission_is_idempotent(store: SQLiteSessionStore) -> None:diff --git a/tests/reading/test_router.py b/tests/reading/test_router.pyindex c00471040..7f36e8baa 100644--- a/tests/reading/test_router.py+++ b/tests/reading/test_router.py@@ -6,6 +6,7 @@ boot every other router; the routes themselves are the real ones.from __future__ import annotations+import asyncioimport iofrom pathlib import Pathimport zipfile@@ -18,6 +19,7 @@ from deeptutor.api.routers import readingfrom deeptutor.learning.storage import LearningStorefrom deeptutor.reading import ReadingCatalogStore, ReadingError, ReadingStorefrom deeptutor.services.path_service import PathService+from deeptutor.services.session import get_sqlite_session_storepymupdf = pytest.importorskip("pymupdf")@@ -801,6 +803,9 @@ def test_library_lists_collection_membership_and_totals(client: TestClient) -> N)assert created.status_code == 201, created.text+ asyncio.run(get_sqlite_session_store().upsert_reading_quiz_reward(shared["material_id"], 1, 3))+ asyncio.run(get_sqlite_session_store().upsert_reading_quiz_reward(shared["material_id"], 2, 2))+payload = client.get("/api/reading/library/materials").json()rows = {row["material_id"]: row for row in payload["materials"]}@@ -811,6 +816,8 @@ def test_library_lists_collection_membership_and_totals(client: TestClient) -> Nassert rows[orphan["material_id"]]["collections"] == []assert rows[shared["material_id"]]["size_bytes"] > 0assert rows[shared["material_id"]]["unit_count"] == len(PAGES)+ assert rows[shared["material_id"]]["quiz_stars"] == 5+ assert rows[orphan["material_id"]]["quiz_stars"] == 0assert payload["counts"]["all"] == 2assert payload["counts"]["unassigned"] == 1diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsxindex 249f83a74..acd5f8445 100644--- a/web/components/reading/ReadingExtensionBar.tsx+++ b/web/components/reading/ReadingExtensionBar.tsx@@ -1,7 +1,16 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { BookOpenText, Loader2, PencilLine, Sparkles, Square, Volume2, X } from "lucide-react";+import {+ BookOpenText,+ Loader2,+ PencilLine,+ Sparkles,+ Square,+ Star,+ Volume2,+ X,+} from "lucide-react";import { useTranslation } from "react-i18next";import { fetchAuthStatus } from "@/lib/auth";import { getOwnLearnerProfile } from "@/lib/profile-api";@@ -17,6 +26,7 @@ import {submitReadingQuizAnswers,type ReadingExtensionManifest,type ReadingExtensionResult,+ type ReadingQuizReward,} from "@/lib/reading-api";import { useReadingActions } from "./reading-actions-context";import Tooltip from "@/shared/ui/Tooltip";@@ -478,6 +488,7 @@ function QuizQuestions({const { t } = useTranslation();const [answers, setAnswers] = useState<Record<string, number>>({});const [verdicts, setVerdicts] = useState<Record<string, boolean>>({});+ const [reward, setReward] = useState<ReadingQuizReward | null>(null);const [saving, setSaving] = useState<Record<string, boolean>>({});const pendingSubmissions = useRef<Record<string, { selected: number; id: string }>>({});@@ -495,10 +506,11 @@ function QuizQuestions({submission_id: submissionId,answers: [{ question_id: questionId, selected_index: choiceIndex }],});- const verdict = results.find((item) => item.question_id === questionId);+ const verdict = results.answers.find((item) => item.question_id === questionId);if (!verdict) throw new Error(t("Failed to save answer. Please try again."));setAnswers((current) => ({ ...current, [key]: choiceIndex }));setVerdicts((current) => ({ ...current, [key]: verdict.is_correct }));+ setReward(results.reward ?? null);delete pendingSubmissions.current[key];} catch (error) {onError(error instanceof Error ? error.message : String(error));@@ -507,57 +519,70 @@ function QuizQuestions({}}- return questions.map((question, index) => {- const key = question.id || String(index);- const selected = answers[key];- const correctChoiceIndex = Number.isInteger(question.correct_choice_index)- ? Number(question.correct_choice_index)- : -1;- const canGrade = correctChoiceIndex >= 0 && correctChoiceIndex < question.choices.length;- if (!canGrade) {- return (- <div key={key} className="mt-3">- <p className="font-medium">{question.prompt}</p>- <ol className="mt-1 list-inside list-[upper-alpha] space-y-0.5 text-[var(--muted-foreground)]">- {question.choices.map((choice) => (- <li key={choice}>{choice}</li>- ))}- </ol>- </div>- );- }- return (- <fieldset key={key} className="mt-3">- <legend className="font-medium">{question.prompt}</legend>- <div className="mt-1 grid gap-1">- {question.choices.map((choice, choiceIndex) => (- <button- key={choice}- type="button"- aria-pressed={selected === choiceIndex}- disabled={Boolean(saving[key])}- onClick={() => {- void persistAnswer(question, index, choiceIndex);- }}- className="rounded-md border border-[var(--border)] px-2 py-1.5 text-left text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] aria-pressed:bg-[var(--muted)] aria-pressed:text-[var(--foreground)]"- >- {String.fromCharCode(65 + choiceIndex)}. {choice}- </button>- ))}- </div>- {selected !== undefined ? (- <p- role="status"- className={`mt-1 font-medium ${- verdicts[key]- ? "text-emerald-600 dark:text-emerald-400"- : "text-amber-600 dark:text-amber-400"- }`}- >- {verdicts[key] ? t("Correct") : t("Incorrect")}- </p>- ) : null}- </fieldset>- );- });+ return (+ <>+ {questions.map((question, index) => {+ const key = question.id || String(index);+ const selected = answers[key];+ const correctChoiceIndex = Number.isInteger(question.correct_choice_index)+ ? Number(question.correct_choice_index)+ : -1;+ const canGrade = correctChoiceIndex >= 0 && correctChoiceIndex < question.choices.length;+ if (!canGrade) {+ return (+ <div key={key} className="mt-3">+ <p className="font-medium">{question.prompt}</p>+ <ol className="mt-1 list-inside list-[upper-alpha] space-y-0.5 text-[var(--muted-foreground)]">+ {question.choices.map((choice) => (+ <li key={choice}>{choice}</li>+ ))}+ </ol>+ </div>+ );+ }+ return (+ <fieldset key={key} className="mt-3">+ <legend className="font-medium">{question.prompt}</legend>+ <div className="mt-1 grid gap-1">+ {question.choices.map((choice, choiceIndex) => (+ <button+ key={choice}+ type="button"+ aria-pressed={selected === choiceIndex}+ disabled={Boolean(saving[key])}+ onClick={() => {+ void persistAnswer(question, index, choiceIndex);+ }}+ className="rounded-md border border-[var(--border)] px-2 py-1.5 text-left text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] aria-pressed:bg-[var(--muted)] aria-pressed:text-[var(--foreground)]"+ >+ {String.fromCharCode(65 + choiceIndex)}. {choice}+ </button>+ ))}+ </div>+ {selected !== undefined ? (+ <p+ role="status"+ className={`mt-1 font-medium ${+ verdicts[key]+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-amber-600 dark:text-amber-400"+ }`}+ >+ {verdicts[key] ? t("Correct") : t("Incorrect")}+ </p>+ ) : null}+ </fieldset>+ );+ })}+ {reward ? (+ <p+ role="status"+ className="mt-3 flex items-center gap-1.5 font-medium text-amber-600 dark:text-amber-400"+ >+ <Star size={14} fill="currentColor" aria-hidden="true" />+ {t("Quiz stars: {{count}}", { count: reward.stars })}+ </p>+ ) : null}+ </>+ );}diff --git a/web/components/reading/library/MaterialLibrary.tsx b/web/components/reading/library/MaterialLibrary.tsxindex e7baa7179..927f7adce 100644--- a/web/components/reading/library/MaterialLibrary.tsx+++ b/web/components/reading/library/MaterialLibrary.tsx@@ -18,6 +18,7 @@ import {Loader2,MoreHorizontal,Search,+ Star,Trash2,X,} from "lucide-react";@@ -357,6 +358,7 @@ function MaterialRow({const preparing =material.status === "processing" || material.status === "queued";const failed = material.status === "failed";+ const quizStars = material.quiz_stars ?? 0;// The file's own identity: what it is called on disk, or where it came from.const identity =@@ -407,6 +409,17 @@ function MaterialRow({{t("Failed")}</span>)}+ {quizStars > 0 && (+ <span+ aria-label={t("Quiz stars: {{count}}", { count: quizStars })}+ className="inline-flex shrink-0 items-center gap-0.5 text-[10px] font-semibold text-amber-600 dark:text-amber-400"+ >+ <Star size={11} fill="currentColor" aria-hidden="true" />+ <span aria-hidden="true" className="tabular-nums">+ {quizStars}+ </span>+ </span>+ )}</span>{/* Narrow screens lose the type and collection columns, so thosefacts lead the second line: they are short and certain, while thediff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex 38b4e1bbc..227d0ec8a 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -396,6 +396,13 @@ export interface ReadingQuizAnswerVerdict {result: "correct" | "incorrect" | "partial" | "ungraded";}+export interface ReadingQuizReward {+ locator: number;+ stars: number;+ updated_at: number;+ awarded: boolean;+}+/*** Persist a reading Focus-Check on the server.*@@ -413,8 +420,14 @@ export async function submitReadingQuizAnswers(submission_id?: string;answers: ReadingQuizAnswer[];},-): Promise<ReadingQuizAnswerVerdict[]> {- const data = await unwrap<{ answers?: ReadingQuizAnswerVerdict[] }>(+): Promise<{+ answers: ReadingQuizAnswerVerdict[];+ reward?: ReadingQuizReward;+}> {+ const data = await unwrap<{+ answers?: ReadingQuizAnswerVerdict[];+ reward?: ReadingQuizReward;+ }>(await apiFetch(apiUrl(`${BASE}/materials/${materialId}/extensions/quiz/answers`),{@@ -435,7 +448,17 @@ export async function submitReadingQuizAnswers(},),);- return data.answers ?? [];+ return { answers: data.answers ?? [], reward: data.reward };+}++export async function listReadingQuizRewards(+ materialId: string,+): Promise<{ rewards: ReadingQuizReward[]; total_stars: number }> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/quiz/rewards`), {+ cache: "no-store",+ }),+ );}/** URL of the original bytes. Served with Range support so pdf.js can stream. */diff --git a/web/lib/reading-workspace-api.ts b/web/lib/reading-workspace-api.tsindex 3612056b5..7be28851d 100644--- a/web/lib/reading-workspace-api.ts+++ b/web/lib/reading-workspace-api.ts@@ -41,6 +41,8 @@ export interface ReadingLibraryMaterial extends LearningOrigin {unit_count?: number;/** Every collection holding this material; empty means unassigned. */collections?: ReadingMaterialCollection[];+ /** Server-owned reading-quiz reward total for this material. */+ quiz_stars?: number;}export interface ReadingMaterialCollection {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex c6167eb21..0acff27bd 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -5270,5 +5270,6 @@"Move this knowledge base with its documents, settings, and indexes. Existing workspace assignments are updated.": "Move this knowledge base with its documents, settings, and indexes. Existing workspace assignments are updated.","Review move": "Review move","{{count}} files · {{bytes}} bytes": "{{count}} files · {{bytes}} bytes",- "Assignments updated: {{names}}": "Assignments updated: {{names}}"+ "Assignments updated: {{names}}": "Assignments updated: {{names}}",+ "Quiz stars: {{count}}": "Quiz stars: {{count}}"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 4312257b3..8cc03ff2f 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -5270,5 +5270,6 @@"Move this knowledge base with its documents, settings, and indexes. Existing workspace assignments are updated.": "连同文档、设置和索引一起移动此知识库。现有工作区分配会同步更新。","Review move": "检查移动详情","{{count}} files · {{bytes}} bytes": "{{count}} 个文件 · {{bytes}} 字节",- "Assignments updated: {{names}}": "将更新以下工作区的分配:{{names}}"+ "Assignments updated: {{names}}": "将更新以下工作区的分配:{{names}}",+ "Quiz stars: {{count}}": "测验星星:{{count}}"}diff --git a/web/tests/reading-extensions.test.ts b/web/tests/reading-extensions.test.tsindex c428066fb..bf77a8e23 100644--- a/web/tests/reading-extensions.test.ts+++ b/web/tests/reading-extensions.test.ts@@ -50,7 +50,7 @@ test("reading quiz answers send only the selected index", () => {assert.match(component, /submitReadingQuizAnswers\(materialId,/);assert.match(component, /selected_index: choiceIndex/);const persistStart = component.indexOf("function persistAnswer");- const persistEnd = component.indexOf("return questions.map", persistStart);+ const persistEnd = component.indexOf("questions.map", persistStart);assert.notEqual(persistStart, -1);assert.notEqual(persistEnd, -1);assert.doesNotMatch(diff --git a/web/tests/reading-quiz-persistence.spec.tsx b/web/tests/reading-quiz-persistence.spec.tsxindex 5e386fccc..5106a4725 100644--- a/web/tests/reading-quiz-persistence.spec.tsx+++ b/web/tests/reading-quiz-persistence.spec.tsx@@ -65,7 +65,9 @@ it("waits for saving, uses the server verdict, and preserves the original locatoanswers: [{ question_id: "quiz-1", selected_index: 1 }],});await act(async () => {- finish([{ question_id: "quiz-1", is_correct: false, result: "incorrect" }]);+ finish({+ answers: [{ question_id: "quiz-1", is_correct: false, result: "incorrect" }],+ });});expect(await screen.findByText("Incorrect")).toBeInTheDocument();expect(answer).not.toBeDisabled();@@ -83,12 +85,24 @@ it("keeps a failed answer retryable without showing a successful grade", async (expect(answer).toHaveAttribute("aria-pressed", "false");expect(answer).not.toBeDisabled();const firstSubmission = vi.mocked(submitReadingQuizAnswers).mock.calls[0][1].submission_id;- vi.mocked(submitReadingQuizAnswers).mockResolvedValueOnce([- { question_id: "quiz-1", is_correct: true, result: "correct" },- ]);+ vi.mocked(submitReadingQuizAnswers).mockResolvedValueOnce({+ answers: [{ question_id: "quiz-1", is_correct: true, result: "correct" }],+ });fireEvent.click(answer);await waitFor(() => expect(submitReadingQuizAnswers).toHaveBeenCalledTimes(2));expect(vi.mocked(submitReadingQuizAnswers).mock.calls[1][1].submission_id).toBe(firstSubmission,);});++it("shows the server-owned reward after the quiz is complete", async () => {+ vi.mocked(submitReadingQuizAnswers).mockResolvedValueOnce({+ answers: [{ question_id: "quiz-1", is_correct: true, result: "correct" }],+ reward: { locator: 4, stars: 1, updated_at: 1, awarded: true },+ });+ render(<ReadingExtensionBar materialId="material-1" locator={4} onError={vi.fn()} />);+ fireEvent.click(await screen.findByRole("button", { name: "Quiz me" }));+ fireEvent.click(await screen.findByRole("button", { name: "B. Atlantic" }));++ expect(await screen.findByText("Quiz stars: 1")).toBeInTheDocument();+});