Skip to content

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

TypeScript fluxerfluxerapp

test(app): drop mock-heavy gateway, read state and config tests

Hampus8df9287b1aed
diff --git a/fluxer_app/src/features/app/state/InstanceSnapshotStore.test.ts b/fluxer_app/src/features/app/state/InstanceSnapshotStore.test.ts
deleted file mode 100644
index ba9a1764e..000000000
--- a/fluxer_app/src/features/app/state/InstanceSnapshotStore.test.ts
+++ /dev/null
@@ -1,735 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import Config from '@app/features/app/config/Config';
-import InstanceSnapshotStore, {
- type RuntimeConfigSnapshot,
- resolveDiscoveryApiEndpoint,
- runtimeConfigSnapshotsAreSameInstance,
- runtimeInstanceKey,
- runtimeSnapshotFromDiscovery,
- storedInstanceKey,
-} from '@app/features/app/state/InstanceSnapshotStore';
-import {requireRuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfigSnapshot';
-import {BOOTSTRAP_APP_PUBLIC} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import {
- type InstanceDiscoveryDocument,
- InstanceDiscoveryUnreachableError,
- parseInstanceDiscoveryDocument,
-} from '@fluxer/instance_bootstrap/src/Discovery';
-import {
- OFFICIAL_CLIENT_API_ENDPOINTS,
- type OfficialReleaseChannel,
-} from '@fluxer/instance_bootstrap/src/OfficialInstance';
-import type {InstanceDiscoveryResponse} from '@fluxer/instance_bootstrap/src/Types';
-import {computeWireFormat} from '@fluxer/limits/src/LimitDiffer';
-import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';
-import {InstanceAppPublicSchema} from '@fluxer/schema/src/domains/instance/InstanceSchemas';
-import {runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const EMPTY_LIMITS: LimitConfigSnapshot = {version: 1, traitDefinitions: [], rules: []};
-
-function discoveryDocument(
- host: string,
- overrides: Partial<InstanceDiscoveryResponse> = {},
-): InstanceDiscoveryResponse {
- return {
- api_code_version: 1,
- endpoints: {
- api: `https://${host}/api`,
- api_client: `https://${host}/api`,
- api_public: `https://${host}/api`,
- gateway: `wss://gateway.${host}`,
- media: `https://media.${host}`,
- static_cdn: `https://cdn.${host}`,
- marketing: `https://${host}`,
- admin: `https://admin.${host}`,
- invite: `https://${host}/invite`,
- gift: `https://${host}/gift`,
- webapp: `https://app.${host}`,
- upload_relay: `https://upload.${host}`,
- },
- captcha: {provider: 'none'},
- features: {
- voice_enabled: true,
- stripe_enabled: false,
- self_hosted: true,
- presigned_attachment_uploads: false,
- emails_enabled: false,
- premium_enabled: false,
- stripe_serviceable: false,
- phone_verification_enabled: false,
- },
- gif: {provider: 'tenor', display_name: 'Tenor', attribution_required: true},
- sso: {enabled: false, enforced: false, display_name: null, redirect_uri: `https://${host}/sso`},
- registration: {mode: 'closed', admin_registration_urls_enabled: false},
- community: {
- single_community: false,
- single_community_guild_id: null,
- direct_messages_disabled: false,
- guild_create_access: true,
- },
- services: {gif_enabled: true, youtube_enabled: true, bluesky_enabled: false},
- limits: EMPTY_LIMITS,
- push: {public_vapid_key: 'vapid'},
- app_public: {
- ...BOOTSTRAP_APP_PUBLIC,
- branding: {...BOOTSTRAP_APP_PUBLIC.branding, product_name: `Fluxer ${host}`},
- },
- ...overrides,
- };
-}
-
-function parsedDocument(host: string): InstanceDiscoveryDocument {
- return parseInstanceDiscoveryDocument(discoveryDocument(host));
-}
-
-function jsonResponse(body: unknown): Response {
- return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}});
-}
-
-afterEach(() => {
- vi.unstubAllGlobals();
-});
-
-function runningChannel(): OfficialReleaseChannel {
- return Config.PUBLIC_RELEASE_CHANNEL === 'stable' ? 'stable' : 'canary';
-}
-
-function stubBrowserDocument(origin: string, {servesOwnApi = false}: {servesOwnApi?: boolean} = {}): void {
- const url = new URL(origin);
- vi.stubGlobal('window', {
- location: {origin: url.origin === 'null' ? origin : url.origin, protocol: url.protocol, hostname: url.hostname},
- });
- vi.stubGlobal('document', {
- querySelector: (selector: string) =>
- servesOwnApi && selector === 'meta[name="fluxer-api-origin"][content="self"]' ? {} : null,
- });
-}
-
-describe('runtimeInstanceKey', () => {
- function snapshotWithEndpoint(apiEndpoint: string): RuntimeConfigSnapshot {
- return {...runtimeSnapshotFromDiscovery(parsedDocument('example.test')), apiEndpoint};
- }
-
- test.each([
- ['https://x.com/api', 'https://x.com/api'],
- ['HTTPS://X.com/api/', 'https://x.com/api'],
- ['http://[::1]:8080/api', 'http://[::1]:8080/api'],
- ])('%s derives %s', (endpoint, expected) => {
- expect(runtimeInstanceKey(snapshotWithEndpoint(endpoint))).toBe(expected);
- });
-
- test.each(['https://x.com/api?q=1', 'https://x.com/api#f', 'https://u:[email protected]/api', 'ftp://x.com', '', '/api'])(
- '%s has no instance key',
- (endpoint) => {
- expect(runtimeInstanceKey(snapshotWithEndpoint(endpoint))).toBeNull();
- },
- );
-
- test('same-instance comparison uses the derived key', () => {
- const left = snapshotWithEndpoint('HTTPS://X.com/api/');
- const right = snapshotWithEndpoint('https://x.com/api');
- expect(runtimeConfigSnapshotsAreSameInstance(left, right)).toBe(true);
- expect(runtimeConfigSnapshotsAreSameInstance(undefined, right)).toBe(false);
- expect(runtimeConfigSnapshotsAreSameInstance(snapshotWithEndpoint('https://y.com/api'), right)).toBe(false);
- });
-});
-
-describe('runtime limit snapshots', () => {
- const snapshot: LimitConfigSnapshot = {
- version: 1,
- traitDefinitions: ['premium'],
- rules: [{id: 'premium', filters: {traits: ['premium']}, limits: {max_guilds: 250}}],
- };
-
- test('accepts the deployed expanded format unchanged', () => {
- const document = discoveryDocument('limits-expanded.test', {limits: snapshot});
- expect(runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document)).limits).toEqual(snapshot);
- });
-
- test('expands the version 2 wire format', () => {
- const wire = computeWireFormat(snapshot);
- expect(wire.version).toBe(2);
- expect(wire.defaultsHash).toBeTruthy();
- const document = discoveryDocument('limits-wire.test', {limits: wire});
- expect(
- runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document)).limits.rules[0]?.limits.max_guilds,
- ).toBe(250);
- });
-
- test('rejects a missing or partial config', () => {
- const missing = discoveryDocument('limits-missing.test', {limits: undefined});
- const partial = discoveryDocument('limits-partial.test', {limits: {version: 1} as LimitConfigSnapshot});
- expect(() => runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(missing))).toThrow(/limits/u);
- expect(() => runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(partial))).toThrow(/limits/u);
- });
-
- test('never aliases the caller its input', () => {
- const document = discoveryDocument('limits-clone.test', {limits: snapshot});
- const read = runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document)).limits;
- read.rules[0]!.limits.max_guilds = 1;
- expect(snapshot.rules[0]?.limits.max_guilds).toBe(250);
- });
-});
-
-describe('runtimeSnapshotFromDiscovery', () => {
- test('carries every advertised field through', () => {
- const snapshot = runtimeSnapshotFromDiscovery(parsedDocument('a.test'));
- expect(snapshot.apiEndpoint).toBe('https://a.test/api');
- expect(snapshot.gatewayEndpoint).toBe('wss://gateway.a.test');
- expect(snapshot.mediaEndpoint).toBe('https://media.a.test');
- expect(snapshot.gifProvider).toBe('tenor');
- expect(snapshot.gifAttributionRequired).toBe(true);
- expect(snapshot.publicPushVapidKey).toBe('vapid');
- expect(snapshot.registration?.mode).toBe('closed');
- expect(snapshot.appPublic.branding.product_name).toBe('Fluxer a.test');
- });
-
- test('rejects a document that omits required runtime blocks', () => {
- const document = discoveryDocument('b.test');
- expect(() =>
- runtimeSnapshotFromDiscovery(
- parseInstanceDiscoveryDocument({
- endpoints: document.endpoints,
- features: {self_hosted: true},
- }),
- ),
- ).toThrow(/required by the client runtime/u);
- });
-
- test('rejects a missing client API endpoint', () => {
- const document = discoveryDocument('c.test');
- document.endpoints.api_client = '';
- expect(() => runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document))).toThrow(
- /endpoints\.api_client/u,
- );
- });
-
- test('keeps a cache-busted branding URL the discovery document advertises', () => {
- const document = discoveryDocument('d.test');
- document.app_public = {
- ...BOOTSTRAP_APP_PUBLIC,
- branding: {...BOOTSTRAP_APP_PUBLIC.branding, icon_url: 'https://cdn.d.test/icon.png?v=3'},
- legal: {terms_url: 'https://d.test/legal?doc=terms', privacy_url: null, guidelines_url: null},
- };
- const snapshot = runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document));
- expect(snapshot.appPublic.branding.icon_url).toBe('https://cdn.d.test/icon.png?v=3');
- expect(snapshot.appPublic.legal.terms_url).toBe('https://d.test/legal?doc=terms');
- });
-
- test('keeps every public app field the discovery schema defines', () => {
- const document = discoveryDocument('q.test');
- document.app_public = {
- branding: {
- product_name: 'Fluxer q.test',
- icon_url: 'https://cdn.q.test/icon.png',
- symbol_url: 'https://cdn.q.test/symbol.png',
- logo_url: 'https://cdn.q.test/logo.png',
- wordmark_url: 'https://cdn.q.test/wordmark.png',
- favicon_url: 'https://cdn.q.test/favicon.png',
- theme_color: '#4641d9',
- status_page_url: 'https://status.q.test',
- status_page_incident_history_url: 'https://status.q.test/history',
- premium_product_name: 'Supporter',
- premium_info_url: 'https://q.test/premium',
- },
- setup: {
- configured: false,
- admin_url: 'https://q.test/admin',
- account_identity_locked: true,
- setup_token_required: true,
- },
- legal: {
- terms_url: 'https://q.test/terms',
- privacy_url: 'https://q.test/privacy',
- guidelines_url: 'https://q.test/guidelines',
- },
- registration: {collect_date_of_birth: true},
- };
- const snapshot = runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document));
- expect(snapshot.appPublic).toEqual(document.app_public);
- expect(requireRuntimeConfigSnapshot(JSON.parse(JSON.stringify(snapshot))).appPublic).toEqual(document.app_public);
- for (const section of ['branding', 'setup', 'legal', 'registration'] as const) {
- expect(Object.keys(snapshot.appPublic[section]).sort()).toEqual(
- Object.keys(InstanceAppPublicSchema.shape[section].shape).sort(),
- );
- }
- });
-
- test('rejects a branding URL that is not an absolute HTTP URL', () => {
- const snapshot = runtimeSnapshotFromDiscovery(parsedDocument('e.test'));
- expect(() =>
- requireRuntimeConfigSnapshot({
- ...snapshot,
- appPublic: {
- ...snapshot.appPublic,
- branding: {...snapshot.appPublic.branding, icon_url: 'javascript:alert(1)'},
- },
- }),
- ).toThrow(/appPublic\.branding\.icon_url/u);
- });
-
- test('treats a black or malformed theme colour as unset and normalises the rest', () => {
- const snapshot = runtimeSnapshotFromDiscovery(parsedDocument('t.test'));
- const themeColorOf = (theme_color: unknown) =>
- requireRuntimeConfigSnapshot({
- ...snapshot,
- appPublic: {...snapshot.appPublic, branding: {...snapshot.appPublic.branding, theme_color}},
- }).appPublic.branding.theme_color;
- for (const unset of ['#000000', '#000', '000000', '', 'rgb(1, 2, 3)', 'rebeccapurple', 0, null]) {
- expect(themeColorOf(unset)).toBeNull();
- }
- expect(themeColorOf('#FF0000')).toBe('#ff0000');
- expect(themeColorOf(' f00 ')).toBe('#ff0000');
- expect(themeColorOf('#000001')).toBe('#000001');
- });
-
- test('carries the advertised domain migration', () => {
- const domainMigration = {
- enabled: true,
- anonymous_rollout_basis_points: 2500,
- rollout_salt: 'domain-migration-v1',
- standalone_forwarding: true,
- };
- const snapshot = runtimeSnapshotFromDiscovery(
- parseInstanceDiscoveryDocument(discoveryDocument('m.test', {domain_migration: domainMigration})),
- );
- expect(snapshot.domainMigration).toEqual(domainMigration);
- expect(requireRuntimeConfigSnapshot(JSON.parse(JSON.stringify(snapshot))).domainMigration).toEqual(domainMigration);
- });
-
- test('treats an absent or malformed domain migration as none', () => {
- expect(runtimeSnapshotFromDiscovery(parsedDocument('n.test')).domainMigration).toBeNull();
- const malformed = {
- ...discoveryDocument('o.test'),
- domain_migration: {
- enabled: true,
- anonymous_rollout_basis_points: 10_001,
- rollout_salt: 'salt',
- standalone_forwarding: false,
- },
- };
- expect(runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(malformed)).domainMigration).toBeNull();
- });
-
- test('loads a cached snapshot written before domain migration was carried', () => {
- const {domainMigration: _omitted, ...older} = runtimeSnapshotFromDiscovery(parsedDocument('p.test'));
- expect(requireRuntimeConfigSnapshot(older).domainMigration).toBeNull();
- });
-
- test('rejects an endpoint the instance advertises in an unusable form', () => {
- const document = discoveryDocument('c.test');
- document.endpoints.media = 'not a url';
- expect(() => runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(document))).toThrow(/endpoints\.media/u);
- });
-});
-
-describe('resolveDiscoveryApiEndpoint', () => {
- test.each([
- ['example.test', 'https://example.test'],
- ['https://example.test/api/', 'https://example.test/api'],
- ['http://localhost:8080', 'http://localhost:8080'],
- ])('%s normalises to %s', (input, expected) => {
- expect(resolveDiscoveryApiEndpoint(input)).toBe(expected);
- });
-
- test('maps an official display host onto the client API endpoint for the running channel outside a browser page', () => {
- const expected = OFFICIAL_CLIENT_API_ENDPOINTS[runningChannel()];
- expect(resolveDiscoveryApiEndpoint('fluxer.app')).toBe(expected);
- expect(resolveDiscoveryApiEndpoint('https://web.fluxer.app')).toBe(expected);
- });
-
- test.each(['', '/api', 'https://user:[email protected]', 'ws://example.test'])('rejects %s', (input) => {
- expect(() => resolveDiscoveryApiEndpoint(input)).toThrow();
- });
-
- test.each([
- ['https://web.fluxer.app', 'https://web.fluxer.app/api'],
- ['https://web.canary.fluxer.app', 'https://web.canary.fluxer.app/api'],
- ['https://fluxer.com', 'https://fluxer.com/api'],
- ['https://canary.fluxer.com', 'https://canary.fluxer.com/api'],
- ])('an official page at %s resolves the official instance through its own %s', (origin, expected) => {
- stubBrowserDocument(origin);
- for (const input of [origin, 'fluxer.app', 'https://web.fluxer.app', 'api.fluxer.app', 'fluxer.com']) {
- expect(resolveDiscoveryApiEndpoint(input)).toBe(expected);
- }
- });
-
- test('a page on another origin reaches the official instance through its client API endpoint', () => {
- stubBrowserDocument('https://chat.example.test');
- expect(resolveDiscoveryApiEndpoint('fluxer.app')).toBe(OFFICIAL_CLIENT_API_ENDPOINTS[runningChannel()]);
- expect(resolveDiscoveryApiEndpoint('https://chat.example.test')).toBe('https://chat.example.test');
- expect(resolveDiscoveryApiEndpoint('other.example.test')).toBe('https://other.example.test');
- });
-
- test('a page that serves its own API resolves its origin onto that API', () => {
- stubBrowserDocument('https://chat.example.test', {servesOwnApi: true});
- expect(resolveDiscoveryApiEndpoint('https://chat.example.test')).toBe('https://chat.example.test/api');
- expect(resolveDiscoveryApiEndpoint('https://chat.example.test/v2')).toBe('https://chat.example.test/v2');
- expect(resolveDiscoveryApiEndpoint('other.example.test')).toBe('https://other.example.test');
- });
-
- test('the desktop local app resolves the official instance through the endpoint its discovery declares', () => {
- stubBrowserDocument('fluxer-app://app', {servesOwnApi: true});
- const expected = OFFICIAL_CLIENT_API_ENDPOINTS[runningChannel()];
- expect(resolveDiscoveryApiEndpoint('https://web.fluxer.app')).toBe(expected);
- expect(resolveDiscoveryApiEndpoint('https://fluxer.com')).toBe(expected);
- });
-
- test.each([
- ['https://fluxer.com/api', OFFICIAL_CLIENT_API_ENDPOINTS.stable],
- ['https://canary.fluxer.com/api', OFFICIAL_CLIENT_API_ENDPOINTS.canary],
- ['https://canary.fluxer.com/api/', OFFICIAL_CLIENT_API_ENDPOINTS.canary],
- ['https://web.fluxer.app/api', OFFICIAL_CLIENT_API_ENDPOINTS.stable],
- ['https://web.canary.fluxer.app/api', OFFICIAL_CLIENT_API_ENDPOINTS.canary],
- ])('the desktop local app reaches the account stored at %s through %s', (stored, expected) => {
- stubBrowserDocument('fluxer-app://app', {servesOwnApi: true});
- expect(resolveDiscoveryApiEndpoint(stored)).toBe(expected);
- expect(storedInstanceKey(stored)).toBe(expected);
- });
-
- test('a page on another origin reaches an account stored on the migrated official domain through the official instance', () => {
- stubBrowserDocument('https://chat.example.test', {servesOwnApi: true});
- expect(resolveDiscoveryApiEndpoint('https://fluxer.com/api')).toBe(OFFICIAL_CLIENT_API_ENDPOINTS.stable);
- expect(storedInstanceKey('https://canary.fluxer.com/api')).toBe(OFFICIAL_CLIENT_API_ENDPOINTS.canary);
- expect(storedInstanceKey('https://chat.example.test/api')).toBe('https://chat.example.test/api');
- expect(storedInstanceKey('https://other.example.test/api/')).toBe('https://other.example.test/api');
- });
-
- test.each([
- 'https://fluxer.com',
- 'https://canary.fluxer.com',
- 'https://web.fluxer.app',
- 'https://web.canary.fluxer.app',
- ])('the official page at %s keeps the account it stored on its own same-origin API', (origin) => {
- stubBrowserDocument(origin, {servesOwnApi: true});
- expect(resolveDiscoveryApiEndpoint(`${origin}/api`)).toBe(`${origin}/api`);
- expect(storedInstanceKey(`${origin}/api`)).toBe(`${origin}/api`);
- });
-
- test('an endpoint that names no instance has no stored instance key', () => {
- expect(storedInstanceKey('')).toBeNull();
- expect(storedInstanceKey('https://user:[email protected]/api')).toBeNull();
- });
-});
-
-describe('InstanceSnapshotStore.resolve on an official web page', () => {
- function productionDocument(webOrigin: string): InstanceDiscoveryResponse {
- const document = discoveryDocument(new URL(webOrigin).host);
- return {
- ...document,
- endpoints: {
- ...document.endpoints,
- api: `${webOrigin}/api`,
- api_client: `${webOrigin}/api`,
- api_public: 'https://api.example.test',
- gateway: 'wss://gateway.example.test',
- webapp: webOrigin,
- },
- };
- }
-
- function serveLikeProduction(canonicalWebOrigin: string): ReturnType<typeof vi.fn> {
- return vi.fn(async (url: string) => {
- if (url.endsWith('.fluxer.app/.well-known/fluxer')) {
- return new Response('<!doctype html><html></html>', {
- status: 200,
- headers: {'content-type': 'text/html; charset=utf-8'},
- });
- }
- return jsonResponse(productionDocument(canonicalWebOrigin));
- });
- }
-
- test('the legacy web origin discovers the instance on its own origin and keeps its API same-origin', async () => {
- const canonical = 'https://web.canary.fluxer.app';
- stubBrowserDocument(canonical);
- const fetchMock = serveLikeProduction(canonical);
- vi.stubGlobal('fetch', fetchMock);
- const resolution = await InstanceSnapshotStore.resolve({input: canonical, signal: null});
- expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([
- `${canonical}/.well-known/fluxer`,
- `${canonical}/api/.well-known/fluxer`,
- ]);
- expect(resolution.snapshot.apiEndpoint).toBe(`${canonical}/api`);
- expect(resolution.instanceKey).toBe(`${canonical}/api`);
- });
-
- test('a same-origin host takes over the client API and web app endpoints, as the app-proxy rewrite did', async () => {
- stubBrowserDocument('https://canary.fluxer.com', {servesOwnApi: true});
- const fetchMock = serveLikeProduction('https://web.canary.fluxer.app');
- vi.stubGlobal('fetch', fetchMock);
- const resolution = await InstanceSnapshotStore.resolve({input: 'https://canary.fluxer.com', signal: null});
- expect(fetchMock.mock.calls[0]?.[0]).toBe('https://canary.fluxer.com/.well-known/fluxer');
- expect(resolution.snapshot.apiEndpoint).toBe('https://canary.fluxer.com/api');
- expect(resolution.snapshot.webAppEndpoint).toBe('https://canary.fluxer.com');
- expect(resolution.snapshot.apiPublicEndpoint).toBe('https://api.example.test');
- expect(resolution.snapshot.gatewayEndpoint).toBe('wss://gateway.example.test');
- expect(resolution.instanceKey).toBe('https://canary.fluxer.com/api');
- });
-
- test('a self-hosted alias host that serves its own API adopts its origin', async () => {
- stubBrowserDocument('https://alias.example.test', {servesOwnApi: true});
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(discoveryDocument('canonical.example.test'))),
- );
- const resolution = await InstanceSnapshotStore.resolve({input: 'https://alias.example.test', signal: null});
- expect(resolution.snapshot.apiEndpoint).toBe('https://alias.example.test/api');
- expect(resolution.snapshot.webAppEndpoint).toBe('https://alias.example.test');
- });
-
- test('an alias host also takes over the gateway and media the canonical host serves', async () => {
- stubBrowserDocument('https://gateway-alias.example.test', {servesOwnApi: true});
- const canonical = discoveryDocument('canonical.example.test');
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () =>
- jsonResponse({
- ...canonical,
- endpoints: {
- ...canonical.endpoints,
- gateway: 'wss://canonical.example.test/gateway',
- media: 'https://canonical.example.test/media',
- },
- }),
- ),
- );
- const resolution = await InstanceSnapshotStore.resolve({input: 'https://gateway-alias.example.test', signal: null});
- expect(resolution.snapshot.gatewayEndpoint).toBe('wss://gateway-alias.example.test/gateway');
- expect(resolution.snapshot.mediaEndpoint).toBe('https://gateway-alias.example.test/media');
- expect(resolution.snapshot.staticCdnEndpoint).toBe('https://cdn.canonical.example.test');
- });
-
- test('a host that is not marked as serving its own API still refuses a foreign API declaration', async () => {
- stubBrowserDocument('https://fluxer.com');
- vi.stubGlobal('fetch', serveLikeProduction('https://web.fluxer.app'));
- await expect(InstanceSnapshotStore.resolve({input: 'https://fluxer.com', signal: null})).rejects.toThrow(
- InstanceDiscoveryUnreachableError,
- );
- });
-
- test('a page that serves its own API never adopts the origin of another instance', async () => {
- stubBrowserDocument('https://alias-two.example.test', {servesOwnApi: true});
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(discoveryDocument('elsewhere.example.test'))),
- );
- await expect(InstanceSnapshotStore.resolve({input: 'https://foreign.example.test', signal: null})).rejects.toThrow(
- InstanceDiscoveryUnreachableError,
- );
- });
-
- test('a web user on the migrated domain restores the account stored on its same-origin API', async () => {
- stubBrowserDocument('https://fluxer.com', {servesOwnApi: true});
- const fetchMock = serveLikeProduction('https://web.fluxer.app');
- vi.stubGlobal('fetch', fetchMock);
- const resolution = await InstanceSnapshotStore.resolve({input: 'https://fluxer.com/api', signal: null});
- expect(fetchMock.mock.calls[0]?.[0]).toBe('https://fluxer.com/.well-known/fluxer');
- expect(resolution.snapshot.apiEndpoint).toBe('https://fluxer.com/api');
- expect(resolution.snapshot.webAppEndpoint).toBe('https://fluxer.com');
- expect(resolution.instanceKey).toBe('https://fluxer.com/api');
- expect(resolution.instanceKey).toBe(storedInstanceKey('https://fluxer.com/api'));
- });
-});
-
-describe('InstanceSnapshotStore.resolve', () => {
- test('resolves on the first candidate that answers with JSON', async () => {
- const fetchMock = vi.fn(async () => jsonResponse(discoveryDocument('one.test')));
- vi.stubGlobal('fetch', fetchMock);
- const resolution = await InstanceSnapshotStore.resolve({input: 'one.test', signal: null});
- expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(resolution.instanceKey).toBe('https://one.test/api');
- expect(resolution.productName).toBe('Fluxer one.test');
- expect(resolution.snapshot.gatewayEndpoint).toBe('wss://gateway.one.test');
- expect(InstanceSnapshotStore.get('https://one.test/api')).toBe(resolution.snapshot);
- });
-
- test('skips an SPA HTML body without parsing it and falls through to /api', async () => {
- const fetchMock = vi.fn(async (url: string) => {
- if (url === 'https://two.test/.well-known/fluxer') {
- return new Response('<!doctype html><html></html>', {
- status: 200,
- headers: {'content-type': 'text/html; charset=utf-8'},
- });
- }
- return jsonResponse(discoveryDocument('two.test'));
- });
- vi.stubGlobal('fetch', fetchMock);
- const resolution = await InstanceSnapshotStore.resolve({input: 'https://two.test', signal: null});
- expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([
- 'https://two.test/.well-known/fluxer',
- 'https://two.test/api/.well-known/fluxer',
- ]);
- expect(resolution.instanceKey).toBe('https://two.test/api');
- });
-
- test('sends only a safelisted Accept header cross-origin so no CORS preflight is triggered', async () => {
- const requests: Array<RequestInit> = [];
- vi.stubGlobal(
- 'fetch',
- vi.fn(async (_url: string, init: RequestInit) => {
- requests.push(init);
- return jsonResponse(discoveryDocument('three.test'));
- }),
- );
- await InstanceSnapshotStore.resolve({input: 'three.test', signal: null});
- const init = requests[0];
- expect(init?.headers).toEqual({Accept: 'application/json'});
- expect(init?.credentials).toBe('omit');
- expect(init?.redirect).toBe('error');
- expect(init?.cache).toBe('no-store');
- expect(init?.referrerPolicy).toBe('no-referrer');
- });
-
- test('treats 304 as a not-modified success when the document is cached', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(discoveryDocument('four.test'))),
- );
- const first = await InstanceSnapshotStore.resolve({input: 'four.test', signal: null});
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => new Response(null, {status: 304})),
- );
- const second = await InstanceSnapshotStore.resolve({input: 'four.test', signal: null});
- expect(second.snapshot).toBe(first.snapshot);
- expect(second.instanceKey).toBe('https://four.test/api');
- });
-
- test('reports every candidate when nothing answers', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => new Response('', {status: 404})),
- );
- await expect(InstanceSnapshotStore.resolve({input: 'five.test', signal: null})).rejects.toThrow(
- /five\.test\/\.well-known\/fluxer.*five\.test\/api\/\.well-known\/fluxer/su,
- );
- });
-
- test('rejects a document whose advertised API endpoint is not an http(s) endpoint', async () => {
- const document = discoveryDocument('six.test');
- document.endpoints.api_client = 'ftp://six.test';
- document.endpoints.api = 'ftp://six.test';
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(document)),
- );
- await expect(InstanceSnapshotStore.resolve({input: 'six.test', signal: null})).rejects.toThrow(
- InstanceDiscoveryUnreachableError,
- );
- });
-
- test('deduplicates concurrent resolutions of the same endpoint', async () => {
- const fetchMock = vi.fn(async () => jsonResponse(discoveryDocument('seven.test')));
- vi.stubGlobal('fetch', fetchMock);
- const [left, right] = await Promise.all([
- InstanceSnapshotStore.resolve({input: 'seven.test', signal: null}),
- InstanceSnapshotStore.resolve({input: 'seven.test', signal: null}),
- ]);
- expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(left.snapshot).toBe(right.snapshot);
- });
-
- test('honours an already-aborted signal', async () => {
- const fetchMock = vi.fn(async () => jsonResponse(discoveryDocument('eight.test')));
- vi.stubGlobal('fetch', fetchMock);
- await expect(InstanceSnapshotStore.resolve({input: 'eight.test', signal: AbortSignal.abort()})).rejects.toThrow();
- expect(fetchMock).not.toHaveBeenCalled();
- });
-});
-
-describe('InstanceSnapshotStore limit lookup', () => {
- test('a resolved snapshot answers by its API hostname and a foreign domain stays null', async () => {
- const limits: LimitConfigSnapshot = {
- version: 1,
- traitDefinitions: [],
- rules: [{id: 'base', limits: {max_guilds: 42}}],
- };
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(discoveryDocument('nine.test', {limits}))),
- );
- await InstanceSnapshotStore.resolve({input: 'nine.test', signal: null});
- expect(InstanceSnapshotStore.getLimitsForInstance('nine.test')).toEqual(limits);
- expect(InstanceSnapshotStore.getLimitsForInstance('NINE.TEST')).toEqual(limits);
- expect(InstanceSnapshotStore.getLimitsForInstance('unheard-of.test')).toBeNull();
- expect(InstanceSnapshotStore.getLimitsForInstance('')).toBeNull();
- });
-
- test('a failed discovery never caches a snapshot with no instance key', async () => {
- const document = discoveryDocument('ten.test');
- document.endpoints.api_client = '/api';
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(document)),
- );
- await expect(InstanceSnapshotStore.resolve({input: 'ten.test', signal: null})).rejects.toThrow();
- expect(InstanceSnapshotStore.getLimitsForInstance('ten.test')).toBeNull();
- });
-});
-
-describe('InstanceSnapshotStore.resolve in the desktop local app', () => {
- beforeEach(() => {
- runInAction(() => InstanceSnapshotStore.entries.clear());
- });
-
- function officialDocument(clientOrigin: string): InstanceDiscoveryResponse {
- const document = discoveryDocument(new URL(clientOrigin).host);
- return {
- ...document,
- endpoints: {
- ...document.endpoints,
- api: `${clientOrigin}/api`,
- api_client: `${clientOrigin}/api`,
- webapp: clientOrigin,
- },
- };
- }
-
- function stubDesktopRuntime(served: ReadonlyMap<string, InstanceDiscoveryResponse>): Array<string> {
- const inputs: Array<string> = [];
- stubBrowserDocument('fluxer-app://app', {servesOwnApi: true});
- vi.stubGlobal('window', {
- ...window,
- electron: {
- desktopRuntimeConfig: {
- resolve: async ({input}: {input: string}) => {
- inputs.push(input);
- const document = served.get(input);
- if (document === undefined) {
- throw new Error(`No usable instance discovery document was served for ${input}`);
- }
- return {
- instanceKey: document.endpoints.api_client,
- apiEndpoint: `fluxer-app://app/api/${encodeURIComponent(input)}`,
- remoteApiEndpoint: document.endpoints.api_client,
- document,
- };
- },
- cancelResolution: async () => undefined,
- },
- },
- });
- return inputs;
- }
-
- test.each([
- ['https://canary.fluxer.com', 'https://web.canary.fluxer.app'],
- ['https://fluxer.com', 'https://web.fluxer.app'],
- ])('an account stored on %s resolves and is keyed as the official instance at %s', async (migrated, official) => {
- const inputs = stubDesktopRuntime(new Map([[`${official}/api`, officialDocument(official)]]));
-
- const resolution = await InstanceSnapshotStore.resolve({input: `${migrated}/api`, signal: null});
-
- expect(inputs).toEqual([`${official}/api`]);
- expect(resolution.instanceKey).toBe(`${official}/api`);
- expect(resolution.snapshot.apiEndpoint).toBe(`${official}/api`);
- expect(resolution.snapshot.webAppEndpoint).toBe(official);
- expect(resolution.instanceKey).toBe(storedInstanceKey(`${migrated}/api`));
- const again = await InstanceSnapshotStore.resolve({input: `${official}/api`, signal: null});
- expect(again.snapshot).toBe(resolution.snapshot);
- expect(inputs).toHaveLength(1);
- });
-});
diff --git a/fluxer_app/src/features/app/state/RuntimeConfig.test.ts b/fluxer_app/src/features/app/state/RuntimeConfig.test.ts
deleted file mode 100644
index caeae52f2..000000000
--- a/fluxer_app/src/features/app/state/RuntimeConfig.test.ts
+++ /dev/null
@@ -1,368 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import DesktopRuntimeTransactions from '@app/features/app/state/DesktopRuntimeTransaction';
-import InstanceSnapshotStore, {
- type RuntimeConfigSnapshot,
- runtimeSnapshotFromDiscovery,
-} from '@app/features/app/state/InstanceSnapshotStore';
-import RuntimeConfig, {describeAPIEndpoint} from '@app/features/app/state/RuntimeConfig';
-import {BOOTSTRAP_APP_PUBLIC} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import {http} from '@app/features/platform/transport/RestTransport';
-import {type InstanceDiscoveryDocument, parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
-import type {InstanceDiscoveryResponse} from '@fluxer/instance_bootstrap/src/Types';
-import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';
-import type {MessageDescriptor} from '@lingui/core';
-import {autorun, configure} from 'mobx';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const desktopRuntime = vi.hoisted(() => ({required: false}));
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));
-vi.mock('@app/features/app/state/DesktopRuntimeTransaction', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@app/features/app/state/DesktopRuntimeTransaction')>();
- return {...actual, requiresDesktopRuntimeTransaction: () => desktopRuntime.required};
-});
-
-const EMPTY_LIMITS: LimitConfigSnapshot = {version: 1, traitDefinitions: [], rules: []};
-
-function discoveryDocument(host: string): InstanceDiscoveryResponse {
- return {
- api_code_version: 1,
- endpoints: {
- api: `https://${host}/api`,
- api_client: `https://${host}/api`,
- api_public: `https://${host}/api`,
- gateway: `wss://gateway.${host}`,
- media: `https://media.${host}`,
- static_cdn: `https://cdn.${host}`,
- marketing: `https://${host}`,
- admin: `https://admin.${host}`,
- invite: `https://${host}/invite`,
- gift: `https://${host}/gift`,
- webapp: `https://app.${host}`,
- upload_relay: `https://upload.${host}`,
- },
- captcha: {provider: 'none'},
- features: {
- voice_enabled: false,
- stripe_enabled: false,
- self_hosted: true,
- presigned_attachment_uploads: false,
- emails_enabled: false,
- premium_enabled: false,
- stripe_serviceable: false,
- phone_verification_enabled: false,
- },
- gif: {provider: 'klipy', display_name: 'Klipy', attribution_required: false},
- sso: {enabled: false, enforced: false, display_name: null, redirect_uri: `https://${host}/sso`},
- registration: {mode: 'open', admin_registration_urls_enabled: true},
- community: {
- single_community: false,
- single_community_guild_id: null,
- direct_messages_disabled: false,
- guild_create_access: true,
- },
- services: {gif_enabled: true, youtube_enabled: false, bluesky_enabled: false},
- limits: EMPTY_LIMITS,
- push: {public_vapid_key: null},
- app_public: {
- ...BOOTSTRAP_APP_PUBLIC,
- branding: {...BOOTSTRAP_APP_PUBLIC.branding, product_name: `Fluxer ${host}`},
- },
- };
-}
-
-function parsedDocument(host: string): InstanceDiscoveryDocument {
- return parseInstanceDiscoveryDocument(discoveryDocument(host));
-}
-
-const bootSnapshot: RuntimeConfigSnapshot = runtimeSnapshotFromDiscovery(parsedDocument('boot.test'));
-RuntimeConfig.applySnapshot(bootSnapshot);
-
-beforeEach(() => {
- RuntimeConfig.applySnapshot(bootSnapshot);
-});
-
-afterEach(() => {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- delete (window as {electron?: unknown}).electron;
-});
-
-describe('boot', () => {
- test('applies the initial runtime snapshot', () => {
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- expect(RuntimeConfig.productName).toBe('Fluxer boot.test');
- });
-
- test('keeps the active runtime out of the discovery cache', () => {
- expect(InstanceSnapshotStore.get('https://boot.test/api')).toBeNull();
- expect(InstanceSnapshotStore.getLimitsForInstance('boot.test')).toBeNull();
- });
-});
-
-describe('applySnapshot', () => {
- test("swaps every endpoint to the second instance's", () => {
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parsedDocument('second.test')));
- expect(RuntimeConfig.apiEndpoint).toBe('https://second.test/api');
- expect(RuntimeConfig.gatewayEndpoint).toBe('wss://gateway.second.test');
- expect(RuntimeConfig.mediaEndpoint).toBe('https://media.second.test');
- expect(RuntimeConfig.productName).toBe('Fluxer second.test');
- expect(RuntimeConfig.isSelfHosted()).toBe(true);
- });
-
- test('leaves REST routing to the runtime effects owner', () => {
- const configure = vi.spyOn(http, 'configure');
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parsedDocument('rest.test')));
- expect(configure).not.toHaveBeenCalled();
- });
-
- test('round-trips its own snapshot without losing a field', () => {
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parsedDocument('round.test')));
- const snapshot = RuntimeConfig.getSnapshot();
- RuntimeConfig.applySnapshot(snapshot);
- expect(RuntimeConfig.getSnapshot()).toEqual(snapshot);
- });
-
- test('rejects a record that predates required runtime blocks', () => {
- const legacy = {
- ...runtimeSnapshotFromDiscovery(parsedDocument('legacy.test')),
- registration: undefined,
- community: undefined,
- services: undefined,
- mediaEndpoint: undefined,
- } as unknown as RuntimeConfigSnapshot;
- expect(() => RuntimeConfig.applySnapshot(legacy)).toThrow(/mediaEndpoint/u);
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- });
-
- test('refuses a snapshot with no instance key and leaves the active instance intact', () => {
- const broken = {...runtimeSnapshotFromDiscovery(parsedDocument('broken.test')), apiEndpoint: '/api'};
- expect(() => RuntimeConfig.applySnapshot(broken)).toThrow(/apiEndpoint must be an absolute network endpoint/u);
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- });
-});
-
-describe('discovery', () => {
- test('treats an instance that does not report discovery as enabled', () => {
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parsedDocument('legacy-discovery.test')));
- expect(RuntimeConfig.discoveryEnabled).toBe(true);
- expect(RuntimeConfig.discoveryAvailable).toBe(true);
- });
-
- test('follows an instance that switches discovery off', () => {
- const document = discoveryDocument('no-discovery.test');
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(
- parseInstanceDiscoveryDocument({...document, features: {...document.features, discovery_enabled: false}}),
- ),
- );
- expect(RuntimeConfig.discoveryEnabled).toBe(false);
- expect(RuntimeConfig.discoveryAvailable).toBe(false);
- });
-
- test('keeps discovery unavailable on a single-community instance', () => {
- const document = discoveryDocument('single-community.test');
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(
- parseInstanceDiscoveryDocument({
- ...document,
- community: {...document.community, single_community: true, single_community_guild_id: '1400000000000000001'},
- }),
- ),
- );
- expect(RuntimeConfig.discoveryEnabled).toBe(true);
- expect(RuntimeConfig.discoveryAvailable).toBe(false);
- });
-});
-
-describe('applySnapshotAndWaitForDesktop', () => {
- test('applies immediately when no desktop shell exposes the runtime bridge', async () => {
- await RuntimeConfig.applySnapshotAndWaitForDesktop({
- snapshot: runtimeSnapshotFromDiscovery(parsedDocument('web.test')),
- signal: null,
- });
- expect(RuntimeConfig.apiEndpoint).toBe('https://web.test/api');
- });
-
- test('does not invoke the desktop bridge outside the local app origin', async () => {
- const prepare = vi.fn();
- (window as {electron?: unknown}).electron = {
- desktopRuntimeConfig: {prepare},
- };
- await RuntimeConfig.applySnapshotAndWaitForDesktop({
- snapshot: runtimeSnapshotFromDiscovery(parsedDocument('shell.test')),
- signal: null,
- });
- expect(prepare).not.toHaveBeenCalled();
- expect(RuntimeConfig.apiEndpoint).toBe('https://shell.test/api');
- });
-
- test('honours an aborted signal without touching the active instance', async () => {
- await expect(
- RuntimeConfig.applySnapshotAndWaitForDesktop({
- snapshot: runtimeSnapshotFromDiscovery(parsedDocument('aborted.test')),
- signal: AbortSignal.abort(),
- }),
- ).rejects.toThrow();
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- });
-});
-
-describe('deactivate', () => {
- afterEach(() => {
- configure({disableErrorBoundaries: false});
- desktopRuntime.required = false;
- });
-
- function observeInstanceReads(): {reads: Array<string>; dispose: () => void} {
- const reads: Array<string> = [];
- const dispose = autorun(() => {
- reads.push(
- `${RuntimeConfig.singleCommunityEnabled}:${RuntimeConfig.features.self_hosted}:${RuntimeConfig.getSnapshot().apiEndpoint}`,
- );
- });
- return {reads, dispose};
- }
-
- test('keeps the page instance active on the web', async () => {
- configure({disableErrorBoundaries: true});
- const {reads, dispose} = observeInstanceReads();
-
- await RuntimeConfig.deactivate();
- dispose();
-
- expect(RuntimeConfig.getSnapshotOrNull()?.apiEndpoint).toBe('https://boot.test/api');
- expect(RuntimeConfig.transportApiEndpoint).toBe('https://boot.test/api');
- expect(reads).toEqual(['false:true:https://boot.test/api']);
- });
-
- test('releases the desktop runtime while mounted readers keep the last instance', async () => {
- const nativeDeactivate = vi.spyOn(DesktopRuntimeTransactions, 'deactivate').mockResolvedValue(undefined);
- desktopRuntime.required = true;
- configure({disableErrorBoundaries: true});
- const {reads, dispose} = observeInstanceReads();
-
- await RuntimeConfig.deactivate();
- dispose();
-
- expect(nativeDeactivate).toHaveBeenCalledWith('https://boot.test/api');
- expect(RuntimeConfig.getSnapshotOrNull()).toBeNull();
- expect(() => RuntimeConfig.transportApiEndpoint).toThrow(/No instance runtime is active/u);
- expect(RuntimeConfig.productName).toBe('Fluxer boot.test');
- expect(reads.at(-1)).toBe('false:true:https://boot.test/api');
- });
-
- test('a desktop runtime activated after a release replaces the retained instance', async () => {
- vi.spyOn(DesktopRuntimeTransactions, 'deactivate').mockResolvedValue(undefined);
- desktopRuntime.required = true;
- await RuntimeConfig.deactivate();
- desktopRuntime.required = false;
-
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parsedDocument('next.test')));
-
- expect(RuntimeConfig.getSnapshotOrNull()?.apiEndpoint).toBe('https://next.test/api');
- expect(RuntimeConfig.apiEndpoint).toBe('https://next.test/api');
- });
-});
-
-describe('resolveEndpoint', () => {
- test('resolves a foreign instance through the snapshot store', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(
- async () =>
- new Response(JSON.stringify(discoveryDocument('resolved.test')), {
- status: 200,
- headers: {'content-type': 'application/json'},
- }),
- ),
- );
- const resolution = await RuntimeConfig.resolveEndpoint({input: 'resolved.test', signal: null});
- expect(resolution.instanceKey).toBe('https://resolved.test/api');
- expect(resolution.productName).toBe('Fluxer resolved.test');
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- });
-});
-
-describe('resolveAndPrepareSnapshot', () => {
- function jsonResponse(body: unknown): Response {
- return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}});
- }
-
- test('prepares the stored snapshot when instance discovery is unreachable', async () => {
- const stored = runtimeSnapshotFromDiscovery(parsedDocument('outage.test'));
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => new Response('upstream unavailable', {status: 503})),
- );
- const prepared = await RuntimeConfig.resolveAndPrepareSnapshot({snapshot: stored, signal: null});
- expect(prepared.snapshot).toEqual(stored);
- await RuntimeConfig.abortPreparedSnapshot(prepared);
- expect(RuntimeConfig.apiEndpoint).toBe('https://boot.test/api');
- });
-
- test('prepares the stored snapshot when the network refuses every discovery request', async () => {
- const stored = runtimeSnapshotFromDiscovery(parsedDocument('offline.test'));
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => {
- throw new TypeError('Failed to fetch');
- }),
- );
- const prepared = await RuntimeConfig.resolveAndPrepareSnapshot({snapshot: stored, signal: null});
- expect(prepared.snapshot).toEqual(stored);
- await RuntimeConfig.abortPreparedSnapshot(prepared);
- });
-
- test('prefers the freshly discovered snapshot when discovery answers', async () => {
- const stored = runtimeSnapshotFromDiscovery(parsedDocument('fresh.test'));
- const document = discoveryDocument('fresh.test');
- document.endpoints.gateway = 'wss://moved.fresh.test';
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse(document)),
- );
- const prepared = await RuntimeConfig.resolveAndPrepareSnapshot({snapshot: stored, signal: null});
- expect(prepared.snapshot.gatewayEndpoint).toBe('wss://moved.fresh.test');
- await RuntimeConfig.abortPreparedSnapshot(prepared);
- });
-
- test('never falls back when the instance now requires a newer client', async () => {
- const stored = runtimeSnapshotFromDiscovery(parsedDocument('upgraded.test'));
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => jsonResponse({...discoveryDocument('upgraded.test'), codename: 'future'})),
- );
- await expect(RuntimeConfig.resolveAndPrepareSnapshot({snapshot: stored, signal: null})).rejects.toThrow(/future/u);
- });
-
- test('honours an aborted signal instead of falling back', async () => {
- const stored = runtimeSnapshotFromDiscovery(parsedDocument('cancelled.test'));
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => new Response('', {status: 503})),
- );
- await expect(
- RuntimeConfig.resolveAndPrepareSnapshot({snapshot: stored, signal: AbortSignal.abort()}),
- ).rejects.toThrow();
- });
-});
-
-describe('describeAPIEndpoint', () => {
- test.each([
- ['https://api.fluxer.app', 'fluxer.app'],
- ['https://web.fluxer.app', 'fluxer.app'],
- ['https://api.canary.fluxer.app', 'fluxer.app'],
- ['https://self.example/api', 'self.example/api'],
- ['https://self.example/api/', 'self.example/api'],
- ['self.example', 'self.example'],
- ['http://localhost:8080/api', 'http://localhost:8080/api'],
- ['https://fluxer.app:8443/api', 'fluxer.app:8443/api'],
- ['/api', '/api'],
- ['not a url at all', 'not a url at all'],
- ])('%s displays as %s', (endpoint, expected) => {
- expect(describeAPIEndpoint(endpoint)).toBe(expected);
- });
-});
diff --git a/fluxer_app/src/features/gateway/events/AccountReadyWork.test.ts b/fluxer_app/src/features/gateway/events/AccountReadyWork.test.ts
deleted file mode 100644
index df124aef9..000000000
--- a/fluxer_app/src/features/gateway/events/AccountReadyWork.test.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- userId: null as string | null,
- start: vi.fn(),
- refreshPremiumState: vi.fn(() => Promise.resolve()),
- passkeyReady: vi.fn(),
-}));
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-
-vi.mock('@app/features/platform/state/AuthSession', () => ({
- default: {
- get userId() {
- return mocks.userId;
- },
- },
-}));
-
-vi.mock('@app/features/experiment/state/ExperimentAssignments', () => ({default: {start: mocks.start}}));
-vi.mock('@app/features/premium/commands/PremiumCommands', () => ({refreshPremiumState: mocks.refreshPremiumState}));
-vi.mock('@app/features/auth/passkey_migration/PasskeyMigration', () => ({
- default: {handleGatewayReady: mocks.passkeyReady},
-}));
-
-const {AccountScopedWork, AccountScopedWorkTransitionReason} = await import(
- '@app/features/platform/state/AccountScopedWork'
-);
-const {scheduleAccountReadyWork} = await import('@app/features/gateway/events/AccountReadyWork');
-
-async function settle(): Promise<void> {
- for (let i = 0; i < 10; i++) {
- await Promise.resolve();
- }
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-function expectRanFor(userId: string): void {
- expect(mocks.start).toHaveBeenCalledTimes(1);
- expect(mocks.start).toHaveBeenCalledWith(userId);
- expect(mocks.refreshPremiumState).toHaveBeenCalledTimes(1);
- expect(mocks.passkeyReady).toHaveBeenCalledWith(userId);
-}
-
-describe('AccountReadyWork', () => {
- afterEach(() => {
- mocks.userId = null;
- vi.clearAllMocks();
- });
-
- it('runs the READY work at once when admission is open', async () => {
- mocks.userId = 'a';
- scheduleAccountReadyWork('a');
- await settle();
- expectRanFor('a');
- });
-
- it('defers READY work scheduled during an account transition until admission opens', async () => {
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- mocks.userId = 'b';
- scheduleAccountReadyWork('b');
- await settle();
- expect(mocks.start).not.toHaveBeenCalled();
- expect(mocks.refreshPremiumState).not.toHaveBeenCalled();
- });
- await settle();
- expectRanFor('b');
- });
-
- it('runs only the last account scheduled within one transition', async () => {
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- scheduleAccountReadyWork('b');
- mocks.userId = 'a';
- scheduleAccountReadyWork('a');
- });
- await settle();
- expectRanFor('a');
- });
-
- it('drops deferred work when the transition ended on another account', async () => {
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- scheduleAccountReadyWork('b');
- mocks.userId = 'a';
- });
- await settle();
- expect(mocks.start).not.toHaveBeenCalled();
- expect(mocks.refreshPremiumState).not.toHaveBeenCalled();
- });
-
- it('does not replay work from an earlier transition on a later one', async () => {
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- mocks.userId = 'b';
- scheduleAccountReadyWork('b');
- });
- await settle();
- vi.clearAllMocks();
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {});
- await settle();
- expect(mocks.start).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayConnectionAuthFailure.test.ts b/fluxer_app/src/features/gateway/transport/GatewayConnectionAuthFailure.test.ts
deleted file mode 100644
index 26a71b6f0..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayConnectionAuthFailure.test.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import Authentication from '@app/features/auth/state/Authentication';
-import GatewaySessions from '@app/features/gateway/transport/GatewaySessionPool';
-import type {GatewaySocket, GatewaySocketProperties} from '@app/features/gateway/transport/GatewaySocket';
-import {resetClientState} from '@app/features/platform/state/ResetClientState';
-import LayerManager from '@app/features/ui/state/LayerManager';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({sequence: [] as Array<string>}));
-
-vi.mock('@app/features/channel/state/ChannelFrecency', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumPosts', () => ({default: {reset: vi.fn(), handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumReadState', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/navigation/state/NavigationSideEffects', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ChannelThreads', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadGuilds', () => ({
- default: {reset: vi.fn(), handleGatewayReady: vi.fn(), isPurgedEvent: () => false},
-}));
-
-vi.mock('@app/features/threads/state/ThreadPanel', () => ({default: {closeCreate: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadRoster', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadSubscriptions', () => ({default: {handleConnectionReady: vi.fn()}}));
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => undefined}}));
-
-vi.mock('@app/features/navigation/state/Navigation', () => ({default: {channelId: null}}));
-
-vi.mock('@app/features/messaging/state/AttachmentUrlRefresher', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/app/state/GeoIP', () => ({
- default: {latitude: null, longitude: null, applyConnectionFallbackGeo: vi.fn()},
-}));
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({
- default: {gatewayEndpoint: 'wss://gateway.test'},
-}));
-
-vi.mock('@app/features/gateway/transport/ForegroundGatewayHandoff', () => ({
- ForegroundGatewayHandoff: class ForegroundGatewayHandoff {},
-}));
-
-vi.mock('@app/features/gateway/events/EventRouter', () => ({createHandlerRegistry: () => new Map()}));
-
-vi.mock('@app/features/platform/utils/DeferUntilModulesLoaded', () => ({deferUntilModulesLoaded: vi.fn()}));
-
-vi.mock('@app/features/platform/state/ResetClientState', () => ({
- ResetClientStateReason: {GATEWAY_AUTH_FAILURE: 'gateway-auth-failure'},
- resetClientState: vi.fn(() => {
- mocks.sequence.push('resetClientState');
- return Promise.resolve();
- }),
-}));
-
-vi.mock('@app/features/ui/state/LayerManager', () => ({
- default: {
- closeAll: vi.fn(() => {
- mocks.sequence.push('closeAllLayers');
- }),
- },
-}));
-
-vi.mock('@app/features/presence/state/Presence', () => ({
- default: {
- handleSessionInvalidated: vi.fn(() => {
- mocks.sequence.push('logout');
- }),
- },
-}));
-
-vi.mock('@app/features/auth/state/Authentication', () => ({
- default: {
- handleConnectionClosed: vi.fn(async () => {
- mocks.sequence.push('handleConnectionClosed');
- }),
- },
-}));
-
-vi.mock('@app/features/app/state/Initialization', () => ({
- default: {setConnecting: vi.fn(), setReady: vi.fn(), reset: vi.fn()},
-}));
-
-vi.mock('@app/features/app/state/RuntimeCrash', () => ({default: {triggerFatalCrash: vi.fn()}}));
-
-vi.mock('@app/features/expressions/state/FavoriteMemes', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/member/state/MemberSearch', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {handleSessionInvalidated: vi.fn(), handleConnectionClosed: vi.fn()},
-}));
-
-vi.mock('@app/features/navigation/state/SelectedGuild', () => ({
- default: {selectedGuildId: null, selectionNonce: 0},
-}));
-
-vi.mock('@app/features/permissions/state/Permission', () => ({default: {}}));
-
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {
- presenceKey: '',
- mobile: false,
- updatePresence: vi.fn(),
- getGatewayPresence: () => null,
- handleSessionChanging: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/search/state/QuickSwitcher', () => ({default: {recomputeIfOpen: vi.fn()}}));
-
-vi.mock('@app/features/typing/rolling/RollingTypingStore', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/ui/state/MobileLayout', () => ({default: {isMobileLayout: () => false}}));
-
-vi.mock('@app/features/voice/VoiceGatewayLifecycle', () => ({
- reportGatewayErrorToVoice: vi.fn(),
- teardownVoiceForFatalGatewayCrash: vi.fn(),
-}));
-
-const PROPERTIES: GatewaySocketProperties = {
- os: 'macos',
- browser: 'Fluxer Client',
- device: 'desktop',
- locale: 'en-US',
- user_agent: 'test',
- browser_version: '1',
- os_version: '1',
- build_version: '1',
-};
-
-const ACCOUNT_KEY = 'instance::100';
-
-interface ConnectionInternals {
- createGatewaySocket: (
- gatewayUrl: string,
- token: string,
- properties: GatewaySocketProperties,
- generation: number,
- accountKey: string | null,
- ) => GatewaySocket;
- socketOwner: {socket: GatewaySocket; accountKey: string | null} | null;
- generation: number;
-}
-
-function adoptSocket(): GatewaySocket {
- const connection = GatewaySessions.foregroundConnection as unknown as ConnectionInternals;
- const socket = connection.createGatewaySocket(
- 'wss://gateway.test',
- 'token-100',
- PROPERTIES,
- connection.generation,
- ACCOUNT_KEY,
- );
- connection.socketOwner = {socket, accountKey: ACCOUNT_KEY};
- return socket;
-}
-
-function closeSocket(socket: GatewaySocket, code: number): void {
- (
- socket as unknown as {handleSocketClose: (event: {code: number; reason: string; wasClean: boolean}) => void}
- ).handleSocketClose({code, reason: 'closed', wasClean: false});
- vi.advanceTimersByTime(0);
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- mocks.sequence.length = 0;
- vi.mocked(resetClientState).mockClear();
- vi.mocked(LayerManager.closeAll).mockClear();
- vi.mocked(Authentication.handleConnectionClosed).mockClear();
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-async function flushMicrotasks(): Promise<void> {
- for (let turn = 0; turn < 8; turn += 1) {
- await Promise.resolve();
- }
-}
-
-describe('gateway authentication failure', () => {
- test('a 4004 close runs the four-step logout in order, from the connection', async () => {
- const socket = adoptSocket();
-
- closeSocket(socket, 4004);
- await flushMicrotasks();
-
- expect(mocks.sequence).toEqual(['resetClientState', 'closeAllLayers', 'logout', 'handleConnectionClosed']);
- expect(resetClientState).toHaveBeenCalledWith({reason: 'gateway-auth-failure', keepDrafts: true});
- expect(Authentication.handleConnectionClosed).toHaveBeenCalledWith({code: 4004, accountKey: ACCOUNT_KEY});
- expect(GatewaySessions.foregroundConnection.socket).toBeNull();
- expect(GatewaySessions.foregroundConnection.isReady).toBe(false);
- expect(GatewaySessions.foregroundConnection.sessionId).toBeNull();
- });
-
- test('any other close code leaves the account signed in', () => {
- const socket = adoptSocket();
-
- closeSocket(socket, 1006);
-
- expect(mocks.sequence).toEqual([]);
- expect(resetClientState).not.toHaveBeenCalled();
- expect(LayerManager.closeAll).not.toHaveBeenCalled();
- expect(Authentication.handleConnectionClosed).not.toHaveBeenCalled();
- });
-
- test('a retired socket never logs the current account out', () => {
- const socket = adoptSocket();
- (GatewaySessions.foregroundConnection as unknown as ConnectionInternals).socketOwner = null;
-
- closeSocket(socket, 4004);
-
- expect(mocks.sequence).toEqual([]);
- expect(resetClientState).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.test.ts b/fluxer_app/src/features/gateway/transport/GatewaySessionPool.test.ts
deleted file mode 100644
index 67dbb0e5d..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.test.ts
+++ /dev/null
@@ -1,499 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import Initialization from '@app/features/app/state/Initialization';
-import {
- MAX_BACKGROUND_GATEWAY_CONNECTIONS,
- readMaxBackgroundGatewayConnections,
-} from '@app/features/gateway/transport/BackgroundGatewaySessionManager';
-import {
- ForegroundGatewayConnectionRecoverableError,
- ForegroundGatewayRecoveryCause,
-} from '@app/features/gateway/transport/ForegroundGatewayConnectionFailure';
-import {
- GATEWAY_FOREGROUND_READY_TIMEOUT_MS,
- GatewayReadyTimeoutError,
-} from '@app/features/gateway/transport/GatewayReadinessWaiters';
-import GatewaySessions from '@app/features/gateway/transport/GatewaySessionPool';
-import SelectedGuild from '@app/features/navigation/state/SelectedGuild';
-import LocalPresence from '@app/features/presence/state/LocalPresence';
-import {runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({token: 'token-primary' as string | null, clientPropertiesFailure: false}));
-
-vi.mock('@app/features/channel/state/ChannelFrecency', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumPosts', () => ({default: {reset: vi.fn(), handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumReadState', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/navigation/state/NavigationSideEffects', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ChannelThreads', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadGuilds', () => ({
- default: {reset: vi.fn(), handleGatewayReady: vi.fn(), isPurgedEvent: () => false},
-}));
-
-vi.mock('@app/features/threads/state/ThreadPanel', () => ({default: {closeCreate: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadRoster', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadSubscriptions', () => ({default: {handleConnectionReady: vi.fn()}}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => undefined}}));
-
-vi.mock('@app/features/navigation/state/Navigation', () => ({default: {channelId: null}}));
-
-vi.mock('@app/features/messaging/state/AttachmentUrlRefresher', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/app/state/GeoIP', () => ({
- default: {latitude: null, longitude: null, applyConnectionFallbackGeo: vi.fn()},
-}));
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({
- default: {gatewayEndpoint: 'wss://gateway.primary.test'},
-}));
-
-vi.mock('@app/features/gateway/transport/ForegroundGatewayHandoff', () => ({
- ForegroundGatewayHandoff: class ForegroundGatewayHandoff {},
-}));
-
-vi.mock('@app/features/gateway/events/EventRouter', () => ({createHandlerRegistry: () => new Map()}));
-
-vi.mock('@app/features/gateway/transport/GatewayCompression', () => ({
- isCompressionSupported: () => true,
- isGatewayCompressionError: () => false,
- GatewayCompressionError: class GatewayCompressionError extends Error {},
- GatewayCompression: class GatewayCompression {
- warmup(): Promise<void> {
- return Promise.resolve();
- }
- destroy(): void {}
- },
-}));
-
-vi.mock('@app/features/platform/utils/ClientInfo', () => ({
- getGatewayClientProperties: () =>
- mocks.clientPropertiesFailure
- ? Promise.reject(new Error('client metadata unavailable'))
- : Promise.resolve({
- os: 'macos',
- browser: 'Fluxer Client',
- device: 'desktop',
- locale: 'en-US',
- user_agent: 'test',
- browser_version: '1',
- os_version: '1',
- build_version: '1',
- }),
-}));
-
-vi.mock('@app/features/platform/state/AuthSession', () => ({
- default: {
- currentAccountKey: 'primary.test::100',
- userId: '100',
- get token() {
- return mocks.token;
- },
- markAccountInvalid: vi.fn(),
- handleConnectionStarted: vi.fn(),
- handleConnectionFailed: vi.fn(),
- handleConnectionReady: vi.fn(),
- handleConnectionClosed: vi.fn(async () => undefined),
- },
-}));
-
-vi.mock('@app/features/auth/state/AccountAccess', () => ({
- default: {markGatewayReady: vi.fn(), markGatewayUnavailable: vi.fn()},
-}));
-
-vi.mock('@app/features/platform/state/ResetClientState', () => ({
- ResetClientStateReason: {GATEWAY_AUTH_FAILURE: 'gateway-auth-failure'},
- resetClientState: vi.fn(() => Promise.resolve()),
-}));
-
-vi.mock('@app/features/ui/state/LayerManager', () => ({default: {closeAll: vi.fn()}}));
-
-vi.mock('@app/features/app/state/Initialization', () => ({
- default: {setConnecting: vi.fn(), setReady: vi.fn(), reset: vi.fn(), setError: vi.fn()},
-}));
-
-vi.mock('@app/features/app/state/RuntimeCrash', () => ({default: {triggerFatalCrash: vi.fn()}}));
-
-vi.mock('@app/features/auth/state/Authentication', () => ({
- default: {handleConnectionClosed: vi.fn(async () => undefined)},
-}));
-
-vi.mock('@app/features/expressions/state/FavoriteMemes', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/member/state/MemberSearch', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/moderation/state/ReportFlows', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {handleSessionInvalidated: vi.fn(), handleConnectionClosed: vi.fn()},
-}));
-
-vi.mock('@app/features/navigation/state/SelectedGuild', async () => {
- const {observable} = await import('mobx');
- return {default: observable({selectedGuildId: null as string | null, selectionNonce: 0})};
-});
-
-vi.mock('@app/features/permissions/state/Permission', () => ({default: {}}));
-
-vi.mock('@app/features/presence/state/LocalPresence', async () => {
- const {observable} = await import('mobx');
- return {
- default: observable(
- {
- presenceKey: '',
- mobile: false,
- updatePresence: () => undefined,
- getGatewayPresence: () => null,
- handleSessionChanging: () => undefined,
- },
- {},
- {deep: false},
- ),
- };
-});
-
-vi.mock('@app/features/presence/state/Presence', () => ({default: {handleSessionInvalidated: vi.fn()}}));
-
-vi.mock('@app/features/search/state/QuickSwitcher', () => ({default: {recomputeIfOpen: vi.fn()}}));
-
-vi.mock('@app/features/typing/rolling/RollingTypingStore', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/ui/state/MobileLayout', () => ({default: {isMobileLayout: () => false}}));
-
-vi.mock('@app/features/voice/VoiceGatewayLifecycle', () => ({
- reportGatewayErrorToVoice: vi.fn(),
- teardownVoiceForFatalGatewayCrash: vi.fn(),
-}));
-
-const ROUTER_GLOBAL_KEY = '__fluxerDesktopGatewayTransport';
-
-class FakeWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
- static instances: Array<FakeWebSocket> = [];
-
- readyState: number = FakeWebSocket.CONNECTING;
- binaryType = 'blob';
- readonly closeCalls: Array<{code: number; reason: string}> = [];
-
- constructor(readonly url: string) {
- FakeWebSocket.instances.push(this);
- }
-
- addEventListener(): void {}
- removeEventListener(): void {}
- send(): void {}
- close(code: number, reason: string): void {
- this.closeCalls.push({code, reason});
- this.readyState = FakeWebSocket.CLOSED;
- }
-}
-
-function liveSocketCount(): number {
- return FakeWebSocket.instances.filter((socket) => socket.readyState !== FakeWebSocket.CLOSED).length;
-}
-
-interface ForegroundConnectionInternals {
- guildSubscriptions: {pendingGuildId: string | null};
-}
-
-function pendingGuildSyncId(): string | null {
- const connection = GatewaySessions.foregroundConnection as unknown as ForegroundConnectionInternals;
- return connection.guildSubscriptions.pendingGuildId;
-}
-
-async function settleSocketOpen(expectedSockets: number): Promise<void> {
- for (let attempt = 0; attempt < 20 && FakeWebSocket.instances.length < expectedSockets; attempt += 1) {
- await vi.advanceTimersByTimeAsync(0);
- }
- expect(FakeWebSocket.instances).toHaveLength(expectedSockets);
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- FakeWebSocket.instances = [];
- mocks.token = 'token-primary';
- mocks.clientPropertiesFailure = false;
- vi.stubGlobal('WebSocket', FakeWebSocket);
- Reflect.deleteProperty(globalThis as unknown as Record<string, unknown>, ROUTER_GLOBAL_KEY);
-});
-
-afterEach(() => {
- GatewaySessions.foregroundConnection.logout();
- GatewaySessions.dispose();
- runInAction(() => {
- SelectedGuild.selectedGuildId = null;
- SelectedGuild.selectionNonce = 0;
- });
- vi.unstubAllGlobals();
- vi.useRealTimers();
-});
-
-describe('background connection cap', () => {
- test('defaults to six when the instance declares nothing', () => {
- expect(readMaxBackgroundGatewayConnections(undefined)).toBe(MAX_BACKGROUND_GATEWAY_CONNECTIONS);
- });
-
- test('an instance may reduce the cap, including to zero', () => {
- expect(readMaxBackgroundGatewayConnections(0)).toBe(0);
- expect(readMaxBackgroundGatewayConnections(2)).toBe(2);
- });
-
- test('an instance can never raise the cap above the client bound', () => {
- expect(readMaxBackgroundGatewayConnections(64)).toBe(MAX_BACKGROUND_GATEWAY_CONNECTIONS);
- });
-
- test('a malformed declaration is rejected', () => {
- expect(() => readMaxBackgroundGatewayConnections(-1)).toThrow(
- 'Background gateway connection limit must be a non-negative integer, got -1',
- );
- expect(() => readMaxBackgroundGatewayConnections(1.5)).toThrow(
- 'Background gateway connection limit must be a non-negative integer, got 1.5',
- );
- });
-});
-
-describe('web inertness', () => {
- test('a full account switch keeps exactly one live WebSocket and installs no desktop router', async () => {
- GatewaySessions.start();
-
- await GatewaySessions.foregroundConnection.startSession('primary.test::100');
- await settleSocketOpen(1);
- expect(liveSocketCount()).toBe(1);
-
- mocks.token = 'token-secondary';
- await GatewaySessions.foregroundConnection.startSession('secondary.test::200');
- await settleSocketOpen(2);
-
- expect(liveSocketCount()).toBe(1);
- expect(GatewaySessions.backgroundConnectionCount).toBe(0);
- expect((globalThis as unknown as Record<string, unknown>)[ROUTER_GLOBAL_KEY]).toBeUndefined();
- });
-});
-
-describe('pool reaction lifecycle', () => {
- test('start installs the foreground reactions and dispose removes them', async () => {
- GatewaySessions.start();
- await vi.advanceTimersByTimeAsync(0);
-
- runInAction(() => {
- SelectedGuild.selectedGuildId = 'guild-1';
- SelectedGuild.selectionNonce = 1;
- });
- expect(pendingGuildSyncId()).toBe('guild-1');
-
- GatewaySessions.dispose();
- runInAction(() => {
- SelectedGuild.selectedGuildId = 'guild-2';
- SelectedGuild.selectionNonce = 2;
- (LocalPresence as unknown as {presenceKey: string}).presenceKey = 'changed';
- });
-
- expect(pendingGuildSyncId()).toBe('guild-1');
- });
-
- test('dispose before the deferred install still leaves no reaction behind', async () => {
- GatewaySessions.start();
- GatewaySessions.dispose();
- await vi.advanceTimersByTimeAsync(0);
-
- runInAction(() => {
- SelectedGuild.selectedGuildId = 'guild-3';
- SelectedGuild.selectionNonce = 3;
- });
-
- expect(pendingGuildSyncId()).toBeNull();
- });
-});
-
-describe('waitForForegroundReady', () => {
- test('rejects with a recoverable error and keeps one socket reconnecting when READY never arrives', async () => {
- const pending = GatewaySessions.waitForForegroundReady('primary.test::100');
- const settled = expect(pending).rejects.toSatisfy(
- (error: unknown) =>
- error instanceof ForegroundGatewayConnectionRecoverableError &&
- error.recoveryCause === ForegroundGatewayRecoveryCause.TRANSPORT_DISCONNECTED,
- );
- await settleSocketOpen(1);
- const socket = GatewaySessions.foregroundConnection.socket;
-
- await vi.advanceTimersByTimeAsync(GATEWAY_FOREGROUND_READY_TIMEOUT_MS);
- await settled;
-
- expect(GatewaySessions.foregroundConnection.socket).toBe(socket);
- expect(GatewaySessions.foregroundConnection.isConnecting).toBe(true);
- expect(liveSocketCount()).toBeLessThanOrEqual(1);
- });
-
- test('a readiness timeout while still connecting reconnects the same socket with backoff', async () => {
- const pending = GatewaySessions.waitForForegroundReady('primary.test::100');
- const settled = expect(pending).rejects.toSatisfy(
- (error: unknown) =>
- error instanceof ForegroundGatewayConnectionRecoverableError &&
- error.recoveryCause === ForegroundGatewayRecoveryCause.READINESS_TIMEOUT &&
- error.cause instanceof GatewayReadyTimeoutError,
- );
- await settleSocketOpen(1);
- const socket = GatewaySessions.foregroundConnection.socket;
- const internals = socket as unknown as {clearHelloTimeout: () => void};
- internals.clearHelloTimeout();
-
- await vi.advanceTimersByTimeAsync(GATEWAY_FOREGROUND_READY_TIMEOUT_MS);
- await settled;
-
- expect(GatewaySessions.foregroundConnection.socket).toBe(socket);
- expect(socket?.getState()).toBe('RECONNECTING');
- });
-
- test('resolves once the foreground session reaches READY', async () => {
- const pending = GatewaySessions.waitForForegroundReady('primary.test::100');
- await settleSocketOpen(1);
-
- GatewaySessions.foregroundConnection.handleConnectionOpen('session-1');
- await pending;
-
- expect(GatewaySessions.foregroundConnection.isReady).toBe(true);
- expect(GatewaySessions.foregroundConnection.sessionId).toBe('session-1');
- expect(liveSocketCount()).toBe(1);
- });
-
- test('rejects without opening a socket when there is no stored token', async () => {
- mocks.token = null;
-
- await expect(GatewaySessions.waitForForegroundReady('primary.test::100')).rejects.toThrow(
- /Gateway session did not start/,
- );
- expect(FakeWebSocket.instances).toHaveLength(0);
- });
-});
-
-function failForegroundTransport(): void {
- const socket = GatewaySessions.foregroundConnection.socket;
- if (socket === null) {
- throw new Error('No foreground socket to fail');
- }
- socket.disconnect(4000, 'Gateway unreachable', true);
-}
-
-describe('foreground session during a gateway outage', () => {
- beforeEach(() => {
- vi.mocked(Initialization.setError).mockClear();
- });
-
- test('a connection failure before READY rejects the wait promptly and keeps the socket reconnecting', async () => {
- const pending = GatewaySessions.waitForForegroundReady('primary.test::100');
- const settled = expect(pending).rejects.toSatisfy(
- (error: unknown) =>
- error instanceof ForegroundGatewayConnectionRecoverableError &&
- error.recoveryCause === ForegroundGatewayRecoveryCause.TRANSPORT_DISCONNECTED,
- );
- await settleSocketOpen(1);
-
- failForegroundTransport();
- await vi.advanceTimersByTimeAsync(0);
- await settled;
-
- expect(GatewaySessions.foregroundConnection.socket).not.toBeNull();
- expect(GatewaySessions.foregroundConnection.isConnecting).toBe(true);
- });
-
- test('a readiness timeout during reconnect backoff leaves the socket to its own retries', async () => {
- GatewaySessions.startRestoredSession();
- await settleSocketOpen(1);
- const socket = GatewaySessions.foregroundConnection.socket;
-
- for (let elapsedMs = 0; elapsedMs < 6 * GATEWAY_FOREGROUND_READY_TIMEOUT_MS; elapsedMs += 5_000) {
- if (GatewaySessions.foregroundConnection.socket?.getState() === 'CONNECTING') {
- failForegroundTransport();
- }
- await vi.advanceTimersByTimeAsync(5_000);
- }
-
- expect(GatewaySessions.foregroundConnection.socket).toBe(socket);
- expect(vi.mocked(Initialization.setError)).not.toHaveBeenCalled();
- expect(liveSocketCount()).toBeLessThanOrEqual(1);
- });
-
- test('an outage longer than the recovery budget reconnects as soon as the gateway is back', async () => {
- GatewaySessions.startRestoredSession();
- await settleSocketOpen(1);
-
- for (let elapsedMs = 0; elapsedMs < 10 * GATEWAY_FOREGROUND_READY_TIMEOUT_MS; elapsedMs += 5_000) {
- if (GatewaySessions.foregroundConnection.socket?.getState() === 'CONNECTING') {
- failForegroundTransport();
- }
- await vi.advanceTimersByTimeAsync(5_000);
- }
- expect(vi.mocked(Initialization.setError)).not.toHaveBeenCalled();
- expect(GatewaySessions.foregroundConnection.socket).not.toBeNull();
-
- await vi.advanceTimersByTimeAsync(GATEWAY_FOREGROUND_READY_TIMEOUT_MS);
- GatewaySessions.foregroundConnection.handleConnectionOpen('session-after-outage');
- await vi.advanceTimersByTimeAsync(0);
-
- expect(GatewaySessions.foregroundConnection.isReady).toBe(true);
- expect(GatewaySessions.foregroundConnection.foregroundAccountKey).toBe('primary.test::100');
- });
-});
-
-describe('foreground recovery after the capped budget', () => {
- const EXHAUSTED_RECOVERY_MS = 1_000 + 3_000 + 10_000 + 1_000;
-
- async function exhaustForegroundRecovery(): Promise<void> {
- mocks.clientPropertiesFailure = true;
- GatewaySessions.startRestoredSession();
- await vi.advanceTimersByTimeAsync(EXHAUSTED_RECOVERY_MS);
- expect(vi.mocked(Initialization.setError)).toHaveBeenCalledTimes(1);
- expect(GatewaySessions.foregroundConnection.socket).toBeNull();
- expect(liveSocketCount()).toBe(0);
- mocks.clientPropertiesFailure = false;
- }
-
- beforeEach(() => {
- vi.mocked(Initialization.setError).mockClear();
- });
-
- test('the network coming back restarts the foreground session', async () => {
- await exhaustForegroundRecovery();
- const socketsBeforeOnline = FakeWebSocket.instances.length;
-
- window.dispatchEvent(new Event('online'));
- await settleSocketOpen(socketsBeforeOnline + 1);
- GatewaySessions.foregroundConnection.handleConnectionOpen('session-after-outage');
- await vi.advanceTimersByTimeAsync(0);
-
- expect(GatewaySessions.foregroundConnection.isReady).toBe(true);
- expect(liveSocketCount()).toBe(1);
- });
-
- test('a gateway outage with no online event is retried on a slow interval', async () => {
- await exhaustForegroundRecovery();
- const socketsBeforeRetry = FakeWebSocket.instances.length;
-
- await vi.advanceTimersByTimeAsync(60_000);
-
- expect(FakeWebSocket.instances).toHaveLength(socketsBeforeRetry + 1);
- expect(liveSocketCount()).toBe(1);
- });
-
- test('dispose removes the re-arm listeners', async () => {
- await exhaustForegroundRecovery();
- const socketsBeforeDispose = FakeWebSocket.instances.length;
- GatewaySessions.dispose();
-
- window.dispatchEvent(new Event('online'));
- await vi.advanceTimersByTimeAsync(120_000);
-
- expect(FakeWebSocket.instances).toHaveLength(socketsBeforeDispose);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/PooledGatewayConnectionDispatch.test.ts b/fluxer_app/src/features/gateway/transport/PooledGatewayConnectionDispatch.test.ts
deleted file mode 100644
index 99f453a16..000000000
--- a/fluxer_app/src/features/gateway/transport/PooledGatewayConnectionDispatch.test.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {GatewaySocket, GatewaySocketProperties} from '@app/features/gateway/transport/GatewaySocket';
-import {PooledGatewayConnection} from '@app/features/gateway/transport/PooledGatewayConnection';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-await vi.hoisted(async () => {
- const {installHarnessBootstrap} = await import('@app/features/auth/state/__fixtures__/AccountSwitchHarness');
- installHarnessBootstrap();
-});
-
-const mocks = vi.hoisted(() => ({
- createHandlerRegistry: vi.fn(() => new Map()),
- currentAccountKey: null as string | null,
-}));
-
-vi.mock('@app/features/channel/state/ChannelFrecency', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumPosts', () => ({default: {reset: vi.fn(), handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/forum/state/ForumReadState', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/navigation/state/NavigationSideEffects', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ChannelThreads', () => ({default: {handleGatewayReady: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadGuilds', () => ({
- default: {reset: vi.fn(), handleGatewayReady: vi.fn(), isPurgedEvent: () => false},
-}));
-
-vi.mock('@app/features/threads/state/ThreadPanel', () => ({default: {closeCreate: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadRoster', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/threads/state/ThreadSubscriptions', () => ({default: {handleConnectionReady: vi.fn()}}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => undefined}}));
-
-vi.mock('@app/features/navigation/state/Navigation', () => ({default: {channelId: null}}));
-
-vi.mock('@app/features/messaging/state/AttachmentUrlRefresher', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/gateway/events/EventRouter', () => ({createHandlerRegistry: mocks.createHandlerRegistry}));
-
-vi.mock('@app/features/app/state/GeoIP', () => ({
- default: {
- latitude: null,
- longitude: null,
- applyConnectionFallbackGeo: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/gateway/transport/GatewayCompression', () => ({
- isCompressionSupported: () => true,
- isGatewayCompressionError: () => false,
- GatewayCompressionError: class GatewayCompressionError extends Error {},
- GatewayCompression: class GatewayCompression {
- warmup(): Promise<void> {
- return Promise.resolve();
- }
- destroy(): void {}
- },
-}));
-
-vi.mock('@app/features/platform/state/AuthSession', () => ({
- default: {
- get currentAccountKey() {
- return mocks.currentAccountKey;
- },
- getAccount(accountKey: string) {
- return accountKey === mocks.currentAccountKey ? {userId: 'user-primary', token: 'token-primary'} : null;
- },
- userId: 'user-primary',
- token: 'token-primary',
- markAccountInvalid: vi.fn(),
- handleConnectionStarted: vi.fn(),
- handleConnectionFailed: vi.fn(),
- handleConnectionReady: vi.fn(),
- handleConnectionClosed: vi.fn(async () => undefined),
- },
-}));
-
-vi.mock('@app/features/auth/state/AccountAccess', () => ({
- default: {markGatewayReady: vi.fn(), markGatewayUnavailable: vi.fn()},
-}));
-
-vi.mock('@app/features/platform/state/ResetClientState', () => ({
- ResetClientStateReason: {GATEWAY_AUTH_FAILURE: 'gateway-auth-failure'},
- resetClientState: vi.fn(() => Promise.resolve()),
-}));
-
-vi.mock('@app/features/ui/state/LayerManager', () => ({default: {closeAll: vi.fn()}}));
-
-vi.mock('@app/features/app/state/RuntimeCrash', () => ({default: {triggerFatalCrash: vi.fn()}}));
-
-vi.mock('@app/features/auth/state/Authentication', () => ({
- default: {handleConnectionClosed: vi.fn(async () => undefined)},
-}));
-
-vi.mock('@app/features/expressions/state/FavoriteMemes', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/member/state/MemberSearch', () => ({default: {handleLogout: vi.fn()}}));
-
-vi.mock('@app/features/moderation/state/ReportFlows', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {handleSessionInvalidated: vi.fn(), handleConnectionClosed: vi.fn()},
-}));
-
-vi.mock('@app/features/navigation/state/SelectedGuild', () => ({
- default: {selectedGuildId: null, selectionNonce: 0},
-}));
-
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {
- presenceKey: '',
- mobile: false,
- updatePresence: vi.fn(),
- getGatewayPresence: () => null,
- handleSessionChanging: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/presence/state/Presence', () => ({default: {handleSessionInvalidated: vi.fn()}}));
-
-vi.mock('@app/features/search/state/QuickSwitcher', () => ({default: {recomputeIfOpen: vi.fn()}}));
-
-vi.mock('@app/features/typing/rolling/RollingTypingStore', () => ({default: {reset: vi.fn()}}));
-
-vi.mock('@app/features/ui/state/MobileLayout', () => ({default: {isMobileLayout: () => false}}));
-
-vi.mock('@app/features/voice/VoiceGatewayLifecycle', () => ({
- reportGatewayErrorToVoice: vi.fn(),
- teardownVoiceForFatalGatewayCrash: vi.fn(),
-}));
-
-const PROPERTIES: GatewaySocketProperties = {
- os: 'macos',
- browser: 'Fluxer Client',
- device: 'desktop',
- locale: 'en-US',
- user_agent: 'test',
- browser_version: '1',
- os_version: '1',
- build_version: '1',
-};
-
-class FakeWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
- static instances: Array<FakeWebSocket> = [];
-
- readyState: number = FakeWebSocket.CONNECTING;
- binaryType = 'blob';
-
- constructor(readonly url: string) {
- FakeWebSocket.instances.push(this);
- }
-
- addEventListener(): void {}
- removeEventListener(): void {}
- send(): void {}
- close(): void {
- this.readyState = FakeWebSocket.CLOSED;
- }
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- FakeWebSocket.instances = [];
- mocks.currentAccountKey = 'primary.test::100';
- mocks.createHandlerRegistry.mockClear();
- vi.stubGlobal('WebSocket', FakeWebSocket);
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
- vi.useRealTimers();
-});
-
-describe('pooled gateway connection', () => {
- test('a dispatch delivered on a retired socket invokes no handler', () => {
- const handler = vi.fn();
- mocks.createHandlerRegistry.mockImplementationOnce(() => new Map([['MESSAGE_CREATE', handler]]));
- const connection = new PooledGatewayConnection();
- const internals = connection as unknown as {
- createGatewaySocket: (
- gatewayUrl: string,
- token: string,
- properties: GatewaySocketProperties,
- generation: number,
- accountKey: string | null,
- ) => GatewaySocket;
- handleGatewayDispatch: (
- socket: GatewaySocket,
- delivery: unknown,
- accountKey: string | null,
- isCurrent: () => boolean,
- ) => void;
- socketOwner: {socket: GatewaySocket; accountKey: string | null} | null;
- generation: number;
- };
- const socket = internals.createGatewaySocket(
- 'wss://gateway.primary.test',
- 'token-primary',
- PROPERTIES,
- internals.generation,
- 'primary.test::100',
- );
- const delivery = {
- type: 'MESSAGE_CREATE',
- data: {},
- retainedByteSize: 2,
- receipt: {sequence: 1, generation: 0},
- };
-
- internals.socketOwner = null;
- internals.handleGatewayDispatch(socket, delivery, 'primary.test::100', () => true);
- expect(handler).not.toHaveBeenCalled();
-
- internals.socketOwner = {socket, accountKey: 'other.test::999'};
- internals.handleGatewayDispatch(socket, delivery, 'primary.test::100', () => true);
- expect(handler).not.toHaveBeenCalled();
-
- internals.socketOwner = {socket, accountKey: 'primary.test::100'};
- internals.handleGatewayDispatch(socket, delivery, 'primary.test::100', () => true);
- expect(handler).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/ReadStates.test.ts b/fluxer_app/src/features/read_state/state/ReadStates.test.ts
deleted file mode 100644
index fdce47b14..000000000
--- a/fluxer_app/src/features/read_state/state/ReadStates.test.ts
+++ /dev/null
@@ -1,1035 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Endpoints} from '@app/features/app/constants/Endpoints';
-import {Channel} from '@app/features/channel/models/Channel';
-import {ACK_BATCH_DELAY_MS, type GatewayReadState} from '@app/features/read_state/state/read_states/shared';
-import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {Channel as WireChannel} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import type {Message as WireMessage} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import type {UserPartial} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const channels = new Map<string, Channel>();
-const guilds = new Map<string, {joinedAt: string | null}>();
-const blockedUserIds = new Set<string>();
-let pinnedToEnd = false;
-let automaticAck = false;
-const loadedMessages: Array<{id: string; author: {id: string}}> = [];
-let hasMoreBefore = false;
-let hasNewestMessages = true;
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => channels.get(id)},
-}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {
- getMessages: () => ({
- get hasMoreBefore() {
- return hasMoreBefore;
- },
- get length() {
- return loadedMessages.length;
- },
- jumpDestinationId: null,
- hasNewestMessages: () => hasNewestMessages,
- has: (id: string) => loadedMessages.some((m) => m.id === id),
- last: () => loadedMessages[loadedMessages.length - 1],
- forEachBuffered: (cb: (m: unknown) => void) => {
- for (const m of loadedMessages) cb(m);
- },
- }),
- },
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getCurrentUser: () => ({id: 'me'}), cacheUsers: () => {}},
-}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({
- default: {isBlocked: (id: string) => blockedUserIds.has(id)},
-}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: (id: string) => guilds.get(id)}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => null}}));
-vi.mock('@app/features/user/state/UserGuildSettings', () => ({
- default: {
- isEveryoneMentionSuppressed: () => false,
- isRoleMentionSuppressed: () => false,
- isGuildOrChannelMuted: () => false,
- },
-}));
-vi.mock('@app/features/ui/state/Dimension', () => ({default: {channelPinnedToEnd: () => pinnedToEnd}}));
-vi.mock('@app/features/notification/state/NotificationAutoAck', () => ({
- default: {isAutomaticAckEnabled: () => automaticAck, disableForChannel: () => {}},
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {post: vi.fn(async () => ({body: {read_states: []}})), get: vi.fn()},
-}));
-
-const {default: ReadStates} = await import('@app/features/read_state/state/ReadStates');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-
-const ID = {
- ack: '1519773906704011264',
- newer: '1519773906708205568',
-};
-
-let nextChannelId = 0;
-
-function seedReadChannel() {
- const channelId = `channel-${++nextChannelId}`;
- channels.set(channelId, new Channel({id: channelId, type: ChannelTypes.GUILD_TEXT, guild_id: 'guild-1'}));
- const state = ReadStates.get(channelId);
- state.ackMessageId = ID.ack;
- state.lastMessageId = ID.ack;
- state.unreadCount = 0;
- state.oldestUnreadMessageId = null;
- return {channelId, state};
-}
-
-beforeEach(() => {
- loadedMessages.length = 0;
- hasMoreBefore = false;
- hasNewestMessages = true;
- blockedUserIds.clear();
- pinnedToEnd = false;
- automaticAck = false;
- vi.mocked(http.post).mockClear();
-});
-
-describe('ReadStates unread invariant', () => {
- it('never reports a positive unread count without an unread anchor after a passive update', () => {
- const {channelId} = seedReadChannel();
- ReadStates.handlePassiveLastMessageUpdates({[channelId]: ID.newer}, 'guild-1');
- const count = ReadStates.getUnreadCount(channelId);
- const anchor = ReadStates.getVisualUnreadMessageId(channelId);
- expect(count > 0).toBe(anchor != null);
- });
-
- it('keeps the channel unread for the sidebar even with no anchor to draw a divider at', () => {
- const {channelId} = seedReadChannel();
- ReadStates.handlePassiveLastMessageUpdates({[channelId]: ID.newer}, 'guild-1');
- expect(ReadStates.hasUnread(channelId)).toBe(true);
- });
-
- it('ignores a passive update that walks the last message id back', () => {
- const {channelId} = seedReadChannel();
- ReadStates.handlePassiveLastMessageUpdates({[channelId]: ID.newer}, 'guild-1');
- expect(ReadStates.hasUnread(channelId)).toBe(true);
- ReadStates.handlePassiveLastMessageUpdates({[channelId]: ID.ack}, 'guild-1');
- expect(ReadStates.lastMessageId(channelId)).toBe(ID.newer);
- expect(ReadStates.hasUnread(channelId)).toBe(true);
- });
-
- it('never lowers the watermark when an after page comes back empty', () => {
- const {channelId} = seedReadChannel();
- loadedMessages.push({id: ID.ack, author: {id: 'someone'}});
- ReadStates.handlePassiveLastMessageUpdates({[channelId]: ID.newer}, 'guild-1');
- ReadStates.handleLoadMessages({channelId, isAfter: true, messages: []});
- expect(ReadStates.lastMessageId(channelId)).toBe(ID.newer);
- expect(ReadStates.hasUnread(channelId)).toBe(true);
- });
-
- it('keeps a watermark that points at a message no longer in the channel', () => {
- const {channelId, state} = seedReadChannel();
- state.lastMessageId = ID.newer;
- loadedMessages.push({id: ID.ack, author: {id: 'someone'}});
- ReadStates.handleLoadMessages({channelId, isAfter: true, messages: []});
- expect(ReadStates.lastMessageId(channelId)).toBe(ID.newer);
- expect(ReadStates.hasUnread(channelId)).toBe(true);
- });
-
- it('acks up to the watermark so a deleted newest message cannot keep the channel unread', () => {
- const {channelId, state} = seedReadChannel();
- state.lastMessageId = ID.newer;
- loadedMessages.push({id: ID.ack, author: {id: 'someone'}});
- ReadStates.handleLoadMessages({channelId, isAfter: true, messages: []});
- ReadStates.handleChannelAckWithStickyUnread({channelId});
- expect(ReadStates.ackMessageId(channelId)).toBe(ID.newer);
- expect(ReadStates.hasUnread(channelId)).toBe(false);
- });
-
- it('anchors the divider when a window is loaded whose ack sits outside it', () => {
- const {channelId, state} = seedReadChannel();
- state.lastMessageId = ID.newer;
- hasMoreBefore = true;
- loadedMessages.push({id: ID.newer, author: {id: 'someone'}});
- ReadStates.handleLoadMessages({channelId, messages: []});
- expect(ReadStates.getVisualUnreadMessageId(channelId)).toBe(ID.newer);
- expect(ReadStates.getUnreadCount(channelId) > 0).toBe(true);
- });
-});
-
-const ME = 'me';
-const TUNA = 'tuna';
-
-const CHANNEL = {
- dm: '1485064866382176259',
- groupDm: '1485064866382176260',
- notes: '1485064866382176261',
- guildText: '1485064866382176262',
- newDm: '1547743690000000000',
-};
-
-const MESSAGE = {
- older: '1547700000000000000',
- last: '1547743000000000000',
- incoming: '1547743701495717888',
- next: '1547743701495717890',
- own: '1547743701495717892',
- reply: '1547743701495717893',
-};
-
-function user(id: string): UserPartial {
- return {id, username: id, discriminator: '0', global_name: null, avatar: null, avatar_color: null, flags: 0};
-}
-
-function dm(id: string, lastMessageId: string | null): WireChannel {
- return {
- id,
- type: ChannelTypes.DM,
- last_message_id: lastMessageId,
- last_pin_timestamp: null,
- recipients: [user(TUNA)],
- };
-}
-
-function groupDm(lastMessageId: string | null): WireChannel {
- return {
- id: CHANNEL.groupDm,
- type: ChannelTypes.GROUP_DM,
- last_message_id: lastMessageId,
- last_pin_timestamp: null,
- recipients: [user(TUNA)],
- };
-}
-
-function guildText(lastMessageId: string): WireChannel {
- return {id: CHANNEL.guildText, type: ChannelTypes.GUILD_TEXT, guild_id: 'guild-1', last_message_id: lastMessageId};
-}
-
-function wireMessage(
- id: string,
- channelId: string,
- authorId: string,
- overrides: Partial<WireMessage> = {},
-): WireMessage {
- return {
- id,
- channel_id: channelId,
- author: user(authorId),
- type: MessageTypes.DEFAULT,
- flags: 0,
- pinned: false,
- tts: false,
- mention_everyone: false,
- content: 'test',
- timestamp: '2026-09-11T00:00:00.000Z',
- mentions: [],
- mention_roles: [],
- ...overrides,
- } as WireMessage;
-}
-
-function recipientAddMessage(): WireMessage {
- return wireMessage(MESSAGE.next, CHANNEL.groupDm, TUNA, {type: MessageTypes.RECIPIENT_ADD, mentions: [user(ME)]});
-}
-
-function readState(channelId: string, ackMessageId: string, mentionCount = 0): GatewayReadState {
- return {id: channelId, last_message_id: ackMessageId, mention_count: mentionCount, version: '1'};
-}
-
-function ready(readStates: Array<GatewayReadState>, openChannels: Array<WireChannel>): void {
- channels.clear();
- for (const channel of openChannels) {
- channels.set(channel.id, new Channel(channel));
- }
- ReadStates.handleGatewayReady({readState: readStates, channels: openChannels});
-}
-
-function channelCreate(channel: WireChannel): void {
- channels.set(channel.id, new Channel(channel));
- ReadStates.handleChannelCreate({channel});
-}
-
-function channelDelete(channel: {id: string; type?: number; guild_id?: string}): void {
- channels.delete(channel.id);
- ReadStates.handleChannelDelete({channel});
-}
-
-function messageCreate(message: WireMessage): void {
- ReadStates.handleIncomingMessage({channelId: message.channel_id, message});
-}
-
-function unreadState(channelId: string) {
- return {
- unread: ReadStates.hasUnread(channelId),
- unreadCount: ReadStates.getUnreadCount(channelId),
- mentionCount: ReadStates.getMentionCount(channelId),
- ackMessageId: ReadStates.ackMessageId(channelId),
- };
-}
-
-describe('ReadStates private channel open, close and reopen', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- ReadStates.clearAll();
- vi.useRealTimers();
- });
-
- it('shows a DM closed before READY as unread when CHANNEL_CREATE and MESSAGE_CREATE reopen it', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- expect(ReadStates.hasUnread(CHANNEL.dm)).toBe(true);
- expect(ReadStates.hasUnreadPrivateChannel(CHANNEL.dm)).toBe(true);
- ReadStates.consumePendingChanges();
- const privateChannelVersion = ReadStates.privateChannelVersion;
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(ReadStates.privateChannelVersion).toBe(privateChannelVersion + 1);
- expect(ReadStates.consumePendingChanges()).toEqual({
- all: false,
- channelIds: [CHANNEL.dm],
- changes: [{channelId: CHANNEL.dm, guildId: null}],
- });
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.older,
- });
- expect(ReadStates.hasUnreadPrivateChannel(CHANNEL.dm)).toBe(true);
- expect(ReadStates.getPrivateChannelUnreadCount(CHANNEL.dm)).toBe(1);
- expect(ReadStates.getPrivateChannelMentionCount(CHANNEL.dm)).toBe(1);
- expect(ReadStates.getOldestUnreadMessageId(CHANNEL.dm)).toBe(MESSAGE.incoming);
- expect(ReadStates.mentionChannelIds).toContain(CHANNEL.dm);
- });
-
- it('keeps the mentions of a DM READY closed over the limit when a message reopens it', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older, 2)], []);
- expect(unreadState(CHANNEL.dm)).toEqual({unread: false, unreadCount: 0, mentionCount: 0, ackMessageId: null});
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 2,
- ackMessageId: MESSAGE.older,
- });
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 3,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('shows a DM closed earlier in the session as unread when a message reopens it', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.older)]);
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.older,
- });
- expect(ReadStates.getOldestUnreadMessageId(CHANNEL.dm)).toBe(MESSAGE.incoming);
- });
-
- it('counts only the messages that arrive after a closed DM reopens', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.older)]);
- messageCreate(wireMessage(MESSAGE.last, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.older,
- });
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 2,
- ackMessageId: MESSAGE.older,
- });
- expect(ReadStates.getOldestUnreadMessageId(CHANNEL.dm)).toBe(MESSAGE.incoming);
- });
-
- it('hides a closed DM and brings its mentions back when a message reopens it', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older, 2)], [dm(CHANNEL.dm, MESSAGE.last)]);
- ReadStates.consumePendingChanges();
- const privateChannelVersion = ReadStates.privateChannelVersion;
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- expect(ReadStates.privateChannelVersion).toBe(privateChannelVersion + 1);
- expect(ReadStates.consumePendingChanges().changes).toEqual([{channelId: CHANNEL.dm, guildId: null}]);
- expect(unreadState(CHANNEL.dm)).toEqual({unread: false, unreadCount: 0, mentionCount: 0, ackMessageId: null});
- expect(ReadStates.mentionChannelIds).not.toContain(CHANNEL.dm);
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 3,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('keeps a closed DM out of every private channel count while its entry survives', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older, 2)], [dm(CHANNEL.dm, MESSAGE.last)]);
- expect(ReadStates.isUnreadOrMentioned(CHANNEL.dm)).toBe(true);
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- expect(ReadStates.getChannelIds()).toContain(CHANNEL.dm);
- expect(ReadStates.hasUnreadPrivateChannel(CHANNEL.dm)).toBe(false);
- expect(ReadStates.getPrivateChannelUnreadCount(CHANNEL.dm)).toBe(0);
- expect(ReadStates.getPrivateChannelMentionCount(CHANNEL.dm)).toBe(0);
- expect(ReadStates.isUnreadOrMentioned(CHANNEL.dm)).toBe(false);
- });
-
- it('forgets the view state of a DM when it is closed', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.last)]);
- const state = ReadStates.get(CHANNEL.dm);
- state.messagesLoaded = true;
- state.ackedManually = true;
- state.stickyUnreadMessageId = MESSAGE.last;
- state.unreadCount = 3;
- state.oldestUnreadMessageId = MESSAGE.last;
- state.estimated = true;
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- expect(ReadStates.getIfExists(CHANNEL.dm)).toMatchObject({
- messagesLoaded: false,
- ackedManually: false,
- stickyUnreadMessageId: null,
- ackMessageId: MESSAGE.older,
- unreadCount: 0,
- oldestUnreadMessageId: null,
- estimated: false,
- });
- });
-
- it('keeps an ack that arrives while the DM is closed', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older, 1)], [dm(CHANNEL.dm, MESSAGE.last)]);
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- ReadStates.handleMessageAck({
- channelId: CHANNEL.dm,
- messageId: MESSAGE.last,
- mentionCount: 0,
- manual: false,
- version: '2',
- });
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.last,
- });
- });
-
- it('ignores an older ack that arrives while the DM is closed', () => {
- ready([readState(CHANNEL.dm, MESSAGE.last, 1)], [dm(CHANNEL.dm, MESSAGE.last)]);
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- ReadStates.handleMessageAck({
- channelId: CHANNEL.dm,
- messageId: MESSAGE.older,
- mentionCount: 9,
- manual: false,
- version: '2',
- });
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 2,
- ackMessageId: MESSAGE.last,
- });
- });
-
- it('applies a manual ack that arrives while the DM is closed', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older, 2)], [dm(CHANNEL.dm, MESSAGE.last)]);
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- ReadStates.handleMessageAck({
- channelId: CHANNEL.dm,
- messageId: MESSAGE.last,
- mentionCount: 0,
- manual: true,
- version: '2',
- });
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.last,
- });
- });
-
- it('still sends the ack for a DM read and closed within the batch delay', async () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.last)]);
- ReadStates.handleChannelAck({channelId: CHANNEL.dm});
- channelDelete({id: CHANNEL.dm, type: ChannelTypes.DM});
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS);
- expect(http.post).toHaveBeenCalledWith(Endpoints.READ_STATES_ACK, {
- body: {read_states: [{channel_id: CHANNEL.dm, message_id: MESSAGE.last}]},
- });
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.last,
- });
- });
-
- it('shows the first messages from a new contact as unread mentions', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.newDm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.newDm, TUNA));
- expect(unreadState(CHANNEL.newDm)).toEqual({unread: true, unreadCount: 1, mentionCount: 1, ackMessageId: null});
- expect(ReadStates.getOldestUnreadMessageId(CHANNEL.newDm)).toBe(MESSAGE.incoming);
- messageCreate(wireMessage(MESSAGE.next, CHANNEL.newDm, TUNA));
- expect(unreadState(CHANNEL.newDm)).toEqual({unread: true, unreadCount: 2, mentionCount: 2, ackMessageId: null});
- });
-
- it('guesses the ack at the newest message for a mention-free DM without read state', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- loadedMessages.push({id: MESSAGE.last, author: {id: TUNA}}, {id: MESSAGE.incoming, author: {id: TUNA}});
- ReadStates.handleLoadMessages({channelId: CHANNEL.dm, messages: []});
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.incoming,
- });
- });
-
- it('characterisation: keeps a self-opened DM read when its read state covers the last message', () => {
- ready([readState(CHANNEL.dm, MESSAGE.last)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.last,
- });
- });
-
- it('shows a self-opened DM as unread when READY had it unread', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('shows a self-opened DM with history and no read state as unread', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({unread: true, unreadCount: 0, mentionCount: 0, ackMessageId: null});
- });
-
- it('keeps an open unread DM unread when a duplicate CHANNEL_CREATE arrives', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.last)]);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it("characterisation: acks the current user's first message in a new DM and counts the reply", () => {
- ready([], []);
- channelCreate(dm(CHANNEL.newDm, null));
- expect(ReadStates.hasUnread(CHANNEL.newDm)).toBe(false);
- messageCreate(wireMessage(MESSAGE.own, CHANNEL.newDm, ME));
- expect(unreadState(CHANNEL.newDm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.own,
- });
- messageCreate(wireMessage(MESSAGE.reply, CHANNEL.newDm, TUNA));
- expect(unreadState(CHANNEL.newDm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.own,
- });
- });
-
- it("acks the current user's message into a reopened DM that READY had unread", () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- expect(ReadStates.hasUnread(CHANNEL.dm)).toBe(true);
- messageCreate(wireMessage(MESSAGE.own, CHANNEL.dm, ME));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.own,
- });
- });
-
- it("characterisation: acks the current user's message that CHANNEL_CREATE already includes", () => {
- ready([], []);
- channelCreate(dm(CHANNEL.newDm, MESSAGE.own));
- messageCreate(wireMessage(MESSAGE.own, CHANNEL.newDm, ME));
- expect(unreadState(CHANNEL.newDm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.own,
- });
- });
-
- it('characterisation: counts only the recipient add message when the user joins a group DM with history', () => {
- ready([], []);
- channelCreate(groupDm(MESSAGE.last));
- expect(ReadStates.hasUnread(CHANNEL.groupDm)).toBe(true);
- messageCreate(recipientAddMessage());
- expect(unreadState(CHANNEL.groupDm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: null,
- });
- });
-
- it('characterisation: counts the recipient add message when the user joins an empty group DM', () => {
- ready([], []);
- channelCreate(groupDm(null));
- messageCreate(recipientAddMessage());
- expect(unreadState(CHANNEL.groupDm)).toEqual({unread: true, unreadCount: 1, mentionCount: 1, ackMessageId: null});
- });
-
- it('keeps the read state of a group DM the user leaves and rejoins', () => {
- ready([readState(CHANNEL.groupDm, MESSAGE.older)], [groupDm(MESSAGE.older)]);
- channelDelete({id: CHANNEL.groupDm, type: ChannelTypes.GROUP_DM});
- channelCreate(groupDm(MESSAGE.last));
- expect(unreadState(CHANNEL.groupDm)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.older,
- });
- messageCreate(recipientAddMessage());
- expect(unreadState(CHANNEL.groupDm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('characterisation: drops the pending ack of a group DM the user leaves', async () => {
- ready([readState(CHANNEL.groupDm, MESSAGE.older)], [groupDm(MESSAGE.last)]);
- ReadStates.handleChannelAck({channelId: CHANNEL.groupDm});
- channelDelete({id: CHANNEL.groupDm, type: ChannelTypes.GROUP_DM});
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS);
- expect(http.post).not.toHaveBeenCalled();
- });
-
- it('keeps the read state of personal notes closed and reopened', () => {
- const notes: WireChannel = {
- id: CHANNEL.notes,
- type: ChannelTypes.DM_PERSONAL_NOTES,
- last_message_id: MESSAGE.older,
- last_pin_timestamp: null,
- };
- ready([readState(CHANNEL.notes, MESSAGE.older)], [notes]);
- channelDelete({id: CHANNEL.notes, type: ChannelTypes.DM_PERSONAL_NOTES});
- channelCreate({...notes, last_message_id: MESSAGE.last});
- expect(unreadState(CHANNEL.notes)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('characterisation: acks own messages in personal notes', () => {
- ready([], []);
- channelCreate({
- id: CHANNEL.notes,
- type: ChannelTypes.DM_PERSONAL_NOTES,
- last_message_id: MESSAGE.own,
- last_pin_timestamp: null,
- });
- messageCreate(wireMessage(MESSAGE.own, CHANNEL.notes, ME));
- expect(unreadState(CHANNEL.notes)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.own,
- });
- });
-
- it('characterisation: auto-acks a message in the open DM pinned to the bottom', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], [dm(CHANNEL.dm, MESSAGE.older)]);
- ReadStates.handleLoadMessages({channelId: CHANNEL.dm, messages: []});
- automaticAck = true;
- pinnedToEnd = true;
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.incoming,
- });
- expect(ReadStates.getIfExists(CHANNEL.dm)?.inFlightAckMessageId).toBe(MESSAGE.incoming);
- });
-
- it('characterisation: keeps a DM reopened by a blocked author read', () => {
- blockedUserIds.add(TUNA);
- ready([readState(CHANNEL.dm, MESSAGE.older)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.incoming,
- });
- });
-
- it('characterisation: keeps a first DM from a blocked author read', () => {
- blockedUserIds.add(TUNA);
- ready([], []);
- channelCreate(dm(CHANNEL.newDm, MESSAGE.incoming));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.newDm, TUNA));
- expect(unreadState(CHANNEL.newDm)).toEqual({
- unread: false,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: MESSAGE.incoming,
- });
- });
-
- it('shows the call message that reopens a DM with read state as unread', () => {
- ready([readState(CHANNEL.dm, MESSAGE.older)], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA, {type: MessageTypes.CALL}));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: MESSAGE.older,
- });
- });
-
- it('characterisation: shows the call message that reopens a DM without read state as unread', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.dm, TUNA, {type: MessageTypes.CALL}));
- expect(unreadState(CHANNEL.dm)).toEqual({
- unread: true,
- unreadCount: 1,
- mentionCount: 1,
- ackMessageId: null,
- });
- });
-
- it('shows a guild message unread when there is no read state to cover it', () => {
- ready([], [guildText(MESSAGE.incoming)]);
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.guildText, TUNA, {guild_id: 'guild-1'}));
- expect(unreadState(CHANNEL.guildText)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: null,
- });
- });
-
- it('characterisation: still forgets a guild channel that a visibility change hides and shows again', () => {
- ready([readState(CHANNEL.guildText, MESSAGE.older, 2)], [guildText(MESSAGE.last)]);
- expect(unreadState(CHANNEL.guildText)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 2,
- ackMessageId: MESSAGE.older,
- });
- channelDelete({id: CHANNEL.guildText, guild_id: 'guild-1'});
- channelCreate(guildText(MESSAGE.last));
- expect(unreadState(CHANNEL.guildText)).toEqual({
- unread: true,
- unreadCount: 0,
- mentionCount: 0,
- ackMessageId: null,
- });
- });
-});
-
-describe('ReadStates ack floor for channels with no read state', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- ReadStates.clearAll();
- guilds.clear();
- vi.useRealTimers();
- });
-
- it('shows a guild channel unread when its newest message postdates the join', () => {
- guilds.set('guild-1', {joinedAt: '2026-09-01T00:00:00.000Z'});
- ready([], [guildText(MESSAGE.last)]);
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(true);
- });
-
- it('leaves a guild channel read when its newest message predates the join', () => {
- guilds.set('guild-1', {joinedAt: '2026-09-11T00:00:00.000Z'});
- ready([], [guildText(MESSAGE.last)]);
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(false);
- });
-
- it('falls back to the channel snowflake while its guild record is missing', () => {
- ready([], [guildText(MESSAGE.last)]);
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(true);
- });
-
- it('recomputes the floor once the guild record arrives instead of freezing it', () => {
- ready([], [guildText(MESSAGE.last)]);
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(true);
- guilds.set('guild-1', {joinedAt: '2026-09-11T00:00:00.000Z'});
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(false);
- });
-
- it('never lets the floor drift forward with the wall clock', () => {
- guilds.set('guild-1', {joinedAt: null});
- ready([], [guildText(MESSAGE.last)]);
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.guildText, TUNA, {guild_id: 'guild-1'}));
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(true);
- vi.advanceTimersByTime(60 * 60 * 1000);
- expect(ReadStates.hasUnread(CHANNEL.guildText)).toBe(true);
- expect(ReadStates.getUnreadCount(CHANNEL.guildText)).toBe(1);
- });
-
- it('counts only the messages that postdate the join', () => {
- guilds.set('guild-1', {joinedAt: '2026-09-10T21:00:00.000Z'});
- ready([], [guildText(MESSAGE.incoming)]);
- loadedMessages.push(
- {id: MESSAGE.older, author: {id: TUNA}},
- {id: MESSAGE.last, author: {id: TUNA}},
- {id: MESSAGE.incoming, author: {id: TUNA}},
- );
- ReadStates.handleLoadMessages({channelId: CHANNEL.guildText, messages: []});
- expect(ReadStates.getUnreadCount(CHANNEL.guildText)).toBe(2);
- expect(ReadStates.getOldestUnreadMessageId(CHANNEL.guildText)).toBe(MESSAGE.last);
- });
-
- it("never writes an ack for someone else's message in a channel with no read state", () => {
- guilds.set('guild-1', {joinedAt: '2026-09-01T00:00:00.000Z'});
- ready([], [guildText(MESSAGE.last)]);
- messageCreate(wireMessage(MESSAGE.incoming, CHANNEL.guildText, TUNA, {guild_id: 'guild-1'}));
- expect(ReadStates.ackMessageId(CHANNEL.guildText)).toBeNull();
- });
-});
-
-describe('ReadStates guessed ack for private channels', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- ReadStates.clearAll();
- vi.useRealTimers();
- });
-
- it('takes the newest message as the ack when a DM has no mentions', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- loadedMessages.push({id: MESSAGE.older, author: {id: TUNA}}, {id: MESSAGE.last, author: {id: TUNA}});
- ReadStates.handleLoadMessages({channelId: CHANNEL.dm, messages: []});
- expect(ReadStates.ackMessageId(CHANNEL.dm)).toBe(MESSAGE.last);
- expect(ReadStates.hasUnread(CHANNEL.dm)).toBe(false);
- });
-
- it('walks back one message per mention, skipping the current user', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.incoming));
- loadedMessages.push(
- {id: MESSAGE.older, author: {id: TUNA}},
- {id: MESSAGE.last, author: {id: ME}},
- {id: MESSAGE.incoming, author: {id: TUNA}},
- );
- const state = ReadStates.get(CHANNEL.dm);
- state.mentionCount = 1;
- state.rebuild();
- expect(ReadStates.ackMessageId(CHANNEL.dm)).toBe(MESSAGE.last);
- });
-
- it('leaves the ack null when the window does not reach the newest message', () => {
- ready([], []);
- channelCreate(dm(CHANNEL.dm, MESSAGE.last));
- hasNewestMessages = false;
- loadedMessages.push({id: MESSAGE.older, author: {id: TUNA}});
- ReadStates.handleLoadMessages({channelId: CHANNEL.dm, messages: []});
- expect(ReadStates.ackMessageId(CHANNEL.dm)).toBeNull();
- });
-});
-
-describe('ReadStates thread seeding', () => {
- const THREAD = '1547743600000000000';
- const PARENT = '1547743500000000000';
-
- function threadChannel(lastMessageId: string | null, overrides: Partial<WireChannel> = {}): WireChannel {
- return {
- id: THREAD,
- guild_id: 'guild-1',
- parent_id: PARENT,
- type: ChannelTypes.PUBLIC_THREAD,
- last_message_id: lastMessageId,
- last_pin_timestamp: null,
- ...overrides,
- };
- }
-
- afterEach(() => {
- ReadStates.clearAll();
- });
-
- it('seeds READY threads like text channels so an unacked thread is unread', () => {
- ready([{id: THREAD, last_message_id: MESSAGE.last, mention_count: 1}], [threadChannel(MESSAGE.incoming)]);
- expect(ReadStates.lastMessageId(THREAD)).toBe(MESSAGE.incoming);
- expect(ReadStates.hasUnread(THREAD)).toBe(true);
- expect(ReadStates.getMentionCount(THREAD)).toBe(1);
- });
-
- it('keeps an unknown thread read state for when the thread loads', () => {
- ready([{id: THREAD, last_message_id: MESSAGE.last, mention_count: 0}], []);
- channelCreate(threadChannel(MESSAGE.last));
- expect(ReadStates.ackMessageId(THREAD)).toBe(MESSAGE.last);
- expect(ReadStates.hasUnread(THREAD)).toBe(false);
- });
-
- it('never walks the thread last message id back on a thread update', () => {
- ready([{id: THREAD, last_message_id: MESSAGE.last, mention_count: 0}], [threadChannel(MESSAGE.incoming)]);
- channelCreate(threadChannel(MESSAGE.last));
- expect(ReadStates.lastMessageId(THREAD)).toBe(MESSAGE.incoming);
- expect(ReadStates.hasUnread(THREAD)).toBe(true);
- });
-
- it('restores the ack of a purged thread when it comes back', () => {
- ready([{id: THREAD, last_message_id: MESSAGE.last, mention_count: 0}], [threadChannel(MESSAGE.last)]);
- channelDelete({id: THREAD, type: ChannelTypes.PUBLIC_THREAD, guild_id: 'guild-1'});
- expect(ReadStates.getIfExists(THREAD)).toBeUndefined();
- channelCreate(threadChannel(MESSAGE.incoming));
- expect(ReadStates.ackMessageId(THREAD)).toBe(MESSAGE.last);
- expect(ReadStates.hasUnread(THREAD)).toBe(true);
- expect(vi.mocked(http.post)).not.toHaveBeenCalled();
- });
-
- it('applies passive last message updates to threads of the guild', () => {
- ready([{id: THREAD, last_message_id: MESSAGE.last, mention_count: 0}], [threadChannel(MESSAGE.last)]);
- ReadStates.handlePassiveLastMessageUpdates({[THREAD]: MESSAGE.incoming}, 'guild-1');
- expect(ReadStates.hasUnread(THREAD)).toBe(true);
- });
-
- it('leaves control channel seeding untouched', () => {
- ready([], [{id: CHANNEL.guildText, guild_id: 'guild-1', type: ChannelTypes.GUILD_TEXT, last_message_id: null}]);
- ReadStates.handleGuildCreate({
- guild: {
- id: 'guild-1',
- channels: [{id: CHANNEL.guildText, type: ChannelTypes.GUILD_TEXT, last_message_id: MESSAGE.last}],
- },
- });
- expect(ReadStates.lastMessageId(CHANNEL.guildText)).toBe(MESSAGE.last);
- expect(ReadStates.getIfExists(THREAD)).toBeUndefined();
- });
-});
-
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/features/user/commands/UserGuildSettingsCommands', () => ({updateChannelOverride: vi.fn()}));
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({default: {foregroundConnection: {}}}));
-vi.mock('@app/features/threads/state/ThreadGuilds', () => ({default: {isActive: () => true}}));
-
-describe('ReadStates forum read state', () => {
- const FORUM = '1547743400000000000';
- const OLD_POST = '1547743000000000000';
- const NEW_POST = '1547743701495717888';
-
- function forumChannel(lastMessageId: string | null): WireChannel {
- return {
- id: FORUM,
- guild_id: 'guild-1',
- type: ChannelTypes.GUILD_FORUM,
- name: 'forum',
- last_message_id: lastMessageId,
- last_pin_timestamp: null,
- };
- }
-
- function post(id: string, ownerId: string): Channel {
- return new Channel({
- id,
- guild_id: 'guild-1',
- parent_id: FORUM,
- owner_id: ownerId,
- type: ChannelTypes.PUBLIC_THREAD,
- });
- }
-
- afterEach(async () => {
- const {default: ForumReadState} = await import('@app/features/forum/state/ForumReadState');
- ForumReadState.endViewing(FORUM);
- ReadStates.clearAll();
- });
-
- it('seeds a forum from READY so a post newer than the ack makes it unread', () => {
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], [forumChannel(NEW_POST)]);
- expect(ReadStates.lastMessageId(FORUM)).toBe(NEW_POST);
- expect(ReadStates.hasUnread(FORUM)).toBe(true);
- });
-
- it('seeds a forum from GUILD_CREATE', () => {
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], []);
- ReadStates.handleGuildCreate({guild: {id: 'guild-1', channels: [forumChannel(NEW_POST)]}});
- expect(ReadStates.hasUnread(FORUM)).toBe(true);
- });
-
- it('never walks the newest post back on a forum update without it', () => {
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], [forumChannel(NEW_POST)]);
- channelCreate(forumChannel(OLD_POST));
- expect(ReadStates.lastMessageId(FORUM)).toBe(NEW_POST);
- expect(ReadStates.hasUnread(FORUM)).toBe(true);
- });
-
- it('reads the forum once it is acked', () => {
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], [forumChannel(NEW_POST)]);
- ReadStates.handleChannelAck({channelId: FORUM});
- expect(ReadStates.ackMessageId(FORUM)).toBe(NEW_POST);
- expect(ReadStates.hasUnread(FORUM)).toBe(false);
- });
-
- it('keeps the New snapshot at the ack from before the forum was opened', async () => {
- const {default: ForumReadState} = await import('@app/features/forum/state/ForumReadState');
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], [forumChannel(NEW_POST)]);
- ForumReadState.beginViewing(FORUM);
- ReadStates.handleChannelAck({channelId: FORUM});
- expect(ForumReadState.getSnapshot(FORUM)).toBe(OLD_POST);
- expect(ForumReadState.isNewPost(post(NEW_POST, 'someone'))).toBe(true);
- expect(ForumReadState.isNewPost(post(OLD_POST, 'someone'))).toBe(false);
- expect(ForumReadState.isNewPost(post(NEW_POST, 'me'))).toBe(false);
- ForumReadState.endViewing(FORUM);
- ForumReadState.beginViewing(FORUM);
- expect(ForumReadState.isNewPost(post(NEW_POST, 'someone'))).toBe(false);
- });
-
- it('marks nothing new while the forum is not open', async () => {
- const {default: ForumReadState} = await import('@app/features/forum/state/ForumReadState');
- ready([{id: FORUM, last_message_id: OLD_POST, mention_count: 0}], [forumChannel(NEW_POST)]);
- expect(ForumReadState.isNewPost(post(NEW_POST, 'someone'))).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/ReadStatesAckQueue.test.ts b/fluxer_app/src/features/read_state/state/ReadStatesAckQueue.test.ts
deleted file mode 100644
index 2d0d7f9a9..000000000
--- a/fluxer_app/src/features/read_state/state/ReadStatesAckQueue.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface AckRequestBody {
- read_states: Array<{channel_id: string; message_id: string}>;
-}
-
-const makeChannel = (id: string) => ({
- id,
- type: 0,
- guildId: 'guild-1',
- isPrivate: () => false,
- getGuildId: () => 'guild-1',
-});
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => makeChannel(id), getBasicChannel: (id: string) => makeChannel(id)},
-}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {
- getMessages: () => ({
- hasMoreBefore: false,
- length: 0,
- jumpDestinationId: null,
- hasNewestMessages: () => true,
- has: () => false,
- last: () => undefined,
- forEachBuffered: () => undefined,
- }),
- },
-}));
-let currentUserId = 'me';
-vi.mock('@app/features/user/state/Users', () => ({default: {getCurrentUser: () => ({id: currentUserId})}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: () => undefined}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => null}}));
-vi.mock('@app/features/user/state/UserGuildSettings', () => ({
- default: {
- isEveryoneMentionSuppressed: () => false,
- isRoleMentionSuppressed: () => false,
- isGuildOrChannelMuted: () => false,
- },
-}));
-vi.mock('@app/features/ui/state/Dimension', () => ({default: {channelPinnedToEnd: () => false}}));
-vi.mock('@app/features/notification/state/NotificationAutoAck', () => ({
- default: {isAutomaticAckEnabled: () => false, disableForChannel: () => undefined},
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {post: vi.fn(async () => ({body: {read_states: []}})), get: vi.fn()},
-}));
-
-const {default: ReadStates} = await import('@app/features/read_state/state/ReadStates');
-const {Endpoints} = await import('@app/features/app/constants/Endpoints');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-const post = vi.mocked(http.post);
-
-const ID = {
- ack: '1519773906704011264',
- newer: '1519773906708205568',
-};
-
-let nextChannelId = 0;
-
-function seedReadChannel() {
- const channelId = `ack-channel-${++nextChannelId}`;
- const state = ReadStates.get(channelId);
- state.ackMessageId = ID.ack;
- state.lastMessageId = ID.ack;
- state.unreadCount = 0;
- state.oldestUnreadMessageId = null;
- return {channelId, state};
-}
-
-function ackedMessageIdsFor(channelId: string): Array<string> {
- return post.mock.calls
- .filter(([url]) => url === Endpoints.READ_STATES_ACK)
- .flatMap(([, options]) => (options?.body as AckRequestBody | undefined)?.read_states ?? [])
- .filter((entry) => entry.channel_id === channelId)
- .map((entry) => entry.message_id);
-}
-
-function hydrateReadChannelSnapshot(channelId: string): void {
- ReadStates.hydrateFromSnapshot(
- new Map([
- [
- channelId,
- {
- ackMessageId: ID.ack,
- ackPinTimestamp: 0,
- mentionCount: 0,
- serverVersion: null,
- readStateKnown: true,
- lastMessageId: ID.ack,
- guildId: 'guild-1',
- },
- ],
- ]),
- );
-}
-
-describe('ReadStates ack queue across gateway ready', () => {
- beforeEach(() => {
- currentUserId = 'me';
- post.mockClear();
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.clearAllTimers();
- vi.useRealTimers();
- });
-
- it('flushes a queued ack before gateway ready reseeds the store', async () => {
- const {channelId} = seedReadChannel();
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- ReadStates.handleGatewayReady({readState: [{id: channelId, last_message_id: ID.ack}], channels: []});
- expect(ackedMessageIdsFor(channelId)).toEqual([ID.newer]);
- await vi.advanceTimersByTimeAsync(0);
- });
-
- it('keeps a queued ack across gateway ready even while an earlier ack is still in flight', async () => {
- const {channelId: stalledChannelId} = seedReadChannel();
- const {channelId} = seedReadChannel();
- const stalledPost: {release: () => void} = {release: () => undefined};
- post.mockImplementationOnce(
- async () =>
- await new Promise((resolve) => {
- stalledPost.release = () => resolve({body: {}} as never);
- }),
- );
- ReadStates.handleChannelAck({channelId: stalledChannelId, messageId: ID.newer});
- await vi.advanceTimersByTimeAsync(3000);
-
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- ReadStates.handleGatewayReady({readState: [{id: channelId, last_message_id: ID.ack}], channels: []});
- stalledPost.release();
- await vi.advanceTimersByTimeAsync(5000);
-
- expect(ackedMessageIdsFor(channelId)).toContain(ID.newer);
- });
-
- it('does not carry a queued ack across an account switch', async () => {
- const {channelId} = seedReadChannel();
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- post.mockClear();
-
- currentUserId = 'someone-else';
- ReadStates.handleGatewayReady({readState: [{id: channelId, last_message_id: ID.ack}], channels: []});
- await vi.advanceTimersByTimeAsync(5000);
-
- expect(ackedMessageIdsFor(channelId)).toEqual([]);
- });
-
- it('flushes a queued ack before a snapshot hydrate reseeds the store', async () => {
- const {channelId} = seedReadChannel();
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- hydrateReadChannelSnapshot(channelId);
- expect(ackedMessageIdsFor(channelId)).toEqual([ID.newer]);
- await vi.advanceTimersByTimeAsync(0);
- });
-
- it('does not carry a queued ack across an account switch snapshot hydrate', async () => {
- const {channelId} = seedReadChannel();
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- post.mockClear();
-
- currentUserId = 'someone-else';
- hydrateReadChannelSnapshot(channelId);
- await vi.advanceTimersByTimeAsync(5000);
-
- expect(ackedMessageIdsFor(channelId)).toEqual([]);
- });
-
- it('drops a queued ack the server already covers', async () => {
- const {channelId} = seedReadChannel();
- ReadStates.handleChannelAck({channelId, messageId: ID.newer});
- post.mockClear();
-
- ReadStates.handleGatewayReady({readState: [{id: channelId, last_message_id: ID.newer}], channels: []});
- await vi.advanceTimersByTimeAsync(5000);
-
- expect(ackedMessageIdsFor(channelId)).toEqual([]);
- });
-});