Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): clear cached state on logout and harden realtime/auth edge cases (#938)

Yudhi Armyndharisef34c69b77e2
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index b32e1a952..70ff83f17 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, Suspense } from 'react';
+import { useState, useEffect, useCallback, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { lazyWithRetry as lazy } from './utils/lazyWithRetry';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -8,6 +8,7 @@ import { ToastProvider } from './components/Toast';
import { RoleProvider, useRole, type UserRole } from './hooks/useRole';
import { ErrorBoundary } from './components/ErrorBoundary';
import { API_BASE_URL } from './services/api';
+import { clearActorState, resolveStartupValidation } from './utils/authLifecycle';
import './App.css';
const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login })));
@@ -61,14 +62,18 @@ function AppContent() {
setIsAuthenticated(true);
};
- const handleLogout = () => {
+ const handleLogout = useCallback(() => {
setApiKey('');
setIsAuthenticated(false);
setRole(null);
sessionStorage.removeItem('openwa_api_key');
- };
+ // Wipe the React Query cache too: it is keyed by resource, not actor, so without a full
+ // clear a logout → login in the same tab with a different key/scope shows the previous
+ // actor's sessions/messages/apiKeys/audit rows.
+ clearActorState(queryClient);
+ }, [setRole]);
- // Re-validate and get role on mount if already authenticated
+ // Re-validate and refresh the role on mount if already authenticated
useEffect(() => {
if (!savedKey) return;
@@ -76,16 +81,19 @@ function AppContent() {
method: 'POST',
headers: { 'X-API-Key': savedKey },
})
- .then(res => res.json())
- .then(data => {
- if (data.valid && data.role) {
- setRole(data.role as UserRole);
+ .then(async res => {
+ const decision = resolveStartupValidation(res.ok, await res.json().catch(() => null));
+ if (decision.action === 'logout') {
+ handleLogout();
+ } else if (decision.action === 'role') {
+ setRole(decision.role);
}
})
.catch(() => {
- // Keep existing role from localStorage if validation fails
+ // Network failure (API unreachable): keep the cached role so a transient outage at
+ // page load doesn't eject the user — an explicit non-ok answer above still logs out.
});
- }, [savedKey, setRole]);
+ }, [savedKey, setRole, handleLogout]);
const loadingFallback = (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.ts
index 09ca9b42a..b8ff45d35 100644
--- a/dashboard/src/hooks/useWebSocket.ts
+++ b/dashboard/src/hooks/useWebSocket.ts
@@ -71,6 +71,18 @@ interface StatusReceivedEvent {
timestamp: string;
}
+/** Ack frame answering a client `subscribe` request (`{type: 'subscribed'}`). */
+interface SubscribedEvent {
+ sessionId: string;
+ events: string[];
+}
+
+/** Error frame answering a client request (`{type: 'error'}`), e.g. FORBIDDEN_SESSION. */
+interface ServerErrorEvent {
+ code: string;
+ message: string;
+}
+
interface WebSocketEvents {
onSessionStatus?: (event: SessionStatusEvent) => void;
onQRCode?: (event: QRCodeEvent) => void;
@@ -80,11 +92,14 @@ interface WebSocketEvents {
onMessageRevoked?: (event: MessageRevokedEvent) => void;
onMessageEdited?: (event: MessageEditedEvent) => void;
onStatusReceived?: (event: StatusReceivedEvent) => void;
+ onSubscribed?: (event: SubscribedEvent) => void;
+ onServerError?: (event: ServerErrorEvent) => void;
}
// Shape of the server -> client event envelope produced by the NestJS gateway.
+// `type` is the 'event' literal so the frame union below narrows on it.
interface ServerEventEnvelope {
- type: string;
+ type: 'event';
timestamp: string;
payload?: {
event: string;
@@ -93,6 +108,22 @@ interface ServerEventEnvelope {
};
}
+// The gateway also answers client requests (subscribe/unsubscribe/ping) with ack frames
+// (`subscribed` / `unsubscribed` / `pong`) and error frames (`error`) on the same 'message'
+// channel. Routing them to the UI matters: a scoped key's rejected wildcard subscribe must be
+// visible so the caller can fall back to per-session rooms instead of waiting forever.
+interface ServerAckFrame {
+ type: 'subscribed' | 'unsubscribed' | 'pong';
+ sessionId?: string;
+ events?: string[];
+}
+
+interface ServerErrorFrame {
+ type: 'error';
+ code?: string;
+ message?: string;
+}
+
// Use current origin for WebSocket (goes through nginx proxy in Docker)
// Falls back to env var or localhost for development
const SOCKET_URL = import.meta.env.VITE_WS_URL || window.location.origin;
@@ -198,8 +229,21 @@ export function useWebSocket(events: WebSocketEvents = {}) {
const socket = socketRef.current;
- const handleIncomingMessage = (msg: ServerEventEnvelope) => {
- if (!msg || msg.type !== 'event' || !msg.payload) return;
+ const handleIncomingMessage = (msg: ServerEventEnvelope | ServerAckFrame | ServerErrorFrame) => {
+ if (!msg || typeof msg.type !== 'string') return;
+
+ if (msg.type === 'error') {
+ events.onServerError?.({ code: String(msg.code ?? ''), message: String(msg.message ?? '') });
+ return;
+ }
+ if (msg.type === 'subscribed') {
+ events.onSubscribed?.({
+ sessionId: String(msg.sessionId ?? ''),
+ events: Array.isArray(msg.events) ? msg.events : [],
+ });
+ return;
+ }
+ if (msg.type !== 'event' || !msg.payload) return;
const { event, sessionId, data } = msg.payload;
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 969dd0d06..47a49c953 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -58,10 +58,14 @@ import { useChannelMessages } from '../hooks/useChannelMessages';
import { useContactStatuses } from '../hooks/useContactStatuses';
import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
import { useCurrentEngineQuery } from '../hooks/queries';
+import { createTrailingCoalescer } from '../utils/trailingCoalescer';
import MessageBody from '../components/chats/MessageBody';
import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';
import './Chats.css';
+// Quiet window for coalescing mark-as-read RPCs (see markReadCoalescer below).
+const MARK_READ_DEBOUNCE_MS = 750;
+
type MessageMedia = { mimetype: string; filename?: string; data?: string; omitted?: boolean; sizeBytes?: number };
// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages
@@ -585,13 +589,28 @@ export function Chats() {
return () => URL.revokeObjectURL(previewUrl);
}, [previewUrl]);
+ // Coalesce mark-as-read RPCs per chat: every incoming message in the visible chat raises a
+ // read event, and a per-event POST sprays the gateway into 429s. One trailing call per chat
+ // after a quiet window carries the same effect.
+ const markReadCoalescer = useMemo(
+ () =>
+ createTrailingCoalescer<string>(chatId => {
+ void sessionApi.markChatRead(selectedSessionId, chatId).catch(err => {
+ showWarningToast(t('chats.errors.markRead'), err instanceof Error ? err.message : undefined);
+ });
+ }, MARK_READ_DEBOUNCE_MS),
+ [selectedSessionId, t, showWarningToast],
+ );
+
+ // Drop pending trailing calls on unmount / session switch so a late fire never targets an
+ // unmounted component or the previous session.
+ useEffect(() => () => markReadCoalescer.cancel(), [markReadCoalescer]);
+
const markChatRead = useCallback(
(chatId: string) => {
- void sessionApi.markChatRead(selectedSessionId, chatId).catch(err => {
- showWarningToast(t('chats.errors.markRead'), err instanceof Error ? err.message : undefined);
- });
+ markReadCoalescer.call(chatId);
},
- [selectedSessionId, t, showWarningToast],
+ [markReadCoalescer],
);
// 3. WebSocket integration for real-time messages
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index 33fb7aa1e..c274adc33 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -8,6 +8,11 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useToast } from '../components/Toast';
import { useWebSocket } from '../hooks/useWebSocket';
import { useRole } from '../hooks/useRole';
+import {
+ createSessionFeedState,
+ noteSessionFeedError,
+ subscribeSessionFeed,
+} from '../utils/sessionFeedSubscription';
import { PageHeader } from '../components/PageHeader';
import { CustomSelect } from '../components/CustomSelect';
import { Modal } from '../components/Modal';
@@ -67,6 +72,12 @@ export function Sessions() {
sessionsRef.current = sessions;
}, [sessions]);
+ // Live session-feed subscription state: wildcard first, per-session fallback for scoped keys.
+ const feedStateRef = useRef(createSessionFeedState());
+ // Most recent server error frame; folded into feedStateRef by the effect below (kept as state
+ // so the fallback runs after `subscribe` exists — the handler can't reference it directly).
+ const [feedErrorFrame, setFeedErrorFrame] = useState<{ code: string } | null>(null);
+
const { isConnected, subscribe } = useWebSocket({
onQRCode: useCallback((event: { sessionId: string; qrCode: string }) => {
// Fill the open QR modal straight from the push — the REST endpoint 400s BY DESIGN until a QR
@@ -96,16 +107,36 @@ export function Sessions() {
},
[toast, t, fetchSessions],
),
+ onServerError: useCallback((frame: { code: string }) => {
+ setFeedErrorFrame(frame);
+ }, []),
});
- // The gateway delivers events only to subscribed rooms; join the wildcard
- // session.status room so status changes for every session are received live.
+ // Fold a server error frame into the feed state: a session-scoped key may not join the '*'
+ // room — silently fall back to one subscription per listed session (the list endpoint is
+ // already scope-filtered server-side), otherwise no status/QR push ever arrives and the QR
+ // modal sits on "generating" forever.
+ useEffect(() => {
+ if (!feedErrorFrame) return;
+ if (noteSessionFeedError(feedStateRef.current, feedErrorFrame.code)) {
+ subscribeSessionFeed({ subscribe }, feedStateRef.current, sessionsRef.current.map(s => s.id));
+ }
+ }, [feedErrorFrame, subscribe]);
+
+ // Join the live session feed (wildcard attempt, or per-session rooms after a scope fallback).
useEffect(() => {
if (isConnected) {
- subscribe('*', ['session.status', 'session.qr']);
+ subscribeSessionFeed({ subscribe }, feedStateRef.current, sessionsRef.current.map(s => s.id));
}
}, [isConnected, subscribe]);
+ // In per-session mode, sessions loaded/created after the fallback still need their rooms.
+ useEffect(() => {
+ if (isConnected && feedStateRef.current.scope === 'per-session') {
+ subscribeSessionFeed({ subscribe }, feedStateRef.current, sessions.map(s => s.id));
+ }
+ }, [isConnected, sessions, subscribe]);
+
useEffect(() => {
fetchSessions();
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.ts
new file mode 100644
index 000000000..b26595a6f
--- /dev/null
+++ b/dashboard/src/utils/authLifecycle.test.ts
@@ -0,0 +1,42 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { QueryClient } from '@tanstack/react-query';
+import { clearActorState, resolveStartupValidation } from './authLifecycle.ts';
+
+test('logout cleanup wipes the React Query cache (no cross-actor residue)', () => {
+ const queryClient = new QueryClient();
+ queryClient.setQueryData(['sessions'], [{ id: 's1' }]);
+ queryClient.setQueryData(['apiKeys'], [{ id: 'k1' }]);
+ queryClient.setQueryData(['logs', { page: 1 }], [{ id: 'a1' }]);
+
+ clearActorState(queryClient);
+
+ assert.equal(queryClient.getQueryData(['sessions']), undefined);
+ assert.equal(queryClient.getQueryData(['apiKeys']), undefined);
+ assert.equal(queryClient.getQueryCache().getAll().length, 0);
+});
+
+test('logout cleanup calls clear() on every provided cache', () => {
+ const calls: string[] = [];
+ const cache = (name: string) => ({ clear: () => calls.push(name) });
+ clearActorState(cache('a'), cache('b'));
+ assert.deepEqual(calls, ['a', 'b']);
+});
+
+test('startup validation: non-ok response (revoked/demoted key) → logout', () => {
+ assert.deepEqual(resolveStartupValidation(false, null), { action: 'logout' });
+ assert.deepEqual(resolveStartupValidation(false, { valid: true, role: 'admin' }), { action: 'logout' });
+});
+
+test('startup validation: ok + role refreshes the cached role from the server', () => {
+ assert.deepEqual(resolveStartupValidation(true, { valid: true, role: 'viewer' }), {
+ action: 'role',
+ role: 'viewer',
+ });
+});
+
+test('startup validation: ok without a usable role keeps the cached role', () => {
+ assert.deepEqual(resolveStartupValidation(true, { valid: false }), { action: 'keep' });
+ assert.deepEqual(resolveStartupValidation(true, { valid: true, role: 'superuser' }), { action: 'keep' });
+ assert.deepEqual(resolveStartupValidation(true, null), { action: 'keep' });
+});
diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.ts
new file mode 100644
index 000000000..2cb4875ae
--- /dev/null
+++ b/dashboard/src/utils/authLifecycle.ts
@@ -0,0 +1,45 @@
+// Auth-lifecycle helpers: logout cleanup and startup re-validation decisions.
+
+import type { UserRole } from '../types/role';
+
+const USER_ROLES: readonly UserRole[] = ['admin', 'operator', 'viewer'];
+
+function isUserRole(value: unknown): value is UserRole {
+ return typeof value === 'string' && (USER_ROLES as readonly string[]).includes(value);
+}
+
+/** Structural cache surface (a TanStack QueryClient satisfies this) so tests can use a stub. */
+export interface ClearableCache {
+ clear(): void;
+}
+
+/**
+ * Drop every piece of actor-scoped cached state on logout. The React Query cache is keyed by
+ * resource, not by actor — without a full clear, logout → login in the same tab with a
+ * different key/scope renders the previous actor's sessions/messages/apiKeys/audit rows.
+ */
+export function clearActorState(...caches: ClearableCache[]): void {
+ for (const cache of caches) cache.clear();
+}
+
+export type StartupValidation =
+ | { action: 'role'; role: UserRole }
+ | { action: 'logout' }
+ | { action: 'keep' };
+
+/**
+ * Fold the startup /auth/validate answer into an auth decision:
+ * - non-ok (401 for a revoked/deleted/expired key) → full logout; the cached role is a lie.
+ * - ok + role → refresh the cached role from the server (a demoted key must lose its old powers).
+ * - anything else (unexpected body shape) → keep the cached role.
+ * A network throw never reaches this function; the caller keeps the cached role for that case
+ * so a transient outage at page load doesn't eject the user.
+ */
+export function resolveStartupValidation(
+ ok: boolean,
+ body: { valid?: boolean; role?: string } | null,
+): StartupValidation {
+ if (!ok) return { action: 'logout' };
+ if (body?.valid && isUserRole(body.role)) return { action: 'role', role: body.role };
+ return { action: 'keep' };
+}
diff --git a/dashboard/src/utils/sessionFeedSubscription.test.ts b/dashboard/src/utils/sessionFeedSubscription.test.ts
new file mode 100644
index 000000000..320c19ccf
--- /dev/null
+++ b/dashboard/src/utils/sessionFeedSubscription.test.ts
@@ -0,0 +1,80 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ SESSION_FEED_EVENTS,
+ createSessionFeedState,
+ noteSessionFeedError,
+ subscribeSessionFeed,
+} from './sessionFeedSubscription.ts';
+
+interface SentSubscribe {
+ sessionId: string;
+ events: string[];
+}
+
+// Minimal socket stand-in capturing subscribe emissions.
+function mockSink() {
+ const sent: SentSubscribe[] = [];
+ return {
+ sent,
+ subscribe(sessionId: string, events: string[]) {
+ sent.push({ sessionId, events });
+ },
+ };
+}
+
+test('unrestricted path subscribes the wildcard room once', () => {
+ const sink = mockSink();
+ const state = createSessionFeedState();
+ subscribeSessionFeed(sink, state, ['s1', 's2']);
+ assert.deepEqual(sink.sent, [{ sessionId: '*', events: [...SESSION_FEED_EVENTS] }]);
+});
+
+test('FORBIDDEN_SESSION error frame triggers the per-session fallback (scoped key)', () => {
+ const sink = mockSink();
+ const state = createSessionFeedState();
+
+ // Wildcard attempt, answered by the gateway with a scope rejection.
+ subscribeSessionFeed(sink, state, ['s1', 's2']);
+ assert.equal(noteSessionFeedError(state, 'FORBIDDEN_SESSION'), true);
+ subscribeSessionFeed(sink, state, ['s1', 's2']);
+
+ assert.deepEqual(
+ sink.sent.map(m => m.sessionId),
+ ['*', 's1', 's2'],
+ );
+ assert.deepEqual(sink.sent[1].events, [...SESSION_FEED_EVENTS]);
+});
+
+test('fallback is silent for unrelated errors and fires only once', () => {
+ const sink = mockSink();
+ const state = createSessionFeedState();
+ subscribeSessionFeed(sink, state, ['s1']);
+
+ assert.equal(noteSessionFeedError(state, 'UNAUTHORIZED'), false);
+ assert.equal(noteSessionFeedError(state, 'FORBIDDEN_SESSION'), true);
+ // A duplicate rejection after the fallback must not re-trigger or re-subscribe.
+ assert.equal(noteSessionFeedError(state, 'FORBIDDEN_SESSION'), false);
+
+ subscribeSessionFeed(sink, state, ['s1']);
+ subscribeSessionFeed(sink, state, ['s1']);
+ assert.deepEqual(
+ sink.sent.map(m => m.sessionId),
+ ['*', 's1'],
+ );
+});
+
+test('per-session mode subscribes only newly listed sessions (e.g. created after fallback)', () => {
+ const sink = mockSink();
+ const state = createSessionFeedState();
+ subscribeSessionFeed(sink, state, []);
+ noteSessionFeedError(state, 'FORBIDDEN_SESSION');
+
+ subscribeSessionFeed(sink, state, ['s1']);
+ subscribeSessionFeed(sink, state, ['s1', 's2']);
+
+ assert.deepEqual(
+ sink.sent.map(m => m.sessionId),
+ ['*', 's1', 's2'],
+ );
+});
diff --git a/dashboard/src/utils/sessionFeedSubscription.ts b/dashboard/src/utils/sessionFeedSubscription.ts
new file mode 100644
index 000000000..9ec0354ea
--- /dev/null
+++ b/dashboard/src/utils/sessionFeedSubscription.ts
@@ -0,0 +1,46 @@
+// Live session-feed (session.status / session.qr) subscription with scoped-key fallback.
+//
+// The dashboard first tries the '*' wildcard room — one round trip covering every session.
+// A session-scoped API key is NOT allowed to join '*' (the gateway answers with a
+// FORBIDDEN_SESSION error frame instead of an ack), so the client silently falls back to
+// one subscription per visible session. The sessions list endpoint is already scope-filtered
+// server-side, so every listed session is joinable.
+
+export const SESSION_FEED_EVENTS = ['session.status', 'session.qr'] as const;
+
+export interface SessionFeedSink {
+ subscribe(sessionId: string, events: string[]): void;
+}
+
+export interface SessionFeedState {
+ scope: 'wildcard' | 'per-session';
+ /** Session ids already subscribed in per-session mode, so list updates don't re-emit. */
+ subscribedIds: Set<string>;
+}
+
+export function createSessionFeedState(): SessionFeedState {
+ return { scope: 'wildcard', subscribedIds: new Set() };
+}
+
+export function subscribeSessionFeed(sink: SessionFeedSink, state: SessionFeedState, sessionIds: string[]): void {
+ if (state.scope === 'wildcard') {
+ sink.subscribe('*', [...SESSION_FEED_EVENTS]);
+ return;
+ }
+ for (const id of sessionIds) {
+ if (state.subscribedIds.has(id)) continue;
+ state.subscribedIds.add(id);
+ sink.subscribe(id, [...SESSION_FEED_EVENTS]);
+ }
+}
+
+/**
+ * Fold a server error frame into the feed state. Returns true exactly once — when the frame
+ * rejects the wildcard subscription on scope grounds — telling the caller to re-run
+ * subscribeSessionFeed (now per-session). Any other error, or a repeat, leaves state alone.
+ */
+export function noteSessionFeedError(state: SessionFeedState, code: string): boolean {
+ if (state.scope !== 'wildcard' || code !== 'FORBIDDEN_SESSION') return false;
+ state.scope = 'per-session';
+ return true;
+}
diff --git a/dashboard/src/utils/trailingCoalescer.test.ts b/dashboard/src/utils/trailingCoalescer.test.ts
new file mode 100644
index 000000000..36950a9d9
--- /dev/null
+++ b/dashboard/src/utils/trailingCoalescer.test.ts
@@ -0,0 +1,62 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createTrailingCoalescer } from './trailingCoalescer.ts';
+
+test('a burst of events for one key collapses into a single trailing request', t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sent: string[] = [];
+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);
+
+ coalescer.call('chat-A');
+ coalescer.call('chat-A');
+ coalescer.call('chat-A');
+ coalescer.call('chat-A');
+
+ t.mock.timers.tick(749);
+ assert.deepEqual(sent, []);
+ t.mock.timers.tick(1);
+ assert.deepEqual(sent, ['chat-A']);
+ coalescer.cancel();
+});
+
+test('the trailing call fires after the quiet window, not at burst time', t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sent: string[] = [];
+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);
+
+ coalescer.call('chat-A');
+ t.mock.timers.tick(400);
+ coalescer.call('chat-A'); // restarts the quiet window
+ t.mock.timers.tick(400);
+ assert.deepEqual(sent, []);
+ t.mock.timers.tick(350);
+ assert.deepEqual(sent, ['chat-A']);
+ coalescer.cancel();
+});
+
+test('different keys coalesce independently', t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sent: string[] = [];
+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);
+
+ coalescer.call('chat-A');
+ coalescer.call('chat-B');
+ coalescer.call('chat-A');
+
+ t.mock.timers.tick(750);
+ assert.deepEqual(sent.sort(), ['chat-A', 'chat-B']);
+ coalescer.cancel();
+});
+
+test('cancel() drops pending calls (unmount) so nothing fires late', t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sent: string[] = [];
+ const coalescer = createTrailingCoalescer<string>(key => sent.push(key), 750);
+
+ coalescer.call('chat-A');
+ coalescer.call('chat-B');
+ coalescer.cancel();
+
+ t.mock.timers.tick(10_000);
+ assert.deepEqual(sent, []);
+});
diff --git a/dashboard/src/utils/trailingCoalescer.ts b/dashboard/src/utils/trailingCoalescer.ts
new file mode 100644
index 000000000..dced48960
--- /dev/null
+++ b/dashboard/src/utils/trailingCoalescer.ts
@@ -0,0 +1,33 @@
+// Per-key trailing coalescer: collapse a burst of calls for the same key into ONE invocation
+// fired after the key goes quiet for `delayMs`.
+//
+// Used for the mark-as-read RPC: every incoming message in the visible chat raises a read
+// event, and a per-event POST sprays the gateway into 429s. Keys are independent (each chat
+// gets its own quiet window), and `cancel()` drops every pending call so a late fire never
+// targets an unmounted component.
+
+export interface TrailingCoalescer<K> {
+ call(key: K): void;
+ cancel(): void;
+}
+
+export function createTrailingCoalescer<K>(send: (key: K) => void, delayMs: number): TrailingCoalescer<K> {
+ const timers = new Map<K, ReturnType<typeof setTimeout>>();
+ return {
+ call(key: K) {
+ const existing = timers.get(key);
+ if (existing !== undefined) clearTimeout(existing);
+ timers.set(
+ key,
+ setTimeout(() => {
+ timers.delete(key);
+ send(key);
+ }, delayMs),
+ );
+ },
+ cancel() {
+ for (const timer of timers.values()) clearTimeout(timer);
+ timers.clear();
+ },
+ };
+}