채팅을 따로 분리해 속도 제한 없이: 방 채팅·마피아·라이어·그림 맞히기(그리기 전) 채팅의 줄 간격 제한(chat-pace)과 브라우저 대기열을 없애 치는 대로 바로 보냄. 서버 연결당 공용 한도(초당 20개)를 채팅·입력 중 신호가 같이 써서 빠르게 치면 15번째 줄부터 조용히 사라지던 문제도: 채팅은 별도 한도(초당 50, 최대 200, 매크로 도배 방지용)로 분리. 게임 채팅은 보내는 동안 게임 버튼을 잠그지 않음(pending 미설정)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 08:58:17 +09:00
parent 13a89a645e
commit 4d1deb8346
26 changed files with 122 additions and 162 deletions

View File

@@ -57,11 +57,10 @@ 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: '조금 천천히 보내 주세요.' });
// No pace limit: a long run of lines in the same instant all goes through.
for (let i = 0; i < 20; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` });
expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(20);
expect(conns[mafia]!.msgs.some((m) => m.t === 'reject')).toBe(false);
room.act(town[0]!, 3, { type: 'phaseTimeout' });
expect(conns[town[0]!]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 3, reason: '잘못된 요청이에요.' });
expect(state().phase.kind).toBe('night');

View File

@@ -228,18 +228,15 @@ describe('윷놀이 room rules', () => {
});
describe('Room chat (2026-10-13)', () => {
test('a quick burst of lines all goes through; a flood is still stopped', () => {
const { room, clock, conn } = harness();
test('no pace limit: any number of lines in the same instant all go through, in order', () => {
const { room, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
for (let i = 0; i < 6; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull();
expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.');
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초 뒤']);
const lines = Array.from({ length: 30 }, (_, i) => `줄 ${i}`);
for (const t of lines) expect(room.chat('A', t)).toBeNull();
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines);
});
test('typing at a person\'s pace (a line every 0.4 s) never waits', () => {

View File

@@ -14,7 +14,6 @@ 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 { chatNext, chatWait } from '@bg/games/chat-pace';
export interface Conn {
userId: string;
@@ -152,8 +151,6 @@ export class Room {
private flushTimer: ReturnType<typeof setTimeout> | null = null;
private recentCs = new Map<string, number[]>();
private lastChatAt = new Map<string, number>();
/** Room chat pace per person (`chat-pace.ts`). */
private chatPace = new Map<string, number>();
/** When each person last said they were typing (to drop repeats within a second). */
private typingAt = new Map<string, number>();
private consecutiveErrors = 0;
@@ -813,10 +810,8 @@ export class Room {
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
// No pace limit: every line goes out as soon as it is typed (the socket's own flood guard still applies).
const now = this.now();
// 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;

View File

@@ -216,6 +216,24 @@ describe('M1 integration scenarios', () => {
expect(h.res.status).toBe(200);
});
test('10b. chat has its own budget: a fast run of lines (with 입력 중 signals) all arrives and leaves game moves untouched', async () => {
const s = start();
const a = await client(s, '빠른손');
const code = await createRoom(s, a);
await join(a, code);
for (let i = 0; i < 60; i++) {
a.send({ t: 'typing', on: true, ch: 'room' });
a.send({ t: 'chat', text: `줄 ${i}` });
a.send({ t: 'typing', on: false, ch: 'room' });
}
await a.next('chat', (m) => m.text === '줄 59');
expect(a.messages.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(Array.from({ length: 60 }, (_, i) => `줄 ${i}`));
// The general budget is still full: a burst of 30 pings all answered.
for (let i = 0; i < 30; i++) a.send({ t: 'ping', ts: i });
await sleep(200);
expect(a.messages.filter((m) => m.t === 'pong').length).toBe(30);
});
test('11. malformed / oversized / schema-invalid messages', async () => {
const s = start();
const a = await client(s, '이상한값');

View File

@@ -9,6 +9,8 @@ export interface WsData {
userId: string;
connId: number;
bucket: TokenBucket;
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
chatBucket: TokenBucket;
strikes: number;
room: string | null;
conn: Conn | null;
@@ -26,6 +28,21 @@ export interface GatewayDeps {
}
export const MAX_CONNS_PER_USER = 5;
/**
* Chat budget per socket: far above any typing speed (a line costs up to three messages: 입력 중 on, the line, off),
* only a script flooding the room is cut off.
*/
const CHAT_RATE_PER_SEC = 50;
const CHAT_BURST = 200;
/** Room chat, game chat (마피아·라이어 게임·그림 맞히기 `act` with `type: 'chat'`) and the "입력 중" signal. */
function isChatMessage(m: unknown): boolean {
if (typeof m !== 'object' || m === null) return false;
const { t, a } = m as { t?: unknown; a?: unknown };
if (t === 'chat' || t === 'typing') return true;
return t === 'act' && typeof a === 'object' && a !== null && (a as { type?: unknown }).type === 'chat';
}
const MAX_BUFFERED = 1024 * 1024;
export class Gateway {
@@ -47,7 +64,7 @@ export class Gateway {
upgrade(req: Request, server: Server<WsData>, userId: string): Response | undefined {
if (this.closing) return new Response('restarting', { status: 503 });
if ((this.byUser.get(userId)?.size ?? 0) >= MAX_CONNS_PER_USER) return new Response('too many connections', { status: 429 });
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), strikes: 0, room: null, conn: null };
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST), strikes: 0, room: null, conn: null };
if (server.upgrade(req, { data })) return undefined;
return new Response('upgrade failed', { status: 400 });
}
@@ -96,23 +113,28 @@ export class Gateway {
ws.close(1009, 'message too big');
return;
}
if (!ws.data.bucket.take()) {
let json: unknown;
let badJson = false;
try {
json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
} catch {
badJson = true;
}
const bucket = !badJson && isChatMessage(json) ? ws.data.chatBucket : ws.data.bucket;
if (!bucket.take()) {
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
return;
}
let parsed: ClientMessage;
try {
const json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
const r = ClientMessage.safeParse(json);
if (!r.success) {
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
return;
}
parsed = r.data;
} catch {
if (badJson) {
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
return;
}
const r = ClientMessage.safeParse(json);
if (!r.success) {
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
return;
}
const parsed: ClientMessage = r.data;
try {
this.dispatch(ws, parsed);
} catch (err) {

View File

@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from 'react';
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
import { create } from 'zustand';
import { socket, useRoom } from '../net/socket';
import { useChatOutbox, useTypingSignal } from '../lib/chat-input';
import { useTypingSignal } from '../lib/chat-input';
import { useStickToBottom } from '../lib/useStickToBottom';
import { BotActivity } from './BotActivity';
import { ChatMessage, sameRun } from './ChatMessage';
@@ -16,7 +16,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
const [text, setText] = useState('');
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
const inputRef = useRef<HTMLInputElement>(null);
const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t }));
const send = (t: string) => socket.send({ t: 'chat', text: t });
const typing = useTypingSignal('room', room.chatEnabled);
const lastId = chat.at(-1)?.id ?? 0;
useEffect(() => {

View File

@@ -15,7 +15,7 @@ import { haptic, sfx, sounds, tone } from '../../lib/feedback';
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
import { useStickToBottom } from '../../lib/useStickToBottom';
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
import { useTypingSignal } from '../../lib/chat-input';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -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<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
const [text, setText] = useState('');
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
const send = useChatOutbox((t: string) => act({ type: 'chat', text: t }));
const send = (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 })),

View File

@@ -15,7 +15,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { useBanner, type BannerTone } from '../card-fx';
import { ChatMessage, sameRun } from '../../components/ChatMessage';
import { useStickToBottom } from '../../lib/useStickToBottom';
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
import { useTypingSignal } from '../../lib/chat-input';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
@@ -458,8 +458,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
const [text, setText] = useState('');
const [seen, setSeen] = useState<Record<string, number>>({});
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
// 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 }));
// Every line goes out the moment it is typed (no pace limit).
const send = (m: { channel: Channel; text: string }) => 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}`;

View File

@@ -1,50 +1,13 @@
/**
* Chat input helpers shared by the room chat and the games with their own chat (마피아, 라이어 게임).
* Chat input helper shared by the room chat and the games with their own chat (마피아, 라이어 게임).
*
* - `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 ("조금 천천히").
* Chat lines are sent the moment Enter is pressed — no queue and no pace limit.
* - `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<T = string>(send: (item: T) => void) {
const queue = useRef<T[]>([]);
const next = useRef<number | undefined>(undefined);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const sendRef = useRef(send);
sendRef.current = send;
const pump = useCallback(() => {
timer.current = null;
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()!);
}
}, []);
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
return useCallback(
(item: T) => {
if (queue.current.length >= MAX_QUEUE) return;
queue.current.push(item);
if (!timer.current) pump();
},
[pump],
);
}
const RENEW_MS = 2000;
export function useTypingSignal(ch: 'room' | 'game', enabled = true) {

View File

@@ -238,13 +238,17 @@ class GameSocket {
useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null });
}
/** Sends a game action; returns false when not connected. */
/**
* Sends a game action; returns false when not connected. A game's chat line (`type: 'chat'`) is sent on its own:
* it does not mark the board as waiting, so typing never locks the game's buttons and lines never wait on each other.
*/
act(a: unknown): boolean {
const cs = ++this.cs;
if (!this.send({ t: 'act', cs, a })) {
toast('연결이 끊겨 있어요. 다시 연결되면 해 주세요.', 'error');
return false;
}
if ((a as { type?: unknown } | null)?.type === 'chat') return true;
useRoom.setState({ pending: cs, slow: false });
if (this.pendingTimer) clearTimeout(this.pendingTimer);
this.pendingTimer = setTimeout(() => {

View File

@@ -91,7 +91,7 @@
| 서버 idle timeout | 40초 (Bun `idleTimeout`), 서버가 25초마다 ping 프레임 |
| 클라이언트 ping | 10초마다, 5초 안에 pong이 없으면 연결을 끊고 재연결 |
| 메시지 최대 크기 | 16KB (그림 맞히기 붓질 메시지만 32KB) |
| 속도 제한 | 연결당 토큰 버킷 초당 20개, 최대 40개. 채팅은 0.5초에 1개. 넘으면 버리고 계속 넘으면 연결 종료 |
| 속도 제한 | 연결당 토큰 버킷 초당 20개, 최대 40개. 채팅(방 채팅·게임 채팅 `act` type `chat`·`typing`)은 따로 초당 50개, 최대 200개(사람은 닿지 않는 매크로 방지용, 채팅 줄 자체의 속도 제한은 없음). 넘으면 버리고 계속 넘으면 연결 종료 |
| 압축 | permessage-deflate 사용(1KB 이상 메시지만 효과) |
| 서버 송신 버퍼 | 연결당 1MB 넘게 밀리면(느린 클라이언트) 연결을 끊음 → 재연결 시 전체 상태로 회복 |

View File

@@ -46,7 +46,7 @@
- 설명 중에는 설명할 차례인 사람만 쓸 수 있다(다른 사람 채팅은 닫힘). 확인 시간·정답 맞히기 중에도 채팅은 닫힌다(라이어에게 힌트를 주지 못하게).
### 5.3 자유 토론
- 모두 [토론 채팅]에 자유롭게 쓴다(200자, 한 번에 6줄까지 바로, 그 뒤 0.3초에 한 줄 — `chat-pace.ts`). 모두 [토론 끝내기]를 누르면 바로 투표(마피아와 같은 "모두 동의" 방식, 방장 혼자서는 못 끝냄).
- 모두 [토론 채팅]에 자유롭게 쓴다(200자, 속도 제한 없음 — 치는 대로 바로 올라감). 모두 [토론 끝내기]를 누르면 바로 투표(마피아와 같은 "모두 동의" 방식, 방장 혼자서는 못 끝냄).
### 5.4 투표
- 나를 뺀 한 명을 고른다. 시간 안에는 바꿀 수 있고, 모두 투표하면 바로 집계한다. 투표하지 않으면 그 사람 표는 없다.
@@ -93,7 +93,7 @@ interface LiarState {
### 8.2 액션
| type | payload | 누가 / 언제 | 검증 조건 |
|---|---|---|---|
| `chat` | `text` | 설명 차례인 사람(설명) / 모두(토론·투표) | 채팅 열린 단계, 80자(설명)·200자, 고운 말, 자기 단어 금지, 한 번에 6줄, 그 뒤 0.3초에 한 줄 |
| `chat` | `text` | 설명 차례인 사람(설명) / 모두(토론·투표) | 채팅 열린 단계, 80자(설명)·200자, 고운 말, 자기 단어 금지, 속도 제한 없음 |
| `ready` | — | 확인 시간·토론 | 아직 안 누름 |
| `vote` | `target` | 투표 | 나 말고, 후보(재투표는 동점자) 중 |
| `guess` | `text` | 정답 맞히기의 라이어 | 1~20자, `choice`면 주제 단어 |

View File

@@ -116,7 +116,7 @@
| `lovers` | 살아 있는 연인 | 연인 | 밤 |
| `system` | 서버 | 전원 | 항상 |
- 메시지 제한: 200자, 한 번에 6줄까지 바로, 그 뒤 0.3초에 1개(서버 레이트 리밋, 방 채팅과 같은 `chat-pace.ts`; 브라우저는 그보다 조금 넘치는 줄만 잠깐 대기열에 둠), `kidSafeChat` 필터. 위반 시 메시지 거부 사유 표시.
- 메시지 제한: 200자, 속도 제한 없음(치는 대로 바로 올라감. 채팅은 게임 행동과 따로 가서 보내는 동안 버튼도 잠기지 않음, 접속별 채팅 예산은 매크로 도배만 막는 초당 50개), `kidSafeChat` 필터. 위반 시 메시지 거부 사유 표시.
- 죽은 사람의 메시지가 살아 있는 사람에게 보이는 경로는 절대 없어야 한다(영매 제외).
- 외부 음성(디스코드)으로 정보를 흘리는 것은 막을 수 없으므로 규칙 보기에 "죽은 사람은 말하지 않기" 에티켓을 안내한다.

View File

@@ -163,23 +163,25 @@ 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 N = 20;
const t0 = performance.now();
for (let i = 1; i <= 7; i++) {
for (let i = 1; i <= N; 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.
await a.locator('.chat-line .chat-text', { hasText: new RegExp(`^연타 ${N}$`) }).waitFor({ timeout: 10_000 });
// No pace limit any more: 20 lines in a row (well past the old 6-line burst) all show right away.
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).
await b.getByRole('button', { name: '채팅, 새 메시지 7개' }).waitFor({ timeout: 5000 });
if (ms > 2000) throw new Error(`${N} quick lines took ${Math.round(ms)}ms to show`);
console.log(` ${N} quick lines shown in ${Math.round(ms)}ms`);
const got = await a.locator('.chat-line .chat-text', { hasText: /^연타 \d+$/ }).allInnerTexts();
const want = Array.from({ length: N }, (_, i) => `연타 ${i + 1}`);
if (got.join(',') !== want.join(',')) throw new Error(`order/lost: ${got.join(',')}`);
// The other side got them all too (phone sheet closed: the badge counts them).
await b.getByRole('button', { name: `채팅, 새 메시지 ${N}개` }).waitFor({ timeout: 5000 });
});
await step('사람도 "입력 중" 표시: 치는 동안 보이고, 보내면 사라짐', async () => {

View File

@@ -2805,6 +2805,21 @@ const PLANS: Record<string, Plan> = {
await mafiaBanner(host, '인사 시간');
await mafiaSay(phone, '전체', '안녕하세요 반가워요');
for (const p of pages) await p.locator('.mf-msgs .mf-msg', { hasText: '안녕하세요 반가워요' }).waitFor({ timeout: 15_000 });
// No chat pace limit: 15 lines typed back to back all show up right away, in order, on every screen.
{
const box = phone.getByLabel('전체 채팅 메시지');
const t0 = performance.now();
for (let i = 1; i <= 15; i++) {
await box.fill(`연타 ${i}`);
await box.press('Enter');
}
for (const p of pages) await p.locator('.mf-msgs .mf-msg', { hasText: /연타 15$/ }).waitFor({ timeout: 15_000 });
const ms = performance.now() - t0;
if (ms > 3000) throw new Error(`15 quick mafia chat lines took ${Math.round(ms)}ms`);
const got = (await host.locator('.mf-msgs .mf-msg', { hasText: /연타 \d+$/ }).allInnerTexts()).map((t) => t.match(/연타 \d+$/)![0]);
if (got.join(',') !== Array.from({ length: 15 }, (_, i) => `연타 ${i + 1}`).join(',')) throw new Error(`mafia chat order/lost: ${got.join(',')}`);
console.log(` mafia: 15 quick chat lines on every screen in ${Math.round(ms)}ms`);
}
for (const p of pages) await p.getByRole('button', { name: /^인사 끝내기/ }).click();
for (const p of pages) await mafiaBanner(p, '밤');

View File

@@ -12,7 +12,6 @@
"./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": {

View File

@@ -173,6 +173,14 @@ describe('채팅 공개 범위(§5.3, §8.3)', () => {
expect(reason(t, g, guess('배3'), T0 + 2300)).toContain('천천히');
expect(reason(t, g, guess('배3'), T0 + 3000)).toBeNull();
});
test('그리기 전 채팅은 제한 없음 (정답 입력만 초당 3개)', () => {
let s = make(3);
expect(s.turn.phase).toBe('choosing');
const g = guessers(s)[0]!;
for (let i = 0; i < 20; i++) s = act(s, g, { type: 'chat', text: `안녕 ${i}` }, T0 + 500);
expect(view(s, g).chat.filter((m) => m.from === g && m.text.startsWith('안녕')).length).toBe(20);
});
});
// ---------------------------------------------------------------- §6 scores

View File

@@ -628,7 +628,6 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
const len = [...cleanText(a.text)].length;
if (len < 1) return fail('내용을 입력해 주세요.');
if (len > CHAT_MAX) return fail(`${CHAT_MAX}자까지 쓸 수 있어요.`);
if (!rateOk(s.msgTimes[actor], GUESS_MSGS_PER_SEC, now)) return fail('조금 천천히 보내 주세요.');
return ok;
}
case 'reaction':
@@ -670,7 +669,6 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
guess(s, actor, a.text, ctx);
break;
case 'chat':
stamp(s, actor, now);
addChat(s, { from: actor, text: maskBanned(cleanText(a.text)), at: now, audience: 'all', kind: 'chat' });
break;
case 'reaction':

View File

@@ -1,26 +0,0 @@
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);
});
});

View File

@@ -1,19 +0,0 @@
/**
* 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;
}

View File

@@ -12,7 +12,6 @@
* 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 {
@@ -338,8 +337,6 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num
if (why) return fail(why);
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 && chatWait(s.lastChatAt[actor], ctx.now) > 0) return fail('조금 천천히 보내 주세요.');
return ok;
}
case 'ready':
@@ -483,7 +480,6 @@ export const liar: Def = {
phase: { kind: 'reveal', startedAt: now, endsAt: now + REVEAL_MS, ready: [] },
descriptions: [],
chat: [],
lastChatAt: {},
events: [],
accused: null,
guess: null,
@@ -514,7 +510,6 @@ 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] = 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);
}

View File

@@ -258,12 +258,11 @@ describe('차례대로 설명 (§5.2)', () => {
expect(reject(s, 'P0', { type: 'chat', text: '안녕' })).toContain('확인하는 중');
s = until(s, 'discussion');
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('조금 천천히 보내 주세요.');
// No pace limit: any number of lines at the same moment all go through.
for (let i = 0; i < 20; i++) s = act(s, 'P1', { type: 'chat', text: `누구지 ${i}` }, t);
s = until(s, 'vote');
s = act(s, 'P2', { type: 'chat', text: '투표해요' });
expect(s.chat.map((m) => m.text)).toEqual(['누구지 0', '누구지 1', '누구지 2', '누구지 3', '누구지 4', '누구지 5', '투표해요']);
expect(s.chat.map((m) => m.text)).toEqual([...Array.from({ length: 20 }, (_, i) => `누구지 ${i}`), '투표해요']);
});
});

View File

@@ -128,8 +128,6 @@ 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<PlayerId, number>;
events: PublicEvent[];
accused: PlayerId | null;
guess: string | null;

View File

@@ -8,7 +8,6 @@
* 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,
@@ -524,7 +523,6 @@ 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 && chatWait(s.lastChatAt[actor], ctx.now) > 0) return fail('조금 천천히 보내 주세요.');
return ok;
}
default:
@@ -718,7 +716,6 @@ export const mafia: Def = {
privateResults: [],
chat: [],
chatCount: { day: 0, mafia: 0, dead: 0, lovers: 0 },
lastChatAt: {},
events: [],
trialVoters: [],
mvpVotes: {},
@@ -749,7 +746,6 @@ 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] = chatNext(s.lastChatAt[actor], now);
break;
}
case 'adjustTime':

View File

@@ -419,14 +419,13 @@ describe('채팅 권한 (§5.6)', () => {
const roles: Role[] = ['mafia', 'mafia', 'police', 'doctor', 'medium', 'lover', 'lover', 'citizen', 'citizen'];
const o = { extraRoles: { medium: true, lovers: true } };
test('밤에 시민 낮 채팅 거부, 죽은 사람 낮 채팅 거부, 레이트 리밋 초과 거부', () => {
test('밤에 시민 낮 채팅 거부, 죽은 사람 낮 채팅 거부, 연달아 치는 채팅은 제한 없음', () => {
let s = until(rig(roles, o), 'greeting');
const g0 = (s.phase as Extract<MafiaState['phase'], { kind: 'greeting' }>).startedAt;
s = say(s, 'P7', 'day', '안녕하세요');
// 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);
// No pace limit: any number of lines at the same moment all go through.
for (let i = 0; i < 20; i++) s = say(s, 'P7', 'day', `연달아 ${i}`, g0 + 1);
expect(s.chat.filter((m) => m.text.startsWith('연달아')).length).toBe(20);
s = tick(s);
expect(reject(s, 'P7', { type: 'chat', channel: 'day', text: '밤인데' })).toBe('밤에는 낮 채팅을 쓸 수 없어요.');
expect(reject(s, 'P7', { type: 'chat', channel: 'mafia', text: '...' })).toBe('마피아만 쓸 수 있어요.');

View File

@@ -196,8 +196,6 @@ export interface MafiaState {
/** Every message of every channel; the view filters by channel permission. */
chat: ChatMessage[];
chatCount: Record<Channel, number>;
/** Chat pace per person: the time the next line is free from (`chat-pace.ts`; older saves hold the last send time). */
lastChatAt: Record<PlayerId, number>;
events: PublicEvent[];
/** Voters (vote phase) for the current accused — for the MVP count. */
trialVoters: PlayerId[];