대시보드 이슈 정리 1차
This commit is contained in:
parent
94cc56592f
commit
f472883c31
13 changed files with 592 additions and 311 deletions
|
|
@ -1410,13 +1410,12 @@ async def submit_turn(
|
|||
detail=f"engine unavailable: {exc}",
|
||||
) from exc
|
||||
|
||||
await turn_runtime.record_completed_turn(
|
||||
await turn_runtime.finalize_completed_turn(
|
||||
sess,
|
||||
ctx,
|
||||
result,
|
||||
context_prefix="session",
|
||||
)
|
||||
await turn_runtime.record_safety_event(sess, ctx, result)
|
||||
|
||||
return TurnResponse(
|
||||
turn_seq=result.turn_seq,
|
||||
|
|
@ -1473,13 +1472,12 @@ async def stream_turn(
|
|||
data = {**ev.data, "stage": _stage_label(ctx.state_after.stage)}
|
||||
evaluation = await _evaluate_stream_turn(ctx, final_reply)
|
||||
result = _stream_result_from_done(ctx, final_reply, data, evaluation)
|
||||
await turn_runtime.record_completed_turn(
|
||||
await turn_runtime.finalize_completed_turn(
|
||||
sess,
|
||||
ctx,
|
||||
result,
|
||||
context_prefix="session",
|
||||
)
|
||||
await turn_runtime.record_safety_event(sess, ctx, result)
|
||||
yield {"event": "done", "data": json.dumps(data, ensure_ascii=False)}
|
||||
else:
|
||||
yield {"event": ev.event, "data": json.dumps(ev.data, ensure_ascii=False)}
|
||||
|
|
|
|||
|
|
@ -329,7 +329,7 @@ async def _run_turn_and_speak(
|
|||
reply = result.client_reply or ""
|
||||
# Persist only after the client reply has been generated. A failed AI turn
|
||||
# must not leave a learner-only transcript in review or history.
|
||||
await turn_runtime.record_completed_turn(
|
||||
await turn_runtime.finalize_completed_turn(
|
||||
sess,
|
||||
ctx,
|
||||
result,
|
||||
|
|
@ -347,7 +347,6 @@ async def _run_turn_and_speak(
|
|||
evaluation=result.evaluation,
|
||||
),
|
||||
)
|
||||
await turn_runtime.record_safety_event(sess, ctx, result)
|
||||
|
||||
# Send the final client text before audio playback.
|
||||
await _safe_send_json(
|
||||
|
|
|
|||
226
apps/api/app/test_phase3_artifact_checker.py
Normal file
226
apps/api/app/test_phase3_artifact_checker.py
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
CHECKER_PATH = REPO_ROOT / "scripts" / "check-phase3-artifacts.py"
|
||||
|
||||
spec = importlib.util.spec_from_file_location("phase3_artifact_checker", CHECKER_PATH)
|
||||
assert spec is not None and spec.loader is not None
|
||||
checker = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = checker
|
||||
spec.loader.exec_module(checker)
|
||||
|
||||
|
||||
def write_text(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
class Phase3ArtifactCheckerTests(unittest.TestCase):
|
||||
def make_root(self) -> Path:
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
root = Path(tmp.name)
|
||||
|
||||
write_text(
|
||||
root / "00-intake" / "pilot_roster.csv",
|
||||
"participant_id,cohort_id,consent_version,consent_signed_at,withdrawal_state,enrolled_at\n"
|
||||
"P3-001,phase3,v1,2026-06-27T00:00:00Z,active,2026-06-27T00:00:00Z\n",
|
||||
)
|
||||
write_text(
|
||||
root / "00-intake" / "consent_receipts.csv",
|
||||
"participant_id,consent_version,signed_at,signer_role,receipt_id\n"
|
||||
"P3-001,v1,2026-06-27T00:00:00Z,self,R-001\n",
|
||||
)
|
||||
write_text(
|
||||
root / "01-sessions" / "session_completion.csv",
|
||||
"participant_id,session_id,persona_id,started_at,ended_at,completion_state,turns_count,supervisor_reviewed_at\n"
|
||||
"P3-001,S-001,P1,2026-06-27T00:00:00Z,2026-06-27T00:50:00Z,completed,12,2026-06-27T01:00:00Z\n",
|
||||
)
|
||||
write_text(
|
||||
root / "02-measures" / "prepost_measures.csv",
|
||||
"participant_id,measure_name,timepoint,score,collected_at\n"
|
||||
"P3-001,self_efficacy,pre,3,2026-06-27T00:00:00Z\n"
|
||||
"P3-001,self_efficacy,post,4,2026-06-27T01:00:00Z\n",
|
||||
)
|
||||
write_text(
|
||||
root / "02-measures" / "sus_responses.csv",
|
||||
"participant_id,item,response,collected_at\n"
|
||||
"P3-001,1,5,2026-06-27T01:00:00Z\n",
|
||||
)
|
||||
write_text(
|
||||
root / "04-privacy" / "withdrawal_log.csv",
|
||||
"participant_id,requested_at,effective_at,scope,status,attestation_path\n",
|
||||
)
|
||||
write_text(
|
||||
root / "04-privacy" / "privacy_audit.md",
|
||||
"# Privacy audit\n\nLegal/privacy reviewer: reviewer@example.invalid\n",
|
||||
)
|
||||
write_text(root / "03-export" / "anonymized_dataset.jsonl", "{}\n")
|
||||
|
||||
metrics = {
|
||||
name: {
|
||||
"value": 1,
|
||||
"threshold": 1,
|
||||
"pass": True,
|
||||
"numerator": 1,
|
||||
"denominator": 1,
|
||||
"method": "fixture",
|
||||
"source_files": ["fixture"],
|
||||
}
|
||||
for name in checker.KPI_METRICS
|
||||
}
|
||||
write_text(
|
||||
root / "02-measures" / "kpi_report.json",
|
||||
json.dumps(
|
||||
{
|
||||
"pilot_id": "phase3-fixture",
|
||||
"generated_at": "2026-06-27T00:00:00Z",
|
||||
"source_window": {
|
||||
"started_at": "2026-06-27T00:00:00Z",
|
||||
"ended_at": "2026-06-27T01:00:00Z",
|
||||
},
|
||||
"cohort_size": 1,
|
||||
"metrics": metrics,
|
||||
"exclusions": [],
|
||||
"open_schema_gaps": [],
|
||||
"review": {
|
||||
"operator": "test",
|
||||
"reviewed_at": "2026-06-27T01:00:00Z",
|
||||
"decision": "fixture",
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
dataset_path = root / "03-export" / "anonymized_dataset.jsonl"
|
||||
write_text(
|
||||
root / "03-export" / "export_manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"export_id": "phase3-fixture",
|
||||
"dataset_name": "vignette_phase3_recursive_learning_seed",
|
||||
"export_status": checker.APPROVED_EXPORT_STATUS,
|
||||
"created_at": "2026-06-27T00:00:00Z",
|
||||
"purpose": "test",
|
||||
"source_window": {
|
||||
"started_at": "2026-06-27T00:00:00Z",
|
||||
"ended_at": "2026-06-27T01:00:00Z",
|
||||
},
|
||||
"source_tables": ["app.sessions"],
|
||||
"selection_criteria": {
|
||||
"include_withdrawn": False,
|
||||
"min_completed_sessions": 2,
|
||||
},
|
||||
"consent_scope": {
|
||||
"allowed_uses": ["education_quality_review", "recursive_learning_seed"],
|
||||
"participants_included": 1,
|
||||
"participants_excluded": 0,
|
||||
},
|
||||
"anonymization": {
|
||||
"text_transform": "masked_text_only",
|
||||
"direct_identifier_policy": "blocked",
|
||||
},
|
||||
"pii_scan": {"status": "pass"},
|
||||
"agreement": {"kappa": 0.60, "icc": 0.75},
|
||||
"files": [
|
||||
{
|
||||
"path": "03-export/anonymized_dataset.jsonl",
|
||||
"rows": 1,
|
||||
"sha256": sha256(dataset_path),
|
||||
"schema": "phase3_dataset_item_v1",
|
||||
}
|
||||
],
|
||||
"approvals": {
|
||||
"data_steward": "steward",
|
||||
"legal_or_privacy_reviewer": "privacy",
|
||||
"technical_operator": "operator",
|
||||
"approved_at": "2026-06-27T01:00:00Z",
|
||||
},
|
||||
"known_limitations": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ "\n",
|
||||
)
|
||||
return root
|
||||
|
||||
def test_valid_approved_fixture_passes(self) -> None:
|
||||
root = self.make_root()
|
||||
report = checker.validate(root, max_scan_rows=100)
|
||||
self.assertEqual([], report.errors)
|
||||
|
||||
def test_approved_manifest_requires_privacy_and_agreement_gates(self) -> None:
|
||||
root = self.make_root()
|
||||
manifest_path = root / "03-export" / "export_manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["pii_scan"]["status"] = "pending"
|
||||
manifest["agreement"]["kappa"] = 0.59
|
||||
manifest["agreement"]["icc"] = 0.74
|
||||
manifest["selection_criteria"]["include_withdrawn"] = True
|
||||
manifest["consent_scope"]["allowed_uses"] = ["education_quality_review"]
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
report = checker.validate(root, max_scan_rows=100)
|
||||
|
||||
errors = "\n".join(report.errors)
|
||||
self.assertIn("pii_scan.status='pass'", errors)
|
||||
self.assertIn("agreement.kappa >= 0.60", errors)
|
||||
self.assertIn("agreement.icc >= 0.75", errors)
|
||||
self.assertIn("include_withdrawn=false", errors)
|
||||
self.assertIn("recursive_learning_seed consent scope", errors)
|
||||
|
||||
def test_kpi_metric_required_fields_are_errors(self) -> None:
|
||||
root = self.make_root()
|
||||
report_path = root / "02-measures" / "kpi_report.json"
|
||||
data = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
del data["metrics"]["sus"]["source_files"]
|
||||
report_path.write_text(json.dumps(data), encoding="utf-8")
|
||||
|
||||
report = checker.validate(root, max_scan_rows=100)
|
||||
|
||||
self.assertTrue(
|
||||
any("metric 'sus' missing 'source_files'" in error for error in report.errors),
|
||||
report.errors,
|
||||
)
|
||||
|
||||
def test_csv_enum_values_are_validated(self) -> None:
|
||||
root = self.make_root()
|
||||
write_text(
|
||||
root / "01-sessions" / "session_completion.csv",
|
||||
"participant_id,session_id,persona_id,started_at,ended_at,completion_state,turns_count,supervisor_reviewed_at\n"
|
||||
"P3-001,S-001,P1,2026-06-27T00:00:00Z,2026-06-27T00:50:00Z,done,12,2026-06-27T01:00:00Z\n",
|
||||
)
|
||||
|
||||
report = checker.validate(root, max_scan_rows=100)
|
||||
|
||||
self.assertTrue(
|
||||
any("invalid completion_state 'done'" in error for error in report.errors),
|
||||
report.errors,
|
||||
)
|
||||
|
||||
def test_approved_manifest_hash_must_match_existing_file(self) -> None:
|
||||
root = self.make_root()
|
||||
manifest_path = root / "03-export" / "export_manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
manifest["files"][0]["sha256"] = "0" * 64
|
||||
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
|
||||
|
||||
report = checker.validate(root, max_scan_rows=100)
|
||||
|
||||
self.assertTrue(any("sha256 mismatch" in error for error in report.errors), report.errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -182,9 +182,29 @@ async def record_safety_event(
|
|||
pass
|
||||
|
||||
|
||||
async def finalize_completed_turn(
|
||||
sess: InProcSession,
|
||||
ctx: orchestrator.TurnContext,
|
||||
result: orchestrator.TurnResult,
|
||||
*,
|
||||
context_prefix: str,
|
||||
counselor_turn: TurnRecord | None = None,
|
||||
) -> None:
|
||||
"""Persist a completed turn and emit any derived safety alert in route-safe order."""
|
||||
await record_completed_turn(
|
||||
sess,
|
||||
ctx,
|
||||
result,
|
||||
context_prefix=context_prefix,
|
||||
counselor_turn=counselor_turn,
|
||||
)
|
||||
await record_safety_event(sess, ctx, result)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SessionAccessError",
|
||||
"append_completed_turn",
|
||||
"finalize_completed_turn",
|
||||
"load_owned_session",
|
||||
"record_safety_event",
|
||||
"record_completed_turn",
|
||||
|
|
|
|||
|
|
@ -53,6 +53,32 @@ def _model_arg(args):
|
|||
return args[args.index("--model") + 1]
|
||||
|
||||
|
||||
async def _read_streaming_response(response):
|
||||
chunks = []
|
||||
async for chunk in response.body_iterator:
|
||||
if isinstance(chunk, bytes):
|
||||
chunks.append(chunk.decode("utf-8"))
|
||||
else:
|
||||
chunks.append(str(chunk))
|
||||
return "".join(chunks)
|
||||
|
||||
|
||||
class _FakeStreamSession:
|
||||
def __init__(self, events, model="test-model"):
|
||||
self.events = events
|
||||
self.model = model
|
||||
self.closed = False
|
||||
|
||||
async def turn_stream(self, content, timeout=600.0):
|
||||
self.content = content
|
||||
self.timeout = timeout
|
||||
for event in self.events:
|
||||
yield event
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class GatewayModelTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
gateway.SESSIONS.clear()
|
||||
|
|
@ -212,6 +238,50 @@ class GatewayModelTest(unittest.TestCase):
|
|||
self.assertEqual(closed, [started[0]])
|
||||
self.assertNotIn(started[0].id, gateway.SESSIONS)
|
||||
|
||||
def test_v1_stream_frames_token_and_done_events(self):
|
||||
session = _FakeStreamSession(
|
||||
[
|
||||
{"type": "delta", "text": "안녕"},
|
||||
{"type": "done", "cost_usd": 0.03, "turns": 2},
|
||||
],
|
||||
model="stream-model",
|
||||
)
|
||||
|
||||
async def fake_resolve(req, system_prompt):
|
||||
return session, True
|
||||
|
||||
with patch.object(gateway, "_resolve_session", fake_resolve):
|
||||
response = asyncio.run(gateway.v1_stream(_request()))
|
||||
body = asyncio.run(_read_streaming_response(response))
|
||||
|
||||
self.assertIn("event: token", body)
|
||||
self.assertIn('data: {"text": "안녕"}', body)
|
||||
self.assertIn("event: done", body)
|
||||
self.assertIn('"provider": "claude_cli"', body)
|
||||
self.assertIn('"model": "stream-model"', body)
|
||||
self.assertIn('"cost_usd": 0.03', body)
|
||||
self.assertEqual(session.content, "hello")
|
||||
self.assertEqual(session.timeout, 600.0)
|
||||
self.assertTrue(session.closed)
|
||||
|
||||
def test_v1_stream_frames_engine_error_event(self):
|
||||
session = _FakeStreamSession(
|
||||
[
|
||||
{"type": "done", "is_error": True, "error": "engine failed"},
|
||||
]
|
||||
)
|
||||
|
||||
async def fake_resolve(req, system_prompt):
|
||||
return session, False
|
||||
|
||||
with patch.object(gateway, "_resolve_session", fake_resolve):
|
||||
response = asyncio.run(gateway.v1_stream(_request()))
|
||||
body = asyncio.run(_read_streaming_response(response))
|
||||
|
||||
self.assertIn("event: error", body)
|
||||
self.assertIn('data: {"detail": "engine failed"}', body)
|
||||
self.assertFalse(session.closed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -155,32 +155,9 @@ export const 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[];
|
||||
consent_at: number | null;
|
||||
}
|
||||
|
||||
export interface ConsentResponse {
|
||||
consent_at: number | null;
|
||||
}
|
||||
|
||||
export interface AuthConfigResponse {
|
||||
google_oauth_configured: boolean;
|
||||
saml_configured: boolean;
|
||||
providers: Array<{
|
||||
provider: "google" | "saml";
|
||||
configured: boolean;
|
||||
enabled: boolean;
|
||||
login_path: string;
|
||||
}>;
|
||||
allowed_email_domains: string[];
|
||||
redirect_uri: string;
|
||||
dev_login_enabled: boolean;
|
||||
}
|
||||
export type MeResponse = ApiSchema<"MeResponse">;
|
||||
export type ConsentResponse = ApiSchema<"ConsentResponse">;
|
||||
export type AuthConfigResponse = ApiSchema<"AuthConfigResponse">;
|
||||
|
||||
export const authApi = {
|
||||
config: () => api.get<AuthConfigResponse>("/auth/config"),
|
||||
|
|
@ -191,34 +168,11 @@ export const authApi = {
|
|||
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<string, unknown>;
|
||||
presenting_summary: string;
|
||||
voice_preset: string | null;
|
||||
source: string;
|
||||
degraded: boolean;
|
||||
}
|
||||
export type PersonaSummary = ApiSchema<"PersonaSummary">;
|
||||
|
||||
export type PersonaReviewStatus = "draft" | "review" | "approved" | "archived";
|
||||
export type PersonaReviewAction = "approve" | "reject";
|
||||
|
||||
export interface PersonaReviewSummary {
|
||||
persona_id: string;
|
||||
code: string;
|
||||
version: number;
|
||||
status: PersonaReviewStatus;
|
||||
display_name: string;
|
||||
difficulty: "easy" | "moderate" | "hard" | string;
|
||||
theory_target: string[];
|
||||
source_provenance: string;
|
||||
is_synthetic: boolean;
|
||||
created_at: string | null;
|
||||
approved_at: string | null;
|
||||
}
|
||||
export type PersonaReviewAction = ApiSchema<"PersonaReviewDecisionRequest">["action"];
|
||||
export type PersonaReviewSummary = ApiSchema<"PersonaReviewSummary">;
|
||||
|
||||
export type PersonaDraftPayload = ApiSchema<"PersonaDraftPayload">;
|
||||
export type PersonaDraftDetail = ApiSchema<"PersonaDraftDetail">;
|
||||
|
|
@ -240,39 +194,15 @@ export type TurnResponse = ApiSchema<"TurnResponse">;
|
|||
/** POST /sessions/{id}/end — sessions.py SessionEndResponse */
|
||||
export type SessionEndResponse = ApiSchema<"SessionEndResponse">;
|
||||
|
||||
export interface CrisisResource {
|
||||
title: string;
|
||||
number: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
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 type CrisisResource = ApiSchema<"CrisisResourceResponse">;
|
||||
export type LearnerSessionSummary = ApiSchema<"LearnerSessionSummary">;
|
||||
|
||||
export interface LearnerSessionsResponse {
|
||||
source: string;
|
||||
sessions: LearnerSessionSummary[];
|
||||
}
|
||||
|
||||
export interface SessionDetailTurn {
|
||||
turn_seq: number;
|
||||
speaker: "learner" | "client";
|
||||
stage: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
export type SessionDetailTurn = ApiSchema<"SessionDetailTurn">;
|
||||
|
||||
export interface SessionDetailResponse {
|
||||
session_id: string;
|
||||
|
|
@ -289,30 +219,10 @@ export interface SessionDetailResponse {
|
|||
review_ready: boolean;
|
||||
}
|
||||
|
||||
export interface ReviewClient {
|
||||
name: string;
|
||||
initial: string;
|
||||
persona: string;
|
||||
}
|
||||
|
||||
export interface ReviewTechnique {
|
||||
kind: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ReviewNonverbalEvent {
|
||||
kind: "audio" | "silence" | "pace" | "barge_in";
|
||||
label: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ReviewNote {
|
||||
author: "ai" | "instructor" | string;
|
||||
tone: "good" | "watch";
|
||||
title: string;
|
||||
body: string;
|
||||
quote?: string | null;
|
||||
}
|
||||
export type ReviewClient = ApiSchema<"ReviewClient">;
|
||||
export type ReviewTechnique = ApiSchema<"ReviewTechnique">;
|
||||
export type ReviewNonverbalEvent = ApiSchema<"ReviewNonverbalEvent">;
|
||||
export type ReviewNote = ApiSchema<"ReviewNote">;
|
||||
|
||||
export interface ReviewTurn {
|
||||
id: string;
|
||||
|
|
@ -325,36 +235,11 @@ export interface ReviewTurn {
|
|||
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 ReviewWorksheetEvidence {
|
||||
turnId: string;
|
||||
speaker: "learner" | "client";
|
||||
quote: string;
|
||||
}
|
||||
export type ReviewPhaseSegment = ApiSchema<"ReviewPhaseSegment">;
|
||||
export type ReviewValencePoint = ApiSchema<"ReviewValencePoint">;
|
||||
export type ReviewRubricRow = ApiSchema<"ReviewRubricRow">;
|
||||
export type ReviewPoint = ApiSchema<"ReviewPoint">;
|
||||
export type ReviewWorksheetEvidence = ApiSchema<"ReviewWorksheetEvidence">;
|
||||
|
||||
export interface ReviewWorksheetItem {
|
||||
key: string;
|
||||
|
|
@ -608,82 +493,23 @@ export const sessionApi = {
|
|||
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 interface AdminUsageBreakdown {
|
||||
provider: string;
|
||||
model: string;
|
||||
turns: number;
|
||||
tokens_in: number;
|
||||
tokens_out: number;
|
||||
cost_usd: number;
|
||||
}
|
||||
|
||||
export interface AdminUsageBudget {
|
||||
limit_usd: number;
|
||||
used_ratio: number;
|
||||
remaining_usd: number | null;
|
||||
status: "disabled" | "ok" | "warn" | "exceeded";
|
||||
}
|
||||
|
||||
export interface AdminUsageResponse {
|
||||
source: "database" | "server_session_registry";
|
||||
durable: boolean;
|
||||
window_days: number;
|
||||
generated_at: number;
|
||||
total_turns: number;
|
||||
metered_turns: number;
|
||||
tokens_in: number;
|
||||
tokens_out: number;
|
||||
cost_usd: number;
|
||||
budget: AdminUsageBudget;
|
||||
by_provider: AdminUsageBreakdown[];
|
||||
}
|
||||
export type AdminHealthStatus = ApiSchema<"AdminHealthResponse">["status"];
|
||||
export type AdminServiceHealth = ApiSchema<"AdminServiceHealth">;
|
||||
export type AdminHealthResponse = ApiSchema<"AdminHealthResponse">;
|
||||
export type AdminUsageBreakdown = ApiSchema<"AdminUsageBreakdown">;
|
||||
export type AdminUsageBudget = ApiSchema<"AdminUsageBudget">;
|
||||
export type AdminUsageResponse = ApiSchema<"AdminUsageResponse">;
|
||||
|
||||
export const adminApi = {
|
||||
health: () => api.get<AdminHealthResponse>("/admin/health"),
|
||||
usage: (windowDays = 7) => api.get<AdminUsageResponse>(`/admin/usage?window_days=${windowDays}`),
|
||||
};
|
||||
|
||||
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 type AdminManagedUser = ApiSchema<"AdminUserResponse">;
|
||||
export type AdminUsersResponse = ApiSchema<"AdminUsersResponse">;
|
||||
export type AdminUserCreateRequest = ApiSchema<"AdminUserCreate">;
|
||||
export type AdminUserPatchRequest = ApiSchema<"AdminUserPatch">;
|
||||
export type AdminUserDeleteResponse = ApiSchema<"AdminUserDeleteResponse">;
|
||||
|
||||
export const adminUsersApi = {
|
||||
list: () => api.get<AdminUsersResponse>("/admin/users"),
|
||||
|
|
@ -691,13 +517,13 @@ export const adminUsersApi = {
|
|||
apiFetch<AdminManagedUser>("/admin/users", { method: "POST", body }),
|
||||
update: (
|
||||
userId: string,
|
||||
body: Partial<Pick<AdminManagedUser, "display_name" | "role" | "affiliation" | "cohort_ids">>,
|
||||
body: AdminUserPatchRequest,
|
||||
) => apiFetch<AdminManagedUser>(`/admin/users/${encodeURIComponent(userId)}`, {
|
||||
method: "PATCH",
|
||||
body,
|
||||
}),
|
||||
deactivate: (userId: string) =>
|
||||
apiFetch<{ ok: boolean; user_id: string }>(`/admin/users/${encodeURIComponent(userId)}`, {
|
||||
apiFetch<AdminUserDeleteResponse>(`/admin/users/${encodeURIComponent(userId)}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
};
|
||||
|
|
@ -718,33 +544,8 @@ export interface TeacherSessionSummary {
|
|||
ended_at: string | null;
|
||||
}
|
||||
|
||||
export interface TeacherSafetyAlert {
|
||||
id: string;
|
||||
session_id: string;
|
||||
learner_id: string;
|
||||
learner_label: string;
|
||||
persona_code: string;
|
||||
session_no: number;
|
||||
trigger_type: string;
|
||||
ko_risk_level: number;
|
||||
escalated: boolean;
|
||||
created_at: string;
|
||||
resource_title: string;
|
||||
resource_number: string;
|
||||
}
|
||||
|
||||
export interface TeacherGrowthPoint {
|
||||
session_id: string;
|
||||
session_no: number;
|
||||
persona_code: string;
|
||||
stage: string;
|
||||
started_at: string;
|
||||
ended_at: string | null;
|
||||
score: number | null;
|
||||
rapport: number | null;
|
||||
technique_count: number;
|
||||
watch_count: number;
|
||||
}
|
||||
export type TeacherSafetyAlert = ApiSchema<"TeacherSafetyAlert">;
|
||||
export type TeacherGrowthPoint = ApiSchema<"TeacherGrowthPoint">;
|
||||
|
||||
export interface TeacherLearnerGrowth {
|
||||
learner_id: string;
|
||||
|
|
@ -779,61 +580,30 @@ export const teacherApi = {
|
|||
dashboard: () => api.get<TeacherDashboardResponse>("/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 UserProfileResponse = ApiSchema<"UserProfileResponse">;
|
||||
export type NotificationPreferences = ApiSchema<"NotificationPreferences">;
|
||||
export type UserPreferencesResponse = ApiSchema<"UserPreferencesResponse">;
|
||||
export type UserPreferencesPatchRequest = ApiSchema<"UserPreferencesPatch">;
|
||||
export type UserProfilePatchRequest = ApiSchema<"UserProfilePatch">;
|
||||
export type VoicePresetResponse = ApiSchema<"VoicePresetResponse">;
|
||||
|
||||
export type RoleString = "learner" | "teacher" | "admin" | string;
|
||||
|
||||
export const userApi = {
|
||||
me: () => api.get<UserProfileResponse>("/users/me"),
|
||||
updateMe: (body: { display_name?: string; affiliation?: string }) =>
|
||||
updateMe: (body: UserProfilePatchRequest) =>
|
||||
apiFetch<UserProfileResponse>("/users/me", { method: "PATCH", body }),
|
||||
preferences: () => api.get<UserPreferencesResponse>("/users/me/preferences"),
|
||||
updatePreferences: (body: Partial<UserPreferencesResponse>) =>
|
||||
updatePreferences: (body: UserPreferencesPatchRequest) =>
|
||||
apiFetch<UserPreferencesResponse>("/users/me/preferences", { method: "PATCH", body }),
|
||||
voicePresets: () => api.get<VoicePresetResponse[]>("/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 type AdminEngineConfigResponse = ApiSchema<"AdminEngineConfigResponse">;
|
||||
export type AdminEngineConfigPatchRequest = ApiSchema<"AdminEngineConfigPatch">;
|
||||
|
||||
export const adminEngineApi = {
|
||||
get: () => api.get<AdminEngineConfigResponse>("/admin/engine-config"),
|
||||
update: (body: Partial<Pick<AdminEngineConfigResponse, "engine_mode" | "engine_url" | "model">>) =>
|
||||
update: (body: AdminEngineConfigPatchRequest) =>
|
||||
apiFetch<AdminEngineConfigResponse>("/admin/engine-config", { method: "PATCH", body }),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ import {
|
|||
} from "../lib/api";
|
||||
|
||||
type UserDraft = Pick<AdminManagedUser, "display_name" | "role" | "affiliation" | "cohort_ids">;
|
||||
type NewUserDraft = AdminUserCreateRequest;
|
||||
type NewUserDraft = Required<Pick<AdminUserCreateRequest, "email" | "display_name" | "role">> &
|
||||
Pick<UserDraft, "affiliation" | "cohort_ids">;
|
||||
const MAX_RENDERED_USERS = 40;
|
||||
|
||||
const EMPTY_NEW_USER: NewUserDraft = {
|
||||
|
|
|
|||
|
|
@ -554,7 +554,7 @@ export default function Professor() {
|
|||
<Badge tone={personaReviewTone(persona.status)}>
|
||||
{personaReviewStatusLabel(persona.status)}
|
||||
</Badge>
|
||||
<span>{formatDateTime(persona.created_at)}</span>
|
||||
<span>{formatDateTime(persona.created_at ?? null)}</span>
|
||||
</div>
|
||||
<div className="pf-persona__actions">
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -127,6 +127,22 @@ function SettingsSkeleton({
|
|||
);
|
||||
}
|
||||
|
||||
const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {
|
||||
session_done: true,
|
||||
safety_signal: true,
|
||||
learner_progress: true,
|
||||
product_news: false,
|
||||
};
|
||||
|
||||
function completeNotificationPreferences(
|
||||
preferences?: NotificationPreferences | null,
|
||||
): NotificationPreferences {
|
||||
return {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
...preferences,
|
||||
};
|
||||
}
|
||||
|
||||
export default function Settings() {
|
||||
const { user } = useAuth();
|
||||
const role = user?.role ?? "learner";
|
||||
|
|
@ -313,11 +329,12 @@ export default function Settings() {
|
|||
|
||||
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: preferences.notifications,
|
||||
notifications,
|
||||
});
|
||||
setPreferences(next);
|
||||
flashSaved(key);
|
||||
|
|
@ -348,7 +365,7 @@ export default function Settings() {
|
|||
setPreferences((cur) => cur ? ({
|
||||
...cur,
|
||||
notifications: {
|
||||
...cur.notifications,
|
||||
...completeNotificationPreferences(cur.notifications),
|
||||
[key]: value,
|
||||
},
|
||||
}) : cur);
|
||||
|
|
@ -362,13 +379,12 @@ export default function Settings() {
|
|||
: false;
|
||||
const engineStorageLabel = !engineConfig
|
||||
? "확인 중"
|
||||
: engineConfig.source === "unconfigured"
|
||||
? "미구성"
|
||||
: engineConfig.durable
|
||||
: engineConfig.durable
|
||||
? "DB 저장"
|
||||
: "런타임 적용";
|
||||
const engineService = adminHealth?.services.find((service) => service.key === "engine");
|
||||
const engineServiceStatus = engineService?.status ?? "degraded";
|
||||
const notificationPreferences = completeNotificationPreferences(preferences?.notifications);
|
||||
|
||||
return (
|
||||
<AppShell contextLabel="설정" hideNav hideTopbar bleed>
|
||||
|
|
@ -828,7 +844,7 @@ export default function Settings() {
|
|||
</div>
|
||||
<Toggle
|
||||
checked={Boolean(
|
||||
preferences.notifications[item.id as keyof NotificationPreferences],
|
||||
notificationPreferences[item.id as keyof NotificationPreferences],
|
||||
)}
|
||||
onChange={(next) =>
|
||||
updateNotification(item.id as keyof NotificationPreferences, next)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue