English
The message store
Step 1. One store per open chat
Why. ChatsStore is a singleton: there is one list of chats. Messages belong to one open chat. The conversation page therefore provides its own MessagesStore (providers: [MessagesStore] in its @Component, chapter 4): Angular creates an instance for the page and destroys it with the page, like a scoped service in ASP.NET Core whose scope is the component. The class is decorated with plain @Injectable(), without providedIn: 'root'.
The store's rules:
- Messages are kept oldest first, the order of the screen, although the API returns pages newest first (topic 11).
- Messages are merged by id. The same message can arrive twice — as the response to
POSTand, from topic 20, as a hub event — and must appear once. - Sending is optimistic. The message appears immediately with a spinner (pending) and a temporary id; when the server answers, the server's copy replaces it. If sending fails, the message stays on screen as failed with "Retry" and "Delete".
- Late answers are dropped. If the user switches chats while a page is loading, the answer for the old chat must not end up in the new one.
Do. Create the store. The lines that apply hub events and catch up after a reconnect come in topic 20; one import line is shorter until then (yellow).
ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { AttachmentDto, MessageDto, compareIds } from '../core/api/models';
import { AuthService } from '../core/auth/auth.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;
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;
});
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);
}
}
}
/** 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 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];
}ChatMessageis aMessageDtowith an optionallocalState: 'pending' | 'failed'. Pending messages have ids likelocal-1, which can never collide with the server's UUIDs.byId,lastConfirmed,lastReadable,peerReadUpToarecomputedviews: a lookup map, the newest message that the server knows, the newest one that can be a read position (the API refuses deleted ones), and how far other members have read.readBystays empty until topic 20 fills it fromMessagesReadevents.generationgrows on everyopen(). Each async method remembers the generation at its start and ignores its result if the generation has changed meanwhile — a simple, explicit form of cancellation.open(chatId)resets the state and loads the newest page;loadOlder()loads the pagebeforethe oldest cursor. Both reverse the page and merge it.send(body, attachments, replyToMessageId)builds the pending message from the signed-in user's profile, appends it and callsdeliver.deliverposts the request; on success it removes the pending copy and merges the server's message, and tellsChatsStoreto move the chat to the top (noteOwnMessage); on failure it marks the message failed and rethrows, so the caller can show a toast.retry(localId)sends a failed message again;discardremoves it.editanddeletewait for the server, then update the list. These are not optimistic: an edit or a deletion that the server refuses (another user's message, a chat the user has left) must not appear to have worked.markRead()sends the newest readable message as the read position, but only once per message (lastMarkedRead), and clears the unread badge in the list at once (markReadLocally). If the request fails, the next call tries again.merge(current, incoming)is an exported pure function: confirmed messages go into aMapby id (so a newer copy replaces an older one), are sorted by id — UUIDv7 ids sort by time — and the pending ones stay at the end, in the order they were sent.
Optimistic updates
An optimistic user interface shows the expected result before the server confirms it, because the server almost always does. It makes a messenger feel instant on a slow network. The cost is the failure path: the client must be able to show "this did not happen" and offer a retry. Chatex sends optimistically, where a failure is easy to show next to the message, and edits and deletes pessimistically, where a silent rollback would confuse.
Step 2. Testing the store
Why. The store has many paths — paging, sending, failures, retries, late answers, read positions — and each is easy to break in a refactoring. The tests replace the APIs and ChatsStore with mocks and drive the store directly.
Do. Create the spec. The tests of hub events and reconnects join it in topic 20, together with a longer import line (yellow).
ts
import { TestBed } from '@angular/core/testing';
import { Subject, of, throwError } from 'rxjs';
import { BOB, ME, fakeAuth, message, messageId } 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 { ChatsStore } from './chats.store';
import { MessagesStore, merge } from './messages.store';
describe('MessagesStore', () => {
let store: MessagesStore;
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(() => {
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() },
],
});
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('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('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('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('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');
});
});providers: [MessagesStore, …]registers the store itself, because it is not provided in the root.api.list.mockReturnValueOnce(of(page))answers the next call only, so a test can script a sequence of pages.- "shows a sent message at once" uses a
Subjectas the HTTP response: the test checks the pending state before the server answers, then emits the response withnextandcomplete. - "marks a message failed" returns
throwError(...), expectssendto reject, and then retries successfully. - "drops responses for a chat that is no longer open" opens chat 1 with a slow response, opens chat 2, and only then lets chat 1's answer arrive: the store must show only chat 2's message.
mergeis tested on its own, as a pure function.
Check
powershell
npm test -- --watch=false --include src/app/state/messages.store.spec.ts Test Files 1 passed (1)
Tests 8 passed (8)