From 065b8d2f63da451b1ca0db626a6f3b6afa052df8 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:09:22 +0530 Subject: [PATCH 01/19] chore: migrate loadNextMessages DDP method to GET rooms.history The loadNextMessages DDP method is removed in server 9.0.0. On servers >= 8.9.0 the Newer Loader now loads through GET /v1/rooms.history; older servers keep the DDP call. An empty response removes the Newer Loader row instead of leaving it stuck. --- app/definitions/rest/v1/rooms.ts | 8 +- .../__tests__/loadNextMessages.test.ts | 126 +++++++++++++++++ app/lib/methods/loadNextMessages.test.ts | 129 ------------------ app/lib/methods/loadNextMessages.ts | 36 +++-- .../__tests__/restApi.getNextMessages.test.ts | 123 +++++++++++++++++ app/lib/services/restApi.ts | 25 ++++ 6 files changed, 298 insertions(+), 149 deletions(-) create mode 100644 app/lib/methods/__tests__/loadNextMessages.test.ts delete mode 100644 app/lib/methods/loadNextMessages.test.ts create mode 100644 app/lib/services/__tests__/restApi.getNextMessages.test.ts diff --git a/app/definitions/rest/v1/rooms.ts b/app/definitions/rest/v1/rooms.ts index b35922df0d8..69daa2820c7 100644 --- a/app/definitions/rest/v1/rooms.ts +++ b/app/definitions/rest/v1/rooms.ts @@ -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'; @@ -57,6 +57,12 @@ export type RoomsEndpoints = { 'rooms.invite': { POST: (params: { roomId: string; action: 'accept' | 'reject' }) => void; }; + 'rooms.history': { + GET: (params: { roomId: IServerRoom['_id']; next?: string; count?: number; showThreadMessages?: boolean }) => { + messages: IMessageFromServer[]; + cursor: { next: string | null; previous: string | null }; + }; + }; }; export type TRoomsMediaResponse = { diff --git a/app/lib/methods/__tests__/loadNextMessages.test.ts b/app/lib/methods/__tests__/loadNextMessages.test.ts new file mode 100644 index 00000000000..12cd9ff961b --- /dev/null +++ b/app/lib/methods/__tests__/loadNextMessages.test.ts @@ -0,0 +1,126 @@ +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 dayjs from '../../dayjs'; +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; +const mockedGetMessageById = getMessageById as jest.MockedFunction; +const mockedUpdateMessages = updateMessages as jest.MockedFunction; +const mockedLog = log as jest.MockedFunction; + +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 NEWEST_MS = TS.getTime() + COUNT * 1000; + +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 after the last loaded message, one millisecond before the loader', async () => { + serve([], false); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + expect(mockedGetNextMessages).toHaveBeenCalledWith({ rid: RID, after: new Date(TS.getTime() - 1), 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'); + const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; + expect(update).toHaveLength(COUNT + 1); + expect(update.slice(0, COUNT)).toEqual(messages); + const loaderRow = update[COUNT]; + expect(loaderRow._id).toBe('load-more-msg-50'); + expect(loaderRow.rid).toBe(RID); + expect(loaderRow.t).toBe(MessageTypeLoad.NEXT_CHUNK); + expect(dayjs(loaderRow.ts).valueOf()).toBe(NEWEST_MS + 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(); + }); +}); diff --git a/app/lib/methods/loadNextMessages.test.ts b/app/lib/methods/loadNextMessages.test.ts deleted file mode 100644 index f1009d1360c..00000000000 --- a/app/lib/methods/loadNextMessages.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { loadNextMessages } from './loadNextMessages'; -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() } -})); - -jest.mock('../database/services/Message', () => ({ - getMessageById: jest.fn() -})); - -jest.mock('./updateMessages', () => jest.fn()); - -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; -const mockedGetMessageById = getMessageById as jest.MockedFunction; -const mockedUpdateMessages = updateMessages as jest.MockedFunction; -const mockedLog = log as jest.MockedFunction; - -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 buildMessage = (id: string, ts: Date) => ({ _id: id, rid: RID, ts, msg: `msg-${id}` }) as any; - -const buildPage = (length: number, baseMs = Date.UTC(2024, 0, 1, 12, 0, 0)) => - Array.from({ length }, (_, index) => buildMessage(`msg-${index + 1}`, new Date(baseMs + (index + 1) * 1000))); - -describe('loadNextMessages', () => { - beforeEach(() => { - jest.clearAllMocks(); - mockedGetMessageById.mockResolvedValue(null as never); - mockedUpdateMessages.mockResolvedValue(0 as never); - }); - - it('resolves without delegating when the server returns no messages', async () => { - mockedMethodCall.mockResolvedValue({ messages: [] } as never); - - await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).resolves.toBeUndefined(); - - expect(mockedMethodCall).toHaveBeenCalledWith('loadNextMessages', RID, TS, COUNT); - expect(mockedUpdateMessages).not.toHaveBeenCalled(); - expect(mockedGetMessageById).not.toHaveBeenCalled(); - }); - - it('delegates a partial page with no marker', async () => { - const messages = buildPage(10); - - mockedMethodCall.mockResolvedValue({ messages } as never); - - await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); - - expect(mockedUpdateMessages).toHaveBeenCalledTimes(1); - expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: messages, loaderItem: LOADER_ITEM }); - }); - - it('appends a load_next_chunk marker on a full page when the last message is not local', async () => { - const messages = buildPage(COUNT); - - mockedMethodCall.mockResolvedValue({ messages } as never); - - await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); - - const lastMessage = messages[messages.length - 1]; - expect(mockedGetMessageById).toHaveBeenCalledWith(lastMessage._id); - const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; - expect(update).toHaveLength(COUNT + 1); - const marker = update[update.length - 1]; - expect(marker._id).toBe(`load-more-${lastMessage._id}`); - expect(marker.rid).toBe(lastMessage.rid); - expect(marker.t).toBe(MessageTypeLoad.NEXT_CHUNK); - expect(dayjs(marker.ts).valueOf()).toBe(dayjs(lastMessage.ts).add(1, 'millisecond').valueOf()); - expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update, loaderItem: LOADER_ITEM }); - }); - - it('adds no marker on a full page when the last message is already local', async () => { - const messages = buildPage(COUNT); - mockedMethodCall.mockResolvedValue({ messages } as never); - mockedGetMessageById.mockResolvedValue({ id: messages[messages.length - 1]._id } as never); - - await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); - - const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; - expect(update).toHaveLength(COUNT); - expect(update.find(m => m.t === MessageTypeLoad.NEXT_CHUNK)).toBeUndefined(); - }); - - it('orders decoded messages by ts ascending before picking the last message', async () => { - const ordered = buildPage(COUNT); - const unordered = [...ordered].reverse(); - mockedMethodCall.mockResolvedValue({ messages: unordered } as never); - - await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); - - const lastMessage = ordered[ordered.length - 1]; - expect(mockedGetMessageById).toHaveBeenCalledWith(lastMessage._id); - const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; - expect(update.slice(0, COUNT).map(m => m._id)).toEqual(ordered.map(m => m._id)); - const marker = update[update.length - 1]; - expect(marker._id).toBe(`load-more-${lastMessage._id}`); - expect(dayjs(marker.ts).valueOf()).toBe(dayjs(lastMessage.ts).add(1, 'millisecond').valueOf()); - }); - - it('logs and rejects with the same error when the SDK call fails', async () => { - const error = new Error('boom'); - mockedMethodCall.mockRejectedValue(error); - - await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).rejects.toBe(error); - - expect(mockedLog).toHaveBeenCalledWith(error); - expect(mockedUpdateMessages).not.toHaveBeenCalled(); - }); -}); diff --git a/app/lib/methods/loadNextMessages.ts b/app/lib/methods/loadNextMessages.ts index f52c5e99621..137a6888a80 100644 --- a/app/lib/methods/loadNextMessages.ts +++ b/app/lib/methods/loadNextMessages.ts @@ -1,4 +1,3 @@ -import EJSON from 'ejson'; import orderBy from 'lodash/orderBy'; import dayjs from '../dayjs'; @@ -6,8 +5,8 @@ import log from './helpers/log'; import { getMessageById } from '../database/services/Message'; import { MessageTypeLoad } from '../constants/messageTypeLoad'; import updateMessages from './updateMessages'; -import { type TMessageModel } from '~/definitions'; -import sdk from '../services/sdk'; +import { type IMessage, type TMessageModel } from '~/definitions'; +import { getNextMessages } from '../services/restApi'; import { generateLoadMoreId } from './helpers/generateLoadMoreId'; const COUNT = 50; @@ -21,24 +20,23 @@ interface ILoadNextMessages { export function loadNextMessages(args: ILoadNextMessages): Promise { return new Promise(async (resolve, reject) => { try { - const data = await sdk.methodCallWrapper('loadNextMessages', args.rid, args.ts, COUNT); - let messages = EJSON.fromJSONValue(data?.messages); - messages = orderBy(messages, 'ts'); - if (messages?.length) { - const lastMessage = messages[messages.length - 1]; - const lastMessageRecord = await getMessageById(lastMessage._id); - if (!lastMessageRecord && messages.length === COUNT) { - const loadMoreItem = { - _id: generateLoadMoreId(lastMessage._id), - rid: lastMessage.rid, - ts: dayjs(lastMessage.ts).add(1, 'millisecond'), - t: MessageTypeLoad.NEXT_CHUNK - }; - messages.push(loadMoreItem); - } - await updateMessages({ rid: args.rid, update: messages, loaderItem: args.loaderItem }); + const after = dayjs(args.ts).subtract(1, 'millisecond').toDate(); + const { messages: fetched, hasMore } = await getNextMessages({ rid: args.rid, after, count: COUNT }); + const messages = orderBy(fetched, 'ts'); + if (!messages.length) { + await updateMessages({ rid: args.rid, update: [], remove: [{ _id: args.loaderItem.id }] }); return resolve(); } + const lastMessage = messages[messages.length - 1]; + if (hasMore && !(await getMessageById(lastMessage._id))) { + messages.push({ + _id: generateLoadMoreId(lastMessage._id), + rid: lastMessage.rid, + ts: dayjs(lastMessage.ts).add(1, 'millisecond').toDate(), + t: MessageTypeLoad.NEXT_CHUNK + } as IMessage); + } + await updateMessages({ rid: args.rid, update: messages, loaderItem: args.loaderItem }); return resolve(); } catch (e) { log(e); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts new file mode 100644 index 00000000000..f0aad4f4518 --- /dev/null +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -0,0 +1,123 @@ +import { store as reduxStore } from '../../store/auxStore'; +import sdk from '../sdk'; +import { getNextMessages } from '../restApi'; + +jest.mock('../../store/auxStore', () => ({ + store: { + getState: jest.fn() + } +})); + +jest.mock('../sdk', () => ({ + __esModule: true, + default: { + get: jest.fn(), + methodCallWrapper: jest.fn() + } +})); + +const mockedGet = sdk.get as jest.Mock; +const mockedMethodCallWrapper = sdk.methodCallWrapper as jest.Mock; + +const setServerVersion = (version: string) => (reduxStore.getState as jest.Mock).mockReturnValue({ server: { version } }); + +const RID = 'ROOM_ID'; +const AFTER_MS = 1704110400000; +const AFTER = new Date(AFTER_MS); +const COUNT = 3; + +const restResponse = (ids: string[], next: string | null) => ({ + success: true, + messages: ids.map(_id => ({ _id, rid: RID })), + cursor: { next, previous: String(AFTER_MS + 1000) } +}); + +const ddpResponse = (ids: string[]) => ({ + messages: ids.map((_id, index) => ({ _id, rid: RID, ts: { $date: AFTER_MS + 1000 + index } })) +}); + +describe('getNextMessages', () => { + beforeEach(() => { + jest.clearAllMocks(); + setServerVersion('8.9.0'); + mockedGet.mockResolvedValue(restResponse([], null)); + mockedMethodCallWrapper.mockResolvedValue(ddpResponse([])); + }); + + it.each([ + ['8.8.9', 1, 0], + ['8.9.0', 0, 1], + ['8.10.0', 0, 1] + ])('server %s makes %i DDP call(s) and %i REST call(s)', async (version, ddpCalls, restCalls) => { + setServerVersion(version); + + await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(mockedMethodCallWrapper).toHaveBeenCalledTimes(ddpCalls); + expect(mockedGet).toHaveBeenCalledTimes(restCalls); + }); + + it('requests the messages after the given timestamp without thread replies', async () => { + await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(mockedGet).toHaveBeenCalledWith('rooms.history', { + roomId: RID, + next: String(AFTER_MS), + count: COUNT, + showThreadMessages: false + }); + }); + + it.each([ + ['more newer messages exist', String(AFTER_MS + 3000), true], + ['no newer messages exist', null, false] + ])('reports hasMore from the cursor when %s', async (_name, next, hasMore) => { + mockedGet.mockResolvedValue(restResponse(['a', 'b', 'c'], next)); + + const result = await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(result.hasMore).toBe(hasMore); + expect(result.messages.map(message => message._id)).toEqual(['a', 'b', 'c']); + }); + + it('rejects instead of returning no messages when the response is not successful', async () => { + mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); + + await expect(getNextMessages({ rid: RID, after: AFTER, count: COUNT })).rejects.toThrow('Unable to load newer messages'); + }); + + it('does not turn a failed REST call into an empty response', async () => { + const error = { status: 429 }; + mockedGet.mockRejectedValue(error); + + await expect(getNextMessages({ rid: RID, after: AFTER, count: COUNT })).rejects.toBe(error); + }); + + describe('below 8.9.0', () => { + beforeEach(() => setServerVersion('8.8.9')); + + it('asks the DDP method for the messages after the given timestamp', async () => { + await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(mockedMethodCallWrapper).toHaveBeenCalledWith('loadNextMessages', RID, AFTER, COUNT); + }); + + it.each([ + ['a full response', ['a', 'b', 'c'], true], + ['a partial response', ['a', 'b'], false] + ])('decodes the DDP dates and guesses hasMore from %s', async (_name, ids, hasMore) => { + mockedMethodCallWrapper.mockResolvedValue(ddpResponse(ids)); + + const result = await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(result.hasMore).toBe(hasMore); + expect(result.messages[0].ts).toEqual(new Date(AFTER_MS + 1000)); + }); + + it('rejects a DDP reply without messages instead of reporting nothing newer', async () => { + mockedMethodCallWrapper.mockResolvedValue(undefined); + + await expect(getNextMessages({ rid: RID, after: AFTER, count: COUNT })).rejects.toThrow('Unable to load newer messages'); + }); + }); +}); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 3981dbf5210..e550b3cbb2d 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -1,9 +1,11 @@ import { settings as RocketChatSettings } from '@rocket.chat/sdk'; +import EJSON from 'ejson'; import { getUniqueId } from 'react-native-device-info'; import type { ServerMediaSignal } from '@rocket.chat/media-signaling'; import { type IAvatarSuggestion, + type IMessage, type IMessagePreferences, type INotificationPreferences, type IPreviewItem, @@ -26,6 +28,7 @@ import { uploadUserAvatarMultipart } from '../methods/uploadAvatar/uploadAvatar' import { compareServerVersion, getBundleId, isIOS } from '../methods/helpers'; import { getDeviceToken } from '../notifications/deviceToken'; import NativeVoipModule from '../native/NativeVoip'; +import { tsToMs } from '../dayjs'; import { store as reduxStore } from '../store/auxStore'; import sdk from './sdk'; import fetch from '../methods/helpers/fetch'; @@ -898,6 +901,28 @@ export const getSyncThreadsList = ({ rid, updatedSince }: { rid: string; updated updatedSince }); +export const getNextMessages = async ({ rid, after, count }: { rid: string; after: Date; count: number }) => { + const serverVersion = reduxStore.getState().server.version; + if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { + const history = await sdk.get('rooms.history', { + roomId: rid, + next: String(tsToMs(after)), + count, + showThreadMessages: false + }); + if (!history.success) { + throw new Error('Unable to load newer messages'); + } + return { messages: history.messages as IMessage[], hasMore: history.cursor.next !== null }; + } + const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); + if (!result?.messages) { + throw new Error('Unable to load newer messages'); + } + const messages: IMessage[] = EJSON.fromJSONValue(result.messages); + return { messages, hasMore: messages.length === count }; +}; + export const runSlashCommand = (command: string, roomId: string, params: string, triggerId?: string, tmid?: string) => // RC 0.60.2 sdk.post('commands.run', { From aeb4ca1938c8f53f4392e6b74e3986921f4e6029 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:21:32 +0530 Subject: [PATCH 02/19] test: assert the Newer Loader row in one expectation --- app/lib/methods/__tests__/loadNextMessages.test.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/app/lib/methods/__tests__/loadNextMessages.test.ts b/app/lib/methods/__tests__/loadNextMessages.test.ts index 12cd9ff961b..dc0e8e44953 100644 --- a/app/lib/methods/__tests__/loadNextMessages.test.ts +++ b/app/lib/methods/__tests__/loadNextMessages.test.ts @@ -3,7 +3,6 @@ import { getNextMessages } 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', () => ({ @@ -92,14 +91,10 @@ describe('loadNextMessages', () => { await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); expect(mockedGetMessageById).toHaveBeenCalledWith('msg-50'); - const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; - expect(update).toHaveLength(COUNT + 1); - expect(update.slice(0, COUNT)).toEqual(messages); - const loaderRow = update[COUNT]; - expect(loaderRow._id).toBe('load-more-msg-50'); - expect(loaderRow.rid).toBe(RID); - expect(loaderRow.t).toBe(MessageTypeLoad.NEXT_CHUNK); - expect(dayjs(loaderRow.ts).valueOf()).toBe(NEWEST_MS + 1); + expect(mockedUpdateMessages.mock.calls[0][0].update).toEqual([ + ...messages, + { _id: 'load-more-msg-50', rid: RID, t: MessageTypeLoad.NEXT_CHUNK, ts: new Date(NEWEST_MS + 1) } + ]); }); it('stores a newest-first response oldest-first', async () => { From 9fd627b1b8195350d62f0b69901461185b958c14 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:29:02 +0530 Subject: [PATCH 03/19] fix: return rooms.history _updatedAt as a Date so thread rows keep updating updateMessages compares stored thread rows against the incoming _updatedAt with <, which is always false for an ISO string. The DDP reply carried Dates, so the REST path stopped updating existing threads and thread_messages rows from the Newer Loader. --- app/lib/methods/__tests__/loadNextMessages.test.ts | 3 +-- .../__tests__/restApi.getNextMessages.test.ts | 11 ++++++++++- app/lib/services/restApi.ts | 3 ++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/app/lib/methods/__tests__/loadNextMessages.test.ts b/app/lib/methods/__tests__/loadNextMessages.test.ts index dc0e8e44953..a1423b4ea5b 100644 --- a/app/lib/methods/__tests__/loadNextMessages.test.ts +++ b/app/lib/methods/__tests__/loadNextMessages.test.ts @@ -29,7 +29,6 @@ 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 NEWEST_MS = TS.getTime() + COUNT * 1000; const buildMessages = (length: number) => Array.from( @@ -93,7 +92,7 @@ describe('loadNextMessages', () => { 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(NEWEST_MS + 1) } + { _id: 'load-more-msg-50', rid: RID, t: MessageTypeLoad.NEXT_CHUNK, ts: new Date(messages[COUNT - 1].ts.getTime() + 1) } ]); }); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index f0aad4f4518..f85dba75753 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -25,10 +25,11 @@ const RID = 'ROOM_ID'; const AFTER_MS = 1704110400000; const AFTER = new Date(AFTER_MS); const COUNT = 3; +const UPDATED_AT = '2024-01-01T12:00:01.000Z'; const restResponse = (ids: string[], next: string | null) => ({ success: true, - messages: ids.map(_id => ({ _id, rid: RID })), + messages: ids.map(_id => ({ _id, rid: RID, _updatedAt: UPDATED_AT })), cursor: { next, previous: String(AFTER_MS + 1000) } }); @@ -80,6 +81,14 @@ describe('getNextMessages', () => { expect(result.messages.map(message => message._id)).toEqual(['a', 'b', 'c']); }); + it('returns _updatedAt as a Date', async () => { + mockedGet.mockResolvedValue(restResponse(['a'], null)); + + const result = await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(result.messages[0]._updatedAt).toEqual(new Date(UPDATED_AT)); + }); + it('rejects instead of returning no messages when the response is not successful', async () => { mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index e550b3cbb2d..2d9dd9fc75e 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -913,7 +913,8 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte if (!history.success) { throw new Error('Unable to load newer messages'); } - return { messages: history.messages as IMessage[], hasMore: history.cursor.next !== null }; + const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })) as IMessage[]; + return { messages, hasMore: history.cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); if (!result?.messages) { From ade7e2d5e02497c196f1ddb0409946d71c5051af Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:42:55 +0530 Subject: [PATCH 04/19] fix: convert a string _updatedAt to a Date in normalizeMessage updateMessages compares stored thread rows against the incoming _updatedAt with <, which is always false for an ISO string. Convert it where the message is normalized instead of in getNextMessages, so every REST loader feeding updateMessages gets the comparison right. Dates, numbers and a missing value are left as they were. --- app/lib/methods/helpers/buildMessage.test.ts | 7 +++++++ app/lib/methods/helpers/normalizeMessage.ts | 3 ++- .../__tests__/restApi.getNextMessages.test.ts | 11 +---------- app/lib/services/restApi.ts | 3 +-- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/app/lib/methods/helpers/buildMessage.test.ts b/app/lib/methods/helpers/buildMessage.test.ts index 33323345050..25e9bb00fcd 100644 --- a/app/lib/methods/helpers/buildMessage.test.ts +++ b/app/lib/methods/helpers/buildMessage.test.ts @@ -142,6 +142,13 @@ describe('normalizeMessage', () => { expect((normalizeMessage({ _id: 'm1', _updatedAt: kept } as any) as any)._updatedAt).toBe(kept); }); + it('converts an ISO string _updatedAt to a Date', () => { + const iso = '2024-01-15T12:00:00.000Z'; + const result = normalizeMessage({ _id: 'm1', _updatedAt: iso } as any) as any; + + expect(result._updatedAt).toEqual(new Date(iso)); + }); + it('normalizes starred', () => { expect((normalizeMessage({ _id: 'm1', starred: [{ _id: 'u1' }] } as any) as any).starred).toBe(true); expect((normalizeMessage({ _id: 'm1', starred: [] } as any) as any).starred).toBe(false); diff --git a/app/lib/methods/helpers/normalizeMessage.ts b/app/lib/methods/helpers/normalizeMessage.ts index 82e5a6f7856..0dbda65dec2 100644 --- a/app/lib/methods/helpers/normalizeMessage.ts +++ b/app/lib/methods/helpers/normalizeMessage.ts @@ -53,7 +53,8 @@ export default (msg: any): IMessage | IThreadResult | null => { msg.autoTranslate = true; } msg.urls = msg.urls ? parseUrls(msg.urls) : []; - msg._updatedAt = msg._updatedAt || new Date(); + const updatedAt = msg._updatedAt || new Date(); + msg._updatedAt = typeof updatedAt === 'string' ? new Date(updatedAt) : updatedAt; // loadHistory returns msg.starred as object // stream-room-msgs returns msg.starred as an array msg.starred = msg.starred && (Array.isArray(msg.starred) ? msg.starred.length > 0 : !!msg.starred); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index f85dba75753..f0aad4f4518 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -25,11 +25,10 @@ const RID = 'ROOM_ID'; const AFTER_MS = 1704110400000; const AFTER = new Date(AFTER_MS); const COUNT = 3; -const UPDATED_AT = '2024-01-01T12:00:01.000Z'; const restResponse = (ids: string[], next: string | null) => ({ success: true, - messages: ids.map(_id => ({ _id, rid: RID, _updatedAt: UPDATED_AT })), + messages: ids.map(_id => ({ _id, rid: RID })), cursor: { next, previous: String(AFTER_MS + 1000) } }); @@ -81,14 +80,6 @@ describe('getNextMessages', () => { expect(result.messages.map(message => message._id)).toEqual(['a', 'b', 'c']); }); - it('returns _updatedAt as a Date', async () => { - mockedGet.mockResolvedValue(restResponse(['a'], null)); - - const result = await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); - - expect(result.messages[0]._updatedAt).toEqual(new Date(UPDATED_AT)); - }); - it('rejects instead of returning no messages when the response is not successful', async () => { mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 2d9dd9fc75e..e550b3cbb2d 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -913,8 +913,7 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte if (!history.success) { throw new Error('Unable to load newer messages'); } - const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })) as IMessage[]; - return { messages, hasMore: history.cursor.next !== null }; + return { messages: history.messages as IMessage[], hasMore: history.cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); if (!result?.messages) { From 1b3f8edb01ae2ae0a24d8054b34a48a1cca6af16 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:57:02 +0530 Subject: [PATCH 05/19] test: cover an ISO string _updatedAt through updateMessages with the real buildMessage The existing thread tests mock buildMessage as identity and use numeric _updatedAt, so they pass with or without the Date conversion. Run the thread and thread message update paths through the real buildMessage with a stored Date and an incoming ISO string. --- app/lib/methods/updateMessages.test.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/app/lib/methods/updateMessages.test.ts b/app/lib/methods/updateMessages.test.ts index 53a06660f96..e9b8e7e15f4 100644 --- a/app/lib/methods/updateMessages.test.ts +++ b/app/lib/methods/updateMessages.test.ts @@ -3,6 +3,7 @@ import { getSubscriptionByRoomId } from '../database/services/Subscription'; import { makeFakeRecord } from '../database/__tests__/mockedWatermelonDB'; import { Encryption } from '../encryption'; import { generateLoadMoreId } from './helpers/generateLoadMoreId'; +import buildMessage from './helpers/buildMessage'; jest.mock('../database/services/Subscription', () => ({ getSubscriptionByRoomId: jest.fn() @@ -20,7 +21,7 @@ jest.mock('@nozbe/watermelondb/RawRecord', () => ({ jest.mock('./helpers/buildMessage', () => ({ __esModule: true, - default: (message: unknown) => message + default: jest.fn() })); jest.mock('./helpers/protectedFunction', () => ({ @@ -73,6 +74,7 @@ describe('updateMessages', () => { beforeEach(() => { jest.clearAllMocks(); + (buildMessage as jest.Mock).mockImplementation((message: unknown) => message); mockDbBatch.mockImplementation((records: any[]) => { records.filter(Boolean).forEach((r: any) => { r._preparedState = null; @@ -363,6 +365,25 @@ describe('updateMessages', () => { }); }); + describe('with the real buildMessage', () => { + beforeEach(() => { + (buildMessage as jest.Mock).mockImplementation(jest.requireActual('./helpers/buildMessage').default); + }); + + it.each([ + ['thread', 'threads', 't1', { tlm: { $date: 1 } }], + ['thread message', 'thread_messages', 'tm1', { tmid: 'parent' }] + ])('updates a stored %s when the incoming _updatedAt is a newer ISO string', async (_name, table, _id, fields) => { + const record = makeFakeRecord(`${table}#${_id}`, { msg: 'old', _updatedAt: new Date('2024-01-01T00:00:00.000Z') }); + setRecords(table, [record]); + + await updateMessages({ rid, update: [{ _id, rid, msg: 'new', _updatedAt: '2024-01-02T00:00:00.000Z', ...fields } as any] }); + + expect(record.msg).toBe('new'); + expect(batched()).toContain(record); + }); + }); + describe('batch', () => { it('batches every prepared record once and returns how many there were', async () => { setRecords('messages', []); From 910d8651eeed8e85a958ca8b75b8a5cd1967154c Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:13:41 +0530 Subject: [PATCH 06/19] fix: convert _updatedAt to a Date in getNextMessages instead of normalizeMessage The rooms.history response carries ISO strings, which never compare as newer in the thread branches of updateMessages. Converting in the REST branch of the wrapper keeps normalizeMessage, loadMessagesForRoom and loadMissedMessages unchanged, so those loaders do not start refreshing stored thread rows and overwriting their downloaded file:// title_link. --- app/lib/methods/helpers/buildMessage.test.ts | 7 ------ app/lib/methods/helpers/normalizeMessage.ts | 3 +-- app/lib/methods/updateMessages.test.ts | 23 +------------------ .../__tests__/restApi.getNextMessages.test.ts | 12 ++++++++++ app/lib/services/restApi.ts | 3 ++- 5 files changed, 16 insertions(+), 32 deletions(-) diff --git a/app/lib/methods/helpers/buildMessage.test.ts b/app/lib/methods/helpers/buildMessage.test.ts index 25e9bb00fcd..33323345050 100644 --- a/app/lib/methods/helpers/buildMessage.test.ts +++ b/app/lib/methods/helpers/buildMessage.test.ts @@ -142,13 +142,6 @@ describe('normalizeMessage', () => { expect((normalizeMessage({ _id: 'm1', _updatedAt: kept } as any) as any)._updatedAt).toBe(kept); }); - it('converts an ISO string _updatedAt to a Date', () => { - const iso = '2024-01-15T12:00:00.000Z'; - const result = normalizeMessage({ _id: 'm1', _updatedAt: iso } as any) as any; - - expect(result._updatedAt).toEqual(new Date(iso)); - }); - it('normalizes starred', () => { expect((normalizeMessage({ _id: 'm1', starred: [{ _id: 'u1' }] } as any) as any).starred).toBe(true); expect((normalizeMessage({ _id: 'm1', starred: [] } as any) as any).starred).toBe(false); diff --git a/app/lib/methods/helpers/normalizeMessage.ts b/app/lib/methods/helpers/normalizeMessage.ts index 0dbda65dec2..82e5a6f7856 100644 --- a/app/lib/methods/helpers/normalizeMessage.ts +++ b/app/lib/methods/helpers/normalizeMessage.ts @@ -53,8 +53,7 @@ export default (msg: any): IMessage | IThreadResult | null => { msg.autoTranslate = true; } msg.urls = msg.urls ? parseUrls(msg.urls) : []; - const updatedAt = msg._updatedAt || new Date(); - msg._updatedAt = typeof updatedAt === 'string' ? new Date(updatedAt) : updatedAt; + msg._updatedAt = msg._updatedAt || new Date(); // loadHistory returns msg.starred as object // stream-room-msgs returns msg.starred as an array msg.starred = msg.starred && (Array.isArray(msg.starred) ? msg.starred.length > 0 : !!msg.starred); diff --git a/app/lib/methods/updateMessages.test.ts b/app/lib/methods/updateMessages.test.ts index e9b8e7e15f4..53a06660f96 100644 --- a/app/lib/methods/updateMessages.test.ts +++ b/app/lib/methods/updateMessages.test.ts @@ -3,7 +3,6 @@ import { getSubscriptionByRoomId } from '../database/services/Subscription'; import { makeFakeRecord } from '../database/__tests__/mockedWatermelonDB'; import { Encryption } from '../encryption'; import { generateLoadMoreId } from './helpers/generateLoadMoreId'; -import buildMessage from './helpers/buildMessage'; jest.mock('../database/services/Subscription', () => ({ getSubscriptionByRoomId: jest.fn() @@ -21,7 +20,7 @@ jest.mock('@nozbe/watermelondb/RawRecord', () => ({ jest.mock('./helpers/buildMessage', () => ({ __esModule: true, - default: jest.fn() + default: (message: unknown) => message })); jest.mock('./helpers/protectedFunction', () => ({ @@ -74,7 +73,6 @@ describe('updateMessages', () => { beforeEach(() => { jest.clearAllMocks(); - (buildMessage as jest.Mock).mockImplementation((message: unknown) => message); mockDbBatch.mockImplementation((records: any[]) => { records.filter(Boolean).forEach((r: any) => { r._preparedState = null; @@ -365,25 +363,6 @@ describe('updateMessages', () => { }); }); - describe('with the real buildMessage', () => { - beforeEach(() => { - (buildMessage as jest.Mock).mockImplementation(jest.requireActual('./helpers/buildMessage').default); - }); - - it.each([ - ['thread', 'threads', 't1', { tlm: { $date: 1 } }], - ['thread message', 'thread_messages', 'tm1', { tmid: 'parent' }] - ])('updates a stored %s when the incoming _updatedAt is a newer ISO string', async (_name, table, _id, fields) => { - const record = makeFakeRecord(`${table}#${_id}`, { msg: 'old', _updatedAt: new Date('2024-01-01T00:00:00.000Z') }); - setRecords(table, [record]); - - await updateMessages({ rid, update: [{ _id, rid, msg: 'new', _updatedAt: '2024-01-02T00:00:00.000Z', ...fields } as any] }); - - expect(record.msg).toBe('new'); - expect(batched()).toContain(record); - }); - }); - describe('batch', () => { it('batches every prepared record once and returns how many there were', async () => { setRecords('messages', []); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index f0aad4f4518..9af2b39896a 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -80,6 +80,18 @@ describe('getNextMessages', () => { expect(result.messages.map(message => message._id)).toEqual(['a', 'b', 'c']); }); + it('converts the ISO _updatedAt of each REST message to a Date', async () => { + const updatedAt = '2024-01-15T12:00:00.000Z'; + mockedGet.mockResolvedValue({ + ...restResponse([], null), + messages: [{ _id: 'a', rid: RID, _updatedAt: updatedAt }] + }); + + const result = await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(result.messages[0]._updatedAt).toEqual(new Date(updatedAt)); + }); + it('rejects instead of returning no messages when the response is not successful', async () => { mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index e550b3cbb2d..f3c05251fd5 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -913,7 +913,8 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte if (!history.success) { throw new Error('Unable to load newer messages'); } - return { messages: history.messages as IMessage[], hasMore: history.cursor.next !== null }; + const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })); + return { messages: messages as IMessage[], hasMore: history.cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); if (!result?.messages) { From 2d9458ee70d5d046d10a568c1b557676347e49ae Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:13:41 +0530 Subject: [PATCH 07/19] refactor: make loadNextMessages an async function --- app/lib/methods/loadNextMessages.ts | 47 ++++++++++++++--------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/app/lib/methods/loadNextMessages.ts b/app/lib/methods/loadNextMessages.ts index 137a6888a80..2a2173a0340 100644 --- a/app/lib/methods/loadNextMessages.ts +++ b/app/lib/methods/loadNextMessages.ts @@ -17,30 +17,27 @@ interface ILoadNextMessages { loaderItem: TMessageModel; } -export function loadNextMessages(args: ILoadNextMessages): Promise { - return new Promise(async (resolve, reject) => { - try { - const after = dayjs(args.ts).subtract(1, 'millisecond').toDate(); - const { messages: fetched, hasMore } = await getNextMessages({ rid: args.rid, after, count: COUNT }); - const messages = orderBy(fetched, 'ts'); - if (!messages.length) { - await updateMessages({ rid: args.rid, update: [], remove: [{ _id: args.loaderItem.id }] }); - return resolve(); - } - const lastMessage = messages[messages.length - 1]; - if (hasMore && !(await getMessageById(lastMessage._id))) { - messages.push({ - _id: generateLoadMoreId(lastMessage._id), - rid: lastMessage.rid, - ts: dayjs(lastMessage.ts).add(1, 'millisecond').toDate(), - t: MessageTypeLoad.NEXT_CHUNK - } as IMessage); - } - await updateMessages({ rid: args.rid, update: messages, loaderItem: args.loaderItem }); - return resolve(); - } catch (e) { - log(e); - reject(e); +export async function loadNextMessages(args: ILoadNextMessages): Promise { + try { + const after = dayjs(args.ts).subtract(1, 'millisecond').toDate(); + const { messages: fetched, hasMore } = await getNextMessages({ rid: args.rid, after, count: COUNT }); + const messages = orderBy(fetched, 'ts'); + if (!messages.length) { + await updateMessages({ rid: args.rid, update: [], remove: [{ _id: args.loaderItem.id }] }); + return; } - }); + const lastMessage = messages[messages.length - 1]; + if (hasMore && !(await getMessageById(lastMessage._id))) { + messages.push({ + _id: generateLoadMoreId(lastMessage._id), + rid: lastMessage.rid, + ts: dayjs(lastMessage.ts).add(1, 'millisecond').toDate(), + t: MessageTypeLoad.NEXT_CHUNK + } as IMessage); + } + await updateMessages({ rid: args.rid, update: messages, loaderItem: args.loaderItem }); + } catch (e) { + log(e); + throw e; + } } From e31f8d6893dc68e7595295a28bb317a86a4f2342 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:14:28 +0530 Subject: [PATCH 08/19] chore: format the rooms.history type and import auxStore by alias in its test --- app/definitions/rest/v1/rooms.ts | 4 ++-- app/lib/services/__tests__/restApi.getNextMessages.test.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/definitions/rest/v1/rooms.ts b/app/definitions/rest/v1/rooms.ts index af42aeced01..e14a53178f6 100644 --- a/app/definitions/rest/v1/rooms.ts +++ b/app/definitions/rest/v1/rooms.ts @@ -61,8 +61,8 @@ export type RoomsEndpoints = { GET: (params: { roomId: IServerRoom['_id']; next?: string; count?: number; showThreadMessages?: boolean }) => { messages: IMessageFromServer[]; cursor: { next: string | null; previous: string | null }; - }; - }; + }; + }; 'rooms.join': { POST: (params: { roomId: string; joinCode: string | null }) => { room: IServerRoom; diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index 9af2b39896a..0c29c9670e2 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -1,8 +1,8 @@ -import { store as reduxStore } from '../../store/auxStore'; +import { store as reduxStore } from '~/lib/store/auxStore'; import sdk from '../sdk'; import { getNextMessages } from '../restApi'; -jest.mock('../../store/auxStore', () => ({ +jest.mock('~/lib/store/auxStore', () => ({ store: { getState: jest.fn() } From ae5b15e98119853644c84aa6a300b9ba1aae602e Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:29:19 +0530 Subject: [PATCH 09/19] refactor: use getTime() for the rooms.history cursor instead of tsToMs --- app/lib/services/restApi.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index b79645c698a..af3cf559f7f 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -28,7 +28,6 @@ import { uploadUserAvatarMultipart } from '../methods/uploadAvatar/uploadAvatar' import { compareServerVersion, getBundleId, isIOS } from '../methods/helpers'; import { getDeviceToken } from '../notifications/deviceToken'; import NativeVoipModule from '../native/NativeVoip'; -import { tsToMs } from '../dayjs'; import { store as reduxStore } from '../store/auxStore'; import sdk from './sdk'; import fetch from '../methods/helpers/fetch'; @@ -930,7 +929,7 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { const history = await sdk.get('rooms.history', { roomId: rid, - next: String(tsToMs(after)), + next: String(after.getTime()), count, showThreadMessages: false }); From 2d3c67ce555d01546b296cb868a77967c087247b Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:15:30 +0530 Subject: [PATCH 10/19] chore: remove duplicate ejson import and pass runSlashCommand params as an object --- .../MessageComposer/MessageComposer.test.tsx | 8 +++++++- .../MessageComposer/MessageComposer.tsx | 2 +- app/lib/services/restApi.ts | 15 +++++++++++++-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/app/containers/MessageComposer/MessageComposer.test.tsx b/app/containers/MessageComposer/MessageComposer.test.tsx index 56dce8186ae..ddc6a25c440 100644 --- a/app/containers/MessageComposer/MessageComposer.test.tsx +++ b/app/containers/MessageComposer/MessageComposer.test.tsx @@ -646,7 +646,13 @@ describe('MessageComposer', () => { await screen.findByTestId('autocomplete'); await user.press(screen.getByTestId('message-composer-send')); await waitFor(() => expect(screen.queryByTestId('autocomplete')).not.toBeOnTheScreen()); - expect(runSlashCommand).toHaveBeenCalledWith('hello', 'rid', '', expect.any(String), undefined); + expect(runSlashCommand).toHaveBeenCalledWith({ + command: 'hello', + roomId: 'rid', + params: '', + triggerId: expect.any(String), + tmid: undefined + }); expect(onSendMessage).not.toHaveBeenCalled(); }); diff --git a/app/containers/MessageComposer/MessageComposer.tsx b/app/containers/MessageComposer/MessageComposer.tsx index 0db6ef38897..626ab1929d2 100644 --- a/app/containers/MessageComposer/MessageComposer.tsx +++ b/app/containers/MessageComposer/MessageComposer.tsx @@ -174,7 +174,7 @@ export const MessageComposer = ({ const messageWithoutCommand = textFromInput.replace(/([^\s]+)/, '').trim(); const [{ appId }] = slashCommand; const triggerId = generateTriggerId(appId); - await runSlashCommand(command, rid, messageWithoutCommand, triggerId, tmid); + await runSlashCommand({ command, roomId: rid, params: messageWithoutCommand, triggerId, tmid }); } catch (e) { log(e); } diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 204d72adb03..a5e214a0ec3 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -1,5 +1,4 @@ import { settings as RocketChatSettings } from '@rocket.chat/sdk'; -import EJSON from 'ejson'; import { getUniqueId } from 'react-native-device-info'; import EJSON from 'ejson'; import type { ServerMediaSignal } from '@rocket.chat/media-signaling'; @@ -963,7 +962,19 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte return { messages, hasMore: messages.length === count }; }; -export const runSlashCommand = (command: string, roomId: string, params: string, triggerId?: string, tmid?: string) => +export const runSlashCommand = ({ + command, + roomId, + params, + triggerId, + tmid +}: { + command: string; + roomId: string; + params: string; + triggerId?: string; + tmid?: string; +}) => // RC 0.60.2 sdk.post('commands.run', { command, From b0ffceede535e7683b6e015948b0ebb9be8d5b30 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:22:26 +0530 Subject: [PATCH 11/19] revert: restore runSlashCommand positional params --- .../MessageComposer/MessageComposer.test.tsx | 8 +------- app/containers/MessageComposer/MessageComposer.tsx | 2 +- app/lib/services/restApi.ts | 14 +------------- 3 files changed, 3 insertions(+), 21 deletions(-) diff --git a/app/containers/MessageComposer/MessageComposer.test.tsx b/app/containers/MessageComposer/MessageComposer.test.tsx index ddc6a25c440..56dce8186ae 100644 --- a/app/containers/MessageComposer/MessageComposer.test.tsx +++ b/app/containers/MessageComposer/MessageComposer.test.tsx @@ -646,13 +646,7 @@ describe('MessageComposer', () => { await screen.findByTestId('autocomplete'); await user.press(screen.getByTestId('message-composer-send')); await waitFor(() => expect(screen.queryByTestId('autocomplete')).not.toBeOnTheScreen()); - expect(runSlashCommand).toHaveBeenCalledWith({ - command: 'hello', - roomId: 'rid', - params: '', - triggerId: expect.any(String), - tmid: undefined - }); + expect(runSlashCommand).toHaveBeenCalledWith('hello', 'rid', '', expect.any(String), undefined); expect(onSendMessage).not.toHaveBeenCalled(); }); diff --git a/app/containers/MessageComposer/MessageComposer.tsx b/app/containers/MessageComposer/MessageComposer.tsx index 626ab1929d2..0db6ef38897 100644 --- a/app/containers/MessageComposer/MessageComposer.tsx +++ b/app/containers/MessageComposer/MessageComposer.tsx @@ -174,7 +174,7 @@ export const MessageComposer = ({ const messageWithoutCommand = textFromInput.replace(/([^\s]+)/, '').trim(); const [{ appId }] = slashCommand; const triggerId = generateTriggerId(appId); - await runSlashCommand({ command, roomId: rid, params: messageWithoutCommand, triggerId, tmid }); + await runSlashCommand(command, rid, messageWithoutCommand, triggerId, tmid); } catch (e) { log(e); } diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index a5e214a0ec3..e2d045253af 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -962,19 +962,7 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte return { messages, hasMore: messages.length === count }; }; -export const runSlashCommand = ({ - command, - roomId, - params, - triggerId, - tmid -}: { - command: string; - roomId: string; - params: string; - triggerId?: string; - tmid?: string; -}) => +export const runSlashCommand = (command: string, roomId: string, params: string, triggerId?: string, tmid?: string) => // RC 0.60.2 sdk.post('commands.run', { command, From f33ff417678a1c249dd66c8b830cfa7a65cdf6de Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 02:04:59 +0530 Subject: [PATCH 12/19] chore: migrate loadSurroundingMessages DDP method to GET rooms.history The loadSurroundingMessages DDP method is deprecated and removed in server 9.0.0 in favor of the aroundId param of GET /v1/rooms.history. Servers >= 8.9.0 now use the endpoint through a new getSurroundingMessages wrapper; older servers keep the DDP call. --- app/definitions/rest/v1/rooms.ts | 8 +- .../loadSurroundingMessages.test.ts | 94 +++++------ app/lib/methods/loadSurroundingMessages.ts | 81 +++++----- .../restApi.getSurroundingMessages.test.ts | 146 ++++++++++++++++++ app/lib/services/restApi.ts | 27 ++++ 5 files changed, 266 insertions(+), 90 deletions(-) rename app/lib/methods/{ => __tests__}/loadSurroundingMessages.test.ts (60%) create mode 100644 app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts diff --git a/app/definitions/rest/v1/rooms.ts b/app/definitions/rest/v1/rooms.ts index e14a53178f6..19148d6d3bc 100644 --- a/app/definitions/rest/v1/rooms.ts +++ b/app/definitions/rest/v1/rooms.ts @@ -58,7 +58,13 @@ export type RoomsEndpoints = { POST: (params: { roomId: string; action: 'accept' | 'reject' }) => void; }; 'rooms.history': { - GET: (params: { roomId: IServerRoom['_id']; next?: string; count?: number; showThreadMessages?: boolean }) => { + GET: (params: { + roomId: IServerRoom['_id']; + next?: string; + aroundId?: IMessage['_id']; + count?: number; + showThreadMessages?: boolean; + }) => { messages: IMessageFromServer[]; cursor: { next: string | null; previous: string | null }; }; diff --git a/app/lib/methods/loadSurroundingMessages.test.ts b/app/lib/methods/__tests__/loadSurroundingMessages.test.ts similarity index 60% rename from app/lib/methods/loadSurroundingMessages.test.ts rename to app/lib/methods/__tests__/loadSurroundingMessages.test.ts index 01156d72eac..83ffeb9c5cf 100644 --- a/app/lib/methods/loadSurroundingMessages.test.ts +++ b/app/lib/methods/__tests__/loadSurroundingMessages.test.ts @@ -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; +const mockedGetSurroundingMessages = getSurroundingMessages as jest.MockedFunction; const mockedGetMessageById = getMessageById as jest.MockedFunction; const mockedUpdateMessages = updateMessages as jest.MockedFunction; const mockedLog = log as jest.MockedFunction; @@ -41,6 +35,9 @@ 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(); @@ -48,18 +45,25 @@ describe('loadSurroundingMessages', () => { mockedUpdateMessages.mockResolvedValue(0 as never); }); + it('asks for the window around the message', 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 }); @@ -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); @@ -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); @@ -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); @@ -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); @@ -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); diff --git a/app/lib/methods/loadSurroundingMessages.ts b/app/lib/methods/loadSurroundingMessages.ts index 2da40b05f20..c397dc91b74 100644 --- a/app/lib/methods/loadSurroundingMessages.ts +++ b/app/lib/methods/loadSurroundingMessages.ts @@ -1,62 +1,55 @@ -import EJSON from 'ejson'; import orderBy from 'lodash/orderBy'; import dayjs from '../dayjs'; import log from './helpers/log'; import { getMessageById } from '../database/services/Message'; import { MessageTypeLoad } from '../constants/messageTypeLoad'; -import sdk from '../services/sdk'; import { type IMessage } from '~/definitions'; import updateMessages from './updateMessages'; +import { getSurroundingMessages } from '../services/restApi'; import { generateLoadMoreId } from './helpers/generateLoadMoreId'; const COUNT = 50; -export function loadSurroundingMessages({ messageId, rid }: { messageId: string; rid: string }) { - return new Promise(async (resolve, reject) => { - try { - const data = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, COUNT); - let messages: IMessage[] = EJSON.fromJSONValue(data?.messages); - messages = orderBy(messages, 'ts'); +export async function loadSurroundingMessages({ messageId, rid }: { messageId: string; rid: string }): Promise { + try { + const { messages: fetched, moreBefore, moreAfter } = await getSurroundingMessages({ rid, messageId, count: COUNT }); + const messages = orderBy(fetched, 'ts'); - if (messages?.length) { - if (data?.moreBefore) { - const firstMessage = messages[0]; - const firstMessageRecord = await getMessageById(firstMessage._id); - if (!firstMessageRecord) { - const loadMoreItem = { - _id: generateLoadMoreId(firstMessage._id), - rid: firstMessage.rid, - ts: dayjs(firstMessage.ts).subtract(1, 'millisecond').toDate(), - t: MessageTypeLoad.PREVIOUS_CHUNK, - msg: firstMessage.msg - } as IMessage; - messages.unshift(loadMoreItem); - } - } + if (!messages.length) { + return []; + } - if (data?.moreAfter) { - const lastMessage = messages[messages.length - 1]; - const lastMessageRecord = await getMessageById(lastMessage._id); - if (!lastMessageRecord) { - const loadMoreItem = { - _id: generateLoadMoreId(lastMessage._id), - rid: lastMessage.rid, - ts: dayjs(lastMessage.ts).add(1, 'millisecond').toDate(), - t: MessageTypeLoad.NEXT_CHUNK, - msg: lastMessage.msg - } as IMessage; - messages.push(loadMoreItem); - } - } + if (moreBefore) { + const firstMessage = messages[0]; + if (!(await getMessageById(firstMessage._id))) { + messages.unshift({ + _id: generateLoadMoreId(firstMessage._id), + rid: firstMessage.rid, + ts: dayjs(firstMessage.ts).subtract(1, 'millisecond').toDate(), + t: MessageTypeLoad.PREVIOUS_CHUNK, + msg: firstMessage.msg + } as IMessage); + } + } - await updateMessages({ rid, update: messages }); - return resolve(messages); + if (moreAfter) { + const lastMessage = messages[messages.length - 1]; + if (!(await getMessageById(lastMessage._id))) { + messages.push({ + _id: generateLoadMoreId(lastMessage._id), + rid: lastMessage.rid, + ts: dayjs(lastMessage.ts).add(1, 'millisecond').toDate(), + t: MessageTypeLoad.NEXT_CHUNK, + msg: lastMessage.msg + } as IMessage); } - return resolve([]); - } catch (e) { - log(e); - reject(e); } - }); + + await updateMessages({ rid, update: messages }); + return messages; + } catch (e) { + log(e); + throw e; + } } diff --git a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts new file mode 100644 index 00000000000..038ec934518 --- /dev/null +++ b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts @@ -0,0 +1,146 @@ +import { store as reduxStore } from '~/lib/store/auxStore'; +import sdk from '../sdk'; +import { getSurroundingMessages } from '../restApi'; + +jest.mock('~/lib/store/auxStore', () => ({ + store: { + getState: jest.fn() + } +})); + +jest.mock('../sdk', () => ({ + __esModule: true, + default: { + get: jest.fn(), + methodCallWrapper: jest.fn() + } +})); + +const mockedGet = sdk.get as jest.Mock; +const mockedMethodCallWrapper = sdk.methodCallWrapper as jest.Mock; + +const setServerVersion = (version: string) => (reduxStore.getState as jest.Mock).mockReturnValue({ server: { version } }); + +const RID = 'ROOM_ID'; +const MESSAGE_ID = 'TARGET_ID'; +const TARGET_MS = 1704110400000; +const COUNT = 3; + +const restResponse = (ids: string[], cursor: { next: string | null; previous: string | null }) => ({ + success: true, + messages: ids.map(_id => ({ _id, rid: RID })), + cursor +}); + +const NO_MORE = { next: null, previous: null }; + +const ddpResponse = (ids: string[], moreBefore: boolean, moreAfter: boolean) => ({ + messages: ids.map((_id, index) => ({ _id, rid: RID, ts: { $date: TARGET_MS + index } })), + moreBefore, + moreAfter +}); + +describe('getSurroundingMessages', () => { + beforeEach(() => { + jest.clearAllMocks(); + setServerVersion('8.9.0'); + mockedGet.mockResolvedValue(restResponse([], NO_MORE)); + mockedMethodCallWrapper.mockResolvedValue(ddpResponse([], false, false)); + }); + + it.each([ + ['8.8.9', 1, 0], + ['8.9.0', 0, 1], + ['8.10.0', 0, 1] + ])('server %s makes %i DDP call(s) and %i REST call(s)', async (version, ddpCalls, restCalls) => { + setServerVersion(version); + + await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(mockedMethodCallWrapper).toHaveBeenCalledTimes(ddpCalls); + expect(mockedGet).toHaveBeenCalledTimes(restCalls); + }); + + it('requests the window around the message without thread replies', async () => { + await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(mockedGet).toHaveBeenCalledWith('rooms.history', { + roomId: RID, + aroundId: MESSAGE_ID, + count: COUNT, + showThreadMessages: false + }); + }); + + it.each([ + ['older and newer messages exist', { next: '1704110403000', previous: '1704110397000' }, true, true], + ['only older messages exist', { next: null, previous: '1704110397000' }, true, false], + ['only newer messages exist', { next: '1704110403000', previous: null }, false, true], + ['the window reaches both ends of the room', NO_MORE, false, false] + ])('reports moreBefore and moreAfter from the cursor when %s', async (_name, cursor, moreBefore, moreAfter) => { + mockedGet.mockResolvedValue(restResponse(['a', 'b', 'c'], cursor)); + + const result = await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(result.moreBefore).toBe(moreBefore); + expect(result.moreAfter).toBe(moreAfter); + expect(result.messages.map(message => message._id)).toEqual(['a', 'b', 'c']); + }); + + it('converts the ISO _updatedAt of each REST message to a Date', async () => { + const updatedAt = '2024-01-15T12:00:00.000Z'; + mockedGet.mockResolvedValue({ + ...restResponse([], NO_MORE), + messages: [{ _id: 'a', rid: RID, _updatedAt: updatedAt }] + }); + + const result = await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(result.messages[0]._updatedAt).toEqual(new Date(updatedAt)); + }); + + it('rejects instead of returning no messages when the response is not successful', async () => { + mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); + + await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).rejects.toThrow( + 'Unable to load surrounding messages' + ); + }); + + it('does not turn a failed REST call into an empty response', async () => { + const error = { status: 404 }; + mockedGet.mockRejectedValue(error); + + await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).rejects.toBe(error); + }); + + describe('below 8.9.0', () => { + beforeEach(() => setServerVersion('8.8.9')); + + it('asks the DDP method for the window around the message', async () => { + await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(mockedMethodCallWrapper).toHaveBeenCalledWith('loadSurroundingMessages', { _id: MESSAGE_ID, rid: RID }, COUNT); + }); + + it('decodes the DDP dates and passes moreBefore and moreAfter through', async () => { + mockedMethodCallWrapper.mockResolvedValue(ddpResponse(['a', 'b', 'c'], true, false)); + + const result = await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(result.moreBefore).toBe(true); + expect(result.moreAfter).toBe(false); + expect(result.messages[0].ts).toEqual(new Date(TARGET_MS)); + }); + + it('returns no messages when the DDP method refuses with false', async () => { + mockedMethodCallWrapper.mockResolvedValue(false); + + await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).resolves.toEqual({ + messages: [], + moreBefore: false, + moreAfter: false + }); + }); + }); +}); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index e2d045253af..261429a4bc1 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -962,6 +962,33 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte return { messages, hasMore: messages.length === count }; }; +export const getSurroundingMessages = async ({ rid, messageId, count }: { rid: string; messageId: string; count: number }) => { + const serverVersion = reduxStore.getState().server.version; + if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { + const history = await sdk.get('rooms.history', { + roomId: rid, + aroundId: messageId, + count, + showThreadMessages: false + }); + if (!history.success) { + throw new Error('Unable to load surrounding messages'); + } + const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })); + return { + messages: messages as IMessage[], + moreBefore: history.cursor.previous !== null, + moreAfter: history.cursor.next !== null + }; + } + const result = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, count); + if (!result?.messages) { + return { messages: [] as IMessage[], moreBefore: false, moreAfter: false }; + } + const messages: IMessage[] = EJSON.fromJSONValue(result.messages); + return { messages, moreBefore: !!result.moreBefore, moreAfter: !!result.moreAfter }; +}; + export const runSlashCommand = (command: string, roomId: string, params: string, triggerId?: string, tmid?: string) => // RC 0.60.2 sdk.post('commands.run', { From b1bfb04e870b2ef97ba4a10c49a5019acb5fbf86 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 03:31:35 +0530 Subject: [PATCH 13/19] fix: keep the loadNextMessages DDP argument unchanged and offset only the rooms.history cursor --- app/lib/methods/__tests__/loadNextMessages.test.ts | 4 ++-- app/lib/methods/loadNextMessages.ts | 3 +-- app/lib/services/__tests__/restApi.getNextMessages.test.ts | 6 +++--- app/lib/services/restApi.ts | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/app/lib/methods/__tests__/loadNextMessages.test.ts b/app/lib/methods/__tests__/loadNextMessages.test.ts index a1423b4ea5b..7db085bb884 100644 --- a/app/lib/methods/__tests__/loadNextMessages.test.ts +++ b/app/lib/methods/__tests__/loadNextMessages.test.ts @@ -45,12 +45,12 @@ describe('loadNextMessages', () => { mockedUpdateMessages.mockResolvedValue(0 as never); }); - it('asks for the messages after the last loaded message, one millisecond before the loader', async () => { + 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: new Date(TS.getTime() - 1), count: COUNT }); + expect(mockedGetNextMessages).toHaveBeenCalledWith({ rid: RID, after: TS, count: COUNT }); }); it('removes the Newer Loader when the server returns nothing newer', async () => { diff --git a/app/lib/methods/loadNextMessages.ts b/app/lib/methods/loadNextMessages.ts index 2a2173a0340..1b5d4b17035 100644 --- a/app/lib/methods/loadNextMessages.ts +++ b/app/lib/methods/loadNextMessages.ts @@ -19,8 +19,7 @@ interface ILoadNextMessages { export async function loadNextMessages(args: ILoadNextMessages): Promise { try { - const after = dayjs(args.ts).subtract(1, 'millisecond').toDate(); - const { messages: fetched, hasMore } = await getNextMessages({ rid: args.rid, after, count: COUNT }); + const { messages: fetched, hasMore } = await getNextMessages({ rid: args.rid, after: args.ts, count: COUNT }); const messages = orderBy(fetched, 'ts'); if (!messages.length) { await updateMessages({ rid: args.rid, update: [], remove: [{ _id: args.loaderItem.id }] }); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index 0c29c9670e2..591e6b902ea 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -57,12 +57,12 @@ describe('getNextMessages', () => { expect(mockedGet).toHaveBeenCalledTimes(restCalls); }); - it('requests the messages after the given timestamp without thread replies', async () => { + it('requests the messages from one millisecond before the loader without thread replies', async () => { await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); expect(mockedGet).toHaveBeenCalledWith('rooms.history', { roomId: RID, - next: String(AFTER_MS), + next: String(AFTER_MS - 1), count: COUNT, showThreadMessages: false }); @@ -108,7 +108,7 @@ describe('getNextMessages', () => { describe('below 8.9.0', () => { beforeEach(() => setServerVersion('8.8.9')); - it('asks the DDP method for the messages after the given timestamp', async () => { + it('passes the loader timestamp to the DDP method unchanged', async () => { await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); expect(mockedMethodCallWrapper).toHaveBeenCalledWith('loadNextMessages', RID, AFTER, COUNT); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 261429a4bc1..2c30f91622c 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -944,7 +944,7 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { const history = await sdk.get('rooms.history', { roomId: rid, - next: String(after.getTime()), + next: String(after.getTime() - 1), count, showThreadMessages: false }); From f87815eb8da79a46be3c672db89fc39651515b53 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Tue, 13 Oct 2026 04:55:32 +0530 Subject: [PATCH 14/19] refactor: type the loadSurroundingMessages dep as IMessage[] and drop the cast in resolveJumpAnchor --- app/views/RoomView/definitions.ts | 2 +- app/views/RoomView/services/resolveJumpAnchor.ts | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/app/views/RoomView/definitions.ts b/app/views/RoomView/definitions.ts index 09e9f971dc5..3aded85ee2f 100644 --- a/app/views/RoomView/definitions.ts +++ b/app/views/RoomView/definitions.ts @@ -156,7 +156,7 @@ export interface IJumpTarget { } export interface IJumpAnchorDeps { - loadSurroundingMessages: (params: { messageId: string; rid: string }) => Promise; + loadSurroundingMessages: (params: { messageId: string; rid: string }) => Promise; getLocalAnchorTs: (rid: string, ts: Date | number | string) => Promise; } diff --git a/app/views/RoomView/services/resolveJumpAnchor.ts b/app/views/RoomView/services/resolveJumpAnchor.ts index 9410f5d62ab..92d203310e5 100644 --- a/app/views/RoomView/services/resolveJumpAnchor.ts +++ b/app/views/RoomView/services/resolveJumpAnchor.ts @@ -1,4 +1,3 @@ -import { type IMessage } from '~/definitions'; import { tsToMs } from '~/lib/dayjs'; import { anchorForServerChunk } from './anchorResolver'; import { type AnchorMessage, type IJumpAnchorDeps, type IJumpTarget } from '../definitions'; @@ -14,8 +13,8 @@ export const resolveJumpAnchor = async ( } if (target.fromServer) { - const chunk = (await deps.loadSurroundingMessages({ messageId: target.id, rid })) as IMessage[]; - const anchorMessages: AnchorMessage[] = (Array.isArray(chunk) ? chunk : []).map(m => ({ + const chunk = await deps.loadSurroundingMessages({ messageId: target.id, rid }); + const anchorMessages: AnchorMessage[] = chunk.map(m => ({ id: m._id, t: m.t, ts: tsToMs(m.ts) From 31203fce8a8a1e6b7cf1177542fbcfd5cfbc2a3b Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:08:31 +0530 Subject: [PATCH 15/19] refactor: share one rooms.history helper between the wrappers and reject getSurroundingMessages when the DDP method returns nothing --- .../__tests__/restApi.getNextMessages.test.ts | 2 +- .../restApi.getSurroundingMessages.test.ts | 12 +++--- app/lib/services/restApi.ts | 41 +++++++------------ 3 files changed, 20 insertions(+), 35 deletions(-) diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index 591e6b902ea..09d4d4c6aba 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -95,7 +95,7 @@ describe('getNextMessages', () => { it('rejects instead of returning no messages when the response is not successful', async () => { mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); - await expect(getNextMessages({ rid: RID, after: AFTER, count: COUNT })).rejects.toThrow('Unable to load newer messages'); + await expect(getNextMessages({ rid: RID, after: AFTER, count: COUNT })).rejects.toThrow('Unable to load room history'); }); it('does not turn a failed REST call into an empty response', async () => { diff --git a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts index 038ec934518..53f69f39672 100644 --- a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts @@ -103,7 +103,7 @@ describe('getSurroundingMessages', () => { mockedGet.mockResolvedValue({ success: false, error: 'error-invalid-room' }); await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).rejects.toThrow( - 'Unable to load surrounding messages' + 'Unable to load room history' ); }); @@ -133,14 +133,12 @@ describe('getSurroundingMessages', () => { expect(result.messages[0].ts).toEqual(new Date(TARGET_MS)); }); - it('returns no messages when the DDP method refuses with false', async () => { + it('rejects when the DDP method refuses with false', async () => { mockedMethodCallWrapper.mockResolvedValue(false); - await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).resolves.toEqual({ - messages: [], - moreBefore: false, - moreAfter: false - }); + await expect(getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT })).rejects.toThrow( + 'Unable to load surrounding messages' + ); }); }); }); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 2c30f91622c..d37d640de17 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -939,20 +939,20 @@ export const getSyncThreadsList = ({ rid, updatedSince }: { rid: string; updated updatedSince }); +const getRoomHistory = async (roomId: string, position: { next: string } | { aroundId: string }, count: number) => { + const history = await sdk.get('rooms.history', { roomId, ...position, count, showThreadMessages: false }); + if (!history.success) { + throw new Error('Unable to load room history'); + } + const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })); + return { messages: messages as IMessage[], cursor: history.cursor }; +}; + export const getNextMessages = async ({ rid, after, count }: { rid: string; after: Date; count: number }) => { const serverVersion = reduxStore.getState().server.version; if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { - const history = await sdk.get('rooms.history', { - roomId: rid, - next: String(after.getTime() - 1), - count, - showThreadMessages: false - }); - if (!history.success) { - throw new Error('Unable to load newer messages'); - } - const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })); - return { messages: messages as IMessage[], hasMore: history.cursor.next !== null }; + const { messages, cursor } = await getRoomHistory(rid, { next: String(after.getTime() - 1) }, count); + return { messages, hasMore: cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); if (!result?.messages) { @@ -965,25 +965,12 @@ export const getNextMessages = async ({ rid, after, count }: { rid: string; afte export const getSurroundingMessages = async ({ rid, messageId, count }: { rid: string; messageId: string; count: number }) => { const serverVersion = reduxStore.getState().server.version; if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { - const history = await sdk.get('rooms.history', { - roomId: rid, - aroundId: messageId, - count, - showThreadMessages: false - }); - if (!history.success) { - throw new Error('Unable to load surrounding messages'); - } - const messages = history.messages.map(message => ({ ...message, _updatedAt: new Date(message._updatedAt) })); - return { - messages: messages as IMessage[], - moreBefore: history.cursor.previous !== null, - moreAfter: history.cursor.next !== null - }; + const { messages, cursor } = await getRoomHistory(rid, { aroundId: messageId }, count); + return { messages, moreBefore: cursor.previous !== null, moreAfter: cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, count); if (!result?.messages) { - return { messages: [] as IMessage[], moreBefore: false, moreAfter: false }; + throw new Error('Unable to load surrounding messages'); } const messages: IMessage[] = EJSON.fromJSONValue(result.messages); return { messages, moreBefore: !!result.moreBefore, moreAfter: !!result.moreAfter }; From 50770da7f099c0f1c6ae2256c2a4f9d4c41a487d Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:08:31 +0530 Subject: [PATCH 16/19] fix: request thread replies from rooms.history so the loaders store the same rows as the DDP methods --- app/lib/services/__tests__/restApi.getNextMessages.test.ts | 4 ++-- .../services/__tests__/restApi.getSurroundingMessages.test.ts | 4 ++-- app/lib/services/restApi.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index 09d4d4c6aba..38635a6cf7a 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -57,14 +57,14 @@ describe('getNextMessages', () => { expect(mockedGet).toHaveBeenCalledTimes(restCalls); }); - it('requests the messages from one millisecond before the loader without thread replies', async () => { + it('requests the messages from one millisecond before the loader with thread replies', async () => { await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); expect(mockedGet).toHaveBeenCalledWith('rooms.history', { roomId: RID, next: String(AFTER_MS - 1), count: COUNT, - showThreadMessages: false + showThreadMessages: true }); }); diff --git a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts index 53f69f39672..efbb0768011 100644 --- a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts @@ -61,14 +61,14 @@ describe('getSurroundingMessages', () => { expect(mockedGet).toHaveBeenCalledTimes(restCalls); }); - it('requests the window around the message without thread replies', async () => { + it('requests the window around the message with thread replies', async () => { await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); expect(mockedGet).toHaveBeenCalledWith('rooms.history', { roomId: RID, aroundId: MESSAGE_ID, count: COUNT, - showThreadMessages: false + showThreadMessages: true }); }); diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index d37d640de17..01018b3e0c8 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -940,7 +940,7 @@ export const getSyncThreadsList = ({ rid, updatedSince }: { rid: string; updated }); const getRoomHistory = async (roomId: string, position: { next: string } | { aroundId: string }, count: number) => { - const history = await sdk.get('rooms.history', { roomId, ...position, count, showThreadMessages: false }); + const history = await sdk.get('rooms.history', { roomId, ...position, count, showThreadMessages: true }); if (!history.success) { throw new Error('Unable to load room history'); } From 86feebe4a9aaaec6b14b9eeccbca1d775341fc23 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:51:54 +0530 Subject: [PATCH 17/19] refactor: name the newest loaded timestamp behind the rooms.history next cursor --- app/lib/services/restApi.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 01018b3e0c8..c5582d31748 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -951,7 +951,8 @@ const getRoomHistory = async (roomId: string, position: { next: string } | { aro export const getNextMessages = async ({ rid, after, count }: { rid: string; after: Date; count: number }) => { const serverVersion = reduxStore.getState().server.version; if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '8.9.0')) { - const { messages, cursor } = await getRoomHistory(rid, { next: String(after.getTime() - 1) }, count); + const newestLoadedTs = after.getTime() - 1; + const { messages, cursor } = await getRoomHistory(rid, { next: String(newestLoadedTs) }, count); return { messages, hasMore: cursor.next !== null }; } const result = await sdk.methodCallWrapper('loadNextMessages', rid, after, count); From 460c2f278bb176449badd1bfbc72df6cafba22a0 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Wed, 14 Oct 2026 03:51:54 +0530 Subject: [PATCH 18/19] test: pin the jump cancel when the server Chunk fails to load and use CONTEXT.md terms in test titles --- .../__tests__/loadSurroundingMessages.test.ts | 2 +- .../__tests__/restApi.getNextMessages.test.ts | 2 +- .../restApi.getSurroundingMessages.test.ts | 6 +++--- .../__tests__/useJumpToMessage.lifecycle.test.tsx | 15 +++++++++++++++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/app/lib/methods/__tests__/loadSurroundingMessages.test.ts b/app/lib/methods/__tests__/loadSurroundingMessages.test.ts index 83ffeb9c5cf..580c098b9ff 100644 --- a/app/lib/methods/__tests__/loadSurroundingMessages.test.ts +++ b/app/lib/methods/__tests__/loadSurroundingMessages.test.ts @@ -45,7 +45,7 @@ describe('loadSurroundingMessages', () => { mockedUpdateMessages.mockResolvedValue(0 as never); }); - it('asks for the window around the message', async () => { + it('asks for the surrounding Chunk', async () => { serve([], false, false); await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID }); diff --git a/app/lib/services/__tests__/restApi.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts index 38635a6cf7a..7398601cfa8 100644 --- a/app/lib/services/__tests__/restApi.getNextMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -57,7 +57,7 @@ describe('getNextMessages', () => { expect(mockedGet).toHaveBeenCalledTimes(restCalls); }); - it('requests the messages from one millisecond before the loader with thread replies', async () => { + it('requests the messages from one millisecond before the Newer Loader with Thread Messages', async () => { await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); expect(mockedGet).toHaveBeenCalledWith('rooms.history', { diff --git a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts index efbb0768011..76b9c73a609 100644 --- a/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts +++ b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts @@ -61,7 +61,7 @@ describe('getSurroundingMessages', () => { expect(mockedGet).toHaveBeenCalledTimes(restCalls); }); - it('requests the window around the message with thread replies', async () => { + it('requests the surrounding Chunk with Thread Messages', async () => { await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); expect(mockedGet).toHaveBeenCalledWith('rooms.history', { @@ -76,7 +76,7 @@ describe('getSurroundingMessages', () => { ['older and newer messages exist', { next: '1704110403000', previous: '1704110397000' }, true, true], ['only older messages exist', { next: null, previous: '1704110397000' }, true, false], ['only newer messages exist', { next: '1704110403000', previous: null }, false, true], - ['the window reaches both ends of the room', NO_MORE, false, false] + ['the Chunk reaches both ends of the room', NO_MORE, false, false] ])('reports moreBefore and moreAfter from the cursor when %s', async (_name, cursor, moreBefore, moreAfter) => { mockedGet.mockResolvedValue(restResponse(['a', 'b', 'c'], cursor)); @@ -117,7 +117,7 @@ describe('getSurroundingMessages', () => { describe('below 8.9.0', () => { beforeEach(() => setServerVersion('8.8.9')); - it('asks the DDP method for the window around the message', async () => { + it('asks the DDP method for the surrounding Chunk', async () => { await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); expect(mockedMethodCallWrapper).toHaveBeenCalledWith('loadSurroundingMessages', { _id: MESSAGE_ID, rid: RID }, COUNT); diff --git a/app/views/RoomView/hooks/__tests__/useJumpToMessage.lifecycle.test.tsx b/app/views/RoomView/hooks/__tests__/useJumpToMessage.lifecycle.test.tsx index bb6d3f439ee..9b2d7c433dc 100644 --- a/app/views/RoomView/hooks/__tests__/useJumpToMessage.lifecycle.test.tsx +++ b/app/views/RoomView/hooks/__tests__/useJumpToMessage.lifecycle.test.tsx @@ -165,6 +165,21 @@ it('resolves the server Chunk anchor through the real resolver before requesting expect(getLocalAnchorTs).not.toHaveBeenCalled(); }); +it('cancels the jump and logs when the server Chunk fails to load', async () => { + const failure = new Error('Unable to load room history'); + lookup.mockResolvedValue(message('target', { fromServer: true }) as any); + jest.mocked(loadSurroundingMessages).mockRejectedValue(failure); + const view = screen(); + view.list.isMessageInWindow.mockReturnValue(false); + const jump = view.jump('target'); + await advance(100); + await jump; + expect(log).toHaveBeenCalledWith(failure); + expect(view.list.cancelJumpToMessage).toHaveBeenCalledTimes(1); + expect(view.list.jumpToMessage).not.toHaveBeenCalled(); + expect(visibility()).toEqual([true, false]); +}); + it('lets an older successful List completion dismiss loading while a newer lookup remains pending', async () => { const completion = deferred(); const newerLookup = deferred(); From 28012ee4f6e5aa2a103486192be4f4244e6462e9 Mon Sep 17 00:00:00 2001 From: Rohit <40559587+Rohit3523@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:51:02 +0530 Subject: [PATCH 19/19] fix: keep milliseconds on the Older Loader timestamp so Load more can fetch same-second messages --- app/lib/methods/loadMessagesForRoom.test.ts | 40 +++++++++++++++++++++ app/lib/methods/loadMessagesForRoom.ts | 4 +-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/app/lib/methods/loadMessagesForRoom.test.ts b/app/lib/methods/loadMessagesForRoom.test.ts index 1ad7d467bf4..3016f46541a 100644 --- a/app/lib/methods/loadMessagesForRoom.test.ts +++ b/app/lib/methods/loadMessagesForRoom.test.ts @@ -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 () => { + 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'); diff --git a/app/lib/methods/loadMessagesForRoom.ts b/app/lib/methods/loadMessagesForRoom.ts index c5abce1442b..980967e0fdf 100644 --- a/app/lib/methods/loadMessagesForRoom.ts +++ b/app/lib/methods/loadMessagesForRoom.ts @@ -91,7 +91,7 @@ async function load(args: { const loadMoreMessage = { _id: generateLoadMoreId(lastMessage._id as string), rid: lastMessage.rid, - ts: dayjs(lastMessage.ts).subtract(1, 'millisecond').toString(), + ts: dayjs(lastMessage.ts).subtract(1, 'millisecond').toDate(), t: MessageTypeLoad.MORE, msg: lastMessage.msg } as IMessage; @@ -135,7 +135,7 @@ export async function loadMessagesForRoom(args: { messages.push({ _id: generateLoadMoreId(lastMessage._id as string), rid: lastMessage.rid, - ts: dayjs(lastMessage.ts).subtract(1, 'millisecond').toString(), + ts: dayjs(lastMessage.ts).subtract(1, 'millisecond').toDate(), t: MessageTypeLoad.MORE, msg: lastMessage.msg } as IMessage);