From 84d64b27f284a9d54f705f263e77f75956eadd70 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 11 Oct 2026 17:46:13 +0900 Subject: [PATCH] =?UTF-8?q?=EC=BB=B4=ED=93=A8=ED=84=B0=20=EB=82=9C?= =?UTF-8?q?=EC=9D=B4=EB=8F=84=201~60=EB=8B=A8=EA=B3=84=C2=B7=EB=B0=A9?= =?UTF-8?q?=EC=9E=A5=20=EC=84=A0=ED=83=9D=C2=B7=ED=8C=90=EB=A7=88=EB=8B=A4?= =?UTF-8?q?=20=EB=B3=80=ED=99=94=C2=B7=EC=9A=B4,=20=EA=B3=B5=EC=A0=95?= =?UTF-8?q?=EC=84=B1=20=ED=99=95=EC=9D=B8=EC=97=90=20=ED=91=9C=EA=B8=B0,?= =?UTF-8?q?=20=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=20=EC=95=8C=EB=A6=BC=20?= =?UTF-8?q?=ED=8C=9D=EC=97=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위 - 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말) - humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60) - 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로 - 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수 - 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕] - 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa) Co-Authored-By: Claude Opus 5.5 --- apps/server/src/ai/brain.ts | 5 + apps/server/src/ai/lines.ts | 19 +- apps/server/src/http/app.ts | 8 + apps/server/src/rooms/bot-level.room.test.ts | 238 +++++++++++++++++++ apps/server/src/rooms/bot-profile.ts | 62 +++++ apps/server/src/rooms/bots.ts | 8 +- apps/server/src/rooms/luck-worker.ts | 18 ++ apps/server/src/rooms/luck.test.ts | 49 ++++ apps/server/src/rooms/luck.ts | 76 ++++++ apps/server/src/rooms/manager.ts | 3 + apps/server/src/rooms/room.ts | 128 +++++++++- apps/server/src/server.ts | 37 ++- apps/server/src/version.test.ts | 44 ++++ apps/server/src/ws/gateway.ts | 6 + apps/web/src/components/ui.tsx | 18 ++ apps/web/src/lib/update.ts | 61 +++++ apps/web/src/main.tsx | 5 +- apps/web/src/net/socket.ts | 6 +- apps/web/src/pages/RoomPage.tsx | 81 +++++-- apps/web/src/styles/global.css | 58 +++++ apps/web/vite.config.ts | 22 +- docs/03-realtime-protocol.md | 3 +- docs/04-stability-security.md | 22 ++ docs/06-lobby-rooms.md | 3 +- docs/07-ui-ux.md | 8 +- docs/09-game-engine.md | 42 ++-- e2e/bots.e2e.ts | 17 ++ e2e/pwa.e2e.ts | 40 ++++ packages/games/package.json | 1 + packages/games/src/bots/bots.test.ts | 4 +- packages/games/src/bots/index.ts | 3 +- packages/games/src/bots/level.test.ts | 70 ++++-- packages/games/src/bots/luck.test.ts | 81 +++++++ packages/games/src/bots/luck.ts | 123 ++++++++++ packages/games/src/bots/persona.ts | 34 ++- packages/games/src/bots/policy.ts | 33 ++- packages/games/src/mafia/bot.test.ts | 8 +- packages/shared/src/bots.ts | 27 +++ packages/shared/src/protocol.ts | 1 + packages/shared/src/types.ts | 10 +- 40 files changed, 1349 insertions(+), 133 deletions(-) create mode 100644 apps/server/src/rooms/bot-level.room.test.ts create mode 100644 apps/server/src/rooms/bot-profile.ts create mode 100644 apps/server/src/rooms/luck-worker.ts create mode 100644 apps/server/src/rooms/luck.test.ts create mode 100644 apps/server/src/rooms/luck.ts create mode 100644 apps/server/src/version.test.ts create mode 100644 apps/web/src/lib/update.ts create mode 100644 packages/games/src/bots/luck.test.ts create mode 100644 packages/games/src/bots/luck.ts diff --git a/apps/server/src/ai/brain.ts b/apps/server/src/ai/brain.ts index 8d10508..f9b4168 100644 --- a/apps/server/src/ai/brain.ts +++ b/apps/server/src/ai/brain.ts @@ -29,6 +29,8 @@ export interface BrainRoom { roomChat(bot: string, text: string): void; setActivity(bot: string, a: BotActivity | null): void; recentChat(): { from: string; text: string }[]; + /** 똑똑한 편 (존댓말) or 허술한 편 (반말), docs/09 §9.1. */ + smart(bot: string): boolean; now(): number; } @@ -90,6 +92,7 @@ export class BotBrain { return { bot, name: this.room.nameOf(bot), + smart: this.room.smart(bot), game: this.room.gameName(), situation, task, @@ -175,6 +178,7 @@ export class BotBrain { this.llm, bot, this.room.nameOf(bot), + this.room.smart(bot), `바퀴벌레 포커. 나는 ${target}에게 카드를 건넨다. 실제 카드는 ${KO[kind] ?? kind}다. ${target}의 앞마당: ${pile}.\n` + `진짜 이름을 말할지(bluff=false) 다른 벌레라고 거짓말할지(bluff=true) 정하고, 건네며 할 한마디(say, 30자 이내, 실제 카드를 밝히지 말 것)를 정해.`, { type: 'object', properties: { bluff: { type: 'boolean' }, say: { type: 'string' } }, required: ['bluff', 'say'] }, @@ -243,6 +247,7 @@ export class BotBrain { const line = await writeLine(this.llm, { bot, name: this.room.nameOf(bot), + smart: this.room.smart(bot), game: '마피아(낮 토론, 모두가 보는 채팅)', situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.', task: hint, diff --git a/apps/server/src/ai/lines.ts b/apps/server/src/ai/lines.ts index e8d53fd..0c86f4e 100644 --- a/apps/server/src/ai/lines.ts +++ b/apps/server/src/ai/lines.ts @@ -2,7 +2,7 @@ * What a computer says, written by the local model (docs/06 §12.1): a character (성격 + 말투) per computer, a prompt * per moment, and a strict clean-up so only one short, kind, Korean chat line ever reaches people. */ -import { botPersona, hash01 } from '@bg/games/bots'; +import { hash01 } from '@bg/games/bots'; import { chatProblem } from '@bg/games/mafia'; import type { Llm, LlmMessage } from './llm'; @@ -27,16 +27,17 @@ export function temperOf(bot: string): Temper { return TEMPERS[Math.floor(hash01(bot, 'temper') * TEMPERS.length)]!; } -export function speechOf(bot: string): string { - return botPersona(bot).smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임'; +/** `smart` = 똑똑한 편 (the room's `botPersona`). */ +export function speechOf(smart: boolean): string { + return smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임'; } -export function systemPrompt(bot: string, name: string, maxLen: number): string { +export function systemPrompt(bot: string, name: string, maxLen: number, smart: boolean): string { const t = temperOf(bot); return [ `너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`, `성격: ${t.ko} — ${t.desc}`, - `말투: ${speechOf(bot)}.`, + `말투: ${speechOf(smart)}.`, `규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`, '욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.', '자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.', @@ -46,6 +47,8 @@ export function systemPrompt(bot: string, name: string, maxLen: number): string export interface LineRequest { bot: string; name: string; + /** 똑똑한 편 (존댓말) / 허술한 편 (반말). */ + smart: boolean; game: string; /** What is going on, in plain Korean. */ situation: string; @@ -99,7 +102,7 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise(llm: Llm | null, bot: string, name: string, prompt: string, schema: object): Promise { +export async function decide(llm: Llm | null, bot: string, name: string, smart: boolean, prompt: string, schema: object): Promise { if (!llm || !llm.available()) return null; const raw = await llm.chat( [ - { role: 'system', content: systemPrompt(bot, name, 40) + '\n대답은 요청한 JSON 형식으로만 한다.' }, + { role: 'system', content: systemPrompt(bot, name, 40, smart) + '\n대답은 요청한 JSON 형식으로만 한다.' }, { role: 'user', content: prompt }, ], { maxTokens: 120, temperature: 0.9, format: schema }, diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index ad7ec58..d838514 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -16,6 +16,8 @@ import type { SettingsStore } from '../admin/settings'; export interface HttpDeps { config: Config; + /** Web build being served (`/api/version`, docs/07 §11.1); null without a web build. */ + build?: string | null; users: Users; sessions: Sessions; rooms: RoomManager; @@ -76,6 +78,12 @@ export function createHttpApp(d: HttpDeps) { setCookie(c, SESSION_COOKIE, token, cookieOpts(SESSION_TTL[kind])); }; + // Open pages ask now and then whether the site was updated (docs/07 §11.1). + app.get('/api/version', (c) => { + c.header('Cache-Control', 'no-store'); + return c.json({ build: d.build ?? null }); + }); + app.get('/healthz', (c) => { const h = d.health(); return c.json(h, h.ok ? 200 : 503); diff --git a/apps/server/src/rooms/bot-level.room.test.ts b/apps/server/src/rooms/bot-level.room.test.ts new file mode 100644 index 0000000..82e919b --- /dev/null +++ b/apps/server/src/rooms/bot-level.room.test.ts @@ -0,0 +1,238 @@ +/** Computer levels 1~60, the host's 쉬움/보통/어려움, drift between games and luck shuffles (docs/09 §9.1, docs/04 §5.1). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { seedToHex, type ChaChaSeed } from '@bg/engine'; +import { GAMES } from '@bg/games'; +import { BOT_BANDS, ClientMessage, bandOf, botProfile, isBotId, luckLabel, type ServerMessage } from '@bg/shared'; +import type { LuckJob } from '@bg/games/bots/luck'; +import { openDb } from '../db'; +import { sha256Hex } from '../auth/sessions'; +import { DRIFT_RANGE, DRIFT_STEP, drift, newBotProfile, profileFromId, repick, rollLevel } from './bot-profile'; +import { RoomManager } from './manager'; +import { Room, type Conn, type RoomSnapshot } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness(luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>) { + const db = openDb(':memory:'); + const store = new RoomStore(db); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 60_000, luckSeed }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + const practice = (gameId: string) => { + const r = manager.createPractice('A', gameId) as Room; + rooms.push(r); + r.join(conn('A'), 'player'); + return r; + }; + return { db, store, clock, manager, conn, practice, users }; +} + +const botsOf = (room: Room) => room.seatedIds().filter(isBotId); +const seq = (...xs: number[]) => { + let i = 0; + return () => xs[i++ % xs.length]!; +}; + +describe('levels', () => { + test('rolls: 랜덤 1~60, 쉬움 1~20, 보통 21~40, 어려움 41~60, all values reachable', () => { + for (const pick of ['random', 'easy', 'normal', 'hard'] as const) { + const [lo, hi] = pick === 'random' ? [1, 60] : BOT_BANDS[pick]; + expect(rollLevel(pick, () => 0)).toBe(lo); + expect(rollLevel(pick, () => 0.999999)).toBe(hi); + for (let i = 0; i < 500; i++) { + const l = rollLevel(pick); + expect(l >= lo && l <= hi).toBe(true); + } + } + expect(bandOf(20)).toBe('easy'); + expect(bandOf(21)).toBe('normal'); + expect(bandOf(41)).toBe('hard'); + }); + + test('a new computer: any level, its own luck in [-1, 1]; picking a band keeps the luck', () => { + const p = newBotProfile(seq(0.5, 0.9)); + expect(p).toEqual({ pick: 'random', base: 31, level: 31, luck: expect.closeTo(0.8, 9), played: 0 }); + const q = repick(p, 'easy', () => 0.3); + expect(q).toEqual({ pick: 'easy', base: 7, level: 7, luck: p.luck, played: 0 }); + expect(luckLabel(-1)).toBe('아주 나쁨'); + expect(luckLabel(0)).toBe('보통'); + expect(luckLabel(0.7)).toBe('아주 좋음'); + }); + + test('drift: none before the first game, then at most 2 a game, within ±5 of the start and never out of its band', () => { + for (const base of [1, 20, 21, 33, 41, 60]) { + let p = { ...newBotProfile(), base, level: base }; + p = drift(p); + expect(p.level).toBe(base); + const [lo, hi] = BOT_BANDS[bandOf(base)]; + for (let g = 0; g < 300; g++) { + const prev = p.level; + p = drift(p); + expect(Math.abs(p.level - prev)).toBeLessThanOrEqual(DRIFT_STEP); + expect(Math.abs(p.level - base)).toBeLessThanOrEqual(DRIFT_RANGE); + expect(p.level >= lo && p.level <= hi).toBe(true); + } + } + // A 60 can become 58 next game, never 41. + expect(drift({ ...newBotProfile(), base: 60, level: 60, played: 1 }, () => 0).level).toBe(58); + }); + + test('computers saved without a level get one from their id (the same every time)', () => { + const id = 'bot:1:01J0000000ZZZZZZ0000000000'; + expect(profileFromId(id)).toEqual(profileFromId(id)); + expect(profileFromId(id).level).toBe(60); + }); +}); + +describe('room', () => { + test('protocol accepts botLevel with the four choices only', () => { + expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'hard' }).success).toBe(true); + expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'insane' }).success).toBe(false); + }); + + test('the host picks a band; everyone sees the pick, nobody sees the level until the game is over', () => { + const { practice, conn } = harness(); + const room = practice('omok'); + const bot = botsOf(room)[0]!; + expect(room.profile(bot).pick).toBe('random'); + expect(room.roomView().botPicks).toEqual({ [bot]: 'random' }); + room.join(conn('S'), 'spectator'); + expect(room.setBotLevel('S', bot, 'hard')).toBe('방장만 난이도를 바꿀 수 있어요.'); + expect(room.setBotLevel('A', 'bot:9:nope', 'hard')).toBe('없는 컴퓨터예요.'); + expect(room.setBotLevel('A', bot, 'hard')).toBeNull(); + expect(room.roomView().botPicks).toEqual({ [bot]: 'hard' }); + const level = room.profile(bot).level; + expect(level >= 41 && level <= 60).toBe(true); + expect(JSON.stringify(room.roomView())).not.toContain('"level"'); + + expect(room.start('A')).toBeNull(); + expect(room.setBotLevel('A', bot, 'easy')).toBe('게임 중에는 바꿀 수 없어요.'); + expect(room.roomView().lastBots).toBeUndefined(); + room.act('A', 1, { type: 'resign' }); + expect(room.status).toBe('finished'); + expect(room.roomView().lastBots).toEqual({ [bot]: { level, luck: room.profile(bot).luck } }); + expect(room.roomView().lastShuffles).toBe(1); + }); + + test('every next game the level moves a little around where it started', () => { + const { practice } = harness(); + const room = practice('omok'); + const bot = botsOf(room)[0]!; + room.setBotLevel('A', bot, 'hard'); + const base = room.profile(bot).base; + const seen: number[] = []; + for (let g = 0; g < 25; g++) { + expect(g === 0 ? room.start('A') : room.rematch('A')).toBeNull(); + seen.push(room.game!.bots![bot]!.level); + room.act('A', g + 1, { type: 'resign' }); + } + expect(seen[0]).toBe(base); + for (let i = 1; i < seen.length; i++) expect(Math.abs(seen[i]! - seen[i - 1]!)).toBeLessThanOrEqual(DRIFT_STEP); + for (const l of seen) expect(l >= Math.max(41, base - DRIFT_RANGE) && l <= Math.min(60, base + DRIFT_RANGE)).toBe(true); + expect(new Set(seen).size).toBeGreaterThan(1); + }); + + test('levels and luck survive a restart; rooms saved before get them from the id', () => { + const { practice, store, clock, users } = harness(); + const room = practice('omok'); + const bot = botsOf(room)[0]!; + room.setBotLevel('A', bot, 'easy'); + const before = room.profile(bot); + const { seq: s, stateJson } = store.openRooms()[0]!; + const deps = { store, games: GAMES, users, now: clock.now, botDelay: () => 60_000 }; + const restored = Room.restore(room.id, room.code, s, JSON.parse(stateJson) as RoomSnapshot, deps); + rooms.push(restored); + expect(restored.profile(bot)).toEqual(before); + const old = JSON.parse(stateJson) as RoomSnapshot; + delete old.bots; + const legacy = Room.restore(room.id, room.code, s, old, deps); + rooms.push(legacy); + expect(legacy.profile(bot)).toEqual(profileFromId(bot)); + }); +}); + +describe('luck shuffles', () => { + const seedA = [1, 2, 3, 4, 5, 6, 7, 8] as ChaChaSeed; + + test('a card game with computers waits for the shuffles, then starts with the chosen seed', async () => { + const jobs: LuckJob[] = []; + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const { practice } = harness(async (job) => { + jobs.push(job); + await gate; + return { seed: seedA, tried: 4 }; + }); + const room = practice('one-card'); + const bot = botsOf(room)[0]!; + room.botProfiles[bot]!.luck = 0.9; + expect(room.start('A')).toBeNull(); + expect(room.status).toBe('lobby'); + expect(room.roomView().starting).toBe(true); + expect(room.start('A')).toBe('게임을 준비하고 있어요.'); + expect(room.setBotLevel('A', bot, 'easy')).toBe('게임을 준비하고 있어요.'); + expect(jobs).toHaveLength(1); + expect(jobs[0]).toMatchObject({ gameId: 'one-card', players: room.seatedIds(), luck: { [bot]: room.profile(bot).luck }, gameNo: 1 }); + release(); + await gate; + await Bun.sleep(0); + expect(room.status).toBe('playing'); + expect(room.roomView().starting).toBeUndefined(); + expect(room.game!.seedHex).toBe(seedToHex(seedA)); + expect(room.game!.seedHash).toBe(sha256Hex(seedToHex(seedA))); + expect(room.game!.shuffles).toBe(4); + }); + + test('if the seats change while shuffling, nothing starts', async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const { practice } = harness(async () => { + await gate; + return { seed: seedA, tried: 2 }; + }); + const room = practice('one-card'); + room.botProfiles[botsOf(room)[0]!]!.luck = -0.9; + expect(room.start('A')).toBeNull(); + room.leave('A'); + release(); + await gate; + await Bun.sleep(0); + expect(room.status).toBe('lobby'); + expect(room.game).toBeNull(); + expect(room.starting).toBe(false); + }); + + test('a failed shuffle job still starts the game with a fresh seed; board games and luck near 0 never ask', async () => { + const asked: string[] = []; + const { practice } = harness(async (job) => { + asked.push(job.gameId); + throw new Error('worker down'); + }); + const omok = practice('omok'); + expect(omok.start('A')).toBeNull(); + expect(omok.status).toBe('playing'); + const cards = practice('one-card'); + cards.botProfiles[botsOf(cards)[0]!]!.luck = 1; + expect(cards.start('A')).toBeNull(); + expect(cards.status).toBe('lobby'); + await Bun.sleep(0); + await Bun.sleep(0); + expect(cards.status).toBe('playing'); + expect(cards.game!.shuffles).toBe(1); + const plain = practice('one-card'); + plain.botProfiles[botsOf(plain)[0]!]!.luck = 0.05; + expect(plain.start('A')).toBeNull(); + expect(plain.status).toBe('playing'); + expect(asked).toEqual(['one-card']); + }); +}); diff --git a/apps/server/src/rooms/bot-profile.ts b/apps/server/src/rooms/bot-profile.ts new file mode 100644 index 0000000..f6b29c7 --- /dev/null +++ b/apps/server/src/rooms/bot-profile.ts @@ -0,0 +1,62 @@ +/** + * Each computer's level and luck in a room (docs/09-game-engine.md §9.1, docs/06-lobby-rooms.md §12). + * Level 1~60: drawn when the computer is added (any level) or when the host picks a band (쉬움 1~20, 보통 21~40, + * 어려움 41~60). After that it moves a little from game to game but stays near where it started. + */ +import { secureRandom } from '@bg/engine'; +import { BOT_BANDS, BOT_LEVEL_MAX, bandOf, type BotPick } from '@bg/shared'; +import { hash01, idLevel } from '@bg/games/bots'; + +export interface BotProfile { + /** What the host chose: 랜덤 (any level) or a band. */ + pick: BotPick; + /** The level drawn for that choice; the drift stays around it. */ + base: number; + /** The level it plays at now. */ + level: number; + /** -1 (아주 나쁨) … 1 (아주 좋음), drawn once when the computer is added. */ + luck: number; + /** Games it has started with this base. */ + played: number; +} + +/** How far a level may move from where it started, and how much in one game. */ +export const DRIFT_RANGE = 5; +export const DRIFT_STEP = 2; + +const int = (lo: number, hi: number, random: () => number) => lo + Math.floor(random() * (hi - lo + 1)); + +export function rollLevel(pick: BotPick, random: () => number = secureRandom): number { + const [lo, hi] = pick === 'random' ? [1, BOT_LEVEL_MAX] : BOT_BANDS[pick]; + return int(lo, hi, random); +} + +export function newBotProfile(random: () => number = secureRandom): BotProfile { + const base = rollLevel('random', random); + return { pick: 'random', base, level: base, luck: random() * 2 - 1, played: 0 }; +} + +/** The host picked a difficulty: a new level from that range, luck stays. */ +export function repick(p: BotProfile, pick: BotPick, random: () => number = secureRandom): BotProfile { + const base = rollLevel(pick, random); + return { ...p, pick, base, level: base, played: 0 }; +} + +/** + * Before each game after the first: the level moves by at most `DRIFT_STEP`, never more than `DRIFT_RANGE` from where + * it started and never out of that band (a 60 can become 58, never 41). + */ +export function drift(p: BotProfile, random: () => number = secureRandom): BotProfile { + if (p.played === 0) return { ...p, played: 1 }; + const [blo, bhi] = BOT_BANDS[bandOf(p.base)]; + const lo = Math.max(blo, p.base - DRIFT_RANGE); + const hi = Math.min(bhi, p.base + DRIFT_RANGE); + const level = Math.min(hi, Math.max(lo, p.level + int(-DRIFT_STEP, DRIFT_STEP, random))); + return { ...p, level, played: p.played + 1 }; +} + +/** Computers saved before rooms kept a profile: level and luck fixed by the id. */ +export function profileFromId(bot: string): BotProfile { + const base = idLevel(bot); + return { pick: 'random', base, level: base, luck: hash01(bot, 'luck') * 2 - 1, played: 0 }; +} diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index 06a2d28..e330eba 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -5,7 +5,7 @@ */ import { secureRandom, type AnyGameDefinition } from '@bg/engine'; import { isBotId } from '@bg/shared'; -import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, type LiveBotStrategy } from '@bg/games/bots'; +import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; import type { BotBrain } from '../ai/brain'; @@ -23,6 +23,8 @@ export interface BotRoom { log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record) => void; /** Display name of a player (live bots talk about each other by name). */ nameOf?(id: string): string; + /** A computer's level now and the level it started with (docs/09 §9.1); absent = fixed by the id. */ + profile?(bot: string): { level: number; base: number }; /** The computers' talk and visible activity with the local model (docs/06 §12.1). */ brain?: BotBrain; } @@ -157,7 +159,7 @@ export class BotDriver { let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 }; const t0 = performance.now(); try { - decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot), names, memory }); + decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, this.room.profile?.(bot).base), names, memory }); } catch (err) { this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) }); } @@ -247,7 +249,7 @@ export class BotDriver { const t0 = performance.now(); let action: unknown; try { - action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: botPersona(next.bot).level }); + action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: this.room.profile?.(next.bot).level ?? idLevel(next.bot) }); } catch (err) { this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) }); action = null; diff --git a/apps/server/src/rooms/luck-worker.ts b/apps/server/src/rooms/luck-worker.ts new file mode 100644 index 0000000..a8646d8 --- /dev/null +++ b/apps/server/src/rooms/luck-worker.ts @@ -0,0 +1,18 @@ +/** Worker thread for the computers' luck (docs/04 §5.1): plays out candidate shuffles off the rooms' thread. */ +import { createSeed, secureRandom } from '@bg/engine'; +import { GAMES } from '@bg/games'; +import { chooseLuckySeed, type LuckJob } from '@bg/games/bots/luck'; + +declare const self: Worker; + +self.onmessage = (e: MessageEvent<{ id: number; job: LuckJob }>) => { + const { id, job } = e.data; + try { + const def = GAMES[job.gameId]; + if (!def) throw new Error(`unknown game ${job.gameId}`); + const { seed, tried } = chooseLuckySeed(def, job, createSeed, secureRandom); + self.postMessage({ id, seed, tried }); + } catch (err) { + self.postMessage({ id, error: String(err) }); + } +}; diff --git a/apps/server/src/rooms/luck.test.ts b/apps/server/src/rooms/luck.test.ts new file mode 100644 index 0000000..3791c63 --- /dev/null +++ b/apps/server/src/rooms/luck.test.ts @@ -0,0 +1,49 @@ +/** The luck worker (docs/04 §5.1): real thread, real play-outs. */ +import { expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import { createLuckSeeder } from './luck'; + +const job = (gameId: string, luck: number) => ({ + gameId, + players: ['human', 'bot:1:a'], + options: GAMES[gameId]?.defaultOptions ?? {}, + now: Date.now(), + gameNo: 1, + luck: { 'bot:1:a': luck }, + levels: { 'bot:1:a': 30 }, + budgetMs: 1500, +}); + +test('plays out the shuffles on a worker thread and returns one of them', async () => { + const seeder = createLuckSeeder(); + try { + const [lucky, plain] = await Promise.all([seeder.seed(job('one-card', 1)), seeder.seed(job('one-card', 0))]); + expect(lucky.seed).toHaveLength(8); + expect(lucky.tried).toBe(5); + expect(plain.tried).toBe(1); + expect(lucky.seed.every((w) => Number.isInteger(w) && w >= 0 && w < 2 ** 32)).toBe(true); + } finally { + seeder.stop(); + } +}, 20_000); + +test('an unknown game or a slow worker falls back to one fresh seed', async () => { + const logs: string[] = []; + const seeder = createLuckSeeder({ log: (_l, msg) => logs.push(msg) }); + try { + const r = await seeder.seed(job('nope', 1)); + expect(r.tried).toBe(1); + expect(r.seed).toHaveLength(8); + expect(logs).toContain('luck shuffle failed'); + } finally { + seeder.stop(); + } + const slow = createLuckSeeder({ timeoutMs: 1, log: (_l, msg) => logs.push(msg) }); + try { + const r = await slow.seed(job('mahjong', 1)); + expect(r.tried).toBe(1); + expect(logs).toContain('luck shuffle timed out'); + } finally { + slow.stop(); + } +}, 20_000); diff --git a/apps/server/src/rooms/luck.ts b/apps/server/src/rooms/luck.ts new file mode 100644 index 0000000..52f24eb --- /dev/null +++ b/apps/server/src/rooms/luck.ts @@ -0,0 +1,76 @@ +/** + * The rooms' side of the luck worker (docs/04-stability-security.md §5.1). Playing out a few shuffles takes up to a + * couple of seconds for the heaviest games (마작), so it runs on its own thread; the rooms keep running meanwhile. + * One worker, jobs in order. If the worker fails or takes too long, the game starts with one fresh seed (no luck). + */ +import { createSeed, type ChaChaSeed } from '@bg/engine'; +import type { LuckJob } from '@bg/games/bots/luck'; + +type Picked = { seed: ChaChaSeed; tried: number }; + +export interface LuckSeeder { + seed(job: LuckJob): Promise; + stop(): void; +} + +export function createLuckSeeder(opts: { timeoutMs?: number; log?: (level: 'warn' | 'error', msg: string, extra?: Record) => void } = {}): LuckSeeder { + const timeoutMs = opts.timeoutMs ?? 8000; + let worker: Worker | null = null; + let nextId = 1; + const pending = new Map void; timer: ReturnType }>(); + const fallback = (): Picked => ({ seed: createSeed(), tried: 1 }); + + const settle = (id: number, p: Picked) => { + const job = pending.get(id); + if (!job) return; + pending.delete(id); + clearTimeout(job.timer); + job.resolve(p); + }; + + const reset = (why: string) => { + opts.log?.('error', 'luck worker failed', { why }); + worker?.terminate(); + worker = null; + for (const id of [...pending.keys()]) settle(id, fallback()); + }; + + const get = (): Worker => { + if (worker) return worker; + const w = new Worker(new URL('./luck-worker.ts', import.meta.url).href); + w.onmessage = (e: MessageEvent<{ id: number; seed?: ChaChaSeed; tried?: number; error?: string }>) => { + const { id, seed, tried, error } = e.data; + if (error || !seed) { + opts.log?.('warn', 'luck shuffle failed', { error }); + settle(id, fallback()); + } else settle(id, { seed, tried: tried ?? 1 }); + }; + w.onerror = (e) => reset(String((e as ErrorEvent).message ?? e)); + w.unref(); + worker = w; + return w; + }; + + return { + seed(job) { + return new Promise((resolve) => { + const id = nextId++; + const timer = setTimeout(() => { + opts.log?.('warn', 'luck shuffle timed out', { game: job.gameId }); + settle(id, fallback()); + }, timeoutMs); + pending.set(id, { resolve, timer }); + try { + get().postMessage({ id, job }); + } catch (err) { + reset(String(err)); + } + }); + }, + stop() { + worker?.terminate(); + worker = null; + for (const id of [...pending.keys()]) settle(id, fallback()); + }, + }; +} diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index afeb6ab..6feb385 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -29,6 +29,8 @@ export interface ManagerDeps { ai?: RoomDeps['ai']; aiSleep?: RoomDeps['aiSleep']; aiRandom?: RoomDeps['aiRandom']; + /** Shuffles for the computers' luck (docs/04 §5.1); absent = one fresh seed per game. */ + luckSeed?: RoomDeps['luckSeed']; /** When the user's last socket to the site closed; null while the site is open somewhere (the gateway knows). */ offlineSince?: (userId: string) => number | null; } @@ -56,6 +58,7 @@ export class RoomManager { ai: this.deps.ai, aiSleep: this.deps.aiSleep, aiRandom: this.deps.aiRandom, + luckSeed: this.deps.luckSeed, onEmpty: (room, why) => { // The last person left on purpose and nobody holds a seat (only computers, or nobody joined): close it now. if (why === 'leave' && this.byCode.get(room.code) === room && !room.hasPeopleSeated()) this.close(room); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index 70fc2df..1d63fbb 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -3,10 +3,13 @@ * All mutations run on the single JS thread, so a room never sees concurrent updates. */ import { ulid } from 'ulid'; -import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine'; -import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared'; +import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine'; +import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared'; +import { botPersona } from '@bg/games/bots'; +import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck'; import { sha256Hex } from '../auth/sessions'; import { BotDriver, type BotDelayInput } from './bots'; +import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile'; import { BotBrain, type BotActivity } from '../ai/brain'; import type { Llm } from '../ai/llm'; import type { LogEntry, RoomStore } from './store'; @@ -54,6 +57,10 @@ interface GameSlot { finished: boolean; /** After a restore, deadlines are not enforced before this time (docs/04 §3.3). */ deadlineFloor: number | null; + /** Each computer's level and luck in this game (shown in the fairness check afterwards). */ + bots?: Record; + /** Shuffles tried for the computers' luck (docs/04 §5.1); 1 or absent = the first one. */ + shuffles?: number; } /** Shape persisted to room_state.state_json. */ @@ -70,6 +77,8 @@ export interface RoomSnapshot { lastResult: GameResult | null; game: GameSlot | null; joinedAt: Record; + /** Computers' level and luck (absent in rooms saved before 2026-10-11: then fixed by the bot id). */ + bots?: Record; } export interface RoomDeps { @@ -91,9 +100,16 @@ export interface RoomDeps { aiSleep?: (ms: number) => Promise; /** Dice for the computers' talk (whether to speak now); tests may pin it. */ aiRandom?: () => number; + /** + * Tries shuffles for the computers' luck off the main thread (docs/04 §5.1). Absent (tests): every game starts at + * once with one fresh seed. + */ + luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>; } const CHAT_HISTORY = 30; +/** Time the luck worker may spend on more shuffles (the first is always played out), docs/04 §5.1. */ +export const LUCK_BUDGET_MS = 1500; const ERROR_LIMIT = 3; /** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */ const STREAM_FLUSH_MS = 1000; @@ -117,6 +133,12 @@ export class Room { lastSeed: string | null = null; lastResult: GameResult | null = null; game: GameSlot | null = null; + /** Computers' level and luck (docs/09 §9.1), by bot id. */ + botProfiles: Record = {}; + /** The computers' shuffles are being tried; the game starts when they're done. */ + starting = false; + /** Shut down or closed: late callbacks (the luck worker) must not touch it. */ + private closed = false; chatLog: Extract[] = []; lastActiveAt: number; /** When the last connection went away (null while someone is connected). */ @@ -166,6 +188,7 @@ export class Room { this.broadcastRoom(); }, recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })), + smart: (bot) => botPersona(bot, this.profile(bot).base).smart, now: this.now, }, deps.ai ?? null, @@ -191,6 +214,7 @@ export class Room { }, log: deps.log, nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가', + profile: (bot) => this.profile(bot), brain: this.brain, }, secureRandom, @@ -289,6 +313,7 @@ export class Room { lastResult: this.lastResult, game: this.game, joinedAt, + bots: this.botProfiles, }; } @@ -303,6 +328,7 @@ export class Room { room.lastSeed = snap.lastSeed; room.lastResult = snap.lastResult; room.game = snap.game; + room.botProfiles = snap.bots ?? {}; const now = room.now(); for (const s of room.seats) { // Computer players have no connection (and so no reconnect grace period). @@ -396,6 +422,10 @@ export class Room { lastSeed: this.lastSeed, lastGamePk: this.game?.finished ? this.game.gamePk : null, ...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}), + ...(this.hasBots() ? { botPicks: Object.fromEntries(this.seatedIds().filter(isBotId).map((b) => [b, this.profile(b).pick])) } : {}), + ...(this.starting ? { starting: true } : {}), + // Levels are revealed only once the game is over (fairness check). + ...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}), }; } @@ -574,9 +604,15 @@ export class Room { // ---------------------------------------------------------------- lobby commands private requireLobby(): string | null { + if (this.starting) return '게임을 준비하고 있어요.'; return this.status === 'lobby' || this.status === 'finished' ? null : '게임 중에는 바꿀 수 없어요.'; } + /** A computer's level and luck; computers saved without one get it from their id. */ + profile(bot: string): BotProfile { + return (this.botProfiles[bot] ??= profileFromId(bot)); + } + seat(userId: string, seat?: number): string | null { const err = this.requireLobby(); if (err) return err; @@ -712,9 +748,10 @@ export class Room { const used = new Set(this.seatedIds().map(botNumber)); let n = 1; while (used.has(n)) n++; - // The id's random part is the computer's level roll (`botDraw`): uniform OS randomness. const id = makeBotId(n, ulid(this.now(), secureRandom)); this.seats[target] = { userId: id, ready: true }; + // Any level 1~60 and its own luck, from OS randomness; the host may pick 쉬움/보통/어려움 afterwards. + this.botProfiles[id] = newBotProfile(); if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' }; this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } }); this.broadcastRoom(); @@ -729,11 +766,24 @@ export class Room { if (seat < 0 || !isBotId(botId)) return '없는 컴퓨터예요.'; this.seats[seat] = null; this.rematchVotes.delete(botId); + delete this.botProfiles[botId]; this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } }); this.broadcastRoom(); return null; } + /** Host picks a computer's difficulty: a new level from that range (랜덤 = any), hidden until the game is over. */ + setBotLevel(userId: string, botId: string, pick: BotPick): string | null { + if (userId !== this.hostId) return '방장만 난이도를 바꿀 수 있어요.'; + const err = this.requireLobby(); + if (err) return err; + if (this.seatOf(botId) < 0 || !isBotId(botId)) return '없는 컴퓨터예요.'; + this.botProfiles[botId] = repick(this.profile(botId), pick); + this.persist({ actorId: userId, kind: 'botLevel', data: { bot: botId, pick } }); + this.broadcastRoom(); + return null; + } + chat(userId: string, text: string): string | null { if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.'; if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.'; @@ -781,17 +831,18 @@ export class Room { if (players.length > range.max) return `최대 ${range.max}명까지 할 수 있어요.`; if (this.hasBots() && !botsAllowed(this.config.gameId)) return '컴퓨터는 이 게임을 할 수 없어요.'; if (players.every(isBotId)) return '사람이 한 명은 앉아야 해요.'; - return this.startGame(players); + return this.beginGame(players); } rematch(userId: string): string | null { if (this.status !== 'finished') return '게임이 끝난 뒤에 누를 수 있어요.'; + if (this.starting) return '게임을 준비하고 있어요.'; if (this.seatOf(userId) < 0) return '자리에 앉아야 해요.'; this.rematchVotes.add(userId); const seated = this.seatedIds(); const range = this.playerRange(); if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) { - return this.startGame(this.orderedPlayers()); + return this.beginGame(this.orderedPlayers()); } this.persist(null); this.broadcastRoom(); @@ -805,7 +856,8 @@ export class Room { return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids; } - private startGame(players: string[]): string | null { + /** The options the game would start with, or why it can't start. */ + private startOptions(players: string[]): { options: unknown } | string { const def = this.def; const lk = this.locked(def.id); const parsed = def.optionsSchema.safeParse(lk.paths.length ? applyLocks(this.config.options, lk.defaults, lk.paths) : this.config.options); @@ -814,22 +866,75 @@ export class Room { if (countErr) return countErr; const eff = this.deps.settings?.game(def.id); if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.'; - this.config = { ...this.config, options: parsed.data }; - const seed = createSeed(); + return { options: parsed.data }; + } + + /** + * Starts a game. With computers in a game of chance, a few shuffles are tried first for their luck (docs/04 §5.1) + * on the luck worker; the room shows "섞는 중" and starts when they are done (well under a few seconds). If the + * seats changed meanwhile, nothing starts and the host can press start again. + */ + private beginGame(players: string[]): string | null { + const ok = this.startOptions(players); + if (typeof ok === 'string') return ok; + const bots = players.filter(isBotId); + const luckSeed = this.deps.luckSeed; + if (!luckSeed || !luckApplies(this.def.id) || shufflesFor(bots.map((b) => this.profile(b).luck)) <= 1) return this.startGame(players, null); + const job: LuckJob = { + gameId: this.def.id, + players, + options: ok.options, + now: this.now(), + gameNo: this.gameNo + 1, + luck: Object.fromEntries(bots.map((b) => [b, this.profile(b).luck])), + levels: Object.fromEntries(bots.map((b) => [b, this.profile(b).level])), + budgetMs: LUCK_BUDGET_MS, + }; + this.starting = true; + this.broadcastRoom(); + const gameNo = this.gameNo; + void luckSeed(job) + .catch((err) => { + this.deps.log?.('warn', 'luck shuffle failed', { room: this.code, err: String(err) }); + return null; + }) + .then((picked) => { + this.starting = false; + if (this.closed) return; + const same = this.gameNo === gameNo && this.requireLobby() === null && this.orderedPlayers().join() === players.join(); + const err = same ? this.startGame(players, picked) : null; + if (err) this.notice('start-failed', err); + if (!same || err) this.broadcastRoom(); + }); + return null; + } + + private startGame(players: string[], picked: { seed: ChaChaSeed; tried: number } | null): string | null { + const def = this.def; + const ok = this.startOptions(players); + if (typeof ok === 'string') return ok; + this.config = { ...this.config, options: ok.options }; + const seed = picked?.seed ?? createSeed(); const seedHex = seedToHex(seed); const rng = SeededRng.fromSeed(seed); const now = this.now(); const gameNo = this.gameNo + 1; let state: unknown; try { - state = def.setup({ players, options: parsed.data, rng, now, gameNo }); + state = def.setup({ players, options: ok.options, rng, now, gameNo }); } catch (err) { this.deps.log?.('error', 'setup failed', { room: this.code, err: String(err) }); return '게임을 시작하지 못했어요.'; } const gamePk = ulid(now); const seedHash = sha256Hex(seedHex); - this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: parsed.data, seedHash, startedAt: now }); + // From the second game on, each computer's level moves a little around where it started (docs/09 §9.1). + const bots: Record = {}; + for (const b of players.filter(isBotId)) { + const p = (this.botProfiles[b] = drift(this.profile(b))); + bots[b] = { level: p.level, luck: p.luck }; + } + this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: ok.options, seedHash, startedAt: now }); this.gameNo = gameNo; this.game = { gameId: def.id, @@ -843,6 +948,7 @@ export class Room { players, finished: false, deadlineFloor: null, + ...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}), }; this.status = 'playing'; this.rematchVotes.clear(); @@ -1074,6 +1180,7 @@ export class Room { /** Ends a running game uncounted and sends everyone still in the room away (the manager then closes it). */ closeWith(summary: string, notice: string): void { + this.closed = true; if (this.game && !this.game.finished) { this.finishGame({ ranking: [this.game.players], summary, reason: 'abandoned' }, true); } @@ -1087,6 +1194,7 @@ export class Room { } shutdown(): void { + this.closed = true; this.flushStream(); this.clearTimer(); for (const c of this.conns.values()) { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ddc7fff..a0b65ae 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,5 +1,5 @@ /** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */ -import { existsSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { join, normalize } from 'node:path'; import type { Server } from 'bun'; import { GAMES } from '@bg/games'; @@ -11,6 +11,7 @@ import { SESSION_COOKIE, Sessions } from './auth/sessions'; import { Users, toPublicUser } from './auth/users'; import { createHttpApp, type HttpDeps } from './http/app'; import { RoomManager } from './rooms/manager'; +import { createLuckSeeder } from './rooms/luck'; import type { BotDelayInput } from './rooms/bots'; import { RoomStore } from './rooms/store'; import { Replays } from './rooms/replay'; @@ -38,6 +39,8 @@ export interface StartOptions { botDelay?: (input: BotDelayInput) => number; /** Upper bound for waiting on Bun's server.stop() (tests shorten it). */ stopWaitMs?: number; + /** Computers' luck on a worker thread (docs/04 §5.1); default on. */ + luck?: boolean; } export function startServer(opts: StartOptions) { @@ -60,10 +63,21 @@ export function startServer(opts: StartOptions) { // Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8). const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null; if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok })); - const rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, ai, offlineSince: (id): number | null => gateway.offlineSince(id) }); + const luck = opts.luck === false ? null : createLuckSeeder({ log }); + const rooms = new RoomManager({ + store, + games: GAMES, + users: { publicUser }, + log, + settings, + botDelay: opts.botDelay, + ai, + luckSeed: luck ? (job) => luck.seed(job) : undefined, + offlineSince: (id): number | null => gateway.offlineSince(id), + }); const restored = rooms.restoreAll(); log('info', 'rooms restored', restored); - const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id) }); + const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id), build: () => build }); const removeGuest = (id: string) => { rooms.leaveAll(id); gateway.closeUser(id); @@ -85,8 +99,13 @@ export function startServer(opts: StartOptions) { server?.requestIP(req)?.address || 'unknown'; + const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir; + const serveStatic = staticDir && existsSync(staticDir); + // The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh. + const build = serveStatic ? webBuildId(staticDir!) : null; const app = createHttpApp({ config, + build, users, sessions, rooms, @@ -121,8 +140,6 @@ export function startServer(opts: StartOptions) { }, }); - const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir; - const serveStatic = staticDir && existsSync(staticDir); const server: Server = Bun.serve({ port: config.port, @@ -171,6 +188,7 @@ export function startServer(opts: StartOptions) { clearInterval(sweeper); gateway.shutdown(); rooms.shutdown(); + luck?.stop(); // Bun's stop() promise can stay pending after server-initiated WS closes even though the // listener is already closed, so bound the wait. await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]); @@ -180,6 +198,15 @@ export function startServer(opts: StartOptions) { return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests }; } +/** The build id the web build wrote into its index.html (``, vite.config.ts), or null. */ +export function webBuildId(root: string): string | null { + try { + return / { const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, ''); const candidate = join(root, safe); diff --git a/apps/server/src/version.test.ts b/apps/server/src/version.test.ts new file mode 100644 index 0000000..a273711 --- /dev/null +++ b/apps/server/src/version.test.ts @@ -0,0 +1,44 @@ +/** "업데이트 내용이 있습니다" (docs/07 §11.1): the server tells which web build it serves. */ +import { afterEach, expect, test } from 'bun:test'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { webBuildId } from './server'; +import { Client, api, boot, guest } from './test-utils'; + +const running: ReturnType[] = []; +const clients: Client[] = []; +afterEach(async () => { + for (const c of clients.splice(0)) c.close(); + for (const s of running.splice(0)) await s.stop(); +}); + +function webDir(html: string): string { + const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'bg-web-')); + writeFileSync(join(dir, 'index.html'), html); + return dir; +} + +test('the build id comes from the meta tag of the served index.html', () => { + expect(webBuildId(webDir(''))).toBe('abc123def456'); + expect(webBuildId(webDir(''))).toBeNull(); + expect(webBuildId('/nonexistent/dir')).toBeNull(); +}); + +test('/api/version and the socket welcome carry the build', async () => { + const s = boot(undefined, { staticDir: webDir('') }); + running.push(s); + const r = await api(s.base, '/api/version'); + expect(r.res.headers.get('cache-control')).toBe('no-store'); + expect(r.body).toEqual({ build: '0123456789ab' }); + const g = await guest(s.base, '버전확인'); + const c = await new Client(s.base, g.cookie, g.id).connect(); + clients.push(c); + expect(c.lastOf('welcome')!.build).toBe('0123456789ab'); +}); + +test('without a web build (dev, tests) there is nothing to compare', async () => { + const s = boot(); + running.push(s); + expect((await api(s.base, '/api/version')).body).toEqual({ build: null }); +}); diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 2e1703c..d223bf2 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -21,6 +21,8 @@ export interface GatewayDeps { log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record) => void; /** A socket closed (the user may have left the site). */ onClose?: (userId: string) => void; + /** Web build being served (pages opened with an older one offer to refresh, docs/07 §11.1). */ + build?: () => string | null; } export const MAX_CONNS_PER_USER = 5; @@ -84,6 +86,7 @@ export class Gateway { serverTime: (this.deps.now ?? Date.now)(), protocol: PROTOCOL, activeRoom: this.deps.rooms.activeRoomFor(ws.data.userId), + build: this.deps.build?.() ?? null, }); }, @@ -193,6 +196,9 @@ export class Gateway { case 'removeBot': e = room.removeBot(u, m.userId); break; + case 'botLevel': + e = room.setBotLevel(u, m.userId, m.pick); + break; case 'act': room.act(u, m.cs, m.a); return; diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx index 46612d7..1731bbe 100644 --- a/apps/web/src/components/ui.tsx +++ b/apps/web/src/components/ui.tsx @@ -6,6 +6,7 @@ import { useToasts, toast } from '../store/toast'; import { useRoom } from '../net/socket'; import { haptic } from '../lib/feedback'; import { useOnline } from '../lib/pwa'; +import { dismissUpdate, useUpdateAvailable } from '../lib/update'; const AVATAR_COLORS = ['#2563eb', '#db2777', '#16a34a', '#ea580c', '#7c3aed', '#0891b2', '#ca8a04', '#dc2626']; @@ -146,6 +147,23 @@ export function ConnectionBanner() { return null; } +/** The site was updated while this page was open (docs/07 §11.1): refresh, or ✕ to close until the next update. */ +export function UpdateBanner() { + const show = useUpdateAvailable(); + if (!show) return null; + return ( +
+ 업데이트 내용이 있습니다. + + +
+ ); +} + export function CodeLabel({ code }: { code: string }) { return {formatRoomCode(code)}; } diff --git a/apps/web/src/lib/update.ts b/apps/web/src/lib/update.ts new file mode 100644 index 0000000..6368e8c --- /dev/null +++ b/apps/web/src/lib/update.ts @@ -0,0 +1,61 @@ +/** + * "업데이트 내용이 있습니다" (docs/07 §11.1). The page knows its own build (``, written by + * vite.config.ts); the server tells its build in `welcome` and at `/api/version`. When they differ the page offers a + * refresh at the top; ✕ hides it until the next update. Dev builds have no meta and never ask. + */ +import { useSyncExternalStore } from 'react'; + +const POLL_MS = 5 * 60_000; + +const mine = typeof document === 'undefined' ? null : (document.querySelector('meta[name="bg-build"]')?.content ?? null); +/** Build the server has that this page doesn't ('protocol' = the server speaks a newer protocol). */ +let latest: string | null = null; +let dismissed: string | null = null; +const listeners = new Set<() => void>(); +const emit = () => listeners.forEach((l) => l()); + +/** The server's build (welcome message, `/api/version`). */ +export function noteServerBuild(build: string | null | undefined): void { + if (!mine || !build || build === mine || build === latest) return; + latest = build; + emit(); +} + +/** The server speaks a different protocol: this page must be refreshed whatever its build. */ +export function markOutdated(): void { + if (latest) return; + latest = 'protocol'; + emit(); +} + +export function dismissUpdate(): void { + dismissed = latest; + emit(); +} + +async function check(): Promise { + try { + const res = await fetch('/api/version', { cache: 'no-store' }); + if (res.ok) noteServerBuild(((await res.json()) as { build?: string | null }).build); + } catch { + // Offline or restarting: the next check (or the socket's welcome) will tell. + } +} + +/** Call once at startup: checks now and then, and whenever the tab comes back into view. */ +export function initUpdateCheck(): void { + if (!mine) return; + setInterval(() => void check(), POLL_MS); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') void check(); + }); +} + +const subscribe = (l: () => void) => { + listeners.add(l); + return () => void listeners.delete(l); +}; + +export function useUpdateAvailable(): boolean { + return useSyncExternalStore(subscribe, () => latest !== null && latest !== dismissed, () => false); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index c2f6c51..889a9d0 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -3,12 +3,13 @@ import { createRoot } from 'react-dom/client'; import { BrowserRouter, Route, Routes, useLocation, useNavigate } from 'react-router'; import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css'; import './styles/global.css'; -import { ConnectionBanner, Toasts } from './components/ui'; +import { ConnectionBanner, Toasts, UpdateBanner } from './components/ui'; import { useSession } from './store/session'; import { toast } from './store/toast'; import { Home } from './pages/Home'; import { SiteHeader } from './components/SiteHeader'; import { initPwa } from './lib/pwa'; +import { initUpdateCheck } from './lib/update'; const JoinPage = lazy(() => import('./pages/JoinPage')); const RoomPage = lazy(() => import('./pages/RoomPage')); @@ -58,6 +59,7 @@ function Shell() { return ( <> + @@ -82,6 +84,7 @@ function Shell() { } initPwa(); +initUpdateCheck(); createRoot(document.getElementById('root')!).render( diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index d5f25f3..523b593 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -5,6 +5,7 @@ import { create } from 'zustand'; import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite'; import { toast } from '../store/toast'; +import { markOutdated, noteServerBuild } from '../lib/update'; export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline'; @@ -39,7 +40,6 @@ interface RoomStore { clockOffset: number; joinError: string | null; kicked: boolean; - needsRefresh: boolean; } export const useRoom = create(() => ({ @@ -58,7 +58,6 @@ export const useRoom = create(() => ({ clockOffset: 0, joinError: null, kicked: false, - needsRefresh: false, })); const BACKOFF = [500, 1000, 2000, 4000, 8000]; @@ -256,7 +255,8 @@ class GameSocket { const st = useRoom.getState(); switch (m.t) { case 'welcome': { - if (m.protocol !== PROTOCOL) useRoom.setState({ needsRefresh: true }); + if (m.protocol !== PROTOCOL) markOutdated(); + else noteServerBuild(m.build); useRoom.setState({ status: 'open', me: m.me }); this.offsets = [m.serverTime - Date.now()]; useRoom.setState({ clockOffset: this.offsets[0]! }); diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index 7219bdc..fe12e90 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -1,7 +1,7 @@ /** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; -import { botsAllowed, formatRoomCode, isBotId, type PublicUser, type RoomView } from '@bg/shared/lite'; +import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite'; import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui'; import { GuestWarning, NicknameForm } from '../components/NicknameForm'; import { GameNotice, gameName } from '../components/GameNotice'; @@ -88,7 +88,7 @@ function RoomGone({ message }: { message: string }) { function Room({ code, me }: { code: string; me: PublicUser }) { const nav = useNavigate(); - const { room, game, result, status, joinError, pending, slow, needsRefresh } = useRoom(); + const { room, game, result, status, joinError, pending, slow } = useRoom(); const [ui, setUi] = useState(null); const [leaveAsk, setLeaveAsk] = useState(false); const [chatOpen, setChatOpen] = useState(false); @@ -224,14 +224,6 @@ function Room({ code, me }: { code: string; me: PublicUser }) { - {needsRefresh && ( -
- 새 버전이 있어요. - -
- )} {inGame && game ? ( ) : ( @@ -331,18 +323,38 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
4 ? 3 : 2}, minmax(0, 1fr))` : '1fr', gap: 10 }}> {room.seats.map((s, i) => s && isBotId(s.user.id) ? ( -
- -
-
{s.user.nickname}
-
- 🤖 컴퓨터 +
+
+ +
+
{s.user.nickname}
+
+ 🤖 컴퓨터 + {!isHost && 난이도 {BOT_PICK_LABEL[room.botPicks?.[s.user.id] ?? 'random']}} +
+ {isHost && ( + + )}
+ {/* docs/06 §12: 랜덤 = any level 1~60; a band = a random level inside it. The level shows after the game. */} {isHost && ( - +
+ {BOT_PICKS.map((p) => ( + + ))} +
)}
) : s ? ( @@ -428,8 +440,8 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
{isHost ? ( - ) : mySeat >= 0 ? ( room.seats[mySeat]!.ready ? ( @@ -751,7 +763,7 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView; 방 나가기 {room.lastSeed && ( - + )} ); @@ -761,7 +773,19 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView; * docs/04 §5: the seed's SHA-256 was published when the game started; the seed is revealed at the end. * The browser recomputes the hash itself so players don't have to trust the server's word. */ -function FairnessCheck({ seedHash, seed }: { seedHash: string | null; seed: string }) { +function FairnessCheck({ + seedHash, + seed, + bots, + shuffles, + players, +}: { + seedHash: string | null; + seed: string; + bots?: RoomView['lastBots']; + shuffles?: number; + players: Record; +}) { const [verdict, setVerdict] = useState(null); const check = async () => { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed)); @@ -771,6 +795,17 @@ function FairnessCheck({ seedHash, seed }: { seedHash: string | null; seed: stri return (
공정성 확인 + {/* docs/09 §9.1: each computer's level (1~60) and luck in this game; docs/04 §5.1: shuffles tried for luck. */} + {bots && Object.keys(bots).length > 0 && ( +
+ {Object.entries(bots).map(([id, b]) => ( +

+ 🤖 {players[id]?.nickname ?? '컴퓨터'}: 난이도 {b.level}단계 ({BOT_PICK_LABEL[bandOf(b.level)]}) · 운 {luckLabel(b.luck)} +

+ ))} + {(shuffles ?? 1) > 1 &&

이번 판은 컴퓨터의 운에 맞춰, 미리 섞어 본 {shuffles}가지 중 하나로 시작했어요. 고른 결과는 시작할 때 아래 값으로 공개했어요.

} +
+ )}

시작할 때 공개한 값(SHA-256): {seedHash ?? '-'}

끝나고 공개한 난수 씨앗: {seed}