/* ===================================================================== Vignette — API 클라이언트 (fetch wrapper + SSE 헬퍼) 백엔드 계약: apps/api/app/routes (auth.py, sessions.py). - 모든 요청은 credentials:"include" (BFF __Host-vignette_sid HttpOnly 쿠키). - 에러는 ApiError 로 표준화. - SSE: POST /sessions/{id}/stream 의 token/done/ping/error 이벤트를 콜백으로 전달. ===================================================================== */ // Vite 환경변수. 기본 "/api" (vite proxy 또는 nginx 가 백엔드로 라우팅). function defaultApiBase(): string { if (typeof window !== "undefined") { const host = window.location.hostname; if (host === "vignette.chanpaca.net" || host.endsWith(".pages.dev")) { return "https://api-vignette.chanpaca.net"; } } return "/api"; } const configuredApiBase = (import.meta.env.VITE_API_BASE as string | undefined)?.trim(); const API_BASE: string = configuredApiBase || defaultApiBase(); export class ApiError extends Error { readonly status: number; readonly detail: string; readonly body: unknown; constructor(status: number, detail: string, body?: unknown) { super(`API ${status}: ${detail}`); this.name = "ApiError"; this.status = status; this.detail = detail; this.body = body; } } type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; interface RequestOptions { method?: HttpMethod; /** JSON 직렬화될 요청 바디 */ body?: unknown; /** 추가 헤더 */ headers?: Record; /** AbortSignal (취소·타임아웃) */ signal?: AbortSignal; } function joinUrl(path: string): string { if (/^https?:\/\//.test(path)) return path; const base = API_BASE.replace(/\/$/, ""); const p = path.startsWith("/") ? path : `/${path}`; return `${base}${p}`; } export function apiUrl(path: string): string { return joinUrl(path); } export function apiWsUrl(path: string): string { const url = new URL(joinUrl(path), window.location.origin); url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; return url.toString(); } async function parseError(res: Response): Promise { let detail = res.statusText || "request failed"; let body: unknown = undefined; try { const ct = res.headers.get("content-type") ?? ""; if (ct.includes("application/json")) { body = await res.json(); // FastAPI 표준 에러는 { detail: ... } const d = (body as { detail?: unknown }).detail; if (typeof d === "string") detail = d; else if (d != null) detail = JSON.stringify(d); } else { const text = await res.text(); if (text) detail = text; body = text; } } catch { /* 본문 파싱 실패는 무시하고 statusText 사용 */ } return new ApiError(res.status, detail, body); } /** * JSON API 호출. 2xx 가 아니면 ApiError throw. * 204/빈 응답은 undefined 반환. */ export async function apiFetch( path: string, options: RequestOptions = {}, ): Promise { const { method = "GET", body, headers = {}, signal } = options; const finalHeaders: Record = { Accept: "application/json", ...headers, }; const init: RequestInit = { method, credentials: "include", // __Host-vignette_sid 쿠키 전송 (BFF) signal, }; if (body !== undefined) { finalHeaders["Content-Type"] = "application/json"; init.body = JSON.stringify(body); } init.headers = finalHeaders; const res = await fetch(joinUrl(path), init); if (!res.ok) { throw await parseError(res); } if (res.status === 204) return undefined as T; const ct = res.headers.get("content-type") ?? ""; if (!ct.includes("application/json")) { return (await res.text()) as unknown as T; } const len = res.headers.get("content-length"); if (len === "0") return undefined as T; return (await res.json()) as T; } export const api = { get: (path: string, opts?: Omit) => apiFetch(path, { ...opts, method: "GET" }), post: (path: string, body?: unknown, opts?: Omit) => apiFetch(path, { ...opts, method: "POST", body }), put: (path: string, body?: unknown, opts?: Omit) => apiFetch(path, { ...opts, method: "PUT", body }), del: (path: string, opts?: Omit) => apiFetch(path, { ...opts, method: "DELETE" }), }; /* ===================================================================== 백엔드 응답 타입 (apps/api 계약 미러) ===================================================================== */ /** GET /auth/me — auth.py MeResponse */ export interface MeResponse { user_id: string; email: string; display_name: string; role: string; // "learner" | "teacher" | "admin" cohort_ids: string[]; } export interface AuthConfigResponse { google_oauth_configured: boolean; allowed_email_domains: string[]; redirect_uri: string; dev_login_enabled: boolean; } export const authApi = { config: () => api.get("/auth/config"), }; export type SessionStage = "라포" | "탐색" | "개입" | "정리"; /** GET /personas — personas.py PersonaSummary */ export interface PersonaSummary { code: string; display_name: string; difficulty: "easy" | "moderate" | "hard" | string; theory_target: string[]; demographics: Record; presenting_summary: string; voice_preset: string | null; source: string; degraded: boolean; } /** POST /sessions — sessions.py SessionStartResponse */ export interface SessionStartResponse { session_id: string; case_id: string; session_no: number; stage: SessionStage; effective_openness: number; recall_summary: string | null; degraded: boolean; } /** POST /sessions/{id}/turn — sessions.py TurnResponse */ export interface TurnResponse { turn_seq: number; stage: SessionStage; effective_openness: number; client_reply: string | null; safety_flagged: boolean; } /** POST /sessions/{id}/end — sessions.py SessionEndResponse */ export interface SessionEndResponse { session_id: string; session_no: number; digest_pending: boolean; } export interface LearnerSessionSummary { session_id: string; persona_code: string; persona_name: string; session_no: number; status: "active" | "ended"; stage: string; turn_count: number; learner_turn_count: number; client_turn_count: number; started_at: string; ended_at: string | null; review_ready: boolean; } export interface LearnerSessionsResponse { source: string; sessions: LearnerSessionSummary[]; } export interface SessionDetailTurn { turn_seq: number; speaker: "learner" | "client"; stage: string; text: string; created_at: string; } export interface SessionDetailResponse { session_id: string; case_id: string; persona_code: string; persona_name: string; theory_mode: string; status: "active" | "ended"; stage: SessionStage; effective_openness: number; started_at: string; ended_at: string | null; turns: SessionDetailTurn[]; review_ready: boolean; } export interface ReviewClient { name: string; initial: string; persona: string; } export interface ReviewTechnique { kind: string; label: string; } export interface ReviewNote { author: "ai" | "instructor" | string; tone: "good" | "watch"; title: string; body: string; quote?: string | null; } export interface ReviewTurn { id: string; ts: string; speaker: "learner" | "client"; who: string; text: string; techniques: ReviewTechnique[]; note?: ReviewNote | null; } export interface ReviewPhaseSegment { key: string; label: string; weight: number; } export interface ReviewValencePoint { t: number; v: number; } export interface ReviewRubricRow { name: string; cluster: string; ratio: number; quality: "good" | "watch"; freq: string; } export interface ReviewPoint { title: string; body: string; jumpTo?: string | null; } export interface SessionReviewResponse { session_id: string; client: ReviewClient; date: string; durationLabel: string; durationSeconds: number; reachedPhase: string; sessionSignal: string; supervisorState: string; supervisorName: string; summary: string; phases: ReviewPhaseSegment[]; phaseAxis: string[]; valenceAxis: string[]; clientValence: ReviewValencePoint[]; counselorBaseline: ReviewValencePoint[]; turns: ReviewTurn[]; rubric: ReviewRubricRow[]; goodMoments: ReviewPoint[]; growthPoints: ReviewPoint[]; nextLine?: string | null; clientFeedback?: string | null; audioUrl?: string | null; pdfExportUrl?: string | null; degraded: boolean; reviewReady: boolean; } /* ===================================================================== SSE 헬퍼 — POST /sessions/{id}/stream 백엔드 이벤트(sse_starlette): "token" | "done" | "ping" | "safety" | "error" 턴 본문이 필요하므로 EventSource 가 아니라 fetch stream 으로 처리한다. ===================================================================== */ export interface SessionStreamHandlers { /** 서버가 요청을 수락했고 learner turn 이 저장 가능한 지점 */ onOpen?: () => void; /** 내담자 AI 토큰 1조각 */ onToken?: (chunk: string) => void; /** 스트림 정상 종료 */ onDone?: (data: SessionStreamDone) => void; /** 안전(위기) 신호 */ onSafety?: (data: unknown) => void; /** 에러 이벤트(백엔드 EngineError) 또는 연결 오류 */ onError?: (err: { detail: string }) => void; /** keep-alive ping (Cloudflare 타임아웃 회피용 heartbeat) */ onPing?: () => void; } export interface SessionStreamDone { session_id: string; stage?: SessionStage; effective_openness?: number; turn_seq?: number; safety_flagged?: boolean; } function safeParse(data: string): unknown { try { return JSON.parse(data); } catch { return data; } } /** * 내담자 AI 응답 SSE 스트림을 실행한다. * 백엔드는 learner turn 을 저장한 뒤 token/done 이벤트를 흘린다. */ export async function openSessionStream( sessionId: string, text: string, handlers: SessionStreamHandlers, ): Promise { const res = await fetch(joinUrl(`/sessions/${encodeURIComponent(sessionId)}/stream`), { method: "POST", credentials: "include", headers: { Accept: "text/event-stream", "Content-Type": "application/json", }, body: JSON.stringify({ text }), }); if (!res.ok) { throw await parseError(res); } if (!res.body) { throw new ApiError(res.status, "스트림 응답 본문이 없습니다."); } handlers.onOpen?.(); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let eventName = "message"; let dataLines: string[] = []; let donePayload: SessionStreamDone | null = null; let streamError: ApiError | null = null; const dispatch = () => { if (!eventName && dataLines.length === 0) return; const data = dataLines.join("\n"); const event = eventName || "message"; eventName = "message"; dataLines = []; if (event === "token") { handlers.onToken?.(data); return; } if (event === "done") { const parsed = safeParse(data || "{}") as Partial; donePayload = { session_id: parsed.session_id ?? sessionId, stage: parsed.stage, effective_openness: parsed.effective_openness, turn_seq: parsed.turn_seq, safety_flagged: parsed.safety_flagged, }; handlers.onDone?.(donePayload); return; } if (event === "safety") { handlers.onSafety?.(safeParse(data || "null")); return; } if (event === "ping") { handlers.onPing?.(); return; } if (event === "error") { const parsed = safeParse(data || "{}") as { detail?: string }; const detail = parsed.detail ?? "stream error"; handlers.onError?.({ detail }); streamError = new ApiError(503, detail, parsed); } }; const processLine = (line: string) => { if (line === "") { dispatch(); return; } if (line.startsWith(":")) return; const idx = line.indexOf(":"); const field = idx === -1 ? line : line.slice(0, idx); const rawValue = idx === -1 ? "" : line.slice(idx + 1); const value = rawValue.startsWith(" ") ? rawValue.slice(1) : rawValue; if (field === "event") eventName = value; else if (field === "data") dataLines.push(value); }; const processBuffer = (final = false) => { const lines = buffer.split(/\r?\n/); buffer = final ? "" : (lines.pop() ?? ""); for (const line of lines) processLine(line.endsWith("\r") ? line.slice(0, -1) : line); if (final && buffer) processLine(buffer); if (final && dataLines.length > 0) dispatch(); }; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); processBuffer(); if (streamError) break; } buffer += decoder.decode(); processBuffer(true); if (streamError) throw streamError; return donePayload ?? { session_id: sessionId }; } /* === 세션 API 헬퍼 (Features 단계 Session 페이지가 사용) === */ export const personaApi = { list: () => api.get("/personas"), }; export const sessionApi = { list: () => api.get("/sessions"), get: (sessionId: string) => api.get(`/sessions/${encodeURIComponent(sessionId)}`), start: (persona_code: string, theory_mode: "humanistic" | "cbt" | "integrative" = "humanistic") => api.post("/sessions", { persona_code, theory_mode }), turn: (sessionId: string, text: string) => api.post(`/sessions/${encodeURIComponent(sessionId)}/turn`, { text }), end: (sessionId: string) => api.post(`/sessions/${encodeURIComponent(sessionId)}/end`), review: (sessionId: string) => api.get(`/sessions/${encodeURIComponent(sessionId)}/review`), stream: openSessionStream, }; export type AdminHealthStatus = "ok" | "degraded" | "down"; export interface AdminServiceHealth { key: string; name: string; status: AdminHealthStatus; detail: string; metric: string; load: number; } export interface AdminHealthResponse { status: AdminHealthStatus; environment: string; engine_mode: string; services: AdminServiceHealth[]; } export const adminApi = { health: () => api.get("/admin/health"), }; export interface AdminManagedUser { user_id: string; email: string; display_name: string; role: "learner" | "teacher" | "admin"; cohort_ids: string[]; affiliation: string; active_sessions: number; created_at: number; last_seen_at: number; source: "database" | "server_session_registry"; } export interface AdminUsersResponse { source: "database" | "server_session_registry"; durable: boolean; users: AdminManagedUser[]; } export type AdminUserCreateRequest = Pick< AdminManagedUser, "email" | "display_name" | "role" | "affiliation" | "cohort_ids" >; export const adminUsersApi = { list: () => api.get("/admin/users"), create: (body: AdminUserCreateRequest) => apiFetch("/admin/users", { method: "POST", body }), update: ( userId: string, body: Partial>, ) => apiFetch(`/admin/users/${encodeURIComponent(userId)}`, { method: "PATCH", body, }), deactivate: (userId: string) => apiFetch<{ ok: boolean; user_id: string }>(`/admin/users/${encodeURIComponent(userId)}`, { method: "DELETE", }), }; export interface TeacherSessionSummary { session_id: string; learner_id: string; learner_label: string; persona_code: string; persona_name: string; session_no: number; status: "active" | "ended" | string; stage: string; turn_count: number; learner_turn_count: number; client_turn_count: number; started_at: string; ended_at: string | null; } export interface TeacherDashboardResponse { source: string; cohort_label: string; total_learners: number; active_sessions: number; ended_sessions: number; pending_reviews: TeacherSessionSummary[]; recent_sessions: TeacherSessionSummary[]; message: string; } export const teacherApi = { dashboard: () => api.get("/teacher/dashboard"), }; export interface UserProfileResponse { user_id: string; email: string; display_name: string; role: RoleString; cohort_ids: string[]; affiliation: string; } export interface NotificationPreferences { session_done: boolean; safety_signal: boolean; learner_progress: boolean; product_news: boolean; } export interface UserPreferencesResponse { theme: "system" | "light" | "dark" | string; voice_preset_id: string; voice_rate: number; notifications: NotificationPreferences; } export interface VoicePresetResponse { id: string; voice_id: string; name: string; desc: string; persona_hint: string; } export type RoleString = "learner" | "teacher" | "admin" | string; export const userApi = { me: () => api.get("/users/me"), updateMe: (body: { display_name?: string; affiliation?: string }) => apiFetch("/users/me", { method: "PATCH", body }), preferences: () => api.get("/users/me/preferences"), updatePreferences: (body: Partial) => apiFetch("/users/me/preferences", { method: "PATCH", body }), voicePresets: () => api.get("/users/me/voice-presets"), }; export interface AdminEngineConfigResponse { engine_mode: string; engine_url: string; model: string; updated_by: string | null; updated_at: number | null; durable: boolean; source: "database" | "runtime_cache" | "runtime_default" | string; } export const adminEngineApi = { get: () => api.get("/admin/engine-config"), update: (body: Partial>) => apiFetch("/admin/engine-config", { method: "PATCH", body }), };