Spaces:
Sleeping
Sleeping
Enforce shared round chat message cap only
Browse filesFiles changed (13)
- HANDOFF.md+17-17
- README.md+1-1
- SYSTEM_VERIFICATION.md+19-20
- backend/app.py+10-62
- backend/test_api.py+55-77
- challenge_runtime.py+1-6
- frontend/src/App.test.tsx+9-13
- frontend/src/App.tsx+10-27
- frontend/src/api.ts+2-13
- supabase_challenge_rounds.py+4-6
- supabase_history.py+1-2
- supabase_schema.sql+11-39
- test_supabase_challenge_rounds.py+4-4
10 unmodified lines1112131415161723 unmodified lines414243444546474849505152535434 unmodified lines89909192939495969798991008 unmodified lines10911011111211311411511610 unmodified lines## Architecture- `backend/app.py`: OAuth/session handling, student and instructor authorization,challenge jobs, round publishing/admission, history, submissions, and quota APIs.- `architect/`: challenge generation, sabotage, repository cloning, and private testartifacts.- `challenge_runtime.py`: isolated UUID workspaces and immutable shared-round23 unmodified linessnapshot that must be opened.- The challenge solution/diagnosis button is instructor-only in the UI and its APIendpoint also requires the instructor role. Student sessions cannot fetch the diff.- Each round has an instructor-selected cap of 0-100 LLM units per student (default20), selected at publish time, persisted with the round, and frozen on publication.Chat/hint generation costs one unit per provider call; automatic submission gradingcosts two. The official score uses 90% deterministic test results and 10% LLM gradebefore hint and unrelated-function scope penalties. Keyless submissions use testresults alone; a later-added key adds the LLM component without replacing the testscore. An unavailable/exhausted quota leaves deterministic scoring in place. Thecomplete patch is included in the LLM review for line-level minimality assessment.- Personal API keys are held per in-memory session when no server key is configured.They are not written to progress/submission records. Jobs capture the key at enqueue.- Round state transitions compare the requesting instructor identity with the round's34 unmodified lines## VerificationLatest checks after self-service authoring, admin publication, and scoring updates:150 Python tests plus 20 subtests passed; 4 opt-in live-LLM tests skipped; 27 Reacttests, the TypeScript/Vite build, Docker build, Render Blueprint parse, and SQLmigration/rerun plus request, approval, role, and quota smoke tests on local PostgreSQL16 passed. The user reports applying the updated schema to live Supabase; it was notqueried directly during verification. The latest code changes have not been deployed.Localpublic config reports `course_mode=false`, HF and Google OAuth enabled, and dev logindisabled; no identity or secret values are stored in this handoff. The local FastAPI8 unmodified linessandboxing is still deferred.- Student code and private artifacts are still not isolated by an OS/container sandbox;filesystem redaction reduces accidental exposure but is not a hostile-code boundary.- Round quota metering is persistent for shared rounds; unmetered standalone authoringis intended for instructor/local use.## Working Conventions10 unmodified lines1112131415161723 unmodified lines414243444546474849505152535434 unmodified lines89909192939495969798991008 unmodified lines10911011111211311411511610 unmodified lines## Architecture- `backend/app.py`: OAuth/session handling, student and instructor authorization,challenge jobs, round publishing/admission, history, submissions, and usage gates.- `architect/`: challenge generation, sabotage, repository cloning, and private testartifacts.- `challenge_runtime.py`: isolated UUID workspaces and immutable shared-round23 unmodified linessnapshot that must be opened.- The challenge solution/diagnosis button is instructor-only in the UI and its APIendpoint also requires the instructor role. Student sessions cannot fetch the diff.- Each round has one instructor-selected chat-message cap per student (default 5),selected at publish time and frozen when opened. The server enforces this cap forchat; automatic grading has no separate LLM-unit limit. Score-review claims stillenforce ownership, round availability, and idempotency. The official score uses90% deterministic test results and 10% LLM grade before hint and unrelated-function scope penalties.Keyless submissions use test results alone; a later-added key adds the LLM componentwithout replacing the test score. The complete patch is included in LLM review forline-level minimality assessment.- Personal API keys are held per in-memory session when no server key is configured.They are not written to progress/submission records. Jobs capture the key at enqueue.- Round state transitions compare the requesting instructor identity with the round's34 unmodified lines## VerificationLatest one-limit checks: 186 Python tests passed and 4 opt-in live-LLM tests skipped;32 React tests, the TypeScript/Vite build, Docker build, Render Blueprint parse, andSQL migration/rerun plus request, approval, role, and quota smoke tests on localPostgreSQL 16 passed. An earlier schema revision was applied to live Supabase; theone-limit SQL revision still needs to be applied and was not queried directly here.The latest code changes have not been deployed.Localpublic config reports `course_mode=false`, HF and Google OAuth enabled, and dev logindisabled; no identity or secret values are stored in this handoff. The local FastAPI8 unmodified linessandboxing is still deferred.- Student code and private artifacts are still not isolated by an OS/container sandbox;filesystem redaction reduces accidental exposure but is not a hostile-code boundary.- Personal challenge generation retains its separate daily course limit. Shared-roundchat and grading do not use a second LLM-unit cap.## Working Conventions
44 unmodified lines45464748495044 unmodified linesCreate a free Supabase project and configure `SUPABASE_URL` and `SUPABASE_SECRET_KEY` in Hugging Face Spaces Settings. Follow [SUPABASE_SETUP.md](SUPABASE_SETUP.md) for the SQL schema and setup steps.## ScoringThe official score combines the deterministic test score (90%) and, when available, the LLM assessment (10%); hint and deterministic scope penalties are then deducted. In shared rounds, grading costs two LLM units and each chat/hint call costs one. The complete student diff is included in grading so unrelated additions, including lines inside a bug function, can lower the LLM minimality assessment. Keyless submissions and submissions without available quota use the test score alone; adding a key later adds the 10% LLM component without replacing the test score. The deterministic scope penalty is two points per unrelated changed/added function, capped at six; helpers called by a bug function are exempt. Generated challenges may also include one or two regression checks that pass on the received code and can catch a fix that breaks existing behavior. The post-submission expected-changes panel shows only the focused diff, not a full reference file.Google Sheets summaries remain optional. New submissions are no longer uploaded to Git.44 unmodified lines45464748495044 unmodified linesCreate a free Supabase project and configure `SUPABASE_URL` and `SUPABASE_SECRET_KEY` in Hugging Face Spaces Settings. Follow [SUPABASE_SETUP.md](SUPABASE_SETUP.md) for the SQL schema and setup steps.## ScoringThe official score combines the deterministic test score (90%) and, when available, the LLM assessment (10%); hint and deterministic scope penalties are then deducted. Shared rounds have one instructor-set limit: chat messages per student. The server enforces this cap for chat, and no separate LLM-unit limit blocks automatic grading. Score-review claims still enforce ownership, round availability, and idempotency. The complete student diff is included in grading so unrelated additions, including lines inside a bug function, can lower the LLM minimality assessment. Keyless submissions use the test score alone; adding a key later adds the 10% LLM component without replacing the test score. The deterministic scope penalty is two points per unrelated changed/added function, capped at six; helpers called by a bug function are exempt. Generated challenges may also include one or two regression checks that pass on the received code and can catch a fix that breaks existing behavior. The post-submission expected-changes panel shows only the focused diff, not a full reference file.Google Sheets summaries remain optional. New submissions are no longer uploaded to Git.
36 unmodified lines373839404142434445464748495017 unmodified lines686970717273747576777879808182838485868788899091929318 unmodified lines11211311411511611711836 unmodified lines## Implementation Verification: 2026-11-17- Durable quota reservation is wired before chat/hint and automatic submission-gradeLLM calls. The official score blends 90% deterministic tests and 10% LLM grade;keyed submissions consume two units in a shared round, while keyless submissionsretain deterministic scoring without consuming quota. Instructors set a 0–100 per-student cap when publishing (default20); it is stored with and frozen for the round.- Shared rounds now follow `prepared` -> `open` -> `closed`; publication stores thepublisher and configured course ID. Admission and quota reservation are designedto serialize against close through service-only PostgreSQL RPCs. Re-publishing thesame workspace in a session returns its existing round code without creating asecond snapshot or storage upload; a new workspace gets a new code.- Roles are resolved server-side from `COURSE_INSTRUCTOR_IDENTITIES` entries in17 unmodified lines- The same Python regression set passed inside the rebuilt image as non-root:136 passed, 20 subtests passed.- PostgreSQL 16 applied `supabase_schema.sql` twice without errors in a disposablecontainer. Transactional RPC smoke checks passed for quota reserve, idempotentscore-review claim/completion, round open/close, and rejection of admission afterclose. Quota cap boundaries 0 and 100 were accepted and 101 was rejected. Thedatabase used local stubs for Supabase roles and `storage.buckets`; it does notverify permissions in the user's live project.- The user confirmed the earlier SQL revision completed successfully in Supabase.The 0–100 quota-cap constraints were added afterward; the latest SQL revision hasbeen verified against disposable PostgreSQL but has not yet been rerun in the liveproject. This session has no Supabase server settings to inspect it directly.### Remaining Deployment Checks- Rerun the latest `supabase_schema.sql` in the intended project to install the newquota-cap constraints and confirm the tables, `course_id` columns, and service-onlyRPC grants are visible. Existing rows default to `course_id='local'`; backfill onlyafter identifying their actual course owner.- Configure `COURSE_ID`, `COURSE_INSTRUCTOR_IDENTITIES`, and`COURSE_APPROVED_REPOSITORIES` as server-side settings.Never put role grants or storage secrets in the frontend.- Verify Supabase RPC signatures, concurrent quota reservations, round close races,private storage access, and history filters in a disposable Supabase project.- Verify HF and Google OAuth callbacks in the intended deployment; mocked OAuthfixtures do not certify provider configuration.18 unmodified lines| Challenge creation | Unique workspace, initial checkpoint before scoring, timer and options passed through, generation failure releases operation | `backend/test_api.py`, `test_challenge_runtime.py` || Generation and diagnosis | Literal-only generated arguments, changed functions, detectable bugs, refactored solution reconstruction without changing student code | `test_saboteur_generated_test_validation.py`, `backend/test_api.py` || Shared rounds | Durable publish failure, join isolation, artifact hashes, archive restoration across different roots, unchanged source template | `test_challenge_runtime.py`, `test_supabase_challenge_rounds.py`, `backend/test_api.py` || Quotas | Instructor-selected 0–100 per-round cap (default 20), frozen per round; atomic operation ledger, one unit per chat/hint call, two-unit advisory opt-in | `test_supabase_quota.py`, `test_supabase_challenge_rounds.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` || Round lifecycle | Prepared/open/closed transitions, publisher authorization, course-scoped admission, no join after close | `test_supabase_challenge_rounds.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` || Roles and authoring | Exact provider/subject instructor allowlist, invite-code student admission, approved-repository validation | `backend/test_api.py`, `frontend/src/App.test.tsx` || Student history | Owner/course-filtered summaries, secret payload redaction, local unfinished-attempt resume | `test_supabase_history.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` |36 unmodified lines3738394041424344454647484917 unmodified lines676869707172737475767778798081828384858687888990919218 unmodified lines11111211311411511611736 unmodified lines## Implementation Verification: 2026-11-17- Shared rounds enforce one instructor-set 0–100 chat-message cap per student(default 5), stored with and frozen for the round. Automatic grading is not gatedby a separate LLM-unit cap. The official score blends 90% deterministic tests and10% LLM grade when a model key is available.- Shared rounds now follow `prepared` -> `open` -> `closed`; publication stores thepublisher and configured course ID. Admission is designed to serialize againstclose through service-only PostgreSQL RPCs. Re-publishing thesame workspace in a session returns its existing round code without creating asecond snapshot or storage upload; a new workspace gets a new code.- Roles are resolved server-side from `COURSE_INSTRUCTOR_IDENTITIES` entries in17 unmodified lines- The same Python regression set passed inside the rebuilt image as non-root:136 passed, 20 subtests passed.- PostgreSQL 16 applied `supabase_schema.sql` twice without errors in a disposablecontainer. Transactional RPC smoke checks passed for the legacy quota-reservationRPC, idempotent score-review claim/completion, round open/close, and rejection ofadmission after close. The instructor-facing chat-message cap accepts 0–100 andrejects 101; score-review claims do not reserve or check round LLM units. Thedatabase used local stubs for Supabase roles and `storage.buckets`; it does notverify permissions in the user's live project.- The user confirmed an earlier SQL revision completed successfully in Supabase.The one-limit revision is verified against disposable PostgreSQL but has not beenrerun in the live project. This session has no Supabase settings to inspect it.### Remaining Deployment Checks- Rerun the latest `supabase_schema.sql` in the intended project to install themessage-cap and score-review RPC updates and confirm the tables, `course_id`columns, and service-only RPC grants are visible. Existing rows default to`course_id='local'`; backfill only after identifying their actual course owner.- Configure `COURSE_ID`, `COURSE_INSTRUCTOR_IDENTITIES`, and`COURSE_APPROVED_REPOSITORIES` as server-side settings.Never put role grants or storage secrets in the frontend.- Verify Supabase RPC signatures, score-review idempotency, round close races,private storage access, and history filters in a disposable Supabase project.- Verify HF and Google OAuth callbacks in the intended deployment; mocked OAuthfixtures do not certify provider configuration.18 unmodified lines| Challenge creation | Unique workspace, initial checkpoint before scoring, timer and options passed through, generation failure releases operation | `backend/test_api.py`, `test_challenge_runtime.py` || Generation and diagnosis | Literal-only generated arguments, changed functions, detectable bugs, refactored solution reconstruction without changing student code | `test_saboteur_generated_test_validation.py`, `backend/test_api.py` || Shared rounds | Durable publish failure, join isolation, artifact hashes, archive restoration across different roots, unchanged source template | `test_challenge_runtime.py`, `test_supabase_challenge_rounds.py`, `backend/test_api.py` || Chat limit | One instructor-selected 0–100 message cap per student (default 5); no separate LLM-unit cap blocks automatic grading | `test_supabase_challenge_rounds.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` || Round lifecycle | Prepared/open/closed transitions, publisher authorization, course-scoped admission, no join after close | `test_supabase_challenge_rounds.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` || Roles and authoring | Exact provider/subject instructor allowlist, invite-code student admission, approved-repository validation | `backend/test_api.py`, `frontend/src/App.test.tsx` || Student history | Owner/course-filtered summaries, secret payload redaction, local unfinished-attempt resume | `test_supabase_history.py`, `backend/test_api.py`, `frontend/src/App.test.tsx` |
47 unmodified lines4849505152535455166 unmodified lines2222232242252262272283 unmodified lines232233234235236237238151 unmodified lines390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425697 unmodified lines11231124112511261127112811291 unmodified line11311132113311341135113611371138113911401141114211435 unmodified lines114911501151115211531154101 unmodified lines12561257125812591260126112623 unmodified lines12661267126812691270127112721273127412751276127739 unmodified lines13171318131913201321132213231324132513261327132813291330133113321333151 unmodified lines1485148614871488148914901491350 unmodified lines184218431844184518461847184818491850293 unmodified lines214421452146214721482149215081 unmodified lines223222332234223522362237223822392240224122422243224426 unmodified lines2271227222732274227522762277227822792280113 unmodified lines2394239523962397239823992400240138 unmodified lines244024412442244324442445244647 unmodified linesclaim_submission_score_review,complete_submission_score_review,fail_submission_score_review,get_round_llm_quota,reserve_round_llm_quota,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_student_historyfrom supabase_course_access import (166 unmodified linesclass ChallengeRoundPublishRequest(BaseModel):quota_units_per_student: int = Field(default=20, ge=0, le=100, strict=True)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)3 unmodified linestime_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)quota_units_per_student: int = Field(ge=0, le=100, strict=True)class FileWriteRequest(BaseModel):151 unmodified linesraise HTTPException(status_code=400, detail="Add an OpenAI or Groq API key for this session")def _reserve_session_llm_quota(session: UserSession,operation_id: str,operation_type: str,units: int = 1,) -> dict[str, Any] | None:if not session.challenge_round_id:return Nonetry:result = reserve_round_llm_quota(session.challenge_round_id, session.identity, operation_type, units, operation_id)except LLMQuotaStoreError as exc:logger.warning("Round LLM quota reservation failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Round usage limit is temporarily unavailable; no LLM request was sent") from excif not result.get("reserved"):reason = result.get("reason")if reason == "quota_exhausted":raise HTTPException(status_code=429,detail=f"Round LLM usage limit reached ({result.get('units_used', 0)}/{result.get('units_limit', 0)} units).",)if reason == "duplicate_operation":raise HTTPException(status_code=409, detail="This LLM operation was already charged")if reason == "round_unavailable":raise HTTPException(status_code=410, detail="This challenge round is closed or unavailable for LLM requests")raise HTTPException(status_code=503, detail="Could not reserve round LLM usage")return resultdef _clear_active_job(session: UserSession, job_id: str) -> None:with session.thread_lock:if session.active_job_id == job_id:697 unmodified linestime_limit_enabled=timer_minutes > 0,timer_minutes=timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,quota_units_per_student=payload.quota_units_per_student,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)1 unmodified lineif updated is None:raise HTTPException(status_code=409, detail="Only a prepared challenge round can be edited")previous.update(updated)session.published_round = dict(previous)_persist_challenge_progress(session)return dict(previous)manifest = create_challenge_round(session.workspace_path,timer_minutes,payload.quota_units_per_student,payload.chat_messages_per_student,)try:5 unmodified lineslogger.warning("Persistent challenge round publish failed: %s", type(exc).__name__)detail = str(exc) if isinstance(exc, ChallengeRoundStoreError) else "Could not package this challenge for persistent storage"raise HTTPException(status_code=503, detail=detail) from excmanifest["persistence"] = "supabase"manifest["status"] = "prepared"manifest["course_id"] = _course_id()101 unmodified linestime_limit_enabled=payload.time_limit_enabled,timer_minutes=payload.timer_minutes,chat_messages_per_student=payload.chat_messages_per_student,quota_units_per_student=payload.quota_units_per_student,)except ChallengeRoundStoreError as exc:logger.warning("Challenge round settings update failed: %s", type(exc).__name__)3 unmodified linestimer_minutes = int(updated["timer_minutes"])if session.published_round and session.published_round.get("round_id") == round_id:session.published_round.update(updated)if session.challenge_round_id == round_id:session.challenge_timer_minutes = timer_minutessession.timer_deadline = time.time() + timer_minutes * 60 if timer_minutes else Nonesession.chat_messages_per_student = int(updated["chat_messages_per_student"])if session.workspace_path:_persist_challenge_progress(session)return updatedfinally:_release_session_operation(session, operation_id)39 unmodified lines}@app.get("/api/session/quota")def get_session_quota(session: UserSession = Depends(require_session)) -> dict[str, Any]:if not session.challenge_round_id:return {"enabled": False, "units_limit": None, "units_used": 0, "units_remaining": None}try:return {"enabled": True, **get_round_llm_quota(session.challenge_round_id, session.identity)}except LLMQuotaStoreError as exc:logger.warning("Round LLM quota lookup failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Round usage limit is temporarily unavailable") from excdef _local_student_history(identity: dict[str, str], limit: int) -> dict[str, list[dict[str, Any]]]:attempts: list[dict[str, Any]] = []submissions: list[dict[str, Any]] = []151 unmodified lines"created_at": row.get("created_at"),"opened_at": row.get("opened_at"),"closed_at": row.get("closed_at"),"quota_units_per_student": row.get("quota_units_per_student"),"participants": participants,})return {"rounds": rounds}350 unmodified linesif confirmed and session.pending_hint_result is not None:result = session.pending_hint_resultelse:await run_in_threadpool(_reserve_session_llm_quota, session, operation_id, "chat", 1)result = await asyncio.to_thread(generate_hint)session.pending_hint_result = Noneif (result.get("gave_hint") or result.get("hint_summary")) and not confirmed:293 unmodified lineswith session.thread_lock:if session.last_submission_id == submission_id and session.last_submission_result is not None:session.last_submission_result["llm_review_status"] = "failed"job.error = "Advisory review failed after quota was reserved. It will not be retried or charged again."job.status = "failed"finally:with session.thread_lock:81 unmodified linesrecord["submission_id"], dict(session.identity), str(uuid4()))except LLMQuotaStoreError as exc:logger.warning("Automatic score quota claim failed: %s", type(exc).__name__)review_status = "quota_unavailable"else:if claim.get("claimed"):review_claimed = Trueelif claim.get("reason") == "quota_exhausted":review_status = "quota_exhausted"else:review_status = "quota_unavailable"26 unmodified linesrecord["scoring"]["llm_review_status"] = review_statusif review_status == "not_requested":result["llm_explanation"] = "No model key was available; the score is based on test results."elif review_status == "quota_exhausted":result["llm_explanation"] = "LLM grading was skipped because the round usage limit is exhausted; the deterministic score is shown."elif review_status == "quota_unavailable":result["llm_explanation"] = "LLM grading could not start because round usage could not be verified; the deterministic score is shown."elif review_status == "failed":result["llm_explanation"] = "LLM grading failed; the deterministic score is shown."record["scoring"]["llm_explanation"] = result["llm_explanation"]113 unmodified linestry:claim = claim_submission_score_review(submission_id, dict(session.identity), str(uuid4()))except LLMQuotaStoreError as exc:logger.warning("Score review quota claim failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Round usage limit is temporarily unavailable; no review was started") from excif not claim.get("claimed"):status = claim.get("status")if status == "completed":38 unmodified linesreturn {"status": "processing"}reason = claim.get("reason")if reason == "quota_exhausted":raise HTTPException(status_code=429, detail=f"Round LLM usage limit reached ({claim.get('units_used', 0)}/{claim.get('units_limit', 0)} units).")if reason == "round_unavailable":raise HTTPException(status_code=410, detail="This challenge round is closed or unavailable for LLM reviews")if reason == "submission_not_found":47 unmodified lines484950515253166 unmodified lines2202212222232242253 unmodified lines229230231232233234151 unmodified lines386387388389390391697 unmodified lines1089109010911092109310941 unmodified line10961097109810991100110111021103110411051106110711085 unmodified lines1114111511161117111811191120101 unmodified lines1222122312241225122612273 unmodified lines1231123212331234123512361237123812391240124112421243124439 unmodified lines128412851286128712881289151 unmodified lines144114421443144414451446350 unmodified lines179717981799180018011802293 unmodified lines209620972098209921002101210281 unmodified lines2184218521862187218821892190219121922193219426 unmodified lines22212222222322242225222622272228113 unmodified lines2342234323442345234623472348234938 unmodified lines238823892390239123922393239447 unmodified linesclaim_submission_score_review,complete_submission_score_review,fail_submission_score_review,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_student_historyfrom supabase_course_access import (166 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)3 unmodified linestime_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)class FileWriteRequest(BaseModel):151 unmodified linesraise HTTPException(status_code=400, detail="Add an OpenAI or Groq API key for this session")def _clear_active_job(session: UserSession, job_id: str) -> None:with session.thread_lock:if session.active_job_id == job_id:697 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__)1 unmodified lineif updated is None:raise HTTPException(status_code=409, detail="Only a prepared challenge round can be edited")previous.update(updated)previous.pop("quota_units_per_student", None)session.published_round = dict(previous)_persist_challenge_progress(session)return dict(previous)manifest = create_challenge_round(session.workspace_path,timer_minutes,payload.chat_messages_per_student,)try:5 unmodified lineslogger.warning("Persistent challenge round publish failed: %s", type(exc).__name__)detail = 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()101 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__)3 unmodified linestimer_minutes = int(updated["timer_minutes"])if session.published_round and session.published_round.get("round_id") == round_id:session.published_round.update(updated)session.published_round.pop("quota_units_per_student", None)if session.challenge_round_id == round_id:session.challenge_timer_minutes = timer_minutessession.timer_deadline = time.time() + timer_minutes * 60 if timer_minutes else Nonesession.chat_messages_per_student = int(updated["chat_messages_per_student"])if session.workspace_path:_persist_challenge_progress(session)updated.pop("quota_units_per_student", None)return updatedfinally:_release_session_operation(session, operation_id)39 unmodified lines}def _local_student_history(identity: dict[str, str], limit: int) -> dict[str, list[dict[str, Any]]]:attempts: list[dict[str, Any]] = []submissions: list[dict[str, Any]] = []151 unmodified lines"created_at": row.get("created_at"),"opened_at": row.get("opened_at"),"closed_at": row.get("closed_at"),"participants": participants,})return {"rounds": rounds}350 unmodified linesif confirmed and session.pending_hint_result is not None:result = session.pending_hint_resultelse:result = await asyncio.to_thread(generate_hint)session.pending_hint_result = Noneif (result.get("gave_hint") or result.get("hint_summary")) and not confirmed:293 unmodified lineswith session.thread_lock:if session.last_submission_id == submission_id and session.last_submission_result is not None:session.last_submission_result["llm_review_status"] = "failed"job.error = "Advisory review failed. It will not be retried."job.status = "failed"finally:with session.thread_lock:81 unmodified linesrecord["submission_id"], dict(session.identity), str(uuid4()))except LLMQuotaStoreError as exc:logger.warning("Automatic score-review claim failed: %s", type(exc).__name__)review_status = "quota_unavailable"else:if claim.get("claimed"):review_claimed = Trueelse:review_status = "quota_unavailable"26 unmodified linesrecord["scoring"]["llm_review_status"] = review_statusif review_status == "not_requested":result["llm_explanation"] = "No model key was available; the score is based on test results."elif review_status == "quota_unavailable":result["llm_explanation"] = "LLM grading could not start because score-review storage is unavailable; the deterministic score is shown."elif review_status == "failed":result["llm_explanation"] = "LLM grading failed; the deterministic score is shown."record["scoring"]["llm_explanation"] = result["llm_explanation"]113 unmodified linestry:claim = claim_submission_score_review(submission_id, dict(session.identity), str(uuid4()))except LLMQuotaStoreError as exc:logger.warning("Score review claim failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Score-review storage is temporarily unavailable; no review was started") from excif not claim.get("claimed"):status = claim.get("status")if status == "completed":38 unmodified linesreturn {"status": "processing"}reason = claim.get("reason")if reason == "quota_exhausted":raise HTTPException(status_code=503, detail="The database schema must be updated before LLM grading is available")if reason == "round_unavailable":raise HTTPException(status_code=410, detail="This challenge round is closed or unavailable for LLM reviews")if reason == "submission_not_found":
811 unmodified lines81281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285345 unmodified lines899900901902903904905214 unmodified lines112011211122112311241125112611271128112911301131121 unmodified lines12531254125512561257125812591260126112621263126435 unmodified lines13001301130213031304130513061307130813091310131116 unmodified lines13281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135715 unmodified lines13731374137513761377137813791380138114 unmodified lines139613971398139914001401140213 unmodified lines141614171418141914201421142249 unmodified lines14721473147414751476147714781479148014811482148314841485148650 unmodified lines15371538153915401541154215433 unmodified lines15471548154915501551155215536 unmodified lines15601561156215631564156515666 unmodified lines157315741575157615771578157951 unmodified lines16311632163316341635163616371 unmodified line1639164016411642164316441645164616471648164916501651165216531654165516561657726 unmodified lines23842385238623872388238923908 unmodified lines239924002401240224032404240524062407240824092410241124122413811 unmodified linesinstructor = self.add_session(workspace_path=str(source))instructor.challenge_timer_minutes = 25with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "create_challenge_round", wraps=api.create_challenge_round) as create_round, patch.object(api, "create_challenge_round_archive", return_value=b"zip-bundle"), patch.object(api, "save_challenge_round") as save_round, patch.object(api, "update_challenge_round_settings", side_effect=lambda round_id, *_args, **_kwargs: {"round_id": round_id, "timer_minutes": 25,"chat_messages_per_student": 5, "quota_units_per_student": 80,"status": "prepared",},) as update_settings:published = self.client.post("/api/challenge-rounds", json={"quota_units_per_student": 35})repeated = self.client.post("/api/challenge-rounds", json={"quota_units_per_student": 80})self.assertEqual(published.status_code, 200)self.assertEqual(repeated.status_code, 200)round_info = published.json()self.assertEqual(round_info["persistence"], "supabase")self.assertEqual(round_info["quota_units_per_student"], 35)self.assertEqual(repeated.json()["round_id"], round_info["round_id"])self.assertEqual(repeated.json()["artifact_hash"], round_info["artifact_hash"])self.assertEqual(repeated.json()["quota_units_per_student"], 80)create_round.assert_called_once_with(str(source), 25, 35, 5)update_settings.assert_called_once()save_round.assert_called_once()def verify_round_saved(manifest, archive, published_by, course_id):self.assertEqual(manifest["round_id"], round_info["round_id"])self.assertEqual(archive, b"zip-bundle")self.assertEqual(published_by, "development:test-user")self.assertEqual(course_id, "local")self.assertEqual(manifest["quota_units_per_student"], 35)save_round.assert_called_once_with(save_round.call_args.args[0], b"zip-bundle", "development:test-user", "local")verify_round_saved(*save_round.call_args.args)with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "transition_challenge_round", return_value={"updated": True, "status": "open"}45 unmodified lineswith 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={"quota_units_per_student": 100})self.assertEqual(opened.status_code, 403)self.assertEqual(closed.status_code, 403)self.assertEqual(publish.status_code, 403)214 unmodified linesself.assertEqual(reviewed.status_code, 200)review_request.assert_called_once_with(request_id, "owner/course-space", session.identity, "approved")def test_round_publish_rejects_out_of_range_instructor_quota(self):session = self.add_session(workspace_path="unused-workspace")with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "create_challenge_round") as create_round:response = self.client.post("/api/challenge-rounds", json={"quota_units_per_student": 101})self.assertEqual(response.status_code, 422)create_round.assert_not_called()self.assertEqual(session.active_job_id, None)121 unmodified lines"teacher-2": ("google", "teacher-2"),}round_ids = {teacher_id: str(uuid4()) for teacher_id in teacher_specs}quota_limit = 6workspace_rounds = {}workspace_owners = {}manifests = {}round_states = {round_id: "prepared" for round_id in round_ids.values()}quota_usage = {}joined_students = set()submission_rounds = {}participations = {index: [] for index in range(10)}35 unmodified lines(private / "challenge_run_secret.py").write_text(runner, encoding="utf-8")(private / "secret_tests.json").write_text(json.dumps({"secret_tests": []}), encoding="utf-8")def fake_create_round(workspace_path, timer_minutes, student_quota, chat_limit):round_id = workspace_rounds[str(workspace_path)]manifest = dict(manifests[round_id])manifest["timer_minutes"] = timer_minutesmanifest["quota_units_per_student"] = student_quotamanifest["chat_messages_per_student"] = chat_limitreturn manifestdef fake_transition(round_id, actor, action, course_id):16 unmodified lineswrite_workspace(workspace, round_id)return str(workspace), dict(manifests[round_id])def fake_reserve(round_id, identity, operation_type, units, operation_id=None):key = (round_id, identity["provider"], identity["user_id"])used = quota_usage.get(key, 0)if used + units > quota_limit:return {"reserved": False, "reason": "quota_exhausted", "units_limit": quota_limit, "units_used": used}quota_usage[key] = used + unitsreturn {"reserved": True, "units_limit": quota_limit, "units_used": used + units}def fake_quota(round_id, identity):key = (round_id, identity["provider"], identity["user_id"])used = quota_usage.get(key, 0)return {"round_id": round_id, "units_limit": quota_limit, "units_used": used, "units_remaining": quota_limit - used}def fake_upload(record):submission_rounds[record["submission_id"]] = record["challenge"]["round_id"]return True, ""def fake_claim(submission_id, identity, operation_id):round_id = submission_rounds[submission_id]key = (round_id, identity["provider"], identity["user_id"])used = quota_usage.get(key, 0)if used + 2 > quota_limit:return {"claimed": False, "reason": "quota_exhausted", "units_limit": quota_limit, "units_used": used}quota_usage[key] = used + 2return {"claimed": True, "status": "processing", "units": 2}def fake_hint(*, user_message, **kwargs):15 unmodified linesapi, "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(api, "reserve_round_llm_quota", side_effect=fake_reserve), patch.object(api, "get_round_llm_quota", side_effect=fake_quota), patch.object(api, "upload_submission_to_supabase", side_effect=fake_upload), patch.object(api, "claim_submission_score_review", side_effect=fake_claim), patch.object(api, "complete_submission_score_review", return_value={"completed": True}), patch.object(api, "get_hint", side_effect=fake_hint14 unmodified lines"artifact_hash": "a" * 64,"tests_hash": "b" * 64,"timer_minutes": 15,"quota_units_per_student": quota_limit,"status": "prepared",}session = self.add_session(api_key="simulation-key", workspace_path=str(workspace))13 unmodified linesfor teacher_id, (_provider, _user_id) in teacher_specs.items():teacher = next(session for session in api.app.state.sessions.values() if session.identity.get("user_id") == _user_id)self.client.cookies.set(api.SESSION_COOKIE, teacher.session_id)published = self.client.post("/api/challenge-rounds", json={"quota_units_per_student": quota_limit})self.assertEqual(published.status_code, 200, published.text)self.assertEqual(published.json()["round_id"], round_ids[teacher_id])opened = self.client.post(f"/api/challenge-rounds/{round_ids[teacher_id]}/open")49 unmodified linesself.assertEqual(result["llm_score"], 90)self.assertEqual(result["score"], 97)self.assertEqual(result["passed"], result["total_tests"])quota = self.client.get("/api/session/quota").json()self.assertEqual(quota["units_used"], 4)self.assertEqual(quota["units_remaining"], 2)self.assertEqual(len([round_id for ids in participations.values() for round_id in ids]), 12)self.assertEqual([len(ids) for ids in participations.values()], [1] * 8 + [2, 2])self.assertEqual(review.call_count, 12)self.assertEqual(len(quota_usage), 12)self.assertTrue(all(used == 4 for used in quota_usage.values()))self.client.cookies.set(api.SESSION_COOKIE, student_sessions[0].session_id)repeated_join = self.client.post("/api/challenges", json={"round_id": round_ids["teacher-1"]})50 unmodified lines"round_id": round_id,"timer_minutes": 0,"chat_messages_per_student": 8,"quota_units_per_student": 30,"status": "prepared",}with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(3 unmodified lines"time_limit_enabled": False,"timer_minutes": 30,"chat_messages_per_student": 8,"quota_units_per_student": 30,})self.assertEqual(response.status_code, 200)6 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=8,quota_units_per_student=30,)def test_timed_round_requires_a_positive_duration(self):6 unmodified lines"time_limit_enabled": True,"timer_minutes": 0,"chat_messages_per_student": 5,"quota_units_per_student": 20,})self.assertEqual(response.status_code, 422)51 unmodified linesself.assertEqual(second["hints_used"], 1)self.assertEqual(second["penalty"], 2)def test_hint_quota_denial_and_store_failure_never_call_model(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):workspace = Path(root) / "challenge"workspace.mkdir()1 unmodified line(workspace / "challenge_state.json").write_text(json.dumps({"target_file": "main.py"}), encoding="utf-8")session = self.add_session(workspace_path=str(workspace))session.challenge_round_id = str(uuid4())with patch.object(api, "reserve_round_llm_quota", return_value={"reserved": False, "reason": "quota_exhausted", "units_limit": 2, "units_used": 2,}), patch.object(api, "get_hint") as get_hint:exhausted = self.client.post("/api/challenge/hints", json={"message": "Help me debug"})self.assertEqual(exhausted.status_code, 429)get_hint.assert_not_called()with patch.object(api, "reserve_round_llm_quota", side_effect=api.LLMQuotaStoreError("unavailable")), patch.object(api, "get_hint") as get_hint:unavailable = self.client.post("/api/challenge/hints", json={"message": "Explain this behavior"})self.assertEqual(unavailable.status_code, 503)get_hint.assert_not_called()def test_completed_score_review_is_returned_without_second_claim(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):726 unmodified linesself.assertIs(evaluate.call_args.kwargs["include_llm_review"], False)review.assert_not_called()def test_score_review_quota_exhaustion_never_calls_advisory_model(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):workspace = Path(root) / "challenge"workspace.mkdir()8 unmodified linesrecords.mkdir()(records / "submission-1.json").write_text(json.dumps({"submission": {"bug_function_names": ["result"], "changed_function_names": ["result"]},}), encoding="utf-8")with patch.object(api, "claim_submission_score_review", return_value={"claimed": False, "reason": "quota_exhausted", "units_limit": 2, "units_used": 2,}), patch.object(api, "review_submission_record") as review:response = self.client.post("/api/submissions/submission-1/score-review")self.assertEqual(response.status_code, 429)review.assert_not_called()self.assertEqual(session.last_submission_result["score"], 80)def test_second_submission_while_first_is_queued_cannot_overwrite_code(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):811 unmodified lines81281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085145 unmodified lines897898899900901902903214 unmodified lines111811191120112111221123112411251126112711281129121 unmodified lines1251125212531254125512561257125812591260126135 unmodified lines1297129812991300130113021303130413051306130716 unmodified lines1324132513261327132813291330133113321333133415 unmodified lines13501351135213531354135513561357135814 unmodified lines137313741375137613771378137913 unmodified lines139313941395139613971398139949 unmodified lines1449145014511452145314541455145614571458145950 unmodified lines1510151115121513151415153 unmodified lines1519152015211522152315246 unmodified lines1531153215331534153515366 unmodified lines15431544154515461547154851 unmodified lines16001601160216031604160516061 unmodified line1608160916101611161216131614161516161617161816191620162116221623726 unmodified lines23502351235223532354235523568 unmodified lines236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391811 unmodified linesinstructor = self.add_session(workspace_path=str(source))instructor.challenge_timer_minutes = 25saved_manifests = []with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "create_challenge_round", wraps=api.create_challenge_round) as create_round, patch.object(api, "create_challenge_round_archive", return_value=b"zip-bundle"), patch.object(api, "save_challenge_round", side_effect=lambda manifest, *_args: saved_manifests.append(dict(manifest))) as save_round, patch.object(api, "update_challenge_round_settings", side_effect=lambda round_id, *_args, **kwargs: {"round_id": round_id, "timer_minutes": 25,"chat_messages_per_student": kwargs["chat_messages_per_student"],"status": "prepared",},) as update_settings:published = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": 35})repeated = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": 80})self.assertEqual(published.status_code, 200)self.assertEqual(repeated.status_code, 200)round_info = published.json()self.assertEqual(round_info["persistence"], "supabase")self.assertEqual(round_info["chat_messages_per_student"], 35)self.assertNotIn("quota_units_per_student", round_info)self.assertEqual(repeated.json()["round_id"], round_info["round_id"])self.assertEqual(repeated.json()["artifact_hash"], round_info["artifact_hash"])self.assertEqual(repeated.json()["chat_messages_per_student"], 80)self.assertNotIn("quota_units_per_student", repeated.json())create_round.assert_called_once_with(str(source), 25, 35)update_settings.assert_called_once()save_round.assert_called_once()save_round.assert_called_once_with(save_round.call_args.args[0], b"zip-bundle", "development:test-user", "local")self.assertEqual(saved_manifests[0]["round_id"], round_info["round_id"])self.assertEqual(saved_manifests[0]["quota_units_per_student"], 37)self.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"}45 unmodified lineswith 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})self.assertEqual(opened.status_code, 403)self.assertEqual(closed.status_code, 403)self.assertEqual(publish.status_code, 403)214 unmodified linesself.assertEqual(reviewed.status_code, 200)review_request.assert_called_once_with(request_id, "owner/course-space", session.identity, "approved")def test_round_publish_rejects_out_of_range_chat_message_limit(self):session = self.add_session(workspace_path="unused-workspace")with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "create_challenge_round") as create_round:response = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": 101})self.assertEqual(response.status_code, 422)create_round.assert_not_called()self.assertEqual(session.active_job_id, None)121 unmodified lines"teacher-2": ("google", "teacher-2"),}round_ids = {teacher_id: str(uuid4()) for teacher_id in teacher_specs}chat_limit = 4workspace_rounds = {}workspace_owners = {}manifests = {}round_states = {round_id: "prepared" for round_id in round_ids.values()}joined_students = set()submission_rounds = {}participations = {index: [] for index in range(10)}35 unmodified lines(private / "challenge_run_secret.py").write_text(runner, encoding="utf-8")(private / "secret_tests.json").write_text(json.dumps({"secret_tests": []}), encoding="utf-8")def fake_create_round(workspace_path, timer_minutes, round_chat_limit):round_id = workspace_rounds[str(workspace_path)]manifest = dict(manifests[round_id])manifest["timer_minutes"] = timer_minutesmanifest["chat_messages_per_student"] = round_chat_limitreturn manifestdef fake_transition(round_id, actor, action, course_id):16 unmodified lineswrite_workspace(workspace, round_id)return str(workspace), dict(manifests[round_id])def fake_upload(record):submission_rounds[record["submission_id"]] = record["challenge"]["round_id"]return True, ""def fake_claim(submission_id, identity, operation_id):return {"claimed": True, "status": "processing", "units": 2}def fake_hint(*, user_message, **kwargs):15 unmodified linesapi, "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(api, "upload_submission_to_supabase", side_effect=fake_upload), patch.object(api, "claim_submission_score_review", side_effect=fake_claim), patch.object(api, "complete_submission_score_review", return_value={"completed": True}), patch.object(api, "get_hint", side_effect=fake_hint14 unmodified lines"artifact_hash": "a" * 64,"tests_hash": "b" * 64,"timer_minutes": 15,"chat_messages_per_student": chat_limit,"status": "prepared",}session = self.add_session(api_key="simulation-key", workspace_path=str(workspace))13 unmodified linesfor teacher_id, (_provider, _user_id) in teacher_specs.items():teacher = next(session for session in api.app.state.sessions.values() if session.identity.get("user_id") == _user_id)self.client.cookies.set(api.SESSION_COOKIE, teacher.session_id)published = self.client.post("/api/challenge-rounds", json={"chat_messages_per_student": chat_limit})self.assertEqual(published.status_code, 200, published.text)self.assertEqual(published.json()["round_id"], round_ids[teacher_id])opened = self.client.post(f"/api/challenge-rounds/{round_ids[teacher_id]}/open")49 unmodified linesself.assertEqual(result["llm_score"], 90)self.assertEqual(result["score"], 97)self.assertEqual(result["passed"], result["total_tests"])self.assertEqual(session.chat_messages_used, 2 * len(participations[student_index]))self.assertEqual(len([round_id for ids in participations.values() for round_id in ids]), 12)self.assertEqual([len(ids) for ids in participations.values()], [1] * 8 + [2, 2])self.assertEqual(review.call_count, 12)self.client.cookies.set(api.SESSION_COOKIE, student_sessions[0].session_id)repeated_join = self.client.post("/api/challenges", json={"round_id": round_ids["teacher-1"]})50 unmodified lines"round_id": round_id,"timer_minutes": 0,"chat_messages_per_student": 8,"status": "prepared",}with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(3 unmodified lines"time_limit_enabled": False,"timer_minutes": 30,"chat_messages_per_student": 8,})self.assertEqual(response.status_code, 200)6 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=8,)def test_timed_round_requires_a_positive_duration(self):6 unmodified lines"time_limit_enabled": True,"timer_minutes": 0,"chat_messages_per_student": 5,})self.assertEqual(response.status_code, 422)51 unmodified linesself.assertEqual(second["hints_used"], 1)self.assertEqual(second["penalty"], 2)def test_chat_hint_is_not_limited_by_a_separate_unit_quota(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):workspace = Path(root) / "challenge"workspace.mkdir()1 unmodified line(workspace / "challenge_state.json").write_text(json.dumps({"target_file": "main.py"}), encoding="utf-8")session = self.add_session(workspace_path=str(workspace))session.challenge_round_id = str(uuid4())with patch.object(api, "_persist_challenge_progress"), patch.object(api, "get_hint", return_value={"response": "Check the current code against the public example.","gave_hint": False,"hint_summary": "",}) as get_hint:response = self.client.post("/api/challenge/hints", json={"message": "Help me debug"})self.assertEqual(response.status_code, 200)get_hint.assert_called_once()self.assertEqual(session.chat_messages_used, 1)def test_completed_score_review_is_returned_without_second_claim(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):726 unmodified linesself.assertIs(evaluate.call_args.kwargs["include_llm_review"], False)review.assert_not_called()def test_score_review_claim_allows_grading_without_unit_limit(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):workspace = Path(root) / "challenge"workspace.mkdir()8 unmodified linesrecords.mkdir()(records / "submission-1.json").write_text(json.dumps({"submission": {"bug_function_names": ["result"], "changed_function_names": ["result"]},"scoring": {"test_score": 80, "hint_penalty": 0, "scope_penalty": 0},}), encoding="utf-8")with patch.object(api, "claim_submission_score_review", return_value={"claimed": True, "status": "processing",}) as claim, patch.object(api, "review_submission_record", return_value={"score": 90, "explanation": "The fix is correct and focused.",}) as review, patch.object(api, "complete_submission_score_review", return_value={"completed": True,}) as complete, patch.object(api, "upload_submission_to_supabase", return_value=(True, "")), patch.object(api.app.state, "executor", self.ImmediateExecutor()):response = self.client.post("/api/submissions/submission-1/score-review")job = self.client.get(f"/api/jobs/{response.json()['job_id']}").json()self.assertEqual(response.status_code, 202)self.assertEqual(job["status"], "completed")self.assertEqual(job["result"]["llm_score"], 90)self.assertEqual(job["result"]["status"], "completed")claim.assert_called_once()review.assert_called_once()complete.assert_called_once()def test_second_submission_while_first_is_queued_cannot_overwrite_code(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):
207 unmodified lines20820921021121221321421521621721821922022122222342 unmodified lines266267268269270271272207 unmodified linesdef create_challenge_round(workspace_path: str | Path,timer_minutes: int = 0,quota_units_per_student: int = 20,chat_messages_per_student: int = 5,) -> dict[str, str | int]:"""Publish the current challenge and private tests as an immutable local round."""from architect.repo_cloner import WORKSPACES_DIRif isinstance(quota_units_per_student, bool) or not isinstance(quota_units_per_student, int):raise ValueError("Round quota must be an integer")if not 0 <= quota_units_per_student <= 100:raise ValueError("Round quota must be between 0 and 100 units per student")if isinstance(chat_messages_per_student, bool) or not isinstance(chat_messages_per_student, int):raise ValueError("Round chat message limit must be an integer")if not 0 <= chat_messages_per_student <= 100:42 unmodified lines"artifact_hash": artifact_hash,"tests_hash": tests_hash,"timer_minutes": max(0, min(int(timer_minutes), 120)),"quota_units_per_student": quota_units_per_student,"chat_messages_per_student": chat_messages_per_student,}(round_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")207 unmodified lines20820921021121221321421521621721842 unmodified lines261262263264265266267207 unmodified linesdef create_challenge_round(workspace_path: str | Path,timer_minutes: int = 0,chat_messages_per_student: int = 5,) -> dict[str, str | int]:"""Publish the current challenge and private tests as an immutable local round."""from architect.repo_cloner import WORKSPACES_DIRif isinstance(chat_messages_per_student, bool) or not isinstance(chat_messages_per_student, int):raise ValueError("Round chat message limit must be an integer")if not 0 <= chat_messages_per_student <= 100:42 unmodified lines"artifact_hash": artifact_hash,"tests_hash": tests_hash,"timer_minutes": max(0, min(int(timer_minutes), 120)),"quota_units_per_student": chat_messages_per_student + 2,"chat_messages_per_student": chat_messages_per_student,}(round_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
12 unmodified lines1314151617181962 unmodified lines828384858687883 unmodified lines92939495969798166 unmodified lines26526626726826927027121 unmodified lines293294295296297298299165 unmodified lines465466467468469470471298 unmodified lines77077177277377477577677777877978078178278378478578678778878979079179212 unmodified linespublishChallengeRound: vi.fn(),pollJob: vi.fn(),challenge: vi.fn(),quota: vi.fn(),history: vi.fn(),resume: vi.fn(),instructorDashboard: vi.fn(),62 unmodified linesmocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: false, dev_login: true, dev_diagnostics: false, model_key_configured: true, course_mode: false, approved_repositories: [] });mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1", hints_used: 0, submission_count: 0 });mocks.challenge.mockResolvedValue(challenge);mocks.quota.mockResolvedValue({ enabled: true, round_id: "round-1", units_limit: 10, units_used: 1, units_remaining: 9 });mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-1", started_at: "2026-01-01T10:00:00Z", updated_at: "2026-01-01T11:00:00Z", status: "submitted", hints_used: 1, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", round_id: "round-1", submission_count: 1, reflection_saved: true, submissions: [{ submission_id: "submission-1", submitted_at: "2026-01-01T11:00:00Z", attempt_number: 1, total_score: 90, passed_tests: 3, total_tests: 3, submission_outcome: "full_fix" }] }], limit: 50 });mocks.resume.mockResolvedValue(challenge);mocks.instructorDashboard.mockResolvedValue({ rounds: [] });3 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, quota_units_per_student: 20, 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 });166 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, quota_units_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,quota_units_per_student: 20,}));await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-prepared");165 unmodified linesexpect(mocks.saveModelKey).toHaveBeenCalledWith("valid-key");mocks.waitForJob.mockResolvedValueOnce({ status: "completed", llm_score: 91, total_score: 89, explanation: "The fix is focused and correct." });await user.click(await screen.findByRole("button", { name: /request llm grade.*2 units/i }));expect(mocks.requestScoreReview).toHaveBeenCalledWith("submission-1");expect(await screen.findByText("91/100")).toBeTruthy();298 unmodified linesartifact_hash: "artifact-hash-123456",tests_hash: "tests-hash-123456",timer_minutes: 15,status: "prepared",quota_units_per_student: 35,});render(<App />);const quotaInput = await screen.findByRole("spinbutton", { name: /llm units per student/i });await user.clear(quotaInput);await user.type(quotaInput, "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 LLM units\/student/)).toBeTruthy();expect(mocks.publishChallengeRound).toHaveBeenCalledWith({time_limit_enabled: false,timer_minutes: 30,chat_messages_per_student: 5,quota_units_per_student: 35,});await user.click(screen.getByRole("button", { name: "Open round" }));expect(mocks.openRound).toHaveBeenCalledWith("round-123");12 unmodified lines13141516171862 unmodified lines8182838485863 unmodified lines90919293949596166 unmodified lines26326426526626726826921 unmodified lines291292293294295296165 unmodified lines462463464465466467468298 unmodified lines76776876977077177277377477577677777877978078178278378478578678778812 unmodified linespublishChallengeRound: vi.fn(),pollJob: vi.fn(),challenge: vi.fn(),history: vi.fn(),resume: vi.fn(),instructorDashboard: vi.fn(),62 unmodified linesmocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: false, dev_login: true, dev_diagnostics: false, model_key_configured: true, course_mode: false, approved_repositories: [] });mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1", hints_used: 0, submission_count: 0 });mocks.challenge.mockResolvedValue(challenge);mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-1", started_at: "2026-01-01T10:00:00Z", updated_at: "2026-01-01T11:00:00Z", status: "submitted", hints_used: 1, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", round_id: "round-1", submission_count: 1, reflection_saved: true, submissions: [{ submission_id: "submission-1", submitted_at: "2026-01-01T11:00:00Z", attempt_number: 1, total_score: 90, passed_tests: 3, total_tests: 3, submission_outcome: "full_fix" }] }], limit: 50 });mocks.resume.mockResolvedValue(challenge);mocks.instructorDashboard.mockResolvedValue({ rounds: [] });3 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 });166 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");165 unmodified linesexpect(mocks.saveModelKey).toHaveBeenCalledWith("valid-key");mocks.waitForJob.mockResolvedValueOnce({ status: "completed", llm_score: 91, total_score: 89, explanation: "The fix is focused and correct." });await user.click(await screen.findByRole("button", { name: /request llm grade/i }));expect(mocks.requestScoreReview).toHaveBeenCalledWith("submission-1");expect(await screen.findByText("91/100")).toBeTruthy();298 unmodified linesartifact_hash: "artifact-hash-123456",tests_hash: "tests-hash-123456",timer_minutes: 15,chat_messages_per_student: 35,status: "prepared",});render(<App />);const 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();expect(mocks.publishChallengeRound).toHaveBeenCalledWith({time_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");
33 unmodified lines3435363738394041424356 unmodified lines10010110210310410510622 unmodified lines129130131132133134135136140 unmodified lines277278279280281282283118 unmodified lines4024034044054064074081 unmodified line41041141241341441541641772 unmodified lines490491492493494495496145 unmodified lines64264364464564664764864965065165265355 unmodified lines70971071171271371471571671771859 unmodified lines77877978078178278378479 unmodified lines8648658668678688698704 unmodified lines875876877878879880881157 unmodified lines10391040104110421043104410455 unmodified lines105110521053105410551056105730 unmodified lines108810891090109110921093109430 unmodified lines11251126112711281129113011311132113311341135113611371138113935 unmodified lines11751176117711781179118011811182118311841185118633 unmodified linesXCircle,} from "lucide-react";import { api, waitForChallenge, waitForJob } from "./api";import type { ChallengeData, CourseAccessRequest, CourseAccessStatus, DevDiagnosis, HintResult, Identity, InstructorDashboard, QuotaInfo, 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; quota_units_per_student: number };type EditorHandle = {trigger: (source: string, handlerId: string, payload: null) => void;revealLineInCenter: (lineNumber: number) => void;56 unmodified linesconst [messages, setMessages] = useState<ChatMessage[]>([]);const [chatOpen, setChatOpen] = useState(false);const [submission, setSubmission] = useState<SubmissionResult | null>(null);const [quota, setQuota] = useState<QuotaInfo | null>(null);const [studentHistory, setStudentHistory] = useState<StudentHistory | null>(null);const [historyOpen, setHistoryOpen] = useState(false);const [historyLoading, setHistoryLoading] = useState(false);22 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"; quota_units_per_student: number } | null>(null);const [roundQuota, setRoundQuota] = useState(20);const [roundChatMessageLimit, setRoundChatMessageLimit] = useState(5);const [roundCopied, setRoundCopied] = useState(false);const [selfConfidence, setSelfConfidence] = useState(3);140 unmodified linesasync function loadChallenge() {try {const current = await api.challenge();void api.quota().then(setQuota).catch(() => setQuota(null));setChallenge(current);setError(current.storage_warning || "");setDirty(false);118 unmodified linessetDiagnosis(null);setDirty(false);setPublishedRound(null);setRoundQuota(20);setRoundCopied(false);setSelfConfidence(3);setKnownLimitations("");1 unmodified linesetReflectionIndependent(3);setReflectionSaved(false);setReflectionExplanation("");setQuota(null);void api.quota().then(setQuota).catch(() => setQuota(null));setSession((current) => current ? {...current,workspace_id: created.workspace_id,72 unmodified linestime_limit_enabled: timerEnabled,timer_minutes: timerMinutes,chat_messages_per_student: roundChatMessageLimit,quota_units_per_student: roundQuota,}));setRoundCopied(false);} catch (cause) {145 unmodified lines} : current);setMessages((current) => [...current, { role: "assistant", content: result.response, gave_hint: result.gave_hint }]);setSession((current) => current ? { ...current, hints_used: result.hints_used } : current);void api.quota().then(setQuota).catch(() => setQuota(null));} catch (cause) {const errorText = cause instanceof Error ? cause.message : "Hint request failed";setError(errorText);setMessages((current) => [...current, { role: "assistant", content: errorText }]);void api.quota().then(setQuota).catch(() => setQuota(null));} finally {setBusy(false);}55 unmodified linesllm_explanation: result.explanation ?? current.last_submission_result.llm_explanation,},} : current);void api.quota().then(setQuota).catch(() => setQuota(null));} catch (cause) {setError(cause instanceof Error ? cause.message : "LLM grading failed");void api.quota().then(setQuota).catch(() => setQuota(null));} finally {setBusy(false);setStatus("");59 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,quota_units_per_student: round.quota_units_per_student ?? 20,},])));} catch (cause) {79 unmodified lines...round,timer_minutes: updated.timer_minutes,chat_messages_per_student: updated.chat_messages_per_student,quota_units_per_student: updated.quota_units_per_student,status: updated.status,} : round),} : current);4 unmodified linestimer_minutes: updated.timer_minutes || settings.timer_minutes,time_limit_enabled: updated.timer_minutes > 0,chat_messages_per_student: updated.chat_messages_per_student,quota_units_per_student: updated.quota_units_per_student,},}));setEditingRoundId(null);157 unmodified linestime_limit_enabled: round.timer_minutes > 0,timer_minutes: round.timer_minutes || 30,chat_messages_per_student: round.chat_messages_per_student,quota_units_per_student: round.quota_units_per_student ?? 20,};const isEditing = editingRoundId === round.round_id;return (5 unmodified lines</div><span className={`history-status round-status-${round.status}`}>{round.status}</span></div><small>{round.participants.length} participants · {round.timer_minutes ? `${round.timer_minutes} min` : "No time limit"} · {round.chat_messages_per_student} chat messages · {round.quota_units_per_student ?? 0} LLM units each</small><div className="managed-round-share"><span>Share code</span><code>{round.round_id}</code>30 unmodified lines{isEditing && <div className="round-settings-editor"><div className="option-row"><div><strong>Timed challenge</strong><small>Turn off for an untimed round.</small></div><button type="button" className={`switch ${draft.time_limit_enabled ? "switch-on" : ""}`} role="switch" aria-label={`${round.round_id} timed challenge`} aria-checked={draft.time_limit_enabled} onClick={() => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, time_limit_enabled: !draft.time_limit_enabled } }))}><span /></button></div>{draft.time_limit_enabled && <label>Time limit in minutes<input type="number" min={1} max={120} step={5} value={draft.timer_minutes} onChange={(event) => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, timer_minutes: Math.min(120, Math.max(1, Number(event.target.value))) } }))} /></label>}<div className="round-settings-grid"><label>Chat messages per student<input type="number" min={0} max={100} value={draft.chat_messages_per_student} onChange={(event) => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, chat_messages_per_student: Math.min(100, Math.max(0, Number(event.target.value))) } }))} /></label><label>LLM units per student<input type="number" min={0} max={100} value={draft.quota_units_per_student} onChange={(event) => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, quota_units_per_student: Math.min(100, Math.max(0, Number(event.target.value))) } }))} /></label></div><button className="button button-primary" onClick={() => void handleSaveRoundSettings(round.round_id)} disabled={busy}><Check size={15} />Save settings</button></div>}</article>30 unmodified lines{page === "challenge" && challenge && (<main className="challenge-layout"><section className="editor-column"><div className="challenge-heading"><div><p className="eyebrow">ACTIVE CHALLENGE</p><h1>{challenge.target_file}</h1></div><div className="heading-stats"><span><FlaskConical size={15} />{testResult ? `${testResult.passed}/${testResult.total}` : "Tests not run"}</span><span><Lightbulb size={15} />{session.hints_used ?? challenge.hints_used ?? 0}/5 hints</span>{quota?.enabled && <span aria-label={`${quota.units_remaining} of ${quota.units_limit} LLM units remaining`}><Sparkles size={15} />{quota.units_remaining}/{quota.units_limit} LLM units</span>}{timerRemaining !== null && <span className={timerRemaining === 0 ? "timer-expired" : "timer-chip"} aria-live="polite" aria-label={`${Math.floor(timerRemaining / 60)} minutes ${timerRemaining % 60} seconds remaining`}><Timer size={15} />{Math.floor(timerRemaining / 60).toString().padStart(2, "0")}:{(timerRemaining % 60).toString().padStart(2, "0")}</span>}</div></div><div className="editor-frame"><div className="editor-toolbar"><div className="file-picker"><FileCode2 size={16} /><select value={selectedFile} onChange={(event) => void handleFileChange(event.target.value)} aria-label="Choose Python file">{challenge.files.map((file) => <option key={file} value={file}>{file}</option>)}</select><ChevronDown size={14} /></div><div className="editor-actions"><span className={`save-state ${dirty ? "save-dirty" : ""}`}>{dirty ? "Unsaved changes" : status || "Saved"}</span><div className="editor-history-actions"><button className="editor-history-button" onClick={() => editorRef.current?.trigger("toolbar", "undo", null)} disabled={busy || !editorReady} aria-label="Undo" title="Undo"><Undo2 size={15} /></button><button className="editor-history-button" onClick={() => editorRef.current?.trigger("toolbar", "redo", null)} disabled={busy || !editorReady} aria-label="Redo" title="Redo"><Redo2 size={15} /></button></div><button className="subtle-button" onClick={() => void handleSave()} disabled={busy || !dirty}>Save</button><button className="subtle-button" onClick={() => void handleReset()} disabled={busy || selectedFile !== challenge.target_file}><RotateCcw size={14} />Reset</button></div></div><Editor onMount={(editor) => { editorRef.current = editor; setEditorReady(true); }} height="min(54vh, 590px)" language="python" theme="vs-dark" value={code} onChange={(value) => { setCode(value ?? ""); setDirty(true); }} options={{ minimap: { enabled: false }, fontSize: 14, lineNumbers: "on", scrollBeyondLastLine: false, wordWrap: "on", padding: { top: 16 } }} /><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 handleRunTests()} disabled={busy}><Play size={16} />Run public tests</button><button className="button button-secondary" onClick={() => void handleShowPublicTests()} disabled={busy}><FileCode2 size={16} />View 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">LLM units per student<input type="number" min={0} max={100} step={1} value={roundQuota} onChange={(event) => setRoundQuota(Math.min(100, Math.max(0, Number(event.target.value))))} disabled={busy} /></label>}{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.quota_units_per_student} LLM units/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">READ-ONLY SOURCE</p><h2>Public tests · {publicTestsView.file_path}</h2></div><button className="icon-button" onClick={() => setPublicTestsView(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><pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre><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>}{diffOpen && diffResult && <section className="test-panel diff-panel"><div className="panel-heading"><div><p className="eyebrow">WORKSPACE DIFF</p><h2>{diffResult.has_changes ? "Your changes" : "No changes yet"}</h2></div><button className="icon-button" onClick={() => setDiffOpen(false)} aria-label="Close diff"><XCircle size={16} /></button></div><pre className="diff-content">{diffResult.diff || "The file is unchanged from the buggy version."}</pre></section>}35 unmodified lines<div><span>Hint penalty</span><strong>−{submission.hint_penalty}</strong></div>{(submission.scope_penalty ?? 0) > 0 && <div><span>Unrelated code changes{submission.unrelated_functions?.length ? ` · ${submission.unrelated_functions.join(", ")}` : ""}</span><strong>−{submission.scope_penalty}</strong></div>}</div>{submission.llm_review_status === "not_requested" && hasModelAccess && <div className="score-review-action"><button className="button button-secondary" onClick={() => void handleRequestScoreReview()} disabled={busy}><Sparkles size={16} />Request LLM grade{quota?.enabled ? " · 2 units" : ""}</button>{quota?.enabled && <small>This updates the official score and uses 2 units; {quota.units_remaining} remain.</small>}</div>}{submission.llm_review_status === "not_requested" && !hasModelAccess && <p className="muted-copy" role="status">LLM grading is unavailable without a model API key. The displayed score uses deterministic tests only.</p>}{submission.llm_review_status === "processing" && <p className="muted-copy" role="status">LLM grading is processing.</p>}{submission.llm_review_status === "failed" && <p className="muted-copy" role="status">LLM grading failed. The deterministic score remains; reserved units cannot be recovered.</p>}{submission.llm_review_status === "quota_exhausted" && <p className="muted-copy" role="status">LLM grading was skipped because this round's usage limit is reached. The deterministic score is shown.</p>}{submission.llm_review_status === "quota_unavailable" && <p className="muted-copy" role="status">LLM grading could not start because round usage could not be verified. The deterministic score is shown.</p>}{submission.llm_review_status === "not_applicable" && <p className="muted-copy">No injected bug function was changed, so the LLM grade is zero.</p>}{submission.llm_explanation && <p className="review-explanation">{submission.llm_explanation}</p>}{submission.storage_warning && <div className="notice notice-warning"><AlertCircle size={16} />{submission.storage_warning}</div>}33 unmodified lines3435363738394041424356 unmodified lines10010110210310410522 unmodified lines128129130131132133134140 unmodified lines275276277278279280118 unmodified lines3994004014024034041 unmodified line40640740840941041172 unmodified lines484485486487488489145 unmodified lines63563663763863964064164264364455 unmodified lines70070170270370470570670759 unmodified lines76776876977077177279 unmodified lines8528538548558568574 unmodified lines862863864865866867157 unmodified lines1025102610271028102910305 unmodified lines103610371038103910401041104230 unmodified lines107310741075107610771078107930 unmodified lines11101111111211131114111511161117111811191120112111221123112435 unmodified lines116011611162116311641165116611671168116933 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;56 unmodified linesconst [messages, setMessages] = useState<ChatMessage[]>([]);const [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);22 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);140 unmodified linesasync function loadChallenge() {try {const current = await api.challenge();setChallenge(current);setError(current.storage_warning || "");setDirty(false);118 unmodified linessetDiagnosis(null);setDirty(false);setPublishedRound(null);setRoundCopied(false);setSelfConfidence(3);setKnownLimitations("");1 unmodified linesetReflectionIndependent(3);setReflectionSaved(false);setReflectionExplanation("");setSession((current) => current ? {...current,workspace_id: created.workspace_id,72 unmodified linestime_limit_enabled: timerEnabled,timer_minutes: timerMinutes,chat_messages_per_student: roundChatMessageLimit,}));setRoundCopied(false);} catch (cause) {145 unmodified lines} : current);setMessages((current) => [...current, { role: "assistant", content: result.response, gave_hint: result.gave_hint }]);setSession((current) => current ? { ...current, hints_used: result.hints_used } : current);} catch (cause) {const errorText = cause instanceof Error ? cause.message : "Hint request failed";setError(errorText);setMessages((current) => [...current, { role: "assistant", content: errorText }]);} finally {setBusy(false);}55 unmodified linesllm_explanation: result.explanation ?? current.last_submission_result.llm_explanation,},} : current);} catch (cause) {setError(cause instanceof Error ? cause.message : "LLM grading failed");} finally {setBusy(false);setStatus("");59 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);4 unmodified linestimer_minutes: updated.timer_minutes || settings.timer_minutes,time_limit_enabled: updated.timer_minutes > 0,chat_messages_per_student: updated.chat_messages_per_student,},}));setEditingRoundId(null);157 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 (5 unmodified lines</div><span className={`history-status round-status-${round.status}`}>{round.status}</span></div><small>{round.participants.length} participants · {round.timer_minutes ? `${round.timer_minutes} min` : "No time limit"} · {round.chat_messages_per_student} chat messages/student</small><div className="managed-round-share"><span>Share code</span><code>{round.round_id}</code>30 unmodified lines{isEditing && <div className="round-settings-editor"><div className="option-row"><div><strong>Timed challenge</strong><small>Turn off for an untimed round.</small></div><button type="button" className={`switch ${draft.time_limit_enabled ? "switch-on" : ""}`} role="switch" aria-label={`${round.round_id} timed challenge`} aria-checked={draft.time_limit_enabled} onClick={() => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, time_limit_enabled: !draft.time_limit_enabled } }))}><span /></button></div>{draft.time_limit_enabled && <label>Time limit in minutes<input type="number" min={1} max={120} step={5} value={draft.timer_minutes} onChange={(event) => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, timer_minutes: Math.min(120, Math.max(1, Number(event.target.value))) } }))} /></label>}<label>Chat messages per student<input type="number" min={0} max={100} value={draft.chat_messages_per_student} onChange={(event) => setRoundSettingsDrafts((current) => ({ ...current, [round.round_id]: { ...draft, chat_messages_per_student: Math.min(100, Math.max(0, Number(event.target.value))) } }))} /></label><button className="button button-primary" onClick={() => void handleSaveRoundSettings(round.round_id)} disabled={busy}><Check size={15} />Save settings</button></div>}</article>30 unmodified lines{page === "challenge" && challenge && (<main className="challenge-layout"><section className="editor-column"><div className="challenge-heading"><div><p className="eyebrow">ACTIVE CHALLENGE</p><h1>{challenge.target_file}</h1></div><div className="heading-stats"><span><FlaskConical size={15} />{testResult ? `${testResult.passed}/${testResult.total}` : "Tests not run"}</span><span><Lightbulb size={15} />{session.hints_used ?? challenge.hints_used ?? 0}/5 hints</span>{timerRemaining !== null && <span className={timerRemaining === 0 ? "timer-expired" : "timer-chip"} aria-live="polite" aria-label={`${Math.floor(timerRemaining / 60)} minutes ${timerRemaining % 60} seconds remaining`}><Timer size={15} />{Math.floor(timerRemaining / 60).toString().padStart(2, "0")}:{(timerRemaining % 60).toString().padStart(2, "0")}</span>}</div></div><div className="editor-frame"><div className="editor-toolbar"><div className="file-picker"><FileCode2 size={16} /><select value={selectedFile} onChange={(event) => void handleFileChange(event.target.value)} aria-label="Choose Python file">{challenge.files.map((file) => <option key={file} value={file}>{file}</option>)}</select><ChevronDown size={14} /></div><div className="editor-actions"><span className={`save-state ${dirty ? "save-dirty" : ""}`}>{dirty ? "Unsaved changes" : status || "Saved"}</span><div className="editor-history-actions"><button className="editor-history-button" onClick={() => editorRef.current?.trigger("toolbar", "undo", null)} disabled={busy || !editorReady} aria-label="Undo" title="Undo"><Undo2 size={15} /></button><button className="editor-history-button" onClick={() => editorRef.current?.trigger("toolbar", "redo", null)} disabled={busy || !editorReady} aria-label="Redo" title="Redo"><Redo2 size={15} /></button></div><button className="subtle-button" onClick={() => void handleSave()} disabled={busy || !dirty}>Save</button><button className="subtle-button" onClick={() => void handleReset()} disabled={busy || selectedFile !== challenge.target_file}><RotateCcw size={14} />Reset</button></div></div><Editor onMount={(editor) => { editorRef.current = editor; setEditorReady(true); }} height="min(54vh, 590px)" language="python" theme="vs-dark" value={code} onChange={(value) => { setCode(value ?? ""); setDirty(true); }} options={{ minimap: { enabled: false }, fontSize: 14, lineNumbers: "on", scrollBeyondLastLine: false, wordWrap: "on", padding: { top: 16 } }} /><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 handleRunTests()} disabled={busy}><Play size={16} />Run public tests</button><button className="button button-secondary" onClick={() => void handleShowPublicTests()} disabled={busy}><FileCode2 size={16} />View 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">READ-ONLY SOURCE</p><h2>Public tests · {publicTestsView.file_path}</h2></div><button className="icon-button" onClick={() => setPublicTestsView(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><pre className="public-tests-source" aria-readonly="true">{publicTestsView.source}</pre><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>}{diffOpen && diffResult && <section className="test-panel diff-panel"><div className="panel-heading"><div><p className="eyebrow">WORKSPACE DIFF</p><h2>{diffResult.has_changes ? "Your changes" : "No changes yet"}</h2></div><button className="icon-button" onClick={() => setDiffOpen(false)} aria-label="Close diff"><XCircle size={16} /></button></div><pre className="diff-content">{diffResult.diff || "The file is unchanged from the buggy version."}</pre></section>}35 unmodified lines<div><span>Hint penalty</span><strong>−{submission.hint_penalty}</strong></div>{(submission.scope_penalty ?? 0) > 0 && <div><span>Unrelated code changes{submission.unrelated_functions?.length ? ` · ${submission.unrelated_functions.join(", ")}` : ""}</span><strong>−{submission.scope_penalty}</strong></div>}</div>{submission.llm_review_status === "not_requested" && hasModelAccess && <div className="score-review-action"><button className="button button-secondary" onClick={() => void handleRequestScoreReview()} disabled={busy}><Sparkles size={16} />Request LLM grade</button></div>}{submission.llm_review_status === "not_requested" && !hasModelAccess && <p className="muted-copy" role="status">LLM grading is unavailable without a model API key. The displayed score uses deterministic tests only.</p>}{submission.llm_review_status === "processing" && <p className="muted-copy" role="status">LLM grading is processing.</p>}{submission.llm_review_status === "failed" && <p className="muted-copy" role="status">LLM grading failed. The deterministic score remains.</p>}{submission.llm_review_status === "not_applicable" && <p className="muted-copy">No injected bug function was changed, so the LLM grade is zero.</p>}{submission.llm_explanation && <p className="review-explanation">{submission.llm_explanation}</p>}{submission.storage_warning && <div className="notice notice-warning"><AlertCircle size={16} />{submission.storage_warning}</div>}
134 unmodified lines13513613713813914014114214314414514614714834 unmodified lines18318418518618718818912 unmodified lines20220320420520620720868 unmodified lines277278279280281282283284285286287288289290291292293294134 unmodified linesresult: T;};export type QuotaInfo = {enabled: boolean;round_id?: string;units_limit: number | null;units_used: number;units_remaining: number | null;};export type HistorySubmission = {submission_id: string;submitted_at: string;34 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;quota_units_per_student: number | null;participants: Array<{student_name: string | null;status: string;12 unmodified linestime_limit_enabled: boolean;timer_minutes: number;chat_messages_per_student: number;quota_units_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"; quota_units_per_student: number }>("/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; quota_units_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"),quota: () => request<QuotaInfo>("/api/session/quota"),history: (limit = 50) => request<StudentHistory>(`/api/me/history?limit=${limit}`),resume: (workspaceId: string) => request<ChallengeData>(`/api/challenges/${encodeURIComponent(workspaceId)}/resume`, { method: "POST" }),instructorDashboard: () => request<InstructorDashboard>("/api/instructor/dashboard"),134 unmodified lines13513613713813914034 unmodified lines17517617717817918012 unmodified lines19319419519619719868 unmodified lines267268269270271272273274275276277278279280281282283134 unmodified linesresult: T;};export type HistorySubmission = {submission_id: string;submitted_at: string;34 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;participants: Array<{student_name: string | null;status: string;12 unmodified linestime_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" }),instructorDashboard: () => request<InstructorDashboard>("/api/instructor/dashboard"),
69 unmodified lines7071727374757677110 unmodified lines1881891901911921931946 unmodified lines2012022032042052062073 unmodified lines21121221321421521621721821922022122269 unmodified linesif not isinstance(archive, bytes) or not archive or len(archive) > MAX_BUNDLE_BYTES:raise ChallengeRoundStoreError("Challenge round bundle is empty or exceeds 45 MiB")quota_units = manifest.get("quota_units_per_student", 20)if isinstance(quota_units, bool) or not isinstance(quota_units, int) or not 0 <= quota_units <= 100:raise ChallengeRoundStoreError("Round quota must be an integer between 0 and 100")chat_limit = manifest.get("chat_messages_per_student", 5)if isinstance(chat_limit, bool) or not isinstance(chat_limit, int) or not 0 <= chat_limit <= 100:raise ChallengeRoundStoreError("Round chat message limit must be an integer between 0 and 100")110 unmodified linestime_limit_enabled: bool,timer_minutes: int,chat_messages_per_student: int,quota_units_per_student: int,) -> dict[str, Any] | None:"""Update settings only while the creator's round is still prepared."""url, key = _configuration()6 unmodified linesfor value, label, maximum in ((timer_minutes, "Timer", 120),(chat_messages_per_student, "Chat message limit", 100),(quota_units_per_student, "LLM quota", 100),):if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:raise ChallengeRoundStoreError(f"{label} is outside the allowed range")3 unmodified lines"course_id": f"eq.{course_id}","published_by": f"eq.{publisher}","status": "eq.prepared","select": "round_id,timer_minutes,chat_messages_per_student,quota_units_per_student,status",})payload = {"timer_minutes": timer_minutes if time_limit_enabled else 0,"chat_messages_per_student": chat_messages_per_student,"quota_units_per_student": quota_units_per_student,}try:with urlopen(Request(69 unmodified lines7071727374757677110 unmodified lines1881891901911921936 unmodified lines2002012022032042053 unmodified lines20921021121221321421521621721821922069 unmodified linesif not isinstance(archive, bytes) or not archive or len(archive) > MAX_BUNDLE_BYTES:raise ChallengeRoundStoreError("Challenge round bundle is empty or exceeds 45 MiB")quota_units = manifest.get("quota_units_per_student", 20)if isinstance(quota_units, bool) or not isinstance(quota_units, int) or not 0 <= quota_units <= 102:raise ChallengeRoundStoreError("Internal round budget must be an integer between 0 and 102")chat_limit = manifest.get("chat_messages_per_student", 5)if isinstance(chat_limit, bool) or not isinstance(chat_limit, int) or not 0 <= chat_limit <= 100:raise ChallengeRoundStoreError("Round chat message limit must be an integer between 0 and 100")110 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()6 unmodified linesfor value, label, maximum in ((timer_minutes, "Timer", 120),(chat_messages_per_student, "Chat message limit", 100),):if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:raise ChallengeRoundStoreError(f"{label} is outside the allowed range")3 unmodified lines"course_id": f"eq.{course_id}","published_by": f"eq.{publisher}","status": "eq.prepared","select": "round_id,timer_minutes,chat_messages_per_student,status",})payload = {"timer_minutes": timer_minutes if time_limit_enabled else 0,"chat_messages_per_student": chat_messages_per_student,"quota_units_per_student": chat_messages_per_student + 2,}try:with urlopen(Request(
95 unmodified lines9697989910010110261 unmodified lines16416516616716816917095 unmodified linesraise HistoryStoreError("Instructor dashboard requires persistent course storage")url, key = configuredrounds = _get_rows(url, key, "challenge_rounds", {"select": "round_id,repo_url,target_file,status,created_at,opened_at,closed_at,timer_minutes,chat_messages_per_student,quota_units_per_student","course_id": f"eq.{_course_id(course_id)}","published_by": f"eq.{provider}:{user_id}","order": "created_at.desc,round_id.desc",61 unmodified lines"closed_at": round_row.get("closed_at"),"timer_minutes": round_row.get("timer_minutes", 0),"chat_messages_per_student": round_row.get("chat_messages_per_student", 5),"quota_units_per_student": round_row.get("quota_units_per_student"),"participants": participants,})return {"rounds": result_rounds}95 unmodified lines9697989910010110261 unmodified lines16416516616716816995 unmodified linesraise HistoryStoreError("Instructor dashboard requires persistent course storage")url, key = configuredrounds = _get_rows(url, key, "challenge_rounds", {"select": "round_id,repo_url,target_file,status,created_at,opened_at,closed_at,timer_minutes,chat_messages_per_student","course_id": f"eq.{_course_id(course_id)}","published_by": f"eq.{provider}:{user_id}","order": "created_at.desc,round_id.desc",61 unmodified lines"closed_at": round_row.get("closed_at"),"timer_minutes": round_row.get("timer_minutes", 0),"chat_messages_per_student": round_row.get("chat_messages_per_student", 5),"participants": participants,})return {"rounds": result_rounds}
110 unmodified lines1111121131141151161174 unmodified lines12212312412512612712812913013113213313414 unmodified lines1491501511521531541554 unmodified lines160161162163164165166122 unmodified lines28929029129229329429529629721 unmodified lines319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361110 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 20 check (quota_units_per_student between 0 and 100),status text not null default 'prepared' check (status in ('prepared', 'open', 'closed')),published_by text,opened_by text,4 unmodified lines);alter table public.challenge_roundsadd column if not exists quota_units_per_student integer not null default 20 check (quota_units_per_student between 0 and 100);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_roundsadd constraint challenge_rounds_quota_units_per_student_cap_check check (quota_units_per_student between 0 and 100);alter table public.challenge_roundsadd column if not exists status text not null default 'open' check (status in ('prepared', 'open', 'closed'));alter table public.challenge_rounds alter column status set default 'prepared';14 unmodified linesround_id uuid not null references public.challenge_rounds(round_id) on delete cascade,auth_provider text not null,provider_user_id text not null,units_limit integer not null check (units_limit between 0 and 100),units_used integer not null default 0 check (units_used >= 0),updated_at timestamptz not null default now(),primary key (round_id, auth_provider, provider_user_id),4 unmodified linesalter table public.round_student_quotas drop constraint if exists round_student_quotas_units_limit_check;alter table public.round_student_quotas drop constraint if exists round_student_quotas_units_limit_cap_check;alter table public.round_student_quotasadd constraint round_student_quotas_units_limit_cap_check check (units_limit between 0 and 100);alter table public.round_student_quotas enable row level security;revoke all on table public.round_student_quotas from anon, authenticated;grant select, insert, update on table public.round_student_quotas to service_role;122 unmodified linesas $$declarev_round_id uuid;v_review public.submission_score_reviews%rowtype;v_limit integer;v_used integer;beginperform pg_advisory_xact_lock(hashtextextended(p_submission_id, 0));21 unmodified linesend if;if v_round_id is not null thenselect quota_units_per_student into v_limitfrom public.challenge_roundswhere round_id = v_round_id and status = 'open'for update;if not found thenreturn jsonb_build_object('claimed', false, 'reason', 'round_unavailable');end if;insert into public.round_student_quotas(round_id, auth_provider, provider_user_id, units_limit)values (v_round_id, p_auth_provider, p_provider_user_id, v_limit)on conflict (round_id, auth_provider, provider_user_id) do nothing;select units_limit, units_used into v_limit, v_usedfrom public.round_student_quotaswhere round_id = v_round_idand auth_provider = p_auth_providerand provider_user_id = p_provider_user_idfor update;if exists (select 1 from public.round_quota_operations where operation_id = p_operation_id) thenreturn jsonb_build_object('claimed', false, 'reason', 'duplicate_operation');end if;if v_used + 2 > v_limit thenreturn jsonb_build_object('claimed', false, 'reason', 'quota_exhausted','units_limit', v_limit, 'units_used', v_used);end if;update public.round_student_quotasset units_used = units_used + 2, updated_at = now()where round_id = v_round_idand auth_provider = p_auth_providerand provider_user_id = p_provider_user_id;insert into public.round_quota_operations(operation_id, round_id, auth_provider, provider_user_id, operation_type, units) values (p_operation_id, v_round_id, p_auth_provider, p_provider_user_id, 'score_review', 2);end if;insert into public.submission_score_reviews(110 unmodified lines1111121131141151161174 unmodified lines12212312412512612712812913013113213313413514 unmodified lines1501511521531541551564 unmodified lines161162163164165166167122 unmodified lines29029129229329429529629721 unmodified lines319320321322323324325326327328329330331332333110 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,opened_by text,4 unmodified lines);alter table public.challenge_roundsadd column if not exists quota_units_per_student integer not null default 7 check (quota_units_per_student between 0 and 102);alter 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_roundsadd constraint challenge_rounds_quota_units_per_student_cap_check check (quota_units_per_student between 0 and 102);alter table public.challenge_roundsadd column if not exists status text not null default 'open' check (status in ('prepared', 'open', 'closed'));alter table public.challenge_rounds alter column status set default 'prepared';14 unmodified linesround_id uuid not null references public.challenge_rounds(round_id) on delete cascade,auth_provider text not null,provider_user_id text not null,units_limit integer not null check (units_limit between 0 and 102),units_used integer not null default 0 check (units_used >= 0),updated_at timestamptz not null default now(),primary key (round_id, auth_provider, provider_user_id),4 unmodified linesalter table public.round_student_quotas drop constraint if exists round_student_quotas_units_limit_check;alter table public.round_student_quotas drop constraint if exists round_student_quotas_units_limit_cap_check;alter table public.round_student_quotasadd constraint round_student_quotas_units_limit_cap_check check (units_limit between 0 and 102);alter table public.round_student_quotas enable row level security;revoke all on table public.round_student_quotas from anon, authenticated;grant select, insert, update on table public.round_student_quotas to service_role;122 unmodified linesas $$declarev_round_id uuid;v_round_status text;v_review public.submission_score_reviews%rowtype;beginperform pg_advisory_xact_lock(hashtextextended(p_submission_id, 0));21 unmodified linesend if;if v_round_id is not null thenselect status into v_round_statusfrom public.challenge_roundswhere round_id = v_round_id and course_id = (select course_id from public.submissions where submission_id = p_submission_id) and status = 'open'for update;if not found thenreturn jsonb_build_object('claimed', false, 'reason', 'round_unavailable');end if;end if;insert into public.submission_score_reviews(
63 unmodified lines646566676869707172737475767730 unmodified lines1081091101111121131144 unmodified lines1191201211221231241253 unmodified lines12913013113213313463 unmodified linesself.assertEqual(row["chat_messages_per_student"], 4)self.assertNotIn("secret_tests", row)def test_publish_rejects_invalid_quota_before_network_access(self):manifest = {"round_id": str(uuid4()),"github_url": "https://github.com/acme/demo","target_file": "main.py","artifact_hash": "a" * 64,"tests_hash": "b" * 64,"quota_units_per_student": 101,}with patch.object(rounds, "urlopen") as send:with self.assertRaises(rounds.ChallengeRoundStoreError):30 unmodified lines"round_id": round_id,"timer_minutes": 0,"chat_messages_per_student": 7,"quota_units_per_student": 25,"status": "prepared",}with patch.object(rounds, "urlopen", return_value=FakeResponse(json.dumps([row]).encode())) as send:4 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=7,quota_units_per_student=25,)request = send.call_args.args[0]3 unmodified linesself.assertEqual(query["published_by"], ["eq.huggingface:teacher-2"])self.assertEqual(query["status"], ["eq.prepared"])self.assertEqual(payload["timer_minutes"], 0)self.assertEqual(updated["chat_messages_per_student"], 7)def test_round_transition_preserves_non_publisher_denial(self):63 unmodified lines646566676869707172737475767730 unmodified lines1081091101111121134 unmodified lines1181191201211221233 unmodified lines12712812913013113213313463 unmodified linesself.assertEqual(row["chat_messages_per_student"], 4)self.assertNotIn("secret_tests", row)def test_publish_rejects_invalid_internal_budget_before_network_access(self):manifest = {"round_id": str(uuid4()),"github_url": "https://github.com/acme/demo","target_file": "main.py","artifact_hash": "a" * 64,"tests_hash": "b" * 64,"quota_units_per_student": 103,}with patch.object(rounds, "urlopen") as send:with self.assertRaises(rounds.ChallengeRoundStoreError):30 unmodified lines"round_id": round_id,"timer_minutes": 0,"chat_messages_per_student": 7,"status": "prepared",}with patch.object(rounds, "urlopen", return_value=FakeResponse(json.dumps([row]).encode())) as send:4 unmodified linestime_limit_enabled=False,timer_minutes=30,chat_messages_per_student=7,)request = send.call_args.args[0]3 unmodified linesself.assertEqual(query["published_by"], ["eq.huggingface:teacher-2"])self.assertEqual(query["status"], ["eq.prepared"])self.assertEqual(payload["timer_minutes"], 0)self.assertEqual(payload["quota_units_per_student"], 9)self.assertNotIn("quota_units_per_student", updated)self.assertEqual(updated["chat_messages_per_student"], 7)def test_round_transition_preserves_non_publisher_denial(self):
HANDOFF.md+17-17
README.md+1-1
SYSTEM_VERIFICATION.md+19-20
backend/app.py+10-62
backend/test_api.py+55-77
challenge_runtime.py+1-6
frontend/src/App.test.tsx+9-13
frontend/src/App.tsx+10-27
frontend/src/api.ts+2-13
supabase_challenge_rounds.py+4-6
supabase_history.py+1-2
supabase_schema.sql+11-39
test_supabase_challenge_rounds.py+4-4