From 7b72eed4be2cf49ef845fad9a0a1c1b643ce8f6f Mon Sep 17 00:00:00 2001 From: maoji-y <255648417+maoji-y@users.noreply.github.com> Date: Fri, 4 Dec 2026 16:29:21 +0100 Subject: [PATCH] fix(tui): confirm before resetting the current exercise --- Readme.md | 4 +- docs-site/interface.md | 4 +- pythonlings/core/reset.py | 35 +++++++- pythonlings/pythonlings.tcss | 22 +++++ pythonlings/screens/reset.py | 39 +++++++++ pythonlings/screens/track.py | 51 +++++++++-- tests/tui/test_app_pilot.py | 162 +++++++++++++++++++++++++++++++++++ tests/unit/test_reset.py | 18 ++++ 8 files changed, 320 insertions(+), 15 deletions(-) create mode 100644 pythonlings/screens/reset.py diff --git a/Readme.md b/Readme.md index 8c81640..89f148e 100644 --- a/Readme.md +++ b/Readme.md @@ -147,12 +147,12 @@ path. | Key | Action | |---|---| | `F1` | Toggle hint | -| `F2` | Reset the current exercise | +| `F2` | Ask to reset the current exercise (`Y` resets, `N` or `Esc` cancels) | | `F3` | Toggle the exercise list | | `F4` | Return to the topic picker | | `F5` | Show the local Python reference | | `O` | Open official docs from the reference window | -| `Esc` | Close docs, or quit from main screens | +| `Esc` | Close docs, cancel reset, or quit from main screens | | `Ctrl+Q` | Quit | ![Local docs reference](https://raw.githubusercontent.com/abhiksark/pythonlings/v0.4.4/docs/assets/screenshots/docs-reference.png) diff --git a/docs-site/interface.md b/docs-site/interface.md index aabb0fb..5c8350c 100644 --- a/docs-site/interface.md +++ b/docs-site/interface.md @@ -26,10 +26,10 @@ exercise. Press `O` from that window to open the official Python docs page. | Key | Action | |---|---| | `F1` | Toggle hint | -| `F2` | Reset the current exercise | +| `F2` | Ask to reset the current exercise (`Y` resets, `N` or `Esc` cancels) | | `F3` | Toggle the exercise list | | `F4` | Return to the topic picker | | `F5` | Show the local Python reference | | `O` | Open official docs from the reference window | -| `Esc` | Close docs, or quit from main screens | +| `Esc` | Close docs, cancel reset, or quit from main screens | | `Ctrl+Q` | Quit | diff --git a/pythonlings/core/reset.py b/pythonlings/core/reset.py index 6012c3c..e1bdc95 100644 --- a/pythonlings/core/reset.py +++ b/pythonlings/core/reset.py @@ -3,6 +3,7 @@ from __future__ import annotations import shutil +import tempfile from pathlib import Path from pythonlings.core.exercise import Exercise @@ -41,9 +42,37 @@ def snapshot(root: Path, exercise: Exercise) -> None: def restore(root: Path, exercise: Exercise) -> None: """Overwrite the exercise file with its pristine original.""" snap = _original_path(root, exercise) - if not snap.exists(): + try: + contents = snap.read_bytes() + except FileNotFoundError as exc: raise ResetError( f"no snapshot for {exercise.name!r}. " "Run 'pythonlings update' first." - ) - shutil.copy2(snap, exercise.path) + ) from exc + except OSError as exc: + raise ResetError( + f"could not read the snapshot for {exercise.name!r}: {exc}" + ) from exc + try: + contents.decode("utf-8") + except UnicodeDecodeError as exc: + raise ResetError( + f"snapshot for {exercise.name!r} is not valid UTF-8. " + "Check .pythonlings/originals before retrying." + ) from exc + + try: + # Stage the replacement next to the exercise so a failed copy leaves + # the learner's file intact. Follow an in-workspace exercise symlink + # as the previous copy did. + destination = exercise.path.resolve() + with tempfile.TemporaryDirectory(dir=destination.parent) as staging: + replacement = Path(staging) / destination.name + replacement.write_bytes(contents) + shutil.copystat(snap, replacement) + replacement.replace(destination) + except (OSError, RuntimeError) as exc: + raise ResetError( + f"could not restore {exercise.name!r}. " + f"Check that its file is writable: {exc}" + ) from exc diff --git a/pythonlings/pythonlings.tcss b/pythonlings/pythonlings.tcss index c431d7b..585531b 100644 --- a/pythonlings/pythonlings.tcss +++ b/pythonlings/pythonlings.tcss @@ -122,6 +122,28 @@ DocsScreen { color: $text; } +ResetConfirmScreen { + align: center middle; +} + +#reset-window { + width: 90%; + max-width: 60; + height: auto; + padding: 1 2; + border: heavy $primary; + background: $surface; + color: $text; +} + +#reset-message { + margin: 1 0; +} + +#reset-keys { + color: $text-muted; +} + WelcomeScreen { align: center middle; } diff --git a/pythonlings/screens/reset.py b/pythonlings/screens/reset.py new file mode 100644 index 0000000..9dfebbf --- /dev/null +++ b/pythonlings/screens/reset.py @@ -0,0 +1,39 @@ +# pythonlings/screens/reset.py +from __future__ import annotations + +from textual.app import ComposeResult +from textual.binding import Binding +from textual.containers import Vertical +from textual.screen import ModalScreen +from textual.widgets import Static + + +class ResetConfirmScreen(ModalScreen[bool]): + """Ask before overwriting the current exercise with its snapshot.""" + + BINDINGS = [ + Binding("y", "confirm", "Reset"), + Binding("n,escape", "cancel", "Cancel", priority=True), + ] + + def __init__(self, exercise_name: str) -> None: + super().__init__() + self.exercise_name = exercise_name + + def compose(self) -> ComposeResult: + yield Vertical( + Static("[bold]Reset exercise?[/bold]"), + Static( + f"Replace edits to {self.exercise_name} with the original?", + markup=False, + id="reset-message", + ), + Static("Y Reset N / Esc Cancel", id="reset-keys"), + id="reset-window", + ) + + def action_confirm(self) -> None: + self.dismiss(True) + + def action_cancel(self) -> None: + self.dismiss(False) diff --git a/pythonlings/screens/track.py b/pythonlings/screens/track.py index f251d0a..1914dc2 100644 --- a/pythonlings/screens/track.py +++ b/pythonlings/screens/track.py @@ -1,6 +1,7 @@ # pythonlings/screens/track.py from __future__ import annotations +from rich.markup import escape from textual import events from textual.app import ComposeResult from textual.binding import Binding @@ -10,9 +11,11 @@ from textual.widgets import Footer, Header, TextArea from pythonlings.core.exercise import Exercise, RunResult +from pythonlings.core.reset import ResetError, restore from pythonlings.core.runner import run as run_exercise from pythonlings.core.state import completed_count, next_pending from pythonlings.core.state import save as save_state +from pythonlings.screens.reset import ResetConfirmScreen from pythonlings.widgets.editor_pane import EditorPane from pythonlings.widgets.exercise_tree import ExerciseTree from pythonlings.widgets.output_panel import OutputPanel @@ -87,6 +90,10 @@ def __init__(self, topic: str, start_exercise: str | None = None) -> None: self._persisted_text = "" self._run_id = 0 self._failure_counts: dict[str, int] = {} + self._confirming_reset = False + self._deferred_result: tuple[Exercise, RunResult, str, int] | None = ( + None + ) self.current: str | None = None def compose(self) -> ComposeResult: @@ -183,7 +190,9 @@ def on_text_area_changed(self, event: TextArea.Changed) -> None: if self._save_timer is not None: self._save_timer.stop() self._save_timer = self.set_timer( - _DEBOUNCE_SECONDS, self._flush_and_run + _DEBOUNCE_SECONDS, + self._flush_and_run, + pause=self._confirming_reset, ) def _flush_and_run(self) -> None: @@ -235,6 +244,9 @@ def _apply_result( or self.query_one(EditorPane).text != checked_text ): return + if self._confirming_reset: + self._deferred_result = (exercise, result, checked_text, run_id) + return if result.exit_code != 0 or result.timed_out: self._failure_counts[exercise.name] = ( self._failure_counts.get(exercise.name, 0) + 1 @@ -300,6 +312,8 @@ def _stop_advance_timer(self) -> None: def _tick_advance(self) -> None: """Decrement the countdown each second, firing the advance at zero.""" + if self._confirming_reset: + return self._advance_remaining -= 1 exercise, checked_text = self._advance_exercise, self._advance_text if self._advance_remaining <= 0: @@ -337,16 +351,37 @@ def action_toggle_hint(self) -> None: ) def action_reset(self) -> None: - from pythonlings.core.reset import restore - if self.current is None: return + # Keep queued edits and checks from changing the exercise mid-prompt. + self._confirming_reset = True if self._save_timer is not None: - self._save_timer.stop() - self._save_timer = None - restore(self.app.root, self._exercise(self.current)) - self._load_current() - self._run_current() + self._save_timer.pause() + self.app.push_screen( + ResetConfirmScreen(self.current), self._finish_reset + ) + + def _finish_reset(self, confirmed: bool | None) -> None: + self._confirming_reset = False + deferred, self._deferred_result = self._deferred_result, None + if confirmed and self.current is not None: + try: + restore(self.app.root, self._exercise(self.current)) + except ResetError as exc: + self.notify( + escape(str(exc)), + title="Reset failed", + severity="error", + timeout=8, + ) + else: + self._load_current() + self._run_current() + return + if self._save_timer is not None: + self._save_timer.resume() + if deferred is not None: + self._apply_result(*deferred) def action_toggle_list(self) -> None: tree = self.query_one(ExerciseTree) diff --git a/tests/tui/test_app_pilot.py b/tests/tui/test_app_pilot.py index 82deaa5..344415e 100644 --- a/tests/tui/test_app_pilot.py +++ b/tests/tui/test_app_pilot.py @@ -1,4 +1,6 @@ # tests/tui/test_app_pilot.py +from __future__ import annotations + import asyncio import shutil import threading @@ -11,6 +13,7 @@ from pythonlings.app import PythonlingsApp from pythonlings.core.exercise import RunResult +from pythonlings.core.reset import snapshot from pythonlings.core.state import State from pythonlings.core.state import save as save_state from pythonlings.screens import track as track_module @@ -222,6 +225,165 @@ async def test_f4_returns_to_picker(tmp_path: Path) -> None: assert isinstance(app.screen, TopicPickerScreen) +@pytest.mark.asyncio +@pytest.mark.parametrize("key", ["y", "n", "escape"]) +async def test_reset_waits_for_confirmation(tmp_path: Path, key: str) -> None: + work = _work_copy(tmp_path) + app = PythonlingsApp(root=work) + exercise = app.manifest.by_name("a1") + pristine = exercise.path.read_text(encoding="utf-8") + snapshot(work, exercise) + modified = "# I AM NOT DONE\nx = 2\n" + exercise.path.write_text(modified, encoding="utf-8") + + async with app.run_test(size=(40, 15)) as pilot: + await _settle(pilot) + track = app.screen + state_path = work / ".pythonlings" / "state.json" + state_before = state_path.read_bytes() + + await pilot.press("f2", "f2", "enter", "x") + assert app.screen is not track + assert exercise.path.read_text(encoding="utf-8") == modified + assert state_path.read_bytes() == state_before + + await pilot.press(key) + await _settle(pilot) + assert app.screen is track + assert app.focused is track.query_one("#code", TextArea) + expected = pristine if key == "y" else modified + assert app.focused.text == expected + assert exercise.path.read_text(encoding="utf-8") == expected + assert state_path.read_bytes() == state_before + assert app.return_code is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("key", ["y", "n"]) +async def test_reset_prompt_holds_a_queued_editor_save( + tmp_path: Path, key: str +) -> None: + app = PythonlingsApp(root=_work_copy(tmp_path)) + exercise = app.manifest.by_name("a1") + original = exercise.path.read_text(encoding="utf-8") + edited = "# I AM NOT DONE\nx = 2\n" + snapshot(app.root, exercise) + + async with app.run_test() as pilot: + await _settle(pilot) + track = app.screen + editor = track.query_one("#code", TextArea) + editor.text = edited + track.action_reset() + await pilot.pause(0.8) + assert app.screen is not track + assert exercise.path.read_text(encoding="utf-8") == original + + await pilot.press(key) + await pilot.pause(0.8) + assert app.screen is track + expected = original if key == "y" else edited + assert exercise.path.read_text(encoding="utf-8") == expected + assert editor.text == expected + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("broken_snapshot", "message"), + [(None, "no snapshot"), (b"\xff", "not valid UTF-8")], +) +async def test_reset_failure_preserves_exercise( + tmp_path: Path, broken_snapshot: bytes | None, message: str +) -> None: + work = _work_copy(tmp_path) + app = PythonlingsApp(root=work) + exercise = app.manifest.by_name("a1") + original = exercise.path.read_bytes() + if broken_snapshot is not None: + snapshot(work, exercise) + (work / ".pythonlings" / "originals" / "alpha" / "a1.py").write_bytes( + broken_snapshot + ) + + async with app.run_test(notifications=True) as pilot: + await _settle(pilot) + track = app.screen + await pilot.press("f2", "y") + await pilot.pause() + assert app.screen is track + assert exercise.path.read_bytes() == original + assert message in str(track.query_one("Toast.-error", Static).render()) + assert app.return_code is None + + +@pytest.mark.asyncio +async def test_reset_prompt_holds_an_in_flight_completion( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + started, release = threading.Event(), threading.Event() + + def delayed_run(exercise): + if exercise.name == "a1": + started.set() + assert release.wait(timeout=5) + return RunResult(True, 0, "ok", "", 0.1, False) + return RunResult(False, 1, "", "", 0.1, False) + + app = PythonlingsApp(root=_work_copy(tmp_path)) + async with app.run_test() as pilot: + await _settle(pilot) + track = app.screen + monkeypatch.setattr(track_module, "run_exercise", delayed_run) + track.query_one("#code", TextArea).text = "x = 1\n" + track._flush_and_run() + try: + assert await asyncio.to_thread(started.wait, 5) + await pilot.press("f2") + finally: + release.set() + await _settle(pilot) + assert app.screen is not track + assert track.current == "a1" + assert "a1" not in app.state.completed + + await pilot.press("escape") + await _settle(pilot) + assert app.screen is track + assert track.current == "a2" + assert "a1" in app.state.completed + + +@pytest.mark.asyncio +async def test_reset_prompt_pauses_the_auto_advance_countdown( + tmp_path: Path, +) -> None: + app = PythonlingsApp(root=_work_copy(tmp_path)) + exercise = app.manifest.by_name("a1") + snapshot(app.root, exercise) + + async with app.run_test() as pilot: + await _settle(pilot) + track = app.screen + checked = "# I AM NOT DONE\nx = 1\n" + track.query_one("#code", TextArea).text = checked + track._flush_and_run() + await _settle(pilot) + await pilot.press("f2") + remaining = track._advance_remaining + assert remaining > 0 + for _ in range(remaining): + track._tick_advance() + assert track._advance_remaining == remaining + assert exercise.path.read_text(encoding="utf-8") == checked + + await pilot.press("y") + await _settle(pilot) + assert app.screen is track + assert track._advance_timer is None + assert track.current == "a1" + assert "a1" not in app.state.completed + + @pytest.mark.asyncio async def test_narrow_layout_keeps_navigation_discoverable_and_usable( tmp_path: Path, diff --git a/tests/unit/test_reset.py b/tests/unit/test_reset.py index 822e98a..6218975 100644 --- a/tests/unit/test_reset.py +++ b/tests/unit/test_reset.py @@ -54,6 +54,24 @@ def test_restore_raises_when_no_snapshot(tmp_path: Path) -> None: restore(tmp_path, ex) +def test_restore_preserves_edits_if_replacement_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + ex = _ex(tmp_path, "pristine\n") + snapshot(tmp_path, ex) + ex.path.write_text("learner edits\n", encoding="utf-8") + + def deny_replace(self: Path, target: Path) -> None: + raise PermissionError("exercise file is locked") + + monkeypatch.setattr(Path, "replace", deny_replace) + with pytest.raises(ResetError, match="exercise file is locked"): + restore(tmp_path, ex) + + assert ex.path.read_text(encoding="utf-8") == "learner edits\n" + assert set(tmp_path.iterdir()) == {ex.path, tmp_path / ".pythonlings"} + + def test_snapshot_keys_on_exercise_name_not_filename(tmp_path: Path) -> None: # Two exercises with the same filename in different topic subdirs must # snapshot to distinct files (regression: previously keyed on