keeps the markup one raw HTML block for Markdown.
+ st.markdown(
+ f'
\n{radar_chart_svg(axes)}\n
',
+ unsafe_allow_html=True,
+ )
+
+
+def render_radar_figure(
+ course: StudyPackage,
+ radar: learning_radar.CourseRadar,
+ *,
+ focus_topic_id: str | None = None,
+ limit: int = 6,
+ key: str,
+) -> None:
+ """Draw the chart and its axis caption only, for panels that print their
+ own "No topics have been flagged yet." and sample-data notes."""
+ axes = course_radar_axes(
+ course, radar, focus_topic_id=focus_topic_id, limit=limit
+ )
+ with st.container(key=key):
+ if axes:
+ _render_svg(axes)
+ st.caption(tr("Students stuck per topic"))
+
+
+def render_course_radar_chart(
+ course: StudyPackage,
+ radar: learning_radar.CourseRadar,
+ *,
+ focus_topic_id: str | None = None,
+ limit: int = 6,
+ key: str,
+) -> None:
+ """Draw the course's Learning Radar chart with its captions."""
+ axes = course_radar_axes(
+ course, radar, focus_topic_id=focus_topic_id, limit=limit
+ )
+ with st.container(key=key):
+ if not axes:
+ return
+ _render_svg(axes)
+ st.caption(tr("Students stuck per topic"))
+ if not any(axis.value > 0 for axis in axes):
+ st.caption(tr("No topics have been flagged yet."))
+ if radar.has_sample:
+ st.caption(tr("Includes sample data"))
+
+
+def _finish_write(
+ session_state: MutableMapping[str, Any],
+ course_id: str,
+ result: Any,
+) -> None:
+ """Refresh the counts after a saved change; otherwise show a short notice.
+
+ The stored failure reason may describe the database, so it is not shown.
+ """
+ if result.success:
+ # Show the new count right away instead of waiting for the cache.
+ forget_course_radar(session_state, course_id)
+ st.rerun()
+ st.warning(tr(STUCK_FAILURE_MESSAGE))
+
+
+def render_stuck_buttons(
+ session_state: MutableMapping[str, Any],
+ course_id: str,
+ topic_id: str,
+ user_id: str | None,
+ *,
+ key: str,
+) -> None:
+ """Show the topic's count and one-click buttons to flag or unflag it.
+
+ Without a signed-in user only the count is shown.
+ """
+ radar, user_flags = load_course_radar(session_state, course_id, user_id)
+ st.markdown(tr(radar_count_text(radar.topics.get(topic_id))))
+ if user_id is None:
+ return
+
+ if topic_id in user_flags:
+ st.markdown(tr("You marked this topic."))
+ render_saved_reason(user_flags[topic_id])
+ if st.button(tr("Not stuck anymore"), key=f"{key}_clear"):
+ _finish_write(
+ session_state,
+ course_id,
+ learning_radar.clear_flag(user_id, course_id, topic_id),
+ )
+ return
+
+ st.caption(tr("I'm stuck here because…"))
+ chosen: tuple[str | None] | None = None
+ with st.container(horizontal=True, gap="small", key=f"{key}_stuck_reasons"):
+ for reason in RADAR_REASON_OPTIONS:
+ if st.button(
+ tr(radar_reason_label(reason)),
+ key=f"{key}_{reason if reason is not None else 'no_reason'}",
+ ):
+ chosen = (reason,)
+ if chosen is not None:
+ _finish_write(
+ session_state,
+ course_id,
+ learning_radar.set_flag(user_id, course_id, topic_id, chosen[0]),
+ )
diff --git a/pages/0_Dashboard.py b/pages/0_Dashboard.py
index e7e2409..8d63b3d 100644
--- a/pages/0_Dashboard.py
+++ b/pages/0_Dashboard.py
@@ -5,7 +5,7 @@
import streamlit as st
from models.schemas import StudyPackage
-from services.account_sync import save_course_to_account
+from services.account_sync import SAVE_FAILED_MESSAGE, save_course_to_account
from services.course_state import (
initialize_courses,
remove_course,
@@ -140,7 +140,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
)
st.caption(tr("2 · Upload materials and extract text"))
- st.caption(tr("When you save the course, extracted text and source pages are stored with your account. Original files are not stored."))
+ st.caption(tr("Only the extracted text is saved with your course, not the original file."))
uploaded_file = st.file_uploader(
tr("Upload course materials"),
type=["pdf", "pptx", "txt", "png", "jpg", "jpeg"],
@@ -205,10 +205,6 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
".png", ".jpg", ".jpeg"
}
- st.caption(
- tr(f"Extracted text: {len(extracted_text):,} / 50,000 characters")
- )
-
st.caption(tr("Sources"))
for source in document["sources"]:
page = source["page"]
@@ -227,26 +223,6 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
)
st.caption(tr(f"{source['filename']} · {location}"))
- if "pages" in document:
- page_label = (
- "PPTX slides"
- if document_extension == ".pptx"
- else ("Image" if is_image_document else "PDF pages")
- )
- with st.expander(
- tr(f"{page_label} ({len(document['pages'])})")
- ):
- for page in document["pages"]:
- page_unit = (
- "Slide"
- if document_extension == ".pptx"
- else ("Image" if is_image_document else "Page")
- )
- st.markdown(
- tr(f"**{page_unit} {page['page']}** · "
- f"{len(page['text']):,} characters")
- )
-
with st.expander(tr("Preview extracted text")):
st.text(extracted_text)
@@ -254,6 +230,8 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
"setup_course_name", ""
).strip()
+ if st.session_state.pop("course_save_failed_notice", False):
+ st.warning(tr(SAVE_FAILED_MESSAGE))
if st.session_state.pop("course_generation_notice", False):
st.success(
tr("Topics generated. Review them in Study Hub, "
@@ -287,9 +265,9 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
new_course = StudyPackage.model_validate(
generated["package"]
)
- except ValueError as error:
+ except ValueError:
st.error(
- tr(f"Could not load generated topics: {error}")
+ tr("Couldn't use the generated topics. Try generating them again.")
)
else:
# Retain the material for later question generation.
@@ -304,11 +282,8 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
st.session_state, new_course
)
if sync_outcome is not None and not sync_outcome.success:
- st.warning(
- tr("Course kept in this session but not saved to "
- f"your account: {sync_outcome.message} "
- "Use Save in Study Plan to retry.")
- )
+ # Shown after the rerun below, which would wipe it now.
+ st.session_state["course_save_failed_notice"] = True
st.success(
tr("Topics generated. Review them in Study Hub, "
@@ -319,11 +294,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
if not ai_available:
- st.info(
- tr("AI topic generation is not available on this server "
- "because ANTHROPIC_API_KEY is not configured. The built-in "
- "demo courses still work.")
- )
+ st.info(tr("AI generation is unavailable right now."))
elif not course_name:
st.info(tr("Enter a course name to enable topic generation."))
else:
@@ -434,10 +405,10 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
if not is_demo and st.session_state.get(
f"pending_course_removal_{course.course_id}", False
):
- st.warning(
+ st.warning(tr(
f"Delete {course.course_name}? Its materials and practice "
"progress will be removed from this session."
- )
+ ))
confirmation_columns = st.columns(2)
with confirmation_columns[0]:
cancel_removal = st.button(
diff --git a/pages/1_Study_Hub.py b/pages/1_Study_Hub.py
index 4b70ed9..a210877 100644
--- a/pages/1_Study_Hub.py
+++ b/pages/1_Study_Hub.py
@@ -1,10 +1,11 @@
from services.i18n import tr
import streamlit as st
-from components.knowledge_graph import load_course_radar, radar_count_text
+from components.knowledge_graph import load_course_radar, radar_count_text, radar_display_order
from models.schemas import StudyPackage
from services import learning_radar
from services.account_sync import (
+ SAVE_FAILED_MESSAGE,
render_save_restore_controls,
save_course_to_account,
)
@@ -34,6 +35,7 @@
# Keep scope confirmation separate for each course.
scope_key = f"scope_selection_{course.course_id}"
confirmed_key = f"confirmed_scope_{course.course_id}"
+save_failed_notice_key = f"study_save_failed_notice_{course.course_id}"
# Hydrate widgets on first entry, before their frontend defaults can clear
# the separately saved confirmation. Subsequent edits still require confirmation.
initialised_key = f"scope_initialised_{course.course_id}"
@@ -62,12 +64,16 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
user.user_id if user is not None else None,
)
topic_names = {topic.id: topic.name for topic in course.topics}
+ # Ranked for display first, then cut to three, so neither the order nor the
+ # cut reveals a count hidden by the privacy rule.
most_flagged = [
topic_radar
- for topic_radar in learning_radar.top_hard_topics(radar, limit=3)
- if topic_radar.topic_id in topic_names
- and topic_radar.real_count + topic_radar.sample_count > 0
- ]
+ for topic_radar in radar_display_order(
+ learning_radar.top_hard_topics(radar, limit=max(3, len(radar.topics))),
+ list(topic_names),
+ )
+ if topic_radar.real_count + topic_radar.sample_count > 0
+ ][:3]
with st.container(border=True, key="study_radar_panel"):
st.subheader(tr("Most flagged topics · Top 3"))
@@ -96,8 +102,6 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
)
if radar.has_sample:
st.caption(tr("Includes sample data"))
- if not radar.live:
- st.caption(tr("Live flags are unavailable right now."))
if not course.topics:
@@ -112,7 +116,8 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
with st.container(border=True, key="study_scope_panel"):
st.subheader(tr("Choose your exam scope"))
- selected_topic_ids = st.multiselect(
+ # One click per topic; the value stays a list of topic IDs.
+ selected_topic_ids = st.pills(
tr("Knowledge points"),
options=[topic.id for topic in course.topics],
format_func=lambda topic_id: next(
@@ -120,6 +125,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
for topic in course.topics
if topic.id == topic_id
),
+ selection_mode="multi",
key=scope_key,
)
st.caption(
@@ -133,14 +139,20 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
if not selected_topic_ids:
st.error(tr("Select at least one topic."))
elif len(selected_topic_ids) != len(set(selected_topic_ids)):
- st.error(tr("Duplicate topic IDs are not allowed."))
+ st.error(tr("Each topic can be selected only once."))
elif not set(selected_topic_ids).issubset(valid_topic_ids):
st.error(tr("The selection contains an invalid topic."))
else:
st.session_state[confirmed_key] = selected_topic_ids.copy()
- save_course_to_account(st.session_state, course)
+ sync_outcome = save_course_to_account(st.session_state, course)
+ if sync_outcome is not None and not sync_outcome.success:
+ # Shown after the rerun below, which would wipe it now.
+ st.session_state[save_failed_notice_key] = True
st.rerun()
+if st.session_state.pop(save_failed_notice_key, False):
+ st.warning(tr(SAVE_FAILED_MESSAGE))
+
# A changed selection requires confirmation again.
if st.session_state.get(confirmed_key) != selected_topic_ids:
st.session_state.pop(confirmed_key, None)
@@ -179,10 +191,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
ai_available = generation_available()
if not ai_available:
- st.info(
- tr("AI question generation is not available on this server "
- "because ANTHROPIC_API_KEY is not configured.")
- )
+ st.info(tr("AI generation is unavailable right now."))
if st.button(
tr("Generate questions"),
@@ -211,9 +220,9 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
updated_course = StudyPackage.model_validate(
generated["package"]
)
- except ValueError as error:
+ except ValueError:
st.error(
- tr(f"Could not load generated questions: {error}")
+ tr("Couldn't use the generated questions. Try generating them again.")
)
else:
st.session_state[
@@ -224,11 +233,8 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
st.session_state, updated_course
)
if sync_outcome is not None and not sync_outcome.success:
- st.warning(
- tr("Questions kept in this session but not saved "
- f"to your account: {sync_outcome.message} "
- "Use Save below to retry.")
- )
+ # Shown after the rerun below, which would wipe it now.
+ st.session_state[save_failed_notice_key] = True
# Previous practice used the old question set.
st.session_state.pop(
@@ -243,13 +249,14 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
)
st.caption(
- tr(f"Available questions in confirmed scope: {available_count}")
+ tr(f"{available_count} question ready" if available_count == 1
+ else f"{available_count} questions ready")
)
if available_count:
active = st.session_state.get(f"active_practice_{course.course_id}")
start_label = "Continue practice" if active and "result" not in active else "Start practice"
- if st.button(start_label, type="primary"):
+ if st.button(tr(start_label), type="primary"):
if not active or "result" in active:
stage_practice(st.session_state, course)
else:
@@ -273,7 +280,10 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
pending_count = sum(status_for(course, q.id) == "pending" for q in course.questions)
if pending_count:
- st.caption(f"{pending_count} questions await review before they can be practised.")
+ st.caption(tr(
+ f"{pending_count} new question needs your check" if pending_count == 1
+ else f"{pending_count} new questions need your check"
+ ))
if st.button(tr("Review pending questions"), key=f"open_question_review_{course.course_id}"):
st.session_state[f"question_review_open_{course.course_id}"] = True
with st.expander(tr("Course tools"), expanded=st.session_state.get(f"question_review_open_{course.course_id}", False)):
@@ -282,29 +292,41 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
editable = sorted([q for q in course.questions if status_for(course, q.id) != "superseded"], key=lambda q: status_for(course, q.id) != "pending")
if editable:
by_id = {q.id: q for q in editable}
+ # Plain review labels; questions with no review decision get none.
+ status_labels = {"pending": "Needs check", "approved": "Approved", "flagged": "Flagged"}
+
+ def review_label(qid):
+ text = by_id[qid].question[:100]
+ status = status_labels.get(status_for(course, qid))
+ return f"{tr(status)} · {text}" if status else text
+
question_id = st.selectbox(
tr("Question to review"), list(by_id),
- format_func=lambda qid: f"[{status_for(course, qid)}] {by_id[qid].question[:100]}",
+ format_func=review_label,
key=f"editor_question_{course.course_id}",
)
original = by_id[question_id]
- st.caption(tr("Approve only after checking the answer and explanation. Editing creates a new version; past results stay unchanged. Legacy means no review decision was recorded."))
+ st.caption(tr("Check the answer and explanation before approving; edits never change past results."))
with st.form(f"question_review_{course.course_id}_{question_id}"):
prompt = st.text_area(tr("Question text"), value=original.question)
options = [st.text_input(f"Option {chr(65 + index)}", value=value) for index, value in enumerate(original.options)]
- correct = st.selectbox(tr("Correct answer"), list(range(4)), index=original.correct_index, format_func=lambda i: chr(65+i))
+ correct = st.radio(tr("Correct answer"), list(range(4)), index=original.correct_index, format_func=lambda i: chr(65+i), horizontal=True)
explanation = st.text_area(tr("Explanation"), value=original.explanation)
with st.expander(tr("Question classification (advanced)")):
- dimensions = [None, "computation", "conceptual"]
- dimension = st.selectbox(
+ # "untagged" stands in for None so every radio option is a real value.
+ dimension_labels = {
+ "untagged": "Untagged", "computation": "Computation",
+ "conceptual": "Conceptual understanding",
+ }
+ dimensions = list(dimension_labels)
+ dimension_choice = st.radio(
tr("Learning DNA evidence type"), dimensions,
- index=dimensions.index(original.cognitive_dimension),
- format_func=lambda value: {
- None: "Untagged", "computation": "Computation",
- "conceptual": "Conceptual understanding",
- }[value],
- help="Choose what this question tests. Leave uncertain or mixed questions untagged; this label is not a student ability score.",
+ index=dimensions.index(original.cognitive_dimension or "untagged"),
+ format_func=lambda value: tr(dimension_labels[value]),
+ horizontal=True,
+ help=tr("Choose what this question tests. Leave uncertain or mixed questions untagged; this label is not a student ability score."),
)
+ dimension = None if dimension_choice == "untagged" else dimension_choice
structure = st.text_input(
tr("Practice structure label"), value=original.practice_structure or "", max_chars=80,
help="A task type such as tangent_equation or derivative_at_point. Use the same label for the same task structure; leave uncertain questions blank.",
@@ -321,7 +343,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
save_course(st.session_state, revised)
outcome = save_course_to_account(st.session_state, revised)
if outcome is not None and not outcome.success:
- st.warning(tr("Review kept locally but not saved to your account. Use Save to retry. ") + tr(outcome.message))
+ st.warning(tr(SAVE_FAILED_MESSAGE))
else:
st.session_state[f"question_review_notice_{course.course_id}"] = "Question review saved."
st.rerun()
@@ -355,7 +377,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None:
staged.pop(f"course_document_{course.course_id}", None)
outcome = save_course_to_account(staged, updated)
if outcome is not None and not outcome.success:
- st.error(tr("Material was not deleted from your account. ") + tr(outcome.message))
+ st.error(tr("Couldn't delete the material from your account. Nothing was changed."))
else:
save_course(st.session_state, updated)
st.session_state.pop(f"course_document_{course.course_id}", None)
diff --git a/pages/2_Practice_Center.py b/pages/2_Practice_Center.py
index 1ce556f..6f063b2 100644
--- a/pages/2_Practice_Center.py
+++ b/pages/2_Practice_Center.py
@@ -1,5 +1,6 @@
from services.i18n import tr
from html import escape
+import time
import streamlit as st
@@ -14,36 +15,63 @@
start_focus_controls, answer_controls, checklist, capture_submission,
result_overview, reflection_controls,
)
-from services.practice_insights import session_insights
+from services.practice_insights import focus_question, session_insights
+from services.auth_session import current_user
+from services import learning_radar
+from components.knowledge_graph import load_course_radar, render_topic_radar
from services.learning_flow import install_practice, resume_draft, remember_widget, hydrate_widgets, open_lab
from services.ui_style import apply_app_styles
+try:
+ from components import radar_chart
+except ImportError: # merged later
+ radar_chart = None
+
+# "All missed topics" choice of the review-topic pills; it means no topic filter.
+ALL_MISSED_TOPICS = "__all_missed_topics__"
+
+
+def question_count(count):
+ return tr("1 question") if count == 1 else tr(f"{count} questions")
+
+
def practice_label(records, sid, *, unfinished=False):
"""Human-readable choices; stable session IDs remain internal widget values."""
record = records[sid]
number = list(records).index(sid) + 1
if "session" not in record:
- return f"{number} · Saved practice"
- mode = "Topic practice" if record["session"].mode == "topic" else "Mock exam"
- label = f"{number} · {mode} · {len(record['questions'])} questions"
+ return f"{number} · {tr('Saved practice')}"
+ mode = tr("Topic practice") if record["session"].mode == "topic" else tr("Mock exam")
+ label = f"{number} · {mode} · {question_count(len(record['questions']))}"
result = record.get("result")
if result is not None:
- label += f" · {result['correct_count']}/{result['total_count']} correct"
+ label += " · " + tr(f"{result['correct_count']}/{result['total_count']} correct")
elif unfinished:
- label += " · Unfinished"
+ label += " · " + tr("Unfinished")
return label
+def render_question_heading(number, text):
+ """Paper question card: a two-digit badge beside the question text."""
+ body = "
".join(escape(line, quote=False) for line in text.splitlines())
+ st.markdown(
+ f'
{escape(tr(f"Q{number:02}"))}'
+ f'
{body}
',
+ unsafe_allow_html=True,
+ )
+
+
def submit_practice(course, practice_key):
active = st.session_state[practice_key]
session, questions = active["session"], active["questions"]
if "result" in active:
return
+ hydrate_widgets(st.session_state, active)
answers = {q.id: st.session_state.get(f"answer_{session.session_id}_{q.id}") for q in questions}
try:
result = grade_exam(session, questions, answers)
- except ValueError as error:
- st.session_state["practice_submit_error"] = str(error)
+ except ValueError:
+ st.session_state["practice_submit_error"] = True
return
updated = capture_submission(course, active)
active["result"] = result
@@ -97,32 +125,29 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
st.page_link("pages/1_Study_Hub.py", label=tr("Go to Study Plan"))
st.stop()
-unavailable_count = len(course.questions) - len(available_questions(course))
-if unavailable_count:
- with st.expander(tr("Question availability")):
- st.caption(f"{unavailable_count} pending, flagged or older-version questions are excluded from new practice.")
- st.page_link("pages/1_Study_Hub.py", label="Review questions in Study Plan")
-
practice_key = f"active_practice_{course.course_id}"
active_practice = st.session_state.get(practice_key)
entry_key = f"practice_entry_{course.course_id}"
pending_entry = st.session_state.get(entry_key)
if pending_entry is not None:
target = pending_entry.get("topic_id")
- st.info("Set up a new practice" + (": " + topic_names[target] if target else " for your confirmed topics") + ". Your previous session is kept.")
+ st.info(
+ (tr("New practice: ") + topic_names[target]) if target
+ else tr("New practice for your confirmed topics.")
+ )
if active_practice and st.button(tr("Return to previous session"), key="practice_return_previous"):
st.session_state.pop(entry_key, None)
st.rerun()
st.session_state.pop("priority_ready", None)
drafts = st.session_state.get(f"practice_drafts_{course.course_id}", {})
if drafts:
- with st.expander(f"Unfinished sessions ({len(drafts)})"):
+ with st.expander(tr(f"Unfinished sessions ({len(drafts)})")):
draft_id = st.selectbox(tr("Unfinished session"), list(drafts), format_func=lambda sid: practice_label(drafts, sid, unfinished=True), key=f"draft_choice_{course.course_id}")
st.button(tr("Resume unfinished session"), key=f"resume_draft_{course.course_id}",
on_click=resume_draft, args=(st.session_state, course.course_id, draft_id))
with st.expander(
- "Change settings" if active_practice and pending_entry is None else "Practice settings",
+ tr("Change settings") if active_practice and pending_entry is None else tr("Practice settings"),
expanded=active_practice is None or pending_entry is not None,
):
with st.container(border=True):
@@ -183,8 +208,8 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
confirmed_topic_ids=list(confirmed_topic_ids),
topic_id=topic_id,
)
- except ValueError as error:
- st.error(tr(f"Could not create practice: {error}"))
+ except ValueError:
+ st.error(tr("Could not create practice. Try another topic or check your exam scope in Study Plan."))
else:
install_practice(st.session_state, course.course_id, {
"settings": practice_settings,
@@ -210,75 +235,162 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
st.markdown(f"**{escape(course.course_name)}**")
with overview[1]:
st.caption(tr("Mode"))
- st.markdown(tr(f"**{mode_name}**"))
+ st.markdown(f"**{tr(mode_name)}**")
with overview[2]:
st.caption(tr("Questions"))
- st.markdown(tr(f"**{len(questions)}**"))
+ st.markdown(f"**{len(questions)}**")
if active_practice["warning"]:
- st.warning(active_practice["warning"])
+ st.warning(tr(active_practice["warning"]))
submitted = "result" in active_practice
if not submitted:
- st.subheader(tr("Questions"))
hydrate_widgets(st.session_state, active_practice, force=st.session_state.pop(f"rehydrate_practice_{course.course_id}", False))
- with st.container(key="flight_practice_progress"):
- answered = sum(
- st.session_state.get(f"answer_{session.session_id}_{question.id}") is not None
- for question in questions
- )
- st.progress(answered / len(questions))
- st.caption(tr("Answered") + f" · {answered} / {len(questions)}")
- start_focus_controls(active_practice)
-
- for question_number, question in enumerate(questions, start=1):
- display = display_question(course.course_id, question, st.session_state)
- with st.container(
- border=True,
- key=f"practice_question_{question.id}",
- ):
- st.caption(tr(f"QUESTION {question_number} OF {len(questions)}"))
- st.markdown(f"### {display.question}")
- if display.simplified:
- st.caption(tr("Simplified wording"))
- with st.expander(tr("Show original wording")):
- st.write(question.question)
- for option in question.options:
- st.write(option)
-
- st.radio(
- tr("Choose an answer"),
- options=list(range(len(question.options))),
- format_func=lambda index, options=display.options: (
- options[index]
- ),
- index=None,
- width="stretch",
- key=f"answer_{session.session_id}_{question.id}",
- on_change=remember_widget,
- args=(st.session_state, course.course_id, session.session_id, f"answer_{session.session_id}_{question.id}"),
- )
+ question_index = max(0, min(active_practice.get("worksheet_index", 0), len(questions) - 1))
+ selected_question = questions[question_index]
+ answered = sum(
+ st.session_state.get(f"answer_{session.session_id}_{question.id}") is not None
+ for question in questions
+ )
+ radar_on = learning_radar.radar_enabled(course.course_id)
+ user = current_user(st.session_state) if radar_on else None
+ # The "I'm stuck" choices are only offered to signed-in users of demo courses.
+ offer_stuck = radar_chart is not None and user is not None
+ if session.mode == "topic":
+ paper, margin = st.columns([3, 1], gap="large")
+ visible_questions = [(question_index + 1, selected_question)]
+ else:
+ paper = st.container()
+ margin = None
+ visible_questions = list(enumerate(questions, start=1))
+ with paper, st.container(key="flight_worksheet"):
+ with st.container(key="flight_practice_progress"):
+ st.caption(tr("Question") + f" {question_index + 1:02} / {len(questions):02}" if margin is not None else tr("Questions"))
+ if margin is not None:
+ stops = min(len(questions), 12)
+ current_stop = question_index * (stops - 1) // max(1, len(questions) - 1)
+ markers = "".join(
+ '
✈' if step == current_stop
+ else '
'
+ for step in range(stops)
+ )
+ st.markdown(
+ f'
{markers}
',
+ unsafe_allow_html=True,
+ )
+ else:
+ st.progress(answered / len(questions))
+ st.caption(tr("Answered") + f" · {answered} / {len(questions)}")
+ with st.expander(tr("Focus controls")):
+ start_focus_controls(active_practice)
+
+ paging = margin is not None and len(questions) > 1
+ movement = 0
+ for question_number, question in visible_questions:
+ display = display_question(course.course_id, question, st.session_state)
+ with st.container(
+ border=session.mode == "mock",
+ key=f"practice_question_{question.id}",
+ ):
+ render_question_heading(question_number, display.question)
+ if display.simplified:
+ st.caption(tr("Simplified wording"))
+ with st.expander(tr("Show original wording")):
+ st.write(question.question)
+ for option in question.options:
+ st.write(option)
+
+ st.radio(
+ tr("Choose an answer"),
+ options=list(range(len(question.options))),
+ format_func=lambda index, options=display.options: (
+ f"{chr(ord('A') + index)}. {options[index]}"
+ ),
+ index=None,
+ width="stretch",
+ key=f"answer_{session.session_id}_{question.id}",
+ on_change=remember_widget,
+ args=(st.session_state, course.course_id, session.session_id, f"answer_{session.session_id}_{question.id}"),
+ )
- answer_controls(active_practice, question, course.course_id)
+ answer_controls(active_practice, question, course.course_id)
- if session.mode == "topic" and (hints := hints_for(question)):
+ hints = hints_for(question) if session.mode == "topic" else []
state_key = hint_state_key(session.session_id, question.id)
- shown = st.session_state.get(state_key, 0)
+ shown = st.session_state.get(state_key, 0) if hints else 0
for number, hint in enumerate(hints[:shown], start=1):
st.info(tr(f"Hint {number} of {len(hints)}: {display_text(hint, st.session_state)}"))
- if shown < len(hints) and st.button(
- tr("Show a hint") if shown == 0 else tr("Show next hint"),
- key=f"hint_button_{session.session_id}_{question.id}",
- ):
- st.session_state[state_key] = shown + 1
- remember_widget(st.session_state, course.course_id, session.session_id, state_key)
- st.rerun()
+
+ # Actions under the question: Previous · Hint · Learning Radar · Next.
+ if paging or shown < len(hints) or offer_stuck:
+ with st.container(
+ horizontal=True, horizontal_alignment="distribute",
+ vertical_alignment="center", key=f"paper_actions_{question.id}",
+ ):
+ if paging and st.button(
+ tr("Previous"), icon=":material/arrow_back:", disabled=question_index == 0,
+ key=f"worksheet_previous_{session.session_id}",
+ ):
+ movement = -1
+ if shown < len(hints) and st.button(
+ tr("Hint") if shown == 0 else tr("Next hint"), icon=":material/lightbulb:",
+ key=f"hint_button_{session.session_id}_{question.id}",
+ ):
+ st.session_state[state_key] = shown + 1
+ remember_widget(st.session_state, course.course_id, session.session_id, state_key)
+ st.rerun()
+ if offer_stuck:
+ with st.popover(
+ tr("Learning Radar"), icon=":material/radar:",
+ key=f"practice_radar_menu_{session.session_id}_{question.id}",
+ ):
+ radar_chart.render_stuck_buttons(
+ st.session_state, course.course_id, question.topic_id, user.user_id,
+ key=f"practice_stuck_{session.session_id}_{question.id}",
+ )
+ if paging and st.button(
+ tr("Next"), icon=":material/arrow_forward:", disabled=question_index == len(questions) - 1,
+ key=f"worksheet_next_{session.session_id}",
+ ):
+ movement = 1
+
+ if movement:
+ # A click can still arrive after the button was disabled; stay in range.
+ new_index = max(0, min(len(questions) - 1, question_index + movement))
+ active_practice["worksheet_index"] = new_index
+ timer = active_practice.get("focus_timer", {})
+ if timer.get("since") is not None:
+ focus_question(active_practice, questions[new_index].id, time.monotonic())
+ elif timer:
+ timer["question_id"] = questions[new_index].id
+ st.rerun()
+
+ if margin is not None:
+ with margin, st.container(key="flight_worksheet_margin"):
+ if radar_on:
+ st.subheader(tr("Learning Radar"))
+ radar, _ = load_course_radar(st.session_state, course.course_id, user.user_id if user else None)
+ if radar_chart is not None:
+ # Chart only: the count below already says when sample data is included.
+ radar_chart.render_radar_figure(
+ course, radar, focus_topic_id=selected_question.topic_id, key="practice_radar",
+ )
+ render_topic_radar(radar.topics.get(selected_question.topic_id))
+ if st.button(tr("Explore this topic"), key=f"worksheet_radar_{session.session_id}"):
+ st.session_state[f"graph_pending_focus_{course.course_id}"] = selected_question.topic_id
+ st.switch_page("pages/4_Knowledge_Graph.py")
+ st.divider()
+ topic = next((topic for topic in course.topics if topic.id == selected_question.topic_id), None)
+ if topic is not None:
+ st.subheader(tr("Quick Notes"))
+ st.caption(topic.name)
+ st.write(display_text(topic.summary, st.session_state))
checklist(active_practice)
st.button(tr("Submit answers"), type="primary", on_click=submit_practice, args=(course, practice_key))
- if error := st.session_state.pop("practice_submit_error", None):
- st.error(tr(f"Could not grade practice: {error}"))
+ if st.session_state.pop("practice_submit_error", None):
+ st.error(tr("Could not grade this practice. Please try again."))
if "result" in active_practice:
result = active_practice["result"]
@@ -305,7 +417,7 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
next_question = next((q for q in questions if q.id in missed_ids), questions[0])
with st.container(border=True, key="flight_next_topic"):
st.caption(tr("Take the next step"))
- st.markdown(f"**{escape(topic_names.get(next_question.topic_id, next_question.topic_id))}**")
+ st.markdown(f"**{escape(topic_names.get(next_question.topic_id, tr('Topic')))}**")
if next_question.topic_id in topic_names and st.button(
tr("Open this topic in Knowledge Map"), key=f"flight_map_{session.session_id}",
icon=":material/hub:",
@@ -332,13 +444,18 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
st.warning(tr("This result could not be prepared for mistake review."))
if missed:
st.markdown(tr("**Review missed questions**"))
- st.caption(tr(f"{len(missed)} incorrect or unanswered questions. A review creates a new graded session; your original score is preserved."))
+ st.caption(
+ tr("1 missed question to practise; your score stays the same.") if len(missed) == 1
+ else tr(f"{len(missed)} missed questions to practise; your score stays the same.")
+ )
missed_topics = list(dict.fromkeys(q.topic_id for q in missed if q.topic_id in confirmed_topic_ids))
- review_topic = st.selectbox(
- tr("Review topic"), [None, *missed_topics],
- format_func=lambda value: tr("All missed topics") if value is None else topic_names[value],
+ review_choice = st.pills(
+ tr("Review topic"), [ALL_MISSED_TOPICS, *missed_topics], default=ALL_MISSED_TOPICS,
+ format_func=lambda value: tr("All missed topics") if value == ALL_MISSED_TOPICS else topic_names[value],
key=f"mistake_topic_{course.course_id}_{session.session_id}",
)
+ # No pill, or the "All missed topics" pill, keeps every missed topic.
+ review_topic = None if review_choice in (None, ALL_MISSED_TOPICS) else review_choice
st.button(
tr("Practise missed questions"), type="secondary" if guided_review_available else "primary",
key=f"review_mistakes_{session.session_id}",
@@ -361,8 +478,7 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
border=True,
key=f"practice_review_{question.id}",
):
- st.caption(tr(f"QUESTION {question_number}"))
- st.markdown(f"### {display.question}")
+ render_question_heading(question_number, display.question)
if display.simplified:
st.caption(tr("Simplified wording"))
with st.expander(tr("Show original wording")):
@@ -403,16 +519,11 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids
for page, text in sources:
st.caption(tr(f"Page / slide {page}"))
st.text(text, width="stretch")
- else:
- st.caption(tr("Source text is not available in this session; check the original material."))
- else:
- st.caption(tr("No source page was provided for this question."))
-# Show the number of graded sessions saved for this course.
+# Graded sessions saved for this course can be reopened.
history_key = f"practice_history_{course.course_id}"
history = st.session_state.get(history_key, {})
-st.caption(tr(f"Saved practice sessions: {len(history)}"))
if history:
with st.expander(tr("Review a saved session")):
saved_sid = st.selectbox(tr("Saved session"), list(history), format_func=lambda sid: practice_label(history, sid), key=f"saved_session_{course.course_id}")
diff --git a/pages/3_Performance.py b/pages/3_Performance.py
index 5511ff4..2a4eb3e 100644
--- a/pages/3_Performance.py
+++ b/pages/3_Performance.py
@@ -51,8 +51,8 @@
sessions=sessions,
questions=list(questions_by_id.values()),
)
-except ValueError as error:
- st.error(tr(f"Could not calculate performance: {error}"))
+except ValueError:
+ st.error(tr("Couldn't calculate your progress from this practice history."))
st.stop()
mode_label = st.radio(
@@ -189,10 +189,6 @@
"in the selected mode. "
"Below 60%: Weak · 60–79.99%: Developing · 80% or above: Mastered."
) )
- st.caption(
- tr("Signed-in users' saved practice records can be restored across sessions. "
- "Unsaved records remain in the current session only.")
- )
if st.button(tr("Start practice"), type="primary"):
from services.learning_flow import stage_practice
stage_practice(st.session_state, course)
diff --git a/pages/4_Knowledge_Graph.py b/pages/4_Knowledge_Graph.py
index b521129..9c40fca 100644
--- a/pages/4_Knowledge_Graph.py
+++ b/pages/4_Knowledge_Graph.py
@@ -3,20 +3,16 @@
import streamlit as st
from components.knowledge_graph import (
- RADAR_REASON_OPTIONS,
concept_lab_available,
render_knowledge_graph,
- forget_course_radar,
get_selected_topic_details,
load_course_radar,
radar_node_badges,
- radar_reason_label,
render_radar_panel,
- render_reason_hint,
- render_saved_reason,
render_topic_details,
render_topic_radar,
)
+from components.radar_chart import render_stuck_buttons
from services import learning_radar
from services.account_sync import save_course_to_account
from services.ai_service import generate_relationships
@@ -57,7 +53,7 @@
demo_path.read_text(encoding="utf-8")
)
except (OSError, ValueError) as error:
- st.error(tr(f"Could not update the Calculus demo course: {error}"))
+ st.error(tr("Couldn't load the Calculus demo course. Try again later."))
st.stop()
topic_ids = {topic.id for topic in course.topics}
@@ -71,7 +67,8 @@
with st.container(key="graph_course_heading"):
st.subheader(course.course_name)
- st.caption(tr(f"{len(course.topics)} knowledge points"))
+ topic_count = len(course.topics)
+ st.caption(tr(f"{topic_count} knowledge point" if topic_count == 1 else f"{topic_count} knowledge points"))
if not course.topics:
st.info(tr("This course has no topics yet."))
@@ -99,7 +96,6 @@
help=tr("Show only this topic and its directly connected neighbors."),
)
view_course = local_graph(course, focus_id) if focus_id and local_view else course
-st.caption(tr(f"Showing {len(view_course.topics)} of {len(course.topics)} topics · Connections: {len(view_course.relationships)}"))
reset_key = f"graph_view_reset_{course.course_id}_{mode}"
zoom_key = f"graph_zoom_{course.course_id}_{mode}"
@@ -145,17 +141,16 @@
questions=list(questions_by_id.values()),
)
except ValueError as error:
- st.error(tr(f"Could not calculate mastery: {error}"))
+ st.error(tr("Couldn't calculate your progress from this practice history."))
st.stop()
# Learning Radar (demo courses only). Zooming and selecting topics rerun the
# page, so the course radar and the user's flags are reused for a short time.
radar = None
radar_user = None
-radar_user_flags = {}
if learning_radar.radar_enabled(course.course_id):
radar_user = current_user(st.session_state)
- radar, radar_user_flags = load_course_radar(
+ radar, _ = load_course_radar(
st.session_state,
course.course_id,
radar_user.user_id if radar_user is not None else None,
@@ -202,6 +197,8 @@
radar,
learning_radar.top_hard_topics(radar, limit=len(course.topics)),
topic_names,
+ course=course,
+ focus_topic_id=focus_id,
)
if not course.relationships:
@@ -283,11 +280,13 @@
count = len(suggestions)
noun = "connection" if count == 1 else "connections"
if sync_outcome is not None and not sync_outcome.success:
+ # The stored reason may describe the database, so
+ # the student sees a short notice instead.
st.session_state[notice_state_key] = (
"warning",
"Connections kept in this session but not saved "
- f"to your account: {sync_outcome.message} Use "
- "Save on the Study Plan page to retry.",
+ "to your account. Use Save on the Study Plan "
+ "page to retry.",
)
else:
st.session_state[notice_state_key] = (
@@ -339,7 +338,6 @@
st.caption(tr(label) + ":" + ", ".join(topic_names[item] for item in links[group]))
if not any(links.values()):
st.caption(tr("No connections recorded for this topic."))
- st.caption(tr("These are course-provided relationships, not a diagnosis of your understanding."))
for linked_id in links["prerequisites"]:
if st.button(tr("Review ") + topic_names[linked_id], key=f"graph_prerequisite_{course.course_id}_{linked_id}"):
st.session_state[pending_key] = linked_id
@@ -356,6 +354,16 @@
if radar is not None:
st.divider()
st.markdown(tr("**Learning Radar**"))
+ if radar_user is not None:
+ # One click flags the topic with a reason; to change the
+ # reason, remove the flag and flag again.
+ render_stuck_buttons(
+ st.session_state,
+ course.course_id,
+ selected_node_id,
+ radar_user.user_id,
+ key=f"radar_flag_{course.course_id}_{selected_node_id}",
+ )
render_topic_radar(
radar.topics.get(selected_node_id),
prerequisite_names=[
@@ -363,42 +371,9 @@
for item in links["prerequisites"]
if item in topic_names
],
+ # The buttons above already show the count.
+ show_count=radar_user is None,
)
- if radar_user is not None:
- already_flagged = selected_node_id in radar_user_flags
- if already_flagged:
- # To change the reason, remove the flag and flag again.
- reason = radar_user_flags[selected_node_id]
- render_saved_reason(reason)
- else:
- reason = st.selectbox(
- tr("Why are you stuck?"),
- options=RADAR_REASON_OPTIONS,
- format_func=lambda value: tr(radar_reason_label(value)),
- key=f"radar_reason_{course.course_id}_{selected_node_id}",
- )
- render_reason_hint(reason)
- if st.button(
- tr("Not stuck anymore") if already_flagged else tr("I'm stuck here"),
- key=f"radar_flag_{course.course_id}_{selected_node_id}",
- ):
- if already_flagged:
- result = learning_radar.clear_flag(
- radar_user.user_id, course.course_id, selected_node_id
- )
- else:
- result = learning_radar.set_flag(
- radar_user.user_id,
- course.course_id,
- selected_node_id,
- reason,
- )
- if result.success:
- # Show the new count right away instead of waiting
- # for the cache to expire.
- forget_course_radar(st.session_state, course.course_id)
- st.rerun()
- st.warning(tr(result.message))
if concept_lab_available(course.course_id, selected_node_id):
if st.button(
tr("Open Concept Lab"),
diff --git a/pages/5_Export_Anki.py b/pages/5_Export_Anki.py
index 0bebef3..b14d30b 100644
--- a/pages/5_Export_Anki.py
+++ b/pages/5_Export_Anki.py
@@ -26,13 +26,10 @@ def _topic_tag(topic_id: str) -> str:
apply_app_styles()
st.title(tr("Export to Anki"))
-st.caption(
- tr("Review course knowledge cards here or download a UTF-8 TSV file "
- "for Anki text import.")
-)
+st.caption(tr("Review course knowledge cards here or download them for Anki."))
with st.expander(tr("Import instructions and limitations")):
- st.write(tr("Download the TSV, then use Anki Desktop → File → Import and map Front, Back and Tags. AnkiWeb sync is not supported; Anki Desktop import has not been verified."))
+ st.write(tr("Download the file, then in Anki on your computer choose File → Import and match Front, Back and Tags. Cards are not sent to AnkiWeb automatically."))
course = st.session_state.get("current_course")
@@ -87,8 +84,8 @@ def _topic_tag(topic_id: str) -> str:
sessions=sessions,
questions=list(questions_by_id.values()),
)
- except ValueError as error:
- st.error(tr(f"Could not calculate mastery: {error}"))
+ except ValueError:
+ st.error(tr("Couldn't find your weak topics from this practice history."))
st.stop()
topic_ids = get_weak_topic_ids(stats, mode)
@@ -116,7 +113,7 @@ def _topic_tag(topic_id: str) -> str:
summary_column, download_column = st.columns([1.4, 1], vertical_alignment="center")
with summary_column:
st.markdown(tr("**Your review deck**"))
- st.caption(tr(f"{len(cards)} cards · {export_scope} · UTF-8 TSV"))
+ st.caption(tr(f"{len(cards)} cards · {export_scope}"))
with download_column:
st.download_button(
tr("Download Anki TSV"),
diff --git a/pages/6_Concept_Lab.py b/pages/6_Concept_Lab.py
index 8ce0f06..2575c80 100644
--- a/pages/6_Concept_Lab.py
+++ b/pages/6_Concept_Lab.py
@@ -40,9 +40,10 @@ def practice_topic(topic_id: str, suffix: str = "") -> None:
st.session_state.setdefault(key, value)
requested_topic = st.session_state.get("concept_lab_topic_calculus-i-demo", "calc_limits")
+limits_label, derivatives_label = tr("Limits"), tr("Derivatives")
limits_tab, derivatives_tab, corner_tab = st.tabs(
- ["Limits", "Derivatives", tr("Corners & differentiability")],
- default="Derivatives" if requested_topic == "calc_derivatives" else "Limits",
+ [limits_label, derivatives_label, tr("Corners & differentiability")],
+ default=derivatives_label if requested_topic == "calc_derivatives" else limits_label,
)
with limits_tab:
diff --git a/pages/7_Learning_Radar.py b/pages/7_Learning_Radar.py
new file mode 100644
index 0000000..7a52ef9
--- /dev/null
+++ b/pages/7_Learning_Radar.py
@@ -0,0 +1,101 @@
+"""Learning Radar: where students of the built-in demo courses get stuck."""
+
+from services.i18n import tr
+
+import streamlit as st
+
+from components.knowledge_graph import load_course_radar, render_radar_panel
+from components.radar_chart import render_course_radar_chart, render_stuck_buttons
+from services import learning_radar
+from services.auth_session import current_user
+from services.ui_style import apply_app_styles
+
+# Up to this many topics are offered as one-click pills; more use a dropdown.
+MAX_PILL_TOPICS = 8
+
+apply_app_styles()
+
+st.title(tr("Learning Radar"))
+st.caption(tr("See where students get stuck, and mark the topics that stop you."))
+
+course = st.session_state.get("current_course")
+
+if course is None:
+ st.info(tr("Load a course from the dashboard first."))
+ st.page_link("pages/0_Dashboard.py", label=tr("Back to Dashboard"))
+ st.stop()
+
+if not learning_radar.radar_enabled(course.course_id):
+ st.info(tr("Learning Radar is available for the built-in demo courses."))
+ st.stop()
+
+user = current_user(st.session_state)
+user_id = user.user_id if user is not None else None
+# Shared with the Knowledge Map and Study Plan, so reruns reuse one read.
+radar, _ = load_course_radar(st.session_state, course.course_id, user_id)
+topic_names = {topic.id: topic.name for topic in course.topics}
+
+picker_key = f"learning_radar_topic_{course.course_id}"
+# The picker sits below the chart; its last choice is highlighted above.
+picked = st.session_state.get(picker_key)
+if picked not in topic_names:
+ picked = None
+
+chart_column, ranking_column = st.columns([1.15, 1], gap="large")
+with chart_column:
+ with st.container(border=True, key="learning_radar_chart_panel"):
+ render_course_radar_chart(
+ course,
+ radar,
+ focus_topic_id=picked,
+ limit=8,
+ key="learning_radar_page_chart",
+ )
+with ranking_column:
+ with st.container(border=True, key="learning_radar_ranking_panel"):
+ render_radar_panel(
+ radar,
+ learning_radar.top_hard_topics(radar, limit=len(course.topics)),
+ topic_names,
+ title="**Most flagged topics**",
+ )
+
+with st.container(border=True, key="learning_radar_mark_panel"):
+ st.subheader(tr("Where are you stuck?"))
+ if len(topic_names) <= MAX_PILL_TOPICS:
+ picked = st.pills(
+ tr("Pick a topic"),
+ options=list(topic_names),
+ format_func=lambda topic_id: topic_names[topic_id],
+ key=picker_key,
+ label_visibility="collapsed",
+ )
+ else:
+ picked = st.selectbox(
+ tr("Pick a topic"),
+ options=list(topic_names),
+ index=None,
+ format_func=lambda topic_id: topic_names[topic_id],
+ placeholder=tr("Pick a topic"),
+ key=picker_key,
+ label_visibility="collapsed",
+ )
+
+ if picked is None:
+ st.caption(tr("Pick a topic above to mark it."))
+ else:
+ render_stuck_buttons(
+ st.session_state,
+ course.course_id,
+ picked,
+ user_id,
+ key=f"learning_radar_stuck_{course.course_id}_{picked}",
+ )
+ if st.button(
+ tr("Open this topic in Knowledge Map"),
+ key=f"learning_radar_map_{course.course_id}_{picked}",
+ icon=":material/hub:",
+ ):
+ # The Knowledge Map moves this into its topic picker on load.
+ st.session_state[f"graph_pending_focus_{course.course_id}"] = picked
+ st.switch_page("pages/4_Knowledge_Graph.py")
diff --git a/services/accessibility.py b/services/accessibility.py
index 90a4a96..f90ba0f 100644
--- a/services/accessibility.py
+++ b/services/accessibility.py
@@ -8,11 +8,13 @@
import json
import re
from dataclasses import dataclass
+from functools import lru_cache
from pathlib import Path
from collections.abc import Mapping
+from types import MappingProxyType
from models.schemas import Question
-from services.i18n import tr
+from services.i18n import tr, render_language_control
SIMPLIFY_KEY = "a11y_simplify"
@@ -35,17 +37,33 @@ def render_accessibility_controls() -> None:
st.subheader(tr("Accessibility"))
st.toggle(tr("Simplified English"), key=SIMPLIFY_KEY)
- st.toggle("中文界面 / Chinese interface", key=BILINGUAL_KEY)
+ render_language_control()
st.caption(tr("Interface language only; uploaded material and AI-generated answers retain their original language."))
-def _read_mapping(filename: str) -> dict:
- path = _DATA_DIR / filename
+def _read_mapping(filename: str) -> Mapping:
+ # Keyed by the full path, so a different data directory is never served
+ # from the cache.
+ return _load_mapping(_DATA_DIR / filename)
+
+
+def _freeze(value):
+ """Make parsed JSON read-only at every level, so the cached copy cannot change."""
+ if isinstance(value, dict):
+ return MappingProxyType({key: _freeze(item) for key, item in value.items()})
+ if isinstance(value, list):
+ return tuple(_freeze(item) for item in value)
+ return value
+
+
+@lru_cache(maxsize=None)
+def _load_mapping(path: Path) -> Mapping:
+ """Parse a data file once; callers get a read-only view of the cached data."""
if not path.is_file():
- return {}
+ return MappingProxyType({})
with path.open("r", encoding="utf-8") as source:
data = json.load(source)
- return data if isinstance(data, dict) else {}
+ return _freeze(data) if isinstance(data, dict) else MappingProxyType({})
def annotate_terms(text: str, glossary: dict[str, str]) -> str:
@@ -99,10 +117,10 @@ def display_question(
data = _read_mapping(f"simplified_{course_id}.json")
wording = data.get("questions", {}).get(question.id)
simplified = bool(
- isinstance(wording, dict)
+ isinstance(wording, Mapping)
and isinstance(wording.get("question"), str)
and isinstance(wording.get("explanation"), str)
- and isinstance(wording.get("options"), list)
+ and isinstance(wording.get("options"), (list, tuple))
and len(wording["options"]) == 4
and all(isinstance(option, str) for option in wording["options"])
)
diff --git a/services/account_sync.py b/services/account_sync.py
index d9f0936..901c18f 100644
--- a/services/account_sync.py
+++ b/services/account_sync.py
@@ -17,10 +17,21 @@
from services.auth_session import current_user
from services.exam_engine import grade_exam
from services.learning_state import capture_learning_state, restored_learning_state
-from services.ui_adapters import PENDING_INTEGRATION_MESSAGES
STATE_KEY = "account_sync"
+# Student-facing texts. Raw database reasons stay in SyncOutcome.message for
+# diagnostics and are never shown on the page.
+SAVE_FAILED_MESSAGE = (
+ "Couldn't save to your account. Your work is kept on this device for now."
+)
+RESTORE_FAILED_MESSAGE = (
+ "Couldn't restore from your account. Your work on this device is unchanged."
+)
+NOTHING_SAVED_MESSAGE = "Nothing saved for this course yet."
+RESTORE_FIRST_MESSAGE = "Restore this course from your account first, then save."
+_COURSE_NOT_FOUND = "Course was not found."
+
@dataclass(frozen=True)
class SyncOutcome:
@@ -149,19 +160,21 @@ def _restore_one(
state: dict,
user_id: str,
course_id: str,
- label: str,
) -> str | None:
- """Restore one course; return an error text, or None on success."""
+ """Restore one course; return the internal failure reason, or None on success."""
restored = postgres_store.load_course_history(user_id, course_id)
- if not restored.success or restored.package is None:
+ if not restored.success:
state.setdefault("failed_course_ids", set()).add(course_id)
- reason = restored.message if not restored.success else "Course was not found."
- return f"{label}: {reason}"
+ return restored.message
+ if restored.package is None:
+ # Nothing saved yet is not a failed restore; it must not block saves.
+ state.setdefault("failed_course_ids", set()).discard(course_id)
+ return _COURSE_NOT_FOUND
try:
_apply_restored_course(session_state, state, restored)
except (KeyError, ValueError):
state.setdefault("failed_course_ids", set()).add(course_id)
- return f"{label}: Stored exam data could not be matched to its questions."
+ return "Stored exam data could not be matched to its questions."
state.setdefault("failed_course_ids", set()).discard(course_id)
return None
@@ -190,13 +203,11 @@ def restore_all(session_state: MutableMapping[str, Any]) -> SyncOutcome | None:
errors = []
restored_count = 0
for summary in listing.courses:
- error = _restore_one(
- session_state, state, user_id, summary.course_id, summary.course_name
- )
+ error = _restore_one(session_state, state, user_id, summary.course_id)
if error is None:
restored_count += 1
else:
- errors.append(error)
+ errors.append(f"{summary.course_name}: {error}")
state["restore_errors"] = errors
state["restore_message"] = (
@@ -321,9 +332,11 @@ def restore_course(
if user_id is None:
return None
state = _state(session_state, user_id)
- error = _restore_one(session_state, state, user_id, course_id, course_id)
+ error = _restore_one(session_state, state, user_id, course_id)
+ if error == _COURSE_NOT_FOUND:
+ return SyncOutcome(False, NOTHING_SAVED_MESSAGE)
if error is not None:
- return SyncOutcome(False, error)
+ return SyncOutcome(False, RESTORE_FAILED_MESSAGE)
return SyncOutcome(True, "Course and practice history restored.")
@@ -335,22 +348,20 @@ def render_sidebar_status() -> None:
return
state = _state(session_state, user_id)
+ # A successful restore needs no message; only failures are shown.
if state["restore_errors"]:
- st.warning(tr("Some saved records could not be restored. Your current work is unchanged.")
- + "\n\n" + "\n".join(f"- {tr(e)}" for e in state["restore_errors"]))
+ st.warning(tr("Some saved records could not be restored. Your current work is unchanged."))
if st.button(tr("Retry restore"), key="retry_restore", use_container_width=True):
with st.spinner(tr("Restoring your saved study records…")):
restore_all(session_state)
st.rerun()
- elif state["restore_message"]:
- st.caption(tr(state["restore_message"]))
if state.get("restore_conflicts"):
- st.warning(tr("Database history is used for statistics. Conflicting local practice records are kept separately in this login session and are not counted or automatically uploaded. Do not log out before resolving them."))
+ st.warning(tr("Some practice on this device differs from your saved records and is not counted. Logging out will remove it."))
unsaved = len(state["unsaved_courses"]) + len(state["unsaved_exams"])
if unsaved:
- st.warning(tr(f"{unsaved} item(s) are not saved to your account yet. Use Save in Study Plan to retry."))
+ st.warning(tr(f"{unsaved} item(s) not saved yet. Use Save in Study Plan to retry."))
def render_save_restore_controls(course: StudyPackage) -> None:
@@ -358,7 +369,7 @@ def render_save_restore_controls(course: StudyPackage) -> None:
session_state = st.session_state
user_id = _user_id(session_state)
if user_id is None:
- st.caption(tr(PENDING_INTEGRATION_MESSAGES["database"]))
+ st.caption(tr("Log in to back up this course."))
for column, label, kind in zip(st.columns(2), ("Save", "Restore"), ("save", "restore")):
column.button(
tr(label), key=f"database_{kind}_{course.course_id}",
@@ -368,7 +379,7 @@ def render_save_restore_controls(course: StudyPackage) -> None:
state = _state(session_state, user_id)
message_key = course.course_id
- st.caption(tr("Saves this course and its graded practice to your account. Anonymous records from before login are not migrated."))
+ st.caption(tr("Back up this course to your account."))
save_column, restore_column = st.columns(2)
save_clicked = save_column.button(
tr("Save"), key=f"database_save_{course.course_id}", use_container_width=True,
@@ -381,7 +392,15 @@ def render_save_restore_controls(course: StudyPackage) -> None:
if save_clicked:
with st.spinner(tr("Saving…")):
outcome = save_course_with_history(session_state, course)
- state["course_messages"][message_key] = outcome
+ # Show a fixed text; the raw reason from the database stays internal.
+ if outcome.success:
+ message = "Saved to your account."
+ elif state.get("listing_failed") or course.course_id in state.get("failed_course_ids", set()):
+ # Saving stays blocked until a restore works; retrying Save cannot help.
+ message = RESTORE_FIRST_MESSAGE
+ else:
+ message = SAVE_FAILED_MESSAGE
+ state["course_messages"][message_key] = SyncOutcome(outcome.success, message)
elif restore_clicked:
with st.spinner(tr("Restoring…")):
outcome = restore_course(session_state, course.course_id)
@@ -390,8 +409,14 @@ def render_save_restore_controls(course: StudyPackage) -> None:
st.rerun()
outcome = state["course_messages"].get(message_key)
- if outcome is not None:
- (st.success if outcome.success else st.error)(tr(outcome.message))
+ if outcome is None:
+ return
+ if outcome.success:
+ st.success(tr(outcome.message))
+ elif outcome.message == NOTHING_SAVED_MESSAGE:
+ st.info(tr(outcome.message))
+ else:
+ st.error(tr(outcome.message))
def render_last_save_status() -> None:
@@ -400,9 +425,7 @@ def render_last_save_status() -> None:
if user_id is None:
return
outcome = _state(st.session_state, user_id)["last_save"]
- if outcome is None:
+ # A successful save needs no message on the page.
+ if outcome is None or outcome.success:
return
- if outcome.success:
- st.caption(tr("Saved to your account."))
- else:
- st.warning(tr(f"Not saved to your account: {outcome.message} Your local work is kept; use Save in Study Plan to retry."))
+ st.warning(tr(SAVE_FAILED_MESSAGE))
diff --git a/services/ai_service.py b/services/ai_service.py
index 19da039..a9cd481 100644
--- a/services/ai_service.py
+++ b/services/ai_service.py
@@ -42,7 +42,9 @@
TUTOR_TIMEOUT_SECONDS = 60.0
CONNECTION_CHECK_PROMPT = "Reply with only: ExamPilot API OK"
-MISSING_API_KEY_MESSAGE = "ANTHROPIC_API_KEY is not configured."
+# Shown to students: no key names or configuration details.
+AI_UNAVAILABLE_MESSAGE = "AI generation is unavailable right now."
+MISSING_API_KEY_MESSAGE = AI_UNAVAILABLE_MESSAGE
INVALID_DOCUMENT_MESSAGE = "The course material is invalid. Upload and extract it again."
TOO_LONG_MESSAGE = "The course material exceeds 50,000 characters and cannot be analysed."
@@ -114,17 +116,17 @@ def _api_error_result(exc: anthropic.APIStatusError) -> dict:
"""Describe an API error to the user without exposing the raw exception."""
status = exc.status_code
if isinstance(exc, anthropic.AuthenticationError):
- message = "The Claude API key was rejected. Check ANTHROPIC_API_KEY."
+ message = AI_UNAVAILABLE_MESSAGE
elif isinstance(exc, anthropic.PermissionDeniedError):
- message = "This Claude API key is not allowed to use the configured model."
+ message = AI_UNAVAILABLE_MESSAGE
elif isinstance(exc, anthropic.NotFoundError):
- message = "The configured Claude model is not available to this account. Check ANTHROPIC_MODEL."
+ message = AI_UNAVAILABLE_MESSAGE
elif isinstance(exc, anthropic.RateLimitError):
message = "Claude quota or rate limit reached. Try again later."
elif isinstance(status, int) and status >= 500:
message = "Claude is temporarily unavailable. Try again later."
else:
- message = "The Claude API request failed. Check the configuration or try again later."
+ message = "AI generation is unavailable right now. Try again later."
return _failure("API_ERROR", message, status_code=status)
@@ -135,7 +137,7 @@ def _request_failure(exc: Exception, activity: str) -> dict:
elif isinstance(exc, anthropic.APIConnectionError):
message = f"Could not reach Claude while {activity}. Check the network and try again."
else:
- message = f"An error occurred while {activity}. Check the configuration or try again later."
+ message = f"An error occurred while {activity}. Try again later."
return _failure("GENERATION_ERROR", message)
diff --git a/services/auth_ui.py b/services/auth_ui.py
index 6d15f38..76e513e 100644
--- a/services/auth_ui.py
+++ b/services/auth_ui.py
@@ -1,41 +1,32 @@
"""Account forms shown before any learning pages are registered."""
-import base64
-from pathlib import Path
+from html import escape
import streamlit as st
from services.auth_service import login_user, register_user
from services.auth_session import start_authenticated_session
-from services.i18n import LANGUAGE_KEY, tr
-from services.ui_style import apply_app_styles
+from services.i18n import tr, render_language_control
+from services.ui_style import BRAND_LOGO, apply_app_styles, illustration_data_uri
def render_auth_page() -> None:
apply_app_styles()
- with st.container(key="flight_auth_header"):
- st.markdown(
- '
✈ ExamPilot
',
- unsafe_allow_html=True,
- )
- st.toggle("中文界面 / Chinese interface", key=LANGUAGE_KEY)
+ # No sidebar exists before sign-in, so the full logo sits in the app header.
+ st.logo(str(BRAND_LOGO), size="large")
+ with st.container(key="auth_language"):
+ render_language_control()
- intro, forms = st.columns([1.1, 1], gap="large")
- with intro, st.container(key="flight_auth_intro"):
+ # One centred column: headline, campus watercolour, then the account card.
+ with st.container(key="flight_auth_intro"):
st.title(tr("Make your next study session count."))
- st.write(tr("Try one practice question after signing in, then follow the next step from your result."))
- art_path = Path(__file__).resolve().parents[1] / "assets" / "campus-illustration.svg"
- campus_art = base64.b64encode(art_path.read_bytes()).decode("ascii")
st.markdown(
- f'

',
+ f'

',
unsafe_allow_html=True,
)
- with forms, st.container(border=True, key="auth_forms"):
- st.header(tr("Welcome to ExamPilot"))
- st.caption(tr("Log in or create an account to start studying."))
+ with st.container(border=True, key="auth_forms"):
login_tab, register_tab = st.tabs([tr("Log in"), tr("Create account")])
with login_tab:
diff --git a/services/demo_updates.py b/services/demo_updates.py
index cc0cd66..e126f21 100644
--- a/services/demo_updates.py
+++ b/services/demo_updates.py
@@ -1,4 +1,5 @@
"""Explicit append-only demo updates; never replace a learner's saved content."""
+import logging
from pathlib import Path
from copy import deepcopy
from models.schemas import StudyPackage
@@ -52,14 +53,19 @@ def sync_demo_catalog(state):
by_id[current.course_id] = len(courses)
courses.append(current)
for course_id, filename in FILES.items():
- if course_id in by_id:
- index = by_id[course_id]
- courses[index], _ = demo_update(courses[index])
- else:
- package = StudyPackage.model_validate_json(
- (Path(__file__).resolve().parents[1]/'data'/filename).read_text(encoding='utf-8'))
- by_id[course_id] = len(courses)
- courses.append(package)
+ # One broken built-in update must not stop every page; keep that
+ # course as it was and carry on with the others.
+ try:
+ if course_id in by_id:
+ index = by_id[course_id]
+ courses[index], _ = demo_update(courses[index])
+ else:
+ package = StudyPackage.model_validate_json(
+ (Path(__file__).resolve().parents[1]/'data'/filename).read_text(encoding='utf-8'))
+ by_id[course_id] = len(courses)
+ courses.append(package)
+ except Exception:
+ logging.getLogger(__name__).exception('Built-in course %s was not updated.', course_id)
state['courses'] = courses
if current is not None and current.course_id in by_id:
state['current_course'] = courses[by_id[current.course_id]]
diff --git a/services/exam_engine.py b/services/exam_engine.py
index 80085d1..eaa43d3 100644
--- a/services/exam_engine.py
+++ b/services/exam_engine.py
@@ -112,10 +112,11 @@ def create_exam(
warning = None
if len(eligible_questions) < requested_count:
+ available_count = len(eligible_questions)
warning = (
- f"Requested {requested_count} questions, but only "
- f"{len(eligible_questions)} are available in the confirmed topic scope; "
- "all available questions were included."
+ "1 question available; included."
+ if available_count == 1
+ else f"{available_count} questions available; all included."
)
session = ExamSession(
diff --git a/services/guided_limits_ui.py b/services/guided_limits_ui.py
index 725aed8..0a5e603 100644
--- a/services/guided_limits_ui.py
+++ b/services/guided_limits_ui.py
@@ -75,7 +75,7 @@ def render_guided_review(course, session, questions, result) -> bool:
key = f"guided_limits_{session.session_id}"
progress = st.session_state.setdefault(key, {})
- first_answer = question.options[attempt.selected_index] if attempt.selected_index is not None else "Unanswered"
+ first_answer = question.options[attempt.selected_index] if attempt.selected_index is not None else tr("Unanswered")
with st.container(border=True, key="guided_limits_review"):
st.subheader(tr("Redo the step that stopped you"))
diff --git a/services/i18n.py b/services/i18n.py
index a6af182..58dc036 100644
--- a/services/i18n.py
+++ b/services/i18n.py
@@ -5,6 +5,19 @@
import re
LANGUAGE_KEY = "a11y_bilingual_zh"
+LANGUAGE_WIDGET_KEY = "_ui_chinese_toggle"
+
+
+def render_language_control() -> None:
+ """Keep the preference separate from Streamlit's page-scoped widget state."""
+ st.session_state[LANGUAGE_WIDGET_KEY] = bool(st.session_state.get(LANGUAGE_KEY, False))
+
+ def remember_language() -> None:
+ st.session_state[LANGUAGE_KEY] = st.session_state[LANGUAGE_WIDGET_KEY]
+
+ st.toggle("中文界面 / Chinese interface", key=LANGUAGE_WIDGET_KEY,
+ on_change=remember_language)
+
_TRANSLATIONS = {
"Home": "首页", "Review & tools": "复习与工具", "Account": "账户",
@@ -317,6 +330,70 @@
"See computation and conceptual understanding separately, with the answers behind each pattern.": "分别查看计算与概念理解,以及各项判断依据的答案。",
"These are question-based observations, not a validated cognitive diagnosis. Multiple-choice answers do not demonstrate that you can explain an idea in your own words.": "这些是基于题目的观察,并非经过验证的认知诊断;选择题无法证明你能用自己的话解释概念。",
"Answer more different questions in both dimensions before comparing them.": "在两个维度上多做不同题目,再进行比较。",
+ # paper UI: pages
+ "Couldn't save to your account. Your work is kept on this device for now.": "未能保存到账户,你的内容暂时保留在此设备上。",
+ "Couldn't restore from your account. Your work on this device is unchanged.": "未能从账户恢复,此设备上的内容没有改变。",
+ "Nothing saved for this course yet.": "此课程还没有保存的内容。",
+ "Some practice on this device differs from your saved records and is not counted. Logging out will remove it.": "此设备上有部分练习与已保存记录不一致,暂不计入统计;退出登录后将被删除。",
+ "Log in to back up this course.": "登录后可备份此课程。",
+ "Back up this course to your account.": "将此课程备份到你的账户。",
+ "Only the extracted text is saved with your course, not the original file.": "课程只保存提取的文字,不保存原始文件。",
+ "Couldn't use the generated topics. Try generating them again.": "无法使用生成的知识点,请重新生成。",
+ "Couldn't use the generated questions. Try generating them again.": "无法使用生成的题目,请重新生成。",
+ "AI generation is unavailable right now.": "AI 生成功能暂时不可用。",
+ "AI generation is unavailable right now. Try again later.": "AI 生成功能暂时不可用,请稍后重试。",
+ "Each topic can be selected only once.": "每个知识点只能选择一次。",
+ "Needs check": "待检查", "Approved": "已批准", "Flagged": "已标记",
+ "Check the answer and explanation before approving; edits never change past results.": "批准前请检查答案与解析;编辑不会改变以往成绩。",
+ "Couldn't delete the material from your account. Nothing was changed.": "未能从账户删除资料,内容没有任何改变。",
+ "Review course knowledge cards here or download them for Anki.": "在此查看课程知识卡片,或下载后导入 Anki。",
+ "Download the file, then in Anki on your computer choose File → Import and match Front, Back and Tags. Cards are not sent to AnkiWeb automatically.": "下载文件后,在电脑上的 Anki 中选择 文件 → 导入,并将字段对应到 Front、Back 和 Tags。卡片不会自动同步到 AnkiWeb。",
+ "Uses your latest answer to each question. Fewer than 3 different questions shows as insufficient evidence.": "按每道题的最近一次回答计算;不同题目少于 3 道时显示为证据不足。",
+ "Learning DNA couldn't read this practice history.": "学习画像无法读取这段练习历史。",
+ "Couldn't calculate your progress from this practice history.": "无法根据这段练习历史计算学习进度。",
+ "Couldn't find your weak topics from this practice history.": "无法根据这段练习历史找出薄弱知识点。",
+ # paper UI: radar
+ "Learning Radar": "学习雷达",
+ "See where students get stuck, and mark the topics that stop you.": "查看同学们在哪些知识点卡住,并标记让你卡住的知识点。",
+ "Learning Radar is available for the built-in demo courses.": "学习雷达仅适用于内置演示课程。",
+ "**Most flagged topics**": "**被标记最多的知识点**",
+ "Where are you stuck?": "你卡在哪个知识点?",
+ "Pick a topic": "选择知识点",
+ "Pick a topic above to mark it.": "在上方选择一个知识点进行标记。",
+ "Students stuck per topic": "各知识点卡住的学生人数",
+ "I'm stuck here because…": "我卡在这里,因为……",
+ "Just stuck": "就是没搞懂",
+ "You marked this topic.": "你已标记此知识点。",
+ "Couldn't update Learning Radar. Try again in a moment.": "暂时无法更新学习雷达,请稍后再试。",
+ "Connections kept in this session but not saved to your account. Use Save on the Study Plan page to retry.": "关联已保留在当前会话中,但未保存到账户。请在学习计划页面点击保存重试。",
+ # paper UI: fixes
+ "Open Study Plan": "打开学习计划", "Continue practice": "继续练习",
+ "Calculus I · Limits": "微积分 I · 极限",
+ # paper UI: practice
+ "Hint": "提示", "Next hint": "下一条提示", "Previous": "上一题", "Next": "下一题",
+ "Learning Radar": "学习雷达", "Explore this topic": "探索此知识点", "Quick Notes": "速记要点",
+ "Focus controls": "专注计时", "Answered": "已作答",
+ "1 question": "1 道题", "Topic practice": "知识点练习", "Mock exam": "模拟考试",
+ "Saved practice": "已保存的练习", "Unfinished": "未完成",
+ "New practice: ": "新练习:", "New practice for your confirmed topics.": "为已确认的知识点开始新练习。",
+ "Could not create practice. Try another topic or check your exam scope in Study Plan.": "无法创建练习。请换一个知识点,或到学习计划检查考试范围。",
+ "Could not grade this practice. Please try again.": "无法为本次练习评分,请重试。",
+ "1 question available; included.": "仅有 1 道题可用,已加入。",
+ "1 missed question to practise; your score stays the same.": "有 1 道错题可再练习;成绩保持不变。",
+ "1 question could benefit from another look.": "有 1 道题值得再看一遍。",
+ "1 correct answer was marked Guessed. Revisit it before treating it as secure knowledge.": "有 1 道答对的题被标记为猜测;请复习后再认为自己已掌握。",
+ "No hints": "未用提示", "1 hint": "1 条提示", "Saved.": "已保存。",
+ "No similar question yet.": "暂时没有类似的题目。",
+ "Couldn't save your reflection. Your score is unchanged.": "反思未能保存;成绩不变。",
+ "Couldn't save to your account. Your work is kept on this device for now.": "未能保存到账户;你的内容暂时保留在此设备上。",
+ "Your answers were graded, but your practice notes couldn't be saved.": "答案已评分,但练习记录未能保存。",
+ "Mixed-topic smart review is recorded in Mock Exam mode.": "多知识点智能复习按模拟考试模式记录。",
+ "No approved review questions are in the confirmed scope. Review questions or confirm your scope in Study Plan first.": "已确认范围中没有可用的复习题。请先到学习计划审核题目或确认范围。",
+ "Review topic is outside the confirmed scope.": "复习知识点不在已确认范围内。",
+ "No missed questions in this confirmed topic scope.": "已确认范围中没有错题。",
+ # paper UI: review fixes
+ "Couldn't load the Calculus demo course. Try again later.": "无法加载微积分演示课程,请稍后再试。",
+ "Restore this course from your account first, then save.": "请先从账户恢复此课程,然后再保存。",
}
_TRANSLATIONS.update(
@@ -406,6 +483,12 @@
'处不存在唯一的导数。'}
)
+# paper UI: shell
+_TRANSLATIONS.update({
+ "Learning Radar": "学习雷达",
+ "Illustration of a university campus": "大学校园插画",
+})
+
_DYNAMIC = [
(r"^(\d+) questions could benefit from another look\.$", r"有 \1 道题值得再看一遍。"),
(r"^Different questions: (\d+)$", r"不同题目数:\1"),
@@ -413,7 +496,7 @@
(r"^🔥 (\d+) stuck$", r"🔥 \1 人遇到困难"),
(r"^Applied (\d+) suggested connections?\.$", r"已应用 \1 条建议的关联。"),
(r"^Many students are stuck here\. Reviewing (.*) first may help\.$", r"许多学生在这里遇到困难;先复习\1可能有帮助。"),
- (r"^(\d+) knowledge points$", r"\1 个知识点"),
+ (r"^(\d+) knowledge points?$", r"\1 个知识点"),
(r"^Select (.+)$", r"选择\1"),
(r"^Source pages: (.+)$", r"来源页:\1"),
(r"^Option ([A-D])$", r"选项 \1"),
@@ -460,6 +543,24 @@
(r"^(\d+) correct answer\(s\) were marked Guessed\. Revisit them before treating them as secure knowledge\.$", r"有 \1 道答对的题被标记为猜测;请复习后再认为自己已掌握。"),
(r"^(\d+) answer\(s\) used in-app hints\.$", r"\1 道题使用了应用内提示。"),
(r"^Hint use was not recorded for (\d+) answer\(s\)\.$", r"\1 道题没有记录提示使用情况。"),
+ # paper UI: pages
+ (r"^(\d+) item\(s\) not saved yet\. Use Save in Study Plan to retry\.$", r"还有 \1 项未保存;请在学习计划中点击保存重试。"),
+ (r"^(\d+) questions? ready$", r"\1 道题可以练习"),
+ (r"^(\d+) new questions? needs? your check$", r"有 \1 道新题需要你检查"),
+ (r"^(\d+) cards · (.*)$", r"\1 张卡片 · \2"),
+ (r"^An error occurred while .+\. Try again later\.$", r"处理请求时出错,请稍后重试。"),
+ # paper UI: fixes
+ (r"^Delete (.+)\? Its materials and practice progress will be removed from this session\.$", r"删除“\1”?课程资料和练习进度将从本次会话中移除。"),
+ # paper UI: practice
+ (r"^Q0?(\d+)$", r"第 \1 题"),
+ (r"^(\d+) questions$", r"\1 道题"),
+ (r"^(\d+)/(\d+) correct$", r"答对 \1/\2"),
+ (r"^Unfinished sessions \((\d+)\)$", r"未完成的场次(\1)"),
+ (r"^(\d+) questions available; all included\.$", r"仅有 \1 道题可用,已全部加入。"),
+ (r"^(\d+) missed questions to practise; your score stays the same\.$", r"有 \1 道错题可再练习;成绩保持不变。"),
+ (r"^(\d+) correct answers were marked Guessed\. Revisit them before treating them as secure knowledge\.$", r"有 \1 道答对的题被标记为猜测;请复习后再认为自己已掌握。"),
+ (r"^(\d+) hints$", r"\1 条提示"),
+ (r"^(\d+) s$", r"\1 秒"),
]
diff --git a/services/learning_dna_ui.py b/services/learning_dna_ui.py
index 0690768..3143f5f 100644
--- a/services/learning_dna_ui.py
+++ b/services/learning_dna_ui.py
@@ -12,14 +12,12 @@ def render_learning_dna(course, attempts, sessions, questions, mode):
with st.expander(tr("How to read this profile")):
st.caption(tr("These are question-based observations, not a validated cognitive diagnosis. Multiple-choice answers do not demonstrate that you can explain an idea in your own words."))
try:
- profile, excluded = evidence_profile(attempts, sessions, questions, mode)
- except ValueError as error:
- st.warning(tr(f"Learning DNA could not read this history: {error}"))
+ profile, _excluded = evidence_profile(attempts, sessions, questions, mode)
+ except ValueError:
+ st.warning(tr("Learning DNA couldn't read this practice history."))
return
- st.caption(tr("Each question family counts once, using its latest response in this mode. Fewer than 3 different questions means insufficient evidence. Untagged and unanswered responses are excluded."))
+ st.caption(tr("Uses your latest answer to each question. Fewer than 3 different questions shows as insufficient evidence."))
by_key = {(p.topic_id, p.dimension): p for p in profile}
- if excluded:
- st.caption(tr(f"{excluded} latest question-family response(s) excluded because they are untagged or unanswered."))
for topic in course.topics:
with st.container(border=True, key=f"learning_dna_{topic.id}"):
st.markdown(f"**{topic.name}**")
@@ -44,5 +42,3 @@ def render_learning_dna(course, attempts, sessions, questions, mode):
if evidence:
with st.expander(tr("View evidence") + f": {topic.name}"):
st.dataframe(evidence, hide_index=True, width="stretch")
- with st.expander(tr("Question labels and saved history")):
- st.caption(tr("Tag a question's evidence type under Study Plan → Course tools → Review and edit questions. Saved questions and graded history restore with your course; editing a tag creates a new question version and preserves earlier evidence."))
diff --git a/services/postgres_store.py b/services/postgres_store.py
index f2ff97f..3b7b464 100644
--- a/services/postgres_store.py
+++ b/services/postgres_store.py
@@ -160,7 +160,12 @@ def _merge_course_packages(
question.model_dump(mode="json") for question in questions
]
metadata = {**existing.learning_state, **incoming.learning_state}
- reviews = {**existing.learning_state.get("question_reviews", {}), **incoming.learning_state.get("question_reviews", {})}
+ reviews = dict(existing.learning_state.get("question_reviews", {}))
+ for question_id, status in incoming.learning_state.get("question_reviews", {}).items():
+ # A stale session's "pending" must not undo a decision saved elsewhere.
+ if status == "pending" and reviews.get(question_id) in {"approved", "flagged", "superseded"}:
+ continue
+ reviews[question_id] = status
if reviews:
metadata["question_reviews"] = reviews
insights = deepcopy(existing.learning_state.get("practice_insights", {}))
diff --git a/services/practice_insights_ui.py b/services/practice_insights_ui.py
index 62d2f22..dab160e 100644
--- a/services/practice_insights_ui.py
+++ b/services/practice_insights_ui.py
@@ -15,16 +15,23 @@
from services.learning_flow import remember_widget, install_practice
+# Save failures never show the stored reason; the student only needs to know the outcome.
+REFLECTION_NOT_SAVED = "Couldn't save your reflection. Your score is unchanged."
+ACCOUNT_NOT_SAVED = "Couldn't save to your account. Your work is kept on this device for now."
+NOTES_NOT_SAVED = "Your answers were graded, but your practice notes couldn't be saved."
+CONFIRM_TOPIC = 'Confirm this topic in Study Plan first.'
+
+
def save_rows(course, sid, rows):
try:
updated = set_session_insights(course, sid, rows)
except ValueError:
- st.error(tr("Reflection could not be saved because the course metadata is invalid or exceeds its storage limit. Your grade is unchanged."))
+ st.error(tr(REFLECTION_NOT_SAVED))
return None
save_course(st.session_state, updated)
outcome = save_course_with_history(st.session_state, updated)
if outcome is not None and not outcome.success:
- st.warning(tr('Reflection kept in this session but not saved to your account. ') + tr(outcome.message))
+ st.warning(tr(ACCOUNT_NOT_SAVED))
return updated
@@ -50,11 +57,11 @@ def answer_controls(active, question, course_id):
if st.button(tr('Work on this question'), key=f'focus_{sid}_{question.id}'):
focus_question(active, question.id, time.monotonic())
st.rerun()
- if active.get('focus_timer', {}).get('question_id') == question.id:
- st.caption(tr('Selected for focus-time tracking'))
- st.selectbox(tr('How confident are you?'), list(CONFIDENCE),
- format_func=lambda value: tr(CONFIDENCE[value]), key=f'confidence_{sid}_{question.id}',
- on_change=remember_widget, args=(st.session_state, course_id, sid, f'confidence_{sid}_{question.id}'))
+ # One click records confidence; no selection (None) means "not recorded".
+ key = f'confidence_{sid}_{question.id}'
+ st.segmented_control(tr('How confident are you?'), [value for value in CONFIDENCE if value is not None],
+ format_func=lambda value: tr(CONFIDENCE[value]), key=key,
+ on_change=remember_widget, args=(st.session_state, course_id, sid, key))
def checklist(active):
@@ -91,32 +98,23 @@ def capture_submission(course, active):
def result_overview(course, session, questions, result):
if st.session_state.pop('insights_capture_error', False):
- st.warning(tr('Your answers were graded, but optional practice tracking exceeded its storage limit and was not saved.'))
+ st.warning(tr(NOTES_NOT_SAVED))
rows = session_insights(course, session.session_id)
data = analytics(questions, result['attempts'], rows)
st.subheader(tr('Practice insights'))
- st.caption(tr('Confidence is self-reported. No in-app hints used does not prove unaided understanding; older sessions may have no tracking data.'))
- answered = {a.question_id for a in result['attempts'] if a.selected_index is not None}
- assisted_answers = len(answered.intersection(data['assisted']))
- unknown_answers = len(answered.intersection(data['unknown_hints']))
- without_hints = len(answered) - assisted_answers - unknown_answers
- st.caption(tr(f"Answered questions: {without_hints} without in-app hints · {assisted_answers} hint-assisted · {unknown_answers} hint use not recorded."))
- if data['correct_guesses']:
- st.info(tr(f"{len(data['correct_guesses'])} correct answer(s) were marked Guessed. Revisit them before treating them as secure knowledge."))
- if data['assisted']:
- st.caption(tr(f"{len(data['assisted'])} answer(s) used in-app hints."))
- if data['unknown_hints']:
- st.caption(tr(f"Hint use was not recorded for {len(data['unknown_hints'])} answer(s)."))
+ guesses = len(data['correct_guesses'])
+ if guesses == 1:
+ st.info(tr('1 correct answer was marked Guessed. Revisit it before treating it as secure knowledge.'))
+ elif guesses:
+ st.info(tr(f"{guesses} correct answers were marked Guessed. Revisit them before treating them as secure knowledge."))
if data['topic_seconds']:
names={t.id:t.name for t in course.topics}
with st.expander(tr('Time breakdown')):
st.markdown(tr('**Tracked focus time by topic**'))
- st.dataframe([{tr('Topic'):names.get(t,t),tr('Tracked seconds'):round(seconds,1)}
+ st.dataframe([{tr('Topic'):names.get(t,tr('Topic')),tr('Tracked seconds'):round(seconds,1)}
for t,seconds in sorted(data['topic_seconds'].items(),key=lambda p:-p[1])],hide_index=True,width='stretch')
slowest=max(questions,key=lambda q:rows.get(q.id,{}).get('focus_seconds') or 0)
st.caption(tr('Longest tracked question: ') + slowest.question)
- else:
- st.caption(tr('No focus-time measurements were recorded for this session.'))
render_priorities(course, data['priorities'])
@@ -134,11 +132,12 @@ def launch_priority(course, priorities):
def render_priorities(course, priorities):
st.markdown(tr('**Smart review list**'))
if priorities:
- st.caption(tr(f"{len(priorities)} questions could benefit from another look."))
+ st.caption(tr('1 question could benefit from another look.') if len(priorities) == 1
+ else tr(f"{len(priorities)} questions could benefit from another look."))
with st.expander(tr("Why this review order")):
st.caption(tr('Priority uses incorrect/unanswered responses, confidence, hints and relative tracked time. It is a transparent practice suggestion, not a diagnosis.'))
names={t.id:t.name for t in course.topics}
- st.dataframe([{tr('Rank'):i,tr('Topic'):names.get(r['topic_id'],r['topic_id']),
+ st.dataframe([{tr('Rank'):i,tr('Topic'):names.get(r['topic_id'],tr('Topic')),
tr('Question'):r['question'],tr('Why review'):', '.join(tr(reason) for reason in r['reasons'])}
for i,r in enumerate(priorities,1)],hide_index=True,width='stretch')
st.button(tr('Practise review priorities'), key=f'priorities_{course.course_id}',
@@ -156,29 +155,37 @@ def launch_transfer(course, question, session, confirmed, practice_key):
try:
install_practice(st.session_state, course.course_id, transfer_session(course, question, session, confirmed))
except ValueError as error:
- st.session_state['transfer_launch_error'] = str(error)
+ # Only the scope message asks the student to act; any other reason means no match yet.
+ st.session_state['transfer_launch_error'] = CONFIRM_TOPIC if str(error) == CONFIRM_TOPIC else 'No similar question yet.'
+
+
+def evidence_line(saved):
+ """One short line such as "Sure · 1 hint · 42 s"; unrecorded parts are left out."""
+ parts = []
+ if saved.confidence is not None:
+ parts.append(tr(CONFIDENCE[saved.confidence]))
+ if saved.hints_used is not None:
+ hints = saved.hints_used
+ parts.append(tr('No hints') if hints == 0 else tr('1 hint') if hints == 1 else tr(f'{hints} hints'))
+ if saved.focus_seconds is not None:
+ parts.append(tr(f'{round(saved.focus_seconds)} s'))
+ return ' · '.join(parts)
def reflection_controls(course, session, question, review, confirmed, practice_key):
sid=session.session_id
rows=deepcopy(session_insights(course,sid))
saved=ResponseInsight.model_validate(rows.get(question.id,{}))
- st.caption(tr('Confidence') + ': ' + tr(CONFIDENCE[saved.confidence]))
- if saved.hints_used is None:
- st.caption(tr('Completion evidence: hint use not recorded'))
- else:
- st.caption(tr(f'In-app hints shown: {saved.hints_used}'))
- label = 'Hint exposure' if review['selected_index'] is None else 'Completion evidence'
- st.caption(tr(label) + (': ' + tr('hint-assisted') if saved.hints_used else ': ' + tr('no in-app hints used')))
- if saved.focus_seconds is not None:
- st.caption(tr(f'Tracked focus time: {saved.focus_seconds:.1f} seconds'))
+ if line := evidence_line(saved):
+ st.caption(line)
with st.expander(tr('Reflect and explain your answer')):
st.caption(tr('Write your reasoning in your own words. This reflection is after feedback and never changes your score.'))
with st.form(f'reflection_{sid}_{question.id}'):
reason=saved.mistake_reason
if not review['is_correct']:
- reason=st.selectbox(tr('Why did you miss this question?'),list(REASONS),
- index=list(REASONS).index(reason),format_func=lambda v:tr(REASONS[v]),
+ # No pill selected (None) keeps the reason "not recorded".
+ reason=st.pills(tr('Why did you miss this question?'),[v for v in REASONS if v is not None],
+ default=reason,format_func=lambda v:tr(REASONS[v]),
key=f'reason_{sid}_{question.id}')
text=st.text_area(tr('Explain your answer'),value=saved.explanation,max_chars=4000,
key=f'explain_{sid}_{question.id}')
@@ -205,7 +212,7 @@ def reflection_controls(course, session, question, review, confirmed, practice_k
rows[question.id]=row.model_dump(mode='json')
updated = save_rows(course,sid,rows)
if updated is not None:
- st.success(tr('Reflection saved in this session.'))
+ st.success(tr('Saved.'))
saved=row
if saved.feedback is not None and saved.checked_explanation==saved.explanation:
st.markdown(tr('**AI reasoning feedback — not a grade**'))
@@ -245,12 +252,11 @@ def render_history_insights(course, history, mode):
with st.expander(tr('Time by topic')):
st.subheader(tr('Tracked focus time by topic'))
st.caption(tr('Totals across recorded sessions in this mode; missing time is not treated as zero.'))
- st.dataframe([{tr('Topic'):names.get(t,t),tr('Tracked seconds'):round(seconds,1)}
+ st.dataframe([{tr('Topic'):names.get(t,tr('Topic')),tr('Tracked seconds'):round(seconds,1)}
for t,seconds in sorted(total_seconds.items(),key=lambda p:-p[1])],hide_index=True,width='stretch')
qs=[value[0] for value in latest.values()]
attempts=[value[1] for value in latest.values()]
rows={q.id:r for q,a,r in latest.values()}
data=analytics(qs,attempts,rows)
st.subheader(tr('Your next review'))
- st.caption(tr('Uses each question family’s latest response in the selected mode. Older sessions with missing confidence or timing are not treated as measured.'))
render_priorities(course,data['priorities'])
diff --git a/services/relationship_suggestions.py b/services/relationship_suggestions.py
index 63c66c4..6b89d44 100644
--- a/services/relationship_suggestions.py
+++ b/services/relationship_suggestions.py
@@ -6,6 +6,7 @@
"""
from models.schemas import StudyPackage
+from services.i18n import tr
def suggestions_key(course_id: str) -> str:
@@ -17,13 +18,17 @@ def notice_key(course_id: str) -> str:
def describe_suggestions(course: StudyPackage, suggestions: list[dict]) -> list[str]:
- """Return one human-readable label per suggestion, using topic names."""
+ """Return one human-readable label per suggestion, using topic names.
+
+ An unknown topic shows as the plain word "Topic", never its internal ID.
+ """
names = {topic.id: topic.name for topic in course.topics}
+ fallback = tr("Topic")
labels = []
for suggestion in suggestions:
- source = suggestion.get("from_topic", "?")
- target = suggestion.get("to_topic", "?")
- labels.append(f"{names.get(source, source)} ↔ {names.get(target, target)}")
+ source = names.get(suggestion.get("from_topic"), fallback)
+ target = names.get(suggestion.get("to_topic"), fallback)
+ labels.append(f"{source} ↔ {target}")
return labels
diff --git a/services/ui_style.py b/services/ui_style.py
index 5810e7c..59540df 100644
--- a/services/ui_style.py
+++ b/services/ui_style.py
@@ -1,16 +1,62 @@
+"""Shared stylesheets, brand files and paper illustrations for every page."""
+
+import base64
+from functools import lru_cache
from pathlib import Path
import streamlit as st
+ASSETS = Path(__file__).resolve().parents[1] / "assets"
+BRAND_LOGO = ASSETS / "brand-logo.svg"
+BRAND_PLANE = ASSETS / "brand-plane.svg"
+ILLUSTRATIONS = ASSETS / "illustrations"
+# Decorations that stylesheets use as var(--paper-
).
+CSS_ILLUSTRATIONS = ("landscape-left", "landscape-right", "home-foliage")
+
+
+@lru_cache(maxsize=32)
+def _read_text(path: str, modified_ns: int) -> str:
+ # The modification time is part of the key, so an edited file is read again.
+ return Path(path).read_text(encoding="utf-8")
+
+
+def _stylesheet(path: Path) -> str:
+ return _read_text(str(path), path.stat().st_mtime_ns)
+
+
+def paper_stylesheets() -> list[Path]:
+ """paper_shell.css first, then the page sheets (paper_practice.css, ...) by name.
+
+ The shell holds the app-wide base, so page sheets that follow it win ties.
+ """
+ return sorted(
+ ASSETS.glob("paper_*.css"),
+ key=lambda path: (path.name != "paper_shell.css", path.name),
+ )
+
+
+@lru_cache(maxsize=None)
+def illustration_data_uri(name: str) -> str:
+ """Embed a watercolour from assets/illustrations; Streamlit serves no asset folder."""
+ data = (ILLUSTRATIONS / f"{name}.webp").read_bytes()
+ return "data:image/webp;base64," + base64.b64encode(data).decode("ascii")
+
+
+@lru_cache(maxsize=1)
+def _illustration_properties() -> str:
+ properties = "".join(
+ f' --paper-{name}: url("{illustration_data_uri(name)}");\n'
+ for name in CSS_ILLUSTRATIONS
+ )
+ return ":root {\n" + properties + "}\n"
+
def apply_app_styles() -> None:
"""Apply shared presentation styles without changing page behavior."""
- typography = (
- Path(__file__).resolve().parents[1] / "assets" / "ui_typography.css"
- ).read_text(encoding="utf-8")
- academic = (
- Path(__file__).resolve().parents[1] / "assets" / "academic_ui.css"
- ).read_text(encoding="utf-8")
+ typography = _stylesheet(ASSETS / "ui_typography.css")
+ academic = _stylesheet(ASSETS / "academic_ui.css")
+ # Later sheets win: the paper theme layers over the earlier academic styles.
+ paper = "\n".join(_stylesheet(path) for path in paper_stylesheets())
st.markdown(
"",
+ """ + academic + "\n" + paper + "\n" + _illustration_properties() + "",
unsafe_allow_html=True,
)
diff --git a/tests/test_accessibility.py b/tests/test_accessibility.py
index a773e0f..e8d561a 100644
--- a/tests/test_accessibility.py
+++ b/tests/test_accessibility.py
@@ -70,6 +70,48 @@ def test_display_text_reads_glossary_only_when_enabled(monkeypatch) -> None:
)
+def test_mapping_files_are_parsed_once_and_returned_read_only(monkeypatch, tmp_path) -> None:
+ from types import SimpleNamespace
+
+ from services import accessibility
+
+ (tmp_path / "glossary_zh.json").write_text(
+ json.dumps({"limit": "极限"}, ensure_ascii=False), encoding="utf-8"
+ )
+ monkeypatch.setattr(accessibility, "_DATA_DIR", tmp_path)
+ loads = []
+
+ def counting_load(source):
+ loads.append(source)
+ return json.load(source)
+
+ monkeypatch.setattr(accessibility, "json", SimpleNamespace(load=counting_load))
+
+ for _ in range(3):
+ assert display_text("Limit", {BILINGUAL_KEY: True}) == "Limit (极限)"
+ assert len(loads) == 1
+
+ mapping = accessibility._read_mapping("glossary_zh.json")
+ with pytest.raises(TypeError):
+ mapping["limit"] = "changed"
+ assert display_text("Limit", {BILINGUAL_KEY: True}) == "Limit (极限)"
+
+
+def test_a_different_data_directory_is_not_served_from_the_cache(monkeypatch, tmp_path) -> None:
+ from services import accessibility
+
+ for name, translation in (("first", "极限"), ("second", "界限")):
+ folder = tmp_path / name
+ folder.mkdir()
+ (folder / "glossary_zh.json").write_text(
+ json.dumps({"limit": translation}, ensure_ascii=False), encoding="utf-8"
+ )
+ monkeypatch.setattr(accessibility, "_DATA_DIR", tmp_path / "first")
+ assert display_text("Limit", {BILINGUAL_KEY: True}) == "Limit (极限)"
+ monkeypatch.setattr(accessibility, "_DATA_DIR", tmp_path / "second")
+ assert display_text("Limit", {BILINGUAL_KEY: True}) == "Limit (界限)"
+
+
ROOT = Path(__file__).resolve().parents[1]
DEMO_FILES = {
"econ101": "sample_course.json",
@@ -87,7 +129,7 @@ def test_accessibility_controls_have_expected_labels_and_keys() -> None:
assert "Accessibility" in [element.value for element in app.subheader]
assert [(item.label, item.key) for item in app.get("toggle")] == [
("Simplified English", SIMPLIFY_KEY),
- ("中文界面 / Chinese interface", BILINGUAL_KEY),
+ ("中文界面 / Chinese interface", "_ui_chinese_toggle"),
]
@@ -190,3 +232,16 @@ def test_glossary_has_course_terms_and_two_modes_work_together() -> None:
{SIMPLIFY_KEY: True, BILINGUAL_KEY: True})
assert display.simplified is True
assert "需求" in display.question
+
+
+def test_cached_accessibility_data_is_read_only_at_every_level():
+ from services import accessibility
+
+ data = accessibility._read_mapping("simplified_econ101.json")
+ wording = next(iter(data["questions"].values()))
+
+ with pytest.raises(TypeError):
+ wording["question"] = "changed"
+ with pytest.raises(TypeError):
+ data["questions"]["new"] = {}
+ assert isinstance(wording["options"], tuple)
diff --git a/tests/test_account_sync.py b/tests/test_account_sync.py
index 5748bde..5672403 100644
--- a/tests/test_account_sync.py
+++ b/tests/test_account_sync.py
@@ -367,7 +367,46 @@ def test_single_course_restore_failure_does_not_claim_success(store):
seed(store, TEST_USER, course)
store.fail_course_ids.add("course-1")
outcome = account_sync.restore_course(signed_in_state(), "course-1")
- assert not outcome.success and "load failed" in outcome.message
+ assert not outcome.success
+ assert outcome.message == account_sync.RESTORE_FAILED_MESSAGE
+ assert "load failed" not in outcome.message
+
+
+def test_restoring_a_course_with_nothing_saved_hides_its_id(store):
+ outcome = account_sync.restore_course(signed_in_state(), "course-1")
+ assert not outcome.success
+ assert outcome.message == "Nothing saved for this course yet."
+ assert "course-1" not in outcome.message
+
+
+def test_restore_with_nothing_saved_does_not_block_later_saves(store):
+ course = make_course()
+ state = signed_in_state()
+
+ assert account_sync.restore_course(state, course.course_id).message == (
+ account_sync.NOTHING_SAVED_MESSAGE
+ )
+ assert account_sync.save_course_to_account(state, course).success
+ assert account_sync.save_course_with_history(state, course).success
+ assert course.course_id in store.courses[TEST_USER.user_id]
+
+
+def test_failed_restore_still_blocks_later_saves(store):
+ course = make_course()
+ seed(store, TEST_USER, course)
+ store.fail_course_ids.add(course.course_id)
+ state = signed_in_state()
+
+ assert not account_sync.restore_course(state, course.course_id).success
+ assert not account_sync.save_course_to_account(state, course).success
+ assert not account_sync.save_course_with_history(state, course).success
+ assert store.names("save_course") == []
+
+ # A later restore that finds nothing stored clears the earlier block.
+ store.fail_course_ids.clear()
+ del store.courses[TEST_USER.user_id][course.course_id]
+ account_sync.restore_course(state, course.course_id)
+ assert account_sync.save_course_to_account(state, course).success
def test_app_restores_once_per_login_despite_reruns(store):
@@ -393,12 +432,17 @@ def test_failed_login_restore_shows_retry_and_keeps_local_state(store):
app.run()
assert [w.value for w in app.warning if "could not be restored" in w.value]
+ assert not [w for w in app.warning if "list failed" in w.value]
assert len(store.names("list")) == 1
store.fail.clear()
app.button(key="retry_restore").click().run()
assert not app.exception
+ assert app.session_state["account_sync"]["restore_errors"] == []
+ # A successful retry shows nothing in that spot. AppTest keeps the element
+ # from before st.rerun() when nothing replaces it, so render once more.
+ app.run()
assert not [w for w in app.warning if "could not be restored" in w.value]
assert "s1" in app.session_state["practice_history_course-1"]
@@ -449,7 +493,9 @@ def test_practice_submit_saves_course_then_exam_for_signed_in_user(store):
)
saved_attempts = store.exams[TEST_USER.user_id]["session-1"][2]
assert [a.selected_index for a in saved_attempts] == [1]
- assert not [w for w in app.warning if "Not saved" in w.value]
+ assert not [w for w in app.warning if "Couldn't save" in w.value]
+ # A successful save is not announced on the result page.
+ assert not [c for c in app.caption if c.value == "Saved to your account."]
def test_practice_submit_failure_warns_and_keeps_local_history(store):
@@ -467,7 +513,8 @@ def test_practice_submit_failure_warns_and_keeps_local_history(store):
assert not app.exception
assert "session-1" in app.session_state["practice_history_course-1"]
- assert [w for w in app.warning if "Not saved to your account" in w.value]
+ assert [w.value for w in app.warning] == [account_sync.SAVE_FAILED_MESSAGE]
+ assert not [w for w in app.warning if "exam save failed" in w.value]
assert not [c for c in app.caption if c.value == "Saved to your account."]
@@ -485,14 +532,12 @@ def test_study_hub_save_button_reports_success_and_failure(store):
app.button(key="database_save_course-1").click().run()
assert not app.exception
- assert [s.value for s in app.success] == [
- "Course and practice history saved to your account."
- ]
+ assert [s.value for s in app.success] == ["Saved to your account."]
assert course.course_id in store.courses[TEST_USER.user_id]
store.fail.add("save_course")
app.button(key="database_save_course-1").click().run()
- assert [e.value for e in app.error] == ["course save failed"]
+ assert [e.value for e in app.error] == [account_sync.SAVE_FAILED_MESSAGE]
assert not app.success
@@ -509,10 +554,39 @@ def test_study_hub_restore_button_replaces_course_and_reports_failure(store):
store.fail_course_ids.add("course-1")
app.button(key="database_restore_course-1").click().run()
- assert [e.value for e in app.error] == ["course-1: load failed"]
+ assert [e.value for e in app.error] == [account_sync.RESTORE_FAILED_MESSAGE]
assert app.session_state["current_course"].course_name == "Saved Name"
+def test_study_hub_restore_of_unsaved_course_says_nothing_is_saved(store):
+ app = study_hub_app(make_course("course-1", "Local Name"))
+ app.run()
+
+ app.button(key="database_restore_course-1").click().run()
+
+ assert not app.exception
+ assert [i.value for i in app.info if "Nothing saved" in i.value] == [
+ "Nothing saved for this course yet."
+ ]
+ assert not app.error
+ assert not any(
+ "course-1" in element.value
+ for element in [*app.info, *app.error, *app.caption]
+ )
+
+
+def test_successful_login_restore_shows_no_status_message(store):
+ course = make_course()
+ seed(store, TEST_USER, course, make_exam(course, "s1"))
+ app = signed_in_app(APP_PATH)
+ app.run()
+
+ assert not app.exception
+ texts = [item.value for item in [*app.caption, *app.warning, *app.success]]
+ assert not any("Restored" in text or "restored" in text for text in texts)
+ assert not any("No saved study records" in text for text in texts)
+
+
def test_regenerated_questions_keep_saved_history_restorable(store):
old = make_course("course-1", "Economics")
state = signed_in_state()
@@ -617,3 +691,70 @@ def test_has_unresolved_conflicts_tracks_quarantined_records():
assert account_sync.has_unresolved_conflicts(session_state)
session_state["account_sync"]["restore_conflicts"] = {}
assert not account_sync.has_unresolved_conflicts(session_state)
+
+
+def test_dashboard_save_failure_warning_survives_the_rerun(store, monkeypatch):
+ from types import SimpleNamespace
+
+ import streamlit as st
+
+ from services import ai_service
+
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ uploaded = SimpleNamespace(name="notes.txt", getvalue=lambda: b"Course notes.")
+ monkeypatch.setattr(st, "file_uploader", lambda *_args, **_kwargs: uploaded)
+
+ def generate_topics(document, course_id, course_name):
+ return {"ok": True, "package": {
+ "course_id": course_id, "course_name": course_name,
+ "topics": [{"id": "t1", "name": "Topic", "summary": "Summary."}],
+ "relationships": [], "questions": [],
+ }}
+
+ monkeypatch.setattr(ai_service, "generate_topics", generate_topics)
+ store.fail.add("save_course")
+ app = signed_in_app(ROOT / "pages" / "0_Dashboard.py").run()
+ app.button(key="create_course_button").click().run()
+ app.text_input(key="setup_course_name").set_value("New course").run()
+ next(b for b in app.button if b.label == "Extract text").click().run()
+ next(b for b in app.button if b.label == "Generate topics").click().run()
+
+ assert not app.exception
+ assert store.names("save_course")
+ warnings = [w.value for w in app.warning]
+ assert warnings.count(account_sync.SAVE_FAILED_MESSAGE) == 1
+ assert not any("course save failed" in text for text in warnings)
+
+ # Shown once: the next run no longer repeats it.
+ app.run()
+ assert account_sync.SAVE_FAILED_MESSAGE not in [w.value for w in app.warning]
+
+
+def test_study_hub_save_says_restore_first_when_a_failed_restore_blocks_saving(store):
+ course = make_course()
+ app = study_hub_app(course)
+ app.run()
+ state = app.session_state[account_sync.STATE_KEY]
+ state["failed_course_ids"].add(course.course_id)
+ app.session_state[account_sync.STATE_KEY] = state
+
+ app.button(key="database_save_course-1").click().run()
+
+ assert not app.exception
+ assert [e.value for e in app.error] == [account_sync.RESTORE_FIRST_MESSAGE]
+
+
+def test_study_hub_keeps_the_failed_save_warning_after_confirming_the_scope(store):
+ course = make_course()
+ app = study_hub_app(course)
+ app.run()
+ store.fail.add("save_course")
+
+ app.button_group(key=f"scope_selection_{course.course_id}").set_value([course.topics[0].id]).run()
+ next(b for b in app.button if b.label == "Confirm exam scope").click().run()
+
+ assert not app.exception
+ assert account_sync.SAVE_FAILED_MESSAGE in [w.value for w in app.warning]
+ # Shown once: the next run no longer repeats it.
+ app.run()
+ assert account_sync.SAVE_FAILED_MESSAGE not in [w.value for w in app.warning]
diff --git a/tests/test_account_ui.py b/tests/test_account_ui.py
index 2e05b96..93e780b 100644
--- a/tests/test_account_ui.py
+++ b/tests/test_account_ui.py
@@ -83,16 +83,33 @@ def test_account_page_displays_canonical_read_only_identity():
assert "clears when you log out" in " ".join(caption.value for caption in app.caption)
-def test_dashboard_header_identifies_the_signed_in_account_and_links_to_account():
+def test_sidebar_identifies_the_signed_in_account_and_links_to_account():
app = signed_in_app(APP_PATH).run()
assert not app.exception
- header_text = " ".join(item.value for item in app.markdown)
- assert TEST_USER.username in header_text
- assert "SIGNED IN AS" in header_text
- assert any(link.proto.label == "My account" for link in app.get("page_link"))
- assert app.button(key="logout_button").label == "Log out"
- assert not app.sidebar.get("page_link")
+ sidebar_text = " ".join(item.value for item in app.sidebar.markdown)
+ assert TEST_USER.username in sidebar_text
+ assert "SIGNED IN AS" in sidebar_text
+ assert [link.proto.label for link in app.sidebar.get("page_link")] == ["My account"]
+ assert app.sidebar.button(key="logout_button").label == "Log out"
+ # Account controls live only in the sidebar, not in a top header row.
+ assert not [link for link in app.main.get("page_link") if link.proto.label == "My account"]
+ assert not [button for button in app.main.button if button.key == "logout_button"]
+
+
+def test_accessibility_settings_sit_in_the_sidebar_under_the_account():
+ app = signed_in_app(APP_PATH).run()
+
+ assert not app.exception
+ assert [item.label for item in app.sidebar.expander] == ["Accessibility settings"]
+ assert [item.key for item in app.sidebar.toggle] == ["a11y_simplify", "_ui_chinese_toggle"]
+ assert not app.main.get("toggle")
+
+ next(item for item in app.sidebar.toggle if item.key == "_ui_chinese_toggle").set_value(True).run()
+
+ assert not app.exception
+ assert [item.label for item in app.sidebar.expander] == ["无障碍设置"]
+ assert app.sidebar.button(key="logout_button").label == "退出登录"
@pytest.mark.parametrize("logout_location", ["sidebar", "account_page"])
diff --git a/tests/test_ai_service.py b/tests/test_ai_service.py
index bfe6990..0801d73 100644
--- a/tests/test_ai_service.py
+++ b/tests/test_ai_service.py
@@ -164,6 +164,7 @@ def make_relationships(edges=None):
def api_error(status_code, message):
classes = {
+ 400: anthropic.BadRequestError,
401: anthropic.AuthenticationError,
403: anthropic.PermissionDeniedError,
404: anthropic.NotFoundError,
@@ -581,15 +582,16 @@ def test_generate_topics_missing_api_key_does_not_create_client(monkeypatch):
assert result["ok"] is False
assert result["error_code"] == "MISSING_API_KEY"
- assert result["message"] == "ANTHROPIC_API_KEY is not configured."
+ assert result["message"] == "AI generation is unavailable right now."
@pytest.mark.parametrize(
("status_code", "expected_message"),
[
- (401, "API key was rejected"),
- (403, "not allowed to use"),
- (404, "not available to this account"),
+ (401, "AI generation is unavailable right now."),
+ (403, "AI generation is unavailable right now."),
+ (404, "AI generation is unavailable right now."),
+ (400, "AI generation is unavailable right now. Try again later."),
(429, "quota or rate limit"),
(500, "temporarily unavailable"),
(503, "temporarily unavailable"),
@@ -609,6 +611,8 @@ def test_generate_topics_explains_api_errors_without_leaking(
assert result["error_code"] == "API_ERROR"
assert result["status_code"] == status_code
assert expected_message in result["message"]
+ assert "ANTHROPIC" not in result["message"]
+ assert "configur" not in result["message"]
assert FAKE_API_KEY not in str(result)
assert private_message not in str(result)
@@ -1152,7 +1156,7 @@ def test_ask_tutor_rejects_missing_api_key_without_creating_client(monkeypatch):
assert result == {
"ok": False,
"error_code": "MISSING_API_KEY",
- "message": "ANTHROPIC_API_KEY is not configured.",
+ "message": "AI generation is unavailable right now.",
}
@@ -1263,6 +1267,8 @@ def test_ask_tutor_handles_api_errors_without_exposing_details(
assert result["error_code"] == "API_ERROR"
assert result["status_code"] == status_code
assert expected_message in result["message"]
+ assert "ANTHROPIC" not in result["message"]
+ assert "configur" not in result["message"]
assert FAKE_API_KEY not in str(result)
assert private_message not in str(result)
assert "Private question text." not in str(result)
diff --git a/tests/test_auth_ui.py b/tests/test_auth_ui.py
index 5c5cc27..637ca6b 100644
--- a/tests/test_auth_ui.py
+++ b/tests/test_auth_ui.py
@@ -8,7 +8,7 @@
from streamlit.testing.v1 import AppTest
from services import auth_ui
-from services.i18n import LANGUAGE_KEY
+from services.i18n import LANGUAGE_KEY, LANGUAGE_WIDGET_KEY
from services.auth_service import AuthResult, AuthUser
from tests.auth_helpers import TEST_USER, signed_in_app
@@ -62,13 +62,47 @@ def test_logged_out_app_shows_account_forms_before_dashboard(monkeypatch) -> Non
register.assert_not_called()
+def test_sign_in_page_shows_headline_campus_watercolour_then_account_card(monkeypatch) -> None:
+ import base64
+
+ import streamlit as st
+
+ logos = []
+ monkeypatch.setattr(st, "logo", lambda *args, **kwargs: logos.append((args, kwargs)))
+ app = AppTest.from_file(str(APP_PATH)).run()
+
+ assert_auth_gate(app)
+ assert [title.value for title in app.title] == ["Make your next study session count."]
+ campus = (APP_PATH.parent / "assets" / "illustrations" / "campus-watercolor.webp").read_bytes()
+ art = next(item.value for item in app.markdown if 'class="auth-campus"' in item.value)
+ assert f'src="data:image/webp;base64,{base64.b64encode(campus).decode("ascii")}"' in art
+ assert 'alt="Illustration of a university campus"' in art
+ assert not any("campus-illustration" in item.value for item in app.markdown)
+ # Headline and picture come first, then the Log in / Create account card.
+ main = list(app.main)
+ title_at = next(i for i, node in enumerate(main) if node.type == "title")
+ art_at = next(
+ i for i, node in enumerate(main)
+ if node.type == "markdown" and 'class="auth-campus"' in node.value
+ )
+ card_at = next(
+ i for i, node in enumerate(main)
+ if str(getattr(node.proto, "id", "")).endswith("-auth_forms")
+ )
+ assert title_at < art_at < card_at
+ # The sign-in page has no navigation, so it has no sidebar either.
+ assert not app.sidebar.children
+ assert [Path(args[0]).name for args, _ in logos] == ["brand-logo.svg"]
+ assert "icon_image" not in logos[0][1]
+
+
def test_login_language_switch_translates_interface_without_database_calls(monkeypatch) -> None:
login = Mock()
register = Mock()
monkeypatch.setattr(auth_ui, "login_user", login)
monkeypatch.setattr(auth_ui, "register_user", register)
app = AppTest.from_file(str(APP_PATH)).run()
- next(item for item in app.get("toggle") if item.key == LANGUAGE_KEY).set_value(True).run()
+ next(item for item in app.get("toggle") if item.key == LANGUAGE_WIDGET_KEY).set_value(True).run()
assert not app.exception
assert [tab.label for tab in app.tabs] == ["登录", "创建账户"]
@@ -85,7 +119,7 @@ def test_chinese_choice_continues_to_dashboard_after_login(monkeypatch) -> None:
Mock(return_value=AuthResult(success=True, user=TEST_USER, message="Signed in.")),
)
app = AppTest.from_file(str(APP_PATH)).run()
- next(item for item in app.get("toggle") if item.key == LANGUAGE_KEY).set_value(True).run()
+ next(item for item in app.get("toggle") if item.key == LANGUAGE_WIDGET_KEY).set_value(True).run()
app.text_input(key="login_username").set_value(TEST_USER.username)
app.text_input(key="login_password").set_value(PASSWORD)
next(button for button in app.button if button.label == "登录").click().run()
diff --git a/tests/test_dashboard_i18n.py b/tests/test_dashboard_i18n.py
new file mode 100644
index 0000000..f4e5bff
--- /dev/null
+++ b/tests/test_dashboard_i18n.py
@@ -0,0 +1,72 @@
+"""Dashboard interface strings follow the Chinese interface setting."""
+
+from pathlib import Path
+
+import pytest
+from streamlit.testing.v1 import AppTest
+
+from models.schemas import ExamSession, Question, StudyPackage
+from services.i18n import LANGUAGE_KEY
+
+DASHBOARD_PATH = Path(__file__).resolve().parents[1] / "pages" / "0_Dashboard.py"
+
+
+def make_course() -> StudyPackage:
+ return StudyPackage(
+ course_id="my-course",
+ course_name="Biology",
+ topics=[{"id": "t1", "name": "Cells", "summary": "Summary."}],
+ relationships=[],
+ questions=[
+ Question(
+ id="q1", topic_id="t1", question="Question?",
+ options=["a", "b", "c", "d"], correct_index=0, explanation="Because.",
+ )
+ ],
+ )
+
+
+def dashboard(chinese: bool, **state) -> AppTest:
+ app = AppTest.from_file(str(DASHBOARD_PATH))
+ app.session_state[LANGUAGE_KEY] = chinese
+ for key, value in state.items():
+ app.session_state[key] = value
+ return app.run()
+
+
+@pytest.mark.parametrize("chinese,label", [(False, "Open Study Plan"), (True, "打开学习计划")])
+def test_open_study_plan_button_follows_language(chinese, label):
+ course = make_course()
+ app = dashboard(chinese, courses=[course], current_course=course)
+
+ assert not app.exception
+ assert app.button(key="dashboard_continue_learning").label == label
+
+
+@pytest.mark.parametrize("chinese,label", [(False, "Continue practice"), (True, "继续练习")])
+def test_continue_practice_button_follows_language(chinese, label):
+ course = make_course()
+ session = ExamSession(session_id="s1", mode="mock", question_ids=["q1"])
+ app = dashboard(
+ chinese, courses=[course], current_course=course,
+ **{
+ "confirmed_scope_my-course": ["t1"],
+ "active_practice_my-course": {"session": session, "questions": course.questions},
+ },
+ )
+
+ assert not app.exception
+ assert app.button(key="dashboard_continue_learning").label == label
+
+
+@pytest.mark.parametrize("chinese,expected", [
+ (False, "Delete Biology? Its materials and practice progress will be removed from this session."),
+ (True, "删除“Biology”?课程资料和练习进度将从本次会话中移除。"),
+])
+def test_delete_course_confirmation_follows_language(chinese, expected):
+ course = make_course()
+ app = dashboard(chinese, courses=[course], current_course=None)
+ app.button(key="remove_course_my-course").click().run()
+
+ assert not app.exception
+ assert expected in [item.value for item in app.warning]
diff --git a/tests/test_exam_engine.py b/tests/test_exam_engine.py
index f62d3a4..69d00a5 100644
--- a/tests/test_exam_engine.py
+++ b/tests/test_exam_engine.py
@@ -90,8 +90,16 @@ def test_create_exam_topic_mode_can_narrow_to_a_confirmed_topic(
assert session.question_ids == ["q2"]
assert [question.id for question in questions] == ["q2"]
- assert result["warning"] is not None
- assert "only 1 are available" in result["warning"]
+ assert result["warning"] == "1 question available; included."
+
+
+def test_create_exam_availability_notice_is_short_and_plural(
+ package: StudyPackage,
+) -> None:
+ result = create_exam(package, "mock", 10, ["topic-a", "topic-b"])
+
+ assert len(result["questions"]) == 3
+ assert result["warning"] == "3 questions available; all included."
@pytest.mark.parametrize(
diff --git a/tests/test_generation_availability.py b/tests/test_generation_availability.py
index 2bcf299..6d43ac4 100644
--- a/tests/test_generation_availability.py
+++ b/tests/test_generation_availability.py
@@ -9,7 +9,7 @@
ROOT = Path(__file__).resolve().parents[1]
DASHBOARD_PATH = ROOT / "pages" / "0_Dashboard.py"
STUDY_PLAN_PATH = ROOT / "pages" / "1_Study_Hub.py"
-UNAVAILABLE_TEXT = "ANTHROPIC_API_KEY is not configured"
+UNAVAILABLE_TEXT = "AI generation is unavailable right now."
def dashboard_with_extracted_text(monkeypatch) -> AppTest:
@@ -51,6 +51,7 @@ def test_dashboard_disables_topic_generation_without_api_key(monkeypatch):
assert generate_topics_button(app).disabled
assert any(UNAVAILABLE_TEXT in item.value for item in app.info)
+ assert not any("ANTHROPIC_API_KEY" in item.value for item in app.info)
def test_dashboard_enables_topic_generation_with_api_key(monkeypatch):
@@ -70,6 +71,7 @@ def test_study_plan_disables_question_generation_without_api_key(monkeypatch):
assert not app.exception
assert app.button(key="generate_questions_course-1").disabled
assert any(UNAVAILABLE_TEXT in item.value for item in app.info)
+ assert not any("ANTHROPIC_API_KEY" in item.value for item in app.info)
def test_study_plan_enables_question_generation_with_api_key(monkeypatch):
diff --git a/tests/test_graph_exploration.py b/tests/test_graph_exploration.py
index 3b2e159..6e53819 100644
--- a/tests/test_graph_exploration.py
+++ b/tests/test_graph_exploration.py
@@ -45,7 +45,15 @@ def test_missing_topic_is_rejected(course):
fn(course, "not-a-topic")
-def test_search_shows_summary_and_local_graph_preserves_original_course(course):
+def test_search_shows_summary_and_local_graph_preserves_original_course(course, monkeypatch):
+ from components import knowledge_graph
+
+ rendered = []
+ monkeypatch.setattr(
+ knowledge_graph,
+ "agraph",
+ lambda nodes, edges, config, node_scale: rendered.append(nodes) or None,
+ )
app = AppTest.from_file(str(ROOT / "pages/4_Knowledge_Graph.py"))
app.session_state["current_course"] = course
app.run()
@@ -53,9 +61,13 @@ def test_search_shows_summary_and_local_graph_preserves_original_course(course):
assert not app.exception
assert any(header.value == "Summary" for header in app.subheader)
assert any("Limits describe" in entry.value for entry in app.markdown)
+ assert len(rendered[-1]) == 3
app.toggle(key="graph_local_calculus-i-demo").set_value(True).run()
assert not app.exception
- assert any("Showing 2 of 3" in entry.value for entry in app.caption)
+ # The local graph draws only the topic and its neighbour; the topic and
+ # connection counts are no longer printed for students.
+ assert [node.id for node in rendered[-1]] == ["calc_limits", "calc_derivatives"]
+ assert not any(entry.value.startswith("Showing ") for entry in app.caption)
assert len(app.session_state["current_course"].topics) == 3
app.selectbox(key="graph_focus_calculus-i-demo").set_value(None).run()
assert not app.exception
diff --git a/tests/test_guided_limits.py b/tests/test_guided_limits.py
index 918f5b1..84b3b85 100644
--- a/tests/test_guided_limits.py
+++ b/tests/test_guided_limits.py
@@ -31,7 +31,7 @@ def test_demo_launches_from_dashboard_and_keeps_answer_hints():
assert session.mode == "topic"
assert session.question_ids == [guided_limits_ui.QUESTION_ID]
assert app.session_state[f"confirmed_scope_{COURSE_ID}"] == [guided_limits_ui.TOPIC_ID]
- assert any(button.label == "Show a hint" for button in app.button)
+ assert any(button.label == "Hint" for button in app.button)
def test_starter_does_not_replace_an_existing_scope():
@@ -87,3 +87,26 @@ def save_flag(*args):
assert app.session_state[key]["complete"]
assert "Solved after a retry." in [item.value for item in app.caption]
assert result["correct_count"] == 0
+
+
+def test_guided_review_heading_and_unanswered_follow_chinese_setting():
+ from services.i18n import LANGUAGE_KEY
+
+ course = calculus()
+ question = guided_limits_ui.starter_question(course)
+ state = {"courses": [course]}
+ guided_limits_ui.start_demo(state, course, question)
+ session = state[f"active_practice_{COURSE_ID}"]["session"]
+ result = grade_exam(session, [question], {question.id: None})
+ app = AppTest.from_string(
+ "import streamlit as st\n"
+ "from services.guided_limits_ui import render_guided_review\n"
+ "render_guided_review(*st.session_state['fixture'])\n"
+ )
+ app.session_state["fixture"] = (course, session, [question], result)
+ app.session_state[LANGUAGE_KEY] = True
+ app.run()
+
+ assert not app.exception
+ assert "微积分 I · 极限" in [item.value for item in app.caption]
+ assert "**第一次答案:** 未作答" in [item.value for item in app.markdown]
diff --git a/tests/test_hints.py b/tests/test_hints.py
index 4a48a6e..de34289 100644
--- a/tests/test_hints.py
+++ b/tests/test_hints.py
@@ -113,7 +113,7 @@ def test_topic_hints_reveal_in_order_preserve_answer_and_leave_score_unchanged(u
answer_key = f"answer_{session.session_id}_{question.id}"
button_key = f"hint_button_{session.session_id}_{question.id}"
- assert app.button(key=button_key).label == "Show a hint"
+ assert app.button(key=button_key).label == "Hint"
assert not [item for item in app.info if item.value.startswith("Hint ")]
app.radio(key=answer_key).set_value(question.correct_index).run()
@@ -128,7 +128,7 @@ def test_topic_hints_reveal_in_order_preserve_answer_and_leave_score_unchanged(u
assert app.radio(key=answer_key).value == question.correct_index
assert app.session_state[hint_state_key(session.session_id, question.id)] == number
if number < len(hints):
- assert app.button(key=button_key).label == "Show next hint"
+ assert app.button(key=button_key).label == "Next hint"
else:
assert all(button.key != button_key for button in app.button)
@@ -185,7 +185,7 @@ def test_hint_text_shows_chinese_key_terms_only_when_toggle_is_on(bilingual):
def test_hints_are_absent_during_practice_and_review_when_unavailable(mode, use_demo_question):
app, _, _ = start_practice(mode, use_demo_question=use_demo_question)
- assert not any(button.label in {"Show a hint", "Show next hint"} for button in app.button)
+ assert not any(button.label in {"Hint", "Next hint"} for button in app.button)
assert not any(item.value.startswith("Hint ") for item in app.info)
next(button for button in app.button if button.label == "Submit answers").click().run()
diff --git a/tests/test_i18n.py b/tests/test_i18n.py
index f2db19c..953eb22 100644
--- a/tests/test_i18n.py
+++ b/tests/test_i18n.py
@@ -58,3 +58,24 @@ def test_chinese_page_headings_without_rewriting_course(
assert not app.exception
assert app.title[0].value == expected_title
assert app.session_state["current_course"].course_id == course.course_id
+
+
+def test_language_survives_widget_cleanup_and_can_switch_back() -> None:
+ app = AppTest.from_string("""
+import streamlit as st
+from services.i18n import render_language_control, tr
+if st.session_state.get("show_control", True):
+ render_language_control()
+st.title(tr("Practice"))
+""").run()
+ app.toggle[0].set_value(True).run()
+ assert app.title[0].value == "练习"
+ app.session_state["show_control"] = False
+ app.run().run()
+ assert app.session_state[LANGUAGE_KEY] is True
+ assert app.title[0].value == "练习"
+ app.session_state["show_control"] = True
+ app.run()
+ assert app.toggle[0].value is True
+ app.toggle[0].set_value(False).run()
+ assert app.title[0].value == "Practice"
diff --git a/tests/test_knowledge_graph.py b/tests/test_knowledge_graph.py
index 978e2bf..6a30712 100644
--- a/tests/test_knowledge_graph.py
+++ b/tests/test_knowledge_graph.py
@@ -1,4 +1,5 @@
import json
+import re
from contextlib import nullcontext
from pathlib import Path
from unittest.mock import Mock
@@ -636,7 +637,7 @@ def test_render_topic_details_displays_topic_statistics(monkeypatch):
accuracy_column.metric.assert_called_once_with("Accuracy", "66.67%")
-def test_render_topic_details_shows_missing_pages_message(monkeypatch):
+def test_render_topic_details_shows_no_source_line_without_pages(monkeypatch):
caption = Mock()
monkeypatch.setattr(
knowledge_graph.st,
@@ -658,7 +659,8 @@ def test_render_topic_details_shows_missing_pages_message(monkeypatch):
}
)
- caption.assert_called_once_with("Source pages not provided")
+ # Storage bookkeeping is not shown to students.
+ caption.assert_not_called()
def test_render_topic_details_prompts_when_no_topic_is_selected(monkeypatch):
@@ -931,7 +933,10 @@ def _graph_page(course, *, signed_in=False, focus=None):
def _markdown(app):
- return [item.value for item in app.markdown]
+ # The injected stylesheet is a markdown element too; it is not page content.
+ return [
+ item.value for item in app.markdown if not item.value.lstrip().startswith("