From fb1ef210bfa2a552a3859573b726ce85d962fb94 Mon Sep 17 00:00:00 2001 From: Aaron Ruan Date: Fri, 5 Jun 2026 15:58:51 +0800 Subject: [PATCH] update --- README.md | 5 +- src/letscode/agent.py | 41 +++++++-- src/letscode/main.py | 199 ++++++++++++++++++++++++++++++++++++++++-- tests/test_agent.py | 44 ++++++++++ tests/test_main.py | 32 ++++++- 5 files changed, 304 insertions(+), 17 deletions(-) create mode 100644 tests/test_agent.py diff --git a/README.md b/README.md index 52571a6..b115beb 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,14 @@ running generated Python judge suites against local solution files. ## Commands -- `/load_problem [question_id]` loads a LeetCode problem. +- `/problem [question_id]` loads a LeetCode problem. - `/new [PROMPT]` asks the agent to create a new local coding problem. - `/hint [HINT_PROMPT]` generates a progressive hint. +- `/solve` asks the agent to generate a full solution. - `/fix [testfire|full]` fixes the current solution against a judge suite. +- `/clear` clears the visible chat and agent chat history. - `/reset [question_id]` resets the solution file. +- `/random` loads a random LeetCode problem. ## Development diff --git a/src/letscode/agent.py b/src/letscode/agent.py index 9ed858b..7dedbc7 100644 --- a/src/letscode/agent.py +++ b/src/letscode/agent.py @@ -30,7 +30,8 @@ class LetsCodeAgent: You have access to tools for the currently loaded problem: - get_current_problem_context: read the active problem statement and metadata. - get_existing_hints: read hints that were already fetched or generated. - - get_current_solution_code: read the active Python solution file. + - read_user_solution: read the user's active Python solution file. + - get_current_solution_code: legacy alias for read_user_solution. - get_last_judge_output: read the latest judge/test output. - record_solution_attempt: increment the user's solution-attempt counter. @@ -88,6 +89,9 @@ class LetsCodeAgent: self.state.current_solution_code = solution_code self.state.last_judge_output = judge_output + def clear_chat_history(self) -> None: + self.state.messages.clear() + def chat(self, user_text: str) -> str: return self._invoke(user_text) @@ -102,13 +106,25 @@ class LetsCodeAgent: self.state.generated_hints.append(hint) return hint + def solve_problem(self) -> str: + response = self._invoke( + "Solve the active coding problem. Use the get_current_problem_context " + "and read_user_solution tools before answering so you can account for " + "any work the user already has. Return only Python code for the " + "complete solution file, with no Markdown fences or explanation." + ) + solved_code = extract_python_code(response) + self.state.current_solution_code = solved_code + return solved_code + def fix_solution(self, suite: str) -> str: self.state.attempts_count += 1 response = self._invoke( "Fix the current Python solution for the active coding problem. " - f"The failing suite is {suite}. Use the current-problem, current-solution, " - "and judge-output tools before answering. Return only corrected Python " - "code for the complete solution file, with no Markdown fences or explanation." + f"The failing suite is {suite}. Use the get_current_problem_context, " + "read_user_solution, and get_last_judge_output tools before answering. " + "Return only corrected Python code for the complete solution file, with " + "no Markdown fences or explanation." ) fixed_code = extract_python_code(response) self.state.current_solution_code = fixed_code @@ -168,6 +184,12 @@ def extract_python_code(content: str) -> str: def tool_factory(state: LetsCodeAgentState) -> list[BaseTool]: + def current_solution_text() -> str: + if not state.current_solution_code: + return "No solution code is currently loaded." + + return state.current_solution_code + @tool def get_current_problem_context() -> str: """Return the active coding problem statement and metadata.""" @@ -202,13 +224,15 @@ def tool_factory(state: LetsCodeAgentState) -> list[BaseTool]: return "\n\n".join(hints) + @tool + def read_user_solution() -> str: + """Return the user's active Python solution code.""" + return current_solution_text() + @tool def get_current_solution_code() -> str: """Return the active Python solution code.""" - if not state.current_solution_code: - return "No solution code is currently loaded." - - return state.current_solution_code + return current_solution_text() @tool def get_last_judge_output() -> str: @@ -227,6 +251,7 @@ def tool_factory(state: LetsCodeAgentState) -> list[BaseTool]: return [ get_current_problem_context, get_existing_hints, + read_user_solution, get_current_solution_code, get_last_judge_output, record_solution_attempt, diff --git a/src/letscode/main.py b/src/letscode/main.py index 87fa456..d504baa 100644 --- a/src/letscode/main.py +++ b/src/letscode/main.py @@ -281,6 +281,8 @@ class LetsCodeApp(App): NEW_COMMAND = "/new" HINT_COMMAND = "/hint" FIX_COMMAND = "/fix" + SOLVE_COMMAND = "/solve" + CLEAR_COMMAND = "/clear" RESET_COMMAND = "/reset" RANDOM_COMMAND = "/random" SLASH_COMMANDS = ( @@ -288,6 +290,8 @@ class LetsCodeApp(App): NEW_COMMAND, HINT_COMMAND, FIX_COMMAND, + SOLVE_COMMAND, + CLEAR_COMMAND, RESET_COMMAND, RANDOM_COMMAND, ) @@ -471,6 +475,9 @@ class LetsCodeApp(App): self.chat_entries: list[ChatEntry] = [] self.agent: LetsCodeAgent | None = None self.current_judge: GeneratedJudge | None = None + self.current_solution_code = "" + self.current_solution_path: Path | None = None + self.last_judge_output = "" if self.initial_new_prompt is not None: self.run_worker(self.create_problem(self.initial_new_prompt), exclusive=True) elif self.load_initial_problem: @@ -519,6 +526,12 @@ class LetsCodeApp(App): if command == self.FIX_COMMAND: return self._handle_fix_command(args) + if command == self.SOLVE_COMMAND: + return self._handle_solve_command(args) + + if command == self.CLEAR_COMMAND: + return self._handle_clear_command(args) + if command == self.RESET_COMMAND: return self._handle_reset_command(args) @@ -572,6 +585,22 @@ class LetsCodeApp(App): self.run_worker(self.fix_solution(suite), exclusive=True) return True + def _handle_solve_command(self, args: list[str]) -> bool: + if args: + self.notify("Usage: /solve", severity="warning") + return True + + self.run_worker(self.solve_problem(), exclusive=True) + return True + + def _handle_clear_command(self, args: list[str]) -> bool: + if args: + self.notify("Usage: /clear", severity="warning") + return True + + self.run_worker(self.clear_chat_history(), exclusive=True) + return True + def _handle_reset_command(self, args: list[str]) -> bool: question_id = parse_question_id(args[0]) if len(args) == 1 else None if len(args) > 1 or (args and question_id is None): @@ -662,6 +691,9 @@ class LetsCodeApp(App): self.agent = None self.current_judge = None self.chat_entries = [] + self.current_solution_code = "" + self.current_solution_path = None + self.last_judge_output = "" try: self.problem_store.save_last_question_id(question_id) @@ -782,6 +814,36 @@ class LetsCodeApp(App): ) ) + def _set_current_solution_context( + self, + solution_code: str, + path: Path | None = None, + *, + judge_output: str | None = None, + ) -> None: + self.current_solution_code = solution_code + if path is not None: + self.current_solution_path = path + if judge_output is not None: + self.last_judge_output = judge_output + + if self.agent is not None: + self.agent.set_solution_context( + solution_code=self.current_solution_code, + judge_output=self.last_judge_output, + ) + + async def refresh_solution_context(self) -> None: + if not self.current_problem_markdown: + return + + judge = await self._ensure_judge() + path = solution_path(judge) + ensure_solution_file(path, judge.initial_code_snippet) + solution_code = read_solution_file(path) + self._set_current_solution_context(solution_code, path) + await self._update_solution_preview(solution_code, path) + def get_agent(self) -> LetsCodeAgent: if self.agent is None: model_slug = os.getenv("LETSCODE_AGENT_MODEL", self.DEFAULT_AGENT_MODEL) @@ -795,6 +857,10 @@ class LetsCodeApp(App): fetched_hints=self.current_fetched_hints_markdown, generated_hints=self.current_generated_hints_markdown, ) + self.agent.set_solution_context( + solution_code=self.current_solution_code, + judge_output=self.last_judge_output, + ) return self.agent @@ -862,9 +928,99 @@ class LetsCodeApp(App): self.notify(f"Unable to run tests: {error}", severity="error") return + judge_report = format_judge_run(suite, run) + self._set_current_solution_context( + solution_code, + path, + judge_output=judge_report, + ) await judge_output.update_run(suite, run) await self._update_solution_preview(solution_code, path) + async def solve_problem(self) -> None: + if not self.current_problem_markdown: + self.notify("Problem is still loading.", severity="warning") + return + + judge_output = self.query_one(self.JUDGE_SELECTOR, JudgeOutput) + await judge_output.update_status("Preparing to solve...") + + try: + judge = await self._ensure_judge() + path = solution_path(judge) + ensure_solution_file(path, judge.initial_code_snippet) + solution_code = read_solution_file(path) + except Exception as error: + await judge_output.update_error(f"Unable to prepare solve: {error}") + self.notify(f"Unable to prepare solve: {error}", severity="error") + return + + self._set_current_solution_context(solution_code, path, judge_output="") + await judge_output.update_status("Generating solution...") + + try: + solved_code = await asyncio.to_thread(self.get_agent().solve_problem) + except Exception as error: + await judge_output.update_error(f"Unable to generate solution: {error}") + self.notify(f"Unable to generate solution: {error}", severity="error") + return + + if "class Solution" not in solved_code: + await judge_output.update_error( + "Generated solution did not include a Solution class." + ) + self.notify( + "Generated solution did not include a Solution class.", + severity="error", + ) + return + + try: + write_solution_file(path, solved_code) + except OSError as error: + await judge_output.update_error(f"Unable to write solution: {error}") + self.notify(f"Unable to write solution: {error}", severity="error") + return + + self._set_current_solution_context(solved_code, path, judge_output="") + await self._update_solution_preview(solved_code, path) + await judge_output.update_status( + f"Solution written to {path}. Running {DEFAULT_JUDGE_SUITE} tests..." + ) + + try: + run = await asyncio.to_thread( + run_solution_suite, + DEFAULT_JUDGE_SUITE, + solved_code, + judge, + ) + except Exception as error: + judge_report = format_judge_error(DEFAULT_JUDGE_SUITE, error) + self._set_current_solution_context( + solved_code, + path, + judge_output=judge_report, + ) + await judge_output.update_error( + "Solution was written, but tests errored:\n\n" + f"{type(error).__name__}: {error}" + ) + self.notify("Solution written, but tests errored.", severity="warning") + return + + judge_report = format_judge_run(DEFAULT_JUDGE_SUITE, run) + self._set_current_solution_context( + solved_code, + path, + judge_output=judge_report, + ) + await judge_output.update_run(DEFAULT_JUDGE_SUITE, run) + if run.passed: + self.notify("Solution generated.") + else: + self.notify("Solution written, but tests failed.", severity="warning") + async def fix_solution(self, suite: JudgeSuite) -> None: if not self.current_problem_markdown: self.notify("Problem is still loading.", severity="warning") @@ -899,8 +1055,9 @@ class LetsCodeApp(App): try: agent = self.get_agent() - agent.set_solution_context( - solution_code=solution_code, + self._set_current_solution_context( + solution_code, + path, judge_output=judge_report, ) fixed_code = await asyncio.to_thread(agent.fix_solution, suite) @@ -925,6 +1082,7 @@ class LetsCodeApp(App): self.notify(f"Unable to write fixed solution: {error}", severity="error") return + self._set_current_solution_context(fixed_code, path, judge_output="") await self._update_solution_preview(fixed_code, path) await judge_output.update_status( f"Fixed solution written to {path}. Re-running {suite} tests..." @@ -942,9 +1100,21 @@ class LetsCodeApp(App): "Fixed solution was written, but tests errored:\n\n" f"{type(error).__name__}: {error}" ) + judge_report = format_judge_error(suite, error) + self._set_current_solution_context( + fixed_code, + path, + judge_output=judge_report, + ) self.notify("Fix written, but tests errored.", severity="warning") return + judge_report = format_judge_run(suite, fixed_run) + self._set_current_solution_context( + fixed_code, + path, + judge_output=judge_report, + ) await judge_output.update_run(suite, fixed_run) if fixed_run.passed: self.notify("Solution fixed.") @@ -990,11 +1160,11 @@ class LetsCodeApp(App): if is_current_problem: await self._update_solution_preview(judge.initial_code_snippet, path) - if self.agent is not None: - self.agent.set_solution_context( - solution_code=judge.initial_code_snippet, - judge_output="", - ) + self._set_current_solution_context( + judge.initial_code_snippet, + path, + judge_output="", + ) await judge_output.update_status( f"Reset solution for problem {target_question_id} at {path}." @@ -1043,6 +1213,7 @@ class LetsCodeApp(App): self.notify(f"Unable to read edited code: {error}", severity="error") return + self._set_current_solution_context(solution_code, path, judge_output="") await self._update_solution_preview(solution_code, path) await judge_output.update_status( f"Loaded edited solution from {path}. Run Testfire or Full." @@ -1071,6 +1242,7 @@ class LetsCodeApp(App): self.notify(f"Unable to read solution: {error}", severity="error") return + self._set_current_solution_context(solution_code, path, judge_output="") await self._update_solution_preview(solution_code, path) await judge_output.update_status( "Judge ready. Use Edit to change the external solution file, " @@ -1104,6 +1276,11 @@ class LetsCodeApp(App): self.notify("Problem is still loading.", severity="warning") return + try: + await self.refresh_solution_context() + except Exception: + pass + self.chat_entries.append(ChatEntry("user", message)) pending_index = len(self.chat_entries) self.chat_entries.append(ChatEntry("agent", "Thinking...")) @@ -1146,6 +1323,14 @@ class LetsCodeApp(App): chat_container.scroll_end(animate=False) + async def clear_chat_history(self) -> None: + self.chat_entries = [] + if self.agent is not None: + self.agent.clear_chat_history() + + await self._render_chat_log() + self.notify("Chat history cleared.") + async def on_prompt_input_submitted(self, event: PromptInput.Submitted) -> None: """Handle user input.""" input_widget = self.query_one(self.INPUT_SELECTOR, PromptInput) diff --git a/tests/test_agent.py b/tests/test_agent.py new file mode 100644 index 0000000..afb2677 --- /dev/null +++ b/tests/test_agent.py @@ -0,0 +1,44 @@ +import unittest + +from langchain_core.messages import HumanMessage + +from letscode.agent import LetsCodeAgent, LetsCodeAgentState, tool_factory + + +class AgentToolFactoryTest(unittest.TestCase): + def test_read_user_solution_tool_returns_solution_context(self) -> None: + state = LetsCodeAgentState( + current_solution_code="class Solution:\n pass\n" + ) + tools = {tool.name: tool for tool in tool_factory(state)} + + self.assertIn("read_user_solution", tools) + self.assertEqual( + tools["read_user_solution"].invoke({}), + "class Solution:\n pass\n", + ) + + def test_current_solution_tool_remains_available(self) -> None: + state = LetsCodeAgentState( + current_solution_code="class Solution:\n pass\n" + ) + tools = {tool.name: tool for tool in tool_factory(state)} + + self.assertEqual( + tools["get_current_solution_code"].invoke({}), + "class Solution:\n pass\n", + ) + + +class AgentStateTest(unittest.TestCase): + def test_clear_chat_history_removes_messages(self) -> None: + state = LetsCodeAgentState(messages=[HumanMessage(content="hello")]) + agent = LetsCodeAgent.__new__(LetsCodeAgent) + agent.state = state + + agent.clear_chat_history() + self.assertEqual(state.messages, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_main.py b/tests/test_main.py index 80fd24f..78daa31 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -220,6 +220,36 @@ class SlashCommandTest(unittest.TestCase): self.assertTrue(app.handle_slash_command("/random")) self.assertEqual(len(workers), 1) + def test_solve_slash_command_starts_solve_worker(self) -> None: + app = LetsCodeApp() + workers: list[object] = [] + + def run_worker(work: object, *args: object, **kwargs: object) -> object: + workers.append(work) + if inspect.iscoroutine(work): + work.close() + return work + + app.run_worker = run_worker # type: ignore[method-assign] + + self.assertTrue(app.handle_slash_command("/solve")) + self.assertEqual(len(workers), 1) + + def test_clear_slash_command_starts_clear_worker(self) -> None: + app = LetsCodeApp() + workers: list[object] = [] + + def run_worker(work: object, *args: object, **kwargs: object) -> object: + workers.append(work) + if inspect.iscoroutine(work): + work.close() + return work + + app.run_worker = run_worker # type: ignore[method-assign] + + self.assertTrue(app.handle_slash_command("/clear")) + self.assertEqual(len(workers), 1) + def test_unknown_slash_command_is_consumed(self) -> None: app = LetsCodeApp() notifications: list[tuple[str, str | None]] = [] @@ -235,7 +265,7 @@ class SlashCommandTest(unittest.TestCase): [ ( "Unknown command: /typo. Available commands: " - "/problem, /new, /hint, /fix, /reset, /random", + "/problem, /new, /hint, /fix, /solve, /clear, /reset, /random", "warning", ) ], -- knotmirror 0.0.1