From ff3c53ab4a7f15c36cf8994f3cfef28431cf3c0e Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 14 Oct 2026 04:09:29 +0900 Subject: [PATCH] =?UTF-8?q?=EC=B1=84=ED=8C=85=20=EC=97=B0=ED=83=80?= =?UTF-8?q?=EA=B0=80=20=EB=AA=87=20=EC=B4=88=EC=94=A9=20=EB=B0=80=EB=A6=AC?= =?UTF-8?q?=EB=8D=98=20=EB=AC=B8=EC=A0=9C:=20=EB=B8=8C=EB=9D=BC=EC=9A=B0?= =?UTF-8?q?=EC=A0=80=EA=B0=80=200.55=EC=B4=88(=EB=A7=88=ED=94=BC=EC=95=84?= =?UTF-8?q?=C2=B7=EB=9D=BC=EC=9D=B4=EC=96=B4=200.75=EC=B4=88)=EC=97=90=20?= =?UTF-8?q?=ED=95=9C=20=EC=A4=84=EC=94=A9=EB=A7=8C=20=EB=82=B4=EB=B3=B4?= =?UTF-8?q?=EB=82=B4=EB=8D=98=20=EB=8C=80=EA=B8=B0=EC=97=B4=EA=B3=BC=20?= =?UTF-8?q?=EA=B2=8C=EC=9E=84=20=EC=B1=84=ED=8C=85=200.7=EC=B4=88=20?= =?UTF-8?q?=EA=B0=84=EA=B2=A9=20=EC=A0=9C=ED=95=9C=EC=9D=84=20=EC=97=86?= =?UTF-8?q?=EC=95=A0=EA=B3=A0,=20=EB=B0=A9=20=EC=B1=84=ED=8C=85=C2=B7?= =?UTF-8?q?=EB=A7=88=ED=94=BC=EC=95=84=C2=B7=EB=9D=BC=EC=9D=B4=EC=96=B4?= =?UTF-8?q?=EA=B0=80=20=EA=B0=99=EC=9D=80=20=EC=86=8D=EB=8F=84=20=EA=B7=9C?= =?UTF-8?q?=EC=B9=99(=ED=95=9C=20=EB=B2=88=EC=97=90=206=EC=A4=84,=20?= =?UTF-8?q?=EA=B7=B8=20=EB=92=A4=200.3=EC=B4=88=EC=97=90=20=ED=95=9C=20?= =?UTF-8?q?=EC=A4=84)=EC=9D=84=20=EC=93=B0=EA=B2=8C.=20=EC=82=AC=EB=9E=8C?= =?UTF-8?q?=EC=9D=B4=20=EC=B9=98=EB=8A=94=20=EC=86=8D=EB=8F=84=EB=A1=9C?= =?UTF-8?q?=EB=8A=94=20=EA=B8=B0=EB=8B=A4=EB=A6=AC=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EA=B3=A0=20=EB=B0=94=EB=A1=9C=20=EC=98=AC=EB=9D=BC=EA=B0=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/rooms/mafia.room.test.ts | 3 +++ apps/server/src/rooms/room.test.ts | 18 ++++++++++--- apps/server/src/rooms/room.ts | 12 ++++----- apps/web/src/components/ChatPanel.tsx | 2 +- apps/web/src/games/liar/index.tsx | 2 +- apps/web/src/games/mafia/index.tsx | 4 +-- apps/web/src/lib/chat-input.ts | 32 +++++++++++++----------- e2e/chat.e2e.ts | 9 +++++-- packages/games/package.json | 1 + packages/games/src/chat-pace.test.ts | 26 +++++++++++++++++++ packages/games/src/chat-pace.ts | 19 ++++++++++++++ packages/games/src/liar/index.ts | 6 ++--- packages/games/src/liar/liar.test.ts | 8 +++--- packages/games/src/liar/types.ts | 1 + packages/games/src/mafia/index.ts | 6 ++--- packages/games/src/mafia/mafia.test.ts | 6 +++-- packages/games/src/mafia/types.ts | 1 + 17 files changed, 115 insertions(+), 41 deletions(-) create mode 100644 packages/games/src/chat-pace.test.ts create mode 100644 packages/games/src/chat-pace.ts diff --git a/apps/server/src/rooms/mafia.room.test.ts b/apps/server/src/rooms/mafia.room.test.ts index d0a7406..1b51806 100644 --- a/apps/server/src/rooms/mafia.room.test.ts +++ b/apps/server/src/rooms/mafia.room.test.ts @@ -57,6 +57,9 @@ describe('마피아 room flow', () => { expect(all).not.toContain(`"role":"mafia"`); } // Rate limit (validate gets the server clock), and the system-only phase timer cannot be sent by clients. + // A quick run of lines all goes through; only a flood is refused. + for (let i = 0; i < 5; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` }); + expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(5); room.act(mafia, 2, { type: 'chat', channel: 'mafia', text: '또' }); expect(conns[mafia]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 2, reason: '조금 천천히 보내 주세요.' }); room.act(town[0]!, 3, { type: 'phaseTimeout' }); diff --git a/apps/server/src/rooms/room.test.ts b/apps/server/src/rooms/room.test.ts index b83d081..91a941d 100644 --- a/apps/server/src/rooms/room.test.ts +++ b/apps/server/src/rooms/room.test.ts @@ -234,11 +234,21 @@ describe('Room chat (2026-10-13)', () => { const b = conn('B'); room.join(a, 'player'); room.join(b, 'player'); - for (let i = 0; i < 4; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull(); + for (let i = 0; i < 6; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull(); expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.'); - clock.advance(500); - expect(room.chat('A', '0.5초 뒤')).toBeNull(); - expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(['줄 0', '줄 1', '줄 2', '줄 3', '0.5초 뒤']); + clock.advance(300); + expect(room.chat('A', '0.3초 뒤')).toBeNull(); + expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.'); + expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(['줄 0', '줄 1', '줄 2', '줄 3', '줄 4', '줄 5', '0.3초 뒤']); + }); + + test('typing at a person\'s pace (a line every 0.4 s) never waits', () => { + const { room, clock, conn } = harness(); + room.join(conn('A'), 'player'); + for (let i = 0; i < 30; i++) { + expect(room.chat('A', `줄 ${i}`)).toBeNull(); + clock.advance(400); + } }); test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => { diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index 32b8eba..81a10a8 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -14,7 +14,7 @@ import { BotBrain, type BotActivity } from '../ai/brain'; import type { Llm } from '../ai/llm'; import type { LogEntry, RoomStore } from './store'; import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings'; -import { TokenBucket } from '../ws/rate-limit'; +import { chatNext, chatWait } from '@bg/games/chat-pace'; export interface Conn { userId: string; @@ -152,7 +152,8 @@ export class Room { private flushTimer: ReturnType | null = null; private recentCs = new Map(); private lastChatAt = new Map(); - private chatBuckets = new Map(); + /** Room chat pace per person (`chat-pace.ts`). */ + private chatPace = new Map(); /** When each person last said they were typing (to drop repeats within a second). */ private typingAt = new Map(); private consecutiveErrors = 0; @@ -810,10 +811,9 @@ export class Room { if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.'; if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.'; const now = this.now(); - // A few lines in a row go through (people often send 2~3 quick lines); a flood still stops. - let bucket = this.chatBuckets.get(userId); - if (!bucket) this.chatBuckets.set(userId, (bucket = new TokenBucket(2, 4, now))); - if (!bucket.take(now)) return '조금 천천히 보내 주세요.'; + // Quick lines in a row all go through at once; only a flood stops. + if (chatWait(this.chatPace.get(userId), now) > 0) return '조금 천천히 보내 주세요.'; + this.chatPace.set(userId, chatNext(this.chatPace.get(userId), now)); this.typingAt.delete(userId); const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim(); if (!clean) return null; diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index ea80eab..67bdc6d 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -16,7 +16,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ const [text, setText] = useState(''); const { ref: listRef, pin } = useStickToBottom(); const inputRef = useRef(null); - const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t }), 550); + const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t })); const typing = useTypingSignal('room', room.chatEnabled); const lastId = chat.at(-1)?.id ?? 0; useEffect(() => { diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 30b2824..d00cb4d 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -426,7 +426,7 @@ const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : n function ChatBox({ v, players, me, act }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void }) { const [text, setText] = useState(''); const { ref: listRef, pin } = useStickToBottom(); - const send = useChatOutbox((t: string) => act({ type: 'chat', text: t }), 750); + const send = useChatOutbox((t: string) => act({ type: 'chat', text: t })); const lines: Line[] = [ ...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })), ...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })), diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index a3a5711..43b8217 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -458,8 +458,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record>({}); const { ref: listRef, pin } = useStickToBottom(); - // Lines typed quickly all go out, one per CHAT_GAP_MS (the game refuses faster ones). - const send = useChatOutbox<{ channel: Channel; text: string }>((m) => act({ type: 'chat', ...m }), 750); + // Lines typed quickly all go out at once (only a flood waits; the game refuses faster ones). + const send = useChatOutbox<{ channel: Channel; text: string }>((m) => act({ type: 'chat', ...m })); const cur: Channel = tabs.includes(tab) ? tab : 'day'; // Day → 전체; night → the first private channel I may write in (only on my own screen). const phaseKey = `${v.day}-${v.phase.kind}`; diff --git a/apps/web/src/lib/chat-input.ts b/apps/web/src/lib/chat-input.ts index 930619a..1fd01f7 100644 --- a/apps/web/src/lib/chat-input.ts +++ b/apps/web/src/lib/chat-input.ts @@ -1,35 +1,39 @@ /** * Chat input helpers shared by the room chat and the games with their own chat (마피아, 라이어 게임). * - * - `useChatOutbox`: every line typed is sent, in order. The server allows a short burst and then about one line - * per `gapMs`; lines typed faster than that wait in a small queue instead of being refused ("조금 천천히"). + * - `useChatOutbox`: every line typed is sent right away, in order. Only past the server's chat pace (`chat-pace.ts`, + * a burst of lines and then several a second) do lines wait in a small queue instead of being refused ("조금 천천히"). * - `useTypingSignal`: tells the others "입력 중" while there is text in the box (renewed every 2 s, cleared when the * box is emptied or the line is sent, and when the box goes away). */ import { useCallback, useEffect, useRef } from 'react'; +import { CHAT_BURST, CHAT_INTERVAL_MS, chatNext, chatWait } from '@bg/games/chat-pace'; import { socket } from '../net/socket'; const MAX_QUEUE = 10; +// A little under the server's pace, so lines bunched up on the way (network jitter) are not refused there. +const BURST = CHAT_BURST - 1; +const INTERVAL = CHAT_INTERVAL_MS + 40; -export function useChatOutbox(send: (item: T) => void, gapMs: number) { +export function useChatOutbox(send: (item: T) => void) { const queue = useRef([]); - const last = useRef(-Infinity); + const next = useRef(undefined); const timer = useRef | null>(null); const sendRef = useRef(send); sendRef.current = send; const pump = useCallback(() => { timer.current = null; - const wait = last.current + gapMs - Date.now(); - if (wait > 0) { - timer.current = setTimeout(pump, wait); - return; + while (queue.current.length) { + const now = Date.now(); + const wait = chatWait(next.current, now, BURST, INTERVAL); + if (wait > 0) { + timer.current = setTimeout(pump, wait); + return; + } + next.current = chatNext(next.current, now, INTERVAL); + sendRef.current(queue.current.shift()!); } - const next = queue.current.shift(); - if (next === undefined) return; - last.current = Date.now(); - sendRef.current(next); - if (queue.current.length) timer.current = setTimeout(pump, gapMs); - }, [gapMs]); + }, []); useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); return useCallback( (item: T) => { diff --git a/e2e/chat.e2e.ts b/e2e/chat.e2e.ts index b832f2a..9038e65 100644 --- a/e2e/chat.e2e.ts +++ b/e2e/chat.e2e.ts @@ -36,7 +36,7 @@ const step = async (name: string, fn: () => Promise) => { } }; -/** Send one chat line through the input (the server allows one line per 0.5 s per person). */ +/** Send one chat line through the input. */ async function say(p: Page, text: string) { const input = p.locator('.chat-panel input[aria-label="메시지"]').first(); await input.fill(text); @@ -163,14 +163,19 @@ try { await b.getByRole('button', { name: '채팅', exact: true }).waitFor(); }); - await step('빠르게 여러 번 Enter: 전부 순서대로 들어감', async () => { + await step('빠르게 여러 번 Enter: 전부 순서대로, 바로 들어감', async () => { await a.waitForTimeout(1500); const input = a.locator('.chat-panel input[aria-label="메시지"]').first(); + const t0 = performance.now(); for (let i = 1; i <= 7; i++) { await input.fill(`연타 ${i}`); await input.press('Enter'); } for (let i = 1; i <= 7; i++) await a.locator('.chat-line', { hasText: `연타 ${i}` }).waitFor({ timeout: 10_000 }); + // Lines used to go out one per 0.55 s (7 lines ≈ 3.3 s); now a quick run goes at once. + const ms = performance.now() - t0; + if (ms > 1500) throw new Error(`7 quick lines took ${Math.round(ms)}ms to show`); + console.log(` 7 quick lines shown in ${Math.round(ms)}ms`); const got = await a.locator('.chat-line .chat-text', { hasText: /^연타 \d$/ }).allInnerTexts(); if (got.join(',') !== [1, 2, 3, 4, 5, 6, 7].map((i) => `연타 ${i}`).join(',')) throw new Error(`order/lost: ${got.join(',')}`); // The other side got them all too (phone sheet closed: the badge counts 7). diff --git a/packages/games/package.json b/packages/games/package.json index 62f16f9..e965714 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -12,6 +12,7 @@ "./liar/topics": "./src/liar/topics.ts", "./magical-athlete/racers": "./src/magical-athlete/racers.ts", "./seotda/money": "./src/seotda/money.ts", + "./chat-pace": "./src/chat-pace.ts", "./*": "./src/*/index.ts" }, "dependencies": { diff --git a/packages/games/src/chat-pace.test.ts b/packages/games/src/chat-pace.test.ts new file mode 100644 index 0000000..daffee8 --- /dev/null +++ b/packages/games/src/chat-pace.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from 'bun:test'; +import { CHAT_BURST, CHAT_INTERVAL_MS, chatNext, chatWait } from './chat-pace'; + +describe('chat pace', () => { + test(`${CHAT_BURST} lines at once go through, the next waits one interval`, () => { + let next: number | undefined; + for (let i = 0; i < CHAT_BURST; i++) { + expect(chatWait(next, 1000)).toBe(0); + next = chatNext(next, 1000); + } + expect(chatWait(next, 1000)).toBe(CHAT_INTERVAL_MS); + expect(chatWait(next, 1000 + CHAT_INTERVAL_MS)).toBe(0); + }); + + test('a person typing a line every 0.4 s never waits', () => { + let next: number | undefined; + for (let t = 0; t < 60_000; t += 400) { + expect(chatWait(next, t)).toBe(0); + next = chatNext(next, t); + } + }); + + test('an old "last sent at" time from a saved game does not block', () => { + expect(chatWait(5_000, 5_000)).toBe(0); + }); +}); diff --git a/packages/games/src/chat-pace.ts b/packages/games/src/chat-pace.ts new file mode 100644 index 0000000..d9057cf --- /dev/null +++ b/packages/games/src/chat-pace.ts @@ -0,0 +1,19 @@ +/** + * Chat pace, shared by the server checks (room chat, 마피아, 라이어 게임) and the browser's send queue. + * + * One number per person: the time from which the next line is "free" (GCRA). Up to `CHAT_BURST` lines go through + * at once, then about one line per `CHAT_INTERVAL_MS` — far faster than anyone types, while a flood still stops. + * A plain "last sent at" time from older saved games reads as a time in the past, so nothing needs migrating. + */ +export const CHAT_BURST = 6; +export const CHAT_INTERVAL_MS = 300; + +/** How long until one more line is allowed (0 = now). */ +export function chatWait(next: number | undefined, now: number, burst = CHAT_BURST, interval = CHAT_INTERVAL_MS): number { + return Math.max(0, (next ?? -Infinity) - (burst - 1) * interval - now); +} + +/** The new "free from" time after sending a line at `now`. */ +export function chatNext(next: number | undefined, now: number, interval = CHAT_INTERVAL_MS): number { + return Math.max(next ?? -Infinity, now) + interval; +} diff --git a/packages/games/src/liar/index.ts b/packages/games/src/liar/index.ts index 53912be..518bed4 100644 --- a/packages/games/src/liar/index.ts +++ b/packages/games/src/liar/index.ts @@ -12,6 +12,7 @@ * and the liar is told "시민" like everybody else). Who the liar is never appears in any view before the reveal. */ import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine'; +import { chatNext, chatWait } from '../chat-pace'; import { judge, normalize } from '../catchmind/text'; import { chatProblem, cleanChat } from '../mafia'; import { @@ -40,7 +41,6 @@ export const REVEAL_MS = 10_000; export const CHAT_MAX = 200; /** One description is one sentence. */ export const DESCRIBE_MAX = 80; -export const CHAT_GAP_MS = 700; export const GUESS_MAX = 20; /** Points (docs §6): a citizen win gives every citizen 1, a liar win gives the liar 2. */ export const CITIZEN_POINTS = 1; @@ -339,7 +339,7 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num const mine = wordOf(s, actor); if (mine && saysWord(text, s.topic, mine)) return fail('제시어를 직접 말하면 안 돼요.'); // Pace limit for free talk only: a description is one per turn anyway. - if (ph.kind !== 'describe' && ctx && ctx.now - (s.lastChatAt[actor] ?? -Infinity) < CHAT_GAP_MS) return fail('조금 천천히 보내 주세요.'); + if (ph.kind !== 'describe' && ctx && chatWait(s.lastChatAt[actor], ctx.now) > 0) return fail('조금 천천히 보내 주세요.'); return ok; } case 'ready': @@ -514,7 +514,7 @@ export const liar: Def = { s.descriptions.push({ n: s.descriptions.length + 1, round: ph.round, from: actor, text, at: now }); nextTurn(s, now, ph.round, ph.turn + 1); } else { - s.lastChatAt[actor] = now; + s.lastChatAt[actor] = chatNext(s.lastChatAt[actor], now); s.chat.push({ n: (s.chat.at(-1)?.n ?? 0) + 1, from: actor, text, at: now }); if (s.chat.length > CHAT_KEEP) s.chat.splice(0, s.chat.length - CHAT_KEEP); } diff --git a/packages/games/src/liar/liar.test.ts b/packages/games/src/liar/liar.test.ts index cf87876..080487c 100644 --- a/packages/games/src/liar/liar.test.ts +++ b/packages/games/src/liar/liar.test.ts @@ -257,11 +257,13 @@ describe('차례대로 설명 (§5.2)', () => { let s = rig(3); expect(reject(s, 'P0', { type: 'chat', text: '안녕' })).toContain('확인하는 중'); s = until(s, 'discussion'); - s = act(s, 'P1', { type: 'chat', text: '누구지' }); - expect(reject(s, 'P1', { type: 'chat', text: '또' }, at(s) - 1000 + 100)).toBe('조금 천천히 보내 주세요.'); + const t = at(s); + // A quick run of lines goes through at once; only a flood is refused. + for (let i = 0; i < 6; i++) s = act(s, 'P1', { type: 'chat', text: `누구지 ${i}` }, t); + expect(reject(s, 'P1', { type: 'chat', text: '또' }, t + 100)).toBe('조금 천천히 보내 주세요.'); s = until(s, 'vote'); s = act(s, 'P2', { type: 'chat', text: '투표해요' }); - expect(s.chat.map((m) => m.text)).toEqual(['누구지', '투표해요']); + expect(s.chat.map((m) => m.text)).toEqual(['누구지 0', '누구지 1', '누구지 2', '누구지 3', '누구지 4', '누구지 5', '투표해요']); }); }); diff --git a/packages/games/src/liar/types.ts b/packages/games/src/liar/types.ts index c8df602..ea47f57 100644 --- a/packages/games/src/liar/types.ts +++ b/packages/games/src/liar/types.ts @@ -128,6 +128,7 @@ export interface LiarState { phase: Phase; descriptions: Description[]; chat: ChatMessage[]; + /** Chat pace per person: the time the next line is free from (`chat-pace.ts`; older saves hold the last send time). */ lastChatAt: Record; events: PublicEvent[]; accused: PlayerId | null; diff --git a/packages/games/src/mafia/index.ts b/packages/games/src/mafia/index.ts index 9b2f504..b6537f1 100644 --- a/packages/games/src/mafia/index.ts +++ b/packages/games/src/mafia/index.ts @@ -8,6 +8,7 @@ * it by channel permission (§5.6, §8.3). */ import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine'; +import { chatNext, chatWait } from '../chat-pace'; import { CHANNELS, EXTRA_ROLES, @@ -42,7 +43,6 @@ export const ADJUST_MS = 15_000; /** `-15초` never leaves less than this (§5.2). */ export const ADJUST_FLOOR_MS = 5_000; export const CHAT_MAX = 200; -export const CHAT_GAP_MS = 700; /** Voting days in a row without any action → 자리 비움 탈락 (§8.5). */ export const AWAY_DAYS = 2; const CHAT_KEEP = 400; @@ -524,7 +524,7 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n if (block) return fail(block); const why = chatProblem(cleanChat(a.text), s.options.kidSafeChat); if (why) return fail(why); - if (ctx && ctx.now - (s.lastChatAt[actor] ?? -Infinity) < CHAT_GAP_MS) return fail('조금 천천히 보내 주세요.'); + if (ctx && chatWait(s.lastChatAt[actor], ctx.now) > 0) return fail('조금 천천히 보내 주세요.'); return ok; } default: @@ -749,7 +749,7 @@ export const mafia: Def = { s.chatCount[a.channel] += 1; s.chat.push({ id: s.chatCount[a.channel], channel: a.channel, from: actor, text: cleanChat(a.text), at: now, day: s.day }); if (s.chat.length > CHAT_KEEP) s.chat.splice(0, s.chat.length - CHAT_KEEP); - s.lastChatAt[actor] = now; + s.lastChatAt[actor] = chatNext(s.lastChatAt[actor], now); break; } case 'adjustTime': diff --git a/packages/games/src/mafia/mafia.test.ts b/packages/games/src/mafia/mafia.test.ts index 49655fb..ebbe78f 100644 --- a/packages/games/src/mafia/mafia.test.ts +++ b/packages/games/src/mafia/mafia.test.ts @@ -423,8 +423,10 @@ describe('채팅 권한 (§5.6)', () => { let s = until(rig(roles, o), 'greeting'); const g0 = (s.phase as Extract).startedAt; s = say(s, 'P7', 'day', '안녕하세요'); - expect(reject(s, 'P7', { type: 'chat', channel: 'day', text: '또 안녕' }, g0 + 200)).toBe('조금 천천히 보내 주세요.'); - expect(mafia.validate(s, 'P7', { type: 'chat', channel: 'day', text: '또 안녕' }, { now: g0 + 1 + 700 }).ok).toBe(true); + // A quick run of lines goes through at once; only a flood is refused. + for (let i = 0; i < 5; i++) s = say(s, 'P7', 'day', `연달아 ${i}`, g0 + 1); + expect(reject(s, 'P7', { type: 'chat', channel: 'day', text: '또 안녕' }, g0 + 1)).toBe('조금 천천히 보내 주세요.'); + expect(mafia.validate(s, 'P7', { type: 'chat', channel: 'day', text: '또 안녕' }, { now: g0 + 1 + 300 }).ok).toBe(true); s = tick(s); expect(reject(s, 'P7', { type: 'chat', channel: 'day', text: '밤인데' })).toBe('밤에는 낮 채팅을 쓸 수 없어요.'); expect(reject(s, 'P7', { type: 'chat', channel: 'mafia', text: '...' })).toBe('마피아만 쓸 수 있어요.'); diff --git a/packages/games/src/mafia/types.ts b/packages/games/src/mafia/types.ts index a4dbfa5..3237e01 100644 --- a/packages/games/src/mafia/types.ts +++ b/packages/games/src/mafia/types.ts @@ -196,6 +196,7 @@ export interface MafiaState { /** Every message of every channel; the view filters by channel permission. */ chat: ChatMessage[]; chatCount: Record; + /** Chat pace per person: the time the next line is free from (`chat-pace.ts`; older saves hold the last send time). */ lastChatAt: Record; events: PublicEvent[]; /** Voters (vote phase) for the current accused — for the MVP count. */