Spaces:
Sleeping
Sleeping
Download frontend/src/App.test.tsx from refaelz/legacy-code-challenge-v2: direct link, hf CLI and curl.
- Browser
- Download file 95.3 kB
-
https://huggingface.co/spaces/refaelz/legacy-code-challenge-v2/resolve/main/frontend/src/App.test.tsx
- Command line
-
hf download hf://spaces/refaelz/legacy-code-challenge-v2/frontend/src/App.test.tsx
-
curl -L -o App.test.tsx https://huggingface.co/spaces/refaelz/legacy-code-challenge-v2/resolve/main/frontend/src/App.test.tsx
95.3 kB
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({
editor: { trigger: vi.fn(), revealLineInCenter: vi.fn(), setPosition: vi.fn(), focus: vi.fn() },
config: vi.fn(),
session: vi.fn(),
login: vi.fn(),
saveModelKey: vi.fn(),
logout: vi.fn(),
startChallenge: vi.fn(),
publishChallengeRound: vi.fn(),
pollJob: vi.fn(),
challenge: vi.fn(),
history: vi.fn(),
submittedResult: vi.fn(),
resume: vi.fn(),
instructorDashboard: vi.fn(),
instructorRoundAttempts: vi.fn(),
instructorRetryRequests: vi.fn(),
reviewRetryRequest: vi.fn(),
retryRequest: vi.fn(),
createRetryRequest: vi.fn(),
feedback: vi.fn(),
instructorFeedback: vi.fn(),
saveInstructorFeedback: vi.fn(),
courseAccess: vi.fn(),
requestInstructorAccess: vi.fn(),
courseAccessRequests: vi.fn(),
reviewCourseAccessRequest: vi.fn(),
openRound: vi.fn(),
closeRound: vi.fn(),
updateRoundSettings: vi.fn(),
publicTests: vi.fn(),
readFile: vi.fn(),
saveFile: vi.fn(),
reset: vi.fn(),
runTests: vi.fn(),
diff: vi.fn(),
hint: vi.fn(),
diagnosis: vi.fn(),
submit: vi.fn(),
requestScoreReview: vi.fn(),
comprehension: vi.fn(),
gradeComprehension: vi.fn(),
saveReflection: vi.fn(),
waitForChallenge: vi.fn(),
waitForJob: vi.fn(),
}));
vi.mock("./api", () => ({ api: mocks, waitForChallenge: mocks.waitForChallenge, waitForJob: mocks.waitForJob }));
vi.mock("@monaco-editor/react", async () => {
const React = await import("react");
return {
default: ({ value, onChange, onMount }: { value: string; onChange: (value: string) => void; onMount?: (editor: typeof mocks.editor) => void }) => {
React.useEffect(() => { onMount?.(mocks.editor); }, [onMount]);
return React.createElement("textarea", { "aria-label": "Code editor", value, onChange: (event) => onChange((event.target as HTMLTextAreaElement).value) });
},
};
});
import App from "./App";
const identity = {
provider: "huggingface",
user_id: "hf-user-1",
username: "alice",
display_name: "Alice",
profile_url: "https://huggingface.co/alice",
email: "",
};
const challenge = {
workspace_id: "workspace-1",
repo_url: "https://github.com/acme/demo",
target_file: "src/demo.py",
file_path: "src/demo.py",
code: "def normalize(value):\n return value\n",
readme: "# Mission\nRepair the normalizer.",
files: ["src/demo.py"],
challenge_summary: "Fix the return value.",
hints_used: 0,
submission_count: 0,
timer_remaining: 900,
chat_history: [],
};
beforeEach(() => {
vi.clearAllMocks();
window.sessionStorage.clear();
mocks.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.comprehension.mockResolvedValue({ status: "not_applicable" });
mocks.feedback.mockResolvedValue({ feedback: null, updated_at: null });
mocks.instructorFeedback.mockResolvedValue({ feedback: null, updated_at: null });
mocks.saveInstructorFeedback.mockImplementation(async (_id, feedback) => ({ feedback, updated_at: "2026-01-01T12:00:00Z" }));
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: [] });
mocks.instructorRoundAttempts.mockReset().mockResolvedValue({ attempts: [], has_more: false, next_offset: null });
mocks.instructorRetryRequests.mockReset().mockResolvedValue({ requests: [] });
mocks.reviewRetryRequest.mockReset().mockResolvedValue({ status: "approved" });
mocks.retryRequest.mockReset().mockResolvedValue({ status: "none" });
mocks.createRetryRequest.mockReset().mockResolvedValue({ status: "pending" });
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: [] });
mocks.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, hints_per_student: 0, visibility: "private", status: "prepared" });
mocks.publicTests.mockResolvedValue({ file_path: "src/demo.py", functions: ["normalize"], total: 1, source: "# Test 1: normalize(*('value',))\n# Expected: 'value'" });
mocks.runTests.mockResolvedValue({ passed: 1, total: 2, score: 40, output: "Test 1: PASS", all_passed: false, per_test: [{ num: 1, status: "PASS", actual_raw: "1st", actual: "str len=3 diff@0: '1st'" }, { num: 2, status: "FAIL", actual_raw: "2nd", actual: "str len=3 diff@0: '2nd'" }] });
mocks.diff.mockResolvedValue({ diff: "-value = 0\n+value = 2", has_changes: true });
mocks.hint.mockResolvedValue({ response: "Check the return branch.", gave_hint: true, hints_used: 1, penalty: 2, chat_history: [] });
mocks.diagnosis.mockResolvedValue({ file_path: "src/demo.py", functions: ["normalize"], bug_description: "The function returns the input unchanged.", diff: "- return value\n+ return value.strip()" });
mocks.submit.mockResolvedValue({ job_id: "submission-job", kind: "submission", status: "queued" });
mocks.requestScoreReview.mockResolvedValue({ job_id: "review-job", kind: "score_review", status: "queued" });
mocks.waitForJob.mockResolvedValue({ submission_id: "submission-1", score: 78, test_score: 80, llm_score: 80, llm_review_status: "completed", hint_penalty: 2, passed: 1, total_tests: 2, public_passed: 1, public_total: 1, secret_passed: 0, secret_total: 1, all_passed: false, tests: [{ num: 1, status: "PASS" }], public_output: "Test 1: PASS", explanation: "A partial fix.", submission_outcome: "partial_fix", expected_diff: "- return value\n+ return value.strip()", supabase_saved: true, storage_warning: "", submission_count: 1 });
});
afterEach(() => cleanup());
describe("React challenge experience", () => {
it("loads and saves instructor feedback for a submission", 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", status: "open", timer_minutes: 0, visibility: "private", participants: [] }] });
mocks.instructorRoundAttempts.mockResolvedValue({ attempts: [{
workspace_id: "attempt-1", student_name: "Learner", status: "submitted", started_at: null, updated_at: null, submitted_at: null, hints_used: 0,
public_test_runs: null, public_test_history_complete: false, chat_log: null,
submissions: [{ submission_id: "submission-1", submitted_at: null, total_score: 80, passed_tests: 1, total_tests: 1, public_passed: 1, public_total: 1, secret_passed: 0, secret_total: 0, submission_outcome: "full_fix", student_diff: "+fix", self_assessment: {} }],
}], has_more: false, next_offset: null });
mocks.instructorFeedback.mockResolvedValue({ feedback: "Previous feedback", updated_at: 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("Learner"));
const field = await screen.findByLabelText("Feedback");
await waitFor(() => expect((field as HTMLTextAreaElement).value).toBe("Previous feedback"));
await user.clear(field);
await user.type(field, "Well explained");
await user.click(screen.getByRole("button", { name: "Save feedback" }));
await waitFor(() => expect(mocks.saveInstructorFeedback).toHaveBeenCalledWith("submission-1", "Well explained"));
});
it("keeps feedback and retry controls out of challenge history", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
expect(await screen.findByText("Submission 1")).toBeTruthy();
expect(screen.queryByText("Instructor feedback")).toBeNull();
expect(screen.queryByRole("region", { name: "Retry request" })).toBeNull();
expect(mocks.feedback).not.toHaveBeenCalled();
expect(mocks.retryRequest).not.toHaveBeenCalled();
});
it("refreshes history on open so earlier attempts remain visible after a retry", async () => {
const user = userEvent.setup();
mocks.history
.mockResolvedValueOnce({ attempts: [{ workspace_id: "old-attempt", status: "submitted", round_id: "round-1", resumable: false, hints_used: 1, submissions: [{ submission_id: "old-submission", attempt_number: 1, total_score: 40, passed_tests: 1, total_tests: 3 }] }], limit: 50 })
.mockResolvedValueOnce({ attempts: [
{ workspace_id: "new-attempt", status: "submitted", round_id: "round-1", resumable: false, hints_used: 1, submissions: [{ submission_id: "new-submission", attempt_number: 1, total_score: 90, passed_tests: 3, total_tests: 3 }] },
{ workspace_id: "old-attempt", status: "submitted", round_id: "round-1", resumable: false, hints_used: 1, submissions: [{ submission_id: "old-submission", attempt_number: 1, total_score: 40, passed_tests: 1, total_tests: 3 }] },
], limit: 50 })
.mockResolvedValueOnce({ attempts: [
{ workspace_id: "new-attempt", status: "submitted", round_id: "round-1", resumable: false, hints_used: 1, submissions: [{ submission_id: "new-submission", attempt_number: 1, total_score: 90, passed_tests: 3, total_tests: 3 }] },
{ workspace_id: "old-attempt", status: "submitted", round_id: "round-1", resumable: false, hints_used: 1, submissions: [{ submission_id: "old-submission", attempt_number: 1, total_score: 40, passed_tests: 1, total_tests: 3 }] },
], limit: 50 });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
expect(await screen.findByText("40/100")).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Close history" }));
await user.click(screen.getByRole("button", { name: "Challenge history" }));
expect(await screen.findByText("90/100")).toBeTruthy();
expect(screen.getByText("40/100")).toBeTruthy();
expect(mocks.history).toHaveBeenCalledTimes(3);
});
it("opens the selected attempt's full saved summary from challenge history", async () => {
const user = userEvent.setup();
const roundId = "12345678-1234-4234-8234-123456789abc";
mocks.history.mockResolvedValue({ attempts: [{
workspace_id: "old-attempt", status: "submitted", round_id: roundId, resumable: false,
hints_used: 1, reflection_saved: true,
submissions: [{ submission_id: "old-submission", attempt_number: 1, total_score: 42, passed_tests: 1, total_tests: 3 }],
}], limit: 50 });
mocks.submittedResult.mockResolvedValue({ round_id: roundId, result: {
submission_id: "old-submission", score: 42, test_score: 40, llm_score: null,
llm_review_status: "completed", hint_penalty: 2, public_passed: 1, public_total: 2,
secret_passed: 0, secret_total: 1, all_passed: false, submission_outcome: "partial_fix",
tests: [], public_output: "Test failed", explanation: "Partial attempt", expected_diff: "+change",
} });
mocks.feedback.mockResolvedValue({ feedback: "Review this boundary", updated_at: null });
mocks.retryRequest.mockResolvedValue({ status: "none" });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
await user.click(await screen.findByRole("button", { name: "View summary" }));
expect(await screen.findByText("SUBMISSION REVIEW")).toBeTruthy();
expect(await screen.findByText("42")).toBeTruthy();
expect(await screen.findByText("Review this boundary")).toBeTruthy();
expect(await screen.findByRole("heading", { name: "Request another attempt" })).toBeTruthy();
expect(mocks.submittedResult).toHaveBeenCalledWith("old-attempt");
});
it("sends and restores a student's retry request from submission results", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, challenge_round_id: "round-1" });
render(<App />);
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
await user.type(await screen.findByLabelText("Reason (optional)"), "I would like another attempt");
await user.click(screen.getByRole("button", { name: "Send request" }));
await waitFor(() => expect(mocks.createRetryRequest).toHaveBeenCalledWith("submission-1", "I would like another attempt"));
expect(await screen.findByText("Request status: pending")).toBeTruthy();
});
it("shows pending retry requests to the instructor", 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", status: "open", timer_minutes: 0, visibility: "private", participants: [] }] });
mocks.instructorRetryRequests.mockResolvedValue({ requests: [{ request_id: "request-1", student_name: "Learner", reason: "Please reconsider", requested_at: "2026-01-01T10:00:00Z", status: "pending" }] });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Managed rounds" }));
await user.click(await screen.findByRole("button", { name: "View attempts" }));
const queue = await screen.findByRole("region", { name: "Retry requests" });
expect(within(queue).getByText("Learner")).toBeTruthy();
expect(within(queue).getByText("Please reconsider")).toBeTruthy();
expect(mocks.instructorRetryRequests).toHaveBeenCalledWith("private-1");
await user.type(within(queue).getByLabelText("Response (optional)"), "Try again");
await user.click(within(queue).getByRole("button", { name: "Approve" }));
await waitFor(() => expect(mocks.reviewRetryRequest).toHaveBeenCalledWith("private-1", "request-1", "approved", "Try again"));
});
it("shows the lecturer's decision and starts an approved retry", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1" });
mocks.challenge.mockResolvedValue({ ...challenge, challenge_round_id: "round-1" });
mocks.retryRequest.mockResolvedValueOnce({ status: "pending" }).mockResolvedValueOnce({ status: "approved", round_id: "round-1", request_id: "request-1", lecturer_response: "Try again", retry_started: false });
mocks.startChallenge.mockResolvedValue({ job_id: "retry-job", status: "queued" });
mocks.waitForChallenge.mockResolvedValue({ ...challenge, challenge_round_id: "round-1" });
render(<App />);
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
await user.click(await screen.findByRole("button", { name: "Refresh status" }));
expect(await screen.findByText("Try again")).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Start another attempt" }));
await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalledWith({ round_id: "round-1", retry_request_id: "request-1" }));
});
it("shows a denied retry and the lecturer's response without a start button", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, challenge_round_id: "round-1" });
mocks.retryRequest.mockResolvedValue({ status: "denied", lecturer_response: "Please contact me" });
render(<App />);
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
expect(await screen.findByText("Request status: denied")).toBeTruthy();
expect(screen.getByText("Please contact me")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Start another attempt" })).toBeNull();
});
it("downloads a round CSV from the authenticated export endpoint", 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", status: "open", timer_minutes: 0, visibility: "private", participants: [] }] });
const fetchMock = vi.fn().mockResolvedValue({ ok: true, blob: async () => new Blob(["header\n"]) });
vi.stubGlobal("fetch", fetchMock);
const revokeUrl = vi.fn();
const NativeURL = URL;
vi.stubGlobal("URL", class extends NativeURL { static createObjectURL = vi.fn().mockReturnValue("blob:test"); static revokeObjectURL = revokeUrl; });
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
try {
render(<App />);
await user.click(await screen.findByRole("button", { name: "Managed rounds" }));
await user.click(await screen.findByRole("button", { name: "Export CSV" }));
await waitFor(() => expect(click).toHaveBeenCalledOnce());
expect(fetchMock).toHaveBeenCalledWith("/api/instructor/rounds/private-1/export.csv", { credentials: "include" });
expect(revokeUrl).toHaveBeenCalledWith("blob:test");
} finally {
click.mockRestore(); vi.unstubAllGlobals();
}
});
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, comprehension_grade: 0 }] },
{ 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", deadline: "2026-01-01T11:00:00Z", is_late: true, total_score: 83, comprehension_grade: 2, comprehension_answer: "Incorrect return", 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" }));
const managedRoundsPanel = await screen.findByRole("region", { name: "Managed rounds" });
expect(managedRoundsPanel.parentElement).toBe(document.body);
await waitFor(() => {
expect(document.body.style.overflow).toBe("hidden");
expect(document.documentElement.style.overflow).toBe("hidden");
});
expect(await screen.findByText("Summary student")).toBeTruthy();
expect(screen.getByText("Comprehension 0/2")).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);
expect(await screen.findByRole("dialog", { name: "private · Attempts" })).toBeTruthy();
expect(screen.getByText("1 loaded attempt")).toBeTruthy();
expect(screen.getByText("Latest score per attempt · 1 scored")).toBeTruthy();
const scoreChart = screen.getByRole("region", { name: "Score distribution" });
expect(within(scoreChart).getByText("80–100").closest("li")?.textContent).toBe("80–1001");
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("Comprehension").parentElement?.textContent).toBe("Comprehension2/2");
expect(screen.getByText("Incorrect return")).toBeTruthy();
expect(screen.getByText("Late")).toBeTruthy();
expect(screen.getByText("Deadline")).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();
await user.click(screen.getByRole("button", { name: "Back to rounds" }));
expect(screen.queryByRole("dialog", { name: "private · Attempts" })).toBeNull();
expect(screen.getByText("Summary student")).toBeTruthy();
expect(document.activeElement).toBe(screen.getByRole("button", { name: "View attempts" }));
await user.click(screen.getByRole("button", { name: "Close open panel" }));
await waitFor(() => {
expect(document.body.style.overflow).toBe("");
expect(document.documentElement.style.overflow).toBe("");
});
});
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("returns from attempts to the open rounds panel without losing editor changes", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });
mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "private-draft", repo_url: null, target_file: null, status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [] }] });
render(<App />);
const editor = await screen.findByRole("textbox", { name: "Code editor" });
await user.clear(editor);
await user.type(editor, "unsaved draft");
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
await user.click(await screen.findByRole("button", { name: "View attempts" }));
expect(await screen.findByRole("dialog", { name: "Challenge round · Attempts" })).toBeTruthy();
await user.keyboard("{Escape}");
expect(screen.queryByRole("dialog")).toBeNull();
expect(screen.getByRole("button", { name: "Managed rounds" }).getAttribute("aria-expanded")).toBe("true");
expect((editor as HTMLTextAreaElement).value).toBe("unsaved draft");
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
expect(screen.queryByRole("region", { name: "Managed rounds" })).toBeNull();
expect((editor as HTMLTextAreaElement).value).toBe("unsaved draft");
});
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("1 loaded attempt · Partial results")).toBeTruthy();
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 });
render(<App />);
const huggingFaceLink = await screen.findByRole("link", { name: /continue with hugging face/i });
const googleLink = await screen.findByRole("link", { name: /continue with google/i });
expect(huggingFaceLink.getAttribute("href")).toBe("/auth/login");
expect(googleLink.getAttribute("href")).toBe("/auth/google/login");
});
it("preserves a direct challenge link through login and joins it after session restore", async () => {
const roundId = "12345678-1234-4234-8234-123456789abc";
window.history.replaceState({}, "", `/?round_id=${roundId}`);
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 });
const loginView = render(<App />);
expect((await screen.findByRole("link", { name: /continue with hugging face/i })).getAttribute("href")).toBe(`/auth/login?round_id=${roundId}`);
expect(screen.getByRole("link", { name: /continue with google/i }).getAttribute("href")).toBe(`/auth/google/login?round_id=${roundId}`);
loginView.unmount();
window.history.replaceState({}, "", `/?round_id=${roundId}`);
mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: false, course_mode: false, approved_repositories: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: false, workspace_id: null });
mocks.startChallenge.mockResolvedValue({ job_id: "direct-round-job", status: "queued" });
type DirectChallenge = typeof challenge & { challenge_round_id: string };
let finishJoin!: (result: DirectChallenge) => void;
mocks.waitForChallenge.mockImplementationOnce(() => new Promise<DirectChallenge>((resolve) => { finishJoin = resolve; }));
render(<App />);
expect(await screen.findByRole("heading", { name: "Opening your shared challenge" })).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Choose your challenge." })).toBeNull();
expect(screen.queryByRole("heading", { name: "Connect a model key" })).toBeNull();
await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalledWith({ round_id: roundId }));
expect(window.location.search).toContain(roundId);
await act(async () => finishJoin({ ...challenge, challenge_round_id: roundId }));
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Connect a model key" })).toBeNull();
await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalledWith({ round_id: roundId }));
expect(window.location.search).toBe("");
});
it("keeps a direct link loading while checking an active workspace", async () => {
const roundId = "12345678-1234-4234-8234-123456789abc";
window.history.replaceState({}, "", `/?round_id=${roundId}`);
let finishLookup!: (result: typeof challenge & { challenge_round_id: string }) => void;
mocks.challenge.mockImplementation(() => new Promise((resolve) => { finishLookup = resolve; }));
render(<App />);
expect(await screen.findByRole("heading", { name: "Opening your shared challenge" })).toBeTruthy();
await waitFor(() => expect(mocks.challenge).toHaveBeenCalledTimes(2));
await act(async () => finishLookup({ ...challenge, challenge_round_id: roundId }));
await waitFor(() => expect(window.location.search).toBe(""));
window.history.replaceState({}, "", "/");
});
it("opens the submitted round summary when revisiting its direct link", async () => {
const roundId = "12345678-1234-4234-8234-123456789abc";
window.history.replaceState({}, "", `/?round_id=${roundId}`);
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null });
mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-1", status: "submitted", round_id: roundId, resumable: false, hints_used: 0, submissions: [{ submission_id: "submission-1", attempt_number: 1, total_score: 90, passed_tests: 3, total_tests: 3 }] }], limit: 50 });
mocks.submittedResult.mockResolvedValue({ round_id: roundId, result: { submission_id: "submission-1", score: 90, test_score: 90, llm_score: null, llm_review_status: "completed", hint_penalty: 0, public_passed: 2, public_total: 2, secret_passed: 1, secret_total: 1, all_passed: true, submission_outcome: "full_fix", tests: [], public_output: "", explanation: "Done", expected_diff: "" } });
render(<App />);
expect(await screen.findByText("SUBMISSION REVIEW")).toBeTruthy();
expect(screen.getByText("90")).toBeTruthy();
expect(screen.getByRole("heading", { name: "Request another attempt" })).toBeTruthy();
expect(mocks.startChallenge).not.toHaveBeenCalled();
window.history.replaceState({}, "", "/");
});
it("shows startup failures instead of an endless loading screen", async () => {
mocks.config.mockRejectedValueOnce(new Error("Server unavailable"));
render(<App />);
expect((await screen.findByRole("alert")).textContent).toContain("Server unavailable");
expect(screen.getByRole("button", { name: "Retry connection" })).toBeTruthy();
});
it("shows the generation stage and percentage while a challenge job is running", async () => {
const user = userEvent.setup();
let finishChallenge!: (result: typeof challenge) => void;
const pendingChallenge = new Promise<typeof challenge>((resolve) => { finishChallenge = resolve; });
mocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: false, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: false, approved_repositories: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });
mocks.startChallenge.mockResolvedValue({ job_id: "challenge-job", status: "queued" });
mocks.waitForChallenge.mockImplementationOnce((_jobId, onProgress) => {
onProgress("running", 50, "Generating bugs and test cases");
return pendingChallenge;
});
render(<App />);
await user.click(await screen.findByRole("button", { name: /start challenge/i }));
const progressbar = await screen.findByRole("progressbar", { name: "Challenge setup progress" });
expect(progressbar.getAttribute("aria-valuenow")).toBe("50");
expect(screen.getByText("Generating bugs and test cases")).toBeTruthy();
await act(async () => {
finishChallenge(challenge);
await pendingChallenge;
});
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
});
it("shows local diagnosis with the target function and suggested diff", async () => {
const user = userEvent.setup();
mocks.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: "instructor", has_model_key: true, workspace_id: "workspace-1", hints_used: 0, submission_count: 0 });
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
await user.click(screen.getByRole("button", { name: /what to fix and where/i }));
expect(await screen.findByText("The function returns the input unchanged.")).toBeTruthy();
expect(screen.getByText("normalize", { exact: true })).toBeTruthy();
expect(screen.getByText(/return value\.strip\(\)/)).toBeTruthy();
expect(mocks.diagnosis).toHaveBeenCalledOnce();
});
it("lets course students request instructor access without exposing challenge creation", async () => {
const 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: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null });
mocks.courseAccess.mockResolvedValueOnce({ role: "student", is_course_admin: false, request: null }).mockResolvedValue({
role: "student", is_course_admin: false,
request: { request_id: "access-request-1", status: "pending", reason: "", requested_at: "2026-01-01T10:00:00Z", reviewed_at: null },
});
render(<App />);
expect(await screen.findByRole("button", { name: /join round/i })).toBeTruthy();
expect(screen.queryByLabelText(/public github repository/i)).toBeNull();
expect(screen.queryByRole("button", { name: /start challenge/i })).toBeNull();
expect(screen.getByRole("button", { name: /request instructor access/i })).toBeTruthy();
expect(screen.queryByRole("button", { name: /publish round/i })).toBeNull();
await user.click(screen.getByRole("button", { name: /request instructor access/i }));
expect(mocks.requestInstructorAccess).toHaveBeenCalledWith("");
expect(await screen.findByText(/request is pending review/i)).toBeTruthy();
});
it.each([
{ courseMode: false, role: "student" },
{ courseMode: true, role: "student" },
{ courseMode: false, role: undefined },
])("prevents creation for non-instructors (course mode: $courseMode, role: $role)", async ({ courseMode, role }) => {
mocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: false, dev_login: false, dev_diagnostics: false, model_key_configured: true, course_mode: courseMode, approved_repositories: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role, has_model_key: true, workspace_id: null });
render(<App />);
const roundInput = await screen.findByLabelText(/join a shared class challenge/i);
expect(screen.queryByLabelText(/public github repository/i)).toBeNull();
expect(screen.queryByRole("slider", { name: /injected bugs/i })).toBeNull();
expect(screen.queryByRole("button", { name: /start challenge/i })).toBeNull();
fireEvent.submit(roundInput.closest("form")!);
expect(mocks.startChallenge).not.toHaveBeenCalled();
});
it("lets a keyless course student join an existing round with AI tools disabled", async () => {
const user = userEvent.setup();
mocks.config.mockResolvedValue({ hf_oauth: false, google_oauth: true, dev_login: false, dev_diagnostics: false, model_key_configured: false, course_mode: true, approved_repositories: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: false, workspace_id: null });
mocks.startChallenge.mockResolvedValue({ job_id: "join-job", status: "queued" });
mocks.waitForChallenge.mockResolvedValue(challenge);
render(<App />);
expect(await screen.findByRole("heading", { name: "Connect a model key" })).toBeTruthy();
expect(screen.getByText(/without a key, access is very limited/i)).toBeTruthy();
await user.click(screen.getByRole("button", { name: /continue with limited access/i }));
expect(await screen.findByRole("button", { name: /join round/i })).toBeTruthy();
const limitedNoticeTitle = screen.getByText("Limited access without a model key");
expect(limitedNoticeTitle.closest(".keyless-notice")?.classList.contains("global-notice")).toBe(false);
expect(screen.getByText(/you can join existing challenges, run tests and submit/i)).toBeTruthy();
expect(screen.queryByLabelText(/public github repository/i)).toBeNull();
expect(screen.getByText(/challenge creation, ai chat\/hints, and ai review are disabled/i)).toBeTruthy();
await user.click(screen.getByRole("button", { name: /connect model key/i }));
expect(await screen.findByLabelText("OpenAI API key")).toBeTruthy();
expect(screen.getByPlaceholderText("Paste round code")).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Cancel" }));
cleanup();
render(<App />);
expect(await screen.findByRole("button", { name: /join round/i })).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Connect a model key" })).toBeNull();
expect(screen.getByText("Limited access without a model key")).toBeTruthy();
await user.type(screen.getByPlaceholderText("Paste round code"), "round-123");
await user.click(screen.getByRole("button", { name: /join round/i }));
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Open AI chat" }));
expect((screen.getByPlaceholderText(/ask about an unexpected result/i) as HTMLTextAreaElement).disabled).toBe(true);
expect(screen.getByText("AI chat and hints are unavailable without a model API key.")).toBeTruthy();
});
it("allows connecting a model key later after choosing keyless access", async () => {
const user = userEvent.setup();
mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: false, dev_login: false, dev_diagnostics: false, model_key_configured: false, course_mode: false, approved_repositories: [] });
mocks.session
.mockResolvedValueOnce({ authenticated: true, identity, role: "student", has_model_key: false, workspace_id: null })
.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null });
mocks.saveModelKey.mockResolvedValue({ status: "saved" });
render(<App />);
await user.click(await screen.findByRole("button", { name: /continue with limited access/i }));
await user.click(await screen.findByRole("button", { name: /connect model key/i }));
await user.type(screen.getByLabelText("OpenAI API key"), "valid-key");
await user.click(screen.getByRole("button", { name: /validate and connect/i }));
expect(mocks.saveModelKey).toHaveBeenCalledWith("valid-key");
expect(await screen.findByRole("button", { name: /join round/i })).toBeTruthy();
expect(screen.queryByLabelText(/public github repository/i)).toBeNull();
});
it("keeps keyless access active when the entered model key is rejected", async () => {
const user = userEvent.setup();
mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: false, dev_login: false, dev_diagnostics: false, model_key_configured: false, course_mode: false, approved_repositories: [] });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: false, workspace_id: null });
mocks.saveModelKey.mockRejectedValue(new Error("Invalid model API key"));
render(<App />);
await user.click(await screen.findByRole("button", { name: /continue with limited access/i }));
await user.click(screen.getByRole("button", { name: /connect model key/i }));
await user.type(screen.getByLabelText("OpenAI API key"), "invalid-key");
await user.click(screen.getByRole("button", { name: /validate and connect/i }));
expect((await screen.findByRole("alert")).textContent).toContain("Invalid model API key");
expect(screen.getByRole("button", { name: /join round/i })).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Enter the lab" })).toBeNull();
});
it("lets instructors manage rounds and choose only approved repositories", async () => {
const 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, hints_per_student: 3, chat_messages_per_student: 20, visibility: "private", participants: [{ student_name: "Learner", status: "in_progress", last_activity: null, hints_used: 1, submission_count: 0, reflection_saved: false, latest_score: null, passed_tests: null, total_tests: null, submission_outcome: null }] }] });
mocks.courseAccess.mockResolvedValue({ role: "instructor", is_course_admin: true, request: null });
mocks.courseAccessRequests.mockResolvedValue({ requests: [{ request_id: "request-1", auth_provider: "google", provider_user_id: "student-1", display_name: "New instructor", reason: "I teach this course", requested_at: "2026-01-01T10:00:00Z" }] });
render(<App />);
expect(await screen.findByRole("button", { name: "Managed rounds" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Open public challenges" })).toBeNull();
expect((await screen.findByRole("button", { name: "Instructor access requests" })).textContent).toContain("1");
const repositoryInput = await screen.findByRole("textbox", { name: /public github repository/i });
expect((repositoryInput as HTMLInputElement).value).toBe("https://github.com/acme/approved");
await user.clear(repositoryInput);
await user.type(repositoryInput, "https://github.com/acme/unlisted");
expect((repositoryInput as HTMLInputElement).value).toBe("https://github.com/acme/unlisted");
expect(screen.getByRole("button", { name: "Managed rounds" }).getAttribute("aria-expanded")).toBe("false");
expect(screen.queryByText("Learner")).toBeNull();
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
expect(screen.getByRole("button", { name: "Managed rounds" }).getAttribute("aria-expanded")).toBe("true");
expect(await screen.findByText("Learner")).toBeTruthy();
expect(screen.getByText("round-prepared", { exact: true })).toBeTruthy();
expect(screen.getByRole("button", { name: "Copy share code" })).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Edit settings" }));
const hintLimit = screen.getByRole("spinbutton", { name: "Hints per student" }) as HTMLInputElement;
expect(hintLimit.value).toBe("3");
expect(hintLimit.min).toBe("0");
expect(hintLimit.max).toBe("5");
fireEvent.change(hintLimit, { target: { value: "7" } });
expect(hintLimit.value).toBe("5");
await user.clear(hintLimit);
await user.type(hintLimit, "0");
await user.click(screen.getByRole("switch", { name: "round-prepared timed challenge" }));
await user.click(screen.getByRole("button", { name: "Save settings" }));
await waitFor(() => expect(mocks.updateRoundSettings).toHaveBeenCalledWith("round-prepared", {
time_limit_enabled: false,
timer_minutes: 30,
hints_per_student: 0,
visibility: "private",
}));
expect(screen.getByText(/0 hints\/student/)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Open round" }));
expect(mocks.openRound).toHaveBeenCalledWith("round-prepared");
await user.click(screen.getByRole("button", { name: "Instructor access requests" }));
expect(await screen.findByText("New instructor")).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Approve" }));
expect(mocks.reviewCourseAccessRequest).toHaveBeenCalledWith("request-1", "approved");
}, 10000);
it("copies a direct link for an open managed challenge round", async () => {
const user = userEvent.setup();
const roundId = "12345678-1234-4234-8234-123456789abc";
const previousClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });
mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: roundId, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [] }] });
try {
render(<App />);
await user.click(await screen.findByRole("button", { name: "Managed rounds" }));
const attemptsButton = await screen.findByRole("button", { name: "View attempts" });
const footerActions = attemptsButton.closest(".managed-round-footer-actions");
expect(footerActions?.children).toHaveLength(3);
expect(within(footerActions as HTMLElement).getByRole("button", { name: "Export CSV" })).toBeTruthy();
expect(within(footerActions as HTMLElement).getByRole("button", { name: "Close round" })).toBeTruthy();
await user.click(await screen.findByRole("button", { name: "Copy challenge link" }));
const expectedUrl = new URL("/", window.location.origin);
expectedUrl.searchParams.set("round_id", roundId);
expect(writeText).toHaveBeenCalledWith(expectedUrl.toString());
expect(await screen.findByRole("button", { name: "Challenge link copied" })).toBeTruthy();
} finally {
if (previousClipboard) Object.defineProperty(navigator, "clipboard", previousClipboard);
else Reflect.deleteProperty(navigator, "clipboard");
}
});
it("closes managed rounds with its close button or an outside click but leaves chat open", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });
mocks.challenge.mockResolvedValue(challenge);
mocks.instructorDashboard.mockResolvedValue({ rounds: [{ round_id: "private-close", repo_url: null, target_file: null, status: "open", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", participants: [] }] });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Managed rounds" }));
expect(await screen.findByRole("region", { name: "Managed rounds" })).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Close open panel" }));
expect(screen.queryByRole("region", { name: "Managed rounds" })).toBeNull();
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
await user.click(screen.getByRole("button", { name: "Close managed rounds" }));
expect(screen.queryByRole("region", { name: "Managed rounds" })).toBeNull();
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
await user.click(screen.getByRole("button", { name: "Open AI chat" }));
expect(screen.queryByRole("region", { name: "Managed rounds" })).toBeNull();
expect(screen.getByRole("dialog", { name: "AI debugging chat" })).toBeTruthy();
await user.click(document.body);
expect(screen.getByRole("dialog", { name: "AI debugging chat" })).toBeTruthy();
});
it("loads a safe summary of the student's challenge history", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
expect(await screen.findByRole("heading", { name: "Challenge history" })).toBeTruthy();
expect(screen.getAllByText("demo")).toHaveLength(2);
expect(screen.getByText("90/100")).toBeTruthy();
expect(mocks.history).toHaveBeenCalledWith();
expect(screen.queryByRole("button", { name: "Open public challenges" })).toBeNull();
});
it("preloads available lists and opens their panels without refetching", 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.history.mockResolvedValue({ attempts: [], limit: 50 });
mocks.instructorDashboard.mockResolvedValue({ rounds: [] });
mocks.courseAccess.mockResolvedValue({ role: "instructor", is_course_admin: true, request: null });
mocks.courseAccessRequests.mockResolvedValue({ requests: [] });
render(<App />);
await waitFor(() => {
expect(mocks.history).toHaveBeenCalledTimes(1);
expect(mocks.instructorDashboard).toHaveBeenCalledTimes(1);
expect(mocks.courseAccess).toHaveBeenCalledTimes(1);
expect(mocks.courseAccessRequests).toHaveBeenCalledTimes(1);
});
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
expect(await screen.findByRole("heading", { name: "Challenge history" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Refresh challenge history" }).textContent).toBe("");
expect(screen.getByRole("button", { name: "Refresh challenge history" }).parentElement).toBe(screen.getByRole("button", { name: "Close history" }).parentElement);
expect(screen.queryByRole("button", { name: "Open public challenges" })).toBeNull();
await user.click(screen.getByRole("button", { name: "Managed rounds" }));
expect(await screen.findByRole("region", { name: "Managed rounds" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Refresh managed rounds" }).textContent).toBe("");
expect(screen.getByRole("button", { name: "Refresh managed rounds" }).parentElement).toBe(screen.getByRole("button", { name: "Close managed rounds" }).parentElement);
await user.click(screen.getByRole("button", { name: "Instructor access requests" }));
expect(await screen.findByRole("heading", { name: "Instructor requests" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Refresh instructor requests" }).textContent).toBe("");
expect(screen.getByRole("button", { name: "Refresh instructor requests" }).parentElement).toBe(screen.getByRole("button", { name: "Close instructor requests" }).parentElement);
expect(mocks.history).toHaveBeenCalledTimes(2);
expect(mocks.instructorDashboard).toHaveBeenCalledTimes(1);
expect(mocks.courseAccess).toHaveBeenCalledTimes(1);
expect(mocks.courseAccessRequests).toHaveBeenCalledTimes(1);
});
it("shows a continue card for an unfinished challenge on the setup page", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValueOnce({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null, hints_used: 0, submission_count: 0 });
mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-open", started_at: null, updated_at: null, status: "in_progress", hints_used: 2, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", round_id: null, submission_count: 0, reflection_saved: false, resumable: true, submissions: [] }], limit: 50 });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Continue challenge" }));
expect(mocks.resume).toHaveBeenCalledWith("attempt-open");
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
});
it("resumes an unfinished attempt from history", async () => {
const user = userEvent.setup();
mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-open", started_at: null, updated_at: null, status: "in_progress", hints_used: 2, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", round_id: null, submission_count: 0, reflection_saved: false, resumable: true, submissions: [] }], limit: 50 });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
await user.click(await screen.findByRole("button", { name: "Resume attempt" }));
expect(mocks.resume).toHaveBeenCalledWith("attempt-open");
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
});
it("saves editor changes when going back and restores them with the last test result", async () => {
const user = userEvent.setup();
const editedCode = `${challenge.code}# work in progress`;
const lastTestResult = { passed: 1, total: 2, score: 40, output: "Test 1: PASS", all_passed: false, per_test: [] };
mocks.history.mockResolvedValue({ attempts: [], limit: 50 });
mocks.challenge
.mockResolvedValueOnce(challenge)
.mockResolvedValueOnce({ ...challenge, code: editedCode, last_public_test_result: lastTestResult });
mocks.saveFile.mockResolvedValue({ status: "saved", storage_warning: "" });
render(<App />);
const editor = await screen.findByRole("textbox", { name: "Code editor" });
await user.type(editor, "# work in progress");
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
expect(await screen.findByText(/1 of 2 passed/)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Back to challenges" }));
await waitFor(() => expect(mocks.saveFile).toHaveBeenCalledWith("src/demo.py", editedCode));
await user.click(await screen.findByRole("button", { name: "Continue challenge" }));
expect(mocks.resume).toHaveBeenCalledWith("workspace-1");
expect(await screen.findByText("1/2", { selector: ".heading-stats span" })).toBeTruthy();
expect((await screen.findByRole("textbox", { name: "Code editor" }) as HTMLTextAreaElement).value).toBe(editedCode);
});
it("asks before resuming when editor changes are unsaved", async () => {
const user = userEvent.setup();
const confirm = vi.spyOn(window, "confirm").mockReturnValue(false);
mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-open", started_at: null, updated_at: null, status: "in_progress", hints_used: 0, repo_url: "https://github.com/acme/demo", target_file: "src/demo.py", round_id: null, submission_count: 0, reflection_saved: false, resumable: true, submissions: [] }], limit: 50 });
render(<App />);
await user.type(await screen.findByLabelText("Code editor"), "# unsaved");
await user.click(screen.getByRole("button", { name: "Challenge history" }));
await user.click(await screen.findByRole("button", { name: "Resume attempt" }));
expect(confirm).toHaveBeenCalledWith("You have unsaved edits. Resume another attempt and discard them?");
expect(mocks.resume).not.toHaveBeenCalled();
expect((screen.getByLabelText("Code editor") as HTMLTextAreaElement).value).toContain("# unsaved");
confirm.mockRestore();
});
it("disables reset when a non-target file is selected", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, files: ["src/demo.py", "src/other.py"] });
mocks.readFile.mockResolvedValue({ path: "src/other.py", content: "def other(): return 1\n" });
render(<App />);
await user.selectOptions(await screen.findByRole("combobox", { name: "Choose Python file" }), "src/other.py");
await waitFor(() => expect((screen.getByRole("button", { name: "Reset" }) as HTMLButtonElement).disabled).toBe(true));
expect(mocks.reset).not.toHaveBeenCalled();
});
it("clears old test results and viewers when resuming another challenge", async () => {
const user = userEvent.setup();
const nextChallenge = {
...challenge,
workspace_id: "workspace-2",
repo_url: "https://github.com/acme/other-demo",
target_file: "src/other.py",
file_path: "src/other.py",
code: "def other(): return 1\n",
};
mocks.history.mockResolvedValue({ attempts: [{ workspace_id: "attempt-open", started_at: null, updated_at: null, status: "in_progress", hints_used: 0, repo_url: nextChallenge.repo_url, target_file: nextChallenge.target_file, round_id: null, submission_count: 0, reflection_saved: false, resumable: true, submissions: [] }], limit: 50 });
mocks.resume.mockResolvedValueOnce(nextChallenge);
render(<App />);
await screen.findByRole("heading", { name: "src/demo.py" });
await user.type(screen.getByPlaceholderText(/note anything you could not verify/i), "Old attempt note");
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
expect(await screen.findByText(/1 of 2 passed/)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Challenge history" }));
mocks.challenge.mockResolvedValueOnce(nextChallenge);
await user.click(await screen.findByRole("button", { name: "Resume attempt" }));
expect(await screen.findByRole("heading", { name: "src/other.py" })).toBeTruthy();
expect(screen.queryByText(/1 of 2 passed/)).toBeNull();
expect(screen.queryByLabelText("Public tests source")).toBeNull();
expect(screen.getByText("Tests not run")).toBeTruthy();
expect((screen.getByPlaceholderText(/note anything you could not verify/i) as HTMLTextAreaElement).value).toBe("");
});
it("hides solution and round controls for an instructor who does not own the round", async () => {
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1", hints_used: 0, submission_count: 0 });
mocks.challenge.mockResolvedValue({
...challenge,
challenge_round_id: "12345678-1234-4234-8234-123456789abc",
can_manage_round: false,
published_round: {
round_id: "12345678-1234-4234-8234-123456789abc",
artifact_hash: "artifact",
tests_hash: "tests",
timer_minutes: 30,
chat_messages_per_student: 5,
visibility: "private",
status: "prepared",
},
});
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
expect(screen.queryByRole("button", { name: /what to fix and where/i })).toBeNull();
expect(screen.queryByRole("button", { name: "Publish challenge" })).toBeNull();
expect(screen.queryByRole("button", { name: "Open round" })).toBeNull();
expect(screen.queryByRole("button", { name: "Close round" })).toBeNull();
});
it("shows public tests in a terminal-style function input expected actual view", async () => {
const user = userEvent.setup();
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
expect((await screen.findAllByText("INPUT")).length).toBeGreaterThan(0);
expect(screen.getAllByText("EXPECTED").length).toBeGreaterThan(0);
expect(screen.getAllByText("ACTUAL").length).toBeGreaterThan(0);
expect(screen.getAllByRole("button", { name: /jump to target/i }).length).toBeGreaterThan(0);
expect(screen.queryByText(/str len=/i)).toBeNull();
});
it("loads a challenge, runs tests, requests a hint and shows submission results", async () => {
const user = userEvent.setup();
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
expect(screen.queryByRole("button", { name: /what to fix and where/i })).toBeNull();
expect(screen.getByText("15:00")).toBeTruthy();
await user.click(await screen.findByRole("button", { name: "Undo" }));
expect(mocks.editor.trigger).toHaveBeenCalledWith("toolbar", "undo", null);
await user.click(screen.getByRole("button", { name: "Redo" }));
expect(mocks.editor.trigger).toHaveBeenCalledWith("toolbar", "redo", null);
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
expect(await screen.findByText("Test 2")).toBeTruthy();
expect(screen.queryByText(/str len=/i)).toBeNull();
expect(mocks.runTests).toHaveBeenCalledWith("src/demo.py", challenge.code);
await user.click(screen.getByRole("button", { name: /view changes/i }));
expect(await screen.findByText(/\+value = 2/)).toBeTruthy();
expect(mocks.diff).toHaveBeenCalledWith("src/demo.py", challenge.code);
await user.click(screen.getByRole("button", { name: "Open AI chat" }));
await user.type(screen.getByPlaceholderText(/ask about an unexpected result/i), "Why does it fail?");
await user.click(screen.getByRole("button", { name: /send question/i }));
expect(await screen.findByText("Check the return branch.")).toBeTruthy();
expect(screen.getAllByText("1/5 hints")).toHaveLength(2);
await user.click(screen.getByRole("button", { name: /submit fix/i }));
const expectedFix = await screen.findByText("Expected changes");
expect(screen.getByText("Test score")).toBeTruthy();
expect(screen.getByText("LLM score")).toBeTruthy();
expect(screen.getAllByText("80/100")).toHaveLength(2);
const secretSummary = screen.getByText("Secret tests").closest(".secret-summary");
expect(secretSummary?.textContent).toContain("0 / 1");
expect(secretSummary?.textContent).toContain("Individual results are hidden");
expect(screen.getByRole("heading", { name: "Hints used" })).toBeTruthy();
expect(screen.getByText("Hint details are unavailable for this submission.")).toBeTruthy();
await user.click(expectedFix);
expect(await screen.findAllByText(/return value\.strip/)).toHaveLength(1);
expect(screen.getByText("A partial fix.")).toBeTruthy();
expect(mocks.submit).toHaveBeenCalledWith("src/demo.py", challenge.code, {
confidence: 3,
known_limitations: "",
});
}, 10000);
it("shows the question after submission and retries grading without changing the code score", async () => {
const user = userEvent.setup();
mocks.comprehension.mockResolvedValue({ status: "pending", question: "Why did it fail?" });
mocks.gradeComprehension.mockRejectedValueOnce(new Error("Grading unavailable; retry"))
.mockResolvedValueOnce({ status: "completed", question: "Why did it fail?", answer: "Wrong return", grade: 1 });
render(<App />);
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
expect(await screen.findByText("Why did it fail?")).toBeTruthy();
await user.type(screen.getByLabelText("Your answer"), "Wrong return");
await user.click(screen.getByRole("button", { name: "Submit answer" }));
expect(await screen.findByText("Grading unavailable; retry")).toBeTruthy();
expect((screen.getByLabelText("Your answer") as HTMLTextAreaElement).value).toBe("Wrong return");
await user.click(screen.getByRole("button", { name: "Submit answer" }));
expect(await screen.findByText("Grade: 1/2")).toBeTruthy();
expect(screen.getAllByText("80/100")).toHaveLength(2);
expect(mocks.gradeComprehension).toHaveBeenLastCalledWith("submission-1", "Wrong return");
});
it("does not show comprehension in student history", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByRole("button", { name: "Challenge history" }));
expect(await screen.findByText("Submission 1")).toBeTruthy();
expect(screen.queryByRole("button", { name: /comprehension/i })).toBeNull();
expect(screen.queryByRole("region", { name: "Comprehension question" })).toBeNull();
expect(mocks.comprehension).not.toHaveBeenCalled();
});
it("restores a pending answer after reconnecting and retries grading", async () => {
const user = userEvent.setup();
mocks.comprehension.mockResolvedValue({ status: "pending", question: "Why?", answer: "Saved draft", grade: null });
mocks.gradeComprehension.mockRejectedValueOnce(new Error("Answer changed; reload and retry"))
.mockResolvedValueOnce({ status: "completed", question: "Why?", answer: "Updated draft", grade: 2 });
render(<App />);
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
expect((await screen.findByLabelText("Your answer") as HTMLTextAreaElement).value).toBe("Saved draft");
await user.click(screen.getByRole("button", { name: "Submit answer" }));
expect(await screen.findByText("Answer changed; reload and retry")).toBeTruthy();
mocks.comprehension.mockResolvedValue({ status: "pending", question: "Why?", answer: "Updated draft", grade: null });
await user.click(screen.getByRole("button", { name: "Reload saved answer" }));
await waitFor(() => expect((screen.getByLabelText("Your answer") as HTMLTextAreaElement).value).toBe("Updated draft"));
await user.click(screen.getByRole("button", { name: "Submit answer" }));
expect(await screen.findByText("Grade: 2/2")).toBeTruthy();
expect(mocks.gradeComprehension).toHaveBeenLastCalledWith("submission-1", "Updated draft");
});
it("applies a later LLM grade to a keyless submission after connecting a key", async () => {
const user = userEvent.setup();
mocks.config.mockResolvedValue({ hf_oauth: true, google_oauth: false, dev_login: false, dev_diagnostics: false, model_key_configured: false, course_mode: false, approved_repositories: [] });
mocks.session
.mockResolvedValueOnce({ authenticated: true, identity, role: "student", has_model_key: false, workspace_id: "workspace-1" })
.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1" });
mocks.saveModelKey.mockResolvedValue({ status: "saved" });
render(<App />);
await user.click(await screen.findByRole("button", { name: /continue with limited access/i }));
await user.click(await screen.findByRole("button", { name: "Open AI chat" }));
expect(await screen.findByPlaceholderText(/ask about an unexpected result/i)).toBeTruthy();
mocks.waitForJob.mockResolvedValueOnce({
submission_id: "submission-1", score: 78, test_score: 80, llm_score: null,
llm_review_status: "not_requested", hint_penalty: 2, passed: 1, total_tests: 2,
public_passed: 1, public_total: 1, secret_passed: 0, secret_total: 1,
all_passed: false, tests: [{ num: 1, status: "PASS" }], public_output: "PASS",
explanation: "A partial fix.", submission_outcome: "partial_fix", expected_diff: "",
supabase_saved: true, storage_warning: "", submission_count: 1,
});
await user.click(await screen.findByRole("button", { name: /submit fix/i }));
expect(await screen.findByText("Not run")).toBeTruthy();
await user.click(screen.getByRole("button", { name: /connect model key/i }));
await user.type(screen.getByLabelText("OpenAI API key"), "valid-key");
await user.click(screen.getByRole("button", { name: /validate and connect/i }));
expect(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();
expect(screen.getByText("The fix is focused and correct.")).toBeTruthy();
expect(screen.getByText("89", { exact: true })).toBeTruthy();
}, 10000);
it("sends chat with Enter and inserts a newline with Shift+Enter", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(await screen.findByRole("button", { name: "Open AI chat" }));
const input = await screen.findByPlaceholderText(/ask about an unexpected result/i);
await user.click(input);
await user.keyboard("{Enter}");
expect(mocks.hint).not.toHaveBeenCalled();
await user.type(input, "First line");
await user.keyboard("{Shift>}{Enter}{/Shift}");
await user.type(input, "Second line");
expect((input as HTMLTextAreaElement).value).toBe("First line\nSecond line");
expect(mocks.hint).not.toHaveBeenCalled();
await user.keyboard("{Enter}");
await waitFor(() => expect(mocks.hint).toHaveBeenCalledWith("First line\nSecond line", "src/demo.py", challenge.code));
expect(mocks.hint).toHaveBeenCalledOnce();
expect(await screen.findByText("Check the return branch.")).toBeTruthy();
expect((input as HTMLTextAreaElement).value).toBe("");
}, 10000);
it("allows chat after the hint allowance is exhausted", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, hints_used: 0, hints_per_student: 0, chat_messages_used: 5, chat_messages_per_student: 5 });
mocks.hint.mockResolvedValue({ response: "Let's discuss your approach.", gave_hint: false, hints_used: 0, penalty: 0, chat_history: [] });
render(<App />);
const launcher = await screen.findByRole("button", { name: "Open AI chat" });
expect(launcher.textContent).toContain("0/0");
await user.click(launcher);
expect(await screen.findByText("Hint allowance exhausted. You can still chat.")).toBeTruthy();
const input = screen.getByPlaceholderText(/ask about an unexpected result/i);
expect((input as HTMLTextAreaElement).disabled).toBe(false);
await user.type(input, "Can we discuss this?");
await user.click(screen.getByRole("button", { name: "Send question" }));
expect(mocks.hint).toHaveBeenCalledWith("Can we discuss this?", "src/demo.py", challenge.code);
expect(await screen.findByText("Let's discuss your approach.")).toBeTruthy();
expect(screen.getAllByText("0/0 hints")).toHaveLength(2);
});
it("restores the allowance from the session when the challenge omits it", async () => {
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: "workspace-1", hints_used: 2, hints_per_student: 3 });
mocks.challenge.mockResolvedValue({ ...challenge, hints_used: 2 });
render(<App />);
expect(await screen.findByText("2/3 hints")).toBeTruthy();
});
it("keeps the allowance and count after a reply that is not a hint", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, hints_used: 1, hints_per_student: 2 });
mocks.hint.mockResolvedValue({ response: "What have you tried?", gave_hint: false, hints_used: 1, penalty: 2, chat_history: [] });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Open AI chat" }));
await user.type(screen.getByPlaceholderText(/ask about an unexpected result/i), "Can we discuss this?");
await user.click(screen.getByRole("button", { name: "Send question" }));
expect(await screen.findByText("What have you tried?")).toBeTruthy();
expect(screen.getAllByText("1/2 hints")).toHaveLength(2);
expect(screen.queryByText(/hint allowance exhausted/i)).toBeNull();
});
it("preserves unsaved edits when logout is cancelled", async () => {
const user = userEvent.setup();
const confirm = vi.spyOn(window, "confirm").mockReturnValue(false);
try {
render(<App />);
const editor = await screen.findByLabelText("Code editor");
await user.clear(editor);
await user.type(editor, "value = 1");
await user.click(screen.getByRole("button", { name: /sign out/i }));
expect(confirm).toHaveBeenCalledOnce();
expect(confirm).toHaveBeenCalledWith("You have unsaved edits. Sign out and discard them?");
expect(mocks.logout).not.toHaveBeenCalled();
expect(screen.getByRole("heading", { name: "src/demo.py" })).toBeTruthy();
expect((screen.getByLabelText("Code editor") as HTMLTextAreaElement).value).toBe("value = 1");
expect(screen.getByText("Unsaved changes")).toBeTruthy();
expect(screen.queryByRole("heading", { name: "Enter the lab" })).toBeNull();
} finally {
confirm.mockRestore();
}
}, 10000);
it("blocks duplicate hint clicks and Enter while a deferred request is busy", async () => {
const user = userEvent.setup();
const response = { response: "Check the branch.", gave_hint: true, hints_used: 1, penalty: 2, chat_history: [] };
let resolveHint!: (value: typeof response) => void;
const pendingHint = new Promise<typeof response>((resolve) => { resolveHint = resolve; });
mocks.hint.mockReturnValueOnce(pendingHint);
render(<App />);
await user.click(await screen.findByRole("button", { name: "Open AI chat" }));
const input = await screen.findByPlaceholderText(/ask about an unexpected result/i);
const send = screen.getByRole("button", { name: /send question/i });
await user.type(input, "Why?");
await user.click(send);
expect(mocks.hint).toHaveBeenCalledOnce();
expect(mocks.hint).toHaveBeenCalledWith("Why?", "src/demo.py", challenge.code);
expect((input as HTMLTextAreaElement).disabled).toBe(true);
expect((send as HTMLButtonElement).disabled).toBe(true);
await user.dblClick(send);
await user.click(input);
await user.keyboard("{Enter}{Enter}");
expect(mocks.hint).toHaveBeenCalledOnce();
expect(screen.queryByText(response.response)).toBeNull();
await act(async () => {
resolveHint(response);
await pendingHint;
});
expect(await screen.findByText(response.response)).toBeTruthy();
expect(screen.getAllByText("1/5 hints")).toHaveLength(2);
expect((input as HTMLTextAreaElement).disabled).toBe(false);
expect(mocks.hint).toHaveBeenCalledOnce();
}, 10000);
it("clears a save storage warning after editing and a successful retry", async () => {
const user = userEvent.setup();
const warning = "Backup storage unavailable.";
mocks.saveFile
.mockResolvedValueOnce({ status: "saved", storage_warning: warning })
.mockResolvedValueOnce({ status: "saved" });
render(<App />);
const editor = await screen.findByLabelText("Code editor");
await user.clear(editor);
await user.type(editor, "value = 1");
const save = screen.getByRole("button", { name: "Save" });
await user.click(save);
expect(await screen.findByText(warning)).toBeTruthy();
expect(mocks.saveFile).toHaveBeenCalledOnce();
expect(mocks.saveFile).toHaveBeenLastCalledWith("src/demo.py", "value = 1");
expect((save as HTMLButtonElement).disabled).toBe(true);
await user.clear(editor);
await user.type(editor, "value = 2");
expect(screen.getByText(warning)).toBeTruthy();
expect(screen.getByText("Unsaved changes")).toBeTruthy();
expect((save as HTMLButtonElement).disabled).toBe(false);
await user.click(save);
await waitFor(() => expect(mocks.saveFile).toHaveBeenCalledTimes(2));
expect(mocks.saveFile).toHaveBeenLastCalledWith("src/demo.py", "value = 2");
await waitFor(() => expect(screen.queryByText(warning)).toBeNull());
expect((editor as HTMLTextAreaElement).value).toBe("value = 2");
expect(screen.queryByText("Unsaved changes")).toBeNull();
expect((save as HTMLButtonElement).disabled).toBe(true);
}, 10000);
it("reruns public tests with each new editor version", async () => {
const user = userEvent.setup();
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
const editor = screen.getByLabelText("Code editor");
await user.clear(editor);
await user.type(editor, "value = 1");
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
await waitFor(() => expect(mocks.runTests).toHaveBeenLastCalledWith("src/demo.py", "value = 1"));
await user.clear(editor);
await user.type(editor, "value = 2");
await user.click(screen.getByRole("button", { name: /^public tests$/i }));
await waitFor(() => expect(mocks.runTests).toHaveBeenLastCalledWith("src/demo.py", "value = 2"));
}, 10000);
it("collects a pre-submit self-assessment and saves one post-submit reflection", async () => {
const user = userEvent.setup();
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
await user.type(screen.getByLabelText("Known limitations"), "I did not test empty input.");
await user.click(screen.getByRole("button", { name: /submit fix/i }));
expect(await screen.findByRole("heading", { name: "What did you learn?" })).toBeTruthy();
expect(mocks.submit).toHaveBeenCalledWith("src/demo.py", challenge.code, {
confidence: 3,
known_limitations: "I did not test empty input.",
});
await user.type(screen.getByLabelText("What was the core bug?"), "The function returned an unchanged value.");
await user.click(screen.getByRole("button", { name: /save reflection/i }));
await waitFor(() => expect(mocks.saveReflection).toHaveBeenCalledWith("submission-1", {
understanding_rating: 3,
independent_fix_rating: 3,
core_bug_explanation: "The function returned an unchanged value.",
}));
expect(await screen.findByRole("heading", { name: "Reflection saved" })).toBeTruthy();
}, 10000);
it("restores the finalized result instead of reopening the challenge after refresh", async () => {
mocks.session.mockResolvedValue({
authenticated: true,
identity,
has_model_key: true,
workspace_id: "workspace-1",
submission_locked: true,
reflection_saved: true,
last_submission_result: {
submission_id: "submission-1",
score: 78,
test_score: 80,
llm_score: 80,
hint_penalty: 2,
hint_history: [{ question: "Why is it failing?", response: "Check the loop boundary.", hint_summary: "Loop boundary" }],
passed: 1,
total_tests: 2,
public_passed: 1,
public_total: 1,
secret_passed: 0,
secret_total: 1,
all_passed: false,
tests: [],
public_output: "",
explanation: "A partial fix.",
submission_outcome: "partial_fix",
expected_diff: "",
supabase_saved: true,
storage_warning: "",
submission_count: 1,
},
});
render(<App />);
expect(await screen.findByRole("heading", { name: "Reflection saved" })).toBeTruthy();
expect(screen.getByText("78")).toBeTruthy();
expect(screen.getByRole("heading", { name: "Hints used" })).toBeTruthy();
expect(screen.getByRole("heading", { name: "Hint 1" })).toBeTruthy();
expect(screen.getByText("Check the loop boundary.")).toBeTruthy();
expect(mocks.challenge).not.toHaveBeenCalled();
});
it("returns to sign-in with a clear message when the server session expires", async () => {
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
act(() => window.dispatchEvent(new Event("app:session-expired")));
expect(await screen.findByRole("heading", { name: "Enter the lab" })).toBeTruthy();
expect(screen.getByText(/your session expired/i)).toBeTruthy();
});
it("shows when a hint confirmation is pending", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, confirmation_pending: true });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Open AI chat" }));
expect(await screen.findByText("Confirmation needed: reply yes or no")).toBeTruthy();
});
it("resynchronizes the timer with the server when the tab becomes visible", async () => {
const timerChallenge = { ...challenge, timer_remaining: 420 };
mocks.challenge.mockResolvedValueOnce(challenge).mockResolvedValue(timerChallenge);
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
await waitFor(() => expect(mocks.challenge).toHaveBeenCalledTimes(1));
Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
act(() => document.dispatchEvent(new Event("visibilitychange")));
await waitFor(() => expect(mocks.challenge).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.getByLabelText("7 minutes 0 seconds remaining")).toBeTruthy());
});
it("shows an expired timer when a challenge loads with zero seconds remaining", async () => {
const user = userEvent.setup();
mocks.challenge.mockResolvedValue({ ...challenge, timer_remaining: 0 });
mocks.waitForJob.mockResolvedValue({ submission_id: "submission-1", score: 78, test_score: 80, llm_score: null, hint_penalty: 2, passed: 1, total_tests: 2, public_passed: 1, public_total: 1, secret_passed: 0, secret_total: 1, all_passed: false, tests: [], public_output: "", explanation: "", submission_outcome: "partial_fix", expected_diff: "", supabase_saved: true, storage_warning: "", submission_count: 1, submitted_at: "2026-01-01T11:05:12Z", deadline: "2026-01-01T11:00:00Z", is_late: true });
render(<App />);
expect(await screen.findByLabelText("0 minutes 0 seconds remaining")).toBeTruthy();
expect(screen.getByText(/you can still submit/i)).toBeTruthy();
await user.click(screen.getByRole("button", { name: "Submit fix" }));
expect(await screen.findByText(/Late submission/)).toBeTruthy();
expect(mocks.submit).toHaveBeenCalledOnce();
});
it("lets instructors create challenges untimed and without debug mode", async () => {
const user = userEvent.setup();
mocks.session
.mockResolvedValueOnce({ authenticated: false })
.mockResolvedValueOnce({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: null });
mocks.startChallenge.mockResolvedValue({ job_id: "job-1", status: "queued" });
mocks.waitForChallenge.mockResolvedValue(challenge);
render(<App />);
await user.type(await screen.findByLabelText("Display name"), "Alice");
await user.click(screen.getByRole("button", { name: /continue/i }));
await user.click(screen.getByRole("button", { name: /start challenge/i }));
await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalled());
expect(mocks.startChallenge).toHaveBeenCalledWith(expect.objectContaining({ timer_minutes: 0, debug_mode: false }));
expect(screen.queryByRole("switch", { name: "Timed challenge" })).toBeNull();
expect(screen.queryByRole("switch", { name: /debug mode/i })).toBeNull();
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
});
it("joins a shared challenge round by code", async () => {
const user = userEvent.setup();
mocks.session
.mockResolvedValueOnce({ authenticated: false })
.mockResolvedValueOnce({ authenticated: true, identity, has_model_key: false, workspace_id: null });
mocks.startChallenge.mockResolvedValue({ job_id: "round-job", status: "queued" });
mocks.waitForChallenge.mockResolvedValue(challenge);
render(<App />);
await user.type(await screen.findByLabelText("Display name"), "Alice");
await user.click(screen.getByRole("button", { name: /continue/i }));
await user.type(await screen.findByLabelText(/join a shared class challenge/i), "round-123");
await user.click(screen.getByRole("button", { name: /join round/i }));
await waitFor(() => expect(mocks.startChallenge).toHaveBeenCalledWith({ round_id: "round-123" }));
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
});
it("does not offer a global challenge catalog to students", async () => {
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "student", has_model_key: true, workspace_id: null, hints_used: 0, submission_count: 0 });
render(<App />);
expect(await screen.findByLabelText(/join a shared class challenge/i)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Open public challenges" })).toBeNull();
expect(screen.queryByRole("button", { name: "Publish challenge" })).toBeNull();
});
it("hides publishing and round management for a student's restored legacy challenge", async () => {
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, published_round: { round_id: "old-round", artifact_hash: "hash", tests_hash: "hash", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", status: "prepared" } });
render(<App />);
expect(await screen.findByRole("heading", { name: "src/demo.py" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Publish challenge" })).toBeNull();
expect(screen.queryByRole("button", { name: "Open round" })).toBeNull();
expect(screen.queryByRole("button", { name: "Copy round code" })).toBeNull();
expect(mocks.publishChallengeRound).not.toHaveBeenCalled();
});
it("publishes a local challenge round and displays its integrity hashes", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });
mocks.publishChallengeRound.mockResolvedValue({
round_id: "round-123",
artifact_hash: "artifact-hash-123456",
tests_hash: "tests-hash-123456",
timer_minutes: 45,
hints_per_student: 3,
visibility: "private",
status: "open",
});
render(<App />);
await user.click(await screen.findByRole("button", { name: "Publish challenge" }));
const dialog = await screen.findByRole("dialog", { name: "Publish challenge" });
expect(within(dialog).getByText(/comprehension question and private reference answer will be generated automatically/i)).toBeTruthy();
expect(within(dialog).queryByLabelText("Comprehension question")).toBeNull();
expect(within(dialog).queryByLabelText("Private model answer")).toBeNull();
const hintLimitInput = await within(dialog).findByRole("spinbutton", { name: "Hints per student" }) as HTMLInputElement;
expect(hintLimitInput.value).toBe("5");
expect(hintLimitInput.min).toBe("0");
expect(hintLimitInput.max).toBe("5");
await user.clear(hintLimitInput);
await user.type(hintLimitInput, "3");
await user.click(within(dialog).getByRole("switch", { name: "Timed challenge" }));
const timerInput = await within(dialog).findByRole("spinbutton", { name: /time limit in minutes/i });
await user.clear(timerInput);
await user.type(timerInput, "45");
await user.click(within(dialog).getByRole("button", { name: "Publish challenge" }));
expect(await screen.findByText("round-123")).toBeTruthy();
await waitFor(() => {
expect(document.body.style.overflow).toBe("");
expect(document.documentElement.style.overflow).toBe("");
});
expect(screen.getByRole("button", { name: "Copy round code" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Copy challenge link" })).toBeTruthy();
expect(screen.getByText(/3 hints\/student/)).toBeTruthy();
expect((screen.getByRole("button", { name: "Publish challenge" }) as HTMLButtonElement).disabled).toBe(true);
expect(mocks.publishChallengeRound).toHaveBeenCalledWith({
time_limit_enabled: true,
timer_minutes: 45,
hints_per_student: 3,
visibility: "private",
});
expect(screen.queryByRole("button", { name: "Open round" })).toBeNull();
expect(screen.getByRole("button", { name: "Close round" })).toBeTruthy();
});
it("warns when publishing to a server that does not confirm the hint allowance", async () => {
const user = userEvent.setup();
mocks.session.mockResolvedValue({ authenticated: true, identity, role: "instructor", has_model_key: true, workspace_id: "workspace-1" });
mocks.publishChallengeRound.mockResolvedValue({ round_id: "legacy-round", artifact_hash: "artifact", tests_hash: "tests", timer_minutes: 0, chat_messages_per_student: 5, visibility: "private", status: "prepared" });
render(<App />);
await user.click(await screen.findByRole("button", { name: "Publish challenge" }));
await user.click(within(screen.getByRole("dialog", { name: "Publish challenge" })).getByRole("button", { name: "Publish challenge" }));
expect(await screen.findByText(/server did not confirm the hint allowance/i)).toBeTruthy();
expect(screen.getByText("legacy-round")).toBeTruthy();
});
});
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({
editor: { trigger: vi.fn(), revealLineInCenter: vi.fn(), setPosition: vi.fn(), focus: vi.fn() },
config: vi.fn(),
session: vi.fn(),
login: vi.fn(),
saveModelKey: vi.fn(),
logout: vi.fn(),
startChallenge: vi.fn(),
publishChallengeRound: vi.fn(),
pollJob: vi.fn(),
challenge: vi.fn(),
history: vi.fn(),
submittedResult: vi.fn(),
resume: vi.fn(),
instructorDashboard: vi.fn(),
instructorRoundAttempts: vi.fn(),
instructorRetryRequests: vi.fn(),
reviewRetryRequest: vi.fn(),
retryRequest: vi.fn(),
createRetryRequest: vi.fn(),
feedback: vi.fn(),
instructorFeedback: vi.fn(),
saveInstructorFeedback: vi.fn(),
courseAccess: vi.fn(),
requestInstructorAccess: vi.fn(),
courseAccessRequests: vi.fn(),
reviewCourseAccessRequest: vi.fn(),
openRound: vi.fn(),
closeRound: vi.fn(),
updateRoundSettings: vi.fn(),
publicTests: vi.fn(),
readFile: vi.fn(),
saveFile: vi.fn(),
reset: vi.fn(),
runTests: vi.fn(),
diff: vi.fn(),
hint: vi.fn(),
diagnosis: vi.fn(),
submit: vi.fn(),
requestScoreReview: vi.fn(),
comprehension: vi.fn(),
gradeComprehension: vi.fn(),
saveReflection: vi.fn(),
waitForChallenge: vi.fn(),
waitForJob: vi.fn(),
}));
vi.mock("./api", () => ({ api: mocks, waitForChallenge: mocks.waitForChallenge, waitForJob: mocks.waitForJob }));
vi.mock("@monaco-editor/react", async () => {
const React = await import("react");
return {
default: ({ value, onChange, onMount }: { value: string; onChange: (value: string) => void; onMount?: (editor: typeof mocks.editor) => void }) => {
React.useEffect(() => { onMount?.(mocks.editor); }, [onMount]);
return React.createElement("textarea", { "aria-label": "Code editor", value, onChange: (event) => onChange((event.target as HTMLTextAreaElement).value) });
},
};
});
import App from "./App";
const identity = {
provider: "huggingface",
user_id: "hf-user-1",
username: "alice",
display_name: "Alice",
profile_url: "https://huggingface.co/alice",
email: "",
};
const challenge = {
workspace_id: "workspace-1",
repo_url: "https://github.com/acme/demo",
target_file: "src/demo.py",
file_path: "src/demo.py",
code: "def normalize(value):\n return value\n",
readme: "# Mission\nRepair the normalizer.",
files: ["src/demo.py"],
challenge_summary: "Fix the return value.",
hints_used: 0,
submission_count: 0,
timer_remaining: 900,
chat_history: [],
};
beforeEach(() => {
vi.clearAllMocks();
window.sessionStorage.clear();
mocks.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.comprehension.mockResolvedValue({ status: "not_applicable" });
mocks.feedback.mockResolvedValue({ feedback: null, updated_at: null });
mocks.instructorFeedback.mockResolvedValue({ feedback: null, updated_at: null });
mocks.saveInstructorFeedback.mockImplementation(async (_id, feedback) => ({ feedback, updated_at: "2026-01-01T12:00:00Z" }));
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);