From 78c2eef657dc0cb58361dc2e1dd9676963cb42d1 Mon Sep 17 00:00:00 2001 From: Jiale Li Date: Sun, 15 Nov 2026 12:18:30 -0500 Subject: [PATCH 1/3] Carry radar topics into practice and restore saved flags on login --- components/topic_practice_link.py | 13 +++ pages/1_Study_Hub.py | 15 +--- pages/2_Practice_Center.py | 139 +++++++++++++++++++----------- pages/4_Knowledge_Graph.py | 11 +-- pages/6_Concept_Lab.py | 10 +-- pages/7_Learning_Radar.py | 30 ++++++- services/i18n.py | 1 + services/learning_flow.py | 15 ++++ services/learning_radar.py | 3 +- tests/test_concept_lab.py | 35 +++++--- tests/test_learning_radar_page.py | 59 +++++++++++++ tests/test_study_hub_radar.py | 13 ++- 12 files changed, 242 insertions(+), 102 deletions(-) create mode 100644 components/topic_practice_link.py diff --git a/components/topic_practice_link.py b/components/topic_practice_link.py new file mode 100644 index 0000000..2af130e --- /dev/null +++ b/components/topic_practice_link.py @@ -0,0 +1,13 @@ +"""Navigation from a selected topic to its practice setup.""" + +import streamlit as st + +from services.i18n import tr +from services.learning_flow import stage_topic_practice + + +def open_topic_practice(course, topic_id): + if stage_topic_practice(st.session_state, course, topic_id): + st.switch_page("pages/2_Practice_Center.py") + else: + st.info(tr("There are no approved practice questions for this topic yet.")) diff --git a/pages/1_Study_Hub.py b/pages/1_Study_Hub.py index 3b77217..baee626 100644 --- a/pages/1_Study_Hub.py +++ b/pages/1_Study_Hub.py @@ -3,6 +3,7 @@ from components.knowledge_graph import load_course_radar, radar_count_text, radar_display_order from components.page_links import open_page_button +from components.topic_practice_link import open_topic_practice from models.schemas import StudyPackage from services import learning_radar from services.account_sync import SAVE_FAILED_MESSAGE, save_course_to_account @@ -71,7 +72,7 @@ def keep_scope_selection(course_id: str) -> None: } -def render_most_flagged_topics(course, confirmed_key: str) -> None: +def render_most_flagged_topics(course) -> None: """Show a demo course's three most flagged topics with a practice shortcut. The radar comes from the session cache shared with the Knowledge Map, so @@ -111,15 +112,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: tr("Practice now"), key=f"study_radar_practice_{course.course_id}_{topic_id}", ): - # Topic Practice only offers topics from the confirmed scope. - if topic_id in (st.session_state.get(confirmed_key) or []): - stage_practice(st.session_state, course, topic_id) - st.switch_page("pages/2_Practice_Center.py") - else: - st.info( - tr(f"Confirm {topic_name} in your exam scope above, " - "then select Practice now again.") - ) + open_topic_practice(course, topic_id) if radar.has_sample: st.caption(tr("Includes sample data")) @@ -297,7 +290,7 @@ def render_most_flagged_topics(course, confirmed_key: str) -> None: # Learning Radar is only available for the built-in demo courses. if learning_radar.radar_enabled(course.course_id): - render_most_flagged_topics(course, confirmed_key) + render_most_flagged_topics(course) # Question review, backups and source material are course maintenance, not a # study step: a small button on the right opens them on a page of their own. diff --git a/pages/2_Practice_Center.py b/pages/2_Practice_Center.py index c114677..03adc35 100644 --- a/pages/2_Practice_Center.py +++ b/pages/2_Practice_Center.py @@ -88,10 +88,15 @@ def begin_mistake_review(practice_key, course, session, questions, confirmed_ids if graded is None: return # a second click: the review session is already open try: - install_practice(st.session_state, course.course_id, create_mistake_review( + focused_topic = (graded.get("settings") or {}).get("focused_topic") + review = create_mistake_review( session, questions, graded["result"]["attempts"], - confirmed_ids, topic_id, approved_ids={q.id for q in available_questions(course)}, - )) + confirmed_ids, topic_id or focused_topic, + approved_ids={q.id for q in available_questions(course)}, + ) + if focused_topic: + review["settings"]["focused_topic"] = focused_topic + install_practice(st.session_state, course.course_id, review) except ValueError as error: st.session_state["practice_launch_error"] = str(error) else: @@ -116,11 +121,13 @@ def return_to_session(course_id): # always shows the value the page uses (Streamlit sends a value to the browser only when # the key is assigned in the run that draws the widget). -def choice_key(course_id): +def choice_key(course_id, focused_topic=None): + if focused_topic: + return f"practice_focused_choice_{course_id}_{focused_topic}" return f"practice_choice_{course_id}" -def opening_choice(course_id, confirmed_topic_ids, active, pending_entry): +def opening_choice(course_id, confirmed_topic_ids, active, pending_entry, focused_topic=None): """What the setup screen shows when it opens, in this order of preference: a request staged by another page, the open session's settings, the student's last choice, the defaults.""" @@ -135,7 +142,7 @@ def opening_choice(course_id, confirmed_topic_ids, active, pending_entry): else: staged = {} sources = ( # lowest preference first; later ones win - st.session_state.get(choice_key(course_id)) or {}, + st.session_state.get(choice_key(course_id, focused_topic)) or {}, {"mode": settings.get("mode"), "topic_id": settings.get("topic_id"), "count": settings.get("requested_count")}, staged, ) @@ -150,9 +157,9 @@ def opening_choice(course_id, confirmed_topic_ids, active, pending_entry): return choice -def remember_choice(course_id, field, confirmed_topic_ids): +def remember_choice(course_id, field, confirmed_topic_ids, focused_topic=None): """on_change of a setup widget: keep the new value as the student's choice.""" - choice = st.session_state.setdefault(choice_key(course_id), {}) + choice = st.session_state.setdefault(choice_key(course_id, focused_topic), {}) value = st.session_state.get(f"practice_{field}_{course_id}") if field == "mode": choice["mode"] = "mock" if value == tr("Mock Exam") else "topic" @@ -163,14 +170,14 @@ def remember_choice(course_id, field, confirmed_topic_ids): choice["count"] = int(value) -def shown_settings(course_id, confirmed_topic_ids): +def shown_settings(course_id, confirmed_topic_ids, focused_topic=None): """The settings Start uses: the widgets' latest values, which are what the screen shows. The knowledge point counts only if it was on screen; otherwise it is the kept choice, which is what the screen shows as soon as Topic Practice is chosen. """ state = st.session_state - choice = state.get(choice_key(course_id)) or {} + choice = state.get(choice_key(course_id, focused_topic)) or {} mode = "mock" if state.get(f"practice_mode_{course_id}", tr("Mock Exam")) == tr("Mock Exam") else "topic" topic_id = None if mode == "topic": @@ -183,14 +190,16 @@ def shown_settings(course_id, confirmed_topic_ids): return mode, topic_id, int(count) -def start_practice(course, confirmed_topic_ids, session_id): +def start_practice(course, confirmed_topic_ids, session_id, focused_topic=None): """Start button: a new session from the settings on screen.""" state = st.session_state course_id = course.course_id active = state.get(f"active_practice_{course_id}") if (active["session"].session_id if active else None) != session_id: return # a second click: the new session is already open - mode, topic_id, requested_count = shown_settings(course_id, confirmed_topic_ids) + mode, topic_id, requested_count = shown_settings(course_id, confirmed_topic_ids, focused_topic) + if focused_topic: + mode, topic_id = "topic", focused_topic try: exam = create_exam( package=course, @@ -202,13 +211,16 @@ def start_practice(course, confirmed_topic_ids, session_id): except ValueError: state["practice_create_error"] = True return + settings = { + "mode": mode, + "requested_count": requested_count, + "confirmed_topic_ids": sorted(confirmed_topic_ids), + "topic_id": topic_id, + } + if focused_topic: + settings["focused_topic"] = focused_topic install_practice(state, course_id, { - "settings": { - "mode": mode, - "requested_count": requested_count, - "confirmed_topic_ids": sorted(confirmed_topic_ids), - "topic_id": topic_id, - }, + "settings": settings, "session": exam["session"], "questions": exam["questions"], "warning": exam["warning"], @@ -303,27 +315,33 @@ def choose_topic(course_id, confirmed_topic_ids, topic_names): ) -def render_setup_screen(course, confirmed_topic_ids, topic_names, active_practice, pending_entry, opening): +def render_setup_screen( + course, confirmed_topic_ids, topic_names, active_practice, pending_entry, opening, + focused_topic=None, +): cid = course.course_id in_progress = active_practice is not None and "result" not in active_practice - choice = st.session_state.get(choice_key(cid)) + selected_choice_key = choice_key(cid, focused_topic) + choice = st.session_state.get(selected_choice_key) if opening or not isinstance(choice, dict): - choice = st.session_state[choice_key(cid)] = opening_choice( - cid, confirmed_topic_ids, active_practice, pending_entry) + choice = st.session_state[selected_choice_key] = opening_choice( + cid, confirmed_topic_ids, active_practice, pending_entry, focused_topic) if choice.get("topic_id") not in confirmed_topic_ids: # the scope changed since choice["topic_id"] = confirmed_topic_ids[0] + if focused_topic: + choice.update(mode="topic", topic_id=focused_topic) # Assigned in the run that draws the widgets, so the browser shows what Start uses. st.session_state[f"practice_mode_{cid}"] = tr("Topic Practice") if choice["mode"] == "topic" else tr("Mock Exam") st.session_state[f"practice_count_{cid}"] = choice["count"] - st.session_state[f"practice_topic_drawn_{cid}"] = choice["mode"] == "topic" - if choice["mode"] == "topic": + st.session_state[f"practice_topic_drawn_{cid}"] = choice["mode"] == "topic" and not focused_topic + if st.session_state[f"practice_topic_drawn_{cid}"]: st.session_state[f"practice_topic_{cid}"] = choice["topic_id"] setup_heading() - if pending_entry is not None: + if pending_entry is not None and not focused_topic: target = pending_entry.get("topic_id") st.info( - (tr("New practice: ") + topic_names[target]) if target + (tr("New practice: ") + topic_names[target]) if target in topic_names else tr("New practice for your confirmed topics.") ) if in_progress or (pending_entry is not None and active_practice is not None): @@ -334,21 +352,24 @@ def render_setup_screen(course, confirmed_topic_ids, topic_names, active_practic ) with st.container(border=True, key="practice_setup"): - st.caption( - tr("Confirmed topics") + ": " - + " · ".join(topic_names[value] for value in confirmed_topic_ids) - ) - st.radio( - tr("Practice mode"), - options=[tr("Mock Exam"), tr("Topic Practice")], - key=f"practice_mode_{cid}", - horizontal=True, - width="stretch", - on_change=remember_choice, args=(cid, "mode", confirmed_topic_ids), - ) - - if choice["mode"] == "topic": - choose_topic(cid, confirmed_topic_ids, topic_names) + if focused_topic: + st.subheader(topic_names[focused_topic]) + st.caption(tr("Topic Practice")) + else: + st.caption( + tr("Confirmed topics") + ": " + + " · ".join(topic_names[value] for value in confirmed_topic_ids) + ) + st.radio( + tr("Practice mode"), + options=[tr("Mock Exam"), tr("Topic Practice")], + key=f"practice_mode_{cid}", + horizontal=True, + width="stretch", + on_change=remember_choice, args=(cid, "mode", confirmed_topic_ids), + ) + if choice["mode"] == "topic": + choose_topic(cid, confirmed_topic_ids, topic_names) # No default value: the key is always assigned above. st.number_input( @@ -358,7 +379,7 @@ def render_setup_screen(course, confirmed_topic_ids, topic_names, active_practic step=1, key=f"practice_count_{cid}", width=240, - on_change=remember_choice, args=(cid, "count", confirmed_topic_ids), + on_change=remember_choice, args=(cid, "count", confirmed_topic_ids, focused_topic), ) start_label = ( @@ -370,10 +391,14 @@ def render_setup_screen(course, confirmed_topic_ids, topic_names, active_practic st.button( tr(start_label), type="primary", key=f"practice_start_{cid}", on_click=start_practice, - args=(course, confirmed_topic_ids, active_practice["session"].session_id if active_practice else None), + args=(course, confirmed_topic_ids, active_practice["session"].session_id if active_practice else None, + focused_topic), ) if st.session_state.pop("practice_create_error", None): - st.error(tr("Could not create practice. Try another topic or check your exam scope in Study Plan.")) + if focused_topic: + st.error(tr("There are no approved practice questions for this topic yet.")) + else: + st.error(tr("Could not create practice. Try another topic or check your exam scope in Study Plan.")) # Unfinished and graded sessions are listed on a page of their own. if has_practice_history(st.session_state, course.course_id): @@ -715,9 +740,22 @@ def render_result_screen(course, active_practice, confirmed_topic_ids, topic_nam st.page_link("pages/0_Dashboard.py", label=tr("Back to Dashboard")) st.stop() -confirmed_key = f"confirmed_scope_{course.course_id}" -confirmed_topic_ids = st.session_state.get(confirmed_key) +practice_key = f"active_practice_{course.course_id}" +active_practice = st.session_state.get(practice_key) +pending_entry = st.session_state.get(f"practice_entry_{course.course_id}") +topic_names = {topic.id: topic.name for topic in course.topics} + +# A single-topic shortcut supplies scope only for this practice session. +if pending_entry is not None: + focused_topic = pending_entry.get("topic_id") if pending_entry.get("focused") else None +else: + focused_topic = ((active_practice or {}).get("settings") or {}).get("focused_topic") +if focused_topic not in topic_names: + focused_topic = None +confirmed_topic_ids = ( + [focused_topic] if focused_topic else st.session_state.get(f"confirmed_scope_{course.course_id}") +) if not confirmed_topic_ids: setup_heading() st.warning(tr("Confirm your exam scope in Study Plan first.")) @@ -726,8 +764,6 @@ def render_result_screen(course, active_practice, confirmed_topic_ids, topic_nam st.stop() # Validate the confirmed scope before offering practice settings. -topic_names = {topic.id: topic.name for topic in course.topics} - if ( len(confirmed_topic_ids) != len(set(confirmed_topic_ids)) or not set(confirmed_topic_ids).issubset(topic_names) @@ -737,9 +773,6 @@ def render_result_screen(course, active_practice, confirmed_topic_ids, topic_nam st.page_link("pages/1_Study_Hub.py", label=tr("Go to Study Plan")) st.stop() -practice_key = f"active_practice_{course.course_id}" -active_practice = st.session_state.get(practice_key) -pending_entry = st.session_state.get(f"practice_entry_{course.course_id}") st.session_state.pop("priority_ready", None) # app.py sets this flag when the student arrives from another page: the page then opens @@ -775,7 +808,9 @@ def render_result_screen(course, active_practice, confirmed_topic_ids, topic_nam st.session_state[screen_key] = screen if screen == "setup": - render_setup_screen(course, confirmed_topic_ids, topic_names, active_practice, pending_entry, opening) + render_setup_screen( + course, confirmed_topic_ids, topic_names, active_practice, pending_entry, opening, focused_topic + ) elif screen == "result": render_result_screen(course, active_practice, confirmed_topic_ids, topic_names) elif screen == "review": diff --git a/pages/4_Knowledge_Graph.py b/pages/4_Knowledge_Graph.py index e7d9647..d470a68 100644 --- a/pages/4_Knowledge_Graph.py +++ b/pages/4_Knowledge_Graph.py @@ -28,7 +28,8 @@ suggestions_key, ) from services.ui_style import apply_app_styles -from services.learning_flow import open_lab, stage_practice +from components.topic_practice_link import open_topic_practice +from services.learning_flow import open_lab apply_app_styles() @@ -343,13 +344,7 @@ st.session_state[pending_key] = linked_id st.rerun() 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) - except ValueError as error: - st.info(tr(str(error))) - st.page_link("pages/1_Study_Hub.py", label=tr("Confirm scope in Study Plan")) - else: - st.switch_page("pages/2_Practice_Center.py") + open_topic_practice(course, selected_node_id) if radar is not None: st.divider() diff --git a/pages/6_Concept_Lab.py b/pages/6_Concept_Lab.py index 7b9ed8a..3ac4206 100644 --- a/pages/6_Concept_Lab.py +++ b/pages/6_Concept_Lab.py @@ -14,7 +14,7 @@ cubic, cubic_derivative, limit_example, limit_table, secant_slope, tangent_line, corner_slopes, ) from services.ui_style import apply_app_styles -from services.learning_flow import stage_practice +from components.topic_practice_link import open_topic_practice from services.concept_lab_ui import ( DISTANCES, current_step, explanation, explore_navigation, keep_value, observation, prediction, restore_values, step_indicator, @@ -29,13 +29,7 @@ def practice_topic(topic_id: str, suffix: str = "") -> None: if course is None or course.course_id != "calculus-i-demo": st.info(tr("Open the Calculus I Demo course on the Dashboard to practise this topic.")) return - confirmed = st.session_state.get(f"confirmed_scope_{course.course_id}", []) - if topic_id not in confirmed: - st.info(tr("Confirm this topic in Study Plan first.")) - st.page_link("pages/1_Study_Hub.py", label=tr("Go to Study Plan")) - return - stage_practice(st.session_state, course, topic_id) - st.switch_page("pages/2_Practice_Center.py") + open_topic_practice(course, topic_id) def start_step(topic: str) -> int: diff --git a/pages/7_Learning_Radar.py b/pages/7_Learning_Radar.py index 7a52ef9..0a6d04a 100644 --- a/pages/7_Learning_Radar.py +++ b/pages/7_Learning_Radar.py @@ -6,6 +6,7 @@ from components.knowledge_graph import load_course_radar, render_radar_panel from components.radar_chart import render_course_radar_chart, render_stuck_buttons +from components.topic_practice_link import open_topic_practice from services import learning_radar from services.auth_session import current_user from services.ui_style import apply_app_styles @@ -32,14 +33,26 @@ 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) +radar, user_flags = 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. +focus_key = f"learning_radar_focus_{course.course_id}" + + +def remember_topic(): + st.session_state[focus_key] = st.session_state.get(picker_key) + + +# Widget values can disappear on navigation. A fresh login starts at the +# account's most recently marked topic for this course. +if picker_key not in st.session_state: + remembered = st.session_state.get(focus_key) + if remembered not in topic_names: + remembered = next((topic_id for topic_id in user_flags if topic_id in topic_names), None) + if remembered is not None: + st.session_state[picker_key] = remembered 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: @@ -68,6 +81,7 @@ options=list(topic_names), format_func=lambda topic_id: topic_names[topic_id], key=picker_key, + on_change=remember_topic, label_visibility="collapsed", ) else: @@ -78,6 +92,7 @@ format_func=lambda topic_id: topic_names[topic_id], placeholder=tr("Pick a topic"), key=picker_key, + on_change=remember_topic, label_visibility="collapsed", ) @@ -91,6 +106,13 @@ user_id, key=f"learning_radar_stuck_{course.course_id}_{picked}", ) + if st.button( + tr("Practice this topic"), + key=f"learning_radar_practice_{course.course_id}_{picked}", + icon=":material/edit_note:", + type="primary", + ): + open_topic_practice(course, picked) if st.button( tr("Open this topic in Knowledge Map"), key=f"learning_radar_map_{course.course_id}_{picked}", diff --git a/services/i18n.py b/services/i18n.py index f6a2933..1b9d9a4 100644 --- a/services/i18n.py +++ b/services/i18n.py @@ -302,6 +302,7 @@ def remember_language() -> None: "For f(x) = x³ − 5x, shrink h and compare the secant with the tangent at x₀.": "对 f(x) = x³ − 5x,缩小 h 并比较 x₀ 处的割线与切线。", "Secant slope": "割线斜率", "Derivative f′(x₀)": "导数 f′(x₀)", "As h approaches 0, the secant slope approaches f′(x₀) = 3x₀² − 5.": "h 趋于 0 时,割线斜率趋于 f′(x₀) = 3x₀² − 5。", + "There are no approved practice questions for this topic yet.": "这个知识点暂时没有已审核的练习题。", "Practice this topic": "练习这个知识点", "Open the Calculus I Demo course on the Dashboard to practise this topic.": "先在主页打开 Calculus I Demo 课程,再练习这个知识点。", "Confirm this topic in Study Plan first.": "请先在学习计划中确认这个知识点。", "Review course knowledge cards here or download a UTF-8 TSV file for Anki text import. AnkiWeb sync is not supported; Anki Desktop import has not been verified.": "在此查看课程知识卡片,或下载 UTF-8 TSV 文件并导入 Anki。暂不支持 AnkiWeb 同步;Anki 桌面版导入尚未验证。", diff --git a/services/learning_flow.py b/services/learning_flow.py index 12caae7..8c544f9 100644 --- a/services/learning_flow.py +++ b/services/learning_flow.py @@ -1,6 +1,8 @@ """Explicit cross-page intents; switching tools must not discard unfinished work.""" from copy import deepcopy +from services.question_editor import available_questions + def stage_practice(state, course, topic_id=None): @@ -13,6 +15,19 @@ def stage_practice(state, course, topic_id=None): state[f'practice_entry_{course.course_id}']={'topic_id':topic_id} +def stage_topic_practice(state, course, topic_id): + """Prepare practice for an explicitly chosen topic, even outside the exam scope.""" + if topic_id not in {topic.id for topic in course.topics} or not any( + question.topic_id == topic_id for question in available_questions(course) + ): + return False + if topic_id in (state.get(f"confirmed_scope_{course.course_id}") or []): + stage_practice(state, course, topic_id) + else: + state[f"practice_entry_{course.course_id}"] = {"topic_id": topic_id, "focused": True} + return True + + def install_practice(state, course_id, practice): key=f'active_practice_{course_id}' old=state.get(key) diff --git a/services/learning_radar.py b/services/learning_radar.py index 6c5cdb7..452f99b 100644 --- a/services/learning_radar.py +++ b/services/learning_radar.py @@ -55,6 +55,7 @@ SELECT topic_id, reason FROM radar_flags WHERE demo_user_id = %s AND course_id = %s + ORDER BY created_at DESC, topic_id """ _COURSE_COUNTS_SQL = """ @@ -189,7 +190,7 @@ def clear_flag(user_id: str, course_id: str, topic_id: str) -> PersistenceResult def get_user_flags(user_id: str, course_id: str) -> dict[str, str | None]: - """Map each topic this user flagged in the course to its reason; {} if unreadable.""" + """Map this account’s flagged topics to their reasons, newest flag first.""" normalized_user_id = _normalized_user_id(user_id) if normalized_user_id is None or not radar_enabled(course_id): return {} diff --git a/tests/test_concept_lab.py b/tests/test_concept_lab.py index 64be434..6940581 100644 --- a/tests/test_concept_lab.py +++ b/tests/test_concept_lab.py @@ -163,27 +163,40 @@ def test_derivative_sliders_update_exact_and_secant_values(x0, exact): @pytest.mark.parametrize("topic", ["calc_limits", "calc_derivatives"]) -@pytest.mark.parametrize("filename", [None, "sample_course.json", "calculus_i_demo.json"]) -def test_practice_button_explains_missing_course_or_scope(monkeypatch, topic, filename): +@pytest.mark.parametrize("filename", [None, "sample_course.json"]) +def test_practice_button_explains_missing_course(monkeypatch, topic, filename): import streamlit as st - links = [] - monkeypatch.setattr(st, "page_link", lambda page, **kwargs: links.append(page)) + destinations = [] + monkeypatch.setattr(st, "switch_page", lambda page: destinations.append(page)) app = AppTest.from_file(str(PAGE_PATH)) app.session_state["current_course"] = load_course(filename) if filename else None app.session_state[EXPLAIN_STEP[topic]] = 3 # the practice button sits in step 3 app.run().button(key=f"concept_lab_practice_{topic}").click().run() assert not app.exception - expected = ( - "Confirm this topic in Study Plan first." - if filename == "calculus_i_demo.json" - else "Open the Calculus I Demo course on the Dashboard to practise this topic." - ) - assert expected in [item.value for item in app.info] - assert bool(links) == (filename == "calculus_i_demo.json") + assert "Open the Calculus I Demo course on the Dashboard to practise this topic." in [ + item.value for item in app.info + ] + assert not destinations assert "practice_mode_calculus-i-demo" not in app.session_state +@pytest.mark.parametrize("topic", ["calc_limits", "calc_derivatives"]) +def test_lab_can_practise_its_topic_without_an_exam_scope(topic): + from tests.auth_helpers import signed_in_app + + app = signed_in_app(PAGE_PATH.parents[1] / "app.py").run() + app.session_state["current_course"] = load_course() + app.session_state[EXPLAIN_STEP[topic]] = 3 + app.switch_page("pages/6_Concept_Lab.py").run() + app.button(key=f"concept_lab_practice_{topic}").click().run() + + assert not app.exception + assert app.title[0].value == "Practice" + assert app.session_state["practice_entry_calculus-i-demo"]["topic_id"] == topic + assert "confirmed_scope_calculus-i-demo" not in app.session_state + + @pytest.mark.parametrize("topic", ["calc_limits", "calc_derivatives"]) def test_practice_button_sets_contract_and_practice_page_uses_it(monkeypatch, topic): import streamlit as st diff --git a/tests/test_learning_radar_page.py b/tests/test_learning_radar_page.py index 363ae4e..79c1e74 100644 --- a/tests/test_learning_radar_page.py +++ b/tests/test_learning_radar_page.py @@ -219,3 +219,62 @@ def test_page_in_chinese(monkeypatch, signed_in): assert app.title[0].value == "学习雷达" assert "各知识点卡住的学生人数" in _captions(app) assert app.session_state["current_course"].course_id == ECON_ID + + +def test_new_login_opens_the_most_recent_saved_flag(monkeypatch): + radar = RadarFake( + monkeypatch, + [_topic("price_controls", real=4), _topic("elasticity", real=3)], + user_flags={"price_controls": "calculation", "elasticity": "wording"}, + ) + + app = _page(_econ_course()) + + assert not app.exception + assert app.button_group(key=f"learning_radar_topic_{ECON_ID}").value == "price_controls" + assert "You marked this topic." in _markdown(app) + assert any("Calculation errors" in caption for caption in _captions(app)) + assert radar.calls["get_user_flags"] == [(TEST_USER.user_id, ECON_ID)] + + +@pytest.mark.parametrize("exam_scope", [None, ["supply_demand"]]) +def test_radar_uses_the_picked_topic_for_practice_without_changing_scope(monkeypatch, exam_scope): + RadarFake(monkeypatch, [_topic("elasticity", real=4)]) + app = signed_in_app(ROOT / "app.py").run() + app.session_state["current_course"] = _econ_course() + scope_key = f"confirmed_scope_{ECON_ID}" + if exam_scope is not None: + app.session_state[scope_key] = list(exam_scope) + + app.switch_page("pages/7_Learning_Radar.py").run() + app.button_group(key=f"learning_radar_topic_{ECON_ID}").set_value("elasticity").run() + app.button(key=f"learning_radar_practice_{ECON_ID}_elasticity").click().run() + + assert not app.exception + assert app.title[0].value == "Practice" + assert "Price Elasticity of Demand" in [heading.value for heading in app.subheader] + assert not any(radio.label == "Practice mode" for radio in app.radio) + app.button(key=f"practice_start_{ECON_ID}").click().run() + + assert not app.exception + session = app.session_state[f"active_practice_{ECON_ID}"] + assert session["session"].mode == "topic" + assert {q.topic_id for q in session["questions"]} == {"elasticity"} + assert (app.session_state[scope_key] if scope_key in app.session_state else None) == exam_scope + + app.switch_page("pages/7_Learning_Radar.py").run() + assert not app.exception + assert app.button_group(key=f"learning_radar_topic_{ECON_ID}").value == "elasticity" + + +def test_topic_without_questions_stays_on_radar_with_explanation(monkeypatch): + RadarFake(monkeypatch, [_topic("elasticity", real=4)]) + app = _page(_econ_course().model_copy(update={"questions": []})) + app.button_group(key=f"learning_radar_topic_{ECON_ID}").set_value("elasticity").run() + app.button(key=f"learning_radar_practice_{ECON_ID}_elasticity").click().run() + + assert not app.exception + assert [notice.value for notice in app.info] == [ + "There are no approved practice questions for this topic yet." + ] + assert f"practice_entry_{ECON_ID}" not in app.session_state diff --git a/tests/test_study_hub_radar.py b/tests/test_study_hub_radar.py index 0a7ab77..d1fac06 100644 --- a/tests/test_study_hub_radar.py +++ b/tests/test_study_hub_radar.py @@ -364,7 +364,7 @@ def test_practice_now_on_confirmed_topic_preselects_topic_practice(monkeypatch): @pytest.mark.parametrize("confirmed", [None, ["calc_limits"]]) -def test_practice_now_on_unconfirmed_topic_asks_to_confirm_scope(monkeypatch, confirmed): +def test_practice_now_on_unconfirmed_topic_keeps_the_exam_scope(monkeypatch, confirmed): destinations = [] monkeypatch.setattr(st, "switch_page", lambda page: destinations.append(page)) RadarFake( @@ -376,12 +376,11 @@ def test_practice_now_on_unconfirmed_topic_asks_to_confirm_scope(monkeypatch, co app.button(key=_practice_key(CALCULUS_ID, "calc_derivatives")).click().run() assert not app.exception - assert destinations == [] - assert "practice_mode_calculus-i-demo" not in app.session_state - assert "practice_topic_calculus-i-demo" not in app.session_state - assert [item.value for item in _panel(app).info] == [ - "Confirm Derivatives in your exam scope above, then select Practice now again." - ] + assert destinations == [PRACTICE_PAGE] + assert app.session_state["practice_entry_calculus-i-demo"] == { + "topic_id": "calc_derivatives", "focused": True, + } + assert not _panel(app).info assert app.session_state["scope_selection_calculus-i-demo"] == (confirmed or []) From 86859114fcd187ba613fbdf0979cfe5724acf1af Mon Sep 17 00:00:00 2001 From: Jiale Li Date: Sun, 15 Nov 2026 12:21:51 -0500 Subject: [PATCH 2/3] Continue navigation tests without stale AppTest widgets --- tests/test_learning_radar_page.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/tests/test_learning_radar_page.py b/tests/test_learning_radar_page.py index 79c1e74..878d017 100644 --- a/tests/test_learning_radar_page.py +++ b/tests/test_learning_radar_page.py @@ -254,17 +254,28 @@ def test_radar_uses_the_picked_topic_for_practice_without_changing_scope(monkeyp assert app.title[0].value == "Practice" assert "Price Elasticity of Demand" in [heading.value for heading in app.subheader] assert not any(radio.label == "Practice mode" for radio in app.radio) - app.button(key=f"practice_start_{ECON_ID}").click().run() - - assert not app.exception - session = app.session_state[f"active_practice_{ECON_ID}"] + focus_key = f"learning_radar_focus_{ECON_ID}" + assert app.session_state[focus_key] == "elasticity" + + # AppTest retains the previous page's pill node after a switch, even after + # Streamlit removes its widget value. Continue with the real navigation and + # the carried state in a fresh runner, without the obsolete widget nodes. + practice = signed_in_app(ROOT / "app.py").run() + for key in (scope_key, "current_course", focus_key, f"practice_entry_{ECON_ID}"): + if key in app.session_state: + practice.session_state[key] = app.session_state[key] + practice.switch_page("pages/2_Practice_Center.py").run() + practice.button(key=f"practice_start_{ECON_ID}").click().run() + + assert not practice.exception + session = practice.session_state[f"active_practice_{ECON_ID}"] assert session["session"].mode == "topic" assert {q.topic_id for q in session["questions"]} == {"elasticity"} - assert (app.session_state[scope_key] if scope_key in app.session_state else None) == exam_scope + assert (practice.session_state[scope_key] if scope_key in practice.session_state else None) == exam_scope - app.switch_page("pages/7_Learning_Radar.py").run() - assert not app.exception - assert app.button_group(key=f"learning_radar_topic_{ECON_ID}").value == "elasticity" + practice.switch_page("pages/7_Learning_Radar.py").run() + assert not practice.exception + assert practice.button_group(key=f"learning_radar_topic_{ECON_ID}").value == "elasticity" def test_topic_without_questions_stays_on_radar_with_explanation(monkeypatch): From f76b9e62d70ae0d2847af845bb3aa6f7256fb09f Mon Sep 17 00:00:00 2001 From: Jiale Li Date: Sun, 15 Nov 2026 12:28:10 -0500 Subject: [PATCH 3/3] Keep focused practice instructions consistent with its controls --- pages/2_Practice_Center.py | 7 ++++--- tests/test_learning_radar_page.py | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/pages/2_Practice_Center.py b/pages/2_Practice_Center.py index 03adc35..766e81c 100644 --- a/pages/2_Practice_Center.py +++ b/pages/2_Practice_Center.py @@ -296,9 +296,10 @@ def follow_question(active, question_id): # ---- Screens ------------------------------------------------------------------------ -def setup_heading(): +def setup_heading(*, focused=False): st.title(tr("Practice")) - st.caption(tr("Choose a mode, then focus on one question at a time.")) + if not focused: + st.caption(tr("Choose a mode, then focus on one question at a time.")) def choose_topic(course_id, confirmed_topic_ids, topic_names): @@ -337,7 +338,7 @@ def render_setup_screen( if st.session_state[f"practice_topic_drawn_{cid}"]: st.session_state[f"practice_topic_{cid}"] = choice["topic_id"] - setup_heading() + setup_heading(focused=focused_topic is not None) if pending_entry is not None and not focused_topic: target = pending_entry.get("topic_id") st.info( diff --git a/tests/test_learning_radar_page.py b/tests/test_learning_radar_page.py index 878d017..b93dc25 100644 --- a/tests/test_learning_radar_page.py +++ b/tests/test_learning_radar_page.py @@ -254,6 +254,7 @@ def test_radar_uses_the_picked_topic_for_practice_without_changing_scope(monkeyp assert app.title[0].value == "Practice" assert "Price Elasticity of Demand" in [heading.value for heading in app.subheader] assert not any(radio.label == "Practice mode" for radio in app.radio) + assert not any(caption.startswith("Choose a mode") for caption in _captions(app)) focus_key = f"learning_radar_focus_{ECON_ID}" assert app.session_state[focus_key] == "elasticity"