Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
065b8d2
chore: migrate loadNextMessages DDP method to GET rooms.history
Rohit3523 Oct 9, 2026
aeb4ca1
test: assert the Newer Loader row in one expectation
Rohit3523 Oct 9, 2026
9fd627b
fix: return rooms.history _updatedAt as a Date so thread rows keep up…
Rohit3523 Oct 9, 2026
ade7e2d
fix: convert a string _updatedAt to a Date in normalizeMessage
Rohit3523 Oct 9, 2026
1b3f8ed
test: cover an ISO string _updatedAt through updateMessages with the …
Rohit3523 Oct 9, 2026
910d865
fix: convert _updatedAt to a Date in getNextMessages instead of norma…
Rohit3523 Oct 9, 2026
2d9458e
refactor: make loadNextMessages an async function
Rohit3523 Oct 9, 2026
d699dd1
Merge branch 'develop' into chore/migrate-load-next-messages-rest
Rohit3523 Oct 10, 2026
e31f8d6
chore: format the rooms.history type and import auxStore by alias in …
Rohit3523 Oct 12, 2026
ae5b15e
refactor: use getTime() for the rooms.history cursor instead of tsToMs
Rohit3523 Oct 12, 2026
cb82efc
Merge branch 'develop' into chore/migrate-load-next-messages-rest
Rohit3523 Oct 12, 2026
2d3c67c
chore: remove duplicate ejson import and pass runSlashCommand params …
Rohit3523 Oct 12, 2026
b0ffcee
revert: restore runSlashCommand positional params
Rohit3523 Oct 12, 2026
f33ff41
chore: migrate loadSurroundingMessages DDP method to GET rooms.history
Rohit3523 Oct 12, 2026
b1bfb04
fix: keep the loadNextMessages DDP argument unchanged and offset only…
Rohit3523 Oct 12, 2026
f87815e
refactor: type the loadSurroundingMessages dep as IMessage[] and drop…
Rohit3523 Oct 12, 2026
31203fc
refactor: share one rooms.history helper between the wrappers and rej…
Rohit3523 Oct 13, 2026
50770da
fix: request thread replies from rooms.history so the loaders store t…
Rohit3523 Oct 13, 2026
86feebe
refactor: name the newest loaded timestamp behind the rooms.history n…
Rohit3523 Oct 13, 2026
460c2f2
test: pin the jump cancel when the server Chunk fails to load and use…
Rohit3523 Oct 13, 2026
2abbd9c
Merge branch 'develop' into chore/migrate-load-next-messages-rest
Rohit3523 Oct 13, 2026
28012ee
fix: keep milliseconds on the Older Loader timestamp so Load more can…
Rohit3523 Oct 14, 2026
3424df6
Merge branch 'develop' into chore/migrate-load-next-messages-rest
diegolmello Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion app/definitions/rest/v1/rooms.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IMessage } from '~/definitions/IMessage';
import type { IMessage, IMessageFromServer } from '~/definitions/IMessage';
import type { IRoomNotifications, IServerRoom } from '~/definitions/IRoom';
import type { IUser } from '~/definitions/IUser';

Expand Down Expand Up @@ -57,6 +57,18 @@ export type RoomsEndpoints = {
'rooms.invite': {
POST: (params: { roomId: string; action: 'accept' | 'reject' }) => void;
};
'rooms.history': {
GET: (params: {
roomId: IServerRoom['_id'];
next?: string;
aroundId?: IMessage['_id'];
count?: number;
showThreadMessages?: boolean;
}) => {
messages: IMessageFromServer[];
cursor: { next: string | null; previous: string | null };
};
};
'rooms.join': {
POST: (params: { roomId: string; joinCode: string | null }) => {
room: IServerRoom;
Expand Down
120 changes: 120 additions & 0 deletions app/lib/methods/__tests__/loadNextMessages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { loadNextMessages } from '../loadNextMessages';
import { getNextMessages } from '../../services/restApi';
import { getMessageById } from '../../database/services/Message';
import updateMessages from '../updateMessages';
import log from '../helpers/log';
import { MessageTypeLoad } from '../../constants/messageTypeLoad';

jest.mock('../../services/restApi', () => ({
getNextMessages: jest.fn()
}));

jest.mock('../../database/services/Message', () => ({
getMessageById: jest.fn()
}));

jest.mock('../updateMessages', () => jest.fn());

jest.mock('../helpers/log', () => ({
__esModule: true,
default: jest.fn()
}));

const mockedGetNextMessages = getNextMessages as jest.MockedFunction<typeof getNextMessages>;
const mockedGetMessageById = getMessageById as jest.MockedFunction<typeof getMessageById>;
const mockedUpdateMessages = updateMessages as jest.MockedFunction<typeof updateMessages>;
const mockedLog = log as jest.MockedFunction<typeof log>;

const RID = 'ROOM_ID';
const TS = new Date(Date.UTC(2024, 0, 1, 12, 0, 0));
const COUNT = 50;
const LOADER_ITEM = { id: 'tapped-loader' } as any;

const buildMessages = (length: number) =>
Array.from(
{ length },
(_, index) => ({ _id: `msg-${index + 1}`, rid: RID, ts: new Date(TS.getTime() + (index + 1) * 1000) }) as any
);

const serve = (messages: any[], hasMore: boolean) => mockedGetNextMessages.mockResolvedValue({ messages, hasMore });

describe('loadNextMessages', () => {
beforeEach(() => {
jest.clearAllMocks();
mockedGetMessageById.mockResolvedValue(null as never);
mockedUpdateMessages.mockResolvedValue(0 as never);
});

it('asks for the messages newer than the loader', async () => {
serve([], false);

await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM });

expect(mockedGetNextMessages).toHaveBeenCalledWith({ rid: RID, after: TS, count: COUNT });
});

it('removes the Newer Loader when the server returns nothing newer', async () => {
serve([], false);

await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).resolves.toBeUndefined();

expect(mockedUpdateMessages).toHaveBeenCalledTimes(1);
expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: [], remove: [{ _id: 'tapped-loader' }] });
});

it('delegates a full response without adding a Newer Loader when the server reports nothing newer', async () => {
const messages = buildMessages(COUNT);
serve(messages, false);

await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM });

expect(mockedGetMessageById).not.toHaveBeenCalled();
expect(mockedUpdateMessages).toHaveBeenCalledTimes(1);
expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: messages, loaderItem: LOADER_ITEM });
});

it('adds no Newer Loader when more exist but the newest message is already local', async () => {
const messages = buildMessages(COUNT);
serve(messages, true);
mockedGetMessageById.mockResolvedValue({ id: 'msg-50' } as never);

await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM });

expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: messages, loaderItem: LOADER_ITEM });
});

it('appends a Newer Loader one millisecond after the newest message when more exist and it is not local', async () => {
const messages = buildMessages(COUNT);
serve(messages, true);

await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM });

expect(mockedGetMessageById).toHaveBeenCalledWith('msg-50');
expect(mockedUpdateMessages.mock.calls[0][0].update).toEqual([
...messages,
{ _id: 'load-more-msg-50', rid: RID, t: MessageTypeLoad.NEXT_CHUNK, ts: new Date(messages[COUNT - 1].ts.getTime() + 1) }
]);
});

it('stores a newest-first response oldest-first', async () => {
const newestFirst = buildMessages(COUNT)
.reverse()
.map(message => ({ ...message, ts: message.ts.toISOString() }));
serve(newestFirst, false);

await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM });

const update = mockedUpdateMessages.mock.calls[0][0].update as any[];
expect(update.map(m => m._id)).toEqual(buildMessages(COUNT).map(m => m._id));
});

it('logs and rejects with the same error when loading fails', async () => {
const error = new Error('boom');
mockedGetNextMessages.mockRejectedValue(error);

await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).rejects.toBe(error);

expect(mockedLog).toHaveBeenCalledWith(error);
expect(mockedUpdateMessages).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -1,33 +1,27 @@
import { loadSurroundingMessages } from './loadSurroundingMessages';
import sdk from '../services/sdk';
import { getMessageById } from '../database/services/Message';
import updateMessages from './updateMessages';
import log from './helpers/log';
import dayjs from '../dayjs';
import { MessageTypeLoad } from '../constants/messageTypeLoad';

jest.mock('../services/sdk', () => ({
__esModule: true,
default: { methodCallWrapper: jest.fn() }
import { loadSurroundingMessages } from '../loadSurroundingMessages';
import { getSurroundingMessages } from '../../services/restApi';
import { getMessageById } from '../../database/services/Message';
import updateMessages from '../updateMessages';
import log from '../helpers/log';
import dayjs from '../../dayjs';
import { MessageTypeLoad } from '../../constants/messageTypeLoad';

jest.mock('../../services/restApi', () => ({
getSurroundingMessages: jest.fn()
}));

jest.mock('../database/services/Message', () => ({
jest.mock('../../database/services/Message', () => ({
getMessageById: jest.fn()
}));

jest.mock('./updateMessages', () => jest.fn());
jest.mock('../updateMessages', () => jest.fn());

jest.mock('./helpers/log', () => ({
jest.mock('../helpers/log', () => ({
__esModule: true,
default: jest.fn()
}));

jest.mock('ejson', () => ({
__esModule: true,
default: { fromJSONValue: (value: any) => value }
}));

const mockedMethodCall = sdk.methodCallWrapper as jest.MockedFunction<typeof sdk.methodCallWrapper>;
const mockedGetSurroundingMessages = getSurroundingMessages as jest.MockedFunction<typeof getSurroundingMessages>;
const mockedGetMessageById = getMessageById as jest.MockedFunction<typeof getMessageById>;
const mockedUpdateMessages = updateMessages as jest.MockedFunction<typeof updateMessages>;
const mockedLog = log as jest.MockedFunction<typeof log>;
Expand All @@ -41,25 +35,35 @@ const buildMessage = (id: string, seconds: number) =>

const buildMessages = () => [buildMessage('msg-1', 1), buildMessage('msg-2', 2), buildMessage('msg-3', 3)];

const serve = (messages: any[], moreBefore: boolean, moreAfter: boolean) =>
mockedGetSurroundingMessages.mockResolvedValue({ messages, moreBefore, moreAfter });

describe('loadSurroundingMessages', () => {
beforeEach(() => {
jest.clearAllMocks();
mockedGetMessageById.mockResolvedValue(null as never);
mockedUpdateMessages.mockResolvedValue(0 as never);
});

it('asks for the surrounding Chunk', async () => {
serve([], false, false);

await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

expect(mockedGetSurroundingMessages).toHaveBeenCalledWith({ rid: RID, messageId: MESSAGE_ID, count: COUNT });
});

it('resolves [] without delegating when the server returns no messages', async () => {
mockedMethodCall.mockResolvedValue({ messages: [] } as never);
serve([], false, false);

await expect(loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })).resolves.toEqual([]);

expect(mockedMethodCall).toHaveBeenCalledWith('loadSurroundingMessages', { _id: MESSAGE_ID, rid: RID }, COUNT);
expect(mockedUpdateMessages).not.toHaveBeenCalled();
});

it('delegates with no markers when moreBefore and moreAfter are both falsy', async () => {
it('delegates with no markers when moreBefore and moreAfter are both false', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: false, moreAfter: false } as never);
serve(messages, false, false);

const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

Expand All @@ -70,11 +74,11 @@ describe('loadSurroundingMessages', () => {
expect(mockedUpdateMessages.mock.calls[0][0]).not.toHaveProperty('loaderItem');
});

it('prepends a load_previous_chunk marker when moreBefore is true and the first message is not local', async () => {
it('prepends an Older Loader when moreBefore is true and the first message is not local', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: true, moreAfter: false } as never);
serve(messages, true, false);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

const firstMessage = messages[0];
expect(mockedGetMessageById).toHaveBeenCalledWith(firstMessage._id);
Expand All @@ -88,22 +92,22 @@ describe('loadSurroundingMessages', () => {
expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: result });
});

it('prepends no marker when moreBefore is true but the first message is already local', async () => {
it('prepends no Older Loader when moreBefore is true but the first message is already local', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: true, moreAfter: false } as never);
serve(messages, true, false);
mockedGetMessageById.mockResolvedValue({ id: messages[0]._id } as never);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

expect(result).toHaveLength(messages.length);
expect(result.find(m => m.t === MessageTypeLoad.PREVIOUS_CHUNK)).toBeUndefined();
});

it('appends a load_next_chunk marker when moreAfter is true and the last message is not local', async () => {
it('appends a Newer Loader when moreAfter is true and the last message is not local', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: false, moreAfter: true } as never);
serve(messages, false, true);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

const lastMessage = messages[messages.length - 1];
expect(mockedGetMessageById).toHaveBeenCalledWith(lastMessage._id);
Expand All @@ -116,22 +120,22 @@ describe('loadSurroundingMessages', () => {
expect(dayjs(marker.ts).valueOf()).toBe(dayjs(lastMessage.ts).add(1, 'millisecond').valueOf());
});

it('appends no marker when moreAfter is true but the last message is already local', async () => {
it('appends no Newer Loader when moreAfter is true but the last message is already local', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: false, moreAfter: true } as never);
serve(messages, false, true);
mockedGetMessageById.mockResolvedValue({ id: messages[messages.length - 1]._id } as never);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

expect(result).toHaveLength(messages.length);
expect(result.find(m => m.t === MessageTypeLoad.NEXT_CHUNK)).toBeUndefined();
});

it('adds both markers when moreBefore and moreAfter are true and neither endpoint is local', async () => {
it('adds both Loader Rows when moreBefore and moreAfter are true and neither endpoint is local', async () => {
const messages = buildMessages();
mockedMethodCall.mockResolvedValue({ messages, moreBefore: true, moreAfter: true } as never);
serve(messages, true, true);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

expect(result).toHaveLength(messages.length + 2);
expect(result[0].t).toBe(MessageTypeLoad.PREVIOUS_CHUNK);
Expand All @@ -141,12 +145,12 @@ describe('loadSurroundingMessages', () => {
expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: result });
});

it('orders decoded messages by ts ascending before selecting the endpoints', async () => {
it('orders a newest-first response by ts ascending before selecting the endpoints', async () => {
const ordered = buildMessages();
const unordered = [...ordered].reverse();
mockedMethodCall.mockResolvedValue({ messages: unordered, moreBefore: true, moreAfter: true } as never);
const newestFirst = [...ordered].reverse().map(message => ({ ...message, ts: message.ts.toISOString() }));
serve(newestFirst, true, true);

const result = (await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })) as any[];
const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID });

expect(mockedGetMessageById).toHaveBeenCalledWith(ordered[0]._id);
expect(mockedGetMessageById).toHaveBeenCalledWith(ordered[ordered.length - 1]._id);
Expand All @@ -161,9 +165,9 @@ describe('loadSurroundingMessages', () => {
);
});

it('logs and rejects with the same error when the SDK call fails', async () => {
it('logs and rejects with the same error when loading fails', async () => {
const error = new Error('boom');
mockedMethodCall.mockRejectedValue(error);
mockedGetSurroundingMessages.mockRejectedValue(error);

await expect(loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })).rejects.toBe(error);

Expand Down
40 changes: 40 additions & 0 deletions app/lib/methods/loadMessagesForRoom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,46 @@ describe('loadMessagesForRoom', () => {
expect(mockedDispatch).not.toHaveBeenCalledWith(expect.objectContaining({ type: ROOM.HISTORY_UI_LOADER_PUSH }));
});

const buildMillisecondBatch = (prefix: string, baseSeconds: number, t?: string) =>
Array.from({ length: 50 }, (_, index) =>
buildMessage({
id: `${prefix}-${index + 1}`,
ts: new Date(Date.UTC(2024, 0, 1, 0, 0, baseSeconds, 999 - index * 7)).toISOString(),
t
})
);

it('stamps the trailing Older Loader one millisecond before the oldest Message of the Chunk', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: these new tests go into a file outside __tests__, but this PR already moved loadNextMessages.test.ts into app/lib/methods/__tests__/. Could this file move too?

const batch = buildMillisecondBatch('visible', 30);
const oldest = batch[batch.length - 1];

mockedSdkGet.mockResolvedValueOnce({ success: true, messages: batch } as any);

await loadMessagesForRoom({ rid: 'ROOM_ID', t: 'c' });

const { update } = mockedUpdateMessages.mock.calls[0][0] as { update: { _id: string; t?: string; ts: string | Date }[] };
const loaderRow = update.find(m => m.t === 'load_more');
expect(loaderRow?._id).toBe('load-more-visible-50');
expect(new Date(loaderRow?.ts as string | Date).getTime()).toBe(new Date(oldest.ts).getTime() - 1);
});

it('stamps the intermediate Older Loader one millisecond before the oldest Message of the first batch', async () => {
const firstBatch = buildMillisecondBatch('first', 30, 'uj');
const secondBatch = buildMillisecondBatch('second', 10);
const oldest = firstBatch[firstBatch.length - 1];

mockedSdkGet
.mockResolvedValueOnce({ success: true, messages: firstBatch } as any)
.mockResolvedValueOnce({ success: true, messages: secondBatch } as any);

await loadMessagesForRoom({ rid: 'ROOM_ID', t: 'c' });

const { update } = mockedUpdateMessages.mock.calls[0][0] as { update: { _id: string; t?: string; ts: string | Date }[] };
const loaderRow = update.find(m => m.t === 'load_more');
expect(loaderRow?._id).toBe('load-more-first-50');
expect(new Date(loaderRow?.ts as string | Date).getTime()).toBe(new Date(oldest.ts).getTime() - 1);
});

it('pops the ui loader when a recursive batch fetch fails after the loader was pushed', async () => {
const firstBatch = buildHiddenBatch('first', 50);
const networkError = new Error('boom');
Expand Down
Loading
Loading