Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions apps/meteor/app/lib/client/methods/sendMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { onClientMessageReceived } from '../../../../client/lib/onClientMessageR
import { settings } from '../../../../client/lib/settings';
import { dispatchToastMessage } from '../../../../client/lib/toast';
import { getUser, getUserId } from '../../../../client/lib/user';
import { upsertThreadMessageInCache } from '../../../../client/lib/utils/threadMessageUtils';
import { Messages, Rooms } from '../../../../client/stores';
import { trim } from '../../../../lib/utils/stringUtils';
import { t } from '../../../utils/lib/i18n';
Expand Down Expand Up @@ -42,9 +43,14 @@ Meteor.methods<ServerMethods>({
return;
}

await onClientMessageReceived(message as IMessage).then((message) => {
Messages.state.store(message);
return clientCallbacks.run('afterSaveMessage', message, { room, user });
await onClientMessageReceived(message as IMessage).then((msg) => {
Messages.state.store(msg);

if (msg.tmid) {
upsertThreadMessageInCache(msg, msg.rid, msg.tmid);
}

return clientCallbacks.run('afterSaveMessage', msg, { room, user });
});
},
});
8 changes: 7 additions & 1 deletion apps/meteor/client/lib/chats/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Messages, Rooms, Subscriptions } from '../../stores';
import { settings } from '../settings';
import { getUserId } from '../user';
import { prependReplies } from '../utils/prependReplies';
import { upsertThreadMessageInCache } from '../utils/threadMessageUtils';

export const createDataAPI = ({ rid, tmid }: { rid: IRoom['_id']; tmid: IMessage['_id'] | undefined }): DataAPI => {
const composeMessage = async (
Expand Down Expand Up @@ -162,7 +163,12 @@ export const createDataAPI = ({ rid, tmid }: { rid: IRoom['_id']; tmid: IMessage
};

const pushEphemeralMessage = async (message: Omit<IMessage, 'rid' | 'tmid'>): Promise<void> => {
Messages.state.store({ ...message, rid, ...(tmid && { tmid }) });
const fullMessage = { ...message, rid, ...(tmid && { tmid }) } as IMessage;
Messages.state.store(fullMessage);

if (tmid) {
upsertThreadMessageInCache(fullMessage, rid, tmid);
}
};

const updateMessage = async (message: IEditedMessage, previewUrls?: string[]): Promise<void> => {
Expand Down
2 changes: 2 additions & 0 deletions apps/meteor/client/lib/queryKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export const roomsQueryKeys = {
images: (rid: IRoom['_id'], options?: { startingFromId?: string }) => [...roomsQueryKeys.room(rid), 'images', options] as const,
autocomplete: (text: string) => [...roomsQueryKeys.all, 'autocomplete', text] as const,
discussions: (rid: IRoom['_id'], ...args: [filter: { text?: string }]) => [...roomsQueryKeys.room(rid), 'discussions', ...args] as const,
threadMessages: (rid: IRoom['_id'], tmid: IMessage['_id']) => [...roomsQueryKeys.room(rid), 'threads', tmid, 'messages'] as const,
threadMainMessage: (rid: IRoom['_id'], tmid: IMessage['_id']) => [...roomsQueryKeys.room(rid), 'threads', tmid, 'main-message'] as const,
};

export const subscriptionsQueryKeys = {
Expand Down
69 changes: 69 additions & 0 deletions apps/meteor/client/lib/utils/threadMessageUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import type { IMessage, MessageAttachment } from '@rocket.chat/core-typings';
import { createPredicateFromFilter } from '@rocket.chat/mongo-adapter';
import type { QueryClient } from '@tanstack/react-query';
import type { Condition, Filter } from 'mongodb';

import { queryClient as defaultQueryClient } from '../queryClient';
import { roomsQueryKeys } from '../queryKeys';

export type NotifyRoomRidDeleteBulkEvent = {
rid: IMessage['rid'];
excludePinned: boolean;
ignoreDiscussion: boolean;
ts: Condition<Date>;
users: string[];
ids?: string[];
showDeletedStatus?: boolean;
} & (
| {
filesOnly: true;
replaceFileAttachmentsWith?: MessageAttachment;
}
| {
filesOnly?: false;
}
);

export const createDeleteCriteria = (params: NotifyRoomRidDeleteBulkEvent): ((message: IMessage) => boolean) => {
const query: Filter<IMessage> = {};

if (params.ids) {
query._id = { $in: params.ids };
} else {
query.ts = params.ts;
}

if (params.excludePinned) {
query.pinned = { $ne: true };
}

if (params.ignoreDiscussion) {
query.drid = { $exists: false };
}
if (params.users?.length) {
query['u.username'] = { $in: params.users };
}

return createPredicateFromFilter(query);
};

export const upsertThreadMessageInCache = (
message: IMessage,
rid: IMessage['rid'],
tmid: IMessage['_id'],
client: QueryClient = defaultQueryClient,
): void => {
const queryKey = roomsQueryKeys.threadMessages(rid, tmid);
client.setQueryData<IMessage[]>(queryKey, (old) => {
if (!old) {
return [message];
}
const idx = old.findIndex((m) => m._id === message._id);
if (idx >= 0) {
const updated = [...old];
updated[idx] = message;
return updated;
}
return [...old, message].sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime());
});
};
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { useDateScroll } from '../../../hooks/useDateScroll';
import { useFirstUnreadMessageId } from '../../../hooks/useFirstUnreadMessageId';
import { useMessageListNavigation } from '../../../hooks/useMessageListNavigation';
import { useLegacyThreadMessageListScrolling } from '../hooks/useLegacyThreadMessageListScrolling';
import { useLegacyThreadMessages } from '../hooks/useLegacyThreadMessages';
import { useThreadMessagesQuery } from '../hooks/useThreadMessagesQuery';
import './threads.css';

const isMessageSequential = (current: IMessage, previous: IMessage | undefined, groupingRange: number): boolean => {
Expand Down Expand Up @@ -54,7 +54,7 @@ const ThreadMessageList = ({ mainMessage }: ThreadMessageListProps): ReactElemen
const { t } = useTranslation();
const { innerRef, bubbleRef, listStyle, ...bubbleDate } = useDateScroll();

const { messages, loading } = useLegacyThreadMessages(mainMessage._id);
Comment thread
abhinavkrin marked this conversation as resolved.
Resolved
const { data: messages = [], isLoading: loading } = useThreadMessagesQuery(mainMessage._id);

const { innerRef: listScrollRef, jumpToRef } = useLegacyThreadMessageListScrolling(mainMessage);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,60 +1,19 @@
import type { IMessage, IThreadMainMessage, MessageAttachment } from '@rocket.chat/core-typings';
import { createPredicateFromFilter } from '@rocket.chat/mongo-adapter';
import { useStream } from '@rocket.chat/ui-contexts';
import type { UseQueryResult } from '@tanstack/react-query';
import { useQueryClient, useQuery } from '@tanstack/react-query';
import type { Condition, Filter } from 'mongodb';
import { useCallback, useEffect, useRef } from 'react';

import { useGetMessageByID } from './useGetMessageByID';
import { withDebouncing } from '../../../../../../lib/utils/highOrderFunctions';
import { onClientMessageReceived } from '../../../../../lib/onClientMessageReceived';
import { roomsQueryKeys } from '../../../../../lib/queryKeys';
import { modifyMessageOnFilesDelete } from '../../../../../lib/utils/modifyMessageOnFilesDelete';
import { createDeleteCriteria } from '../../../../../lib/utils/threadMessageUtils';
import { useRoom } from '../../../contexts/RoomContext';

type RoomMessagesRidEvent = IMessage;

type NotifyRoomRidDeleteBulkEvent = {
rid: IMessage['rid'];
excludePinned: boolean;
ignoreDiscussion: boolean;
ts: Condition<Date>;
users: string[];
ids?: string[]; // message ids have priority over ts
showDeletedStatus?: boolean;
} & (
| {
filesOnly: true;
replaceFileAttachmentsWith?: MessageAttachment;
}
| {
filesOnly?: false;
}
);

const createDeleteCriteria = (params: NotifyRoomRidDeleteBulkEvent): ((message: IMessage) => boolean) => {
const query: Filter<IMessage> = {};

if (params.ids) {
query._id = { $in: params.ids };
} else {
query.ts = params.ts;
}

if (params.excludePinned) {
query.pinned = { $ne: true };
}

if (params.ignoreDiscussion) {
query.drid = { $exists: false };
}
if (params.users?.length) {
query['u.username'] = { $in: params.users };
}

return createPredicateFromFilter(query);
};

const useSubscribeToMessage = () => {
const subscribeToRoomMessages = useStream('room-messages');
const subscribeToNotifyRoom = useStream('notify-room');
Expand All @@ -67,9 +26,9 @@ const useSubscribeToMessage = () => {
onDelete,
onFilesDelete,
}: {
onMutate?: (message: IMessage) => void;
onDelete?: () => void;
onFilesDelete?: (replaceFileAttachmentsWith?: MessageAttachment) => void;
onMutate?: (message: IMessage) => void | Promise<void>;
onDelete?: () => void | Promise<void>;
onFilesDelete?: (replaceFileAttachmentsWith?: MessageAttachment) => void | Promise<void>;
},
) => {
const unsubscribeFromRoomMessages = subscribeToRoomMessages(message.rid, (event: RoomMessagesRidEvent) => {
Expand Down Expand Up @@ -120,7 +79,7 @@ export const useThreadMainMessageQuery = (
}, [tmid]);

return useQuery({
queryKey: ['rooms', room._id, 'threads', tmid, 'main-message'] as const,
queryKey: roomsQueryKeys.threadMainMessage(room._id, tmid),

queryFn: async ({ queryKey }) => {
const mainMessage = await getMessage(tmid);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { isThreadMessage, type IMessage, type IRoom, type IThreadMainMessage, type IThreadMessage } from '@rocket.chat/core-typings';
import { useMethod, useStream } from '@rocket.chat/ui-contexts';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';

import { onClientMessageReceived } from '../../../../../lib/onClientMessageReceived';
import { roomsQueryKeys } from '../../../../../lib/queryKeys';
import { modifyMessageOnFilesDelete } from '../../../../../lib/utils/modifyMessageOnFilesDelete';
import { createDeleteCriteria, upsertThreadMessageInCache } from '../../../../../lib/utils/threadMessageUtils';
import { useRoom } from '../../../contexts/RoomContext';

const processMessages = async (messages: IMessage[]): Promise<IMessage[]> => {
return Promise.all(messages.map((msg) => onClientMessageReceived(msg)));
};

export const useThreadMessagesQuery = (tmid: IThreadMainMessage['_id'], rid?: IRoom['_id']) => {
const room = useRoom();
const roomId = rid ?? room._id;

const queryClient = useQueryClient();
const queryKey = roomsQueryKeys.threadMessages(roomId, tmid);
const getThreadMessages = useMethod('getThreadMessages');

const subscribeToRoomMessages = useStream('room-messages');
const subscribeToNotifyRoom = useStream('notify-room');

useEffect(() => {
const currentQueryKey = roomsQueryKeys.threadMessages(roomId, tmid);

const unsubscribeFromRoomMessages = subscribeToRoomMessages(roomId, async (event) => {
if (event.tmid !== tmid) {
return;
}

const processed = await onClientMessageReceived(event);
upsertThreadMessageInCache(processed, roomId, tmid, queryClient);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const unsubscribeFromDeleteMessage = subscribeToNotifyRoom(`${roomId}/deleteMessage`, (event) => {
queryClient.setQueryData<IThreadMessage[]>(currentQueryKey, (old) => {
if (!old) {
return old;
}
return old.filter((m) => m._id !== event._id);
});
});

const unsubscribeFromDeleteMessageBulk = subscribeToNotifyRoom(`${roomId}/deleteMessageBulk`, (bulkParams) => {
const matchDeleteCriteria = createDeleteCriteria(bulkParams);

queryClient.setQueryData<IThreadMessage[]>(currentQueryKey, (old) => {
if (!old) {
return old;
}

if (bulkParams.filesOnly) {
return old.map((msg) => {
if (matchDeleteCriteria(msg)) {
return modifyMessageOnFilesDelete(msg, bulkParams.replaceFileAttachmentsWith);
}
return msg;
});
}

return old.filter((msg) => !matchDeleteCriteria(msg));
});
});

return () => {
unsubscribeFromRoomMessages();
unsubscribeFromDeleteMessage();
unsubscribeFromDeleteMessageBulk();
};
}, [tmid, roomId, queryClient, subscribeToRoomMessages, subscribeToNotifyRoom]);
Comment thread
abhinavkrin marked this conversation as resolved.
Resolved

return useQuery({
queryKey,
queryFn: async () => {
const messages = await getThreadMessages({ tmid });
const filtered = messages.filter(
(msg): msg is IThreadMessage => isThreadMessage(msg) && msg.tmid === tmid && msg._id !== tmid && msg._hidden !== true,
);
const sorted = filtered.sort((a, b) => a.ts.getTime() - b.ts.getTime());
return processMessages(sorted) as Promise<Array<IThreadMessage>>;
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
};
62 changes: 62 additions & 0 deletions apps/meteor/tests/e2e/thread-persistence-on-navigation.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { IRoom } from '@rocket.chat/core-typings';

import { Users } from './fixtures/userStates';
import { HomeChannel } from './page-objects';
import { createTargetChannelAndReturnFullRoom } from './utils';
import { sendFillerMessages } from './utils/sendMessage';
import type { BaseTest } from './utils/test';
import { expect, test } from './utils/test';

test.use({ storageState: Users.admin.state });

test.describe.serial('Thread persistence on navigation', () => {
let poHomeChannel: HomeChannel;
let targetChannel: IRoom;
let threadParentMessageId: string;

const setupChannelData = async (api: BaseTest['api']) => {
const rid = targetChannel._id;

const { message: parentMessage } = await (await api.post('/chat.postMessage', { roomId: rid, text: 'Thread parent message' })).json();
threadParentMessageId = parentMessage._id;

await api.post('/chat.postMessage', {
roomId: rid,
text: 'Thread reply that should persist after navigation',
tmid: parentMessage._id,
});

await sendFillerMessages(api, rid);
};

test.beforeAll(async ({ api }) => {
const { channel } = await createTargetChannelAndReturnFullRoom(api);
targetChannel = channel;
await setupChannelData(api);
});

test.afterAll(({ api }) => api.post('/channels.delete', { roomId: targetChannel._id }));

test.beforeEach(async ({ page }) => {
poHomeChannel = new HomeChannel(page);
});

test('expect thread content to persist after clicking Jump to recent messages', async ({ page }) => {
await page.goto(`/channel/${targetChannel.name}?msg=${threadParentMessageId}`);
await poHomeChannel.content.waitForChannel();

await expect(page).toHaveURL(/.*thread/);
await expect(poHomeChannel.content.threadMessageList).toBeVisible();
const threadMessageCount = await poHomeChannel.content.threadMessageListItems.count();
expect(threadMessageCount).toBeGreaterThan(0);

const jumpToRecentButton = page.getByRole('button', { name: 'Jump to recent messages' });
await expect(jumpToRecentButton).toBeVisible();
await jumpToRecentButton.click();

await expect(page).toHaveURL(/.*thread/);
await expect(poHomeChannel.content.threadMessageList).toBeVisible();
await expect(poHomeChannel.content.threadMessageListItems).toHaveCount(threadMessageCount);
await expect(poHomeChannel.content.threadMessageList).toContainText('Thread reply that should persist after navigation');
});
});
8 changes: 8 additions & 0 deletions apps/meteor/tests/e2e/utils/sendMessage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { APIRequestContext } from 'playwright-core';

import type { BaseTest } from './test';
import { BASE_API_URL } from '../config/constants';
import type { IUserState } from '../fixtures/userStates';

Expand All @@ -17,3 +18,10 @@ export const sendMessageFromUser = async (request: APIRequestContext, user: IUse
})
.then((response) => response.json());
};

export const sendFillerMessages = async (api: BaseTest['api'], rid: string, count = 50, batchSize = 10) => {
const messages = Array.from({ length: count }, (_, i) => `filler message ${i + 1}`);
for (let i = 0; i < messages.length; i += batchSize) {
await Promise.all(messages.slice(i, i + batchSize).map((text) => api.post('/chat.postMessage', { roomId: rid, text })));
Comment thread
abhinavkrin marked this conversation as resolved.
Resolved
Comment thread
abhinavkrin marked this conversation as resolved.
Resolved
}
};
Loading