legacy-code-challenge / student_interface.py
refaelz's picture
Polish logout button layout
bc924c8
Raw History Blame Contribute Delete
111 kB
""" Student Interface β€” Gradio GUI for the Legacy Code Challenge. Two-page flow: Page 1 (Setup): student name, GitHub URL, nesting level, num-bugs, options β†’ Start Page 2 (Challenge): README, Code Editor, Test runner + AI Assistant sidebar Page 3 (Results): Score breakdown, diffs, test results, hints review """ from __future__ import annotations import difflib import json import os import sys import threading import logging from io import StringIO from datetime import datetime from pathlib import Path import gradio as gr # Configure detailed logging logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s', handlers=[ logging.FileHandler('app.log', encoding='utf-8'), logging.StreamHandler(sys.stdout) ] ) logger = logging.getLogger(__name__) from orchestrator.scoring import evaluate_submission from orchestrator.hint_graph import get_hint # Optional Google Sheets logging try: from google_sheets_logger import diagnose_google_sheets, log_to_google_sheets GOOGLE_SHEETS_AVAILABLE = True except ImportError: GOOGLE_SHEETS_AVAILABLE = False try: from supabase_submissions_logger import upload_submission_to_supabase SUPABASE_AVAILABLE = True except ImportError: SUPABASE_AVAILABLE = False # ── API Key Validation ──────────────────────────────────────────────────────── from llm_config import llm_api_key_context, validate_api_key as validate_openai_key HF_OAUTH_REQUIRED = bool(os.getenv("SPACE_ID")) def _configured_llm_api_key() -> str: provider = os.getenv("LLM_PROVIDER", "openai").lower() env_var = "GROQ_API_KEY" if provider == "groq" else "OPENAI_API_KEY" return os.getenv(env_var, "") def _hf_oauth_identity(profile: gr.OAuthProfile | None) -> dict | None: if profile is None: return None username = str(profile.username or "").strip() if not username: return None return { "provider": "huggingface", "provider_user_id": username, "profile_url": str(profile.profile or ""), "display_name": str(profile.name or username).strip(), } def _hf_auth_required(profile: gr.OAuthProfile | None) -> bool: return HF_OAUTH_REQUIRED and _hf_oauth_identity(profile) is None def _google_sheets_configured() -> bool: return bool(os.getenv("GOOGLE_SHEET_ID")) and ( bool(os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")) or Path("google-service-account.json").exists() ) def _supabase_configured() -> bool: return bool(os.getenv("SUPABASE_URL")) and bool( os.getenv("SUPABASE_SECRET_KEY") or os.getenv("SUPABASE_SERVICE_ROLE_KEY") ) def _cloud_upload_capabilities() -> dict[str, dict[str, str | bool]]: google_configured = _google_sheets_configured() supabase_configured = _supabase_configured() return { "google_sheets": { "available": GOOGLE_SHEETS_AVAILABLE, "configured": google_configured, "reason": "" if google_configured else "Missing GOOGLE_SHEET_ID or service account credentials", }, "supabase": { "available": SUPABASE_AVAILABLE, "configured": supabase_configured, "reason": "" if supabase_configured else "Missing SUPABASE_URL or Supabase server secret", }, } def _save_submission_to_supabase(log: "SubmissionLog", log_path: Path, record: dict) -> dict[str, str]: capability = _cloud_upload_capabilities()["supabase"] if not capability["available"] or not capability["configured"]: result = {"status": "disabled", "error": str(capability["reason"])} else: try: ok, reason = upload_submission_to_supabase(record) result = { "status": "success" if ok else "failed", "error": "" if ok else reason, } except Exception as exc: result = {"status": "failed", "error": type(exc).__name__} log.update(log_path, {"cloud": {"supabase": result}}) if result["status"] == "success": logger.info("Submission %s stored in Supabase", record.get("submission_id", "")) else: logger.warning("Supabase submission storage %s: %s", result["status"], result["error"]) return result # ── Challenge state loader ──────────────────────────────────────────────────── class ChallengeState: """Loads and exposes data from challenge_state.json.""" _HIDDEN_WORKSPACE_FILES = {"challenge_run_secret.py"} def __init__(self, workspace_path: str) -> None: self.workspace = Path(workspace_path) state_file = self.workspace / "challenge_state.json" if not state_file.exists(): raise FileNotFoundError(f"challenge_state.json not found in {workspace_path}") with open(state_file, encoding="utf-8") as f: data = json.load(f) self.github_url: str = data.get("github_url", "") # Normalise to forward slashes so comparisons work cross-platform raw_target = data.get("target_file", "") try: self.target_file: str = Path(raw_target).resolve().relative_to(self.workspace.resolve()).as_posix() except (ValueError, OSError): self.target_file = Path(raw_target).as_posix() self.original_code: str = data.get("original_code", "") self.sabotaged_code: str = data.get("sabotaged_code", "") self.function_name: str = data.get("function_name", "") self.bug_func_name: str = data.get("bug_func_name", "") self.original_bug_func_source: str = data.get("original_bug_func_source", "") self.bug_func_names: list = data.get("bug_func_names", []) or ( [self.bug_func_name] if self.bug_func_name else [] ) self.bug_func_sources_list: list = data.get("bug_func_sources_list", []) self.original_bug_func_sources_list: list = data.get("original_bug_func_sources_list", []) self.public_tests: list = data.get("public_tests", []) self.secret_tests: list = data.get("secret_tests", []) self.bug_description: str = data.get("bug_description", "") self.challenge_created_at: str = data.get("challenge_created_at", "") self.challenge_summary: str = data.get("challenge_summary", "") self.nesting_level: int = data.get("nesting_level", 3) self.refactoring_enabled: bool = data.get("refactoring_enabled", False) self.debug_mode: bool = data.get("debug_mode", False) # sabotaged_files: {rel_posix_path: content} for every file the # saboteur touched. Primary source: .metadata/ directory # written by the deployer immediately after sabotage (always up-to-date). # Fallback: sabotaged_files dict in JSON, then single sabotaged_code field. snapshot_dir = self.workspace / ".metadata" snap_files: dict[str, str] = {} if snapshot_dir.exists(): # Get the target file path from the data for proper mapping target_rel_from_json = data.get("target_file", "") if target_rel_from_json: try: # Convert to workspace-relative posix path target_abs = Path(target_rel_from_json).resolve() target_rel = target_abs.relative_to(self.workspace.resolve()).as_posix() except (ValueError, OSError): target_rel = Path(target_rel_from_json).as_posix() # Find the corresponding snapshot file # The snapshot filename has separators replaced with __ expected_snapshot_name = target_rel.replace("/", "__") snapshot_path = snapshot_dir / expected_snapshot_name if snapshot_path.exists(): try: snap_files[target_rel] = snapshot_path.read_text(encoding="utf-8") except Exception: pass if snap_files: self.sabotaged_files: dict[str, str] = snap_files else: # Fall back to JSON fields stored = data.get("sabotaged_files", {}) if not stored and self.sabotaged_code: try: rel = Path(self.target_file).resolve().relative_to( self.workspace.resolve() ).as_posix() except ValueError: rel = Path(self.target_file).name stored = {rel: self.sabotaged_code} self.sabotaged_files = stored @property def target_path(self) -> Path: return self.workspace / self.target_file def read_target(self) -> str: if self.target_path.exists(): return self.target_path.read_text(encoding="utf-8") return self.sabotaged_code def write_target(self, code: str) -> None: self.target_path.write_text(code, encoding="utf-8") def write_py_file(self, rel_path: str, code: str) -> None: file_path = self.workspace / rel_path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(code, encoding="utf-8") def reset_target(self) -> None: self.write_target(self.sabotaged_code) def list_py_files(self) -> list[str]: files = sorted(self.workspace.rglob("*.py")) return [ f.relative_to(self.workspace).as_posix() for f in files if ".metadata" not in f.parts and f.relative_to(self.workspace).as_posix() not in self._HIDDEN_WORKSPACE_FILES ] def read_py_file(self, rel_path: str) -> str: if Path(rel_path).as_posix() in self._HIDDEN_WORKSPACE_FILES: return "# File not available in challenge UI." full = self.workspace / rel_path if full.exists(): return full.read_text(encoding="utf-8") return f"# File not found: {rel_path}" def readme(self) -> str: readme_path = self.workspace / "STUDENT_README.md" if readme_path.exists(): return readme_path.read_text(encoding="utf-8") return "# Challenge\n\nREADME not found." def challenge_info(self) -> dict: return { "function_name": self.function_name, "bug_func_name": self.bug_func_name, "target_file": self.target_file, "nesting_level": self.nesting_level, "refactoring_enabled": self.refactoring_enabled, "debug_mode": self.debug_mode, "bug_func_names": self.bug_func_names, "bug_func_sources_list": self.bug_func_sources_list, "original_bug_func_sources_list": self.original_bug_func_sources_list, "original_code": self.original_code, } # ── Submission log ──────────────────────────────────────────────────────────── class SubmissionLog: """Persists submissions to <workspace>/submissions/ as JSON files.""" def __init__(self, workspace: Path) -> None: self.log_dir = workspace / "submissions" self.log_dir.mkdir(exist_ok=True) def save(self, entry: dict) -> Path: submission_id = entry.get("submission_id") or datetime.now().strftime("%Y%m%d_%H%M%S_%f") path = self.log_dir / f"{submission_id}.json" with open(path, "w", encoding="utf-8") as f: json.dump(entry, f, indent=2, ensure_ascii=False) return path def update(self, path: Path, updates: dict) -> None: if not path.exists(): return with open(path, encoding="utf-8") as f: entry = json.load(f) _deep_merge_dict(entry, updates) with open(path, "w", encoding="utf-8") as f: json.dump(entry, f, indent=2, ensure_ascii=False) # ── Pipeline runner ─────────────────────────────────────────────────────────── def _run_pipeline(github_url: str, nesting_level: int, num_bugs: int, refactoring_enabled: bool = False, debug_mode: bool = False) -> str: """Invoke the architect pipeline and return the workspace path.""" from architect.graph import build_graph graph = build_graph() result = graph.invoke({ "github_url": github_url, "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "num_bugs": num_bugs, "clone_path": "", "target_file": "", "original_code": "", "sabotaged_code": "", "function_name": "", "test_args": "", "expected_output": "", "actual_output": "", "bug_description": "", "detailed_explanation": "", "challenge_summary": "", "test_cases": [], "public_tests": [], "secret_tests": [], "candidate_files": [], "bug_func_name": "", "bug_func_source": "", "call_chain": {}, }) workspace_path = result["clone_path"] # Read the actual file on disk (may differ from state if extra transforms ran) target_file_rel = result.get("target_file", "") actual_sabotaged_code = result.get("sabotaged_code", "") workspace_path_obj = Path(workspace_path).resolve() if target_file_rel: target_path = Path(workspace_path) / target_file_rel if target_path.exists(): actual_sabotaged_code = target_path.read_text(encoding="utf-8") # Build sabotaged_files: {rel_posix_path: content} for every file the # saboteur modified. Currently always one file (target_file). sabotaged_files: dict[str, str] = {} if target_file_rel and actual_sabotaged_code: try: rel_posix = Path(target_file_rel).resolve().relative_to(workspace_path_obj).as_posix() except (ValueError, OSError): rel_posix = Path(target_file_rel).as_posix() sabotaged_files[rel_posix] = actual_sabotaged_code # Persist challenge_state.json challenge_state = { "github_url": github_url, "workspace_path": workspace_path, "challenge_created_at": datetime.now().isoformat(), "target_file": target_file_rel, "original_code": result.get("original_code", ""), "sabotaged_code": actual_sabotaged_code, "sabotaged_files": sabotaged_files, "function_name": result.get("function_name", ""), "bug_func_name": result.get("bug_func_name", ""), "bug_func_source": result.get("bug_func_source", ""), "original_bug_func_source": result.get("original_bug_func_source", ""), "bug_func_names": result.get("bug_func_names", []), "bug_func_sources_list": result.get("bug_func_sources_list", []), "original_bug_func_sources_list": result.get("original_bug_func_sources_list", []), "test_cases": result.get("test_cases", []), "public_tests": result.get("public_tests", []), "secret_tests": result.get("secret_tests", []), "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "bug_description": result.get("bug_description", ""), "challenge_summary": result.get("challenge_summary", ""), } state_path = Path(workspace_path) / "challenge_state.json" with open(state_path, "w", encoding="utf-8") as f: json.dump(challenge_state, f, indent=2, ensure_ascii=False) return workspace_path # ── Helpers ─────────────────────────────────────────────────────────────────── PENALTY_TABLE = [0, 2, 6, 12, 20, 30] # Sets dark mode as the default on first visit and defines window.startTimer. def _make_js(timer_minutes: int = 0) -> str: auto_start = ( f""" (function tryStartTimer() {{ if (document.getElementById('timer-inner')) {{ window.startTimer({timer_minutes}); }} else {{ setTimeout(tryStartTimer, 150); }} }})();""" if timer_minutes > 0 else "" ) return """() => { if (!localStorage.getItem('gradio-theme')) { localStorage.setItem('gradio-theme', 'dark'); } window.startTimer = function(minutes) { if (!minutes || minutes <= 0) return; if (window._timerInterval) clearInterval(window._timerInterval); const endTime = Date.now() + minutes * 60 * 1000; function tick() { const remaining = Math.max(0, endTime - Date.now()); const m = Math.floor(remaining / 60000); const s = Math.floor((remaining % 60000) / 1000); const el = document.getElementById('timer-inner'); if (!el) return; if (remaining === 0) { el.innerHTML = '<span style="color:#ef4444;font-weight:bold;font-size:1.1em;">⏱️ TIME\\'S UP!</span>'; clearInterval(window._timerInterval); } else { const color = remaining < 300000 ? '#ef4444' : (remaining < 600000 ? '#f59e0b' : '#22c55e'); el.innerHTML = '⏱️ <span style="font-weight:bold;font-size:1.1em;color:' + color + ';">' + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0') + '</span>'; } } tick(); window._timerInterval = setInterval(tick, 1000); }; """ + auto_start + "\n}" _JS = _make_js(0) _CSS = """ /* Keep footer visible */ footer svg { display: inline !important; } .gradio-container { max-width: 100% !important; } /* Setup page β€” centred card */ .setup-card { max-width: 700px; margin: 40px auto !important; } /* Account action */ #logout-row { display: flex !important; justify-content: flex-end !important; width: min(100%, 1200px) !important; margin: 0 auto 8px !important; } #logout-btn { flex: 0 0 auto !important; width: auto !important; min-width: 96px !important; } #logout-btn button { min-height: 36px !important; padding: 0 12px !important; border-radius: 6px !important; font-weight: 500 !important; } /* Code editor β€” scrollable */ #code-editor .cm-scroller { overflow-y: auto !important; max-height: 60vh !important; } #code-editor .cm-editor { max-height: 60vh !important; } /* Chatbot */ #ai-chatbot .wrap { height: 58vh !important; overflow-y: auto !important; } /* Tab content */ .left-tabs .tabitem { overflow-y: auto !important; max-height: 80vh !important; } /* Results diff blocks */ .diff-block { font-family: monospace; font-size: 0.85em; padding: 12px; border-radius: 8px; overflow-y: auto; max-height: 45vh; white-space: pre-wrap; background: #1e1e1e; color: #d4d4d4; } /* Challenge timer β€” pushed to the right corner of the header */ .header-row { display: flex !important; align-items: center !important; width: 100% !important; gap: 8px; } .header-row > * { flex-shrink: 0 !important; } .header-row > *:first-child { flex: 1 1 auto !important; min-width: 0; } #challenge-timer { flex: 0 0 auto !important; font-family: monospace; font-size: 1em; text-align: right; padding: 4px 8px; min-width: 90px; white-space: nowrap; } """ def _hint_md(hints_used: int, penalty: int) -> str: next_penalty = PENALTY_TABLE[min(hints_used + 1, len(PENALTY_TABLE) - 1)] return ( f"πŸ€– **AI Assistant** &nbsp;|&nbsp; " f"Hints used: **{hints_used}** &nbsp;|&nbsp; Current cumulative penalty: **βˆ’{penalty} pts** &nbsp;|&nbsp; " f"Next hint: **βˆ’{next_penalty} pts** &nbsp; " f"_(schedule: βˆ’2 / βˆ’6 / βˆ’12 / βˆ’20 / βˆ’30)_" ) _HINT_DECLINES = { "no", "nope", "nah", "not now", "nevermind", "never mind", "no thanks", "no thank you", "skip", "cancel", "forget it", "don't", "dont", "no hint", "stop", } _HINT_AFFIRMATIONS = { "yes", "y", "yeah", "yep", "sure", "ok", "okay", "proceed", "go ahead", "do it", "please do", "continue", "hint", "give me a hint", "Χ›ΧŸ", "Χ›ΧŸ Χ‘Χ‘Χ§Χ©Χ”", "ΧͺΧžΧ©Χ™Χš", "Χͺן Χ¨ΧžΧ–", "Χͺן ΧœΧ™ Χ¨ΧžΧ–", "Χ™ΧΧœΧœΧ”", "Χ‘Χ‘Χ‘Χ”", } _CONFIRMATION_KWS = ["would you like", "shall i", "want me to", "proceed", "penalty to your score"] def _is_decline(msg: str) -> bool: m = msg.strip().lower() return ( m in _HINT_DECLINES or m.startswith("no ") or m.startswith("don't") or m.startswith("dont") or m.startswith("nope ") or m.startswith("nah ") ) def _is_confirmation_question(text: str) -> bool: t = text.lower() return any(kw in t for kw in _CONFIRMATION_KWS) def _is_affirmation(msg: str) -> bool: m = msg.strip().lower() return ( m in _HINT_AFFIRMATIONS or m.startswith("yes ") or m.startswith("sure ") or m.startswith("ok ") or m.startswith("okay ") or m.startswith("go ahead") or m.startswith("continue") or m.startswith("Χ›ΧŸ") or m.startswith("Χͺן") or m.startswith("ΧͺΧžΧ©Χ™Χš") ) def _colorise_test_output(raw: str) -> str: """Wrap test output lines in coloured HTML spans.""" html_lines = [] for line in raw.split("\n"): if ": PASS" in line or "ALL PASS" in line: html_lines.append(f'<span style="color:#22c55e;font-weight:bold;">{line}</span>') elif ": FAIL" in line or ": CRASH" in line or "FAILED" in line: html_lines.append(f'<span style="color:#ef4444;font-weight:bold;">{line}</span>') else: html_lines.append(f'<span style="color:#d4d4d4;">{line}</span>') return ( '<pre style="font-family:monospace;padding:12px;background:#1e1e1e;' 'color:#d4d4d4;border-radius:8px;overflow-y:auto;max-height:60dvh;' 'white-space:pre-wrap;">' + "<br>".join(html_lines) + "</pre>" ) def _normalize(code: str) -> str: """Strip trailing whitespace per line and normalize line endings.""" return "\n".join(line.rstrip() for line in code.replace("\r\n", "\n").replace("\r", "\n").splitlines()) def _plain_diff_text(a: str, b: str, from_label: str, to_label: str) -> str: a_lines = _normalize(a).splitlines(keepends=True) b_lines = _normalize(b).splitlines(keepends=True) return "".join(difflib.unified_diff(a_lines, b_lines, fromfile=from_label, tofile=to_label, lineterm="")) def _deep_merge_dict(target: dict, updates: dict) -> None: for key, value in updates.items(): if isinstance(value, dict) and isinstance(target.get(key), dict): _deep_merge_dict(target[key], value) else: target[key] = value def _workspace_diff_html(cs: "ChallengeState") -> str: """ Show a unified diff for the target file the student changed. Compare the locally stored received-state snapshot vs the current disk content. This ensures only the student's changes are shown β€” not the sabotage noise. """ workspace = cs.workspace.resolve() sabotaged_files = cs.sabotaged_files # {rel_posix: received_content} sections: list[str] = [] # Show diff for files modified by the saboteur (the target file) for rel_posix, received_content in sabotaged_files.items(): full_path = workspace / rel_posix if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) == _normalize(received_content): continue diff = _diff_html(received_content, current, rel_posix, rel_posix) sections.append( f"<h4 style='color:#94a3b8;margin:10px 0 4px;font-family:monospace;'>" f"πŸ“„ {rel_posix}</h4>" + diff ) if not sections: return "<div style='color:#22c55e;padding:12px;'>No changes detected in workspace.</div>" return "".join(sections) def _strip_comments_and_docstrings(code: str) -> str: """Remove comment-only lines and docstrings, keeping pure code.""" import ast as _ast docstring_lines: set[int] = set() try: tree = _ast.parse(code) for node in _ast.walk(tree): if isinstance(node, (_ast.FunctionDef, _ast.AsyncFunctionDef, _ast.ClassDef, _ast.Module)): if (node.body and isinstance(node.body[0], _ast.Expr) and isinstance(node.body[0].value, _ast.Constant) and isinstance(node.body[0].value.value, str)): ds = node.body[0] docstring_lines.update(range(ds.lineno, ds.end_lineno + 1)) except Exception: pass result = [] for i, line in enumerate(code.splitlines(), 1): if i in docstring_lines: continue if line.lstrip().startswith("#"): continue result.append(line) return "\n".join(result) def _diff_html(a: str, b: str, from_label: str, to_label: str, strip_comments: bool = False) -> str: """Generate coloured unified-diff HTML between two code strings.""" if strip_comments: a = _strip_comments_and_docstrings(a) b = _strip_comments_and_docstrings(b) a = _normalize(a) b = _normalize(b) a_lines = a.splitlines(keepends=True) b_lines = b.splitlines(keepends=True) diff = list(difflib.unified_diff(a_lines, b_lines, fromfile=from_label, tofile=to_label, lineterm="")) if not diff: return '<div class="diff-block" style="color:#22c55e;">No changes detected.</div>' html_lines = [] for line in diff: escaped = line.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if line.startswith("+++") or line.startswith("---"): html_lines.append(f'<span style="color:#888;font-style:italic;">{escaped}</span><br>') elif line.startswith("@@"): html_lines.append(f'<span style="color:#60a5fa;">{escaped}</span><br>') elif line.startswith("+"): html_lines.append(f'<span style="color:#22c55e;background:#052e16;padding:2px 4px;">{escaped}</span><br>') elif line.startswith("-"): html_lines.append(f'<span style="color:#ef4444;background:#2d0a0a;padding:2px 4px;">{escaped}</span><br>') else: html_lines.append(f'<span style="color:#d4d4d4;">{escaped}</span><br>') return ( '<div class="diff-block">' + "".join(html_lines) + "</div>" ) def _extract_function_source(code: str, func_name: str) -> str: """Extract a named function's source lines from code using ast.""" import ast try: tree = ast.parse(code) for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): if node.name == func_name: lines = code.splitlines() return "\n".join(lines[node.lineno - 1 : node.end_lineno]) except Exception: pass return "" def _apply_one_bug_fix( current_code: str, func_name: str, orig_pre: str, sabot_pre: str, ) -> str | None: """ Apply the fix for a single injected bug by surgically patching func_name inside current_code. Returns the patched file content, or None if the fix could not be determined. Strategy: character-level diff between orig_pre (correct pre-transform source) and sabot_pre (buggy pre-transform source) surfaces the exact changed tokens. Those tokens survive obfuscation so we can find-and-replace them directly in the fully-obfuscated current_code. """ import difflib func_in_code = _extract_function_source(current_code, func_name) if not func_in_code: return None matcher = difflib.SequenceMatcher(None, orig_pre, sabot_pre, autojunk=False) opcodes = matcher.get_opcodes() fixed_func = func_in_code changed = False for tag, i1, i2, j1, j2 in opcodes: if tag == "equal": continue orig_frag = orig_pre[i1:i2] sabot_frag = sabot_pre[j1:j2] if not orig_frag.strip() and not sabot_frag.strip(): continue if tag in ("replace", "insert"): if not sabot_frag.strip(): continue ctx_start_orig = i1 ctx_start_sabot = j1 while ctx_start_orig > 0 and ctx_start_sabot > 0: co = orig_pre[ctx_start_orig - 1] cs_ = sabot_pre[ctx_start_sabot - 1] if co != cs_ or not (co.isalnum() or co == "_"): break ctx_start_orig -= 1 ctx_start_sabot -= 1 search_str = sabot_pre[ctx_start_sabot:j2] replace_str = orig_pre[ctx_start_orig:i2] if search_str and search_str in fixed_func: fixed_func = fixed_func.replace(search_str, replace_str, 1) changed = True elif sabot_frag and sabot_frag in fixed_func: fixed_func = fixed_func.replace(sabot_frag, orig_frag, 1) changed = True elif tag == "delete": if not orig_frag.strip(): continue ctx_left = sabot_pre[max(0, j1 - 30):j1] ctx_right_raw = sabot_pre[j2:j2 + 20] nl = ctx_right_raw.find("\n") ctx_right = ctx_right_raw[:nl] if nl != -1 else ctx_right_raw for trim in range(len(ctx_left)): search_str = ctx_left[trim:] + ctx_right replace_str = ctx_left[trim:] + orig_frag + ctx_right if search_str and search_str in fixed_func: fixed_func = fixed_func.replace(search_str, replace_str, 1) changed = True break if not changed or fixed_func == func_in_code: return None fixed = current_code.replace(func_in_code, fixed_func, 1) return fixed if fixed != current_code else None def _compute_expected_fixed_code(cs: "ChallengeState") -> str | None: """ Compute the expected correct version of the sabotaged file by applying surgical fixes for every injected bug. Supports num_bugs > 1 by iterating over all (func_name, orig_pre, sabot_pre) triples stored in challenge_state.json. IMPORTANT: After inflate_hierarchy, the sources are POST-INFLATE (include wrappers). This ensures surgical patching works correctly even when wrapper layers exist. Returns None if no fix could be determined. """ import json as _json try: _data = _json.loads((cs.workspace / "challenge_state.json").read_text(encoding="utf-8")) except Exception: _data = {} # Multi-bug lists (written by the new pipeline). Fall back to single-bug # fields for workspaces generated before this change. # NOTE: These are POST-INFLATE sources (updated by inflate_hierarchy) bug_func_names = _data.get("bug_func_names") or cs.bug_func_names sabot_sources_list = _data.get("bug_func_sources_list") or [] orig_sources_list = _data.get("original_bug_func_sources_list") or [] # Single-bug fallback: wrap scalar fields in lists if not bug_func_names and cs.bug_func_name: bug_func_names = [cs.bug_func_name] if not sabot_sources_list: sabot_sources_list = [_data.get("bug_func_source", "")] if not orig_sources_list: orig_sources_list = [ cs.original_bug_func_source or _extract_function_source(cs.original_code, cs.bug_func_name) ] if not bug_func_names: return None # Use the snapshot as the starting point (matches what the student received). try: target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix() except ValueError: target_rel = "" current_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code any_changed = False for func_name, orig_pre, sabot_pre in zip(bug_func_names, orig_sources_list, sabot_sources_list): if not (orig_pre and sabot_pre): continue result = _apply_one_bug_fix(current_code, func_name, orig_pre, sabot_pre) if result is not None: current_code = result any_changed = True return current_code if any_changed else None def _expected_fix_diff_html(cs: "ChallengeState", submitted_code: str = "") -> str: """ Show two sections: 1. What the expected fix looks like (buggy β†’ expected). 2. How the student's submission compares to the expected fix (expected β†’ submitted): empty if perfect, otherwise shows extra/wrong changes. """ func = cs.bug_func_name # Resolve the received (snapshot) content for the target file try: target_rel = cs.target_path.resolve().relative_to(cs.workspace.resolve()).as_posix() except ValueError: target_rel = "" received_code = cs.sabotaged_files.get(target_rel) or cs.sabotaged_code expected_fixed = _compute_expected_fixed_code(cs) # ── Fallback: function-level or full-file diff ──────────────────────────── if expected_fixed is None: approx = received_code for fn in cs.bug_func_names: sabot_func = _extract_function_source(approx, fn) orig_func = _extract_function_source(cs.original_code, fn) if sabot_func and orig_func: candidate = approx.replace(sabot_func, orig_func, 1) if candidate != approx: approx = candidate if approx != received_code: expected_fixed = approx else: return _diff_html(received_code, cs.original_code, target_rel, target_rel, strip_comments=True) # ── Section 1: expected fix ─────────────────────────────────────────────── section1 = ( "<h4 style='color:#94a3b8;margin:8px 0 4px;'>🎯 Expected fix</h4>" + _diff_html(received_code, expected_fixed, target_rel, target_rel, strip_comments=True) ) if not submitted_code: return section1 # ── Section 2: workspace-wide comparison ───────────────────────────────── # "Perfect fix" = target file matches expected AND no other files were changed. def _ast_equivalent(a: str, b: str) -> bool: try: import ast as _ast return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b)) except SyntaxError: return _normalize(a) == _normalize(b) target_file_ok = _ast_equivalent(expected_fixed, submitted_code) # Check whether the student touched any files outside the sabotaged set. # Known-modified files = snapshot keys + the challenge target file itself. known_changed = set(cs.sabotaged_files.keys()) | ({target_rel} if target_rel else set()) import subprocess as _sp try: proc = _sp.run( ["git", "diff", "HEAD", "--name-only"], cwd=str(cs.workspace.resolve()), capture_output=True, text=True, encoding="utf-8", timeout=10, ) extra_changed = [ f.replace("\\", "/") for f in proc.stdout.splitlines() if f.replace("\\", "/") not in known_changed ] except Exception: extra_changed = [] is_perfect = target_file_ok and not extra_changed if is_perfect: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#052e16;" "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>" "βœ… Perfect fix β€” you changed exactly the right lines and nothing more." "</div>" ) else: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;" "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>" "⚠️ Your fix differs from the expected solution β€” see Your Changes on the left." "</div>" ) return section1 + verdict def _combined_changes_html(cs: "ChallengeState", submitted_code: str = "") -> str: """ Render the "Changes & Expected" tab as a single HTML block. For each file in the union of (student-changed files βˆͺ expected-fix files), a row is rendered with two side-by-side diff panels: - Left: student's diff (vs received sabotaged code) - Right: expected fix diff (vs received sabotaged code) If one side has no changes for a given file, a "No changes" placeholder is shown. A verdict banner spans the full width at the bottom. """ import subprocess as _sp workspace = cs.workspace.resolve() try: target_rel = cs.target_path.resolve().relative_to(workspace).as_posix() except ValueError: target_rel = "" sabotaged_files = cs.sabotaged_files received_code = sabotaged_files.get(target_rel) or cs.sabotaged_code # ── Collect student-changed files ───────────────────────────────────────── # student_changes: {rel_posix: (received_content, current_content)} student_changes: dict[str, tuple[str, str]] = {} for rel_posix, received_content in sabotaged_files.items(): full_path = workspace / rel_posix if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) != _normalize(received_content): student_changes[rel_posix] = (received_content, current) try: proc = _sp.run( ["git", "diff", "HEAD", "--name-only"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) for changed_rel in proc.stdout.splitlines(): changed_posix = changed_rel.replace("\\", "/") if changed_posix in sabotaged_files: continue if not changed_rel.endswith(".py"): continue orig_proc = _sp.run( ["git", "show", f"HEAD:{changed_rel}"], cwd=str(workspace), capture_output=True, text=True, encoding="utf-8", timeout=10, ) if orig_proc.returncode != 0: continue full_path = workspace / changed_rel if not full_path.exists(): continue current = full_path.read_text(encoding="utf-8") if _normalize(current) != _normalize(orig_proc.stdout): student_changes[changed_posix] = (orig_proc.stdout, current) except Exception: pass # ── Compute expected fix for target file ────────────────────────────────── expected_fixed = _compute_expected_fixed_code(cs) if expected_fixed is None and cs.bug_func_name: sabot_func = _extract_function_source(received_code, cs.bug_func_name) orig_func = _extract_function_source(cs.original_code, cs.bug_func_name) if sabot_func and orig_func: ef = received_code.replace(sabot_func, orig_func, 1) if ef != received_code: expected_fixed = ef # ── Build union of files to show ────────────────────────────────────────── expected_files = {target_rel} if (target_rel and expected_fixed is not None) else set() all_files = sorted(set(student_changes.keys()) | expected_files) # ── Column header row ───────────────────────────────────────────────────── col_headers = ( "<div style='display:flex;gap:12px;margin-bottom:8px;'>" "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>✏️ Your Changes" " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>" "β€” your submitted code vs the buggy code you received</span></div>" "<div style='flex:1;min-width:0;font-weight:600;color:#cbd5e1;'>🎯 Expected Fix" " <span style='font-weight:400;color:#64748b;font-size:0.88em;'>" "β€” the minimal correct fix</span></div>" "</div>" ) if not all_files: return col_headers + "<div class='diff-block' style='color:#22c55e;'>No changes detected in workspace.</div>" _no_change_left = "<div class='diff-block' style='color:#22c55e;'>No changes</div>" _no_change_right = "<div class='diff-block' style='color:#64748b;'>No change expected</div>" # ── Per-file side-by-side rows ──────────────────────────────────────────── rows: list[str] = [] for rel in all_files: file_header = ( f"<h4 style='color:#94a3b8;margin:6px 0 4px;font-family:monospace;'>πŸ“„ {rel}</h4>" ) # Left: student's changes if rel in student_changes: recv, curr = student_changes[rel] left_body = _diff_html(recv, curr, rel, rel) else: left_body = _no_change_left # Right: expected fix (only for the sabotaged target file) if rel == target_rel and expected_fixed is not None: right_body = _diff_html(received_code, expected_fixed, rel, rel) else: right_body = _no_change_right rows.append( "<div style='display:flex;gap:12px;margin-bottom:20px;'>" f"<div style='flex:1;min-width:0;'>{file_header}{left_body}</div>" f"<div style='flex:1;min-width:0;'>{file_header}{right_body}</div>" "</div>" ) # ── Verdict banner (full-width) ─────────────────────────────────────────── verdict = "" if submitted_code: def _ast_eq(a: str, b: str) -> bool: try: import ast as _ast return _ast.dump(_ast.parse(a)) == _ast.dump(_ast.parse(b)) except SyntaxError: return _normalize(a) == _normalize(b) target_ok = expected_fixed is not None and _ast_eq(expected_fixed, submitted_code) extra_files = [f for f in student_changes if f != target_rel] is_perfect = target_ok and not extra_files if is_perfect: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#052e16;" "border:1px solid #22c55e;border-radius:6px;color:#22c55e;font-weight:600;'>" "βœ… Perfect fix β€” you changed exactly the right lines and nothing more." "</div>" ) else: verdict = ( "<div style='margin-top:12px;padding:10px 14px;background:#2d1a00;" "border:1px solid #f59e0b;border-radius:6px;color:#f59e0b;font-weight:600;'>" "⚠️ Your fix differs from the expected solution." "</div>" ) return col_headers + "".join(rows) + verdict def _hints_html(hint_log: list) -> str: """Render hint log with the student's actual question and the assistant response.""" def _esc(s: str) -> str: return (s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")) entries = [e for e in (hint_log or []) if isinstance(e, dict)] if not entries: return "<p style='color:#888;font-style:italic;'>No hints were used.</p>" parts: list[str] = [] for n, entry in enumerate(entries, 1): question = entry.get("question", "").strip() or entry.get("summary", "").strip() response = entry.get("response", "").strip() hint_summary = entry.get("hint_summary", "").strip() if not question: first_line = response.split("\n")[0].strip() dot = first_line.find(". ") question = first_line[: dot + 1] if dot != -1 else first_line parts.append( f'<div style="margin:6px 0;padding:8px 14px;border:1px solid #374151;' f'border-radius:8px;background:#1a2e1a;">' f'<span style="color:#93c5fd;font-weight:bold;margin-right:10px;">Hint #{n}</span>' f'<div style="color:#86efac;margin-top:6px;"><strong>Question:</strong> {_esc(question)}</div>' f'<div style="color:#d1d5db;margin-top:6px;white-space:pre-wrap;"><strong>Answer:</strong> {_esc(response)}</div>' + (f'<div style="color:#94a3b8;margin-top:6px;font-size:0.9em;"><strong>Internal hint summary:</strong> {_esc(hint_summary)}</div>' if hint_summary else '') + f'</div>' ) header = (f'<p style="color:#888;font-size:0.85em;margin:0 0 8px 0;">' f'{len(entries)} hint(s) used</p>') return ( header + '<div style="max-height:50vh;overflow-y:auto;padding:4px;">' + "".join(parts) + "</div>" ) def _score_summary_html(result: dict) -> str: """Build a prominent score summary block.""" total = result["total_score"] llm_score = result.get("llm_score", total) explanation = result.get("llm_explanation", "") penalty = result["hint_penalty"] passed = result["passed"] ttl = result["total_tests"] all_ok = result["all_passed"] color = "#22c55e" if all_ok else ("#f59e0b" if total >= 50 else "#ef4444") badge = "πŸŽ‰ ALL TESTS PASS!" if all_ok else ("⚠️ Partial" if total > 0 else "❌ Failed") explanation_html = "" if explanation: import html as _html escaped = _html.escape(explanation) explanation_html = ( f'<div style="margin-top:14px;padding:10px 14px;background:#0f172a;' f'border-left:3px solid #60a5fa;border-radius:4px;color:#cbd5e1;' f'font-size:0.9em;line-height:1.5;">' f'<strong style="color:#60a5fa;">πŸ€– AI Evaluation:</strong><br>{escaped}</div>' ) return f""" <div style="padding:20px;border-radius:12px;background:#1e1e1e;border:2px solid {color};"> <div style="font-size:2.5em;font-weight:bold;color:{color};text-align:center;">{total}/100</div> <div style="text-align:center;color:{color};font-size:1.1em;margin-bottom:16px;">{badge}</div> <table style="width:100%;border-collapse:collapse;font-family:monospace;"> <tr> <td style="padding:6px 12px;color:#d4d4d4;">πŸ€– AI Score</td> <td style="padding:6px 12px;color:#60a5fa;text-align:right;font-weight:bold;">{llm_score}/100</td> <td style="padding:6px 12px;color:#888;">({passed}/{ttl} tests passed)</td> </tr> <tr> <td style="padding:6px 12px;color:#d4d4d4;">πŸ’‘ Hint Penalty</td> <td style="padding:6px 12px;color:#f87171;text-align:right;font-weight:bold;">βˆ’{penalty}</td> <td style="padding:6px 12px;color:#888;"></td> </tr> </table> {explanation_html} </div> """ def _submission_outcome(result: dict) -> str: if not result.get("touched_bug_function", True): return "wrong_location" if result.get("changed_function_names") else "no_attempt" if result.get("all_passed"): return "full_fix" before_passed = result.get("before_passed", 0) after_passed = result.get("passed", 0) if after_passed > before_passed: return "partial_fix" if after_passed < before_passed: return "regression" return "attempted_no_improvement" def _build_submission_record( cs: "ChallengeState", student_name: str, submitted_code: str, result: dict, hints_used: int, chat_log: list, hint_log: list, attempt_number: int, debug_logs: str, enable_cloud_uploads: bool, identity: dict | None = None, ) -> dict: timestamp = datetime.now() submission_id = timestamp.strftime("%Y%m%d_%H%M%S_%f") expected_fixed_code = _compute_expected_fixed_code(cs) or cs.original_code challenge_id = f"{cs.workspace.name}:{cs.target_file}:{cs.function_name or 'unknown'}" student_name = (student_name or "Anonymous").strip() or "Anonymous" outcome = _submission_outcome(result) cloud_caps = _cloud_upload_capabilities() google_status = "pending" if enable_cloud_uploads and cloud_caps["google_sheets"]["available"] and cloud_caps["google_sheets"]["configured"] else "disabled" supabase_status = "pending" if enable_cloud_uploads and cloud_caps["supabase"]["available"] and cloud_caps["supabase"]["configured"] else "disabled" google_error = "" if google_status == "pending" else str(cloud_caps["google_sheets"]["reason"]) supabase_error = "" if supabase_status == "pending" else str(cloud_caps["supabase"]["reason"]) return { "submission_id": submission_id, "timestamp": timestamp.isoformat(), "student": { "name": student_name, "email": "", "auth_provider": (identity or {}).get("provider", ""), "provider_user_id": (identity or {}).get("provider_user_id", ""), "profile_url": (identity or {}).get("profile_url", ""), }, "challenge": { "challenge_id": challenge_id, "created_at": cs.challenge_created_at, "challenge_summary": cs.challenge_summary, "workspace_name": cs.workspace.name, "workspace_path": str(cs.workspace), "repo_url": cs.github_url, "target_file": cs.target_file, "function_name": cs.function_name, "bug_func_name": cs.bug_func_name, "bug_func_names": cs.bug_func_names, "bug_description": cs.bug_description, "difficulty_level": cs.nesting_level, "refactoring_enabled": cs.refactoring_enabled, "debug_mode": cs.debug_mode, "challenge_prompt": cs.readme(), "original_code": cs.original_code, "buggy_code": cs.sabotaged_code, "expected_fixed_code": expected_fixed_code, "public_tests": cs.public_tests, "secret_tests": cs.secret_tests, }, "submission": { "attempt_number": attempt_number, "hints_used": hints_used, "chat_history": chat_log or [], "hint_history": hint_log or [], "student_code": submitted_code, "student_diff": _plain_diff_text( cs.sabotaged_code, submitted_code, f"received/{cs.target_file}", f"student/{cs.target_file}", ), "changed_function_names": result.get("changed_function_names", []), "changed_functions": result.get("changed_functions", []), "bug_function_names": result.get("bug_function_names", []), "touched_bug_function": result.get("touched_bug_function", False), }, "tests": { "before_passed": result.get("before_passed", 0), "before_total": result.get("before_total", 0), "public_passed": result.get("public_passed", 0), "public_total": result.get("public_total", 0), "secret_passed": result.get("secret_passed", 0), "secret_total": result.get("secret_total", 0), "passed_tests": result.get("passed", 0), "total_tests": result.get("total_tests", 0), "all_passed": result.get("all_passed", False), "per_test_before": result.get("per_test_before", []), "per_test_after": result.get("per_test_after", []), "public_output": result.get("public_output", ""), "secret_output": result.get("secret_output", ""), "test_output": result.get("test_output", ""), }, "scoring": { "llm_score": result.get("llm_score", result.get("total_score", 0)), "llm_explanation": result.get("llm_explanation", ""), "hint_penalty": result.get("hint_penalty", 0), "total_score": result.get("total_score", 0), "test_score": result.get("test_score", 0), "correct_location": result.get("correct_location", False), "submission_outcome": outcome, }, "system": { "llm_provider": os.getenv("LLM_PROVIDER", ""), "llm_model": os.getenv("LLM_MODEL", ""), "agent_model": os.getenv("AGENT_MODEL", ""), }, "cloud": { "google_sheets": {"status": google_status, "error": google_error}, "supabase": {"status": supabase_status, "error": supabase_error}, }, "debug": { "captured_logs": debug_logs, }, } # ── Full two-page interface ─────────────────────────────────────────────────── def create_full_interface() -> gr.Blocks: """ Returns a Gradio app with login page (if needed) + challenge interface: Page 0: Login (visible only if OPENAI_API_KEY not in .env) Page 1: Setup form (name / URL / level / bugs) Page 2: Challenge interface (shown after pipeline finishes) Page 3: Results (shown after Submit) """ # Spaces require an identity even when a server-side model key is configured. has_env_key = bool(_configured_llm_api_key()) css = """ #code-editor { font-size: 14px !important; font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important; background-color: #1e1e1e !important; border-radius: 8px !important; } #code-editor .codemirror-wrapper { background-color: #1e1e1e !important; } #code-editor .cm-editor { background-color: #1e1e1e !important; } .setup-card { max-width: 800px; margin: 40px auto; padding: 30px; } """ # Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility with gr.Blocks(title="Legacy Code Challenge") as demo: # Shared state user_api_key_state = gr.State("") user_name_state = gr.State("") workspace_state = gr.State("") hints_used_state = gr.State(0) submission_count_state = gr.State(0) chat_log_state = gr.State([]) hint_log_state = gr.State([]) confirmation_pending_state = gr.State(False) timer_trigger = gr.Number(value=0, visible=False) # Account action, shown only after login. with gr.Row(visible=False, elem_id="logout-row") as logout_row: logout_btn = gr.Button("Log out", variant="secondary", elem_id="logout-btn", size="sm") # ════════════════════════════════════════════════════════════════════ # PAGE 0 β€” Login (visible only if no .env key) # ════════════════════════════════════════════════════════════════════ with gr.Column(visible=not has_env_key or HF_OAUTH_REQUIRED, elem_classes=["setup-card"]) as login_page: gr.Markdown( "# πŸ” Welcome to Legacy Code Challenge\n" "### Please enter your details to continue" ) if HF_OAUTH_REQUIRED: gr.LoginButton(elem_id="huggingface-login") login_name = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", elem_id="login-name", interactive=not HF_OAUTH_REQUIRED, ) login_api_key = gr.Textbox( label="OpenAI API Key", placeholder="sk-proj-...", type="password", info="Get one at platform.openai.com/api-keys", elem_id="login-api-key", visible=not has_env_key, ) if has_env_key: gr.Markdown("The app's configured model key will be used.") gr.Markdown( "⚠️ **Note:** Your API key is only used for this session and consumes credits from your OpenAI account." ) login_btn = gr.Button("πŸš€ Continue", variant="primary", size="lg") login_status = gr.Markdown("") # ════════════════════════════════════════════════════════════════════ # PAGE 1 β€” Setup (visible if .env exists, else hidden) # ════════════════════════════════════════════════════════════════════ with gr.Column(visible=has_env_key and not HF_OAUTH_REQUIRED, elem_classes=["setup-card"]) as setup_page: gr.Markdown( "# πŸ› Legacy Code Challenge\n" "Fill in the details below, then click **Start Challenge**." ) name_box = gr.Textbox( label="Your Name", placeholder="e.g. Alice Smith", ) url_box = gr.Textbox( label="GitHub Repository URL", placeholder="https://github.com/mahmoud/boltons", ) with gr.Row(): nesting_slider = gr.Slider( minimum=1, maximum=6, value=3, step=1, label="πŸ”— Nesting Level (call-chain depth)", info="Higher = deeper call chains (1=simple, 6=very deep)", ) bugs_slider = gr.Slider( minimum=1, maximum=5, value=1, step=1, label="πŸ› Number of Bugs to Inject", ) with gr.Row(): refactoring_check = gr.Checkbox( label="πŸ”€ Enable Refactoring (obfuscation/spaghettification)", value=False, ) debug_check = gr.Checkbox( label="🐞 Debug Mode (verbose output, show bug locations)", value=False, ) timer_slider = gr.Slider( minimum=0, maximum=120, value=0, step=5, label="⏱️ Challenge Timer (minutes β€” 0 = no timer)", ) start_btn = gr.Button("πŸš€ Start Challenge", variant="primary", size="lg") status_box = gr.Textbox( label="Status", interactive=False, visible=False, lines=3, ) # ════════════════════════════════════════════════════════════════════ # PAGE 2 β€” Challenge (hidden until pipeline finishes) # ════════════════════════════════════════════════════════════════════ with gr.Column(visible=False) as challenge_page: with gr.Row(elem_classes=["header-row"]): header_md = gr.Markdown("### πŸ› Legacy Code Challenge") timer_html = gr.HTML('<span id="timer-inner" style="font-family:monospace"></span>', elem_id="challenge-timer") with gr.Row(elem_classes=["main-row"]): # ── Left column: tabs ───────────────────────────────────── with gr.Column(scale=3, elem_classes=["left-col"]): with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs: with gr.Tab("πŸ“‹ Challenge", id=0): challenge_readme = gr.Markdown("") with gr.Tab("πŸ’» Code Editor", id=1): file_dropdown = gr.Dropdown( choices=[], label="File", info="Select a file to view. Submit saves to the target file.", ) with gr.Row(): btn_tests = gr.Button("β–Ά Run Tests", variant="secondary") btn_changes = gr.Button("πŸ‘οΈ View My Changes", variant="secondary") save_btn = gr.Button("πŸ’Ύ Save", variant="secondary", elem_id="save-btn") save_status = gr.Markdown("") code_editor = gr.Code( value="", language="python", label="", interactive=True, lines=30, elem_id="code-editor", show_label=False, ) with gr.Tab("πŸ§ͺ Test Results", id=2): run_tests_tab_btn = gr.Button("β–Ά Run Tests", variant="secondary") test_output = gr.HTML( "<p style='color:#888;font-family:monospace;'>Click 'β–Ά Run Tests' to run…</p>" ) with gr.Tab("πŸ‘οΈ My Changes", id=3): gr.Markdown("_Diff: your saved file vs the original buggy code you received_") with gr.Row(): refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary") revert_btn = gr.Button("↩️ Revert to Original", variant="secondary") changes_diff_html = gr.HTML("") # ── Right column: AI assistant + submit ─────────────────── with gr.Column(scale=2, elem_classes=["right-col"]): hint_counter = gr.Markdown(_hint_md(0, 0)) chatbot = gr.Chatbot( label="AI Assistant", elem_id="ai-chatbot", ) with gr.Row(): chat_input = gr.Textbox( placeholder="Ask the AI assistant for a hint…", show_label=False, scale=5, ) send_btn = gr.Button("Send", variant="secondary", scale=1) gr.Markdown("---") submit_btn = gr.Button("πŸš€ Submit Fix", variant="primary") # Live Debug Console (always visible at bottom) gr.Markdown("---") with gr.Accordion("πŸ› Live Debug Console", open=False): live_debug_console = gr.Textbox( label="Real-time Execution Logs", lines=10, max_lines=20, interactive=False, placeholder="Debug logs will appear here during submission...", elem_id="live-debug-console" ) # Hidden trigger for submit (ensures at least 1 UI input) submit_trigger = gr.Number(value=0, visible=False) # ════════════════════════════════════════════════════════════════════ # PAGE 3 β€” Results (hidden until Submit clicked) # ════════════════════════════════════════════════════════════════════ with gr.Column(visible=False) as results_page: gr.Markdown("## πŸ“Š Submission Results") score_summary_html = gr.HTML("") # Use Accordions instead of nested Tabs (more stable for dynamic updates) with gr.Accordion("πŸ§ͺ Test Results", open=True): results_test_html = gr.HTML("") with gr.Accordion("πŸ” Changes & Expected", open=False): results_changes_html = gr.HTML("") with gr.Accordion("οΏ½ Hints Used", open=False): results_hints_html = gr.HTML("") # Debug console (collapsible) with gr.Accordion("πŸ› Debug Console", open=False): debug_console = gr.Textbox( label="Execution Logs", lines=15, max_lines=30, interactive=False, placeholder="Debug logs will appear here...", ) # ── Login callback ──────────────────────────────────────────────── def on_oauth_profile(profile: gr.OAuthProfile | None): identity = _hf_oauth_identity(profile) if identity is None: return gr.update(), gr.update() return ( gr.update(value=identity["display_name"]), f"Signed in to Hugging Face as **@{identity['provider_user_id']}**.", ) def on_login(name, api_key, profile: gr.OAuthProfile | None = None): identity = _hf_oauth_identity(profile) if _hf_auth_required(profile): return ( gr.update(), gr.update(), gr.update(), gr.update(), "❌ Sign in with Hugging Face before continuing.", "", "", ) name = identity["display_name"] if identity else (name or "").strip() if not name: return ( gr.update(), # login page stays gr.update(), # setup page hidden gr.update(), # logout row remains hidden gr.update(), # keep setup name as-is "❌ Please enter your name", "", "" # states empty ) submitted_api_key = (api_key or "").strip() api_key_for_validation = submitted_api_key or _configured_llm_api_key() if not api_key_for_validation: return ( gr.update(), gr.update(), gr.update(), gr.update(), "❌ Enter an API key to continue.", "", "", ) valid, msg = validate_openai_key(api_key_for_validation) if not valid: return ( gr.update(), gr.update(), gr.update(), gr.update(), msg, "", "" ) # Success! return ( gr.update(visible=False), # hide login gr.update(visible=True), # show setup gr.update(visible=True), # show logout row gr.update(value=name), # prefill setup page name "βœ… Logged in!", submitted_api_key, name, ) def on_logout(): """Clear session values and return to the login page.""" return ( gr.update(visible=not has_env_key or HF_OAUTH_REQUIRED), # show login gr.update(visible=has_env_key and not HF_OAUTH_REQUIRED), # hide setup gr.update(visible=False), # hide challenge gr.update(visible=False), # hide results gr.update(visible=False), # hide logout row "", "", "", "", # clear textboxes "", "" # clear states ) # ── Setup callback ───────────────────────────────────────────────── def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, user_name_from_login, user_api_key, profile: gr.OAuthProfile | None = None): if _hf_auth_required(profile): yield ( gr.update(visible=True, value="❌ Sign in with Hugging Face before starting a challenge."), gr.update(interactive=True), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ) return logger.info(f"=== START CHALLENGE ===") logger.info(f"User: {user_name_from_login or name}") logger.info(f"URL: {url}") logger.info(f"Nesting: {nesting_lvl}, Bugs: {num_bugs}, Refactoring: {refactoring}, Debug: {debug}") nesting = int(nesting_lvl) # Use login name if available, otherwise name from setup form name_str = user_name_from_login.strip() if user_name_from_login else name.strip() if not user_api_key and not _configured_llm_api_key(): logger.warning("No user_api_key provided!") logger.info("Yielding loading message...") yield ( gr.update(visible=True, value="⏳ Cloning repository and generating challenge…" " this may take 1–2 minutes."), gr.update(interactive=False), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ) try: logger.info(f"Starting pipeline for {url.strip()}") with llm_api_key_context(user_api_key or None): workspace_path = _run_pipeline(url.strip(), nesting, int(num_bugs), refactoring, debug) logger.info(f"Pipeline completed. Workspace: {workspace_path}") cs = ChallengeState(workspace_path) py_files = cs.list_py_files() default = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else "") suffix = f" &nbsp;|&nbsp; {name_str}" if name_str else "" logger.info(f"Challenge ready! Target file: {cs.target_file}, {len(py_files)} Python files") yield ( gr.update(visible=False), gr.update(interactive=True), gr.update(visible=False), gr.update(visible=True), gr.update(value=f"### πŸ› Legacy Code Challenge{suffix}"), gr.update(value=cs.readme()), gr.update(choices=py_files, value=default), gr.update(value=cs.read_target(), label=cs.target_file, interactive=True), workspace_path, int(timer_mins), ) except Exception as exc: logger.error(f"Pipeline failed: {exc}", exc_info=True) error_msg = str(exc) # Provide user-friendly error messages if "verify_sabotage" in error_msg and "crashed" in error_msg: user_message = ( "❌ Challenge generation failed: The bugs introduced caused all tests to crash.\n\n" "πŸ’‘ **Suggestions:**\n" "β€’ Try reducing the number of bugs (use 1-2 instead of 3)\n" "β€’ Try a different repository with simpler code\n" "β€’ Enable 'Debug Mode' to see detailed logs\n\n" f"Technical details: {error_msg}" ) elif "clone" in error_msg.lower(): user_message = ( "❌ Failed to clone repository.\n\n" "πŸ’‘ **Check:**\n" "β€’ Is the URL correct?\n" "β€’ Is the repository public?\n\n" f"Details: {error_msg}" ) else: user_message = f"❌ Error: {error_msg}\n\nπŸ’‘ Try enabling 'Debug Mode' for more details." yield ( gr.update(visible=True, value=user_message), gr.update(interactive=True), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), ) # ── Wiring for login ────────────────────────────────────────────── demo.load( on_oauth_profile, inputs=None, outputs=[login_name, login_status], ) login_btn.click( on_login, inputs=[login_name, login_api_key], outputs=[ login_page, setup_page, logout_row, name_box, login_status, user_api_key_state, user_name_state ] ) logout_btn.click( on_logout, outputs=[ login_page, setup_page, challenge_page, results_page, logout_row, login_name, login_api_key, name_box, url_box, user_api_key_state, user_name_state ] ) start_btn.click( on_start, inputs=[name_box, url_box, nesting_slider, bugs_slider, refactoring_check, debug_check, timer_slider, user_name_state, user_api_key_state], outputs=[ status_box, start_btn, setup_page, challenge_page, header_md, challenge_readme, file_dropdown, code_editor, workspace_state, timer_trigger, ], ) timer_trigger.change( fn=None, inputs=[timer_trigger], js="(n) => { window.startTimer && window.startTimer(n); return n; }", outputs=[timer_trigger], ) # ── Challenge callbacks ──────────────────────────────────────────── def on_file_select(rel_path, workspace_path): if not workspace_path: return gr.update() cs = ChallengeState(workspace_path) content = cs.read_py_file(rel_path) return gr.update(value=content, interactive=True, label=rel_path) def on_save(code, rel_path, workspace_path): if not workspace_path: return "⚠️ No challenge loaded." cs = ChallengeState(workspace_path) if rel_path: cs.write_py_file(rel_path, code) else: cs.write_target(code) return "βœ… Saved" def on_run_tests(code, rel_path, workspace_path): loading = '<p style="text-align:center;padding:20px;color:#888;">⏳ Running tests…</p>' yield (gr.update(selected=2), loading) if not workspace_path: yield (gr.update(selected=2), "<p style='color:#888'>No challenge loaded.</p>") return # Auto-save before running tests cs_temp = ChallengeState(workspace_path) if rel_path: cs_temp.write_py_file(rel_path, code) else: cs_temp.write_target(code) try: from orchestrator.scoring import run_tests r = run_tests(workspace_path) raw = r["output"] if r["output"] else "No output." yield (gr.update(selected=2), _colorise_test_output(raw)) except Exception as exc: yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>❌ Error: {exc}</p>") def on_show_changes(code, rel_path, workspace_path): if not workspace_path: diff = "<p style='color:#888'>No challenge loaded.</p>" else: try: # Save code from editor, then read from disk for comparison # (Gradio code_editor doesn't always pass updated content reliably) cs = ChallengeState(workspace_path) if rel_path: cs.write_py_file(rel_path, code) else: cs.write_target(code) diff = _workspace_diff_html(cs) except Exception as e: diff = f"<p style='color:#ef4444;'>Error generating diff: {str(e)[:200]}</p>" return (gr.update(selected=3), diff) def on_revert(workspace_path): if not workspace_path: return gr.update(), gr.update(selected=1) cs = ChallengeState(workspace_path) cs.reset_target() return cs.sabotaged_code, gr.update(selected=1) def on_submit(trigger, hints_used, submit_count, workspace_path, chat_log, hint_log, user_name, code, rel_path, user_api_key, profile: gr.OAuthProfile | None = None): if _hf_auth_required(profile): message = "❌ Sign in with Hugging Face before submitting." yield ( gr.update(visible=True), gr.update(visible=False), message, "", "", "", submit_count, "", message, ) return logger.info(f"=== SUBMIT CHALLENGE ===") logger.info(f"Trigger: {trigger}, User: {user_name}, Hints: {hints_used}, Submit#: {submit_count}") logger.info(f"Workspace: {workspace_path}") # First yield IMMEDIATELY: Hide challenge, show results with loading _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">⏳ Running tests…</p>' yield ( gr.update(visible=False), # Hide challenge page gr.update(visible=True), # Show results page _loading, "", "", "", # Show loading message in results area submit_count, "", # debug console "Starting submission evaluation...", # live debug ) # Capture all print statements for debug console log_capture = StringIO() original_stdout = sys.stdout try: sys.stdout = log_capture if not workspace_path: sys.stdout = original_stdout yield (gr.update(visible=False), gr.update(visible=True), "No challenge loaded.", "", "", "", submit_count, log_capture.getvalue(), "❌ No workspace loaded") return print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸš€ Starting submission evaluation...") cs = ChallengeState(workspace_path) log = SubmissionLog(cs.workspace) if rel_path: cs.write_py_file(rel_path, code) print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“– Reading submitted code...") submitted_code = cs.read_target() print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ§ͺ Running tests...") with llm_api_key_context(user_api_key or None): result = evaluate_submission( workspace_path=workspace_path, student_code=submitted_code, original_code=cs.original_code, bug_func_name=cs.bug_func_name, hints_used=hints_used, sabotaged_code=cs.sabotaged_code, target_file=str(cs.target_path), bug_func_names=cs.bug_func_names, ) new_count = submit_count + 1 print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“Š Generating results...") score_html = _score_summary_html(result) combined_diff = _combined_changes_html(cs, submitted_code) test_html = _colorise_test_output(result["test_output"] or "No test output.") hints_html = _hints_html(hint_log or []) print(f"[{datetime.now().strftime('%H:%M:%S')}] βœ… Results ready, returning to user...") # Get all captured logs debug_logs = log_capture.getvalue() print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ’Ύ Saving submission...") submission_record = _build_submission_record( cs=cs, student_name=user_name, submitted_code=submitted_code, result=result, hints_used=hints_used, chat_log=chat_log or [], hint_log=hint_log or [], attempt_number=new_count, debug_logs=debug_logs, enable_cloud_uploads=True, identity=_hf_oauth_identity(profile), ) log_path = log.save(submission_record) supabase_result = _save_submission_to_supabase(log, log_path, submission_record) if supabase_result["status"] != "success": debug_logs += f"\n\nSupabase storage {supabase_result['status']}: {supabase_result['error']}" log.update(log_path, {"debug": {"captured_logs": debug_logs}}) sys.stdout = original_stdout # Restore stdout # Return results to user IMMEDIATELY yield ( gr.update(visible=False), # Hide challenge page gr.update(visible=True), # Show results page score_html, combined_diff, test_html, hints_html, new_count, debug_logs, debug_logs, # live debug (same) ) # Google Sheets remains an optional summary destination. def _background_upload(): student_name = user_name.strip() if user_name else "Anonymous" cloud_updates = {} cloud_caps = _cloud_upload_capabilities() logger.info( "Cloud upload capabilities: google available=%s configured=%s, Supabase status=%s", cloud_caps["google_sheets"]["available"], cloud_caps["google_sheets"]["configured"], supabase_result["status"], ) # Google Sheets (fast summary) if cloud_caps["google_sheets"]["available"] and cloud_caps["google_sheets"]["configured"]: try: print("πŸ“Š Uploading to Google Sheets...") sheets_ok = log_to_google_sheets( student_name=student_name, repo_url=cs.github_url, hints_used=hints_used, score=result["total_score"], total_tests=result["total_tests"], passed_tests=result["passed"], all_passed=result["all_passed"], chat_history=chat_log or [], submission_record=submission_record, ) if sheets_ok: print(f"βœ… Logged to Google Sheets: {student_name}") cloud_updates["google_sheets"] = {"status": "success", "error": ""} else: diag = diagnose_google_sheets() reason = diag.get("reason", "Logger returned False") print(f"⚠️ Google Sheets logging returned False: {reason}") cloud_updates["google_sheets"] = {"status": "failed", "error": reason} except Exception as e: print(f"⚠️ Google Sheets logging failed: {e}") cloud_updates["google_sheets"] = {"status": "failed", "error": str(e)} else: reason = str(cloud_caps["google_sheets"]["reason"]) logger.warning("Google Sheets upload disabled: %s", reason) cloud_updates["google_sheets"] = {"status": "disabled", "error": reason} log.update(log_path, {"cloud": cloud_updates}) # Start background upload (won't block UI) upload_thread = threading.Thread(target=_background_upload, daemon=True) upload_thread.start() except Exception as exc: import traceback error_details = traceback.format_exc() debug_logs = log_capture.getvalue() + f"\n\n❌ ERROR:\n{error_details}" sys.stdout = original_stdout # Restore stdout err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>❌ Error during evaluation:<br>{exc}</p>" yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs, debug_logs) finally: sys.stdout = original_stdout # Always restore stdout def on_send(message, history, hints_used, submit_count, workspace_path, chat_log, hint_log, confirmation_pending, user_api_key, profile: gr.OAuthProfile | None = None): if _hf_auth_required(profile): response = "Please sign in with Hugging Face before using the assistant." history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": response}, ] return history, "", hints_used, _hint_md(hints_used, 0), chat_log, hint_log, confirmation_pending if not message.strip(): penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)] return history, "", hints_used, _hint_md(hints_used, penalty), chat_log, hint_log, confirmation_pending if not workspace_path: history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": "No challenge loaded yet."}, ] new_chat_log = list(chat_log or []) new_chat_log.append({ "question": message, "response": "No challenge loaded yet.", "gave_hint": False, "hint_summary": "", }) return history, "", hints_used, _hint_md(hints_used, 0), new_chat_log, hint_log, False cs = ChallengeState(workspace_path) with llm_api_key_context(user_api_key or None): result = get_hint( user_message=message, history=history, hints_used=hints_used, submission_attempts=submit_count, challenge_info=cs.challenge_info(), ) # Python-level guarantee: if a confirmation was pending and the student # didn't explicitly decline, the hint counts β€” regardless of LLM marker. accepted_pending = confirmation_pending and _is_affirmation(message) gave_hint = result["gave_hint"] or accepted_pending new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"]) history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": result["response"]}, ] new_chat_log = list(chat_log or []) new_chat_log.append({ "question": message, "response": result["response"], "gave_hint": gave_hint, "hint_summary": result.get("hint_summary", ""), }) new_hints = hints_used + (1 if gave_hint else 0) penalty = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)] new_log = list(hint_log or []) if gave_hint: new_log.append({ "question": message, "response": result["response"], "hint_summary": result.get("hint_summary", ""), "summary": result.get("hint_summary", ""), }) return history, "", new_hints, _hint_md(new_hints, penalty), new_chat_log, new_log, new_confirmation_pending # ── Wiring ──────────────────────────────────────────────────────── file_dropdown.change( on_file_select, inputs=[file_dropdown, workspace_state], outputs=[code_editor], ) save_btn.click(on_save, inputs=[code_editor, file_dropdown, workspace_state], outputs=[save_status]) btn_tests.click(on_run_tests, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, test_output]) run_tests_tab_btn.click(on_run_tests, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, test_output]) btn_changes.click(on_show_changes, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, changes_diff_html]) refresh_btn.click(on_show_changes, inputs=[code_editor, file_dropdown, workspace_state], outputs=[left_tabs, changes_diff_html]) revert_btn.click(on_revert, inputs=[workspace_state], outputs=[code_editor, left_tabs]) submit_btn.click( on_submit, inputs=[submit_trigger, hints_used_state, submission_count_state, workspace_state, chat_log_state, hint_log_state, user_name_state, code_editor, file_dropdown, user_api_key_state], outputs=[ challenge_page, # Hide challenge page results_page, # Show results page score_summary_html, results_changes_html, results_test_html, results_hints_html, submission_count_state, debug_console, live_debug_console, ], ) send_btn.click( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, chat_log_state, hint_log_state, confirmation_pending_state, user_api_key_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state], ) chat_input.submit( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, workspace_state, chat_log_state, hint_log_state, confirmation_pending_state, user_api_key_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state], ) # CRITICAL: Enable queue for generator functions to work on production servers # max_size: Maximum queue size to prevent overflow # default_concurrency_limit: Number of requests processed in parallel demo.queue(max_size=20, default_concurrency_limit=10) return demo # ── Legacy entry point (used by challenge.py CLI path) ─────────────────────── def create_interface(workspace_path: str, student_name: str = "", timer_minutes: int = 0) -> gr.Blocks: """Build the challenge-only interface for a pre-existing workspace.""" cs = ChallengeState(workspace_path) log = SubmissionLog(cs.workspace) py_files = cs.list_py_files() default_file = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else None) name_suffix = f" &nbsp;|&nbsp; {student_name.strip()}" if student_name.strip() else "" css = """ #code-editor { font-size: 14px !important; font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important; background-color: #1e1e1e !important; border-radius: 8px !important; } #code-editor .codemirror-wrapper { background-color: #1e1e1e !important; } #code-editor .cm-editor { background-color: #1e1e1e !important; } """ # Note: CSS parameter moved to launch() in Gradio 6.0, removed for compatibility with gr.Blocks(title="Legacy Code Challenge", js=_make_js(timer_minutes)) as demo: hints_used_state = gr.State(0) submission_count_state = gr.State(0) chat_log_state = gr.State([]) hint_log_state = gr.State([]) confirmation_pending_state = gr.State(False) with gr.Row(elem_classes=["header-row"]): gr.Markdown( f"### πŸ› Legacy Code Challenge{name_suffix}", elem_classes=["app-header"], ) gr.HTML('<span id="timer-inner"></span>', elem_id="challenge-timer") # ── Challenge page ──────────────────────────────────────────────── with gr.Column(visible=True) as challenge_col: with gr.Row(elem_classes=["main-row"]): with gr.Column(scale=3, elem_classes=["left-col"]): with gr.Tabs(selected=0, elem_classes=["left-tabs"]) as left_tabs: with gr.Tab("πŸ“‹ Challenge", id=0): gr.Markdown(cs.readme()) with gr.Tab("πŸ’» Code Editor", id=1): file_dropdown = gr.Dropdown( choices=py_files, value=default_file, label="File", info="Select a file to view. Submit saves to the target file.", ) with gr.Row(): btn_tests = gr.Button("β–Ά Run Tests", variant="secondary") btn_changes = gr.Button("πŸ‘οΈ View My Changes", variant="secondary") save_btn = gr.Button("πŸ’Ύ Save", variant="secondary", elem_id="save-btn") save_status = gr.Markdown("") code_editor = gr.Code( value=cs.read_target(), language="python", label=cs.target_file, interactive=True, lines=30, elem_id="code-editor", show_label=False, ) with gr.Tab("πŸ§ͺ Test Results", id=2): run_tests_tab_btn = gr.Button("β–Ά Run Tests", variant="secondary") test_output = gr.HTML( "<p style='color:#888;font-family:monospace;'>Click 'β–Ά Run Tests' to run…</p>" ) with gr.Tab("πŸ‘οΈ My Changes", id=3): gr.Markdown("_Diff: your saved file vs the original buggy code you received_") with gr.Row(): refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary") revert_btn = gr.Button("↩️ Revert to Original", variant="secondary") changes_diff_html = gr.HTML("") with gr.Column(scale=2, elem_classes=["right-col"]): hint_counter = gr.Markdown(_hint_md(0, 0)) chatbot = gr.Chatbot( label="AI Assistant", elem_id="ai-chatbot", ) with gr.Row(): chat_input = gr.Textbox( placeholder="Ask the AI assistant for a hint…", show_label=False, scale=5, ) send_btn = gr.Button("Send", variant="secondary", scale=1) gr.Markdown("---") submit_btn = gr.Button("πŸš€ Submit Fix", variant="primary") # ── Results page ────────────────────────────────────────────────── with gr.Column(visible=False) as results_col: gr.Markdown("## πŸ“Š Submission Results") score_summary_html = gr.HTML("") with gr.Tabs(): with gr.Tab("πŸ§ͺ Test Results"): results_test_html = gr.HTML("") with gr.Tab("πŸ” Changes & Expected"): results_changes_html = gr.HTML("") with gr.Tab("πŸ’‘ Hints Used"): results_hints_html = gr.HTML("") # Debug console (collapsible) with gr.Accordion("πŸ› Debug Console", open=False): debug_console_standalone = gr.Textbox( label="Execution Logs", lines=15, max_lines=30, interactive=False, placeholder="Debug logs will appear here...", ) # ── Callbacks ───────────────────────────────────────────────────── def on_file_select(rel_path): content = cs.read_py_file(rel_path) return gr.update(value=content, interactive=True, label=rel_path) def on_save(code, rel_path): if rel_path: cs.write_py_file(rel_path, code) else: cs.write_target(code) return "βœ… Saved" def on_run_tests(code, rel_path): loading = '<p style="text-align:center;padding:20px;color:#888;">⏳ Running tests…</p>' yield (gr.update(selected=2), loading) # Auto-save before running tests if rel_path: cs.write_py_file(rel_path, code) else: cs.write_target(code) try: from orchestrator.scoring import run_tests r = run_tests(workspace_path) raw = r["output"] if r["output"] else "No output." yield (gr.update(selected=2), _colorise_test_output(raw)) except Exception as exc: yield (gr.update(selected=2), f"<p style='color:#ef4444;font-family:monospace;'>❌ Error: {exc}</p>") def on_show_changes(): # Read directly from disk (Gradio code_editor doesn't update its value reliably) diff = _workspace_diff_html(cs) return (gr.update(selected=3), diff) def on_revert(): cs.reset_target() return cs.sabotaged_code, gr.update(selected=1) def on_submit(hints_used, submit_count, chat_log, hint_log, code, rel_path): # Capture all print statements for debug console log_capture = StringIO() original_stdout = sys.stdout sys.stdout = log_capture try: _loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">⏳ Running tests…</p>' sys.stdout = original_stdout # Restore for yield yield ( gr.update(visible=False), gr.update(visible=True), _loading, "", "", "", submit_count, "", # debug console ) sys.stdout = log_capture # Capture again print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸš€ Starting submission evaluation (standalone mode)...") if rel_path: cs.write_py_file(rel_path, code) print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“– Reading submitted code...") submitted_code = cs.read_target() print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ§ͺ Running tests...") result = evaluate_submission( workspace_path=workspace_path, student_code=submitted_code, original_code=cs.original_code, bug_func_name=cs.bug_func_name, hints_used=hints_used, sabotaged_code=cs.sabotaged_code, target_file=str(cs.target_path), bug_func_names=cs.bug_func_names, ) new_count = submit_count + 1 print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ“Š Generating results...") score_html = _score_summary_html(result) combined_diff = _combined_changes_html(cs, submitted_code) test_html = _colorise_test_output(result["test_output"] or "No test output.") hints_html = _hints_html(hint_log or []) print(f"[{datetime.now().strftime('%H:%M:%S')}] βœ… Results ready, returning to user...") # Get all captured logs debug_logs = log_capture.getvalue() print(f"[{datetime.now().strftime('%H:%M:%S')}] πŸ’Ύ Saving submission...") submission_record = _build_submission_record( cs=cs, student_name="Anonymous (standalone mode)", submitted_code=submitted_code, result=result, hints_used=hints_used, chat_log=chat_log or [], hint_log=hint_log or [], attempt_number=new_count, debug_logs=debug_logs, enable_cloud_uploads=False, ) log_path = log.save(submission_record) supabase_result = _save_submission_to_supabase(log, log_path, submission_record) if supabase_result["status"] != "success": debug_logs += f"\n\nSupabase storage {supabase_result['status']}: {supabase_result['error']}" log.update(log_path, {"debug": {"captured_logs": debug_logs}}) sys.stdout = original_stdout # Restore stdout # Return results to user IMMEDIATELY yield ( gr.update(visible=False), gr.update(visible=True), score_html, combined_diff, test_html, hints_html, new_count, debug_logs, ) except Exception as exc: import traceback error_details = traceback.format_exc() debug_logs = log_capture.getvalue() + f"\n\n❌ ERROR:\n{error_details}" sys.stdout = original_stdout # Restore stdout err = f"<p style='color:#ef4444;padding:20px;font-family:monospace;'>❌ Error during evaluation:<br>{exc}</p>" yield (gr.update(visible=False), gr.update(visible=True), err, "", "", "", submit_count, debug_logs) finally: sys.stdout = original_stdout # Always restore stdout def on_send(message, history, hints_used, submit_count, chat_log, hint_log, confirmation_pending): if not message.strip(): penalty = PENALTY_TABLE[min(hints_used, len(PENALTY_TABLE) - 1)] return history, "", hints_used, _hint_md(hints_used, penalty), chat_log, hint_log, confirmation_pending result = get_hint( user_message=message, history=history, hints_used=hints_used, submission_attempts=submit_count, challenge_info=cs.challenge_info(), ) # Python-level guarantee: if a confirmation was pending and the student # didn't explicitly decline, the hint counts β€” regardless of LLM marker. accepted_pending = confirmation_pending and _is_affirmation(message) gave_hint = result["gave_hint"] or accepted_pending new_confirmation_pending = not gave_hint and _is_confirmation_question(result["response"]) history = list(history or []) + [ {"role": "user", "content": message}, {"role": "assistant", "content": result["response"]}, ] new_chat_log = list(chat_log or []) new_chat_log.append({ "question": message, "response": result["response"], "gave_hint": gave_hint, "hint_summary": result.get("hint_summary", ""), }) new_hints = hints_used + (1 if gave_hint else 0) penalty = PENALTY_TABLE[min(new_hints, len(PENALTY_TABLE) - 1)] new_log = list(hint_log or []) if gave_hint: new_log.append({ "question": message, "response": result["response"], "hint_summary": result.get("hint_summary", ""), "summary": result.get("hint_summary", ""), }) return history, "", new_hints, _hint_md(new_hints, penalty), new_chat_log, new_log, new_confirmation_pending # ── Wiring ──────────────────────────────────────────────────────── file_dropdown.change(on_file_select, inputs=[file_dropdown], outputs=[code_editor]) save_btn.click(on_save, inputs=[code_editor, file_dropdown], outputs=[save_status]) btn_tests.click(on_run_tests, inputs=[code_editor, file_dropdown], outputs=[left_tabs, test_output]) run_tests_tab_btn.click(on_run_tests, inputs=[code_editor, file_dropdown], outputs=[left_tabs, test_output]) btn_changes.click(on_show_changes, outputs=[left_tabs, changes_diff_html]) refresh_btn.click(on_show_changes, outputs=[left_tabs, changes_diff_html]) revert_btn.click(on_revert, outputs=[code_editor, left_tabs]) submit_btn.click( on_submit, inputs=[hints_used_state, submission_count_state, chat_log_state, hint_log_state, code_editor, file_dropdown], outputs=[ challenge_col, results_col, score_summary_html, results_changes_html, results_test_html, results_hints_html, submission_count_state, debug_console_standalone, ], ) send_btn.click( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, chat_log_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state], ) chat_input.submit( on_send, inputs=[chat_input, chatbot, hints_used_state, submission_count_state, chat_log_state, hint_log_state, confirmation_pending_state], outputs=[chatbot, chat_input, hints_used_state, hint_counter, chat_log_state, hint_log_state, confirmation_pending_state], ) # CRITICAL: Enable queue for generator functions to work on production servers # max_size: Maximum queue size | default_concurrency_limit: Parallel requests demo.queue(max_size=20, default_concurrency_limit=10) return demo # Create the demo instance for app.py to import demo = create_full_interface() if __name__ == "__main__": demo.launch()
"""
Student Interface β€” Gradio GUI for the Legacy Code Challenge.
Two-page flow:
Page 1 (Setup): student name, GitHub URL, nesting level, num-bugs, options β†’ Start
Page 2 (Challenge): README, Code Editor, Test runner + AI Assistant sidebar
Page 3 (Results): Score breakdown, diffs, test results, hints review
"""
from __future__ import annotations
import difflib
import json
import os
import sys
import threading
import logging
from io import StringIO
from datetime import datetime
from pathlib import Path
import gradio as gr
# Configure detailed logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler('app.log', encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
from orchestrator.scoring import evaluate_submission
from orchestrator.hint_graph import get_hint
# Optional Google Sheets logging
try:
from google_sheets_logger import diagnose_google_sheets, log_to_google_sheets
GOOGLE_SHEETS_AVAILABLE = True
except ImportError:
GOOGLE_SHEETS_AVAILABLE = False
try:
from supabase_submissions_logger import upload_submission_to_supabase
SUPABASE_AVAILABLE = True
except ImportError:
SUPABASE_AVAILABLE = False
# ── API Key Validation ────────────────────────────────────────────────────────
from llm_config import llm_api_key_context, validate_api_key as validate_openai_key
HF_OAUTH_REQUIRED = bool(os.getenv("SPACE_ID"))
def _configured_llm_api_key() -> str:
provider = os.getenv("LLM_PROVIDER", "openai").lower()
env_var = "GROQ_API_KEY" if provider == "groq" else "OPENAI_API_KEY"
return os.getenv(env_var, "")
def _hf_oauth_identity(profile: gr.OAuthProfile | None) -> dict | None:
if profile is None:
return None
username = str(profile.username or "").strip()
if not username:
return None
return {
"provider": "huggingface",
"provider_user_id": username,
"profile_url": str(profile.profile or ""),
"display_name": str(profile.name or username).strip(),
}
def _hf_auth_required(profile: gr.OAuthProfile | None) -> bool:
return HF_OAUTH_REQUIRED and _hf_oauth_identity(profile) is None
def _google_sheets_configured() -> bool:
return bool(os.getenv("GOOGLE_SHEET_ID")) and (
bool(os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON"))
or Path("google-service-account.json").exists()
)
def _supabase_configured() -> bool:
return bool(os.getenv("SUPABASE_URL")) and bool(
os.getenv("SUPABASE_SECRET_KEY") or os.getenv("SUPABASE_SERVICE_ROLE_KEY")
)
def _cloud_upload_capabilities() -> dict[str, dict[str, str | bool]]:
google_configured = _google_sheets_configured()
supabase_configured = _supabase_configured()
return {
"google_sheets": {