혼자인 대기실에서 브라우저 뒤로가기(홈)로 나가면 빈 방이 10분 동안 남던 문제: 다른 사람이 없고 게임 전이면 detach를 나가기로 처리해 방을 바로 닫음. 방 안 📖 규칙도 팝업으로(규칙 페이지로 넘어가며 방을 떠나지 않게), e2e/room-back.e2e.ts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 05:03:12 +09:00
parent b93228e5af
commit 71bdfd201a
6 changed files with 175 additions and 4 deletions

View File

@@ -50,6 +50,7 @@ bun e2e/replay.e2e.ts # 다시 보기
bun e2e/tutorial.e2e.ts # 처음 하는 사람용 규칙 요약
bun e2e/speed.e2e.ts # 게임 속도 배율: 판 애니메이션 재생 속도와 컴퓨터 응답 시간
bun e2e/settings.e2e.ts # 설정 팝업: 게임 중에 열어도 방에서 나가지 않음, 바로 적용, 닫기·포커스
bun e2e/room-back.e2e.ts # 혼자인 대기실에서 뒤로가기 → 빈 방 바로 닫힘, 친구가 있으면 자리 유지, 규칙 팝업
bun scripts/loadtest.ts --help # 부하·장애 주입 (docs/reports 참고)
```

View File

@@ -93,12 +93,51 @@ describe('idle guests', () => {
});
describe('leaving the room page', () => {
test('detach keeps the seat but the room no longer counts the connection', async () => {
test('alone with no game running (뒤로가기 from the lobby): leaving the page leaves the room and it closes at once', async () => {
const s = start();
const g = await guest(s.base, '혼자');
const c = await connect(s, g);
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: c.cookie, body: JSON.stringify({ gameId: 'omok' }) });
c.send({ t: 'join', code: r.body.code, as: 'player' });
await c.waitFor((m) => m.t === 'room');
expect(s.rooms.get(r.body.code)).toBeDefined();
c.send({ t: 'detach' });
for (let i = 0; i < 50 && s.rooms.get(r.body.code); i++) await sleep(10);
expect(s.rooms.get(r.body.code)).toBeUndefined();
expect(s.rooms.activeRoomFor(g.id)).toBeNull();
// The same socket is fine afterwards.
c.send({ t: 'ping', ts: 1 });
await c.waitFor((m) => m.t === 'pong');
});
test('someone else is in the lobby: leaving the page keeps my seat (I can come back)', async () => {
const s = start();
const a = await guest(s.base, '방장');
const b = await guest(s.base, '친구');
const ca = await connect(s, a);
const cb = await connect(s, b);
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: ca.cookie, body: JSON.stringify({ gameId: 'omok' }) });
ca.send({ t: 'join', code: r.body.code, as: 'player' });
await ca.waitFor((m) => m.t === 'room');
cb.send({ t: 'join', code: r.body.code, as: 'player' });
await cb.waitFor((m) => m.t === 'room');
const room = s.rooms.get(r.body.code)!;
ca.send({ t: 'detach' });
for (let i = 0; i < 50 && room.conns.size > 1; i++) await sleep(10);
expect(room.conns.size).toBe(1);
expect(room.seatOf(a.id)).toBeGreaterThanOrEqual(0);
expect(s.rooms.get(r.body.code)).toBe(room);
});
test('detach during a game keeps the seat but the room no longer counts the connection', async () => {
const s = start();
const g = await guest(s.base, '홈으로');
const c = await connect(s, g);
const code = await practiceRoom(s, c);
const room = s.rooms.get(code)!;
c.send({ t: 'start' });
for (let i = 0; i < 50 && room.status !== 'playing'; i++) await sleep(10);
expect(room.status).toBe('playing');
expect(room.conns.size).toBe(1);
c.send({ t: 'detach' });
for (let i = 0; i < 50 && room.conns.size; i++) await sleep(10);

View File

@@ -546,6 +546,9 @@ export class Room {
const u = conn.userId;
if (this.conns.get(u) !== conn) return;
if (this.spectators.has(u)) return this.disconnect(conn);
// Alone in the lobby: nobody to come back to, so leaving the page (뒤로가기, 홈) leaves the room and the empty room
// closes now instead of lingering (2026-10-14). A game (running, or its result: 다시 보기 comes back) keeps the seat.
if (this.status === 'lobby' && this.conns.size === 1 && !this.seatedIds().some((x) => x !== u && !isBotId(x) && !this.leftDuringGame.has(x))) return this.leave(u);
this.conns.delete(u);
this.detached.set(u, conn);
if (this.conns.size === 0) this.becameEmpty('disconnect');

View File

@@ -98,6 +98,8 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
// 설정 opens as a popup over the room: going to /me would unmount the room and detach from it.
const [settingsOpen, setSettingsOpen] = useState(false);
const closeSettings = useCallback(() => setSettingsOpen(false), []);
// 규칙 too: going to /rules would leave the room page (and, alone in a lobby, the room itself).
const [rulesOpen, setRulesOpen] = useState(false);
// [한 판 더] takes me back to this room's lobby after game N (kept per tab so a reload stays there).
const lobbyKey = `bg:lobby:${code}`;
const [lobbyAfter, setLobbyAfter] = useState<number | null>(() => Number(sessionStorage.getItem(lobbyKey)) || null);
@@ -217,7 +219,7 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
</span>
)}
<VolumeControl className="btn btn-ghost btn-sm rb-btn" label />
<button className="btn btn-ghost btn-sm rb-btn" onClick={() => nav(`/rules/${room.gameId}`)} aria-label="규칙 보기">
<button className="btn btn-ghost btn-sm rb-btn" onClick={() => setRulesOpen(true)} aria-haspopup="dialog" aria-label="규칙 보기">
<span className="rb-ico">📖</span>
<span className="rb-lbl">규칙</span>
</button>
@@ -247,6 +249,16 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
</Sheet>
)}
{settingsOpen && <SettingsPopup onClose={closeSettings} />}
{rulesOpen && (
<Sheet onClose={() => setRulesOpen(false)} label={`${gameName(room.gameId)} 규칙`}>
<h2>{gameName(room.gameId)} 규칙</h2>
<GameNotice gameId={room.gameId} />
{ui ? <ui.Rules options={room.options} /> : <p className="muted">불러오는 중…</p>}
<button type="button" className="btn btn-secondary btn-block" onClick={() => setRulesOpen(false)}>
닫기
</button>
</Sheet>
)}
{leaveAsk && (
<ConfirmSheet
title="방에서 나갈까요?"

View File

@@ -58,7 +58,7 @@
## 8. 게임 중
- 위쪽 상태 줄: 지금 할 일 문장("내 차례예요" / "OO님 차례예요"), 남은 시간 링.
- 방 막대(메뉴 버튼 없이 모두 밖에): [← 홈] 게임 이름(PC) · [🔗 방 코드 링크 복사] · [💬 채팅](휴대폰) · [📖 규칙] · [⚙️ 설정](글자 크기·소리 팝업, 방에서 나가지 않음) · **[🚪 나가기]**. 휴대폰에서는 아이콘 아래 짧은 글자로 쌓아 한 줄(320px)에 들어가게 한다(버튼은 최대 6개).
- 방 막대(메뉴 버튼 없이 모두 밖에): [← 홈] 게임 이름(PC) · [🔗 방 코드 링크 복사] · [💬 채팅](휴대폰) · [📖 규칙](팝업) · [⚙️ 설정](글자 크기·소리 팝업, 방에서 나가지 않음) · **[🚪 나가기]**. 휴대폰에서는 아이콘 아래 짧은 글자로 쌓아 한 줄(320px)에 들어가게 한다(버튼은 최대 6개).
- 오류로 게임이 멈추면 방장에게만 상태 줄 바로 아래 [⏹ 게임 끝내기(무효)] 버튼이 나온다.
- [🚪 나가기]와 [← 홈]은 같은 동작이다: 방에서 나가고 홈으로. 한 번 누르면 바로 나가고, 게임 중에 자리에 앉아 있을 때만 "게임 중에 나가면 기권으로 처리돼요" 확인을 한 번 더 묻는다.
- 무르기 요청·무승부 제안·기권은 게임 화면 안의 버튼으로 한다(지원 게임).
@@ -102,7 +102,8 @@ interface Room {
- 제한: 서버 전체 방 2,000개, 사용자당 동시에 만든 방 3개.
- 방 정리(1분마다): 접속이 하나도 없는 방 중 대기실은 10분, 끝난 방·멈춘 방은 30분 동안 활동이 없으면 닫는다. 컴퓨터가 있는 방(연습 방)은 마지막 사람이 나간 때부터 재서 대기실·끝난 방은 1분, 게임 중인 방은 30분 뒤 닫는다(사이트를 닫았으면 아래 규칙대로 1분). 마지막 사람이 [방 나가기]로 나가서 자리에 앉은 사람이 없으면(컴퓨터만 남았거나 아무도 들어오지 않은 방) 바로 닫는다.
- 게임 중이거나 끝난 방(대기실 제외)에서 자리에 앉은 사람이 모두 사이트를 닫으면(서버와 연결된 창이 하나도 없으면) 마지막 사람이 닫은 때부터 1분 뒤 정리 때 닫는다. 진행 중인 게임은 무효 처리되고, 관전자는 셈하지 않고, 남아 있던 관전자도 방에서 내보낸다. 대기실은 초대받은 사람이 들어올 수 있으므로 위 규칙을 따른다. 자리가 있는 사람은 다른 화면에 있어도 서버 연결을 유지한다(새로 연 창에서도 `/api/me`의 `activeRoom`이 있으면 연결).
- [← 홈]·[🚪 나가기]가 아닌 길(사이트 로고·위쪽 '홈' 링크, 규칙, 브라우저 뒤로 가기 등)로 방 화면을 벗어나면 클라이언트가 `detach`를 보낸다. 자리는 그대로이고 '접속 중'으로 남지만, 방 메시지를 받지 않고 방의 접속 수에서도 빠진다. 그 상태로 사이트를 닫으면 연결 끊김으로 처리한다.
- [← 홈]·[🚪 나가기]가 아닌 길(사이트 로고·위쪽 '홈' 링크, 브라우저 뒤로 가기 등)로 방 화면을 벗어나면 클라이언트가 `detach`를 보낸다. 자리는 그대로이고 '접속 중'으로 남지만, 방 메시지를 받지 않고 방의 접속 수에서도 빠진다. 그 상태로 사이트를 닫으면 연결 끊김으로 처리한다. [📖 규칙]·[⚙️ 설정]은 팝업이라 방 화면을 벗어나지 않는다.
- 다만 **대기실에 나 혼자**(다른 사람이 앉아 있지도, 보고 있지도 않음)일 때 방 화면을 벗어나면 `detach`를 `leave`로 처리한다. 돌아올 사람이 없으니 빈 방이 남지 않고 바로 닫힌다(2026-10-14). 게임 중이거나 결과 화면(다시 보기 뒤 돌아옴)일 때는 그대로 자리가 남는다.
## 12. 컴퓨터 상대 (혼자 연습)
- 들어가는 곳: 게임 상세와 홈의 [🤖 컴퓨터와 연습하기]. 친구만 방이 열리고, 바로 시작할 수 있을 만큼 컴퓨터가 앉아 있다(예: 오목 1명, 마작 2명, 뱅 3명).

115
e2e/room-back.e2e.ts Normal file
View File

@@ -0,0 +1,115 @@
/**
* E2E (2026-10-14): alone in a lobby, the browser's back button (Alt+← / Ctrl+←) takes me home and the empty room closes
* at once — no "하던 게임으로 돌아가기", not in the room list, the code no longer opens. 📖 규칙 in the room is a popup
* (it used to go to the rules page, which would now close the room). With a friend in the lobby, back keeps my seat.
* Run: E2E_PORT=4663 bun e2e/room-back.e2e.ts (needs apps/web/dist built)
*/
import { chromium, type Page } from 'playwright-core';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
const PORT = Number(process.env.E2E_PORT ?? 4663);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
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]}`);
throw e;
}
};
async function makeRoom(p: Page, name?: string): Promise<string> {
await p.goto(ORIGIN + '/');
await p.getByRole('button', { name: '+ 방 만들기' }).click();
await p.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /오목/ }).click();
if (name) {
await p.getByLabel('내 이름(닉네임)').fill(name);
await p.getByRole('button', { name: '이 이름으로 시작하기' }).click();
}
await p.waitForURL(/\/r\/\d{6}$/);
await p.getByRole('button', { name: '규칙 보기' }).waitFor();
return p.url().slice(-6);
}
const roomOpen = async (code: string) => {
const r = await fetch(`${ORIGIN}/api/rooms/${code}`);
if (r.status !== 200 && r.status !== 404) throw new Error(`room lookup ${r.status}`);
return r.ok;
};
try {
const ctxA = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
const ctxB = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, locale: 'ko-KR' });
const a = await ctxA.newPage();
const b = await ctxB.newPage();
const errors: string[] = [];
for (const p of [a, b]) p.on('pageerror', (e) => errors.push(e.message));
for (const p of [a, b]) await p.addInitScript(() => localStorage.setItem('bg:qs:omok', '1'));
let code = '';
await step('혼자 방 만들기 → 📖 규칙은 팝업(주소 그대로, 방 그대로)', async () => {
code = await makeRoom(a, '호랑이');
await a.getByRole('button', { name: '규칙 보기' }).click();
const sheet = a.getByRole('dialog', { name: '오목 규칙' });
await sheet.waitFor();
if (!a.url().endsWith(`/r/${code}`)) throw new Error(`navigated to ${a.url()}`);
await a.waitForTimeout(600);
await a.screenshot({ path: join(SHOTS, 'room-rules-popup.png') });
await sheet.getByRole('button', { name: '닫기' }).click();
if (!(await roomOpen(code))) throw new Error('the room closed while reading the rules');
});
await step('혼자인 대기실에서 브라우저 뒤로가기 → 홈, 방이 바로 없어짐', async () => {
await a.goBack();
await a.waitForURL(ORIGIN + '/');
for (let i = 0; i < 6 && (await roomOpen(code)); i++) await a.waitForTimeout(500);
if (await roomOpen(code)) throw new Error('the empty room is still open');
await a.reload();
await a.getByRole('button', { name: '+ 방 만들기' }).waitFor();
if (await a.getByText(/하던 게임으로 돌아가기/).count()) throw new Error('home still offers to go back to the room');
await a.screenshot({ path: join(SHOTS, 'room-back-home.png') });
});
await step('친구가 있는 대기실에서 뒤로가기 → 내 자리는 남고, 다시 들어갈 수 있음', async () => {
code = await makeRoom(a);
await b.goto(`${ORIGIN}/r/${code}`);
await b.getByLabel('내 이름(닉네임)').fill('고양이');
await b.getByRole('button', { name: '이 이름으로 입장하기' }).click();
await a.getByLabel('자리').getByText('고양이').waitFor();
await a.goBack();
await a.waitForURL(ORIGIN + '/');
await a.waitForTimeout(500);
if (!(await roomOpen(code))) throw new Error('the room closed although a friend is in it');
await b.getByLabel('자리').getByText('호랑이').waitFor({ timeout: 3000 });
await a.goForward();
await a.waitForURL(`${ORIGIN}/r/${code}`);
await a.getByLabel('자리').getByText('고양이').waitFor();
});
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
} catch (e) {
failed = true;
console.log(String((e as Error).stack ?? e));
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);