Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): reload the chat list once at a time

Yudhi Armyndharise6886ea32988
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index f14753beb..0697f1241 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -1115,7 +1115,7 @@ test('logging out sends no pending mark-as-read without a key', async () => {
assert.equal(await leaveWithPendingRead(true), 0, 'a keyless mark-as-read went out after logout');
});
-test('a reconnect refetch overtaken by a newer list still marks the open chat read', async () => {
+test('a reconnect that arrives while another reload is out is answered by the trailing one, which marks the open chat read', async () => {
const { screen, fireEvent, within, act, waitFor } = rtl;
const { container } = renderChats();
await screen.findByText('Main (15551234567)');
@@ -1124,48 +1124,41 @@ test('a reconnect refetch overtaken by a newer list still marks the open chat re
await new Promise(resolve => setTimeout(resolve, 1_000));
resetFetchCalls();
- // The reconnect refetch stays out while a live frame for an unlisted chat fires a second one, which
- // lands first. Both snapshots count Alice's gap messages, although her chat is open.
- const DAVE: Chat = { ...CHAT_2, id: '[email protected]', name: 'Dave', timestamp: 1_700_000_900 };
- const snapshot = [{ ...CHAT, unreadCount: 4, lastMessage: 'sent during the gap' }, CHAT_2, DAVE];
- let releaseFirst!: () => void;
- const firstGate = new Promise<void>(resolve => {
- releaseFirst = resolve;
- });
- let served = 0;
+ // An edit in a chat that was never opened reloads the list, and that reload stays out while the socket
+ // drops and reconnects, so the reconnect's own reload waits behind it. Both snapshots count Alice's gap
+ // messages, although her chat is open.
+ const snapshot = [{ ...CHAT, unreadCount: 4, lastMessage: 'sent during the gap' }, CHAT_2];
+ const answers: Array<() => void> = [];
chatsResponder = () =>
- ++served === 1 ? firstGate.then(() => jsonResponse(snapshot)) : Promise.resolve(jsonResponse(snapshot));
+ new Promise<Response>(resolve => {
+ answers.push(() => resolve(jsonResponse(snapshot)));
+ });
+ receiveEvent('message.edited', {
+ messageId: 'wamid.carol.1',
+ chatId: CHAT_2.id,
+ body: 'edited',
+ timestamp: 1_700_003_000,
+ });
+ await waitFor(() => assert.equal(answers.length, 1));
const socket = lastSocket();
assert.ok(socket, 'expected the page to have opened a socket');
act(() => socket.receive('disconnect', 'transport close'));
act(() => socket.receive('connect'));
- await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`), 1));
+ await flush();
+ assert.equal(answers.length, 1, 'the reconnect started a reload of its own while one was out');
- act(() =>
- socket.receive('message', {
- type: 'event',
- timestamp: new Date(1_700_002_000_000).toISOString(),
- payload: {
- event: 'message.received',
- sessionId: SESSION.id,
- data: {
- id: 'wamid.live.dave',
- chatId: DAVE.id,
- from: DAVE.id,
- to: 'me',
- body: 'dave says hi',
- type: 'text',
- fromMe: false,
- timestamp: 1_700_001_900,
- },
- },
- }),
- );
+ // The reload that was already out lands first. It began before the reconnect, so it is not the
+ // reconnect's answer and the open chat keeps the gap count for now.
+ answers[0]();
await screen.findByText('sent during the gap');
+ assert.ok(screen.queryByLabelText('4 unread messages'), 'a reload that began before the reconnect answered it');
+ await waitFor(() => assert.equal(answers.length, 2));
- releaseFirst();
+ answers[1]();
+ await waitFor(() =>
+ assert.ok(!screen.queryByLabelText('4 unread messages'), 'the open chat was badged with the gap count'),
+ );
await new Promise(resolve => setTimeout(resolve, 1_000));
- assert.ok(!screen.queryByLabelText('4 unread messages'), 'the open chat was badged with the gap count');
assert.ok(
fetchCalls.some(
c =>
@@ -1809,48 +1802,181 @@ test("a failed background refetch during a session switch keeps the spinner over
}
});
-test('a chat list refetch lands while a newer one is out, and an older answer never overwrites a newer', async () => {
- const { screen, waitFor } = rtl;
- const { container } = renderChats();
- await screen.findByText('Alice');
-
- // Edits to a chat that was never opened refetch the list each, and they arrive faster than it answers.
+// Answers every chat list request by hand, in the order asked. Each answer is a list led by Carol, whose
+// preview names the request it answers, so a test sees which one the sidebar shows.
+function holdChatLists(): Array<() => void> {
const answers: Array<() => void> = [];
chatsResponder = () =>
new Promise<Response>(resolve => {
const version = answers.length + 1;
answers.push(() => resolve(jsonResponse([{ ...CHAT_2, lastMessage: `carol v${version}` }, CHAT])));
});
- const socket = lastSocket();
- assert.ok(socket, 'expected the page to have opened a socket');
- const edit = (messageId: string): void =>
- socket.receive('message', {
- type: 'event',
- timestamp: new Date(1_700_003_000_000).toISOString(),
- payload: {
- event: 'message.edited',
- sessionId: SESSION.id,
- data: { messageId, chatId: CHAT_2.id, body: 'edited', timestamp: 1_700_003_000 },
- },
- });
- edit('wamid.carol.1');
- edit('wamid.carol.2');
- edit('wamid.carol.3');
- await waitFor(() => assert.equal(answers.length, 3));
- assert.ok(screen.queryByText('Alice'), 'a background refetch hid the chat list behind the loading spinner');
+ return answers;
+}
+
+// Two edits and a deletion in a chat that was never opened, and a message from a chat the sidebar does not
+// list: four events that each ask for a list reload.
+function askForReloads(): void {
+ const DAVE = '[email protected]';
+ for (const messageId of ['wamid.carol.1', 'wamid.carol.2']) {
+ receiveEvent('message.edited', { messageId, chatId: CHAT_2.id, body: 'edited', timestamp: 1_700_003_000 });
+ }
+ receiveEvent('message.revoked', {
+ id: 'wamid.carol.3',
+ revokedId: 'wamid.carol.3',
+ chatId: CHAT_2.id,
+ from: CHAT_2.id,
+ to: 'me',
+ body: '',
+ type: 'revoked',
+ timestamp: 1_700_003_000,
+ });
+ receiveEvent('message.received', {
+ id: 'wamid.dave.1',
+ chatId: DAVE,
+ from: DAVE,
+ to: 'me',
+ body: 'hi',
+ type: 'text',
+ fromMe: false,
+ timestamp: 1_700_003_000,
+ });
+}
+
+test('background reloads asked for while one is out share a single trailing reload', async () => {
+ const { screen, waitFor } = rtl;
+ renderChats();
+ await screen.findByText('Alice');
+ resetFetchCalls();
+ const chatsPath = `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`;
+ const answers = holdChatLists();
- // The first answer is the newest one applied so far, so it lands although newer calls are still out.
+ askForReloads();
+ await waitFor(() => assert.equal(answers.length, 1));
+ await flush();
+ await flush();
+ assert.equal(countFetchCalls('GET', chatsPath), 1, 'a trigger made while a reload was out started its own');
+ assert.ok(screen.queryByText('Alice'), 'a background reload hid the chat list behind the loading spinner');
+
+ // The reload that was out lands, and the three triggers it left waiting are answered by ONE more.
answers[0]();
await screen.findByText('carol v1');
- assert.equal(container.querySelector('.chats-list-loading') === null, true, 'the list stayed on the loading spinner');
+ await waitFor(() => assert.equal(answers.length, 2));
+ answers[1]();
+ await screen.findByText('carol v2');
+ await flush();
+ await flush();
+ assert.equal(countFetchCalls('GET', chatsPath), 2, 'the waiting triggers did not share one reload');
+});
+test('triggers made while the trailing reload is out queue one more behind it', async () => {
+ const { screen, waitFor } = rtl;
+ renderChats();
+ await screen.findByText('Alice');
+ resetFetchCalls();
+ const chatsPath = `/api/sessions/${SESSION.id}/chats?limit=1000&offset=0`;
+ const answers = holdChatLists();
+
+ askForReloads();
+ await waitFor(() => assert.equal(answers.length, 1));
+ answers[0]();
+ await waitFor(() => assert.equal(answers.length, 2));
+
+ // The trailing reload is the one out now, so these four wait for one more reload, not four.
+ askForReloads();
+ await flush();
+ await flush();
+ assert.equal(countFetchCalls('GET', chatsPath), 2);
+ answers[1]();
+ await waitFor(() => assert.equal(answers.length, 3));
answers[2]();
await screen.findByText('carol v3');
+ await flush();
+ await flush();
+ assert.equal(countFetchCalls('GET', chatsPath), 3);
+});
+
+test('a background reload that lands before the initial list is not overwritten by it', async () => {
+ const { screen, waitFor } = rtl;
+ const answers = holdChatLists();
+ const { container } = renderChats();
+ await screen.findByText('Main (15551234567)');
+ await waitFor(() => assert.equal(answers.length, 1));
+ assert.ok(container.querySelector('.chats-list-loading'), 'the initial list showed no spinner');
+
+ // The reload is a different kind of load from the one under the spinner, so it starts at once instead of
+ // waiting behind it, and whichever began later wins however the two land.
+ receiveEvent('message.edited', {
+ messageId: 'wamid.carol.1',
+ chatId: CHAT_2.id,
+ body: 'edited',
+ timestamp: 1_700_003_000,
+ });
+ await waitFor(() => assert.equal(answers.length, 2));
+
answers[1]();
await flush();
await flush();
- assert.ok(screen.queryByText('carol v3'), 'an older answer replaced the newer list');
- assert.ok(!screen.queryByText('carol v2'), 'an older answer replaced the newer list');
+ assert.ok(container.querySelector('.chats-list-loading'), 'a background reload cleared the initial list spinner');
+
+ answers[0]();
+ await screen.findByText('carol v2');
+ assert.ok(!screen.queryByText('carol v1'), 'the older initial answer replaced the newer list');
+ assert.equal(container.querySelector('.chats-list-loading') === null, true, 'the list stayed on the loading spinner');
+});
+
+test("a session switch drops the previous session's trailing reload and lets the new session reload at once", async () => {
+ const { screen, fireEvent, waitFor } = rtl;
+ twoSessions = true;
+ const asked = { one: 0, two: 0 };
+ const held: Array<() => void> = [];
+ let holdOne = false;
+ chatsResponder = sessionId => {
+ if (sessionId === SESSION_2.id) {
+ asked.two += 1;
+ return Promise.resolve(jsonResponse([{ ...CHAT_2, lastMessage: 'carol on two' }]));
+ }
+ asked.one += 1;
+ if (!holdOne) return Promise.resolve(jsonResponse([CHAT, CHAT_2]));
+ return new Promise<Response>(resolve => {
+ held.push(() => resolve(jsonResponse([{ ...CHAT, lastMessage: 'alice on one' }, CHAT_2])));
+ });
+ };
+ try {
+ const { container } = renderChats();
+ await screen.findByText('Alice');
+ holdOne = true;
+
+ // One reload is out for session 1 and a second trigger waits behind it.
+ for (const messageId of ['wamid.carol.1', 'wamid.carol.2']) {
+ receiveEvent('message.edited', { messageId, chatId: CHAT_2.id, body: 'edited', timestamp: 1_700_003_000 });
+ }
+ await waitFor(() => assert.equal(held.length, 1));
+ assert.equal(asked.one, 2);
+
+ fireEvent.change(container.querySelector('select.session-selector') as HTMLSelectElement, {
+ target: { value: SESSION_2.id },
+ });
+ await screen.findByText('carol on two');
+
+ // Session 2 is not queued behind the reload session 1 left out.
+ receiveEvent(
+ 'message.edited',
+ { messageId: 'wamid.carol.9', chatId: CHAT_2.id, body: 'edited', timestamp: 1 },
+ SESSION_2.id,
+ );
+ await waitFor(() => assert.equal(asked.two, 2));
+
+ held[0]();
+ await flush();
+ await flush();
+ await new Promise(resolve => setTimeout(resolve, 100));
+ assert.equal(asked.one, 2, 'the trailing reload of the session left behind started after the switch');
+ assert.ok(screen.queryByText('carol on two'), "the previous session's reload replaced the new session's list");
+ assert.ok(!screen.queryByText('alice on one'), "the previous session's list showed under the new session");
+ } finally {
+ twoSessions = false;
+ }
});
test('a failed background refetch keeps the chat list and raises no error', async () => {
@@ -2813,13 +2939,13 @@ test('a message sent while the first page is still loading survives the page lan
await waitFor(() => assert.equal(within(thread).queryAllByText('sent while loading').length, 1));
});
-function receiveEvent(event: string, data: Record<string, unknown>): void {
+function receiveEvent(event: string, data: Record<string, unknown>, sessionId: string = SESSION.id): void {
const socket = lastSocket();
assert.ok(socket, 'expected the page to have opened a socket');
socket.receive('message', {
type: 'event',
timestamp: new Date(1_700_003_000_000).toISOString(),
- payload: { event, sessionId: SESSION.id, data },
+ payload: { event, sessionId, data },
});
}
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index f9c30ecb8..83e5688f3 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -50,6 +50,7 @@ import { useChannelMessages } from '../hooks/useChannelMessages';
import { useContactStatuses } from '../hooks/useContactStatuses';
import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
import { createTrailingCoalescer } from '../utils/trailingCoalescer';
+import { createReloadCoalescer, type ReloadCoalescer } from '../utils/reloadCoalescer';
import MessageBody from '../components/chats/MessageBody';
import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';
import KindIcon from '../components/chats/KindIcon';
@@ -63,6 +64,10 @@ import './Chats.css';
// Quiet window for coalescing mark-as-read RPCs (see markReadCoalescer below).
const MARK_READ_DEBOUNCE_MS = 750;
+// Longest one background chat-list walk may take before it is abandoned. A walk is a dozen small requests, and
+// the gateway answers a stalled engine at 180 s, so this is far above a healthy walk and below that.
+const BACKGROUND_RELOAD_DEADLINE_MS = 120_000;
+
// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages
// so the WS append path and the ack path apply the exact same rule.
@@ -323,9 +328,16 @@ export function Chats() {
// with the browser clock, so only this, not a newer timestamp, shows a row changed after a refetch left.
const liveRowsRef = useRef(new Map<string, number>());
const loadChats = useCallback(
- async (sessionId: string, { background = false } = {}): Promise<boolean> => {
+ async (
+ sessionId: string,
+ { background = false, signal }: { background?: boolean; signal?: AbortSignal } = {},
+ ): Promise<boolean> => {
if (!sessionId) return false;
const controller = new AbortController();
+ // The caller's own deadline ends this load the way a session switch does.
+ const abortWithCaller = () => controller.abort();
+ if (signal?.aborted) abortWithCaller();
+ else signal?.addEventListener('abort', abortWithCaller, { once: true });
chatsLoadsRef.current.add(controller);
const request = ++chatsRequestRef.current;
chatsSessionRef.current = sessionId;
@@ -365,6 +377,7 @@ export function Chats() {
setChats([]);
return false;
} finally {
+ signal?.removeEventListener('abort', abortWithCaller);
chatsLoadsRef.current.delete(controller);
// Only the call that raised the spinner clears it: a background refetch settling first would
// otherwise uncover the previous session's list while the switch's own load is still out.
@@ -374,6 +387,29 @@ export function Chats() {
[showLoadError],
);
+ // A reload walks every page of the list, and each live event the sidebar cannot apply locally asks for
+ // one, so a burst of them must not start a walk apiece: per session one runs at a time and whatever
+ // arrives meanwhile shares a single trailing reload (utils/reloadCoalescer). Foreground loads stay out of
+ // it. The session effect below drops the trailing reload on a switch or unmount: started after one, it
+ // would point chatsSessionRef back at the session left and strand the new session's own list. A walk
+ // that never answers is abandoned at BACKGROUND_RELOAD_DEADLINE_MS, or every later trigger, the reconnect
+ // refresh included, would wait behind it.
+ const backgroundReloadsRef = useRef(new Map<string, ReloadCoalescer>());
+ const reloadChatsInBackground = useCallback(
+ (sessionId: string): Promise<boolean> => {
+ const reloads = backgroundReloadsRef.current;
+ let reload = reloads.get(sessionId);
+ if (!reload) {
+ reload = createReloadCoalescer(signal => loadChats(sessionId, { background: true, signal }), {
+ deadlineMs: BACKGROUND_RELOAD_DEADLINE_MS,
+ });
+ reloads.set(sessionId, reload);
+ }
+ return reload.run();
+ },
+ [loadChats],
+ );
+
// A send resolves after the await, possibly once another session's list is on screen. That list can
// hold a chat with the same id (a group or contact both accounts share), so the promote only applies
// to the session the send started in.
@@ -384,6 +420,7 @@ export function Chats() {
useEffect(() => {
const loads = chatsLoadsRef.current;
+ const reloads = backgroundReloadsRef.current;
if (selectedSessionId) {
void loadChats(selectedSessionId);
setActiveChat(null);
@@ -401,6 +438,7 @@ export function Chats() {
return () => {
for (const controller of loads) controller.abort();
loads.clear();
+ for (const reload of reloads.values()) reload.cancel();
};
}, [selectedSessionId, loadChats]);
@@ -518,14 +556,14 @@ export function Chats() {
const { needsSidebarRefetch } = applyIncomingToChatList(chatsRef.current, newMsg, listOptions);
setChats(prevChats => applyIncomingToChatList(prevChats, newMsg, listOptions).chats);
if (needsSidebarRefetch) {
- void loadChats(selectedSessionId, { background: true });
+ void reloadChatsInBackground(selectedSessionId);
}
},
[
selectedSessionId,
activeChat,
canWrite,
- loadChats,
+ reloadChatsInBackground,
markChatRead,
appendMessage,
onMessageAppended,
@@ -616,10 +654,10 @@ export function Chats() {
} else if (!matchedCachedMessage) {
// No cached thread proves whether the deleted message was the chat's newest; refresh the
// summaries, as an edit does.
- void loadChats(selectedSessionId, { background: true });
+ void reloadChatsInBackground(selectedSessionId);
}
},
- [selectedSessionId, queryClient, loadChats],
+ [selectedSessionId, queryClient, reloadChatsInBackground],
);
const handleIncomingMessageEdited = useCallback(
@@ -648,10 +686,10 @@ export function Chats() {
// The chat may never have been opened, so there is no message cache from which to prove
// whether this was its latest row. Refresh summaries instead of guessing and overwriting the
// sidebar with the body of an older edited message.
- void loadChats(selectedSessionId, { background: true });
+ void reloadChatsInBackground(selectedSessionId);
}
},
- [selectedSessionId, queryClient, loadChats],
+ [selectedSessionId, queryClient, reloadChatsInBackground],
);
// A contact's new story lands here instead of in the message pipeline; invalidate the statuses
@@ -712,18 +750,27 @@ export function Chats() {
// The open chat's gap messages are read on screen, so once the refetch has applied this session's
// list and the chat is still open, mark it read and zero its row, since the snapshot still counts
// them (the same rule a live frame and opening a chat follow). An applied list also means the engine
- // answers again: after a backend restart it may still be starting, and a read sent then fails. A
- // newer list for this session that overtook the refetch counts as applied. A refetch that failed
- // with no newer list applied, or a session switch, sends nothing; a chat the user left keeps its
+ // answers again: after a backend restart it may still be starting, and a read sent then fails. When
+ // another reload is already out, this call is answered by the trailing one, which starts after the
+ // gap. A refetch that failed, or a session switch, sends nothing; a chat the user left keeps its
// count.
const readChatId = canWrite ? activeChatId : undefined;
- void loadChats(selectedSessionId, { background: true }).then(applied => {
+ void reloadChatsInBackground(selectedSessionId).then(applied => {
if (!applied || !readChatId || activeChatIdRef.current !== readChatId) return;
markChatRead(readChatId);
setChats(prev => prev.map(c => (c.id === readChatId ? { ...c, unreadCount: 0 } : c)));
});
}
- }, [isConnected, connectionFailed, selectedSessionId, queryClient, loadChats, activeChatId, canWrite, markChatRead]);
+ }, [
+ isConnected,
+ connectionFailed,
+ selectedSessionId,
+ queryClient,
+ reloadChatsInBackground,
+ activeChatId,
+ canWrite,
+ markChatRead,
+ ]);
// The threads cache at staleTime: Infinity, and this session's events were not delivered while
// another session was selected or the page was away. Mark them stale on a mount or a session switch
diff --git a/dashboard/src/utils/reloadCoalescer.test.ts b/dashboard/src/utils/reloadCoalescer.test.ts
new file mode 100644
index 000000000..d5b29945e
--- /dev/null
+++ b/dashboard/src/utils/reloadCoalescer.test.ts
@@ -0,0 +1,222 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createReloadCoalescer } from './reloadCoalescer.ts';
+
+// A reload the test settles by hand, in the order it was started.
+function manualReloads() {
+ const out: Array<{ resolve: (applied: boolean) => void; reject: (err: unknown) => void }> = [];
+ const reload = () =>
+ new Promise<boolean>((resolve, reject) => {
+ out.push({ resolve, reject });
+ });
+ return { reload, out };
+}
+
+const settled = () => new Promise<void>(resolve => setImmediate(resolve));
+
+test('a call with no reload out starts one at once and gets its result', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ const result = coalescer.run();
+ assert.equal(out.length, 1);
+ out[0].resolve(true);
+ assert.equal(await result, true);
+});
+
+test('calls made while a reload is out share one trailing reload that starts after it settles', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ const first = coalescer.run();
+ const absorbed = [coalescer.run(), coalescer.run(), coalescer.run(), coalescer.run()];
+ assert.equal(out.length, 1, 'a call made while a reload was out started its own');
+
+ out[0].resolve(false);
+ assert.equal(await first, false);
+ await settled();
+ assert.equal(out.length, 2, 'the trailing reload did not start');
+
+ // Every absorbed caller is answered by the trailing reload, not by the one that was out before it.
+ out[1].resolve(true);
+ assert.deepEqual(await Promise.all(absorbed), [true, true, true, true]);
+ await settled();
+ assert.equal(out.length, 2);
+});
+
+test('a call made while the trailing reload runs queues exactly one more', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ void coalescer.run();
+ void coalescer.run();
+ out[0].resolve(true);
+ await settled();
+ assert.equal(out.length, 2);
+
+ const queued = [coalescer.run(), coalescer.run()];
+ assert.equal(out.length, 2);
+ out[1].resolve(true);
+ await settled();
+ assert.equal(out.length, 3);
+ out[2].resolve(false);
+ assert.deepEqual(await Promise.all(queued), [false, false]);
+});
+
+test('once everything has settled the next call starts a reload at once', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ void coalescer.run();
+ out[0].resolve(true);
+ await settled();
+ void coalescer.run();
+ assert.equal(out.length, 2);
+});
+
+test('cancel settles the callers waiting on the trailing reload with false and starts no second reload', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ const first = coalescer.run();
+ const absorbed = [coalescer.run(), coalescer.run()];
+ coalescer.cancel();
+ assert.deepEqual(await Promise.all(absorbed), [false, false]);
+
+ out[0].resolve(true);
+ assert.equal(await first, true);
+ await settled();
+ assert.equal(out.length, 1, 'a cancelled trailing reload started');
+});
+
+test('the coalescer keeps working after a cancel', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ void coalescer.run();
+ coalescer.cancel();
+ out[0].resolve(true);
+ await settled();
+
+ const result = coalescer.run();
+ assert.equal(out.length, 2, 'a call after a cancel did not run');
+ out[1].resolve(true);
+ assert.equal(await result, true);
+});
+
+test('a call made after a cancel, while the old reload is still out, trails it', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ void coalescer.run();
+ coalescer.cancel();
+ const later = coalescer.run();
+ assert.equal(out.length, 1);
+ out[0].resolve(false);
+ await settled();
+ assert.equal(out.length, 2);
+ out[1].resolve(true);
+ assert.equal(await later, true);
+});
+
+test('a reload that rejects releases the trailing reload and still answers its own caller', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ const first = coalescer.run();
+ const absorbed = coalescer.run();
+ out[0].reject(new Error('boom'));
+ await assert.rejects(first, /boom/);
+ await settled();
+ assert.equal(out.length, 2, 'a failed reload starved the trailing one');
+ out[1].resolve(true);
+ assert.equal(await absorbed, true);
+
+ await settled();
+ void coalescer.run();
+ assert.equal(out.length, 3, 'the slot stayed taken after a failure');
+});
+
+test('a trailing reload that rejects rejects its callers and frees the slot', async () => {
+ const { reload, out } = manualReloads();
+ const coalescer = createReloadCoalescer(reload);
+ void coalescer.run();
+ const absorbed = coalescer.run();
+ out[0].resolve(true);
+ await settled();
+ out[1].reject(new Error('boom'));
+ await assert.rejects(absorbed, /boom/);
+ await settled();
+ void coalescer.run();
+ assert.equal(out.length, 3);
+});
+
+test('a reload that throws before returning a promise counts as a failure', async () => {
+ let calls = 0;
+ const coalescer = createReloadCoalescer(() => {
+ calls += 1;
+ throw new Error('sync boom');
+ });
+ await assert.rejects(coalescer.run(), /sync boom/);
+ await settled();
+ await assert.rejects(coalescer.run(), /sync boom/);
+ assert.equal(calls, 2);
+});
+
+// A reload that records the signal it was handed, settled by hand like manualReloads.
+function signalledReloads() {
+ const out: Array<{ signal: AbortSignal; resolve: (applied: boolean) => void }> = [];
+ const reload = (signal: AbortSignal) =>
+ new Promise<boolean>(resolve => {
+ out.push({ signal, resolve });
+ });
+ return { reload, out };
+}
+
+test('a reload that outlasts its deadline is abandoned: its signal aborts and the next call starts a new one', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { reload, out } = signalledReloads();
+ const coalescer = createReloadCoalescer(reload, { deadlineMs: 1_000 });
+ const stuck = coalescer.run();
+ t.mock.timers.tick(999);
+ assert.equal(out[0].signal.aborted, false);
+
+ t.mock.timers.tick(1);
+ assert.equal(await stuck, false);
+ assert.equal(out[0].signal.aborted, true);
+ await settled();
+
+ const next = coalescer.run();
+ assert.equal(out.length, 2, 'a call after the deadline waited behind the abandoned reload');
+ out[1].resolve(true);
+ assert.equal(await next, true);
+});
+
+test('the trailing reload behind a stuck one starts when the stuck one is abandoned', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { reload, out } = signalledReloads();
+ const coalescer = createReloadCoalescer(reload, { deadlineMs: 1_000 });
+ const stuck = coalescer.run();
+ const waiting = [coalescer.run(), coalescer.run()];
+ assert.equal(out.length, 1);
+
+ t.mock.timers.tick(1_000);
+ assert.equal(await stuck, false);
+ await settled();
+ assert.equal(out.length, 2, 'the trailing reload stayed behind the abandoned one');
+ out[1].resolve(true);
+ assert.deepEqual(await Promise.all(waiting), [true, true]);
+
+ // What the abandoned reload answers later changes nothing.
+ out[0].resolve(true);
+ await settled();
+ assert.equal(out.length, 2);
+});
+
+test('a reload that answers in time is not aborted and leaves no deadline behind', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { reload, out } = signalledReloads();
+ const coalescer = createReloadCoalescer(reload, { deadlineMs: 1_000 });
+ const result = coalescer.run();
+ t.mock.timers.tick(500);
+ out[0].resolve(true);
+ assert.equal(await result, true);
+
+ t.mock.timers.tick(10_000);
+ assert.equal(out[0].signal.aborted, false);
+ await settled();
+ void coalescer.run();
+ assert.equal(out.length, 2);
+});
diff --git a/dashboard/src/utils/reloadCoalescer.ts b/dashboard/src/utils/reloadCoalescer.ts
new file mode 100644
index 000000000..71e923657
--- /dev/null
+++ b/dashboard/src/utils/reloadCoalescer.ts
@@ -0,0 +1,91 @@
+// Single-flight reloads with one trailing run: while a reload is out, every call shares ONE follow-up
+// reload that starts when it settles, so a burst of triggers costs two reloads instead of one each.
+//
+// Used for the chat-list refetch. A reload walks every page of the list, and each live event the sidebar
+// cannot apply locally asks for one. A caller gets the result of the run that serves IT: a call made while
+// a reload is out waits for the trailing run, which starts after the call, so what it reads includes
+// whatever raised the call.
+//
+// `cancel()` drops the trailing run that has not started (its session was left) and settles that run's
+// callers with `false`. The run already out is the owner's to abort. The coalescer stays usable after a
+// cancel, because React replays effect cleanups in StrictMode.
+//
+// A reload that never answers (a connection that went half-open) would hold every later call behind it, so
+// a run can be given a deadline: at the deadline the signal handed to the reload is aborted, the run settles
+// with `false` and the trailing run, if any, starts.
+
+export interface ReloadCoalescer {
+ run(): Promise<boolean>;
+ cancel(): void;
+}
+
+export interface ReloadCoalescerOptions {
+ /** How long one run may take before it is abandoned. No deadline when omitted. */
+ deadlineMs?: number;
+}
+
+interface Trailing {
+ promise: Promise<boolean>;
+ settle: (result: boolean | PromiseLike<boolean>) => void;
+}
+
+export function createReloadCoalescer(
+ reload: (signal: AbortSignal) => Promise<boolean>,
+ { deadlineMs }: ReloadCoalescerOptions = {},
+): ReloadCoalescer {
+ let running = false;
+ let trailing: Trailing | null = null;
+
+ const start = (): Promise<boolean> => {
+ running = true;
+ const controller = new AbortController();
+ const current = new Promise<boolean>((resolve, reject) => {
+ const timer =
+ deadlineMs === undefined
+ ? undefined
+ : setTimeout(() => {
+ controller.abort();
+ resolve(false);
+ }, deadlineMs);
+ // A pending deadline must not keep a Node process open (the unit tests); a browser timer is a number.
+ if (typeof timer === 'object') (timer as { unref?: () => void }).unref?.();
+ new Promise<boolean>(started => started(reload(controller.signal))).then(
+ result => {
+ clearTimeout(timer);
+ resolve(result);
+ },
+ (error: unknown) => {
+ clearTimeout(timer);
+ reject(error instanceof Error ? error : new Error(String(error)));
+ },
+ );
+ });
+ // Both outcomes release the slot, or one failed reload would starve every later call.
+ const release = () => {
+ const queued = trailing;
+ trailing = null;
+ if (queued) queued.settle(start());
+ else running = false;
+ };
+ current.then(release, release);
+ return current;
+ };
+
+ return {
+ run() {
+ if (!running) return start();
+ if (!trailing) {
+ let settle!: Trailing['settle'];
+ const promise = new Promise<boolean>(resolve => {
+ settle = resolve;
+ });
+ trailing = { promise, settle };
+ }
+ return trailing.promise;
+ },
+ cancel() {
+ trailing?.settle(false);
+ trailing = null;
+ },
+ };
+}