-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.ts
More file actions
2072 lines (1940 loc) · 68.4 KB
/
Copy pathclient.ts
File metadata and controls
2072 lines (1940 loc) · 68.4 KB
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Phase 17 / H-A3: mutating routes require a custom header so the backend
// can reject simple cross-origin POSTs (which can't set arbitrary headers
// without tripping CORS preflight, which the backend then rejects by
// Origin). Attach to every POST from this client.
const JSON_HEADERS = { "Content-Type": "application/json" };
const CSRF_HEADER = { "X-Requested-With": "codetutor" };
// Phase 19d: on SWA the frontend runs on a separate origin from the VM, so
// `/api/*` must resolve to the VM's absolute URL. In dev this is empty and
// `/api/*` stays same-origin (Vite proxies — see vite.config.ts).
export const API_BASE = import.meta.env.VITE_API_BASE_URL ?? "";
import { supabase } from "../auth/supabaseClient";
import { ApiError } from "./ApiError";
import { readDistributionAttribution } from "../features/distribution/attribution";
// Read the response body once for an error path, then wrap it in ApiError.
// We also `console.error` the raw so the detail survives in devtools even
// though the user-facing alert shows only the friendly message.
async function throwApiError(res: Response, path: string): Promise<never> {
const body = await res.text().catch(() => "");
console.error(`[api] ${path} failed: ${res.status} ${body}`);
const retryAfterRaw = res.headers.get("Retry-After");
const retryAfterSeconds = retryAfterRaw
? Math.max(0, Number.parseInt(retryAfterRaw, 10))
: null;
throw new ApiError(
res.status,
body,
path,
Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : null,
);
}
// Phase 18a: attach the Supabase access token to every backend request so
// the `authMiddleware` on the server side can identify the user. We fetch
// the session lazily per-request — the SDK caches and auto-refreshes, so
// `getSession()` returns synchronously from cache in the common path.
//
// /api/health is callable pre-auth; every other backend route (including
// /api/ai/validate-key) requires an Authorization header.
async function authHeaders(): Promise<Record<string, string>> {
try {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
return token ? { Authorization: `Bearer ${token}` } : {};
} catch {
return {};
}
}
let refreshInFlight: Promise<string | null> | null = null;
// Admin operations are intentionally bounded. The console is an incident-
// response surface: an unanswered request must become a visible retry state
// instead of leaving an operator to guess whether a skeleton is still alive.
// Keep this longer than the normal 5 s polling cadence, while still short
// enough to be useful during an outage.
export const ADMIN_REQUEST_TIMEOUT_MS = 10_000;
// Model changes deliberately combine live provider discovery, guarded config
// storage, an authoritative reread, and audit logging. Keep the normal admin
// read budget sharp, but do not let this longer mutation report failure while
// the server is still completing an accepted change.
export const TUTOR_MODEL_ADMIN_TIMEOUT_MS = 30_000;
async function refreshAccessToken(): Promise<string | null> {
if (refreshInFlight) return refreshInFlight;
refreshInFlight = supabase.auth
.refreshSession()
.then(({ data, error }) => {
if (error) return null;
return data.session?.access_token ?? null;
})
.catch(() => null)
.finally(() => {
refreshInFlight = null;
});
return refreshInFlight;
}
/**
* Authenticated requests get one explicit token-refresh retry on 401. A
* second 401 is returned to the caller as a recoverable action error; it does
* not silently sign the learner out or destroy the route they were using.
*/
async function authenticatedFetch(path: string, init: RequestInit = {}): Promise<Response> {
const isAdminRequest = path.startsWith("/api/admin/");
const isTutorModelMutation = path === "/api/admin/tutor-model" &&
init.method !== undefined && init.method.toUpperCase() !== "GET";
const timeoutController = isAdminRequest ? new AbortController() : null;
const callerSignal = init.signal;
let timedOut = false;
const forwardAbort = () => timeoutController?.abort(callerSignal?.reason);
if (callerSignal && timeoutController) {
if (callerSignal.aborted) forwardAbort();
else callerSignal.addEventListener("abort", forwardAbort, { once: true });
}
const timeoutId = timeoutController
? globalThis.setTimeout(() => {
timedOut = true;
timeoutController.abort();
}, isTutorModelMutation
? TUTOR_MODEL_ADMIN_TIMEOUT_MS
: ADMIN_REQUEST_TIMEOUT_MS)
: null;
const send = async (tokenOverride?: string | null) => {
const auth = tokenOverride
? { Authorization: `Bearer ${tokenOverride}` }
: await authHeaders();
return fetch(`${API_BASE}${path}`, {
...init,
signal: timeoutController?.signal ?? callerSignal,
headers: { ...auth, ...(init.headers ?? {}) },
});
};
try {
let res = await send();
if (res.status !== 401) return res;
const refreshed = await refreshAccessToken();
if (!refreshed) return res;
res = await send(refreshed);
return res;
} catch (error) {
if (timedOut) {
throw new Error(
"The admin request took too long. Check the connection and try again.",
);
}
throw error;
} finally {
if (timeoutId !== null) globalThis.clearTimeout(timeoutId);
callerSignal?.removeEventListener("abort", forwardAbort);
}
}
// QA-H3: registry of in-flight fetches keyed by sessionId so a rebind that
// returns a *different* id can abort them atomically. Without this, a
// snapshot/execute/status call fired before the rebind lands with the old
// sessionId in its body, the backend 404s it, and the UI flashes a spurious
// "session not found" error against a session that was just successfully
// recreated under a new id.
const sessionAbortRegistry = new Map<string, Set<AbortController>>();
const anonRunAbortRegistry = new Set<AbortController>();
function registerSessionRequest(sessionId: string): AbortController {
const ctrl = new AbortController();
let bucket = sessionAbortRegistry.get(sessionId);
if (!bucket) {
bucket = new Set();
sessionAbortRegistry.set(sessionId, bucket);
}
bucket.add(ctrl);
return ctrl;
}
function releaseSessionRequest(sessionId: string, ctrl: AbortController): void {
const bucket = sessionAbortRegistry.get(sessionId);
if (!bucket) return;
bucket.delete(ctrl);
if (bucket.size === 0) sessionAbortRegistry.delete(sessionId);
}
export function abortSessionRequests(sessionId: string): number {
const bucket = sessionAbortRegistry.get(sessionId);
if (!bucket) return 0;
const n = bucket.size;
for (const ctrl of bucket) ctrl.abort();
sessionAbortRegistry.delete(sessionId);
return n;
}
export function abortAnonRunRequests(): number {
const count = anonRunAbortRegistry.size;
for (const controller of anonRunAbortRegistry) controller.abort();
anonRunAbortRegistry.clear();
return count;
}
async function post<T>(path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<T> {
const res = await authenticatedFetch(path, {
method: "POST",
headers: { ...JSON_HEADERS, ...CSRF_HEADER, ...(extraHeaders ?? {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
async function patch<T>(path: string, body: unknown): Promise<T> {
const res = await authenticatedFetch(path, {
method: "PATCH",
headers: { ...JSON_HEADERS, ...CSRF_HEADER },
body: JSON.stringify(body),
});
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
async function put<T>(path: string, body: unknown): Promise<T> {
const res = await authenticatedFetch(path, {
method: "PUT",
headers: { ...JSON_HEADERS, ...CSRF_HEADER },
body: JSON.stringify(body),
});
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
async function del<T>(path: string): Promise<T> {
const res = await authenticatedFetch(path, {
method: "DELETE",
headers: { ...CSRF_HEADER },
});
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
// Phase 25: DELETE-with-body. Some admin destructive endpoints
// (kill session, kill all-for-user) carry a phrase-confirm body even
// though the HTTP semantics are deletion.
async function delJson<T>(path: string, body: unknown): Promise<T> {
const res = await authenticatedFetch(path, {
method: "DELETE",
headers: { "Content-Type": "application/json", ...CSRF_HEADER },
body: JSON.stringify(body),
});
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
async function get<T>(path: string, extraHeaders?: Record<string, string>): Promise<T> {
const res = await authenticatedFetch(path, { headers: { ...(extraHeaders ?? {}) } });
if (!res.ok) {
await throwApiError(res, path);
}
return res.json() as Promise<T>;
}
import type {
AIMessage,
AIModel,
ContextualTutorOfferRequest,
EditorSelection,
Language,
Persona,
ProjectFile,
RunResult,
TokenUsage,
TutorAction,
TutorSections,
} from "../types";
import type { CompletionRule, FunctionTest, SourceCheck, TestReport } from "../features/learning/types";
export interface ExecuteTestsResponse {
report: TestReport;
stderr: string;
exitCode: number;
timedOut: boolean;
durationMs: number;
}
// Phase 20-P4: /api/user/ai-status response shape. Mirrors the backend's
// CredentialNoneReason union in services/ai/credential.ts — keep in sync.
export type AIStatusNoneReason =
| "no_key"
| "free_disabled"
| "free_exhausted"
| "daily_usd_per_user_hit"
| "lifetime_usd_per_user_hit"
| "usd_cap_hit"
| "denylisted"
| "provider_auth_failed";
export interface AIStatusResponse {
source: "byok" | "platform" | "none";
reason?: AIStatusNoneReason;
remainingToday: number | null;
capToday: number | null;
resetAtUtc: string | null;
// Phase 20-P4: once a user has clicked the paid-interest CTA anywhere,
// every surface hides the button — one signal per user is enough and more
// clutter is noise. Backend derives from EXISTS on paid_access_interest.
hasShownPaidInterest: boolean;
/** Independent Release 1C runtime model-call gate. */
contextualTutorEnabled: boolean;
/** Whether the effective platform model passed the contextual-offer eval gate. */
contextualTutorModelEligible: boolean;
}
// Phase 18b: per-user data API surface. Every shape here mirrors the
// backend's db/*.ts types; mismatches surface as runtime shape errors
// rather than type errors, so keep the two in sync when the schema moves.
export interface UserPreferences {
persona: "beginner" | "intermediate" | "advanced";
openaiModel: string | null;
theme: "system" | "light" | "dark";
welcomeDone: boolean;
workspaceCoachDone: boolean;
editorCoachDone: boolean;
uiLayout: Record<string, unknown>;
// Phase 18e: BYOK presence flag. The plaintext key lives only on the
// backend (encrypted at rest in user_preferences) — the frontend only
// learns whether one is set, never the value itself.
hasOpenaiKey: boolean;
// First-run cinematic: timestamp of the last time the daily welcome-
// back overlay was shown. Server-backed so one device's heartbeat
// suppresses the next device's — a learner who got welcomed on
// laptop at 9am shouldn't be re-welcomed on phone at noon.
lastWelcomeBackAt: string | null;
// Phase 22D: opt-in for the streak re-engagement email. Defaults TRUE
// for new accounts. Settings panel exposes a toggle; the email's
// unsubscribe link flips this to false directly via the unsubscribe
// route (bypasses the patch path).
emailOptIn: boolean;
// Phase 27: hide the streak system entirely for this user. Defaults
// FALSE; when TRUE, StreakChip + lesson-complete streak section +
// share-page streak count + daily streak email are all suppressed.
// Streak data on the server is preserved; toggling back to FALSE
// resumes display from the persisted value.
disableStreaks: boolean;
updatedAt: string;
// Phase 25: account-freeze flag. When true, the user is blocked from
// creating new sessions and the authed shell renders a generic
// "account suspended — contact support" banner. Backend's
// sessionManager.startSession returns 403 ACCOUNT_FROZEN. The
// operator's internal freeze reason is NOT exposed here — it's
// audit-trail only and stays server-side.
accountFrozen?: boolean;
}
export interface UserPreferencesPatch {
persona?: UserPreferences["persona"];
openaiModel?: string | null;
theme?: UserPreferences["theme"];
welcomeDone?: boolean;
workspaceCoachDone?: boolean;
editorCoachDone?: boolean;
uiLayout?: Record<string, unknown>;
lastWelcomeBackAt?: string | null;
emailOptIn?: boolean;
disableStreaks?: boolean;
}
export interface ServerCourseProgress {
courseId: string;
status: "not_started" | "in_progress" | "completed";
startedAt: string | null;
completedAt: string | null;
updatedAt: string;
lastLessonId: string | null;
completedLessonIds: string[];
}
export interface ServerCoursePatch {
status?: ServerCourseProgress["status"];
startedAt?: string | null;
completedAt?: string | null;
lastLessonId?: string | null;
completedLessonIds?: string[];
}
export interface ServerLessonProgress {
courseId: string;
lessonId: string;
status: "not_started" | "in_progress" | "completed";
startedAt: string | null;
completedAt: string | null;
updatedAt: string;
attemptCount: number;
runCount: number;
hintCount: number;
timeSpentMs: number;
lastCode: Record<string, string> | null;
draftRevision: number;
draftWriterId: string | null;
draftUpdatedAt: string | null;
lastOutput: string | null;
practiceCompletedIds: string[];
practiceExerciseCode: Record<string, Record<string, string>>;
}
export interface ServerLessonPatch {
status?: ServerLessonProgress["status"];
startedAt?: string | null;
completedAt?: string | null;
attemptCount?: number;
runCount?: number;
hintCount?: number;
timeSpentMs?: number;
lastOutput?: string | null;
practiceCompletedIds?: string[];
practiceExerciseCode?: Record<string, Record<string, string>>;
practiceEvidence?: PracticeEvidencePayload;
}
export interface PracticeEvidencePayload {
exerciseId: string;
requestId: string;
attemptCount: number;
hintCount: number;
timeSpentMs: number;
modelAssisted: boolean;
}
export type ConceptMemoryState =
| "unseen"
| "encountered"
| "practiced"
| "remembered"
| "retained";
export interface ConceptMemoryItem {
conceptTag: string;
state: ConceptMemoryState;
firstSeenAt: string | null;
lastSeenAt: string | null;
lastRetrievalAt: string | null;
practiceCount: number;
supportedRetrievalCount: number;
independentRetrievalCount: number;
refreshDue: boolean;
}
export interface ConceptMemoryResponse {
courseId: string;
refreshAfterDays: number;
concepts: ConceptMemoryItem[];
}
export interface MemoryWarmupPrompt {
episodeId: string;
courseId: string;
lessonId: string;
warmupId: string;
warmupVersion: number;
conceptTags: string[];
prompt: string;
choices: string[];
attemptCount: number;
}
export interface MemoryWarmupAnswer {
episodeId: string;
isCorrect: boolean;
attemptNumber: number;
completed: boolean;
firstAttemptCorrect: boolean;
explanation: string;
}
export interface EditorProjectPayload {
language: string;
files: Record<string, string>;
activeFile: string | null;
openTabs: string[];
fileOrder: string[];
stdin: string;
expectedRevision: number;
writerId: string;
}
export interface EditorProjectResponse extends Omit<EditorProjectPayload, "expectedRevision" | "writerId"> {
revision: number;
writerId: string | null;
updatedAt: string;
}
export interface AskStreamRequest {
/** One identifier per user-accepted action; never reused for a new action. */
requestId: string;
/** Omitted for platform-funded requests; the backend owns that choice. */
model?: string;
question: string;
tutorAction?: TutorAction;
contextualOffer?: ContextualTutorOfferRequest;
files: ProjectFile[];
activeFile?: string;
language?: Language;
lastRun?: RunResult | null;
history: AIMessage[];
tutorProgressToken?: string;
stdin?: string | null;
diffSinceLastTurn?: string | null;
runsSinceLastTurn?: number;
editsSinceLastTurn?: number;
persona?: Persona;
selection?: EditorSelection | null;
lessonContext?: {
courseId: string;
lessonId: string;
exerciseId?: string | null;
} | null;
evalSamplingConsent?: {
version: 1;
subjectToken: string;
};
}
export interface AskStreamHandlers {
onDelta(chunk: string): void;
onDone(
raw: string,
sections: TutorSections,
usage?: TokenUsage,
tutorProgressToken?: string,
remainingToday?: number | null,
countsTowardQuota?: boolean,
): void;
onError(message: string): void;
signal?: AbortSignal;
}
// -------------------------------------------------------------------------
// Phase 20-P5: admin types
// -------------------------------------------------------------------------
export interface AdminUserOverride {
userId: string;
dailyQuestionsCap: number | null;
dailyUsdCap: number | null;
lifetimeUsdCap: number | null;
setBy: string | null;
setAt: string;
reason: string | null;
}
export interface AdminUserListEntry {
id: string;
email: string | null;
displayName: string | null;
createdAt: string;
lastSignInAt: string | null;
questionsToday: number;
usdToday: number;
usdLifetime: number;
override: AdminUserOverride | null;
denylisted: boolean;
}
export interface AdminDenylistRow {
userId: string;
reason: string;
deniedAt: string;
frozen: boolean;
frozenReason: string | null;
frozenAt: string | null;
frozenSetBy: string | null;
}
export interface AdminUsersListResponse {
users: AdminUserListEntry[];
page: number;
perPage: number;
hasMore: boolean;
}
export interface AdminUserDetailResponse {
user: {
id: string;
email: string | null;
displayName: string | null;
createdAt: string;
lastSignInAt: string | null;
};
questionsToday: number;
usdToday: number;
usdLifetime: number;
override: AdminUserOverride | null;
denylisted: boolean;
// Phase 25: full denylist row when present (frozen state + reasons).
denylist: AdminDenylistRow | null;
}
export type SystemConfigKey =
| "free_tier_enabled"
| "free_tier_daily_questions"
| "free_tier_daily_usd_per_user"
| "free_tier_lifetime_usd_per_user"
| "free_tier_daily_usd_cap"
// Phase 21C kill switches — admin-toggleable for fast incident
// response. Boolean: `true` = the kill is engaged.
| "share_public_disabled"
| "share_create_disabled"
| "share_render_disabled"
| "share_preview_disabled"
// Phase 24B operational knobs — admin-toggleable for fast spike
// response. `aci_overflow_enabled = false` is the runtime kill switch
// (no new ACI spawns; cap shrinks to local-only). Daily $ cap and
// max overflow are dial-tweakable without redeploy.
| "aci_overflow_enabled"
| "aci_daily_usd_cap"
| "aci_max_overflow"
// Slice 8.5: warm-pool master toggle. Default off; flip on if cold-
// start latency surfaces post-launch.
| "aci_warm_pool_enabled"
// P2-2: warm-pool hysteresis knobs.
| "aci_warm_high_watermark"
| "aci_warm_low_watermark"
| "aci_warm_max_pool_size"
// Phase 27-v2.2 Fix 7c — master kill switch for /api/anon/*. False
// 503s the anon trial path on the next request (60s cache TTL).
| "anon_lesson_enabled"
// Phase A — A2: granular kill for the phone-graduation magic link.
| "anon_laptop_invite_disabled"
// Phase A — A5 operational floor: anon-only global daily $ ceiling
// and per-IP daily container-spawn cap on /api/anon/run.
| "anon_daily_usd_cap"
| "anon_daily_runs_per_ip"
| "ai_eval_sampling_enabled"
| "contextual_tutor_enabled";
export interface SystemConfigEntry {
value: boolean | number;
source: "override" | "env";
envDefault: boolean | number;
setBy: string | null;
setAt: string | null;
reason: string | null;
bounds:
| { type: "number"; min: number; max: number; step: string }
| { type: "boolean" };
}
export interface SystemConfigResponse {
config: Record<SystemConfigKey, SystemConfigEntry>;
}
export interface AdminTutorModelCandidate {
id: string;
label: string;
qualityStatus: "evaluated" | "unevaluated";
qualityLabel: string;
evalSetVersion: string | null;
availableToPlatform: boolean;
selectable: boolean;
recommended: boolean;
priceUsdPerMillion: { input: number; output: number } | null;
costMultiplierVsRecommended: number | null;
unavailableReason: string | null;
}
export interface AdminTutorModelState {
current: {
model: string;
source: "override" | "fallback";
setBy: string | null;
setAt: string | null;
reason: string | null;
invalidOverride: string | null;
};
fallbackModel: string;
candidates: AdminTutorModelCandidate[];
discoveryError: string | null;
}
export type AdminAuditEventType =
| "user_override_set"
| "user_override_cleared"
| "system_config_set"
| "system_config_cleared"
| "denylist_added"
| "denylist_removed"
| "tab_opened"
| "rejected_attempt"
// Phase 25 additions
| "session_terminated"
| "session_terminated_bulk"
| "user_frozen"
| "user_unfrozen"
| "budget_watcher_reset"
| "platform_auth_unstick"
// Phase 26 additions
| "user_force_signout"
// Phase B8 governed evaluation review.
| "eval_sample_viewed"
| "eval_sample_reviewed"
| "eval_sample_queue_resolved";
export type AdminAuditLogCategory = "changes" | "reviews" | "all";
export interface AdminAuditLogEntry {
id: string;
actorId: string;
eventType: AdminAuditEventType;
targetUserId: string | null;
targetKey: string | null;
before: unknown;
after: unknown;
reason: string | null;
createdAt: string;
}
export interface AdminAuditLogResponse {
entries: AdminAuditLogEntry[];
nextCursor: string | null;
}
// Phase 27-v2.2 Fix 7b: anon-trial-path summary for the new admin tab.
// Read-only; the kill switch toggle goes through adminSetSystemConfig.
export interface AdminAnonSummary {
generatedAt: string;
/** Today's anon questions counted against quota (counts_toward_quota). */
questionsToday: number;
/** Distinct ip_hash values seen today. */
distinctIpsToday: number;
/** IPs that hit the per-IP daily cap today (count == anonDailyQuestionsPerIp). */
exhaustedIpsToday: number;
/** Per-IP cap and combined L4 daily cap (for context). */
perIpDailyCap: number;
/** Cumulative abuse signals since process boot (Counter snapshot). */
abuseSignals: {
anon_lesson_not_allowed: number;
model_rejection: number;
/** Phase A — A4: fabricated-API tripwire hits (all tutor routes). */
tutor_suspect_api: number;
};
/** Unique privacy-bounded same-day cohorts. Every later stage is
* intersected with its prerequisite, so conversion stays <= 100%. */
funnelEvents: {
anon_page_view: number;
anon_first_run: number;
anon_lesson_completed: number;
anon_wall_opened: number;
anon_signup_completed: number;
anon_lesson2_reached: number;
};
distributionChannels: Array<{
source: "direct" | "organic" | "share";
anon_page_view: number;
anon_first_run: number;
anon_lesson_completed: number;
anon_signup_completed: number;
anon_lesson2_reached: number;
}>;
killSwitch: {
/** True if /api/anon/* is currently enabled. */
enabled: boolean;
/** "override" if system_config has a row, "env" otherwise. */
source: "override" | "env";
setBy: string | null;
setAt: string | null;
reason: string | null;
};
}
// Phase 25: dashboard snapshot.
export interface AdminDashboardSnapshot {
generatedAt: string;
sessions: {
/** Total local active = authed + anon. */
local: number;
/** Authed-only local (from sessionManager). */
localAuthed: number;
/** Anon ephemeral local sessions in flight. */
localAnon: number;
/** Total ACI active = authed + anon. */
aci: number;
/** Authed-only ACI. */
aciAuthed: number;
/** Anon ACI in flight when overflow routes anon. */
aciAnon: number;
total: number;
capLocal: number;
capAbsolute: number;
counterDrift: number;
};
aci: {
enabled: boolean;
costTrackerState: "hydrated" | "degraded";
spentTodayUsd: number;
dailyUsdCap: number;
activeSessions: number;
configRefreshAgeMs: number | null;
};
freeTier: {
enabled: boolean;
spentTodayUsd: number;
/** Phase 27-v2.2 Fix 7a — authed-only spend today; sums with
* spentTodayUsdAnon to spentTodayUsd. */
spentTodayUsdAuthed: number;
/** Phase 27-v2.2 Fix 7a — anon-only spend today. */
spentTodayUsdAnon: number;
dailyUsdCap: number;
lastFiredKey: string | null;
};
queues: {
dockerExecInflight: number;
dockerExecQueued: number;
renderActive: number;
renderWaiting: number;
};
/** Phase A — A5: projected monthly burn (fixed infra baseline + AI
* spend extrapolated from the trailing 7 days). Directional. */
burn: {
infraMonthlyUsd: number;
aiSpendLast7dUsd: number;
aiDailyAvgUsd: number;
projectedMonthlyUsd: number;
};
health: {
db: "ok" | "fail";
platformAuth: "ok" | "failed";
platformAuthSinceMs: number | null;
};
bootId: string;
rates: {
httpResponses: Record<string, number>;
aciSpawnAttempts: Record<string, number>;
};
}
export interface AdminSession {
sessionId: string;
userId: string;
userEmail: string | null;
backend: "local" | "aci";
ageMs: number;
lastSeenMs: number;
selectedModel: string | null;
}
export interface AdminSessionsResponse {
sessions: AdminSession[];
total: number;
}
export interface AdminEmailLogEntry {
id: string;
userId: string;
kind: string;
toEmail: string;
subject: string;
textBody: string;
htmlBody: string;
acsOpId: string | null;
sentAt: string;
capabilitiesRedacted: true;
}
export interface AdminEmailLogResponse {
entries: AdminEmailLogEntry[];
nextCursor: string | null;
}
export interface AdminBudgetWatcherState {
lastFiredKey: string | null;
dailyCapUsd: number;
spentTodayUsd: number;
}
export interface AdminEvalSample {
id: string;
model: string;
language: string;
courseId: string;
lessonId: string;
intent: string;
tutorStage: string;
questionRedacted: string;
responseRedacted: string;
contentFingerprint: string;
fileCount: number;
sourceBytesBucket: string;
historyTurnCount: number;
hadRunResult: boolean;
runErrorType: string | null;
sectionKeys: string[];
redactionCounts: { code: number; sensitive: number; identifiers: number };
disposition: "pending_review" | "review_complete" | "synthesis_queued" | "rejected";
reviewCount: number;
distinctVerdictCount: number;
createdAt: string;
expiresAt: string;
}
export interface AdminEvalSynthesisQueueItem {
id: string;
sampleId: string;
sourceFingerprint: string;
reviewCount: number;
distinctVerdictCount: number;
state: "pending_synthesis" | "synthetic_case_authored" | "rejected";
syntheticCaseId: string | null;
createdAt: string;
resolvedAt: string | null;
}
export interface AdminPlatformAuthState {
failed: boolean;
sinceMs: number | null;
}
// Phase 21B: learning streak.
export interface UserStreakResponse {
current: number;
longest: number;
lastActiveDate: string | null;
lastFreezeUsed: string | null;
isActiveToday: boolean;
isAtRisk: boolean;
resetAtUtc: string;
freezeActive: boolean;
wasFirstToday: boolean;
freezeUsedToday: boolean;
}
export interface StreakHistoryResponse {
/** UTC dates 'YYYY-MM-DD', oldest → newest, length = days. */
windowDates: string[];
/** Subset of windowDates where qualifying activity was recorded. */
activeDates: string[];
/** Subset of windowDates where the freeze covered a missed day. */
freezeUsedDates: string[];
/** Today's UTC date. */
todayUtc: string;
}
// Phase 21C: shared lesson completions (cinematic share artifact).
export type ShareMastery = "strong" | "okay" | "shaky";
export interface SharedLessonCompletion {
shareToken: string;
courseId: string;
lessonId: string;
lessonTitle: string;
lessonOrder: number;
courseTitle: string;
courseTotalLessons: number;
mastery: ShareMastery;
timeSpentMs: number;
attemptCount: number;
codeSnippet: string;
displayName: string | null;
ogImageUrl: string | null;
/** Phase 21C-ext: 9:16 Story-format image (1080×1920). Null until
* the fire-and-forget render+upload pipeline lands; the
* ShareDialog polls until this becomes non-null. */
ogStoryImageUrl: string | null;
viewCount: number;
createdAt: string;
}
// Post-audit: lesson title / order / course title / total are NOT
// part of the wire schema anymore. The backend looks them up
// canonically from the published course catalog (defends against
// brand-impersonation shares).
export interface CreateShareBody {
courseId: string;
lessonId: string;
mastery: ShareMastery;
timeSpentMs: number;
attemptCount: number;
codeSnippet: string;
displayName: string | null;
}
export interface OwnerShare {
shareToken: string;
courseId: string;
lessonId: string;
lessonTitle: string;
courseTitle: string;
displayName: string | null;
codeSnippet: string;
mastery: ShareMastery;
timeSpentMs: number;
attemptCount: number;
viewCount: number;
url: string;
ogImageUrl: string | null;
ogStoryImageUrl: string | null;
createdAt: string;
updatedAt: string;
rotatedAt: string | null;
revision: number;
}
// Phase 21A: saved tutor messages.
export interface SavedTutorMessage {
id: string;
courseId: string | null;
lessonId: string | null;
exerciseId: string | null;
messageId: string;
role: "assistant";
content: string;
sections: Record<string, unknown> | null;
model: string | null;