Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(app): remove messaging, composer, thread and forum tests

Hampusa87035a460cf
diff --git a/fluxer_app/src/features/forum/state/ForumPosts.test.ts b/fluxer_app/src/features/forum/state/ForumPosts.test.ts
deleted file mode 100644
index 70cb2873f..000000000
--- a/fluxer_app/src/features/forum/state/ForumPosts.test.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Channel, type ChannelWire} from '@app/features/channel/models/Channel';
-import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const channels = new Map<string, Channel>();
-const activeGuilds = new Set<string>();
-const readableChannels = new Set<string>();
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: () => undefined, cacheUsers: () => {}}}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => channels.get(id)},
-}));
-vi.mock('@app/features/threads/state/ThreadGuilds', () => ({
- default: {isActive: (guildId: string | null | undefined) => guildId != null && activeGuilds.has(guildId)},
-}));
-vi.mock('@app/features/threads/state/ChannelThreads', () => ({
- default: {
- upsert: (wire: ChannelWire, guildId?: string) => {
- const channel = new Channel({...wire, guild_id: wire.guild_id ?? guildId});
- channels.set(channel.id, channel);
- return channel;
- },
- },
-}));
-vi.mock('@app/features/permissions/state/Permission', () => ({
- default: {
- can: (permission: bigint, channel: {id: string}) =>
- permission === Permissions.READ_MESSAGE_HISTORY && readableChannels.has(channel.id),
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn()},
-}));
-
-const {
- default: ForumPosts,
- FORUM_SEARCH_DEBOUNCE_MS,
- POST_DATA_DEBOUNCE_MS,
-} = await import('@app/features/forum/state/ForumPosts');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-
-const GUILD = '1500000000000000001';
-const FORUM = '1500000000000000002';
-const POST = '1500000000000000003';
-
-function seedForum(): Channel {
- const forum = new Channel({id: FORUM, type: ChannelTypes.GUILD_FORUM, guild_id: GUILD, name: 'forum'});
- channels.set(FORUM, forum);
- return forum;
-}
-
-function searchBody(threadIds: Array<string>) {
- return {
- threads: threadIds.map((id) => ({id, type: ChannelTypes.PUBLIC_THREAD, guild_id: GUILD, parent_id: FORUM})),
- members: [],
- has_more: false,
- total_results: threadIds.length,
- first_messages: [],
- };
-}
-
-function requestedPath(call: number): URL {
- const path = vi.mocked(http.get).mock.calls[call][0] as string;
- return new URL(path, 'https://fluxer.test');
-}
-
-async function flush(): Promise<void> {
- await vi.advanceTimersByTimeAsync(0);
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- channels.clear();
- activeGuilds.clear();
- readableChannels.clear();
- activeGuilds.add(GUILD);
- readableChannels.add(FORUM);
- vi.mocked(http.get).mockReset();
- vi.mocked(http.post).mockReset();
- ForumPosts.reset();
-});
-
-afterEach(() => {
- ForumPosts.reset();
- vi.useRealTimers();
-});
-
-describe('ForumPosts search debounce', () => {
- it('sends one search after the user stops typing', async () => {
- const forum = seedForum();
- vi.mocked(http.get).mockResolvedValue({ok: true, status: 200, headers: {}, body: searchBody([POST])});
- ForumPosts.setQuery(forum, 'he');
- await vi.advanceTimersByTimeAsync(FORUM_SEARCH_DEBOUNCE_MS - 1);
- ForumPosts.setQuery(forum, 'hello');
- await vi.advanceTimersByTimeAsync(FORUM_SEARCH_DEBOUNCE_MS - 1);
- expect(http.get).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(1);
- expect(http.get).toHaveBeenCalledTimes(1);
- expect(requestedPath(0).pathname).toBe(`/channels/${FORUM}/threads/search`);
- expect(requestedPath(0).searchParams.get('name')).toBe('hello');
- expect(ForumPosts.getList(FORUM, 'search').ids).toEqual([POST]);
- });
-
- it('cancels a pending search when the query is cleared', async () => {
- const forum = seedForum();
- ForumPosts.setQuery(forum, 'hello');
- ForumPosts.setQuery(forum, '');
- await vi.advanceTimersByTimeAsync(FORUM_SEARCH_DEBOUNCE_MS * 2);
- expect(http.get).not.toHaveBeenCalled();
- expect(ForumPosts.isSearching(FORUM)).toBe(false);
- });
-});
-
-describe('ForumPosts index backoff', () => {
- it('retries a 202 after retry_after and doubles the wait', async () => {
- const forum = seedForum();
- const notReady = {ok: true, status: 202, headers: {}, body: {code: 'SEARCH_INDEX_NOT_READY', retry_after: 2}};
- vi.mocked(http.get)
- .mockResolvedValueOnce(notReady)
- .mockResolvedValueOnce(notReady)
- .mockResolvedValueOnce({ok: true, status: 200, headers: {}, body: searchBody([POST])});
- ForumPosts.loadMore(forum, 'archived');
- await flush();
- expect(http.get).toHaveBeenCalledTimes(1);
- expect(ForumPosts.getList(FORUM, 'archived').indexing).toBe(true);
- await vi.advanceTimersByTimeAsync(1999);
- expect(http.get).toHaveBeenCalledTimes(1);
- await vi.advanceTimersByTimeAsync(1);
- expect(http.get).toHaveBeenCalledTimes(2);
- await vi.advanceTimersByTimeAsync(3999);
- expect(http.get).toHaveBeenCalledTimes(2);
- await vi.advanceTimersByTimeAsync(1);
- expect(http.get).toHaveBeenCalledTimes(3);
- const list = ForumPosts.getList(FORUM, 'archived');
- expect(list.indexing).toBe(false);
- expect(list.ids).toEqual([POST]);
- });
-
- it('gives up with a failed state after too many 202 answers', async () => {
- const forum = seedForum();
- vi.mocked(http.get).mockResolvedValue({ok: true, status: 202, headers: {}, body: {retry_after: 1}});
- ForumPosts.loadMore(forum, 'archived');
- await vi.advanceTimersByTimeAsync(10 * 60_000);
- const list = ForumPosts.getList(FORUM, 'archived');
- expect(list.failed).toBe(true);
- expect(list.indexing).toBe(false);
- const calls = vi.mocked(http.get).mock.calls.length;
- await vi.advanceTimersByTimeAsync(10 * 60_000);
- expect(http.get).toHaveBeenCalledTimes(calls);
- });
-
- it('drops a retry when the filter changes', async () => {
- const forum = seedForum();
- vi.mocked(http.get).mockResolvedValue({ok: true, status: 202, headers: {}, body: {retry_after: 1}});
- ForumPosts.loadMore(forum, 'archived');
- await flush();
- ForumPosts.setTagFilter(forum, ['11']);
- await vi.advanceTimersByTimeAsync(60_000);
- expect(http.get).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('ForumPosts post data', () => {
- it('batches ids within the debounce and never asks twice', async () => {
- const forum = seedForum();
- vi.mocked(http.post).mockResolvedValue({
- ok: true,
- status: 200,
- headers: {},
- body: {threads: {[POST]: {owner: null, first_message: null}}},
- });
- ForumPosts.requestPostData(forum, [POST]);
- ForumPosts.requestPostData(forum, [POST, '1500000000000000004']);
- await vi.advanceTimersByTimeAsync(POST_DATA_DEBOUNCE_MS);
- expect(http.post).toHaveBeenCalledTimes(1);
- expect(vi.mocked(http.post).mock.calls[0][1]).toEqual({body: {thread_ids: [POST, '1500000000000000004']}});
- expect(ForumPosts.getFirstMessage(POST)).toBeNull();
- ForumPosts.requestPostData(forum, [POST]);
- await vi.advanceTimersByTimeAsync(POST_DATA_DEBOUNCE_MS);
- expect(http.post).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/useAutocompleteMemberSearch.test.tsx b/fluxer_app/src/features/lexical/composer/useAutocompleteMemberSearch.test.tsx
deleted file mode 100644
index 66abe7c7c..000000000
--- a/fluxer_app/src/features/lexical/composer/useAutocompleteMemberSearch.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {useGuildMemberAutocompleteSearch} from '@app/features/lexical/composer/useAutocompleteMemberSearch';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- begin: vi.fn(),
- cancel: vi.fn(),
- destroy: vi.fn(),
- fetch: vi.fn(),
- member: vi.fn((guildId: string, id: string) => ({guildId, id})),
- emit: null as null | ((results: Array<{id: string}>) => void),
- results: vi.fn(),
-}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: mocks.member}}));
-vi.mock('@app/features/member/state/MemberSearch', () => ({
- default: {
- getSearchContext: (emit: typeof mocks.emit) => {
- mocks.emit = emit;
- return {beginSearch: mocks.begin, cancelSearch: mocks.cancel, destroy: mocks.destroy};
- },
- fetchMembersInBackground: mocks.fetch,
- },
-}));
-vi.mock('@app/features/messaging/utils/AutocompleteOptionBuilders', () => ({MEMBER_SEARCH_LIMIT: 20}));
-let root: Root;
-let node: HTMLDivElement;
-function Probe({guildId = 'guild-a', query = 'alice'}: {guildId?: string; query?: string | null}) {
- useGuildMemberAutocompleteSearch({guildId, query, setResults: mocks.results});
- return null;
-}
-beforeEach(async () => {
- vi.clearAllMocks();
- vi.useFakeTimers();
- node = document.createElement('div');
- document.body.append(node);
- root = createRoot(node);
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- await act(async () => root.render(<Probe data-flx="lexical.composer.use-autocomplete-member-search-test.probe" />));
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- node.remove();
- vi.useRealTimers();
-});
-describe('autocomplete member search lifecycle', () => {
- it('fetches only the latest query after rapid edits', async () => {
- await act(async () =>
- root.render(<Probe query="alicia" data-flx="lexical.composer.use-autocomplete-member-search-test.probe--2" />),
- );
- await act(async () => vi.advanceTimersByTime(200));
- expect(mocks.fetch).toHaveBeenCalledExactlyOnceWith('alicia', ['guild-a']);
- });
- it('maps results against the active guild after switching context', async () => {
- await act(async () =>
- root.render(<Probe guildId="guild-b" data-flx="lexical.composer.use-autocomplete-member-search-test.probe--3" />),
- );
- mocks.emit?.([{id: 'user'}]);
- expect(mocks.results).toHaveBeenLastCalledWith([{guildId: 'guild-b', id: 'user'}]);
- });
- it('cancels pending work when the trigger closes and destroys the search context on unmount', async () => {
- await act(async () =>
- root.render(<Probe query={null} data-flx="lexical.composer.use-autocomplete-member-search-test.probe--4" />),
- );
- expect(mocks.cancel).toHaveBeenCalledOnce();
- mocks.emit?.([{id: 'late'}]);
- expect(mocks.results).toHaveBeenLastCalledWith([]);
- await act(async () => vi.advanceTimersByTime(200));
- expect(mocks.fetch).not.toHaveBeenCalled();
- await act(async () => root.unmount());
- expect(mocks.destroy).toHaveBeenCalledOnce();
- });
-});
diff --git a/fluxer_app/src/features/messaging/hooks/useImageRecovery.test.tsx b/fluxer_app/src/features/messaging/hooks/useImageRecovery.test.tsx
deleted file mode 100644
index 8eac8acc2..000000000
--- a/fluxer_app/src/features/messaging/hooks/useImageRecovery.test.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// @vitest-environment happy-dom
-
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-vi.mock('@lingui/react/macro', () => ({
- useLingui: () => ({i18n: {_: (descriptor: {message?: string} | undefined) => descriptor?.message ?? ''}}),
-}));
-vi.mock('@app/features/accessibility/state/Accessibility', () => ({default: {useReducedMotion: false}}));
-vi.mock('@app/features/ui/tooltip/Tooltip', () => ({Tooltip: ({children}: {children: unknown}) => children}));
-vi.mock('@app/features/ui/focus_ring/FocusRing', () => ({default: ({children}: {children: unknown}) => children}));
-vi.mock('@app/features/app/constants/AppConstants', () => ({getStatusTypeLabel: () => ''}));
-
-const AVATAR_URL = 'https://chat.example.com/media/avatars/1/abc.webp?size=128';
-const GUILD_ICON_URL = 'https://chat.example.com/media/icons/2/def.webp?size=96';
-const RESPONSE_DELAY_MS = 5;
-
-const network = {up: true, requests: [] as Array<string>};
-
-class SelfHostImage {
- onload: (() => void) | null = null;
- onerror: (() => void) | null = null;
- decoding = 'auto';
- complete = false;
- naturalWidth = 0;
- naturalHeight = 0;
- currentSrc = '';
- private source = '';
-
- get src(): string {
- return this.source;
- }
-
- set src(next: string) {
- this.source = next;
- const answered = network.up;
- network.requests.push(next);
- setTimeout(() => {
- this.complete = true;
- if (!answered) {
- this.onerror?.();
- return;
- }
- this.naturalWidth = 64;
- this.naturalHeight = 64;
- this.currentSrc = next;
- this.onload?.();
- }, RESPONSE_DELAY_MS);
- }
-
- getAttribute(): string {
- return this.source;
- }
-
- get ownerDocument(): Document {
- return document;
- }
-}
-
-async function loadHarness() {
- const React = await import('react');
- const {act} = React;
- const {createRoot} = await import('react-dom/client');
- const {BaseAvatar} = await import('@app/features/ui/components/BaseAvatar');
- const {useRecoveringBackgroundImageURL} = await import('@app/features/messaging/hooks/useImageRecovery');
- const ImageCacheUtils = await import('@app/features/messaging/utils/ImageCacheUtils');
- ImageCacheUtils._clearForTests();
- const host = document.createElement('div');
- document.body.appendChild(host);
- const root = createRoot(host);
- function GuildRailIcon({url}: {url: string}) {
- const paintable = useRecoveringBackgroundImageURL(url);
- return React.createElement('div', {
- 'data-testid': 'guild-icon',
- style: paintable == null ? undefined : {backgroundImage: `url(${paintable})`},
- });
- }
- const advance = async (ms: number, step = 1000) => {
- for (let elapsed = 0; elapsed < ms; elapsed += step) {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(Math.min(step, ms - elapsed));
- });
- }
- };
- const avatarImage = () => host.querySelector<HTMLImageElement>('[data-flx="ui.base-avatar.image"]');
- const guildIcon = () => host.querySelector<HTMLElement>('[data-testid="guild-icon"]');
- const failAvatarElement = async () => {
- await act(async () => {
- avatarImage()?.dispatchEvent(new Event('error'));
- });
- };
- const render = async (children: Array<React.ReactElement>) => {
- await act(async () => {
- root.render(React.createElement(React.Fragment, null, ...children));
- });
- };
- const avatar = React.createElement(BaseAvatar, {key: 'avatar', size: 40, avatarUrl: AVATAR_URL});
- const rail = React.createElement(GuildRailIcon, {key: 'rail', url: GUILD_ICON_URL});
- return {act, root, advance, avatarImage, guildIcon, failAvatarElement, render, avatar, rail, ImageCacheUtils};
-}
-
-beforeEach(() => {
- vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'Date']});
- vi.stubGlobal('Image', SelfHostImage);
- vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
- network.up = true;
- network.requests.length = 0;
-});
-
-afterEach(() => {
- vi.useRealTimers();
- vi.unstubAllGlobals();
- document.body.innerHTML = '';
-});
-
-describe('self-hosted media that failed during an outage loads again on the same mount', () => {
- test('a long-lived avatar and guild rail icon come back after a self-host restart without a remount', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar, harness.rail]);
- await harness.failAvatarElement();
- await harness.advance(30_000);
-
- expect(harness.avatarImage()).toBeNull();
- expect(harness.guildIcon()?.style.backgroundImage).toBe('');
- const requestsDuringOutage = network.requests.length;
-
- network.up = true;
- await harness.advance(5 * 60_000);
-
- expect(harness.avatarImage()?.getAttribute('src')).toBe(AVATAR_URL);
- expect(harness.guildIcon()?.style.backgroundImage).toContain(GUILD_ICON_URL);
- expect(harness.ImageCacheUtils.hasFailedImage(AVATAR_URL)).toBe(false);
- expect(network.requests.length).toBeGreaterThan(requestsDuringOutage);
- await harness.act(async () => harness.root.unmount());
- });
-
- test('retries back off during a long outage instead of hammering the self-host', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar]);
- await harness.failAvatarElement();
- await harness.advance(10 * 60_000, 5000);
-
- const lateWindowStart = network.requests.length;
- await harness.advance(5 * 60_000, 5000);
- const lateWindowRequests = network.requests.length - lateWindowStart;
-
- expect(lateWindowRequests).toBeGreaterThan(0);
- expect(lateWindowRequests).toBeLessThanOrEqual(5 * 3 + 3);
- await harness.act(async () => harness.root.unmount());
- });
-
- test('an avatar mounted while its URL is cooling down starts blank and still recovers', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar]);
- await harness.failAvatarElement();
- expect(harness.ImageCacheUtils.hasFailedImage(AVATAR_URL)).toBe(true);
-
- await harness.render([]);
- await harness.render([harness.avatar]);
- expect(harness.avatarImage()).toBeNull();
-
- network.up = true;
- await harness.advance(70_000);
- expect(harness.avatarImage()?.getAttribute('src')).toBe(AVATAR_URL);
- await harness.act(async () => harness.root.unmount());
- });
-
- test('coming back online retries at once instead of waiting out the backoff', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar]);
- await harness.failAvatarElement();
- await harness.advance(10 * 60_000, 5000);
- expect(harness.avatarImage()).toBeNull();
-
- network.up = true;
- await harness.act(async () => {
- window.dispatchEvent(new Event('online'));
- });
- await harness.advance(100, 10);
- expect(harness.avatarImage()?.getAttribute('src')).toBe(AVATAR_URL);
- await harness.act(async () => harness.root.unmount());
- });
-
- test('refocusing the window during an outage does not retry in a burst', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar]);
- await harness.failAvatarElement();
- await harness.advance(10 * 60_000, 5000);
- const before = network.requests.length;
- for (let i = 0; i < 20; i++) {
- await harness.act(async () => {
- window.dispatchEvent(new Event('focus'));
- });
- await harness.advance(500, 10);
- }
- expect(network.requests.length - before).toBeLessThanOrEqual(3);
- await harness.act(async () => harness.root.unmount());
- });
-
- test('an unmounted avatar stops retrying', async () => {
- const harness = await loadHarness();
- network.up = false;
- await harness.render([harness.avatar]);
- await harness.failAvatarElement();
- await harness.render([]);
- await harness.advance(60_000, 5000);
- const afterUnmount = network.requests.length;
- await harness.advance(10 * 60_000, 5000);
- expect(network.requests.length).toBe(afterUnmount);
- await harness.act(async () => harness.root.unmount());
- });
-});
diff --git a/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx b/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx
deleted file mode 100644
index 7e3e8c61c..000000000
--- a/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {APP_STORAGE_INDEXED_DB_NAME} from '@app/features/platform/state/PersistentStorageBackend';
-import {getProtectedIndexedDB} from '@app/features/platform/state/ProtectedWebStorage';
-import {observer} from 'mobx-react-lite';
-import {act, useImperativeHandle, useRef, useState} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/typing/rolling/RollingTypingSender', () => ({
- default: {handleComposerChange: vi.fn(), stopTyping: vi.fn(), handleOwnMessageSent: vi.fn()},
-}));
-
-type StorageModule = typeof import('@app/features/platform/state/PersistentStorage');
-type PersistenceModule = typeof import('@app/features/platform/utils/MobXPersistence');
-type DraftsStore = typeof import('@app/features/messaging/state/MessagingDrafts').default;
-type DraftHook = typeof import('@app/features/messaging/hooks/useTextareaDraftAndTyping').useTextareaDraftAndTyping;
-
-interface ComposerHandle {
- type(value: string): void;
- value(): string;
-}
-
-interface Client {
- readonly storage: StorageModule;
- readonly persistence: PersistenceModule;
- readonly drafts: DraftsStore;
- readonly Composer: React.FC<{owner: string; handle: React.RefObject<ComposerHandle | null>}>;
-}
-
-const ACCOUNT_A = 'https://one.example/api::100';
-const ACCOUNT_B = 'https://one.example/api::200';
-const CHANNEL_ID = '1555752678099779590';
-const DRAFT_FLUSH_DELAY_MS = 450;
-
-let root: Root | null = null;
-let container: HTMLElement | null = null;
-
-function deleteAppStorageDatabase(): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const factory = getProtectedIndexedDB();
- if (factory == null) {
- resolve();
- return;
- }
- const request = factory.deleteDatabase(APP_STORAGE_INDEXED_DB_NAME);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error);
- request.onblocked = () => resolve();
- });
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-async function loadClient(): Promise<Client> {
- vi.resetModules();
- const storage: StorageModule = await import('@app/features/platform/state/PersistentStorage');
- const persistence: PersistenceModule = await import('@app/features/platform/utils/MobXPersistence');
- await storage.initializeAppStorage({scoped: true});
- await storage.activateAppStorageScope(ACCOUNT_A);
- const drafts = (await import('@app/features/messaging/state/MessagingDrafts')).default;
- await persistence.awaitHydration('Drafts');
- const useTextareaDraftAndTyping: DraftHook = (await import('@app/features/messaging/hooks/useTextareaDraftAndTyping'))
- .useTextareaDraftAndTyping;
- const Composer = observer(({owner, handle}: {owner: string; handle: React.RefObject<ComposerHandle | null>}) => {
- const draft = drafts.getDraft(CHANNEL_ID);
- const [value, setValue] = useState(draft);
- const previousValueRef = useRef(value);
- const valueRef = useRef(value);
- valueRef.current = value;
- useImperativeHandle(handle, () => ({type: setValue, value: () => valueRef.current}), []);
- useTextareaDraftAndTyping({
- draftOwner: owner,
- channelId: CHANNEL_ID,
- value,
- setValue,
- draft,
- previousValueRef,
- enabled: true,
- isEditingMessageInComposer: false,
- });
- return null;
- });
- return {storage, persistence, drafts, Composer};
-}
-
-async function render(client: Client, owner: string, handle: React.RefObject<ComposerHandle | null>): Promise<void> {
- await act(async () => {
- root?.render(
- <client.Composer
- key={owner}
- owner={owner}
- handle={handle}
- data-flx="messaging.use-textarea-draft-and-typing-test.client-composer"
- />,
- );
- });
-}
-
-async function type(handle: React.RefObject<ComposerHandle | null>, value: string): Promise<void> {
- await act(async () => {
- handle.current?.type(value);
- });
-}
-
-async function switchScope(client: Client, scope: string): Promise<void> {
- await act(async () => {
- await client.storage.activateAppStorageScope(scope);
- });
-}
-
-async function storedDrafts(client: Client, scope: string): Promise<Record<string, string>> {
- client.persistence.flushPendingPersistWrites();
- await client.storage.flushAppStorageWrites();
- const {getPersistentStorageBackend} = await import('@app/features/platform/state/PersistentStorageBackend');
- const entry = await getPersistentStorageBackend().get(scope, 'Drafts');
- if (entry?.value == null) {
- return {};
- }
- return (JSON.parse(entry.value) as {drafts?: Record<string, string>}).drafts ?? {};
-}
-
-beforeEach(async () => {
- Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true);
- window.localStorage.clear();
- await deleteAppStorageDatabase();
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
-});
-
-afterEach(async () => {
- await act(async () => {
- root?.unmount();
- });
- container?.remove();
- root = null;
- container = null;
-});
-
-test('text typed under one account never reaches the next account on the same channel', async () => {
- const client = await loadClient();
- const handle: React.RefObject<ComposerHandle | null> = {current: null};
- await render(client, ACCOUNT_A, handle);
- await type(handle, 'draft typed by account A');
-
- await switchScope(client, ACCOUNT_B);
- await render(client, ACCOUNT_B, handle);
-
- expect(handle.current?.value()).toBe('');
- expect(client.drafts.getDraft(CHANNEL_ID)).toBe('');
- await type(handle, 'typed by account B');
- await act(() => sleep(DRAFT_FLUSH_DELAY_MS));
- expect(await storedDrafts(client, ACCOUNT_B)).toEqual({[CHANNEL_ID]: 'typed by account B'});
- expect(await storedDrafts(client, ACCOUNT_A)).toEqual({[CHANNEL_ID]: 'draft typed by account A'});
-
- await switchScope(client, ACCOUNT_A);
- await render(client, ACCOUNT_A, handle);
- expect(handle.current?.value()).toBe('draft typed by account A');
-});
-
-test('a composer that outlives its account neither adopts nor writes the next account drafts', async () => {
- const client = await loadClient();
- await switchScope(client, ACCOUNT_B);
- client.drafts.createDraft(CHANNEL_ID, 'draft owned by account B');
- await switchScope(client, ACCOUNT_A);
- const handle: React.RefObject<ComposerHandle | null> = {current: null};
- await render(client, ACCOUNT_A, handle);
- await type(handle, 'saved before the switch');
-
- await switchScope(client, ACCOUNT_B);
- expect(handle.current?.value()).toBe('saved before the switch');
- await type(handle, 'typed after the storage scope moved');
- await act(() => sleep(DRAFT_FLUSH_DELAY_MS));
- await act(async () => {
- root?.render(null);
- });
-
- expect(client.drafts.getDraft(CHANNEL_ID)).toBe('draft owned by account B');
- expect(await storedDrafts(client, ACCOUNT_B)).toEqual({[CHANNEL_ID]: 'draft owned by account B'});
- expect(await storedDrafts(client, ACCOUNT_A)).toEqual({[CHANNEL_ID]: 'saved before the switch'});
-});
diff --git a/fluxer_app/src/features/messaging/state/MessageQueueAccountTransition.test.ts b/fluxer_app/src/features/messaging/state/MessageQueueAccountTransition.test.ts
deleted file mode 100644
index 42f2b24a4..000000000
--- a/fluxer_app/src/features/messaging/state/MessageQueueAccountTransition.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// @vitest-environment happy-dom
-
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- accountKey: 'https://one.example/api::100' as string | null,
- post: vi.fn(),
-}));
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-vi.mock('@lingui/react/macro', () => ({Trans: () => null, useLingui: () => ({i18n: {_: () => ''}})}));
-
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {post: mocks.post, get: vi.fn()}}));
-
-vi.mock('@app/features/platform/state/AuthSession', () => ({
- default: {
- get currentAccountKey() {
- return mocks.accountKey;
- },
- userId: null,
- },
-}));
-
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({
- default: {foregroundConnection: {isReady: false, isConnected: false, connectionEpoch: 1}},
-}));
-
-vi.mock('@app/features/navigation/state/SelectedChannel', () => ({
- default: {currentChannelId: null, selectedChannelIds: new Map<string, string>()},
-}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {
- getChannel: (id: string) => ({id, guildId: null, lastMessageId: null, isPrivate: () => true}),
- handleMessageCreate: vi.fn(),
- },
-}));
-
-const {AccountScopedWork, AccountScopedWorkTransitionReason} = await import(
- '@app/features/platform/state/AccountScopedWork'
-);
-const MessageCommands = await import('@app/features/messaging/commands/MessageCommands');
-const {default: ChannelSearch} = await import('@app/features/channel/state/ChannelSearch');
-const {default: ChannelSticker} = await import('@app/features/channel/state/ChannelSticker');
-const {default: MessageEdit} = await import('@app/features/messaging/state/MessageEdit');
-const {default: Drafts} = await import('@app/features/messaging/state/MessagingDrafts');
-const {default: MessageEditMobile} = await import('@app/features/messaging/state/MessageEditMobile');
-const {default: MessageFocus} = await import('@app/features/messaging/state/MessageFocus');
-const {default: MessageReply} = await import('@app/features/messaging/state/MessageReply');
-const {CloudUpload} = await import('@app/features/messaging/upload/CloudUpload');
-const {default: KeyboardMode} = await import('@app/features/ui/state/KeyboardMode');
-
-const ACCOUNT_A = 'https://one.example/api::100';
-const ACCOUNT_B = 'https://one.example/api::200';
-const CHANNEL_ID = '1555752678099779590';
-const MESSAGE_ID = '1555923739894349824';
-
-interface Deferred<T> {
- readonly promise: Promise<T>;
- readonly resolve: (value: T) => void;
-}
-
-function deferred<T>(): Deferred<T> {
- let resolve: (value: T) => void = () => undefined;
- const promise = new Promise<T>((settle) => {
- resolve = settle;
- });
- return {promise, resolve};
-}
-
-async function settle(): Promise<void> {
- for (let i = 0; i < 10; i++) {
- await Promise.resolve();
- }
- await new Promise((resolve) => setTimeout(resolve, 5));
-}
-
-function send(nonce: string, content: string): Promise<unknown> {
- expect(MessageCommands.reserveSend(CHANNEL_ID, nonce)).toBe(true);
- return MessageCommands.send(CHANNEL_ID, {content, nonce});
-}
-
-describe('composer state across an account transition', () => {
- afterEach(() => {
- mocks.accountKey = ACCOUNT_A;
- mocks.post.mockReset();
- });
-
- it('never sends a message queued by the previous account', async () => {
- const first = deferred<{body: {id: string; channel_id: string}}>();
- mocks.post.mockImplementationOnce(() => first.promise);
- mocks.post.mockResolvedValue({body: {id: '2', channel_id: CHANNEL_ID}});
- const firstSend = send('1001', 'first message from account A');
- const queuedSend = send('1002', 'queued message from account A');
- await settle();
- expect(mocks.post).toHaveBeenCalledTimes(1);
-
- mocks.accountKey = ACCOUNT_B;
- first.resolve({body: {id: '1', channel_id: CHANNEL_ID}});
- await firstSend;
- await settle();
-
- expect(await queuedSend).toBeNull();
- expect(mocks.post).toHaveBeenCalledTimes(1);
- });
-
- it('drops every pending upload with the composer and keeps the typed draft when the account changes', async () => {
- const otherChannelId = '1555752678099779591';
- Drafts.createDraft(CHANNEL_ID, 'draft typed by account A');
- await CloudUpload.addFiles(CHANNEL_ID, [new File(['one'], 'pending-one.txt', {type: 'text/plain'})]);
- await CloudUpload.addFiles(otherChannelId, [new File(['two'], 'pending-two.txt', {type: 'text/plain'})]);
- const claimed = CloudUpload.claimAttachmentsForMessage(CHANNEL_ID, '2001', undefined, {
- content: 'message being sent by account A',
- });
- expect(claimed).toHaveLength(1);
- expect(CloudUpload.getMessageUpload('2001')).not.toBeNull();
- expect(CloudUpload.getTextareaAttachments(otherChannelId)).toHaveLength(1);
-
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {});
-
- expect(CloudUpload.getTextareaAttachments(CHANNEL_ID)).toHaveLength(0);
- expect(CloudUpload.getTextareaAttachments(otherChannelId)).toHaveLength(0);
- expect(CloudUpload.getMessageUpload('2001')).toBeNull();
- expect(Drafts.getDraft(CHANNEL_ID)).toBe('draft typed by account A');
- Drafts.deleteDraft(CHANNEL_ID);
- });
-
- it('clears reply, edit, search, sticker, selection, attachment and message focus state when the account changes', async () => {
- MessageEdit.startEditing(CHANNEL_ID, MESSAGE_ID, 'edit typed by account A');
- MessageEditMobile.startEditingMobile(CHANNEL_ID, MESSAGE_ID);
- ChannelSearch.setSearchInput(CHANNEL_ID, 'query typed by account A', []);
- ChannelSearch.setActiveSearch(CHANNEL_ID, 'query typed by account A', []);
- ChannelSticker.pendingStickers.set(CHANNEL_ID, {id: '1'} as never);
- MessageReply.replyingMessageIds[CHANNEL_ID] = {messageId: MESSAGE_ID, mentioning: true, snapshot: {} as never};
- await CloudUpload.addFiles(CHANNEL_ID, [new File(['attachment'], 'from-account-a.txt', {type: 'text/plain'})]);
- expect(CloudUpload.getTextareaAttachments(CHANNEL_ID)).toHaveLength(1);
- KeyboardMode.enterKeyboardMode(false);
- MessageFocus.focusMessage(CHANNEL_ID, MESSAGE_ID);
- expect(MessageFocus.focusedMessageId).toBe(MESSAGE_ID);
-
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {});
-
- expect(MessageEdit.getEditingMessageId(CHANNEL_ID)).toBeNull();
- expect(MessageEdit.getDraftContent(MESSAGE_ID)).toBeNull();
- expect(MessageEditMobile.getEditingMobileMessageId(CHANNEL_ID)).toBeNull();
- expect(ChannelSearch.getContext(CHANNEL_ID).searchQuery).toBe('');
- expect(ChannelSearch.getContext(CHANNEL_ID).isSearchActive).toBe(false);
- expect(ChannelSticker.getPendingSticker(CHANNEL_ID)).toBeNull();
- expect(MessageReply.getReplyingMessage(CHANNEL_ID)).toBeNull();
- expect(CloudUpload.getTextareaAttachments(CHANNEL_ID)).toHaveLength(0);
- expect(MessageFocus.focusedMessageId).toBeNull();
- expect(MessageFocus.focusedChannelId).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/MessagingMessagesAccountTransition.test.ts b/fluxer_app/src/features/messaging/state/MessagingMessagesAccountTransition.test.ts
deleted file mode 100644
index 993e462d4..000000000
--- a/fluxer_app/src/features/messaging/state/MessagingMessagesAccountTransition.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// @vitest-environment happy-dom
-
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- selectedChannelId: null as string | null,
- gatewayReady: false,
- get: vi.fn(),
-}));
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-vi.mock('@lingui/react/macro', () => ({Trans: () => null, useLingui: () => ({i18n: {_: () => ''}})}));
-
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {get: mocks.get}}));
-
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({
- default: {
- foregroundConnection: {
- get isReady() {
- return mocks.gatewayReady;
- },
- get isConnected() {
- return mocks.gatewayReady;
- },
- connectionEpoch: 1,
- },
- },
-}));
-
-vi.mock('@app/features/navigation/state/SelectedChannel', () => ({
- default: {
- get currentChannelId() {
- return mocks.selectedChannelId;
- },
- selectedChannelIds: new Map<string, string>(),
- },
-}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {
- getChannel: (id: string) => ({id, guildId: null, lastMessageId: null, isPrivate: () => true}),
- handleMessageCreate: vi.fn(),
- },
-}));
-
-const {AccountScopedWork, AccountScopedWorkTransitionReason} = await import(
- '@app/features/platform/state/AccountScopedWork'
-);
-const {default: Messages} = await import('@app/features/messaging/state/MessagingMessages');
-const MessageCommands = await import('@app/features/messaging/commands/MessageCommands');
-
-const CHANNEL_ID = '1555752678099779590';
-
-function respondThroughAdmission(): void {
- mocks.get.mockImplementation(async () => {
- const ticket = AccountScopedWork.begin();
- ticket.dispose();
- return {body: []};
- });
-}
-
-async function settle(): Promise<void> {
- for (let i = 0; i < 10; i++) {
- await Promise.resolve();
- }
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-describe('message hydration across an account transition', () => {
- afterEach(() => {
- Messages.handleSessionInvalidated();
- mocks.selectedChannelId = null;
- mocks.gatewayReady = false;
- mocks.get.mockReset();
- });
-
- it('loads the restored channel after READY arrives inside the transition', async () => {
- respondThroughAdmission();
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- Messages.handleSessionInvalidated();
- mocks.selectedChannelId = CHANNEL_ID;
- mocks.gatewayReady = true;
- Messages.handleGatewayReady();
- await settle();
- expect(mocks.get).not.toHaveBeenCalled();
- expect(Messages.getMessages(CHANNEL_ID).error).toBe(false);
- });
- await settle();
- expect(mocks.get).toHaveBeenCalledTimes(1);
- const messages = Messages.getMessages(CHANNEL_ID);
- expect(messages.error).toBe(false);
- expect(messages.ready).toBe(true);
- });
-
- it('loads the restored channel when it is selected inside the transition on a ready gateway', async () => {
- respondThroughAdmission();
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- mocks.gatewayReady = true;
- Messages.handleGatewayReady();
- mocks.selectedChannelId = CHANNEL_ID;
- Messages.handleChannelSelect({channelId: CHANNEL_ID});
- await settle();
- expect(mocks.get).not.toHaveBeenCalled();
- const held = Messages.getMessages(CHANNEL_ID);
- expect(held.error).toBe(false);
- expect(held.loadingMore).toBe(false);
- });
- await settle();
- expect(mocks.get).toHaveBeenCalledTimes(1);
- const messages = Messages.getMessages(CHANNEL_ID);
- expect(messages.error).toBe(false);
- expect(messages.ready).toBe(true);
- });
-
- it('does not churn message state for fetches requested while admission is suspended', async () => {
- respondThroughAdmission();
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- mocks.selectedChannelId = CHANNEL_ID;
- Messages.getMessages(CHANNEL_ID);
- const version = Messages.version;
- await MessageCommands.fetchMessages(CHANNEL_ID, null, null, 50);
- await MessageCommands.fetchMessages(CHANNEL_ID, null, null, 50);
- expect(Messages.version).toBe(version);
- expect(mocks.get).not.toHaveBeenCalled();
- });
- });
-
- it('keeps a load interrupted by the transition out of the failed state and reloads it on release', async () => {
- mocks.selectedChannelId = CHANNEL_ID;
- mocks.gatewayReady = true;
- mocks.get.mockImplementationOnce(() => {
- const ticket = AccountScopedWork.begin();
- return new Promise((_resolve, reject) => {
- ticket.signal.addEventListener('abort', () => {
- ticket.dispose();
- reject(ticket.signal.reason);
- });
- });
- });
- const interrupted = MessageCommands.fetchMessages(CHANNEL_ID, null, null, 50);
- await settle();
- expect(Messages.getMessages(CHANNEL_ID).loadingMore).toBe(true);
- respondThroughAdmission();
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- await interrupted;
- const held = Messages.getMessages(CHANNEL_ID);
- expect(held.error).toBe(false);
- expect(held.loadingMore).toBe(false);
- });
- await settle();
- expect(mocks.get).toHaveBeenCalledTimes(2);
- const messages = Messages.getMessages(CHANNEL_ID);
- expect(messages.error).toBe(false);
- expect(messages.ready).toBe(true);
- });
-
- it('still marks the channel failed for an ordinary request failure', async () => {
- mocks.selectedChannelId = CHANNEL_ID;
- mocks.gatewayReady = true;
- mocks.get.mockRejectedValue(new Error('boom'));
- await MessageCommands.fetchMessages(CHANNEL_ID, null, null, 50);
- expect(Messages.getMessages(CHANNEL_ID).error).toBe(true);
- });
-
- it('leaves the channel alone on release while the gateway is not ready', async () => {
- respondThroughAdmission();
- mocks.selectedChannelId = CHANNEL_ID;
- Messages.getMessages(CHANNEL_ID);
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.LOGOUT, async () => {});
- await settle();
- expect(mocks.get).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/MessagingMessagesViewGeneration.test.ts b/fluxer_app/src/features/messaging/state/MessagingMessagesViewGeneration.test.ts
deleted file mode 100644
index 3011ade36..000000000
--- a/fluxer_app/src/features/messaging/state/MessagingMessagesViewGeneration.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// @vitest-environment happy-dom
-
-import {instanceDiscoveryFixture} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-vi.mock('@lingui/react/macro', () => ({Trans: () => null, useLingui: () => ({i18n: {_: () => ''}})}));
-
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {get: vi.fn()}}));
-
-vi.mock('@app/features/app/state/GeoIP', () => ({default: {latitude: null, longitude: null}}));
-
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({
- default: {foregroundConnection: {isReady: false, isConnected: false, connectionEpoch: 1}},
-}));
-
-vi.mock('@app/features/navigation/state/SelectedChannel', () => ({
- default: {currentChannelId: null, selectedChannelIds: new Map<string, string>()},
-}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {
- getChannel: (id: string) => ({id, guildId: null, lastMessageId: null, isPrivate: () => true}),
- handleMessageCreate: vi.fn(),
- },
-}));
-
-const {default: RuntimeConfig} = await import('@app/features/app/state/RuntimeConfig');
-const {runtimeSnapshotFromDiscovery} = await import('@app/features/app/state/InstanceSnapshotStore');
-const {parseInstanceDiscoveryDocument} = await import('@fluxer/instance_bootstrap/src/Discovery');
-const {default: Messages} = await import('@app/features/messaging/state/MessagingMessages');
-
-RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(instanceDiscoveryFixture('https://one.example/api'))),
-);
-
-const CHANNEL_ID = '1555752678099779590';
-
-describe('message list view generation', () => {
- afterEach(() => {
- Messages.handleSessionInvalidated();
- });
-
- function loadOneMessage(): void {
- Messages.handleLoadMessagesSuccess({
- channelId: CHANNEL_ID,
- messages: [
- {
- id: '1555923739894349824',
- channel_id: CHANNEL_ID,
- author: {
- id: '100',
- username: 'nera1',
- discriminator: '0001',
- global_name: null,
- avatar: null,
- avatar_color: null,
- flags: 0,
- },
- type: 0,
- flags: 0,
- pinned: false,
- tts: false,
- mention_everyone: false,
- mentions: [],
- mention_roles: [],
- content: 'scrolled away under the first account',
- timestamp: '2026-10-04T18:50:00.000Z',
- },
- ],
- });
- }
-
- it('restarts the message list view when loaded messages are discarded', () => {
- loadOneMessage();
- expect(Messages.getMessages(CHANNEL_ID).length).toBe(1);
- const generation = Messages.cacheGeneration;
- Messages.handleSessionInvalidated();
- expect(Messages.cacheGeneration).toBe(generation + 1);
- expect(Messages.getMessages(CHANNEL_ID).length).toBe(0);
- });
-
- it('keeps the view when the next session invalidation finds nothing loaded', () => {
- loadOneMessage();
- Messages.handleSessionInvalidated();
- Messages.getMessages(CHANNEL_ID);
- const generation = Messages.cacheGeneration;
- Messages.handleSessionInvalidated();
- expect(Messages.cacheGeneration).toBe(generation);
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/ReactionStateMachine.test.ts b/fluxer_app/src/features/messaging/state/ReactionStateMachine.test.ts
deleted file mode 100644
index 84386359d..000000000
--- a/fluxer_app/src/features/messaging/state/ReactionStateMachine.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- emptyMap,
- getEmojiKey,
- type ReactionMap,
- transitionReactionMap,
-} from '@app/features/messaging/state/ReactionStateMachine';
-import type {ReactionEmoji} from '@app/features/messaging/utils/ReactionUtils';
-import type {MessageReaction} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-const ME = 'me-user-id';
-const ALICE = 'alice-id';
-const BOB = 'bob-id';
-const CAROL = 'carol-id';
-const FIRE: ReactionEmoji = {name: '🔥'};
-const HEART: ReactionEmoji = {name: '❤️'};
-const add = (map: ReactionMap, emoji: ReactionEmoji, userId: string, isCurrentUser = userId === ME) =>
- transitionReactionMap(map, {type: 'reaction.add', emoji, userId, isCurrentUser});
-const remove = (map: ReactionMap, emoji: ReactionEmoji, userId: string, isCurrentUser = userId === ME) =>
- transitionReactionMap(map, {type: 'reaction.remove', emoji, userId, isCurrentUser});
-const getRecord = (map: ReactionMap, emoji: ReactionEmoji) => map.get(getEmojiKey(emoji));
-const hydrate = (map: ReactionMap, reactions: ReadonlyArray<MessageReaction>, currentUserId?: string) =>
- transitionReactionMap(map, {type: 'reaction.hydrate', reactions, currentUserId}, currentUserId);
-
-describe('ReactionStateMachine: applyRemove (PRIMARY BUG)', () => {
- it('REGRESSION: 2 reactors, one removes → reaction is preserved with count 1', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, FIRE, BOB);
- expect(getRecord(m, FIRE)!.count).toBe(2);
- m = remove(m, FIRE, ALICE);
- const rec = getRecord(m, FIRE);
- expect(rec).toBeDefined();
- expect(rec!.count).toBe(1);
- expect(rec!.knownReactors.has(BOB)).toBe(true);
- expect(rec!.knownReactors.has(ALICE)).toBe(false);
- });
- it('REGRESSION: me + other, other removes → reaction kept, me preserved', () => {
- let m = add(emptyMap(), FIRE, ME);
- m = add(m, FIRE, ALICE);
- m = remove(m, FIRE, ALICE);
- const rec = getRecord(m, FIRE);
- expect(rec!.count).toBe(1);
- expect(rec!.me).toBe(true);
- });
- it('REGRESSION: me + other, me removes → reaction kept with other', () => {
- let m = add(emptyMap(), FIRE, ME);
- m = add(m, FIRE, ALICE);
- m = remove(m, FIRE, ME);
- const rec = getRecord(m, FIRE);
- expect(rec!.count).toBe(1);
- expect(rec!.me).toBe(false);
- });
- it('removes reaction entirely when last reactor leaves', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = remove(m, FIRE, ALICE);
- expect(getRecord(m, FIRE)).toBeUndefined();
- });
- it('idempotent: removing same userId twice does not double-decrement', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, FIRE, BOB);
- m = remove(m, FIRE, ALICE);
- m = remove(m, FIRE, ALICE);
- expect(getRecord(m, FIRE)!.count).toBe(1);
- });
- it('remove on unknown emoji is a no-op', () => {
- const m = remove(emptyMap(), FIRE, ALICE);
- expect(m.size).toBe(0);
- });
- it('remove unknown user when me=false but isCurrentUser=true is no-op', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = remove(m, FIRE, ME, true);
- expect(getRecord(m, FIRE)!.count).toBe(1);
- });
- it('untracked user remove (not in knownReactors but server says they left)', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = hydrate(m, [{emoji: FIRE, count: 5}]);
- expect(getRecord(m, FIRE)!.count).toBe(5);
- m = remove(m, FIRE, CAROL);
- expect(getRecord(m, FIRE)!.count).toBe(4);
- });
- it('me=true server hydration + me removes drops me flag and count', () => {
- let m = hydrate(emptyMap(), [{emoji: FIRE, count: 3, me: true}]);
- expect(getRecord(m, FIRE)!.me).toBe(true);
- m = remove(m, FIRE, ME);
- expect(getRecord(m, FIRE)!.count).toBe(2);
- expect(getRecord(m, FIRE)!.me).toBe(false);
- });
- it('count cannot go below zero', () => {
- let m = hydrate(emptyMap(), [{emoji: FIRE, count: 1}]);
- m = remove(m, FIRE, ALICE);
- m = remove(m, FIRE, BOB);
- expect(getRecord(m, FIRE)).toBeUndefined();
- });
-});
-
-describe('ReactionStateMachine: hydrate', () => {
- it('replaces existing reactions but preserves knownReactors', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, FIRE, BOB);
- m = hydrate(m, [{emoji: FIRE, count: 10}]);
- expect(getRecord(m, FIRE)!.count).toBe(10);
- expect(getRecord(m, FIRE)!.knownReactors.size).toBe(2);
- });
- it('hydrate with smaller server count never drops below known reactor count', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, FIRE, BOB);
- m = add(m, FIRE, CAROL);
- m = hydrate(m, [{emoji: FIRE, count: 1}]);
- expect(getRecord(m, FIRE)!.count).toBe(3);
- });
- it('hydrate without an emoji drops it from the map', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, HEART, BOB);
- m = hydrate(m, [{emoji: FIRE, count: 1}]);
- expect(getRecord(m, FIRE)).toBeDefined();
- expect(getRecord(m, HEART)).toBeUndefined();
- });
- it('hydrate is identity when nothing changes', () => {
- const m = hydrate(emptyMap(), [{emoji: FIRE, count: 3}]);
- const again = hydrate(m, [{emoji: FIRE, count: 3}]);
- expect(again).toBe(m);
- });
- it('hydrate preserves me flag if server says me=true even if locally false', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = hydrate(m, [{emoji: FIRE, count: 1, me: true}]);
- expect(getRecord(m, FIRE)!.me).toBe(true);
- });
- it('hydrate preserves locally-known me=true even if server omits it', () => {
- let m = add(emptyMap(), FIRE, ME);
- m = hydrate(m, [{emoji: FIRE, count: 5}]);
- expect(getRecord(m, FIRE)!.me).toBe(true);
- });
- it('REGRESSION: stale hydrate does not resurrect a removed current-user reaction', () => {
- let m = hydrate(emptyMap(), [{emoji: FIRE, count: 1, me: true}], ME);
- m = add(m, FIRE, BOB, false);
- m = remove(m, FIRE, ME, true);
- expect(getRecord(m, FIRE)!.count).toBe(1);
- expect(getRecord(m, FIRE)!.me).toBe(false);
- m = hydrate(m, [{emoji: FIRE, count: 2, me: true}], ME);
- expect(getRecord(m, FIRE)!.count).toBe(1);
- expect(getRecord(m, FIRE)!.me).toBe(false);
- expect(getRecord(m, FIRE)!.knownReactors.has(BOB)).toBe(true);
- });
- it('REGRESSION: stale hydrate does not re-count a removed remote reactor', () => {
- let m = add(emptyMap(), FIRE, ALICE);
- m = add(m, FIRE, BOB);
- m = remove(m, FIRE, ALICE);
- m = hydrate(m, [{emoji: FIRE, count: 2}], ME);
- expect(getRecord(m, FIRE)!.count).toBe(1);
- expect(getRecord(m, FIRE)!.knownReactors.has(BOB)).toBe(true);
- expect(getRecord(m, FIRE)!.knownReactors.has(ALICE)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessagePaginationUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessagePaginationUtils.test.ts
deleted file mode 100644
index 34f09a076..000000000
--- a/fluxer_app/src/features/messaging/utils/MessagePaginationUtils.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {calculateAroundPaginationState, mergeAscendingById} from '@app/features/messaging/utils/MessagePaginationUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('MessagePaginationUtils', () => {
- it('keeps newer pagination open when an oldest-edge around response fills the newer side', () => {
- const state = calculateAroundPaginationState({
- limit: 50,
- messageCount: 26,
- targetIndex: 25,
- newestFetchedMessageId: '26',
- knownLatestMessageId: '100',
- });
- expect(state).toMatchObject({
- expectedNewer: 25,
- expectedOlder: 24,
- messagesNewer: 25,
- messagesOlder: 0,
- hasMoreBefore: false,
- hasMoreAfter: true,
- });
- });
-
- it('closes newer pagination when the fetched page reaches the known latest message', () => {
- const state = calculateAroundPaginationState({
- limit: 50,
- messageCount: 25,
- targetIndex: 0,
- newestFetchedMessageId: '100',
- knownLatestMessageId: '100',
- });
- expect(state.hasMoreBefore).toBe(true);
- expect(state.hasMoreAfter).toBe(false);
- });
-});
-
-describe('mergeAscendingById', () => {
- const ID = {a: '1519773906704011264', b: '1519773906708205568', c: '1519773906712399872'};
-
- it('interleaves a recovered message that is older than a live message already at the tail', () => {
- expect(mergeAscendingById([{id: ID.a}, {id: ID.c}], [{id: ID.b}])).toEqual([{id: ID.a}, {id: ID.b}, {id: ID.c}]);
- });
-
- it('keeps the whole page in order when it spans a live message already at the tail', () => {
- expect(mergeAscendingById([{id: ID.a}, {id: ID.b}], [{id: ID.c}])).toEqual([{id: ID.a}, {id: ID.b}, {id: ID.c}]);
- expect(mergeAscendingById([{id: ID.b}], [{id: ID.a}, {id: ID.c}])).toEqual([{id: ID.a}, {id: ID.b}, {id: ID.c}]);
- });
-});
diff --git a/fluxer_app/src/features/threads/state/ChannelThreads.test.ts b/fluxer_app/src/features/threads/state/ChannelThreads.test.ts
deleted file mode 100644
index 3c348df5a..000000000
--- a/fluxer_app/src/features/threads/state/ChannelThreads.test.ts
+++ /dev/null
@@ -1,599 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Channel, type ChannelWire} from '@app/features/channel/models/Channel';
-import {ChannelTypes, MessageTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
-import {observable, runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const channelStore = new Map<string, Channel>();
-const viewable = new Set<string>();
-const moderatorParents = new Set<string>();
-const navigation = observable({
- guildId: null as string | null,
- channelId: null as string | null,
- threadId: null as string | null,
-});
-const selectedGuild = observable({selectedGuildId: null as string | null});
-const updateGuildSubscriptions = vi.fn();
-const gateway = observable({isReady: false, socket: {isConnected: () => true, updateGuildSubscriptions}});
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getUser: () => undefined, cacheUsers: () => {}, getCurrentUser: () => ({id: 'me', mfaEnabled: true})},
-}));
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/app/Routes', () => ({
- Routes: {guildChannel: (guildId: string, channelId?: string) => `/channels/${guildId}/${channelId ?? ''}`},
-}));
-vi.mock('@app/features/channel/events/ChannelDelete', () => ({
- cleanupChannelLocalState: vi.fn((channel: {id: string}) => channelStore.delete(channel.id)),
-}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {
- getChannel: (id: string) => channelStore.get(id),
- upsertThread: (wire: ChannelWire) => channelStore.set(wire.id, new Channel(wire)),
- removeThread: (id: string) => channelStore.delete(id),
- handleChannelCreate: ({channel}: {channel: Channel | ChannelWire}) =>
- channelStore.set(channel.id, channel instanceof Channel ? channel : new Channel(channel)),
- getGuildChannels: (guildId: string) =>
- [...channelStore.values()].filter((channel) => channel.guildId === guildId && !channel.isThread()),
- },
-}));
-vi.mock('@app/features/guild/state/GuildReadState', () => ({default: {handleGenericUpdate: vi.fn()}}));
-vi.mock('@app/features/read_state/state/ReadStates', () => ({default: {handleChannelCreate: vi.fn()}}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {handleCleanup: vi.fn(), handleGuildThreadsPurged: vi.fn()},
-}));
-vi.mock('@app/features/ui/commands/ContextMenuCommands', () => ({close: vi.fn()}));
-vi.mock('@app/features/ui/commands/PopoutCommands', () => ({closeAll: vi.fn()}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: () => ({ownerId: 'owner', mfaLevel: 0})}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({
- default: {getMember: () => null, hydrateOrRefresh: () => {}},
-}));
-vi.mock('@app/features/permissions/state/Permission', () => ({
- default: {
- can: (_permission: bigint, channel: {id: string}) => viewable.has(channel.id),
- getChannelPermissions: (id: string) => {
- if (!viewable.has(id)) return 0n;
- const base = Permissions.VIEW_CHANNEL | Permissions.READ_MESSAGE_HISTORY | Permissions.SEND_MESSAGES;
- return moderatorParents.has(id) ? base | ThreadPermissionFlags.MANAGE_THREADS : base;
- },
- handleChannelUpdate: vi.fn(),
- },
-}));
-vi.mock('@app/features/navigation/state/Navigation', () => ({default: navigation}));
-vi.mock('@app/features/navigation/state/SelectedGuild', () => ({default: selectedGuild}));
-vi.mock('@app/features/navigation/utils/RouterUtils', () => ({replaceWith: vi.fn(), transitionTo: vi.fn()}));
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({default: {foregroundConnection: gateway}}));
-vi.mock('@app/features/user/utils/DateFormatting', () => ({getFormattedFullDate: () => ''}));
-vi.mock('@app/features/moderation/state/LocalUserSpamOverride', () => ({
- default: {isUserMarkedAsSpammer: () => false},
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), delete: vi.fn()},
-}));
-
-const {default: ChannelThreads} = await import('@app/features/threads/state/ChannelThreads');
-const {default: ThreadGuilds} = await import('@app/features/threads/state/ThreadGuilds');
-const {default: ThreadMemberships} = await import('@app/features/threads/state/ThreadMemberships');
-const {default: ThreadRoster} = await import('@app/features/threads/state/ThreadRoster');
-const {default: ThreadSubscriptions} = await import('@app/features/threads/state/ThreadSubscriptions');
-const {isSyncExcludedChannelId} = await import('@app/features/threads/utils/SyncedPreferenceGuard');
-const {cleanupChannelLocalState} = await import('@app/features/channel/events/ChannelDelete');
-const RouterUtils = await import('@app/features/navigation/utils/RouterUtils');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-
-const GUILD = '1500000000000000000';
-const PARENT = '1500000000000000001';
-const OTHER_PARENT = '1500000000000000002';
-const FORUM = '1500000000000000003';
-const THREAD_A = '1500000000000000010';
-const THREAD_B = '1500000000000000011';
-const PRIVATE_THREAD = '1500000000000000012';
-const MEMBER = {join_timestamp: '2026-09-28T00:00:00.000Z', flags: 0};
-
-function metadata(overrides: Partial<{archived: boolean; locked: boolean}> = {}) {
- return {
- archived: false,
- locked: false,
- auto_archive_duration: 4320,
- archive_timestamp: '2026-09-28T00:00:00.000Z',
- create_timestamp: '2026-09-28T00:00:00.000Z',
- ...overrides,
- };
-}
-
-function thread(id: string, overrides: Partial<ChannelWire> = {}): ChannelWire {
- return {
- id,
- guild_id: GUILD,
- parent_id: PARENT,
- type: ChannelTypes.PUBLIC_THREAD,
- name: `thread-${id}`,
- last_message_id: id,
- thread_metadata: metadata(),
- message_count: 0,
- total_message_sent: 0,
- ...overrides,
- };
-}
-
-function seedParents(): void {
- channelStore.set(PARENT, new Channel({id: PARENT, guild_id: GUILD, type: ChannelTypes.GUILD_TEXT, name: 'general'}));
- channelStore.set(OTHER_PARENT, new Channel({id: OTHER_PARENT, guild_id: GUILD, type: ChannelTypes.GUILD_TEXT}));
- channelStore.set(FORUM, new Channel({id: FORUM, guild_id: GUILD, type: ChannelTypes.GUILD_FORUM, name: 'forum'}));
- viewable.add(PARENT);
- viewable.add(OTHER_PARENT);
- viewable.add(FORUM);
-}
-
-function guildObject(threads?: Array<ChannelWire>) {
- return {
- id: GUILD,
- properties: {},
- channels: [],
- emojis: [],
- members: [],
- member_count: 0,
- roles: [],
- joined_at: '2026-09-28T00:00:00.000Z',
- ...(threads ? {threads} : {}),
- } as unknown as Parameters<typeof ThreadGuilds.handleGuild>[0];
-}
-
-beforeEach(() => {
- channelStore.clear();
- viewable.clear();
- moderatorParents.clear();
- ChannelThreads.handleGatewayReady([]);
- ThreadGuilds.reset();
- runInAction(() => {
- navigation.guildId = null;
- navigation.channelId = null;
- navigation.threadId = null;
- selectedGuild.selectedGuildId = null;
- gateway.isReady = false;
- });
- updateGuildSubscriptions.mockClear();
- vi.mocked(cleanupChannelLocalState).mockClear();
- vi.mocked(RouterUtils.replaceWith).mockClear();
- seedParents();
-});
-
-afterEach(() => {
- vi.mocked(http.delete).mockClear();
-});
-
-describe('ChannelThreads ingest and upsert', () => {
- beforeEach(() => {
- ThreadGuilds.handleGuild(guildObject([]));
- });
-
- it('indexes READY threads by parent and records the viewer membership', () => {
- ChannelThreads.handleGatewayReady([
- {id: GUILD, threads: [thread(THREAD_A, {member: MEMBER}), thread(THREAD_B, {parent_id: OTHER_PARENT})]},
- ]);
- expect(ChannelThreads.getThreadIdsForParent(PARENT)).toEqual([THREAD_A]);
- expect(ChannelThreads.getThreadIdsForParent(OTHER_PARENT)).toEqual([THREAD_B]);
- expect(ChannelThreads.getGuildThreadIds(GUILD)).toEqual([THREAD_A, THREAD_B]);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(true);
- expect(ThreadMemberships.isMember(THREAD_B)).toBe(false);
- expect(channelStore.get(THREAD_A)?.isThread()).toBe(true);
- });
-
- it('never walks the last message id back on an update', () => {
- ChannelThreads.upsert(thread(THREAD_A, {last_message_id: '1500000000000000099'}));
- ChannelThreads.upsert(thread(THREAD_A, {last_message_id: '1500000000000000050', name: 'renamed'}));
- expect(channelStore.get(THREAD_A)?.lastMessageId).toBe('1500000000000000099');
- expect(channelStore.get(THREAD_A)?.name).toBe('renamed');
- });
-
- it('keeps archived threads out of the active and sidebar lists unless open', () => {
- ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}));
- ChannelThreads.upsert(thread(THREAD_A, {thread_metadata: metadata({archived: true})}));
- expect(ChannelThreads.getThreadsForParent(PARENT).map((entry) => entry.id)).toEqual([THREAD_A]);
- expect(ChannelThreads.getActiveThreadsForParent(PARENT)).toEqual([]);
- expect(ChannelThreads.getSidebarThreads(PARENT, null)).toEqual([]);
- expect(ChannelThreads.getSidebarThreads(PARENT, THREAD_A).map((entry) => entry.id)).toEqual([THREAD_A]);
- });
-
- it('filters every getter on parent VIEW_CHANNEL', () => {
- ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}));
- viewable.delete(PARENT);
- expect(ChannelThreads.getThread(THREAD_A)).toBeUndefined();
- expect(ChannelThreads.getThreadsForParent(PARENT)).toEqual([]);
- expect(ChannelThreads.getGuildThreads(GUILD)).toEqual([]);
- expect(ChannelThreads.getSidebarThreads(PARENT, THREAD_A)).toEqual([]);
- });
-
- it('shows private threads only to members and thread moderators', () => {
- ChannelThreads.upsert(thread(PRIVATE_THREAD, {type: ChannelTypes.PRIVATE_THREAD}));
- expect(ChannelThreads.getThread(PRIVATE_THREAD)).toBeUndefined();
- moderatorParents.add(PARENT);
- expect(ChannelThreads.getThread(PRIVATE_THREAD)?.id).toBe(PRIVATE_THREAD);
- moderatorParents.delete(PARENT);
- ChannelThreads.upsert(thread(PRIVATE_THREAD, {type: ChannelTypes.PRIVATE_THREAD, member: MEMBER}));
- expect(ChannelThreads.getThread(PRIVATE_THREAD)?.id).toBe(PRIVATE_THREAD);
- });
-
- it('ingests the thread attached to a loaded source message', () => {
- ChannelThreads.ingestMessageThreads([
- {
- id: THREAD_A,
- channel_id: PARENT,
- type: MessageTypes.DEFAULT,
- thread: thread(THREAD_A),
- } as unknown as Parameters<typeof ChannelThreads.ingestMessageThreads>[0][number],
- ]);
- expect(ChannelThreads.getThread(THREAD_A)?.parentId).toBe(PARENT);
- });
-});
-
-describe('ChannelThreads cascades', () => {
- beforeEach(() => {
- ThreadGuilds.handleGuild(guildObject([]));
- });
-
- it('cleans up every thread of a deleted parent', () => {
- ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}));
- ChannelThreads.upsert(thread(THREAD_B));
- ChannelThreads.handleParentDelete(PARENT);
- expect(
- vi
- .mocked(cleanupChannelLocalState)
- .mock.calls.map(([channel]) => channel.id)
- .sort(),
- ).toEqual([THREAD_A, THREAD_B]);
- expect(ChannelThreads.getThreadIdsForParent(PARENT)).toEqual([]);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(false);
- });
-
- it('drops a deleted thread and its membership', () => {
- ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}));
- ChannelThreads.handleThreadDelete({id: THREAD_A, guild_id: GUILD, parent_id: PARENT, type: 11});
- expect(ChannelThreads.hasThread(THREAD_A)).toBe(false);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(false);
- expect(channelStore.has(THREAD_A)).toBe(false);
- });
-
- it('returns a full view of a deleted thread to its parent before the generic fallback', () => {
- ChannelThreads.upsert(thread(THREAD_A));
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = THREAD_A;
- });
- const replaceWith = vi.mocked(RouterUtils.replaceWith);
- const cleanup = vi.mocked(cleanupChannelLocalState);
- ChannelThreads.handleThreadDelete({id: THREAD_A, guild_id: GUILD, parent_id: PARENT, type: 11});
- expect(replaceWith).toHaveBeenCalledWith(`/channels/${GUILD}/${PARENT}`);
- expect(replaceWith.mock.invocationCallOrder[0]).toBeLessThan(cleanup.mock.invocationCallOrder[0]);
- });
-
- it('removes stale active threads only for the synced parents', () => {
- ChannelThreads.upsert(thread(THREAD_A));
- ChannelThreads.upsert(thread(THREAD_B, {parent_id: OTHER_PARENT}));
- ChannelThreads.handleListSync(
- {guild_id: GUILD, channel_ids: [PARENT], threads: [], members: []},
- new Set<string>(),
- );
- expect(ChannelThreads.hasThread(THREAD_A)).toBe(false);
- expect(ChannelThreads.hasThread(THREAD_B)).toBe(true);
- });
-
- it('drops stale memberships on a guild resync but keeps the threads', () => {
- ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}));
- ChannelThreads.upsert(thread(THREAD_B, {member: MEMBER, thread_metadata: metadata({archived: true})}));
- ChannelThreads.ingestGuildThreads(GUILD, []);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(false);
- expect(ThreadMemberships.isMember(THREAD_B)).toBe(true);
- expect(ChannelThreads.hasThread(THREAD_A)).toBe(true);
- });
-
- it('keeps the thread that is open in a view through a list sync', () => {
- ChannelThreads.upsert(thread(THREAD_A));
- ChannelThreads.handleListSync({guild_id: GUILD, threads: [], members: []}, new Set([THREAD_A]));
- expect(ChannelThreads.hasThread(THREAD_A)).toBe(true);
- });
-});
-
-describe('ThreadGuilds flip', () => {
- it('activates from the threads key and purges on the kill', () => {
- ThreadGuilds.handleGuild(guildObject([thread(THREAD_A, {member: MEMBER})]));
- ChannelThreads.ingestGuildThreads(GUILD, [thread(THREAD_A, {member: MEMBER})]);
- expect(ThreadGuilds.isActive(GUILD)).toBe(true);
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = PARENT;
- navigation.threadId = THREAD_A;
- });
- ThreadGuilds.handleGuild(guildObject());
- expect(ThreadGuilds.isActive(GUILD)).toBe(false);
- const cleaned = vi.mocked(cleanupChannelLocalState).mock.calls.map(([channel]) => channel.id);
- expect(cleaned).toContain(THREAD_A);
- expect(cleaned).toContain(FORUM);
- expect(cleaned).not.toContain(PARENT);
- expect(ChannelThreads.getGuildThreadIds(GUILD)).toEqual([]);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(false);
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenCalledWith(`/channels/${GUILD}/${PARENT}`);
- expect(ThreadGuilds.isPurgedEvent({channel_id: THREAD_A})).toBe(true);
- expect(ThreadGuilds.isPurgedEvent({channel_id: PARENT})).toBe(false);
- expect(vi.mocked(http.delete)).not.toHaveBeenCalled();
- ThreadGuilds.handleGuild(guildObject([]));
- expect(ThreadGuilds.isPurgedEvent({channel_id: THREAD_A})).toBe(false);
- });
-
- it('routes a forum post panel to the guild root on the kill', () => {
- const post = thread(THREAD_B, {parent_id: FORUM, member: MEMBER});
- ThreadGuilds.handleGuild(guildObject([post]));
- ChannelThreads.ingestGuildThreads(GUILD, [post]);
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = FORUM;
- navigation.threadId = THREAD_B;
- });
- ThreadGuilds.handleGuild(guildObject());
- expect(vi.mocked(cleanupChannelLocalState).mock.calls.map(([channel]) => channel.id)).toContain(FORUM);
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenLastCalledWith(`/channels/${GUILD}/`);
- });
-
- it('routes a full view forum post to the guild root on the kill', () => {
- const post = thread(THREAD_B, {parent_id: FORUM, member: MEMBER});
- ThreadGuilds.handleGuild(guildObject([post]));
- ChannelThreads.ingestGuildThreads(GUILD, [post]);
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = THREAD_B;
- });
- ThreadGuilds.handleGuild(guildObject());
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenLastCalledWith(`/channels/${GUILD}/`);
- });
-
- it('routes a full view text thread to its parent on the kill', () => {
- const child = thread(THREAD_A, {member: MEMBER});
- ThreadGuilds.handleGuild(guildObject([child]));
- ChannelThreads.ingestGuildThreads(GUILD, [child]);
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = THREAD_A;
- });
- ThreadGuilds.handleGuild(guildObject());
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenLastCalledWith(`/channels/${GUILD}/${PARENT}`);
- });
-
- it('routes a thread view to the guild root when a new READY drops its forum', () => {
- runInAction(() => {
- navigation.guildId = GUILD;
- navigation.channelId = FORUM;
- navigation.threadId = THREAD_B;
- });
- const forum = {id: FORUM, guild_id: GUILD, type: ChannelTypes.GUILD_FORUM};
- ThreadGuilds.handleGatewayReady([{...guildObject(), channels: [forum]}]);
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenLastCalledWith(`/channels/${GUILD}/`);
- const parent = {id: PARENT, guild_id: GUILD, type: ChannelTypes.GUILD_TEXT};
- runInAction(() => {
- navigation.channelId = PARENT;
- });
- ThreadGuilds.handleGatewayReady([{...guildObject(), channels: [parent]}]);
- expect(vi.mocked(RouterUtils.replaceWith)).toHaveBeenLastCalledWith(`/channels/${GUILD}/${PARENT}`);
- });
-
- it('purges a guild that is missing from a new READY', () => {
- ThreadGuilds.handleGuild(guildObject([thread(THREAD_A, {member: MEMBER})]));
- ChannelThreads.ingestGuildThreads(GUILD, [thread(THREAD_A, {member: MEMBER})]);
- ThreadGuilds.handleGatewayReady([]);
- expect(ThreadGuilds.isActive(GUILD)).toBe(false);
- const cleaned = vi.mocked(cleanupChannelLocalState).mock.calls.map(([channel]) => channel.id);
- expect(cleaned).toContain(FORUM);
- expect(ThreadGuilds.isPurgedEvent({channel_id: THREAD_A})).toBe(true);
- });
-
- it('ignores unavailable guild stubs and deletes for the gate', () => {
- ThreadGuilds.handleGuild(guildObject([]));
- ThreadGuilds.handleGatewayReady([
- {id: GUILD, unavailable: true} as unknown as Parameters<typeof ThreadGuilds.handleGuild>[0],
- ]);
- ThreadGuilds.handleGuildDelete(GUILD, true);
- expect(ThreadGuilds.isActive(GUILD)).toBe(true);
- ThreadGuilds.handleGuildDelete(GUILD, false);
- expect(ThreadGuilds.isActive(GUILD)).toBe(false);
- });
-});
-
-describe('control arm', () => {
- it('stays inert for guilds without the threads key', async () => {
- ThreadGuilds.handleGatewayReady([guildObject()]);
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- await Promise.resolve();
- expect(ThreadGuilds.anyActive).toBe(false);
- expect(ThreadGuilds.isPurgedEvent({channel_id: PARENT})).toBe(false);
- expect(updateGuildSubscriptions).not.toHaveBeenCalled();
- expect(vi.mocked(http.get)).not.toHaveBeenCalled();
- expect(vi.mocked(http.post)).not.toHaveBeenCalled();
- ThreadGuilds.handleGuild(guildObject([]));
- await Promise.resolve();
- expect(updateGuildSubscriptions).toHaveBeenCalledWith({
- subscriptions: {[GUILD]: {threads: true, thread_member_lists: []}},
- });
- });
-
- it('sends thread member lists only for subscribed threads of the active guild', async () => {
- ThreadGuilds.handleGuild(guildObject([]));
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- const release = ThreadRoster.subscribe(GUILD, THREAD_A);
- await Promise.resolve();
- expect(updateGuildSubscriptions).toHaveBeenLastCalledWith({
- subscriptions: {[GUILD]: {threads: true, thread_member_lists: [THREAD_A]}},
- });
- release();
- await Promise.resolve();
- });
-
- it('switches thread member lists in a single request', async () => {
- ThreadGuilds.handleGuild(guildObject([]));
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- const releaseA = ThreadRoster.subscribe(GUILD, THREAD_A);
- await Promise.resolve();
- updateGuildSubscriptions.mockClear();
- releaseA();
- const releaseB = ThreadRoster.subscribe(GUILD, THREAD_B);
- await Promise.resolve();
- expect(updateGuildSubscriptions).toHaveBeenCalledTimes(1);
- expect(updateGuildSubscriptions).toHaveBeenCalledWith({
- subscriptions: {[GUILD]: {threads: true, thread_member_lists: [THREAD_B]}},
- });
- releaseB();
- await Promise.resolve();
- });
-
- it('clears the previous guild thread member lists when the selected guild changes', async () => {
- const otherGuild = '1500000000000000099';
- ThreadGuilds.handleGuild(guildObject([]));
- ThreadGuilds.handleGuild({...guildObject([]), id: otherGuild});
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- const release = ThreadRoster.subscribe(GUILD, THREAD_A);
- await Promise.resolve();
- updateGuildSubscriptions.mockClear();
- runInAction(() => {
- selectedGuild.selectedGuildId = otherGuild;
- });
- await Promise.resolve();
- expect(updateGuildSubscriptions).toHaveBeenCalledWith({
- subscriptions: {
- [GUILD]: {thread_member_lists: []},
- [otherGuild]: {threads: true, thread_member_lists: []},
- },
- });
- release();
- await Promise.resolve();
- });
-
- it('serializes a control channel without any new keys', () => {
- const wire = {
- id: PARENT,
- guild_id: GUILD,
- type: ChannelTypes.GUILD_TEXT,
- name: 'general',
- topic: null,
- position: 1,
- parent_id: null,
- last_message_id: null,
- permission_overwrites: [],
- nsfw: false,
- rate_limit_per_user: 0,
- };
- const keys = Object.keys(new Channel(wire).toJSON()).sort();
- expect(keys).toEqual(
- [
- 'bitrate',
- 'content_warning_level',
- 'content_warning_text',
- 'guild_id',
- 'icon',
- 'id',
- 'last_message_id',
- 'last_pin_timestamp',
- 'name',
- 'nicks',
- 'nsfw',
- 'nsfw_override',
- 'owner_id',
- 'parent_id',
- 'permission_overwrites',
- 'position',
- 'rate_limit_per_user',
- 'recipients',
- 'rtc_p2p',
- 'rtc_region',
- 'topic',
- 'type',
- 'url',
- 'user_limit',
- 'voice_connection_limit',
- ].sort(),
- );
- expect(new Channel(wire).threadFields).toBeNull();
- });
-
- it('refuses a thread for a guild that is not active', () => {
- expect(ChannelThreads.upsert(thread(THREAD_A, {member: MEMBER}))).toBeUndefined();
- expect(channelStore.has(THREAD_A)).toBe(false);
- expect(ChannelThreads.hasThread(THREAD_A)).toBe(false);
- expect(ThreadMemberships.isMember(THREAD_A)).toBe(false);
- });
-
- it('sends no thread keys on a new connection until READY was ingested', () => {
- ThreadGuilds.handleGuild(guildObject([]));
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- expect(updateGuildSubscriptions).not.toHaveBeenCalled();
- ThreadGuilds.handleGatewayReady([guildObject()]);
- ThreadSubscriptions.handleConnectionReady();
- expect(updateGuildSubscriptions).not.toHaveBeenCalled();
- });
-
- it('refuses thread and forum ids for synced preferences only', () => {
- ThreadGuilds.handleGuild(guildObject([]));
- ChannelThreads.upsert(thread(THREAD_A));
- expect(isSyncExcludedChannelId(THREAD_A)).toBe(true);
- expect(isSyncExcludedChannelId(FORUM)).toBe(true);
- expect(isSyncExcludedChannelId(PARENT)).toBe(false);
- expect(isSyncExcludedChannelId('1500000000000000999')).toBe(false);
- });
-
- it('clears the previous guild thread member lists after a guild switch during a reconnect', async () => {
- const otherGuild = '1500000000000000099';
- ThreadGuilds.handleGuild(guildObject([]));
- ThreadGuilds.handleGuild({...guildObject([]), id: otherGuild});
- runInAction(() => {
- selectedGuild.selectedGuildId = GUILD;
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- const release = ThreadRoster.subscribe(GUILD, THREAD_A);
- await Promise.resolve();
- runInAction(() => {
- gateway.isReady = false;
- });
- release();
- runInAction(() => {
- selectedGuild.selectedGuildId = otherGuild;
- });
- await Promise.resolve();
- updateGuildSubscriptions.mockClear();
- runInAction(() => {
- gateway.isReady = true;
- });
- ThreadSubscriptions.handleConnectionReady();
- await Promise.resolve();
- expect(updateGuildSubscriptions).toHaveBeenCalledTimes(1);
- expect(updateGuildSubscriptions).toHaveBeenCalledWith({
- subscriptions: {
- [GUILD]: {thread_member_lists: []},
- [otherGuild]: {threads: true, thread_member_lists: []},
- },
- });
- });
-});