From b7d5b3ad755402a0da50414b38ced457c36daace Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 14 Oct 2026 09:42:31 +0900 Subject: [PATCH] =?UTF-8?q?=EC=B1=84=ED=8C=85=20=EC=86=8C=EB=A6=AC(?= =?UTF-8?q?=EC=8A=A4=ED=83=80=ED=81=AC=EB=9E=98=ED=94=84=ED=8A=B8=20?= =?UTF-8?q?=EA=B0=99=EC=9D=80=20"=EB=9D=A0=EB=A6=AD"):=20=EC=83=88=20?= =?UTF-8?q?=EC=B1=84=ED=8C=85=20=EC=A4=84=EB=A7=88=EB=8B=A4(=EB=82=B4?= =?UTF-8?q?=EA=B0=80=20=EB=B3=B4=EB=82=B8=20=EC=A4=84=EB=8F=84)=20?= =?UTF-8?q?=EB=A7=91=EC=9D=80=20=EB=91=90=20=EC=9D=8C=EC=9D=B4=20=EC=98=AC?= =?UTF-8?q?=EB=9D=BC=EA=B0=80=EB=8A=94=20=EC=A7=A7=EC=9D=80=20=EC=86=8C?= =?UTF-8?q?=EB=A6=AC.=20=ED=81=AC=EA=B8=B0=EB=8A=94=20=EA=B2=8C=EC=9E=84?= =?UTF-8?q?=20=EC=86=8C=EB=A6=AC=20=EA=B8=B0=EC=A4=80(0.15)=EC=9D=98=2090%?= =?UTF-8?q?=EB=A1=9C=20=EC=86=8C=EB=A6=AC=20=ED=81=AC=EA=B8=B0=20=EC=84=A4?= =?UTF-8?q?=EC=A0=95=EC=9D=84=20=EA=B7=B8=EB=8C=80=EB=A1=9C=20=EB=94=B0?= =?UTF-8?q?=EB=A5=B4=EA=B3=A0,=20=EC=86=8C=EB=A6=AC=20=EB=81=84=EA=B8=B0?= =?UTF-8?q?=EB=A9=B4=20=EC=95=88=20=EB=82=A8.=20=EB=AA=B0=EB=A0=A4=20?= =?UTF-8?q?=EC=98=A8=20=EC=A4=84=EC=9D=80=20=ED=95=9C=20=EB=B2=88=EB=A7=8C?= =?UTF-8?q?.=20=EB=B0=A9=EC=97=90=20(=EB=8B=A4=EC=8B=9C)=20=EB=93=A4?= =?UTF-8?q?=EC=96=B4=EC=98=AC=20=EB=95=8C=20=EC=84=9C=EB=B2=84=EA=B0=80=20?= =?UTF-8?q?=EB=8B=A4=EC=8B=9C=20=EB=B3=B4=EB=82=B4=EB=8A=94=20=EC=A7=80?= =?UTF-8?q?=EB=82=9C=20=EC=B1=84=ED=8C=85=EC=9D=80=20replay=20=ED=91=9C?= =?UTF-8?q?=EC=8B=9C=EB=A1=9C=20=EC=A1=B0=EC=9A=A9=ED=9E=88.=20=EB=A7=88?= =?UTF-8?q?=ED=94=BC=EC=95=84=C2=B7=EB=9D=BC=EC=9D=B4=EC=96=B4=20=EA=B2=8C?= =?UTF-8?q?=EC=9E=84=20=EC=95=88=20=EC=B1=84=ED=8C=85=EB=8F=84=20=EA=B0=99?= =?UTF-8?q?=EC=9D=80=20=EC=86=8C=EB=A6=AC.=20feedback.test.ts,=20room.test?= =?UTF-8?q?.ts,=20chat.e2e.ts=EC=97=90=20=ED=99=95=EC=9D=B8=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= 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/room.test.ts | 16 +++++ apps/server/src/rooms/room.ts | 2 +- apps/web/src/games/liar/index.tsx | 4 +- apps/web/src/games/mafia/index.tsx | 4 +- apps/web/src/lib/feedback.test.ts | 111 +++++++++++++++++++++++++++++ apps/web/src/lib/feedback.ts | 32 +++++++++ apps/web/src/net/socket.ts | 4 +- apps/web/src/pages/RoomPage.tsx | 8 ++- e2e/chat.e2e.ts | 35 ++++++++- packages/shared/src/types.ts | 3 +- 10 files changed, 212 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/lib/feedback.test.ts diff --git a/apps/server/src/rooms/room.test.ts b/apps/server/src/rooms/room.test.ts index 6f970e0..4b4c266 100644 --- a/apps/server/src/rooms/room.test.ts +++ b/apps/server/src/rooms/room.test.ts @@ -239,6 +239,22 @@ describe('Room chat (2026-10-13)', () => { expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines); }); + test('lines sent before joining come back marked as replay; live lines are not', () => { + const { room, conn } = harness(); + const a = conn('A'); + room.join(a, 'player'); + room.chat('A', '먼저 한 말'); + const b = conn('B'); + room.join(b, 'player'); + room.chat('A', '지금 한 말'); + const got = b.msgs.filter((m) => m.t === 'chat').map((m) => [(m as { text: string }).text, (m as { replay?: true }).replay ?? false]); + expect(got).toEqual([ + ['먼저 한 말', true], + ['지금 한 말', false], + ]); + expect((a.msgs.find((m) => m.t === 'chat') as { replay?: true }).replay).toBeUndefined(); + }); + 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'); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index b758e44..1fa9c8a 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -530,7 +530,7 @@ export class Room { const st = this.stateMessage(u, undefined, true); if (st) conn.send(st); if (this.status === 'finished' && this.lastResult) conn.send({ t: 'result', seq: this.seq, result: this.lastResult }); - for (const m of this.chatLog) conn.send(m); + for (const m of this.chatLog) conn.send({ ...m, replay: true }); this.scheduleTimer(); return null; } diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index ea36a18..f7f8244 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -11,7 +11,7 @@ import { TOPIC_IDS, TOPIC_KO } from '@bg/games/liar/topics'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { useServerNow } from '../../components/TurnTimer'; -import { haptic, sfx, sounds, tone } from '../../lib/feedback'; +import { haptic, sfx, sounds, tone, useChatSound } from '../../lib/feedback'; import { cssEsc, useBanner, type BannerTone } from '../card-fx'; import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; @@ -779,6 +779,8 @@ function useLiarFx(v: LiarView, me: string | null, players: Record) { + // The room chat is closed while playing, so the 토론 chat lines play the chat sound. + useChatSound(v.chat.at(-1)?.n); const ph = v.phase; const my = v.my; const [announce, setAnnounce] = useState(''); diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index 1fdfd4f..52bf46e 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -11,7 +11,7 @@ import type { Channel, ChatView, MafiaOptions, MafiaView, PlayerView, PrivateRes import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { useServerNow } from '../../components/TurnTimer'; -import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; +import { haptic, noise, sfx, sounds, tone, useChatSound } from '../../lib/feedback'; import { useBanner, type BannerTone } from '../card-fx'; import { ChatMessage, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; @@ -854,6 +854,8 @@ function useMafiaFx(v: MafiaView, players: Record, showBanne } function MafiaBoard({ view: v, me, players, act, pending }: BoardProps) { + // The room chat is closed while playing, so this game's own chat lines play the chat sound. + useChatSound(v.chat.at(-1)?.key); const ph = v.phase; const my = v.my; const [announce, setAnnounce] = useState(''); diff --git a/apps/web/src/lib/feedback.test.ts b/apps/web/src/lib/feedback.test.ts new file mode 100644 index 0000000..1c983f3 --- /dev/null +++ b/apps/web/src/lib/feedback.test.ts @@ -0,0 +1,111 @@ +import { beforeEach, expect, mock, test } from 'bun:test'; + +/** A fake Web Audio graph that records every oscillator note: frequency, start and peak level. */ +interface Note { + freq: number; + start: number; + peak: number; +} +let notes: Note[] = []; +let master: FakeParam | null = null; +class FakeParam { + value = 0; + peak = 0; + setValueAtTime(v: number) { + this.value = v; + this.peak = Math.max(this.peak, v); + } + exponentialRampToValueAtTime(v: number) { + this.peak = Math.max(this.peak, v); + } +} +class FakeCtx { + state = 'running'; + currentTime = 0; + destination = {}; + resume() {} + createGain() { + const gain = new FakeParam(); + return { + gain, + connect: (to: unknown) => { + if (to === this.destination) master = gain; + return to; + }, + }; + } + createOscillator() { + const frequency = new FakeParam(); + let g: { gain: FakeParam } | null = null; + return { + type: 'sine', + frequency, + connect(to: { gain: FakeParam }) { + g = to; + return { connect: () => {} }; + }, + start(t: number) { + notes.push({ freq: frequency.value, start: t, peak: g!.gain.peak }); + }, + stop() {}, + }; + } +} +(globalThis as any).AudioContext = FakeCtx; + +// The real settings store needs a page (document); only the sound settings matter here. +let settings = { sound: true, volume: 100 }; +mock.module('../store/session', () => ({ useSession: { getState: () => ({ settings }) } })); +const { CHAT_LEVEL, GAME_LEVEL, chatSound, sounds } = await import('./feedback'); + +const setVolume = (volume: number, sound = true) => { + settings = { sound, volume }; +}; + +beforeEach(() => { + notes = []; +}); + +test('chat sound is 10% under the game sounds', () => { + expect(GAME_LEVEL).toBe(0.15); + expect(CHAT_LEVEL).toBeCloseTo(GAME_LEVEL * 0.9, 10); + setVolume(100); + sounds.myTurn(); // a typical game sound at the usual level + const game = Math.max(...notes.map((n) => n.peak)); + notes = []; + chatSound(); + // Notes playing at the same moment add up; the loudest moment of the chat sound is 90% of a game sound. + const byStart = new Map(); + for (const n of notes) byStart.set(n.start, (byStart.get(n.start) ?? 0) + n.peak); + const loudest = Math.max(...byStart.values()); + expect(loudest).toBeCloseTo(game * 0.9, 6); + // Two rising notes ("띠릭"). + const mains = [...new Set(notes.map((n) => n.start))].sort().map((t) => Math.min(...notes.filter((n) => n.start === t).map((n) => n.freq))); + expect(mains).toEqual([1568, 2093]); +}); + +test('chat sound follows the volume setting and is silent when sound is off', async () => { + await new Promise((r) => setTimeout(r, 100)); // past the burst guard + setVolume(50); + chatSound(); + expect(notes.length).toBeGreaterThan(0); + expect(master!.value).toBe(0.5); + notes = []; + await new Promise((r) => setTimeout(r, 100)); + setVolume(50, false); + chatSound(); + expect(notes).toEqual([]); +}); + +test('lines arriving in a burst share one sound', async () => { + await new Promise((r) => setTimeout(r, 100)); + setVolume(100); + chatSound(); + const one = notes.length; + chatSound(); + chatSound(); + expect(notes.length).toBe(one); + await new Promise((r) => setTimeout(r, 100)); + chatSound(); + expect(notes.length).toBe(one * 2); +}); diff --git a/apps/web/src/lib/feedback.ts b/apps/web/src/lib/feedback.ts index 33f9ef3..0d77885 100644 --- a/apps/web/src/lib/feedback.ts +++ b/apps/web/src/lib/feedback.ts @@ -4,6 +4,7 @@ * are now volume 100, so the default plays them at half). Games use `sfx.*` (shared palette) or `tone`/`noise` * directly for something of their own. */ +import { useEffect, useRef } from 'react'; import { useSession } from '../store/session'; let ctx: AudioContext | null = null; @@ -187,6 +188,37 @@ export const sounds = { buzz: () => tone(180, 260, 'square', 0.08), }; +/** The usual level of a game sound at volume 100 (`tone`'s default). */ +export const GAME_LEVEL = 0.15; +/** Chat sound: 10% under the game sounds (it follows the same volume setting). */ +export const CHAT_LEVEL = GAME_LEVEL * 0.9; +let lastChatAt = -Infinity; + +/** + * StarCraft-like chat "띠릭": two quick, glassy notes going up (sine + a soft octave on top), about 0.2 s. + * The layers of a note add up to CHAT_LEVEL at most. Lines arriving in a burst share one sound. + */ +export function chatSound(): void { + const now = performance.now(); + if (now - lastChatAt < 80) return; + lastChatAt = now; + const main = CHAT_LEVEL * 0.8; + const air = CHAT_LEVEL * 0.2; + tone(1568, 70, 'sine', main, 0, { attack: 3, slideTo: 1661 }); + tone(3136, 50, 'sine', air, 0, { attack: 3 }); + tone(2093, 140, 'sine', main, 65, { attack: 3 }); + tone(4186, 90, 'sine', air, 65, { attack: 3 }); +} + +/** Plays the chat sound whenever `lastKey` (the newest live chat line) changes after the first render. */ +export function useChatSound(lastKey: string | number | undefined): void { + const prev = useRef(lastKey); + useEffect(() => { + if (lastKey !== undefined && lastKey !== prev.current) chatSound(); + prev.current = lastKey; + }, [lastKey]); +} + export function haptic(pattern: number | number[]): void { if (!useSession.getState().settings.vibrate) return; try { diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 2f11e32..8e84dfc 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -15,6 +15,8 @@ export interface ChatLine { from: PublicUser | null; text: string; at: number; + /** Arrived just now (not resent history on joining): plays the chat sound. */ + live: boolean; } export interface GameState { @@ -307,7 +309,7 @@ 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), typing: withoutTyping(st.typing, m.from?.id) }); + useRoom.setState({ chat: [...st.chat, { id: this.chatId++, from: m.from, text: m.text, at: m.at, live: !m.replay }].slice(-100), typing: withoutTyping(st.typing, m.from?.id) }); break; case 'typing': if (m.on) { diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index a8ee36a..73f6e13 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -13,7 +13,7 @@ import { useSession } from '../store/session'; import { OptionSync, withLocks } from '../lib/option-sync'; import { loadGameUI } from '../games/registry'; import type { GameUI } from '../games/types'; -import { sounds } from '../lib/feedback'; +import { sounds, useChatSound } from '../lib/feedback'; import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel'; import { BotActivity } from '../components/BotActivity'; import { VolumeControl } from '../components/VolumeControl'; @@ -119,6 +119,12 @@ function Room({ code, me }: { code: string; me: PublicUser }) { }, [room]); useTurnTitle(ui, game?.view, me.id); + // Every new room chat line (mine too, like StarCraft) plays the chat sound; history resent on joining does not. + const lastLiveChat = useRoom((s) => { + const l = s.chat.at(-1); + return l?.live ? l.id : undefined; + }); + useChatSound(lastLiveChat); // Inside a room the room bar replaces the site header, so the board gets that height back. useEffect(() => { document.documentElement.classList.add('in-room'); diff --git a/e2e/chat.e2e.ts b/e2e/chat.e2e.ts index 22550dc..2f08a63 100644 --- a/e2e/chat.e2e.ts +++ b/e2e/chat.e2e.ts @@ -1,7 +1,8 @@ /** * E2E: the room chat stays at the newest line (also after more than 100 lines, when the list is full), lets the reader * scroll up without jumping, shows who said what as a name line + bubble, and has no "가리기" button any more. - * PC lobby + PC in-game side panel + phone chat sheet (unread badge past 100 lines too) + narrowed PC window (720–1099px) chat button. + * PC lobby + PC in-game side panel + phone chat sheet (unread badge past 100 lines too) + narrowed PC window (720–1099px) chat button + * + chat sound on live lines only. * Run: E2E_PORT=4641 bun e2e/chat.e2e.ts (needs apps/web/dist built) */ import { chromium, type Page } from 'playwright-core'; @@ -241,6 +242,38 @@ try { if (await a.locator('.room-bar').getByRole('button', { name: /^채팅/ }).count()) throw new Error('chat button still on the wide bar'); }); + await step('채팅 소리: 새 줄마다 "띠릭"(보낸 사람도), 다시 들어올 때 받는 지난 줄은 조용히', async () => { + // Count the chat sound's first note (1568 Hz) as it is scheduled. + const rec = () => { + const w = window as unknown as { __chatBeeps: number }; + w.__chatBeeps = 0; + const orig = AudioParam.prototype.setValueAtTime; + AudioParam.prototype.setValueAtTime = function (v: number, t: number) { + if (v === 1568) w.__chatBeeps++; + return orig.call(this, v, t); + }; + }; + const beeps = (p: Page) => p.evaluate(() => (window as unknown as { __chatBeeps: number }).__chatBeeps); + await b.addInitScript(rec); + await a.evaluate(rec); + await b.evaluate(rec); + await a.waitForTimeout(200); + await say(a, '소리 확인'); + await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 }); + await a.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 }); + // Reload: the room resends its chat history, which must not beep. + await b.reload(); + await b.getByRole('button', { name: /^채팅/ }).click(); + const sheet = b.getByRole('dialog', { name: '채팅' }); + await sheet.locator('.chat-line', { hasText: '소리 확인' }).waitFor(); + await b.waitForTimeout(500); + if ((await beeps(b)) !== 0) throw new Error(`history beeped ${await beeps(b)} times`); + await say(a, '다시 들어온 뒤'); + await sheet.locator('.chat-line', { hasText: '다시 들어온 뒤' }).waitFor(); + await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 }); + await sheet.getByRole('button', { name: '닫기' }).click(); + }); + await step('소리 크기: 방 막대 오른쪽 위, 기본 50, 0~100', async () => { const btn = a.locator('.room-bar').getByRole('button', { name: /^소리 크기/ }); if ((await btn.getAttribute('aria-label')) !== '소리 크기 50') throw new Error(`default: ${await btn.getAttribute('aria-label')}`); diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 2924252..d958ed6 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -109,7 +109,8 @@ export type ServerMessage = /** Events of streaming actions (e.g. drawing), relayed without a full view (docs/games/catchmind.md §5.5). */ | { t: 'stream'; seq: number; events: unknown[]; cs?: number } | { t: 'reject'; cs: number; reason: string } - | { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string } + /** `replay`: an earlier line resent on (re)joining, so the client shows it without the chat sound. */ + | { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string; replay?: true } | { t: 'emote'; from: string; id: string } /** Someone is typing (room chat, or the game's public chat when the game has its own). Expires on its own after a few seconds. */ | { t: 'typing'; from: string; on: boolean; ch: 'room' | 'game' }