refaelz's picture
Restore submitted results and approve retries
f532534
Raw History Blame Contribute Delete
17.4 kB
export type Identity = {
provider: string;
user_id: string;
username: string;
display_name: string;
profile_url: string;
email: string;
};
export type SessionInfo = {
authenticated: boolean;
role?: "student" | "instructor";
is_course_admin?: boolean;
identity?: Identity;
has_model_key?: boolean;
workspace_id?: string | null;
challenge_round_id?: string | null;
hints_used?: number;
hints_per_student?: number;
chat_messages_used?: number;
chat_messages_per_student?: number;
submission_count?: number;
submission_locked?: boolean;
submitted_at?: string | null;
last_submission_result?: SubmissionResult | null;
reflection_saved?: boolean;
};
export type ChallengeSetup = {
github_url?: string;
round_id?: string;
retry_request_id?: string;
nesting_level?: number;
num_bugs?: number;
refactoring_enabled?: boolean;
debug_mode?: boolean;
timer_minutes?: number;
};
export type ChallengeData = {
workspace_id: string;
challenge_round_id?: string | null;
can_manage_round?: boolean;
repo_url: string;
target_file: string;
file_path: string;
code: string;
readme: string;
files: string[];
challenge_summary: string;
hints_used?: number;
hints_per_student?: number;
submission_count?: number;
timer_remaining?: number | null;
chat_history?: Array<{ role: "user" | "assistant"; content: string; gave_hint?: boolean }>;
chat_log?: Array<{ question: string; response: string; gave_hint: boolean }>;
hint_log?: Array<{ question: string; response: string; gave_hint: boolean }>;
confirmation_pending?: boolean;
chat_messages_used?: number;
chat_messages_per_student?: number;
public_test_runs?: Array<{ ran_at: string; passed: number; total: number }>;
public_test_history_complete?: boolean;
last_public_test_result?: TestResult | null;
storage_warning?: string;
published_round?: {
round_id: string;
artifact_hash: string;
tests_hash: string;
timer_minutes: number;
hints_per_student?: number;
chat_messages_per_student?: number;
visibility: "private";
status: "prepared" | "open" | "closed";
} | null;
};
export type TestResult = {
passed: number;
total: number;
score: number;
output: string;
all_passed: boolean;
per_test?: Array<{ num: number; status: string; function_name?: string; args?: string; expected?: string; actual?: unknown; actual_raw?: unknown }>;
storage_warning?: string;
};
export type HintResult = {
response: string;
gave_hint: boolean;
hints_used: number;
hints_per_student?: number;
chat_messages_used?: number;
chat_messages_per_student?: number;
penalty: number;
confirmation_pending: boolean;
storage_warning?: string;
chat_history: Array<{ question: string; response: string; gave_hint: boolean }>;
};
export type SubmissionResult = {
submission_id: string;
submitted_at?: string | null;
deadline?: string | null;
is_late?: boolean | null;
score: number;
test_score: number;
llm_score: number | null;
llm_review_status?: "not_requested" | "processing" | "completed" | "failed" | "not_applicable" | "quota_exhausted" | "quota_unavailable";
llm_explanation?: string;
hint_penalty: number;
scope_penalty?: number;
unrelated_functions?: string[];
hint_history?: Array<{ question: string; response: string; hint_summary?: string }>;
passed: number;
total_tests: number;
public_passed: number;
public_total: number;
secret_passed: number;
secret_total: number;
all_passed: boolean;
tests: Array<{ num: number; status: string }>;
public_output: string;
explanation: string;
submission_outcome: string;
expected_diff: string;
supabase_saved: boolean;
storage_warning: string;
submission_count: number;
};
export type ReflectionAnswers = {
understanding_rating: number;
independent_fix_rating: number;
core_bug_explanation: string;
};
export type DevDiagnosis = {
file_path: string;
functions: string[];
bug_description: string;
diff: string;
};
export type PublicTestsView = {
file_path: string;
source: string;
functions: string[];
tests?: Array<{ num: number; function_name: string; args: string; expected: string }>;
total: number;
};
export type ApiJob<T> = {
job_id: string;
kind: "challenge" | "submission" | "score_review";
status: "queued" | "running" | "completed" | "failed";
error: string;
progress: number;
message: string;
result: T;
};
export type HistorySubmission = {
submission_id: string;
submitted_at: string;
deadline?: string | null;
is_late?: boolean | null;
attempt_number: number;
total_score: number | null;
passed_tests: number | null;
total_tests: number | null;
submission_outcome: string | null;
comprehension_grade?: number | null;
};
export type HistoryAttempt = {
workspace_id: string;
started_at: string | null;
updated_at: string | null;
status: string;
hints_used: number;
repo_url: string | null;
target_file: string | null;
round_id: string | null;
submission_count: number;
reflection_saved: boolean;
resumable: boolean;
submissions: HistorySubmission[];
};
export type StudentHistory = {
attempts: HistoryAttempt[];
limit: number;
};
export type InstructorRound = {
round_id: string;
repo_url: string | null;
target_file: string | null;
status: "prepared" | "open" | "closed";
created_at: string | null;
opened_at: string | null;
closed_at: string | null;
timer_minutes: number;
hints_per_student?: number;
chat_messages_per_student?: number;
visibility?: "private";
can_manage?: boolean;
participants: Array<{
student_name: string | null;
status: string;
submitted_at?: string | null;
deadline?: string | null;
is_late?: boolean | null;
last_activity: string | null;
hints_used: number;
submission_count: number;
reflection_saved: boolean;
latest_score: number | null;
comprehension_grade?: number | null;
passed_tests: number | null;
total_tests: number | null;
submission_outcome: string | null;
}>;
};
export type ChallengeRoundSettings = {
time_limit_enabled: boolean;
timer_minutes: number;
hints_per_student: number;
visibility: "private";
};
export type ComprehensionResult = {
status: "pending" | "completed" | "legacy" | "not_applicable";
question?: string;
answer?: string | null;
grade?: number | null;
};
export type InstructorDashboard = { rounds: InstructorRound[] };
export type InstructorFeedback = { feedback: string | null; updated_at: string | null };
export type RetryRequest = {
request_id?: string;
submission_id?: string;
round_id?: string;
student_name?: string;
reason?: string;
status: "none" | "pending" | "approved" | "denied";
requested_at?: string;
lecturer_response?: string | null;
reviewed_at?: string | null;
retry_started?: boolean;
};
export type InstructorAttempt = {
workspace_id: string;
student_name: string;
status: string;
started_at: string | null;
updated_at: string | null;
submitted_at: string | null;
hints_used: number;
public_test_runs: Array<{ ran_at: string; passed: number; total: number }> | null;
public_test_history_complete: boolean;
chat_log: Array<{ question: string; response: string; gave_hint: boolean; hint_summary: string }> | null;
submissions: Array<{
submission_id: string;
submitted_at: string | null;
deadline?: string | null;
is_late?: boolean | null;
total_score: number | null;
comprehension_grade?: number | null;
comprehension_answer?: string | null;
passed_tests: number | null;
total_tests: number | null;
public_passed: number | null;
public_total: number | null;
secret_passed: number | null;
secret_total: number | null;
submission_outcome: string | null;
student_diff: string;
self_assessment: { confidence?: number; known_limitations?: string };
}>;
};
export type InstructorAttemptsPage = {
attempts: InstructorAttempt[];
has_more: boolean;
next_offset: number | null;
};
export type CourseAccessRequest = {
request_id: string;
auth_provider: string;
provider_user_id: string;
display_name: string;
reason: string;
requested_at: string;
};
export type CourseAccessStatus = {
role: "student" | "instructor";
is_course_admin: boolean;
request: {
request_id: string;
status: "pending" | "approved" | "rejected";
reason: string;
requested_at: string;
reviewed_at: string | null;
} | null;
};
export type ScoreReviewRequest = {
job_id?: string;
kind?: string;
status: "queued" | "processing" | "completed" | "failed" | "not_applicable";
llm_score?: number | null;
total_score?: number;
explanation?: string;
error?: string;
};
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
const response = await fetch(path, {
...init,
credentials: "include",
headers: {
...(init.body ? { "Content-Type": "application/json" } : {}),
...init.headers,
},
});
if (!response.ok) {
let message = `Request failed (${response.status})`;
try {
const body = await response.json();
message = body.detail || message;
} catch {
// Keep the generic HTTP message for non-JSON responses.
}
if (response.status === 401) {
message = "Your session expired. Please sign in again; unsaved edits may need to be reapplied.";
if (typeof window !== "undefined") window.dispatchEvent(new Event("app:session-expired"));
}
throw new Error(message);
}
if (response.status === 204) return undefined as T;
return response.json() as Promise<T>;
}
export const api = {
config: () => request<{ hf_oauth: boolean; google_oauth: boolean; dev_login: boolean; dev_diagnostics: boolean; model_key_configured: boolean; course_mode: boolean; approved_repositories: string[] }>("/api/config"),
session: () => request<SessionInfo>("/api/session"),
login: (name: string, apiKey: string) =>
request<void>("/api/dev/login", { method: "POST", body: JSON.stringify({ name, api_key: apiKey }) }),
saveModelKey: (apiKey: string) =>
request<{ status: string }>("/api/session/model-key", { method: "POST", body: JSON.stringify({ api_key: apiKey }) }),
logout: () => request<void>("/api/logout", { method: "POST" }),
startChallenge: (setup: ChallengeSetup) =>
request<{ job_id: string; status: string }>("/api/challenges", { method: "POST", body: JSON.stringify(setup) }),
publishChallengeRound: (settings: ChallengeRoundSettings) =>
request<{ round_id: string; artifact_hash: string; tests_hash: string; timer_minutes: number; hints_per_student?: number; visibility: "private"; status: "prepared" }>("/api/challenge-rounds", {
method: "POST",
body: JSON.stringify(settings),
}),
updateRoundSettings: (roundId: string, settings: ChallengeRoundSettings) =>
request<{ round_id: string; timer_minutes: number; hints_per_student?: number; visibility: "private"; status: "prepared" }>(`/api/challenge-rounds/${encodeURIComponent(roundId)}/settings`, {
method: "PATCH",
body: JSON.stringify(settings),
}),
pollJob: <T>(jobId: string) => request<ApiJob<T>>(`/api/jobs/${encodeURIComponent(jobId)}`),
challenge: () => request<ChallengeData>("/api/challenge"),
history: (limit = 50) => request<StudentHistory>(`/api/me/history?limit=${limit}`),
submittedResult: (workspaceId: string) => request<{ round_id: string | null; result: SubmissionResult }>(`/api/challenges/${encodeURIComponent(workspaceId)}/result`),
resume: (workspaceId: string) => request<ChallengeData>(`/api/challenges/${encodeURIComponent(workspaceId)}/resume`, { method: "POST" }),
instructorDashboard: () => request<InstructorDashboard>("/api/instructor/dashboard"),
instructorRoundAttempts: (roundId: string, offset = 0) => request<InstructorAttemptsPage>(`/api/instructor/rounds/${encodeURIComponent(roundId)}/attempts?offset=${offset}`),
instructorRetryRequests: (roundId: string) => request<{ requests: RetryRequest[] }>(`/api/instructor/rounds/${encodeURIComponent(roundId)}/retry-requests`),
reviewRetryRequest: (roundId: string, requestId: string, decision: "approved" | "denied", response: string) => request<RetryRequest>(`/api/instructor/rounds/${encodeURIComponent(roundId)}/retry-requests/${encodeURIComponent(requestId)}/review`, { method: "POST", body: JSON.stringify({ decision, response }) }),
retryRequest: (submissionId: string) => request<RetryRequest>(`/api/submissions/${encodeURIComponent(submissionId)}/retry-request`),
createRetryRequest: (submissionId: string, reason: string) => request<RetryRequest>(`/api/submissions/${encodeURIComponent(submissionId)}/retry-request`, { method: "POST", body: JSON.stringify({ reason }) }),
feedback: (submissionId: string) => request<InstructorFeedback>(`/api/submissions/${encodeURIComponent(submissionId)}/feedback`),
instructorFeedback: (submissionId: string) => request<InstructorFeedback>(`/api/instructor/submissions/${encodeURIComponent(submissionId)}/feedback`),
saveInstructorFeedback: (submissionId: string, feedback: string) => request<InstructorFeedback>(`/api/instructor/submissions/${encodeURIComponent(submissionId)}/feedback`, { method: "PUT", body: JSON.stringify({ feedback }) }),
courseAccess: () => request<CourseAccessStatus>("/api/course/access"),
requestInstructorAccess: (reason: string) =>
request<{ request_id: string; status: string }>("/api/course/access-requests", {
method: "POST",
body: JSON.stringify({ reason }),
}),
courseAccessRequests: () => request<{ requests: CourseAccessRequest[] }>("/api/admin/course-access-requests"),
reviewCourseAccessRequest: (requestId: string, decision: "approved" | "rejected") =>
request<{ reviewed: boolean; status: string }>(`/api/admin/course-access-requests/${encodeURIComponent(requestId)}/review`, {
method: "POST",
body: JSON.stringify({ decision }),
}),
openRound: (roundId: string) => request<{ round_id: string; status: string }>(`/api/challenge-rounds/${encodeURIComponent(roundId)}/open`, { method: "POST" }),
closeRound: (roundId: string) => request<{ round_id: string; status: string }>(`/api/challenge-rounds/${encodeURIComponent(roundId)}/close`, { method: "POST" }),
publicTests: () => request<PublicTestsView>("/api/challenge/public-tests"),
readFile: (path: string) => request<{ path: string; content: string }>(`/api/challenge/files/${path.split("/").map(encodeURIComponent).join("/")}`),
saveFile: (path: string, content: string) =>
request<{ status: string; storage_warning?: string }>(`/api/challenge/files/${path.split("/").map(encodeURIComponent).join("/")}`, {
method: "PUT",
body: JSON.stringify({ content }),
}),
reset: () => request<{ status: string; code: string; path: string; storage_warning?: string }>("/api/challenge/reset", { method: "POST" }),
diff: (filePath: string, code: string) =>
request<{ diff: string; has_changes: boolean }>("/api/challenge/diff", { method: "POST", body: JSON.stringify({ file_path: filePath, code }) }),
runTests: (filePath: string, code: string) =>
request<TestResult>("/api/challenge/run-tests", { method: "POST", body: JSON.stringify({ file_path: filePath, code }) }),
hint: (message: string, filePath: string, code: string) =>
request<HintResult>("/api/challenge/hints", {
method: "POST",
body: JSON.stringify({ message, file_path: filePath, code }),
}),
diagnosis: () => request<DevDiagnosis>("/api/challenge/dev-diagnosis"),
submit: (filePath: string, code: string, selfAssessment: { confidence: number; known_limitations: string }) =>
request<{ job_id: string; kind: string; status: string }>("/api/challenge/submit", { method: "POST", body: JSON.stringify({ file_path: filePath, code, self_assessment: selfAssessment }) }),
requestScoreReview: (submissionId: string) =>
request<ScoreReviewRequest>(`/api/submissions/${encodeURIComponent(submissionId)}/score-review`, { method: "POST" }),
comprehension: (submissionId: string) =>
request<ComprehensionResult>(`/api/submissions/${encodeURIComponent(submissionId)}/comprehension`),
gradeComprehension: (submissionId: string, answer: string) =>
request<ComprehensionResult>(`/api/submissions/${encodeURIComponent(submissionId)}/comprehension`, { method: "POST", body: JSON.stringify({ answer }) }),
saveReflection: (submissionId: string, reflection: ReflectionAnswers) =>
request<{ status: string }>(`/api/submissions/${encodeURIComponent(submissionId)}/reflection`, { method: "POST", body: JSON.stringify(reflection) }),
};
export async function waitForJob<T>(
jobId: string,
onProgress: (status: string, progress?: number, message?: string) => void,
): Promise<T> {
for (;;) {
const job = await api.pollJob<T>(jobId);
onProgress(job.status, job.progress, job.message);
if (job.status === "completed") return job.result;
if (job.status === "failed") throw new Error(job.error || "Challenge operation failed");
await new Promise((resolve) => window.setTimeout(resolve, 1200));
}
}
export function waitForChallenge(
jobId: string,
onProgress: (status: string, progress?: number, message?: string) => void,
): Promise<ChallengeData> {
return waitForJob<ChallengeData>(jobId, onProgress);
}