feat(chat): unread read-receipts with lobby/game dot and history-open ack
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 49s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m16s

Persist per-message read state as a chat_messages.unread_seats bitmask
(migration 00008): a text message seeds every recipient seat's bit, a nudge
only the awaited seat's. A seat's bit clears when the player opens the move
history or chat (POST /games/:id/chat/read, sent only when something is
unread), and a nudge additionally clears when its recipient answers by moving
(a wired game NudgeClearer, dependency-inverted so game keeps off social).

UI shows a per-viewer unread dot in the lobby (next to the opponent) and the
game score bar — the unread_chat game-view flag seeds it from authoritative
REST views, live chat/nudge events raise it. Opening the move history counts
as reading (even without entering chat): the 💬 fade-blinks twice and the
client acks. Admin Messages gains an unread-only filter, a read/unread column,
and a per-message card with the per-seat read breakdown. Observability:
chat_read_duration histogram + chat_unread_messages gauge + social tracing.
This commit is contained in:
Ilia Denisov
2026-06-17 11:12:38 +02:00
parent d53ff18a67
commit aaac816dc2
51 changed files with 1000 additions and 111 deletions
+2 -2
View File
@@ -2,7 +2,7 @@
import { onMount } from 'svelte';
import Chat from './Chat.svelte';
import { gateway } from '../lib/gateway';
import { app, handleError, clearChatUnread } from '../lib/app.svelte';
import { app, handleError, markChatRead } from '../lib/app.svelte';
import { canSendChat, sentThisTurn } from '../lib/chatlimit';
import type { ChatMessage, StateView } from '../lib/model';
@@ -50,7 +50,7 @@
async function refresh() {
try {
messages = await gateway.chatList(id);
clearChatUnread(id);
markChatRead(id);
} catch {
/* best-effort */
}
+46 -20
View File
@@ -8,7 +8,7 @@
import Rack from './Rack.svelte';
import { gateway } from '../lib/gateway';
import { navigate } from '../lib/router.svelte';
import { app, handleError, showToast } from '../lib/app.svelte';
import { app, handleError, showToast, markChatRead, seedChatUnread } from '../lib/app.svelte';
import { connection } from '../lib/connection.svelte';
import { GatewayError } from '../lib/client';
import { t, type MessageKey } from '../lib/i18n/index.svelte';
@@ -71,6 +71,19 @@
// landscape, where it is docked open in the left panel. Gates the per-seat add-friend
// affordance and its confirm reset so both work regardless of layout.
const historyShown = $derived(historyOpen || landscape);
// A nonce bumped to replay the 💬 fade-blink each time the history is shown with unread chat.
let chatBlink = $state(0);
// Opening the move history counts as reading the chat (even without entering it): when the
// history is shown with unread present, play the 💬 fade-blink (a two-cycle nudge) and mark the
// chat read. In landscape the history is docked open, so a message arriving while it is visible
// blinks and is read at once. markChatRead clears the flag (and acks the backend), so this
// settles after one pass and re-fires only when a new message raises unread again.
$effect(() => {
if (historyShown && app.chatUnread[id]) {
chatBlink++;
markChatRead(id);
}
});
const variant = $derived(view?.game.variant ?? 'scrabble_en');
const board = $derived(replay(moves));
@@ -154,6 +167,8 @@
gateway.draftGet(id).catch(() => ''),
]);
view = st;
// Seed the unread flag from the authoritative state (the live stream only raises it).
seedChatUnread(id, st.game.unreadChat);
moves = hist.moves;
setCachedGame(id, st, hist.moves, draft);
// Mirror the fresh status into the lobby snapshot so returning there shows it without a
@@ -601,6 +616,9 @@
// post-move game and the refilled rack — without a follow-up game.state + game.history.
function applyMoveResult(r: MoveResult) {
view = { game: r.game, seat: r.move.player, rack: r.rack, bagLen: r.bagLen, hintsRemaining: view?.hintsRemaining ?? 0 };
// The move result is an authoritative per-viewer view: a nudge the actor just answered by
// moving is already cleared server-side, so reconcile the unread flag from it.
seedChatUnread(id, r.game.unreadChat);
moves = [...moves, r.move];
// A committed move clears the actor's draft on the server, so clear the cached draft too;
// otherwise a same-session re-entry would briefly re-apply the now-stale composition.
@@ -937,7 +955,7 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="scoreboard" class:flat={landscape} onclick={landscape ? undefined : toggleHistory}>
{#if (app.chatUnread[id] ?? 0) > 0}<span class="cbadge sbadge">{app.chatUnread[id]}</span>{/if}
{#if app.chatUnread[id]}<span class="unread-dot sbadge-dot"></span>{/if}
{#each view.game.seats as s (s.seat)}
<div class="seat" class:turn={view.game.toMove === s.seat && !gameOver} class:win={s.isWinner}>
<div class="nm">{seatName(s)}</div>
@@ -970,7 +988,7 @@
{/if}
{#if !view.game.multipleWordsPerTurn}<span class="oneword-label">{t('game.oneWordRule')}</span>{/if}
<button class="hicon" onclick={() => navigate(`/game/${id}/chat`)} aria-label={t('game.chat')}>
💬{#if (app.chatUnread[id] ?? 0) > 0}<span class="cbadge">{app.chatUnread[id]}</span>{/if}
{#key chatBlink}<span class="chat-ico" class:blink={chatBlink > 0 && !app.reduceMotion}>💬</span>{/key}
</button>
</div>
<div class="hgridwrap">
@@ -1378,26 +1396,34 @@
.fico {
line-height: 1;
}
/* The unread-chat count: on the score bar's corner and on the history's 💬 icon. */
.cbadge {
/* The unread-chat dot on the score bar's corner; the history's 💬 icon fade-blinks (two cycles)
when the history is opened with unread present, rather than carrying a count badge. */
.unread-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--danger);
}
.sbadge-dot {
position: absolute;
font-size: 0.68rem;
font-weight: 700;
background: var(--accent);
color: var(--accent-text);
border-radius: 999px;
min-width: 15px;
padding: 0 3px;
line-height: 1.4;
text-align: center;
top: 4px;
right: 6px;
}
.sbadge {
top: 2px;
right: 4px;
.chat-ico {
display: inline-block;
line-height: 1;
}
.hicon .cbadge {
top: -1px;
right: -1px;
.chat-ico.blink {
animation: chat-blink 1s ease-in-out 2;
}
@keyframes chat-blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
.loading {
text-align: center;
+12 -2
View File
@@ -103,8 +103,13 @@ vsAi():boolean {
return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
}
unreadChat():boolean {
const offset = this.bb!.__offset(this.bb_pos, 30);
return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false;
}
static startGameView(builder:flatbuffers.Builder) {
builder.startObject(13);
builder.startObject(14);
}
static addId(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset) {
@@ -171,12 +176,16 @@ static addVsAi(builder:flatbuffers.Builder, vsAi:boolean) {
builder.addFieldInt8(12, +vsAi, +false);
}
static addUnreadChat(builder:flatbuffers.Builder, unreadChat:boolean) {
builder.addFieldInt8(13, +unreadChat, +false);
}
static endGameView(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static createGameView(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset, variantOffset:flatbuffers.Offset, dictVersionOffset:flatbuffers.Offset, statusOffset:flatbuffers.Offset, players:number, toMove:number, turnTimeoutSecs:number, multipleWordsPerTurn:boolean, moveCount:number, endReasonOffset:flatbuffers.Offset, seatsOffset:flatbuffers.Offset, lastActivityUnix:bigint, vsAi:boolean):flatbuffers.Offset {
static createGameView(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset, variantOffset:flatbuffers.Offset, dictVersionOffset:flatbuffers.Offset, statusOffset:flatbuffers.Offset, players:number, toMove:number, turnTimeoutSecs:number, multipleWordsPerTurn:boolean, moveCount:number, endReasonOffset:flatbuffers.Offset, seatsOffset:flatbuffers.Offset, lastActivityUnix:bigint, vsAi:boolean, unreadChat:boolean):flatbuffers.Offset {
GameView.startGameView(builder);
GameView.addId(builder, idOffset);
GameView.addVariant(builder, variantOffset);
@@ -191,6 +200,7 @@ static createGameView(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset,
GameView.addSeats(builder, seatsOffset);
GameView.addLastActivityUnix(builder, lastActivityUnix);
GameView.addVsAi(builder, vsAi);
GameView.addUnreadChat(builder, unreadChat);
return GameView.endGameView(builder);
}
}
+36 -11
View File
@@ -61,8 +61,10 @@ export const app = $state<{
localeLocked: boolean;
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
notifications: number;
/** Unread chat-message count per game id, for the in-game score-bar and 💬 badges. */
chatUnread: Record<string, number>;
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
* game, for the lobby and in-game unread dot. Seeded from the authoritative REST views and
* raised by live chat/nudge events; cleared (with a backend ack) on opening the history/chat. */
chatUnread: Record<string, boolean>;
/** Whether an operator feedback reply awaits the player, for the lobby ⚙️ badge (combined
* with friend requests) and the Settings → Info badge. */
feedbackReplyUnread: boolean;
@@ -149,9 +151,29 @@ export function dismissStaleInvite(): void {
app.staleInvite = false;
}
/** clearChatUnread resets a game's unread chat-message count (called when its chat is opened). */
export function clearChatUnread(gameId: string): void {
if (app.chatUnread[gameId]) app.chatUnread = { ...app.chatUnread, [gameId]: 0 };
/**
* seedChatUnread sets a game's unread flag from an authoritative per-viewer REST view (the lobby
* list, a game's state, or a move result). The live-event GameView omits the flag, so the live
* stream raises unread (bumpChatUnread) rather than seeding it from a GameView.
*/
export function seedChatUnread(gameId: string, unread: boolean): void {
if ((app.chatUnread[gameId] ?? false) !== unread) {
app.chatUnread = { ...app.chatUnread, [gameId]: unread };
}
}
/**
* markChatRead clears a game's unread badge and tells the backend the player has read the chat —
* called when the move history or the chat opens. It hits the backend only when something is
* actually unread, so opening the history does not call the backend on every tap. The clear is
* optimistic; a failed ack restores the badge so a later open retries.
*/
export function markChatRead(gameId: string): void {
if (!app.chatUnread[gameId]) return;
app.chatUnread = { ...app.chatUnread, [gameId]: false };
void gateway.markChatRead(gameId).catch(() => {
app.chatUnread = { ...app.chatUnread, [gameId]: true };
});
}
/** handleError maps a GatewayError to a toast; an invalid session logs out. A connectivity
@@ -220,15 +242,18 @@ function openStream(): void {
(router.route.name === 'gameChat' || router.route.name === 'gameCheck') &&
router.route.params.id === e.message.gameId;
if (!inComms) {
if (e.message.kind !== 'nudge') {
const gid = e.message.gameId;
app.chatUnread = { ...app.chatUnread, [gid]: (app.chatUnread[gid] ?? 0) + 1 };
}
app.chatUnread = { ...app.chatUnread, [e.message.gameId]: true };
showToast(e.message.kind === 'nudge' ? t('chat.nudge') : e.message.body, 'info');
}
} else if (e.kind === 'nudge') {
// Name the nudger (their per-game seat name, carried on the event), so the toast reads
// "<opponent>: …" like the your-turn toast; fall back to the plain phrase when absent.
// A nudge only reaches the awaited player; raise their unread badge for the game (unless
// they are already in its chat), then toast — naming the nudger (their per-game seat name,
// carried on the event), so it reads "<opponent>: …" like the your-turn toast; fall back to
// the plain phrase when absent.
const inComms =
(router.route.name === 'gameChat' || router.route.name === 'gameCheck') &&
router.route.params.id === e.gameId;
if (!inComms) app.chatUnread = { ...app.chatUnread, [e.gameId]: true };
showToast(e.senderName ? t('chat.nudgeBy', { name: e.senderName }) : t('chat.nudge'), 'info');
} else if (e.kind === 'your_turn') {
// Name the player who moved just before this one (the previous seat in turn order), so the
+3
View File
@@ -102,6 +102,9 @@ export interface GatewayClient {
chatPost(gameId: string, body: string): Promise<ChatMessage>;
chatList(gameId: string): Promise<ChatMessage[]>;
nudge(gameId: string): Promise<ChatMessage>;
/** Acknowledge the caller has read the game's chat (sent when they open the move history
* or chat), so the backend clears their unread bits and records the read latency. */
markChatRead(gameId: string): Promise<void>;
// --- feedback ---
/** feedbackSubmit sends a feedback message with an optional single attachment. */
+2
View File
@@ -237,6 +237,7 @@ describe('codec', () => {
fb.GameView.addSeats(b, seats);
fb.GameView.addLastActivityUnix(b, BigInt(1717000000));
fb.GameView.addVsAi(b, true);
fb.GameView.addUnreadChat(b, true);
const game = fb.GameView.endGameView(b);
const games = fb.GameList.createGamesVector(b, [game]);
fb.GameList.startGameList(b);
@@ -251,6 +252,7 @@ describe('codec', () => {
expect(gl.games[0].seats[0].score).toBe(13);
expect(gl.games[0].lastActivityUnix).toBe(1717000000);
expect(gl.games[0].vsAi).toBe(true);
expect(gl.games[0].unreadChat).toBe(true);
expect(gl.atGameLimit).toBe(true);
});
+2
View File
@@ -248,6 +248,7 @@ function decodeGameView(g: fb.GameView): GameView {
endReason: s(g.endReason()),
lastActivityUnix: Number(g.lastActivityUnix()),
vsAi: g.vsAi(),
unreadChat: g.unreadChat(),
seats,
};
}
@@ -813,6 +814,7 @@ function emptyGame(): GameView {
endReason: '',
lastActivityUnix: 0,
vsAi: false,
unreadChat: false,
seats: [],
};
}
+1
View File
@@ -8,6 +8,7 @@ function gameView(id: string): GameView {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status: 'active',
players: 2,
toMove: 0,
+1
View File
@@ -9,6 +9,7 @@ function gameView(moveCount: number, over = false): GameView {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status: over ? 'finished' : 'active',
players: 2,
toMove: 1,
+1
View File
@@ -25,6 +25,7 @@ function gameView(id: string, status: GameView['status'] = 'active', toMove = 0)
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status,
players: 2,
toMove,
+1
View File
@@ -18,6 +18,7 @@ function game(id: string, status: GameView['status'], toMove: number, lastActivi
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status,
players: 2,
toMove,
+6
View File
@@ -180,6 +180,7 @@ export class MockGateway implements GatewayClient {
endReason: '',
lastActivityUnix: Math.floor(Date.now() / 1000),
vsAi: true,
unreadChat: false,
seats: [
{ seat: 0, accountId: ME, displayName: 'You', score: 0, hintsUsed: 0, isWinner: false },
{ seat: 1, accountId: 'robot', displayName: 'Robot', score: 0, hintsUsed: 0, isWinner: false },
@@ -211,6 +212,7 @@ export class MockGateway implements GatewayClient {
endReason: '',
lastActivityUnix: Math.floor(Date.now() / 1000),
vsAi: false,
unreadChat: false,
seats: [
{ seat: 0, accountId: ME, displayName: 'You', score: 0, hintsUsed: 0, isWinner: false },
{ seat: 1, accountId: '', displayName: '', score: 0, hintsUsed: 0, isWinner: false },
@@ -487,6 +489,10 @@ export class MockGateway implements GatewayClient {
this.feedbackReplyUnread = true;
this.emit({ kind: 'notify', sub: 'admin_reply' });
}
// The mock holds no server-side unread state; the read ack is a no-op (the client clears its
// own unread flag optimistically).
async markChatRead(): Promise<void> {}
async nudge(gameId: string): Promise<ChatMessage> {
const g = this.game(gameId);
const msg: ChatMessage = {
+3
View File
@@ -140,6 +140,7 @@ function activeGame(): MockGame {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status: 'active',
players: 2,
toMove: 0,
@@ -176,6 +177,7 @@ function finishedG2(): MockGame {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status: 'finished',
players: 2,
toMove: 0,
@@ -213,6 +215,7 @@ function finishedG3(): MockGame {
variant: 'scrabble_ru',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status: 'finished',
players: 2,
toMove: 0,
+4
View File
@@ -47,6 +47,10 @@ export interface GameView {
lastActivityUnix: number;
/** true = an honest-AI game: the opponent is shown as 🤖 and chat/nudge/add-friend are disabled. */
vsAi: boolean;
/** Per-viewer flag: the requesting player has at least one unread chat entry (message or
* nudge) in this game. Set on the authoritative REST views (lobby list, game state,
* move result); the live-event GameView leaves it false (events bump unread instead). */
unreadChat: boolean;
seats: Seat[];
}
+1
View File
@@ -20,6 +20,7 @@ function gameView(id: string, status: GameView['status'] = 'active'): GameView {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status,
players: 2,
toMove: 0,
+1
View File
@@ -17,6 +17,7 @@ function game(seats: Seat[], status = 'finished', toMove = 0): GameView {
variant: 'scrabble_en',
dictVersion: 'v1',
vsAi: false,
unreadChat: false,
status,
players: seats.length,
toMove,
+3
View File
@@ -143,6 +143,9 @@ export function createTransport(baseUrl: string): GatewayClient {
async nudge(id) {
return codec.decodeChatMessage(await exec('chat.nudge', codec.encodeGameAction(id)));
},
async markChatRead(id) {
await exec('chat.read', codec.encodeGameAction(id));
},
async feedbackSubmit(body, attachment, attachmentName, channel) {
await exec('feedback.submit', codec.encodeFeedbackSubmit(body, attachment, attachmentName, channel));
},
+22 -2
View File
@@ -3,7 +3,7 @@
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
import Screen from '../components/Screen.svelte';
import TabBar from '../components/TabBar.svelte';
import { app, handleError, refreshFeedbackBadge } from '../lib/app.svelte';
import { app, handleError, refreshFeedbackBadge, seedChatUnread } from '../lib/app.svelte';
import { connection } from '../lib/connection.svelte';
import { gateway } from '../lib/gateway';
import { navigate } from '../lib/router.svelte';
@@ -33,6 +33,9 @@
try {
const list = await gateway.gamesList();
games = list.games;
// Seed the per-game unread badges from the authoritative list. The live stream only raises
// unread (it never seeds it from a GameView), so a persisted unread survives a reload here.
for (const g of games) seedChatUnread(g.id, g.unreadChat);
atGameLimit = list.atGameLimit;
if (!guest) {
[invitations, incoming] = await Promise.all([gateway.invitationsList(), gateway.friendsIncoming()]);
@@ -262,7 +265,10 @@
onclick={() => openGame(g)}
>
<span class="info">
<span class="who">{opponents(g) || '—'}</span>
<span class="who">
<span class="who-name">{opponents(g) || '—'}</span>
{#if app.chatUnread[g.id]}<span class="unread-dot"></span>{/if}
</span>
<span class="sub">{scoreline(g)}</span>
</span>
<!-- Re-key on the per-card blink nonce so a repeat blink restarts the fade. -->
@@ -441,11 +447,25 @@
min-width: 0;
}
.who {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
font-weight: 600;
}
.who-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* A small red dot beside the opponent name: this game has an unread chat entry. */
.unread-dot {
flex: 0 0 auto;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--danger);
}
.sub {
font-size: 0.85rem;
color: var(--text-muted);