Files
joke-app/e2e/motion.e2e.ts
EJClaw fa53175f51 결과는 움직임이 끝날 때까지(시간 상한 없음), 제한 시간은 각자 화면이 연출을 다 보여 준 뒤부터
- lib/motion: useMotionSettled에서 12초 상한을 없앰(명시한 maxMs만)
- 서버: 클라이언트 settled(seq)를 받으면 그 사람의 제한 시간을 연출에 걸린 만큼 늦춤(보고 전에는 최대 15초×속도,
  보고한 적 없는 화면·컴퓨터·실시간 게임은 예전 그대로), 마감이 바뀌면 deadline 메시지
- 바퀴벌레 포커: 게임을 끝낸 판정은 패배 배너까지 다 끝난 뒤에 끝 화면
- 증강 윷놀이: 선택 창 열림을 후보 묶음마다 따로, 이의있음! 재선택 창은 이의있음! 화면이 사라진 뒤에
- e2e/motion.e2e.ts: 30초 움직임·바퀴벌레 포커 마지막 판정·이의있음! 재선택·다빈치 ×1/8 회귀 확인, 방 타이머 단위 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00

224 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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>): 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();
}
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' }];
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 });
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');
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, stopped 3 s later without a timeout`);
await p.context().close();
setSpeed(1);
});
} finally {
await browser.close();
app.stop?.();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);