diff --git a/apps/web/src/net/duel-player.ts b/apps/web/src/net/duel-player.ts index ffdbb14..8c0c79d 100644 --- a/apps/web/src/net/duel-player.ts +++ b/apps/web/src/net/duel-player.ts @@ -26,6 +26,8 @@ interface Slot { loaded: boolean; /** Bumped by every command, so an older preload stops before pausing a song the player started meanwhile. */ tk: number; + /** A tap before the player was ready: the load waits for it (cancelled when another card is tapped or this one again). */ + pending: boolean; } const slots = new Map(); @@ -40,6 +42,7 @@ function make(): Slot { gain: 1, loaded: false, tk: 0, + pending: false, }; s.engine = cardEngine({ onError: (code) => { @@ -89,6 +92,16 @@ async function preload(s: Slot): Promise { video: (side: DuelSide) => slots.get(side)?.videoId ?? null, }; +/** Stop this card: pause it and drop a load still waiting for the player to get ready. */ +function halt(s: Slot): void { + if (s.pending) { + s.tk++; + s.pending = false; + s.loaded = false; + } + s.engine.pause(); +} + const volumeOf = (s: Slot) => Math.round(usePlayer.getState().volume * s.gain); usePlayer.subscribe((st, prev) => { @@ -103,8 +116,8 @@ export const duelPlayer = { key = k; const old = new Map(slots); for (const s of old.values()) { + halt(s); s.tk++; - s.engine.pause(); } useDuelPlayer.setState({ playing: null }); const next = new Map(); @@ -133,11 +146,11 @@ export const duelPlayer = { if (!s?.videoId) return; const st = useDuelPlayer.getState(); if (st.playing === side) { - s.engine.pause(); + halt(s); useDuelPlayer.setState({ playing: null }); return; } - for (const [other, o] of slots) if (other !== side) o.engine.pause(); + for (const [other, o] of slots) if (other !== side) halt(o); const tk = ++s.tk; const e = s.engine; const id = s.videoId; @@ -146,7 +159,12 @@ export const duelPlayer = { if (s.loaded) e.play(); else { s.loaded = true; - void s.ready.then(() => tk === s.tk && e.load(id, s.startSec)); + s.pending = true; + void s.ready.then(() => { + if (tk !== s.tk) return; + s.pending = false; + e.load(id, s.startSec); + }); } useDuelPlayer.setState({ playing: side }); }, @@ -154,8 +172,8 @@ export const duelPlayer = { stop(): void { key = ''; for (const s of slots.values()) { + halt(s); s.tk++; - s.engine.pause(); } useDuelPlayer.setState({ playing: null }); }, diff --git a/apps/web/src/net/player.ts b/apps/web/src/net/player.ts index eb1dec5..0c88b52 100644 --- a/apps/web/src/net/player.ts +++ b/apps/web/src/net/player.ts @@ -249,7 +249,11 @@ function fakeEngine(l: Listener): Engine { (window as unknown as { mqFake: typeof fake }).mqFake = fake; const time = () => (state === 1 ? base + (performance.now() - since) / 1000 : base); return { - init: () => Promise.resolve(), + // e2e: localStorage mq:fakeInitMs makes the player get ready late (taps before it is ready) + init: () => { + const ms = Number(localStorage.getItem('mq:fakeInitMs') ?? 0); + return ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve(); + }, unlock: () => {}, load(id, startSec) { current = id; diff --git a/e2e/duel.e2e.ts b/e2e/duel.e2e.ts index 32c169e..e80cf4e 100644 --- a/e2e/duel.e2e.ts +++ b/e2e/duel.e2e.ts @@ -60,9 +60,10 @@ async function fakeDiscord(ctx: BrowserContext, discordId: string) { await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `` }); }); } -async function guestPage(name: string, opts: { width?: number; height?: number; mobile?: boolean; fake?: boolean } = {}): Promise { +async function guestPage(name: string, opts: { width?: number; height?: number; mobile?: boolean; fake?: boolean; initMs?: number } = {}): Promise { const ctx = await browser.newContext({ viewport: { width: opts.width ?? 1440, height: opts.height ?? 900 }, locale: 'ko-KR', isMobile: opts.mobile, hasTouch: opts.mobile }); if (opts.fake !== false) await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1')); + if (opts.initMs) await ctx.addInitScript((ms) => localStorage.setItem('mq:fakeInitMs', String(ms)), opts.initMs); const p = await ctx.newPage(); p.on('pageerror', (e) => errors.push(`${name}: ${e.message}`)); await p.goto(ORIGIN + '/'); @@ -197,6 +198,40 @@ try { await audit(host, 'PC 게임 결과'); }); + await step('플레이어 준비 전에 누르기: A→B면 B만 나오고 A는 안 나옴, A→A(멈춤)면 둘 다 안 나옴', async () => { + db.query("UPDATE custom_quizzes SET visibility = 'public' WHERE id = ?").run(quizId); + // players that get ready 5s late, so both taps land before + const x = await guestPage('늦은준비1', { initMs: 5000 }); + const y = await guestPage('늦은준비2', { initMs: 5000 }); + const rc = await x.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string); + await x.goto(`${ORIGIN}/r/${rc}`); + await x.getByRole('radio', { name: '🆚 이지선다' }).click(); + await x.getByRole('listbox', { name: '이지선다 퀴즈 목록' }).getByRole('option', { name: /조회수 대결/ }).click(); + await x.getByText('퀴즈 곡 4곡').waitFor(); + await y.goto(`${ORIGIN}/r/${rc}`); + await x.locator('.pl', { hasText: '늦은준비2' }).waitFor(); + await x.getByRole('button', { name: '게임 시작' }).click(); + await Promise.all([x, y].map((p) => p.locator('.duel-card').nth(1).waitFor({ timeout: 8000 }))); + await card(x, 'A').click(); + await card(x, 'B').click(); + await card(y, 'A').click(); + await card(y, 'A').click(); + // nothing has loaded yet (state 1 = playing; the fake's pause shows 2) + const before = await x.evaluate(() => [(window as any).mqDuel.state('a'), (window as any).mqDuel.state('b')]); + expect(!before.includes(1) && !before.includes(3), `준비 전이 아님 (상태 ${before})`); + await x.waitForFunction(() => (window as any).mqDuel.state('b') === 1, null, { timeout: 8000 }); + await x.waitForTimeout(500); + const st = (p: Page) => p.evaluate(() => ({ a: (window as any).mqDuel.state('a'), b: (window as any).mqDuel.state('b') })); + const sx = await st(x); + const sy = await st(y); + expect(sx.a !== 1 && sx.b === 1, `A→B: B만 나와야 함 ${JSON.stringify(sx)}`); + expect(sy.a !== 1 && sy.b !== 1, `A→A: 둘 다 멈춰야 함 ${JSON.stringify(sy)}`); + expect((await x.locator('.duel-card.playing').count()) === 1 && (await card(x, 'B').getAttribute('class'))!.includes('playing'), 'A→B 화면 표시가 B가 아님'); + expect((await y.locator('.duel-card.playing').count()) === 0, 'A→A 화면에 재생 중 표시가 남음'); + await x.context().close(); + await y.context().close(); + }); + if (!process.env.E2E_NO_YT) { await step('실제 유튜브: A를 누르면 소리 나게 재생, B를 누르면 A가 멈추고 B 재생, 다시 A는 멈춘 곳부터 이어서', async () => { const r = await host.evaluate(async () => {