import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { AppShell } from "../components/shell/AppShell"; import { Badge, Button, Field, Icon, Input, Kicker, Panel, surfaceClassName, type IconName, } from "../components/ui"; import { roleLabel, useAuth } from "../lib/auth"; import { adminApi, adminEngineApi, apiUrl, userApi, type AdminHealthResponse, type AdminEngineConfigResponse, type EngineCapabilitiesResponse, type NotificationPreferences, type UserPreferencesResponse, type UserProfileResponse, type UserSupportTicketListItem, type UserSupportTicketsResponse, type VoicePresetResponse, } from "../lib/api"; import { readInitialTheme } from "../lib/theme"; import { Toggle } from "./settings/Toggle"; import { useTheme } from "../lib/useTheme"; import "./settings/settings.css"; interface NavItem { id: string; label: string; icon: IconName; adminOnly?: boolean; } const ENGINE_MODE_LABEL: Record = { claude_cli: "Claude CLI 게이트웨이", messages_api: "클라우드 연결", claude_api: "Anthropic API", codex_cli: "Codex CLI 게이트웨이", agy_cli: "Agy CLI 게이트웨이", openai: "OpenAI 호환", solar: "Solar", }; const ENGINE_MODES = [ "claude_cli", "claude_api", "codex_cli", "agy_cli", "openai", "solar", ] as const; const TICKET_STATUS_LABEL: Record = { open: "접수", triaged: "분류됨", in_progress: "처리 중", resolved: "해결", closed: "종료", }; const TICKET_CATEGORY_LABEL: Record = { account_access: "계정", session_review: "회기 리뷰", voice_browser: "음성·브라우저", content_scenario: "콘텐츠", safety: "안전", other: "기타", }; const TICKET_PRIORITY_LABEL: Record = { low: "낮음", normal: "보통", high: "높음", urgent: "긴급", }; function SpeakerIcon({ size = 15 }: { size?: number }) { return ( ); } function healthStatusLabel(status: string | undefined): string { if (status === "ok") return "정상"; if (status === "degraded") return "제한 운영"; if (status === "down") return "중단"; return "확인 중"; } function ticketStatusTone(status: UserSupportTicketListItem["status"]) { if (status === "resolved" || status === "closed") return "pos"; if (status === "in_progress" || status === "triaged") return "info"; return "warn"; } function formatTicketDate(value?: number | null): string { if (!value) return "-"; return new Intl.DateTimeFormat("ko-KR", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }).format(new Date(value * 1000)); } /** 동의 시각 표기 — 감사 추적을 위해 연도까지 포함한다. */ function formatConsentDate(value?: number | null): string { if (!value) return "-"; return new Intl.DateTimeFormat("ko-KR", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }).format(new Date(value * 1000)); } function SettingsLoadingState({ children, testId, }: { children: string; testId: string; }) { return (
); } /** * 로딩 스켈레톤 — 회색 박스 반복 대신 섹션 형태(라벨/행 윤곽)를 미리 그려 * 미완성·오류로 오인되지 않게 한다. 로딩 testId·role 은 그대로 유지한다. */ function SettingsSkeleton({ children, testId, variant = "lines", }: { children: string; testId: string; variant?: "lines" | "rows" | "voice"; }) { return (
{children} {variant === "rows" ? ( <>
); } const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = { session_done: true, safety_signal: true, learner_progress: true, account_approval: true, product_news: false, }; function completeNotificationPreferences( preferences?: NotificationPreferences | null, ): NotificationPreferences { return { ...DEFAULT_NOTIFICATION_PREFERENCES, ...preferences, }; } export default function Settings() { const { user, refresh, acceptConsent, withdrawConsent } = useAuth(); const role = user?.role ?? "learner"; const isAdmin = role === "admin"; const [dark, setDark] = useTheme(); const [activeSection, setActiveSection] = useState("account"); // goSection의 스무스 스크롤 동안 IntersectionObserver가 활성 섹션을 되돌리지 않게 억제한다. const spySuppressUntilRef = useRef(0); const [profile, setProfile] = useState(null); const [displayName, setDisplayName] = useState(user?.name ?? ""); const [affiliation, setAffiliation] = useState(""); const [preferences, setPreferences] = useState(null); const [supportTickets, setSupportTickets] = useState(null); const [voicePresets, setVoicePresets] = useState([]); const [engineConfig, setEngineConfig] = useState(null); const [engineCapabilities, setEngineCapabilities] = useState(null); const [engineCapabilitiesLoading, setEngineCapabilitiesLoading] = useState(false); const [engineCapabilitiesError, setEngineCapabilitiesError] = useState(null); const [adminHealth, setAdminHealth] = useState(null); const [profileReady, setProfileReady] = useState(false); const [preferencesReady, setPreferencesReady] = useState(false); const [supportTicketsReady, setSupportTicketsReady] = useState(false); const [supportTicketsError, setSupportTicketsError] = useState(null); // 지원 요청 작성 — 접수 목록을 보는 자리에서 새 티켓을 접수한다(POST /users/support-tickets). const [supportComposeOpen, setSupportComposeOpen] = useState(false); const [supportSubject, setSupportSubject] = useState(""); const [supportBody, setSupportBody] = useState(""); const [supportSubmitting, setSupportSubmitting] = useState(false); const [supportComposeError, setSupportComposeError] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [savedKey, setSavedKey] = useState(null); const savedTimer = useRef(null); const displayNameInputRef = useRef(null); const affiliationInputRef = useRef(null); const displayNameValueRef = useRef(user?.name ?? ""); const affiliationValueRef = useRef(""); const displayNameDirtyRef = useRef(false); const affiliationDirtyRef = useRef(false); const engineConfigRef = useRef(null); const engineCapabilityRequestRef = useRef(0); const loadSettingsRequestRef = useRef(0); // 아바타 업로드 — 온보딩과 같은 계약(3MB, PNG/JPEG/WebP)을 설정에서도 쓴다. const avatarInputRef = useRef(null); const [uploadingAvatar, setUploadingAvatar] = useState(false); const [avatarError, setAvatarError] = useState(""); // 실습 동의 관리 — 철회는 인라인 2단계 확인을 거친다. const [consentConfirming, setConsentConfirming] = useState(false); const [consentBusy, setConsentBusy] = useState(false); const [consentWithdrawn, setConsentWithdrawn] = useState(false); const [consentError, setConsentError] = useState(""); const flashSaved = (key: string) => { setSavedKey(key); if (savedTimer.current) window.clearTimeout(savedTimer.current); savedTimer.current = window.setTimeout(() => setSavedKey(null), 2400); }; const submitSupportTicket = async () => { const subject = supportSubject.trim(); const body = supportBody.trim(); if (!subject || !body || supportSubmitting) return; setSupportSubmitting(true); setSupportComposeError(null); try { await userApi.createSupportTicket({ subject, body, category: "other", priority: "normal", source_path: "/settings", }); // 접수 직후 목록을 재조회해 서버 원장의 상태를 그대로 보여준다. const nextTickets = await userApi.supportTickets().catch(() => null); if (nextTickets) { setSupportTickets(nextTickets); setSupportTicketsError(null); } setSupportComposeOpen(false); setSupportSubject(""); setSupportBody(""); flashSaved("support"); } catch (err) { setSupportComposeError( err instanceof Error ? err.message : "지원 요청을 접수하지 못했습니다.", ); } finally { setSupportSubmitting(false); } }; const updateEngineConfig = useCallback((patch: Partial) => { if (!engineConfigRef.current) return; engineConfigRef.current = { ...engineConfigRef.current, ...patch }; setEngineConfig((current) => (current ? { ...current, ...patch } : current)); }, []); const loadEngineCapabilities = useCallback( async ( engineMode: string, engineUrl: string, options: { force?: boolean; applyDefault?: boolean } = {}, ) => { const requestId = ++engineCapabilityRequestRef.current; setEngineCapabilitiesLoading(true); setEngineCapabilitiesError(null); try { const next = await adminEngineApi.capabilities( engineMode, options.force ?? false, engineUrl, ); if (requestId !== engineCapabilityRequestRef.current) return; setEngineCapabilities(next); if (options.applyDefault && next.available && next.default_model) { updateEngineConfig({ model: next.default_model, reasoning_effort: next.default_reasoning_effort, }); } } catch (cause) { if (requestId !== engineCapabilityRequestRef.current) return; setEngineCapabilities(null); setEngineCapabilitiesError( cause instanceof Error ? cause.message : "모델 목록을 불러오지 못했습니다.", ); } finally { if (requestId === engineCapabilityRequestRef.current) { setEngineCapabilitiesLoading(false); } } }, [updateEngineConfig], ); const loadSettings = useCallback(async () => { const requestId = loadSettingsRequestRef.current + 1; loadSettingsRequestRef.current = requestId; engineCapabilityRequestRef.current += 1; setLoading(true); setError(null); setProfileReady(false); setPreferencesReady(false); setSupportTicketsReady(false); setPreferences(null); setSupportTickets(null); setSupportTicketsError(null); setVoicePresets([]); setEngineConfig(null); setEngineCapabilities(null); setEngineCapabilitiesError(null); engineConfigRef.current = null; try { let nextSupportTicketsError: string | null = null; const [nextProfile, nextPrefs, nextTickets, presets, nextEngine] = await Promise.all([ userApi.me(), userApi.preferences(), userApi.supportTickets().catch((err) => { nextSupportTicketsError = err instanceof Error ? err.message : "지원 요청을 불러오지 못했습니다."; return null; }), userApi.voicePresets(), isAdmin ? adminEngineApi.get() : Promise.resolve(null), ]); if (loadSettingsRequestRef.current !== requestId) return; setProfile(nextProfile); setProfileReady(true); if (!displayNameDirtyRef.current) { setDisplayName(nextProfile.display_name); displayNameValueRef.current = nextProfile.display_name; } if (!affiliationDirtyRef.current) { setAffiliation(nextProfile.affiliation); affiliationValueRef.current = nextProfile.affiliation; } setPreferences(nextPrefs); setPreferencesReady(true); setSupportTickets(nextTickets); setSupportTicketsError(nextSupportTicketsError); setSupportTicketsReady(true); setDark(nextPrefs.theme === "dark" || (nextPrefs.theme !== "light" && readInitialTheme() === "dark")); setVoicePresets(presets); if (nextEngine) { engineConfigRef.current = nextEngine; setEngineConfig(nextEngine); await loadEngineCapabilities(nextEngine.engine_mode, nextEngine.engine_url); } if (isAdmin) { void adminApi.health() .then((health) => { if (loadSettingsRequestRef.current === requestId) setAdminHealth(health); }) .catch(() => { if (loadSettingsRequestRef.current === requestId) setAdminHealth(null); }); } } catch (err) { if (loadSettingsRequestRef.current !== requestId) return; setError(err instanceof Error ? err.message : "설정을 불러오지 못했습니다."); } finally { if (loadSettingsRequestRef.current === requestId) setLoading(false); } }, [isAdmin, loadEngineCapabilities, setDark]); useEffect(() => { void loadSettings(); return () => { loadSettingsRequestRef.current += 1; }; }, [loadSettings]); useEffect(() => { document.body.dataset.page = "settings"; return () => { delete document.body.dataset.page; }; }, []); const navItems: NavItem[] = useMemo(() => { const base: NavItem[] = [ { id: "account", label: "계정", icon: "users" }, { id: "support", label: "지원 요청", icon: "review" }, { id: "consent", label: "동의", icon: "check" }, { id: "appearance", label: "테마", icon: "settings" }, { id: "notify", label: "알림", icon: "info" }, { id: "voice", label: "음성", icon: "mic" }, ]; if (isAdmin) { base.splice(1, 0, { id: "engine", label: "AI 운영", icon: "shield", adminOnly: true }); } return base; }, [isAdmin]); useEffect(() => { // 활성 규칙: 뷰포트 상단 18~38% 밴드에 걸친 섹션 중 가장 아래(=방금 지나친 헤딩). // 비율 우세 방식은 scroll-margin 정렬 지점이 밴드 하단 근처인 모바일에서 // 직전 섹션이 계속 이겨 마지막 섹션이 활성화되지 않는다(결함 로그 #17). const pickActiveSection = () => { const bandTop = window.innerHeight * 0.18; const bandBottom = window.innerHeight * 0.38; let winner: { id: string; top: number } | null = null; for (const item of navItems) { const section = document.getElementById(`set-${item.id}`); if (!section) continue; const rect = section.getBoundingClientRect(); if (rect.top > bandBottom || rect.bottom < bandTop) continue; if (!winner || rect.top > winner.top) { winner = { id: item.id, top: rect.top }; } } if (winner) setActiveSection(winner.id); }; const observer = new IntersectionObserver( () => { if (Date.now() < spySuppressUntilRef.current) return; pickActiveSection(); }, { rootMargin: "-18% 0px -62% 0px", // 0 임계값이 없으면 긴 섹션(모바일)은 밴드 대비 비율이 0.2에 못 미쳐 // 콜백이 아예 오지 않는다(결함 로그 #17). threshold: [0, 0.2, 0.55], }, ); for (const item of navItems) { const section = document.getElementById(`set-${item.id}`); if (section) observer.observe(section); } // 마지막 섹션은 짧은 뷰포트에서 활성 밴드(18~38%)에 도달하지 못한다. // 스크롤 컨테이너가 바닥에 닿으면 마지막 섹션을 활성으로 처리한다(결함 로그 #17). const scroller = document.querySelector(".vg-main"); const onScroll = () => { if (!scroller || Date.now() < spySuppressUntilRef.current) return; if (scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 4) { const last = navItems[navItems.length - 1]; if (last) setActiveSection(last.id); } }; scroller?.addEventListener("scroll", onScroll, { passive: true }); return () => { observer.disconnect(); scroller?.removeEventListener("scroll", onScroll); }; }, [navItems]); const visibleNotifications = useMemo( () => [ { id: "session_done", label: "세션 완료", hint: "학습 회기가 종료되면 알려줍니다.", }, { id: "safety_signal", label: "안전 신호", hint: "위기 신호가 감지되면 우선 알림을 표시합니다.", }, { id: "learner_progress", label: "담당 학습자 진행", hint: "교수자와 관리자에게만 표시됩니다.", roles: ["teacher", "admin"], }, { id: "account_approval", label: "가입 승인", hint: "신규 가입 승인 요청이 있으면 알려줍니다.", roles: ["admin"], }, { id: "product_news", label: "제품 소식", hint: "기능 변경과 연구 운영 공지를 받습니다.", }, ].filter((item) => !item.roles || item.roles.includes(role)), [role], ); const goSection = (id: string) => { spySuppressUntilRef.current = Date.now() + 900; setActiveSection(id); document.getElementById(`set-${id}`)?.scrollIntoView({ behavior: "smooth", block: "start" }); }; const saveProfile = async () => { if (!profileReady) return; const next = await userApi.updateMe({ display_name: displayNameValueRef.current, affiliation: affiliationValueRef.current, }); setProfile(next); setDisplayName(next.display_name); setAffiliation(next.affiliation); displayNameValueRef.current = next.display_name; affiliationValueRef.current = next.affiliation; displayNameDirtyRef.current = false; affiliationDirtyRef.current = false; flashSaved("account"); }; /** 아바타 업로드 → PATCH /users/me 저장 → 톱바·레일 아바타 갱신. */ const uploadAvatar = async (file: File | null) => { if (!file || uploadingAvatar) return; setUploadingAvatar(true); setAvatarError(""); try { const uploaded = await userApi.uploadAvatar(file); const next = await userApi.updateMe({ avatar_url: uploaded.avatar_url }); setProfile(next); await refresh(); flashSaved("account"); } catch (err) { console.warn("[settings] avatar upload failed", err); setAvatarError("아바타 업로드에 실패했습니다. PNG, JPG, WebP 파일을 3MB 이하로 올려 주세요."); } finally { setUploadingAvatar(false); } }; /** 실습 동의 철회 확정 — DELETE /auth/consent, learner 전용. */ const confirmWithdrawConsent = async () => { if (consentBusy) return; setConsentBusy(true); setConsentError(""); try { await withdrawConsent(); setConsentWithdrawn(true); setConsentConfirming(false); } catch (err) { console.warn("[settings] consent withdraw failed", err); setConsentError(err instanceof Error ? err.message : "실습 동의 철회에 실패했습니다."); } finally { setConsentBusy(false); } }; /** 실습 동의 재동의 — POST /auth/consent, 회기 시작 화면과 같은 계약. */ const reacceptConsent = async () => { if (consentBusy) return; setConsentBusy(true); setConsentError(""); try { await acceptConsent(); setConsentWithdrawn(false); } catch (err) { console.warn("[settings] consent accept failed", err); setConsentError(err instanceof Error ? err.message : "실습 동의 저장에 실패했습니다."); } finally { setConsentBusy(false); } }; const savePreferences = async (key: string) => { if (!preferencesReady || !preferences) return; const notifications = completeNotificationPreferences(preferences.notifications); const next = await userApi.updatePreferences({ theme: dark ? "dark" : "light", voice_preset_id: preferences.voice_preset_id, voice_rate: preferences.voice_rate, notifications, }); setPreferences(next); flashSaved(key); }; const saveEngine = async () => { const currentEngine = engineConfigRef.current; if (!currentEngine) return; const next = await adminEngineApi.update({ engine_mode: currentEngine.engine_mode, engine_url: currentEngine.engine_url, model: currentEngine.model, reasoning_effort: currentEngine.reasoning_effort, }); engineConfigRef.current = next; setEngineConfig(next); try { setAdminHealth(await adminApi.health()); } catch { setAdminHealth(null); } flashSaved("engine"); }; const updateNotification = (key: keyof NotificationPreferences, value: boolean) => { setPreferences((cur) => cur ? ({ ...cur, notifications: { ...completeNotificationPreferences(cur.notifications), [key]: value, }, }) : cur); }; const accountName = displayName || profile?.email || user?.name || user?.email || "사용자"; const accountEmail = profile?.email ?? user?.email ?? ""; const initials = accountName.trim().slice(0, 1).toUpperCase(); // 프로필이 먼저 도착하면 프로필 값을, 아니면 auth 스토어의 절대화된 URL을 쓴다. const avatarSrc = profile?.avatar_url ? apiUrl(profile.avatar_url) : user?.avatarUrl ?? ""; const isLearner = role === "learner"; const consentAt = user?.consentAt ?? null; const engineModels = engineCapabilities?.models ?? []; const selectedEngineModel = engineModels.find((model) => model.id === engineConfig?.model); const selectedEngineEfforts = selectedEngineModel?.reasoning_efforts ?? []; const engineHasRequiredFields = Boolean( engineConfig && engineConfig.engine_url.trim().length > 0 && engineCapabilities?.available && selectedEngineModel && (!engineConfig.reasoning_effort || selectedEngineEfforts.includes(engineConfig.reasoning_effort)), ); const engineStorageLabel = !engineConfig ? "확인 중" : engineConfig.durable ? "DB 저장" : "런타임 적용"; const engineService = adminHealth?.services.find((service) => service.key === "engine"); const engineServiceStatus = engineService?.status ?? "degraded"; const notificationPreferences = completeNotificationPreferences(preferences?.notifications); return ( {error ? (
{error}
) : null}
계정
로그인 계정과 표시 정보를 관리합니다.
{accountName}
{accountEmail}
{roleLabel(role)} {affiliation ? {affiliation} : null}
{avatarError ? (
) : null}
표시 이름 교수자와 운영자가 확인하는 이름입니다.
{ displayNameDirtyRef.current = true; displayNameValueRef.current = event.target.value; setDisplayName(event.target.value); }} placeholder="표시할 이름을 입력하세요" aria-label="표시 이름" />
이메일 로그인으로 확인된 주소입니다.
소속 강의나 연구 운영에서 표시할 소속입니다.
{ affiliationDirtyRef.current = true; affiliationValueRef.current = event.target.value; setAffiliation(event.target.value); }} placeholder="소속을 입력하세요" aria-label="소속" />
{savedKey === "account" ? ( 저장됨 ) : null}
{/* 숨은 아바타 file input — 계정 텍스트 입력들의 DOM 순서(0=표시 이름)를 흔들지 않도록 섹션 마지막에 둔다. 버튼이 ref 로 클릭을 위임한다. */} { void uploadAvatar(event.currentTarget.files?.[0] ?? null); event.currentTarget.value = ""; }} />
지원 요청
내가 접수한 운영 티켓의 처리 상태와 해결 메모입니다.
{supportTickets ? ( {supportTickets.tickets.length}건 ) : null}
{supportComposeOpen ? (
setSupportSubject(event.target.value)} />