vignette/apps/web/e2e/layout-visual-gate.spec.ts

1279 lines
54 KiB
TypeScript

import { promises as fs } from "node:fs";
import path from "node:path";
import { expect, test, type Page } from "@playwright/test";
import {
EMPTY_REVIEW_SESSION_ID,
FILLED_REVIEW_SESSION_ID,
routeEmptySessionReview,
routeFilledSessionReview,
routePrepostMeasures,
} from "./session-review-fixture";
import {
completeAlliancePreCheckpoint,
completeOnboarding,
expectNoHorizontalOverflow,
fetchAvailablePersona,
signInAsLearner,
signInAsTeacher,
} from "./support";
/**
* Strict visual layout gate.
*
* The layout-redesign handoff (docs/archive/ops/layout-redesign-handoff-2026-06-26.md)
* required a human-style visual acceptance pass across the redesigned screens at
* the suggested breakpoints. This spec hardens that pass into an automated gate:
* every redesigned screen is rendered at every required width, asserted free of
* horizontal overflow and clipped primary controls, and captured as a full-page
* screenshot artifact for review. Any single failure fails the whole gate.
*/
const GATE_WIDTHS = [
{ width: 390, height: 844, label: "390-mobile" },
{ width: 720, height: 900, label: "720-phablet" },
{ width: 861, height: 900, label: "861-tablet-min" },
{ width: 900, height: 900, label: "900-tablet" },
{ width: 1024, height: 768, label: "1024-tablet-land" },
{ width: 1280, height: 800, label: "1280-laptop" },
{ width: 1440, height: 900, label: "1440-desktop" },
] as const;
const SHOT_DIR = path.join(process.cwd(), "node_modules", ".tmp", "layout-gate");
const TEACHER_REVIEW_SESSION_ID = "teacher-review-visual";
function teacherAnalysisFixture() {
const learnerId = "visual-analysis-learner";
const sessions = Array.from({ length: 5 }, (_unused, index) => {
const sessionNo = index + 1;
return {
session_id: `${learnerId}-session-${sessionNo}`,
learner_id: learnerId,
learner_label: "분석 검증 학습자",
persona_code: sessionNo % 2 === 0 ? "P2" : "P1",
persona_name: sessionNo % 2 === 0 ? "민재" : "서연",
session_no: sessionNo,
status: "ended",
stage: sessionNo >= 4 ? "개입" : "탐색",
turn_count: 8 + sessionNo,
learner_turn_count: 4 + sessionNo,
client_turn_count: 4,
started_at: `2026-06-${String(10 + sessionNo).padStart(2, "0")}T09:00:00Z`,
ended_at: `2026-06-${String(10 + sessionNo).padStart(2, "0")}T09:30:00Z`,
review_status: sessionNo === 3 ? "closed" : "pending",
review_note: null,
reviewed_at: sessionNo === 3 ? "2026-06-13T10:00:00Z" : null,
};
});
const points = sessions.map((session) => ({
session_id: session.session_id,
session_no: session.session_no,
persona_code: session.persona_code,
stage: session.stage,
started_at: session.started_at,
ended_at: session.ended_at,
score: session.session_no >= 4 ? 0.88 : 0.52,
rapport: Math.min(0.8, session.session_no * 0.12),
technique_count: session.session_no + 1,
watch_count: session.session_no < 4 ? 1 : 0,
}));
const summary = {
learner_id: learnerId,
learner_label: "분석 검증 학습자",
sessions: sessions.length,
ended_sessions: sessions.length,
latest_at: sessions[sessions.length - 1].ended_at ?? "",
first_score: points[0].score,
latest_score: points[points.length - 1].score,
score_delta: (points[points.length - 1].score ?? 0) - (points[0].score ?? 0),
avg_score: 0.72,
avg_rapport: 0.44,
trend: "up",
top_techniques: ["reflection", "summary"],
points,
};
return {
dashboard: {
source: "database",
cohort_label: "Visual cohort",
total_learners: 1,
active_sessions: 0,
ended_sessions: sessions.length,
learner_growth: [{ ...summary, points: points.slice(-4) }],
safety_alerts: [],
pending_reviews: [],
recent_sessions: sessions.slice(-2),
message: "학생 분석 시각 검증 fixture.",
},
analysis: {
source: "database",
learner_id: learnerId,
learner_label: "분석 검증 학습자",
total_sessions: sessions.length,
ended_sessions: sessions.length,
active_sessions: 0,
pending_reviews: 2,
summary,
points,
stage_breakdown: [
{ stage: "라포", sessions: 0, turns: 0 },
{ stage: "탐색", sessions: 3, turns: 31 },
{ stage: "개입", sessions: 2, turns: 22 },
{ stage: "정리", sessions: 0, turns: 0 },
],
sessions,
message: "분석 검증 학습자 전체 회기 5건",
},
};
}
async function ensureShotDir() {
await fs.mkdir(SHOT_DIR, { recursive: true });
}
interface ClipReport {
viewport: { width: number; height: number };
horizontalOverflow: number;
offenders: Array<{
tag: string;
role: string;
className: string;
text: string;
reason: string;
left: number;
right: number;
}>;
}
type ScrollOwner = {
id: string;
token: string;
label: string;
clientHeight: number;
clientWidth: number;
maxTop: number;
maxLeft: number;
top: number;
left: number;
};
type CaptureManifestRecord = {
capturedAt: string;
screen: string;
viewport: { width: number; height: number; label: string };
kind: "full-page" | "vertical-segment" | "horizontal-end" | "scroll-reset" | "scroll-excluded";
owner: Pick<ScrollOwner, "id" | "label" | "clientHeight" | "clientWidth" | "maxTop" | "maxLeft">;
offset: { top: number; left: number };
path: string | null;
reason?: string;
ownerToken?: string;
ownerMatchCount?: number;
theoreticalMaxLeft?: number;
actualMaxLeft?: number;
};
type ScrollPosition = {
token: string;
matchCount: number;
top: number;
left: number;
clientHeight: number;
clientWidth: number;
scrollHeight: number;
scrollWidth: number;
maxTop: number;
maxLeft: number;
rect: { top: number; bottom: number; left: number; right: number };
};
type HorizontalLimitProbe = {
token: string;
matchCount: number;
originalLeft: number;
theoreticalMaxLeft: number;
actualMaxLeft: number;
};
const SCROLL_OWNER_ATTRIBUTE = "data-layout-gate-scroll-owner";
const MAX_SCROLL_SEGMENTS = 30;
let scrollOwnerGeneration = 0;
async function writeCaptureManifest(record: CaptureManifestRecord) {
await fs.appendFile(
path.join(SHOT_DIR, "capture-manifest.jsonl"),
`${JSON.stringify(record)}\n`,
"utf8",
);
}
async function resetScrollableOwners(page: Page): Promise<ScrollOwner[]> {
const generation = ++scrollOwnerGeneration;
return page.evaluate(async ({ ownerAttribute, ownerGeneration }) => {
const isVisible = (element: HTMLElement) => {
const style = getComputedStyle(element);
const rect = element.getBoundingClientRect();
return (
style.display !== "none" &&
style.visibility !== "hidden" &&
Number(style.opacity) !== 0 &&
rect.width > 0 &&
rect.height > 0
);
};
for (const previousOwner of Array.from(document.querySelectorAll<HTMLElement>(`[${ownerAttribute}]`))) {
previousOwner.removeAttribute(ownerAttribute);
}
const owners = new Map<HTMLElement, { id: string; token: string; label: string }>();
let nextId = 0;
const add = (element: HTMLElement | null, label: string, preferredId?: string) => {
if (!element || owners.has(element)) return;
const id = preferredId ?? `scroll-${nextId++}`;
owners.set(element, { id, token: `owner-${ownerGeneration}-${id}`, label });
};
add(document.scrollingElement as HTMLElement | null, "document", "document");
add(document.querySelector<HTMLElement>("#root"), "#root", "root");
add(document.querySelector<HTMLElement>(".vg-main"), ".vg-main", "vg-main");
add(document.querySelector<HTMLElement>("main"), "main", "main");
for (const element of Array.from(document.querySelectorAll<HTMLElement>("*"))) {
if (!isVisible(element)) continue;
const style = getComputedStyle(element);
const canScrollY =
(style.overflowY === "auto" || style.overflowY === "scroll" || style.overflowY === "overlay") &&
element.scrollHeight > element.clientHeight + 1;
const canScrollX =
(style.overflowX === "auto" || style.overflowX === "scroll" || style.overflowX === "overlay") &&
element.scrollWidth > element.clientWidth + 1;
if (!canScrollY && !canScrollX) continue;
const tag = element.tagName.toLowerCase();
const identifier = element.id ? `#${element.id}` : element.classList.length > 0 ? `.${element.classList[0]}` : tag;
add(element, identifier);
}
for (const [element, owner] of owners) {
element.setAttribute(ownerAttribute, owner.token);
element.scrollTop = 0;
element.scrollLeft = 0;
}
const ownerIds = Array.from(owners.values(), (owner) => owner.id);
const ownerTokens = Array.from(owners.values(), (owner) => owner.token);
if (new Set(ownerIds).size !== ownerIds.length || new Set(ownerTokens).size !== ownerTokens.length) {
throw new Error("Layout capture scroll-owner assignment contains duplicate IDs.");
}
for (const owner of owners.values()) {
const matches = document.querySelectorAll(`[${ownerAttribute}="${owner.token}"]`).length;
if (matches !== 1) {
throw new Error(`Layout capture scroll-owner ${owner.id} resolved to ${matches} nodes after reset.`);
}
}
window.scrollTo(0, 0);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
return Array.from(owners, ([element, owner]) => ({
...owner,
clientHeight: element.clientHeight,
clientWidth: element.clientWidth,
maxTop: Math.max(0, element.scrollHeight - element.clientHeight),
maxLeft: Math.max(0, element.scrollWidth - element.clientWidth),
top: element.scrollTop,
left: element.scrollLeft,
}));
}, { ownerAttribute: SCROLL_OWNER_ATTRIBUTE, ownerGeneration: generation });
}
async function scrollOwnerTo(page: Page, owner: ScrollOwner, top: number, left = 0) {
return page.evaluate(
async ({ ownerAttribute, ownerId: requestedOwnerId, ownerToken, top: requestedTop, left: requestedLeft }) => {
const matches = Array.from(document.querySelectorAll<HTMLElement>(`[${ownerAttribute}="${ownerToken}"]`));
if (matches.length !== 1) {
throw new Error(`Scroll owner ${requestedOwnerId} expected one node for ${ownerToken}, found ${matches.length}.`);
}
const element = matches[0];
element.scrollIntoView({ block: "nearest", inline: "nearest" });
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const maxTop = Math.max(0, element.scrollHeight - element.clientHeight);
const maxLeft = Math.max(0, element.scrollWidth - element.clientWidth);
const targetTop = Math.min(requestedTop, maxTop);
const targetLeft = Math.min(requestedLeft, maxLeft);
element.scrollTop = targetTop;
element.scrollLeft = targetLeft;
if (requestedOwnerId === "document") window.scrollTo(targetLeft, targetTop);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const rect = element.getBoundingClientRect();
return {
token: ownerToken,
matchCount: matches.length,
top: element.scrollTop,
left: element.scrollLeft,
clientHeight: element.clientHeight,
clientWidth: element.clientWidth,
scrollHeight: element.scrollHeight,
scrollWidth: element.scrollWidth,
maxTop: Math.max(0, element.scrollHeight - element.clientHeight),
maxLeft: Math.max(0, element.scrollWidth - element.clientWidth),
rect: { top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right },
};
},
{ ownerAttribute: SCROLL_OWNER_ATTRIBUTE, ownerId: owner.id, ownerToken: owner.token, top, left },
);
}
async function probeNativeMaxLeft(page: Page, owner: ScrollOwner): Promise<HorizontalLimitProbe> {
return page.evaluate(
async ({ ownerAttribute, ownerId: requestedOwnerId, ownerToken }) => {
const matches = Array.from(document.querySelectorAll<HTMLElement>(`[${ownerAttribute}="${ownerToken}"]`));
if (matches.length !== 1) {
throw new Error(`Scroll owner ${requestedOwnerId} expected one node for ${ownerToken}, found ${matches.length}.`);
}
const element = matches[0];
const originalLeft = element.scrollLeft;
const theoreticalMaxLeft = Math.max(0, element.scrollWidth - element.clientWidth);
element.scrollLeft = Number.MAX_SAFE_INTEGER;
if (requestedOwnerId === "document") window.scrollTo(Number.MAX_SAFE_INTEGER, window.scrollY);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
const actualMaxLeft = element.scrollLeft;
element.scrollLeft = originalLeft;
if (requestedOwnerId === "document") window.scrollTo(originalLeft, window.scrollY);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
return {
token: ownerToken,
matchCount: matches.length,
originalLeft,
theoreticalMaxLeft,
actualMaxLeft,
};
},
{ ownerAttribute: SCROLL_OWNER_ATTRIBUTE, ownerId: owner.id, ownerToken: owner.token },
);
}
function segmentOffsets(maxOffset: number, clientSize: number, owner: ScrollOwner) {
if (maxOffset <= 0) return [];
const step = Math.max(1, Math.floor(clientSize * 0.8));
const offsets = [0];
for (let offset = step; offset < maxOffset; offset += step) offsets.push(offset);
if (offsets[offsets.length - 1] !== maxOffset) offsets.push(maxOffset);
if (offsets.length > MAX_SCROLL_SEGMENTS) {
throw new Error(
`[${owner.label}] needs ${offsets.length} scroll captures; the ${MAX_SCROLL_SEGMENTS}-segment ceiling would omit its bottom.`,
);
}
return offsets;
}
async function captureScrollableSegments(
page: Page,
screen: string,
viewport: (typeof GATE_WIDTHS)[number],
owners: ScrollOwner[],
) {
for (const owner of owners) {
const initialPosition = await scrollOwnerTo(page, owner, 0);
expect(initialPosition.matchCount, `[${screen} @ ${viewport.label}] ${owner.label} owner identity`).toBe(1);
const liveOwner = {
...owner,
clientHeight: initialPosition.clientHeight,
clientWidth: initialPosition.clientWidth,
maxTop: initialPosition.maxTop,
maxLeft: initialPosition.maxLeft,
};
if (owner.maxTop > 0 && liveOwner.maxTop <= 0) {
await writeCaptureManifest({
capturedAt: new Date().toISOString(),
screen,
viewport,
kind: "scroll-excluded",
owner: liveOwner,
offset: { top: initialPosition.top, left: initialPosition.left },
path: null,
reason: "Owner stopped scrolling after it was brought into the capture viewport.",
ownerToken: owner.token,
ownerMatchCount: initialPosition.matchCount,
});
}
const offsets = segmentOffsets(liveOwner.maxTop, liveOwner.clientHeight, liveOwner);
for (const [segmentIndex, top] of offsets.entries()) {
const offset = await scrollOwnerTo(page, owner, top);
expect(offset.matchCount, `[${screen} @ ${viewport.label}] ${owner.label} owner identity`).toBe(1);
const reachableTarget = Math.min(top, offset.maxTop);
expect(
Math.abs(offset.top - reachableTarget),
`[${screen} @ ${viewport.label}] ${owner.label} vertical capture offset`,
).toBeLessThanOrEqual(1);
const shotPath = path.join(
SHOT_DIR,
`${screen}__${viewport.label}__${owner.id}__segment-${String(segmentIndex).padStart(2, "0")}.png`,
);
await page.screenshot({ path: shotPath, fullPage: false });
await writeCaptureManifest({
capturedAt: new Date().toISOString(),
screen,
viewport,
kind: "vertical-segment",
owner: { ...liveOwner, maxTop: offset.maxTop, maxLeft: offset.maxLeft },
offset,
path: path.relative(process.cwd(), shotPath),
ownerToken: owner.token,
ownerMatchCount: offset.matchCount,
});
}
if (liveOwner.maxLeft > 0) {
const horizontalProbe = await probeNativeMaxLeft(page, owner);
expect(horizontalProbe.matchCount, `[${screen} @ ${viewport.label}] ${owner.label} owner identity`).toBe(1);
expect(horizontalProbe.theoreticalMaxLeft, `[${screen} @ ${viewport.label}] ${owner.label} theoretical horizontal maximum`).toBe(liveOwner.maxLeft);
const offset = await scrollOwnerTo(page, owner, 0, horizontalProbe.actualMaxLeft);
expect(offset.matchCount, `[${screen} @ ${viewport.label}] ${owner.label} owner identity`).toBe(1);
expect(
Math.abs(offset.left - horizontalProbe.actualMaxLeft),
`[${screen} @ ${viewport.label}] ${owner.label} horizontal capture offset`,
).toBeLessThanOrEqual(1);
const shotPath = path.join(SHOT_DIR, `${screen}__${viewport.label}__${owner.id}__horizontal-end.png`);
await page.screenshot({ path: shotPath, fullPage: false });
await writeCaptureManifest({
capturedAt: new Date().toISOString(),
screen,
viewport,
kind: "horizontal-end",
owner: { ...liveOwner, maxTop: offset.maxTop, maxLeft: offset.maxLeft },
offset,
path: path.relative(process.cwd(), shotPath),
ownerToken: owner.token,
ownerMatchCount: offset.matchCount,
theoreticalMaxLeft: horizontalProbe.theoreticalMaxLeft,
actualMaxLeft: horizontalProbe.actualMaxLeft,
});
const afterActualMax = await scrollOwnerTo(
page,
owner,
0,
horizontalProbe.actualMaxLeft + Math.max(100, offset.clientWidth),
);
expect(afterActualMax.matchCount, `[${screen} @ ${viewport.label}] ${owner.label} owner identity`).toBe(1);
expect(
Math.abs(afterActualMax.left - horizontalProbe.actualMaxLeft),
`[${screen} @ ${viewport.label}] ${owner.label} native horizontal maximum`,
).toBeLessThanOrEqual(1);
}
}
await resetScrollableOwners(page);
}
/**
* Scans every visible interactive control and prominent text container for
* either (a) extending beyond the viewport horizontally, or (b) clipping its own
* content (scrollWidth/scrollHeight exceeding the client box) — the two failure
* modes the redesign was meant to eliminate.
*/
async function auditClipping(page: Page): Promise<ClipReport> {
return page.evaluate(() => {
const doc = document.documentElement;
const viewport = { width: doc.clientWidth, height: window.innerHeight };
const selector = [
"button",
"a[href]",
"input",
"select",
"textarea",
"[role='tab']",
"[role='button']",
"[role='option']",
"h1",
"h2",
"h3",
".vg-btn",
].join(",");
// Walks ancestors to find the nearest box that clips overflow. Returns the
// clipping rect when that ancestor is NOT scrollable (i.e. content cut off,
// not reachable by scrolling). A scrollable carousel (overflow auto/scroll)
// legitimately holds off-screen children, so it is treated as non-clipping.
// X-axis only: offender detection compares horizontal edges, so only the
// horizontal overflow behaviour of ancestors matters. A horizontal carousel
// (overflow-x auto/scroll) holds reachable off-screen children and is fine;
// overflow-x hidden genuinely cuts content off.
function nearestHardClip(el: HTMLElement): DOMRect | null {
let node: HTMLElement | null = el.parentElement;
while (node && node !== document.body && node !== document.documentElement) {
const ox = window.getComputedStyle(node).overflowX;
if (ox === "auto" || ox === "scroll") return null; // reachable by scroll
if (ox === "hidden" || ox === "clip") return node.getBoundingClientRect();
node = node.parentElement;
}
return null;
}
const offenders: ClipReport["offenders"] = [];
const nodes = Array.from(document.querySelectorAll<HTMLElement>(selector));
for (const el of nodes) {
const rect = el.getBoundingClientRect();
const style = window.getComputedStyle(el);
const visible =
style.display !== "none" &&
style.visibility !== "hidden" &&
Number(style.opacity) !== 0 &&
rect.width > 0 &&
rect.height > 0;
if (!visible) continue;
// Clipped by a hard (non-scrollable) overflow ancestor: content is cut off.
const clipRect = nearestHardClip(el);
const clippedByAncestor =
!!clipRect && (rect.right > clipRect.right + 1 || rect.left < clipRect.left - 1);
// Content clipping: the element cannot show its own text/children — but
// intentional truncation affordances (ellipsis, -webkit-line-clamp) are
// design choices the redesign uses for dense data, not defects.
const clipsX = style.overflowX === "hidden" || style.overflowX === "clip";
const clipsY = style.overflowY === "hidden" || style.overflowY === "clip";
const lineClamp =
style.getPropertyValue("-webkit-line-clamp") || (style as unknown as { webkitLineClamp?: string }).webkitLineClamp || "none";
const hasLineClamp = lineClamp !== "none" && lineClamp !== "" && lineClamp !== "0";
const hasEllipsis = style.textOverflow === "ellipsis";
// 폼 컨트롤(input/textarea/select)은 자기 값을 *설계상* 스크롤한다(커서/키보드로 전부
// 도달 가능). 박스보다 긴 값은 잘린 결함이 아니라 정상 스크롤 UX → ellipsis/line-clamp
// 와 같은 의도된 어포던스로 보고 text-clip 판정에서 제외(clipped-by-ancestor·가로 overflow는 유지).
const tagName = el.tagName.toLowerCase();
const isFormControl =
tagName === "input" || tagName === "textarea" || tagName === "select";
const textClippedX =
clipsX && !hasEllipsis && !isFormControl && Math.ceil(el.scrollWidth - el.clientWidth) > 1;
const textClippedY =
clipsY && !hasLineClamp && !isFormControl && Math.ceil(el.scrollHeight - el.clientHeight) > 1;
if (clippedByAncestor || textClippedX || textClippedY) {
const reasons: string[] = [];
if (clippedByAncestor) reasons.push("clipped-by-ancestor");
if (textClippedX) reasons.push("text-clipped-x");
if (textClippedY) reasons.push("text-clipped-y");
offenders.push({
tag: el.tagName.toLowerCase(),
role: el.getAttribute("role") ?? "",
className: String(el.className || "").slice(0, 80),
text: (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 60),
reason: reasons.join(","),
left: Math.floor(rect.left),
right: Math.ceil(rect.right),
});
}
if (offenders.length >= 16) break;
}
return {
viewport,
horizontalOverflow: Math.ceil(doc.scrollWidth - doc.clientWidth),
offenders,
};
});
}
async function gateScreen(
page: Page,
screen: string,
prepareReady: () => Promise<void>,
) {
for (const vp of GATE_WIDTHS) {
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => r(null))));
await prepareReady();
const owners = await resetScrollableOwners(page);
for (const owner of owners) {
await writeCaptureManifest({
capturedAt: new Date().toISOString(),
screen,
viewport: vp,
kind: "scroll-reset",
owner,
offset: { top: owner.top, left: owner.left },
path: null,
});
}
await expect(
page.locator("html"),
`[${screen} @ ${vp.label}] layout gate must capture the dark UI surface`,
).toHaveAttribute("data-theme", "dark");
await expectNoHorizontalOverflow(page);
const navGeometry = await page.evaluate(() => {
const nav = document.querySelector<HTMLElement>(".vg-nav");
const label = document.querySelector<HTMLElement>(".vg-nav__label");
const topbar = document.querySelector<HTMLElement>(".vg-topbar");
if (!nav || !label || !topbar || getComputedStyle(label).display === "none") return null;
const navRect = nav.getBoundingClientRect();
return {
innerGap: Math.round(label.getBoundingClientRect().top - navRect.top),
shellGap: Math.round(navRect.top - topbar.getBoundingClientRect().bottom),
};
});
if (navGeometry !== null) {
expect(
navGeometry.innerGap,
`[${screen} @ ${vp.label}] GNB should start near the topbar without a dead top zone`,
).toBeLessThanOrEqual(40);
expect(
Math.abs(navGeometry.shellGap),
`[${screen} @ ${vp.label}] GNB should begin directly below the topbar`,
).toBeLessThanOrEqual(1);
}
const report = await auditClipping(page);
expect(
report.horizontalOverflow,
`[${screen} @ ${vp.label}] horizontal overflow ${report.horizontalOverflow}px`,
).toBeLessThanOrEqual(1);
expect(
report.offenders,
`[${screen} @ ${vp.label}] clipped/overflowing controls: ${JSON.stringify(
report.offenders,
null,
2,
)}`,
).toEqual([]);
const topShotPath = path.join(SHOT_DIR, `${screen}__${vp.label}.png`);
await page.screenshot({
path: topShotPath,
fullPage: true,
});
await writeCaptureManifest({
capturedAt: new Date().toISOString(),
screen,
viewport: vp,
kind: "full-page",
owner: {
id: "document",
label: "document",
clientHeight: page.viewportSize()?.height ?? vp.height,
clientWidth: page.viewportSize()?.width ?? vp.width,
maxTop: 0,
maxLeft: 0,
},
offset: { top: 0, left: 0 },
path: path.relative(process.cwd(), topShotPath),
});
await captureScrollableSegments(page, screen, vp, owners);
}
}
async function expectProfessorSummaryGap(page: Page) {
const metrics = await page.locator(".pf-signal-strip").evaluate((strip) => {
const triage = strip.querySelector<HTMLElement>(".pf-triage");
const summary = strip.querySelector<HTMLElement>(".pf-kpis");
if (!triage || !summary) return null;
const triageRect = triage.getBoundingClientRect();
const summaryRect = summary.getBoundingClientRect();
return {
actualGap: summaryRect.top - triageRect.bottom,
rowGap: Number.parseFloat(getComputedStyle(strip).rowGap),
};
});
const width = page.viewportSize()?.width ?? "unknown";
expect(metrics, `[professor @ ${width}px] signal cards must be measurable`).not.toBeNull();
expect(
Math.abs(metrics!.actualGap - 12),
`[professor @ ${width}px] rendered signal-card gap`,
).toBeLessThanOrEqual(1);
expect(
Math.abs(metrics!.rowGap - 12),
`[professor @ ${width}px] computed signal-card row-gap`,
).toBeLessThanOrEqual(0.1);
}
/** 리뷰는 모든 폭에서 가로 탭으로 영역을 전환한다. */
async function openReviewTabIfPresent(page: Page, label: string) {
const tab = page.locator(".sr-tabs button", { hasText: label });
if (await tab.isVisible().catch(() => false)) {
await tab.click();
}
}
async function expectEmptyReviewNoDeadThirdColumn(page: Page) {
const report = await page.evaluate(() => {
const root = document.querySelector<HTMLElement>(".sr-root--empty");
const cols = document.querySelector<HTMLElement>(".sr-root--empty .sr-cols");
const transcript = document.querySelector<HTMLElement>(".sr-card--transcript");
if (!root || !cols || !transcript) {
return {
present: false,
columnCount: 0,
};
}
const gridTemplate = getComputedStyle(cols).gridTemplateColumns;
const columnCount = gridTemplate.split(" ").filter(Boolean).length;
const transcriptRect = transcript.getBoundingClientRect();
return {
present: true,
columnCount,
transcriptWidth: Math.round(transcriptRect.width),
mainColumnWidth: Math.round(cols.getBoundingClientRect().width),
};
});
expect(report.present, "empty review layout should be mounted").toBe(true);
expect(report.columnCount, "empty review should keep the single-pane tab layout").toBe(1);
}
async function expectFilledReviewLearnerWorkbench(page: Page) {
const report = await page.evaluate(() => {
const cols = document.querySelector<HTMLElement>(".sr-cols--learner");
const transcript = document.querySelector<HTMLElement>(".sr-card--transcript");
const overview = document.querySelector<HTMLElement>(".sr-overview");
if (!cols || !transcript || !overview) {
return {
present: false,
columnCount: 0,
overviewBottom: 0,
colsTop: 0,
transcriptWidth: 0,
colsWidth: 0,
};
}
const columnCount = getComputedStyle(cols).gridTemplateColumns.split(" ").filter(Boolean).length;
const colsRect = cols.getBoundingClientRect();
const transcriptRect = transcript.getBoundingClientRect();
const overviewRect = overview.getBoundingClientRect();
return {
present: true,
columnCount,
overviewBottom: Math.ceil(overviewRect.bottom),
colsTop: Math.floor(colsRect.top),
transcriptWidth: Math.round(transcriptRect.width),
colsWidth: Math.round(colsRect.width),
};
});
expect(report.present, "filled learner review layout should be mounted").toBe(true);
expect(report.columnCount, "learner review should use one active tab pane").toBe(1);
expect(report.overviewBottom).toBeLessThanOrEqual(report.colsTop + 1);
expect(Math.abs(report.transcriptWidth - report.colsWidth)).toBeLessThanOrEqual(2);
}
async function expectSupervisorReviewNoDeadGaps(page: Page) {
const report = await page.evaluate(() => {
const cols = document.querySelector<HTMLElement>(".sr-cols--supervisor");
const left = document.querySelector<HTMLElement>(".sr-cols--supervisor .sr-left");
const right = document.querySelector<HTMLElement>(".sr-cols--supervisor .sr-right");
if (!cols || !left || !right) {
return {
present: false,
columnCount: 0,
leftDisplay: "",
rightDisplay: "",
maxMainGap: 0,
maxSideGap: 0,
};
}
const colsStyle = getComputedStyle(cols);
const leftStyle = getComputedStyle(left);
const rightStyle = getComputedStyle(right);
return {
present: true,
columnCount: colsStyle.gridTemplateColumns.split(" ").filter(Boolean).length,
leftDisplay: leftStyle.display,
rightDisplay: rightStyle.display,
maxMainGap: 0,
maxSideGap: 0,
};
});
expect(report.present, "supervisor review layout should be mounted").toBe(true);
expect(report.columnCount, "supervisor review should use one active tab pane").toBe(1);
expect(report.leftDisplay).toBe("none");
expect(report.rightDisplay).toBe("none");
}
test.describe("layout visual gate @single-run", () => {
test.describe.configure({ mode: "serial", timeout: 90_000 });
test.beforeAll(async () => {
await ensureShotDir();
await fs.writeFile(path.join(SHOT_DIR, "capture-manifest.jsonl"), "", "utf8");
});
// 이 게이트는 다크 표면을 기준으로 레이아웃을 캡처하고, 라이트 검사는 각 테스트가
// "라이트 모드로" 버튼을 눌러 명시적으로 전환한 뒤에만 한다. 예전에는 앱이 저장값
// 없을 때 무조건 dark 로 떨어져서 이 전제가 공짜로 성립했다. 2026-07-27 부터
// readInitialTheme() 이 prefers-color-scheme 을 따르므로(소유자 결정), 이 프로젝트에
// colorScheme 설정이 없으면 Chromium 기본값인 light 로 시작해 게이트가 깨진다.
// 게이트가 자기 전제를 직접 심는다. 테마 store 의 "저장값 우선" 규칙을 그대로 쓴다.
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
try {
localStorage.setItem("vignette.theme", "dark");
} catch {
/* storage 접근 불가 환경에서는 앱 폴백(dark)에 맡긴다 */
}
});
});
test("learner home stays contained and legible across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: {
email: `gate.learner.${Date.now()}@hs.ac.kr`,
role: "learner",
display_name: "이름이 아주 길게 표시되는 학습자 케이스 검증용 계정",
},
});
await completeOnboarding(page, {
legal_name: "이름이 아주 길게 표시되는 학습자 케이스 검증용 계정",
affiliation: "한신대학교",
department: "상담심리학과",
grade_level: "4학년",
phone: "010-3333-3333",
contact_address: "경기도 오산시 한신대학교",
});
// Seed dense history: one active + two ended sessions.
const persona = await fetchAvailablePersona(page);
const made: string[] = [];
for (let i = 0; i < 3; i += 1) {
const res = await page.request.post("/api/sessions", {
data: { persona_code: persona.code, theory_mode: "humanistic" },
});
const body = (await res.json()) as { session_id: string };
made.push(body.session_id);
}
await page.request.post(`/api/sessions/${made[1]}/end`);
await page.request.post(`/api/sessions/${made[2]}/end`);
await page.goto("/learn");
await gateScreen(page, "learner-home", async () => {
await expect(page.locator(".lh-root")).toBeVisible({ timeout: 15_000 });
const dashTabs = page.locator(".lh-tabs");
await expect(dashTabs).toBeVisible({ timeout: 15_000 });
await dashTabs.getByRole("tab", { name: "오늘의 회기", exact: true }).click();
await expect(page.locator("[data-learner-primary-action]")).toBeVisible({ timeout: 15_000 });
await expect(page.locator("#lh-panel-today .lh-session-focus")).toBeVisible({ timeout: 15_000 });
await dashTabs.getByRole("tab", { name: "성장 지표", exact: true }).click();
const growthPanel = page.locator("#lh-panel-growth");
const growthStatus = growthPanel.locator(".lh-dashboard-status");
const metricCards = growthStatus.locator(".lh-metric-card");
await expect(growthStatus).toBeVisible({ timeout: 15_000 });
await expect(metricCards).toHaveCount(4);
await expect(metricCards.first()).toBeVisible();
const metricGeometry = await growthStatus.evaluate((status) => {
const panel = status.closest<HTMLElement>("#lh-panel-growth");
if (!panel) return null;
const statusRect = status.getBoundingClientRect();
const panelRect = panel.getBoundingClientRect();
const cards = Array.from(status.querySelectorAll<HTMLElement>(".lh-metric-card")).map((card) => {
const rect = card.getBoundingClientRect();
return { width: rect.width, height: rect.height };
});
return {
leftGap: Math.abs(statusRect.left - panelRect.left),
rightGap: Math.abs(panelRect.right - statusRect.right),
cards,
};
});
expect(metricGeometry, "growth metrics should stay inside the growth panel").not.toBeNull();
expect(metricGeometry!.leftGap, "growth metrics should span the panel at every gate width").toBeLessThanOrEqual(1);
expect(metricGeometry!.rightGap, "growth metrics should span the panel at every gate width").toBeLessThanOrEqual(1);
expect(metricGeometry!.cards.every((card) => card.width > 0 && card.height > 0)).toBe(true);
const viewport = page.viewportSize();
const viewportLabel = GATE_WIDTHS.find(
(candidate) => candidate.width === viewport?.width && candidate.height === viewport?.height,
)?.label;
await page.screenshot({
path: path.join(SHOT_DIR, `learner-home-growth__${viewportLabel ?? "unknown"}.png`),
fullPage: true,
});
await dashTabs.getByRole("tab", { name: "기록 · 리뷰", exact: true }).click();
await expect(page.locator(".lh-compact-list li").first()).toBeVisible({ timeout: 15_000 });
await dashTabs.getByRole("tab", { name: "오늘의 회기", exact: true }).click();
await expect(page.locator(".lh-work-cluster")).toBeVisible({ timeout: 15_000 });
const shellScroll = await page.evaluate(async () => {
const nav = document.querySelector<HTMLElement>(".vg-nav");
const main = document.querySelector<HTMLElement>(".vg-main");
if (!nav || !main) return null;
const navTopBefore = nav.getBoundingClientRect().top;
const windowScrollBefore = window.scrollY;
const maxScroll = Math.max(0, main.scrollHeight - main.clientHeight);
main.scrollTop = Math.min(240, maxScroll);
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
const report = {
maxScroll,
mainScrollTop: main.scrollTop,
navTopDelta: Math.abs(nav.getBoundingClientRect().top - navTopBefore),
windowScrollDelta: Math.abs(window.scrollY - windowScrollBefore),
};
main.scrollTop = 0;
return report;
});
expect(shellScroll, "learner shell should include nav and main scroll frame").not.toBeNull();
expect(shellScroll!.maxScroll, "main content should own the vertical overflow").toBeGreaterThan(0);
expect(shellScroll!.mainScrollTop, "main content should scroll independently").toBeGreaterThan(0);
expect(shellScroll!.navTopDelta, "GNB should remain fixed while main content scrolls").toBeLessThanOrEqual(1);
expect(shellScroll!.windowScrollDelta, "document should not be the app scroll owner").toBeLessThanOrEqual(1);
});
await page.setViewportSize({ width: 1200, height: 1320 });
await expect(page.locator(".lh-tabs")).toBeVisible();
await page.screenshot({
path: path.join(SHOT_DIR, "learner-home__1200-reference-dark.png"),
fullPage: true,
});
await page.getByRole("button", { name: "라이트 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
const lightAssets = await page.evaluate(() => {
const card = document.querySelector<HTMLElement>(".lh-metric-card");
const shellBody = document.querySelector<HTMLElement>(".vg-shell--learner-dashboard .vg-shell__body");
const nav = document.querySelector<HTMLElement>(".vg-shell--learner-dashboard .vg-nav");
return {
card: card ? getComputedStyle(card, "::after").backgroundImage : "",
cardSurface: card
? {
backgroundImage: getComputedStyle(card).backgroundImage,
backdropFilter: getComputedStyle(card).backdropFilter,
boxShadow: getComputedStyle(card).boxShadow,
}
: null,
shellBody: shellBody ? getComputedStyle(shellBody).backgroundImage : "",
nav: nav ? getComputedStyle(nav).backgroundImage : "",
};
});
expect(lightAssets.card).toContain("card-leaf-sprig-light.png");
expect(lightAssets.cardSurface).not.toBeNull();
expect(lightAssets.cardSurface!.boxShadow).not.toBe("none");
expect(lightAssets.shellBody).toContain("background-light-corner.png");
expect(lightAssets.nav).toContain("background-light-sidebar.png");
await page.screenshot({
path: path.join(SHOT_DIR, "learner-home__1200-reference-light.png"),
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
await page.evaluate(() => window.scrollTo(0, 0));
const lightMobileReport = await auditClipping(page);
expect(lightMobileReport.horizontalOverflow, "[learner-home light @ 390] horizontal overflow").toBeLessThanOrEqual(1);
expect(lightMobileReport.offenders, "[learner-home light @ 390] clipped controls").toEqual([]);
await expect
.poll(() =>
page.locator(".vg-shell--learner-dashboard .vg-shell__body").evaluate((element) => getComputedStyle(element).backgroundImage),
)
.toContain("background-light-corner.png");
await page.screenshot({
path: path.join(SHOT_DIR, "learner-home__390-reference-light.png"),
fullPage: true,
});
await page.getByRole("button", { name: "다크 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
});
test("session prestart stays contained across all widths", async ({ page }) => {
await signInAsLearner(page);
const persona = await fetchAvailablePersona(page, 1);
await page.goto(`/learn/session/${persona.code}`);
await gateScreen(page, "session-prestart", async () => {
await expect(page.getByRole("button", { name: "회기 시작" })).toBeVisible({
timeout: 15_000,
});
const plan = page.locator(".sx-prestart__plan");
await expect(plan).toContainText("준비");
await expect(plan).toContainText("대화");
await expect(plan).toContainText("리뷰·재연습");
await expect(plan).toContainText("위험 신호는 대화보다 안전 확인을 우선합니다.");
const widths = await page.evaluate(() => {
const head = document.querySelector<HTMLElement>(".sx-page--prestart .sx-head");
const prestart = document.querySelector<HTMLElement>(".sx-page--prestart .sx-prestart");
return {
head: head?.getBoundingClientRect().width ?? 0,
prestart: prestart?.getBoundingClientRect().width ?? 0,
};
});
expect(widths.head).toBeGreaterThan(0);
expect(
Math.abs(widths.head - widths.prestart),
`prestart width ${widths.prestart}px should align with head width ${widths.head}px`,
).toBeLessThanOrEqual(1);
});
await page.setViewportSize({ width: 1280, height: 800 });
await page.getByRole("button", { name: "라이트 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
await expect(page.locator(".sx-prestart")).toHaveClass(/vg-surface--panel/);
await expect(page.locator(".sx-prestart__plan")).toHaveClass(/vg-surface--inset/);
const insetSurface = await page.locator(".sx-prestart__plan").evaluate((element) => {
const style = getComputedStyle(element);
return {
borderTopWidth: style.borderTopWidth,
borderRadius: style.borderRadius,
};
});
expect(insetSurface).toEqual({ borderTopWidth: "1px", borderRadius: "6px" });
await page.screenshot({
path: path.join(SHOT_DIR, "session-prestart__1280-reference-light.png"),
fullPage: true,
});
await page.getByRole("button", { name: "다크 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
});
test("active session keeps controls contained across all widths", async ({ page }) => {
await signInAsLearner(page);
const persona = await fetchAvailablePersona(page, 1);
await page.goto(`/learn/session/${persona.code}`);
await page.getByRole("button", { name: "회기 시작" }).click();
await completeAlliancePreCheckpoint(page);
await expect(page.locator(".sx-page--active")).toBeVisible({ timeout: 15_000 });
await gateScreen(page, "session-active", async () => {
await expect(page.locator(".sx-page--active")).toBeVisible();
});
});
test("session review stays contained across all widths", async ({ page }) => {
await signInAsLearner(page);
await routeFilledSessionReview(page);
await routePrepostMeasures(page);
await page.goto(`/learn/session/${FILLED_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review", async () => {
await expect(page.locator(".sr-overview")).toBeVisible({ timeout: 15_000 });
await openReviewTabIfPresent(page, "워크시트");
await expect(page.getByText("사례개념화 워크시트")).toBeVisible();
await openReviewTabIfPresent(page, "축어록");
await expectFilledReviewLearnerWorkbench(page);
});
});
test("professor session review avoids dead vertical gaps across all widths", async ({ page }) => {
await signInAsTeacher(page);
await routeFilledSessionReview(page, TEACHER_REVIEW_SESSION_ID);
await page.goto(`/teach/session/${TEACHER_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review-professor", async () => {
await expect(page.locator(".sr-cols--supervisor")).toBeVisible({ timeout: 15_000 });
await openReviewTabIfPresent(page, "피드백");
await expect(page.getByText("교수자 검토", { exact: true })).toBeVisible();
await openReviewTabIfPresent(page, "축어록");
await expect(page.getByText("세션 트랜스크립트")).toBeVisible();
await expectSupervisorReviewNoDeadGaps(page);
});
});
test("empty session review avoids sparse column gaps across all widths", async ({ page }) => {
await signInAsLearner(page);
await routeEmptySessionReview(page);
await routePrepostMeasures(page);
await page.goto(`/learn/session/${EMPTY_REVIEW_SESSION_ID}/review`);
await gateScreen(page, "session-review-empty", async () => {
await expect(page.locator(".sr-root--empty")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("축어록 저장 후 생성")).toBeVisible();
await openReviewTabIfPresent(page, "피드백");
await expect(page.getByText("감정 타임라인 대기")).toBeVisible();
await openReviewTabIfPresent(page, "축어록");
await expectEmptyReviewNoDeadThirdColumn(page);
});
});
test("professor console stays contained across all widths", async ({ page }) => {
await signInAsTeacher(page);
await page.goto("/teach");
await gateScreen(page, "professor", async () => {
await expect(page.locator(".pf-root--console")).toBeVisible({
timeout: 15_000,
});
await expect(page.locator(".pf-triage__copy > span").last()).toContainText("실제 기록", {
timeout: 15_000,
});
await expect(page.getByRole("button", { name: "새로고침" })).toBeEnabled();
await expectProfessorSummaryGap(page);
});
});
test("professor student analysis overview stays contained across all widths", async ({ page }) => {
const fixture = teacherAnalysisFixture();
await page.route("**/api/teacher/dashboard", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.dashboard),
}),
);
await signInAsTeacher(page);
await page.goto("/teach/analysis");
await gateScreen(page, "professor-analysis", async () => {
await expect(page.locator('[data-learner-overview-table="true"]')).toBeVisible({
timeout: 15_000,
});
await expect(page.locator('[data-learner-overview-row="true"]')).toHaveCount(1);
await expect(page.locator('[data-learner-analysis-panel="true"]')).toHaveCount(0);
await expect(page.getByLabel("학습자 검색")).toBeVisible();
const expandButton = page.getByRole("button", { name: /분석 검증 학습자 요약/ });
if ((await expandButton.getAttribute("aria-expanded")) !== "true") {
await expandButton.click();
}
await expect(page.locator('[data-learner-expanded-row="true"]')).toBeVisible();
});
});
test("professor learner detail analysis stays contained across all widths", async ({ page }) => {
const fixture = teacherAnalysisFixture();
await page.route("**/api/teacher/dashboard", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.dashboard),
}),
);
await page.route("**/api/teacher/learners/*/analysis", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(fixture.analysis),
}),
);
await signInAsTeacher(page);
await page.goto(`/teach/analysis?learner=${fixture.analysis.learner_id}`);
await gateScreen(page, "professor-analysis-detail", async () => {
await expect(page.locator('[data-learner-analysis-panel="true"]')).toBeVisible({
timeout: 15_000,
});
await expect(page.locator('[data-learner-persona-group="true"]')).toHaveCount(2);
const firstPersona = page.locator('[data-learner-persona-group="true"]').first();
const expandButton = firstPersona.getByRole("button", { name: /회기 (펼치기|접기)/ });
if ((await expandButton.getAttribute("aria-expanded")) !== "true") {
await expandButton.click();
}
await expect(page.locator('[data-learner-persona-sessions="true"]')).toBeVisible();
await expect(page.locator('[data-learner-session-row="true"]').first()).toBeVisible();
});
});
test("persona workspace stays contained across all widths", async ({ page }) => {
await signInAsTeacher(page);
await page.goto("/teach/personas");
await gateScreen(page, "persona-workspace", async () => {
await expect(page.locator(".ps-overview")).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole("heading", { name: "페르소나 운영" })).toBeVisible();
await expect(page.getByRole("navigation", { name: "페르소나 관리 영역" })).toBeVisible();
await expect(page.getByRole("button", { name: "새로고침" })).toBeEnabled({ timeout: 15_000 });
await expect(page.locator(".ps-error")).toHaveCount(0);
});
});
test("persona authoring steps stay contained across all widths", async ({ page }) => {
await signInAsTeacher(page);
await page.goto("/teach/personas?view=personas&mode=create&step=edit");
await gateScreen(page, "persona-authoring", async () => {
await expect(page.locator(".ps-authoring-layout")).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole("navigation", { name: "페르소나 작성 단계" })).toBeVisible();
await expect(page.getByRole("tab", { name: "개요" })).toBeVisible();
await expect(page.getByRole("button", { name: "새로고침" })).toBeEnabled({ timeout: 15_000 });
});
});
test("admin console stays contained across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/admin");
await gateScreen(page, "admin", async () => {
await expect(page.locator("main").first()).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole("button", { name: "새로고침" })).toBeEnabled({ timeout: 15_000 });
await expect(page.locator(".vgops-status > div > span")).not.toHaveText("연결 확인 중");
});
});
test("admin AI operations stays contained across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/admin/ai");
await gateScreen(page, "admin-ai", async () => {
await expect(page.getByRole("heading", { name: "AI 운영과 DB 계량" })).toBeVisible({
timeout: 15_000,
});
await expect(page.locator(".aic-grid")).toBeVisible();
const adminAi = page.getByTestId("admin-ai-page");
await expect(adminAi).toHaveAttribute("aria-busy", "false", { timeout: 15_000 });
await expect(adminAi.getByRole("button", { name: "새로고침", exact: true })).toBeEnabled();
await expect(page.locator(".aic-source b")).not.toHaveText("계량 원천 확인 중");
await expect(page.getByText("현재 AI 엔진 설정을 불러오는 중입니다.")).toHaveCount(0);
await expect(page.locator('[data-testid="provider-connections-panel"] .aic-runtime')).not.toHaveText("확인 중");
});
});
test("admin user table keeps its own horizontal scroll", async ({ page }) => {
test.setTimeout(60_000);
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/admin/users");
await page.getByRole("tab", { name: "사용자 목록" }).evaluate((element) => element.click());
await expect(page.getByRole("table")).toBeVisible({ timeout: 15_000 });
for (const viewport of [
{ width: 1280, height: 800, label: "desktop" },
{ width: 390, height: 844, label: "mobile" },
]) {
await page.setViewportSize(viewport);
await expectNoHorizontalOverflow(page);
await expect.poll(() => page.locator('[data-admin-section="users"]').evaluate((element) => {
const rect = element.getBoundingClientRect();
return rect.left >= -1 && rect.right <= window.innerWidth + 1;
})).toBe(true);
const scrollReport = await page.locator(".vgops-user-table-scroll").evaluate((element) => {
element.scrollLeft = 0;
const report = {
clientWidth: element.clientWidth,
scrollWidth: element.scrollWidth,
initialScroll: element.scrollLeft,
};
element.scrollLeft = element.scrollWidth;
return { ...report, finalScroll: element.scrollLeft };
});
expect(scrollReport.scrollWidth, `[admin users @ ${viewport.label}] table min width`).toBeGreaterThan(
scrollReport.clientWidth,
);
expect(scrollReport.finalScroll, `[admin users @ ${viewport.label}] horizontal scroll`).toBeGreaterThan(
scrollReport.initialScroll,
);
await expect(page.getByRole("columnheader", { name: /작업/ })).toBeVisible();
await page.locator(".vgops-user-table-scroll").evaluate((element) => {
element.scrollLeft = 0;
});
await resetScrollableOwners(page);
await page.screenshot({
path: path.join(SHOT_DIR, `admin-users__${viewport.width}-reference-dark.png`),
fullPage: true,
});
}
await page.setViewportSize({ width: 1280, height: 800 });
await page.getByRole("button", { name: "라이트 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
await page.screenshot({
path: path.join(SHOT_DIR, "admin-users__1280-reference-light.png"),
fullPage: true,
});
});
test("settings stays contained across all widths", async ({ page }) => {
await page.request.post("/api/auth/dev-login", {
data: { email: "admin@twentyoz.kr", role: "admin", display_name: "E2E Admin" },
});
await page.goto("/settings");
await gateScreen(page, "settings", async () => {
await expect(page.locator("main").first()).toBeVisible({ timeout: 15_000 });
await expect(page.locator(".vg-set")).toHaveAttribute("aria-busy", "false", { timeout: 15_000 });
await expect(page.locator(".vg-set__callout--warn")).toHaveCount(0);
});
await page.setViewportSize({ width: 1280, height: 800 });
await page.getByRole("button", { name: "라이트 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
await expect(page.locator(".vg-set__group").first()).toHaveAttribute("data-surface", "panel");
await page.screenshot({
path: path.join(SHOT_DIR, "settings__1280-reference-light.png"),
fullPage: true,
});
await page.getByRole("button", { name: "다크 모드로" }).click();
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
});
});