회기 무발화 0턴 분리, 자기예측 락 불변식 및 TDD 회귀 검증 완료
Some checks failed
API contract / OpenAPI type drift (push) Failing after 3m27s

This commit is contained in:
Yun Chan 2026-09-08 23:28:06 +09:00
parent a479db7a5a
commit a0311c5957
100 changed files with 4884 additions and 11210 deletions

View file

@ -0,0 +1,280 @@
import type { AvatarAffect, AvatarPersona, AvatarState } from "../../components/avatar/ClientAvatar";
import type {
LiveCoachQuota,
PersonaSummary,
SessionDetailResponse,
SessionStage,
} from "../../lib/api";
import { clamp01 } from "../../lib/format";
import {
DIFFICULTY_LABEL,
PENDING_PERSONA_AVATAR_APPEARANCE,
personaAvatarAppearance,
personaBaselineExpression,
personaMeta,
personaTheoryLabel,
shortPersonaName,
} from "../../lib/personaViewModel";
export type FeedbackMode = "immersive" | "ambient" | "coached";
export type TheoryMode = "humanistic" | "cbt" | "integrative";
export type Speaker = "client" | "learner";
export type SignalTone = "pos" | "warn" | "neutral";
export interface Utterance {
id: number;
speaker: Speaker;
text: string;
turnSeq?: number;
/** 발화 시작 시점(세션 경과 초) */
at: number;
/** 진행 중(스트리밍/타이핑) 발화 여부 */
partial?: boolean;
/** 음성 WebSocket이 reply 전에 실패해 DB 턴으로 확정되지 않은 발화 */
failed?: boolean;
/** 실시간 음성 전사의 현재 확정 단계 */
voiceTranscriptState?: "interim" | "finalizing";
}
export interface PhaseInfo {
key: SessionStage;
desc: string;
}
export interface ClientContext {
initial: string;
name: string;
meta: string;
rows: { l: string; v: string }[];
chips: { t: string; clay: boolean }[];
}
export const AI_VOICE_DISCLOSURE =
"내담자 음성은 AI가 생성한 합성 음성이며 사람의 목소리가 아닙니다.";
export const SESSION_PHASES: PhaseInfo[] = [
{ key: "라포", desc: "첫 인사와 안전감 형성" },
{ key: "탐색", desc: "호소 문제와 일상을 함께 이해" },
{ key: "개입", desc: "감정과 생각을 다루는 기법 적용" },
{ key: "정리", desc: "오늘의 대화 정리와 다음 약속" },
];
export function primaryGoalActionLabel(goal: SessionStage): string {
const lastCode = goal.charCodeAt(goal.length - 1);
const hasFinalConsonant =
lastCode >= 0xac00 && lastCode <= 0xd7a3 && (lastCode - 0xac00) % 28 !== 0;
return `${goal}${hasFinalConsonant ? "을" : "를"} 핵심 초점으로 설정`;
}
export const THEORY_MODE_OPTIONS: {
value: TheoryMode;
label: string;
detail: string;
focus: string;
}[] = [
{
value: "humanistic",
label: "인간중심",
detail: "공감·반영",
focus: "감정과 욕구를 반영한 뒤 열린 질문으로 이어갑니다.",
},
{
value: "cbt",
label: "CBT",
detail: "생각·행동",
focus: "상황·생각·감정·행동의 연결을 한 단계씩 확인합니다.",
},
{
value: "integrative",
label: "통합",
detail: "혼합 접근",
focus: "공감적 반영을 먼저 두고 필요한 지점만 구조화합니다.",
},
];
export const DEFAULT_COACH_QUOTA: LiveCoachQuota = { remaining: 3, max: 3 };
export function preferredTheoryMode(summary: PersonaSummary | null): TheoryMode {
const firstSupported = summary?.theory_target.find(
(target): target is TheoryMode =>
target === "humanistic" || target === "cbt" || target === "integrative",
);
return firstSupported ?? "humanistic";
}
export function normalizePersonaCode(raw?: string): string {
return (raw ?? "").trim().toUpperCase();
}
export function looksLikeSessionId(raw?: string): boolean {
const value = (raw ?? "").trim();
return (
/^[0-9a-f]{32}$/i.test(value) ||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
);
}
export function secondsBetween(startedAt: string, createdAt: string): number {
const start = Date.parse(startedAt);
const created = Date.parse(createdAt);
if (!Number.isFinite(start) || !Number.isFinite(created)) return 0;
return Math.max(0, Math.round((created - start) / 1000));
}
export function elapsedFromSession(detail: SessionDetailResponse): number {
const start = Date.parse(detail.started_at);
const end = detail.ended_at ? Date.parse(detail.ended_at) : Date.now();
if (!Number.isFinite(start) || !Number.isFinite(end)) return 0;
return Math.max(0, Math.round((end - start) / 1000));
}
export function buildPersonaUi(
summary: PersonaSummary | null,
code: string,
): { avatar: AvatarPersona; context: ClientContext } {
if (!summary) {
return {
avatar: {
label: "내담자 정보 확인 중",
...PENDING_PERSONA_AVATAR_APPEARANCE,
realism: 0.3,
},
context: {
initial: "?",
name: "내담자 확인 중",
meta: code ? `${code} · DB 카탈로그 확인 중` : "DB 카탈로그 확인 중",
rows: [{ l: "상태", v: "실제 연습 대상 정보를 확인하고 있습니다." }],
chips: [],
},
};
}
const name = shortPersonaName(summary.display_name);
const difficulty = DIFFICULTY_LABEL[summary.difficulty] ?? summary.difficulty;
const theories = summary.theory_target.length
? summary.theory_target.map(personaTheoryLabel).join(" · ")
: "공통";
const chips = [
{ t: summary.code, clay: false },
{ t: difficulty, clay: summary.difficulty === "hard" },
...summary.theory_target.slice(0, 2).map((target) => ({
t: personaTheoryLabel(target),
clay: false,
})),
];
return {
avatar: {
code: summary.code,
label: `${name} · ${personaMeta(summary)}`,
...personaAvatarAppearance(summary),
},
context: {
initial: name.slice(0, 1) || summary.code.slice(0, 1),
name,
meta: personaMeta(summary),
rows: [
{ l: "호소", v: summary.presenting_summary || "요약 정보 없음" },
{ l: "대상", v: theories },
{ l: "난도", v: difficulty },
],
chips,
},
};
}
export function splitMetaLines(meta: string): string[] {
const parts = meta
.split("·")
.map((part) => part.trim())
.filter(Boolean);
if (parts.length <= 2) return [meta];
const lines: string[] = [];
for (let i = 0; i < parts.length; i += 2) {
lines.push(parts.slice(i, i + 2).join(" · "));
}
return lines;
}
// 백엔드가 반환한 effective_openness(0~1)를 실시간 관찰 신호로만 변환한다.
// 점수/정밀 평가는 회기 종료 후 리뷰 화면에서 다룬다.
export function metersFromOpenness(openness: number) {
const o = clamp01(openness);
return {
rapport: o, // 마음 열림(라포)
resistance: clamp01(1 - o * 0.9), // 저항감(반비례)
anxiety: clamp01(0.7 - o * 0.4), // 불안·위축(완만히 감소)
};
}
export function baselineExpressionFor(summary: PersonaSummary | null): AvatarAffect {
return personaBaselineExpression(summary);
}
export function expressionForSession({
state,
openness,
paused,
safety,
summary,
stage,
}: {
state: AvatarState;
openness: number;
paused: boolean;
safety: string | null;
summary: PersonaSummary | null;
stage: SessionStage;
}): AvatarAffect {
const o = clamp01(openness);
const code = summary?.code.toUpperCase() ?? "";
const baseline = baselineExpressionFor(summary);
if (safety) return "startled";
if (paused) return "tired";
if (state === "thinking") {
if (code === "P4" && o < 0.38) return "anxious";
if (code === "P6") return o < 0.55 ? "conflicted" : "determined";
if (code === "P7") return o < 0.45 ? "overwhelmed" : "tired";
if (o < 0.32) return "guarded";
return "confused";
}
if (state === "listening") {
if (o < 0.28) return code === "P4" ? "panic" : "guarded";
if (o < 0.48) return baseline === "tired" ? "bored" : baseline;
if (o > 0.72) return "warm";
return "calm";
}
if (state === "speaking") {
if (o < 0.22) return code === "P7" ? "bored" : "resistant";
if (o < 0.38) return code === "P5" ? "skeptical" : baseline;
if (stage === "정리") return "relief";
if (o > 0.78) return "hopeful";
if (o > 0.62) return "warm";
return "neutral";
}
if (o < 0.3) return baseline;
if (o > 0.76) return "relief";
return "neutral";
}
export function formatCoachTimestamp(value: string | null | undefined) {
if (!value) return "방금";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "방금";
const now = new Date();
const sameDay =
date.getFullYear() === now.getFullYear() &&
date.getMonth() === now.getMonth() &&
date.getDate() === now.getDate();
return new Intl.DateTimeFormat("ko-KR", {
month: sameDay ? undefined : "numeric",
day: sameDay ? undefined : "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}