- room: reveal 단계 키를 게임 마감만으로, clockExtra = max(본인, 답할 사람들) - 라이어·마피아·아발론 시계, 뱅 반응·차례 타이머, 바둑 계가·마작 울기 타이머가 방 마감(연출 시간 포함)을 따름 - 아발론 암살 마감: 당겨진 마감은 숨기고 늘어난 마감은 보여 줌(무제한이면 그대로 숨김) - 테스트: 공통 재투표(대표자 A·느린 B·A 투표 후 유지), e2e 라이어 화면 시계 = 방 마감 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
274 lines
16 KiB
TypeScript
274 lines
16 KiB
TypeScript
/**
|
||
* E2E: results wait for the animation (2026-11-08, "애니메이션 전부 보고나서 결과").
|
||
* - 윷놀이: something on the board moves for 30 s after the winning move; the result window waits for all of it.
|
||
* - 바퀴벌레 포커: the call that ends the game — the end table / result never show while its animation still runs.
|
||
* - 증강 윷놀이 이의있음!: the redo selection opens only after the full-screen call has gone.
|
||
* - 다빈치 코드 at ×1/8: after a correct guess the 계속/멈추기 choice appears after the long flip, and the server
|
||
* still gives the full time for it (the clock starts when the screen has settled), so the player can stop.
|
||
* Run: bun e2e/motion.e2e.ts (needs apps/web/dist built)
|
||
*/
|
||
import { chromium, type Page } from 'playwright-core';
|
||
import { mkdtempSync } from 'node:fs';
|
||
import { join } from 'node:path';
|
||
import { loadConfig } from '../apps/server/src/config';
|
||
import { startServer } from '../apps/server/src/server';
|
||
import { tileOf } from '../packages/games/src/davinci-code';
|
||
|
||
const PORT = Number(process.env.E2E_PORT ?? 4551);
|
||
const ORIGIN = `http://localhost:${PORT}`;
|
||
const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-'));
|
||
const app = startServer({
|
||
config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN }),
|
||
log: () => {},
|
||
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
||
});
|
||
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||
let failed = false;
|
||
const step = async (name: string, fn: () => Promise<void>) => {
|
||
const t0 = performance.now();
|
||
try {
|
||
await fn();
|
||
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
|
||
} catch (e) {
|
||
failed = true;
|
||
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
|
||
}
|
||
};
|
||
const setSpeed = (gameSpeed: number) => app.settings.setSite({ ...app.settings.getSite(), gameSpeed }, 'e2e');
|
||
let cs = 1_000_000;
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
type AnyRoom = any;
|
||
|
||
async function practice(
|
||
gameId: string,
|
||
nick: string,
|
||
options?: (o: Record<string, unknown>) => Record<string, unknown>,
|
||
bots = 1,
|
||
): Promise<{ p: Page; room: AnyRoom; me: string; bot: string }> {
|
||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 }, locale: 'ko-KR' });
|
||
await ctx.addInitScript((g) => localStorage.setItem(`bg:qs:${g}`, '1'), gameId);
|
||
const p = await ctx.newPage();
|
||
p.on('pageerror', (e) => console.log(` pageerror: ${e.message}`));
|
||
await p.goto(`${ORIGIN}/g/${gameId}`);
|
||
await p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
|
||
await p.getByLabel('내 이름(닉네임)').fill(nick);
|
||
await p.getByRole('button', { name: '이 이름으로 시작하기' }).click();
|
||
await p.waitForURL(/\/r\/\d{6}$/);
|
||
const room: AnyRoom = app.rooms.get(p.url().split('/').pop()!);
|
||
await p.getByLabel('자리').getByText('컴퓨터 1').waitFor();
|
||
if (options) {
|
||
room.config.options = options(room.config.options);
|
||
room.broadcastRoom();
|
||
}
|
||
for (let i = 1; i < bots; i++) {
|
||
await p.getByRole('button', { name: '🤖 컴퓨터 넣기' }).first().click();
|
||
await p.getByLabel('자리').getByText(`컴퓨터 ${i + 1}`).waitFor();
|
||
}
|
||
await p.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||
for (let i = 0; i < 100 && !room.game; i++) await Bun.sleep(50);
|
||
const me = room.game.players.find((u: string) => !u.startsWith('bot:'))!;
|
||
const bot = room.game.players.find((u: string) => u.startsWith('bot:'))!;
|
||
return { p, room, me, bot };
|
||
}
|
||
|
||
/**
|
||
* Polls until an element matching `sel` (containing `text`, if given) is on screen; fails if it appears while a finite
|
||
* animation is still running elsewhere on the page (what lib/motion counts as moving; the shown element's own entrance
|
||
* animation, its backdrop and anything that started in the same moment don't count). Returns ms until shown.
|
||
*/
|
||
async function shownOnlyAfterMotion(p: Page, sel: string, text: string | null, limitMs: number, what: string): Promise<number> {
|
||
const t0 = Date.now();
|
||
while (Date.now() - t0 < limitMs) {
|
||
const r = await p.evaluate(
|
||
([sel, text]) => {
|
||
const hits = [...document.querySelectorAll(sel!)].filter((e) => !text || e.textContent?.includes(text));
|
||
if (!hits.length) return null;
|
||
const own = (el: Element) => hits.some((h) => h.contains(el) || h.closest('.sheet-backdrop')?.contains(el));
|
||
return document.getAnimations().filter((a) => {
|
||
if (a.playState !== 'running' && !a.pending) return false;
|
||
const t = a.effect?.getComputedTiming();
|
||
if (!t || t.endTime === Infinity) return false;
|
||
const el = a.effect instanceof KeyframeEffect ? a.effect.target : null;
|
||
// started together with what was just shown (the loser's seat turning red): part of it, not before it
|
||
if (Number(a.currentTime ?? 0) < 150) return false;
|
||
if (!(el instanceof Element)) return true;
|
||
return !own(el) && !el.closest('.chat-panel, [role="timer"], .toasts, .toast, [data-motion-free]');
|
||
}).map((a) => {
|
||
const el = a.effect instanceof KeyframeEffect ? a.effect.target : null;
|
||
return `${(a as CSSAnimation).animationName ?? 'waapi'}@${el instanceof Element ? el.className : '?'}`;
|
||
});
|
||
},
|
||
[sel, text] as const,
|
||
);
|
||
if (r) {
|
||
if (r.length) throw new Error(`${what} showed while animations were still running: ${r.join(', ')} (${Date.now() - t0}ms)`);
|
||
return Date.now() - t0;
|
||
}
|
||
await Bun.sleep(40);
|
||
}
|
||
throw new Error(`${what} never showed within ${limitMs}ms`);
|
||
}
|
||
|
||
const RESULT = '[role="dialog"][aria-label="게임 결과"]';
|
||
|
||
try {
|
||
await step('윷놀이: 30초짜리 움직임이 끝날 때까지 결과 창이 기다림(시간 상한 없음)', async () => {
|
||
setSpeed(1);
|
||
const { p, room, me } = await practice('yut', '호랑이', (o) => ({ ...o, augmented: false }));
|
||
const s = room.game.state;
|
||
const side = s.sideOf[me];
|
||
// My last piece 5 squares before going out; I hold a 모.
|
||
let picked: number | null = null;
|
||
for (const node of [15, 16, 17, 18, 19]) {
|
||
for (const [i, pc] of s.sides[side].pieces.entries()) Object.assign(pc, i === 0 ? { status: 'board', node, trail: [node], lapped: false } : { status: 'done', node: null, trail: [] });
|
||
Object.assign(s, { current: me, turnSide: side, phase: 'move', throwsOwed: 0, pending: ['mo'] });
|
||
const moves = room.def.view(s, me).legalMoves ?? [];
|
||
if (moves.some((m: { to: unknown; path: unknown[] }) => m.to === 'goal' && m.path.length >= 4)) {
|
||
picked = node;
|
||
break;
|
||
}
|
||
}
|
||
if (picked === null) throw new Error('no square 4+ hops from going out');
|
||
room.broadcastState([]);
|
||
await Bun.sleep(1500);
|
||
// Something on the board keeps moving for 30 s (longer than any time limit the wait used to have, twice over).
|
||
await p.evaluate(() => document.querySelector('.yut-board')!.animate([{ opacity: 1 }, { opacity: 0.9 }], { duration: 30_000 }));
|
||
room.act(me, cs++, { type: 'MOVE', throwIndex: 0, from: picked });
|
||
const ms = await shownOnlyAfterMotion(p, RESULT, null, 120_000, 'result window');
|
||
if (await p.locator('.yut-hop').count()) throw new Error('result window showed while the piece was still hopping');
|
||
if (ms < 29_000) throw new Error(`result after ${ms}ms, before the 30 s animation ended`);
|
||
console.log(` yut: result window ${ms}ms after the winning move`);
|
||
await p.context().close();
|
||
});
|
||
|
||
await step('바퀴벌레 포커: 게임을 끝내는 판정 연출이 다 끝난 뒤에 끝 화면·결과 창', async () => {
|
||
setSpeed(1);
|
||
const { p, room, me, bot } = await practice('cockroach-poker', '호랑이');
|
||
// Whoever takes the next card loses: both fronts already have one too few of every kind it could be.
|
||
const s = room.game.state;
|
||
const kinds = [...new Set([...Object.values(s.hands as Record<string, string[]>).flat()].map((id) => id.slice(0, id.lastIndexOf('-'))))];
|
||
for (const u of [me, bot]) s.fronts[u] = kinds.flatMap((k) => Array.from({ length: s.loseCount - 1 }, (_, i) => `${k}-f${u.length}${i}`));
|
||
room.broadcastState([]);
|
||
await Bun.sleep(1500);
|
||
// I start: offer a card to the computer; if it comes back to me, I call.
|
||
for (let i = 0; i < 600 && !room.game.finished; i++) {
|
||
const g = room.game.state;
|
||
if (g.round.holder === null && g.round.starter === me) {
|
||
const card = g.hands[me][0];
|
||
room.act(me, cs++, { type: 'offer', cardId: card, to: bot, claim: card.slice(0, card.lastIndexOf('-')) });
|
||
} else if (g.round.holder === me && !g.round.peeked) room.act(me, cs++, { type: 'call', call: 'true' });
|
||
await Bun.sleep(100);
|
||
}
|
||
if (!room.game.finished) throw new Error('the game did not end');
|
||
const ms = await shownOnlyAfterMotion(p, '.cp-table', '게임이 끝났어요', 30_000, 'end of the game');
|
||
await shownOnlyAfterMotion(p, RESULT, null, 30_000, 'result window');
|
||
console.log(` cockroach-poker: end shown ${ms}ms after the last call`);
|
||
await p.context().close();
|
||
});
|
||
|
||
await step('증강 윷놀이: 이의있음! 화면이 사라진 뒤에 다시 고르는 창이 열림(같은 후보가 다시 나와도)', async () => {
|
||
const { p, room, me, bot } = await practice('yut', '호랑이', (o) => ({ ...o, augmented: true }));
|
||
for (let i = 0; i < 100 && !room.game.state.aug?.select; i++) await Bun.sleep(50);
|
||
const st = () => room.game.state;
|
||
const mine = String(st().sideOf[me]);
|
||
const theirs = String(st().sideOf[bot]);
|
||
// The computer already picked 이의있음!; I pick last.
|
||
const sel = st().aug.select;
|
||
sel.offers[mine] = ['shield', 'tiger', 'fog'];
|
||
sel.offers[theirs] = [];
|
||
sel.left[theirs] = 0;
|
||
sel.picks = [{ side: Number(theirs), id: 'objection' }];
|
||
// The redo deals me the very same offers again (the window must still wait for the call to go away).
|
||
const send = room.broadcastState.bind(room);
|
||
room.broadcastState = (...args: unknown[]) => {
|
||
if (st().aug.select?.redo) st().aug.select.offers[mine] = ['shield', 'tiger', 'fog'];
|
||
return send(...args);
|
||
};
|
||
room.broadcastState([]);
|
||
if (!(await p.locator('.aug-cards').count())) await p.getByRole('button', { name: '증강 후보 보기' }).click();
|
||
await p.locator('.aug-card').first().click();
|
||
await p.locator('.sheet button.btn-primary').last().click();
|
||
await p.locator('.aug-objection').waitFor({ timeout: 10_000 });
|
||
const t0 = Date.now();
|
||
while (await p.locator('.aug-objection').count()) {
|
||
if (await p.getByRole('dialog', { name: /증강 선택/ }).count()) throw new Error('the redo selection opened under the 이의있음! call');
|
||
await Bun.sleep(50);
|
||
}
|
||
await p.getByRole('dialog', { name: /증강 선택/ }).waitFor({ timeout: 10_000 });
|
||
if (st().aug.select.offers[mine].join() !== 'shield,tiger,fog') throw new Error('the redo did not deal the same offers');
|
||
console.log(` yut-aug: 이의있음! on screen ${Date.now() - t0}ms, then the redo selection`);
|
||
await p.context().close();
|
||
});
|
||
|
||
await step('다빈치 코드 ×1/8: 맞힌 뒤 긴 뒤집기 연출 다음에도 계속/멈추기 시간이 남아 있음', async () => {
|
||
setSpeed(1 / 8);
|
||
const { p, room, me, bot } = await practice('davinci-code', '호랑이');
|
||
if (await p.getByRole('button', { name: '검정 2개 · 흰색 2개' }).count()) {
|
||
await p.getByRole('button', { name: '검정 2개 · 흰색 2개' }).click();
|
||
await p.getByRole('button', { name: '이렇게 받기' }).click();
|
||
}
|
||
for (let i = 0; i < 600 && !(room.game.state.current === me && room.game.state.phase.kind === 'draw'); i++) await Bun.sleep(100);
|
||
if (room.game.state.phase.kind !== 'draw' || room.game.state.current !== me) throw new Error('never my turn to draw');
|
||
await Bun.sleep(1000);
|
||
room.act(me, cs++, { type: 'draw', color: room.game.state.pool.black.length ? 'black' : 'white' });
|
||
await Bun.sleep(1000);
|
||
const row = room.game.state.rows[bot] as { id: string; revealed: boolean }[];
|
||
const index = row.findIndex((t) => !t.revealed);
|
||
room.act(me, cs++, { type: 'guess', target: bot, index, value: tileOf(row[index]!.id).n });
|
||
if (room.game.state.phase.kind !== 'afterCorrect') throw new Error(`guess was not correct (${room.game.state.phase.kind})`);
|
||
const t0 = Date.now();
|
||
const stop = p.getByRole('button', { name: '여기서 멈추기' });
|
||
await stop.waitFor({ timeout: 90_000 });
|
||
const waited = Date.now() - t0;
|
||
if (waited < 10_000) throw new Error(`the choice showed after ${waited}ms; the flip at ×1/8 should take longer than the 10 s choice time`);
|
||
if (room.game.state.phase.kind !== 'afterCorrect' || room.game.state.current !== me) throw new Error('the server timed my choice out while the screen was still animating');
|
||
// The clock on my screen is the server's (moved) deadline, not the one sent with the state.
|
||
await Bun.sleep(500);
|
||
const label = (await p.locator('[role="timer"]').first().getAttribute('aria-label')) ?? '';
|
||
const shown = Number(label.match(/(\d+)초/)?.[1] ?? NaN);
|
||
const left = (room.effectiveDeadline() - Date.now()) / 1000;
|
||
if (!(Math.abs(shown - left) <= 1.5)) throw new Error(`screen timer says ${shown}s, server has ${left.toFixed(1)}s left`);
|
||
await Bun.sleep(3000);
|
||
await stop.click();
|
||
for (let i = 0; i < 50 && room.game.state.phase.kind === 'afterCorrect'; i++) await Bun.sleep(100);
|
||
if (room.game.state.idle[me]) throw new Error('my stop counted as a timeout');
|
||
if (room.game.state.current === me) throw new Error('stopping did not pass the turn');
|
||
console.log(` davinci-code: choice shown ${waited}ms after the guess (timer ${shown}s, server ${left.toFixed(1)}s), stopped 3 s later without a timeout`);
|
||
await p.context().close();
|
||
setSpeed(1);
|
||
});
|
||
|
||
await step('라이어 게임: 연출이 끝난 만큼 늘어난 마감이 화면 시계에도 그대로', async () => {
|
||
const { p, room, me } = await practice('liar', '호랑이', undefined, 2);
|
||
// My screen is made to look 6 s slow to finish each step: the room gives 6 s more, and my clock must show it.
|
||
const report = room.settled.bind(room);
|
||
room.settled = (u: string, seq: number) => {
|
||
if (u === me && room.reveal && !room.reveal.done.has(u)) room.reveal.at -= 6_000;
|
||
return report(u, seq);
|
||
};
|
||
let checked = 0;
|
||
for (let i = 0; i < 400 && checked < 3; i++) {
|
||
await Bun.sleep(250);
|
||
const ph = room.game?.state?.phase;
|
||
const done = room.reveal?.done.get(me);
|
||
if (!ph || ph.endsAt == null || done === undefined || Date.now() - done < 1_000) continue;
|
||
const label = (await p.locator('.lg-clock[role="timer"]').first().getAttribute('aria-label').catch(() => null)) ?? '';
|
||
const shown = Number(label.match(/(\d+)초/)?.[1] ?? NaN);
|
||
const left = (room.publicDeadline() - Date.now()) / 1000;
|
||
const plain = (ph.endsAt - Date.now()) / 1000;
|
||
if (room.reveal?.done.get(me) !== done || room.game.state.phase !== ph) continue; // the step moved on meanwhile
|
||
if (left - plain < 5) throw new Error(`room deadline not moved: ${left.toFixed(1)}s vs phase ${plain.toFixed(1)}s`);
|
||
if (!(Math.abs(shown - left) <= 1.5)) throw new Error(`clock says ${shown}s, the room has ${left.toFixed(1)}s (phase alone ${plain.toFixed(1)}s)`);
|
||
checked++;
|
||
}
|
||
if (checked < 3) throw new Error(`only ${checked} clock checks happened`);
|
||
console.log(' liar: the clock follows the moved deadline (3 checks)');
|
||
await p.context().close();
|
||
});
|
||
} finally {
|
||
await browser.close();
|
||
app.stop?.();
|
||
}
|
||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||
process.exit(failed ? 1 : 0);
|