Skip to content

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

fix(assessment): persist reading answers reliably across learning surfaces

Bingxi Zhao (Frank)fe482d64eb2a
diff --git a/deeptutor/api/routers/question_notebook.py b/deeptutor/api/routers/question_notebook.py
index 68c5abfe8..3c01649e2 100644
--- a/deeptutor/api/routers/question_notebook.py
+++ b/deeptutor/api/routers/question_notebook.py
@@ -12,19 +12,14 @@ import uuid as _uuid
from fastapi import APIRouter, HTTPException, Query, Response
from pydantic import BaseModel, Field
+from deeptutor.core.assessment import AssessmentResult, AssessmentSource
from deeptutor.services.session import get_sqlite_session_store
from deeptutor.services.storage import get_attachment_store
logger = logging.getLogger(__name__)
router = APIRouter()
-AssessmentSource = Literal[
- "deep_question", "mastery_path", "immersive_reading", "book", "partner_chat"
-]
ScoreTrend = Literal["new", "improved", "declined", "unchanged"]
-AssessmentType = Literal["quiz", "focus_check", "qualitative", "review"]
-AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded"]
-
# ── Models ────────────────────────────────────────────────────────
diff --git a/deeptutor/api/routers/reading_extensions.py b/deeptutor/api/routers/reading_extensions.py
index 51785bbb9..5684afa2f 100644
--- a/deeptutor/api/routers/reading_extensions.py
+++ b/deeptutor/api/routers/reading_extensions.py
@@ -7,6 +7,7 @@ import inspect
import logging
import re
from typing import Any
+from uuid import uuid4
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, ConfigDict, Field, ValidationError
@@ -56,7 +57,7 @@ class QuizAnswerItem(BaseModel):
model_config = ConfigDict(extra="ignore")
question_id: str = Field(min_length=1)
- selected_index: int
+ selected_index: int = Field(ge=0)
class QuizAnswersPayload(BaseModel):
@@ -236,17 +237,14 @@ async def _persist_reading_quiz_pending(
questions = payload.get("questions")
if not isinstance(questions, list) or not questions:
return
- try:
- from deeptutor.services.session import get_sqlite_session_store
+ from deeptutor.services.session import get_sqlite_session_store
- await get_sqlite_session_store().put_reading_quiz_pending(material_id, locator, questions)
- except Exception:
- logger.warning(
- "Failed to persist reading quiz keys for material %s locator %s",
- material_id,
- locator,
- exc_info=True,
- )
+ # A regenerated quiz must not reuse q_1 and grade an old card against a new key.
+ quiz_id = uuid4().hex
+ for index, question in enumerate(questions):
+ if isinstance(question, dict):
+ question["id"] = f"{quiz_id}:{index}"
+ await get_sqlite_session_store().put_reading_quiz_pending(material_id, locator, questions)
@router.post("/materials/{material_id}/extensions/quiz/answers")
@@ -271,11 +269,34 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->
if missing:
raise HTTPException(status_code=409, detail="This reading quiz has expired.")
+ # Validate the entire batch before saving any answers.
+ for item in payload.answers:
+ question = pending[item.question_id.strip()]
+ choices = question.get("choices")
+ correct_index = question.get("correct_choice_index")
+ if (
+ not isinstance(choices, list)
+ or type(correct_index) is not int
+ or not 0 <= correct_index < len(choices)
+ ):
+ raise HTTPException(
+ status_code=409, detail="This reading quiz has an invalid answer key."
+ )
+ if item.selected_index >= len(choices):
+ raise HTTPException(status_code=422, detail="Selected answer is outside the choices.")
+
session_id = payload.session_id.strip()
- persist = bool(session_id) and await store.get_session(session_id) is not None
- turn_id = payload.turn_id.strip() or f"loc:{payload.locator}"
section_title = payload.section_title.strip() or payload.source_anchor.strip()
material_title = _material_title(material_id)
+ if session_id:
+ if await store.get_session(session_id) is None:
+ raise HTTPException(status_code=404, detail="Reading session not found.")
+ else:
+ # A notebook container keeps standalone reading quizzes without requiring
+ # the learner to open a conversation first; it holds no invented messages.
+ session_id = f"reading-notebook:{material_id}"
+ await store.ensure_notebook_session(session_id, material_title or "Reading quiz")
+ turn_id = payload.turn_id.strip() or f"reading:{material_id}:loc:{payload.locator}"
graded: list[dict[str, Any]] = []
for item in payload.answers:
question = pending[item.question_id.strip()]
@@ -291,30 +312,29 @@ async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) ->
str(choices[item.selected_index]) if 0 <= item.selected_index < len(choices) else ""
)
correct_text = str(choices[correct_index]) if 0 <= correct_index < len(choices) else ""
- if persist:
- try:
- await record_assessment(
- AssessmentRecord(
- session_id=session_id,
- turn_id=turn_id,
- question_id=item.question_id.strip(),
- question=str(question.get("prompt") or "Reading quiz"),
- question_type="choice",
- options=options,
- user_answer=selected_text,
- correct_answer=correct_text,
- is_correct=is_correct,
- result=result,
- source="immersive_reading",
- assessment_type="focus_check",
- material_id=material_id,
- material_title=material_title,
- section_id=str(payload.locator),
- section_title=section_title,
- )
+ try:
+ await record_assessment(
+ AssessmentRecord(
+ session_id=session_id,
+ turn_id=turn_id,
+ question_id=item.question_id.strip(),
+ question=str(question.get("prompt") or "Reading quiz"),
+ question_type="choice",
+ options=options,
+ user_answer=selected_text,
+ correct_answer=correct_text,
+ is_correct=is_correct,
+ result=result,
+ source="immersive_reading",
+ assessment_type="focus_check",
+ material_id=material_id,
+ material_title=material_title,
+ section_id=str(payload.locator),
+ section_title=section_title,
)
- except RecordAssessmentError as exc:
- raise HTTPException(status_code=500, detail=str(exc)) from exc
+ )
+ except RecordAssessmentError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
graded.append(
{
"question_id": item.question_id.strip(),
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 9ce36f1d1..c577d75db 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -1159,7 +1159,9 @@ class MasteryGradeTool(BaseTool):
attempt_count=getattr(evidence, "attempt_count", 1) if evidence is not None else 1,
hints_used=getattr(evidence, "hints_used", 0) if evidence is not None else 0,
confidence=getattr(evidence, "confidence", None) if evidence is not None else None,
- response_time=getattr(evidence, "response_time", None) if evidence is not None else None,
+ response_time=getattr(evidence, "response_time", None)
+ if evidence is not None
+ else None,
quality=getattr(evidence, "quality", None) if evidence is not None else None,
)
mastered = bool(kp and is_mastered(progress, kp))
diff --git a/deeptutor/core/assessment.py b/deeptutor/core/assessment.py
new file mode 100644
index 000000000..aa67627b2
--- /dev/null
+++ b/deeptutor/core/assessment.py
@@ -0,0 +1,13 @@
+"""Assessment values shared by producers, persistence, and the HTTP API."""
+
+from typing import Literal, get_args
+
+AssessmentSource = Literal[
+ "deep_question", "mastery_path", "immersive_reading", "book", "partner_chat"
+]
+AssessmentType = Literal["quiz", "focus_check", "qualitative", "review"]
+AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded"]
+
+ASSESSMENT_SOURCES = frozenset(get_args(AssessmentSource))
+ASSESSMENT_TYPES = frozenset(get_args(AssessmentType))
+ASSESSMENT_RESULTS = frozenset(get_args(AssessmentResult))
diff --git a/deeptutor/learning/assessment.py b/deeptutor/learning/assessment.py
index 155012521..2fdb99854 100644
--- a/deeptutor/learning/assessment.py
+++ b/deeptutor/learning/assessment.py
@@ -12,21 +12,20 @@ from __future__ import annotations
from hashlib import sha1
import logging
import time
-from typing import Any, Literal
+from typing import Any
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-logger = logging.getLogger(__name__)
-
-AssessmentSource = Literal["deep_question", "mastery_path", "immersive_reading", "book"]
-AssessmentType = Literal["quiz", "focus_check", "qualitative", "review"]
-AssessmentResult = Literal["correct", "incorrect", "partial", "ungraded"]
-
-ASSESSMENT_SOURCES: frozenset[str] = frozenset(
- {"deep_question", "mastery_path", "immersive_reading", "book"}
+from deeptutor.core.assessment import (
+ ASSESSMENT_RESULTS,
+ ASSESSMENT_SOURCES,
+ ASSESSMENT_TYPES,
+ AssessmentResult,
+ AssessmentSource,
+ AssessmentType,
)
-ASSESSMENT_TYPES: frozenset[str] = frozenset({"quiz", "focus_check", "qualitative", "review"})
-ASSESSMENT_RESULTS: frozenset[str] = frozenset({"correct", "incorrect", "partial", "ungraded"})
+
+logger = logging.getLogger(__name__)
class RecordAssessmentError(RuntimeError):
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 84ab8aa4e..35f90f280 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -22,6 +22,7 @@ try: # POSIX is the supported production target; fallback keeps Windows dev usa
except ImportError: # pragma: no cover - exercised only on Windows
fcntl = None # type: ignore[assignment]
+from deeptutor.core.assessment import ASSESSMENT_RESULTS, ASSESSMENT_SOURCES, ASSESSMENT_TYPES
from deeptutor.services.path_service import get_path_service
from deeptutor.services.session.protocol import ActiveTurnConflict
from deeptutor.utils.secret_files import ensure_private_directory, ensure_private_file
@@ -98,11 +99,6 @@ 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", "book", "partner_chat"}
-)
-ASSESSMENT_TYPES = frozenset({"quiz", "focus_check", "qualitative", "review"})
-ASSESSMENT_RESULTS = frozenset({"correct", "incorrect", "partial", "ungraded"})
SCORE_TRENDS = frozenset({"new", "improved", "declined", "unchanged"})
# Stored ``result=''`` is a pre-v2 row: treat it as already graded so wrong
# lists do not swallow ungraded spectacle rows, and old incorrect rows stay
diff --git a/tests/api/test_reading_quiz_answers.py b/tests/api/test_reading_quiz_answers.py
index 1bdc8cff8..fb82f9bae 100644
--- a/tests/api/test_reading_quiz_answers.py
+++ b/tests/api/test_reading_quiz_answers.py
@@ -3,8 +3,7 @@
The endpoint is where browser-graded reading quizzes become durable review
records: the server grades each submission against its own stored answer key
(the browser sends only the chosen index), records ``immersive_reading``
-entries into the unified Question Notebook, and never fabricates data when no
-real conversation exists.
+entries into the unified Question Notebook, and retains standalone quizzes without requiring a chat.
"""
from __future__ import annotations
@@ -137,7 +136,7 @@ def test_focus_check_entries_land_in_unified_list(
assert by_id["q_2"]["user_answer"] == "3"
-def test_no_session_degrades_without_fabricating_data(store: SQLiteSessionStore) -> None:
+def test_no_session_saves_in_a_reading_notebook_container(store: SQLiteSessionStore) -> None:
asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))
with TestClient(_build_app(store)) as client:
resp = client.post(
@@ -147,7 +146,8 @@ def test_no_session_degrades_without_fabricating_data(store: SQLiteSessionStore)
assert resp.status_code == 200
assert resp.json()["answers"][0]["is_correct"] is True
listing = asyncio.run(store.list_notebook_entries())
- assert listing["total"] == 0
+ assert listing["total"] == 2
+ assert {item["session_id"] for item in listing["items"]} == {f"reading-notebook:{MATERIAL_ID}"}
def test_missing_answer_key_is_409(store: SQLiteSessionStore) -> None:
@@ -190,3 +190,68 @@ def test_repeat_submission_is_idempotent(store: SQLiteSessionStore) -> None:
assert first.status_code == second.status_code == 200
listing = asyncio.run(store.list_notebook_entries(session_id="reading-session"))
assert listing["total"] == 2
+
+
[email protected]("selected_index", [-1, 2])
+def test_invalid_selection_does_not_save_any_part_of_batch(store, selected_index):
+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))
+ with TestClient(_build_app(store)) as client:
+ response = client.post(
+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",
+ json=_payload(session_id="", answers=_answers(("q_2", 1), ("q_1", selected_index))),
+ )
+ assert response.status_code == 422
+ assert asyncio.run(store.list_notebook_entries())["total"] == 0
+
+
+def test_missing_explicit_session_is_an_error(store):
+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))
+ with TestClient(_build_app(store)) as client:
+ response = client.post(
+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers", json=_payload()
+ )
+ assert response.status_code == 404
+ assert asyncio.run(store.list_notebook_entries())["total"] == 0
+
+
+def test_invalid_answer_key_is_not_graded(store):
+ questions = _quiz_questions()
+ questions[0]["correct_choice_index"] = -1
+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, questions))
+ with TestClient(_build_app(store)) as client:
+ response = client.post(
+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",
+ json=_payload(session_id=""),
+ )
+ assert response.status_code == 409
+ assert asyncio.run(store.list_notebook_entries())["total"] == 0
+
+
+def test_regenerated_quiz_rejects_the_previous_cards(store):
+ persist = importlib.import_module(
+ "deeptutor.api.routers.reading_extensions"
+ )._persist_reading_quiz_pending
+ first = {"questions": _quiz_questions()}
+ second = {"questions": _quiz_questions()}
+ asyncio.run(persist(MATERIAL_ID, LOCATOR, first))
+ asyncio.run(persist(MATERIAL_ID, LOCATOR, second))
+ old_id = first["questions"][0]["id"]
+ assert old_id != second["questions"][0]["id"]
+ with TestClient(_build_app(store)) as client:
+ response = client.post(
+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",
+ json=_payload(session_id="", answers=_answers((old_id, 1))),
+ )
+ assert response.status_code == 409
+
+
+def test_standalone_submission_retry_keeps_one_container_and_one_record(store):
+ asyncio.run(store.put_reading_quiz_pending(MATERIAL_ID, LOCATOR, _quiz_questions()))
+ with TestClient(_build_app(store)) as client:
+ for _ in range(2):
+ response = client.post(
+ f"/api/reading/materials/{MATERIAL_ID}/extensions/quiz/answers",
+ json=_payload(session_id="", answers=_answers(("q_1", 1))),
+ )
+ assert response.status_code == 200
+ assert asyncio.run(store.list_notebook_entries())["total"] == 1
diff --git a/web/components/reading/ReadingExtensionBar.tsx b/web/components/reading/ReadingExtensionBar.tsx
index a10cc3f3d..c7706d07c 100644
--- a/web/components/reading/ReadingExtensionBar.tsx
+++ b/web/components/reading/ReadingExtensionBar.tsx
@@ -1,34 +1,34 @@
-"use client";
+'use client'
-import { useEffect, useMemo, useState } from "react";
-import { Loader2, Sparkles, Square, Volume2, X } from "lucide-react";
-import { useTranslation } from "react-i18next";
+import { useEffect, useMemo, useState } from 'react'
+import { Loader2, Sparkles, Square, Volume2, X } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
import {
listReadingExtensions,
runReadingExtension,
submitReadingQuizAnswers,
type ReadingExtensionManifest,
type ReadingExtensionResult,
-} from "@/lib/reading-api";
+} from '@/lib/reading-api'
type VocabularyTerm = {
- term: string;
- meaning: string;
- usage: string;
-};
+ term: string
+ meaning: string
+ usage: string
+}
type QuizQuestion = {
- id?: string;
- prompt: string;
- choices: string[];
- correct_choice_index?: number;
-};
+ id?: string
+ prompt: string
+ choices: string[]
+ correct_choice_index?: number
+}
type TranslationResult = {
- translation: string;
- alternatives: string[];
- note: string;
-};
+ translation: string
+ alternatives: string[]
+ note: string
+}
export function ReadingExtensionBar({
materialId,
@@ -38,8 +38,8 @@ export function ReadingExtensionBar({
sessionId,
onError,
}: {
- materialId: string;
- locator: number;
+ materialId: string
+ locator: number
/**
* The unit the selection was made in, when there is one.
*
@@ -47,124 +47,113 @@ export function ReadingExtensionBar({
* server verifies the quote against the text of the unit it is told about
* and 400s when they disagree, so a selection has to travel with its own.
*/
- selectionLocator?: number;
- selection?: string;
- sessionId?: string | null;
- onError: (message: string) => void;
+ selectionLocator?: number
+ selection?: string
+ sessionId?: string | null
+ onError: (message: string) => void
}) {
- const { i18n, t } = useTranslation();
- const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([]);
- const [busy, setBusy] = useState("");
- const [result, setResult] = useState<ReadingExtensionResult | null>(null);
- const [speaking, setSpeaking] = useState(false);
+ const { i18n, t } = useTranslation()
+ const [extensions, setExtensions] = useState<ReadingExtensionManifest[]>([])
+ const [busy, setBusy] = useState('')
+ const [result, setResult] = useState<ReadingExtensionResult | null>(null)
+ const [resultLocator, setResultLocator] = useState(locator)
+ const [speaking, setSpeaking] = useState(false)
function stopSpeaking() {
- window.speechSynthesis?.cancel();
- setSpeaking(false);
+ window.speechSynthesis?.cancel()
+ setSpeaking(false)
}
useEffect(() => {
- let active = true;
+ let active = true
void listReadingExtensions()
- .then((rows) => {
- if (active) setExtensions(rows);
+ .then(rows => {
+ if (active) setExtensions(rows)
+ })
+ .catch(error => {
+ if (active) onError(error instanceof Error ? error.message : String(error))
})
- .catch((error) => {
- if (active)
- onError(error instanceof Error ? error.message : String(error));
- });
return () => {
- active = false;
- };
- }, [onError]);
+ active = false
+ }
+ }, [onError])
// Two effects, because the two things they clean up move on different
// clocks. A result belongs to the document: keyed on `locator` as well, an
// ordinary scroll erased a card the reader was still reading, since
// `locator` is the scroll-derived *viewport* locator.
useEffect(() => {
- setResult(null);
- }, [materialId]);
+ setResult(null)
+ }, [materialId])
// Speech, on the other hand, must stop the moment the reader navigates
// away from the passage being read aloud — so this one keeps both keys.
useEffect(() => {
return () => {
- window.speechSynthesis?.cancel();
- setSpeaking(false);
- };
- }, [locator, materialId]);
+ window.speechSynthesis?.cancel()
+ setSpeaking(false)
+ }
+ }, [locator, materialId])
const actions = useMemo(
- () =>
- extensions.flatMap((extension) =>
- extension.actions.map((action) => ({ extension, action })),
- ),
- [extensions],
- );
+ () => extensions.flatMap(extension => extension.actions.map(action => ({ extension, action }))),
+ [extensions]
+ )
async function run(
extension: ReadingExtensionManifest,
- action: ReadingExtensionManifest["actions"][number],
+ action: ReadingExtensionManifest['actions'][number]
) {
- const key = `${extension.id}:${action.id}`;
- setBusy(key);
+ const key = `${extension.id}:${action.id}`
+ const requestedLocator = selection?.trim() ? (selectionLocator ?? locator) : locator
+ setBusy(key)
try {
- const next = await runReadingExtension(
- materialId,
- extension.id,
- action.id,
- {
- locator: selection?.trim() ? (selectionLocator ?? locator) : locator,
- selection: selection || "",
- locale: i18n.language,
- },
- );
- setResult(next);
- if (next.type === "browser_speech") {
- const text = String(next.payload.text || "");
- if (!("speechSynthesis" in window) || !text) {
- onError(t("No speech voice is available in this browser."));
- return;
+ const next = await runReadingExtension(materialId, extension.id, action.id, {
+ locator: requestedLocator,
+ selection: selection || '',
+ locale: i18n.language,
+ })
+ setResult(next)
+ setResultLocator(requestedLocator)
+ if (next.type === 'browser_speech') {
+ const text = String(next.payload.text || '')
+ if (!('speechSynthesis' in window) || !text) {
+ onError(t('No speech voice is available in this browser.'))
+ return
}
- window.speechSynthesis.cancel();
- const utterance = new SpeechSynthesisUtterance(text);
- utterance.lang = String(next.payload.locale || i18n.language);
- utterance.onend = () => setSpeaking(false);
- utterance.onerror = () => setSpeaking(false);
- window.speechSynthesis.speak(utterance);
- setSpeaking(true);
+ window.speechSynthesis.cancel()
+ const utterance = new SpeechSynthesisUtterance(text)
+ utterance.lang = String(next.payload.locale || i18n.language)
+ utterance.onend = () => setSpeaking(false)
+ utterance.onerror = () => setSpeaking(false)
+ window.speechSynthesis.speak(utterance)
+ setSpeaking(true)
}
} catch (error) {
- onError(error instanceof Error ? error.message : String(error));
+ onError(error instanceof Error ? error.message : String(error))
} finally {
- setBusy("");
+ setBusy('')
}
}
- if (actions.length === 0) return null;
+ if (actions.length === 0) return null
return (
<>
<div className="flex shrink-0 gap-1.5 overflow-x-auto border-b border-[var(--border)] bg-[color-mix(in_srgb,var(--muted)_25%,transparent)] px-2.5 py-2">
{actions.map(({ extension, action }) => {
- const key = `${extension.id}:${action.id}`;
- const needsSelection =
- action.requires.includes("selection") && !selection?.trim();
+ const key = `${extension.id}:${action.id}`
+ const needsSelection = action.requires.includes('selection') && !selection?.trim()
// `busy === key`, not `Boolean(busy)`: an action can take the full
// server timeout, and disabling all six meanwhile is
// indistinguishable from the toolbar being broken.
- const disabled = busy === key || needsSelection;
- const builtInLabel = builtInActionLabel(extension.id, action.id);
+ const disabled = busy === key || needsSelection
+ const builtInLabel = builtInActionLabel(extension.id, action.id)
return (
<button
key={key}
type="button"
disabled={disabled}
- title={
- needsSelection
- ? t("Select text in the document first.")
- : undefined
- }
+ title={needsSelection ? t('Select text in the document first.') : undefined}
onClick={() => void run(extension, action)}
className="inline-flex h-8 min-w-[88px] flex-1 items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2 text-xs font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)] disabled:opacity-50"
>
@@ -173,11 +162,9 @@ export function ReadingExtensionBar({
) : (
<Sparkles size={14} />
)}
- <span className="truncate">
- {builtInLabel ? t(builtInLabel) : action.label}
- </span>
+ <span className="truncate">{builtInLabel ? t(builtInLabel) : action.label}</span>
</button>
- );
+ )
})}
</div>
{speaking ? (
@@ -186,11 +173,11 @@ export function ReadingExtensionBar({
className="flex shrink-0 items-center gap-2 border-b border-[var(--border)] bg-[var(--card)] px-3 py-2 text-xs text-[var(--muted-foreground)]"
>
<Volume2 size={14} />
- <span>{t("Reading aloud")}</span>
+ <span>{t('Reading aloud')}</span>
<button
type="button"
- aria-label={t("Stop reading aloud")}
- title={t("Stop reading aloud")}
+ aria-label={t('Stop reading aloud')}
+ title={t('Stop reading aloud')}
onClick={stopSpeaking}
className="ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md text-[var(--foreground)] transition hover:bg-[var(--muted)]"
>
@@ -198,41 +185,41 @@ export function ReadingExtensionBar({
</button>
</div>
) : null}
- {result && result.type !== "browser_speech" ? (
+ {result && result.type !== 'browser_speech' ? (
<ExtensionResult
result={result}
materialId={materialId}
- locator={selection?.trim() ? (selectionLocator ?? locator) : locator}
+ locator={resultLocator}
sessionId={sessionId}
- closeLabel={t("Close")}
+ closeLabel={t('Close')}
onClose={() => setResult(null)}
onError={onError}
/>
) : null}
</>
- );
+ )
}
function builtInActionLabel(extensionId: string, actionId: string) {
- if (extensionId === "read_aloud" && actionId === "read") {
- return "Read aloud";
+ if (extensionId === 'read_aloud' && actionId === 'read') {
+ return 'Read aloud'
}
- if (extensionId === "guided_learning" && actionId === "guide") {
- return "Guide me";
+ if (extensionId === 'guided_learning' && actionId === 'guide') {
+ return 'Guide me'
}
- if (extensionId === "vocabulary" && actionId === "explain") {
- return "Explain vocabulary";
+ if (extensionId === 'vocabulary' && actionId === 'explain') {
+ return 'Explain vocabulary'
}
- if (extensionId === "quiz" && actionId === "start") {
- return "Quiz me";
+ if (extensionId === 'quiz' && actionId === 'start') {
+ return 'Quiz me'
}
- if (extensionId === "translation" && actionId === "translate_en") {
- return "Translate to English";
+ if (extensionId === 'translation' && actionId === 'translate_en') {
+ return 'Translate to English'
}
- if (extensionId === "translation" && actionId === "translate_zh") {
- return "Translate to Chinese";
+ if (extensionId === 'translation' && actionId === 'translate_zh') {
+ return 'Translate to Chinese'
}
- return "";
+ return ''
}
function ExtensionResult({
@@ -244,44 +231,40 @@ function ExtensionResult({
onClose,
onError,
}: {
- result: ReadingExtensionResult;
- materialId: string;
- locator: number;
- sessionId?: string | null;
- closeLabel: string;
- onClose: () => void;
- onError: (message: string) => void;
+ result: ReadingExtensionResult
+ materialId: string
+ locator: number
+ sessionId?: string | null
+ closeLabel: string
+ onClose: () => void
+ onError: (message: string) => void
}) {
const questions = Array.isArray(result.payload.questions)
? (result.payload.questions as QuizQuestion[])
- : [];
- const items = Array.isArray(result.payload.items)
- ? result.payload.items.map(String)
- : [];
- const steps = Array.isArray(result.payload.steps)
- ? result.payload.steps.map(String)
- : [];
+ : []
+ const items = Array.isArray(result.payload.items) ? result.payload.items.map(String) : []
+ const steps = Array.isArray(result.payload.steps) ? result.payload.steps.map(String) : []
const terms: VocabularyTerm[] = Array.isArray(result.payload.terms)
? result.payload.terms
- .map((row) => {
- if (typeof row !== "object" || row === null) return null;
- const term = row as Partial<VocabularyTerm>;
+ .map(row => {
+ if (typeof row !== 'object' || row === null) return null
+ const term = row as Partial<VocabularyTerm>
return {
- term: String(term.term || ""),
- meaning: String(term.meaning || ""),
- usage: String(term.usage || ""),
- };
+ term: String(term.term || ''),
+ meaning: String(term.meaning || ''),
+ usage: String(term.usage || ''),
+ }
})
.filter((row): row is VocabularyTerm => row !== null)
- : [];
+ : []
const translation: TranslationResult = {
- translation: String(result.payload.translation || ""),
+ translation: String(result.payload.translation || ''),
alternatives: Array.isArray(result.payload.alternatives)
? result.payload.alternatives.map(String)
: [],
- note: String(result.payload.note || ""),
- };
- const body = String(result.payload.body || result.payload.overview || "");
+ note: String(result.payload.note || ''),
+ }
+ const body = String(result.payload.body || result.payload.overview || '')
return (
<section className="relative shrink-0 border-b border-[var(--border)] bg-[var(--card)] px-3 py-3 text-xs text-[var(--foreground)]">
<button
@@ -298,14 +281,10 @@ function ExtensionResult({
) : null}
{body ? <p className="mt-2 whitespace-pre-wrap">{body}</p> : null}
{translation.translation ? (
- <p className="mt-2 whitespace-pre-wrap font-medium">
- {translation.translation}
- </p>
+ <p className="mt-2 whitespace-pre-wrap font-medium">{translation.translation}</p>
) : null}
{translation.note ? (
- <p className="mt-1 text-[var(--muted-foreground)]">
- {translation.note}
- </p>
+ <p className="mt-1 text-[var(--muted-foreground)]">{translation.note}</p>
) : null}
{translation.alternatives.length ? (
<ul className="mt-2 list-disc space-y-1 pl-5 text-[var(--muted-foreground)]">
@@ -336,12 +315,8 @@ function ExtensionResult({
className="border-t border-[var(--border)] pt-2 first:border-t-0 first:pt-0"
>
<dt className="font-medium">{term.term}</dt>
- <dd className="mt-1 text-[var(--muted-foreground)]">
- {term.meaning}
- </dd>
- <dd className="mt-1 text-[var(--muted-foreground)]">
- {term.usage}
- </dd>
+ <dd className="mt-1 text-[var(--muted-foreground)]">{term.meaning}</dd>
+ <dd className="mt-1 text-[var(--muted-foreground)]">{term.usage}</dd>
</div>
))}
</dl>
@@ -356,7 +331,7 @@ function ExtensionResult({
/>
) : null}
</section>
- );
+ )
}
function QuizQuestions({
@@ -366,45 +341,56 @@ function QuizQuestions({
sessionId,
onError,
}: {
- questions: QuizQuestion[];
- materialId: string;
- locator: number;
- sessionId?: string | null;
- onError: (message: string) => void;
+ questions: QuizQuestion[]
+ materialId: string
+ locator: number
+ sessionId?: string | null
+ onError: (message: string) => void
}) {
- const { t } = useTranslation();
- const [answers, setAnswers] = useState<Record<string, number>>({});
+ const { t } = useTranslation()
+ const [answers, setAnswers] = useState<Record<string, number>>({})
+ const [verdicts, setVerdicts] = useState<Record<string, boolean>>({})
+ const [saving, setSaving] = useState<Record<string, boolean>>({})
- function persistAnswer(question: QuizQuestion, index: number, choiceIndex: number) {
- const questionId = question.id || `q_${index + 1}`;
- void submitReadingQuizAnswers(materialId, {
- locator,
- session_id: sessionId || "",
- answers: [{ question_id: questionId, selected_index: choiceIndex }],
- }).catch((error) => {
- onError(error instanceof Error ? error.message : String(error));
- });
+ async function persistAnswer(question: QuizQuestion, index: number, choiceIndex: number) {
+ const questionId = question.id || `q_${index + 1}`
+ const key = question.id || String(index)
+ setSaving(current => ({ ...current, [key]: true }))
+ try {
+ const results = await submitReadingQuizAnswers(materialId, {
+ locator,
+ session_id: sessionId || '',
+ answers: [{ question_id: questionId, selected_index: choiceIndex }],
+ })
+ const verdict = results.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 }))
+ } catch (error) {
+ onError(error instanceof Error ? error.message : String(error))
+ } finally {
+ setSaving(current => ({ ...current, [key]: false }))
+ }
}
return questions.map((question, index) => {
- const key = question.id || String(index);
- const selected = answers[key];
+ 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;
+ : -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) => (
+ {question.choices.map(choice => (
<li key={choice}>{choice}</li>
))}
</ol>
</div>
- );
+ )
}
return (
<fieldset key={key} className="mt-3">
@@ -415,9 +401,9 @@ function QuizQuestions({
key={choice}
type="button"
aria-pressed={selected === choiceIndex}
+ disabled={Boolean(saving[key])}
onClick={() => {
- setAnswers((current) => ({ ...current, [key]: choiceIndex }));
- persistAnswer(question, index, choiceIndex);
+ 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)]"
>
@@ -429,15 +415,15 @@ function QuizQuestions({
<p
role="status"
className={`mt-1 font-medium ${
- selected === correctChoiceIndex
- ? "text-emerald-600 dark:text-emerald-400"
- : "text-amber-600 dark:text-amber-400"
+ verdicts[key]
+ ? 'text-emerald-600 dark:text-emerald-400'
+ : 'text-amber-600 dark:text-amber-400'
}`}
>
- {selected === correctChoiceIndex ? t("Correct") : t("Incorrect")}
+ {verdicts[key] ? t('Correct') : t('Incorrect')}
</p>
) : null}
</fieldset>
- );
- });
+ )
+ })
}
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index b0379a47f..92a341c7f 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -6235,6 +6235,7 @@
"type": "string"
},
"selected_index": {
+ "minimum": 0.0,
"title": "Selected Index",
"type": "integer"
}
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index d867284c9..a818d99fc 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -360,8 +360,8 @@ export interface ReadingQuizAnswerVerdict {
/**
* Persist a reading Focus-Check on the server.
*
- * The browser never sends the answer key — only the chosen index. Instant
- * local feedback stays on the existing quiz card.
+ * The browser sends only the chosen index and shows the server's verdict
+ * after the answer has been saved successfully.
*/
export async function submitReadingQuizAnswers(
materialId: string,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ee969faa8..e89c9f654 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -4071,5 +4071,6 @@
"The Invidious instance could not verify your account. Check the instance and reconnect.": "The Invidious instance could not verify your account. Check the instance and reconnect.",
"Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.",
"The account could not be connected. Please start a new connection.": "The account could not be connected. Please start a new connection.",
- "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate."
+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.",
+ "Failed to save answer. Please try again.": "Failed to save answer. Please try again."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 0ca59a04e..f34cfdb13 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -4071,5 +4071,6 @@
"The Invidious instance could not verify your account. Check the instance and reconnect.": "Invidious 实例暂时无法验证账号,请检查实例后重新关联。",
"Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "授权期间 DeepTutor 登录已失效,请先登录 DeepTutor,再重新关联 Invidious。",
"The account could not be connected. Please start a new connection.": "账号关联失败,请重新发起关联。",
- "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。"
+ "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。",
+ "Failed to save answer. Please try again.": "答案保存失败,请重试。"
}
diff --git a/web/tests/reading-extensions.test.ts b/web/tests/reading-extensions.test.ts
index 56882bd8b..c428066fb 100644
--- a/web/tests/reading-extensions.test.ts
+++ b/web/tests/reading-extensions.test.ts
@@ -140,7 +140,7 @@ test("reading quizzes reveal grading only after the learner answers", () => {
assert.match(component, /correct_choice_index\?: number/);
assert.match(component, /const \[answers, setAnswers\] = useState/);
assert.match(component, /aria-pressed=\{selected === choiceIndex\}/);
- assert.match(component, /selected === correctChoiceIndex/);
+ assert.match(component, /verdicts\[key\]/);
assert.match(component, /t\("Correct"\).*t\("Incorrect"\)/s);
});
diff --git a/web/tests/reading-quiz-persistence.spec.tsx b/web/tests/reading-quiz-persistence.spec.tsx
new file mode 100644
index 000000000..bd1625568
--- /dev/null
+++ b/web/tests/reading-quiz-persistence.spec.tsx
@@ -0,0 +1,82 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, expect, it, vi } from 'vitest'
+import { ReadingExtensionBar } from '@/components/reading/ReadingExtensionBar'
+import { initI18n } from '@/i18n/init'
+import {
+ listReadingExtensions,
+ runReadingExtension,
+ submitReadingQuizAnswers,
+} from '@/lib/reading-api'
+vi.mock('@/lib/reading-api', () => ({
+ listReadingExtensions: vi.fn(),
+ runReadingExtension: vi.fn(),
+ submitReadingQuizAnswers: vi.fn(),
+}))
+initI18n('en')
+beforeEach(() => {
+ vi.mocked(listReadingExtensions).mockResolvedValue([
+ {
+ id: 'quiz',
+ name: 'Quiz',
+ version: '1',
+ protocol_version: '1',
+ actions: [{ id: 'start', label: 'Quiz me', trigger: 'toolbar', requires: [] }],
+ result_types: ['quiz'],
+ },
+ ])
+ vi.mocked(runReadingExtension).mockResolvedValue({
+ type: 'quiz',
+ title: '',
+ message: '',
+ payload: {
+ questions: [
+ {
+ id: 'quiz-1',
+ prompt: 'Which ocean?',
+ choices: ['Pacific', 'Atlantic'],
+ correct_choice_index: 1,
+ },
+ ],
+ },
+ })
+})
+it('waits for saving, uses the server verdict, and preserves the original locator after scrolling', async () => {
+ const onError = vi.fn()
+ let finish!: (value: Awaited<ReturnType<typeof submitReadingQuizAnswers>>) => void
+ vi.mocked(submitReadingQuizAnswers).mockImplementation(
+ () =>
+ new Promise(resolve => {
+ finish = resolve
+ })
+ )
+ const view = render(<ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />)
+ fireEvent.click(await screen.findByRole('button', { name: 'Quiz me' }))
+ const answer = await screen.findByRole('button', { name: 'B. Atlantic' })
+ view.rerender(<ReadingExtensionBar materialId="material-1" locator={9} onError={onError} />)
+ fireEvent.click(answer)
+ expect(answer).toBeDisabled()
+ expect(screen.queryByText('Correct')).not.toBeInTheDocument()
+ expect(submitReadingQuizAnswers).toHaveBeenCalledWith('material-1', {
+ locator: 4,
+ session_id: '',
+ answers: [{ question_id: 'quiz-1', selected_index: 1 }],
+ })
+ await act(async () => {
+ finish([{ question_id: 'quiz-1', is_correct: false, result: 'incorrect' }])
+ })
+ expect(await screen.findByText('Incorrect')).toBeInTheDocument()
+ expect(answer).not.toBeDisabled()
+ expect(onError).not.toHaveBeenCalled()
+})
+it('keeps a failed answer retryable without showing a successful grade', async () => {
+ const onError = vi.fn()
+ vi.mocked(submitReadingQuizAnswers).mockRejectedValueOnce(new Error('Save failed'))
+ render(<ReadingExtensionBar materialId="material-1" locator={4} onError={onError} />)
+ fireEvent.click(await screen.findByRole('button', { name: 'Quiz me' }))
+ const answer = await screen.findByRole('button', { name: 'B. Atlantic' })
+ fireEvent.click(answer)
+ await waitFor(() => expect(onError).toHaveBeenCalledWith('Save failed'))
+ expect(screen.queryByText('Correct')).not.toBeInTheDocument()
+ expect(answer).toHaveAttribute('aria-pressed', 'false')
+ expect(answer).not.toBeDisabled()
+})