Spaces:
Sleeping
Sleeping
Add public challenge catalog and private publishing
Browse filesFiles changed (9)
68 unmodified lines697071727374149 unmodified lines224225226227228229230231232233234235824 unmodified lines10601061106210631064106510661067106824 unmodified lines10931094109510961097109820 unmodified lines11191120112111221123112463 unmodified lines11881189119011911192119311941195119611971198119912001201120212031204120512062 unmodified lines120912101211121212131214121510 unmodified lines12261227122812291230123168 unmodified linesChallengeRoundStoreError,admit_challenge_round,get_challenge_round_publisher,save_challenge_round,transition_challenge_round,update_challenge_round_settings,149 unmodified linesclass ChallengeRoundPublishRequest(BaseModel):time_limit_enabled: bool | None = Nonetimer_minutes: int | None = Field(default=None, ge=0, le=120, strict=True)chat_messages_per_student: int = Field(default=DEFAULT_CHAT_MESSAGE_LIMIT, ge=0, le=MAX_CHAT_MESSAGE_LIMIT, strict=True)class ChallengeRoundSettingsRequest(BaseModel):time_limit_enabled: booltimer_minutes: int = Field(ge=0, le=120, strict=True)chat_messages_per_student: int = Field(ge=0, le=MAX_CHAT_MESSAGE_LIMIT, strict=True)824 unmodified linesdef publish_challenge_round(request: Request,payload: ChallengeRoundPublishRequest = Body(default=ChallengeRoundPublishRequest()),session: UserSession = Depends(require_instructor),) -> dict[str, str | int]:_verify_origin(request)if not session.workspace_path:raise HTTPException(status_code=409, detail="Start a challenge before publishing a round")_require_round_creator(session)24 unmodified linestime_limit_enabled=timer_minutes > 0,timer_minutes=timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)20 unmodified linesdetail = str(exc) if isinstance(exc, ChallengeRoundStoreError) else "Could not package this challenge for persistent storage"raise HTTPException(status_code=503, detail=detail) from excmanifest.pop("quota_units_per_student", None)manifest["persistence"] = "supabase"manifest["status"] = "prepared"manifest["course_id"] = _course_id()63 unmodified linesreturn actor@app.post("/api/challenge-rounds/{round_id}/open")def open_challenge_round(round_id: str,session: UserSession = Depends(require_instructor),) -> dict[str, Any]:return _transition_round(round_id, "open", session)@app.post("/api/challenge-rounds/{round_id}/close")def close_challenge_round(round_id: str,session: UserSession = Depends(require_instructor),) -> dict[str, Any]:return _transition_round(round_id, "close", session)2 unmodified linesround_id: str,payload: ChallengeRoundSettingsRequest,request: Request,session: UserSession = Depends(require_instructor),) -> dict[str, Any]:_verify_origin(request)actor = _require_round_publisher(round_id, session)10 unmodified linestime_limit_enabled=payload.time_limit_enabled,timer_minutes=payload.timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)68 unmodified lines6970717273747576149 unmodified lines226227228229230231232233234235236237238239824 unmodified lines1064106510661067106810691070107110721073107424 unmodified lines109911001101110211031104110520 unmodified lines112611271128112911301131113263 unmodified lines11961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512262 unmodified lines122912301231123212331234123510 unmodified lines124612471248124912501251125268 unmodified linesChallengeRoundStoreError,admit_challenge_round,get_challenge_round_publisher,get_public_challenge_rounds,claim_public_challenge_submission,save_challenge_round,transition_challenge_round,update_challenge_round_settings,149 unmodified linesclass ChallengeRoundPublishRequest(BaseModel):visibility: str = Field(default="private", pattern="^(private|public)$")time_limit_enabled: bool | None = Nonetimer_minutes: int | None = Field(default=None, ge=0, le=120, strict=True)chat_messages_per_student: int = Field(default=DEFAULT_CHAT_MESSAGE_LIMIT, ge=0, le=MAX_CHAT_MESSAGE_LIMIT, strict=True)class ChallengeRoundSettingsRequest(BaseModel):visibility: str = Field(default="private", pattern="^(private|public)$")time_limit_enabled: booltimer_minutes: int = Field(ge=0, le=120, strict=True)chat_messages_per_student: int = Field(ge=0, le=MAX_CHAT_MESSAGE_LIMIT, strict=True)824 unmodified linesdef publish_challenge_round(request: Request,payload: ChallengeRoundPublishRequest = Body(default=ChallengeRoundPublishRequest()),session: UserSession = Depends(require_session),) -> dict[str, str | int]:_verify_origin(request)if payload.visibility == "private" and not _is_course_instructor(session.identity):raise HTTPException(status_code=403, detail="Private challenges can be published only by an instructor")if not session.workspace_path:raise HTTPException(status_code=409, detail="Start a challenge before publishing a round")_require_round_creator(session)24 unmodified linestime_limit_enabled=timer_minutes > 0,timer_minutes=timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,visibility=payload.visibility,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)20 unmodified linesdetail = str(exc) if isinstance(exc, ChallengeRoundStoreError) else "Could not package this challenge for persistent storage"raise HTTPException(status_code=503, detail=detail) from excmanifest.pop("quota_units_per_student", None)manifest["visibility"] = payload.visibilitymanifest["persistence"] = "supabase"manifest["status"] = "prepared"manifest["course_id"] = _course_id()63 unmodified linesreturn actor@app.get("/api/challenge-rounds/public")def list_public_challenge_rounds(session: UserSession = Depends(require_session)) -> dict[str, Any]:try:rounds = get_public_challenge_rounds(_course_id())except ChallengeRoundStoreError as exc:logger.warning("Public challenge catalog lookup failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Public challenges are temporarily unavailable") from excreturn {"rounds": rounds}@app.post("/api/challenge-rounds/{round_id}/open")def open_challenge_round(round_id: str,session: UserSession = Depends(require_session),) -> dict[str, Any]:_require_round_publisher(round_id, session)return _transition_round(round_id, "open", session)@app.post("/api/challenge-rounds/{round_id}/close")def close_challenge_round(round_id: str,session: UserSession = Depends(require_session),) -> dict[str, Any]:_require_round_publisher(round_id, session)return _transition_round(round_id, "close", session)2 unmodified linesround_id: str,payload: ChallengeRoundSettingsRequest,request: Request,session: UserSession = Depends(require_session),) -> dict[str, Any]:_verify_origin(request)actor = _require_round_publisher(round_id, session)10 unmodified linestime_limit_enabled=payload.time_limit_enabled,timer_minutes=payload.timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,visibility=payload.visibility,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)
847 unmodified lines84884985085185285385485538 unmodified lines894895896897898899900309 unmodified lines121012111212121312141215121618 unmodified lines1235123612371238123912401241105 unmodified lines1347134813491350135113521353177 unmodified lines153115321533153415351536847 unmodified linesself.assertEqual(saved_manifests[0]["chat_messages_per_student"], 35)with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "open"}):opened = self.client.post(f"/api/challenge-rounds/{round_info['round_id']}/open")self.assertEqual(opened.status_code, 200)self.assertEqual(opened.json()["status"], "open")38 unmodified linesdef test_students_cannot_transition_shared_rounds(self):self.add_session()with patch.object(api, "transition_challenge_round") as transition:opened = self.client.post(f"/api/challenge-rounds/{uuid4()}/open")closed = self.client.post(f"/api/challenge-rounds/{uuid4()}/close")publish = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": 5})309 unmodified linesself.assertEqual(prepared.status_code, 200)self.assertEqual(prepared.json()["status"], "prepared")with patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "open"}):opened = self.client.post(f"/api/challenge-rounds/{round_id}/open")self.assertEqual(opened.json()["status"], "open")18 unmodified linesself.assertEqual(job["result"]["challenge_round_id"], round_id)self.client.cookies.set(api.SESSION_COOKIE, instructor.session_id)with patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "closed"}):closed = self.client.post(f"/api/challenge-rounds/{round_id}/close")self.assertEqual(closed.json()["status"], "closed")105 unmodified lines}, clear=False), patch.object(api, "create_challenge_round", side_effect=fake_create_round), patch.object(api, "create_challenge_round_archive", return_value=b"round snapshot"), patch.object(api, "save_challenge_round"), patch.object(api, "transition_challenge_round", side_effect=fake_transition), patch.object(api, "admit_challenge_round", side_effect=fake_admit), patch.object(api, "create_challenge_from_round", side_effect=fake_join_round), patch.object(177 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=8,)def test_timed_round_requires_a_positive_duration(self):847 unmodified lines84884985085185285385485538 unmodified lines894895896897898899900309 unmodified lines121012111212121312141215121618 unmodified lines1235123612371238123912401241105 unmodified lines13471348134913501351135213531354177 unmodified lines1532153315341535153615371538847 unmodified linesself.assertEqual(saved_manifests[0]["chat_messages_per_student"], 35)with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "get_challenge_round_publisher", return_value="development:test-user"), patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "open"}):opened = self.client.post(f"/api/challenge-rounds/{round_info['round_id']}/open")self.assertEqual(opened.status_code, 200)self.assertEqual(opened.json()["status"], "open")38 unmodified linesdef test_students_cannot_transition_shared_rounds(self):self.add_session()with patch.object(api, "get_challenge_round_publisher", return_value="development:another-user"), patch.object(api, "transition_challenge_round") as transition:opened = self.client.post(f"/api/challenge-rounds/{uuid4()}/open")closed = self.client.post(f"/api/challenge-rounds/{uuid4()}/close")publish = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": 5})309 unmodified linesself.assertEqual(prepared.status_code, 200)self.assertEqual(prepared.json()["status"], "prepared")with patch.object(api, "get_challenge_round_publisher", return_value="huggingface:teacher-1"), patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "open"}):opened = self.client.post(f"/api/challenge-rounds/{round_id}/open")self.assertEqual(opened.json()["status"], "open")18 unmodified linesself.assertEqual(job["result"]["challenge_round_id"], round_id)self.client.cookies.set(api.SESSION_COOKIE, instructor.session_id)with patch.object(api, "get_challenge_round_publisher", return_value="huggingface:teacher-1"), patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "closed"}):closed = self.client.post(f"/api/challenge-rounds/{round_id}/close")self.assertEqual(closed.json()["status"], "closed")105 unmodified lines}, clear=False), patch.object(api, "create_challenge_round", side_effect=fake_create_round), patch.object(api, "create_challenge_round_archive", return_value=b"round snapshot"), patch.object(api, "save_challenge_round"), patch.object(api, "get_challenge_round_publisher", side_effect=lambda round_id, course_id: workspace_owners[round_id]), patch.object(api, "transition_challenge_round", side_effect=fake_transition), patch.object(api, "admit_challenge_round", side_effect=fake_admit), patch.object(api, "create_challenge_from_round", side_effect=fake_join_round), patch.object(177 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=8,visibility="private",)def test_timed_round_requires_a_positive_duration(self):
23 unmodified lines24252627282960 unmodified lines9091929394959697165 unmodified lines26326426526626726826921 unmodified lines291292293294295296474 unmodified lines7717727737747757763 unmodified lines7807817827837847851 unmodified line7877887897907917927931 unmodified line79579679779879980023 unmodified linescloseRound: vi.fn(),updateRoundSettings: vi.fn(),publicTests: vi.fn(),readFile: vi.fn(),saveFile: vi.fn(),reset: vi.fn(),60 unmodified linesmocks.reviewCourseAccessRequest.mockResolvedValue({ reviewed: true, status: "approved" });mocks.openRound.mockResolvedValue({ round_id: "round-prepared", status: "open" });mocks.closeRound.mockResolvedValue({ round_id: "round-open", status: "closed" });mocks.updateRoundSettings.mockResolvedValue({ round_id: "round-prepared", timer_minutes: 0, chat_messages_per_student: 5, status: "prepared" });mocks.publicTests.mockResolvedValue({ file_path: "src/demo.py", functions: ["normalize"], total: 1, source: "# Test 1: normalize(*('value',))\n# Expected: 'value'" });mocks.runTests.mockResolvedValue({ passed: 1, total: 2, score: 40, output: "Test 1: PASS", all_passed: false, per_test: [{ num: 1, status: "PASS" }, { num: 2, status: "FAIL" }] });mocks.diff.mockResolvedValue({ diff: "-value = 0\n+value = 2", has_changes: true });mocks.hint.mockResolvedValue({ response: "Check the return branch.", gave_hint: true, hints_used: 1, penalty: 2, chat_history: [] });165 unmodified linesconst user = userEvent.setup();mocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: true, approved_repositories: ["https://github.com/acme/approved"] });mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", is_course_admin: true, has_model_key: true, workspace_id: null });mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "round-prepared", repo_url: "https://github.com/acme/approved", target_file: "src/demo.py", status: "prepared", created_at: null, opened_at: null, closed_at: null, timer_minutes: 30, chat_messages_per_student: 20, participants: [{ student_name: "Learner", status: "in_progress", last_activity: null, hints_used: 1, submission_count: 0, reflection_saved: false, latest_score: null, passed_tests: null, total_tests: null, submission_outcome: null }] }] });mocks.courseAccess.mockResolvedValue({ role: "instructor", is_course_admin: true, request: null });mocks.courseAccessRequests.mockResolvedValue({ requests: [{ request_id: "request-1", auth_provider: "google", provider_user_id: "student-1", display_name: "New instructor", reason: "I teach this course", requested_at: "2026-01-01T10:00:00Z" }] });render(<App />);21 unmodified linestime_limit_enabled: false,timer_minutes: 30,chat_messages_per_student: 5,}));await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-prepared");474 unmodified linesexpect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();});it("publishes a local challenge round and displays its integrity hashes", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });3 unmodified linestests_hash: "tests-hash-123456",timer_minutes: 15,chat_messages_per_student: 35,status: "prepared",});render(<App />);1 unmodified lineconst messageLimitInput = await screen.findByRole("spinbutton", { name: /chat messages per student/i });await user.clear(messageLimitInput);await user.type(messageLimitInput, "35");await user.click(await screen.findByRole("button", { name: /publish round/i }));expect(await screen.findByText("round-123")).toBeTruthy();expect(screen.getByText(/Artifact artifact-has · Tests tests-hash-1/)).toBeTruthy();expect(screen.getByText(/35 chat messages\/student/)).toBeTruthy();1 unmodified linetime_limit_enabled: false,timer_minutes: 30,chat_messages_per_student: 35,});await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-123");23 unmodified lines2425262728293060 unmodified lines919293949596979899165 unmodified lines26526626726826927027121 unmodified lines293294295296297298299474 unmodified lines7747757767777787797807817827837847857867877887897907917927933 unmodified lines7977987998008018028031 unmodified line8058068078088098108111 unmodified line81381481581681781881923 unmodified linescloseRound: vi.fn(),updateRoundSettings: vi.fn(),publicTests: vi.fn(),publicChallengeRounds: vi.fn(),readFile: vi.fn(),saveFile: vi.fn(),reset: vi.fn(),60 unmodified linesmocks.reviewCourseAccessRequest.mockResolvedValue({ reviewed: true, status: "approved" });mocks.openRound.mockResolvedValue({ round_id: "round-prepared", status: "open" });mocks.closeRound.mockResolvedValue({ round_id: "round-open", status: "closed" });mocks.updateRoundSettings.mockResolvedValue({ round_id: "round-prepared", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", status: "prepared" });mocks.publicTests.mockResolvedValue({ file_path: "src/demo.py", functions: ["normalize"], total: 1, source: "# Test 1: normalize(*('value',))\n# Expected: 'value'" });mocks.publicChallengeRounds.mockResolvedValue({ rounds: [] });mocks.runTests.mockResolvedValue({ passed: 1, total: 2, score: 40, output: "Test 1: PASS", all_passed: false, per_test: [{ num: 1, status: "PASS" }, { num: 2, status: "FAIL" }] });mocks.diff.mockResolvedValue({ diff: "-value = 0\n+value = 2", has_changes: true });mocks.hint.mockResolvedValue({ response: "Check the return branch.", gave_hint: true, hints_used: 1, penalty: 2, chat_history: [] });165 unmodified linesconst user = userEvent.setup();mocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: true, approved_repositories: ["https://github.com/acme/approved"] });mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", is_course_admin: true, has_model_key: true, workspace_id: null });mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "round-prepared", repo_url: "https://github.com/acme/approved", target_file: "src/demo.py", status: "prepared", created_at: null, opened_at: null, closed_at: null, timer_minutes: 30, chat_messages_per_student: 20, visibility: "private", participants: [{ student_name: "Learner", status: "in_progress", last_activity: null, hints_used: 1, submission_count: 0, reflection_saved: false, latest_score: null, passed_tests: null, total_tests: null, submission_outcome: null }] }] });mocks.courseAccess.mockResolvedValue({ role: "instructor", is_course_admin: true, request: null });mocks.courseAccessRequests.mockResolvedValue({ requests: [{ request_id: "request-1", auth_provider: "google", provider_user_id: "student-1", display_name: "New instructor", reason: "I teach this course", requested_at: "2026-01-01T10:00:00Z" }] });render(<App />);21 unmodified linestime_limit_enabled: false,timer_minutes: 30,chat_messages_per_student: 5,visibility: "private",}));await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-prepared");474 unmodified linesexpect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();});it("shows public challenge scores and lets a student join a catalog challenge", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null, hints_used: 0, submission_count: 0 });mocks.publicChallengeRounds.mockResolvedValueOnce({ rounds: [{ round_id: "public-round-1", repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", status: "open", opened_at: null, timer_minutes: 30, chat_messages_per_student: 5, published_by: "huggingface:creator", participant_count: 4, submission_count: 4, average_score: 82.5 }] });mocks.startChallenge.mockResolvedValue({ job_id: "public-job", status: "queued" });mocks.waitForChallenge.mockResolvedValue(challenge);render(<App />);expect(await screen.findByText("82.5/100")).toBeTruthy();expect(screen.getByText(/4 participants/)).toBeTruthy();await user.click(screen.getByRole("button", { name: "Join challenge" }));await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalledWith({ round_id: "public-round-1" }));});it("publishes a local challenge round and displays its integrity hashes", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });3 unmodified linestests_hash: "tests-hash-123456",timer_minutes: 15,chat_messages_per_student: 35,visibility: "public",status: "prepared",});render(<App />);1 unmodified lineconst messageLimitInput = await screen.findByRole("spinbutton", { name: /chat messages per student/i });await user.clear(messageLimitInput);await user.type(messageLimitInput, "35");await user.click(await screen.findByRole("button", { name: /publish public challenge/i }));expect(await screen.findByText("round-123")).toBeTruthy();expect(screen.getByText(/Artifact artifact-has · Tests tests-hash-1/)).toBeTruthy();expect(screen.getByText(/35 chat messages\/student/)).toBeTruthy();1 unmodified linetime_limit_enabled: false,timer_minutes: 30,chat_messages_per_student: 35,visibility: "public",});await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-123");
33 unmodified lines3435363738394041424357 unmodified lines10110210310410510621 unmodified lines12812913013113213313413549 unmodified lines185186187188189190265 unmodified lines45645745845946046146246346446546646746846917 unmodified lines487488489490491492241 unmodified lines73473573673773873926 unmodified lines76676776876977077179 unmodified lines851852853854855856136 unmodified lines99399499599699799826 unmodified lines10251026102710281029103086 unmodified lines111711181119112011211122112333 unmodified linesXCircle,} from "lucide-react";import { api, waitForChallenge, waitForJob } from "./api";import type { ChallengeData, CourseAccessRequest, CourseAccessStatus, DevDiagnosis, HintResult, Identity, InstructorDashboard, ReflectionAnswers, ScoreReviewRequest, SessionInfo, StudentHistory, SubmissionResult, TestResult } from "./api";type ChatMessage = { role: "user" | "assistant"; content: string; gave_hint?: boolean };type RoundSettingsDraft = { time_limit_enabled: boolean; timer_minutes: number; chat_messages_per_student: number };type EditorHandle = {trigger: (source: string, handlerId: string, payload: null) => void;revealLineInCenter: (lineNumber: number) => void;57 unmodified linesconst [chatOpen, setChatOpen] = useState(false);const [submission, setSubmission] = useState<SubmissionResult | null>(null);const [studentHistory, setStudentHistory] = useState<StudentHistory | null>(null);const [historyOpen, setHistoryOpen] = useState(false);const [historyLoading, setHistoryLoading] = useState(false);const [instructorDashboard, setInstructorDashboard] = useState<InstructorDashboard | null>(null);21 unmodified linesconst [debugMode, setDebugMode] = useState(false);const [message, setMessage] = useState("");const [roundCode, setRoundCode] = useState("");const [publishedRound, setPublishedRound] = useState<{ round_id: string; artifact_hash: string; tests_hash: string; timer_minutes: number; chat_messages_per_student: number; status: "prepared" | "open" | "closed" } | null>(null);const [roundChatMessageLimit, setRoundChatMessageLimit] = useState(5);const [roundCopied, setRoundCopied] = useState(false);const [selfConfidence, setSelfConfidence] = useState(3);const [knownLimitations, setKnownLimitations] = useState("");49 unmodified lines}if (nextSession.authenticated && !nextSession.workspace_id) {void loadStudentHistorySummary();}if (nextSession.submission_locked && nextSession.last_submission_result) {setSubmission(nextSession.last_submission_result);265 unmodified lines}}async function handleJoinRound() {if (!roundCode.trim()) return;setError("");setBusy(true);setProgress(1);setStatus("Loading shared challenge");try {const { job_id: jobId } = await api.startChallenge({ round_id: roundCode.trim() });const created = await waitForChallenge(jobId, (_jobStatus, nextProgress, message) => {if (typeof nextProgress === "number") setProgress(nextProgress);setStatus(message || "Loading shared challenge");17 unmodified linestime_limit_enabled: timerEnabled,timer_minutes: timerMinutes,chat_messages_per_student: roundChatMessageLimit,}));setRoundCopied(false);} catch (cause) {241 unmodified lines}}async function handleLoadHistory() {setHistoryOpen(true);await loadStudentHistorySummary();26 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,},])));} catch (cause) {79 unmodified lines...round,timer_minutes: updated.timer_minutes,chat_messages_per_student: updated.chat_messages_per_student,status: updated.status,} : round),} : current);136 unmodified lines{page === "setup" && (<main className="setup-layout"><div className="setup-intro"><p className="eyebrow">NEW DEBUGGING SESSION</p><h1>Choose your challenge.</h1><p>Each run starts from a fresh repository copy. Your work and results stay attached to this session.</p></div>{(() => { const resumableAttempt = studentHistory?.attempts.find((attempt) => attempt.resumable && attempt.status === "in_progress"); return resumableAttempt ? <section className="continue-challenge-panel" aria-label="Continue started challenge"><div className="continue-challenge-copy"><p className="eyebrow">IN PROGRESS</p><h2>Continue your challenge</h2><p><strong>{resumableAttempt.target_file || "Challenge workspace"}</strong>{resumableAttempt.repo_url ? ` · ${resumableAttempt.repo_url.replace(/^https?:\/\//, "")}` : ""}</p>{resumableAttempt.hints_used > 0 && <small>{resumableAttempt.hints_used} hints used</small>}</div><button className="button button-primary" onClick={() => void handleResumeAttempt(resumableAttempt.workspace_id)} disabled={busy}><History size={16} />Continue challenge</button></section> : historyLoading ? <p className="continue-challenge-loading" role="status">Checking for an unfinished challenge…</p> : null; })()}{config.course_mode && session.role === "student" && <section className="instructor-dashboard course-access-panel"><div className="panel-heading"><div><p className="eyebrow">COURSE ACCESS</p><h2>Instructor access</h2></div><button className="button button-secondary" onClick={() => void handleLoadCourseAccess()} disabled={courseAccessLoading}>{courseAccessLoading ? <LoaderCircle className="spin" size={15} /> : <RefreshCw size={15} />}Refresh access</button></div>{courseAccessError && <p className="notice notice-error" role="alert">{courseAccessError}</p>}{courseAccess?.request?.status === "pending" ? <p role="status">Your instructor access request is pending review.</p> : courseAccess?.request?.status === "approved" ? <p role="status">Your request was approved. Refresh access to activate instructor tools.</p> : <><label>Why do you need instructor access?<textarea value={accessRequestReason} onChange={(event) => setAccessRequestReason(event.target.value)} maxLength={1000} rows={2} placeholder="Optional note for the course administrator." /></label><button className="button button-secondary" onClick={() => void handleRequestInstructorAccess()} disabled={courseAccessLoading}><UserPlus size={16} />Request instructor access</button></>}</section>}{session.role === "instructor" && (26 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,};const isEditing = editingRoundId === round.round_id;return (86 unmodified lines<div className="editor-footer"><span><Code2 size={14} />Python</span><span>{code.split("\n").length} lines</span>{dirty && <span className="unsaved-indicator">Not saved</span>}</div></div><section className="self-assessment-panel"><div><p className="eyebrow">BEFORE SUBMITTING</p><h2>Self-assessment</h2></div><label>Confidence in your fix<div className="range-line"><input type="range" min={1} max={5} value={selfConfidence} onChange={(event) => setSelfConfidence(Number(event.target.value))} /><output>{selfConfidence}/5</output></div></label><label>Known limitations<textarea value={knownLimitations} onChange={(event) => setKnownLimitations(event.target.value)} maxLength={4000} rows={2} placeholder="Optional: note anything you could not verify." /></label></section><div className="editor-cta-row"><button className="button button-secondary" onClick={() => void handleRunAndViewPublicTests()} disabled={busy}><Play size={16} />Public tests</button><button className="button button-secondary" onClick={() => void handleShowDiff()} disabled={busy || selectedFile !== challenge.target_file} title={selectedFile !== challenge.target_file ? "Diff snapshot is available for the challenge target file" : "View changes"}><Code2 size={16} />View changes</button>{session.role === "instructor" && <button className="button button-secondary" onClick={() => void handleShowDiagnosis()} disabled={busy}><CircleHelp size={16} />What to fix and where</button>}{session.role === "instructor" && <label className="round-quota-control">Chat messages per student<input type="number" min={0} max={100} step={1} value={roundChatMessageLimit} onChange={(event) => setRoundChatMessageLimit(Math.min(100, Math.max(0, Number(event.target.value))))} disabled={busy} /></label>}{session.role === "instructor" && <button className="button button-secondary" onClick={() => void handlePublishRound()} disabled={busy}><Share2 size={16} />Publish round</button>}<button className="button button-primary submit-button" onClick={() => void handleSubmit()} disabled={busy || selectedFile !== challenge.target_file} title={selectedFile !== challenge.target_file ? "Select the challenge target file before submitting" : "Submit fix"}><Upload size={16} />Submit fix</button></div>{publishedRound && <section className="round-share-panel" aria-live="polite"><div><p className="eyebrow">SHARED ROUND · {publishedRound.status}</p><strong>{publishedRound.round_id}</strong><small>{publishedRound.chat_messages_per_student} chat messages/student · Artifact {publishedRound.artifact_hash.slice(0, 12)} · Tests {publishedRound.tests_hash.slice(0, 12)}</small></div>{publishedRound.status === "prepared" && <button className="button button-secondary" onClick={() => void handleRoundTransition(publishedRound.round_id, "open")} disabled={busy}><Play size={15} />Open round</button>}{publishedRound.status === "open" && <button className="button button-secondary" onClick={() => void handleRoundTransition(publishedRound.round_id, "close")} disabled={busy}><XCircle size={15} />Close round</button>}<button className="icon-button" onClick={async () => { try { await navigator.clipboard.writeText(publishedRound.round_id); setRoundCopied(true); } catch { setError("Clipboard access is unavailable. Select and copy the round code."); } }} aria-label="Copy round code" title="Copy round code"><Copy size={16} /></button>{roundCopied && <span className="round-copied">Copied</span>}</section>}{publicTestsView && <section className="test-panel public-tests-panel" aria-label="Public tests source"><div className="panel-heading"><div><p className="eyebrow">PUBLIC TESTS · {publicTestsView.file_path}</p><h2>{testResult ? `${testResult.passed} of ${testResult.total} passed` : `Showing ${publicTestsView.total} tests`}</h2></div>{testResult && <span className={`result-pill ${testResult.all_passed ? "pill-success" : "pill-warning"}`}>{testResult.all_passed ? <CheckCircle2 size={15} /> : <AlertCircle size={15} />}{testResult.all_passed ? "All passing" : "Needs work"}</span>}<button className="icon-button" onClick={() => { setPublicTestsView(null); setTestResult(null); }} aria-label="Close public tests"><XCircle size={16} /></button></div><div className="public-test-functions">{publicTestsView.functions.map((functionName) => <button className="button button-secondary" key={functionName} onClick={() => void handleJumpToTestFunction(functionName)}>Go to {functionName}</button>)}</div><details className="output-details"><summary><FileCode2 size={15} />Read-only test source</summary><pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre></details><div className="public-test-table">{((publicTestsView.tests && publicTestsView.tests.length ? publicTestsView.tests : (testResult?.per_test ?? []).map((item) => ({ num: item.num, function_name: item.function_name ?? "target", args: item.args ?? "Not provided", expected: item.expected ?? "Not provided" })))).map((test) => { const result = (testResult?.per_test ?? []).find((item) => item.num === test.num); const actual = result?.actual; return <article className="public-test-row" key={test.num}><div className="public-test-status"><span className={result?.status === "PASS" ? "test-pass" : result?.status ? "test-fail" : "test-pending"}>{result?.status === "PASS" ? <Check size={15} /> : result?.status ? <XCircle size={15} /> : <TerminalSquare size={15} />}</span><strong>Test {test.num}</strong><code>{result?.status ?? "NOT RUN"}</code></div><dl><div><dt>Function</dt><dd><code>{test.function_name}</code></dd></div><div><dt>Input</dt><dd><code>{test.args}</code></dd></div><div><dt>Expected</dt><dd><code>{test.expected}</code></dd></div><div><dt>Actual</dt><dd><code>{actual === undefined ? (result ? "Not returned by runner" : "Run tests to compare") : typeof actual === "object" ? JSON.stringify(actual) : String(actual)}</code></dd></div></dl></article>; })}</div>{!publicTestsView.tests?.length && !testResult?.per_test?.length && <pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre>}<details className="output-details"><summary><TerminalSquare size={15} />Full test output</summary><pre>{testResult?.output || "No test run yet."}</pre></details><p className="muted-copy">Showing {publicTestsView.total} public tests. Secret tests are not shown.</p></section>}{diagnosis && <section className="test-panel diagnosis-panel"><div className="panel-heading"><div><p className="eyebrow">LOCAL TEST DIAGNOSIS</p><h2>{diagnosis.file_path}</h2></div><button className="icon-button" onClick={() => setDiagnosis(null)} aria-label="Close diagnosis"><XCircle size={16} /></button></div><p><strong>Function:</strong> {diagnosis.functions.join(", ") || "Target logic"}</p><p>{diagnosis.bug_description}</p><pre className="expected-diff">{diagnosis.diff || "No focused diff is available."}</pre></section>}33 unmodified lines3435363738394041424357 unmodified lines10110210310410510610710821 unmodified lines13013113213313413513613713849 unmodified lines188189190191192193194265 unmodified lines46046146246346446546646746846947047147247347417 unmodified lines492493494495496497498241 unmodified lines74074174274374474574674774874975075175275375475575675726 unmodified lines78478578678778878979079 unmodified lines870871872873874875876136 unmodified lines101310141015101610171018101926 unmodified lines104610471048104910501051105286 unmodified lines113911401141114211431144114533 unmodified linesXCircle,} from "lucide-react";import { api, waitForChallenge, waitForJob } from "./api";import type { ChallengeData, CourseAccessRequest, CourseAccessStatus, DevDiagnosis, HintResult, Identity, InstructorDashboard, PublicChallengeRound, ReflectionAnswers, ScoreReviewRequest, SessionInfo, StudentHistory, SubmissionResult, TestResult } from "./api";type ChatMessage = { role: "user" | "assistant"; content: string; gave_hint?: boolean };type RoundSettingsDraft = { time_limit_enabled: boolean; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public" };type EditorHandle = {trigger: (source: string, handlerId: string, payload: null) => void;revealLineInCenter: (lineNumber: number) => void;57 unmodified linesconst [chatOpen, setChatOpen] = useState(false);const [submission, setSubmission] = useState<SubmissionResult | null>(null);const [studentHistory, setStudentHistory] = useState<StudentHistory | null>(null);const [publicChallenges, setPublicChallenges] = useState<PublicChallengeRound[]>([]);const [publicChallengesLoading, setPublicChallengesLoading] = useState(false);const [historyOpen, setHistoryOpen] = useState(false);const [historyLoading, setHistoryLoading] = useState(false);const [instructorDashboard, setInstructorDashboard] = useState<InstructorDashboard | null>(null);21 unmodified linesconst [debugMode, setDebugMode] = useState(false);const [message, setMessage] = useState("");const [roundCode, setRoundCode] = useState("");const [publishedRound, setPublishedRound] = useState<{ round_id: string; artifact_hash: string; tests_hash: string; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public"; status: "prepared" | "open" | "closed" } | null>(null);const [roundChatMessageLimit, setRoundChatMessageLimit] = useState(5);const [roundVisibility, setRoundVisibility] = useState<"private" | "public">("public");const [roundCopied, setRoundCopied] = useState(false);const [selfConfidence, setSelfConfidence] = useState(3);const [knownLimitations, setKnownLimitations] = useState("");49 unmodified lines}if (nextSession.authenticated && !nextSession.workspace_id) {void loadStudentHistorySummary();void handleLoadPublicChallenges();}if (nextSession.submission_locked && nextSession.last_submission_result) {setSubmission(nextSession.last_submission_result);265 unmodified lines}}async function handleJoinRound(roundIdOverride?: string) {const roundId = (roundIdOverride ?? roundCode).trim();if (!roundId) return;setError("");setBusy(true);setProgress(1);setStatus("Loading shared challenge");try {const { job_id: jobId } = await api.startChallenge({ round_id: roundId });const created = await waitForChallenge(jobId, (_jobStatus, nextProgress, message) => {if (typeof nextProgress === "number") setProgress(nextProgress);setStatus(message || "Loading shared challenge");17 unmodified linestime_limit_enabled: timerEnabled,timer_minutes: timerMinutes,chat_messages_per_student: roundChatMessageLimit,visibility: session?.role === "instructor" ? roundVisibility : "public",}));setRoundCopied(false);} catch (cause) {241 unmodified lines}}async function handleLoadPublicChallenges() {setPublicChallengesLoading(true);try {const result = await api.publicChallengeRounds();setPublicChallenges(result.rounds);} catch (cause) {setError(cause instanceof Error ? cause.message : "Could not load public challenges");} finally {setPublicChallengesLoading(false);}}async function handleLoadHistory() {setHistoryOpen(true);await loadStudentHistorySummary();26 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,visibility: round.visibility ?? "private",},])));} catch (cause) {79 unmodified lines...round,timer_minutes: updated.timer_minutes,chat_messages_per_student: updated.chat_messages_per_student,visibility: updated.visibility,status: updated.status,} : round),} : current);136 unmodified lines{page === "setup" && (<main className="setup-layout"><div className="setup-intro"><p className="eyebrow">NEW DEBUGGING SESSION</p><h1>Choose your challenge.</h1><p>Each run starts from a fresh repository copy. Your work and results stay attached to this session.</p></div><section className="public-challenges-panel" aria-label="Public challenges"><div className="panel-heading"><div><p className="eyebrow">PUBLIC CHALLENGE CATALOG</p><h2>Open challenges</h2></div><button className="button button-secondary" onClick={() => void handleLoadPublicChallenges()} disabled={publicChallengesLoading}>{publicChallengesLoading ? <LoaderCircle className="spin" size={15} /> : <RefreshCw size={15} />}Refresh</button></div>{publicChallengesLoading ? <p role="status">Loading public challenges…</p> : publicChallenges.length ? <div className="public-challenge-list">{publicChallenges.map((challenge) => <article className="public-challenge-row" key={challenge.round_id}><div><strong>{challenge.repo_url?.split("/").slice(-1)[0] || "Challenge"}</strong><span>{challenge.target_file || "Target unavailable"}</span></div><div className="public-challenge-average"><strong>{challenge.average_score == null ? "No scores yet" : `${challenge.average_score}/100`}</strong><small>{challenge.participant_count} participants · {challenge.submission_count} final submissions</small></div><button className="button button-primary" onClick={() => void handleJoinRound(challenge.round_id)} disabled={busy}>Join challenge</button></article>)}</div> : <p>No public challenges are open yet.</p>}</section>{(() => { const resumableAttempt = studentHistory?.attempts.find((attempt) => attempt.resumable && attempt.status === "in_progress"); return resumableAttempt ? <section className="continue-challenge-panel" aria-label="Continue started challenge"><div className="continue-challenge-copy"><p className="eyebrow">IN PROGRESS</p><h2>Continue your challenge</h2><p><strong>{resumableAttempt.target_file || "Challenge workspace"}</strong>{resumableAttempt.repo_url ? ` · ${resumableAttempt.repo_url.replace(/^https?:\/\//, "")}` : ""}</p>{resumableAttempt.hints_used > 0 && <small>{resumableAttempt.hints_used} hints used</small>}</div><button className="button button-primary" onClick={() => void handleResumeAttempt(resumableAttempt.workspace_id)} disabled={busy}><History size={16} />Continue challenge</button></section> : historyLoading ? <p className="continue-challenge-loading" role="status">Checking for an unfinished challenge…</p> : null; })()}{config.course_mode && session.role === "student" && <section className="instructor-dashboard course-access-panel"><div className="panel-heading"><div><p className="eyebrow">COURSE ACCESS</p><h2>Instructor access</h2></div><button className="button button-secondary" onClick={() => void handleLoadCourseAccess()} disabled={courseAccessLoading}>{courseAccessLoading ? <LoaderCircle className="spin" size={15} /> : <RefreshCw size={15} />}Refresh access</button></div>{courseAccessError && <p className="notice notice-error" role="alert">{courseAccessError}</p>}{courseAccess?.request?.status === "pending" ? <p role="status">Your instructor access request is pending review.</p> : courseAccess?.request?.status === "approved" ? <p role="status">Your request was approved. Refresh access to activate instructor tools.</p> : <><label>Why do you need instructor access?<textarea value={accessRequestReason} onChange={(event) => setAccessRequestReason(event.target.value)} maxLength={1000} rows={2} placeholder="Optional note for the course administrator." /></label><button className="button button-secondary" onClick={() => void handleRequestInstructorAccess()} disabled={courseAccessLoading}><UserPlus size={16} />Request instructor access</button></>}</section>}{session.role === "instructor" && (26 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,visibility: round.visibility ?? "private",};const isEditing = editingRoundId === round.round_id;return (86 unmodified lines<div className="editor-footer"><span><Code2 size={14} />Python</span><span>{code.split("\n").length} lines</span>{dirty && <span className="unsaved-indicator">Not saved</span>}</div></div><section className="self-assessment-panel"><div><p className="eyebrow">BEFORE SUBMITTING</p><h2>Self-assessment</h2></div><label>Confidence in your fix<div className="range-line"><input type="range" min={1} max={5} value={selfConfidence} onChange={(event) => setSelfConfidence(Number(event.target.value))} /><output>{selfConfidence}/5</output></div></label><label>Known limitations<textarea value={knownLimitations} onChange={(event) => setKnownLimitations(event.target.value)} maxLength={4000} rows={2} placeholder="Optional: note anything you could not verify." /></label></section><div className="editor-cta-row"><button className="button button-secondary" onClick={() => void handleRunAndViewPublicTests()} disabled={busy}><Play size={16} />Public tests</button><button className="button button-secondary" onClick={() => void handleShowDiff()} disabled={busy || selectedFile !== challenge.target_file} title={selectedFile !== challenge.target_file ? "Diff snapshot is available for the challenge target file" : "View changes"}><Code2 size={16} />View changes</button>{session.role === "instructor" && <button className="button button-secondary" onClick={() => void handleShowDiagnosis()} disabled={busy}><CircleHelp size={16} />What to fix and where</button>}{session.role === "instructor" && <label className="round-quota-control">Chat messages per student<input type="number" min={0} max={100} step={1} value={roundChatMessageLimit} onChange={(event) => setRoundChatMessageLimit(Math.min(100, Math.max(0, Number(event.target.value))))} disabled={busy} /></label>}<label className="round-quota-control">Challenge visibility<select value={session.role === "instructor" ? roundVisibility : "public"} onChange={(event) => setRoundVisibility(event.target.value === "private" ? "private" : "public")} disabled={busy || session.role !== "instructor"}><option value="public">Public</option>{session.role === "instructor" && <option value="private">Private</option>}</select></label><button className="button button-secondary" onClick={() => void handlePublishRound()} disabled={busy}><Share2 size={16} />Publish {session.role === "instructor" && roundVisibility === "private" ? "private" : "public"} challenge</button><button className="button button-primary submit-button" onClick={() => void handleSubmit()} disabled={busy || selectedFile !== challenge.target_file} title={selectedFile !== challenge.target_file ? "Select the challenge target file before submitting" : "Submit fix"}><Upload size={16} />Submit fix</button></div>{publishedRound && <section className="round-share-panel" aria-live="polite"><div><p className="eyebrow">SHARED ROUND · {publishedRound.status}</p><strong>{publishedRound.round_id}</strong><small>{publishedRound.chat_messages_per_student} chat messages/student · Artifact {publishedRound.artifact_hash.slice(0, 12)} · Tests {publishedRound.tests_hash.slice(0, 12)}</small></div>{publishedRound.status === "prepared" && <button className="button button-secondary" onClick={() => void handleRoundTransition(publishedRound.round_id, "open")} disabled={busy}><Play size={15} />Open round</button>}{publishedRound.status === "open" && <button className="button button-secondary" onClick={() => void handleRoundTransition(publishedRound.round_id, "close")} disabled={busy}><XCircle size={15} />Close round</button>}<button className="icon-button" onClick={async () => { try { await navigator.clipboard.writeText(publishedRound.round_id); setRoundCopied(true); } catch { setError("Clipboard access is unavailable. Select and copy the round code."); } }} aria-label="Copy round code" title="Copy round code"><Copy size={16} /></button>{roundCopied && <span className="round-copied">Copied</span>}</section>}{publicTestsView && <section className="test-panel public-tests-panel" aria-label="Public tests source"><div className="panel-heading"><div><p className="eyebrow">PUBLIC TESTS · {publicTestsView.file_path}</p><h2>{testResult ? `${testResult.passed} of ${testResult.total} passed` : `Showing ${publicTestsView.total} tests`}</h2></div>{testResult && <span className={`result-pill ${testResult.all_passed ? "pill-success" : "pill-warning"}`}>{testResult.all_passed ? <CheckCircle2 size={15} /> : <AlertCircle size={15} />}{testResult.all_passed ? "All passing" : "Needs work"}</span>}<button className="icon-button" onClick={() => { setPublicTestsView(null); setTestResult(null); }} aria-label="Close public tests"><XCircle size={16} /></button></div><div className="public-test-functions">{publicTestsView.functions.map((functionName) => <button className="button button-secondary" key={functionName} onClick={() => void handleJumpToTestFunction(functionName)}>Go to {functionName}</button>)}</div><details className="output-details"><summary><FileCode2 size={15} />Read-only test source</summary><pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre></details><div className="public-test-table">{((publicTestsView.tests && publicTestsView.tests.length ? publicTestsView.tests : (testResult?.per_test ?? []).map((item) => ({ num: item.num, function_name: item.function_name ?? "target", args: item.args ?? "Not provided", expected: item.expected ?? "Not provided" })))).map((test) => { const result = (testResult?.per_test ?? []).find((item) => item.num === test.num); const actual = result?.actual; return <article className="public-test-row" key={test.num}><div className="public-test-status"><span className={result?.status === "PASS" ? "test-pass" : result?.status ? "test-fail" : "test-pending"}>{result?.status === "PASS" ? <Check size={15} /> : result?.status ? <XCircle size={15} /> : <TerminalSquare size={15} />}</span><strong>Test {test.num}</strong><code>{result?.status ?? "NOT RUN"}</code></div><dl><div><dt>Function</dt><dd><code>{test.function_name}</code></dd></div><div><dt>Input</dt><dd><code>{test.args}</code></dd></div><div><dt>Expected</dt><dd><code>{test.expected}</code></dd></div><div><dt>Actual</dt><dd><code>{actual === undefined ? (result ? "Not returned by runner" : "Run tests to compare") : typeof actual === "object" ? JSON.stringify(actual) : String(actual)}</code></dd></div></dl></article>; })}</div>{!publicTestsView.tests?.length && !testResult?.per_test?.length && <pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre>}<details className="output-details"><summary><TerminalSquare size={15} />Full test output</summary><pre>{testResult?.output || "No test run yet."}</pre></details><p className="muted-copy">Showing {publicTestsView.total} public tests. Secret tests are not shown.</p></section>}{diagnosis && <section className="test-panel diagnosis-panel"><div className="panel-heading"><div><p className="eyebrow">LOCAL TEST DIAGNOSIS</p><h2>{diagnosis.file_path}</h2></div><button className="icon-button" onClick={() => setDiagnosis(null)} aria-label="Close diagnosis"><XCircle size={16} /></button></div><p><strong>Function:</strong> {diagnosis.functions.join(", ") || "Target logic"}</p><p>{diagnosis.bug_description}</p><pre className="expected-diff">{diagnosis.diff || "No focused diff is available."}</pre></section>}
175 unmodified lines1761771781791801818 unmodified lines19019119219319419519619719819968 unmodified lines268269270271272273274275276277278279280281282283175 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;participants: Array<{student_name: string | null;status: string;8 unmodified lines}>;};export type ChallengeRoundSettings = {time_limit_enabled: boolean;timer_minutes: number;chat_messages_per_student: number;};export type InstructorDashboard = { rounds: InstructorRound[] };68 unmodified linesstartChallenge: (setup: ChallengeSetup) =>request<{ job_id: string; status: string }>("/api/challenges", { method: "POST", body: JSON.stringify(setup) }),publishChallengeRound: (settings: ChallengeRoundSettings) =>request<{ round_id: string; artifact_hash: string; tests_hash: string; timer_minutes: number; chat_messages_per_student: number; status: "prepared" }>("/api/challenge-rounds", {method: "POST",body: JSON.stringify(settings),}),updateRoundSettings: (roundId: string, settings: ChallengeRoundSettings) =>request<{ round_id: string; timer_minutes: number; chat_messages_per_student: number; status: "prepared" }>(`/api/challenge-rounds/${encodeURIComponent(roundId)}/settings`, {method: "PATCH",body: JSON.stringify(settings),}),pollJob: <T>(jobId: string) => request<ApiJob<T>>(`/api/jobs/${encodeURIComponent(jobId)}`),challenge: () => request<ChallengeData>("/api/challenge"),history: (limit = 50) => request<StudentHistory>(`/api/me/history?limit=${limit}`),resume: (workspaceId: string) => request<ChallengeData>(`/api/challenges/${encodeURIComponent(workspaceId)}/resume`, { method: "POST" }),175 unmodified lines1761771781791801811828 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421568 unmodified lines284285286287288289290291292293294295296297298299300175 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;visibility: "private" | "public";participants: Array<{student_name: string | null;status: string;8 unmodified lines}>;};export type PublicChallengeRound = {round_id: string;repo_url: string | null;target_file: string | null;status: "open";opened_at: string | null;timer_minutes: number;chat_messages_per_student: number;published_by: string | null;participant_count: number;submission_count: number;average_score: number | null;};export type ChallengeRoundSettings = {time_limit_enabled: boolean;timer_minutes: number;chat_messages_per_student: number;visibility: "private" | "public";};export type InstructorDashboard = { rounds: InstructorRound[] };68 unmodified linesstartChallenge: (setup: ChallengeSetup) =>request<{ job_id: string; status: string }>("/api/challenges", { method: "POST", body: JSON.stringify(setup) }),publishChallengeRound: (settings: ChallengeRoundSettings) =>request<{ round_id: string; artifact_hash: string; tests_hash: string; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public"; status: "prepared" }>("/api/challenge-rounds", {method: "POST",body: JSON.stringify(settings),}),updateRoundSettings: (roundId: string, settings: ChallengeRoundSettings) =>request<{ round_id: string; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public"; status: "prepared" }>(`/api/challenge-rounds/${encodeURIComponent(roundId)}/settings`, {method: "PATCH",body: JSON.stringify(settings),}),pollJob: <T>(jobId: string) => request<ApiJob<T>>(`/api/jobs/${encodeURIComponent(jobId)}`),publicChallengeRounds: () => request<{ rounds: PublicChallengeRound[] }>("/api/challenge-rounds/public"),challenge: () => request<ChallengeData>("/api/challenge"),history: (limit = 50) => request<StudentHistory>(`/api/me/history?limit=${limit}`),resume: (workspaceId: string) => request<ChallengeData>(`/api/challenges/${encodeURIComponent(workspaceId)}/resume`, { method: "POST" }),
143 unmodified lines144145146147148149143 unmodified lines.round-settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }.notice-dismiss { margin-left: auto; border: 0; color: inherit; background: transparent; }.setup-layout { width: min(100% - 40px, 890px); margin: 76px auto 80px; }.setup-intro { margin-bottom: 27px; }.setup-intro h1 { margin: 0; font-size: clamp(30px, 5vw, 45px); font-weight: 600; }.setup-intro > p:last-child { max-width: 520px; margin: 10px 0 0; color: var(--muted); font-size: 14px; line-height: 1.6; }143 unmodified lines144145146147148149150151152153154155156143 unmodified lines.round-settings-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }.notice-dismiss { margin-left: auto; border: 0; color: inherit; background: transparent; }.setup-layout { width: min(100% - 40px, 890px); margin: 76px auto 80px; }.public-challenges-panel { margin-bottom: 18px; border: 1px solid var(--line); border-radius: 8px; padding: 16px; background: var(--panel); }.public-challenge-list { display: grid; gap: 8px; }.public-challenge-row { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 12px; border: 1px solid var(--line); border-radius: 6px; padding: 12px; }.public-challenge-row > div { display: grid; gap: 3px; }.public-challenge-row span, .public-challenge-row small { color: var(--muted); }.public-challenge-average { text-align: right; }.round-quota-control select { width: 100%; min-height: 34px; border: 1px solid #cfd9df; border-radius: 5px; padding: 0 9px; background: #fff; }.setup-intro { margin-bottom: 27px; }.setup-intro h1 { margin: 0; font-size: clamp(30px, 5vw, 45px); font-weight: 600; }.setup-intro > p:last-child { max-width: 520px; margin: 10px 0 0; color: var(--muted); font-size: 14px; line-height: 1.6; }
95 unmodified lines9697989910010171 unmodified lines1731741751761771789 unmodified lines18818919019119219341 unmodified lines23523623723823924095 unmodified lines"tests_hash": manifest["tests_hash"],"timer_minutes": int(manifest.get("timer_minutes", 0)),"chat_messages_per_student": chat_limit,"quota_units_per_student": quota_units,"status": "prepared","published_by": published_by,71 unmodified lines"tests_hash": row["tests_hash"],"timer_minutes": int(row["timer_minutes"]),"chat_messages_per_student": int(row.get("chat_messages_per_student", 5)),"status": row.get("status", "prepared"),"published_by": row.get("published_by"),"quota_units_per_student": int(row.get("quota_units_per_student", 20)),9 unmodified linestime_limit_enabled: bool,timer_minutes: int,chat_messages_per_student: int,) -> dict[str, Any] | None:"""Update settings only while the creator's round is still prepared."""url, key = _configuration()41 unmodified linesreturn rows[0]def get_challenge_round_publisher(round_id: str, course_id: str = "local") -> str | None:"""Return the immutable publisher identity for a round without loading its bundle."""url, key = _configuration()95 unmodified lines9697989910010110271 unmodified lines1741751761771781791809 unmodified lines19019119219319419519641 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135295 unmodified lines"tests_hash": manifest["tests_hash"],"timer_minutes": int(manifest.get("timer_minutes", 0)),"chat_messages_per_student": chat_limit,"visibility": manifest.get("visibility", "private") if manifest.get("visibility") in {"private", "public"} else "private","quota_units_per_student": quota_units,"status": "prepared","published_by": published_by,71 unmodified lines"tests_hash": row["tests_hash"],"timer_minutes": int(row["timer_minutes"]),"chat_messages_per_student": int(row.get("chat_messages_per_student", 5)),"visibility": row.get("visibility", "private"),"status": row.get("status", "prepared"),"published_by": row.get("published_by"),"quota_units_per_student": int(row.get("quota_units_per_student", 20)),9 unmodified linestime_limit_enabled: bool,timer_minutes: int,chat_messages_per_student: int,visibility: str = "private",) -> dict[str, Any] | None:"""Update settings only while the creator's round is still prepared."""url, key = _configuration()41 unmodified linesreturn rows[0]def get_public_challenge_rounds(course_id: str = "local") -> list[dict[str, Any]]:url, key = _configuration()query = urlencode({"select": "round_id,repo_url,target_file,status,created_at,opened_at,closed_at,timer_minutes,chat_messages_per_student,published_by","course_id": f"eq.{course_id}","visibility": "eq.public","status": "eq.open","order": "opened_at.desc,created_at.desc",})try:with urlopen(Request(f"{url}/rest/v1/{TABLE_NAME}?{query}",headers=_headers(key, "application/json"),method="GET",), timeout=12) as response:rounds = json.loads(response.read().decode("utf-8"))except HTTPError as exc:raise _safe_http_error(exc, "public challenge catalog lookup") from excexcept (TimeoutError, URLError, OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:raise ChallengeRoundStoreError(f"Public challenge catalog lookup failed ({type(exc).__name__})") from excif not isinstance(rounds, list):raise ChallengeRoundStoreError("Supabase returned an invalid public challenge catalog")if not rounds:return []round_ids = [str(row.get("round_id") or "") for row in rounds if row.get("round_id")]latest_scores: dict[str, dict[str, int]] = {}if round_ids:submissions_query = urlencode({"select": "submission_id,round_id,auth_provider,provider_user_id,total_score,submitted_at","round_id": f"in.({','.join(round_ids)})","limit": "1000","order": "submitted_at.desc,submission_id.desc",})try:with urlopen(Request(f"{url}/rest/v1/submissions?{submissions_query}",headers=_headers(key, "application/json"),method="GET",), timeout=12) as response:submissions = json.loads(response.read().decode("utf-8"))except HTTPError as exc:raise _safe_http_error(exc, "public challenge score lookup") from excexcept (TimeoutError, URLError, OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:raise ChallengeRoundStoreError(f"Public challenge score lookup failed ({type(exc).__name__})") from excif isinstance(submissions, list):for submission in submissions:round_id = str(submission.get("round_id") or "")provider = str(submission.get("auth_provider") or "")user_id = str(submission.get("provider_user_id") or "")score = submission.get("total_score")if not round_id or not provider or not user_id or isinstance(score, bool):continueif not isinstance(score, (int, float)):continueparticipant_key = f"{provider}:{user_id}"latest_scores.setdefault(round_id, {}).setdefault(participant_key, int(score))catalog = []for row in rounds:round_id = str(row.get("round_id") or "")scores = list(latest_scores.get(round_id, {}).values())catalog.append({"round_id": round_id,"repo_url": row.get("repo_url"),"target_file": row.get("target_file"),"status": row.get("status"),"created_at": row.get("created_at"),"opened_at": row.get("opened_at"),"timer_minutes": int(row.get("timer_minutes", 0)),"chat_messages_per_student": int(row.get("chat_messages_per_student", 5)),"published_by": row.get("published_by"),"participant_count": len(scores),"submission_count": len(scores),"average_score": round(sum(scores) / len(scores), 1) if scores else None,})return catalogdef claim_public_challenge_submission(round_id: str,identity: dict[str, str],submission_id: str,) -> dict[str, Any]:url, key = _configuration()payload = {"p_round_id": str(UUID(round_id)),"p_auth_provider": str(identity.get("provider") or ""),"p_provider_user_id": str(identity.get("user_id") or ""),"p_submission_id": submission_id,}request = Request(f"{url}/rest/v1/rpc/claim_public_challenge_submission",data=json.dumps(payload).encode("utf-8"),headers=_headers(key, "application/json"),method="POST",)try:with urlopen(request, timeout=8) as response:data = json.loads(response.read().decode("utf-8"))except HTTPError as exc:raise ChallengeRoundStoreError(f"Public submission claim failed ({exc.code})") from excexcept (TimeoutError, URLError, OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:raise ChallengeRoundStoreError(f"Public submission claim unavailable ({type(exc).__name__})") from excif not isinstance(data, dict):raise ChallengeRoundStoreError("Public submission claim returned an invalid response")return datadef get_challenge_round_publisher(round_id: str, course_id: str = "local") -> str | None:"""Return the immutable publisher identity for a round without loading its bundle."""url, key = _configuration()
110 unmodified lines1111121131141151169 unmodified lines12612712812913013182 unmodified lines214215216217218219110 unmodified linestests_hash text not null,timer_minutes integer not null default 0 check (timer_minutes between 0 and 120),chat_messages_per_student integer not null default 5 check (chat_messages_per_student between 0 and 100),quota_units_per_student integer not null default 7 check (quota_units_per_student between 0 and 102),status text not null default 'prepared' check (status in ('prepared', 'open', 'closed')),published_by text,9 unmodified linesalter table public.challenge_rounds alter column quota_units_per_student set default 7;alter table public.challenge_roundsadd column if not exists chat_messages_per_student integer not null default 5 check (chat_messages_per_student between 0 and 100);alter table public.challenge_rounds drop constraint if exists challenge_rounds_quota_units_per_student_check;alter table public.challenge_rounds drop constraint if exists challenge_rounds_quota_units_per_student_cap_check;alter table public.challenge_rounds82 unmodified linesrevoke all on table public.submission_score_reviews from anon, authenticated;grant select, insert, update on table public.submission_score_reviews to service_role;create or replace function public.reserve_round_llm_quota(p_operation_id uuid,p_round_id uuid,110 unmodified lines1111121131141151161179 unmodified lines12712812913013113213313482 unmodified lines217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276110 unmodified linestests_hash text not null,timer_minutes integer not null default 0 check (timer_minutes between 0 and 120),chat_messages_per_student integer not null default 5 check (chat_messages_per_student between 0 and 100),visibility text not null default 'private' check (visibility in ('private', 'public')),quota_units_per_student integer not null default 7 check (quota_units_per_student between 0 and 102),status text not null default 'prepared' check (status in ('prepared', 'open', 'closed')),published_by text,9 unmodified linesalter table public.challenge_rounds alter column quota_units_per_student set default 7;alter table public.challenge_roundsadd column if not exists chat_messages_per_student integer not null default 5 check (chat_messages_per_student between 0 and 100);alter table public.challenge_roundsadd column if not exists visibility text not null default 'private' check (visibility in ('private', 'public'));alter table public.challenge_rounds drop constraint if exists challenge_rounds_quota_units_per_student_check;alter table public.challenge_rounds drop constraint if exists challenge_rounds_quota_units_per_student_cap_check;alter table public.challenge_rounds82 unmodified linesrevoke all on table public.submission_score_reviews from anon, authenticated;grant select, insert, update on table public.submission_score_reviews to service_role;create table if not exists public.public_challenge_submissions (round_id uuid not null references public.challenge_rounds(round_id) on delete cascade,auth_provider text not null,provider_user_id text not null,submission_id text not null,claimed_at timestamptz not null default now(),primary key (round_id, auth_provider, provider_user_id));alter table public.public_challenge_submissions enable row level security;revoke all on table public.public_challenge_submissions from public, anon, authenticated;grant select, insert, update, delete on table public.public_challenge_submissions to service_role;create or replace function public.claim_public_challenge_submission(p_round_id uuid,p_auth_provider text,p_provider_user_id text,p_submission_id text) returns jsonblanguage plpgsqlsecurity definerset search_path = public, pg_tempas $$declarev_visibility text;v_status text;beginselect visibility, status into v_visibility, v_statusfrom public.challenge_roundswhere round_id = p_round_id;if not found thenreturn jsonb_build_object('claimed', false, 'reason', 'round_unavailable');end if;if v_status <> 'open' thenreturn jsonb_build_object('claimed', false, 'reason', 'round_unavailable');end if;if v_visibility <> 'public' thenreturn jsonb_build_object('claimed', true, 'public_challenge', false);end if;if exists (select 1 from public.public_challenge_submissionswhere round_id = p_round_idand auth_provider = p_auth_providerand provider_user_id = p_provider_user_id) thenreturn jsonb_build_object('claimed', false, 'reason', 'already_submitted');end if;insert into public.public_challenge_submissions(round_id, auth_provider, provider_user_id, submission_id)values (p_round_id, p_auth_provider, p_provider_user_id, p_submission_id);return jsonb_build_object('claimed', true, 'public_challenge', true);end;$$;revoke all on function public.claim_public_challenge_submission(uuid, text, text, text) from public, anon, authenticated;grant execute on function public.claim_public_challenge_submission(uuid, text, text, text) to service_role;create or replace function public.reserve_round_llm_quota(p_operation_id uuid,p_round_id uuid,
42 unmodified lines43444546474813 unmodified lines62636465666763 unmodified lines13113213313413513642 unmodified lines"timer_minutes": 30,"quota_units_per_student": 35,"chat_messages_per_student": 4,}with patch.object(rounds, "urlopen", side_effect=[FakeResponse(), FakeResponse()]) as open_url:rounds.save_challenge_round(manifest, b"zip-bundle", "huggingface:teacher-1")13 unmodified linesself.assertEqual(row["course_id"], "local")self.assertEqual(row["quota_units_per_student"], 35)self.assertEqual(row["chat_messages_per_student"], 4)self.assertNotIn("secret_tests", row)def test_publish_rejects_invalid_internal_budget_before_network_access(self):63 unmodified linesself.assertNotIn("quota_units_per_student", updated)self.assertEqual(updated["chat_messages_per_student"], 7)def test_round_transition_preserves_non_publisher_denial(self):round_id = str(uuid4())with patch.object(rounds, "urlopen", return_value=FakeResponse(42 unmodified lines4344454647484913 unmodified lines6364656667686963 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517642 unmodified lines"timer_minutes": 30,"quota_units_per_student": 35,"chat_messages_per_student": 4,"visibility": "public",}with patch.object(rounds, "urlopen", side_effect=[FakeResponse(), FakeResponse()]) as open_url:rounds.save_challenge_round(manifest, b"zip-bundle", "huggingface:teacher-1")13 unmodified linesself.assertEqual(row["course_id"], "local")self.assertEqual(row["quota_units_per_student"], 35)self.assertEqual(row["chat_messages_per_student"], 4)self.assertEqual(row["visibility"], "public")self.assertNotIn("secret_tests", row)def test_publish_rejects_invalid_internal_budget_before_network_access(self):63 unmodified linesself.assertNotIn("quota_units_per_student", updated)self.assertEqual(updated["chat_messages_per_student"], 7)def test_public_catalog_returns_latest_scores_per_participant(self):round_id = str(uuid4())responses = [FakeResponse(json.dumps([{"round_id": round_id,"repo_url": "https://github.com/acme/demo","target_file": "src/main.py","status": "open","created_at": "2026-11-22T10:00:00Z","opened_at": "2026-11-22T10:05:00Z","timer_minutes": 30,"chat_messages_per_student": 5,"published_by": "huggingface:creator",}]).encode()),FakeResponse(json.dumps([{"submission_id": "submission-1", "round_id": round_id, "auth_provider": "huggingface", "provider_user_id": "student-1", "total_score": 80, "submitted_at": "2026-11-22T10:10:00Z"},{"submission_id": "submission-2", "round_id": round_id, "auth_provider": "google", "provider_user_id": "student-2", "total_score": 90, "submitted_at": "2026-11-22T10:11:00Z"},]).encode()),]with patch.object(rounds, "urlopen", side_effect=responses):catalog = rounds.get_public_challenge_rounds("local")self.assertEqual(catalog[0]["participant_count"], 2)self.assertEqual(catalog[0]["submission_count"], 2)self.assertEqual(catalog[0]["average_score"], 85.0)def test_public_submission_claim_rejects_duplicate_in_rpc(self):round_id = str(uuid4())identity = {"provider": "huggingface", "user_id": "student-1"}with patch.object(rounds, "urlopen", return_value=FakeResponse(json.dumps({"claimed": False,"reason": "already_submitted",}).encode())):claim = rounds.claim_public_challenge_submission(round_id, identity, "submission-1")self.assertFalse(claim["claimed"])self.assertEqual(claim["reason"], "already_submitted")def test_round_transition_preserves_non_publisher_denial(self):round_id = str(uuid4())with patch.object(rounds, "urlopen", return_value=FakeResponse(
backend/app.py+25-4
backend/test_api.py+8-6
frontend/src/App.test.tsx+22-3
frontend/src/App.tsx+29-7
frontend/src/api.ts+19-2
frontend/src/styles.css+7
supabase_challenge_rounds.py+112
supabase_schema.sql+57
test_supabase_challenge_rounds.py+40