Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368import argparseimport asyncioimport osimport subprocessfrom collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Literal
from dotenv import load_dotenvfrom rich.syntax import Syntaxfrom textual.app import App, ComposeResultfrom textual.binding import Bindingfrom textual.containers import Horizontal, ScrollableContainer, Verticalfrom textual.message import Messagefrom textual.widgets import ( Button, Collapsible, Footer, Header, Markdown, Static, TabbedContent, TabPane, TextArea,)
from .ai_http import OpenAIHttpClientsfrom .agent import LetsCodeAgentfrom .judge import ( DEFAULT_JUDGE_SUITE, GeneratedJudge, JudgeRun, JudgeSuite, format_judge_error, format_judge_run, generate_judge, is_judge_suite, run_solution_suite,)from .leetcode import LeetCodeFetcherfrom .problem import ( ProblemMarkdown, generate_custom_problem_markdown, load_problem_markdown,)from .solution import ( editor_command, ensure_solution_file, read_solution_file, reset_solution_file, solution_path, write_solution_file,)from .storage import GeneratedHint, ProblemStore
ChatRole = Literal["user", "agent"]
@dataclass(frozen=True)class ChatEntry: role: ChatRole content: str
def parse_question_id(value: str) -> int | None: try: return int(value) except ValueError: return None
def parse_cli_question_id(value: str) -> int: question_id = parse_question_id(value) if question_id is None: raise argparse.ArgumentTypeError("must be an integer question id")
return question_id
def parse_cli_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(prog="letscode") parser.add_argument( "--reset", action="store_true", help="Reset saved state, cached problems, judges, and solutions, then quit.", ) parser.add_argument( "--problem", type=parse_cli_question_id, metavar="ID", help="Load the given problem on launch instead of the last session.", ) parser.add_argument( "--no-leetcode", action="store_true", help="Start without loading a LeetCode problem.", ) parser.add_argument( "--new", metavar="PROMPT", help="Generate a new AI-created problem from the given prompt on launch.", ) args = parser.parse_args(argv)
if args.problem is not None and args.no_leetcode: parser.error("--problem cannot be used with --no-leetcode")
if args.problem is not None and args.new is not None: parser.error("--problem cannot be used with --new")
return args
class ChatBubble(Horizontal): """A single chat message row."""
def __init__(self, entry: ChatEntry) -> None: super().__init__(classes=f"chat-row {entry.role}") self.entry = entry
def compose(self) -> ComposeResult: content = self.entry.content.strip() or "No content." yield Static( content, classes=f"chat-bubble {self.entry.role}", markup=False, )
class SolutionPreview(Vertical): """Native Textual solution preview for the Judge tab."""
def compose(self) -> ComposeResult: yield Static("No solution file loaded.", classes="solution-path", markup=False) yield self._code_widget("# Loading solution...")
async def update_solution( self, solution_code: str, path: Path | None = None, ) -> None: label = str(path) if path is not None else "No solution file loaded." preview = solution_code.strip() or "# No solution loaded."
await self.remove_children() await self.mount( Static(label, classes="solution-path", markup=False), self._code_widget(preview), )
@staticmethod def _code_widget(code: str) -> Static: return Static( Syntax( code, "python", word_wrap=True, ), classes="solution-code", )
class JudgeOutput(Vertical): """Native Textual judge status and result renderer."""
def compose(self) -> ComposeResult: yield Static("Judge", classes="judge-title", markup=False) yield Static("Loading problem...", classes="judge-message", markup=False)
async def update_status(self, message: str) -> None: await self._replace_content( Static(message, classes="judge-message", markup=False) )
async def update_error(self, message: str) -> None: await self._replace_content( Static(message, classes="judge-error", markup=False) )
async def update_run(self, suite: JudgeSuite, run: JudgeRun) -> None: summary = f"{suite.title()} tests: {'passed' if run.passed else 'failed'}" children: list[Static] = [ Static( summary, classes=f"judge-summary {'passed' if run.passed else 'failed'}", markup=False, ) ]
for result in run.results: state = "passed" if result.passed else "failed" children.append( Static( f"{result.suite}: {state}", classes=f"judge-result-title {state}", markup=False, ) ) if result.message: children.append( Static(result.message, classes="judge-message", markup=False) ) if result.error: children.append( Static( result.error.strip(), classes="judge-code judge-error-detail", markup=False, ) )
await self._replace_content(*children)
async def _replace_content(self, *children: Static) -> None: await self.remove_children() await self.mount(Static("Judge", classes="judge-title", markup=False)) await self.mount(*children)
class PromptInput(TextArea): """Multiline prompt input that submits on Enter."""
MIN_CONTENT_LINES = 1 MAX_CONTENT_LINES = 5 BORDER_HEIGHT = 2
BINDINGS = [ Binding("alt+enter", "new_line", show=False, priority=True), Binding("enter", "submit", show=False, priority=True), Binding("ctrl+c", "clear_input", show=False, priority=True), ]
class Submitted(Message): """Posted when the prompt should be submitted."""
def __init__(self, value: str) -> None: super().__init__() self.value = value
def action_new_line(self) -> None: self.insert("\n")
def action_submit(self) -> None: self.post_message(self.Submitted(self.text))
def action_clear_input(self) -> None: self.text = ""
def on_mount(self) -> None: self.resize_to_content()
def on_text_area_changed(self, event: TextArea.Changed) -> None: if event.text_area is self: self.resize_to_content()
def resize_to_content(self) -> None: content_lines = max(self.MIN_CONTENT_LINES, self.text.count("\n") + 1) visible_lines = min(content_lines, self.MAX_CONTENT_LINES) self.styles.height = visible_lines + self.BORDER_HEIGHT
class LetsCodeApp(App): DEFAULT_PROBLEM_ID = 1 DEFAULT_AGENT_MODEL = "openai:gpt-5.4-mini"
INPUT_SELECTOR = "#input" PROBLEM_SELECTOR = "#problem" HINTS_SELECTOR = "#hints" JUDGE_SELECTOR = "#judge-output" SOLUTION_PREVIEW_SELECTOR = "#solution-preview" CHAT_CONTAINER_SELECTOR = "#chat" CHAT_TAB_ID = "chat-tab"
TESTFIRE_BUTTON_ID = "testfire-button" FULL_TEST_BUTTON_ID = "full-test-button" EDIT_BUTTON_ID = "edit-button" REFRESH_JUDGE_BUTTON_ID = "refresh-judge-button"
LOAD_PROBLEM_COMMAND = "/problem" NEW_COMMAND = "/new" HINT_COMMAND = "/hint" FIX_COMMAND = "/fix" SOLVE_COMMAND = "/solve" CLEAR_COMMAND = "/clear" RESET_COMMAND = "/reset" RANDOM_COMMAND = "/random" SLASH_COMMANDS = ( LOAD_PROBLEM_COMMAND, NEW_COMMAND, HINT_COMMAND, FIX_COMMAND, SOLVE_COMMAND, CLEAR_COMMAND, RESET_COMMAND, RANDOM_COMMAND, )
CSS = """\ Screen { layout: vertical; background: transparent; }
TabbedContent { height: 1fr; margin: 1; background: transparent; }
TabPane { padding: 1; }
#problem, #hints, #judge-output, #solution-preview, #chat { height: auto; background: transparent; }
#solution-preview { margin-bottom: 1; }
.solution-path { height: auto; margin-bottom: 1; color: $text-muted; }
.solution-code, .judge-code { height: auto; padding: 1; background: $surface; border-left: $primary tall; }
.judge-title { height: auto; text-style: bold; margin-bottom: 1; }
.judge-message, .judge-error, .judge-summary, .judge-result-title { height: auto; margin-bottom: 1; }
.judge-summary.passed, .judge-result-title.passed { color: $success; }
.judge-summary.failed, .judge-result-title.failed, .judge-error { color: $error; }
.judge-result-title { text-style: bold; }
.chat-row { height: auto; width: 100%; margin-bottom: 1; }
.chat-bubble { height: auto; padding: 1; }
.chat-bubble.user { background: $primary 20%; border-left: $primary tall; }
.chat-bubble.agent { background: $surface; border-left: $foreground tall; }
.chat-empty { height: auto; color: $text-muted; }
#judge-buttons { height: auto; margin-bottom: 1; }
#judge-buttons Button { margin-right: 1; }
#input { min-height: 3; max-height: 7; margin: 1; padding: 1; } """
def __init__( self, initial_problem_id: int | None = None, *, initial_new_prompt: str | None = None, load_initial_problem: bool = True, ) -> None: super().__init__() self.initial_problem_id = initial_problem_id self.initial_new_prompt = initial_new_prompt self.load_initial_problem = load_initial_problem self.openai_http_clients = OpenAIHttpClients()
def compose(self) -> ComposeResult: yield Header() with TabbedContent(): with TabPane("Problem", id="problem-tab"): yield ScrollableContainer( Markdown("# Loading problem...", id="problem") ) with TabPane("Judge", id="judge-tab"): yield ScrollableContainer( Horizontal( Button("Edit", id=self.EDIT_BUTTON_ID), Button("Refresh", id=self.REFRESH_JUDGE_BUTTON_ID), Button("Testfire", id=self.TESTFIRE_BUTTON_ID), Button("Full", id=self.FULL_TEST_BUTTON_ID), id="judge-buttons", ), SolutionPreview(id="solution-preview"), JudgeOutput(id="judge-output"), id="judge", ) with TabPane("Hints", id="hints-tab"): yield ScrollableContainer( Markdown("# Loading problem..."), id="hints", ) with TabPane("Chat", id=self.CHAT_TAB_ID): yield ScrollableContainer( Static( "No messages yet. Type a question or request below.", classes="chat-empty", markup=False, ), id="chat", ) yield PromptInput( language="markdown", placeholder=( "Ask the agent or type a command. Enter submits, Alt+Enter adds " "a new line." ), id="input", compact=True, highlight_cursor_line=False, ) yield Footer()
def on_mount(self) -> None: self.query_one(self.INPUT_SELECTOR, PromptInput).focus() self.problem_store = ProblemStore() last_question_id = self.problem_store.load_last_question_id() self.current_problem_id = ( self.initial_problem_id if self.initial_problem_id is not None else last_question_id or self.DEFAULT_PROBLEM_ID ) self.current_problem_markdown = "" self.current_fetched_hints_markdown: list[str] = [] self.current_generated_hints_markdown: list[str] = [] self.generated_hints_count = 0 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: self.action_load_problem() else: self.run_worker(self.show_no_problem(), exclusive=True)
def action_load_problem(self) -> None: self.run_worker(self.load_problem(self.current_problem_id), exclusive=True)
async def show_no_problem(self) -> None: await self.query_one(self.PROBLEM_SELECTOR, Markdown).update( "# No Problem Loaded\n\nUse `/problem [question_id]`, `/random`, " "or `/new [prompt]` to start." ) await self._update_solution_preview("") await self.query_one(self.JUDGE_SELECTOR, JudgeOutput).update_status( "No problem loaded." ) await self._render_hints([], []) await self._render_chat_log()
def action_quit(self) -> None: self.workers.cancel_all() self.openai_http_clients.close() self.exit()
def handle_slash_command(self, message: str) -> bool: parts = message.split(maxsplit=1) if not parts: return False
command = parts[0] arg_text = parts[1] if len(parts) == 2 else "" args = arg_text.split()
if command == self.LOAD_PROBLEM_COMMAND: return self._handle_load_problem_command(args)
if command == self.NEW_COMMAND: return self._handle_new_command(arg_text.strip())
if command == self.HINT_COMMAND: return self._handle_hint_command(args)
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)
if command == self.RANDOM_COMMAND: return self._handle_random_command(args)
available_commands = ", ".join(self.SLASH_COMMANDS) self.notify( f"Unknown command: {command}. Available commands: {available_commands}", severity="warning", ) return True
def _handle_load_problem_command(self, args: list[str]) -> bool: if not args: self.notify(f"Loading problem {self.current_problem_id}...") self.action_load_problem() return True
question_id = parse_question_id(args[0]) if len(args) == 1 else None if question_id is not None: self.notify(f"Loading problem {question_id}...") self.run_worker(self.load_problem(question_id), exclusive=True) return True
self.notify("Usage: /problem [question_id]", severity="warning") return True
def _handle_new_command(self, prompt: str) -> bool: if not prompt: self.notify("Usage: /new [PROMPT]", severity="warning") return True
self.run_worker(self.create_problem(prompt), exclusive=True) return True
def _handle_hint_command(self, args: list[str]) -> bool: if len(args) > 1: self.notify("Usage: /hint [HINT_PROMPT]", severity="warning") return True
self.run_worker(self.generate_hint(args[0] if args else None), exclusive=True) return True
def _handle_fix_command(self, args: list[str]) -> bool: suite = args[0] if args else DEFAULT_JUDGE_SUITE if len(args) > 1 or not is_judge_suite(suite): self.notify("Usage: /fix [testfire|full]", severity="warning") return True
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): self.notify("Usage: /reset [question_id]", severity="warning") return True
self.run_worker(self.reset_solution(question_id), exclusive=True) return True
def _handle_random_command(self, args: list[str]) -> bool: if args: self.notify("Usage: /random", severity="warning") return True
self.run_worker(self.load_random_problem(), exclusive=True) return True
async def load_problem(self, question_id: int) -> None: problem_markdown = await load_problem_markdown( question_id, store=self.problem_store, ) await self.activate_problem(question_id, problem_markdown)
async def load_random_problem(self) -> None: self.notify("Loading a random problem...") question_id = await LeetCodeFetcher().get_random_problem_id() if question_id is None: self.notify("Unable to find a random problem.", severity="error") return
await self.load_problem(question_id)
async def create_problem(self, prompt: str) -> None: self.notify("Generating new problem...") await self.query_one(self.PROBLEM_SELECTOR, Markdown).update( "# New Problem\n\nGenerating a custom problem from your prompt..." ) await self._update_solution_preview("") await self.query_one(self.JUDGE_SELECTOR, JudgeOutput).update_status( "Waiting for the new problem..." )
try: model_slug = os.getenv("LETSCODE_AGENT_MODEL", self.DEFAULT_AGENT_MODEL) problem = await asyncio.to_thread( generate_custom_problem_markdown, prompt, model_slug, http_clients=self.openai_http_clients, ) except Exception as error: await self.query_one(self.JUDGE_SELECTOR, JudgeOutput).update_error( f"Unable to generate new problem: {error}" ) self.notify(f"Unable to generate new problem: {error}", severity="error") return
question_id = self.problem_store.next_custom_question_id() try: stored_problem = self.problem_store.save_generated_problem( question_id, problem, ) except OSError as error: self.notify(f"Unable to persist new problem: {error}", severity="warning") problem_markdown = ProblemMarkdown( problem=problem, fetched_hints=[], generated_hints=[], ) else: problem_markdown = ProblemMarkdown( problem=stored_problem.problem, fetched_hints=stored_problem.fetched_hints, generated_hints=stored_problem.generated_hints, )
await self.activate_problem(question_id, problem_markdown) self.notify(f"Generated custom problem {question_id}.")
async def activate_problem( self, question_id: int, problem_markdown: ProblemMarkdown, ) -> None: self.current_problem_id = question_id 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) except OSError as error: self.notify( f"Unable to persist current problem: {error}", severity="warning", )
self.current_problem_markdown = problem_markdown.problem self.current_fetched_hints_markdown = problem_markdown.fetched_hints self.current_generated_hints_markdown = [ hint.hint for hint in problem_markdown.generated_hints ] self.generated_hints_count = len(problem_markdown.generated_hints)
await self.query_one(self.PROBLEM_SELECTOR, Markdown).update( problem_markdown.problem ) await self._update_solution_preview("") await self.query_one(self.JUDGE_SELECTOR, JudgeOutput).update_status( "Generating judge from the current problem..." ) await self._render_hints( problem_markdown.fetched_hints, problem_markdown.generated_hints, ) await self._render_chat_log() await self.prepare_judge()
async def _render_hints( self, fetched_hints_markdown: list[str], generated_hints: list[GeneratedHint], ) -> None: hints_container = self.query_one(self.HINTS_SELECTOR, ScrollableContainer) await hints_container.remove_children()
if not fetched_hints_markdown and not generated_hints: await hints_container.mount(Markdown("No hints available.")) return
for index, hint_markdown in enumerate(fetched_hints_markdown, start=1): await self._mount_hint( hints_container, hint_markdown, title=f"Hint {index}", collapsed=True, )
for index, generated_hint in enumerate(generated_hints, start=1): await self._mount_hint( hints_container, generated_hint.hint, title=f"AI Hint {index}", collapsed=True, )
async def generate_hint(self, prompt: str | None) -> None: if not self.current_problem_markdown: self.notify("Problem is still loading.", severity="warning") return
self.notify("Generating hint...")
try: hint_markdown = await asyncio.to_thread( self.get_agent().generate_hint, prompt, ) except Exception as error: self.notify(f"Unable to generate hint: {error}", severity="error") return
total_hints_count = ( len(self.current_fetched_hints_markdown) + self.generated_hints_count ) self.generated_hints_count += 1 self.current_generated_hints_markdown.append(hint_markdown)
try: self.problem_store.add_generated_hint( self.current_problem_id, self.current_problem_markdown, self.current_fetched_hints_markdown, hint_markdown, prompt, ) except OSError as error: self.notify(f"Unable to persist hint: {error}", severity="warning")
hints_container = self.query_one(self.HINTS_SELECTOR, ScrollableContainer)
if total_hints_count == 0: await hints_container.remove_children()
await self._mount_hint( hints_container, hint_markdown, title=f"AI Hint {self.generated_hints_count}", collapsed=False, ) self.notify("Hint generated.")
async def _mount_hint( self, container: ScrollableContainer, hint_markdown: str, *, title: str, collapsed: bool, ) -> None: await container.mount( Collapsible( Markdown(hint_markdown), title=title, collapsed=collapsed, ) )
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) self.agent = LetsCodeAgent( model_slug, http_clients=self.openai_http_clients, ) self.agent.set_problem_context( question_id=self.current_problem_id, problem_markdown=self.current_problem_markdown, 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
async def on_button_pressed(self, event: Button.Pressed) -> None: if event.button.id == self.EDIT_BUTTON_ID: event.stop() self.run_worker(self.open_solution_editor(), exclusive=True) return
if event.button.id == self.REFRESH_JUDGE_BUTTON_ID: event.stop() self.run_worker(self.refresh_judge(), exclusive=True) return
if event.button.id == self.TESTFIRE_BUTTON_ID: event.stop() self.run_worker(self.run_judge("testfire"), exclusive=True) return
if event.button.id == self.FULL_TEST_BUTTON_ID: event.stop() self.run_worker(self.run_judge("full"), exclusive=True) return
async def refresh_judge(self) -> None: if not self.current_problem_markdown: self.notify("Problem is still loading.", severity="warning") return
await self.query_one(self.JUDGE_SELECTOR, JudgeOutput).update_status( "Refreshing judge..." ) await self.prepare_judge()
async def run_judge(self, suite: JudgeSuite) -> 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(f"Generating {suite} judge...")
try: judge = await self._ensure_judge() except Exception as error: await judge_output.update_error(f"Unable to generate judge: {error}") self.notify(f"Unable to generate judge: {error}", severity="error") return
path = solution_path(judge) ensure_solution_file(path, judge.initial_code_snippet)
await judge_output.update_status(f"Running {suite} tests...")
try: solution_code = read_solution_file(path) run = await asyncio.to_thread( run_solution_suite, suite, solution_code, judge, ) except Exception as error: await judge_output.update_error(f"Unable to run tests: {error}") 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") return
judge_output = self.query_one(self.JUDGE_SELECTOR, JudgeOutput) await judge_output.update_status(f"Preparing to fix with {suite} tests...")
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 fix: {error}") self.notify(f"Unable to prepare fix: {error}", severity="error") return
await judge_output.update_status(f"Running {suite} tests before fixing...") try: run = await asyncio.to_thread( run_solution_suite, suite, solution_code, judge, ) judge_report = format_judge_run(suite, run) except Exception as error: judge_report = format_judge_error(suite, error)
await judge_output.update_status("Generating fix...")
try: agent = self.get_agent() self._set_current_solution_context( solution_code, path, judge_output=judge_report, ) fixed_code = await asyncio.to_thread(agent.fix_solution, suite) except Exception as error: await judge_output.update_error(f"Unable to generate fix: {error}") self.notify(f"Unable to generate fix: {error}", severity="error") return
if "class Solution" not in fixed_code: await judge_output.update_error( "Generated fix did not include a Solution class." ) self.notify( "Generated fix did not include a Solution class.", severity="error" ) return
try: write_solution_file(path, fixed_code) except OSError as error: await judge_output.update_error(f"Unable to write fixed solution: {error}") 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..." )
try: fixed_run = await asyncio.to_thread( run_solution_suite, suite, fixed_code, judge, ) except Exception as error: await judge_output.update_error( "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.") else: self.notify("Fix written, but tests still fail.", severity="warning")
async def reset_solution(self, question_id: int | None = None) -> None: if question_id is None and not self.current_problem_markdown: self.notify("Problem is still loading.", severity="warning") return
target_question_id = ( self.current_problem_id if question_id is None else question_id ) is_current_problem = target_question_id == self.current_problem_id and bool( self.current_problem_markdown )
judge_output = self.query_one(self.JUDGE_SELECTOR, JudgeOutput) await judge_output.update_status( f"Resetting solution for problem {target_question_id}..." )
try: if is_current_problem: judge = await self._ensure_judge() else: problem_markdown = await load_problem_markdown(target_question_id) model_slug = os.getenv("LETSCODE_AGENT_MODEL", self.DEFAULT_AGENT_MODEL) judge = await asyncio.to_thread( generate_judge, problem_markdown.problem, model_slug, http_clients=self.openai_http_clients, )
path = solution_path(judge) reset_solution_file(path, judge.initial_code_snippet) except Exception as error: await judge_output.update_error(f"Unable to reset solution: {error}") self.notify(f"Unable to reset solution: {error}", severity="error") return
if is_current_problem: await self._update_solution_preview(judge.initial_code_snippet, path) 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}." ) self.notify(f"Reset solution for problem {target_question_id}.")
async def open_solution_editor(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 editor...")
try: judge = await self._ensure_judge() path = solution_path(judge) ensure_solution_file(path, judge.initial_code_snippet) editor = editor_command(path) except Exception as error: await judge_output.update_error(f"Unable to prepare editor: {error}") self.notify(f"Unable to prepare editor: {error}", severity="error") return
try: with self.suspend(): await asyncio.to_thread(subprocess.run, editor, check=True) except FileNotFoundError: await judge_output.update_error(f"Editor command not found: {editor[0]}") self.notify(f"Editor command not found: {editor[0]}", severity="error") return except subprocess.CalledProcessError as error: await judge_output.update_error( f"Editor exited with status {error.returncode}." ) self.notify( f"Editor exited with status {error.returncode}.", severity="error", ) return
try: solution_code = read_solution_file(path) except OSError as error: await judge_output.update_error(f"Unable to read edited code: {error}") 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." )
async def prepare_judge(self) -> None: if not self.current_problem_markdown: return
judge_output = self.query_one(self.JUDGE_SELECTOR, JudgeOutput)
try: judge = await self._ensure_judge() except Exception as error: await judge_output.update_error(f"Unable to generate judge: {error}") self.notify(f"Unable to generate judge: {error}", severity="error") return
path = solution_path(judge) ensure_solution_file(path, judge.initial_code_snippet)
try: solution_code = read_solution_file(path) except OSError as error: await judge_output.update_error(f"Unable to read solution: {error}") 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, " "then run Testfire or Full." )
async def _ensure_judge(self) -> GeneratedJudge: if self.current_judge is None: model_slug = os.getenv("LETSCODE_AGENT_MODEL", self.DEFAULT_AGENT_MODEL) self.current_judge = await asyncio.to_thread( generate_judge, self.current_problem_markdown, model_slug, http_clients=self.openai_http_clients, )
return self.current_judge
async def _update_solution_preview( self, solution_code: str, path: Path | None = None, ) -> None: await self.query_one( self.SOLUTION_PREVIEW_SELECTOR, SolutionPreview, ).update_solution(solution_code, path)
async def chat_with_agent(self, message: str) -> None: if not self.current_problem_markdown: 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...")) self.query_one(TabbedContent).active = self.CHAT_TAB_ID await self._render_chat_log()
try: response = await asyncio.to_thread(self.get_agent().chat, message) except Exception as error: self.chat_entries[pending_index] = ChatEntry( "agent", f"Unable to get a response: {error}", ) await self._render_chat_log() self.notify(f"Unable to chat with agent: {error}", severity="error") return
self.chat_entries[pending_index] = ChatEntry("agent", response) await self._render_chat_log()
async def _render_chat_log(self) -> None: chat_container = self.query_one( self.CHAT_CONTAINER_SELECTOR, ScrollableContainer, ) await chat_container.remove_children()
if not self.chat_entries: await chat_container.mount( Static( "No messages yet. Type a question or request below.", classes="chat-empty", markup=False, ) ) else: await chat_container.mount( *(ChatBubble(entry) for entry in self.chat_entries) )
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) message = event.value.strip()
if not message: return
input_widget.clear() input_widget.focus()
if message.startswith("/") and self.handle_slash_command(message): return
self.run_worker(self.chat_with_agent(message), exclusive=True)
def main(argv: Sequence[str] | None = None) -> None: load_dotenv() args = parse_cli_args(argv) if args.reset: ProblemStore().reset_all() return
app = LetsCodeApp( initial_problem_id=args.problem, initial_new_prompt=args.new, load_initial_problem=not args.no_leetcode and args.new is None, ) app.run()
if __name__ == "__main__": main()