Skip to content

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

TypeScript fluxerfluxerapp

test(app): remove app shell, gateway, router and worker tests

Hampus41e0bbc2a076
diff --git a/fluxer_app/src/features/app/components/BootstrapErrorKind.test.ts b/fluxer_app/src/features/app/components/BootstrapErrorKind.test.ts
deleted file mode 100644
index 0641478eb..000000000
--- a/fluxer_app/src/features/app/components/BootstrapErrorKind.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {BootstrapErrorKind, classifyBootstrapError} from '@app/features/app/components/BootstrapErrorKind';
-import {InstanceDiscoveryUnreachableError} from '@fluxer/instance_bootstrap/src/Discovery';
-import {expect, test} from 'vitest';
-
-const DESKTOP_UNREACHABLE = new Error(
- "Error invoking remote method 'desktop-runtime-config:resolve': DesktopRuntimeDiscoveryUnreachableError: No usable instance discovery document was served for https://web.canary.fluxer.app/api: https://web.canary.fluxer.app/.well-known/fluxer (connect ECONNREFUSED 127.0.0.1:9)",
-);
-
-test('a desktop discovery that could not reach the instance is a connection failure', () => {
- expect(classifyBootstrapError(DESKTOP_UNREACHABLE, true)).toBe(BootstrapErrorKind.UNREACHABLE);
-});
-
-test('a web discovery that no candidate served is a connection failure', () => {
- const error = new InstanceDiscoveryUnreachableError([{url: 'https://one.example', reason: 'Failed to fetch'}]);
-
- expect(classifyBootstrapError(error, true)).toBe(BootstrapErrorKind.UNREACHABLE);
-});
-
-test('an unreachable instance wrapped as a cause or inside an aggregate is still a connection failure', () => {
- const wrapped = new Error('Failed to restore the session', {cause: DESKTOP_UNREACHABLE});
- const aggregate = new AggregateError([new Error('cancellation was rejected'), wrapped], 'Instance discovery failed');
-
- expect(classifyBootstrapError(wrapped, true)).toBe(BootstrapErrorKind.UNREACHABLE);
- expect(classifyBootstrapError(aggregate, true)).toBe(BootstrapErrorKind.UNREACHABLE);
-});
-
-test('any failure while the device is offline is a connection failure', () => {
- expect(classifyBootstrapError(new TypeError('Failed to fetch'), false)).toBe(BootstrapErrorKind.UNREACHABLE);
-});
-
-test('an instance that answered without a usable document, or a local failure, is not a connection failure', () => {
- const refused = new Error(
- "Error invoking remote method 'desktop-runtime-config:resolve': DesktopRuntimeDiscoveryFailedError: No usable instance discovery document was served for https://one.example/api: https://one.example/.well-known/fluxer (responded HTTP 404)",
- );
-
- expect(classifyBootstrapError(refused, true)).toBe(BootstrapErrorKind.FAILED);
- expect(classifyBootstrapError(new Error('Stored account record is malformed'), true)).toBe(BootstrapErrorKind.FAILED);
- expect(classifyBootstrapError('boom', true)).toBe(BootstrapErrorKind.FAILED);
-});
diff --git a/fluxer_app/src/features/app/components/HookOrderStability.test.ts b/fluxer_app/src/features/app/components/HookOrderStability.test.ts
deleted file mode 100644
index 06e67b389..000000000
--- a/fluxer_app/src/features/app/components/HookOrderStability.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync, statSync} from 'node:fs';
-import {join, relative} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {parse} from '@babel/parser';
-import {describe, expect, it} from 'vitest';
-
-interface AstNode {
- type?: string;
- start?: number | null;
- end?: number | null;
- loc?: {
- start: {
- line: number;
- };
- };
- [key: string]: unknown;
-}
-
-interface HookOrderFinding {
- file: string;
- functionName: string;
- returnLine: number;
- hookLine: number;
- hookName: string;
-}
-
-const SRC_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
-const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx']);
-
-function listSourceFiles(directory: string): Array<string> {
- return readdirSync(directory).flatMap((entry) => {
- const filePath = join(directory, entry);
- const stats = statSync(filePath);
- if (stats.isDirectory()) {
- return listSourceFiles(filePath);
- }
- if (!stats.isFile()) {
- return [];
- }
- const extension = filePath.endsWith('.tsx') ? '.tsx' : filePath.endsWith('.ts') ? '.ts' : '';
- if (!SOURCE_EXTENSIONS.has(extension)) {
- return [];
- }
- return [filePath];
- });
-}
-
-function isFunctionNode(node: AstNode | null | undefined): boolean {
- return Boolean(
- node &&
- (node.type === 'FunctionDeclaration' ||
- node.type === 'FunctionExpression' ||
- node.type === 'ArrowFunctionExpression' ||
- node.type === 'ObjectMethod' ||
- node.type === 'ClassMethod'),
- );
-}
-
-const REACT_HOOK_NAMESPACES = new Set(['React']);
-
-function isReactHookNamespace(object: AstNode | null | undefined): boolean {
- if (object?.type !== 'Identifier' || typeof object.name !== 'string') {
- return false;
- }
- return REACT_HOOK_NAMESPACES.has(object.name);
-}
-
-function getCalleeName(callee: AstNode | null | undefined): string | null {
- if (!callee) {
- return null;
- }
- if (callee.type === 'Identifier' && typeof callee.name === 'string') {
- return callee.name;
- }
- if (
- callee.type === 'MemberExpression' &&
- callee.computed !== true &&
- typeof callee.property === 'object' &&
- callee.property !== null &&
- isReactHookNamespace(callee.object as AstNode)
- ) {
- return getCalleeName(callee.property as AstNode);
- }
- return null;
-}
-
-function isHookName(name: string | null): name is string {
- return Boolean(name && (name === 'use' || /^use[A-Z0-9]/.test(name)));
-}
-
-function isLikelyReactFunctionName(name: string): boolean {
- return name === '<anonymous>' || /^[A-Z]/.test(name) || /^use[A-Z0-9]/.test(name);
-}
-
-function getFunctionName(node: AstNode, parent: AstNode | null | undefined): string {
- if (typeof node.id === 'object' && node.id && typeof (node.id as AstNode).name === 'string') {
- return (node.id as AstNode).name as string;
- }
- if (parent?.type === 'VariableDeclarator' && typeof parent.id === 'object' && parent.id) {
- const id = parent.id as AstNode;
- return typeof id.name === 'string' ? id.name : '<anonymous>';
- }
- if (parent?.type === 'CallExpression') {
- return getFunctionName(parent, parent.__parent as AstNode | null | undefined);
- }
- if (parent?.type === 'ExportNamedDeclaration') {
- return getFunctionName(node, parent.__parent as AstNode | null | undefined);
- }
- return '<anonymous>';
-}
-
-function walk(
- node: AstNode | null | undefined,
- visitor: (node: AstNode, parent: AstNode | null) => void,
- parent: AstNode | null = null,
-) {
- if (!node || typeof node !== 'object') {
- return;
- }
- node.__parent = parent;
- visitor(node, parent);
- for (const [key, value] of Object.entries(node)) {
- if (key === 'loc' || key === 'start' || key === 'end' || key === '__parent') {
- continue;
- }
- if (Array.isArray(value)) {
- for (const child of value) {
- if (child && typeof child === 'object' && typeof child.type === 'string') {
- walk(child as AstNode, visitor, node);
- }
- }
- } else if (value && typeof value === 'object' && typeof (value as AstNode).type === 'string') {
- walk(value as AstNode, visitor, node);
- }
- }
-}
-
-function collectReturnsAndHooks(functionNode: AstNode): {returns: Array<AstNode>; hooks: Array<AstNode>} {
- const returns: Array<AstNode> = [];
- const hooks: Array<AstNode> = [];
- function visit(node: AstNode | null | undefined) {
- if (!node || typeof node !== 'object') {
- return;
- }
- if (node !== functionNode && isFunctionNode(node)) {
- return;
- }
- if (node.type === 'ReturnStatement') {
- returns.push(node);
- }
- if (node.type === 'CallExpression') {
- const hookName = getCalleeName(node.callee as AstNode | null | undefined);
- if (isHookName(hookName)) {
- hooks.push(node);
- }
- }
- for (const [key, value] of Object.entries(node)) {
- if (key === 'loc' || key === 'start' || key === 'end' || key === '__parent') {
- continue;
- }
- if (Array.isArray(value)) {
- for (const child of value) {
- if (child && typeof child === 'object' && typeof child.type === 'string') {
- visit(child as AstNode);
- }
- }
- } else if (value && typeof value === 'object' && typeof (value as AstNode).type === 'string') {
- visit(value as AstNode);
- }
- }
- }
- visit(functionNode.body as AstNode | null | undefined);
- return {returns, hooks};
-}
-
-function findHookOrderHazards(): Array<HookOrderFinding> {
- const findings: Array<HookOrderFinding> = [];
- for (const file of listSourceFiles(SRC_ROOT)) {
- const source = readFileSync(file, 'utf8');
- const ast = parse(source, {
- sourceType: 'module',
- plugins: file.endsWith('.tsx') ? ['typescript', 'jsx'] : ['typescript'],
- }) as unknown as AstNode;
- walk(ast, (node, parent) => {
- if (!isFunctionNode(node)) {
- return;
- }
- const functionName = getFunctionName(node, parent);
- if (!isLikelyReactFunctionName(functionName)) {
- return;
- }
- const {returns, hooks} = collectReturnsAndHooks(node);
- for (const hook of hooks) {
- const hookStart = hook.start ?? 0;
- const earlierReturn = returns.find((returnNode) => (returnNode.end ?? 0) < hookStart);
- if (!earlierReturn) {
- continue;
- }
- findings.push({
- file: relative(SRC_ROOT, file),
- functionName,
- returnLine: earlierReturn.loc?.start.line ?? 0,
- hookLine: hook.loc?.start.line ?? 0,
- hookName: getCalleeName(hook.callee as AstNode | null | undefined) ?? '<unknown>',
- });
- return;
- }
- });
- }
- return findings;
-}
-
-describe('React hook order stability', () => {
- it('keeps guard returns outside hook-bearing component bodies', () => {
- expect(findHookOrderHazards()).toEqual([]);
- }, 60_000);
-});
diff --git a/fluxer_app/src/features/app/components/layout/UserAreaState.test.ts b/fluxer_app/src/features/app/components/layout/UserAreaState.test.ts
deleted file mode 100644
index 2cfd36c63..000000000
--- a/fluxer_app/src/features/app/components/layout/UserAreaState.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- selectUserAreaMicrophoneState,
- type UserAreaMicrophoneSignals,
-} from '@app/features/app/components/layout/UserAreaState';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<UserAreaMicrophoneSignals>): UserAreaMicrophoneSignals {
- return {
- effectiveAudioMuted: false,
- effectiveAudioDeafened: false,
- isGuildMuted: false,
- isGuildDeafened: false,
- isPermissionMuted: false,
- muteReason: null,
- isPushToTalkEffective: false,
- isPushToMuteEffective: false,
- isPushToMuteHeld: false,
- ...overrides,
- };
-}
-
-describe('selectUserAreaMicrophoneState', () => {
- it('shows the idle push to talk gate as unmuted without locking the toggle', () => {
- expect(
- selectUserAreaMicrophoneState(signals({isPushToTalkEffective: true, muteReason: 'voice_push_to_talk'})),
- ).toEqual({effectiveMuted: false, muteToggleLocked: false});
- });
-
- it('shows a self-muted push to talk user as muted', () => {
- expect(
- selectUserAreaMicrophoneState(
- signals({isPushToTalkEffective: true, effectiveAudioMuted: true, muteReason: 'self'}),
- ),
- ).toEqual({effectiveMuted: true, muteToggleLocked: false});
- });
-
- it('shows a push to talk user muted by the failure latch as muted', () => {
- expect(selectUserAreaMicrophoneState(signals({isPushToTalkEffective: true, muteReason: 'self'}))).toEqual({
- effectiveMuted: true,
- muteToggleLocked: false,
- });
- });
-
- it('lets a self-deafened push to talk user click the toggle', () => {
- expect(
- selectUserAreaMicrophoneState(
- signals({isPushToTalkEffective: true, effectiveAudioMuted: true, effectiveAudioDeafened: true}),
- ),
- ).toEqual({effectiveMuted: true, muteToggleLocked: false});
- });
-
- it('locks the toggle for server and permission mutes in push to talk', () => {
- for (const overrides of [
- {isGuildMuted: true, muteReason: 'guild' as const},
- {isGuildDeafened: true},
- {isPermissionMuted: true, muteReason: 'permission' as const},
- ]) {
- expect(selectUserAreaMicrophoneState(signals({isPushToTalkEffective: true, ...overrides}))).toEqual({
- effectiveMuted: true,
- muteToggleLocked: true,
- });
- }
- });
-
- it('keeps voice activity and push to mute behaviour unchanged', () => {
- expect(selectUserAreaMicrophoneState(signals({}))).toEqual({effectiveMuted: false, muteToggleLocked: false});
- expect(selectUserAreaMicrophoneState(signals({effectiveAudioMuted: true, muteReason: 'self'}))).toEqual({
- effectiveMuted: true,
- muteToggleLocked: false,
- });
- expect(selectUserAreaMicrophoneState(signals({isPushToMuteEffective: true, isPushToMuteHeld: true}))).toEqual({
- effectiveMuted: true,
- muteToggleLocked: false,
- });
- expect(selectUserAreaMicrophoneState(signals({isGuildMuted: true}))).toEqual({
- effectiveMuted: true,
- muteToggleLocked: true,
- });
- });
-});
diff --git a/fluxer_app/src/features/app/components/setup/SetupWizardStateMachine.test.ts b/fluxer_app/src/features/app/components/setup/SetupWizardStateMachine.test.ts
deleted file mode 100644
index a1973826a..000000000
--- a/fluxer_app/src/features/app/components/setup/SetupWizardStateMachine.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createSetupWizardSnapshot,
- type SetupWizardSnapshot,
- selectSetupWizardModel,
- transitionSetupWizardSnapshot,
-} from '@app/features/app/components/setup/SetupWizardStateMachine';
-import {runtimeSnapshotFromDiscovery} from '@app/features/app/state/InstanceSnapshotStore';
-import {instanceDiscoveryFixture} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
-import {parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
-import {describe, expect, test} from 'vitest';
-
-function registerSnapshot(setupTokenRequired: boolean): SetupWizardSnapshot {
- return transitionSetupWizardSnapshot(createSetupWizardSnapshot(), {
- type: 'wizard.sync',
- isAuthenticated: false,
- hasConfig: false,
- accountIdentity: AccountIdentityModes.USERNAME,
- identityLocked: false,
- setupTokenRequired,
- });
-}
-
-describe('setup wizard setup token step', () => {
- test('follows the welcome step when the discovery document requires the token', () => {
- const wire = instanceDiscoveryFixture('https://chat.example.test/api');
- wire.app_public = {
- ...wire.app_public,
- setup: {configured: false, admin_url: null, account_identity_locked: false, setup_token_required: true},
- };
- const setup = runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(wire)).appPublic.setup;
- expect(setup.setup_token_required).toBe(true);
- expect(selectSetupWizardModel(registerSnapshot(setup.setup_token_required === true)).steps).toEqual([
- 'welcome',
- 'setup_token',
- 'theme',
- 'sign_in_method',
- 'admin_intro',
- 'admin_account',
- ]);
- });
-
- test('opens after a rejection while the client believes no token is required', () => {
- let snapshot = registerSnapshot(false);
- snapshot = transitionSetupWizardSnapshot(snapshot, {type: 'wizard.next'});
- snapshot = transitionSetupWizardSnapshot(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('sign_in_method');
- snapshot = transitionSetupWizardSnapshot(snapshot, {type: 'wizard.setupTokenRejected'});
- snapshot = transitionSetupWizardSnapshot(snapshot, {
- type: 'wizard.sync',
- isAuthenticated: false,
- hasConfig: false,
- accountIdentity: AccountIdentityModes.USERNAME,
- identityLocked: false,
- setupTokenRequired: false,
- });
- const model = selectSetupWizardModel(snapshot);
- expect(model.step).toBe('setup_token');
- expect(model.steps[model.stepIndex + 1]).toBe('theme');
- });
-});
diff --git a/fluxer_app/src/features/app/domain_migration/DomainMigration.test.ts b/fluxer_app/src/features/app/domain_migration/DomainMigration.test.ts
deleted file mode 100644
index e2716722a..000000000
--- a/fluxer_app/src/features/app/domain_migration/DomainMigration.test.ts
+++ /dev/null
@@ -1,880 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- collectExportableAppStorage,
- writeImportedAppStorage,
-} from '@app/features/app/domain_migration/DomainMigrationAppStorage';
-import {
- detectDomainMigrationInstallKind,
- readDomainMigrationDiscovery,
-} from '@app/features/app/domain_migration/DomainMigrationBrowser';
-import * as core from '@app/features/app/domain_migration/DomainMigrationCore';
-import {
- decryptDomainMigrationPayload,
- encryptDomainMigrationPayload,
-} from '@app/features/app/domain_migration/DomainMigrationCrypto';
-import {runDomainMigrationPreMount} from '@app/features/app/domain_migration/DomainMigrationPreMount';
-import InstanceSnapshotStore from '@app/features/app/state/InstanceSnapshotStore';
-import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';
-import type {StoredAccount} from '@app/features/auth/state/AccountStorageContract';
-import {accountStorageKey} from '@app/features/auth/state/AccountStorageKey';
-import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';
-import {LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY} from '@app/features/platform/state/LegacyAppStorageMigration';
-import {createPersistentStorageBackend} from '@app/features/platform/state/PersistentStorageBackend';
-import {DEPLOYED_OFFICIAL_DOCUMENT} from '@fluxer/instance_bootstrap/src/__tests__/DiscoveryFixtures';
-import type {DomainMigrationDiscoveryResponse} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
-import {experimentBucket} from '@fluxer/schema/src/domains/experiment/ExperimentBucket';
-import {runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-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/auth/state/AccountStorage', () => ({
- default: {getAllAccounts: async () => ({records: [], source: 'idb'})},
-}));
-
-const ENABLED_DISCOVERY: DomainMigrationDiscoveryResponse = {
- enabled: true,
- anonymous_rollout_basis_points: 0,
- rollout_salt: 'domain-migration-v1',
- standalone_forwarding: false,
-};
-
-const NOW = 1_800_000_000_000;
-
-function memoryStorage(initial: Record<string, string> = {}): core.StorageLike {
- const entries = new Map(Object.entries(initial));
- return {
- getItem: (key) => entries.get(key) ?? null,
- setItem: (key, value) => {
- entries.set(key, value);
- },
- removeItem: (key) => {
- entries.delete(key);
- },
- key: (index) => [...entries.keys()][index] ?? null,
- get length() {
- return entries.size;
- },
- };
-}
-
-function environment(
- installKind: core.DomainMigrationInstallKind,
- overrides: Partial<core.DomainMigrationEnvironment> = {},
-): core.DomainMigrationEnvironment {
- return {installKind, electron: false, ...overrides};
-}
-
-function gateInput(overrides: Partial<core.DomainMigrationGateInput> = {}): core.DomainMigrationGateInput {
- return {
- environment: environment('none'),
- assignmentEnabled: true,
- discovery: ENABLED_DISCOVERY,
- marker: null,
- now: NOW,
- voiceActive: false,
- oneShotRoute: false,
- ...overrides,
- };
-}
-
-describe('sanitizeNextPath', () => {
- it.each([
- ['/channels/123/456?x=1#y', '/channels/123/456?x=1#y'],
- ['/reset#token=abc', '/reset#token=abc'],
- ['/', '/app'],
- ['/?a=1', '/app?a=1'],
- ['//evil.example', '/channels/@me'],
- ['/\\evil.example', '/channels/@me'],
- ['/migrate/begin', '/channels/@me'],
- ['/migrate', '/channels/@me'],
- ['/\t/evil.example', '/channels/@me'],
- ['/\n/evil.example', '/channels/@me'],
- ['/\r/evil.example', '/channels/@me'],
- ['/\tmigrate/done', '/channels/@me'],
- ['/channels/\u0000', '/channels/@me'],
- ['/a/../migrate/done', '/channels/@me'],
- ['/%09/evil.example', '/%09/evil.example'],
- ['https://evil.example/', '/channels/@me'],
- ['channels/@me', '/channels/@me'],
- [null, '/channels/@me'],
- [42, '/channels/@me'],
- ])('maps %j to %j', (input, expected) => {
- expect(core.sanitizeNextPath(input)).toBe(expected);
- });
-
- it('never leaves the origin it is resolved against', () => {
- for (const input of ['/\t/evil.example', '/\n/evil.example', '/%09/evil.example', '/@evil.example']) {
- expect(new URL(core.sanitizeNextPath(input), 'https://web.fluxer.app/x').origin).toBe('https://web.fluxer.app');
- }
- });
-});
-
-describe('resolveDomainMigrationSide', () => {
- it('recognises only the four official origins', () => {
- expect(core.resolveDomainMigrationSide('https://web.fluxer.app')).toEqual({
- role: 'source',
- source: 'https://web.fluxer.app',
- target: 'https://fluxer.com',
- });
- expect(core.resolveDomainMigrationSide('https://canary.fluxer.com')).toEqual({
- role: 'target',
- source: 'https://web.canary.fluxer.app',
- target: 'https://canary.fluxer.com',
- });
- for (const origin of [
- 'http://localhost:3000',
- 'https://chat.example.com',
- 'http://web.fluxer.app',
- 'https://fluxer.app',
- 'https://web.fluxer.com',
- ]) {
- expect(core.resolveDomainMigrationSide(origin)).toBeNull();
- }
- });
-});
-
-describe('payload encryption', () => {
- it('round trips through encrypt and decrypt', async () => {
- const payload = {
- version: 1,
- source_origin: 'https://web.fluxer.app',
- local_storage: {token: 'abc', big: 'x'.repeat(200_000)},
- };
- const sealed = await encryptDomainMigrationPayload(payload);
- expect(sealed.payload).toMatch(/^[A-Za-z0-9_-]+$/u);
- expect(sealed.key).toMatch(/^[A-Za-z0-9_-]{43}$/u);
- expect(sealed.payload.length).toBeLessThan(200_000);
- expect(await decryptDomainMigrationPayload(sealed.payload, sealed.key)).toEqual(payload);
- });
-
- it('rejects a payload opened with another key', async () => {
- const sealed = await encryptDomainMigrationPayload({version: 1});
- const other = await encryptDomainMigrationPayload({version: 1});
- await expect(decryptDomainMigrationPayload(sealed.payload, other.key)).rejects.toThrow();
- });
-
- it('rejects payloads from another source or version', () => {
- const payload = {
- version: 1,
- source_origin: 'https://web.fluxer.app',
- exported_at: NOW,
- local_storage: {},
- accounts: [],
- notification_permission: 'granted',
- };
- expect(core.parseDomainMigrationPayload(payload, 'https://web.fluxer.app')).not.toBeNull();
- expect(core.parseDomainMigrationPayload(payload, 'https://web.canary.fluxer.app')).toBeNull();
- expect(core.parseDomainMigrationPayload({...payload, version: 2}, 'https://web.fluxer.app')).toBeNull();
- expect(
- core.parseDomainMigrationPayload({...payload, accounts: [{userId: 1}]}, 'https://web.fluxer.app'),
- ).toBeNull();
- });
-
- it('accepts a theme library and rejects a malformed one', () => {
- const payload = {
- version: 1,
- source_origin: 'https://web.fluxer.app',
- exported_at: NOW,
- local_storage: {},
- accounts: [],
- notification_permission: 'default',
- };
- const themeLibrary: core.DomainMigrationThemeLibrary = {
- themes: [{id: 'quick-css', css: 'body{}'}],
- assets: [
- {
- id: 'asset',
- name: 'bg.png',
- mime_type: 'image/png',
- size: 3,
- data: 'AQID',
- created_at: NOW,
- updated_at: NOW,
- },
- ],
- local_files: [],
- enabled_theme_ids: ['quick-css'],
- };
- expect(
- core.parseDomainMigrationPayload({...payload, theme_library: themeLibrary}, 'https://web.fluxer.app'),
- ).not.toBeNull();
- expect(
- core.parseDomainMigrationPayload(
- {...payload, theme_library: {...themeLibrary, enabled_theme_ids: [1]}},
- 'https://web.fluxer.app',
- ),
- ).toBeNull();
- const trimmed = core.withoutOptionalPayloadData({
- ...payload,
- version: 1,
- custom_sounds: [],
- theme_library: themeLibrary,
- });
- expect(trimmed.custom_sounds).toBeUndefined();
- expect(trimmed.theme_library).toEqual({...themeLibrary, assets: []});
- });
-});
-
-describe('rewriteImportedAccount', () => {
- it('points the account at the current instance and drops runtimeConfig', () => {
- const current = {apiEndpoint: 'https://fluxer.com/api'} as RuntimeConfigSnapshot;
- const record: StoredAccount = {
- userId: '1',
- token: 'token',
- localStorageData: {runtimeConfig: '{}', token: 'token'},
- managedStorageData: {
- runtimeConfig: '{}',
- token: 'token',
- 'fluxer.theme': 'dark',
- 'fluxer.lastPushEndpoint': 'https://push',
- [core.DOMAIN_MIGRATION_MARKER_KEY]: '{}',
- },
- lastActive: NOW,
- instance: {apiEndpoint: 'https://web.fluxer.app/api'} as RuntimeConfigSnapshot,
- };
- const rewritten = core.rewriteImportedAccount(record, current);
- expect(rewritten.instance).toBe(current);
- expect(rewritten.managedStorageData).toEqual({token: 'token', 'fluxer.theme': 'dark'});
- expect(rewritten.localStorageData).toEqual({token: 'token', 'fluxer.theme': 'dark'});
- expect(rewritten.token).toBe('token');
- });
-});
-
-describe('local storage export', () => {
- it('skips push, test, runtime config and migration keys', () => {
- const storage = memoryStorage({
- token: 't',
- 'fluxer.lastPushEndpoint': 'https://push',
- 'fluxer.pushSubscription': '{}',
- __test__: '1',
- runtimeConfig: '{}',
- [core.DOMAIN_MIGRATION_MARKER_KEY]: '{}',
- [core.DOMAIN_MIGRATION_DEVICE_KEY]: 'device',
- 'mobx-persist:Theme': '{}',
- });
- expect(core.collectExportableLocalStorage(storage)).toEqual({token: 't', 'mobx-persist:Theme': '{}'});
- });
-});
-
-describe('scoped app storage handoff', () => {
- const sourceInstance = {apiEndpoint: 'https://api.fluxer.app'} as RuntimeConfigSnapshot;
- const targetInstance = {apiEndpoint: 'https://api.fluxer.com'} as RuntimeConfigSnapshot;
- const account: StoredAccount = {
- userId: '1',
- token: 'token',
- localStorageData: {},
- lastActive: NOW,
- instance: sourceInstance,
- };
-
- async function exportSource() {
- const source = createPersistentStorageBackend(null);
- await source.setMany([
- {scope: 'global', key: AppStorageKey.VOICE_SETTINGS, value: '{"inputVolume":40}'},
- {scope: 'global', key: AppStorageKey.DELETED_KEYS, value: JSON.stringify(['locale'])},
- {scope: 'global', key: 'fluxer.lastPushEndpoint', value: 'https://push'},
- {scope: 'global', key: LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY, value: '{"version":1}'},
- {scope: accountStorageKey('1', sourceInstance)!, key: AppStorageKey.NOTIFICATION, value: '{"fresh":true}'},
- ]);
- const raw = {
- token: '"token"',
- VoiceSettings: '{"inputVolume":100}',
- Notification: '{"fresh":false}',
- locale: 'sv-SE',
- };
- return collectExportableAppStorage(source, raw, [account], '1');
- }
-
- it('carries values saved after the upgrade and drops raw values the source deleted', async () => {
- const exported = await exportSource();
-
- expect(exported.app_storage).toEqual(
- expect.arrayContaining([
- {user_id: null, key: AppStorageKey.VOICE_SETTINGS, value: '{"inputVolume":40}'},
- {user_id: '1', key: AppStorageKey.NOTIFICATION, value: '{"fresh":true}'},
- ]),
- );
- const keys = exported.app_storage.map((entry) => entry.key);
- expect(keys).not.toContain('fluxer.lastPushEndpoint');
- expect(keys).not.toContain(LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY);
- expect(exported.local_storage).not.toHaveProperty('locale');
- expect(exported.local_storage.token).toBe('"token"');
- });
-
- it('seeds the target scoped store so its legacy migration cannot restore the stale raw values', async () => {
- const exported = await exportSource();
- const parsed = core.parseDomainMigrationPayload(
- {
- version: core.DOMAIN_MIGRATION_PAYLOAD_VERSION,
- source_origin: 'https://web.fluxer.app',
- exported_at: NOW,
- local_storage: exported.local_storage,
- app_storage: [...exported.app_storage, {user_id: 1, key: 'bad', value: 'x'}],
- accounts: [account],
- notification_permission: 'default',
- },
- 'https://web.fluxer.app',
- );
- expect(parsed?.app_storage).toHaveLength(exported.app_storage.length);
-
- const target = createPersistentStorageBackend(null);
- await writeImportedAppStorage(target, parsed!.app_storage!, parsed!.accounts, targetInstance);
- const targetScope = accountStorageKey('1', targetInstance)!;
- await target.setMany([
- {scope: 'global', key: AppStorageKey.VOICE_SETTINGS, value: '{"inputVolume":100}', ifAbsent: true},
- {scope: targetScope, key: AppStorageKey.NOTIFICATION, value: '{"fresh":false}', ifAbsent: true},
- ]);
-
- expect((await target.get('global', AppStorageKey.VOICE_SETTINGS))?.value).toBe('{"inputVolume":40}');
- expect((await target.get(targetScope, AppStorageKey.NOTIFICATION))?.value).toBe('{"fresh":true}');
- expect(await target.get('global', LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY)).toBeNull();
- });
-});
-
-describe('migration gate', () => {
- it('passes when every condition holds', () => {
- expect(core.shouldStartDomainMigration(gateInput())).toBe(true);
- });
-
- it.each<[string, Partial<core.DomainMigrationGateInput>]>([
- ['assignment off', {assignmentEnabled: false}],
- ['kill switch', {discovery: {...ENABLED_DISCOVERY, enabled: false}}],
- ['no discovery', {discovery: null}],
- ['already completed', {marker: {state: 'completed', target: 'https://fluxer.com', at: NOW, attempts: 1}}],
- ['failed recently', {marker: {state: 'failed', at: NOW - 60_000, attempts: 1}}],
- ['failed too often', {marker: {state: 'failed', at: NOW - 3 * 24 * 60 * 60 * 1000, attempts: 3}}],
- ['Android web app', {environment: environment('chromium-android')}],
- ['Apple web app', {environment: environment('webkit')}],
- ['Firefox web app', {environment: environment('firefox')}],
- ['other web app', {environment: environment('other')}],
- ['the desktop app', {environment: environment('none', {electron: true})}],
- ['in a voice call', {voiceActive: true}],
- ['on a one-shot token route', {oneShotRoute: true}],
- ])('blocks when %s', (_label, overrides) => {
- expect(core.shouldStartDomainMigration(gateInput(overrides))).toBe(false);
- });
-
- it('runs the handoff inside a Chromium desktop web app', () => {
- expect(core.shouldStartDomainMigration(gateInput({environment: environment('chromium-desktop')}))).toBe(true);
- });
-
- it('retries a failure after a day', () => {
- const marker: core.DomainMigrationMarker = {state: 'failed', at: NOW - 25 * 60 * 60 * 1000, attempts: 2};
- expect(core.shouldStartDomainMigration(gateInput({marker}))).toBe(true);
- });
-});
-
-describe('marker state', () => {
- it('counts failures and records completion', () => {
- const storage = memoryStorage();
- expect(core.readDomainMigrationMarker(storage)).toBeNull();
- core.markDomainMigrationFailed(storage, NOW);
- core.markDomainMigrationFailed(storage, NOW + 1);
- expect(core.readDomainMigrationMarker(storage)).toEqual({state: 'failed', at: NOW + 1, attempts: 2});
- core.markDomainMigrationCompleted(storage, 'https://fluxer.com', NOW + 2);
- expect(core.readDomainMigrationMarker(storage)).toEqual({
- state: 'completed',
- target: 'https://fluxer.com',
- at: NOW + 2,
- attempts: 2,
- });
- core.markDomainMigrationFailed(storage, NOW + 3);
- expect(core.readDomainMigrationMarker(storage)).toEqual({state: 'failed', at: NOW + 3, attempts: 2});
- });
-
- it('ignores malformed markers', () => {
- expect(core.parseDomainMigrationMarker('not json')).toBeNull();
- expect(core.parseDomainMigrationMarker('{"state":"completed","at":1}')).toBeNull();
- });
-});
-
-describe('migration intent', () => {
- it('expires and ties completion to the exported handoff', () => {
- const storage = memoryStorage();
- expect(core.readDomainMigrationIntent(storage, NOW)).toBeNull();
- core.writeDomainMigrationIntent(storage, {at: NOW});
- expect(core.readDomainMigrationIntent(storage, NOW + 1000)).toEqual({at: NOW});
- expect(core.readDomainMigrationIntent(storage, NOW + core.DOMAIN_MIGRATION_PENDING_MAX_AGE_MS + 1)).toBeNull();
- expect(core.intentConfirmsCompletion(null, null)).toBe(false);
- expect(core.intentConfirmsCompletion({at: NOW}, null)).toBe(true);
- expect(core.intentConfirmsCompletion({at: NOW, handoff_id: 'abc'}, 'abc')).toBe(true);
- expect(core.intentConfirmsCompletion({at: NOW, handoff_id: 'abc'}, 'xyz')).toBe(false);
- expect(core.intentConfirmsCompletion({at: NOW, handoff_id: 'abc'}, null)).toBe(false);
- core.clearDomainMigrationIntent(storage);
- expect(core.readDomainMigrationIntent(storage, NOW)).toBeNull();
- });
-});
-
-describe('forwarding', () => {
- it('keeps the path, query and hash', () => {
- expect(core.buildTargetUrl('https://fluxer.com', '/reset', '?a=1', '#token=abc')).toBe(
- 'https://fluxer.com/reset?a=1#token=abc',
- );
- expect(core.buildTargetUrl('https://fluxer.com', '/', '', '')).toBe('https://fluxer.com/app');
- });
-
- it('honours the kill switch', () => {
- const completed: core.DomainMigrationMarker = {
- state: 'completed',
- target: 'https://fluxer.com',
- at: NOW,
- attempts: 1,
- };
- const browser = environment('none');
- expect(core.shouldForwardCompletedSource(ENABLED_DISCOVERY, completed, browser)).toBe(true);
- expect(core.shouldForwardCompletedSource({...ENABLED_DISCOVERY, enabled: false}, completed, browser)).toBe(false);
- expect(core.shouldForwardCompletedSource(null, completed, browser)).toBe(false);
- expect(core.shouldForwardCompletedSource(ENABLED_DISCOVERY, null, browser)).toBe(false);
- });
-
- it('forwards installed apps only when standalone forwarding is on', () => {
- const completed: core.DomainMigrationMarker = {
- state: 'completed',
- target: 'https://fluxer.com',
- at: NOW,
- attempts: 1,
- };
- const forwarding = {...ENABLED_DISCOVERY, standalone_forwarding: true};
- const desktop = environment('chromium-desktop');
- expect(core.shouldForwardCompletedSource(ENABLED_DISCOVERY, completed, desktop)).toBe(false);
- expect(core.shouldForwardCompletedSource(forwarding, completed, desktop)).toBe(true);
- const legacyDiscovery = {...ENABLED_DISCOVERY} as Partial<DomainMigrationDiscoveryResponse>;
- delete legacyDiscovery.standalone_forwarding;
- expect(
- core.shouldForwardCompletedSource(legacyDiscovery as DomainMigrationDiscoveryResponse, completed, desktop),
- ).toBe(false);
- for (const kind of ['chromium-android', 'webkit', 'firefox', 'other'] as const) {
- expect(core.shouldForwardCompletedSource(forwarding, completed, environment(kind))).toBe(false);
- expect(core.environmentMayForward(environment(kind), forwarding)).toBe(false);
- }
- expect(core.environmentMayForward(environment('none'), ENABLED_DISCOVERY)).toBe(true);
- expect(core.environmentMayForward(environment('none', {electron: true}), ENABLED_DISCOVERY)).toBe(false);
- });
-
- it('buckets anonymous devices by basis points', () => {
- expect(core.anonymousRolloutIsOpen(ENABLED_DISCOVERY)).toBe(false);
- expect(
- core.anonymousRolloutIsOpen({...ENABLED_DISCOVERY, enabled: false, anonymous_rollout_basis_points: 10000}),
- ).toBe(false);
- const all = {...ENABLED_DISCOVERY, anonymous_rollout_basis_points: 10000};
- expect(core.anonymousRolloutIsOpen(all)).toBe(true);
- expect(core.deviceIsInAnonymousRollout(all, 'device-a')).toBe(true);
- const half = {...ENABLED_DISCOVERY, anonymous_rollout_basis_points: 5000};
- for (const deviceId of ['device-a', 'device-b', 'device-c', 'device-d']) {
- expect(core.deviceIsInAnonymousRollout(half, deviceId)).toBe(
- experimentBucket(deviceId, half.rollout_salt) < 5000,
- );
- }
- });
-});
-
-const CHROME_DESKTOP_UA =
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
-const EDGE_DESKTOP_UA = `${CHROME_DESKTOP_UA} Edg/140.0.0.0`;
-const CHROME_ANDROID_UA =
- 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36';
-const CHROME_ANDROID_TABLET_UA =
- 'Mozilla/5.0 (Linux; Android 14; SM-X910) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
-const SAMSUNG_UA =
- 'Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/27.0 Chrome/125.0.0.0 Mobile Safari/537.36';
-const IPHONE_UA =
- 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1';
-const IPAD_DESKTOP_UA =
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15';
-const MAC_SAFARI_UA = IPAD_DESKTOP_UA;
-const MAC_CHROME_UA =
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
-const FIREFOX_DESKTOP_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:143.0) Gecko/20100101 Firefox/143.0';
-const FIREFOX_ANDROID_UA = 'Mozilla/5.0 (Android 14; Mobile; rv:143.0) Gecko/143.0 Firefox/143.0';
-const UNKNOWN_UA = 'SomeBrowser/1.0';
-const CHROMIUM_BRANDS = [{brand: 'Chromium'}, {brand: 'Google Chrome'}, {brand: 'Not=A?Brand'}];
-
-function signals(overrides: Partial<core.DomainMigrationInstallSignals>): core.DomainMigrationInstallSignals {
- return {
- displayMode: 'standalone',
- navigatorStandalone: false,
- userAgent: CHROME_DESKTOP_UA,
- userAgentData: null,
- maxTouchPoints: 0,
- ...overrides,
- };
-}
-
-describe('classifyDomainMigrationInstallKind', () => {
- it.each<[string, Partial<core.DomainMigrationInstallSignals>, core.DomainMigrationInstallKind]>([
- ['a browser tab', {displayMode: 'browser'}, 'none'],
- ['a Firefox taskbar tab', {displayMode: 'minimal-ui', userAgent: FIREFOX_DESKTOP_UA}, 'none'],
- ['Safari on iPhone in a tab', {displayMode: 'browser', userAgent: IPHONE_UA}, 'none'],
- ['Chrome desktop by brand', {userAgentData: {brands: CHROMIUM_BRANDS, mobile: false}}, 'chromium-desktop'],
- ['Chrome desktop by user agent', {}, 'chromium-desktop'],
- ['Edge desktop', {userAgent: EDGE_DESKTOP_UA}, 'chromium-desktop'],
- ['Chrome on a Mac', {userAgent: MAC_CHROME_UA}, 'chromium-desktop'],
- ['window controls overlay', {displayMode: 'window-controls-overlay'}, 'chromium-desktop'],
- [
- 'Chrome Android by brand',
- {userAgent: CHROME_ANDROID_UA, userAgentData: {brands: CHROMIUM_BRANDS, mobile: true}},
- 'chromium-android',
- ],
- ['Chrome Android by user agent', {userAgent: CHROME_ANDROID_UA}, 'chromium-android'],
- [
- 'Chrome on an Android tablet by brand',
- {
- userAgent: CHROME_ANDROID_TABLET_UA,
- userAgentData: {brands: CHROMIUM_BRANDS, mobile: false, platform: 'Android'},
- },
- 'chromium-android',
- ],
- ['Chrome on an Android tablet by user agent', {userAgent: CHROME_ANDROID_TABLET_UA}, 'chromium-android'],
- ['Samsung Internet', {userAgent: SAMSUNG_UA}, 'chromium-android'],
- ['an iPhone home screen app', {displayMode: 'browser', navigatorStandalone: true, userAgent: IPHONE_UA}, 'webkit'],
- ['an iPad home screen app', {userAgent: IPAD_DESKTOP_UA, maxTouchPoints: 5}, 'webkit'],
- ['a Safari Dock app', {userAgent: MAC_SAFARI_UA}, 'webkit'],
- ['a Firefox desktop app', {userAgent: FIREFOX_DESKTOP_UA}, 'firefox'],
- ['a Firefox Android app', {userAgent: FIREFOX_ANDROID_UA}, 'firefox'],
- ['an unknown browser', {userAgent: UNKNOWN_UA}, 'other'],
- ])('classifies %s', (_label, overrides, expected) => {
- expect(core.classifyDomainMigrationInstallKind(signals(overrides))).toBe(expected);
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it.each([CHROME_DESKTOP_UA, FIREFOX_DESKTOP_UA, MAC_SAFARI_UA])(
- 'treats a full screen browser window as a tab',
- (userAgent) => {
- vi.stubGlobal('matchMedia', (query: string) => ({matches: query === '(display-mode: fullscreen)'}));
- vi.stubGlobal('navigator', {userAgent, maxTouchPoints: 0});
- expect(detectDomainMigrationInstallKind()).toBe('none');
- },
- );
-
- it('reads an installed app window from the display mode', () => {
- vi.stubGlobal('matchMedia', (query: string) => ({matches: query === '(display-mode: standalone)'}));
- vi.stubGlobal('navigator', {userAgent: CHROME_DESKTOP_UA, maxTouchPoints: 0});
- expect(detectDomainMigrationInstallKind()).toBe('chromium-desktop');
- });
-});
-
-describe('runDomainMigrationPreMount', () => {
- let replace: ReturnType<typeof vi.fn>;
-
- let discoveryFetch: ReturnType<typeof vi.fn>;
-
- function serveDiscovery(discovery: DomainMigrationDiscoveryResponse | undefined): void {
- runInAction(() => InstanceSnapshotStore.entries.clear());
- discoveryFetch = vi.fn(async (url: string) => {
- const api = `${new URL(url).origin}/api`;
- const body = JSON.stringify({
- ...DEPLOYED_OFFICIAL_DOCUMENT,
- endpoints: {...DEPLOYED_OFFICIAL_DOCUMENT.endpoints, api, api_client: api, api_public: api},
- ...(discovery === undefined ? {} : {domain_migration: discovery}),
- });
- return {
- status: 200,
- headers: {get: (name: string) => (name.toLowerCase() === 'content-type' ? 'application/json' : null)},
- body: null,
- text: async () => body,
- };
- });
- vi.stubGlobal('fetch', discoveryFetch);
- }
-
- function visit(url: string, discovery: DomainMigrationDiscoveryResponse | undefined): void {
- const parsed = new URL(url);
- replace = vi.fn();
- vi.stubGlobal('location', {
- origin: parsed.origin,
- pathname: parsed.pathname,
- search: parsed.search,
- hash: parsed.hash,
- replace,
- });
- serveDiscovery(discovery);
- }
-
- function readMarker(): core.DomainMigrationMarker | null {
- return core.parseDomainMigrationMarker(window.localStorage.getItem(core.DOMAIN_MIGRATION_MARKER_KEY));
- }
-
- function writeIntent(intent: core.DomainMigrationIntent): void {
- window.sessionStorage.setItem(core.DOMAIN_MIGRATION_INTENT_KEY, JSON.stringify(intent));
- }
-
- function writeCompletedMarker(): void {
- window.localStorage.setItem(
- core.DOMAIN_MIGRATION_MARKER_KEY,
- JSON.stringify({state: 'completed', target: 'https://fluxer.com', at: NOW}),
- );
- }
-
- beforeEach(() => {
- window.localStorage.clear();
- window.sessionStorage.clear();
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it('does nothing on a self-hosted origin', async () => {
- visit('https://chat.example.com/migrate/done?next=/channels/@me', ENABLED_DISCOVERY);
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- });
-
- it('does nothing in the desktop local renderer', async () => {
- visit('fluxer-app://app/channels/@me', ENABLED_DISCOVERY);
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- expect(discoveryFetch).not.toHaveBeenCalled();
- expect(readDomainMigrationDiscovery()).toBeNull();
- });
-
- it('reads the migration from the instance discovery document', async () => {
- visit('https://web.fluxer.app/channels/@me', ENABLED_DISCOVERY);
- expect(readDomainMigrationDiscovery()).toBeNull();
- await runDomainMigrationPreMount();
- expect(discoveryFetch).toHaveBeenCalled();
- expect(readDomainMigrationDiscovery()).toEqual(ENABLED_DISCOVERY);
- });
-
- it('stays put when discovery is unreachable', async () => {
- visit('https://web.fluxer.app/channels/1/2', ENABLED_DISCOVERY);
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('offline')));
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- });
-
- it('forwards a migrated source tab with its hash', async () => {
- visit('https://web.fluxer.app/channels/1/2?a=1#b', ENABLED_DISCOVERY);
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://fluxer.com/channels/1/2?a=1#b');
- });
-
- it('keeps one-shot routes on the source', async () => {
- visit('https://web.fluxer.app/reset#token=abc', ENABLED_DISCOVERY);
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- });
-
- it('stays put when the kill switch is off', async () => {
- visit('https://web.fluxer.app/reset#token=abc', {...ENABLED_DISCOVERY, enabled: false});
- writeCompletedMarker();
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- });
-
- it('marks the source completed when the intent matches the handoff', async () => {
- writeIntent({at: Date.now(), handoff_id: 'handoff'});
- visit('https://web.fluxer.app/migrate/done?h=handoff&next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://fluxer.com/channels/1/2');
- expect(readMarker()).toMatchObject({state: 'completed', target: 'https://fluxer.com'});
- expect(window.sessionStorage.getItem(core.DOMAIN_MIGRATION_INTENT_KEY)).toBeNull();
- });
-
- it('ignores a done link without a matching intent', async () => {
- visit('https://web.fluxer.app/migrate/done?next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toBeNull();
-
- writeIntent({at: Date.now(), handoff_id: 'handoff'});
- visit('https://web.fluxer.app/migrate/done?h=other&next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toBeNull();
- });
-
- it('ignores migrate links while the kill switch is off', async () => {
- writeIntent({at: Date.now()});
- visit('https://web.fluxer.app/migrate/done?next=%2Fchannels%2F1%2F2', {...ENABLED_DISCOVERY, enabled: false});
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toBeNull();
- });
-
- it('refuses to export without an intent from the source trigger', async () => {
- const fetchSpy = vi.fn();
- vi.stubGlobal('fetch', fetchSpy);
- visit(`https://web.fluxer.app/migrate/export?n=${'a'.repeat(43)}`, ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/@me');
- expect(fetchSpy).not.toHaveBeenCalled();
- });
-
- it('leaves the marker alone on a failed link and refuses an open redirect', async () => {
- visit('https://web.fluxer.app/migrate/failed?reason=nonce_mismatch&next=%2F%09%2Fevil.example', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/@me');
- expect(readMarker()).toBeNull();
- });
-
- it('reopens a completed source when a resumed migration fails', async () => {
- writeCompletedMarker();
- writeIntent({at: Date.now()});
- visit('https://web.fluxer.app/migrate/failed?reason=redeem_failed&next=%2Fchannels%2F%40me', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/@me');
- expect(readMarker()).toMatchObject({state: 'failed', attempts: 1});
- });
-
- it('resumes through the target when a migrated source still holds a session', async () => {
- writeCompletedMarker();
- window.localStorage.setItem('token', 'session-token');
- visit('https://web.fluxer.app/channels/1/2#x', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith(
- `https://fluxer.com/migrate/begin?resume=1&imported=1&next=${encodeURIComponent('/channels/1/2#x')}`,
- );
- expect(core.readDomainMigrationIntent(window.sessionStorage, Date.now())).not.toBeNull();
- });
-
- function installApp(userAgent: string): void {
- vi.stubGlobal('matchMedia', (query: string) => ({matches: query === '(display-mode: standalone)'}));
- vi.stubGlobal('navigator', {userAgent, maxTouchPoints: 0});
- }
-
- it('returns a Chromium desktop app to the source after the handoff', async () => {
- installApp(CHROME_DESKTOP_UA);
- writeIntent({at: Date.now(), handoff_id: 'handoff'});
- visit('https://web.fluxer.app/migrate/done?h=handoff&next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toMatchObject({state: 'completed', target: 'https://fluxer.com'});
- });
-
- it('forwards a Chromium desktop app when standalone forwarding is on', async () => {
- installApp(CHROME_DESKTOP_UA);
- writeIntent({at: Date.now(), handoff_id: 'handoff'});
- visit('https://web.fluxer.app/migrate/done?h=handoff&next=%2Fchannels%2F1%2F2', {
- ...ENABLED_DISCOVERY,
- standalone_forwarding: true,
- });
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://fluxer.com/channels/1/2');
- });
-
- it('keeps a migrated Chromium desktop app on the source', async () => {
- installApp(CHROME_DESKTOP_UA);
- writeCompletedMarker();
- visit('https://web.fluxer.app/channels/1/2', {...ENABLED_DISCOVERY, anonymous_rollout_basis_points: 10000});
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
-
- visit('https://web.fluxer.app/channels/1/2', {...ENABLED_DISCOVERY, standalone_forwarding: true});
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://fluxer.com/channels/1/2');
- });
-
- it('does not forward logged-out installed apps in the anonymous rollout', async () => {
- installApp(CHROME_DESKTOP_UA);
- visit('https://web.fluxer.app/login', {...ENABLED_DISCOVERY, anonymous_rollout_basis_points: 10000});
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- });
-
- it('never runs the handoff or forwards in an Apple web app', async () => {
- installApp(IPHONE_UA);
- writeCompletedMarker();
- visit('https://web.fluxer.app/channels/1/2', {...ENABLED_DISCOVERY, standalone_forwarding: true});
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
-
- window.localStorage.clear();
- writeIntent({at: Date.now(), handoff_id: 'handoff'});
- visit('https://web.fluxer.app/migrate/done?h=handoff&next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toBeNull();
- });
-
- it('never runs the handoff in an Android web app', async () => {
- installApp(CHROME_ANDROID_UA);
- writeIntent({at: Date.now()});
- visit('https://web.fluxer.app/migrate/done?next=%2Fchannels%2F1%2F2', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/channels/1/2');
- expect(readMarker()).toBeNull();
- });
-
- it('starts a browser migration opened from an installed Android app on the source', async () => {
- visit('https://fluxer.com/migrate/begin?start=1&next=%2Fapp', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/migrate/start?next=%2Fapp');
- expect(window.sessionStorage.getItem(core.DOMAIN_MIGRATION_PENDING_KEY)).toBeNull();
-
- visit('https://web.fluxer.app/migrate/start?next=%2Fapp', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://fluxer.com/migrate/begin?next=%2Fapp');
- expect(core.readDomainMigrationIntent(window.sessionStorage, Date.now())).toMatchObject({at: expect.any(Number)});
-
- visit('https://fluxer.com/migrate/begin?next=%2Fapp', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace.mock.calls[0]?.[0]).toMatch(/^https:\/\/web\.fluxer\.app\/migrate\/export\?n=[\w-]+$/u);
- });
-
- it('opens the target in place when the browser already migrated', async () => {
- window.localStorage.setItem('token', 'session-token');
- visit('https://fluxer.com/migrate/begin?start=1&next=%2Fapp', ENABLED_DISCOVERY);
- const replaceState = vi.fn();
- vi.stubGlobal('history', {state: null, replaceState});
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- expect(replaceState).toHaveBeenCalledWith(null, '', '/app');
- });
-
- it('does not start a migration inside an installed Android app', async () => {
- installApp(CHROME_ANDROID_UA);
- visit('https://web.fluxer.app/migrate/start?next=%2Fapp', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith('https://web.fluxer.app/app');
- expect(core.readDomainMigrationIntent(window.sessionStorage, Date.now())).toBeNull();
- });
-
- it('sends a target completion without a pending nonce back as failed', async () => {
- visit('https://fluxer.com/migrate/complete#h=abc&k=def', ENABLED_DISCOVERY);
- vi.stubGlobal('history', {state: null, replaceState: vi.fn()});
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace).toHaveBeenCalledWith(
- 'https://web.fluxer.app/migrate/failed?reason=no_pending&next=%2Fchannels%2F%40me',
- );
- });
-
- it('still imports into a target that already holds a session', async () => {
- window.localStorage.setItem('token', 'session-token');
- visit('https://fluxer.com/migrate/begin?next=%2Fchannels%2F1', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace.mock.calls[0]?.[0]).toMatch(/^https:\/\/web\.fluxer\.app\/migrate\/export\?n=[\w-]+$/u);
- expect(window.sessionStorage.getItem(core.DOMAIN_MIGRATION_PENDING_KEY)).not.toBeNull();
-
- window.localStorage.removeItem(core.DOMAIN_MIGRATION_IMPORT_KEY);
- visit('https://fluxer.com/migrate/begin?resume=1&next=%2Fchannels%2F1', ENABLED_DISCOVERY);
- expect(await runDomainMigrationPreMount()).toBe(true);
- expect(replace.mock.calls[0]?.[0]).toMatch(/^https:\/\/web\.fluxer\.app\/migrate\/export\?n=[\w-]+$/u);
-
- core.writeDomainMigrationImport(window.localStorage, {state: 'done', at: Date.now()});
- visit('https://fluxer.com/migrate/begin?resume=1&next=%2Fchannels%2F1', ENABLED_DISCOVERY);
- const replaceState = vi.fn();
- vi.stubGlobal('history', {state: null, replaceState});
- expect(await runDomainMigrationPreMount()).toBe(false);
- expect(replace).not.toHaveBeenCalled();
- expect(replaceState).toHaveBeenCalledWith(null, '', '/channels/1');
- });
-});
diff --git a/fluxer_app/src/features/app/hooks/useBottomSheetBackHandler.test.tsx b/fluxer_app/src/features/app/hooks/useBottomSheetBackHandler.test.tsx
deleted file mode 100644
index 2a93523ce..000000000
--- a/fluxer_app/src/features/app/hooks/useBottomSheetBackHandler.test.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createMemoryHistory} from '@app/features/platform/components/router/RouterHistory';
-import {AccountScopedWork, AccountScopedWorkTransitionReason} from '@app/features/platform/state/AccountScopedWork';
-import {act, useState} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, expect, test, vi} from 'vitest';
-
-const SHEET_URL = 'http://localhost/channels/100/200';
-const INCOMING_ACCOUNT_URL = 'http://localhost/channels/300/400';
-
-const router = vi.hoisted(() => ({history: null as ReturnType<typeof createMemoryHistory> | null}));
-
-vi.mock('@app/features/navigation/utils/RouterUtils', () => ({getHistory: () => router.history}));
-
-const {useBottomSheetBackHandler} = await import('@app/features/app/hooks/useBottomSheetBackHandler');
-const {useAccountTransitionDismissal} = await import('@app/features/platform/hooks/useAccountTransitionDismissal');
-
-let root: Root | null = null;
-let container: HTMLElement | null = null;
-let closeSheet: (() => void) | null = null;
-
-function Sheet() {
- const [open, setOpen] = useState(true);
- closeSheet = () => setOpen(false);
- useAccountTransitionDismissal(open, closeSheet);
- useBottomSheetBackHandler(open, closeSheet);
- return null;
-}
-
-function requireHistory(): ReturnType<typeof createMemoryHistory> {
- if (router.history === null) {
- throw new Error('The test history is not installed');
- }
- return router.history;
-}
-
-function sheetMarker(): unknown {
- const state = requireHistory().getLocation().state;
- return state !== null && typeof state === 'object' && 'bottomSheet' in state ? state.bottomSheet : undefined;
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- (window as unknown as {happyDOM: {setURL(url: string): void}}).happyDOM.setURL(SHEET_URL);
- router.history = createMemoryHistory(SHEET_URL);
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => root?.unmount());
- container?.remove();
- root = null;
- container = null;
- closeSheet = null;
- router.history = null;
-});
-
-test('a sheet dismissed by an account switch leaves navigation to the switch', async () => {
- const history = requireHistory();
- const back = vi.spyOn(history, 'back');
- act(() => root?.render(<Sheet data-flx="app.use-bottom-sheet-back-handler-test.sheet--2" />));
- expect(sheetMarker()).toBeTypeOf('string');
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = false;
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {
- await vi.waitFor(() => expect(sheetMarker()).toBeUndefined());
- history.replace(new URL(INCOMING_ACCOUNT_URL));
- });
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- expect(back).not.toHaveBeenCalled();
- expect(history.location.href).toBe(INCOMING_ACCOUNT_URL);
-});
diff --git a/fluxer_app/src/features/app/keybindings/utils/PushToTalkModeReconcile.test.ts b/fluxer_app/src/features/app/keybindings/utils/PushToTalkModeReconcile.test.ts
deleted file mode 100644
index de9aca269..000000000
--- a/fluxer_app/src/features/app/keybindings/utils/PushToTalkModeReconcile.test.ts
+++ /dev/null
@@ -1,262 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- GlobalShortcutsApi,
- GlobalShortcutsBackend,
- GlobalShortcutsPortalState,
- GlobalShortcutsPortalStatus,
- GlobalShortcutsStatus,
-} from '@app/types/electron.d';
-import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
- t: (descriptor: unknown) => descriptor,
-}));
-
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}),
-}));
-
-const BOOTSTRAP_ENDPOINT = 'https://primary.test/api';
-
-(globalThis.window as unknown as Record<string, unknown>).__FLUXER_BOOTSTRAP__ = {
- config: {
- releaseChannel: 'stable',
- bootstrapApiEndpoint: BOOTSTRAP_ENDPOINT,
- bootstrapApiPublicEndpoint: BOOTSTRAP_ENDPOINT,
- },
- instance: {
- api_code_version: Number.MAX_SAFE_INTEGER,
- endpoints: {
- api: BOOTSTRAP_ENDPOINT,
- api_client: BOOTSTRAP_ENDPOINT,
- api_public: BOOTSTRAP_ENDPOINT,
- gateway: 'wss://gateway.primary.test',
- media: 'https://media.primary.test',
- static_cdn: 'https://cdn.primary.test',
- marketing: 'https://primary.test',
- admin: 'https://admin.primary.test',
- invite: 'https://primary.test/invite',
- gift: 'https://primary.test/gift',
- webapp: 'https://app.primary.test',
- upload_relay: 'https://upload.primary.test',
- },
- captcha: {provider: 'none'},
- features: {
- voice_enabled: false,
- stripe_enabled: false,
- self_hosted: false,
- presigned_attachment_uploads: false,
- emails_enabled: false,
- phone_verification_enabled: false,
- },
- gif: {provider: 'klipy', display_name: 'Klipy', attribution_required: false},
- sso: {enabled: false, enforced: false, display_name: null, redirect_uri: ''},
- registration: {mode: 'open', admin_registration_urls_enabled: true},
- community: {single_community: false, single_community_guild_id: null, direct_messages_disabled: false},
- services: {gif_enabled: true, youtube_enabled: false, bluesky_enabled: false},
- limits: undefined,
- push: {public_vapid_key: null},
- app_public: {
- branding: {
- product_name: 'Fluxer',
- icon_url: null,
- symbol_url: null,
- logo_url: null,
- wordmark_url: null,
- favicon_url: null,
- theme_color: null,
- },
- setup: {configured: true, admin_url: null},
- legal: {terms_url: null, privacy_url: null},
- registration: {collect_date_of_birth: true},
- },
- },
-};
-
-let statusListener: ((status: GlobalShortcutsStatus) => void) | null = null;
-
-const globalShortcutsApi: Partial<GlobalShortcutsApi> = {
- sync: async () => {},
- getStatus: () => new Promise<GlobalShortcutsStatus>(() => {}),
- onStatus: (callback) => {
- statusListener = callback;
- return () => {
- statusListener = null;
- };
- },
-};
-
-vi.mock('@app/features/ui/utils/NativeUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/ui/utils/NativeUtils')>()),
- getElectronAPI: () => ({globalShortcuts: globalShortcutsApi}),
-}));
-
-const PORTAL_ASSIGNED_ACTIONS_KEY = 'GlobalShortcuts:portalAssignedActions:v1';
-
-interface PortalStatusOptions {
- recovering?: boolean;
- trigger?: string | null;
- error?: string | null;
- backend?: GlobalShortcutsBackend;
- directInputEnabled?: boolean;
-}
-
-function portalStatus(state: GlobalShortcutsPortalState, options: PortalStatusOptions = {}): GlobalShortcutsStatus {
- const trigger = options.trigger === undefined ? 'F13' : options.trigger;
- const portal: GlobalShortcutsPortalStatus = {
- state,
- version: 2,
- canConfigure: true,
- canRecheck: state === 'unsupported' || state === 'error',
- portalAppId: 'app.fluxer.FluxerDesktop',
- shortcuts: [
- {action: 'voice_push_to_talk', triggerDescription: state === 'bound' ? trigger : null},
- {action: 'voice_push_to_mute', triggerDescription: null},
- ],
- error: options.error ?? (state === 'error' ? 'portal-unavailable' : null),
- recovering: options.recovering ?? false,
- };
- return {
- backend: options.backend ?? (state === 'unsupported' ? 'none' : 'portal'),
- platform: 'linux',
- linux: {
- session: 'wayland',
- sandbox: 'none',
- desktop: 'gnome',
- portal,
- directInput: {available: true, enabled: options.directInputEnabled ?? false, locked: false},
- },
- hooksActive: false,
- hookError: null,
- supportsMouseButtons: false,
- supportsModifierOnly: false,
- };
-}
-
-type Modules = {
- GlobalShortcuts: typeof import('@app/features/input/state/GlobalShortcuts').default;
- Keybind: typeof import('@app/features/input/state/InputKeybind').default;
- AppStorage: typeof import('@app/features/platform/state/PersistentStorage').default;
- reactToPushToTalkModeChanges: typeof import('@app/features/app/keybindings/utils/PushToTalkModeReconcile').reactToPushToTalkModeChanges;
-};
-
-let modules: Modules;
-
-function emit(status: GlobalShortcutsStatus): void {
- expect(statusListener).not.toBeNull();
- statusListener?.(status);
-}
-
-describe('push-to-talk mode reconcile', () => {
- beforeAll(async () => {
- const {default: AppStorage} = await import('@app/features/platform/state/PersistentStorage');
- AppStorage.setJSON(PORTAL_ASSIGNED_ACTIONS_KEY, ['voice_push_to_talk']);
- const {default: GlobalShortcuts} = await import('@app/features/input/state/GlobalShortcuts');
- const {default: Keybind} = await import('@app/features/input/state/InputKeybind');
- const {reactToPushToTalkModeChanges} = await import('@app/features/app/keybindings/utils/PushToTalkModeReconcile');
- modules = {GlobalShortcuts, Keybind, AppStorage, reactToPushToTalkModeChanges};
- Keybind.setTransmitMode('voice_push_to_talk');
- }, 180_000);
-
- afterAll(async () => {
- modules.GlobalShortcuts.detach();
- const {default: Idle} = await import('@app/features/ui/state/Idle');
- Idle.destroy();
- });
-
- it('restores the last settled portal assignment at startup before any status arrives', () => {
- const {GlobalShortcuts, Keybind} = modules;
- expect(Keybind.isPushToTalkEffective()).toBe(false);
- GlobalShortcuts.attach();
- expect(Keybind.isPushToTalkEffective()).toBe(true);
- emit(portalStatus('unknown'));
- emit(portalStatus('probing'));
- expect(Keybind.isPushToTalkEffective()).toBe(true);
- });
-
- it('keeps push-to-talk effective through transient and error portal states', () => {
- const {Keybind, AppStorage, reactToPushToTalkModeChanges} = modules;
- const reconcile = vi.fn();
- const dispose = reactToPushToTalkModeChanges(reconcile);
- emit(portalStatus('bound'));
- expect(AppStorage.getJSON(PORTAL_ASSIGNED_ACTIONS_KEY)).toEqual(['voice_push_to_talk']);
- for (const status of [
- portalStatus('bound', {recovering: true}),
- portalStatus('bound', {recovering: true, trigger: null}),
- portalStatus('declined', {recovering: true}),
- portalStatus('unknown', {recovering: true, backend: 'none'}),
- portalStatus('probing', {recovering: true}),
- portalStatus('binding'),
- portalStatus('error', {recovering: true}),
- portalStatus('error', {error: 'portal-unavailable'}),
- portalStatus('error', {error: 'timeout'}),
- portalStatus('error', {error: 'session-closed'}),
- portalStatus('error', {error: 'identity'}),
- portalStatus('error', {error: 'bind-failed'}),
- portalStatus('unsupported', {recovering: true}),
- portalStatus('not-set-up'),
- portalStatus('unknown'),
- portalStatus('bound'),
- ]) {
- emit(status);
- expect(Keybind.isPushToTalkEffective()).toBe(true);
- }
- expect(reconcile).not.toHaveBeenCalled();
- expect(AppStorage.getJSON(PORTAL_ASSIGNED_ACTIONS_KEY)).toEqual(['voice_push_to_talk']);
- dispose();
- });
-
- it('keeps push-to-talk effective while a recovering session reopens with no listed triggers', () => {
- const {Keybind, AppStorage, reactToPushToTalkModeChanges} = modules;
- const reconcile = vi.fn();
- const dispose = reactToPushToTalkModeChanges(reconcile);
- emit(portalStatus('bound'));
- for (const status of [
- portalStatus('bound', {recovering: true}),
- portalStatus('bound', {recovering: true, trigger: null}),
- portalStatus('binding', {recovering: true}),
- portalStatus('bound'),
- ]) {
- emit(status);
- expect(Keybind.isPushToTalkEffective()).toBe(true);
- expect(AppStorage.getJSON(PORTAL_ASSIGNED_ACTIONS_KEY)).toEqual(['voice_push_to_talk']);
- }
- expect(reconcile).not.toHaveBeenCalled();
- dispose();
- });
-
- it('flips push-to-talk only on settled states and reconciles once per flip', () => {
- const {Keybind, AppStorage, reactToPushToTalkModeChanges} = modules;
- const reconcile = vi.fn();
- const dispose = reactToPushToTalkModeChanges(reconcile);
- const expectFlip = (status: GlobalShortcutsStatus, effective: boolean): void => {
- reconcile.mockClear();
- emit(status);
- expect(Keybind.isPushToTalkEffective()).toBe(effective);
- expect(reconcile).toHaveBeenCalledTimes(1);
- expect(reconcile).toHaveBeenLastCalledWith();
- };
- expectFlip(portalStatus('declined'), false);
- expect(AppStorage.getJSON(PORTAL_ASSIGNED_ACTIONS_KEY)).toEqual([]);
- expectFlip(portalStatus('bound'), true);
- expectFlip(portalStatus('unsupported'), false);
- expectFlip(portalStatus('bound'), true);
- expectFlip(portalStatus('unknown', {backend: 'evdev', directInputEnabled: true}), false);
- expectFlip(portalStatus('bound'), true);
- expectFlip(portalStatus('bound', {trigger: null}), false);
- expectFlip(portalStatus('bound'), true);
- reconcile.mockClear();
- Keybind.setTransmitMode('voice_activity');
- expect(Keybind.isPushToTalkEffective()).toBe(false);
- expect(reconcile).toHaveBeenCalledTimes(1);
- expect(reconcile).toHaveBeenLastCalledWith();
- Keybind.setTransmitMode('voice_push_to_talk');
- expect(Keybind.isPushToTalkEffective()).toBe(true);
- expect(reconcile).toHaveBeenCalledTimes(2);
- dispose();
- });
-});
diff --git a/fluxer_app/src/features/app/state/DesktopRuntimeTransaction.test.ts b/fluxer_app/src/features/app/state/DesktopRuntimeTransaction.test.ts
deleted file mode 100644
index 8f218a739..000000000
--- a/fluxer_app/src/features/app/state/DesktopRuntimeTransaction.test.ts
+++ /dev/null
@@ -1,384 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {type RuntimeConfigSnapshot, runtimeSnapshotFromDiscovery} from '@app/features/app/state/InstanceSnapshotStore';
-import {desktopLocalApiEndpoint} from '@app/features/platform/DesktopLocalAppRuntime';
-import {BOOTSTRAP_APP_PUBLIC} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {
- DesktopRuntimeAbort,
- DesktopRuntimeCommit,
- DesktopRuntimeDeactivation,
- DesktopRuntimeFinalization,
- DesktopRuntimePreparation,
- DesktopRuntimeRollback,
-} from '@fluxer/desktop_ipc/src/LocalAppRuntimeContract';
-import {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 {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/platform/DesktopLocalAppRuntime', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/platform/DesktopLocalAppRuntime')>()),
- isDesktopLocalAppDocument: () => true,
-}));
-
-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,
- };
-}
-
-function snapshotFor(host: string): RuntimeConfigSnapshot {
- return runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(discoveryDocument(host)));
-}
-
-interface BridgeScript {
- readonly prepare?: (request: {preparationId: string; instanceKey: string}) => DesktopRuntimePreparation;
- readonly commit?: (request: {
- preparationId: string;
- instanceKey: string;
- baseRevision: number;
- }) => DesktopRuntimeCommit | Promise<DesktopRuntimeCommit>;
- readonly abort?: () => DesktopRuntimeAbort | Promise<DesktopRuntimeAbort>;
- readonly finalize?: (request: DesktopRuntimeFinalization) => DesktopRuntimeFinalization;
- readonly rollback?: () => DesktopRuntimeRollback;
- readonly deactivate?: () => DesktopRuntimeDeactivation;
- readonly baseRevision?: number;
- readonly baseActiveInstanceKey?: string | null;
-}
-
-function installBridge(host: string, script: BridgeScript = {}) {
- const calls: Array<[string, unknown]> = [];
- const document = discoveryDocument(host);
- const instanceKey = `https://${host}/api`;
- const baseRevision = script.baseRevision ?? 0;
- const baseActiveInstanceKey = script.baseActiveInstanceKey ?? null;
- const record = <T>(method: string, request: unknown, produce: () => T): T => {
- calls.push([method, request]);
- return produce();
- };
- const api = {
- prepare: async (request: {preparationId: string; instanceKey: string}) =>
- record('prepare', request, () =>
- script.prepare == null
- ? {
- preparationId: request.preparationId,
- instanceKey,
- apiEndpoint: desktopLocalApiEndpoint(instanceKey),
- remoteApiEndpoint: instanceKey,
- document,
- baseRevision,
- baseActiveInstanceKey,
- }
- : script.prepare(request),
- ),
- commit: async (request: {preparationId: string; instanceKey: string; baseRevision: number}) =>
- record('commit', request, () =>
- script.commit == null
- ? {
- preparationId: request.preparationId,
- instanceKey: request.instanceKey,
- baseRevision: request.baseRevision,
- revision: request.baseRevision + 1,
- }
- : script.commit(request),
- ),
- abort: async (request: {preparationId: string}) =>
- record('abort', request, () =>
- script.abort == null
- ? {disposition: 'aborted' as const, revision: baseRevision, activeInstanceKey: baseActiveInstanceKey}
- : script.abort(),
- ),
- finalize: async (request: DesktopRuntimeFinalization) =>
- record('finalize', request, () => (script.finalize == null ? request : script.finalize(request))),
- rollback: async (request: {preparationId: string; committedRevision: number}) =>
- record('rollback', request, () =>
- script.rollback == null
- ? {revision: request.committedRevision + 1, activeInstanceKey: baseActiveInstanceKey}
- : script.rollback(),
- ),
- deactivate: async (request: {rendererActiveInstanceKey: string}) =>
- record('deactivate', request, () =>
- script.deactivate == null
- ? {revision: baseRevision + 1, deactivatedInstanceKey: request.rendererActiveInstanceKey}
- : script.deactivate(),
- ),
- };
- (window as {electron?: unknown}).electron = {desktopRuntimeConfig: api};
- return {calls, instanceKey, snapshot: snapshotFor(host)};
-}
-
-type TransactionClient = typeof import('@app/features/app/state/DesktopRuntimeTransaction')['default'];
-
-let transactions: TransactionClient;
-let DesktopRuntimeTransactionError: typeof import('@app/features/app/state/DesktopRuntimeTransaction').DesktopRuntimeTransactionError;
-
-beforeEach(async () => {
- vi.resetModules();
- const module = await import('@app/features/app/state/DesktopRuntimeTransaction');
- transactions = module.default;
- DesktopRuntimeTransactionError = module.DesktopRuntimeTransactionError;
-});
-
-afterEach(() => {
- delete (window as {electron?: unknown}).electron;
-});
-
-describe('prepare/commit/publish/finalize', () => {
- test('every bridge call carries the identity the preparation handed back', async () => {
- const bridge = installBridge('one.test');
-
- const prepared = await transactions.prepare(bridge.snapshot, null);
- expect(prepared.transportApiEndpoint).toBe(desktopLocalApiEndpoint(bridge.instanceKey));
- expect(prepared.snapshot.apiEndpoint).toBe(bridge.instanceKey);
-
- const committed = await transactions.commit(prepared);
- expect(committed.committedRevision).toBe(1);
- expect(committed.previousPublishedRevision).toBe(0);
-
- transactions.publish(committed);
- await transactions.finalize(committed);
-
- const preparationId = prepared.preparation.preparationId;
- expect(bridge.calls).toEqual([
- ['prepare', {preparationId, instanceKey: bridge.instanceKey}],
- ['commit', {preparationId, instanceKey: bridge.instanceKey, baseRevision: 0}],
- ['finalize', {preparationId, instanceKey: bridge.instanceKey, baseRevision: 0, committedRevision: 1}],
- ]);
- });
-
- test('a finalization acknowledgement that is not exact is refused', async () => {
- const bridge = installBridge('one.test', {
- finalize: (request) => ({...request, committedRevision: request.committedRevision + 1}),
- });
-
- const committed = await transactions.commit(await transactions.prepare(bridge.snapshot, null));
- transactions.publish(committed);
-
- await expect(transactions.finalize(committed)).rejects.toThrow(
- 'Desktop runtime finalization acknowledgement is not exact',
- );
- });
-});
-
-describe('commit', () => {
- test('a commit that skips a revision is aborted instead of published', async () => {
- const bridge = installBridge('one.test', {
- commit: (request) => ({...request, revision: request.baseRevision + 2}),
- });
- const prepared = await transactions.prepare(bridge.snapshot, null);
-
- await expect(transactions.commit(prepared)).rejects.toThrow(
- 'Desktop runtime commit does not match its preparation',
- );
- expect(bridge.calls.map(([method]) => method)).toEqual(['prepare', 'commit', 'abort']);
- expect(bridge.calls.at(-1)).toEqual(['abort', {preparationId: prepared.preparation.preparationId}]);
- });
-
- test('an abort that restored a different base instance is reported instead of the original failure', async () => {
- const bridge = installBridge('one.test', {
- baseActiveInstanceKey: 'https://base.test/api',
- commit: () => {
- throw new Error('main process refused the commit');
- },
- abort: () => ({disposition: 'rolled-back', revision: 2, activeInstanceKey: 'https://other.test/api'}),
- });
- const prepared = await transactions.prepare(bridge.snapshot, null);
-
- const failure = await transactions.commit(prepared).catch((error: unknown) => error);
- expect(failure).toBeInstanceOf(AggregateError);
- expect((failure as AggregateError).name).toBe('DesktopRuntimeTransactionRollbackError');
- expect((failure as AggregateError).errors.map((error: unknown) => (error as Error).message)).toEqual([
- 'main process refused the commit',
- 'Desktop runtime abort restored a different base instance',
- ]);
- });
-
- test('an abort that lost the transaction is reported instead of the original failure', async () => {
- const bridge = installBridge('one.test', {
- commit: () => {
- throw new Error('main process refused the commit');
- },
- abort: () => ({disposition: 'absent', revision: 0, activeInstanceKey: null}),
- });
- const prepared = await transactions.prepare(bridge.snapshot, null);
-
- const failure = await transactions.commit(prepared).catch((error: unknown) => error);
- expect((failure as AggregateError).errors.map((error: unknown) => (error as Error).message)).toEqual([
- 'main process refused the commit',
- 'Desktop runtime abort lost its prepared transaction',
- ]);
- });
-
- test('a failing commit whose rollback also fails carries both errors', async () => {
- const commitError = new Error('main process refused the commit');
- const rollbackError = new Error('abort channel is gone');
- const bridge = installBridge('one.test', {
- commit: () => {
- throw commitError;
- },
- abort: () => {
- throw rollbackError;
- },
- });
- const prepared = await transactions.prepare(bridge.snapshot, null);
-
- const failure = await transactions.commit(prepared).catch((error: unknown) => error);
- expect(failure).toBeInstanceOf(AggregateError);
- expect((failure as AggregateError).errors).toEqual([commitError, rollbackError]);
- });
-});
-
-describe('publish', () => {
- test('the same commit cannot be published twice', async () => {
- const bridge = installBridge('one.test');
- const committed = await transactions.commit(await transactions.prepare(bridge.snapshot, null));
-
- transactions.publish(committed);
-
- expect(() => transactions.publish(committed)).toThrow(DesktopRuntimeTransactionError);
- expect(() => transactions.publish(committed)).toThrow(
- 'Desktop runtime commit was superseded before renderer publication',
- );
- });
-
- test('a rolled-back publication frees the revision for the next commit', async () => {
- const bridge = installBridge('one.test');
- const first = await transactions.commit(await transactions.prepare(bridge.snapshot, null));
- transactions.publish(first);
- transactions.rollbackPublished(first);
-
- expect(() => transactions.publish(first)).not.toThrow();
- });
-
- test('rolling back a publication that never happened is refused', async () => {
- const bridge = installBridge('one.test');
- const committed = await transactions.commit(await transactions.prepare(bridge.snapshot, null));
-
- expect(() => transactions.rollbackPublished(committed)).toThrow(
- 'Published desktop runtime was superseded before renderer rollback',
- );
- });
-});
-
-describe('deactivate', () => {
- test('a deactivation that does not advance past the published revision is refused', async () => {
- const bridge = installBridge('one.test', {
- deactivate: () => ({revision: 1, deactivatedInstanceKey: 'https://one.test/api'}),
- });
- const committed = await transactions.commit(await transactions.prepare(bridge.snapshot, null));
- transactions.publish(committed);
-
- await expect(transactions.deactivate(bridge.instanceKey)).rejects.toThrow(
- 'Desktop runtime deactivation returned a stale revision',
- );
- });
-
- test('a deactivation that cleared another instance is refused', async () => {
- const bridge = installBridge('one.test', {
- deactivate: () => ({revision: 9, deactivatedInstanceKey: 'https://other.test/api'}),
- });
-
- await expect(transactions.deactivate(bridge.instanceKey)).rejects.toThrow(
- 'Desktop runtime deactivation cleared a different instance',
- );
- });
-
- test('a deactivation moves the published revision forward for later preparations', async () => {
- const bridge = installBridge('one.test', {
- deactivate: () => ({revision: 4, deactivatedInstanceKey: `https://one.test/api`}),
- });
- await transactions.deactivate(bridge.instanceKey);
-
- await expect(transactions.prepare(bridge.snapshot, null)).rejects.toThrow(
- 'Desktop runtime preparation was superseded before validation',
- );
- });
-});
-
-describe('prepare', () => {
- test('a preparation answering a different identity is aborted and reported', async () => {
- const bridge = installBridge('one.test', {
- prepare: (request) => ({
- preparationId: `${request.preparationId}-other`,
- instanceKey: request.instanceKey,
- apiEndpoint: desktopLocalApiEndpoint(request.instanceKey),
- remoteApiEndpoint: request.instanceKey,
- document: discoveryDocument('one.test'),
- baseRevision: 0,
- baseActiveInstanceKey: null,
- }),
- });
-
- await expect(transactions.prepare(bridge.snapshot, null)).rejects.toThrow(
- 'Desktop runtime returned a different preparation identity',
- );
- expect(bridge.calls.map(([method]) => method)).toEqual(['prepare', 'abort']);
- });
-
- test('a preparation whose transport does not match its own document is aborted', async () => {
- const bridge = installBridge('one.test', {
- prepare: (request) => ({
- preparationId: request.preparationId,
- instanceKey: request.instanceKey,
- apiEndpoint: desktopLocalApiEndpoint('https://elsewhere.test/api'),
- remoteApiEndpoint: request.instanceKey,
- document: discoveryDocument('one.test'),
- baseRevision: 0,
- baseActiveInstanceKey: null,
- }),
- });
-
- await expect(transactions.prepare(bridge.snapshot, null)).rejects.toThrow(
- 'Desktop runtime preparation transport does not match its discovery document',
- );
- expect(bridge.calls.map(([method]) => method)).toEqual(['prepare', 'abort']);
- });
-
- test('an already aborted signal never reaches the bridge', async () => {
- const bridge = installBridge('one.test');
-
- await expect(transactions.prepare(bridge.snapshot, AbortSignal.abort())).rejects.toThrow();
- expect(bridge.calls.map(([method]) => method)).toEqual(['abort']);
- });
-});
diff --git a/fluxer_app/src/features/app/state/GeoIP.test.ts b/fluxer_app/src/features/app/state/GeoIP.test.ts
deleted file mode 100644
index 3cfa399da..000000000
--- a/fluxer_app/src/features/app/state/GeoIP.test.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// @vitest-environment happy-dom
-
-import {createServer, type Server} from 'node:http';
-import type {AddressInfo} from 'node:net';
-import {instanceDiscoveryFixture} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {InstanceAgePolicy, InstanceDiscoveryResponse} from '@fluxer/instance_bootstrap/src/Types';
-import {afterEach, beforeEach, expect, test, vi} from 'vitest';
-
-const UK_ONLY: InstanceAgePolicy = {
- geos: [{country_code: 'GB', region_code: null, action: 'restrict', card_verification_available: false}],
-};
-const SWEDEN_BLOCKS_STOCKHOLM: InstanceAgePolicy = {
- geos: [{country_code: 'SE', region_code: 'AB', action: 'block', card_verification_available: false}],
-};
-
-const STOCKHOLM = {
- countryCode: 'SE',
- regionCode: 'AB',
- latitude: '59.3293',
- longitude: '18.0686',
- ageRestrictedGeos: [],
-};
-
-interface Instance {
- origin: string;
- apiEndpoint: string;
- requests: Array<string>;
- body: unknown;
- status: number;
- delayMs: number;
-}
-
-const servers: Array<Server> = [];
-let instances: Array<Instance> = [];
-let runtimeDocument: InstanceDiscoveryResponse | null;
-
-async function startInstance(): Promise<Instance> {
- const instance: Instance = {origin: '', apiEndpoint: '', requests: [], body: STOCKHOLM, status: 200, delayMs: 0};
- const server = createServer((request, response) => {
- instance.requests.push(`${request.method} ${request.url ?? ''}`);
- const reply = (): void => {
- response.writeHead(instance.status, {
- 'Content-Type': 'application/json',
- 'Access-Control-Allow-Origin': '*',
- });
- response.end(JSON.stringify(instance.body));
- };
- if (request.method === 'GET' && instance.delayMs > 0) {
- setTimeout(reply, instance.delayMs);
- return;
- }
- reply();
- });
- await new Promise<void>((resolve) => {
- server.listen(0, '127.0.0.1', resolve);
- });
- servers.push(server);
- const {port} = server.address() as AddressInfo;
- instance.origin = `http://127.0.0.1:${port}`;
- instance.apiEndpoint = `${instance.origin}/api`;
- instances.push(instance);
- return instance;
-}
-
-function lookups(instance: Instance): Array<string> {
- return instance.requests.filter((request) => request.startsWith('GET '));
-}
-
-function documentFor(instance: Instance, agePolicy?: InstanceAgePolicy): InstanceDiscoveryResponse {
- return instanceDiscoveryFixture(instance.apiEndpoint, agePolicy);
-}
-
-function installRuntime(document: InstanceDiscoveryResponse | null): void {
- runtimeDocument = document;
-}
-
-async function loadRuntimeConfig() {
- vi.resetModules();
- const [{default: RuntimeConfig}, {runtimeSnapshotFromDiscovery}, {parseInstanceDiscoveryDocument}] =
- await Promise.all([
- import('@app/features/app/state/RuntimeConfig'),
- import('@app/features/app/state/InstanceSnapshotStore'),
- import('@fluxer/instance_bootstrap/src/Discovery'),
- ]);
- if (runtimeDocument !== null) {
- RuntimeConfig.applySnapshot(runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(runtimeDocument)));
- }
- return RuntimeConfig;
-}
-
-async function loadGeoIPContext() {
- const RuntimeConfig = await loadRuntimeConfig();
- const {default: GeoIP} = await import('@app/features/app/state/GeoIP');
- return {GeoIP, RuntimeConfig};
-}
-
-async function loadGeoIP() {
- return (await loadGeoIPContext()).GeoIP;
-}
-
-beforeEach(() => {
- instances = [];
-});
-
-afterEach(async () => {
- await Promise.all(
- servers.splice(0).map(
- (server) =>
- new Promise<void>((resolve) => {
- server.close(() => resolve());
- }),
- ),
- );
-});
-
-test('the served age policy seeds both tables before anything is fetched', async () => {
- const instance = await startInstance();
- installRuntime(documentFor(instance, SWEDEN_BLOCKS_STOCKHOLM));
- const GeoIP = await loadGeoIP();
- expect(GeoIP.ageRestrictedGeos).toEqual([]);
- expect(instance.requests).toEqual([]);
- await GeoIP.ready();
-});
-
-test('a document with no age policy falls back to the bundled table', async () => {
- const instance = await startInstance();
- installRuntime(documentFor(instance));
- const GeoIP = await loadGeoIP();
- expect(GeoIP.ageRestrictedGeos).toEqual([
- {countryCode: 'GB', regionCode: null},
- {countryCode: 'BR', regionCode: null},
- ]);
- await GeoIP.ready();
-});
-
-test('the location is resolved from GET /ip on the instance the document names', async () => {
- const instance = await startInstance();
- installRuntime(documentFor(instance, UK_ONLY));
- const GeoIP = await loadGeoIP();
- expect(GeoIP.resolution).toBe('pending');
- await GeoIP.ready();
- expect(lookups(instance)).toEqual(['GET /api/ip']);
- expect(GeoIP.resolution).toBe('resolved');
- expect(GeoIP.countryCode).toBe('SE');
- expect(GeoIP.regionCode).toBe('AB');
- expect(GeoIP.latitude).toBe('59.3293');
- expect(GeoIP.longitude).toBe('18.0686');
-});
-
-test('no active runtime never reaches the network and stays age gated', async () => {
- const instance = await startInstance();
- installRuntime(null);
- const GeoIP = await loadGeoIP();
- await GeoIP.ready();
- expect(instance.requests).toEqual([]);
- expect(GeoIP.resolution).toBe('unavailable');
- expect(GeoIP.ageRestrictedGeos).toEqual([
- {countryCode: 'GB', regionCode: null},
- {countryCode: 'BR', regionCode: null},
- ]);
-});
-
-test('a failed lookup leaves the gateway free to supply the country', async () => {
- const instance = await startInstance();
- instance.status = 500;
- installRuntime(documentFor(instance, SWEDEN_BLOCKS_STOCKHOLM));
- const GeoIP = await loadGeoIP();
- await GeoIP.ready();
- expect(GeoIP.resolution).toBe('unavailable');
- expect(GeoIP.countryCode).toBeNull();
- GeoIP.applyConnectionFallbackGeo({countryCode: 'SE', regionCode: 'AB', latitude: '1', longitude: '2'});
- expect(GeoIP.countryCode).toBe('SE');
-});
-
-test('the gateway never overwrites a resolved location', async () => {
- const instance = await startInstance();
- installRuntime(documentFor(instance, UK_ONLY));
- const GeoIP = await loadGeoIP();
- await GeoIP.ready();
- GeoIP.applyConnectionFallbackGeo({countryCode: 'GB', regionCode: null, latitude: '0', longitude: '0'});
- expect(GeoIP.countryCode).toBe('SE');
- expect(GeoIP.latitude).toBe('59.3293');
-});
-
-test('switching to another instance re-seeds the tables and re-resolves against it', async () => {
- const first = await startInstance();
- const second = await startInstance();
- second.body = {...STOCKHOLM, countryCode: 'GB', regionCode: null};
- installRuntime(documentFor(first, SWEDEN_BLOCKS_STOCKHOLM));
- const {GeoIP, RuntimeConfig} = await loadGeoIPContext();
- const [{runtimeSnapshotFromDiscovery}, {parseInstanceDiscoveryDocument}] = await Promise.all([
- import('@app/features/app/state/InstanceSnapshotStore'),
- import('@fluxer/instance_bootstrap/src/Discovery'),
- ]);
- await GeoIP.ready();
- expect(GeoIP.countryCode).toBe('SE');
-
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(documentFor(second, UK_ONLY))),
- );
- expect(GeoIP.resolution).toBe('pending');
- expect(GeoIP.ageRestrictedGeos).toEqual([{countryCode: 'GB', regionCode: null}]);
- await GeoIP.ready();
- expect(lookups(second)).toEqual(['GET /api/ip']);
- expect(GeoIP.countryCode).toBe('GB');
- expect(GeoIP.resolution).toBe('resolved');
-});
-
-test('installing the first runtime re-seeds and resolves', async () => {
- const instance = await startInstance();
- installRuntime(null);
- const {GeoIP, RuntimeConfig} = await loadGeoIPContext();
- const [{runtimeSnapshotFromDiscovery}, {parseInstanceDiscoveryDocument}] = await Promise.all([
- import('@app/features/app/state/InstanceSnapshotStore'),
- import('@fluxer/instance_bootstrap/src/Discovery'),
- ]);
- await GeoIP.ready();
- expect(instance.requests).toEqual([]);
- expect(GeoIP.resolution).toBe('unavailable');
-
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(documentFor(instance, SWEDEN_BLOCKS_STOCKHOLM))),
- );
- await GeoIP.ready();
- expect(lookups(instance)).toEqual(['GET /api/ip']);
- expect(GeoIP.resolution).toBe('resolved');
- expect(GeoIP.countryCode).toBe('SE');
-});
-
-test('an instance that cannot geolocate never wipes a country the gateway already supplied', async () => {
- const instance = await startInstance();
- instance.body = {...STOCKHOLM, countryCode: null, regionCode: null, latitude: null, longitude: null};
- instance.delayMs = 50;
- installRuntime(documentFor(instance, UK_ONLY));
- const GeoIP = await loadGeoIP();
- GeoIP.applyConnectionFallbackGeo({countryCode: 'GB', regionCode: null, latitude: '51.5', longitude: '-0.1'});
- await GeoIP.ready();
- expect(GeoIP.resolution).toBe('resolved');
- expect(GeoIP.countryCode).toBe('GB');
- expect(GeoIP.latitude).toBe('51.5');
- expect(GeoIP.longitude).toBe('-0.1');
-});
diff --git a/fluxer_app/src/features/gateway/snapshot/SnapshotThreads.test.ts b/fluxer_app/src/features/gateway/snapshot/SnapshotThreads.test.ts
deleted file mode 100644
index f76b5d5ad..000000000
--- a/fluxer_app/src/features/gateway/snapshot/SnapshotThreads.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ReadyPayload} from '@app/features/gateway/events/GatewayReady';
-import type {SnapshotRowOp} from '@app/features/gateway/snapshot/SnapshotEntities';
-import {SnapshotReducer} from '@app/features/gateway/snapshot/SnapshotReducer';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, test} from 'vitest';
-
-const SELF_ID = '900';
-
-function guild(id: string, threads?: Array<Record<string, unknown>>): Record<string, unknown> {
- return {
- id,
- properties: {id, name: id},
- channels: [{id: `${id}-text`, type: ChannelTypes.GUILD_TEXT, last_message_id: null}],
- ...(threads !== undefined ? {threads} : {}),
- emojis: [],
- members: [],
- roles: [],
- member_count: 1,
- joined_at: '2026-01-01T00:00:00.000Z',
- };
-}
-
-function thread(id: string, guildId: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
- return {
- id,
- guild_id: guildId,
- parent_id: `${guildId}-text`,
- type: ChannelTypes.PUBLIC_THREAD,
- last_message_id: null,
- ...overrides,
- };
-}
-
-function ready(guilds: Array<Record<string, unknown>>): ReadyPayload {
- return {
- session_id: 'session',
- user: {id: SELF_ID, username: 'self', email: '[email protected]'},
- guilds,
- private_channels: [],
- relationships: [],
- read_states: [],
- user_guild_settings: [],
- } as unknown as ReadyPayload;
-}
-
-class Rows {
- readonly channels = new Map<string, Record<string, unknown>>();
- readonly guilds = new Map<string, Record<string, unknown>>();
-
- emit = (op: SnapshotRowOp): void => {
- const target = op.entity === 'channel' ? this.channels : op.entity === 'guild' ? this.guilds : null;
- if (target === null) return;
- if (op.kind === 'replaceEntity') {
- target.clear();
- for (const entry of op.entries) target.set(entry.key, entry.value as unknown as Record<string, unknown>);
- } else if (op.kind === 'upsert') {
- target.set(op.key, op.value as unknown as Record<string, unknown>);
- } else if (op.kind === 'delete') {
- target.delete(op.key);
- }
- };
-}
-
-function setup(): {reducer: SnapshotReducer; rows: Rows} {
- const reducer = new SnapshotReducer();
- const rows = new Rows();
- reducer.applyReady(rows.emit, ready([guild('g1', [thread('t1', 'g1')]), guild('g2')]));
- return {reducer, rows};
-}
-
-describe('snapshot thread state', () => {
- test('READY keeps the active threads and marks only thread guilds active', () => {
- const {rows} = setup();
- expect(rows.channels.has('t1')).toBe(true);
- expect(rows.guilds.get('g1')?.threads_active).toBe(true);
- expect(rows.guilds.get('g2')?.threads_active).toBeUndefined();
- });
-
- test('thread events only land in guilds that have threads', () => {
- const {reducer, rows} = setup();
- reducer.applyDispatch(rows.emit, {type: 'THREAD_CREATE', data: thread('t2', 'g1') as never});
- reducer.applyDispatch(rows.emit, {type: 'THREAD_CREATE', data: thread('t3', 'g2') as never});
- expect(rows.channels.has('t2')).toBe(true);
- expect(rows.channels.has('t3')).toBe(false);
- reducer.applyDispatch(rows.emit, {type: 'THREAD_DELETE', data: {id: 't2', guild_id: 'g1'} as never});
- expect(rows.channels.has('t2')).toBe(false);
- });
-
- test('a message in a thread advances its last message', () => {
- const {reducer, rows} = setup();
- reducer.applyDispatch(rows.emit, {
- type: 'MESSAGE_CREATE',
- data: {id: '5000', channel_id: 't1', guild_id: 'g1', author: {id: '1'}} as never,
- });
- expect(rows.channels.get('t1')?.last_message_id).toBe('5000');
- });
-
- test('a list sync drops active threads the server no longer lists and keeps archived ones', () => {
- const {reducer, rows} = setup();
- reducer.applyDispatch(rows.emit, {
- type: 'THREAD_CREATE',
- data: thread('t4', 'g1', {thread_metadata: {archived: true}}) as never,
- });
- reducer.applyDispatch(rows.emit, {
- type: 'THREAD_LIST_SYNC',
- data: {guild_id: 'g1', threads: [thread('t5', 'g1')], members: []} as never,
- });
- expect(rows.channels.has('t1')).toBe(false);
- expect(rows.channels.has('t4')).toBe(true);
- expect(rows.channels.has('t5')).toBe(true);
- });
-
- test('deleting the parent channel removes its threads', () => {
- const {reducer, rows} = setup();
- reducer.applyDispatch(rows.emit, {type: 'CHANNEL_DELETE', data: {id: 'g1-text', type: 0, guild_id: 'g1'} as never});
- expect(rows.channels.has('t1')).toBe(false);
- });
-
- test('a guild that stops sending threads drops them', () => {
- const {reducer, rows} = setup();
- reducer.applyDispatch(rows.emit, {type: 'GUILD_CREATE', data: guild('g1') as never});
- expect(rows.channels.has('t1')).toBe(false);
- expect(rows.guilds.get('g1')?.threads_active).toBeUndefined();
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/BackgroundGatewaySnapshotHydration.test.ts b/fluxer_app/src/features/gateway/transport/BackgroundGatewaySnapshotHydration.test.ts
deleted file mode 100644
index d68f239bd..000000000
--- a/fluxer_app/src/features/gateway/transport/BackgroundGatewaySnapshotHydration.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {StateSnapshotEntries} from '@app/features/gateway/snapshot/SnapshotTypes';
-import {buildBackgroundSnapshotReadySeed} from '@app/features/gateway/transport/BackgroundGatewaySnapshotHydration';
-import {BackgroundReadStateReducer} from '@app/features/gateway/transport/BackgroundReadStateReducer';
-import type {BackgroundMessageNotification} from '@app/features/gateway/transport/BackgroundSnapshotSink';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {RelationshipTypes} from '@fluxer/constants/src/UserConstants';
-import {describe, expect, test} from 'vitest';
-
-const USER_ID = '200';
-
-function rows(values: Record<string, unknown>): Record<string, string> {
- return Object.fromEntries(Object.entries(values).map(([key, value]) => [key, JSON.stringify(value)]));
-}
-
-function demotionEntries(): StateSnapshotEntries {
- return {
- user: rows({[USER_ID]: {id: USER_ID, username: 'self'}}),
- guild: rows({
- 'guild-1': {
- id: 'guild-1',
- properties: {name: 'Guild One', default_message_notifications: MessageNotifications.ONLY_MENTIONS},
- joined_at: null,
- member_count: 10,
- },
- }),
- channel: rows({
- 'channel-1': {id: 'channel-1', guild_id: 'guild-1', type: ChannelTypes.GUILD_TEXT, name: 'general'},
- 'dm-1': {id: 'dm-1', type: ChannelTypes.DM},
- }),
- guild_member: rows({[`guild-1:${USER_ID}`]: {user: {id: USER_ID}, roles: []}}),
- relationship: rows({'666': {id: '666', type: RelationshipTypes.BLOCKED}}),
- read_state: rows({
- 'channel-1': {mentionCount: 0},
- 'dm-1': {mentionCount: 0},
- }),
- };
-}
-
-describe('background snapshot ready seed', () => {
- test('mention counts come from the live counter, not the snapshot read state rows', () => {
- const seed = buildBackgroundSnapshotReadySeed(demotionEntries(), USER_ID, new Map([['channel-1', 3]]));
-
- expect(seed.read_states).toEqual([{id: 'channel-1', mention_count: 3}]);
- });
-
- test('a seeded reducer keeps guild names, notification defaults and blocked users', () => {
- const counts = new Map<string, number>();
- const notifications: Array<BackgroundMessageNotification> = [];
- const reducer = new BackgroundReadStateReducer({
- userId: USER_ID,
- observeMentionCounts: (mentionCounts) => {
- for (const [channelId, count] of mentionCounts) counts.set(channelId, count);
- },
- observeMessageNotification: (notification) => notifications.push(notification),
- });
-
- reducer.applyReady(buildBackgroundSnapshotReadySeed(demotionEntries(), USER_ID, new Map([['channel-1', 2]])));
- reducer.applyDispatch('MESSAGE_CREATE', {
- id: 'm-1',
- channel_id: 'channel-1',
- guild_id: 'guild-1',
- author: {id: '999'},
- mentions: [],
- });
- reducer.applyDispatch('MESSAGE_CREATE', {
- id: 'm-2',
- channel_id: 'channel-1',
- guild_id: 'guild-1',
- author: {id: '999'},
- mentions: [{id: USER_ID}],
- });
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm-3', channel_id: 'dm-1', author: {id: '666'}, mentions: []});
-
- expect(counts.get('channel-1')).toBe(3);
- expect(notifications.map((notification) => [notification.message.id, notification.guildName])).toEqual([
- ['m-2', 'Guild One'],
- ]);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/BackgroundReadStateReducer.test.ts b/fluxer_app/src/features/gateway/transport/BackgroundReadStateReducer.test.ts
deleted file mode 100644
index 869bd66fe..000000000
--- a/fluxer_app/src/features/gateway/transport/BackgroundReadStateReducer.test.ts
+++ /dev/null
@@ -1,558 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {BackgroundReadStateReducer} from '@app/features/gateway/transport/BackgroundReadStateReducer';
-import {
- type BackgroundMentionCountMode,
- type BackgroundMessageNotification,
- BackgroundMentionCountMode as MentionCountMode,
-} from '@app/features/gateway/transport/BackgroundSnapshotSink';
-import {ME} from '@fluxer/constants/src/AppConstants';
-import {ChannelTypes, MessageFlags, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {RelationshipTypes} from '@fluxer/constants/src/UserConstants';
-import {beforeEach, describe, expect, test} from 'vitest';
-
-const USER_ID = '200';
-
-class MentionCountRecorder {
- readonly counts = new Map<string, number>();
-
- observe = (mentionCounts: ReadonlyMap<string, number>, mode: BackgroundMentionCountMode): void => {
- if (mode === MentionCountMode.REPLACE) {
- for (const channelId of [...this.counts.keys()]) {
- if (!mentionCounts.has(channelId)) {
- this.counts.delete(channelId);
- }
- }
- }
- for (const [channelId, count] of mentionCounts) {
- if (count > 0) {
- this.counts.set(channelId, count);
- } else {
- this.counts.delete(channelId);
- }
- }
- };
-
- get total(): number {
- let total = 0;
- for (const count of this.counts.values()) {
- total += count;
- }
- return total;
- }
-}
-
-function readyPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
- return {
- user: {id: USER_ID},
- guilds: [
- {
- id: 'guild-1',
- channels: [{id: 'channel-1'}, {id: 'channel-2'}],
- members: [{user: {id: USER_ID}, roles: ['role-1']}],
- },
- {id: 'guild-2', channels: [{id: 'channel-3'}], members: []},
- ],
- user_guild_settings: [],
- read_states: [],
- ...overrides,
- };
-}
-
-function guildMessage(channelId: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
- return {
- id: 'message-1',
- channel_id: channelId,
- guild_id: 'guild-1',
- author: {id: '999'},
- mentions: [{id: USER_ID}],
- ...overrides,
- };
-}
-
-let recorder: MentionCountRecorder;
-let notifications: Array<BackgroundMessageNotification>;
-let reducer: BackgroundReadStateReducer;
-
-beforeEach(() => {
- recorder = new MentionCountRecorder();
- notifications = [];
- reducer = new BackgroundReadStateReducer({
- userId: USER_ID,
- observeMentionCounts: recorder.observe,
- observeMessageNotification: (notification) => notifications.push(notification),
- });
-});
-
-describe('background read state reducer', () => {
- test('READY seeds the mention counts and replaces whatever was there', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 3}]}));
- expect(recorder.counts.get('channel-1')).toBe(3);
-
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-2', mention_count: 1}]}));
-
- expect(recorder.counts.has('channel-1')).toBe(false);
- expect(recorder.total).toBe(1);
- });
-
- test('a leftover mention in a channel the account can no longer see is not counted, as in the foreground', () => {
- reducer.applyReady(
- readyPayload({
- private_channels: [{id: 'dm-open', type: ChannelTypes.DM}],
- read_states: [
- {id: 'dm-closed', mention_count: 1},
- {id: 'left-guild-channel', mention_count: 1},
- {id: 'dm-open', mention_count: 2},
- ],
- }),
- );
-
- expect([...recorder.counts]).toEqual([['dm-open', 2]]);
- });
-
- test('a leftover mention appears once its guild arrives and its channel is known', () => {
- reducer.applyReady(
- readyPayload({
- guilds: [{id: 'guild-9', unavailable: true}],
- read_states: [{id: 'late-1', mention_count: 2}],
- }),
- );
- expect(recorder.total).toBe(0);
-
- reducer.applyDispatch('GUILD_CREATE', {id: 'guild-9', channels: [{id: 'late-1'}], members: []});
-
- expect(recorder.counts.get('late-1')).toBe(2);
- });
-
- test('a reopened direct message brings its leftover mention back', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'dm-closed', mention_count: 1}]}));
-
- reducer.applyDispatch('CHANNEL_CREATE', {id: 'dm-closed', type: ChannelTypes.DM});
-
- expect(recorder.counts.get('dm-closed')).toBe(1);
- });
-
- test('an acknowledgement for a channel the account cannot see is not counted', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('MESSAGE_ACK', {channel_id: 'gone', message_id: 'm', mention_count: 1});
-
- expect(recorder.total).toBe(0);
- });
-
- test('a muted guild still contributes an explicit mention, exactly as the foreground badge does', () => {
- reducer.applyReady(readyPayload({user_guild_settings: [{guild_id: 'guild-1', muted: true}]}));
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1'));
-
- expect(recorder.counts.get('channel-1')).toBe(1);
- });
-
- test('a muted direct message is not counted', () => {
- reducer.applyReady(
- readyPayload({user_guild_settings: [{guild_id: ME, channel_overrides: [{channel_id: 'dm-1', muted: true}]}]}),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(recorder.total).toBe(0);
- });
-
- test('a direct message muted by the wire-shaped private-channel row is not counted', () => {
- reducer.applyReady(
- readyPayload({
- user_guild_settings: [
- {guild_id: null, channel_overrides: {'dm-1': {channel_id: 'dm-1', muted: true}}},
- {guild_id: 'guild-1', channel_overrides: null},
- ],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(recorder.total).toBe(0);
- });
-
- test('an expired direct message mute stops suppressing messages', () => {
- reducer.applyReady(
- readyPayload({
- user_guild_settings: [
- {
- guild_id: ME,
- channel_overrides: [
- {channel_id: 'dm-1', muted: true, mute_config: {end_time: new Date(Date.now() - 1000).toISOString()}},
- ],
- },
- ],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(recorder.counts.get('dm-1')).toBe(1);
- });
-
- test('an everyone mention counts unless the guild suppresses it', () => {
- reducer.applyReady(readyPayload({user_guild_settings: [{guild_id: 'guild-1', suppress_everyone: true}]}));
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: [], mention_everyone: true}));
- expect(recorder.total).toBe(0);
-
- reducer.applyReady(readyPayload());
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: [], mention_everyone: true}));
- expect(recorder.counts.get('channel-1')).toBe(1);
- });
-
- test('a role mention counts only for a role the account actually holds', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: [], mention_roles: ['role-9']}));
- expect(recorder.total).toBe(0);
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: [], mention_roles: ['role-1']}));
- expect(recorder.counts.get('channel-1')).toBe(1);
- });
-
- test('a direct message counts without an explicit mention', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('MESSAGE_CREATE', {
- id: 'message-2',
- channel_id: 'dm-1',
- author: {id: '999'},
- mentions: [],
- });
-
- expect(recorder.counts.get('dm-1')).toBe(1);
- });
-
- test('a message the account sent itself never counts', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('MESSAGE_CREATE', {
- id: 'message-3',
- channel_id: 'dm-1',
- author: {id: USER_ID},
- mentions: [],
- });
-
- expect(recorder.total).toBe(0);
- });
-
- test('an acknowledgement clears the channel', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 4}]}));
-
- reducer.applyDispatch('MESSAGE_ACK', {channel_id: 'channel-1', message_id: 'message-1'});
-
- expect(recorder.counts.has('channel-1')).toBe(false);
- });
-
- test('an acknowledgement may carry a remaining mention count', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 4}]}));
-
- reducer.applyDispatch('MESSAGE_ACK', {channel_id: 'channel-1', message_id: 'message-1', mention_count: 2});
-
- expect(recorder.counts.get('channel-1')).toBe(2);
- });
-
- test('CHANNEL_DELETE clears that channel only', () => {
- reducer.applyReady(
- readyPayload({
- read_states: [
- {id: 'channel-1', mention_count: 2},
- {id: 'channel-2', mention_count: 1},
- ],
- }),
- );
-
- reducer.applyDispatch('CHANNEL_DELETE', {id: 'channel-1', guild_id: 'guild-1'});
-
- expect(recorder.counts.has('channel-1')).toBe(false);
- expect(recorder.counts.get('channel-2')).toBe(1);
- });
-
- test('GUILD_DELETE removes every channel of that guild and nothing else', () => {
- reducer.applyReady(
- readyPayload({
- read_states: [
- {id: 'channel-1', mention_count: 2},
- {id: 'channel-2', mention_count: 1},
- {id: 'channel-3', mention_count: 5},
- ],
- }),
- );
-
- reducer.applyDispatch('GUILD_DELETE', {id: 'guild-1'});
-
- expect(recorder.counts.has('channel-1')).toBe(false);
- expect(recorder.counts.has('channel-2')).toBe(false);
- expect(recorder.counts.get('channel-3')).toBe(5);
- });
-
- test('an unavailable GUILD_DELETE is an outage and keeps the counts', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 2}]}));
-
- reducer.applyDispatch('GUILD_DELETE', {id: 'guild-1', unavailable: true});
-
- expect(recorder.counts.get('channel-1')).toBe(2);
- });
-
- test('USER_GUILD_SETTINGS_UPDATE starts suppressing everyone mentions for later messages', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('USER_GUILD_SETTINGS_UPDATE', {guild_id: 'guild-1', suppress_everyone: true});
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: [], mention_everyone: true}));
-
- expect(recorder.total).toBe(0);
- });
-
- test('USER_GUILD_SETTINGS_UPDATE mutes a direct message for later messages', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('USER_GUILD_SETTINGS_UPDATE', {
- guild_id: ME,
- channel_overrides: [{channel_id: 'dm-1', muted: true}],
- });
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(recorder.total).toBe(0);
- });
-
- test('USER_GUILD_SETTINGS_UPDATE with a null guild id mutes a direct message', () => {
- reducer.applyReady(readyPayload());
-
- reducer.applyDispatch('USER_GUILD_SETTINGS_UPDATE', {
- guild_id: null,
- channel_overrides: {'dm-1': {channel_id: 'dm-1', muted: true}},
- });
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(recorder.total).toBe(0);
- });
-
- test('reset clears everything it emitted', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 2}]}));
-
- reducer.reset();
-
- expect(recorder.total).toBe(0);
- });
-
- test('a malformed payload is ignored rather than thrown on', () => {
- reducer.applyReady(readyPayload({read_states: [{id: 'channel-1', mention_count: 2}]}));
-
- reducer.applyDispatch('MESSAGE_CREATE', null);
- reducer.applyDispatch('MESSAGE_ACK', {});
- reducer.applyDispatch('GUILD_DELETE', {});
- reducer.applyDispatch('UNRELATED_EVENT', {id: 'guild-1'});
-
- expect(recorder.counts.get('channel-1')).toBe(2);
- });
-
- test('a mention from a blocked author is neither counted nor notified', () => {
- reducer.applyReady(readyPayload({relationships: [{id: '999', type: RelationshipTypes.BLOCKED}]}));
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1'));
-
- expect(recorder.total).toBe(0);
- expect(notifications).toHaveLength(0);
- });
-});
-
-function notificationReady(overrides: Record<string, unknown> = {}): Record<string, unknown> {
- return readyPayload({
- guilds: [
- {
- id: 'guild-1',
- properties: {name: 'Guild One', default_message_notifications: MessageNotifications.ONLY_MENTIONS},
- member_count: 10,
- channels: [
- {id: 'category-1', type: ChannelTypes.GUILD_CATEGORY, name: 'Category'},
- {id: 'channel-1', type: ChannelTypes.GUILD_TEXT, name: 'general', parent_id: 'category-1'},
- {id: 'channel-2', type: ChannelTypes.GUILD_TEXT, name: 'random'},
- ],
- members: [{user: {id: USER_ID}, roles: ['role-1']}],
- },
- ],
- private_channels: [{id: 'group-1', type: ChannelTypes.GROUP_DM, name: 'Friends'}],
- ...overrides,
- });
-}
-
-describe('background message notifications', () => {
- test('a mention in an only-mentions guild notifies with the guild and channel names', () => {
- reducer.applyReady(notificationReady());
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {type: MessageTypes.DEFAULT, flags: 0}));
-
- expect(notifications).toHaveLength(1);
- expect(notifications[0]).toMatchObject({
- guildName: 'Guild One',
- channelName: 'general',
- channelType: ChannelTypes.GUILD_TEXT,
- });
- expect(notifications[0].message.id).toBe('message-1');
- });
-
- test('a plain message in an only-mentions guild does not notify', () => {
- reducer.applyReady(notificationReady());
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: []}));
-
- expect(notifications).toHaveLength(0);
- });
-
- test('the guild default applies until the account overrides it, and a category override wins over it', () => {
- reducer.applyReady(
- notificationReady({
- user_guild_settings: [
- {
- guild_id: 'guild-1',
- message_notifications: MessageNotifications.ALL_MESSAGES,
- channel_overrides: [{channel_id: 'category-1', message_notifications: MessageNotifications.NO_MESSAGES}],
- },
- ],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-2', {id: 'm-2', mentions: []}));
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {id: 'm-1'}));
-
- expect(notifications.map((notification) => notification.message.id)).toEqual(['m-2']);
- });
-
- test('a large guild falls back to only mentions even when its default is all messages', () => {
- reducer.applyReady(
- notificationReady({
- guilds: [
- {
- id: 'guild-1',
- properties: {name: 'Big', default_message_notifications: MessageNotifications.ALL_MESSAGES},
- member_count: 5000,
- channels: [{id: 'channel-1', type: ChannelTypes.GUILD_TEXT, name: 'general'}],
- members: [],
- },
- ],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {mentions: []}));
-
- expect(notifications).toHaveLength(0);
- });
-
- test('a muted guild never notifies, even for a mention', () => {
- reducer.applyReady(notificationReady({user_guild_settings: [{guild_id: 'guild-1', muted: true}]}));
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1'));
-
- expect(recorder.counts.get('channel-1')).toBe(1);
- expect(notifications).toHaveLength(0);
- });
-
- test('suppressed and system messages do not notify', () => {
- reducer.applyReady(notificationReady());
-
- reducer.applyDispatch(
- 'MESSAGE_CREATE',
- guildMessage('channel-1', {id: 'm-1', flags: MessageFlags.SUPPRESS_NOTIFICATIONS}),
- );
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1', {id: 'm-2', type: 7}));
-
- expect(notifications).toHaveLength(0);
- });
-
- test('a group DM message notifies with the conversation name and a direct message notifies without one', () => {
- reducer.applyReady(notificationReady());
-
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm-1', channel_id: 'group-1', author: {id: '999'}, mentions: []});
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm-2', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(notifications.map(({channelName, channelType}) => ({channelName, channelType}))).toEqual([
- {channelName: 'Friends', channelType: ChannelTypes.GROUP_DM},
- {channelName: null, channelType: null},
- ]);
- });
-
- test('a direct message set to no messages does not notify', () => {
- reducer.applyReady(
- notificationReady({
- user_guild_settings: [{guild_id: null, message_notifications: MessageNotifications.NO_MESSAGES}],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', {id: 'm-1', channel_id: 'dm-1', author: {id: '999'}, mentions: []});
-
- expect(notifications).toHaveLength(0);
- });
-
- test('a guild that arrives after READY is learned from GUILD_CREATE', () => {
- reducer.applyReady(readyPayload({guilds: [{id: 'guild-9', unavailable: true}]}));
-
- reducer.applyDispatch('GUILD_CREATE', {
- id: 'guild-9',
- properties: {name: 'Late', default_message_notifications: MessageNotifications.ONLY_MENTIONS},
- member_count: 3,
- channels: [{id: 'late-1', type: ChannelTypes.GUILD_TEXT, name: 'late'}],
- members: [{user: {id: USER_ID}, roles: ['late-role']}],
- });
- reducer.applyDispatch(
- 'MESSAGE_CREATE',
- guildMessage('late-1', {guild_id: 'guild-9', mentions: [], mention_roles: ['late-role']}),
- );
-
- expect(recorder.counts.get('late-1')).toBe(1);
- expect(notifications[0]).toMatchObject({guildName: 'Late', channelName: 'late'});
- });
-
- test('unblocking an author lets their messages notify again', () => {
- reducer.applyReady(notificationReady({relationships: [{id: '999', type: RelationshipTypes.BLOCKED}]}));
-
- reducer.applyDispatch('RELATIONSHIP_REMOVE', {id: '999'});
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('channel-1'));
-
- expect(notifications).toHaveLength(1);
- });
-
- test('a mention inside a thread counts toward the background badge and names the thread', () => {
- reducer.applyReady(
- readyPayload({
- guilds: [
- {
- id: 'guild-1',
- channels: [{id: 'channel-1', name: 'general', type: ChannelTypes.GUILD_TEXT}],
- threads: [{id: 'thread-1', name: 'plans', parent_id: 'channel-1', type: ChannelTypes.PUBLIC_THREAD}],
- members: [{user: {id: USER_ID}, roles: []}],
- },
- ],
- }),
- );
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('thread-1'));
-
- expect(recorder.counts.get('thread-1')).toBe(1);
- expect(notifications.at(-1)?.channelName).toBe('plans');
- });
-
- test('a thread under a muted channel stays quiet for plain messages', () => {
- reducer.applyReady(
- readyPayload({
- user_guild_settings: [
- {guild_id: 'guild-1', channel_overrides: [{channel_id: 'channel-1', muted: true}], message_notifications: 0},
- ],
- }),
- );
- reducer.applyDispatch('THREAD_CREATE', {
- id: 'thread-2',
- guild_id: 'guild-1',
- parent_id: 'channel-1',
- type: ChannelTypes.PUBLIC_THREAD,
- });
-
- reducer.applyDispatch('MESSAGE_CREATE', guildMessage('thread-2', {mentions: []}));
-
- expect(recorder.total).toBe(0);
- expect(notifications).toHaveLength(0);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.test.ts b/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.test.ts
deleted file mode 100644
index 2e7a18007..000000000
--- a/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- ForegroundDemotionHandover,
- type ForegroundDemotionHandoverHost,
-} from '@app/features/gateway/transport/ForegroundDemotionHandover';
-import type {GatewayDispatchDelivery, GatewaySocket} from '@app/features/gateway/transport/GatewaySocket';
-import {describe, expect, test} from 'vitest';
-
-const ACCOUNT_KEY = 'primary.test::100';
-const EXPECTED_USER_ID = '100';
-const DEMOTION_BUFFER_MAX_BYTES = 16 * 1024 * 1024;
-
-class FakeSocket {
- connected = true;
- readonly failures: Array<unknown> = [];
- readonly tokens: Array<string> = [];
- readonly resets: Array<boolean> = [];
- private readonly listeners = new Map<string, Array<(payload: never) => void>>();
-
- on(event: string, listener: (payload: never) => void): void {
- const existing = this.listeners.get(event) ?? [];
- existing.push(listener);
- this.listeners.set(event, existing);
- }
-
- removeAllListeners(event: string): void {
- this.listeners.delete(event);
- }
-
- isDispatchActive(): boolean {
- return true;
- }
-
- completeDispatchProcessing(): void {}
-
- failDispatchProcessing(_receipt: unknown, error: unknown): void {
- this.failures.push(error);
- this.connected = false;
- }
-
- isConnected(): boolean {
- return this.connected;
- }
-
- reset(discardSession: boolean): void {
- this.resets.push(discardSession);
- }
-
- setToken(token: string): void {
- this.tokens.push(token);
- }
-
- deliver(delivery: GatewayDispatchDelivery): void {
- for (const listener of this.listeners.get('dispatch') ?? []) {
- (listener as (payload: GatewayDispatchDelivery) => void)(delivery);
- }
- }
-
- resume(): void {
- this.connected = true;
- }
-
- asGatewaySocket(): GatewaySocket {
- return this as unknown as GatewaySocket;
- }
-}
-
-class FakeHost implements ForegroundDemotionHandoverHost {
- readonly applied: Array<string> = [];
- retiringTokenPersists = true;
- private token: string | null = null;
-
- applySnapshotDispatch(_accountKey: string, _expectedUserId: string, delivery: GatewayDispatchDelivery): void {
- this.applied.push(delivery.type);
- }
-
- persistRetiringToken(_accountKey: string, token: string): Promise<boolean> {
- if (!this.retiringTokenPersists) {
- return Promise.resolve(false);
- }
- this.token = token;
- return Promise.resolve(true);
- }
-
- persistAccountToken(_accountKey: string, token: string): Promise<boolean> {
- this.token = token;
- return Promise.resolve(true);
- }
-
- getAccountToken(): string | null {
- return this.token;
- }
-}
-
-function delivery(type: string, retainedByteSize = 8): GatewayDispatchDelivery {
- return {
- type,
- data: {},
- retainedByteSize,
- receipt: {sequence: 1, generation: 0},
- } as unknown as GatewayDispatchDelivery;
-}
-
-function authSessionChange(newToken: unknown, retainedByteSize = 8): GatewayDispatchDelivery {
- return {
- type: 'AUTH_SESSION_CHANGE',
- data: {new_token: newToken},
- retainedByteSize,
- receipt: {sequence: 1, generation: 0},
- } as unknown as GatewayDispatchDelivery;
-}
-
-function createHarness(): {socket: FakeSocket; host: FakeHost; handover: ForegroundDemotionHandover} {
- const socket = new FakeSocket();
- const host = new FakeHost();
- const handover = new ForegroundDemotionHandover(host);
- handover.begin({accountKey: ACCOUNT_KEY, expectedUserId: EXPECTED_USER_ID, socket: socket.asGatewaySocket()});
- return {socket, host, handover};
-}
-
-describe('foreground demotion handover', () => {
- test('a demotion that stayed within its bounds applies its buffered dispatches and reports success', async () => {
- const {host, socket, handover} = createHarness();
-
- socket.deliver(delivery('MESSAGE_CREATE'));
- socket.deliver(delivery('MESSAGE_UPDATE'));
-
- await expect(handover.consume(ACCOUNT_KEY)).resolves.toBe(true);
- expect(host.applied).toEqual(['MESSAGE_CREATE', 'MESSAGE_UPDATE']);
- });
-
- test('a demotion whose buffer overflowed reports failure even once the socket is connected again', async () => {
- const {host, socket, handover} = createHarness();
-
- socket.deliver(delivery('MESSAGE_CREATE'));
- socket.deliver(delivery('MESSAGE_UPDATE', DEMOTION_BUFFER_MAX_BYTES));
- socket.resume();
-
- await expect(handover.consume(ACCOUNT_KEY)).resolves.toBe(false);
- expect(host.applied).toEqual([]);
- });
-
- test('a rollback after a buffer overflow refuses to restore the retained session', async () => {
- const {socket, handover} = createHarness();
-
- socket.deliver(delivery('MESSAGE_CREATE', DEMOTION_BUFFER_MAX_BYTES));
- socket.resume();
-
- const rollback = await handover.rollback(ACCOUNT_KEY);
-
- expect(rollback).toEqual({
- outcome: 'restore',
- socket: socket.asGatewaySocket(),
- deliveries: [],
- persistedAuthToken: null,
- canRestore: false,
- });
- });
-});
-
-describe('foreground demotion handover token rotation', () => {
- test('a rotation the host refuses to persist fails the demotion rather than retiring the stale token', async () => {
- const {host, socket, handover} = createHarness();
- host.retiringTokenPersists = false;
-
- socket.deliver(delivery('MESSAGE_CREATE'));
- socket.deliver(authSessionChange('rotated-token'));
-
- await expect(handover.consume(ACCOUNT_KEY)).resolves.toBe(false);
- expect(socket.resets).toEqual([true]);
- expect(host.applied).toEqual([]);
- });
-
- test('a rotation carrying an unusable token fails the dispatch and drops what was buffered', async () => {
- const {host, socket, handover} = createHarness();
-
- socket.deliver(delivery('MESSAGE_CREATE'));
- socket.deliver(authSessionChange(''));
-
- expect(socket.failures).toHaveLength(1);
- expect((socket.failures[0] as Error).name).toBe('ForegroundDemotionAuthTokenError');
-
- await expect(handover.consume(ACCOUNT_KEY)).resolves.toBe(false);
- expect(host.applied).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayCompression.test.ts b/fluxer_app/src/features/gateway/transport/GatewayCompression.test.ts
deleted file mode 100644
index d35b7e73c..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayCompression.test.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {constants, createZstdCompress, type ZstdCompress} from 'node:zlib';
-import {GatewayCompression, isGatewayCompressionError} from '@app/features/gateway/transport/GatewayCompression';
-import {initSync} from '@pkgs/libfluxcore/libfluxcore';
-import {beforeAll, describe, expect, it} from 'vitest';
-
-const wasmBytes = readFileSync(new URL('../../../../pkgs/libfluxcore/libfluxcore_bg.wasm', import.meta.url));
-const STREAM_MESSAGE_COUNT = 10_000;
-
-describe('GatewayCompression', () => {
- beforeAll(() => {
- initSync({module: wasmBytes});
- });
-
- it('passes uncompressed payloads through as text', async () => {
- const compression = new GatewayCompression('none');
- const payload = new TextEncoder().encode('{"op":11}');
-
- await expect(compression.decompress(payload.buffer)).resolves.toBe('{"op":11}');
- });
-
- it('classifies invalid zstd as a gateway compression error', async () => {
- const compression = new GatewayCompression('zstd-stream');
-
- try {
- await compression.decompress(new Uint8Array([0x6e, 0x6f, 0x70, 0x65]).buffer);
- expect.fail('expected zstd decompression to fail');
- } catch (error) {
- expect(isGatewayCompressionError(error)).toBe(true);
- if (isGatewayCompressionError(error)) {
- expect(error.compression).toBe('zstd-stream');
- }
- }
- });
-
- it('decodes 10,000 flushed zstd stream gateway JSON messages', async () => {
- const encoder = createZstdCompress({
- params: {
- [constants.ZSTD_c_compressionLevel]: 3,
- },
- });
- const compression = new GatewayCompression('zstd-stream');
- const messages: Array<{compressed: Uint8Array; payload: string}> = [];
-
- try {
- for (let seq = 1; seq <= STREAM_MESSAGE_COUNT; seq++) {
- const payload = gatewayJsonPayload(seq);
- const compressed = await compressAndFlushChunk(encoder, payload);
- expect(compressed.byteLength).toBeGreaterThan(0);
- messages.push({compressed, payload});
- }
-
- const decodedMessages = await Promise.all(
- messages.map(({compressed}) => compression.decompress(toArrayBuffer(compressed))),
- );
- for (let index = 0; index < messages.length; index++) {
- const decoded = decodedMessages[index];
- const payload = messages[index].payload;
- const parsed = JSON.parse(decoded) as {s: number; d: {id: string}};
- const seq = index + 1;
-
- expect(decoded).toBe(payload);
- expect(parsed.s).toBe(seq);
- expect(parsed.d.id).toBe(String(seq));
- }
- } finally {
- compression.destroy();
- encoder.destroy();
- }
- }, 30_000);
-
- it('round-trips 10,000 outbound messages through the wasm encoder into a peer decoder', async () => {
- const client = new GatewayCompression('zstd-stream');
- const server = new GatewayCompression('zstd-stream');
- await client.warmup();
-
- try {
- for (let seq = 1; seq <= STREAM_MESSAGE_COUNT; seq++) {
- const payload = gatewayJsonPayload(seq);
- const compressed = client.compress(payload);
- expect(compressed.byteLength).toBeGreaterThan(0);
-
- const decoded = await server.decompress(toArrayBuffer(compressed));
- expect(decoded).toBe(payload);
- }
- } finally {
- client.destroy();
- server.destroy();
- }
- }, 30_000);
-});
-
-function gatewayJsonPayload(seq: number): string {
- return JSON.stringify({
- op: 0,
- t: 'MESSAGE_CREATE',
- s: seq,
- d: {
- id: String(seq),
- channel_id: '1497639278555484216',
- guild_id: '1427764661718740994',
- author: {
- id: '1042',
- username: 'canary',
- bot: false,
- },
- content: `gateway zstd stream stress payload ${seq}`,
- mentions: [],
- attachments: [],
- embeds: [],
- flags: seq % 8,
- },
- });
-}
-
-function compressAndFlushChunk(encoder: ZstdCompress, payload: string): Promise<Uint8Array> {
- return new Promise((resolve, reject) => {
- const chunks: Array<Buffer> = [];
- const cleanup = (): void => {
- encoder.off('data', onData);
- encoder.off('error', onError);
- };
- const onData = (chunk: Buffer): void => {
- chunks.push(Buffer.from(chunk));
- };
- const onError = (error: Error): void => {
- cleanup();
- reject(error);
- };
-
- encoder.on('data', onData);
- encoder.once('error', onError);
- encoder.write(Buffer.from(payload), (error?: Error | null) => {
- if (error) {
- onError(error);
- return;
- }
- encoder.flush(constants.ZSTD_e_flush, () => {
- cleanup();
- resolve(new Uint8Array(Buffer.concat(chunks)));
- });
- });
- });
-}
-
-function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
- const copy = new Uint8Array(bytes.byteLength);
- copy.set(bytes);
- return copy.buffer;
-}
diff --git a/fluxer_app/src/features/gateway/transport/GatewaySocket.test.ts b/fluxer_app/src/features/gateway/transport/GatewaySocket.test.ts
deleted file mode 100644
index 1e46f626c..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewaySocket.test.ts
+++ /dev/null
@@ -1,451 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {dirname, join} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {GatewayCompression} from '@app/features/gateway/transport/GatewayCompression';
-import {GatewayConnectionRole} from '@app/features/gateway/transport/GatewayConnectionRole';
-import {
- type GatewayDispatchDelivery,
- GatewaySocket,
- type GatewaySocketOptions,
- type GatewaySocketProperties,
- GatewayState,
- MAX_DEFERRED_GATEWAY_EMIT_BYTES,
- MAX_DEFERRED_GATEWAY_EMITS,
-} from '@app/features/gateway/transport/GatewaySocket';
-import {GatewayCloseCodes, GatewayOpcodes} from '@fluxer/constants/src/GatewayConstants';
-import {initSync} from '@pkgs/libfluxcore/libfluxcore';
-import {afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-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',
-};
-
-interface SocketInternals {
- socket: {
- readyState: number;
- send: (data: string | Uint8Array) => void;
- close?: (code: number, reason: string) => void;
- } | null;
- payloadDecompressor: GatewayCompression | null;
- deferredEmitQueue: Array<() => void>;
- deferredEmitBytes: number;
- emitDispatchDeferred: (delivery: GatewayDispatchDelivery) => void;
- buildGatewayUrl: () => Promise<string>;
- openSocket: () => void;
- handleSocketMessage: (event: {data: string | ArrayBuffer}) => Promise<void>;
- handleSocketClose: (event: {code: number; reason: string; wasClean: boolean}) => void;
- sendIdentify: () => void;
-}
-
-function internals(socket: GatewaySocket): SocketInternals {
- return socket as unknown as SocketInternals;
-}
-
-function createSocket(overrides: Partial<GatewaySocketOptions> = {}): GatewaySocket {
- return new GatewaySocket('wss://gateway.example/', {
- token: 'token-100',
- apiVersion: 9,
- properties: PROPERTIES,
- isMobileLayout: () => false,
- geo: () => ({latitude: null, longitude: null}),
- role: GatewayConnectionRole.FOREGROUND,
- ...overrides,
- });
-}
-
-function attachOpenTransport(socket: GatewaySocket): Array<string> {
- const sent: Array<string> = [];
- internals(socket).socket = {
- readyState: WebSocket.OPEN,
- send: (data) => {
- sent.push(typeof data === 'string' ? data : new TextDecoder().decode(data));
- },
- };
- return sent;
-}
-
-function sequenceOf(data: unknown): number {
- return (data as {sequence: number}).sequence;
-}
-
-function enqueueDispatch(socket: GatewaySocket, sequence: number, retainedByteSize: number): void {
- internals(socket).emitDispatchDeferred({
- type: 'TYPING_START',
- data: {sequence},
- retainedByteSize,
- receipt: {sequence, generation: 0},
- });
-}
-
-function dispatchFrame(eventType: string, sequence: number, data: unknown): string {
- return JSON.stringify({op: 0, t: eventType, s: sequence, d: data});
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe('voice state payloads', () => {
- test('two sockets each stamp only their own connection id', () => {
- const first = createSocket();
- const second = createSocket();
- const firstSent = attachOpenTransport(first);
- const secondSent = attachOpenTransport(second);
- const params = {
- guild_id: 'guild-1',
- channel_id: 'channel-1',
- self_mute: false,
- self_deaf: false,
- self_video: false,
- self_stream: false,
- };
-
- first.updateVoiceStateExplicit({...params, connection_id: 'connection-first'});
- second.updateVoiceStateExplicit({...params, connection_id: null});
-
- expect(JSON.parse(firstSent[0]).d.connection_id).toBe('connection-first');
- expect(JSON.parse(secondSent[0]).d.connection_id).toBeNull();
- });
-});
-
-function presenceFrames(sent: Array<string>): Array<unknown> {
- return sent
- .map((frame) => JSON.parse(frame) as {op: number; d: unknown})
- .filter((payload) => payload.op === GatewayOpcodes.PRESENCE_UPDATE || payload.op === GatewayOpcodes.IDENTIFY)
- .map((payload) =>
- payload.op === GatewayOpcodes.IDENTIFY ? (payload.d as {presence: unknown}).presence : payload.d,
- );
-}
-
-describe('presence across reconnects', () => {
- test('resends the presence dropped while disconnected once the session resumes', async () => {
- const socket = createSocket({presence: {status: 'online', afk: false, mobile: false}});
- const sent = attachOpenTransport(socket);
-
- socket.updatePresence('online', true, false, null);
- expect(sent).toHaveLength(0);
-
- await internals(socket).handleSocketMessage({data: JSON.stringify({op: 0, t: 'RESUMED', s: 1, d: {}})});
-
- expect(presenceFrames(sent)).toEqual([{status: 'online', afk: true, mobile: false, custom_status: null}]);
- });
-
- test('identifies with the latest presence instead of the one it was created with', () => {
- const socket = createSocket({presence: {status: 'online', afk: false, mobile: false}});
- const sent = attachOpenTransport(socket);
-
- socket.updatePresence('dnd', true, false);
- internals(socket).sendIdentify();
-
- expect(presenceFrames(sent)).toEqual([{status: 'dnd', afk: true, mobile: false}]);
- });
-});
-
-describe('dispatch delivery', () => {
- test('carries the event, the retained byte size and an active receipt', async () => {
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
- const frame = dispatchFrame('MESSAGE_CREATE', 7, {id: 'message-1'});
-
- await internals(socket).handleSocketMessage({data: frame});
- vi.advanceTimersByTime(5000);
-
- expect(deliveries).toHaveLength(1);
- expect(deliveries[0].type).toBe('MESSAGE_CREATE');
- expect(deliveries[0].data).toEqual({id: 'message-1'});
- expect(deliveries[0].retainedByteSize).toBe(frame.length * 3);
- expect(deliveries[0].receipt.sequence).toBe(7);
- expect(socket.isDispatchActive(deliveries[0].receipt)).toBe(true);
- });
-
- test('completing a dispatch retires its receipt', async () => {
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- await internals(socket).handleSocketMessage({data: dispatchFrame('TYPING_START', 1, {})});
- vi.advanceTimersByTime(5000);
- socket.completeDispatchProcessing(deliveries[0].receipt);
-
- expect(socket.isDispatchActive(deliveries[0].receipt)).toBe(false);
- });
-
- test('failing a dispatch clears the session and reconnects with a fresh identify', async () => {
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- await internals(socket).handleSocketMessage({
- data: JSON.stringify({op: 0, t: 'READY', s: 1, d: {session_id: 'session-1'}}),
- });
- vi.advanceTimersByTime(0);
- expect(socket.getSessionId()).toBe('session-1');
-
- socket.failDispatchProcessing(deliveries[0].receipt, new Error('handler blew up'));
-
- expect(socket.getSessionId()).toBeNull();
- expect(socket.getState()).toBe(GatewayState.Reconnecting);
- expect(socket.isDispatchActive(deliveries[0].receipt)).toBe(false);
- });
-
- test('a receipt from a cleared session is no longer active', async () => {
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- await internals(socket).handleSocketMessage({data: dispatchFrame('TYPING_START', 4, {})});
- vi.advanceTimersByTime(5000);
- socket.reset(false);
-
- expect(socket.isDispatchActive(deliveries[0].receipt)).toBe(false);
- });
-});
-
-describe('dispatch failure reconnects', () => {
- beforeEach(() => {
- vi.spyOn(Math, 'random').mockReturnValue(0.5);
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- function recordSocketOpens(socket: GatewaySocket): Array<number> {
- const opens: Array<number> = [];
- internals(socket).openSocket = () => {
- opens.push(Date.now());
- };
- return opens;
- }
-
- function advanceToNextSocketOpen(opens: ReadonlyArray<number>): void {
- const seen = opens.length;
- for (let step = 0; step < 10 && opens.length === seen; step += 1) {
- vi.advanceTimersToNextTimer();
- }
- }
-
- function readyFrame(sequence: number): string {
- return JSON.stringify({op: 0, t: 'READY', s: sequence, d: {session_id: `session-${sequence}`}});
- }
-
- test('a failed dispatch waits out the minimum reconnect delay instead of reopening at 0ms', async () => {
- const socket = createSocket();
- const opens = recordSocketOpens(socket);
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- await internals(socket).handleSocketMessage({data: readyFrame(1)});
- vi.advanceTimersByTime(0);
- socket.failDispatchProcessing(deliveries[0].receipt, new Error('handler blew up'));
-
- vi.advanceTimersByTime(999);
- expect(opens).toHaveLength(0);
-
- vi.advanceTimersByTime(1000);
- expect(opens).toHaveLength(1);
- });
-
- test('a dispatch failure that repeats on every READY escalates the reconnect delay', async () => {
- const socket = createSocket();
- const opens = recordSocketOpens(socket);
- socket.on('dispatch', (delivery) => {
- socket.failDispatchProcessing(delivery.receipt, new Error('handler blew up'));
- });
- const delays: Array<number> = [];
-
- for (let sequence = 1; sequence <= 4; sequence += 1) {
- const scheduledAt = Date.now();
- await internals(socket).handleSocketMessage({data: readyFrame(sequence)});
- advanceToNextSocketOpen(opens);
- delays.push(Date.now() - scheduledAt);
- }
-
- expect(opens).toHaveLength(4);
- expect(delays[0]).toBeGreaterThanOrEqual(1000);
- expect(delays[1]).toBeGreaterThan(delays[0]);
- expect(delays[2]).toBeGreaterThan(delays[1]);
- expect(delays[3]).toBeGreaterThan(delays[2]);
- });
-
- test('a dispatch that completes lets the next READY clear the backoff again', async () => {
- const socket = createSocket();
- const opens = recordSocketOpens(socket);
- let shouldFail = true;
- socket.on('dispatch', (delivery) => {
- if (shouldFail) {
- socket.failDispatchProcessing(delivery.receipt, new Error('handler blew up'));
- } else {
- socket.completeDispatchProcessing(delivery.receipt);
- }
- });
-
- await internals(socket).handleSocketMessage({data: readyFrame(1)});
- advanceToNextSocketOpen(opens);
- shouldFail = false;
- await internals(socket).handleSocketMessage({data: readyFrame(2)});
- vi.advanceTimersToNextTimer();
- shouldFail = true;
- const scheduledAt = Date.now();
- await internals(socket).handleSocketMessage({data: readyFrame(3)});
- advanceToNextSocketOpen(opens);
-
- expect(opens).toHaveLength(2);
- expect(Date.now() - scheduledAt).toBeLessThan(1500);
- });
-});
-
-describe('compression decode failure recovery', () => {
- beforeAll(() => {
- const wasmPath = join(dirname(fileURLToPath(import.meta.url)), '../../../../pkgs/libfluxcore/libfluxcore_bg.wasm');
- initSync({module: readFileSync(wasmPath)});
- });
-
- function attachRecordingTransport(socket: GatewaySocket): Array<{code: number; reason: string}> {
- const closes: Array<{code: number; reason: string}> = [];
- internals(socket).socket = {
- readyState: WebSocket.OPEN,
- send: () => {},
- close: (code, reason) => {
- closes.push({code, reason});
- },
- };
- internals(socket).payloadDecompressor = new GatewayCompression('zstd-stream');
- return closes;
- }
-
- function corruptZstdFrame(): ArrayBuffer {
- return new Uint8Array([0x6e, 0x6f, 0x70, 0x65]).buffer;
- }
-
- test('an undecodable frame closes with DECODE_ERROR and reopens without compression', async () => {
- const socket = createSocket();
- const closes = attachRecordingTransport(socket);
-
- await internals(socket).handleSocketMessage({data: corruptZstdFrame()});
-
- expect(closes).toEqual([{code: GatewayCloseCodes.DECODE_ERROR, reason: 'Retrying without compression'}]);
- expect(socket.getState()).toBe(GatewayState.Reconnecting);
- expect(await internals(socket).buildGatewayUrl()).toBe('wss://gateway.example/?v=9&encoding=json&compress=none');
- });
-
- test('a second undecodable frame before the reconnect neither closes again nor reports a fatal error', async () => {
- const socket = createSocket();
- const closes = attachRecordingTransport(socket);
- const fatalErrors: Array<Error> = [];
- socket.on('fatalError', (error) => fatalErrors.push(error));
-
- await internals(socket).handleSocketMessage({data: corruptZstdFrame()});
- await internals(socket).handleSocketMessage({data: corruptZstdFrame()});
- vi.advanceTimersByTime(0);
-
- expect(closes).toHaveLength(1);
- expect(fatalErrors).toEqual([]);
- });
-});
-
-describe('deferred emit queue bounds', () => {
- test('2000 undrained dispatches never grow the queue past the entry cap and never lose an event', () => {
- const socket = createSocket();
- const received: Array<number> = [];
- socket.on('dispatch', (delivery) => received.push(sequenceOf(delivery.data)));
- let observedMaxLength = 0;
-
- for (let sequence = 1; sequence <= 2000; sequence += 1) {
- enqueueDispatch(socket, sequence, 0);
- observedMaxLength = Math.max(observedMaxLength, internals(socket).deferredEmitQueue.length);
- }
- vi.advanceTimersByTime(5000);
-
- expect(observedMaxLength).toBe(MAX_DEFERRED_GATEWAY_EMITS);
- expect(received).toHaveLength(2000);
- expect(received[0]).toBe(1);
- expect(received[1999]).toBe(2000);
- });
-
- test('a burst of large payloads never grows the queue past the byte cap', () => {
- const socket = createSocket();
- const received: Array<number> = [];
- socket.on('dispatch', (delivery) => received.push(sequenceOf(delivery.data)));
- const byteSize = 4_500_000;
- let observedMaxBytes = 0;
-
- for (let sequence = 1; sequence <= 40; sequence += 1) {
- enqueueDispatch(socket, sequence, byteSize);
- observedMaxBytes = Math.max(observedMaxBytes, internals(socket).deferredEmitBytes);
- }
- vi.advanceTimersByTime(5000);
-
- expect(observedMaxBytes).toBeGreaterThan(0);
- expect(observedMaxBytes).toBeLessThanOrEqual(MAX_DEFERRED_GATEWAY_EMIT_BYTES);
- expect(received).toHaveLength(40);
- });
-
- test('a throwing listener does not drop the rest of the flush', () => {
- const socket = createSocket();
- const received: Array<number> = [];
- socket.on('dispatch', (delivery) => {
- const sequence = sequenceOf(delivery.data);
- if (sequence === 1) throw new Error('listener blew up');
- received.push(sequence);
- });
-
- for (let sequence = 1; sequence <= 3; sequence += 1) {
- enqueueDispatch(socket, sequence, 0);
- }
- vi.advanceTimersByTime(5000);
-
- expect(received).toEqual([2, 3]);
- });
-
- test('reset discards queued emits', () => {
- const socket = createSocket();
- const received: Array<number> = [];
- socket.on('dispatch', (delivery) => received.push(sequenceOf(delivery.data)));
-
- enqueueDispatch(socket, 1, 128);
- socket.reset(false);
- vi.advanceTimersByTime(5000);
-
- expect(received).toEqual([]);
- expect(internals(socket).deferredEmitQueue).toHaveLength(0);
- expect(internals(socket).deferredEmitBytes).toBe(0);
- });
-});
-
-describe('authentication failure', () => {
- test('a 4004 close only disconnects and reports it to the owner', () => {
- const socket = createSocket();
- const disconnects: Array<{code: number}> = [];
- socket.on('disconnect', (event) => disconnects.push(event));
-
- internals(socket).handleSocketClose({code: 4004, reason: 'Authentication failed', wasClean: false});
- vi.advanceTimersByTime(0);
-
- expect(disconnects).toEqual([{code: 4004, reason: 'Authentication failed', wasClean: false}]);
- expect(socket.getState()).toBe(GatewayState.Disconnected);
- });
-
- test('a non-4004 close still schedules a reconnect', () => {
- const socket = createSocket();
-
- internals(socket).handleSocketClose({code: 1006, reason: 'Abnormal closure', wasClean: false});
-
- expect(socket.getState()).toBe(GatewayState.Reconnecting);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayWireBytePipe.test.ts b/fluxer_app/src/features/gateway/transport/GatewayWireBytePipe.test.ts
deleted file mode 100644
index 5646e0505..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayWireBytePipe.test.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {resolve} from 'node:path';
-import {constants, createZstdCompress, type ZstdCompress} from 'node:zlib';
-import {GatewayConnectionRole} from '@app/features/gateway/transport/GatewayConnectionRole';
-import {
- type GatewayDispatchDelivery,
- GatewaySocket,
- type GatewaySocketProperties,
-} from '@app/features/gateway/transport/GatewaySocket';
-import type {
- NativeGatewayTransportAPI,
- NativeGatewayTransportEvent,
- NativeGatewayTransportEventKind,
-} from '@fluxer/desktop_ipc/src/GatewayTransportContract';
-import {initSync} from '@pkgs/libfluxcore/libfluxcore';
-import {afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/platform/DesktopLocalAppRuntime', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/platform/DesktopLocalAppRuntime')>()),
- isDesktopLocalAppDocument: vi.fn(() => true),
-}));
-
-const wasmBytes = readFileSync(resolve(process.cwd(), 'pkgs/libfluxcore/libfluxcore_bg.wasm'));
-
-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',
-};
-
-type SocketEvent = {data?: unknown; code?: number; reason?: string; wasClean?: boolean};
-
-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}> = [];
- private readonly listeners = new Map<string, Set<(event: SocketEvent) => void>>();
-
- constructor(readonly url: string) {
- FakeWebSocket.instances.push(this);
- }
-
- addEventListener(type: string, callback: (event: SocketEvent) => void): void {
- const existing = this.listeners.get(type) ?? new Set();
- existing.add(callback);
- this.listeners.set(type, existing);
- }
-
- removeEventListener(type: string, callback: (event: SocketEvent) => void): void {
- this.listeners.get(type)?.delete(callback);
- }
-
- send(): void {}
-
- close(code: number, reason: string): void {
- this.closeCalls.push({code, reason});
- this.readyState = FakeWebSocket.CLOSED;
- }
-
- dispatch(type: string, event: SocketEvent = {}): void {
- for (const callback of [...(this.listeners.get(type) ?? [])]) {
- callback(event);
- }
- }
-
- openSocket(): void {
- this.readyState = FakeWebSocket.OPEN;
- this.dispatch('open');
- }
-}
-
-function gatewayJsonFrame(sequence: number): string {
- return JSON.stringify({
- op: 0,
- t: 'MESSAGE_CREATE',
- s: sequence,
- d: {id: String(sequence), content: `byte pipe payload ${sequence}`},
- });
-}
-
-function compressAndFlushChunk(encoder: ZstdCompress, payload: string): Promise<Uint8Array> {
- return new Promise((resolve, reject) => {
- const chunks: Array<Buffer> = [];
- const onData = (chunk: Buffer): void => {
- chunks.push(Buffer.from(chunk));
- };
- const cleanup = (): void => {
- encoder.off('data', onData);
- encoder.off('error', onError);
- };
- function onError(error: Error): void {
- cleanup();
- reject(error);
- }
- encoder.on('data', onData);
- encoder.once('error', onError);
- encoder.write(Buffer.from(payload), (error?: Error | null) => {
- if (error) {
- onError(error);
- return;
- }
- encoder.flush(constants.ZSTD_e_flush, () => {
- cleanup();
- resolve(new Uint8Array(Buffer.concat(chunks)));
- });
- });
- });
-}
-
-function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
- const copy = new Uint8Array(bytes.byteLength);
- copy.set(bytes);
- return copy.buffer;
-}
-
-function createDeployedGatewayEncoder(): ZstdCompress {
- return createZstdCompress({params: {[constants.ZSTD_c_compressionLevel]: 3}});
-}
-
-function createSocket(): GatewaySocket {
- return new GatewaySocket('wss://gateway.example/', {
- token: 'token-100',
- apiVersion: 9,
- properties: PROPERTIES,
- isMobileLayout: () => false,
- geo: () => ({latitude: null, longitude: null}),
- role: GatewayConnectionRole.FOREGROUND,
- });
-}
-
-async function waitFor(predicate: () => boolean): Promise<void> {
- for (let attempt = 0; attempt < 400; attempt += 1) {
- if (predicate()) return;
- await new Promise((resolve) => setTimeout(resolve, 5));
- }
- throw new Error('timed out waiting for the gateway socket');
-}
-
-function nativeEvent(
- connectionId: string,
- kind: NativeGatewayTransportEventKind,
- overrides: Partial<NativeGatewayTransportEvent> = {},
-): NativeGatewayTransportEvent {
- return {
- connectionId,
- kind,
- data: null,
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- ...overrides,
- };
-}
-
-interface NativeStub {
- api: NativeGatewayTransportAPI;
- connectionIds: Array<string>;
- emit(event: NativeGatewayTransportEvent): void;
-}
-
-function createNativeStub(): NativeStub {
- const listeners = new Set<(event: NativeGatewayTransportEvent) => void>();
- const connectionIds: Array<string> = [];
- return {
- api: {
- isAvailable: true,
- create: async ({connectionId}) => {
- connectionIds.push(connectionId);
- return {connectionId};
- },
- sendText: async () => undefined,
- sendBinary: async () => undefined,
- close: async () => undefined,
- dispose: async () => undefined,
- onEvent: (callback) => {
- listeners.add(callback);
- return () => listeners.delete(callback);
- },
- },
- connectionIds,
- emit: (event) => {
- for (const callback of [...listeners]) {
- callback(event);
- }
- },
- };
-}
-
-let originalWebSocket: unknown;
-
-beforeAll(() => {
- initSync({module: wasmBytes});
-});
-
-beforeEach(() => {
- originalWebSocket = Reflect.get(globalThis, 'WebSocket');
- Reflect.set(globalThis, 'WebSocket', FakeWebSocket);
- FakeWebSocket.instances = [];
-});
-
-afterEach(() => {
- Reflect.set(globalThis, 'WebSocket', originalWebSocket);
- Reflect.deleteProperty(window, 'electron');
- Reflect.deleteProperty(globalThis, '__fluxerDesktopGatewayTransport');
-});
-
-describe('deployed zstd-stream frames decode over both transports', () => {
- test('the browser transport delivers a level-3 unconstrained-window frame to the renderer codec', async () => {
- const encoder = createDeployedGatewayEncoder();
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- try {
- socket.connect();
- await waitFor(() => FakeWebSocket.instances.length === 1);
- const wire = FakeWebSocket.instances[0];
- wire.openSocket();
-
- for (let sequence = 1; sequence <= 3; sequence += 1) {
- const compressed = await compressAndFlushChunk(encoder, gatewayJsonFrame(sequence));
- wire.dispatch('message', {data: toArrayBuffer(compressed)});
- }
- await waitFor(() => deliveries.length === 3);
-
- expect(wire.url).toBe('wss://gateway.example/?v=9&encoding=json&compress=zstd-stream&stream=1');
- expect(wire.binaryType).toBe('arraybuffer');
- expect(deliveries.map((delivery) => delivery.receipt.sequence)).toEqual([1, 2, 3]);
- expect(deliveries.map((delivery) => (delivery.data as {content: string}).content)).toEqual([
- 'byte pipe payload 1',
- 'byte pipe payload 2',
- 'byte pipe payload 3',
- ]);
- } finally {
- socket.reset(false);
- encoder.destroy();
- }
- });
-
- test('the desktop native transport forwards the same frame verbatim and the renderer still decodes it', async () => {
- const encoder = createDeployedGatewayEncoder();
- const stub = createNativeStub();
- Reflect.set(window, 'electron', {nativeGatewayTransport: stub.api});
- const socket = createSocket();
- const deliveries: Array<GatewayDispatchDelivery> = [];
- socket.on('dispatch', (delivery) => deliveries.push(delivery));
-
- try {
- socket.connect();
- await waitFor(() => stub.connectionIds.length === 1);
- const connectionId = stub.connectionIds[0];
- stub.emit(nativeEvent(connectionId, 'open'));
-
- for (let sequence = 1; sequence <= 3; sequence += 1) {
- const compressed = await compressAndFlushChunk(encoder, gatewayJsonFrame(sequence));
- stub.emit(nativeEvent(connectionId, 'binary', {binary: toArrayBuffer(compressed)}));
- }
- await waitFor(() => deliveries.length === 3);
-
- expect(FakeWebSocket.instances).toHaveLength(0);
- expect(deliveries.map((delivery) => delivery.receipt.sequence)).toEqual([1, 2, 3]);
- expect(deliveries.map((delivery) => (delivery.data as {content: string}).content)).toEqual([
- 'byte pipe payload 1',
- 'byte pipe payload 2',
- 'byte pipe payload 3',
- ]);
- } finally {
- socket.reset(false);
- encoder.destroy();
- }
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayWireTransport.test.ts b/fluxer_app/src/features/gateway/transport/GatewayWireTransport.test.ts
deleted file mode 100644
index 90abf7541..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayWireTransport.test.ts
+++ /dev/null
@@ -1,521 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createGatewayWireTransport,
- GatewayWireReadyState,
- GatewayWireTransportKind,
- InvalidDesktopGatewayTransportRouterStateError,
- isDesktopNativeGatewayTransportAvailable,
-} from '@app/features/gateway/transport/GatewayWireTransport';
-import {isDesktopLocalAppDocument} from '@app/features/platform/DesktopLocalAppRuntime';
-import {
- NATIVE_GATEWAY_TRANSPORT_PROXIED_MESSAGE,
- type NativeGatewayTransportAPI,
- type NativeGatewayTransportEvent,
-} from '@fluxer/desktop_ipc/src/GatewayTransportContract';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/platform/DesktopLocalAppRuntime', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/platform/DesktopLocalAppRuntime')>()),
- isDesktopLocalAppDocument: vi.fn(() => true),
-}));
-
-const ROUTER_GLOBAL_KEY = '__fluxerDesktopGatewayTransport';
-
-type SocketEvent = {data?: unknown; code?: number; reason?: string; wasClean?: boolean};
-
-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 sent: Array<string | ArrayBuffer> = [];
- readonly closeCalls: Array<{code: number; reason: string}> = [];
- private readonly listeners = new Map<string, Set<(event: SocketEvent) => void>>();
-
- constructor(readonly url: string) {
- FakeWebSocket.instances.push(this);
- }
-
- addEventListener(type: string, callback: (event: SocketEvent) => void): void {
- const existing = this.listeners.get(type) ?? new Set();
- existing.add(callback);
- this.listeners.set(type, existing);
- }
-
- removeEventListener(type: string, callback: (event: SocketEvent) => void): void {
- this.listeners.get(type)?.delete(callback);
- }
-
- send(data: string | ArrayBuffer): void {
- this.sent.push(data);
- }
-
- close(code: number, reason: string): void {
- this.closeCalls.push({code, reason});
- this.readyState = FakeWebSocket.CLOSED;
- }
-
- dispatch(type: string, event: SocketEvent = {}): void {
- for (const callback of [...(this.listeners.get(type) ?? [])]) {
- callback(event);
- }
- }
-
- openSocket(): void {
- this.readyState = FakeWebSocket.OPEN;
- this.dispatch('open');
- }
-}
-
-interface NativeGatewayTransportStub {
- api: NativeGatewayTransportAPI;
- createdConnectionIds: Array<string>;
- disposedConnectionIds: Array<string>;
- sentBinary: Array<{connectionId: string; byteLength: number}>;
- sentText: Array<{connectionId: string; payload: string}>;
- emit(event: NativeGatewayTransportEvent): void;
- listenerCount(): number;
-}
-
-function createNativeGatewayTransportStub(
- overrides: Partial<NativeGatewayTransportAPI> = {},
-): NativeGatewayTransportStub {
- const listeners = new Set<(event: NativeGatewayTransportEvent) => void>();
- const createdConnectionIds: Array<string> = [];
- const disposedConnectionIds: Array<string> = [];
- const sentBinary: Array<{connectionId: string; byteLength: number}> = [];
- const sentText: Array<{connectionId: string; payload: string}> = [];
- const api: NativeGatewayTransportAPI = {
- isAvailable: true,
- create: async ({connectionId}) => {
- createdConnectionIds.push(connectionId);
- return {connectionId};
- },
- sendText: async ({connectionId, payload}) => {
- sentText.push({connectionId, payload});
- },
- sendBinary: async ({connectionId, payload}) => {
- sentBinary.push({connectionId, byteLength: payload.byteLength});
- },
- close: async () => undefined,
- dispose: async (connectionId) => {
- disposedConnectionIds.push(connectionId);
- },
- onEvent: (callback) => {
- listeners.add(callback);
- return () => listeners.delete(callback);
- },
- ...overrides,
- };
- return {
- api,
- createdConnectionIds,
- disposedConnectionIds,
- sentBinary,
- sentText,
- emit: (event) => {
- for (const callback of [...listeners]) {
- callback(event);
- }
- },
- listenerCount: () => listeners.size,
- };
-}
-
-function installElectronAPI(nativeGatewayTransport: unknown): void {
- Reflect.set(window, 'electron', {nativeGatewayTransport});
-}
-
-function flush(): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-let originalWebSocket: unknown;
-
-beforeEach(() => {
- originalWebSocket = Reflect.get(globalThis, 'WebSocket');
- Reflect.set(globalThis, 'WebSocket', FakeWebSocket);
- FakeWebSocket.instances = [];
-});
-
-afterEach(() => {
- Reflect.set(globalThis, 'WebSocket', originalWebSocket);
- Reflect.deleteProperty(window, 'electron');
- Reflect.deleteProperty(globalThis, ROUTER_GLOBAL_KEY);
-});
-
-describe('transport selection', () => {
- test('a web document with no electron API gets the browser transport', () => {
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- expect(Reflect.get(globalThis, ROUTER_GLOBAL_KEY)).toBeUndefined();
- });
-
- test('a desktop shell whose addon failed to load degrades to the browser transport', () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI({...stub.api, isAvailable: false});
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- });
-
- test('a desktop shell that predates the transport namespace degrades to the browser transport', () => {
- Reflect.set(window, 'electron', {});
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- });
-
- test('a shell missing any one transport method degrades to the browser transport', () => {
- const stub = createNativeGatewayTransportStub();
- const {sendBinary: _dropped, ...partial} = stub.api;
- installElectronAPI({...partial, isAvailable: true});
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- });
-
- test('an available addon gets the desktop native transport', () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.DESKTOP_NATIVE);
- });
-
- test('a non-local-app document (e.g. a bounced web login) never uses the native transport', () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- vi.mocked(isDesktopLocalAppDocument).mockReturnValueOnce(false);
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
-
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- expect(stub.createdConnectionIds).toEqual([]);
- });
-
- test('a corrupted router global throws a typed error', () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- Reflect.set(globalThis, ROUTER_GLOBAL_KEY, {rendererRouterId: 'not-a-uuid', api: null, router: null});
-
- expect(() => createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'})).toThrow(
- InvalidDesktopGatewayTransportRouterStateError,
- );
- });
-});
-
-describe('browser transport', () => {
- test('dispose closes a still-connecting socket and detaches every listener', () => {
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- const closes: Array<number> = [];
- transport.on('close', (event) => closes.push(event.code));
- transport.start();
- const socket = FakeWebSocket.instances[0];
-
- transport.dispose();
- socket.dispatch('close', {code: 1000, reason: '', wasClean: true});
-
- expect(socket.closeCalls).toEqual([{code: 1000, reason: 'Disposing stale socket'}]);
- expect(closes).toEqual([]);
- expect(transport.readyState).toBe(GatewayWireReadyState.CLOSED);
- });
-});
-
-describe('desktop connection routing', () => {
- test('an event for a retired connection is dropped, not misrouted', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- const retired = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- const survivor = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- const survivorMessages: Array<unknown> = [];
- survivor.on('message', (event) => survivorMessages.push(event.data));
- retired.start();
- survivor.start();
- await flush();
- const [retiredConnectionId, survivorConnectionId] = stub.createdConnectionIds;
- retired.dispose();
-
- stub.emit({
- connectionId: survivorConnectionId,
- kind: 'open',
- data: null,
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- });
- stub.emit({
- connectionId: retiredConnectionId,
- kind: 'message',
- data: '{"op":11}',
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- });
-
- expect(retiredConnectionId).not.toBe(survivorConnectionId);
- expect(survivorMessages).toEqual([]);
- expect(stub.disposedConnectionIds).toEqual([retiredConnectionId]);
- });
-
- test('connection ids are scoped to this document', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- const messages: Array<unknown> = [];
- transport.on('message', (event) => messages.push(event.data));
- transport.start();
- await flush();
- stub.emit({
- connectionId: stub.createdConnectionIds[0],
- kind: 'open',
- data: null,
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- });
-
- stub.emit({
- connectionId: 'gateway-renderer-00000000-0000-4000-8000-000000000000:other',
- kind: 'message',
- data: '{"op":11}',
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- });
-
- expect(stub.createdConnectionIds[0]).toMatch(
- /^gateway-renderer-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}:/,
- );
- expect(messages).toEqual([]);
- });
-
- test('one router serves every connection in the document', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
-
- const first = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- const second = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- first.start();
- second.start();
- await flush();
-
- expect(stub.listenerCount()).toBe(1);
- expect(stub.createdConnectionIds).toHaveLength(2);
- });
-
- test('the renderer sends compressed frames as binary and never as text', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- const transport = createGatewayWireTransport('wss://gateway.example/', {
- binaryType: 'arraybuffer',
- });
- transport.start();
- await flush();
- stub.emit({
- connectionId: stub.createdConnectionIds[0],
- kind: 'open',
- data: null,
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- });
-
- transport.send(new Uint8Array([1, 2, 3, 4]));
- await flush();
-
- expect(stub.sentBinary).toEqual([{connectionId: stub.createdConnectionIds[0], byteLength: 4}]);
- expect(stub.sentText).toEqual([]);
- });
-});
-
-describe('native transport fallback', () => {
- function nativeEvent(
- connectionId: string,
- overrides: Partial<NativeGatewayTransportEvent>,
- ): NativeGatewayTransportEvent {
- return {
- connectionId,
- kind: 'open',
- data: null,
- binary: null,
- code: null,
- reason: null,
- wasClean: null,
- message: null,
- ...overrides,
- };
- }
-
- async function failBeforeOpen(stub: NativeGatewayTransportStub, message: string): Promise<void> {
- const transport = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- expect(transport.kind).toBe(GatewayWireTransportKind.DESKTOP_NATIVE);
- const closes: Array<number> = [];
- transport.on('close', (event) => closes.push(event.code));
- transport.on('error', () => undefined);
- transport.start();
- await flush();
- const connectionId = stub.createdConnectionIds.at(-1) ?? '';
- stub.emit(nativeEvent(connectionId, {kind: 'error', message}));
- stub.emit(
- nativeEvent(connectionId, {
- kind: 'close',
- code: 1006,
- reason: 'Gateway websocket connect failed',
- wasClean: false,
- }),
- );
- expect(closes).toEqual([1006]);
- transport.dispose();
- }
-
- test('three native connects that close before opening switch new transports to the browser', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
-
- for (let attempt = 0; attempt < 3; attempt += 1) {
- await failBeforeOpen(stub, 'gateway websocket connect failed: IO error: invalid peer certificate: UnknownIssuer');
- }
-
- expect(isDesktopNativeGatewayTransportAvailable()).toBe(false);
- const transport = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- expect(transport.kind).toBe(GatewayWireTransportKind.BROWSER);
- transport.start();
- expect(FakeWebSocket.instances.map((socket) => socket.url)).toEqual(['wss://gateway.example/']);
- });
-
- test('native creates the shell refuses count toward the fallback', async () => {
- const stub = createNativeGatewayTransportStub({
- create: async () => {
- throw new Error('The native gateway transport addon is unavailable');
- },
- });
- installElectronAPI(stub.api);
-
- for (let attempt = 0; attempt < 3; attempt += 1) {
- const transport = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- expect(transport.kind).toBe(GatewayWireTransportKind.DESKTOP_NATIVE);
- const closes: Array<number> = [];
- transport.on('close', (event) => closes.push(event.code));
- transport.on('error', () => undefined);
- transport.start();
- await flush();
- expect(closes).toEqual([1006]);
- }
-
- expect(createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'}).kind).toBe(
- GatewayWireTransportKind.BROWSER,
- );
- });
-
- test('a gateway the shell routes through a proxy switches new transports to the browser at once', async () => {
- const stub = createNativeGatewayTransportStub({
- create: async () => {
- throw new Error(
- `Error invoking remote method 'native-gateway-transport:create': Error: ${NATIVE_GATEWAY_TRANSPORT_PROXIED_MESSAGE}`,
- );
- },
- });
- installElectronAPI(stub.api);
-
- const transport = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- expect(transport.kind).toBe(GatewayWireTransportKind.DESKTOP_NATIVE);
- transport.on('error', () => undefined);
- transport.start();
- await flush();
-
- const next = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- expect(next.kind).toBe(GatewayWireTransportKind.BROWSER);
- next.start();
- expect(FakeWebSocket.instances.map((socket) => socket.url)).toEqual(['wss://gateway.example/']);
- });
-
- test('an open between failures resets the count', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
-
- await failBeforeOpen(stub, 'gateway websocket connect timed out');
- await failBeforeOpen(stub, 'gateway websocket connect timed out');
- const healthy = createGatewayWireTransport('wss://gateway.example/', {binaryType: 'arraybuffer'});
- healthy.start();
- await flush();
- stub.emit(nativeEvent(stub.createdConnectionIds.at(-1) ?? '', {kind: 'open'}));
- healthy.dispose();
- await failBeforeOpen(stub, 'gateway websocket connect timed out');
- await failBeforeOpen(stub, 'gateway websocket connect timed out');
-
- expect(isDesktopNativeGatewayTransportAvailable()).toBe(true);
- });
-
- test('a gateway that answers the upgrade with an HTTP error does not trip the fallback', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
-
- for (let attempt = 0; attempt < 4; attempt += 1) {
- await failBeforeOpen(stub, 'gateway websocket connect failed: HTTP error: 502 Bad Gateway');
- }
-
- expect(isDesktopNativeGatewayTransportAvailable()).toBe(true);
- });
-
- test('failures while the browser reports offline do not trip the fallback', async () => {
- const stub = createNativeGatewayTransportStub();
- installElectronAPI(stub.api);
- const onLine = vi.spyOn(window.navigator, 'onLine', 'get').mockReturnValue(false);
-
- try {
- for (let attempt = 0; attempt < 4; attempt += 1) {
- await failBeforeOpen(stub, 'gateway websocket connect failed: IO error: Network is unreachable');
- }
- } finally {
- onLine.mockRestore();
- }
-
- expect(isDesktopNativeGatewayTransportAvailable()).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/platform/components/router/RouterHistory.test.ts b/fluxer_app/src/features/platform/components/router/RouterHistory.test.ts
deleted file mode 100644
index 439195358..000000000
--- a/fluxer_app/src/features/platform/components/router/RouterHistory.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-interface Entry {
- url: string;
- state: unknown;
-}
-
-class SessionHistory extends EventTarget {
- entries: Array<Entry> = [{url: 'http://localhost/channels/@me', state: null}];
- index = 0;
- readonly location = {
- get href(): string {
- return session.entries[session.index].url;
- },
- };
- readonly history = {
- get state(): unknown {
- return session.entries[session.index].state;
- },
- pushState: (state: unknown, _title: string, url: URL | string) => {
- this.entries.splice(this.index + 1, this.entries.length, {url: String(url), state});
- this.index += 1;
- },
- replaceState: (state: unknown, _title: string, url: URL | string) => {
- this.entries[this.index] = {url: String(url), state};
- },
- go: (delta: number) => this.traverse(delta),
- back: () => this.traverse(-1),
- };
-
- private traverse(delta: number): void {
- setTimeout(() => {
- const target = this.index + delta;
- if (target < 0 || target >= this.entries.length) return;
- this.index = target;
- this.dispatchEvent(new Event('popstate'));
- }, 0);
- }
-}
-
-let session: SessionHistory;
-
-beforeEach(() => {
- vi.resetModules();
- session = new SessionHistory();
- vi.stubGlobal('window', session);
-});
-
-afterEach(() => {
- vi.unstubAllGlobals();
-});
-
-async function settle(): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, 5));
-}
-
-describe('browser history', () => {
- test('a replace issued while a back traversal is in flight lands after it', async () => {
- const {createBrowserHistory} = await import('@app/features/platform/components/router/RouterHistory');
- const history = createBrowserHistory();
- history.push(new URL('http://localhost/channels/@me'), {modal: 'switcher'});
-
- history.back();
- history.replace(new URL('http://localhost/channels/1/2'));
- await settle();
-
- expect(session.index).toBe(0);
- expect(session.location.href).toBe('http://localhost/channels/1/2');
- expect(session.history.state).toBeNull();
- });
-
- test('a push issued while a back traversal is in flight lands after it', async () => {
- const {createBrowserHistory} = await import('@app/features/platform/components/router/RouterHistory');
- const history = createBrowserHistory();
- history.push(new URL('http://localhost/channels/@me'), {modal: 'switcher'});
-
- history.back();
- history.push(new URL('http://localhost/channels/1/2'));
- await settle();
-
- expect(session.entries.map((entry) => entry.url)).toEqual([
- 'http://localhost/channels/@me',
- 'http://localhost/channels/1/2',
- ]);
- expect(session.index).toBe(1);
- });
-
- test('a back traversal with nowhere to go does not hold later navigation forever', async () => {
- const {createBrowserHistory} = await import('@app/features/platform/components/router/RouterHistory');
- const history = createBrowserHistory();
-
- history.back();
- history.replace(new URL('http://localhost/channels/1/2'));
- await new Promise((resolve) => setTimeout(resolve, 600));
-
- expect(session.location.href).toBe('http://localhost/channels/1/2');
- });
-
- test('listeners hear the deferred navigation', async () => {
- const {createBrowserHistory} = await import('@app/features/platform/components/router/RouterHistory');
- const history = createBrowserHistory();
- const heard: Array<string> = [];
- history.listen((location) => heard.push(location.url.pathname));
- history.push(new URL('http://localhost/channels/@me'), {modal: 'switcher'});
- heard.length = 0;
-
- history.back();
- history.replace(new URL('http://localhost/channels/1/2'));
- await settle();
-
- expect(heard.at(-1)).toBe('/channels/1/2');
- });
-});
diff --git a/fluxer_app/src/features/platform/service_worker/WorkerAppShell.test.ts b/fluxer_app/src/features/platform/service_worker/WorkerAppShell.test.ts
deleted file mode 100644
index a4f19081b..000000000
--- a/fluxer_app/src/features/platform/service_worker/WorkerAppShell.test.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type AppShellRuntime,
- fetchAppShellNavigation,
- type PrecacheEntry,
- precacheAssets,
- seedAppShell,
-} from '@app/features/platform/service_worker/WorkerAppShell';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-const WORKER_ORIGIN = 'https://self-hosted.fluxer.test';
-const PRECACHE_NAME = 'fluxer-precache-test';
-const NAVIGATION_CACHE_NAME = 'fluxer-navigation-test';
-const NETWORK_TIMEOUT_MS = 10;
-const SLOW_NETWORK_MS = 80;
-
-const UNRENDERED_INDEX_TEMPLATE = [
- '<!doctype html><html lang="en"><head>',
- '<link rel="preconnect" href="{{STATIC_CDN_ENDPOINT}}">',
- '<link rel="apple-touch-icon" href="{{STATIC_CDN_ENDPOINT}}/web/apple-touch-icon.png">',
- '<script></script>',
- '</head><body><div id="root"></div></body></html>',
-].join('');
-
-const RENDERED_INDEX_DOCUMENT = [
- '<!doctype html><html lang="en"><head>',
- '<link rel="preconnect" href="https://cdn.fluxer.test">',
- '<script>window.__FLUXER_BOOTSTRAP__={"instance":{}};</script>',
- '</head><body><div id="root"></div></body></html>',
-].join('');
-
-const MARKETING_DOCUMENT = '<!doctype html><html lang="en"><head></head><body>Marketing</body></html>';
-
-const DEPLOYED_PRECACHE_MANIFEST: ReadonlyArray<PrecacheEntry> = [
- {url: '/manifest.json', revision: '512:1'},
- {url: '/version.json', revision: '32:1'},
-];
-
-class FakeCache {
- private readonly entries = new Map<string, Response>();
-
- async put(request: Request | string, response: Response): Promise<void> {
- this.entries.set(cacheKey(request), response);
- }
-
- async match(request: Request | string): Promise<Response | undefined> {
- return this.entries.get(cacheKey(request))?.clone();
- }
-
- async delete(request: Request | string): Promise<boolean> {
- return this.entries.delete(cacheKey(request));
- }
-}
-
-class FakeCacheStorage {
- private readonly caches = new Map<string, FakeCache>();
-
- async open(name: string): Promise<FakeCache> {
- const existing = this.caches.get(name);
- if (existing) {
- return existing;
- }
- const created = new FakeCache();
- this.caches.set(name, created);
- return created;
- }
-
- async match(request: Request | string): Promise<Response | undefined> {
- for (const cache of this.caches.values()) {
- const hit = await cache.match(request);
- if (hit) {
- return hit;
- }
- }
- return undefined;
- }
-
- async keys(): Promise<Array<string>> {
- return Array.from(this.caches.keys());
- }
-}
-
-function cacheKey(request: Request | string): string {
- const url = typeof request === 'string' ? request : request.url;
- return new URL(url, WORKER_ORIGIN).toString();
-}
-
-function delay(milliseconds: number): Promise<void> {
- return new Promise((resolve) => {
- setTimeout(resolve, milliseconds);
- });
-}
-
-function createAppProxyFetch(navigationDelayMs: number): (request: Request) => Promise<Response> {
- return async (request: Request) => {
- const {pathname} = new URL(request.url);
- if (pathname === '/index.html') {
- return new Response(UNRENDERED_INDEX_TEMPLATE, {headers: {'content-type': 'text/html; charset=utf-8'}});
- }
- if (pathname === '/manifest.json' || pathname === '/version.json') {
- return new Response('{}', {headers: {'content-type': 'application/json'}});
- }
- await delay(navigationDelayMs);
- return new Response(RENDERED_INDEX_DOCUMENT, {
- headers: {'content-type': 'text/html; charset=utf-8', 'x-fluxer-app-shell': '1'},
- });
- };
-}
-
-function navigationRequest(pathname: string): Request {
- return new Request(`${WORKER_ORIGIN}${pathname}`, {headers: {accept: 'text/html'}});
-}
-
-describe('WorkerAppShell', () => {
- let cacheStorage: FakeCacheStorage;
-
- function createRuntime(navigationDelayMs: number): AppShellRuntime {
- return {
- caches: cacheStorage as unknown as CacheStorage,
- fetch: createAppProxyFetch(navigationDelayMs),
- origin: WORKER_ORIGIN,
- precacheName: PRECACHE_NAME,
- navigationCacheName: NAVIGATION_CACHE_NAME,
- networkTimeoutMs: NETWORK_TIMEOUT_MS,
- onCacheWriteError: (error) => {
- throw error;
- },
- };
- }
-
- beforeEach(() => {
- cacheStorage = new FakeCacheStorage();
- });
-
- it('never serves the app-proxy index template that was fetched outside the bootstrap render', async () => {
- const runtime = createRuntime(SLOW_NETWORK_MS);
- await precacheAssets(runtime, DEPLOYED_PRECACHE_MANIFEST);
-
- const response = await fetchAppShellNavigation(runtime, navigationRequest('/channels/1234567890/9876543210'));
- const html = await response.text();
-
- expect(html).toContain('window.__FLUXER_BOOTSTRAP__');
- expect(html).not.toContain('{{STATIC_CDN_ENDPOINT}}');
- });
-
- it('replays the previously rendered document when the network loses the navigation race', async () => {
- const runtime = createRuntime(0);
- await precacheAssets(runtime, DEPLOYED_PRECACHE_MANIFEST);
- await fetchAppShellNavigation(runtime, navigationRequest('/channels/@me'));
-
- const slowRuntime = createRuntime(SLOW_NETWORK_MS);
- const response = await fetchAppShellNavigation(slowRuntime, navigationRequest('/channels/1234567890/9876543210'));
- const html = await response.text();
-
- expect(html).toBe(RENDERED_INDEX_DOCUMENT);
- });
-
- it('serves the seeded app shell when the network is unavailable', async () => {
- await seedAppShell(createRuntime(0));
-
- const offlineRuntime: AppShellRuntime = {
- ...createRuntime(0),
- fetch: () => Promise.reject(new Error('Failed to fetch')),
- };
- const response = await fetchAppShellNavigation(offlineRuntime, navigationRequest('/channels/@me'));
-
- expect(await response.text()).toBe(RENDERED_INDEX_DOCUMENT);
- });
-
- it('ignores an unrendered template left in the precache by an older worker', async () => {
- const precache = await cacheStorage.open(PRECACHE_NAME);
- await precache.put(
- '/index.html',
- new Response(UNRENDERED_INDEX_TEMPLATE, {headers: {'content-type': 'text/html; charset=utf-8'}}),
- );
- await precache.put(
- '/',
- new Response(UNRENDERED_INDEX_TEMPLATE, {headers: {'content-type': 'text/html; charset=utf-8'}}),
- );
- await seedAppShell(createRuntime(0));
-
- const response = await fetchAppShellNavigation(createRuntime(SLOW_NETWORK_MS), navigationRequest('/channels/1/2'));
- const html = await response.text();
-
- expect(html).toContain('window.__FLUXER_BOOTSTRAP__');
- expect(html).not.toContain('{{STATIC_CDN_ENDPOINT}}');
- });
-
- it('never keeps a document without the app shell marker as the app shell', async () => {
- await seedAppShell(createRuntime(0));
- const marketingRuntime: AppShellRuntime = {
- ...createRuntime(0),
- fetch: async () => new Response(MARKETING_DOCUMENT, {headers: {'content-type': 'text/html; charset=utf-8'}}),
- };
- await fetchAppShellNavigation(marketingRuntime, navigationRequest('/channels/@me'));
-
- const offlineRuntime: AppShellRuntime = {
- ...createRuntime(0),
- fetch: () => Promise.reject(new Error('Failed to fetch')),
- };
- const response = await fetchAppShellNavigation(offlineRuntime, navigationRequest('/channels/@me'));
-
- expect(await response.text()).toBe(RENDERED_INDEX_DOCUMENT);
- });
-});
diff --git a/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.test.ts b/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.test.ts
deleted file mode 100644
index 288d1c4c1..000000000
--- a/fluxer_app/src/features/platform/service_worker/WorkerFetchRouting.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getWorkerFetchRoute} from '@app/features/platform/service_worker/WorkerFetchRouting';
-import {describe, expect, it} from 'vitest';
-
-const WORKER_ORIGIN = 'https://app.fluxer.test';
-
-function request(url: string, init?: RequestInit): Request {
- return new Request(url, init);
-}
-
-describe('WorkerFetchRouting', () => {
- it('does not intercept expression media URLs', () => {
- expect(getWorkerFetchRoute(request('https://fluxerusercontent.com/emojis/123.webp'), WORKER_ORIGIN)).toBe('ignore');
- expect(getWorkerFetchRoute(request('https://fluxerusercontent.com/stickers/456.webp'), WORKER_ORIGIN)).toBe(
- 'ignore',
- );
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/emojis/123.webp`), WORKER_ORIGIN)).toBe('ignore');
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/stickers/456.webp`), WORKER_ORIGIN)).toBe('ignore');
- });
-
- it('keeps app-owned runtime routes explicit', () => {
- expect(
- getWorkerFetchRoute(request(`${WORKER_ORIGIN}/channels/@me`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN),
- ).toBe('navigation');
- expect(
- getWorkerFetchRoute(request(`${WORKER_ORIGIN}/admin`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN),
- ).toBe('ignore');
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/app`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN)).toBe(
- 'navigation',
- );
- expect(
- getWorkerFetchRoute(request(`${WORKER_ORIGIN}/migrate/export`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN),
- ).toBe('navigation');
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN)).toBe(
- 'ignore',
- );
- expect(
- getWorkerFetchRoute(request(`${WORKER_ORIGIN}/passkey-bridge`, {headers: {accept: 'text/html'}}), WORKER_ORIGIN),
- ).toBe('ignore');
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/manifest.json`), WORKER_ORIGIN)).toBe('metadata');
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/version.json`), WORKER_ORIGIN)).toBe('metadata');
- });
-
- it('leaves every build output under /assets/ to the immutable HTTP cache', () => {
- const buildOutputs = [
- '/assets/16bf14551996ba83.js',
- '/assets/2d715e4730758083.worker.js',
- '/assets/38cf6fb33e42e52d.css',
- '/assets/a79f1c3119cd700d.woff2',
- '/assets/0f50c815cd5e74ce.wasm',
- '/assets/ff9b1f835d5aa8cb.png',
- '/assets/22e569554c3be0e5.webm',
- '/assets/63a33cf1048e51c7.mp3',
- '/assets/fonts-NOTICE.txt',
- '/assets/chunk',
- '/assets/fonts/inter',
- ];
- for (const pathname of buildOutputs) {
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}${pathname}`), WORKER_ORIGIN)).toBe('ignore');
- }
- });
-
- it('only recognises metadata served from the worker origin', () => {
- expect(getWorkerFetchRoute(request('https://cdn.fluxer.test/manifest.json'), WORKER_ORIGIN)).toBe('ignore');
- expect(getWorkerFetchRoute(request('https://cdn.fluxer.test/version.json'), WORKER_ORIGIN)).toBe('ignore');
- });
-
- it('ignores non-GET requests', () => {
- expect(getWorkerFetchRoute(request(`${WORKER_ORIGIN}/version.json`, {method: 'POST'}), WORKER_ORIGIN)).toBe(
- 'ignore',
- );
- });
-});
diff --git a/fluxer_app/src/features/platform/transport/RestTransport.test.ts b/fluxer_app/src/features/platform/transport/RestTransport.test.ts
deleted file mode 100644
index 12f8cddd9..000000000
--- a/fluxer_app/src/features/platform/transport/RestTransport.test.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {RestClient} from '@app/features/platform/transport/RestTransport';
-import type {RestInterceptor, RestResponse} from '@app/features/platform/types/TransportTypes';
-import type {MessageDescriptor} from '@lingui/core';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));
-
-const desktopDocument = vi.hoisted(() => ({active: false}));
-
-vi.mock('@app/features/platform/DesktopLocalAppRuntime', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@app/features/platform/DesktopLocalAppRuntime')>();
- return {...actual, isDesktopLocalAppDocument: () => desktopDocument.active};
-});
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- getElectronAPI: () => (desktopDocument.active ? {localAppUpload: {subscribe: () => () => {}}} : undefined),
-}));
-
-interface SentRequest {
- method: string;
- url: string;
- headers: Record<string, string>;
- body: unknown;
-}
-
-interface Reply {
- status: number;
- body: unknown;
-}
-
-const replies: Array<Reply> = [];
-const sent: Array<SentRequest> = [];
-
-class StubXMLHttpRequest extends EventTarget {
- readonly upload = new EventTarget();
- private readonly headers: Record<string, string> = {};
- private method = '';
- private url = '';
- status = 200;
- statusText = 'OK';
- responseText = '';
- response: unknown = '';
- responseType = '';
- timeout = 0;
-
- open(method: string, url: string): void {
- this.method = method;
- this.url = url;
- }
-
- setRequestHeader(name: string, value: string): void {
- this.headers[name.toLowerCase()] = value;
- }
-
- getAllResponseHeaders(): string {
- return 'content-type: application/json\r\n';
- }
-
- abort(): void {
- this.dispatchEvent(new Event('abort'));
- this.dispatchEvent(new Event('loadend'));
- }
-
- send(body: unknown): void {
- sent.push({method: this.method, url: this.url, headers: {...this.headers}, body});
- const reply = replies.shift() ?? {status: 200, body: {}};
- this.status = reply.status;
- this.statusText = reply.status >= 200 && reply.status < 300 ? 'OK' : 'Error';
- this.responseText = JSON.stringify(reply.body);
- this.response = this.responseText;
- queueMicrotask(() => {
- this.dispatchEvent(new Event('load'));
- this.dispatchEvent(new Event('loadend'));
- });
- }
-}
-
-const CAPTCHA_REPLY: Reply = {status: 400, body: {code: 'CAPTCHA_REQUIRED'}};
-const SUDO_REQUIRED_REPLY: Reply = {status: 403, body: {code: 'SUDO_MODE_REQUIRED'}};
-
-function captchaRetryingInterceptor(token: string): RestInterceptor & ReturnType<typeof vi.fn> {
- return vi.fn((reply: RestResponse, retry: (extra: Record<string, string>) => Promise<RestResponse>) => {
- if (reply.status !== 400) return undefined;
- return retry({'X-Captcha-Token': token});
- });
-}
-
-function captchaCalls(interceptor: ReturnType<typeof vi.fn>): number {
- return interceptor.mock.calls.filter(([reply]) => (reply as RestResponse).status === 400).length;
-}
-
-function createClient(): RestClient {
- const client = new RestClient();
- client.configure({baseUrl: 'https://active.test/api', apiVersion: 1});
- return client;
-}
-
-beforeEach(() => {
- vi.stubGlobal('XMLHttpRequest', StubXMLHttpRequest);
- replies.length = 0;
- sent.length = 0;
-});
-
-afterEach(() => {
- vi.unstubAllGlobals();
- desktopDocument.active = false;
-});
-
-describe('RestClient desktop local upload tagging', () => {
- const uploadIdHeader = 'x-fluxer-local-upload-id';
-
- test('a remote upload from the desktop app never carries the local upload id', async () => {
- desktopDocument.active = true;
- await createClient().put('https://uploads.fluxer.app/v1/relay/abc?t=token', {
- body: new Blob(['x']),
- auth: 'none',
- onProgress: () => {},
- });
- expect(sent[0].headers[uploadIdHeader]).toBeUndefined();
- });
-
- test('an upload through the desktop local proxy is tagged for progress', async () => {
- desktopDocument.active = true;
- await createClient().put('fluxer-app://app/_remote/key?url=https%3A%2F%2Fuploads.test%2Fv1%2Frelay%2Fabc', {
- body: new Blob(['x']),
- auth: 'none',
- onProgress: () => {},
- });
- expect(sent[0].headers[uploadIdHeader]).toMatch(/^[0-9a-f]{32}$/u);
- });
-});
-
-describe('RestClient interceptor selection', () => {
- test('uses the global interceptor when the request has none', async () => {
- const client = createClient();
- const global = captchaRetryingInterceptor('global-token');
- client.installHooks({intercept: global});
- replies.push(CAPTCHA_REPLY, {status: 200, body: {ok: true}});
-
- const reply = await client.post('/auth/login', {body: {}});
-
- expect(reply.status).toBe(200);
- expect(global).toHaveBeenCalledTimes(1);
- expect(sent[1].headers['x-captcha-token']).toBe('global-token');
- });
-
- test('the interceptor retry runs with no interceptor at all', async () => {
- const client = createClient();
- const global = captchaRetryingInterceptor('global-token');
- client.installHooks({intercept: global});
- replies.push(CAPTCHA_REPLY, CAPTCHA_REPLY);
-
- await expect(client.post('/auth/register', {body: {}})).rejects.toMatchObject({status: 400});
-
- expect(global).toHaveBeenCalledTimes(1);
- expect(sent).toHaveLength(2);
- });
-
- test('the sudo reissue falls back to the global interceptor', async () => {
- const client = createClient();
- const global = captchaRetryingInterceptor('global-token');
- client.installHooks({intercept: global});
- client.installSudo({
- tokenProvider: () => null,
- tokenListener: () => undefined,
- invalidate: () => undefined,
- prompt: async () => ({password: 'hunter2'}),
- onFailure: () => undefined,
- });
- replies.push(SUDO_REQUIRED_REPLY, CAPTCHA_REPLY, {status: 200, body: {}});
-
- const reply = await client.post('/users/@me/disable', {body: {}});
-
- expect(reply.status).toBe(200);
- expect(captchaCalls(global)).toBe(1);
- expect(sent[2].headers['x-captcha-token']).toBe('global-token');
- });
-});
-
-describe('RestClient account transition aborts', () => {
- test('a request waiting out a retry backoff rejects with the account transition abort', async () => {
- const {AccountScopedWork, AccountScopedWorkTransitionReason} = await import(
- '@app/features/platform/state/AccountScopedWork'
- );
- const {isAccountTransitionAbortError} = await import('@app/features/platform/state/AccountTransitionAbort');
- const client = createClient();
- replies.push({status: 502, body: {}});
-
- const request = client.get('/users/@me', {retries: 3});
- const settled = request.then(
- () => null,
- (error: unknown) => error,
- );
- await vi.waitFor(() => expect(sent).toHaveLength(1));
- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.ACCOUNT_SWITCH, async () => {});
-
- const error = await settled;
- expect(isAccountTransitionAbortError(error)).toBe(true);
- expect(sent).toHaveLength(1);
- });
-});
diff --git a/fluxer_app/src/features/platform/utils/DesktopModuleRequest.test.ts b/fluxer_app/src/features/platform/utils/DesktopModuleRequest.test.ts
deleted file mode 100644
index a084ffaa2..000000000
--- a/fluxer_app/src/features/platform/utils/DesktopModuleRequest.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createDesktopModuleRequest} from '@app/features/platform/utils/DesktopModuleRequest';
-import type {ElectronAPI} from '@app/types/electron.d';
-import type {DesktopModuleEnsureResult, DesktopModuleEnsureStatus} from '@fluxer/desktop_ipc/src/ModuleContract';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const MODULE_NAME = 'fluxer_twemoji';
-const BACKOFF_MAX_MS = 30_000;
-
-type EnsureSpy = ReturnType<typeof vi.fn<(module: string) => Promise<DesktopModuleEnsureResult>>>;
-
-function installElectron(api: Partial<ElectronAPI>): void {
- Object.defineProperty(window, 'electron', {value: api as ElectronAPI, configurable: true, writable: true});
-}
-
-function installEnsure(ensure: (module: string) => Promise<DesktopModuleEnsureResult>): EnsureSpy {
- const spy = vi.fn(ensure);
- installElectron({desktopModules: {ensure: spy}});
- return spy;
-}
-
-function settled(status: DesktopModuleEnsureStatus): (module: string) => Promise<DesktopModuleEnsureResult> {
- return (module: string) => Promise.resolve({module, status});
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- Reflect.deleteProperty(window, 'electron');
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe('createDesktopModuleRequest', () => {
- it('settles ready and notifies once when there is no desktop shell', async () => {
- const request = createDesktopModuleRequest(MODULE_NAME);
- const listener = vi.fn();
- request.subscribe(listener);
-
- await expect(request.ensure()).resolves.toBeNull();
-
- expect(request.isSettled()).toBe(true);
- expect(listener).toHaveBeenCalledTimes(1);
- });
-
- it('holds off while the module is unavailable, then upgrades on the scheduled retry', async () => {
- let call = 0;
- const ensure = installEnsure((module) => {
- call += 1;
- return Promise.resolve({module, status: call === 1 ? 'unavailable' : 'installed'});
- });
- const request = createDesktopModuleRequest(MODULE_NAME);
- const listener = vi.fn();
- request.subscribe(listener);
-
- await expect(request.ensure()).resolves.toBe('unavailable');
- expect(request.isSettled()).toBe(false);
- expect(listener).toHaveBeenCalled();
- const notificationsBeforeRetry = listener.mock.calls.length;
-
- await vi.advanceTimersByTimeAsync(BACKOFF_MAX_MS);
-
- expect(ensure).toHaveBeenCalledTimes(2);
- expect(request.isSettled()).toBe(true);
- expect(listener.mock.calls.length).toBeGreaterThan(notificationsBeforeRetry);
- await expect(request.ensure()).resolves.toBeNull();
- });
-
- it('recovers on the scheduled retry after the shell rejects the request', async () => {
- let call = 0;
- const ensure = installEnsure((module) => {
- call += 1;
- if (call === 1) {
- return Promise.reject(new Error('ipc down'));
- }
- return Promise.resolve({module, status: 'installed'});
- });
- const request = createDesktopModuleRequest(MODULE_NAME);
-
- await expect(request.ensure()).resolves.toBeNull();
- expect(request.isSettled()).toBe(false);
-
- await vi.advanceTimersByTimeAsync(BACKOFF_MAX_MS);
-
- expect(ensure).toHaveBeenCalledTimes(2);
- expect(request.isSettled()).toBe(true);
- await expect(request.ensure()).resolves.toBeNull();
- });
-
- it('treats ready as terminal and never re-enters loading', async () => {
- const ensure = installEnsure(settled('installed'));
- const request = createDesktopModuleRequest(MODULE_NAME);
-
- await expect(request.ensure()).resolves.toBe('installed');
- await expect(request.ensure()).resolves.toBeNull();
- await expect(request.ensure()).resolves.toBeNull();
-
- expect(ensure).toHaveBeenCalledTimes(1);
- expect(request.isSettled()).toBe(true);
- });
-
- it('clears the armed retry timer on reset so no further load fires', async () => {
- const ensure = installEnsure(settled('unavailable'));
- const request = createDesktopModuleRequest(MODULE_NAME);
-
- await expect(request.ensure()).resolves.toBe('unavailable');
- expect(ensure).toHaveBeenCalledTimes(1);
-
- request.reset();
- await vi.advanceTimersByTimeAsync(BACKOFF_MAX_MS);
-
- expect(ensure).toHaveBeenCalledTimes(1);
- expect(request.isSettled()).toBe(false);
- });
-
- it('coalesces a re-entrant ensure fired from a notify listener into the in-flight load', async () => {
- const ensure = installEnsure(settled('unavailable'));
- const request = createDesktopModuleRequest(MODULE_NAME);
- let reentered = 0;
- request.subscribe(() => {
- reentered += 1;
- void request.ensure();
- });
-
- await expect(request.ensure()).resolves.toBe('unavailable');
-
- expect(ensure).toHaveBeenCalledTimes(1);
- expect(reentered).toBeGreaterThan(0);
- expect(request.isSettled()).toBe(false);
- });
-
- it('drops a stale in-flight resolution that lands after reset', async () => {
- let resolveEnsure: (result: DesktopModuleEnsureResult) => void = () => {};
- installEnsure(
- (module) =>
- new Promise<DesktopModuleEnsureResult>((resolve) => {
- resolveEnsure = () => resolve({module, status: 'installed'});
- }),
- );
- const request = createDesktopModuleRequest(MODULE_NAME);
-
- const settle = request.ensure();
- expect(request.isSettled()).toBe(false);
-
- request.reset();
- resolveEnsure({module: MODULE_NAME, status: 'installed'});
- await settle;
-
- expect(request.isSettled()).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/utils/RandomUuid.test.ts b/fluxer_app/src/features/platform/utils/RandomUuid.test.ts
deleted file mode 100644
index ff250f909..000000000
--- a/fluxer_app/src/features/platform/utils/RandomUuid.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {randomUuid} from '@app/features/platform/utils/RandomUuid';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {}}));
-
-const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
-
-describe('without crypto.randomUUID', () => {
- beforeEach(() => {
- Object.defineProperty(globalThis.crypto, 'randomUUID', {value: undefined, configurable: true});
- });
-
- afterEach(() => {
- Reflect.deleteProperty(globalThis.crypto, 'randomUUID');
- });
-
- test('randomUuid returns distinct v4 UUIDs', () => {
- const ids = new Set(Array.from({length: 64}, () => randomUuid()));
- expect(ids.size).toBe(64);
- for (const id of ids) {
- expect(id).toMatch(UUID_V4);
- }
- });
-
- test('member search context is created on composer mount', async () => {
- const {SearchContext} = await import('@app/features/member/state/MemberSearch');
- const first = new SearchContext(() => {});
- const second = new SearchContext(() => {});
- expect(first).toBeInstanceOf(SearchContext);
- expect(second).not.toBe(first);
- });
-
- test('toasts and custom keybinds get ids', async () => {
- const [{default: Toasts}, {generateCustomKeybindId}] = await Promise.all([
- import('@app/features/ui/state/Toast'),
- import('@app/features/input/state/input_keybind/KeybindSyncCodec'),
- ]);
- const toastId = Toasts.success('saved');
- expect(toastId).toMatch(UUID_V4);
- expect(generateCustomKeybindId()).toMatch(UUID_V4);
- });
-});