import { InfiniteData, QueryClient } from '@tanstack/react-query' import { buildTestQueryClient } from '../../../__utils__/query_client' import type { ApiCollection, MessageResource } from '../../../types' import type { PersonResource } from '../../../types/resources/person' import { updateCacheWithMessage } from '../messages_cache' type MessagesQueryData = InfiniteData> const queryKey = ['messages'] const author = { type: 'Person', id: 1, name: 'Me', avatar: null } as unknown as PersonResource const message = (overrides: Partial): MessageResource => ({ type: 'Message', text: 'ok', html: '', createdAt: '2026-01-01T00:00:00Z', deletedAt: null, textEditedAt: null, mine: true, attachments: [], author, reactionCounts: [], replyCount: 0, replyRootId: null, messageType: 'user', ...overrides, }) as MessageResource const seed = (queryClient: QueryClient, ...messages: MessageResource[]) => queryClient.setQueryData(queryKey, { pages: [ { data: messages, links: {}, meta: { count: messages.length, totalCount: messages.length } }, ], pageParams: [], }) const idsInCache = (queryClient: QueryClient) => queryClient.getQueryData(queryKey)!.pages[0].data.map(m => m.id) const echo = (queryClient: QueryClient, overrides: Partial) => updateCacheWithMessage(queryClient, queryKey, message(overrides), 'message.created') describe('updateCacheWithMessage on message.created', () => { let queryClient: QueryClient beforeEach(() => { queryClient = buildTestQueryClient() seed( queryClient, message({ id: '01B-temp', idempotentKey: 'key-b', pending: true }), message({ id: '01A-temp', idempotentKey: 'key-a', pending: true }) ) }) it('swaps out only the pending message with the same idempotent key', () => { echo(queryClient, { id: '01A', idempotentKey: 'key-a' }) expect(idsInCache(queryClient)).toEqual(['01A', '01B-temp']) }) it('does not swap out a pending message that only shares the same text', () => { echo(queryClient, { id: '01C', idempotentKey: 'key-c', text: 'ok' }) expect(idsInCache(queryClient)).toEqual(['01C', '01B-temp', '01A-temp']) }) it('swaps out an attachment-only pending message, which has no text to match', () => { seed( queryClient, message({ id: '01D-temp', idempotentKey: 'key-d', text: null, pending: true }) ) echo(queryClient, { id: '01D', idempotentKey: 'key-d', text: null }) expect(idsInCache(queryClient)).toEqual(['01D']) }) it('leaves pending messages alone when the echo carries no key', () => { echo(queryClient, { id: '01E', idempotentKey: null }) expect(idsInCache(queryClient)).toEqual(['01E', '01B-temp', '01A-temp']) }) it("leaves pending messages alone when the echo is someone else's", () => { echo(queryClient, { id: '01F', idempotentKey: 'key-a', mine: false }) expect(idsInCache(queryClient)).toEqual(['01F', '01B-temp', '01A-temp']) }) })