diff --git a/apps/server/src/game.test.ts b/apps/server/src/game.test.ts index e35636d..246e4e9 100644 --- a/apps/server/src/game.test.ts +++ b/apps/server/src/game.test.ts @@ -236,6 +236,60 @@ describe('game flow', () => { stop(); }); + test('새로고침 while the music runs: the new page catches up on the same timeline, nobody else stops, the answer still counts', async () => { + seedLater(() => seed(2)); + const { users, cls, code } = await room(['방장', '새로고침']); + const [a, b] = cls as [Client, Client]; + const stop = autoReady([a, b]); + a.send({ t: 'start' }); + const play = await nextOf(a, 'play', 0); + await sleep(Math.max(0, play.startAt - Date.now()) + 30); + const fa = since(a); + b.close(); + await gameWhere(a, (g) => g.scores.some((x) => x.id === users[1]!.id && !x.online)); + const b2 = await new Client(s.base, users[1]!.cookie).connect(); + b2.send({ t: 'join', code }); + const cu = await nextOf(b2, 'catchup', 0); + const prep = (await nextOf(a, 'prepare', 0)) as Msg<'prepare'>; + expect(cu).toMatchObject({ n: 1, videoId: prep.videoId, clipStart: prep.startSec, startAt: play.startAt, atSec: play.atSec, endSec: play.endSec }); + expect(b2.messages.some((m) => m.t === 'prepare' || m.t === 'play')).toBe(false); + // the others were never paused or re-prepared, and no "들어왔어요" line for someone who was already here + await sleep(60); + expect(a.messages.slice(fa).some((m) => m.t === 'pause' || m.t === 'prepare')).toBe(false); + expect(a.messages.slice(fa).some((m) => m.t === 'chat' && m.line.text.includes('들어왔어요'))).toBe(false); + // still a player of this question: the answer counts + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(prep.videoId)!.title; + b2.send({ t: 'chat', text: title }); + expect((await gameWhere(a, (g) => g.phase === 'reveal')).history[0]).toMatchObject({ winnerId: users[1]!.id, how: 'correct' }); + stop(); + b2.close(); + }); + + test('새로고침 while waiting for ready: the new page gets the prepare again and the room waits for it (no stuck question)', async () => { + seedLater(() => seed(2)); + const { users, cls, code } = await room(['방장', '새로고침']); + const [a, b] = cls as [Client, Client]; + a.send({ t: 'start' }); + const prep = await nextOf(a, 'prepare', 0); + await nextOf(b, 'prepare', 0); + b.send({ t: 'audio', n: 1, ev: 'ready' }); + b.close(); + await gameWhere(a, (g) => g.scores.some((x) => x.id === users[1]!.id && !x.online)); + const b2 = await new Client(s.base, users[1]!.cookie).connect(); + b2.send({ t: 'join', code }); + expect(await nextOf(b2, 'prepare', 0)).toMatchObject({ n: 1, videoId: prep.videoId, startSec: prep.startSec }); + // the old page's ready is gone with it: 방장 alone does not start the music + const fa = since(a); + a.send({ t: 'audio', n: 1, ev: 'ready' }); + expect((await gameWhere(a, (g) => g.waiting.some((w) => w.id === users[1]!.id))).phase).toBe('prepare'); + await sleep(60); + expect(a.messages.slice(fa).some((m) => m.t === 'play')).toBe(false); + b2.send({ t: 'audio', n: 1, ev: 'ready' }); + const pa = await nextOf(a, 'play', fa); + expect((await nextOf(b2, 'play', 0)).startAt).toBe(pa.startAt); + b2.close(); + }); + test('player error 150 swaps the song for everyone under the same number and marks it unplayable', async () => { seedLater(() => seed(3)); const { cls } = await room(['방장', '철수']); diff --git a/apps/server/src/game/engine.ts b/apps/server/src/game/engine.ts index 1199440..f5b0e2a 100644 --- a/apps/server/src/game/engine.ts +++ b/apps/server/src/game/engine.ts @@ -504,6 +504,24 @@ export class Game { this.broadcast(); } + /** + * A player of this question is back (refresh / reconnect, same account within the grace period): bring their player to + * where everyone is. Waiting for ready → prepare again (their new page has nothing loaded, so the room waits for them); + * music running → catch up on the running timeline without stopping anyone. They can answer as before. + */ + rejoin(userId: string, send: (m: ServerMessage) => void): void { + if (!this.listening || !this.song?.videoId || !this.participants.has(userId) || this.excluded.has(userId)) return; + if (this.phase !== 'prepare' && this.phase !== 'play') return; + if (this.awaitingReady) { + this.ready.delete(userId); + if (!this.waitingSince.has(userId)) this.waitingSince.set(userId, this.now()); + send({ t: 'prepare', code: this.room.code, n: this.n, videoId: this.song.videoId, startSec: this.resumeAt, endSec: this.clip.endSec }); + this.broadcast(); + } else if (this.playing && !this.clipOver) { + send({ t: 'catchup', code: this.room.code, n: this.n, videoId: this.song.videoId, clipStart: this.clip.startSec, startAt: this.audioStartAt, atSec: this.audioAtSec, endSec: this.clip.endSec }); + } + } + /** Host: leave out someone who has not been ready for 30s (docs/12 Q1). */ exclude(target: string): string | null { const since = this.waitingSince.get(target); diff --git a/apps/server/src/rooms.test.ts b/apps/server/src/rooms.test.ts index 0823fe6..71ed2b0 100644 --- a/apps/server/src/rooms.test.ts +++ b/apps/server/src/rooms.test.ts @@ -150,6 +150,27 @@ describe('rooms over WebSocket', () => { expect((await nextRoom(ca, (x) => x.players.length === 1)).players[0]!.id).toBe(a.id); }); + test('a host who drops (새로고침) stays host for 15s; back in time keeps it, gone longer hands it to someone online', async () => { + const { a, b, ca, cb, code } = await setup(); + ca.close(); + await nextRoom(cb, (x) => x.players.some((p) => p.id === a.id && !p.online)); + s.rooms.sweep(Date.now() + 10_000); + expect(s.rooms.rooms.get(code)!.hostId).toBe(a.id); + // back (a refresh): still host, nothing said + const ca2 = await new Client(s.base, ca.cookie).connect(); + ca2.send({ t: 'join', code }); + await nextRoom(cb, (x) => x.players.every((p) => p.online)); + s.rooms.sweep(Date.now() + 20_000); + expect(s.rooms.rooms.get(code)!.hostId).toBe(a.id); + expect(chatOf(cb).some((l) => l.text.startsWith('방장이 '))).toBe(false); + // gone for good: after 15s the next player online takes over + ca2.close(); + await nextRoom(cb, (x) => x.players.some((p) => p.id === a.id && !p.online)); + s.rooms.sweep(Date.now() + 16_000); + expect((await nextRoom(cb, (x) => x.hostId === b.id)).hostId).toBe(b.id); + await cb.waitFor((m) => m.t === 'chat' && m.line.text === '방장이 손님님으로 바뀌었어요'); + }); + test('no player limit: 40 people in one room', async () => { const { ca, code } = await setup(); const clients: Client[] = []; diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index 673a330..e2f51c9 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -12,6 +12,8 @@ import type { WsData } from '../ws/gateway'; /** Back within this long after a disconnect: keeps the place (and later the score). */ export const GRACE_MS = 60_000; +/** The host dropped (refresh, short disconnect): stays host this long before someone online takes over. */ +export const HOST_HOLD_MS = 15_000; const EMPTY_ROOM_MS = 5 * 60_000; /** Chat lines a newcomer gets (the screen keeps 200, docs/06). */ export const CHAT_HISTORY = 100; @@ -235,6 +237,7 @@ export class RoomManager { if (prev && prev !== room) this.removePlayer(prev, userId, 'elsewhere'); if (ws.data.roomCode && ws.data.roomCode !== code) this.detach(ws); const p = already ?? { joinedAt: Date.now(), ready: false, conns: new Set(), offlineSince: null }; + const wasHere = !!already && ws.data.roomCode !== code; p.conns.add(ws); p.offlineSince = null; room.players.set(userId, p); @@ -244,8 +247,11 @@ export class RoomManager { if (!room.players.has(room.hostId)) room.hostId = userId; ws.send(JSON.stringify({ t: 'chatlog', code, lines: room.chat } satisfies ServerMessage)); room.broadcast(); - if (room.game) room.game.broadcast(); - else ws.send(JSON.stringify({ t: 'game', code, game: null } satisfies ServerMessage)); + if (room.game) { + room.game.broadcast(); + // Refresh / reconnect in the middle of a question: this socket's player joins the music where everyone is. + if (wasHere) room.game.rejoin(userId, (m) => ws.send(JSON.stringify(m))); + } else ws.send(JSON.stringify({ t: 'game', code, game: null } satisfies ServerMessage)); if (!already) room.say(null, room.game && room.game.phase !== 'result' ? `${room.nick(userId)}님이 들어왔어요 · 다음 문제부터 같이 해요` : `${room.nick(userId)}님이 들어왔어요`); return null; } @@ -262,10 +268,8 @@ export class RoomManager { p.offlineSince = Date.now(); p.ready = false; room.typing.delete(ws.data.userId); - const wasHost = room.hostId === ws.data.userId; - if (wasHost) room.pickHost(); + // A host who dropped keeps the role for HOST_HOLD_MS (a refresh is back in a second or two): see sweep(). room.broadcast(); - if (wasHost && room.hostId !== ws.data.userId) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`); room.game?.onGone(ws.data.userId); } } @@ -524,9 +528,18 @@ export class RoomManager { return true; } - /** Every 10s: drop players gone longer than the grace period, close rooms created but never entered. */ + /** Every 5s: hand over the host role, drop players gone longer than the grace period, close rooms created but never entered. */ sweep(now = Date.now()): void { for (const room of this.rooms.values()) { + const host = room.players.get(room.hostId); + if (host?.offlineSince && now - host.offlineSince > HOST_HOLD_MS && room.online().length) { + const before = room.hostId; + room.pickHost(); + if (room.hostId !== before) { + room.broadcast(); + room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`); + } + } for (const [id, p] of room.players) if (p.offlineSince && now - p.offlineSince > GRACE_MS) this.removePlayer(room, id, 'closed'); if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.close(room); } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index df6b701..ab7e916 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -158,7 +158,7 @@ export function startServer(opts: StartOptions) { }, }); - const roomSweeper = setInterval(() => rooms.sweep(), 10_000); + const roomSweeper = setInterval(() => rooms.sweep(), 5_000); // 입력 중 goes out at most once a second (docs/06); chat itself never waits. const typingFlush = setInterval(() => rooms.flushTyping(), 1000); // The collector runs in its own process, so lobbies re-count now and then to show newly matched songs. diff --git a/apps/web/src/net/player.ts b/apps/web/src/net/player.ts index ab8ed39..fd9a494 100644 --- a/apps/web/src/net/player.ts +++ b/apps/web/src/net/player.ts @@ -2,9 +2,11 @@ * Hidden YouTube IFrame player with server-timed playback (docs/12 Q1, prototype tools/prototypes/iframe-sync). * - prepare: load muted at the start position, wait until really PLAYING (an ad would come first), pause, seek back → ready * (reloads by itself at 8s and 16s) - * - play: at server time `startAt` unmute and play from `atSec`; stop by playback POSITION at `endSec` + * - play: at server time `startAt` unmute and play from `atSec` (started late: from where everyone is now); stop by playback POSITION at `endSec` * (checked every frame + 10ms); 0.3s drift correction every second; buffering > 0.5s → stall; muted / not playing * 0.3s after the start → blocked + * - catchUp: back in a running question (refresh / reconnect): load muted where everyone is, then play along; a fresh + * page first waits for "참가 (소리 켜기)" (the browser blocks sound before a click), the others never stop for it * A fake player (localStorage mq:fakePlayer = "1") lets e2e runs play 30 questions without YouTube. */ import { create } from 'zustand'; @@ -217,6 +219,8 @@ let bufferingSince: number | null = null; let stallSent = false; let pendingReady: { n: number; tk: number; at: number } | null = null; let timeline: { startAt: number; atSec: number; endSec: number | null } | null = null; +/** catchUp loaded but this page has no click yet: play along right after "참가 (소리 켜기)". */ +let pendingCatchUp: { n: number; tk: number; startAt: number; atSec: number; endSec: number | null } | null = null; const useFake = () => { try { @@ -296,13 +300,17 @@ export const player = { e.unlock(); const held = pendingReady; pendingReady = null; + const along = pendingCatchUp?.tk === token ? pendingCatchUp : null; + pendingCatchUp = null; usePlayer.setState({ unlocked: true, needsGesture: false }); const tk = token; const release = () => held && held.tk === token && report(held.n, 'ready'); - if (useFake()) return void release(); + if (useFake()) return void (along ? player.play(along.n, along.startAt, along.atSec, along.endSec) : release()); void waitFor(() => e.state() === 1, 5000, tk).then(async () => { e.volume(usePlayer.getState().volume); if (tk !== token || timeline) return; + // Came back mid-question: join the music where everyone is now. + if (along) return player.play(along.n, along.startAt, along.atSec, along.endSec); e.pause(); if (!held) return; // The question was waiting for this click: back to the position everyone resumes from, then ready. @@ -319,6 +327,7 @@ export const player = { stopLoop(); timeline = null; pendingReady = null; + pendingCatchUp = null; usePlayer.setState({ loading: true, playing: false, pos: startSec, clip: { start: startSec, end: endSec } }); const e = eng(); await e.init(); @@ -350,6 +359,7 @@ export const player = { curN = n; stopLoop(); pendingReady = null; + pendingCatchUp = null; const e = eng(); timeline = { startAt, atSec, endSec }; stallSent = false; @@ -359,7 +369,9 @@ export const player = { if (tk !== token) return; e.volume(usePlayer.getState().volume); e.mute(false); - if (Math.abs(e.time() - atSec) > 0.15) e.seek(atSec); + // On time this is atSec; joining a running timeline (catchUp, a late start) it is where everyone is now. + const at = atSec + Math.max(0, now() - startAt) / 1000; + if (Math.abs(e.time() - at) > 0.15) e.seek(at); e.play(); usePlayer.setState({ playing: true }); // 소리 확인 (docs/12 Q1): 0.3s later it must be unmuted and playing. @@ -394,11 +406,45 @@ export const player = { else go(); }, + /** Back in a question whose music is running (refresh / reconnect): load muted where everyone is, then play along. */ + async catchUp(n: number, videoId: string, clipStart: number, startAt: number, atSec: number, endSec: number | null): Promise { + const at = () => atSec + Math.max(0, now() - startAt) / 1000; + if (endSec !== null && at() >= endSec) return; // the clip is over: nothing to hear until the next question + const tk = ++token; + curN = n; + stopLoop(); + timeline = null; + pendingReady = null; + pendingCatchUp = null; + usePlayer.setState({ loading: true, playing: false, pos: at(), clip: { start: clipStart, end: endSec } }); + const e = eng(); + await e.init(); + if (tk !== token) return; + e.mute(true); + if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) { + e.seek(at()); + e.play(); + } else e.load(videoId, at()); + let ok = await waitFor(() => e.state() === 1, 8000, tk); + if (!ok && tk === token) (e.load(videoId, at()), (ok = await waitFor(() => e.state() === 1, 8000, tk))); + if (!ok || tk !== token) return; + usePlayer.setState({ loading: false }); + const s = usePlayer.getState(); + if (!s.unlocked || s.needsGesture) { + // A fresh page: the browser allows sound only after a click. Wait muted; "참가 (소리 켜기)" starts it in sync. + e.pause(); + pendingCatchUp = { n, tk, startAt, atSec, endSec }; + return; + } + player.play(n, startAt, atSec, endSec); + }, + pause(): void { token++; stopLoop(); timeline = null; pendingReady = null; + pendingCatchUp = null; const e = engine; if (e && e.state() === 1) e.pause(); usePlayer.setState({ playing: false, loading: false, pos: e?.time() ?? 0 }); diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 42faed0..5a9f8b4 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -136,6 +136,9 @@ function onMessage(m: ServerMessage): void { case 'pause': if (m.code === useRoom.getState().code) player.pause(); return; + case 'catchup': + if (m.code === useRoom.getState().code) void player.catchUp(m.n, m.videoId, m.clipStart, m.startAt, m.atSec, m.endSec); + return; case 'typing': if (m.code === useRoom.getState().code) useRoom.setState({ typing: m.ids }); return; diff --git a/docs/12-decisions.md b/docs/12-decisions.md index c8192d1..2206de0 100644 --- a/docs/12-decisions.md +++ b/docs/12-decisions.md @@ -152,3 +152,12 @@ 2. 정답 공개 동안 노래는 계속 나온다(5~7단계 6번 그대로, 길이만 방 설정) 3. `다음문제인원(이상)`(기본 1/3명): 정답 공개 중 `⏭ 다음 문제`(Ctrl+K) 표가 이 인원 이상이면 바로 넘어감. 방장 전용이 아니라 스킵처럼 투표, 기준은 방에 접속 중인 사람 수 4. 관리자 사이트의 새 방 기본값·잠금, 퀴즈 저장·불러오기에 같이 들어간다(예전 저장본은 기본값 5초·1/3명) + +## 새로고침 이어하기·업데이트 알림·곡 제목 특수문자 (2026-10-19, 사용자: 질문은 알아서 결정) +1. 퀴즈 중 새로고침(같은 계정이 60초 안에 돌아옴)은 그 문제부터 그대로 이어서 한다. 5~7단계 4번의 "다시 연결한 사람은 다음 문제부터"를 이렇게 바꾼다. 처음 들어온 사람은 그대로 다음 문제부터 + - 노래가 나오는 중이면 서버가 `catchup`(영상, 서버 기준 시작 시각·위치)을 보내고, 새 화면은 소리를 끈 채 같은 위치에 맞춰 둔다. 브라우저는 클릭 전 소리를 막으므로 `참가 (소리 켜기)`를 누르는 순간 다른 사람과 같은 위치에서 소리가 난다. 다른 사람은 멈추지 않는다 + - 준비(prepare) 중이면 새 화면에 prepare를 다시 보내고 방은 그 사람의 준비를 기다린다(예전에는 이때 문제가 멈춘 채 안 넘어갈 수 있었음) + - 방장이 끊기면 15초 동안 방장을 유지한다. 그 안에 돌아오면 그대로, 아니면 접속 중인 다음 사람에게 넘어간다(5초마다 확인). 스스로 나가기는 지금처럼 바로 넘어감 + - 서버 업데이트(재시작) 때는 지금처럼 방이 닫힌다(방은 메모리에만 있음) +2. 업데이트 알림은 joke-app과 같다: 웹 빌드 id(``)가 서버와 다르면 위쪽에 "업데이트 내용이 있습니다 · 지금 새로고침하기 · ✕". 퀴즈 중에도 바로 띄우고 저절로 새로고침하지 않는다 +3. 곡 제목·가수의 HTML 특수문자(`'`, `&`)는 수집할 때 풀어서 저장한다. 이미 저장된 곡은 `cli.ts fix-text`로 한 번 고치고, 고친 곡은 원곡 찾기를 다시 하며, 깨진 키 때문에 생긴 중복은 오래된 곡으로 합친다 diff --git a/e2e/game.e2e.ts b/e2e/game.e2e.ts index 054d0b3..0269c5b 100644 --- a/e2e/game.e2e.ts +++ b/e2e/game.e2e.ts @@ -3,7 +3,7 @@ * Part A uses the fake player (localStorage mq:fakePlayer) so 30 questions run in about a minute without YouTube: * start, synced play, answers by chat (정답 줄 + 5줄 블록 on every screen), scores, past questions, buffering pause for * everyone, skip / hint / replay votes with Ctrl+K / Ctrl+I / Ctrl+R, a broken video swapped, typing indicator, - * reconnect mid-game, results with YouTube links, 이어풀기, 다시 하기, phone / dark screens, the last one out closes the room. + * reconnect mid-game, refresh while the music runs (catch up in sync), results with YouTube links, 이어풀기, 다시 하기, phone / dark screens, the last one out closes the room. * Part B plays real YouTube Topic videos in two browsers: sound on after the entry click, same start, 3s clip stop. * Run: bun run build && bun e2e/game.e2e.ts (needs /usr/bin/google-chrome; Part B needs internet, skip with E2E_NO_YT=1) */ @@ -213,7 +213,7 @@ try { await answer(6, b); }); - await step('A: 7~30번 — 돌아가며 정답, 15번에 영희 새로고침(다시 소리 켜기 → 다음 문제부터 참가)', async () => { + await step('A: 7~30번 — 돌아가며 정답, 15번에 영희 새로고침(다시 소리 켜기 → 그 문제부터 이어서)', async () => { for (let n = 7; n <= 30; n++) { const who = all[n % 3]!; if (n === 15) { @@ -313,6 +313,43 @@ try { await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor(); }); + await step('A: 노래 나오는 중 새로고침 → 소리 켜기 누르면 다른 사람과 같은 위치에서 이어 재생, 다른 사람은 안 멈춤, 바로 정답 가능', async () => { + await a.getByRole('button', { name: '↺ 다시 하기' }).click(); + await a.locator('.pool-banner').waitFor(); + await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /듣고맞추기/ }).click(); + await a.getByRole('radiogroup', { name: '듣고맞출시간' }).getByRole('radio', { name: '끝까지' }).click(); + await a.getByRole('radiogroup', { name: '듣고맞출시간' }).getByRole('radio', { name: '끝까지', checked: true }).waitFor(); + await a.getByRole('button', { name: '게임 시작' }).click(); + const fewer = a.getByRole('button', { name: '그대로 시작' }); + if (await fewer.isVisible({ timeout: 1000 }).catch(() => false)) await fewer.click(); + await Promise.all(all.map((p) => playing(p, 1))); + await a.waitForTimeout(1500); + const pauses = await a.evaluate(() => document.querySelectorAll('.chat-sys').length); + await c.reload(); + await c.locator('.gbar .q', { hasText: /^문제 1 / }).waitFor({ timeout: 10000 }); + // a fresh page may not play sound before a click: it waits muted for "참가 (소리 켜기)", the others keep playing + await c.getByRole('button', { name: '🔊 참가 (소리 켜기)' }).click({ timeout: 10000 }); + await c.locator('.stage .lp.spin').waitFor({ timeout: 5000 }); + await c.waitForTimeout(1200); // past one drift check + const [pa, pc, vidA, vidC] = await Promise.all([ + a.evaluate(() => (window as any).mqPlayer.pos() as number), + c.evaluate(() => (window as any).mqPlayer.pos() as number), + video(a), + video(c), + ]); + console.log(` 새로고침 뒤 위치 방장 ${pa.toFixed(3)} / 영희 ${pc.toFixed(3)}`); + expect(vidA === vidC, `다른 곡: ${vidA} / ${vidC}`); + expect(pa > 2.5 && Math.abs(pa - pc) < 0.4, `재생 위치가 다름: 방장 ${pa.toFixed(2)}s, 영희 ${pc.toFixed(2)}s`); + expect((await a.locator('.stage .lp.spin').count()) > 0, '방장 쪽 음악이 멈춤'); + expect(!(await a.getByText(/잠시 멈춤/).count()), '다른 사람 화면이 잠시 멈춤'); + expect((await a.evaluate(() => document.querySelectorAll('.chat-sys').length)) === pauses, '새로고침했는데 시스템 줄이 생김'); + await answer(1, c); + await a.locator('.sb', { hasText: '영희' }).locator('.sc', { hasText: '1' }).waitFor(); + await a.getByRole('button', { name: '⏹ 끝내기' }).click(); + await a.getByRole('button', { name: '끝내기', exact: true }).click(); + await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor(); + }); + await step('A: 모두 "← 방 목록"으로 나가면 방이 바로 사라짐', async () => { for (const p of all) { await p.getByRole('link', { name: '← 방 목록' }).click(); @@ -366,6 +403,35 @@ try { await x.context().close(); await y.context().close(); }); + + await step('B: 실제 유튜브 — 노래 나오는 중 새로고침 → 소리 켜기 → 다른 사람과 같은 위치에서 소리 나게 이어 재생', async () => { + const x = await guestPage('유튜브방장2', { fake: false }); + const y = await guestPage('유튜브손님2', { fake: false }); + const rc = await makeRoom(x, { count: 10, level: 9, listenSec: 0, startAt: 'highlight' }); + await y.goto(`${ORIGIN}/r/${rc}`); + await y.locator('.pool-banner').waitFor(); + for (const p of [x, y]) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click(); + await x.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 }); + await x.getByRole('button', { name: '게임 시작' }).click(); + await x.getByRole('button', { name: '그대로 시작' }).click(); + await Promise.all([x, y].map((p) => playing(p, 1, 40000))); + await x.waitForTimeout(3000); + await y.reload(); + await y.getByRole('button', { name: '🔊 참가 (소리 켜기)' }).click({ timeout: 30000 }); + await y.locator('.stage .lp.spin').waitFor({ timeout: 15000 }); + await y.waitForTimeout(2500); + const st = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), muted: (window as any).mqPlayer.muted(), state: (window as any).mqPlayer.state(), v: (window as any).mqPlayer.video() })))); + console.log(` 새로고침 뒤 위치 ${st.map((s) => s.pos.toFixed(3)).join(' / ')}`); + expect(st[0]!.v === st[1]!.v, `다른 곡 ${JSON.stringify(st)}`); + expect(st.every((s) => s.state === 1 && !s.muted), `재생 상태 ${JSON.stringify(st)}`); + expect(Math.abs(st[0]!.pos - st[1]!.pos) < 0.4, `두 사람 위치 차이 ${JSON.stringify(st)}`); + expect(!(await x.getByText(/잠시 멈춤/).count()), '방장 화면이 멈춤'); + await x.getByRole('button', { name: '⏹ 끝내기' }).click(); + await x.getByRole('button', { name: '끝내기', exact: true }).click(); + await x.getByRole('heading', { name: '🏁 게임 결과' }).waitFor(); + await x.context().close(); + await y.context().close(); + }); } expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`); diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index 6a23521..6788f78 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -155,6 +155,11 @@ export type ServerMessage = | { t: 'play'; code: string; n: number; startAt: number; atSec: number; endSec: number | null } /** Stop now (someone is buffering / the host paused / the clip is over). */ | { t: 'pause'; code: string; n: number } + /** + * Back in a question whose music is running (refresh / reconnect): load `videoId` and play along the running timeline + * (position `atSec` at server time `startAt`); `clipStart` is where the clip began, for the progress bar. + */ + | { t: 'catchup'; code: string; n: number; videoId: string; clipStart: number; startAt: number; atSec: number; endSec: number | null } | { t: 'typing'; code: string; ids: string[] } | { t: 'saved'; id: number; name: string } /** Recent lines for someone who just joined (or came back). */