File size: 17,377 Bytes
5f3b513
 
 
 
 
 
 
 
 
 
 
 
31c5114
5f3b513
 
 
f532534
5f3b513
92176ae
19bb70b
 
5f3b513
 
 
 
 
 
 
 
 
 
f532534
5f3b513
 
 
 
 
 
 
 
 
1d90e24
77bf821
5f3b513
 
 
 
 
 
 
 
92176ae
5f3b513
19bb70b
5f3b513
 
 
 
19bb70b
 
1d90e24
 
 
5f3b513
7edbaa0
 
 
 
 
92176ae
 
 
7edbaa0
 
5f3b513
 
 
 
 
 
 
 
f591795
5f3b513
 
 
 
 
 
 
92176ae
 
 
5f3b513
 
 
 
 
 
 
 
92176ae
 
 
5f3b513
 
 
d6a809c
5f3b513
 
3616094
 
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3b47c1
5f3b513
 
 
 
 
 
 
 
7277d37
 
5f3b513
 
 
 
 
 
92176ae
 
5f3b513
 
 
 
 
92176ae
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19bb70b
92176ae
 
 
1b0d955
5f3b513
 
 
92176ae
 
 
5f3b513
 
 
 
 
92176ae
5f3b513
 
 
 
 
 
19bb70b
 
 
92176ae
 
 
 
 
 
 
 
 
19bb70b
 
5f3b513
 
92176ae
 
37ab364
 
 
 
 
 
 
 
 
 
f532534
37ab364
 
1b0d955
 
 
 
 
 
 
 
 
 
 
 
92176ae
1b0d955
92176ae
 
1b0d955
92176ae
 
1b0d955
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31c5114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f3b513
 
 
 
 
d6a809c
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24cf471
92176ae
5f3b513
19bb70b
 
 
92176ae
19bb70b
 
5f3b513
 
 
 
f532534
5f3b513
 
1b0d955
37ab364
f532534
37ab364
 
92176ae
 
 
31c5114
 
 
 
 
 
 
 
 
 
 
 
5f3b513
 
 
 
 
 
 
 
 
 
 
 
 
 
98d5301
 
 
 
 
5f3b513
 
 
 
 
92176ae
 
 
 
5f3b513
 
 
 
7277d37
 
 
 
5f3b513
 
7277d37
5f3b513
 
 
 
 
 
7277d37
 
 
 
5f3b513
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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);
}