diff --git a/apps/server/src/rooms/room.test.ts b/apps/server/src/rooms/room.test.ts index 3017e39..b83d081 100644 --- a/apps/server/src/rooms/room.test.ts +++ b/apps/server/src/rooms/room.test.ts @@ -226,3 +226,43 @@ describe('윷놀이 room rules', () => { expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq); }); }); + +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(); + const a = conn('A'); + 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(); + 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초 뒤']); + }); + + test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => { + const { room, clock, conn } = harness(); + const a = conn('A'); + const b = conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + const typingOf = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m) => m.t === 'typing'); + room.typing('A', true, 'room'); + room.typing('A', true, 'room'); + expect(typingOf(b)).toEqual([{ t: 'typing', from: 'A', on: true, ch: 'room' }]); + expect(typingOf(a)).toHaveLength(0); + clock.advance(1000); + room.typing('A', true, 'room'); + room.typing('A', false, 'room'); + expect(typingOf(b)).toHaveLength(3); + // Game chat signal only while a game with its own chat runs (omok has none). + room.typing('A', true, 'game'); + expect(typingOf(b)).toHaveLength(3); + // Chat off: nothing. + room.configure('A', { chatEnabled: false }); + clock.advance(1000); + room.typing('A', true, 'room'); + expect(typingOf(b)).toHaveLength(3); + }); +}); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index bc6686f..dea7cb6 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -14,6 +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'; export interface Conn { userId: string; @@ -151,6 +152,9 @@ export class Room { private flushTimer: ReturnType | null = null; private recentCs = new Map(); private lastChatAt = new Map(); + private chatBuckets = new Map(); + /** When each person last said they were typing (to drop repeats within a second). */ + private typingAt = new Map(); private consecutiveErrors = 0; private readonly now: () => number; /** Plays the computer players' moves (docs/06 §12). */ @@ -798,8 +802,11 @@ export class Room { if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.'; if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.'; const now = this.now(); - if (now - (this.lastChatAt.get(userId) ?? 0) < 500) return '조금 천천히 보내 주세요.'; - this.lastChatAt.set(userId, 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 '조금 천천히 보내 주세요.'; + this.typingAt.delete(userId); const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim(); if (!clean) return null; const msg: Extract = { @@ -820,6 +827,21 @@ export class Room { return (this.status === 'playing' || this.status === 'paused') && !!this.def.ownChat; } + /** + * "입력 중" for people, like the computers'. Room chat: only while the room chat is open. Game chat: only in games + * with their own chat, and the client only sends it from the public channel (마피아 낮, 라이어 토론). + */ + typing(userId: string, on: boolean, ch: 'room' | 'game'): void { + if (!this.isParticipant(userId)) return; + if (ch === 'room' ? !this.config.chatEnabled || this.gameChatOnly() : !this.gameChatOnly()) return; + const now = this.now(); + if (on) { + if (now - (this.typingAt.get(userId) ?? -Infinity) < 1000) return; + this.typingAt.set(userId, now); + } else this.typingAt.delete(userId); + for (const [id, c] of this.conns) if (id !== userId) c.send({ t: 'typing', from: userId, on, ch }); + } + emote(userId: string, id: string): void { if (!this.isParticipant(userId) || this.gameChatOnly()) return; const now = this.now(); diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index d223bf2..56c5596 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -208,6 +208,9 @@ export class Gateway { case 'emote': room.emote(u, m.id); return; + case 'typing': + room.typing(u, m.on, m.ch); + return; case 'rematch': e = room.rematch(u); break; diff --git a/apps/web/src/components/BotActivity.tsx b/apps/web/src/components/BotActivity.tsx index 1fc7526..f0fbe39 100644 --- a/apps/web/src/components/BotActivity.tsx +++ b/apps/web/src/components/BotActivity.tsx @@ -1,18 +1,30 @@ import type { RoomView } from '@bg/shared/lite'; +import { useRoom } from '../net/socket'; /** - * What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…". + * What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…", and people + * typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat). * Not announced to screen readers: the chat line or the move that follows is. */ -export function BotActivity({ room, only }: { room: RoomView; only?: 'typing' }) { +export function BotActivity({ room, only, ch }: { room: RoomView; only?: 'typing'; ch?: 'room' | 'game' }) { + const typing = useRoom((s) => s.typing); + const me = useRoom((s) => s.me?.id); const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only); - if (!entries.length) return null; - const name = (id: string) => room.seats.find((s) => s?.user.id === id)?.user.nickname ?? '컴퓨터'; + const people = ch ? Object.entries(typing).filter(([id, t]) => t.ch === ch && id !== me) : []; + if (!entries.length && !people.length) return null; + const name = (id: string, fallback: string) => + room.seats.find((s) => s?.user.id === id)?.user.nickname ?? room.spectators.find((u) => u.id === id)?.nickname ?? fallback; return (
{entries.map(([id, a]) => ( - {a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'} + {a === 'typing' ? '💬' : '🤖'} {name(id, '컴퓨터')} {a === 'typing' ? '입력 중' : '생각 중'} + + + ))} + {people.map(([id]) => ( + + 💬 {name(id, '누군가')} 입력 중 ))} diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index 404fda4..ea80eab 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -3,6 +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 { useStickToBottom } from '../lib/useStickToBottom'; import { BotActivity } from './BotActivity'; import { ChatMessage, sameRun } from './ChatMessage'; @@ -15,6 +16,8 @@ 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 typing = useTypingSignal('room', room.chatEnabled); const lastId = chat.at(-1)?.id ?? 0; useEffect(() => { useChatSeen.setState({ seen: lastId }); @@ -49,7 +52,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ ), )}
- +
{EMOTES.map((id) => ( + {open && ( +
+
+ 소리 크기 + + {shown} + +
+ updateSettings({ volume: Number(e.target.value), sound: Number(e.target.value) > 0 })} + onPointerUp={() => sfx.good()} + onKeyUp={() => sfx.click()} + /> +
+ + +
+
+ )} +
+ ); +} diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 92306fd..8e7d5cc 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -14,6 +14,7 @@ import { useServerNow } from '../../components/TurnTimer'; import { haptic, sounds } from '../../lib/feedback'; import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; +import { useChatOutbox, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -396,6 +397,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 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 })), @@ -403,6 +405,7 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1)); const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote'; const canWrite = !!v.my?.canChat && talk; + const typing = useTypingSignal('game', canWrite); const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? ''); return (
@@ -428,12 +431,25 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record - setText(e.target.value)} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" /> + { + setText(e.target.value); + typing.onText(e.target.value); + }} + onBlur={typing.stop} + maxLength={200} + placeholder="누가 라이어일까요?" + aria-label="토론 채팅 메시지" + enterKeyHint="send" + /> ) : ( diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index 39844f4..f8379b8 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -14,6 +14,7 @@ import { useServerNow } from '../../components/TurnTimer'; import { haptic, sounds } from '../../lib/feedback'; import { ChatMessage, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; +import { useChatOutbox, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -401,6 +402,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); 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}`; @@ -424,6 +427,8 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record c.channel === cur); const canWrite = !!ch?.canWrite; + // "입력 중" only from the public 전체 chat (night channels stay secret). + const typing = useTypingSignal('game', canWrite && cur === 'day'); const why = ch ? ch.why : me ? '이 채팅은 읽기만 할 수 있어요.' : '관전 중에는 채팅을 쓸 수 없어요.'; const onTabKey = (e: KeyboardEvent) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; @@ -477,15 +482,20 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record setText(e.target.value)} + onChange={(e) => { + setText(e.target.value); + typing.onText(e.target.value); + }} + onBlur={typing.stop} maxLength={200} placeholder={`${CHANNEL_KO[cur]} 채팅에 쓰기`} aria-label={`${CHANNEL_KO[cur]} 채팅 메시지`} diff --git a/apps/web/src/lib/chat-input.ts b/apps/web/src/lib/chat-input.ts new file mode 100644 index 0000000..930619a --- /dev/null +++ b/apps/web/src/lib/chat-input.ts @@ -0,0 +1,71 @@ +/** + * 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 ("조금 천천히"). + * - `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 { socket } from '../net/socket'; + +const MAX_QUEUE = 10; + +export function useChatOutbox(send: (item: T) => void, gapMs: number) { + const queue = useRef([]); + const last = useRef(-Infinity); + 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; + } + 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) => { + 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) { + const sentAt = useRef(0); + const on = useRef(false); + const stop = useCallback(() => { + if (!on.current) return; + on.current = false; + sentAt.current = 0; + socket.send({ t: 'typing', on: false, ch }); + }, [ch]); + const onText = useCallback( + (text: string) => { + if (!enabled || !text.trim()) return stop(); + const now = Date.now(); + if (on.current && now - sentAt.current < RENEW_MS) return; + on.current = true; + sentAt.current = now; + socket.send({ t: 'typing', on: true, ch }); + }, + [ch, enabled, stop], + ); + useEffect(() => { + if (!enabled) stop(); + }, [enabled, stop]); + useEffect(() => stop, [stop]); + return { onText, stop }; +} diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 523b593..ddece7e 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -34,6 +34,8 @@ interface RoomStore { result: GameResultView | null; chat: ChatLine[]; emotes: { id: number; from: string; emote: string }[]; + /** People typing right now: user id → where and until when (ms, local clock). */ + typing: Record; pending: number | null; slow: boolean; rttMs: number | null; @@ -42,6 +44,14 @@ interface RoomStore { kicked: boolean; } +/** A "입력 중" signal lasts this long unless renewed (the typer renews it every couple of seconds). */ +const TYPING_MS = 5000; +const withoutTyping = (t: RoomStore['typing'], id: string | undefined): RoomStore['typing'] => { + if (!id || !(id in t)) return t; + const { [id]: _gone, ...rest } = t; + return rest; +}; + export const useRoom = create(() => ({ status: 'idle', me: null, @@ -52,6 +62,7 @@ export const useRoom = create(() => ({ result: null, chat: [], emotes: [], + typing: {}, pending: null, slow: false, rttMs: null, @@ -208,7 +219,7 @@ class GameSocket { join(code: string, as: 'player' | 'spectator' = 'player'): void { const cur = useRoom.getState(); if (cur.code !== code) { - useRoom.setState({ code, room: null, roomSeq: -1, game: null, result: null, chat: [], joinError: null, kicked: false, pending: null }); + useRoom.setState({ code, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, joinError: null, kicked: false, pending: null }); } this.start(); this.send({ t: 'join', code, as }); @@ -216,14 +227,14 @@ class GameSocket { leave(): void { this.send({ t: 'leave' }); - useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], pending: null }); + useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], typing: {}, pending: null }); } /** Left the room page (홈, 규칙…) without leaving: the seat stays, but the room no longer counts us as there. */ detach(code: string): void { if (useRoom.getState().code !== code) return; this.send({ t: 'detach' }); - useRoom.setState({ code: null, room: null, roomSeq: -1, game: null, result: null, chat: [], pending: null }); + 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. */ @@ -290,7 +301,17 @@ class GameSocket { useRoom.setState({ result: m.result }); break; case 'chat': - useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at }].slice(-100) }); + useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at }].slice(-100), typing: withoutTyping(st.typing, m.from?.id) }); + break; + case 'typing': + if (m.on) { + const until = Date.now() + TYPING_MS; + useRoom.setState({ typing: { ...st.typing, [m.from]: { ch: m.ch, until } } }); + setTimeout(() => { + const cur = useRoom.getState().typing[m.from]; + if (cur && cur.until <= Date.now()) useRoom.setState((s) => ({ typing: withoutTyping(s.typing, m.from) })); + }, TYPING_MS + 50); + } else useRoom.setState({ typing: withoutTyping(st.typing, m.from) }); break; case 'emote': { const id = this.chatId++; diff --git a/apps/web/src/pages/MePage.tsx b/apps/web/src/pages/MePage.tsx index 99858ea..136f1cf 100644 --- a/apps/web/src/pages/MePage.tsx +++ b/apps/web/src/pages/MePage.tsx @@ -58,6 +58,12 @@ export default function MePage() { updateSettings({ fontScale })} /> updateSettings({ theme })} /> updateSettings({ sound: v === 'on' })} /> + updateSettings({ vibrate: v === 'on' })} /> setChatOpen(true)} /> )} +