diff --git a/apps/server/src/rooms/room.test.ts b/apps/server/src/rooms/room.test.ts index e951263..9fef98a 100644 --- a/apps/server/src/rooms/room.test.ts +++ b/apps/server/src/rooms/room.test.ts @@ -117,6 +117,28 @@ describe('Room timers', () => { expect(room.effectiveDeadline()).toBe(base + 2_000); }); + test('a deadline moved by a screen that reported before is told to every client (omok)', () => { + const { room, clock, conn } = harness(); + const a = conn('A'); + const b = conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } }); + room.start('A'); + room.settled('A', room.seq); + room.settled('B', room.seq); + room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]); + room.clearTimer(); + const base = clock.now() + 10_000; + const sent = b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }; + expect(sent.deadline).toBe(base); + clock.advance(2_000); + room.settled('B', room.seq); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 2_000); + for (const c of [a, b]) expect(c.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 2_000 }); + }); + test('disconnected player is auto-acted after the grace period, not before the turn deadline rules', () => { const { room, clock, conn } = harness(); const a = conn('A'); @@ -345,3 +367,63 @@ describe('Room chat (2026-10-13)', () => { expect(typingOf(b)).toHaveLength(3); }); }); + +describe('Room clocks after the animation (shared steps)', () => { + // Like 라이어 게임's last guess: everybody votes, then only the liar (B) answers, while the room times a stand-in (A). + const guess: AnyGameDefinition = { + id: 'guess', + nameKo: '맞히기', + minPlayers: 2, + maxPlayers: 2, + stateVersion: 1, + defaultOptions: {}, + optionsSchema: z.object({}), + actionSchema: z.object({ type: z.enum(['go', 'chat']) }), + setup: ({ players, now }) => ({ players, step: 'vote', deadlineAt: now + 10_000, chats: 0 }), + validate: () => ({ ok: true }), + apply: (s: any, _p, a: any, { now }) => ({ state: a.type === 'go' ? { ...s, step: 'guess', deadlineAt: now + 10_000 } : { ...s, chats: s.chats + 1 }, events: [] }), + view: (s) => s, + activePlayers: (s: any) => (s.step === 'guess' ? [s.players[1]] : s.players), + timeoutPlayers: (s: any) => (s.step === 'guess' ? [s.players[0]] : s.players), + deadline: (s: any) => s.deadlineAt, + onTimeout: () => ({ type: 'chat' }), + result: () => null, + }; + + test('the stand-in\'s clock waits for the real answerer\'s screen, and a chat line keeps the time given', () => { + const { room, clock, conn } = harness({ guess }); + const a = conn('A'); + const b = conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.start('A'); + room.settled('A', room.seq); + room.settled('B', room.seq); + room.act('A', 1, { type: 'go' }); // → only B answers now, A is the timed stand-in + room.clearTimer(); + const base = clock.now() + 10_000; + clock.advance(1_000); + room.settled('A', room.seq); // A's screen is quick: that must not start B's clock + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 15_000); + clock.advance(5_000); + room.settled('B', room.seq); // B's screen took 6 s + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 6_000); + expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 }); + // A chat line in the same step keeps B's 6 s. + clock.advance(1_000); + room.act('A', 2, { type: 'chat' }); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 6_000); + expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000); + room.settled('B', room.seq); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 6_000); + // B still gets the whole 10 s from when the screen settled: nothing fires a moment before that. + clock.advance(base + 6_000 - clock.now() - 1); + room.onTimer(); + room.clearTimer(); + expect((room.game!.state as any).chats).toBe(1); + }); +}); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index ce38b08..8df1313 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -163,7 +163,9 @@ export class Room { * The last game state change and when each player's screen finished animating it (client `settled`). A player's * clock starts then, so a choice shown after the animation still gets its full time (`revealExtra`). */ - private reveal: { seq: number; at: number; done: Map } | null = null; + private reveal: { seq: number; at: number; done: Map; key: string } | null = null; + /** The deadline last sent to the clients (state / deadline messages), so a moved deadline is always told. */ + private sentDeadline: number | null = null; /** Players whose screens report `settled` (pages from before 2026-11-08 don't: their clocks run as before). */ private settles = new Set(); private readonly now: () => number; @@ -474,7 +476,7 @@ export class Room { view, events: [], active: this.game.finished ? [] : def.activePlayers(this.game.state), - deadline: this.game.finished ? null : this.publicDeadline(), + deadline: (this.sentDeadline = this.game.finished ? null : this.publicDeadline()), ...(cs !== undefined ? { cs } : {}), }; } @@ -486,7 +488,10 @@ export class Room { private broadcastState(events: unknown[], actor?: string, cs?: number): void { if (!this.game) return; - this.reveal = { seq: this.seq, at: this.now(), done: new Map() }; + // A change that leaves the step as it was (a chat line, a move inside the same shared clock) keeps the time + // already given for the step's animation; a new step (new clock, new players to act) starts a new reveal. + const key = this.revealKey(); + if (!this.reveal || this.reveal.key !== key) this.reveal = { seq: this.seq, at: this.now(), done: new Map(), key }; let spectatorMsg: ServerMessage | null = null; for (const c of this.conns.values()) { let msg: ServerMessage | null; @@ -1163,16 +1168,35 @@ export class Room { return provisional ? Math.min(cap, Math.max(0, this.now() - r.at)) : cap; } + /** What a step is: its clock and who acts / is timed in it. */ + private revealKey(): string { + const g = this.game!; + const def = this.def; + return JSON.stringify([def.deadline?.(g.state) ?? null, def.activePlayers(g.state), def.timeoutPlayers?.(g.state) ?? null]); + } + + /** + * Extra time on `u`'s clock. A player who has to answer gets their own screen's animation time; a player timed for + * a step others answer (the room times one stand-in for a shared clock) gets the slowest answerer's, so the + * people who really answer are never cut short by someone else's faster screen. + */ + private clockExtra(u: string, provisional = false): number { + const answer = this.def.activePlayers(this.game!.state); + if (answer.includes(u)) return this.revealExtra(u, provisional); + return Math.max(0, ...answer.map((p) => this.revealExtra(p, provisional))); + } + /** A player's screen finished animating the state `seq` (or a later one): their clock starts now. */ settled(userId: string, seq: number): void { const r = this.reveal; if (!r || seq < r.seq || r.done.has(userId) || !this.game || this.game.finished || !this.game.players.includes(userId)) return; - const before = this.publicDeadline(); this.settles.add(userId); r.done.set(userId, this.now()); this.scheduleTimer(); const after = this.publicDeadline(); - if (after !== before) for (const c of this.conns.values()) c.send({ t: 'deadline', deadline: after }); + if (after === this.sentDeadline) return; + this.sentDeadline = after; + for (const c of this.conns.values()) c.send({ t: 'deadline', deadline: after }); } /** Earliest time any timed player must be auto-acted for. */ @@ -1186,7 +1210,7 @@ export class Room { const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000; let best: number | null = null; for (const u of timed) { - let d = base === null ? null : base + this.revealExtra(u, provisional); + let d = base === null ? null : base + this.clockExtra(u, provisional); const p = this.presence.get(u); if (p && !p.connected) { const grace = p.since + graceMs; @@ -1230,7 +1254,7 @@ export class Room { const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state); const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000; for (const u of timed) { - let d = base === null ? null : base + this.revealExtra(u); + let d = base === null ? null : base + this.clockExtra(u); const p = this.presence.get(u); if (p && !p.connected) { const grace = p.since + graceMs; diff --git a/apps/web/src/games/yut/aug-ui.tsx b/apps/web/src/games/yut/aug-ui.tsx index 20b0a22..2382b66 100644 --- a/apps/web/src/games/yut/aug-ui.tsx +++ b/apps/web/src/games/yut/aug-ui.tsx @@ -334,15 +334,20 @@ export function AugSelect({ v, act, pending, players, blocked = false }: { v: Yu const [choice, setChoice] = useState(null); const [target, setTarget] = useState(''); const mine = sel.offers.length > 0 && sel.picksLeft > 0; - const key = sel.offers.join(','); - // The window belongs to one set of offers: new offers (혼돈 mode's second pick, the 이의있음! redo) start closed. + // One key per set of offers to pick from. Picking (or the turn to pick coming back) starts a new one, so an + // 이의있음! redo that happens to deal the very same offers still counts as new. + const epoch = useRef({ mine, n: 0 }); + if (mine && !epoch.current.mine) epoch.current.n += 1; + epoch.current.mine = mine; + const key = `${epoch.current.n}|${sel.offers.join(',')}`; + // The window belongs to one key; it never shows while the 이의있음! call is up (`blocked`). const [openKey, setOpenKey] = useState(null); - const open = mine && openKey === key; + const open = mine && openKey === key && !blocked; const setOpen = (on: boolean) => setOpenKey(on ? key : null); // New offers open the window by themselves, but only after the board has stopped moving (the last move's hop) - // and the 이의있음! call is gone (`blocked`), so nothing pops up over an animation. + // and the 이의있음! call is gone, so nothing pops up over an animation. const [autoKey, setAutoKey] = useState(mine ? key : null); - const ready = useMotionSettled(mine && autoKey === key && !blocked); + const ready = useMotionSettled(mine && autoKey === key && !blocked && !pending); useEffect(() => { setChoice(sel.forced); setTarget(''); @@ -369,6 +374,9 @@ export function AugSelect({ v, act, pending, players, blocked = false }: { v: Yu if (!choice || (needTarget && !target)) return; act({ type: 'AUG_PICK', aug: choice, ...(needTarget ? { target } : {}) }); haptic(30); + // Whatever comes next (my second pick, an 이의있음! redo, even with the same offers) opens as a new window. + epoch.current.n += 1; + setOpenKey(null); }; return ( <> diff --git a/docs/03-realtime-protocol.md b/docs/03-realtime-protocol.md index e3ce8be..58afc88 100644 --- a/docs/03-realtime-protocol.md +++ b/docs/03-realtime-protocol.md @@ -38,7 +38,7 @@ | `rematch` | — | 게임 끝난 뒤 "한 판 더" 투표(2026-10-11부터 화면은 [한 판 더]로 대기실에 돌아가고 이 메시지는 쓰지 않음) | | `void` | — | 방장: 오류로 멈춘 게임을 무효로 끝내기 | | `sync` | — | 전체 상태 다시 요청 | -| `settled` | `seq` | 내 화면이 게임 상태 `seq`의 움직임을 다 보여 줬음(2026-11-08). 그때부터 내 제한 시간이 흐름(실시간 게임 제외). 한 번도 보내지 않은 화면은 예전처럼 상태가 바뀐 때부터, 보낸 적 있는 화면은 이번 상태를 보고하기 전까지 최대 15초(×1 기준, 게임 속도 배율로 늘고 줆) 기다림 | +| `settled` | `seq` | 내 화면이 게임 상태 `seq`의 움직임을 다 보여 줬음(2026-11-08). 그때부터 내 제한 시간이 흐름(실시간 게임 제외). 한 번도 보내지 않은 화면은 예전처럼 상태가 바뀐 때부터, 보낸 적 있는 화면은 이번 상태를 보고하기 전까지 최대 15초(×1 기준, 게임 속도 배율로 늘고 줆) 기다림. 마감·답할 사람이 그대로인 변화(채팅 등)는 이미 준 시간을 유지하고, 다른 사람이 답하는 공통 단계에서 시간을 재는 대표자의 마감은 실제로 답할 사람들의 화면을 기준으로 함 | | `ping` | `ts` | 지연 측정(10초마다) | ### 3.2 서버 → 클라이언트 diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index 67d9ba3..b71388e 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -3712,7 +3712,8 @@ const PLANS: Record = { let power = false; let wild = false; const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); - const until = Date.now() + 420_000; + // (every roll and move plays out before the next choice shows, so a whole game takes a while) + const until = Date.now() + 900_000; while (Date.now() < until && !(await over())) { if (!shots.has('draft') && (await host.locator('section[aria-label="선수 뽑기"]').count()) && st.picks >= 3) { shots.add('draft'); diff --git a/e2e/motion.e2e.ts b/e2e/motion.e2e.ts index 0725251..afe9a23 100644 --- a/e2e/motion.e2e.ts +++ b/e2e/motion.e2e.ts @@ -157,7 +157,7 @@ try { await p.context().close(); }); - await step('증강 윷놀이: 이의있음! 화면이 사라진 뒤에 다시 고르는 창이 열림', async () => { + await step('증강 윷놀이: 이의있음! 화면이 사라진 뒤에 다시 고르는 창이 열림(같은 후보가 다시 나와도)', async () => { const { p, room, me, bot } = await practice('yut', '호랑이', (o) => ({ ...o, augmented: true })); for (let i = 0; i < 100 && !room.game.state.aug?.select; i++) await Bun.sleep(50); const st = () => room.game.state; @@ -169,6 +169,12 @@ try { sel.offers[theirs] = []; sel.left[theirs] = 0; sel.picks = [{ side: Number(theirs), id: 'objection' }]; + // The redo deals me the very same offers again (the window must still wait for the call to go away). + const send = room.broadcastState.bind(room); + room.broadcastState = (...args: unknown[]) => { + if (st().aug.select?.redo) st().aug.select.offers[mine] = ['shield', 'tiger', 'fog']; + return send(...args); + }; room.broadcastState([]); if (!(await p.locator('.aug-cards').count())) await p.getByRole('button', { name: '증강 후보 보기' }).click(); await p.locator('.aug-card').first().click(); @@ -180,6 +186,7 @@ try { await Bun.sleep(50); } await p.getByRole('dialog', { name: /증강 선택/ }).waitFor({ timeout: 10_000 }); + if (st().aug.select.offers[mine].join() !== 'shield,tiger,fog') throw new Error('the redo did not deal the same offers'); console.log(` yut-aug: 이의있음! on screen ${Date.now() - t0}ms, then the redo selection`); await p.context().close(); }); @@ -206,12 +213,18 @@ try { const waited = Date.now() - t0; if (waited < 10_000) throw new Error(`the choice showed after ${waited}ms; the flip at ×1/8 should take longer than the 10 s choice time`); if (room.game.state.phase.kind !== 'afterCorrect' || room.game.state.current !== me) throw new Error('the server timed my choice out while the screen was still animating'); + // The clock on my screen is the server's (moved) deadline, not the one sent with the state. + await Bun.sleep(500); + const label = (await p.locator('[role="timer"]').first().getAttribute('aria-label')) ?? ''; + const shown = Number(label.match(/(\d+)초/)?.[1] ?? NaN); + const left = (room.effectiveDeadline() - Date.now()) / 1000; + if (!(Math.abs(shown - left) <= 1.5)) throw new Error(`screen timer says ${shown}s, server has ${left.toFixed(1)}s left`); await Bun.sleep(3000); await stop.click(); for (let i = 0; i < 50 && room.game.state.phase.kind === 'afterCorrect'; i++) await Bun.sleep(100); if (room.game.state.idle[me]) throw new Error('my stop counted as a timeout'); if (room.game.state.current === me) throw new Error('stopping did not pass the turn'); - console.log(` davinci-code: choice shown ${waited}ms after the guess, stopped 3 s later without a timeout`); + console.log(` davinci-code: choice shown ${waited}ms after the guess (timer ${shown}s, server ${left.toFixed(1)}s), stopped 3 s later without a timeout`); await p.context().close(); setSpeed(1); });