English
Stores that apply events
Step 1. The chat list follows the events
Why. The chat list must react to almost every event (Table 20.1). The store subscribes to the event stream once, in its constructor, and an apply(event) method with one switch handles them — the same pattern as a reducer: an event comes in, the state changes, the screen follows.
Table 20.1. How ChatsStore applies the hub events
| Event | Effect on the list |
|---|---|
messageCreated | the chat moves to the top with the new last message; the unread count grows, except for the user's own messages and for the open, visible chat; an unknown chat (someone started a direct chat with us) triggers a reload |
messageUpdated | the preview changes if it was the last message |
messageDeleted | the preview says "Message deleted" if it was the last message |
membersAdded | if the user was added: reload the list (a new chat); otherwise refresh the details of an opened chat (the member count) |
memberRemoved | if the user was removed: drop the chat and announce it on removed; otherwise refresh the details |
chatUpdated | forget the cached chat avatar and reload the details (title, handle, roles) |
chatDeleted | drop the chat and announce it |
Do. Complete ChatsStore (new lines in green). It is now final:
ts
import { Injectable, computed, effect, inject, signal } from '@angular/core';
import { Subject, firstValueFrom } from 'rxjs';
import { ChatsApi, avatarUrl } from '../core/api/chatex-api';
import { ChatDto, ChatListItemDto, LastMessageDto, MessageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
import { HubEvent, RealtimeService } from '../core/realtime/realtime.service';
/** A chat list row; `lastMessage.deleted` is set locally when the last message gets deleted. */
export type ChatListItem = ChatListItemDto & {
lastMessage?: (LastMessageDto & { deleted?: boolean; hasAttachments?: boolean }) | null;
};
const byActivity = (a: ChatListItem, b: ChatListItem) =>
a.lastActivityAt < b.lastActivityAt ? 1 : a.lastActivityAt > b.lastActivityAt ? -1 : 0;
/** The user's chats (most recently active first), kept current by hub events. */
@Injectable({ providedIn: 'root' })
export class ChatsStore {
private readonly api = inject(ChatsApi);
private readonly auth = inject(AuthService);
private readonly blobs = inject(BlobUrlService);
private nextCursor: string | null = null;
private reloadTimer: ReturnType<typeof setTimeout> | undefined;
readonly items = signal<ChatListItem[]>([]);
readonly loaded = signal(false);
readonly loading = signal(false);
readonly loadingMore = signal(false);
readonly hasMore = signal(false);
/** Full details of chats that were opened, by id. */
readonly details = signal<Readonly<Record<string, ChatDto>>>({});
/** The chat on screen; its new messages don't count as unread. */
readonly activeChatId = signal<string | null>(null);
/** Fires when the user loses access to a chat (deleted, removed, left). */
readonly removed = new Subject<string>();
readonly totalUnread = computed(() =>
this.items().reduce((sum, chat) => sum + (chat.isMuted ? 0 : chat.unreadCount), 0),
);
constructor() {
const realtime = inject(RealtimeService);
realtime.events.subscribe((event) => this.apply(event));
realtime.connected.subscribe(({ reconnected }) => {
if (reconnected && this.loaded()) {
void this.loadFirst();
}
});
effect(() => {
this.auth.sessionEpoch();
this.reset();
});
}
async loadFirst(): Promise<void> {
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list());
this.items.set([...page.items].sort(byActivity));
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
this.loaded.set(true);
} finally {
this.loading.set(false);
}
}
async loadMore(): Promise<void> {
if (!this.nextCursor || this.loadingMore()) {
return;
}
this.loadingMore.set(true);
try {
const page = await firstValueFrom(this.api.list(this.nextCursor));
const known = new Set(this.items().map((c) => c.id));
this.items.update((list) => [...list, ...page.items.filter((c) => !known.has(c.id))]);
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
} finally {
this.loadingMore.set(false);
}
}
/** Loads (or reloads) a chat's details and syncs its list row. */
async loadChat(chatId: string): Promise<ChatDto> {
const chat = await firstValueFrom(this.api.get(chatId));
this.setDetails(chat);
return chat;
}
/** Stores fresh chat details (from any API response) and patches the list row. */
setDetails(chat: ChatDto): void {
const previous = this.details()[chat.id];
if (previous && previous.hasAvatar !== chat.hasAvatar) {
this.blobs.invalidate(avatarUrl.chat(chat.id));
}
this.details.update((all) => ({ ...all, [chat.id]: chat }));
if (!chat.myRole) {
this.items.update((list) => list.filter((c) => c.id !== chat.id));
return;
}
const role = chat.myRole;
const exists = this.items().some((c) => c.id === chat.id);
if (exists) {
this.patch(chat.id, (c) => ({
...c,
title: chat.title,
hasAvatar: chat.hasAvatar,
isMuted: chat.isMuted,
myRole: role,
peer: chat.peer,
}));
} else {
const item: ChatListItem = {
id: chat.id,
type: chat.type,
title: chat.title,
hasAvatar: chat.hasAvatar,
lastActivityAt: new Date().toISOString(),
myRole: role,
isMuted: chat.isMuted,
lastMessage: null,
unreadCount: 0,
peer: chat.peer,
};
this.items.update((list) => [item, ...list]);
}
}
/**
* Forget a chat the user can no longer see. `notify` announces it on `removed` (the open
* conversation then closes with a notice); pass false when the user left or deleted it here.
*/
remove(chatId: string, notify = true): void {
this.items.update((list) => list.filter((c) => c.id !== chatId));
this.details.update((all) => {
const next = { ...all };
delete next[chatId];
return next;
});
if (notify) {
this.removed.next(chatId);
}
}
markReadLocally(chatId: string): void {
this.patch(chatId, (c) => (c.unreadCount ? { ...c, unreadCount: 0 } : c));
}
setMuted(chatId: string, muted: boolean): void {
this.patch(chatId, (c) => ({ ...c, isMuted: muted }));
const chat = this.details()[chatId];
if (chat) {
this.details.update((all) => ({ ...all, [chatId]: { ...chat, isMuted: muted } }));
}
}
/** Keeps the list in step with a message the user just sent. */
noteOwnMessage(message: MessageDto): void {
this.applyMessageCreated(message);
}
private apply(event: HubEvent): void {
const me = this.auth.user()?.id;
switch (event.type) {
case 'messageCreated':
this.applyMessageCreated(event.message);
break;
case 'messageUpdated':
this.patch(event.message.chatId, (c) =>
c.lastMessage?.id === event.message.id
? { ...c, lastMessage: { ...c.lastMessage, body: event.message.body ?? '' } }
: c,
);
break;
case 'messageDeleted':
this.patch(event.chatId, (c) =>
c.lastMessage?.id === event.messageId
? { ...c, lastMessage: { ...c.lastMessage, body: '', deleted: true } }
: c,
);
break;
case 'membersAdded':
if (me && event.userIds.includes(me)) {
this.scheduleReload();
} else if (this.details()[event.chatId]) {
void this.loadChat(event.chatId).catch(() => undefined);
}
break;
case 'memberRemoved':
if (event.userId === me) {
this.remove(event.chatId);
} else if (this.details()[event.chatId]) {
void this.loadChat(event.chatId).catch(() => undefined);
}
break;
case 'chatUpdated':
this.blobs.invalidate(avatarUrl.chat(event.chatId));
void this.loadChat(event.chatId).catch(() => undefined);
break;
case 'chatDeleted':
this.remove(event.chatId);
break;
}
}
private applyMessageCreated(message: MessageDto): void {
const chat = this.items().find((c) => c.id === message.chatId);
if (!chat) {
// A chat we don't have yet (e.g. someone started a direct chat with us).
this.scheduleReload();
return;
}
if (chat.lastMessage && chat.lastMessage.id >= message.id) {
return;
}
const mine = message.sender.id === this.auth.user()?.id;
const visible =
this.activeChatId() === message.chatId && document.visibilityState === 'visible';
this.items.update((list) =>
list
.map((c) =>
c.id === message.chatId
? {
...c,
lastActivityAt: message.createdAt,
lastMessage: {
id: message.id,
senderId: message.sender.id,
body: (message.body ?? '').slice(0, 100),
createdAt: message.createdAt,
hasAttachments: message.attachments.length > 0,
},
unreadCount: mine || visible ? c.unreadCount : c.unreadCount + 1,
}
: c,
)
.sort(byActivity),
);
}
private patch(chatId: string, change: (chat: ChatListItem) => ChatListItem): void {
this.items.update((list) => list.map((c) => (c.id === chatId ? change(c) : c)));
}
private scheduleReload(): void {
clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => void this.loadFirst().catch(() => undefined), 300);
}
private reset(): void {
clearTimeout(this.reloadTimer);
this.items.set([]);
this.details.set({});
this.loaded.set(false);
this.hasMore.set(false);
this.nextCursor = null;
this.activeChatId.set(null);
}
}realtime.events.subscribe((event) => this.apply(event))— the store is a root singleton, so the subscription lives as long as the application; there is nothing to unsubscribe.switch (event.type)narrows the union in everycase:event.messageexists after'messageCreated',event.userIdsafter'membersAdded'. Events that the store does not care about (typing, presence) fall through theswitch.- Duplicates are harmless.
applyMessageCreatedignores a message whose id is not newer than the last one in the row (chat.lastMessage.id >= message.id). The sender's own tab gets its message twice — fromnoteOwnMessageafter thePOSTand from the hub — and counts it once. - The unread rule compares the sender with the signed-in user and checks
activeChatIdanddocument.visibilityState: a message in the chat the user is looking at is not unread, but the same message in a hidden browser tab is. scheduleReload()debounces reloads by 300 ms, so that a burst of events (a user added to five chats at once) costs one request.- After a reconnect the store reloads the first page of chats if it had loaded one: unread counts and last messages may have changed while the client was offline.
Step 2. The conversation follows the events
Why. The open conversation needs four events: new and edited messages are merged by id with merge of topic 19; deleted ones become placeholders; messagesRead from other members moves their read position, which turns one tick into two. After a reconnect, the store fetches everything newer than its newest confirmed message with GET /api/chats/{id}/messages?after= (topic 11), page by page.
Do. Complete MessagesStore (new lines in green). It is now final:
ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { DestroyRef } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { AttachmentDto, MessageDto, PageDto, compareIds } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { HubEvent, RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
/** A message on screen. Messages being sent have `localState` and a temporary id. */
export type ChatMessage = MessageDto & { localState?: 'pending' | 'failed' };
export const PAGE_SIZE = 50;
const CATCH_UP_LIMIT = 100;
let localIds = 0;
/**
* The open chat's messages, oldest first. History is keyset paged (`before=` for older pages,
* `after=` to fill the gap after a reconnect), and hub events are merged in by id so nothing shows
* twice. Provided by the conversation page, so each open chat gets its own instance state.
*/
@Injectable()
export class MessagesStore {
private readonly api = inject(MessagesApi);
private readonly chatsApi = inject(ChatsApi);
private readonly chats = inject(ChatsStore);
private readonly auth = inject(AuthService);
private olderCursor: string | null = null;
/** Bumped on every chat switch so late responses for the previous chat are dropped. */
private generation = 0;
private lastMarkedRead: string | null = null;
readonly chatId = signal<string | null>(null);
readonly messages = signal<ChatMessage[]>([]);
readonly loading = signal(false);
readonly loadingOlder = signal(false);
readonly hasOlder = signal(false);
readonly error = signal<unknown>(null);
/** Read positions of other members, from live MessagesRead events. */
readonly readBy = signal<Readonly<Record<string, string>>>({});
readonly byId = computed(() => new Map(this.messages().map((m) => [m.id, m])));
/** The newest message the server knows about (not a pending one). */
readonly lastConfirmed = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState) return list[i];
}
return null;
});
/** The newest message that can be a read position (the server rejects deleted ones). */
readonly lastReadable = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState && !list[i].isDeleted) return list[i];
}
return null;
});
/** The newest message any other member has read. */
readonly peerReadUpTo = computed(() => {
const ids = Object.values(this.readBy());
return ids.length ? ids.reduce((max, id) => (id > max ? id : max)) : null;
});
constructor() {
const realtime = inject(RealtimeService);
const events = realtime.events.subscribe((event) => this.apply(event));
const connected = realtime.connected.subscribe(({ reconnected }) => {
if (reconnected) {
void this.catchUp();
}
});
inject(DestroyRef).onDestroy(() => {
events.unsubscribe();
connected.unsubscribe();
});
}
async open(chatId: string): Promise<void> {
this.generation++;
this.chatId.set(chatId);
this.messages.set([]);
this.readBy.set({});
this.olderCursor = null;
this.hasOlder.set(false);
this.lastMarkedRead = null;
this.error.set(null);
await this.loadInitial();
}
async loadInitial(): Promise<void> {
const chatId = this.chatId();
if (!chatId) {
return;
}
const generation = this.generation;
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list(chatId, { limit: PAGE_SIZE }));
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} catch (error) {
if (generation === this.generation) {
this.error.set(error);
}
} finally {
if (generation === this.generation) {
this.loading.set(false);
}
}
}
async loadOlder(): Promise<void> {
const chatId = this.chatId();
if (!chatId || !this.olderCursor || this.loadingOlder()) {
return;
}
const generation = this.generation;
this.loadingOlder.set(true);
try {
const page = await firstValueFrom(
this.api.list(chatId, { before: this.olderCursor, limit: PAGE_SIZE }),
);
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} finally {
if (generation === this.generation) {
this.loadingOlder.set(false);
}
}
}
/** Fetches everything newer than the last message on screen (after a reconnect). */
async catchUp(): Promise<void> {
const chatId = this.chatId();
if (!chatId) {
return;
}
let after = this.lastConfirmed()?.id;
if (!after) {
await this.loadInitial();
return;
}
const generation = this.generation;
for (let i = 0; i < 20 && after; i++) {
const page: PageDto<MessageDto> = await firstValueFrom(
this.api.list(chatId, { after, limit: CATCH_UP_LIMIT }),
);
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, page.items));
after = page.nextCursor ?? undefined;
}
}
/** Sends a message, showing it at once as pending. */
async send(body: string, attachments: AttachmentDto[], replyToMessageId?: string | null) {
const chatId = this.chatId();
const me = this.auth.user();
if (!chatId || !me) {
return;
}
const localId = `local-${++localIds}`;
const pending: ChatMessage = {
id: localId,
chatId,
sender: {
id: me.id,
userName: me.userName,
displayName: me.displayName,
hasAvatar: me.hasAvatar,
},
body,
replyToMessageId: replyToMessageId ?? null,
createdAt: new Date().toISOString(),
isDeleted: false,
attachments,
localState: 'pending',
};
this.messages.update((list) => [...list, pending]);
await this.deliver(pending);
}
/** Sends a failed message again. */
async retry(localId: string): Promise<void> {
const message = this.byId().get(localId);
if (message?.localState === 'failed') {
this.replace(localId, { ...message, localState: 'pending' });
await this.deliver(message);
}
}
discard(localId: string): void {
this.messages.update((list) => list.filter((m) => m.id !== localId));
}
async edit(messageId: string, body: string): Promise<void> {
const updated = await firstValueFrom(this.api.edit(messageId, body));
this.upsert(updated);
}
async delete(messageId: string): Promise<void> {
await firstValueFrom(this.api.delete(messageId));
this.markDeleted(messageId);
}
/** Moves the read position to the newest message (once per message). */
async markRead(): Promise<void> {
const chatId = this.chatId();
const last = this.lastReadable();
if (!chatId || !last || last.id === this.lastMarkedRead) {
return;
}
this.lastMarkedRead = last.id;
this.chats.markReadLocally(chatId);
try {
await firstValueFrom(this.chatsApi.markRead(chatId, last.id));
} catch {
this.lastMarkedRead = null;
}
}
private async deliver(pending: ChatMessage): Promise<void> {
const generation = this.generation;
try {
const sent = await firstValueFrom(
this.api.send(pending.chatId, {
body: pending.body || null,
replyToMessageId: pending.replyToMessageId,
attachmentIds: pending.attachments.map((a) => a.id),
}),
);
if (generation !== this.generation) {
return;
}
// The hub event may have arrived first; either way keep exactly one copy.
this.messages.update((list) =>
merge(
list.filter((m) => m.id !== pending.id),
[sent],
),
);
this.chats.noteOwnMessage(sent);
} catch (error) {
if (generation === this.generation) {
this.replace(pending.id, { ...pending, localState: 'failed' });
}
throw error;
}
}
private apply(event: HubEvent): void {
const chatId = this.chatId();
switch (event.type) {
case 'messageCreated':
case 'messageUpdated':
if (event.message.chatId === chatId) {
this.upsert(event.message);
}
break;
case 'messageDeleted':
if (event.chatId === chatId) {
this.markDeleted(event.messageId);
}
break;
case 'messagesRead':
if (event.chatId === chatId && event.userId !== this.auth.user()?.id) {
this.readBy.update((all) =>
(all[event.userId] ?? '') >= event.lastReadMessageId
? all
: { ...all, [event.userId]: event.lastReadMessageId },
);
}
break;
}
}
private upsert(message: MessageDto): void {
this.messages.update((list) => merge(list, [message]));
}
private replace(id: string, message: ChatMessage): void {
this.messages.update((list) => list.map((m) => (m.id === id ? message : m)));
}
private markDeleted(messageId: string): void {
this.messages.update((list) =>
list.map((m) =>
m.id === messageId ? { ...m, isDeleted: true, body: null, attachments: [] } : m,
),
);
}
}
/**
* Merges server messages into the list: replaces ones with the same id, keeps confirmed messages
* ordered by id, and keeps pending messages at the end.
*/
export function merge(current: ChatMessage[], incoming: MessageDto[]): ChatMessage[] {
if (!incoming.length) {
return current;
}
const confirmed = new Map(current.filter((m) => !m.localState).map((m) => [m.id, m]));
for (const message of incoming) {
confirmed.set(message.id, message);
}
const pending = current.filter((m) => m.localState);
return [...[...confirmed.values()].sort((a, b) => compareIds(a.id, b.id)), ...pending];
}- This store is not a singleton: it lives as long as its conversation page.
inject(DestroyRef).onDestroy(...)unsubscribes both subscriptions when the page goes away; without it, every visited chat would leave a store behind that keeps applying events. - Events of other chats are ignored (
event.message.chatId === chatId). readBykeeps the newest read position per other member and never moves it backwards; read events of the user's own other tabs are ignored.peerReadUpTo— the maximum overreadBy— is what the message list compares with to show "seen".catchUp()asks for up to 100 messagesafterthe newest confirmed one and followsnextCursorfor at most 20 pages. If the conversation had no messages, it simply loads the first page. The generation check drops the result if the user has switched chats in the meantime.
Fig. 20.2 shows the reconnect from the store's point of view.
Fig. 20.2. Catching up after a reconnect
Step 3. Testing the events
Do. Replace both specs with their final versions; they now use fakeRealtime() and push events into the stores:
ts
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { BOB, ME, fakeAuth, fakeRealtime, message, messageId } from '../../testing/fakes';
import { ChatsApi } from '../core/api/chatex-api';
import { ChatListItemDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
import { RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
function item(
id: string,
lastActivityAt: string,
overrides: Partial<ChatListItemDto> = {},
): ChatListItemDto {
return {
id,
type: 'group',
title: id,
hasAvatar: false,
lastActivityAt,
myRole: 'member',
isMuted: false,
lastMessage: null,
unreadCount: 0,
peer: null,
...overrides,
};
}
describe('ChatsStore', () => {
let store: ChatsStore;
let realtime: ReturnType<typeof fakeRealtime>;
beforeEach(async () => {
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
realtime = fakeRealtime();
const api = {
list: vi.fn(() =>
of({
items: [
item('chat-old', '2026-11-01T00:00:00Z'),
item('chat-1', '2026-11-05T00:00:00Z'),
item('chat-muted', '2026-11-03T00:00:00Z', { isMuted: true, unreadCount: 4 }),
],
nextCursor: null,
}),
),
};
TestBed.configureTestingModule({
providers: [
{ provide: ChatsApi, useValue: api },
{ provide: AuthService, useValue: fakeAuth() },
{ provide: BlobUrlService, useValue: { invalidate: vi.fn() } },
{ provide: RealtimeService, useValue: realtime },
],
});
store = TestBed.inject(ChatsStore);
TestBed.tick();
await store.loadFirst();
});
const order = () => store.items().map((c) => c.id);
const get = (id: string) => store.items().find((c) => c.id === id)!;
it('lists chats by latest activity', () => {
expect(order()).toEqual(['chat-1', 'chat-muted', 'chat-old']);
});
it('moves a chat with a new message to the top and counts it unread', () => {
realtime.events.next({
type: 'messageCreated',
message: message(10, { chatId: 'chat-old', createdAt: '2026-11-10T00:00:00Z' }),
});
expect(order()[0]).toBe('chat-old');
expect(get('chat-old').unreadCount).toBe(1);
expect(get('chat-old').lastMessage?.id).toBe(messageId(10));
});
it("doesn't count the user's own messages or the open chat as unread", () => {
store.activeChatId.set('chat-old');
realtime.events.next({ type: 'messageCreated', message: message(11, { chatId: 'chat-old' }) });
realtime.events.next({
type: 'messageCreated',
message: message(12, { chatId: 'chat-1', sender: { ...BOB, id: ME.id } }),
});
expect(get('chat-old').unreadCount).toBe(0);
expect(get('chat-1').unreadCount).toBe(0);
});
it('leaves muted chats out of the total unread count', () => {
realtime.events.next({ type: 'messageCreated', message: message(13, { chatId: 'chat-1' }) });
expect(store.totalUnread()).toBe(1);
});
it('marks the last message deleted', () => {
realtime.events.next({ type: 'messageCreated', message: message(14, { chatId: 'chat-1' }) });
realtime.events.next({ type: 'messageDeleted', chatId: 'chat-1', messageId: messageId(14) });
expect(get('chat-1').lastMessage).toMatchObject({ deleted: true, body: '' });
});
it('drops chats that were deleted or that the user was removed from', () => {
const removed: string[] = [];
store.removed.subscribe((id) => removed.push(id));
realtime.events.next({ type: 'chatDeleted', chatId: 'chat-1' });
realtime.events.next({ type: 'memberRemoved', chatId: 'chat-old', userId: ME.id });
realtime.events.next({ type: 'memberRemoved', chatId: 'chat-muted', userId: BOB.id });
expect(order()).toEqual(['chat-muted']);
expect(removed).toEqual(['chat-1', 'chat-old']);
});
it('clears unread counts locally', () => {
store.markReadLocally('chat-muted');
expect(get('chat-muted').unreadCount).toBe(0);
});
});ts
import { TestBed } from '@angular/core/testing';
import { Subject, of, throwError } from 'rxjs';
import { BOB, ME, fakeAuth, fakeRealtime, message, messageId, settle } from '../../testing/fakes';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { MessageDto, PageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
import { MessagesStore, merge } from './messages.store';
describe('MessagesStore', () => {
let store: MessagesStore;
let realtime: ReturnType<typeof fakeRealtime>;
let api: {
list: ReturnType<typeof vi.fn>;
send: ReturnType<typeof vi.fn>;
edit: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
};
let chats: {
markReadLocally: ReturnType<typeof vi.fn>;
noteOwnMessage: ReturnType<typeof vi.fn>;
};
let chatsApi: { markRead: ReturnType<typeof vi.fn> };
const page = (items: MessageDto[], nextCursor: string | null = null): PageDto<MessageDto> => ({
items,
nextCursor,
});
const ids = () => store.messages().map((m) => m.id);
beforeEach(() => {
realtime = fakeRealtime();
api = { list: vi.fn(), send: vi.fn(), edit: vi.fn(), delete: vi.fn() };
chats = { markReadLocally: vi.fn(), noteOwnMessage: vi.fn() };
chatsApi = { markRead: vi.fn(() => of(undefined)) };
TestBed.configureTestingModule({
providers: [
MessagesStore,
{ provide: MessagesApi, useValue: api },
{ provide: ChatsApi, useValue: chatsApi },
{ provide: ChatsStore, useValue: chats },
{ provide: AuthService, useValue: fakeAuth() },
{ provide: RealtimeService, useValue: realtime },
],
});
store = TestBed.inject(MessagesStore);
});
async function openWith(newestFirst: MessageDto[], cursor: string | null = null) {
api.list.mockReturnValueOnce(of(page(newestFirst, cursor)));
await store.open('chat-1');
}
it('shows the newest page oldest first', async () => {
await openWith([message(3), message(2), message(1)], 'cursor-1');
expect(api.list).toHaveBeenCalledWith('chat-1', { limit: 50 });
expect(ids()).toEqual([messageId(1), messageId(2), messageId(3)]);
expect(store.hasOlder()).toBe(true);
});
it('prepends older pages using the cursor', async () => {
await openWith([message(4), message(3)], 'cursor-1');
api.list.mockReturnValueOnce(of(page([message(2), message(1)])));
await store.loadOlder();
expect(api.list).toHaveBeenLastCalledWith('chat-1', { before: 'cursor-1', limit: 50 });
expect(ids()).toEqual([1, 2, 3, 4].map(messageId));
expect(store.hasOlder()).toBe(false);
});
it('adds live messages once and ignores other chats', async () => {
await openWith([message(1)]);
realtime.events.next({ type: 'messageCreated', message: message(2) });
realtime.events.next({ type: 'messageCreated', message: message(2) });
realtime.events.next({ type: 'messageCreated', message: message(3, { chatId: 'other' }) });
expect(ids()).toEqual([messageId(1), messageId(2)]);
});
it('applies edits and deletions from the hub', async () => {
await openWith([message(2), message(1)]);
realtime.events.next({
type: 'messageUpdated',
message: message(1, { body: 'edited', editedAt: '2026-11-10T12:05:00Z' }),
});
realtime.events.next({ type: 'messageDeleted', chatId: 'chat-1', messageId: messageId(2) });
const [first, second] = store.messages();
expect(first.body).toBe('edited');
expect(second.isDeleted).toBe(true);
expect(second.body).toBeNull();
});
it('shows a sent message at once and swaps in the server copy', async () => {
await openWith([message(1)]);
const response = new Subject<MessageDto>();
api.send.mockReturnValueOnce(response);
const sending = store.send('hello', []);
expect(store.messages().at(-1)).toMatchObject({ body: 'hello', localState: 'pending' });
const sent = message(2, {
body: 'hello',
sender: { ...BOB, id: ME.id, displayName: ME.displayName },
});
response.next(sent);
response.complete();
await sending;
expect(ids()).toEqual([messageId(1), messageId(2)]);
expect(store.messages().some((m) => m.localState)).toBe(false);
expect(chats.noteOwnMessage).toHaveBeenCalledWith(sent);
});
it('keeps one copy when the hub event beats the POST response', async () => {
await openWith([message(1)]);
const response = new Subject<MessageDto>();
api.send.mockReturnValueOnce(response);
const sent = message(2, { body: 'hi' });
const sending = store.send('hi', []);
realtime.events.next({ type: 'messageCreated', message: sent });
response.next(sent);
response.complete();
await sending;
expect(ids()).toEqual([messageId(1), messageId(2)]);
});
it('marks a message failed when sending fails, and can retry it', async () => {
await openWith([]);
api.send.mockReturnValueOnce(throwError(() => new Error('offline')));
await expect(store.send('hi', [])).rejects.toThrow('offline');
const failed = store.messages()[0];
expect(failed.localState).toBe('failed');
api.send.mockReturnValueOnce(of(message(5, { body: 'hi' })));
await store.retry(failed.id);
expect(ids()).toEqual([messageId(5)]);
});
it('catches up after a reconnect by following the after cursor', async () => {
await openWith([message(1)]);
api.list
.mockReturnValueOnce(of(page([message(2), message(3)], 'next')))
.mockReturnValueOnce(of(page([message(4)], null)));
realtime.connected.next({ reconnected: true });
await settle();
expect(api.list).toHaveBeenCalledWith('chat-1', { after: messageId(1), limit: 100 });
expect(api.list).toHaveBeenCalledWith('chat-1', { after: 'next', limit: 100 });
expect(ids()).toEqual([1, 2, 3, 4].map(messageId));
});
it('marks the newest message read once', async () => {
await openWith([message(2), message(1)]);
await store.markRead();
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledTimes(1);
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(2));
expect(chats.markReadLocally).toHaveBeenCalledWith('chat-1');
});
it('never uses a deleted message as the read position', async () => {
await openWith([message(2, { isDeleted: true, body: null }), message(1)]);
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(1));
});
it('tracks how far other members have read', async () => {
await openWith([message(2), message(1)]);
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: BOB.id,
lastReadMessageId: messageId(2),
});
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: BOB.id,
lastReadMessageId: messageId(1),
});
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: ME.id,
lastReadMessageId: messageId(9),
});
expect(store.peerReadUpTo()).toBe(messageId(2));
});
it('drops responses for a chat that is no longer open', async () => {
const slow = new Subject<PageDto<MessageDto>>();
api.list.mockReturnValueOnce(slow);
const first = store.open('chat-1');
api.list.mockReturnValueOnce(of(page([message(7, { chatId: 'chat-2' })])));
await store.open('chat-2');
slow.next(page([message(1)]));
slow.complete();
await first;
expect(ids()).toEqual([messageId(7)]);
});
});
describe('merge', () => {
it('orders by id and keeps pending messages last', () => {
const pending = { ...message(0), id: 'local-1', localState: 'pending' as const };
const merged = merge([message(3), pending], [message(1), message(3, { body: 'new' })]);
expect(merged.map((m) => m.id)).toEqual([messageId(1), messageId(3), 'local-1']);
expect(merged[1].body).toBe('new');
});
});The five new tests of ChatsStore move a chat to the top and count it unread, leave the user's own messages and the open chat out of the unread count, leave muted chats out of the total, mark a deleted last message, and drop chats that were deleted or that the user was removed from.
The five new tests of MessagesStore add live messages once and ignore other chats, apply edits and deletions, keep one copy when the hub event beats the POST response, follow the after cursor after a reconnect (await settle() lets the asynchronous catchUp run), and track how far other members have read.
Check
powershell
npm test -- --watch=false Test Files 8 passed (8)
Tests 48 passed (48)Start the API and the client, and sign in as Alice and as Bob in two windows. Send a message as Bob: it appears in Alice's open conversation at once, and in her list with an unread badge if another chat is open. Edit and delete it: Alice's screen follows. When Alice reads Bob's message, the single tick under it in Bob's window becomes a double one.