채팅 연타가 몇 초씩 밀리던 문제: 브라우저가 0.55초(마피아·라이어 0.75초)에 한 줄씩만 내보내던 대기열과 게임 채팅 0.7초 간격 제한을 없애고, 방 채팅·마피아·라이어가 같은 속도 규칙(한 번에 6줄, 그 뒤 0.3초에 한 줄)을 쓰게. 사람이 치는 속도로는 기다리지 않고 바로 올라감
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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' });
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<typeof setTimeout> | null = null;
|
||||
private recentCs = new Map<string, number[]>();
|
||||
private lastChatAt = new Map<string, number>();
|
||||
private chatBuckets = new Map<string, TokenBucket>();
|
||||
/** 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;
|
||||
@@ -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;
|
||||
|
||||
@@ -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 }), 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(() => {
|
||||
|
||||
@@ -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 }), 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 })),
|
||||
|
||||
@@ -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, 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}`;
|
||||
|
||||
@@ -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<T = string>(send: (item: T) => void, gapMs: number) {
|
||||
export function useChatOutbox<T = string>(send: (item: T) => void) {
|
||||
const queue = useRef<T[]>([]);
|
||||
const last = useRef(-Infinity);
|
||||
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;
|
||||
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) => {
|
||||
|
||||
Reference in New Issue
Block a user