Spaces:
Sleeping
Sleeping
Add private round instructor attempt dashboard
Browse filesFiles changed (10)
34 unmodified lines35363738394034 unmodified linesIn course mode, users can create up to three private personal challenges per database day from any public GitHub repository. Creating a personal challenge does not grant instructor permissions. Approved instructors and course admins can publish shared rounds from any valid public GitHub repository. Students may request instructor access in the app; administrators approve requests in the course access panel, and database-backed grants take effect without restarting the server. `COURSE_INSTRUCTOR_IDENTITIES` is retained as a legacy/bootstrap administrator list, not the routine way to grant new instructors. Personal challenge execution is not a hardened sandbox for hostile code.## Submission and ReflectionBefore final submission, students record confidence (1–5) and optional known limitations. A successfully scored submission stores an immutable code snapshot and timestamp, then locks edits, resets, tests, and hints for that challenge. The results screen collects two 1–5 understanding ratings and a short explanation of the core bug; each submission accepts one reflection. Typed lifecycle events are appended to a server-private JSONL file and exclude code, chat text, and personal details. Local development uses per-process file locking; this log is not a cross-worker audit service.34 unmodified lines353637383940414234 unmodified linesIn course mode, users can create up to three private personal challenges per database day from any public GitHub repository. Creating a personal challenge does not grant instructor permissions. Approved instructors and course admins can publish shared rounds from any valid public GitHub repository. Students may request instructor access in the app; administrators approve requests in the course access panel, and database-backed grants take effect without restarting the server. `COURSE_INSTRUCTOR_IDENTITIES` is retained as a legacy/bootstrap administrator list, not the routine way to grant new instructors. Personal challenge execution is not a hardened sandbox for hostile code.For private shared rounds, the publisher and course administrators can view each student's attempt, including the complete recorded chat, hints, public test runs, submission results, and submitted diff. Students are informed of this visibility. Test-run history is recorded for new attempts; older attempts can show incomplete or unavailable history. Elapsed time is measured from the saved start until submission or last activity, not active working time. Data is available to the dashboard after the attempt checkpoint has synced to Supabase.## Submission and ReflectionBefore final submission, students record confidence (1–5) and optional known limitations. A successfully scored submission stores an immutable code snapshot and timestamp, then locks edits, resets, tests, and hints for that challenge. The results screen collects two 1–5 understanding ratings and a short explanation of the core bug; each submission accepts one reflection. Typed lifecycle events are appended to a server-private JSONL file and exclude code, chat text, and personal details. Local development uses per-process file locking; this log is not a cross-worker audit service.
52 unmodified lines5354555657585965 unmodified lines125126127128129130488 unmodified lines619620621622623624861 unmodified lines148614871488148914901491149222 unmodified lines15151516151715181519152015211522152315241525118 unmodified lines164416451646164716481649196 unmodified lines184618471848184918501851206 unmodified lines205820592060206120622063223 unmodified lines22872288228922902291229232 unmodified lines232523262327232823292330309 unmodified lines26402641264226432644264515 unmodified lines26612662266326642665266652 unmodified linescomplete_submission_score_review,fail_submission_score_review,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_student_historyfrom supabase_generation_prompts import record_generation_event, record_generation_runfrom supabase_course_access import (CourseAccessStoreError,65 unmodified lineschat_history: list[dict[str, Any]] = field(default_factory=list)chat_log: list[dict[str, Any]] = field(default_factory=list)hint_log: list[dict[str, Any]] = field(default_factory=list)confirmation_pending: bool = Falsepending_hint_result: dict[str, Any] | None = Noneprogress_storage_warning: str = ""488 unmodified linessession.chat_history.clear()session.chat_log.clear()session.hint_log.clear()session.confirmation_pending = Falsesession.pending_hint_result = Nonesession.progress_storage_warning = ""861 unmodified linessession: UserSession = Depends(require_instructor),) -> dict[str, Any]:try:result = get_instructor_dashboard(dict(session.identity), limit, _course_id())except HistoryStoreError as exc:logger.warning("Instructor dashboard lookup failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Instructor dashboard is temporarily unavailable") from exc22 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}@app.post("/api/challenges/{workspace_id}/resume")def resume_challenge(workspace_id: str,118 unmodified linessession.chat_history = list(progress.get("chat_history") or [])session.chat_log = list(progress.get("chat_log") or [])session.hint_log = list(progress.get("hint_log") or [])session.confirmation_pending = bool(progress.get("confirmation_pending"))session.pending_hint_result = progress.get("pending_hint_result")_persist_challenge_progress(session)196 unmodified linesdetails = next((item for item in public_details if item["num"] == num), None)if details:test.update(details)_log_session_event(session, "public_tests_run", passed=int(result.get("passed", 0)), total=int(result.get("total", 0)))await asyncio.to_thread(_persist_challenge_progress, session, payload.file_path, result)result["storage_warning"] = session.progress_storage_warning206 unmodified lines"chat_history": session.chat_history,"chat_log": session.chat_log,"hint_log": session.hint_log,"confirmation_pending": session.confirmation_pending,"pending_hint_result": session.pending_hint_result,"timer_deadline": session.timer_deadline,223 unmodified lineshint_history: list[dict[str, Any]],self_assessment: dict[str, Any],captured_api_key: str | None = None,) -> None:job: ChallengeJob | None = app.state.jobs.get(job_id)session: UserSession | None = app.state.sessions.get(session_id)32 unmodified linesround_id=session.challenge_round_id,course_id=_course_id(),)local_path = _save_local_record(workspace, record)_append_workspace_event_best_effort(workspace.workspace,309 unmodified lineswith session.thread_lock:job = ChallengeJob(job_id=job_id, owner_session_id=session.session_id, kind="submission")request.app.state.jobs[job_id] = jobsnapshot = (list(session.chat_log),list(session.hint_log),15 unmodified linessnapshot[1],self_assessment,captured_api_key,)except Exception:_release_session_operation(session, job_id)52 unmodified lines5354555657585965 unmodified lines125126127128129130131132488 unmodified lines621622623624625626627628861 unmodified lines149014911492149314941495149614971498149922 unmodified lines1522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561118 unmodified lines16801681168216831684168516861687196 unmodified lines188418851886188718881889189018911892189318941895206 unmodified lines21022103210421052106210721082109223 unmodified lines233323342335233623372338233932 unmodified lines237223732374237523762377237823792380309 unmodified lines269026912692269326942695269615 unmodified lines271227132714271527162717271852 unmodified linescomplete_submission_score_review,fail_submission_score_review,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_instructor_round_attempts, get_student_historyfrom supabase_generation_prompts import record_generation_event, record_generation_runfrom supabase_course_access import (CourseAccessStoreError,65 unmodified lineschat_history: list[dict[str, Any]] = field(default_factory=list)chat_log: list[dict[str, Any]] = field(default_factory=list)hint_log: list[dict[str, Any]] = field(default_factory=list)public_test_runs: list[dict[str, Any]] = field(default_factory=list)public_test_history_complete: bool = Trueconfirmation_pending: bool = Falsepending_hint_result: dict[str, Any] | None = Noneprogress_storage_warning: str = ""488 unmodified linessession.chat_history.clear()session.chat_log.clear()session.hint_log.clear()session.public_test_runs.clear()session.public_test_history_complete = Truesession.confirmation_pending = Falsesession.pending_hint_result = Nonesession.progress_storage_warning = ""861 unmodified linessession: UserSession = Depends(require_instructor),) -> dict[str, Any]:try:if _is_course_admin(session.identity):result = get_instructor_dashboard(dict(session.identity), limit, _course_id(), include_all_private=True)else:result = get_instructor_dashboard(dict(session.identity), limit, _course_id())except HistoryStoreError as exc:logger.warning("Instructor dashboard lookup failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Instructor dashboard is temporarily unavailable") from exc22 unmodified lines"created_at": row.get("created_at"),"opened_at": row.get("opened_at"),"closed_at": row.get("closed_at"),"timer_minutes": row.get("timer_minutes", 0),"chat_messages_per_student": row.get("chat_messages_per_student", 5),"visibility": row.get("visibility"),"can_manage": row.get("can_manage", True),"participants": participants,})return {"rounds": rounds}@app.get("/api/instructor/rounds/{round_id}/attempts")def get_instructor_private_round_attempts(round_id: str,response: Response,offset: int = Query(default=0, ge=0, le=100_000),session: UserSession = Depends(require_instructor),) -> dict[str, Any]:try:round_id = str(UUID(round_id))except (ValueError, TypeError, AttributeError) as exc:raise HTTPException(status_code=404, detail="Private challenge round not found") from exctry:result = get_instructor_round_attempts(dict(session.identity), round_id, _course_id(),is_admin=_is_course_admin(session.identity), offset=offset,)except HistoryStoreError as exc:logger.warning("Private round attempts lookup failed: %s", type(exc).__name__)raise HTTPException(status_code=503, detail="Private round attempts are temporarily unavailable") from excif result is None:raise HTTPException(status_code=404, detail="Private challenge round not found")response.headers["Cache-Control"] = "no-store"return result@app.post("/api/challenges/{workspace_id}/resume")def resume_challenge(workspace_id: str,118 unmodified linessession.chat_history = list(progress.get("chat_history") or [])session.chat_log = list(progress.get("chat_log") or [])session.hint_log = list(progress.get("hint_log") or [])session.public_test_runs = list(progress.get("public_test_runs") or [])session.public_test_history_complete = bool(progress.get("public_test_history_complete", False))session.confirmation_pending = bool(progress.get("confirmation_pending"))session.pending_hint_result = progress.get("pending_hint_result")_persist_challenge_progress(session)196 unmodified linesdetails = next((item for item in public_details if item["num"] == num), None)if details:test.update(details)with session.thread_lock:session.public_test_runs.append({"ran_at": datetime.now(timezone.utc).isoformat(),"passed": int(result.get("passed", 0)),"total": int(result.get("total", 0)),})_log_session_event(session, "public_tests_run", passed=int(result.get("passed", 0)), total=int(result.get("total", 0)))await asyncio.to_thread(_persist_challenge_progress, session, payload.file_path, result)result["storage_warning"] = session.progress_storage_warning206 unmodified lines"chat_history": session.chat_history,"chat_log": session.chat_log,"hint_log": session.hint_log,"public_test_runs": session.public_test_runs,"public_test_history_complete": session.public_test_history_complete,"confirmation_pending": session.confirmation_pending,"pending_hint_result": session.pending_hint_result,"timer_deadline": session.timer_deadline,223 unmodified lineshint_history: list[dict[str, Any]],self_assessment: dict[str, Any],captured_api_key: str | None = None,submitted_at: str | None = None,) -> None:job: ChallengeJob | None = app.state.jobs.get(job_id)session: UserSession | None = app.state.sessions.get(session_id)32 unmodified linesround_id=session.challenge_round_id,course_id=_course_id(),)if submitted_at is not None:record["timestamp"] = submitted_atrecord["submission"]["submitted_at"] = submitted_atlocal_path = _save_local_record(workspace, record)_append_workspace_event_best_effort(workspace.workspace,309 unmodified lineswith session.thread_lock:job = ChallengeJob(job_id=job_id, owner_session_id=session.session_id, kind="submission")request.app.state.jobs[job_id] = jobsubmitted_at = datetime.now(timezone.utc).isoformat()snapshot = (list(session.chat_log),list(session.hint_log),15 unmodified linessnapshot[1],self_assessment,captured_api_key,submitted_at,)except Exception:_release_session_operation(session, job_id)
152 unmodified lines153154155156157158159152 unmodified linesround_id: str | None = None,course_id: str = "local",) -> dict[str, Any]:now = datetime.now()expected_code = expected_fixed_code(workspace) or workspace.original_codechallenge_id = f"{workspace.workspace.name}:{workspace.target_file}:{workspace.function_name or 'unknown'}"outcome = _submission_outcome(result)152 unmodified lines153154155156157158159152 unmodified linesround_id: str | None = None,course_id: str = "local",) -> dict[str, Any]:now = datetime.now().astimezone()expected_code = expected_fixed_code(workspace) or workspace.original_codechallenge_id = f"{workspace.workspace.name}:{workspace.target_file}:{workspace.function_name or 'unknown'}"outcome = _submission_outcome(result)
751 unmodified lines752753754755756757758759760761762401 unmodified lines11641165116611671168116911701171117211731174559 unmodified lines17341735173617371738173914 unmodified lines175417551756175717581759500 unmodified lines226022612262226322642265751 unmodified linesself.assertEqual(response.status_code, 202)session.api_key = "key-after-enqueue"function, arguments = queue.pending.pop(0)function(*arguments)job = self.client.get(f"/api/jobs/{response.json()['job_id']}").json()self.assertEqual(job["status"], "completed")self.assertEqual(captured, ["key-at-enqueue"])def test_challenge_quota_failure_returns_safe_actionable_job_error(self):from llm_config import LLMQuotaExceededError401 unmodified linesallowed = self.client.get("/api/instructor/dashboard")self.assertEqual(allowed.status_code, 200)load_dashboard.assert_called_once_with(session.identity, 100, "local")encoded = json.dumps(allowed.json())self.assertNotIn("secret payload", encoded)self.assertNotIn("private@example.com", encoded)def test_closed_round_rejects_join_before_job_creation(self):self.add_session(api_key="")queued_executor = MagicMock()559 unmodified lines"chat_history": [{"role": "user", "content": "Why?"}],"chat_log": [{"question": "Why?", "response": "Check the branch.", "gave_hint": False}],"hint_log": [],"confirmation_pending": False,}progress_path.write_text(json.dumps(progress), encoding="utf-8")14 unmodified linesself.assertEqual(session.hints_used, 2)self.assertEqual(session.challenge_timer_minutes, 20)self.assertEqual(session.chat_log[0]["question"], "Why?")self.assertEqual((workspace / "main.py").read_text(encoding="utf-8"), "value = 2\n")progress["status"] = "submitted"500 unmodified linesself.assertEqual(first.status_code, 200)self.assertEqual(second.status_code, 200)self.assertEqual(observed_code, ["value = 1\n", "value = 2\n"])def test_submit_scores_and_persists_supabase_and_local_record(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):751 unmodified lines752753754755756757758759760761762763764765401 unmodified lines11671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198559 unmodified lines1758175917601761176217631764176514 unmodified lines17801781178217831784178517861787500 unmodified lines228822892290229122922293229422952296229722982299751 unmodified linesself.assertEqual(response.status_code, 202)session.api_key = "key-after-enqueue"function, arguments = queue.pending.pop(0)queued_submission_time = arguments[-1]function(*arguments)job = self.client.get(f"/api/jobs/{response.json()['job_id']}").json()self.assertEqual(job["status"], "completed")self.assertEqual(captured, ["key-at-enqueue"])self.assertEqual(record["submission"]["submitted_at"], queued_submission_time)self.assertEqual(record["timestamp"], queued_submission_time)def test_challenge_quota_failure_returns_safe_actionable_job_error(self):from llm_config import LLMQuotaExceededError401 unmodified linesallowed = self.client.get("/api/instructor/dashboard")self.assertEqual(allowed.status_code, 200)load_dashboard.assert_called_once_with(session.identity, 100, "local", include_all_private=True)encoded = json.dumps(allowed.json())self.assertNotIn("secret payload", encoded)self.assertNotIn("private@example.com", encoded)def test_private_round_attempts_requires_instructor_and_respects_access_result(self):session = self.add_session()round_id = str(uuid4())with patch.object(api, "get_instructor_round_attempts", return_value=None) as load:self.assertEqual(self.client.get(f"/api/instructor/rounds/{round_id}/attempts").status_code, 403)load.assert_not_called()with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}):self.assertEqual(self.client.get(f"/api/instructor/rounds/{round_id}/attempts?offset=20").status_code, 404)load.assert_called_once_with(session.identity, round_id, "local", is_admin=True, offset=20)self.assertEqual(self.client.get("/api/instructor/rounds/invalid/attempts").status_code, 404)def test_private_round_attempts_response_is_not_cached(self):self.add_session()round_id = str(uuid4())with patch.dict(os.environ, {"COURSE_INSTRUCTOR_IDENTITIES": "development:test-user"}), patch.object(api, "get_instructor_round_attempts", return_value={"attempts": [], "has_more": False, "next_offset": None}):response = self.client.get(f"/api/instructor/rounds/{round_id}/attempts")self.assertEqual(response.status_code, 200)self.assertEqual(response.headers["cache-control"], "no-store")def test_closed_round_rejects_join_before_job_creation(self):self.add_session(api_key="")queued_executor = MagicMock()559 unmodified lines"chat_history": [{"role": "user", "content": "Why?"}],"chat_log": [{"question": "Why?", "response": "Check the branch.", "gave_hint": False}],"hint_log": [],"public_test_runs": [{"ran_at": "2026-01-01T10:00:00Z", "passed": 1, "total": 2}],"public_test_history_complete": True,"confirmation_pending": False,}progress_path.write_text(json.dumps(progress), encoding="utf-8")14 unmodified linesself.assertEqual(session.hints_used, 2)self.assertEqual(session.challenge_timer_minutes, 20)self.assertEqual(session.chat_log[0]["question"], "Why?")self.assertEqual(len(session.public_test_runs), 1)self.assertTrue(session.public_test_history_complete)self.assertEqual((workspace / "main.py").read_text(encoding="utf-8"), "value = 2\n")progress["status"] = "submitted"500 unmodified linesself.assertEqual(first.status_code, 200)self.assertEqual(second.status_code, 200)self.assertEqual(observed_code, ["value = 1\n", "value = 2\n"])progress = json.loads((private_workspace_dir(workspace) / "progress.json").read_text(encoding="utf-8"))self.assertTrue(progress["public_test_history_complete"])self.assertEqual(len(progress["public_test_runs"]), 2)self.assertEqual(progress["public_test_runs"][0]["passed"], 0)self.assertEqual(progress["public_test_runs"][0]["total"], 1)self.assertEqual(self.progress_upload.call_args.args[0]["public_test_runs"], progress["public_test_runs"])def test_submit_scores_and_persists_supabase_and_local_record(self):with tempfile.TemporaryDirectory() as root, patch.object(repo_cloner, "WORKSPACES_DIR", root):
15 unmodified lines16171819202163 unmodified lines85868788899015 unmodified lines10610710810911011115 unmodified lineshistory: vi.fn(),resume: vi.fn(),instructorDashboard: vi.fn(),courseAccess: vi.fn(),requestInstructorAccess: vi.fn(),courseAccessRequests: vi.fn(),63 unmodified linesmocks.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: [] });mocks.courseAccess.mockResolvedValue({ role: "student", is_course_admin: false, request: null });mocks.requestInstructorAccess.mockResolvedValue({ request_id: "access-request-1", status: "pending" });mocks.courseAccessRequests.mockResolvedValue({ requests: [] });15 unmodified linesafterEach(() => cleanup());describe("React challenge experience", () => {it("shows the independent Hugging Face login when OAuth is enabled", async () => {mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: false });mocks.session.mockResolvedValue({ authenticated: false });15 unmodified lines1617181920212263 unmodified lines8687888990919215 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821915 unmodified lineshistory: vi.fn(),resume: vi.fn(),instructorDashboard: vi.fn(),instructorRoundAttempts: vi.fn(),courseAccess: vi.fn(),requestInstructorAccess: vi.fn(),courseAccessRequests: vi.fn(),63 unmodified linesmocks.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: [] });mocks.instructorRoundAttempts.mockReset().mockResolvedValue({ attempts: [], has_more: false, next_offset: null });mocks.courseAccess.mockResolvedValue({ role: "student", is_course_admin: false, request: null });mocks.requestInstructorAccess.mockResolvedValue({ request_id: "access-request-1", status: "pending" });mocks.courseAccessRequests.mockResolvedValue({ requests: [] });15 unmodified linesafterEach(() => cleanup());describe("React challenge experience", () => {it("loads private-round attempts lazily and displays complete per-attempt details", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "private-1", repo_url: "https://github.com/acme/private", target_file: "demo.py", status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [{ student_name: "Summary student", status: "in_progress", submission_count: 0, latest_score: null }] },{ round_id: "public-1", repo_url: "https://github.com/acme/public", target_file: "demo.py", status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "public", participants: [] },{ round_id: "unknown-1", repo_url: "https://github.com/acme/unknown", target_file: "demo.py", status: "open", timer_minutes: 0, chat_messages_per_student: 5, participants: [] },] });mocks.instructorRoundAttempts.mockResolvedValueOnce({ attempts: [{workspace_id: "workspace-private", student_name: "Attempt student", status: "submitted", started_at: "2026-01-01T10:00:00Z", updated_at: "2026-01-01T12:00:00Z", submitted_at: "2026-01-01T11:05:12Z", hints_used: 1,public_test_runs: [{ ran_at: "2026-01-01T10:30:00Z", passed: 1, total: 2 }], public_test_history_complete: true,chat_log: [{ question: "First question?", response: "First answer.", gave_hint: false, hint_summary: "" }, { question: "Second question?", response: "A useful hint.", gave_hint: true, hint_summary: "Check the branch" }],submissions: [{ submitted_at: "2026-01-01T11:05:12Z", total_score: 83, passed_tests: 3, total_tests: 4, public_passed: 2, public_total: 2, secret_passed: 1, secret_total: 2, submission_outcome: "partial_fix", student_diff: "- old\n+ new", self_assessment: { confidence: 4, known_limitations: "Misses empty input" } }],}], has_more: false, next_offset: null });render(<App />);await user.click(await screen.findByRole("button", { name: "Managed rounds" }));expect(await screen.findByText("Summary student")).toBeTruthy();expect(screen.getAllByRole("button", { name: "View attempts" })).toHaveLength(1);expect(mocks.instructorRoundAttempts).not.toHaveBeenCalled();await user.click(screen.getByRole("button", { name: "View attempts" }));expect(mocks.instructorRoundAttempts).toHaveBeenCalledWith("private-1", 0);await user.click(await screen.findByText("Attempt student"));expect(screen.getByText("Elapsed from start to submission")).toBeTruthy();expect(screen.getByText("1h 5m 12s")).toBeTruthy();expect(screen.getByText("1 run")).toBeTruthy();expect(screen.getByText(/1\/2 passed/)).toBeTruthy();expect(screen.getByText("First question?")).toBeTruthy();expect(screen.getByText("First answer.")).toBeTruthy();expect(screen.getByText("Second question?")).toBeTruthy();expect(screen.getByText("Code partner · Hint")).toBeTruthy();expect(screen.getByText("A useful hint.")).toBeTruthy();expect(screen.getByText("Check the branch")).toBeTruthy();expect(screen.getByText("83/100")).toBeTruthy();expect(screen.getByText("Misses empty input")).toBeTruthy();await user.click(screen.getByText("Student diff (before / after)"));expect(screen.getByText("- old + new")).toBeTruthy();expect(screen.queryByText("workspace-private")).toBeNull();});it("lets course admins view another instructor's attempts without management controls", async () => {const user = userEvent.setup();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: "other-private", repo_url: null, target_file: null, status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", can_manage: false, participants: [] }] });mocks.instructorRoundAttempts.mockResolvedValueOnce({ attempts: [], has_more: false, next_offset: null });render(<App />);await user.click(await screen.findByRole("button", { name: "Managed rounds" }));await user.click(await screen.findByRole("button", { name: "View attempts" }));expect(await screen.findByText("No attempts yet.")).toBeTruthy();expect(screen.queryByRole("button", { name: "Close round" })).toBeNull();expect(mocks.instructorRoundAttempts).toHaveBeenCalledWith("other-private", 0);});it("paginates attempts and labels missing or partial test history and invalid elapsed dates", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "private-2", repo_url: null, target_file: null, status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [] }] });const first = { workspace_id: "one", student_name: "First learner", status: "in_progress", started_at: "invalid", updated_at: "2026-01-01T10:00:00Z", submitted_at: null, hints_used: 0, public_test_runs: null, public_test_history_complete: false, chat_log: null, submissions: [] };const second = { ...first, workspace_id: "two", student_name: "Second learner", started_at: "2026-01-01T09:00:00Z", public_test_runs: [], public_test_history_complete: false };mocks.instructorRoundAttempts.mockResolvedValueOnce({ attempts: [first], has_more: true, next_offset: 7 }).mockResolvedValueOnce({ attempts: [second], has_more: false, next_offset: null });render(<App />);await user.click(await screen.findByRole("button", { name: "Managed rounds" }));await user.click(await screen.findByRole("button", { name: "View attempts" }));await user.click(await screen.findByText("First learner"));expect(screen.getByText("History unavailable")).toBeTruthy();expect(screen.getByText("Chat history unavailable.")).toBeTruthy();expect(screen.getByText("Elapsed from start to last activity")).toBeTruthy();expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0);expect(screen.getByText("No submissions yet.")).toBeTruthy();await user.click(screen.getByRole("button", { name: "Load more attempts" }));expect(mocks.instructorRoundAttempts).toHaveBeenCalledWith("private-2", 7);await user.click(await screen.findByText("Second learner"));expect(screen.getByText("Partial history: 0 recorded runs")).toBeTruthy();expect(screen.getByText("1h 0m 0s")).toBeTruthy();expect(screen.queryByRole("button", { name: "Load more attempts" })).toBeNull();});it("shows loading, errors, retry, and empty attempts", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "private-3", repo_url: null, target_file: null, status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [] }] });let rejectLoad: (error: Error) => void = () => {};mocks.instructorRoundAttempts.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectLoad = reject; })).mockResolvedValueOnce({ attempts: [], has_more: false, next_offset: null });render(<App />);await user.click(await screen.findByRole("button", { name: "Managed rounds" }));await user.click(await screen.findByRole("button", { name: "View attempts" }));expect(screen.getByText("Loading attempts...")).toBeTruthy();await act(async () => rejectLoad(new Error("Attempts unavailable")));expect(screen.getByRole("alert").textContent).toContain("Attempts unavailable");await user.click(screen.getByRole("button", { name: "Retry" }));expect(await screen.findByText("No attempts yet.")).toBeTruthy();expect(mocks.instructorRoundAttempts).toHaveBeenLastCalledWith("private-3", 0);});it("discloses private-round chat access at join and in a private challenge", async () => {const user = userEvent.setup();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null });const view = render(<App />);expect(await screen.findByText("For private rounds, the publisher and course admin may view your full chat.")).toBeTruthy();view.unmount();mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1" });mocks.challenge.mockResolvedValue({ ...challenge, published_round: { round_id: "private-1", artifact_hash: "hash", tests_hash: "hash", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", status: "open" } });render(<App />);await user.click(await screen.findByRole("button", { name: "Open AI chat" }));expect(screen.getByText("For private rounds, the publisher and course admin may view your full chat.")).toBeTruthy();});it("shows the independent Hugging Face login when OAuth is enabled", async () => {mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: false });mocks.session.mockResolvedValue({ authenticated: false });
34 unmodified lines3536373839404134 unmodified lines7677787980811084 unmodified lines116611671168116911701171117211731174117511 unmodified lines11871188118911901191119257 unmodified lines12501251125212531254125534 unmodified linesXCircle,} from "lucide-react";import { api, waitForChallenge, waitForJob } from "./api";import type { ChallengeData, CourseAccessRequest, CourseAccessStatus, DevDiagnosis, HintResult, Identity, InstructorDashboard, PublicChallengeRound, ReflectionAnswers, ScoreReviewRequest, SessionInfo, StudentHistory, SubmissionResult, TestResult } from "./api";type ChatMessage = { role: "user" | "assistant"; content: string; gave_hint?: boolean };type RoundSettingsDraft = { time_limit_enabled: boolean; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public" };34 unmodified linestype AppConfig = { hf_oauth: boolean; google_oauth: boolean; dev_login: boolean; dev_diagnostics: boolean; model_key_configured: boolean; course_mode: boolean; approved_repositories: string[] };function App() {const [config, setConfig] = useState<AppConfig | null>(null);const [session, setSession] = useState<SessionInfo | null>(null);1084 unmodified lines<strong>{participant.latest_score == null ? "—" : `${participant.latest_score}/100`}</strong></div>))}<div className="managed-round-actions">{round.status === "prepared" && <button className="button button-secondary" onClick={() => setEditingRoundId(isEditing ? null : round.round_id)} disabled={busy}>{isEditing ? "Cancel settings" : "Edit settings"}</button>}{round.status === "prepared" && <button className="button button-secondary" onClick={() => void handleRoundTransition(round.round_id, "open")} disabled={busy}><Play size={15} />Open round</button>}{round.status === "open" && <button className="button button-secondary" onClick={() => void handleRoundTransition(round.round_id, "close")} disabled={busy}><XCircle size={15} />Close round</button>}</div>{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>11 unmodified lines)}<form className="setup-panel" onSubmit={handleStartChallenge}><div className="round-join-row"><label>Join a shared class challenge<input value={roundCode} onChange={(event) => setRoundCode(event.target.value)} placeholder="Paste round code" /></label>{joinedRoundIds.has(roundCode.trim()) ? <button type="button" className="button button-secondary" disabled><Check size={16} />Already joined</button> : <button type="button" className="button button-secondary" onClick={() => void handleJoinRound()} disabled={busy || !roundCode.trim()}>{busy ? <LoaderCircle className="spin" size={16} /> : <LogIn size={16} />}Join round</button>}</div>{!hasModelAccess && <p className="muted-copy" role="status">Without a model key, you can join existing challenges, run tests, and submit. Challenge creation, AI chat/hints, and AI review are disabled.</p>}{hasModelAccess && <><div className="round-divider">{config.course_mode ? "CREATE A PERSONAL CHALLENGE" : "OR CREATE A NEW CHALLENGE"}</div>57 unmodified lines{chatOpen && <section className="hint-panel chat-floating-panel" role="dialog" aria-modal="false" aria-label="AI debugging chat"><div className="hint-heading"><div className="hint-icon"><Lightbulb size={17} /></div><div><p className="eyebrow">AI DEBUGGING PARTNER</p><h2>Hints & questions</h2>{challenge.confirmation_pending && <span className="hint-confirmation-status" role="status">Confirmation needed: reply yes or no</span>}</div><span className="hint-count">{session.hints_used ?? challenge.hints_used ?? 0}/5 hints</span></div><div className="chat-usage-line"><span>{chatMessageCount} of {chatMessageLimit} messages used</span>{chatLimitReached && <strong>Limit reached</strong>}</div><div className="hint-messages" aria-live="polite">{messages.length === 0 ? <div className="empty-chat"><MessageSquareText size={23} /><p>Describe what you tried or ask a question about the code.</p><span>Hints count toward your final score.</span></div> : messages.map((item, index) => <div className={`chat-message ${item.role === "user" ? "chat-user" : "chat-assistant"}`} key={`${index}-${item.role}`}><span className="chat-role">{item.role === "user" ? identity.display_name : "CODE PARTNER"}{item.gave_hint && <em>HINT</em>}</span><p>{item.content}</p></div>)}</div>{hintResult && <div className="penalty-note">Cumulative hint penalty: <strong>−{hintResult.penalty} points</strong></div>}{!hasModelAccess && <p className="muted-copy" role="status">AI chat and hints are unavailable without a model API key.</p>}34 unmodified lines3536373839404134 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661084 unmodified lines1251125212531254125512561257125812591260126111 unmodified lines127312741275127612771278127957 unmodified lines133713381339134013411342134334 unmodified linesXCircle,} from "lucide-react";import { api, waitForChallenge, waitForJob } from "./api";import type { ChallengeData, CourseAccessRequest, CourseAccessStatus, DevDiagnosis, HintResult, Identity, InstructorAttempt, InstructorAttemptsPage, InstructorDashboard, PublicChallengeRound, ReflectionAnswers, ScoreReviewRequest, SessionInfo, StudentHistory, SubmissionResult, TestResult } from "./api";type ChatMessage = { role: "user" | "assistant"; content: string; gave_hint?: boolean };type RoundSettingsDraft = { time_limit_enabled: boolean; timer_minutes: number; chat_messages_per_student: number; visibility: "private" | "public" };34 unmodified linestype AppConfig = { hf_oauth: boolean; google_oauth: boolean; dev_login: boolean; dev_diagnostics: boolean; model_key_configured: boolean; course_mode: boolean; approved_repositories: string[] };function displayDate(value: string | null): string {if (!value) return "Unavailable";const date = new Date(value);return Number.isNaN(date.getTime()) ? "Unavailable" : date.toLocaleString();}function elapsedTime(attempt: InstructorAttempt): string {const start = attempt.started_at ? Date.parse(attempt.started_at) : NaN;const end = attempt.submitted_at ? Date.parse(attempt.submitted_at) : attempt.updated_at ? Date.parse(attempt.updated_at) : NaN;if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return "Unavailable";const seconds = Math.floor((end - start) / 1000);const hours = Math.floor(seconds / 3600);const minutes = Math.floor((seconds % 3600) / 60);return `${hours}h ${minutes}m ${seconds % 60}s`;}function testFraction(passed: number | null, total: number | null): string {return passed == null || total == null ? "Unavailable" : `${passed}/${total}`;}function RoundAttempts({ roundId }: { roundId: string }) {const [open, setOpen] = useState(false);const [page, setPage] = useState<InstructorAttemptsPage | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState("");async function load(offset: number) {setLoading(true);setError("");try {const result = await api.instructorRoundAttempts(roundId, offset);setPage((current) => ({ ...result, attempts: offset === 0 ? result.attempts : [...(current?.attempts ?? []), ...result.attempts] }));} catch (cause) {setError(cause instanceof Error ? cause.message : "Could not load attempts");} finally {setLoading(false);}}return <div className="round-attempts"><button type="button" className="button button-secondary" aria-expanded={open} onClick={() => { setOpen(!open); if (!open && !page && !loading) void load(0); }}><History size={15} />{open ? "Hide attempts" : "View attempts"}</button>{open && <div className="attempt-list">{page?.attempts.map((attempt) => <details className="attempt-detail" key={attempt.workspace_id}><summary><strong>{attempt.student_name || "Student"}</strong><span>{attempt.status.replaceAll("_", " ")}</span><ChevronDown size={15} /></summary><div className="attempt-content"><dl className="attempt-stats"><div><dt>Started</dt><dd>{displayDate(attempt.started_at)}</dd></div><div><dt>Last activity</dt><dd>{displayDate(attempt.updated_at)}</dd></div><div><dt>Submitted</dt><dd>{displayDate(attempt.submitted_at)}</dd></div><div><dt>Elapsed from start to {attempt.submitted_at ? "submission" : "last activity"}</dt><dd>{elapsedTime(attempt)}</dd></div><div><dt>Hints used</dt><dd>{attempt.hints_used}</dd></div></dl><section aria-label="Public test runs"><h4>Public test runs</h4>{attempt.public_test_runs === null ? <p>History unavailable</p> : <><p>{attempt.public_test_history_complete ? `${attempt.public_test_runs.length} ${attempt.public_test_runs.length === 1 ? "run" : "runs"}` : `Partial history: ${attempt.public_test_runs.length} recorded runs`}</p>{attempt.public_test_runs.map((run, index) => <p key={index}>{displayDate(run.ran_at)}: {run.passed}/{run.total} passed</p>)}</>}</section><section aria-label="Attempt chat"><h4>Chat</h4>{attempt.chat_log === null ? <p>Chat history unavailable.</p> : attempt.chat_log.length ? attempt.chat_log.map((entry, index) => <div className="attempt-chat-entry" key={index}><p><strong>Student</strong><span>{entry.question}</span></p><p><strong>Code partner{entry.gave_hint ? " · Hint" : ""}</strong><span>{entry.response}</span></p>{entry.hint_summary && <p><strong>Hint summary</strong><span>{entry.hint_summary}</span></p>}</div>) : <p>No chat messages recorded.</p>}</section><section aria-label="Attempt submissions"><h4>Submissions</h4>{attempt.submissions.length ? attempt.submissions.map((submission, index) => <div className="attempt-submission" key={index}><strong>Submission {index + 1} · {displayDate(submission.submitted_at)}</strong><dl className="attempt-stats"><div><dt>Score</dt><dd>{submission.total_score == null ? "Unavailable" : `${submission.total_score}/100`}</dd></div><div><dt>All tests</dt><dd>{testFraction(submission.passed_tests, submission.total_tests)}</dd></div><div><dt>Public tests</dt><dd>{testFraction(submission.public_passed, submission.public_total)}</dd></div><div><dt>Secret tests</dt><dd>{testFraction(submission.secret_passed, submission.secret_total)}</dd></div><div><dt>Outcome</dt><dd>{submission.submission_outcome?.replaceAll("_", " ") || "Unavailable"}</dd></div><div><dt>Confidence</dt><dd>{submission.self_assessment?.confidence ?? "Unavailable"}</dd></div></dl><p><strong>Known limitations</strong><span>{submission.self_assessment?.known_limitations || "Not provided"}</span></p><details className="attempt-diff"><summary>Student diff (before / after)</summary><pre>{submission.student_diff || "No diff available."}</pre></details></div>) : <p>No submissions yet.</p>}</section></div></details>)}{page && !page.attempts.length && !loading && <p>No attempts yet.</p>}{loading && <p role="status">Loading attempts...</p>}{error && <div className="attempt-error"><p className="notice notice-error" role="alert">{error}</p><button type="button" className="button button-secondary" onClick={() => void load(page?.next_offset ?? 0)} disabled={loading}><RefreshCw size={15} />Retry</button></div>}{!loading && !error && page?.has_more && page.next_offset !== null && <button type="button" className="button button-secondary" onClick={() => void load(page.next_offset!)}>Load more attempts</button>}</div>}</div>;}function App() {const [config, setConfig] = useState<AppConfig | null>(null);const [session, setSession] = useState<SessionInfo | null>(null);1084 unmodified lines<strong>{participant.latest_score == null ? "—" : `${participant.latest_score}/100`}</strong></div>))}{round.visibility === "private" && <RoundAttempts roundId={round.round_id} />}<div className="managed-round-actions">{round.can_manage !== false && round.status === "prepared" && <button className="button button-secondary" onClick={() => setEditingRoundId(isEditing ? null : round.round_id)} disabled={busy}>{isEditing ? "Cancel settings" : "Edit settings"}</button>}{round.can_manage !== false && round.status === "prepared" && <button className="button button-secondary" onClick={() => void handleRoundTransition(round.round_id, "open")} disabled={busy}><Play size={15} />Open round</button>}{round.can_manage !== false && round.status === "open" && <button className="button button-secondary" onClick={() => void handleRoundTransition(round.round_id, "close")} disabled={busy}><XCircle size={15} />Close round</button>}</div>{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>11 unmodified lines)}<form className="setup-panel" onSubmit={handleStartChallenge}><div className="round-join-row"><label>Join a shared class challenge<input value={roundCode} onChange={(event) => setRoundCode(event.target.value)} placeholder="Paste round code" /></label>{joinedRoundIds.has(roundCode.trim()) ? <button type="button" className="button button-secondary" disabled><Check size={16} />Already joined</button> : <button type="button" className="button button-secondary" onClick={() => void handleJoinRound()} disabled={busy || !roundCode.trim()}>{busy ? <LoaderCircle className="spin" size={16} /> : <LogIn size={16} />}Join round</button>}</div><p className="muted-copy">For private rounds, the publisher and course admin may view your full chat.</p>{!hasModelAccess && <p className="muted-copy" role="status">Without a model key, you can join existing challenges, run tests, and submit. Challenge creation, AI chat/hints, and AI review are disabled.</p>}{hasModelAccess && <><div className="round-divider">{config.course_mode ? "CREATE A PERSONAL CHALLENGE" : "OR CREATE A NEW CHALLENGE"}</div>57 unmodified lines{chatOpen && <section className="hint-panel chat-floating-panel" role="dialog" aria-modal="false" aria-label="AI debugging chat"><div className="hint-heading"><div className="hint-icon"><Lightbulb size={17} /></div><div><p className="eyebrow">AI DEBUGGING PARTNER</p><h2>Hints & questions</h2>{challenge.confirmation_pending && <span className="hint-confirmation-status" role="status">Confirmation needed: reply yes or no</span>}</div><span className="hint-count">{session.hints_used ?? challenge.hints_used ?? 0}/5 hints</span></div><div className="chat-usage-line"><span>{chatMessageCount} of {chatMessageLimit} messages used</span>{chatLimitReached && <strong>Limit reached</strong>}</div><p className="private-chat-notice">For private rounds, the publisher and course admin may view your full chat.</p><div className="hint-messages" aria-live="polite">{messages.length === 0 ? <div className="empty-chat"><MessageSquareText size={23} /><p>Describe what you tried or ask a question about the code.</p><span>Hints count toward your final score.</span></div> : messages.map((item, index) => <div className={`chat-message ${item.role === "user" ? "chat-user" : "chat-assistant"}`} key={`${index}-${item.role}`}><span className="chat-role">{item.role === "user" ? identity.display_name : "CODE PARTNER"}{item.gave_hint && <em>HINT</em>}</span><p>{item.content}</p></div>)}</div>{hintResult && <div className="penalty-note">Cumulative hint penalty: <strong>−{hintResult.penalty} points</strong></div>}{!hasModelAccess && <p className="muted-copy" role="status">AI chat and hints are unavailable without a model API key.</p>}
184 unmodified lines18518618718818919019131 unmodified lines22322422522622722879 unmodified lines308309310311312313184 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;visibility: "private" | "public";participants: Array<{student_name: string | null;status: string;31 unmodified linesexport type InstructorDashboard = { rounds: InstructorRound[] };export type CourseAccessRequest = {request_id: string;auth_provider: string;79 unmodified lineshistory: (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"),courseAccess: () => request<CourseAccessStatus>("/api/course/access"),requestInstructorAccess: (reason: string) =>request<{ request_id: string; status: string }>("/api/course/access-requests", {184 unmodified lines18518618718818919019119231 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026179 unmodified lines341342343344345346347184 unmodified linesclosed_at: string | null;timer_minutes: number;chat_messages_per_student: number;visibility?: "private" | "public";can_manage?: boolean;participants: Array<{student_name: string | null;status: string;31 unmodified linesexport type InstructorDashboard = { rounds: InstructorRound[] };export type InstructorAttempt = {workspace_id: string;student_name: string;status: string;started_at: string | null;updated_at: string | null;submitted_at: string | null;hints_used: number;public_test_runs: Array<{ ran_at: string; passed: number; total: number }> | null;public_test_history_complete: boolean;chat_log: Array<{ question: string; response: string; gave_hint: boolean; hint_summary: string }> | null;submissions: Array<{submitted_at: string | null;total_score: number | null;passed_tests: number | null;total_tests: number | null;public_passed: number | null;public_total: number | null;secret_passed: number | null;secret_total: number | null;submission_outcome: string | null;student_diff: string;self_assessment: { confidence?: number; known_limitations?: string };}>;};export type InstructorAttemptsPage = {attempts: InstructorAttempt[];has_more: boolean;next_offset: number | null;};export type CourseAccessRequest = {request_id: string;auth_provider: string;79 unmodified lineshistory: (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"),instructorRoundAttempts: (roundId: string, offset = 0) => request<InstructorAttemptsPage>(`/api/instructor/rounds/${encodeURIComponent(roundId)}/attempts?offset=${offset}`),courseAccess: () => request<CourseAccessStatus>("/api/course/access"),requestInstructorAccess: (reason: string) =>request<{ request_id: string; status: string }>("/api/course/access-requests", {
139 unmodified lines140141142143144145166 unmodified lines312313314315316317318139 unmodified lines.participant-row { display: grid; grid-template-columns: minmax(0, 1.3fr) .9fr .8fr auto; gap: 10px; border-bottom: 1px solid #e8edef; padding: 9px 4px; color: #50606c; font-size: 11px; line-height: 1.5; }.participant-row strong { color: var(--ink); text-align: right; }.managed-round-actions { display: flex; flex-wrap: wrap; gap: 10px; }.round-settings-editor { display: grid; max-width: 560px; gap: 13px; border: 1px solid var(--line); border-radius: 6px; padding: 14px; background: #f7f9fa; }.round-settings-editor label { display: grid; gap: 7px; color: #455668; font-size: 11px; font-weight: 600; }.round-settings-editor input { width: 100%; min-height: 38px; border: 1px solid #cfd9df; border-radius: 5px; padding: 0 10px; color: var(--ink); background: #fff; font-size: 12px; }166 unmodified lines.chat-role { display: flex; align-items: center; gap: 7px; margin-bottom: 5px; color: #97d3c9; font: 9px 'IBM Plex Mono', monospace; letter-spacing: .4px; }.chat-assistant .chat-role { color: #69818b; }.chat-role em { border-radius: 3px; padding: 2px 4px; color: #80510e; background: #f2dfbd; font-style: normal; }.chat-message p { margin: 0; font-size: 12px; line-height: 1.6; white-space: pre-wrap; }.penalty-note { margin-bottom: 8px; color: #7c694a; font-size: 10px; }.penalty-note strong { color: #8e5c18; }.chat-form { display: flex; align-items: flex-end; gap: 10px; border: 1px solid #d5dfe3; border-radius: 6px; padding: 8px; background: #fff; }139 unmodified lines140141142143144145146147148149150151152153154155156157158159160161162163164165166167168166 unmodified lines335336337338339340341139 unmodified lines.participant-row { display: grid; grid-template-columns: minmax(0, 1.3fr) .9fr .8fr auto; gap: 10px; border-bottom: 1px solid #e8edef; padding: 9px 4px; color: #50606c; font-size: 11px; line-height: 1.5; }.participant-row strong { color: var(--ink); text-align: right; }.managed-round-actions { display: flex; flex-wrap: wrap; gap: 10px; }.round-attempts, .attempt-list, .attempt-content { display: grid; gap: 12px; min-width: 0; }.round-attempts > .button, .attempt-list > .button { justify-self: start; }.attempt-detail { min-width: 0; border-top: 1px solid var(--line); padding-top: 12px; }.attempt-detail > summary { display: flex; align-items: center; gap: 10px; cursor: pointer; font-size: 13px; }.attempt-detail > summary strong { min-width: 0; overflow-wrap: anywhere; }.attempt-detail > summary span { color: var(--muted); font-size: 12px; text-transform: capitalize; }.attempt-detail > summary svg { margin-left: auto; flex: 0 0 auto; }.attempt-content { padding: 14px 0; color: var(--ink); font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; }.attempt-content h4 { margin: 0 0 8px; font-size: 13px; }.attempt-content p { margin: 6px 0; }.attempt-content section { min-width: 0; border-top: 1px solid var(--line); padding-top: 12px; }.attempt-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 10px 16px; margin: 0; }.attempt-stats div { min-width: 0; }.attempt-stats dt { color: var(--muted); font-size: 12px; }.attempt-stats dd { margin: 3px 0 0; font-weight: 600; }.attempt-chat-entry, .attempt-submission { border-top: 1px solid var(--line); padding: 10px 0; }.attempt-chat-entry p, .attempt-submission > p { display: grid; gap: 3px; white-space: pre-wrap; }.attempt-submission > .attempt-stats { margin-top: 10px; }.attempt-diff { margin-top: 10px; }.attempt-diff summary { cursor: pointer; font-weight: 600; }.attempt-diff pre { max-width: 100%; overflow-x: auto; padding: 10px; background: #f5f8f8; font: 12px/1.5 'IBM Plex Mono', monospace; }.attempt-error { display: grid; gap: 8px; justify-items: start; }.private-chat-notice { margin: 0; color: #455668; font-size: 12px; line-height: 1.5; }.round-settings-editor { display: grid; max-width: 560px; gap: 13px; border: 1px solid var(--line); border-radius: 6px; padding: 14px; background: #f7f9fa; }.round-settings-editor label { display: grid; gap: 7px; color: #455668; font-size: 11px; font-weight: 600; }.round-settings-editor input { width: 100%; min-height: 38px; border: 1px solid #cfd9df; border-radius: 5px; padding: 0 10px; color: var(--ink); background: #fff; font-size: 12px; }166 unmodified lines.chat-role { display: flex; align-items: center; gap: 7px; margin-bottom: 5px; color: #97d3c9; font: 9px 'IBM Plex Mono', monospace; letter-spacing: .4px; }.chat-assistant .chat-role { color: #69818b; }.chat-role em { border-radius: 3px; padding: 2px 4px; color: #80510e; background: #f2dfbd; font-style: normal; }.chat-message p { margin: 0; overflow-wrap: anywhere; font-size: 12px; line-height: 1.6; white-space: pre-wrap; }.penalty-note { margin-bottom: 8px; color: #7c694a; font-size: 10px; }.penalty-note strong { color: #8e5c18; }.chat-form { display: flex; align-items: flex-end; gap: 10px; border: 1px solid #d5dfe3; border-radius: 6px; padding: 8px; background: #fff; }
7 unmodified lines891011121371 unmodified lines858687888990914 unmodified lines9697989910010110210310410510610756 unmodified lines1641651661671681697 unmodified linesfrom urllib.error import HTTPError, URLErrorfrom urllib.parse import urlencodefrom urllib.request import Request, urlopenclass HistoryStoreError(RuntimeError):71 unmodified linesdef get_instructor_dashboard(identity: dict[str, str], limit: int = 100, course_id: str | None = None) -> dict[str, list[dict[str, Any]]] | None:provider = str(identity.get("provider") or "").strip()user_id = str(identity.get("user_id") or "").strip()4 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","limit": str(limit),})if not rounds:return {"rounds": []}round_ids = [str(row.get("round_id") or "") for row in rounds]56 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}7 unmodified lines89101112131471 unmodified lines86878889909192934 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012156 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762777 unmodified linesfrom urllib.error import HTTPError, URLErrorfrom urllib.parse import urlencodefrom urllib.request import Request, urlopenfrom uuid import UUIDclass HistoryStoreError(RuntimeError):71 unmodified linesdef get_instructor_dashboard(identity: dict[str, str], limit: int = 100, course_id: str | None = None,include_all_private: bool = False,) -> dict[str, list[dict[str, Any]]] | None:provider = str(identity.get("provider") or "").strip()user_id = str(identity.get("user_id") or "").strip()4 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,visibility,published_by","course_id": f"eq.{_course_id(course_id)}","published_by": f"eq.{provider}:{user_id}","order": "created_at.desc,round_id.desc","limit": str(limit),})if include_all_private:private_rounds = _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,visibility,published_by","course_id": f"eq.{_course_id(course_id)}","visibility": "eq.private","order": "created_at.desc,round_id.desc","limit": str(limit),})seen_rounds = {str(row.get("round_id")) for row in rounds}rounds.extend(row for row in private_rounds if str(row.get("round_id")) not in seen_rounds)rounds.sort(key=lambda row: (str(row.get("created_at") or ""), str(row.get("round_id") or "")), reverse=True)rounds = rounds[:limit]if not rounds:return {"rounds": []}round_ids = [str(row.get("round_id") or "") for row in rounds]56 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),"visibility": round_row.get("visibility"),"can_manage": round_row.get("published_by") == f"{provider}:{user_id}","participants": participants,})return {"rounds": result_rounds}def get_instructor_round_attempts(identity: dict[str, str], round_id: str, course_id: str | None = None,*, is_admin: bool = False, offset: int = 0, limit: int = 20,) -> dict[str, Any] | None:provider = str(identity.get("provider") or "").strip()user_id = str(identity.get("user_id") or "").strip()try:round_id = str(UUID(round_id))except (ValueError, TypeError, AttributeError) as exc:raise HistoryStoreError("Invalid challenge round ID") from excif not provider or not user_id or isinstance(offset, bool) or offset < 0 or not 1 <= limit <= 100:raise HistoryStoreError("Invalid instructor identity or page")configured = _configuration()if configured is None:raise HistoryStoreError("Instructor dashboard requires persistent course storage")url, key = configuredcourse = _course_id(course_id)rounds = _get_rows(url, key, "challenge_rounds", {"select": "round_id,published_by,visibility", "round_id": f"eq.{round_id}","course_id": f"eq.{course}", "limit": "1",})if not rounds or rounds[0].get("visibility") != "private":return Noneif not is_admin and rounds[0].get("published_by") != f"{provider}:{user_id}":return Noneattempts = _get_rows(url, key, "challenge_attempts", {"select": "workspace_id,student_name,status,started_at,updated_at,hints_used,chat_log:payload->chat_log,public_test_runs:payload->public_test_runs,public_test_history_complete:payload->public_test_history_complete","course_id": f"eq.{course}", "round_id": f"eq.{round_id}","order": "started_at.desc,workspace_id.desc", "offset": str(offset), "limit": str(limit + 1),})has_more = len(attempts) > limitattempts = attempts[:limit]workspace_ids = []for attempt in attempts:try:workspace_ids.append(str(UUID(str(attempt.get("workspace_id") or ""))))except ValueError as exc:raise HistoryStoreError("Invalid stored attempt ID") from excsubmissions = []if workspace_ids:submissions = _get_rows(url, key, "submissions", {"select": "workspace_id,submitted_at,total_score,passed_tests,total_tests,submission_outcome,public_passed:payload->tests->>public_passed,public_total:payload->tests->>public_total,secret_passed:payload->tests->>secret_passed,secret_total:payload->tests->>secret_total,student_diff:payload->submission->>student_diff,self_assessment:payload->submission->self_assessment","course_id": f"eq.{course}", "round_id": f"eq.{round_id}","workspace_id": f"in.({','.join(workspace_ids)})","order": "submitted_at.desc,submission_id.desc",})submissions_by_workspace: dict[str, list[dict[str, Any]]] = {}for submission in submissions:assessment = submission.get("self_assessment")assessment = assessment if isinstance(assessment, dict) else {}summary = {name: submission.get(name) for name in ("submitted_at", "total_score", "passed_tests", "total_tests", "submission_outcome",)}for name in ("public_passed", "public_total", "secret_passed", "secret_total"):value = submission.get(name)try:summary[name] = int(value) if value is not None else Noneexcept (TypeError, ValueError):summary[name] = Nonesummary["student_diff"] = str(submission.get("student_diff") or "")summary["self_assessment"] = {name: assessment[name] for name in ("confidence", "known_limitations") if name in assessment}submissions_by_workspace.setdefault(str(submission.get("workspace_id") or ""), []).append(summary)result_attempts = []for attempt, workspace_id in zip(attempts, workspace_ids):messages = attempt.get("chat_log")messages = messages if isinstance(messages, list) else Noneruns = attempt.get("public_test_runs")runs = [{name: run.get(name) for name in ("ran_at", "passed", "total")}for run in runs if isinstance(run, dict)] if isinstance(runs, list) else Noneown_submissions = submissions_by_workspace.get(workspace_id, [])result_attempts.append({"workspace_id": workspace_id,"student_name": str(attempt.get("student_name") or "Student"),"status": str(attempt.get("status") or "in_progress"),"started_at": attempt.get("started_at"), "updated_at": attempt.get("updated_at"),"submitted_at": own_submissions[0].get("submitted_at") if own_submissions else None,"hints_used": int(attempt.get("hints_used") or 0),"public_test_runs": runs,"public_test_history_complete": attempt.get("public_test_history_complete") is True,"chat_log": [{"question": str(message.get("question") or ""), "response": str(message.get("response") or ""),"gave_hint": bool(message.get("gave_hint")), "hint_summary": str(message.get("hint_summary") or "")}for message in messages if isinstance(message, dict)] if messages is not None else None,"submissions": own_submissions,})return {"attempts": result_attempts, "has_more": has_more, "next_offset": offset + limit if has_more else None}
2 unmodified lines34567879 unmodified lines8889909192932 unmodified linesimport unittestfrom unittest.mock import patchfrom urllib.parse import parse_qs, urlsplitimport supabase_history as history79 unmodified linesself.assertEqual(query["course_id"], ["eq.course-7"])self.assertNotIn("payload", query["select"][0])if __name__ == "__main__":unittest.main()2 unmodified lines345678979 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671682 unmodified linesimport unittestfrom unittest.mock import patchfrom urllib.parse import parse_qs, urlsplitfrom uuid import uuid4import supabase_history as history79 unmodified linesself.assertEqual(query["course_id"], ["eq.course-7"])self.assertNotIn("payload", query["select"][0])def test_private_round_attempts_returns_only_authorized_selected_fields(self):round_id, workspace_id, next_workspace_id = (str(uuid4()) for _ in range(3))teacher = {"provider": "huggingface", "user_id": "teacher-1"}responses = [[{"round_id": round_id, "published_by": "huggingface:teacher-1", "visibility": "private"}],[{"workspace_id": workspace_id, "student_name": "Learner", "status": "submitted","started_at": "2026-01-01T10:00:00Z", "updated_at": "2026-01-01T11:00:00Z", "hints_used": 1,"chat_log": [{"question": "Why?", "response": "Check the branch", "gave_hint": True, "secret": "hidden"}],"public_test_runs": [{"ran_at": "2026-01-01T10:10:00Z", "passed": 1, "total": 2, "secret": "hidden"}],"public_test_history_complete": True, "payload": {"secret_tests": "hidden"}},{"workspace_id": next_workspace_id},],[{"workspace_id": workspace_id, "submitted_at": "2026-01-01T11:00:00Z", "total_score": 88,"passed_tests": 4, "total_tests": 5, "public_passed": "2", "public_total": "2","secret_passed": "2", "secret_total": "3", "student_diff": "+fix","self_assessment": {"confidence": 4, "known_limitations": "edge case", "secret": "hidden"},"payload": {"secret_tests": "hidden"}}],]with patch.object(history, "_get_rows", side_effect=responses) as get_rows:result = history.get_instructor_round_attempts(teacher, round_id, "course-7", limit=1)self.assertTrue(result["has_more"])self.assertEqual(result["next_offset"], 1)attempt = result["attempts"][0]self.assertEqual(attempt["workspace_id"], workspace_id)self.assertEqual(attempt["chat_log"][0]["question"], "Why?")self.assertTrue(attempt["chat_log"][0]["gave_hint"])self.assertEqual(attempt["public_test_runs"][0]["passed"], 1)self.assertEqual(attempt["submissions"][0]["secret_total"], 3)self.assertNotIn("hidden", json.dumps(result))self.assertEqual(get_rows.call_args_list[0].args[3]["course_id"], "eq.course-7")self.assertEqual(get_rows.call_args_list[1].args[3]["round_id"], f"eq.{round_id}")self.assertEqual(get_rows.call_args_list[1].args[3]["limit"], "2")self.assertEqual(get_rows.call_args_list[2].args[3]["workspace_id"], f"in.({workspace_id})")def test_admin_dashboard_includes_other_private_rounds_but_only_owns_manage_controls(self):own_round, other_round = str(uuid4()), str(uuid4())identity = {"provider": "huggingface", "user_id": "teacher-1"}own = {"round_id": own_round, "published_by": "huggingface:teacher-1", "visibility": "private"}other = {"round_id": other_round, "published_by": "huggingface:teacher-2", "visibility": "private"}with patch.object(history, "_get_rows", side_effect=[[own], [own, other], [], []]) as get_rows:result = history.get_instructor_dashboard(identity, course_id="course-7", include_all_private=True)rounds = {row["round_id"]: row for row in result["rounds"]}self.assertEqual(len(rounds), 2)self.assertTrue(rounds[own_round]["can_manage"])self.assertFalse(rounds[other_round]["can_manage"])self.assertEqual(get_rows.call_args_list[1].args[3]["visibility"], "eq.private")self.assertEqual(get_rows.call_args_list[1].args[3]["course_id"], "eq.course-7")def test_private_round_attempts_denies_other_publisher_and_public_round_before_fetching_students(self):round_id = str(uuid4())teacher = {"provider": "huggingface", "user_id": "teacher-1"}for row in ({"round_id": round_id, "published_by": "huggingface:other", "visibility": "private"},{"round_id": round_id, "published_by": "huggingface:teacher-1", "visibility": "public"},):with self.subTest(row=row), patch.object(history, "_get_rows", return_value=[row]) as get_rows:self.assertIsNone(history.get_instructor_round_attempts(teacher, round_id, "course-7"))self.assertEqual(get_rows.call_count, 1)def test_course_admin_can_access_other_publishers_private_round_without_inventing_history(self):round_id, workspace_id = str(uuid4()), str(uuid4())responses = [[{"round_id": round_id, "published_by": "huggingface:other", "visibility": "private"}],[{"workspace_id": workspace_id, "status": "in_progress"}],[],]with patch.object(history, "_get_rows", side_effect=responses):result = history.get_instructor_round_attempts(self.identity, round_id, "course-7", is_admin=True)self.assertIsNone(result["attempts"][0]["public_test_runs"])self.assertFalse(result["attempts"][0]["public_test_history_complete"])self.assertIsNone(result["attempts"][0]["chat_log"])if __name__ == "__main__":unittest.main()
README.md+2
backend/app.py+54-2
backend/submission_records.py+1-1
backend/test_api.py+35-1
frontend/src/App.test.tsx+108
frontend/src/App.tsx+92-4
frontend/src/api.ts+35-1
frontend/src/styles.css+24-1
supabase_history.py+111-3
test_supabase_history.py+75