diff --git a/assets/academic_ui.css b/assets/academic_ui.css
index 545c6b0..3a0e3b1 100644
--- a/assets/academic_ui.css
+++ b/assets/academic_ui.css
@@ -48,20 +48,6 @@
margin: 0 0 1rem;
}
.st-key-dashboard_actions { max-width: 850px; padding: 0 0 1.6rem; }
-.st-key-dashboard_actions button {
- min-height: 5.3rem !important;
- border-radius: 1rem !important;
- border-color: #dce7f7 !important;
- justify-content: flex-start !important;
- padding: 1rem 1.6rem !important;
- box-shadow: 0 5px 18px rgba(34,88,160,.035);
-}
-.st-key-dashboard_actions button p { font-size: 1.15rem !important; font-weight: 700 !important; }
-.st-key-dashboard_actions [data-testid="stIconMaterial"] { font-size: 2rem !important; color: #2166db; }
-div.st-key-create_course_button { width: 100% !important; margin: 0; }
-div.st-key-create_course_button button { max-width: none !important; width: 100% !important; justify-content: flex-start !important; }
-div.st-key-create_course_button button > div,
-div.st-key-create_course_button button > div > span { justify-content: flex-start !important; }
.st-key-dashboard_overview { margin: .5rem 0 1.5rem; }
:is(.st-key-dashboard_overview, .st-key-progress_overview, .st-key-practice_result_overview) [data-testid="stMetric"] {
background: rgba(255,255,255,.85);
@@ -132,7 +118,6 @@ div.st-key-create_course_button button > div > span { justify-content: flex-star
[data-testid="stMain"] .exam-hero::after { width: 75%; opacity: .3; }
[data-testid="stMain"] .exam-hero h1 { font-size: clamp(2.15rem, 7vw, 3rem); }
[data-testid="stMain"] .exam-hero p { font-size: 1rem; }
- .st-key-dashboard_actions button { min-height: 4.3rem !important; }
}
@media (max-width: 480px) {
:root { --exam-font-page: 2rem; --exam-font-heading: 1.5rem; --exam-font-stat: 1.8rem; }
@@ -145,16 +130,9 @@ div.st-key-create_course_button button > div > span { justify-content: flex-star
font-size: 1.5rem !important; padding: 0; line-height: 1.25;
}
-.st-key-dashboard_actions div.st-key-create_course_button button {
- min-height: 5.3rem !important;
-}
-.st-key-dashboard_actions button > div > span { gap: .8rem !important; }
[class*="st-key-dashboard_course_card_"] [data-testid="stHorizontalBlock"]:has(.academic-course-icon) {
flex-wrap: nowrap;
}
-@media (max-width: 768px) {
- .st-key-dashboard_actions div.st-key-create_course_button button { min-height: 4.3rem !important; }
-}
[class*="st-key-study_topic_"] [data-testid="stCheckbox"] { padding-top: .3rem; }
[class*="st-key-study_topic_"] [data-testid="stHorizontalBlock"] { align-items: flex-start; flex-wrap: nowrap; }
diff --git a/assets/paper_shell.css b/assets/paper_shell.css
index 04a4570..3568f3c 100644
--- a/assets/paper_shell.css
+++ b/assets/paper_shell.css
@@ -724,20 +724,6 @@ label[data-baseweb="radio"]:focus-within {
}
-/* Home: "Create course" reads as a quiet card, not a filled block. */
-[data-testid="stMain"] .st-key-dashboard_actions div.st-key-create_course_button button {
- background: var(--paper-card) !important;
- border: 1px solid var(--paper-line) !important;
- border-radius: 14px !important;
- min-height: 3.6rem !important;
- color: var(--ink) !important;
- box-shadow: none !important;
-}
-[data-testid="stMain"] .st-key-dashboard_actions div.st-key-create_course_button button:hover {
- background: var(--paper-panel) !important;
- border-color: #D9CFC2 !important;
-}
-
/* ---- Loading: a paper plane instead of a spinner --------------------------- */
/* The brand plane (assets/brand-plane.svg), inlined so the sheet stays one file. */
:root {
diff --git a/assets/paper_zzzzz_results.css b/assets/paper_zzzzz_results.css
new file mode 100644
index 0000000..5991bc0
--- /dev/null
+++ b/assets/paper_zzzzz_results.css
@@ -0,0 +1,58 @@
+/* The Home page inherits exactly the same action palette and shape as study pages. */
+[data-testid="stMain"] .st-key-dashboard_actions div.st-key-create_course_button { width: fit-content !important; }
+[data-testid="stMain"] .st-key-dashboard_actions button {
+ min-height: var(--ep-control-height) !important; border-radius: var(--ep-radius-pill) !important;
+ border: 1px solid var(--ep-border) !important; background: var(--paper-badge) !important;
+ color: var(--ep-text-primary) !important; padding: .55rem 1.1rem !important;
+ box-shadow: none; justify-content: center !important;
+}
+[data-testid="stMain"] .st-key-dashboard_actions button p { font-size: var(--ep-type-body) !important; font-weight: 500 !important; }
+[data-testid="stMain"] .st-key-dashboard_actions [data-testid="stIconMaterial"] { font-size: 1.2rem !important; color: inherit !important; }
+[data-testid="stMain"] .st-key-dashboard_actions button:hover { background: var(--paper-select) !important; border-color: var(--ep-action) !important; }
+/* Results: compact vertical metrics, one central primary action, next step on the right. */
+[data-testid="stMain"] .st-key-result_review_action button { min-height: 4rem; font-size: 1.1rem; }
+[data-testid="stMain"] .st-key-result_review_action button p { font-size: 1.1rem; font-weight: 600; }
+[data-testid="stMain"] .st-key-flight_next_topic h3 { font-size: var(--ep-type-section); }
+[data-testid="stMain"] .st-key-practice_result_overview [data-testid="stMetric"] { border: 0; background: transparent; min-height: 0; padding: .6rem .8rem; }
+[data-testid="stMain"] .st-key-practice_result_overview [data-testid="stMetricValue"] { font-size: 1.8rem; }
+[data-testid="stMain"] .st-key-result_score,
+[data-testid="stMain"] .st-key-result_accuracy { background: var(--ep-surface-panel); }
+/* Rankings: number, topic, difficulty reasons and student count have separate roles. */
+.radar-ranking-scroll { border-radius: var(--ep-radius-panel); padding-inline: .25rem; }
+.radar-ranking-scroll ol { display: grid; gap: .5rem; }
+.radar-ranking-scroll .radar-ranked-row {
+ display: grid; grid-template-columns: 2rem minmax(0, 1fr) auto;
+ grid-template-areas: 'rank topic total' 'rank reasons total';
+ gap: .35rem .75rem; align-content: center; align-items: center;
+ border: 1px solid var(--ep-border); border-radius: var(--ep-radius-control);
+ background: var(--ep-surface-panel); padding: .75rem 1rem; height: 7.5rem;
+}
+.radar-rank-badge { grid-area: rank; display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: 50%; background: var(--ep-surface-subtle); color: var(--ep-text-primary); font-weight: 700; }
+.radar-rank-title { grid-area: topic; font-size: 1rem; line-height: 1.4; }
+.radar-flag-total { grid-area: total; display: grid; place-items: center; min-width: 5rem; padding: .35rem .6rem; border-radius: var(--ep-radius-control); background: var(--ep-surface-subtle); color: var(--ep-text-primary); }
+.radar-flag-total b { font-size: 1.4rem; font-weight: 650; line-height: 1.2; }
+.radar-flag-total span { font-size: .7rem; }
+.radar-reason-chips { grid-area: reasons; display: flex; flex-wrap: wrap; gap: .3rem; }
+.radar-reason-chips .radar-reason-chip { display: inline-block; font-size: .75rem; line-height: 1.4; border: 1px solid var(--ep-border); border-radius: var(--ep-radius-pill); padding: .2rem .5rem; color: var(--ep-text-secondary); background: var(--ep-surface-panel); }
+/* Five cards plus four gaps, preserving the requested five visible entries. */
+.radar-ranking-scroll { max-height: 39.5rem; }
+/* One fixed landscape behind both navigation and content; no replacement on collapse. */
+[data-testid="stAppViewContainer"] { background: var(--ep-surface-page); background-image: var(--paper-landscape-left), var(--paper-landscape-right); background-repeat: no-repeat; background-position: left bottom, right bottom; background-size: 228px auto, 354px auto; background-attachment: fixed; }
+[data-testid="stAppViewContainer"] [data-testid="stMain"] { background-image: none !important; }
+[data-testid="stAppViewContainer"] section[data-testid="stSidebar"] { background: transparent; }
+.st-key-sidebar_accessibility::before { display: none; }
+@media (max-width: 760px) {
+ [data-testid="stAppViewContainer"] section[data-testid="stSidebar"] { background: var(--ep-surface-page); }
+ .radar-ranking-scroll .radar-ranked-row { grid-template-columns: 1.5rem minmax(0,1fr) 3.5rem; gap: .3rem .5rem; padding: .5rem; }
+ .radar-rank-badge { width: 1.5rem; height: 1.5rem; }
+ .radar-flag-total { min-width: 0; padding: .25rem; }
+ .radar-reason-chips .radar-reason-chip { font-size: .7rem; }
+}
+@media (min-width: 1000px) {
+ [data-testid="stMain"] .st-key-practice_result_overview > [data-testid="stLayoutWrapper"] > [data-testid="stHorizontalBlock"] > [data-testid="stColumn"]:nth-child(1) { flex: 1 1 12rem !important; }
+ [data-testid="stMain"] .st-key-practice_result_overview > [data-testid="stLayoutWrapper"] > [data-testid="stHorizontalBlock"] > [data-testid="stColumn"]:nth-child(2) { flex: 1.2 1 14rem !important; }
+ [data-testid="stMain"] .st-key-practice_result_overview > [data-testid="stLayoutWrapper"] > [data-testid="stHorizontalBlock"] > [data-testid="stColumn"]:nth-child(3) { flex: 1.6 1 18rem !important; }
+}
+@media (max-width: 999px) {
+ [data-testid="stMain"] .st-key-practice_result_overview > [data-testid="stLayoutWrapper"] > [data-testid="stHorizontalBlock"] > [data-testid="stColumn"] { flex: 1 1 100% !important; width: 100% !important; min-width: 0 !important; }
+}
diff --git a/assets/ui_tokens.css b/assets/ui_tokens.css
index 4b28100..f27d6a8 100644
--- a/assets/ui_tokens.css
+++ b/assets/ui_tokens.css
@@ -19,6 +19,7 @@
--ep-space-4: 16px;
--ep-space-6: 24px;
--ep-space-8: 32px;
+ --ep-radius-pill: 999px;
--ep-radius-control: 10px;
--ep-radius-panel: 16px;
--ep-font-heading: Georgia, "Times New Roman", serif;
diff --git a/components/knowledge_graph.py b/components/knowledge_graph.py
index 9f343b2..50317de 100644
--- a/components/knowledge_graph.py
+++ b/components/knowledge_graph.py
@@ -227,7 +227,8 @@ def render_topic_details(
with st.container(key="knowledge_topic_summary"):
st.subheader(tr("Summary"))
- st.write(details["summary"])
+ from services.math_text import write_summary
+ write_summary(details["summary"])
if course is not None:
if st.button(tr("Detailed explanation & examples"), key="topic_details_open", icon=":material/open_in_new:"):
@@ -523,11 +524,20 @@ def render_radar_panel(
for code in learning_radar.REASON_LABELS
if item.reasons.get(code, 0) > 0
) if reasons is not None else ""
+ count_label = tr(radar_count_text(item))
+ count = item.display_count
+ badge = (f'{count}{html.escape(tr("Students stuck"))}'
+ if isinstance(count, int) and not isinstance(count, bool)
+ else html.escape(count_label))
+ chips = ''.join('' + html.escape(part) + ''
+ for part in detail.split(' · ') if part)
rows.append(
- '
'
- + html.escape(f"{index}. {topic_names[item.topic_id]}")
- + '' + html.escape(tr(radar_count_text(item)))
- + '' + html.escape(detail) + ''
+ ''
+ + f'{index}'
+ + '' + html.escape(topic_names[item.topic_id]) + ''
+ + '' + badge + ''
+ + '' + chips + '
'
)
st.html(' None:
@@ -26,21 +27,21 @@ def render_topic_explanation(course: StudyPackage, topic_id: str) -> None:
steps, worked, mistake = lesson
st.subheader(tr("Step-by-step explanation"))
for number, step in enumerate(steps, 1):
- st.write(f"{number}. {step}")
+ write_summary(f"{number}. {step}")
with st.container(border=True, key="topic_worked_example"):
st.markdown('**' + tr('Worked example') + '**')
- st.write(worked)
+ write_summary(worked)
st.caption(tr('Common mistake') + ': ' + mistake)
elif course.course_id in FILES:
st.subheader(tr("Step-by-step explanation"))
- st.write(topic.summary)
+ write_summary(topic.summary)
first = next((q for q in course.questions if q.topic_id == topic_id), None)
if first:
st.markdown('**' + tr('Worked example') + '**')
st.write(first.question)
st.write(first.explanation)
else:
- st.caption(tr("Go beyond the summary: understand the idea, then work through an example."))
+ help_tip(tr("Go beyond the summary: understand the idea, then work through an example."))
if st.button(tr("Explain step by step"), key=f"graph_explain_{fingerprint}"):
language = "Simplified Chinese" if chinese else "English"
prompt = (
diff --git a/data/calculus_i_demo.json b/data/calculus_i_demo.json
index c0c7dcb..04ee5fa 100644
--- a/data/calculus_i_demo.json
+++ b/data/calculus_i_demo.json
@@ -1255,7 +1255,7 @@
],
"learning_state": {
"question_reviews": {
- "calc_q004": "pending",
+ "calc_q004": "approved",
"calc_q005": "pending",
"calc_q006": "pending",
"calc_q007": "pending",
@@ -1264,7 +1264,7 @@
"calc_q010": "pending",
"calc_q011": "pending",
"calc_q012": "pending",
- "calc_q013": "pending",
+ "calc_q013": "approved",
"calc_q014": "pending",
"calc_q015": "pending",
"calc_q016": "pending",
@@ -1273,7 +1273,7 @@
"calc_q019": "pending",
"calc_q020": "pending",
"calc_q021": "pending",
- "calc_q022": "pending",
+ "calc_q022": "approved",
"calc_q023": "pending",
"calc_q024": "pending",
"calc_q025": "pending",
@@ -1282,41 +1282,41 @@
"calc_q028": "pending",
"calc_q029": "pending",
"calc_q030": "pending",
- "calc_limit_laws_q01": "pending",
- "calc_limit_laws_q02": "pending",
+ "calc_limit_laws_q01": "approved",
+ "calc_limit_laws_q02": "approved",
"calc_limit_laws_q03": "pending",
- "calc_continuity_q01": "pending",
- "calc_continuity_q02": "pending",
+ "calc_continuity_q01": "approved",
+ "calc_continuity_q02": "approved",
"calc_continuity_q03": "pending",
- "calc_trig_limits_q01": "pending",
- "calc_trig_limits_q02": "pending",
+ "calc_trig_limits_q01": "approved",
+ "calc_trig_limits_q02": "approved",
"calc_trig_limits_q03": "pending",
- "calc_differentiation_rules_q01": "pending",
- "calc_differentiation_rules_q02": "pending",
+ "calc_differentiation_rules_q01": "approved",
+ "calc_differentiation_rules_q02": "approved",
"calc_differentiation_rules_q03": "pending",
- "calc_chain_rule_q01": "pending",
- "calc_chain_rule_q02": "pending",
+ "calc_chain_rule_q01": "approved",
+ "calc_chain_rule_q02": "approved",
"calc_chain_rule_q03": "pending",
- "calc_implicit_differentiation_q01": "pending",
- "calc_implicit_differentiation_q02": "pending",
+ "calc_implicit_differentiation_q01": "approved",
+ "calc_implicit_differentiation_q02": "approved",
"calc_implicit_differentiation_q03": "pending",
- "calc_related_rates_q01": "pending",
- "calc_related_rates_q02": "pending",
+ "calc_related_rates_q01": "approved",
+ "calc_related_rates_q02": "approved",
"calc_related_rates_q03": "pending",
- "calc_mean_value_theorem_q01": "pending",
- "calc_mean_value_theorem_q02": "pending",
+ "calc_mean_value_theorem_q01": "approved",
+ "calc_mean_value_theorem_q02": "approved",
"calc_mean_value_theorem_q03": "pending",
- "calc_curve_sketching_q01": "pending",
- "calc_curve_sketching_q02": "pending",
+ "calc_curve_sketching_q01": "approved",
+ "calc_curve_sketching_q02": "approved",
"calc_curve_sketching_q03": "pending",
- "calc_antiderivatives_q01": "pending",
- "calc_antiderivatives_q02": "pending",
+ "calc_antiderivatives_q01": "approved",
+ "calc_antiderivatives_q02": "approved",
"calc_antiderivatives_q03": "pending",
- "calc_definite_integrals_q01": "pending",
- "calc_definite_integrals_q02": "pending",
+ "calc_definite_integrals_q01": "approved",
+ "calc_definite_integrals_q02": "approved",
"calc_definite_integrals_q03": "pending",
- "calc_fundamental_theorem_q01": "pending",
- "calc_fundamental_theorem_q02": "pending",
+ "calc_fundamental_theorem_q01": "approved",
+ "calc_fundamental_theorem_q02": "approved",
"calc_fundamental_theorem_q03": "pending"
}
}
diff --git a/data/demo_python_basics.json b/data/demo_python_basics.json
index 0b4c861..27250a1 100644
--- a/data/demo_python_basics.json
+++ b/data/demo_python_basics.json
@@ -506,21 +506,21 @@
],
"learning_state": {
"question_reviews": {
- "python-basics-q10": "pending",
+ "python-basics-q10": "approved",
"python-basics-q11": "pending",
"python-basics-q12": "pending",
"python-basics-q13": "pending",
"python-basics-q14": "pending",
"python-basics-q15": "pending",
"python-basics-q16": "pending",
- "python-basics-q17": "pending",
+ "python-basics-q17": "approved",
"python-basics-q18": "pending",
"python-basics-q19": "pending",
"python-basics-q20": "pending",
"python-basics-q21": "pending",
"python-basics-q22": "pending",
"python-basics-q23": "pending",
- "python-basics-q24": "pending",
+ "python-basics-q24": "approved",
"python-basics-q25": "pending",
"python-basics-q26": "pending",
"python-basics-q27": "pending",
diff --git a/data/sample_course.json b/data/sample_course.json
index 8302617..66861cc 100644
--- a/data/sample_course.json
+++ b/data/sample_course.json
@@ -517,7 +517,7 @@
],
"learning_state": {
"question_reviews": {
- "q004": "pending",
+ "q004": "approved",
"q005": "pending",
"q006": "pending",
"q007": "pending",
@@ -526,7 +526,7 @@
"q010": "pending",
"q011": "pending",
"q012": "pending",
- "q013": "pending",
+ "q013": "approved",
"q014": "pending",
"q015": "pending",
"q016": "pending",
@@ -535,7 +535,7 @@
"q019": "pending",
"q020": "pending",
"q021": "pending",
- "q022": "pending",
+ "q022": "approved",
"q023": "pending",
"q024": "pending",
"q025": "pending",
diff --git a/design-system/exampilot/MASTER.md b/design-system/exampilot/MASTER.md
index 2f5e280..785e021 100644
--- a/design-system/exampilot/MASTER.md
+++ b/design-system/exampilot/MASTER.md
@@ -43,3 +43,13 @@ Skill search fit: the focused loading-feedback/reduced-motion results matched th
Follow-up section review: topic details now open a dedicated teaching page with offline course examples and optional AI explanation; the map focus survives the return. Learning DNA cards use a paper surface, a top rule and wider gutters. Concept Lab prediction choices have a bordered panel, followed by a separated primary action. Learning Radar uses a 2:1 chart/picker layout and a keyboard-focusable ranking region below; five 8rem rows fit its 40rem viewport. Counts, privacy thresholds and sample-data labelling are unchanged. Desktop and 375px browser checks confirmed the layout, five-row geometry and no horizontal overflow.
Full Python 3.12 suite after integrating main: 1560 passed, 20 skipped. Browser walkthroughs cover desktop, 375px portrait and 812px landscape, including pause/return, retained answers, retained Pilot draft, mobile navigation, panel bounds and focused controls. Reduced-motion rules were inspected in source; OS preference switching was not emulated. No live AI request or production account data was used.
+
+## Result review and Home consistency
+
+Home uses the shared slate primary and cream secondary pills, semantic type/color tokens and 44px minimum controls. Remove the old oversized Create course treatment rather than maintaining a second button system. Results group stacked score/accuracy at left, a larger primary Review answers action in the middle, and next-topic actions at right; narrow screens stack these groups. Reflection and explanation actions align to the right. Optional functional instructions use the existing hover/focus help control; feedback, errors, learning content and sample-data attribution remain visible.
+
+The ranking uses five 120px cards plus four 8px gaps in a 632px scrolling region. Rank, topic, count and reason chips have distinct visual roles. The landscape belongs to the fixed app backdrop, with transparent desktop navigation and no duplicate sidebar mountain; mobile navigation retains an opaque surface for legibility. Summary and offline lesson notation uses native Streamlit LaTeX rendering via reviewed literal mappings, preserving saved content, existing math and code spans.
+
+Reviewed 33 existing draft demo questions for publication: 27 calculus, 3 economics and 3 Python. This supplies a distinct same-topic practice structure for each currently available question in a one-question session. Availability still respects review status, confirmed scope, unused question families and distinct stems. Legacy copies receive approval metadata only when their built-in question content is unchanged; explicit learner rejections, edits and saved question payloads are preserved. Labels missing in old snapshots are resolved for matching only, without changing those snapshots.
+
+Verification: Python 3.12 full suite 1580 passed, 20 skipped. Browser checks covered the result/review/transfer flow, right-aligned controls, tooltip keyboard disclosure, native mathematical fractions/limits in summaries and worked examples, five-card ranking geometry, Home button computed styles, fixed background before/after navigation collapse, and 375px/812px responsive bounds. All previews used synthetic local state without live AI or production database writes; these checks do not establish public deployment status. UI/UX Pro Max heading-scale guidance, Design Token shared roles and Heuristic Evaluation task grouping informed this pass.
diff --git a/pages/0_Dashboard.py b/pages/0_Dashboard.py
index 33884db..ea1bb83 100644
--- a/pages/0_Dashboard.py
+++ b/pages/0_Dashboard.py
@@ -250,7 +250,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
else ":material/add_circle_outline:"),
key="create_course_button",
type="secondary",
- use_container_width=True,
+ width="content",
):
st.session_state.show_course_setup = not st.session_state.show_course_setup
st.rerun()
@@ -266,7 +266,7 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
)
st.caption(tr("2 · Upload materials and extract text"))
- st.caption(tr("Only the extracted text is saved with your course, not the original file."))
+ help_tip(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"],
@@ -275,11 +275,11 @@ def load_demo_package(filename: str, expected_course_id: str) -> StudyPackage:
max_upload_size=5,
)
- st.caption(
+ help_tip(
tr("PDF, PPTX, TXT, PNG or JPG/JPEG · up to 5 MiB per file · "
"up to 50,000 characters of extracted text.")
)
- st.caption(tr(
+ help_tip(tr(
"Use UTF-8 TXT, text-based PDF or PPTX, or clear images of English text; "
"reading text from images may not always be available. "
"Scanned PDFs, PPTX slide notes and DOCX files are not supported."
diff --git a/pages/10_Topic_Summaries.py b/pages/10_Topic_Summaries.py
index eec5436..beb4990 100644
--- a/pages/10_Topic_Summaries.py
+++ b/pages/10_Topic_Summaries.py
@@ -24,6 +24,7 @@
for topic in course.topics:
with st.container(border=True):
st.markdown(f"**{topic.name}**")
- st.write(topic.summary)
+ from services.math_text import write_summary
+ write_summary(topic.summary)
if topic.source_pages:
st.caption(tr("Source pages: ") + ", ".join(map(str, topic.source_pages)))
diff --git a/pages/14_Topic_Details.py b/pages/14_Topic_Details.py
index 19da477..17384cc 100644
--- a/pages/14_Topic_Details.py
+++ b/pages/14_Topic_Details.py
@@ -20,6 +20,7 @@
st.session_state[f"graph_pending_focus_{course.course_id}"] = topic.id
with st.container(border=True, key="topic_detail_overview"):
st.subheader(topic.name)
- st.write(topic.summary)
+ from services.math_text import write_summary
+ write_summary(topic.summary)
with st.container(border=True, key="topic_detail_lesson"):
render_topic_explanation(course, topic.id)
diff --git a/pages/2_Practice_Center.py b/pages/2_Practice_Center.py
index 3e02185..51ed6c7 100644
--- a/pages/2_Practice_Center.py
+++ b/pages/2_Practice_Center.py
@@ -445,6 +445,8 @@ def render_question_screen(course, active, topic_names):
)
with st.container(key="flight_worksheet"):
+ if active.get("transfer_from"):
+ st.badge(tr("Transfer practice") + " · " + tr("Same topic · Different structure"))
# One row above the question: counter · flight path · session clock (wraps on phones).
with st.container(key="flight_practice_progress", horizontal=True, vertical_alignment="center"):
with st.container(key="flight_progress_count", width="content"):
@@ -634,40 +636,31 @@ def render_result_screen(course, active_practice, confirmed_topic_ids, topic_nam
st.subheader(tr("Your result"))
if st.session_state.get(f"course_stage_{course.course_id}") == "questions_generated":
st.caption(tr("AI-generated questions: verify the answer and explanation against your material."))
- with st.container(key="practice_result_overview"):
- score_columns = st.columns(2)
- with score_columns[0].container(border=True):
- st.metric(
- tr("Score"),
- f"{result['correct_count']} / {result['total_count']}",
- )
- with score_columns[1].container(border=True):
- st.metric(tr("Accuracy"), f"{result['accuracy']:.2f}%")
-
- # Each question's answer, explanation and reflection: on a page of their own.
- open_page_button(
- tr("Review answers"), ANSWER_REVIEW_PAGE, key="open_answer_review",
- icon=":material/fact_check:", align="right",
- )
-
- # Next steps, shown directly.
- missed_ids = {
- attempt.question_id for attempt in result["attempts"] if not attempt.is_correct
- }
+ missed_ids = {attempt.question_id for attempt in result["attempts"] if not attempt.is_correct}
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, 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:",
- ):
- st.session_state[f"graph_pending_focus_{course.course_id}"] = next_question.topic_id
- st.switch_page("pages/4_Knowledge_Graph.py")
- if course.course_id == "calculus-i-demo" and next_question.topic_id in {"calc_limits", "calc_derivatives"}:
- if st.button(tr("Explore this topic in Concept Lab"), key=f"flight_lab_{session.session_id}"):
- open_lab(st.session_state, course.course_id, next_question.topic_id)
- st.switch_page("pages/6_Concept_Lab.py")
+ with st.container(key="practice_result_overview"):
+ stats, review_action, next_step = st.columns([1, 1.2, 1.6], gap="large", vertical_alignment="center")
+ with stats:
+ with st.container(border=True, key="result_score"):
+ st.metric(tr("Score"), f"{result['correct_count']} / {result['total_count']}")
+ with st.container(border=True, key="result_accuracy"):
+ st.metric(tr("Accuracy"), f"{result['accuracy']:.2f}%")
+ with review_action, st.container(key="result_review_action"):
+ if st.button(tr("Review answers"), key="open_answer_review", icon=":material/fact_check:",
+ type="primary", width="stretch"):
+ st.switch_page(ANSWER_REVIEW_PAGE)
+ with next_step, st.container(border=True, key="flight_next_topic"):
+ st.subheader(tr("Take the next step"))
+ 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:",
+ ):
+ st.session_state[f"graph_pending_focus_{course.course_id}"] = next_question.topic_id
+ st.switch_page("pages/4_Knowledge_Graph.py")
+ if course.course_id == "calculus-i-demo" and next_question.topic_id in {"calc_limits", "calc_derivatives"}:
+ if st.button(tr("Explore this topic in Concept Lab"), key=f"flight_lab_{session.session_id}"):
+ open_lab(st.session_state, course.course_id, next_question.topic_id)
+ st.switch_page("pages/6_Concept_Lab.py")
guided_review_available = render_guided_review(course, session, questions, result)
result_overview(course, session, questions, result)
diff --git a/pages/4_Knowledge_Graph.py b/pages/4_Knowledge_Graph.py
index 0c2e19c..adbf7cc 100644
--- a/pages/4_Knowledge_Graph.py
+++ b/pages/4_Knowledge_Graph.py
@@ -332,7 +332,6 @@
render_topic_details(details, topic_stats, course)
if details is not None:
links = related_topics(course, selected_node_id)
- st.divider()
if st.button(tr("Practise this topic"), key=f"graph_practice_{course.course_id}_{selected_node_id}", type="primary"):
try:
stage_practice(st.session_state, course, selected_node_id)
@@ -343,7 +342,6 @@
st.switch_page("pages/2_Practice_Center.py")
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
diff --git a/pages/9_Course_Tools.py b/pages/9_Course_Tools.py
index 20bc261..1d61f7d 100644
--- a/pages/9_Course_Tools.py
+++ b/pages/9_Course_Tools.py
@@ -1,4 +1,5 @@
"""Course tools: question review, account backup and source material, one at a time."""
+from services.ui_help import help_tip
from services.i18n import tr
import streamlit as st
@@ -40,7 +41,7 @@ def review_label(qid):
key=f"editor_question_{course.course_id}",
)
original = by_id[question_id]
- st.caption(tr("Check the answer and explanation before approving; edits never change past results."))
+ help_tip(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(tr(f"Option {chr(65 + index)}"), value=value) for index, value in enumerate(original.options)]
@@ -91,7 +92,7 @@ def render_source_material(course) -> None:
material = st.session_state.get(f"course_document_{course.course_id}")
if material:
st.caption(material.get("filename", tr("Course material")))
- st.caption(tr("The text from your material is saved with this course. The original uploaded file is not stored."))
+ help_tip(tr("The text from your material is saved with this course. The original uploaded file is not stored."))
with st.expander(tr("Read saved text")):
st.text(material.get("text", ""))
with st.form(f"material_delete_form_{course.course_id}"):
@@ -121,7 +122,7 @@ def render_source_material(course) -> None:
back_button(tr("Back to Study Plan"), "pages/1_Study_Hub.py", key="course_tools_back")
st.title(tr("Course tools"))
-st.caption(tr("Manage questions, account backups and source material when needed."))
+help_tip(tr("Manage questions, account backups and source material when needed."))
course = st.session_state.get("current_course")
diff --git a/services/answer_followup.py b/services/answer_followup.py
index a4c6022..84bf1bd 100644
--- a/services/answer_followup.py
+++ b/services/answer_followup.py
@@ -1,5 +1,6 @@
"""Question-scoped follow-up, asked only after a student submits the form."""
import hashlib
+from services.ui_help import help_tip
import streamlit as st
@@ -14,7 +15,7 @@ def render_answer_followup(course: StudyPackage, question: Question) -> None:
).hexdigest()
history_key = f'answer_followup_history_{scope}'
st.subheader(tr('Ask about this explanation'))
- st.caption(tr('Ask what you did not understand. This conversation stays in this session and does not change your score.'))
+ help_tip(tr('Ask what you did not understand. This conversation stays in this session and does not change your score.'))
for item in st.session_state.get(history_key, []):
with st.chat_message('user'):
st.write(item['question'])
@@ -26,7 +27,8 @@ def render_answer_followup(course: StudyPackage, question: Question) -> None:
placeholder=tr('For example: why is option B incorrect?'),
max_chars=MAX_TUTOR_QUESTION_CHARS,
)
- submitted = st.form_submit_button(tr('Ask AI'))
+ with st.container(horizontal=True, horizontal_alignment='right', key=f'followup_actions_{scope}'):
+ submitted = st.form_submit_button(tr('Ask AI'), type='primary')
if not submitted:
return
question_text = question_text.strip()
diff --git a/services/demo_updates.py b/services/demo_updates.py
index e126f21..310d1e8 100644
--- a/services/demo_updates.py
+++ b/services/demo_updates.py
@@ -8,6 +8,28 @@
FILES={'econ101':'sample_course.json','calculus-i-demo':'calculus_i_demo.json','python-basics-demo':'demo_python_basics.json'}
+def builtin_equivalent(saved, catalog):
+ """Match unchanged content, allowing older demos to lack optional labels.
+
+ This does not mutate historical question payloads or replace learner edits.
+ """
+ if catalog is None:
+ return False
+ saved_data, catalog_data = saved.model_dump(), catalog.model_dump()
+ for name in ('cognitive_dimension', 'practice_structure', 'hints'):
+ if saved_data[name] in (None, []):
+ saved_data[name] = catalog_data[name]
+ return saved_data == catalog_data
+
+
+def catalog_questions(course_id):
+ filename = FILES.get(course_id)
+ if filename is None:
+ return {}
+ package = StudyPackage.model_validate_json((Path(__file__).resolve().parents[1]/'data'/filename).read_text(encoding='utf-8'))
+ return {q.id:q for q in package.questions}
+
+
def demo_update(course):
filename=FILES.get(course.course_id)
if not filename:return course,0
@@ -22,15 +44,24 @@ def demo_update(course):
added=[q for q in latest.questions if q.id not in known and q.topic_id in topics and normalized_text(q.question) not in stems]
edges={(r.from_topic,r.to_topic,r.type) for r in course.relationships}
new_edges=[r for r in latest.relationships if (r.from_topic,r.to_topic,r.type) not in edges] if course.course_id=='calculus-i-demo' else []
- if not added and not new_topics and not new_edges:return course,0
+ # Publish only the catalog's explicitly reviewed examples. An existing
+ # learner rejection, edit or superseded version is never promoted.
+ catalog = {q.id:q for q in latest.questions}
+ catalog_reviews = latest.learning_state.get('question_reviews', {})
+ existing_reviews = course.learning_state.get('question_reviews', {})
+ reviewed = [q.id for q in course.questions
+ if builtin_equivalent(q, catalog.get(q.id)) and existing_reviews.get(q.id) == 'pending'
+ and catalog_reviews.get(q.id) == 'approved']
+ if not added and not new_topics and not new_edges and not reviewed:return course,0
data=course.model_dump(mode='json')
data['topics'].extend(t.model_dump(mode='json') for t in new_topics)
data['relationships'].extend(r.model_dump(mode='json') for r in new_edges)
data['questions'].extend(q.model_dump(mode='json') for q in added)
metadata=deepcopy(course.learning_state)
- if added:
+ if added or reviewed:
reviews=metadata.setdefault('question_reviews',{})
- for q in added:reviews[q.id]='pending'
+ for q in added:reviews[q.id]=catalog_reviews.get(q.id, 'pending')
+ for qid in reviewed:reviews[qid]='approved'
data['learning_state']=metadata
return StudyPackage.model_validate(data),len(added)
diff --git a/services/i18n.py b/services/i18n.py
index bc32b30..f94badf 100644
--- a/services/i18n.py
+++ b/services/i18n.py
@@ -20,6 +20,9 @@ def remember_language() -> None:
_TRANSLATIONS = {
+ "Transfer practice": "变式练习",
+ "Same topic · Different structure": "同一知识点 · 不同题型",
+ "Students stuck": "卡住人数",
"Help": "帮助",
"Step-by-step explanation": "分步骤讲解",
"Worked example": "分步例题",
diff --git a/services/math_text.py b/services/math_text.py
new file mode 100644
index 0000000..898c522
--- /dev/null
+++ b/services/math_text.py
@@ -0,0 +1,86 @@
+"""Typeset known course notation without rewriting saved course text or code."""
+import re
+import streamlit as st
+
+# Literal, reviewed notation from the calculus catalog. Longest matches win;
+# existing LaTeX and code spans are kept verbatim rather than parsed again.
+NOTATION = {
+ 'sin(u)/u → 1': r'\frac{\sin u}{u}\to1',
+ 'sin(3x)/x = 3·sin(3x)/(3x)': r'\frac{\sin(3x)}x=3\frac{\sin(3x)}{3x}',
+ '[f(x+h) − f(x)]/h': r'\frac{f(x+h)-f(x)}h',
+ '[(x+h)²−x²]/h = 2x+h': r'\frac{(x+h)^2-x^2}h=2x+h',
+ '(x² − 4)/(x − 2)': r'\frac{x^2-4}{x-2}',
+ '(x²−4)/(x−2)': r'\frac{x^2-4}{x-2}',
+ '(x − 2)(x + 2)': r'(x-2)(x+2)',
+ '[f(b)−f(a)]/(b−a)': r'\frac{f(b)-f(a)}{b-a}',
+ 'f′(x)=2x sin(x)+x² cos(x)': r"f'(x)=2x\sin x+x^2\cos x",
+ 'f′(x)=2x sin(x)+x²cos(x)': r"f'(x)=2x\sin x+x^2\cos x",
+ 'f(x)=x²sin(x)': r'f(x)=x^2\sin x',
+ 'y′=24x(3x²+1)³': r"y'=24x(3x^2+1)^3",
+ 'y=(3x²+1)⁴': r'y=(3x^2+1)^4',
+ '4(3x²+1)³': r'4(3x^2+1)^3',
+ 'x²+y²=25': r'x^2+y^2=25',
+ '2x+2y y′=0': r"2x+2yy'=0",
+ 'y′=−x/y': r"y'=-\frac xy", '2y y′': r"2yy'",
+ 'dA/dt=2πr·dr/dt': r'\frac{dA}{dt}=2\pi r\frac{dr}{dt}',
+ 'dA/dt=12π cm²/s': r'\frac{dA}{dt}=12\pi\,\mathrm{cm}^2/\mathrm{s}',
+ 'dr/dt=2 cm/s': r'\frac{dr}{dt}=2\,\mathrm{cm}/\mathrm{s}',
+ 'A=πr²': r'A=\pi r^2', '12π cm²/s': r'12\pi\,\mathrm{cm}^2/\mathrm{s}',
+ '∫(3x²+2) dx = x³+2x+C': r'\int(3x^2+2)\,dx=x^3+2x+C',
+ '∫₀² x dx = [x²/2]₀² = 2': r'\int_0^2 x\,dx=\left[\frac{x^2}2\right]_0^2=2',
+ '∫₋₁¹ x dx=0': r'\int_{-1}^1x\,dx=0',
+ 'G(x)=∫₀ˣ² cos(t)dt': r'G(x)=\int_0^{x^2}\cos t\,dt',
+ 'G′(x)=cos(x²)·2x': r"G'(x)=\cos(x^2)\cdot2x",
+ '∫₀¹ 2t dt=[t²]₀¹=1': r'\int_0^1 2t\,dt=[t^2]_0^1=1',
+ '∫ₐˣ f(t)dt': r'\int_a^x f(t)\,dt',
+ 'F(b)−F(a)': r'F(b)-F(a)',
+ 'f(x)=x²−4x': r'f(x)=x^2-4x', 'f(x)=x³−3x': r'f(x)=x^3-3x',
+ 'f(x)=x²': r'f(x)=x^2', 'f(x)=x³': r'f(x)=x^3',
+ 'f′(x)=2x−4': r"f'(x)=2x-4", 'f′(x)=2x': r"f'(x)=2x",
+ 'f′(c)=2c=4': r"f'(c)=2c=4", 'f′(c)=2c': r"f'(c)=2c",
+ 'f′=3(x²−1)': r"f'=3(x^2-1)", 'f″=6x': r"f''=6x",
+ 'f′=0': r"f'=0", 'f″=0': r"f''=0",
+ 'x³+2x+C': r'x^3+2x+C', '3x²+2': r'3x^2+2',
+ '3(x²−1)': r'3(x^2-1)', 'x²+3x → 10': r'x^2+3x\to10',
+ '1/(x−2)': r'\frac1{x-2}', '(9−1)/2=4': r'\frac{9-1}2=4',
+ 'f(0)=0': r'f(0)=0', 'f(2)=−4': r'f(2)=-4', 'f(5)=5': r'f(5)=5',
+ 'f(2)=k': r'f(2)=k', 'f(2)': r'f(2)',
+ 'x ≠ 2': r'x\ne2', 'x≠2': r'x\ne2', 'y≠0': r'y\ne0',
+ 'h ≠ 0': r'h\ne0', 'h → 0': r'h\to0', 'x → 0': r'x\to0',
+ 'x → 2': r'x\to2', 'x² → 4': r'x^2\to4', '3x → 6': r'3x\to6',
+ 'n≠−1': r'n\ne-1', 'x⁻¹': r'x^{-1}', 'x³': r'x^3', 'x²': r'x^2',
+ 'f′(x)': r"f'(x)", 'f′(c)': r"f'(c)", 'y′': r"y'",
+ '0/0': r'\frac00', 'x + 2': r'x+2', 'x − 2': r'x-2',
+ 'lim(x→0) sin(x)/x = 1': r'\lim_{x\to0}\frac{\sin x}{x}=1',
+ 'lim(x→0) (1 − cos(x))/x = 0': r'\lim_{x\to0}\frac{1-\cos x}{x}=0',
+ 'f′(c) = [f(b) − f(a)]/(b − a)': r"f'(c)=\frac{f(b)-f(a)}{b-a}",
+ '∫ from a to x of f(t) dt': r'\int_a^x f(t)\,dt',
+ '∫ from a to b of f(x) dx = F(b) − F(a)': r'\int_a^b f(x)\,dx=F(b)-F(a)',
+ 'A(x) = ∫ from a to x of f(t) dt': r'A(x)=\int_a^x f(t)\,dt',
+ '(u′v − uv′)/v²': r"\frac{u'v-uv'}{v^2}",
+ 'u′v + uv′': r"u'v+uv'",
+ 'f′(g(x))': r"f'(g(x))", 'g′(x)': r"g'(x)",
+ 'f(g(x))': r'f(g(x))',
+ 'xⁿ⁺¹/(n + 1)': r'\frac{x^{n+1}}{n+1}',
+ 'n ≠ −1': r'n\ne-1', '1/x': r'\frac1x', 'ln|x|': r'\ln|x|',
+ '2y·dy/dx': r'2y\frac{dy}{dx}', 'dy/dx': r'\frac{dy}{dx}',
+ 'f″ = 0': r"f''=0", 'F′ = f': r"F'=f", 'f′': r"f'", 'f″': r"f''",
+ 'f(a)': r'f(a)', 'f(x)': r'f(x)', 'xⁿ': r'x^n', 'y²': r'y^2', 'v ≠ 0': r'v\ne0',
+ 'u/v': r'\frac uv', '|f|': r'|f|',
+}
+PATTERN = re.compile('|'.join(re.escape(text) for text in sorted(NOTATION, key=len, reverse=True)))
+
+
+def math_markdown(text):
+ # No arbitrary expression evaluation or conversion of user code.
+ parts = re.split(r'(\$\$.*?\$\$|\$[^$\n]+\$|```.*?```|`[^`]+`)', text, flags=re.S)
+ return ''.join(part if i % 2 else PATTERN.sub(lambda match: '$'+NOTATION[match[0]]+'$', part)
+ for i,part in enumerate(parts))
+
+
+def write_summary(text):
+ formatted = math_markdown(text)
+ if formatted == text:
+ st.write(text)
+ else:
+ st.markdown(formatted)
diff --git a/services/practice_insights.py b/services/practice_insights.py
index d2a53fc..c35ff95 100644
--- a/services/practice_insights.py
+++ b/services/practice_insights.py
@@ -141,15 +141,23 @@ def transfer_session(course, source, source_session, confirmed_ids):
"""Curated task labels suggest structural contrast; never generate unreviewed items."""
if source.topic_id not in confirmed_ids:
raise ValueError('Confirm this topic in Study Plan first.')
- if not source.practice_structure:
+ from services.demo_updates import builtin_equivalent, catalog_questions
+ catalog = catalog_questions(course.course_id)
+ def structure(question):
+ if question.practice_structure:
+ return question.practice_structure
+ reference = catalog.get(question.id)
+ return reference.practice_structure if builtin_equivalent(question, reference) else None
+ source_structure = structure(source)
+ if not source_structure:
raise ValueError('This question has no reviewed structure label; no transfer match can be selected.')
by_id = {q.id:q for q in course.questions}
by_id.setdefault(source.id, source)
used = {family_id(by_id[qid], by_id) for qid in source_session.question_ids if qid in by_id}
used.add(family_id(source, by_id))
candidates = [q for q in available_questions(course)
- if q.topic_id == source.topic_id and q.practice_structure
- and q.practice_structure != source.practice_structure
+ if q.topic_id == source.topic_id and structure(q)
+ and structure(q) != source_structure
and family_id(q, by_id) not in used
and normalized_text(q.question) != normalized_text(source.question)]
if not candidates:
diff --git a/services/practice_insights_ui.py b/services/practice_insights_ui.py
index b27d487..8df723a 100644
--- a/services/practice_insights_ui.py
+++ b/services/practice_insights_ui.py
@@ -1,4 +1,5 @@
"""Practice-time controls and post-session reflection; grades remain unchanged."""
+from services.ui_help import help_tip
from services.i18n import tr
import time
@@ -106,7 +107,7 @@ def checklist(active):
st.subheader(tr('Review before submit'))
if rows:
st.dataframe([{tr(key): ', '.join(tr(flag.strip()) for flag in value.split(',')) if key == 'Check' else value for key, value in row.items()} for row in rows], hide_index=True, width='stretch')
- st.caption(tr('Go back to the questions to change these answers, or submit them as they are.'))
+ help_tip(tr('Go back to the questions to change these answers, or submit them as they are.'))
else:
st.caption(tr('No unanswered, unsure or guessed answers to review.'))
@@ -177,7 +178,7 @@ def render_priorities(course, priorities):
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.caption(tr('Priority uses incorrect/unanswered responses, confidence, hints and relative tracked time. It is a transparent practice suggestion, not a diagnosis.'))
+ help_tip(tr('Priority uses incorrect/unanswered responses, confidence, hints and relative tracked time. It is a transparent practice suggestion, not a diagnosis.'))
st.button(tr('Practise review priorities'), key=f'priorities_{course.course_id}',
on_click=launch_priority, args=(course, priorities))
if error := st.session_state.pop('priority_launch_error', None):
@@ -234,9 +235,9 @@ def reflection_controls(course, session, question, review, confirmed, practice_k
rows=deepcopy(session_insights(course,sid))
saved=ResponseInsight.model_validate(rows.get(question.id,{}))
st.subheader(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.'))
+ help_tip(tr('Write your reasoning in your own words. This reflection is after feedback and never changes your score.'))
# A form sends nothing until it is submitted, so text typed here is gone once the page turns.
- st.caption(tr('Save before you go to another question: text that is not saved is not kept.'))
+ help_tip(tr('Save before you go to another question: text that is not saved is not kept.'))
with st.form(f'reflection_{sid}_{question.id}'):
reason=saved.mistake_reason
if not review['is_correct']:
@@ -246,12 +247,13 @@ def reflection_controls(course, session, question, review, confirmed, practice_k
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}')
- save=st.form_submit_button(tr('Save reflection'))
- ai=st.form_submit_button(tr('Check explanation with AI'),disabled=not generation_available())
+ with st.container(horizontal=True, horizontal_alignment='right', key=f'reflection_actions_{sid}_{question.id}'):
+ save=st.form_submit_button(tr('Save reflection'), type='primary')
+ ai=st.form_submit_button(tr('Check explanation with AI'),disabled=not generation_available())
if not generation_available():
- st.caption(tr('AI checking is not configured. You can still write and save your explanation.'))
+ help_tip(tr('AI checking is not configured. You can still write and save your explanation.'))
else:
- st.caption(tr('AI checking sends this explanation and question to the configured Claude service. Its feedback may be wrong; verify it against your material.'))
+ help_tip(tr('AI checking sends this explanation and question to the configured Claude service. Its feedback may be wrong; verify it against your material.'))
if save or ai:
row=saved.model_copy(update={'mistake_reason':reason,'explanation':text})
if text != saved.checked_explanation:
@@ -316,7 +318,7 @@ def render_history_insights(course, history, mode, example=False):
with st.container(border=True,key='progress_time'):
st.subheader(title)
render_bar_chart(title,time_rows(total_seconds,names,tr('Topic'),tr),kind='time')
- st.caption(tr('Totals across recorded sessions in this mode; missing time is not treated as zero.'))
+ help_tip(tr('Totals across recorded sessions in this mode; missing time is not treated as zero.'))
if example: return
qs=[value[0] for value in latest.values()]
attempts=[value[1] for value in latest.values()]
diff --git a/tests/test_accessibility.py b/tests/test_accessibility.py
index e46515a..466698c 100644
--- a/tests/test_accessibility.py
+++ b/tests/test_accessibility.py
@@ -145,8 +145,9 @@ def test_demo_variants_cover_original_questions_without_changing_numbers(
)["questions"]
# Reviewed original questions have simplified variants; new drafts use
# the documented original-wording fallback until variants are authored.
- assert set(variants) == {question.id for question in available_questions(package)}
- for question in available_questions(package):
+ originals = [q for q in package.questions if q.id not in package.learning_state.get("question_reviews", {})]
+ assert set(variants) == {question.id for question in originals}
+ for question in originals:
variant = variants[question.id]
assert set(variant) == {"question", "options", "explanation"}
assert len(variant["options"]) == len(question.options) == 4
diff --git a/tests/test_anki_export_page.py b/tests/test_anki_export_page.py
index bc862bc..24e5b88 100644
--- a/tests/test_anki_export_page.py
+++ b/tests/test_anki_export_page.py
@@ -30,7 +30,7 @@ def _python_basics_course() -> StudyPackage:
path = ROOT / "data" / "demo_python_basics.json"
course = StudyPackage.model_validate_json(path.read_text(encoding="utf-8"))
# These export/mastery fixtures exercise the nine originally available cards.
- return course.model_copy(update={"questions": available_questions(course), "learning_state": {}})
+ return course.model_copy(update={"questions": course.questions[:9], "learning_state": {}})
def _app_with_course(course: StudyPackage | None = None, chinese: bool = False) -> AppTest:
diff --git a/tests/test_anki_export_service.py b/tests/test_anki_export_service.py
index 9623236..ca1c173 100644
--- a/tests/test_anki_export_service.py
+++ b/tests/test_anki_export_service.py
@@ -12,7 +12,8 @@
def _load_python_basics_demo() -> StudyPackage:
path = Path(__file__).parents[1] / "data" / "demo_python_basics.json"
with path.open(encoding="utf-8") as file:
- return StudyPackage.model_validate(json.load(file))
+ course = StudyPackage.model_validate(json.load(file))
+ return course.model_copy(update={"questions": course.questions[:9], "learning_state": {}})
def _read_tsv(content: str) -> list[list[str]]:
diff --git a/tests/test_calculus_expansion.py b/tests/test_calculus_expansion.py
index 3936844..e1f9a1e 100644
--- a/tests/test_calculus_expansion.py
+++ b/tests/test_calculus_expansion.py
@@ -42,7 +42,7 @@ def test_upgrade_adds_graph_and_drafts_without_replacing_saved_content():
for key in ('confirmed_scope', 'session_order'):
assert updated.learning_state[key] == old.learning_state[key]
assert updated.learning_state['question_reviews']['calc_q004'] == 'approved'
- assert all(updated.learning_state['question_reviews'][q.id] == 'pending' for q in updated.questions[30:])
+ assert all(updated.learning_state['question_reviews'][q.id] == latest().learning_state['question_reviews'][q.id] for q in updated.questions[30:])
assert demo_update(updated) == (updated, 0)
# The persistence merge accepts preserved IDs and retains the original rows.
assert _merge_course_packages(old, updated) == updated
@@ -76,7 +76,7 @@ def visit(tid):
assert 'calc_fundamental_theorem' in related_topics(course, 'calc_definite_integrals')['next_topics']
assert {'calc_differentiation_rules', 'calc_chain_rule', 'calc_implicit_differentiation'}.issubset(
{t.id for t in local_graph(course, 'calc_chain_rule').topics})
- assert len(available_questions(course)) == 3
+ assert len(available_questions(course)) == 30
def test_new_topic_is_searchable_and_has_teaching_summary():
diff --git a/tests/test_course_tools_page.py b/tests/test_course_tools_page.py
index 08cbd67..9256bf7 100644
--- a/tests/test_course_tools_page.py
+++ b/tests/test_course_tools_page.py
@@ -3,6 +3,7 @@
The Study Plan page keeps two small edge buttons instead of the expanders;
the Course tools page shows one tool at a time, chosen with one click.
"""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
import re
from pathlib import Path
@@ -165,7 +166,8 @@ def visible_texts(app) -> list[str]:
texts += [item.label, item.proto.help]
if kind in ("radio", "selectbox", "button_group"):
texts += list(item.options)
- return [text for text in texts if text]
+ from tests.test_progress_charts import visible_text
+ return [visible_text(text) for text in texts if text]
# The structure-label tooltip names two example labels; they are values a
@@ -348,7 +350,7 @@ def test_topic_summaries_page_shows_every_topic_in_course_order_and_nothing_else
"**Series**", "Series summary.",
"**Derivatives**", "Derivatives summary.",
]
- assert [item.value for item in app.caption] == ["Source pages: 2, 3"]
+ assert supporting_texts(app) == ["Source pages: 2, 3"]
# One bordered card per topic, directly on the page.
cards = [
node for node in app.main
@@ -392,7 +394,7 @@ def test_topic_summaries_page_in_chinese_has_no_english():
assert not app.exception
assert app.title[0].value == "知识点概要"
assert app.button(key="topic_summaries_back").label == "返回学习计划"
- assert [item.value for item in app.caption] == ["来源页:2, 3"]
+ assert supporting_texts(app) == ["来源页:2, 3"]
assert english_words(visible_texts(app)) == []
@@ -406,7 +408,7 @@ def test_course_tools_page_has_back_button_title_caption_and_one_click_choice(mo
assert not app.exception
assert [item.value for item in app.title] == ["Course tools"]
- assert app.caption[0].value == "Manage questions, account backups and source material when needed."
+ assert "Manage questions, account backups and source material when needed." in tooltip_texts(app)
assert app.button(key="course_tools_back").label == "Back to Study Plan"
assert edge_of(app, "course_tools_back") == "left"
# One click per tool: a button group, not a dropdown and not tabs.
@@ -478,7 +480,7 @@ def test_review_list_shows_plain_status_words_and_pending_first():
assert not any("[" in option or "legacy" in option.lower() for option in picker.options)
assert (
"Check the answer and explanation before approving; edits never change past results."
- in [item.value for item in app.caption]
+ in supporting_texts(app)
)
# The classification stays tucked away, collapsed.
classification = next(item for item in app.expander if item.label == "Question classification (advanced)")
@@ -593,7 +595,7 @@ def test_page_renders_for_any_mix_of_questions(reviews, tool):
assert tool_markers(app, course) == {tool}
if tool == "review":
if reviews is None:
- assert "No questions available for review." in [item.value for item in app.caption]
+ assert "No questions available for review." in supporting_texts(app)
assert not app.selectbox
else:
assert len(app.selectbox(key="editor_question_c1").options) == 4
@@ -621,7 +623,7 @@ def test_source_tool_shows_the_saved_text_and_delete_form():
app = course_tools_page(course, "source", document=material()).run()
assert not app.exception
- captions = [item.value for item in app.caption]
+ captions = supporting_texts(app)
assert "lecture.pdf" in captions
assert (
"The text from your material is saved with this course. The original uploaded file is not stored."
@@ -649,7 +651,7 @@ def test_deleting_material_says_so_and_stays_on_the_source_tool():
assert "course_document_c1" not in app.session_state
assert [item.value for item in app.success] == ["Saved material deleted."]
assert app.button_group(key=choice_key(course)).value == "source"
- assert "No saved material for this course." in [item.value for item in app.caption]
+ assert "No saved material for this course." in supporting_texts(app)
# ---- Chinese interface ------------------------------------------------------------
@@ -695,7 +697,7 @@ def test_chinese_source_tool_names_material_without_a_filename():
app = course_tools_page(course, "source", chinese=True, document=material(None)).run()
assert not app.exception
- assert "课程资料" in [item.value for item in app.caption]
+ assert "课程资料" in supporting_texts(app)
app.button(key="delete_material_c1").click().run()
assert not app.exception
assert english_words(visible_texts(app)) == []
diff --git a/tests/test_demo_courses.py b/tests/test_demo_courses.py
index 705ee33..13d20d6 100644
--- a/tests/test_demo_courses.py
+++ b/tests/test_demo_courses.py
@@ -117,8 +117,8 @@ def test_calculus_demo_can_be_practiced_and_graded_offline() -> None:
expected_answers,
)
- assert result["correct_count"] == 3
- assert result["total_count"] == 3
+ assert result["correct_count"] == len(exam["questions"])
+ assert result["total_count"] == len(exam["questions"])
assert result["accuracy"] == 100
assert all(review["is_correct"] for review in result["question_results"])
assert all(
diff --git a/tests/test_demo_question_bank.py b/tests/test_demo_question_bank.py
index 2d85231..7fc4cb5 100644
--- a/tests/test_demo_question_bank.py
+++ b/tests/test_demo_question_bank.py
@@ -30,10 +30,10 @@ def test_bank_has_ten_distinct_questions_per_topic_with_review_gate(filename, ol
assert question.question.strip() and question.explanation.strip()
assert len({normalized_text(option) for option in question.options}) == 4
assert question.source_pages == [] # Original demo content has no source-page claims.
- assert [q.id for q in available_questions(course)] == [q.id for q in course.questions[:old_count]]
- assert course.learning_state['question_reviews'] == {
- q.id: 'pending' for q in course.questions[old_count:]
- }
+ reviews = course.learning_state['question_reviews']
+ assert [q.id for q in available_questions(course)] == [q.id for q in course.questions if reviews.get(q.id, 'legacy') in {'legacy','approved'}]
+ assert any(status == 'pending' for status in reviews.values())
+ assert set(reviews) == {q.id for q in course.questions[old_count:]}
for question in course.questions[old_count:]:
course = review_question(course, question.id, 'approved')
for topic in course.topics:
@@ -153,7 +153,7 @@ def test_anki_export_excludes_drafts_then_includes_approved_question(filename):
from services.anki_export_service import export_anki_tsv
course = load(filename)
- pending = next(q for q in course.questions if q.id in course.learning_state['question_reviews'])
+ pending = next(q for q in course.questions if course.learning_state['question_reviews'].get(q.id) == 'pending')
before = list(csv.reader(io.StringIO(export_anki_tsv(course)), delimiter='\t'))
assert len(before) == len(available_questions(course))
assert not any(row[0].startswith(pending.question + '\n') for row in before)
diff --git a/tests/test_hints.py b/tests/test_hints.py
index e3c663c..fb6342c 100644
--- a/tests/test_hints.py
+++ b/tests/test_hints.py
@@ -28,14 +28,14 @@ def test_demo_hints_cover_original_available_questions():
}
assert len(questions) == 126
- pending = {
+ expanded = {
qid
for filename in ("sample_course.json", CALCULUS_DEMO, "demo_python_basics.json")
for qid, status in read_data(filename).get("learning_state", {}).get("question_reviews", {}).items()
- if status == "pending"
+ if status in {"pending", "approved"}
}
- assert len(pending) == 111
- assert hint_bank.keys() == questions.keys() - pending
+ assert len(expanded) == 111
+ assert hint_bank.keys() == questions.keys() - expanded
for question_id, hints in hint_bank.items():
question = questions[question_id]
assert 2 <= len(hints) <= MAX_HINTS
diff --git a/tests/test_learning_evidence_page.py b/tests/test_learning_evidence_page.py
index a33d16f..60c52cc 100644
--- a/tests/test_learning_evidence_page.py
+++ b/tests/test_learning_evidence_page.py
@@ -4,6 +4,7 @@
drawn by render_priorities again, and the practice result shows its time by
topic as bars.
"""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
import ast
import re
@@ -464,7 +465,7 @@ def test_review_list_on_progress_is_unchanged():
ranked = [frame.value for frame in app.dataframe if "Why review" in frame.value.columns]
assert len(ranked) == 1 and list(ranked[0].columns) == ["Rank", "Topic", "Question", "Why review"]
assert list(ranked[0]["Rank"]) == list(range(1, len(ranked[0]) + 1))
- assert any(c.value.startswith("Priority uses incorrect/unanswered responses") for c in app.caption)
+ assert any(text.startswith("Priority uses incorrect/unanswered responses") for text in tooltip_texts(app))
assert "**Smart review list**" in [m.value for m in app.markdown]
assert app.button(key=f"priorities_{COURSE_ID}").label == "Practise review priorities"
# Starting practice from it is covered in tests/test_progress_charts.py.
diff --git a/tests/test_learning_flow_ux.py b/tests/test_learning_flow_ux.py
index 0826cad..9c6f56d 100644
--- a/tests/test_learning_flow_ux.py
+++ b/tests/test_learning_flow_ux.py
@@ -213,7 +213,7 @@ def test_explicit_new_practice_replaces_old_result_only_after_start(monkeypatch)
app.run()
next(b for b in app.button if b.label=='Start new practice').click().run()
assert not app.exception
- assert app.session_state['active_practice_calculus-i-demo']['session'].question_ids==['calc_q002']
+ assert set(app.session_state['active_practice_calculus-i-demo']['session'].question_ids)=={'calc_q002','calc_q013'}
assert 'result' not in app.session_state['active_practice_calculus-i-demo']
assert app.session_state['practice_history_calculus-i-demo']==history
diff --git a/tests/test_open_panels.py b/tests/test_open_panels.py
index 86261c6..ec2aac3 100644
--- a/tests/test_open_panels.py
+++ b/tests/test_open_panels.py
@@ -5,6 +5,7 @@
opens the Learning Radar page, which has the chart, ranking and stuck buttons.
The Concept Lab's steps are tested in tests/test_concept_lab_steps.py.
"""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
import re
from pathlib import Path
@@ -175,13 +176,13 @@ def _open_setup(chinese: bool = False, document: dict | None = None) -> AppTest:
return _home(chinese, **state)
-def test_home_supported_materials_is_a_visible_caption_of_two_sentences():
+def test_home_supported_materials_remains_available_in_tooltips():
app = _open_setup()
assert not app.exception
assert "Supported materials" not in _expander_labels(app)
setup = _block(app, "dashboard_course_setup")
- captions = [item.value for item in setup.caption]
+ captions = supporting_texts(setup)
assert SUPPORTED_MATERIALS in captions
# Right under the formats line, where the expander was.
formats = captions.index(
@@ -221,7 +222,7 @@ def test_home_open_panels_have_no_english_in_chinese():
app = _open_setup(chinese=True)
assert not app.exception
- captions = [item.value for item in _block(app, "dashboard_course_setup").caption]
+ captions = supporting_texts(_block(app, "dashboard_course_setup"))
assert SUPPORTED_MATERIALS_ZH in captions
assert SUPPORTED_MATERIALS not in captions
assert len(re.findall(r"。", SUPPORTED_MATERIALS_ZH)) == 2
diff --git a/tests/test_paper_ui_pages.py b/tests/test_paper_ui_pages.py
index d470f99..91a143d 100644
--- a/tests/test_paper_ui_pages.py
+++ b/tests/test_paper_ui_pages.py
@@ -1,4 +1,5 @@
"""Student-facing pages use one-click choices and hide storage bookkeeping."""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
from pathlib import Path
from types import SimpleNamespace
@@ -108,7 +109,7 @@ def test_review_list_shows_plain_status_words_instead_of_internal_codes():
assert not any("[" in option for option in options)
assert (
"Check the answer and explanation before approving; edits never change past results."
- in [item.value for item in app.caption]
+ in supporting_texts(app)
)
@@ -116,7 +117,7 @@ def test_study_plan_counts_ready_questions_without_prompting_a_review():
app = study_plan(make_reviewed_course())
assert not app.exception
- captions = [item.value for item in app.caption]
+ captions = supporting_texts(app)
# The page no longer prompts the student to review pending questions.
assert not any("needs your check" in text or "need your check" in text for text in captions)
assert "Review pending questions" not in [button.label for button in app.button]
@@ -128,7 +129,7 @@ def test_review_texts_are_translated():
app = study_plan(make_reviewed_course(), chinese=True)
assert not app.exception
- captions = [item.value for item in app.caption]
+ captions = supporting_texts(app)
assert not any("需要你检查" in text for text in captions)
assert "2 道题可以练习" in captions
@@ -152,7 +153,7 @@ def test_anonymous_course_tools_do_not_mention_the_database():
app = course_tools(make_reviewed_course(), "backup")
assert not app.exception
- captions = [item.value for item in app.caption]
+ captions = supporting_texts(app)
assert "Log in to back up this course." in captions
assert not any("database" in text.lower() for text in captions)
diff --git a/tests/test_pending_ui.py b/tests/test_pending_ui.py
index 207c584..39cea80 100644
--- a/tests/test_pending_ui.py
+++ b/tests/test_pending_ui.py
@@ -1,3 +1,4 @@
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
from models.schemas import StudyPackage
from io import BytesIO
from pathlib import Path
@@ -87,16 +88,9 @@ def test_dashboard_extracts_txt_and_shows_limits_preview_and_source(monkeypatch)
assert app.session_state["setup_document"]["sources"] == [
{"filename": "notes.txt", "page": None}
]
- assert any("50,000 characters" in item.value for item in app.caption)
- assert any(
- "UTF-8 TXT" in item.value
- and "text-based PDF or PPTX" in item.value
- for item in app.caption
- )
- assert any(
- "notes.txt · TXT file (no page number)" in item.value
- for item in app.caption
- )
+ assert any("50,000 characters" in text for text in tooltip_texts(app))
+ assert any('UTF-8 TXT' in text and 'text-based PDF or PPTX' in text for text in supporting_texts(app))
+ assert any('notes.txt · TXT file (no page number)' in text for text in supporting_texts(app))
assert "A local TXT fixture." in [item.value for item in app.text]
@@ -113,11 +107,11 @@ def test_dashboard_extracts_pdf_and_displays_actual_page_sources(monkeypatch):
document = app.session_state["setup_document"]
assert document["sources"] == [{"filename": "course.pdf", "page": 1}]
assert document["pages"][0]["page"] == 1
- assert any("course.pdf · Page 1" in item.value for item in app.caption)
+ assert any('course.pdf · Page 1' in text for text in supporting_texts(app))
# Page and character counts of the extracted material are not shown.
assert not any("PDF pages" in item.label for item in app.expander)
- assert not any("Extracted text:" in item.value for item in app.caption)
- assert not any(" characters" in item.value for item in app.markdown)
+ assert not any('Extracted text:' in text for text in supporting_texts(app))
+ assert not any(" characters" in item.value for item in app.markdown if "quiet-help-row" not in item.value)
def test_dashboard_image_ocr_uses_image_labels_and_updated_copy(monkeypatch):
@@ -136,13 +130,10 @@ def test_dashboard_image_ocr_uses_image_labels_and_updated_copy(monkeypatch):
assert not app.exception
assert not any("Image (1)" in item.label for item in app.expander)
assert not any("PDF pages" in item.label for item in app.expander)
- assert any("scan.png · Image 1" in item.value for item in app.caption)
+ assert any('scan.png · Image 1' in text for text in supporting_texts(app))
# The materials note says scanned PDFs are not read, without naming the OCR engine.
- assert any(
- "scanned pdfs" in item.value.lower()
- for item in app.caption
- )
- assert not any("tesseract" in item.value.lower() for item in app.caption)
+ assert any('scanned pdfs' in text.lower() for text in supporting_texts(app))
+ assert not any('tesseract' in text.lower() for text in supporting_texts(app))
def test_dashboard_failure_message_clears_old_document_and_disables_generation(
@@ -265,16 +256,10 @@ def test_dashboard_extracts_pptx_and_displays_actual_slide_sources(monkeypatch):
assert document["pages"] == [
{"page": 1, "text": "PPTX extraction fixture."}
]
- assert any(
- "slides.pptx · Slide 1" == item.value for item in app.caption
- )
+ assert any('slides.pptx · Slide 1' == text for text in supporting_texts(app))
assert not any("PPTX slides" in item.label for item in app.expander)
- assert any("50,000 characters" in item.value for item in app.caption)
- assert any(
- "UTF-8 TXT" in item.value
- and "text-based PDF or PPTX" in item.value
- for item in app.caption
- )
+ assert any("50,000 characters" in text for text in tooltip_texts(app))
+ assert any('UTF-8 TXT' in text and 'text-based PDF or PPTX' in text for text in supporting_texts(app))
def test_single_scope_selector_requires_reconfirmation():
diff --git a/tests/test_practice_compatibility.py b/tests/test_practice_compatibility.py
index d3d77e2..27a8da9 100644
--- a/tests/test_practice_compatibility.py
+++ b/tests/test_practice_compatibility.py
@@ -36,7 +36,7 @@ def test_demo_update_appends_drafts_preserving_old_questions_metadata_and_scope(
assert old==before
assert updated.learning_state['confirmed_scope']==old.learning_state['confirmed_scope']
assert updated.learning_state['session_order']==['old']
- assert set(updated.learning_state['question_reviews'].values())=={'pending'}
+ assert updated.learning_state['question_reviews'] == {q.id: current.learning_state['question_reviews'][q.id] for q in updated.questions[old_count:]}
assert demo_update(updated)==(updated,0)
diff --git a/tests/test_practice_focus.py b/tests/test_practice_focus.py
index 3c02c51..36b1774 100644
--- a/tests/test_practice_focus.py
+++ b/tests/test_practice_focus.py
@@ -1,4 +1,5 @@
"""Practice focus: one screen at a time, one question per page, a side panel that folds away."""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
import re
import time
from copy import deepcopy
@@ -332,7 +333,7 @@ def test_review_step_from_the_session_menu_and_from_finish():
assert list(table["Question"]) == [1, 2, 3]
assert list(table["Check"]) == ["Guessed", "Unanswered", "Unanswered"]
assert ("Go back to the questions to change these answers, or submit them as they are."
- in [caption.value for caption in app.caption])
+ in supporting_texts(app))
assert [(button.label, button.proto.type) for button in app.button] == [
("Back to questions", "secondary"), ("Submit answers", "primary"),
]
@@ -808,7 +809,7 @@ def test_question_screen_and_review_step_are_fully_chinese(mode):
assert titles(app) == ["练习 · 检查"]
assert "已作答 1 / 3" in page_markdown(app)
assert {button.label for button in app.button} == {"返回题目", "提交答案"}
- assert "可以返回题目修改这些答案,也可以按现在的答案提交。" in [c.value for c in app.caption]
+ assert "可以返回题目修改这些答案,也可以按现在的答案提交。" in supporting_texts(app)
assert [value for value in shown_strings(app) if re.search(r"[A-Za-z]", value)] == []
diff --git a/tests/test_practice_insights.py b/tests/test_practice_insights.py
index c281863..eaedd94 100644
--- a/tests/test_practice_insights.py
+++ b/tests/test_practice_insights.py
@@ -1,3 +1,4 @@
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
from copy import deepcopy
from pathlib import Path
@@ -74,7 +75,7 @@ def test_smart_review_list_is_on_the_page_not_behind_an_expander():
for expander in app.expander:
assert not any('Why review' in f.value.columns for f in expander.dataframe)
# The note on how the order is decided stays, as a line of text under the list.
- assert any(c.value.startswith('Priority uses incorrect/unanswered responses') for c in app.caption)
+ assert any(text.startswith('Priority uses incorrect/unanswered responses') for text in tooltip_texts(app))
assert app.button(key='priorities_insights').label=='Practise review priorities'
diff --git a/tests/test_practice_pages.py b/tests/test_practice_pages.py
index 5ccea28..2d4b2a6 100644
--- a/tests/test_practice_pages.py
+++ b/tests/test_practice_pages.py
@@ -1,5 +1,6 @@
"""Practice history and Review answers: the last collapsed blocks of the practice page,
each on a page of its own, plus the in-place reveal of a question's original wording."""
+from tests.tooltip_helpers import supporting_texts, tooltip_texts
import json
import re
from copy import deepcopy
@@ -138,7 +139,7 @@ def test_history_shows_a_section_only_when_it_has_rows(drafts, history, sections
def test_history_empty_state_and_no_course(monkeypatch):
app = page_app(HISTORY)
assert not app.exception
- assert [caption.value for caption in app.caption] == [
+ assert supporting_texts(app) == [
"No practice sessions yet. Finished and unfinished sessions will appear here."]
assert [button.label for button in app.button] == ["Back to Practice"]
assert not history_rows(app) and not app.subheader
@@ -217,16 +218,15 @@ def test_result_screen_has_no_tabs_and_a_review_answers_button_under_the_score()
assert not app.tabs and not app.get("tab_container")
keys = block_keys(app)
order = [keys.index(key) for key in (
- "practice_result_overview", "page_link_open_answer_review", "flight_next_topic",
+ "practice_result_overview", "result_review_action", "flight_next_topic",
"practice_mistake_review",
)]
assert order == sorted(order)
button = app.button(key="open_answer_review")
assert (button.label, button.proto.icon) == ("Review answers", ":material/fact_check:")
- assert keyed(app, "page_link_open_answer_review").proto.flex_container.justify == (
- BlockProto.FlexContainer.Justify.JUSTIFY_END)
+ assert button.proto.type == "primary"
# The summary, shown directly: next step, insights, review list, missed questions.
- assert "Take the next step" in [caption.value for caption in app.caption]
+ assert "Take the next step" in subheaders(app)
assert "Practice insights" in subheaders(app)
assert app.button(key="review_mistakes_s") and app.button(key="priorities_insights")
# The per-question answers are not on this screen any more.
@@ -263,7 +263,7 @@ def test_review_page_shows_one_question_with_everything_visible():
assert keyed(app, "page_link_review_answers_back").proto.flex_container.justify == LEFT
back = app.button(key="review_answers_back")
assert (back.label, back.proto.icon) == ("Back to result", ":material/arrow_back:")
- assert "Question 01 / 02" in [caption.value for caption in app.caption]
+ assert "Question 01 / 02" in supporting_texts(app)
assert badges(app) == ["Q01"]
assert [s.value for s in app.success] == ["✓ Your answer: A"]
app.button(key="review_next_s").click().run()
@@ -273,7 +273,7 @@ def test_review_page_shows_one_question_with_everything_visible():
assert subheaders(app) == ["Answer", "Explanation", "Ask about this explanation", "Reflect and explain your answer", "Source material"]
assert [e.value for e in app.error] == ["✕ Your answer: B"]
assert [s.value for s in app.success] == ["✓ Correct answer: A"]
- captions = [caption.value for caption in app.caption]
+ captions = supporting_texts(app)
assert "Hints used: 1 of 2" in captions and "Guessed · 1 hint · 42 s" in captions
assert "Reason" in page_markdown(app) # the explanation
assert app.button_group(key="reason_s_q1") and app.text_area(key="explain_s_q1")
@@ -297,7 +297,7 @@ def test_review_page_shows_the_original_wording_of_a_simplified_question():
"session": session, "questions": [question], "result": result, "warning": None, "settings": {}},
}, scope=[question.topic_id])
assert not app.exception
- assert "Simplified wording" in [caption.value for caption in app.caption]
+ assert "Simplified wording" in supporting_texts(app)
assert subheaders(app)[0] == "Original wording"
markdown = page_markdown(app)
assert question.question in markdown and all(option in markdown for option in question.options)
@@ -351,10 +351,10 @@ def test_reflection_is_shown_directly_and_saves_as_before():
assert not app.expander
assert "Reflect and explain your answer" in subheaders(app)
assert ("Write your reasoning in your own words. This reflection is after feedback and never changes your score."
- in [caption.value for caption in app.caption])
+ in supporting_texts(app))
# Text typed into the form is only sent when it is saved, so the page says so before a page turn loses it.
assert ("Save before you go to another question: text that is not saved is not kept."
- in [caption.value for caption in app.caption])
+ in supporting_texts(app))
app.button_group(key="reason_s_q1").set_value("misread")
app.text_area(key="explain_s_q1").set_value("I read B as A.")
next(b for b in app.button if b.label == "Save reflection").click().run()
@@ -379,7 +379,7 @@ def test_try_a_different_structure_goes_to_the_new_session(monkeypatch):
def test_review_page_without_an_open_result():
app = page_app(REVIEW)
assert not app.exception
- assert [caption.value for caption in app.caption] == ["No result to review yet. Finish a practice session first."]
+ assert supporting_texts(app) == ["No result to review yet. Finish a practice session first."]
assert [button.label for button in app.button] == ["Back to result"]
assert not badges(app)
diff --git a/tests/test_result_review_refinement.py b/tests/test_result_review_refinement.py
new file mode 100644
index 0000000..55c5b8d
--- /dev/null
+++ b/tests/test_result_review_refinement.py
@@ -0,0 +1,66 @@
+from copy import deepcopy
+from pathlib import Path
+
+import pytest
+from models.schemas import ExamSession, StudyPackage
+from services.demo_updates import FILES, demo_update
+from services.practice_insights import transfer_session
+from services.question_editor import available_questions
+from services.math_text import math_markdown
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+@pytest.mark.parametrize('filename', list(FILES.values()))
+def test_each_available_demo_question_has_a_different_structure_for_a_one_question_session(filename):
+ course = StudyPackage.model_validate_json((ROOT/'data'/filename).read_text(encoding='utf-8'))
+ scope = [topic.id for topic in course.topics]
+ for question in available_questions(course):
+ session = ExamSession(session_id='original',mode='topic',question_ids=[question.id])
+ transfer = transfer_session(course,question,session,scope)
+ alternate = transfer['questions'][0]
+ assert alternate.id != question.id and alternate.topic_id == question.topic_id
+ assert alternate.practice_structure != question.practice_structure
+ assert alternate in available_questions(course)
+
+
+def test_catalog_review_preserves_rejections_edits_history_and_scope():
+ course = StudyPackage.model_validate_json((ROOT/'data/calculus_i_demo.json').read_text(encoding='utf-8'))
+ data = course.model_dump()
+ data['learning_state']['question_reviews']['calc_q004'] = 'flagged'
+ data['learning_state']['question_reviews']['calc_q013'] = 'pending'
+ next(q for q in data['questions'] if q['id']=='calc_q013')['question'] += ' Learner edit.'
+ data['learning_state']['question_reviews']['calc_q022'] = 'pending'
+ data['learning_state']['confirmed_scope'] = ['calc_limits']
+ data['learning_state']['session_order'] = ['old-session']
+ old = StudyPackage.model_validate(data)
+ before = deepcopy(old)
+ updated, added = demo_update(old)
+ assert added == 0 and old == before and updated.questions == old.questions
+ assert updated.learning_state['question_reviews']['calc_q004'] == 'flagged'
+ assert updated.learning_state['question_reviews']['calc_q013'] == 'pending'
+ assert updated.learning_state['question_reviews']['calc_q022'] == 'approved'
+ assert updated.learning_state['confirmed_scope'] == ['calc_limits']
+ assert updated.learning_state['session_order'] == ['old-session']
+
+
+def test_legacy_missing_labels_supports_transfer_without_mutating_saved_questions():
+ course = StudyPackage.model_validate_json((ROOT/'data/calculus_i_demo.json').read_text(encoding='utf-8'))
+ rows = [q.model_copy(update={'practice_structure':None,'cognitive_dimension':None,'hints':[]}) for q in course.questions]
+ metadata = deepcopy(course.learning_state)
+ metadata['question_reviews']['calc_q004'] = 'pending'
+ old = course.model_copy(update={'questions':rows,'learning_state':metadata})
+ updated,_ = demo_update(old)
+ assert updated.questions == old.questions
+ source = updated.questions[0]
+ session = ExamSession(session_id='old',mode='topic',question_ids=[source.id])
+ followup = transfer_session(updated,source,session,['calc_limits'])
+ assert followup['questions'][0].id == 'calc_q004'
+ assert source.practice_structure is None
+
+
+def test_known_summary_formulas_use_math_delimiters_and_protect_existing_math_and_code():
+ original = 'With angles in radians, lim(x→0) sin(x)/x = 1.'
+ assert math_markdown(original) == r'With angles in radians, $\lim_{x\to0}\frac{\sin x}{x}=1$.'
+ text = r'Already $f(x)$ and `f(x)` and ```f(x)```.'
+ assert math_markdown(text) == text
diff --git a/tests/tooltip_helpers.py b/tests/tooltip_helpers.py
index 61b4429..2394774 100644
--- a/tests/tooltip_helpers.py
+++ b/tests/tooltip_helpers.py
@@ -6,3 +6,7 @@
def tooltip_texts(app):
return [html.unescape(text) for item in app.markdown
for text in re.findall(r']*>(.*?)', item.value, re.S)]
+
+
+def supporting_texts(app):
+ return [item.value for item in app.caption] + tooltip_texts(app)