import { expect, test } from "@playwright/test"; import { expectNoDocumentOverflow, expectNoHorizontalOverflow, fetchAvailablePersona, fetchAvailablePersonas, completeOnboarding, signInAsLearner, useRealApi, } from "./support"; async function signInAsLearnerEmail( page: import("@playwright/test").Page, email: string, displayName = "History Learner", ) { const res = await page.request.post("/api/auth/dev-login", { data: { email, role: "learner", display_name: displayName, }, }); expect(res.ok(), await res.text()).toBeTruthy(); await completeOnboarding(page, { legal_name: displayName, affiliation: "한신대학교", department: "상담심리학과", grade_level: "3학년", phone: "010-2222-2222", contact_address: "경기도 오산시 한신대학교", }); } async function createPracticeSession(page: import("@playwright/test").Page, personaCode?: string) { const selectedPersonaCode = personaCode ?? (await fetchAvailablePersona(page)).code; const res = await page.request.post("/api/sessions", { data: { persona_code: selectedPersonaCode, theory_mode: "humanistic", }, }); expect(res.ok(), await res.text()).toBeTruthy(); return (await res.json()) as { session_id: string }; } async function expectNoLearnerInternalCopy(page: import("@playwright/test").Page) { await expect(page.getByText(/API|GET \/|OPENAI_API_KEY|teacher\/dashboard/)).toHaveCount(0); } async function expectVisibleResumeLoadedSignal(page: import("@playwright/test").Page) { const result = await page.evaluate(() => { const candidates = Array.from( document.querySelectorAll( ".sx-page--active .sx-mobile-context__resume, .sx-page--active .sx-mic-block__h", ), ); return candidates.map((el) => { const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return { text: el.textContent ?? "", visible: style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) !== 0 && rect.width > 0 && rect.height > 0, }; }); }); expect( result.some( (entry) => entry.visible && entry.text.includes("이전 회기 기록을 불러왔습니다."), ), `Expected visible resume-loaded signal: ${JSON.stringify(result)}`, ).toBeTruthy(); } async function expectReachableLearnerHomeLayout(page: import("@playwright/test").Page) { await expect(page.locator(".lh-preview__main")).toBeVisible(); await expect(page.locator(".lh-activity")).toBeVisible(); await expect(page.getByRole("button", { name: "새 회기 시작" })).toBeInViewport(); const rootOverflow = await page.locator(".lh-root").evaluate((root) => { const style = window.getComputedStyle(root); return { overflow: style.overflow, overflowY: style.overflowY }; }); expect(rootOverflow.overflow).not.toBe("hidden"); expect(rootOverflow.overflowY).not.toBe("hidden"); await expectNoHorizontalOverflow(page); } async function expectPersonaCardsUseContentHeight(page: import("@playwright/test").Page) { const cards = await page.locator(".lh-persona").evaluateAll((items) => items.map((item) => { const card = item as HTMLElement; const rect = card.getBoundingClientRect(); const summary = card.querySelector(".lh-persona__summary"); const body = card.querySelector(".lh-persona__body"); const textNodes = Array.from( card.querySelectorAll( ".lh-persona__name, .lh-persona__meta, .lh-persona__summary", ), ); const childBottom = Math.max( 0, ...textNodes.map((child) => child.getBoundingClientRect().bottom), ); return { label: (card.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 90), height: Math.ceil(rect.height), bodyOverflow: body ? Math.ceil(body.scrollHeight - body.clientHeight) : 0, childBottomOverflow: Math.ceil(childBottom - rect.bottom), cardScrollOverflow: Math.ceil(card.scrollHeight - card.clientHeight), summaryOverflow: summary ? Math.ceil(summary.scrollHeight - summary.clientHeight) : 0, }; }), ); const offenders = cards.filter( (card) => card.bodyOverflow > 1 || card.childBottomOverflow > 1 || card.cardScrollOverflow > 1 || card.summaryOverflow > 1, ); expect(offenders, `Persona card text should fit its fluid-height card: ${JSON.stringify(cards)}`).toEqual([]); } function learnerActivityHeading(page: import("@playwright/test").Page) { return page.locator(".lh-activity__head").getByText("기존 회기", { exact: true }); } test.describe("learner app shell and session launcher", () => { test.beforeEach(async ({ page }) => { await useRealApi(page); }); test("redirects an unauthenticated learner route to login", async ({ page }) => { await page.goto("/learn/practice"); await expect(page).toHaveURL(/\/login$/); await expect(page.getByRole("button", { name: /학교 Google 계정으로 계속/ })).toBeVisible(); expect(await page.evaluate(() => window.localStorage.getItem("vignette.dev-auth"))).toBeNull(); }); test("redirects to login when a protected learner API returns 401 after boot", async ({ page }) => { await page.route("**/api/auth/me", async (route) => { await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ user_id: "stale-learner", email: "stale.learner@hs.ac.kr", display_name: "Stale Learner", role: "learner", admin_access: false, super_admin: false, account_status: "approved", approval_required: false, cohort_ids: [], consent_at: 1, onboarding_completed_at: 1, nickname: "Stale Learner", self_introduction: "", avatar_url: "", }), }); }); await page.route(/\/api\/(personas|sessions(?:\/dashboard)?)$/, async (route) => { await route.fulfill({ status: 401, contentType: "application/json", body: JSON.stringify({ detail: "not authenticated" }), }); }); await page.goto("/learn/practice"); await expect(page).toHaveURL(/\/login$/); await expect(page.getByRole("button", { name: /학교 Google 계정으로 계속/ })).toBeVisible(); await expect(page.getByText("내담자 목록을 불러오지 못했습니다.")).toHaveCount(0); }); test("renders API personas without legacy session rows", async ({ page }) => { await signInAsLearnerEmail(page, `learner.catalog.${Date.now()}@hs.ac.kr`, "Catalog Learner"); await page.goto("/learn/practice"); const personas = await fetchAvailablePersonas(page); await expect(page.locator(".lh-root")).toBeVisible({ timeout: 15_000 }); const launcher = page.getByRole("listbox", { name: "연습 페르소나" }); await expect(launcher).toBeVisible(); await expect(launcher.getByRole("option")).toHaveCount(personas.length, { timeout: 15_000 }); for (const persona of personas) { await expect(launcher.getByRole("option", { name: new RegExp(persona.code) })).toBeVisible(); await expect(launcher.getByRole("option", { name: new RegExp(persona.display_name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) })).toBeVisible(); } await expectPersonaCardsUseContentHeight(page); await expect(page.getByText(/12회/)).toHaveCount(0); await expect(page.getByText(/최근 연습/)).toHaveCount(0); await expect(page.locator(".vg-nav")).toBeVisible(); await expect(page.locator(".vg-main")).not.toHaveClass(/(^|\s)vg-main--bleed(\s|$)/); await expect(page.getByText("음성")).toBeVisible(); await page.getByText("음성").scrollIntoViewIfNeeded(); await expect(page.getByText("음성")).toBeInViewport(); await page.getByRole("button", { name: "새 회기 시작" }).scrollIntoViewIfNeeded(); await expectReachableLearnerHomeLayout(page); const activityHeading = learnerActivityHeading(page); await activityHeading.scrollIntoViewIfNeeded(); await expect(activityHeading).toBeInViewport(); await expectNoLearnerInternalCopy(page); }); test("routes the launcher CTA to the selected database persona", async ({ page }) => { await signInAsLearner(page); await page.goto("/learn/practice"); const persona = await fetchAvailablePersona(page, 1); const option = page.getByRole("option", { name: new RegExp(persona.code) }); await option.click(); await expect(option).toHaveAttribute("aria-selected", "true"); await page.getByRole("button", { name: "새 회기 시작" }).click(); await expect(page).toHaveURL(new RegExp(`/learn/session/${persona.code}$`)); await expect(page.getByRole("button", { name: "회기 시작" })).toBeVisible(); // 프리플라이트(목표 선택 포함)는 좁은 뷰포트에서 세로 스크롤을 허용한다 — 데스크톱만 무스크롤 계약. if ((page.viewportSize()?.width ?? 0) > 1180) { await expectNoDocumentOverflow(page); } await page.getByRole("button", { name: "회기 시작" }).click(); await expect(page.locator(".sx-grid")).toBeVisible(); await expectNoLearnerInternalCopy(page); await expectNoDocumentOverflow(page); await expectNoHorizontalOverflow(page); }); test("shows real session history with resume, record, and retry actions", async ({ page, }, testInfo) => { const suffix = `${testInfo.project.name.replace(/\W+/g, "-")}-${testInfo.workerIndex}-${Date.now()}`.toLowerCase(); await signInAsLearnerEmail(page, `history.${suffix}@hs.ac.kr`); const persona = await fetchAvailablePersona(page); const active = await createPracticeSession(page, persona.code); const ended = await createPracticeSession(page, persona.code); const endResponse = await page.request.post(`/api/sessions/${ended.session_id}/end`); expect(endResponse.ok(), await endResponse.text()).toBeTruthy(); await page.goto("/learn"); await expect(page.locator(".lh-root")).toBeVisible({ timeout: 15_000 }); await expect(page.getByRole("heading", { name: "오늘 이어갈 회기를 먼저 봅니다." })).toBeVisible(); await expect(page.getByLabel("학습 현황")).toContainText("진행 회기"); await expect(page.getByLabel("학습 현황")).toContainText("2회"); await expect(page.getByLabel("학습 현황")).toContainText("리뷰 대기"); await expect(page.getByLabel("학습 현황")).toContainText("최근 평가"); await expect(page.getByLabel("최근 피드백")).toContainText("평가 피드백은 회기 종료 후 표시됩니다."); await page.goto("/learn/history"); await expect( page.getByRole("heading", { name: "회기 기록을 찾고 정리합니다." }), ).toBeVisible({ timeout: 15_000 }); await expect(page.locator(".lh-history-main")).toBeVisible(); await expect(page.getByLabel("기록 검색")).toBeVisible(); await expect(page.locator(".lh-history-overview")).toContainText("전체"); await expect(page.locator(".lh-history-overview")).toContainText("진행 중"); await expect(page.locator(".lh-history-overview")).toContainText("보관됨"); await expect(page.getByRole("button", { name: "이어하기" })).toBeVisible(); await expect(page.getByRole("button", { name: "기록", exact: true })).toBeVisible(); await expect(page.getByRole("button", { name: "다시 연습" })).toHaveCount(2); await expect(page.locator(".lh-archive-note")).toContainText("읽기 전용"); await expectNoHorizontalOverflow(page); await page.locator(".lh-history-main").scrollIntoViewIfNeeded(); await expect(page.getByRole("button", { name: "이어하기" })).toBeInViewport(); await expect(page.getByRole("button", { name: "기록", exact: true })).toBeInViewport(); await expect(page.getByRole("button", { name: "다시 연습" }).first()).toBeInViewport(); await expect(page.locator(".lh-history-main")).toContainText("2개"); await expect(page.locator(".lh-persona-progress")).toContainText(persona.code); await expect(page.locator(".lh-persona-progress")).toContainText("2회"); await page.getByRole("button", { name: "보관", exact: true }).click(); await expect(page.getByText("회기를 보관했습니다.")).toBeVisible(); await page.locator(".lh-history-filter").getByRole("button", { name: "보관됨" }).click(); await expect(page.locator(".lh-history-main")).toContainText("1개"); await expect(page.getByRole("button", { name: "복원" })).toBeVisible(); await page.getByRole("button", { name: "복원" }).click(); await expect(page.getByText("보관을 해제했습니다.")).toBeVisible(); await expect(page.locator(".lh-history-main")).toContainText("0개"); await page.locator(".lh-history-filter").getByRole("button", { name: "전체" }).click(); await expect(page.locator(".lh-history-main")).toContainText("2개"); await page.getByRole("button", { name: "이어하기" }).click(); await expect(page).toHaveURL(new RegExp(`/learn/session/${active.session_id}$`)); await expect(page.locator(".sx-page.sx-page--active")).toBeVisible(); await expectVisibleResumeLoadedSignal(page); await expectNoDocumentOverflow(page); await expectNoHorizontalOverflow(page); }); test("does not fall back to P1 for an unavailable persona code", async ({ page }) => { await signInAsLearner(page); await page.goto("/learn/session/P9"); await expect( page.getByRole("heading", { name: "연습 대상 정보를 확인하고 있습니다." }), ).toBeVisible({ timeout: 15_000 }); await expect(page.getByText(/P9 페르소나는 현재 연습 목록에 없습니다/)).toBeVisible({ timeout: 15_000, }); await expect(page.getByText("페르소나 P9")).toHaveCount(0); await expect(page.getByRole("button", { name: "회기 시작" })).toBeDisabled(); if ((page.viewportSize()?.width ?? 0) > 1180) { await expectNoDocumentOverflow(page); } await expectNoHorizontalOverflow(page); }); test("blocks direct session starts for degraded or non-database personas", async ({ page }) => { await signInAsLearner(page); await page.route("**/api/personas", async (route) => { await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify([ { code: "SEEDX", display_name: "검증 불가 내담자", difficulty: "easy", theory_target: ["humanistic"], demographics: { age_band: "20대" }, presenting_summary: "서버 카탈로그 원본이 확인되지 않은 항목", voice_preset: null, source: "seed_fallback", degraded: true, }, ]), }); }); await page.goto("/learn/session/SEEDX"); await expect( page.getByRole("heading", { name: "이 내담자는 현재 연습에 사용할 수 없습니다." }), ).toBeVisible(); await expect(page.getByText("카탈로그 원본을 확인하지 못해 현재 연습에 사용할 수 없습니다.")).toBeVisible(); await expect(page.getByRole("button", { name: "회기 시작" })).toBeDisabled(); if ((page.viewportSize()?.width ?? 0) > 1180) { await expectNoDocumentOverflow(page); } await expectNoHorizontalOverflow(page); }); });