diff --git a/app/definitions/rest/v1/rooms.ts b/app/definitions/rest/v1/rooms.ts index b29d5cfae7e..19148d6d3bc 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,18 @@ export type RoomsEndpoints = { 'rooms.invite': { POST: (params: { roomId: string; action: 'accept' | 'reject' }) => void; }; + 'rooms.history': { + GET: (params: { + roomId: IServerRoom['_id']; + next?: string; + aroundId?: IMessage['_id']; + count?: number; + showThreadMessages?: boolean; + }) => { + messages: IMessageFromServer[]; + cursor: { next: string | null; previous: string | null }; + }; + }; 'rooms.join': { POST: (params: { roomId: string; joinCode: string | null }) => { room: IServerRoom; diff --git a/app/lib/methods/__tests__/loadNextMessages.test.ts b/app/lib/methods/__tests__/loadNextMessages.test.ts new file mode 100644 index 00000000000..7db085bb884 --- /dev/null +++ b/app/lib/methods/__tests__/loadNextMessages.test.ts @@ -0,0 +1,120 @@ +import { loadNextMessages } from '../loadNextMessages'; +import { getNextMessages } from '../../services/restApi'; +import { getMessageById } from '../../database/services/Message'; +import updateMessages from '../updateMessages'; +import log from '../helpers/log'; +import { MessageTypeLoad } from '../../constants/messageTypeLoad'; + +jest.mock('../../services/restApi', () => ({ + getNextMessages: jest.fn() +})); + +jest.mock('../../database/services/Message', () => ({ + getMessageById: jest.fn() +})); + +jest.mock('../updateMessages', () => jest.fn()); + +jest.mock('../helpers/log', () => ({ + __esModule: true, + default: jest.fn() +})); + +const mockedGetNextMessages = getNextMessages as jest.MockedFunction; +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 buildMessages = (length: number) => + Array.from( + { length }, + (_, index) => ({ _id: `msg-${index + 1}`, rid: RID, ts: new Date(TS.getTime() + (index + 1) * 1000) }) as any + ); + +const serve = (messages: any[], hasMore: boolean) => mockedGetNextMessages.mockResolvedValue({ messages, hasMore }); + +describe('loadNextMessages', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockedGetMessageById.mockResolvedValue(null as never); + mockedUpdateMessages.mockResolvedValue(0 as never); + }); + + it('asks for the messages newer than the loader', async () => { + serve([], false); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + expect(mockedGetNextMessages).toHaveBeenCalledWith({ rid: RID, after: TS, count: COUNT }); + }); + + it('removes the Newer Loader when the server returns nothing newer', async () => { + serve([], false); + + await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).resolves.toBeUndefined(); + + expect(mockedUpdateMessages).toHaveBeenCalledTimes(1); + expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: [], remove: [{ _id: 'tapped-loader' }] }); + }); + + it('delegates a full response without adding a Newer Loader when the server reports nothing newer', async () => { + const messages = buildMessages(COUNT); + serve(messages, false); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + expect(mockedGetMessageById).not.toHaveBeenCalled(); + expect(mockedUpdateMessages).toHaveBeenCalledTimes(1); + expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: messages, loaderItem: LOADER_ITEM }); + }); + + it('adds no Newer Loader when more exist but the newest message is already local', async () => { + const messages = buildMessages(COUNT); + serve(messages, true); + mockedGetMessageById.mockResolvedValue({ id: 'msg-50' } as never); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + expect(mockedUpdateMessages).toHaveBeenCalledWith({ rid: RID, update: messages, loaderItem: LOADER_ITEM }); + }); + + it('appends a Newer Loader one millisecond after the newest message when more exist and it is not local', async () => { + const messages = buildMessages(COUNT); + serve(messages, true); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + expect(mockedGetMessageById).toHaveBeenCalledWith('msg-50'); + expect(mockedUpdateMessages.mock.calls[0][0].update).toEqual([ + ...messages, + { _id: 'load-more-msg-50', rid: RID, t: MessageTypeLoad.NEXT_CHUNK, ts: new Date(messages[COUNT - 1].ts.getTime() + 1) } + ]); + }); + + it('stores a newest-first response oldest-first', async () => { + const newestFirst = buildMessages(COUNT) + .reverse() + .map(message => ({ ...message, ts: message.ts.toISOString() })); + serve(newestFirst, false); + + await loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM }); + + const update = mockedUpdateMessages.mock.calls[0][0].update as any[]; + expect(update.map(m => m._id)).toEqual(buildMessages(COUNT).map(m => m._id)); + }); + + it('logs and rejects with the same error when loading fails', async () => { + const error = new Error('boom'); + mockedGetNextMessages.mockRejectedValue(error); + + await expect(loadNextMessages({ rid: RID, ts: TS, loaderItem: LOADER_ITEM })).rejects.toBe(error); + + expect(mockedLog).toHaveBeenCalledWith(error); + expect(mockedUpdateMessages).not.toHaveBeenCalled(); + }); +}); 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..580c098b9ff 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 surrounding Chunk', async () => { + serve([], false, false); + + await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID }); + + expect(mockedGetSurroundingMessages).toHaveBeenCalledWith({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + }); + it('resolves [] without delegating when the server returns no messages', async () => { - mockedMethodCall.mockResolvedValue({ messages: [] } as never); + serve([], false, false); await expect(loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID })).resolves.toEqual([]); - expect(mockedMethodCall).toHaveBeenCalledWith('loadSurroundingMessages', { _id: MESSAGE_ID, rid: RID }, COUNT); expect(mockedUpdateMessages).not.toHaveBeenCalled(); }); - it('delegates with no markers when moreBefore and moreAfter are both falsy', async () => { + it('delegates with no markers when moreBefore and moreAfter are both false', async () => { const messages = buildMessages(); - mockedMethodCall.mockResolvedValue({ messages, moreBefore: false, moreAfter: false } as never); + serve(messages, false, false); const result = await loadSurroundingMessages({ messageId: MESSAGE_ID, rid: RID }); @@ -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/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); 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..1b5d4b17035 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; @@ -18,31 +17,26 @@ interface ILoadNextMessages { loaderItem: TMessageModel; } -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 }); - return resolve(); - } - return resolve(); - } catch (e) { - log(e); - reject(e); +export async function loadNextMessages(args: ILoadNextMessages): Promise { + try { + 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 }] }); + 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; + } } 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.getNextMessages.test.ts b/app/lib/services/__tests__/restApi.getNextMessages.test.ts new file mode 100644 index 00000000000..7398601cfa8 --- /dev/null +++ b/app/lib/services/__tests__/restApi.getNextMessages.test.ts @@ -0,0 +1,135 @@ +import { store as reduxStore } from '~/lib/store/auxStore'; +import sdk from '../sdk'; +import { getNextMessages } 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 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 from one millisecond before the Newer Loader with Thread Messages', async () => { + await getNextMessages({ rid: RID, after: AFTER, count: COUNT }); + + expect(mockedGet).toHaveBeenCalledWith('rooms.history', { + roomId: RID, + next: String(AFTER_MS - 1), + count: COUNT, + showThreadMessages: true + }); + }); + + 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('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' }); + + 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 () => { + 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('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); + }); + + 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/__tests__/restApi.getSurroundingMessages.test.ts b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts new file mode 100644 index 00000000000..76b9c73a609 --- /dev/null +++ b/app/lib/services/__tests__/restApi.getSurroundingMessages.test.ts @@ -0,0 +1,144 @@ +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 surrounding Chunk with Thread Messages', async () => { + await getSurroundingMessages({ rid: RID, messageId: MESSAGE_ID, count: COUNT }); + + expect(mockedGet).toHaveBeenCalledWith('rooms.history', { + roomId: RID, + aroundId: MESSAGE_ID, + count: COUNT, + showThreadMessages: true + }); + }); + + 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 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)); + + 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 room history' + ); + }); + + 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 surrounding Chunk', 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('rejects when the DDP method refuses with false', async () => { + mockedMethodCallWrapper.mockResolvedValue(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 d61ced67d57..c5582d31748 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -939,6 +939,44 @@ 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: true }); + 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 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); + 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 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 { 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) { + throw new Error('Unable to load surrounding messages'); + } + 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', { 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/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(); 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)