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 useless frontend tests (#2819)

Hampusdeac653a9ed1
diff --git a/fluxer_app/pkgs/livekit-client/src/room/defaults.test.ts b/fluxer_app/pkgs/livekit-client/src/room/defaults.test.ts
deleted file mode 100644
index 385389026..000000000
--- a/fluxer_app/pkgs/livekit-client/src/room/defaults.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
-//
-// SPDX-License-Identifier: Apache-2.0
-import {describe, expect, it} from 'vitest';
-import {defaultVideoCodec, publishDefaults, roomOptionDefaults} from './defaults.ts';
-import {BackupCodecPolicy} from './track/options.ts';
-import {selectPreferredVideoCodec} from './utils.ts';
-
-describe('Fluxer media publish defaults', () => {
- it('defaults new video publishes to an opt-in-safe codec with H.264 backup', () => {
- expect(defaultVideoCodec).toBe('h264');
- expect(publishDefaults).toMatchObject({
- videoCodec: 'h264',
- backupCodec: {codec: 'h264'},
- backupCodecPolicy: BackupCodecPolicy.SIMULCAST,
- degradationPreference: 'maintain-resolution',
- dtx: false,
- red: true,
- });
- });
-
- it('falls back away from the opt-in codecs before reaching them', () => {
- expect(selectPreferredVideoCodec()).toBe('h264');
- expect(selectPreferredVideoCodec()).not.toBe('av1');
- expect(selectPreferredVideoCodec()).not.toBe('h265');
- });
-
- it('keeps original screen-share publishing at a 4K60-ready transport ceiling', () => {
- expect(publishDefaults.screenShareEncoding).toMatchObject({
- maxBitrate: 20_000_000,
- maxFramerate: 60,
- priority: 'high',
- });
- });
-
- it('uses publisher-side stream control defaults for high-fidelity screen sharing', () => {
- expect(roomOptionDefaults).toMatchObject({
- adaptiveStream: false,
- dynacast: true,
- singlePeerConnection: true,
- });
- });
-});
diff --git a/fluxer_app/pkgs/livekit-client/src/room/participant/publishUtils.maxEncodingBitrate.test.ts b/fluxer_app/pkgs/livekit-client/src/room/participant/publishUtils.maxEncodingBitrate.test.ts
deleted file mode 100644
index bac9a1078..000000000
--- a/fluxer_app/pkgs/livekit-client/src/room/participant/publishUtils.maxEncodingBitrate.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
-//
-// SPDX-License-Identifier: Apache-2.0
-import {describe, expect, it} from 'vitest';
-import {maxEncodingBitrate} from './publishUtils.ts';
-
-describe('maxEncodingBitrate', () => {
- it('returns the highest layer bitrate for a simulcast ladder', () => {
- expect(maxEncodingBitrate([{maxBitrate: 150_000}, {maxBitrate: 500_000}, {maxBitrate: 1_700_000}])).toBe(1_700_000);
- });
-
- it('returns the single encoding bitrate for a non-simulcast publish', () => {
- expect(maxEncodingBitrate([{maxBitrate: 3_000_000}])).toBe(3_000_000);
- });
-
- it('returns zero when no encoding declares a bitrate', () => {
- expect(maxEncodingBitrate([{}])).toBe(0);
- expect(maxEncodingBitrate([])).toBe(0);
- expect(maxEncodingBitrate(undefined)).toBe(0);
- });
-});
diff --git a/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.test.ts b/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.test.ts
deleted file mode 100644
index c398fcbb2..000000000
--- a/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
-//
-// SPDX-License-Identifier: Apache-2.0
-import {describe, expect, it} from 'vitest';
-import {videoLayersFromEncodings} from './LocalVideoTrack.ts';
-
-describe('videoLayersFromEncodings', () => {
- it('treats SVC codecs without a configured scalability mode as a single layer', () => {
- const layers = videoLayersFromEncodings(1920, 1080, [{maxBitrate: 12_000_000}], true);
- expect(layers).toHaveLength(1);
- expect(layers[0]).toMatchObject({
- width: 1920,
- height: 1080,
- bitrate: 12_000_000,
- });
- });
-});
diff --git a/fluxer_app/src/features/accessibility/state/MessageGroupSpacing.test.ts b/fluxer_app/src/features/accessibility/state/MessageGroupSpacing.test.ts
deleted file mode 100644
index f3dae7385..000000000
--- a/fluxer_app/src/features/accessibility/state/MessageGroupSpacing.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- COMFY_MESSAGE_GROUP_SPACING_DEFAULT,
- COMPACT_MESSAGE_GROUP_SPACING_DEFAULT,
- getDefaultMessageGroupSpacing,
- getMessageGroupSpacingForDisplayMode,
- getMessageGroupSpacingPatch,
- migrateLegacyMessageGroupSpacing,
-} from '@app/features/accessibility/state/MessageGroupSpacing';
-import {describe, expect, it} from 'vitest';
-
-describe('MessageGroupSpacing', () => {
- it('keeps explicit defaults per display mode', () => {
- expect(getDefaultMessageGroupSpacing(false)).toBe(COMFY_MESSAGE_GROUP_SPACING_DEFAULT);
- expect(getDefaultMessageGroupSpacing(true)).toBe(COMPACT_MESSAGE_GROUP_SPACING_DEFAULT);
- });
- it('reads the spacing for the active display mode', () => {
- const settings = {messageGroupSpacing: 16, compactMessageGroupSpacing: 0};
- expect(getMessageGroupSpacingForDisplayMode(settings, false)).toBe(16);
- expect(getMessageGroupSpacingForDisplayMode(settings, true)).toBe(0);
- });
- it('updates only the active display mode', () => {
- expect(getMessageGroupSpacingPatch(false, 8)).toEqual({messageGroupSpacing: 8});
- expect(getMessageGroupSpacingPatch(true, 8)).toEqual({compactMessageGroupSpacing: 8});
- });
- it('migrates legacy default spacing to separate mode defaults', () => {
- expect(migrateLegacyMessageGroupSpacing(16, false)).toEqual({
- messageGroupSpacing: 16,
- compactMessageGroupSpacing: 0,
- });
- expect(migrateLegacyMessageGroupSpacing(0, true)).toEqual({
- messageGroupSpacing: 16,
- compactMessageGroupSpacing: 0,
- });
- });
- it('migrates legacy custom spacing as a shared custom value', () => {
- expect(migrateLegacyMessageGroupSpacing(8, false)).toEqual({
- messageGroupSpacing: 8,
- compactMessageGroupSpacing: 8,
- });
- expect(migrateLegacyMessageGroupSpacing(8, true)).toEqual({
- messageGroupSpacing: 8,
- compactMessageGroupSpacing: 8,
- });
- });
-});
diff --git a/fluxer_app/src/features/accessibility/state/MotionPreferencesMachine.test.ts b/fluxer_app/src/features/accessibility/state/MotionPreferencesMachine.test.ts
deleted file mode 100644
index 124ed9deb..000000000
--- a/fluxer_app/src/features/accessibility/state/MotionPreferencesMachine.test.ts
+++ /dev/null
@@ -1,393 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMotionPreferencesContext,
- createMotionPreferencesSnapshot,
- getMotionPreferencesStateValue,
- type MotionPreferencesEvent,
- type MotionPreferencesInput,
- type MotionPreferencesSnapshot,
- resolveAnimateEmojiRequest,
- resolveAnimateStickersRequest,
- resolveGifAutoPlayRequest,
- resolveMotionPreferencesModel,
- selectBaseAnimateStickers,
- selectEffectiveAnimateEmoji,
- selectEffectiveAnimateStickers,
- selectEffectiveGifAutoPlay,
- selectIsAnimationKeptUnderReducedMotion,
- selectReducedMotionActive,
- selectReducedMotionSource,
- selectSmoothScrollingEnabled,
- transitionMotionPreferencesSnapshot,
-} from '@app/features/accessibility/state/MotionPreferencesMachine';
-import {StickerAnimationOptions} from '@fluxer/constants/src/UserConstants';
-import {describe, expect, it} from 'vitest';
-
-const {ALWAYS_ANIMATE, ANIMATE_ON_INTERACTION, NEVER_ANIMATE} = StickerAnimationOptions;
-
-function ctx(input: MotionPreferencesInput = {}) {
- return createMotionPreferencesContext(input);
-}
-
-function transition(snapshot: MotionPreferencesSnapshot, event: MotionPreferencesEvent): MotionPreferencesSnapshot {
- return transitionMotionPreferencesSnapshot(snapshot, event);
-}
-
-function legacyEffectiveEmoji(base: boolean, reduced: boolean): boolean {
- return reduced ? false : base;
-}
-function legacyEffectiveGif(base: boolean, reduced: boolean): boolean {
- return reduced ? false : base;
-}
-function legacyEffectiveSticker(base: number, reduced: boolean): number {
- if (reduced && base === ALWAYS_ANIMATE) return ANIMATE_ON_INTERACTION;
- return base;
-}
-
-describe('selectReducedMotionActive / source', () => {
- it('follows the system query when syncing', () => {
- expect(selectReducedMotionActive(ctx({syncWithSystem: true, systemReducedMotion: true}))).toBe(true);
- expect(selectReducedMotionActive(ctx({syncWithSystem: true, systemReducedMotion: false}))).toBe(false);
- expect(selectReducedMotionSource(ctx({syncWithSystem: true}))).toBe('system');
- });
-
- it('ignores the system query and uses the manual override when not syncing', () => {
- expect(
- selectReducedMotionActive(ctx({syncWithSystem: false, manualReducedMotion: true, systemReducedMotion: false})),
- ).toBe(true);
- expect(
- selectReducedMotionActive(ctx({syncWithSystem: false, manualReducedMotion: false, systemReducedMotion: true})),
- ).toBe(false);
- expect(selectReducedMotionSource(ctx({syncWithSystem: false}))).toBe('manual');
- });
-
- it('keeps smooth scrolling tied to the inverse of reduced motion', () => {
- expect(selectSmoothScrollingEnabled(ctx({syncWithSystem: false, manualReducedMotion: false}))).toBe(true);
- expect(selectSmoothScrollingEnabled(ctx({syncWithSystem: false, manualReducedMotion: true}))).toBe(false);
- });
-});
-
-describe('effective values without reduced motion', () => {
- it('returns the base desktop preference verbatim', () => {
- const c = ctx({
- syncWithSystem: false,
- manualReducedMotion: false,
- animateEmoji: true,
- gifAutoPlay: false,
- animateStickers: ALWAYS_ANIMATE,
- });
- expect(selectEffectiveAnimateEmoji(c)).toBe(true);
- expect(selectEffectiveGifAutoPlay(c)).toBe(false);
- expect(selectEffectiveAnimateStickers(c)).toBe(ALWAYS_ANIMATE);
- });
-
- it('applies mobile overrides and defaults', () => {
- const overridden = ctx({
- isMobile: true,
- mobileAnimateEmojiOverridden: true,
- mobileAnimateEmojiValue: false,
- mobileGifAutoPlayOverridden: true,
- mobileGifAutoPlayValue: true,
- mobileStickerAnimationOverridden: true,
- mobileStickerAnimationValue: NEVER_ANIMATE,
- });
- expect(selectEffectiveAnimateEmoji(overridden)).toBe(false);
- expect(selectEffectiveGifAutoPlay(overridden)).toBe(true);
- expect(selectEffectiveAnimateStickers(overridden)).toBe(NEVER_ANIMATE);
-
- const defaults = ctx({isMobile: true, animateEmoji: true, gifAutoPlay: true, animateStickers: ALWAYS_ANIMATE});
- expect(selectEffectiveAnimateEmoji(defaults)).toBe(true);
- expect(selectEffectiveGifAutoPlay(defaults)).toBe(false);
- expect(selectBaseAnimateStickers(defaults)).toBe(ANIMATE_ON_INTERACTION);
- });
-});
-
-describe('reduced motion defaults content animation off (no opt-in)', () => {
- const reduced = {syncWithSystem: false, manualReducedMotion: true} as const;
-
- it('pauses emoji and gif and downgrades always-animate stickers', () => {
- const c = ctx({...reduced, animateEmoji: true, gifAutoPlay: true, animateStickers: ALWAYS_ANIMATE});
- expect(selectEffectiveAnimateEmoji(c)).toBe(false);
- expect(selectEffectiveGifAutoPlay(c)).toBe(false);
- expect(selectEffectiveAnimateStickers(c)).toBe(ANIMATE_ON_INTERACTION);
- });
-
- it('leaves on-interaction and never-animate stickers untouched', () => {
- expect(selectEffectiveAnimateStickers(ctx({...reduced, animateStickers: ANIMATE_ON_INTERACTION}))).toBe(
- ANIMATE_ON_INTERACTION,
- );
- expect(selectEffectiveAnimateStickers(ctx({...reduced, animateStickers: NEVER_ANIMATE}))).toBe(NEVER_ANIMATE);
- });
-});
-
-describe('reduced motion can be overridden per setting (the fix)', () => {
- const reduced = {syncWithSystem: false, manualReducedMotion: true} as const;
-
- it('keeps emoji animating when opted in', () => {
- const c = ctx({...reduced, animateEmoji: true, keepAnimatedEmojiUnderReducedMotion: true});
- expect(selectEffectiveAnimateEmoji(c)).toBe(true);
- });
-
- it('keeps gif autoplay when opted in', () => {
- const c = ctx({...reduced, gifAutoPlay: true, keepGifAutoPlayUnderReducedMotion: true});
- expect(selectEffectiveGifAutoPlay(c)).toBe(true);
- });
-
- it('keeps always-animate stickers when opted in', () => {
- const c = ctx({...reduced, animateStickers: ALWAYS_ANIMATE, keepStickerAnimationUnderReducedMotion: true});
- expect(selectEffectiveAnimateStickers(c)).toBe(ALWAYS_ANIMATE);
- });
-
- it('opting in does not resurrect a base preference that is itself off', () => {
- const c = ctx({...reduced, animateEmoji: false, keepAnimatedEmojiUnderReducedMotion: true});
- expect(selectEffectiveAnimateEmoji(c)).toBe(false);
- });
-
- it('overrides are independent across settings', () => {
- const c = ctx({
- ...reduced,
- animateEmoji: true,
- gifAutoPlay: true,
- animateStickers: ALWAYS_ANIMATE,
- keepAnimatedEmojiUnderReducedMotion: true,
- });
- expect(selectEffectiveAnimateEmoji(c)).toBe(true);
- expect(selectEffectiveGifAutoPlay(c)).toBe(false);
- expect(selectEffectiveAnimateStickers(c)).toBe(ANIMATE_ON_INTERACTION);
- });
-});
-
-describe('useShouldAnimate gate helper', () => {
- const reduced = {syncWithSystem: false, manualReducedMotion: true} as const;
-
- it('reports the per-kind keep flag', () => {
- const c = ctx({
- ...reduced,
- keepAnimatedEmojiUnderReducedMotion: true,
- keepGifAutoPlayUnderReducedMotion: false,
- keepStickerAnimationUnderReducedMotion: true,
- });
- expect(selectIsAnimationKeptUnderReducedMotion(c, 'emoji')).toBe(true);
- expect(selectIsAnimationKeptUnderReducedMotion(c, 'gif')).toBe(false);
- expect(selectIsAnimationKeptUnderReducedMotion(c, 'sticker')).toBe(true);
- });
-});
-
-describe('backwards compatibility with the legacy forced override', () => {
- const bases = [true, false];
- const stickerValues = [ALWAYS_ANIMATE, ANIMATE_ON_INTERACTION, NEVER_ANIMATE];
- for (const reduced of [false, true]) {
- for (const emoji of bases) {
- it(`emoji base=${emoji} reduced=${reduced} matches legacy with no opt-in`, () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: reduced, animateEmoji: emoji});
- expect(selectEffectiveAnimateEmoji(c)).toBe(legacyEffectiveEmoji(emoji, reduced));
- });
- }
- for (const gif of bases) {
- it(`gif base=${gif} reduced=${reduced} matches legacy with no opt-in`, () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: reduced, gifAutoPlay: gif});
- expect(selectEffectiveGifAutoPlay(c)).toBe(legacyEffectiveGif(gif, reduced));
- });
- }
- for (const sticker of stickerValues) {
- it(`sticker base=${sticker} reduced=${reduced} matches legacy with no opt-in`, () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: reduced, animateStickers: sticker});
- expect(selectEffectiveAnimateStickers(c)).toBe(legacyEffectiveSticker(sticker, reduced));
- });
- }
- }
-});
-
-describe('resolveAnimateEmojiRequest', () => {
- it('writes the base preference directly when reduced motion is off (desktop)', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: false});
- expect(resolveAnimateEmojiRequest(c, true)).toEqual({animateEmoji: true});
- expect(resolveAnimateEmojiRequest(c, false)).toEqual({animateEmoji: false});
- });
-
- it('writes the mobile override when reduced motion is off (mobile)', () => {
- const c = ctx({isMobile: true, syncWithSystem: false, manualReducedMotion: false});
- expect(resolveAnimateEmojiRequest(c, true)).toEqual({
- mobileAnimateEmojiOverridden: true,
- mobileAnimateEmojiValue: true,
- });
- });
-
- it('opting in under reduced motion sets the keep flag and the base preference', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true, animateEmoji: false});
- expect(resolveAnimateEmojiRequest(c, true)).toEqual({
- animateEmoji: true,
- keepAnimatedEmojiUnderReducedMotion: true,
- });
- });
-
- it('opting out under reduced motion only clears the keep flag, preserving the base preference', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true, animateEmoji: true});
- expect(resolveAnimateEmojiRequest(c, false)).toEqual({keepAnimatedEmojiUnderReducedMotion: false});
- });
-});
-
-describe('resolveGifAutoPlayRequest', () => {
- it('opting in under reduced motion sets the keep flag', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true});
- expect(resolveGifAutoPlayRequest(c, true)).toEqual({gifAutoPlay: true, keepGifAutoPlayUnderReducedMotion: true});
- });
-
- it('opting out under reduced motion clears the keep flag', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true});
- expect(resolveGifAutoPlayRequest(c, false)).toEqual({keepGifAutoPlayUnderReducedMotion: false});
- });
-});
-
-describe('resolveAnimateStickersRequest', () => {
- it('writes the value directly when reduced motion is off', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: false});
- expect(resolveAnimateStickersRequest(c, ALWAYS_ANIMATE)).toEqual({animateStickers: ALWAYS_ANIMATE});
- });
-
- it('always-animate opts the setting out of reduced motion', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true});
- expect(resolveAnimateStickersRequest(c, ALWAYS_ANIMATE)).toEqual({
- animateStickers: ALWAYS_ANIMATE,
- keepStickerAnimationUnderReducedMotion: true,
- });
- });
-
- it('reduced-motion-friendly choices store the value and clear the keep flag', () => {
- const c = ctx({syncWithSystem: false, manualReducedMotion: true});
- expect(resolveAnimateStickersRequest(c, ANIMATE_ON_INTERACTION)).toEqual({
- animateStickers: ANIMATE_ON_INTERACTION,
- keepStickerAnimationUnderReducedMotion: false,
- });
- expect(resolveAnimateStickersRequest(c, NEVER_ANIMATE)).toEqual({
- animateStickers: NEVER_ANIMATE,
- keepStickerAnimationUnderReducedMotion: false,
- });
- });
-
- it('routes through the mobile override on mobile', () => {
- const c = ctx({isMobile: true, syncWithSystem: false, manualReducedMotion: true});
- expect(resolveAnimateStickersRequest(c, ALWAYS_ANIMATE)).toEqual({
- mobileStickerAnimationOverridden: true,
- mobileStickerAnimationValue: ALWAYS_ANIMATE,
- keepStickerAnimationUnderReducedMotion: true,
- });
- });
-});
-
-describe('machine state value', () => {
- it('settles to full when reduced motion is inactive', () => {
- const snapshot = createMotionPreferencesSnapshot({syncWithSystem: true, systemReducedMotion: false});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('full');
- });
-
- it('settles to reduced when reduced motion is active', () => {
- const snapshot = createMotionPreferencesSnapshot({syncWithSystem: false, manualReducedMotion: true});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('reduced');
- });
-
- it('transitions full -> reduced when the system query flips', () => {
- let snapshot = createMotionPreferencesSnapshot({syncWithSystem: true, systemReducedMotion: false});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('full');
- snapshot = transition(snapshot, {type: 'system.reducedMotionChanged', value: true});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('reduced');
- snapshot = transition(snapshot, {type: 'system.reducedMotionChanged', value: false});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('full');
- });
-
- it('disabling sync falls back to the manual override and re-routes', () => {
- let snapshot = createMotionPreferencesSnapshot({
- syncWithSystem: true,
- systemReducedMotion: true,
- manualReducedMotion: false,
- });
- expect(getMotionPreferencesStateValue(snapshot)).toBe('reduced');
- snapshot = transition(snapshot, {type: 'syncWithSystem.set', value: false});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('full');
- });
-});
-
-describe('machine request lifecycle', () => {
- it('re-enables emoji under reduced motion and restores the base when reduced motion lifts', () => {
- let snapshot = createMotionPreferencesSnapshot({
- syncWithSystem: false,
- manualReducedMotion: true,
- animateEmoji: false,
- });
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(false);
-
- snapshot = transition(snapshot, {type: 'animateEmoji.requested', value: true});
- expect(snapshot.context.keepAnimatedEmojiUnderReducedMotion).toBe(true);
- expect(snapshot.context.animateEmoji).toBe(true);
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(true);
-
- snapshot = transition(snapshot, {type: 'manualReducedMotion.set', value: false});
- expect(getMotionPreferencesStateValue(snapshot)).toBe('full');
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(true);
- });
-
- it('opting an animation back out under reduced motion preserves the pre-reduced-motion base', () => {
- let snapshot = createMotionPreferencesSnapshot({
- syncWithSystem: false,
- manualReducedMotion: false,
- animateEmoji: true,
- });
- snapshot = transition(snapshot, {type: 'manualReducedMotion.set', value: true});
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(false);
-
- snapshot = transition(snapshot, {type: 'animateEmoji.requested', value: true});
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(true);
- snapshot = transition(snapshot, {type: 'animateEmoji.requested', value: false});
- expect(snapshot.context.keepAnimatedEmojiUnderReducedMotion).toBe(false);
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(false);
-
- snapshot = transition(snapshot, {type: 'manualReducedMotion.set', value: false});
- expect(selectEffectiveAnimateEmoji(snapshot.context)).toBe(true);
- });
-
- it('keeps external syncs (base prefs, mobile, keep flags) flowing into the resolved model', () => {
- let snapshot = createMotionPreferencesSnapshot({syncWithSystem: false, manualReducedMotion: true});
- snapshot = transition(snapshot, {type: 'basePreferences.synced', animateStickers: ALWAYS_ANIMATE});
- snapshot = transition(snapshot, {type: 'keepFlags.synced', keepStickerAnimationUnderReducedMotion: true});
- expect(selectEffectiveAnimateStickers(snapshot.context)).toBe(ALWAYS_ANIMATE);
- snapshot = transition(snapshot, {type: 'platform.changed', isMobile: true});
- snapshot = transition(snapshot, {
- type: 'mobileOverrides.synced',
- mobileStickerAnimationOverridden: true,
- mobileStickerAnimationValue: NEVER_ANIMATE,
- });
- expect(selectEffectiveAnimateStickers(snapshot.context)).toBe(NEVER_ANIMATE);
- });
-});
-
-describe('resolveMotionPreferencesModel', () => {
- it('flags settings that are overriding reduced motion for the UI', () => {
- const model = resolveMotionPreferencesModel({
- syncWithSystem: false,
- manualReducedMotion: true,
- animateEmoji: true,
- gifAutoPlay: true,
- animateStickers: ALWAYS_ANIMATE,
- keepAnimatedEmojiUnderReducedMotion: true,
- keepStickerAnimationUnderReducedMotion: true,
- });
- expect(model.reducedMotion).toBe(true);
- expect(model.emojiOverridesReducedMotion).toBe(true);
- expect(model.gifOverridesReducedMotion).toBe(false);
- expect(model.stickerOverridesReducedMotion).toBe(true);
- expect(model.effectiveAnimateEmoji).toBe(true);
- expect(model.effectiveGifAutoPlay).toBe(false);
- expect(model.effectiveAnimateStickers).toBe(ALWAYS_ANIMATE);
- });
-
- it('reports no overrides when reduced motion is off', () => {
- const model = resolveMotionPreferencesModel({
- syncWithSystem: false,
- manualReducedMotion: false,
- keepAnimatedEmojiUnderReducedMotion: true,
- });
- expect(model.reducedMotion).toBe(false);
- expect(model.emojiOverridesReducedMotion).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDefaultDestinations.test.ts b/fluxer_app/src/features/app/components/dialogs/shared/ForwardDefaultDestinations.test.ts
deleted file mode 100644
index 3441ba9d0..000000000
--- a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDefaultDestinations.test.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildForwardDefaultDestinations,
- type ForwardDestination,
- type ForwardDestinationRow,
- type ForwardRowIdentity,
- filterForwardSearchRows,
- resolveForwardOrigin,
-} from '@app/features/app/components/dialogs/shared/ForwardDefaultDestinations';
-import type {ForwardResultType} from '@app/features/app/components/dialogs/shared/ForwardDestinationQuery';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it} from 'vitest';
-
-const DM_RECIPIENTS: ReadonlyMap<string, string> = new Map([['dm-1', 'user-1']]);
-const KNOWN_USERS: ReadonlySet<string> = new Set(['user-1', 'user-9']);
-const INVALID_IDS: ReadonlySet<string> = new Set(['text-blocked']);
-
-function channelType(channelId: string): ForwardResultType | null {
- if (channelId.startsWith('text-')) return 'text_channel';
- if (channelId.startsWith('voice-')) return 'voice_channel';
- if (channelId.startsWith('gdm-')) return 'group_dm';
- return null;
-}
-
-function resolveChannel(channelId: string): ForwardRowIdentity | null {
- const recipientId = DM_RECIPIENTS.get(channelId);
- if (recipientId !== undefined) return {id: recipientId, type: 'user'};
- const type = channelType(channelId);
- return type == null ? null : {id: channelId, type};
-}
-
-function resolveDestination(destination: ForwardDestination): ForwardRowIdentity | null {
- if (destination.type === 'channel') return resolveChannel(destination.id);
- return KNOWN_USERS.has(destination.id) ? {id: destination.id, type: 'user'} : null;
-}
-
-function isValid(row: ForwardRowIdentity): boolean {
- return !INVALID_IDS.has(row.id);
-}
-
-interface DefaultsOverrides {
- readonly frequentIds?: ReadonlyArray<string>;
- readonly history?: ReadonlyArray<string>;
- readonly mode?: ForwardResultType | null;
- readonly origin?: ForwardDestination | null;
- readonly pinned?: ReadonlyArray<ForwardDestination>;
- readonly selected?: ReadonlyArray<ForwardDestination>;
-}
-
-function defaults(overrides: DefaultsOverrides): ReadonlyArray<string> {
- const rows = buildForwardDefaultDestinations({
- frequentIds: [],
- history: [],
- isValid,
- mode: null,
- origin: null,
- pinned: [],
- resolveChannel,
- resolveDestination,
- selected: [],
- ...overrides,
- });
- return rows.map((row) => `${row.type}:${row.id}`);
-}
-
-function channelIds(prefix: string, count: number): ReadonlyArray<string> {
- return Array.from({length: count}, (_, index) => `${prefix}-${index}`);
-}
-
-describe('buildForwardDefaultDestinations', () => {
- it('lists pinned destinations, then history, then frecency, keeping the first copy of each', () => {
- expect(
- defaults({
- frequentIds: ['voice-1', 'guild-1', 'text-1', 'gdm-1'],
- history: ['text-1', 'text-2', 'dm-1'],
- pinned: [
- {id: 'text-2', type: 'channel'},
- {id: 'user-9', type: 'user'},
- ],
- }),
- ).toEqual([
- 'text_channel:text-2',
- 'user:user-9',
- 'text_channel:text-1',
- 'user:user-1',
- 'voice_channel:voice-1',
- 'group_dm:gdm-1',
- ]);
- });
-
- it('drops unknown users, unresolvable ids and invalid rows', () => {
- expect(
- defaults({
- frequentIds: ['guild-1', 'text-blocked', 'text-1'],
- pinned: [{id: 'user-unknown', type: 'user'}],
- }),
- ).toEqual(['text_channel:text-1']);
- });
-
- it('hides the origin channel unless it is selected', () => {
- const origin: ForwardDestination = {id: 'text-1', type: 'channel'};
- expect(defaults({history: ['text-1', 'text-2'], origin})).toEqual(['text_channel:text-2']);
- expect(defaults({history: ['text-1', 'text-2'], origin, selected: [origin]})).toEqual([
- 'text_channel:text-1',
- 'text_channel:text-2',
- ]);
- });
-
- it('hides the recipient of a DM origin', () => {
- const origin = resolveForwardOrigin('dm-1', {recipientIds: ['user-1'], type: ChannelTypes.DM});
- expect(origin).toEqual({id: 'user-1', type: 'user'});
- expect(defaults({history: ['dm-1', 'text-1'], origin})).toEqual(['text_channel:text-1']);
- });
-
- it('caps the list at 15 rows', () => {
- expect(defaults({frequentIds: channelIds('text', 20)})).toEqual(
- channelIds('text', 15).map((id) => `text_channel:${id}`),
- );
- });
-
- it('filters to the mode without a cap', () => {
- const frequentIds = [...channelIds('text', 20), 'dm-1', 'voice-1'];
- expect(defaults({frequentIds, mode: 'text_channel'})).toEqual(
- channelIds('text', 20).map((id) => `text_channel:${id}`),
- );
- expect(defaults({frequentIds, mode: 'user'})).toEqual(['user:user-1']);
- });
-
- it('reads at most 8 history entries and 100 frecency entries', () => {
- const history = channelIds('text-h', 10);
- const frequentIds = channelIds('text-f', 120);
- const rows = defaults({frequentIds, history, mode: 'text_channel'});
- expect(rows).toHaveLength(108);
- expect(rows).not.toContain('text_channel:text-h-8');
- expect(rows).not.toContain('text_channel:text-f-100');
- });
-
- it('maps each row to the destination the selection stores', () => {
- const rows = buildForwardDefaultDestinations({
- frequentIds: ['dm-1', 'gdm-1', 'voice-1'],
- history: [],
- isValid,
- mode: null,
- origin: null,
- pinned: [],
- resolveChannel,
- resolveDestination,
- selected: [],
- });
- expect(rows.map((row) => row.destination)).toEqual([
- {id: 'user-1', type: 'user'},
- {id: 'gdm-1', type: 'channel'},
- {id: 'voice-1', type: 'channel'},
- ]);
- });
-});
-
-describe('resolveForwardOrigin', () => {
- it('uses the channel for anything but a DM', () => {
- expect(resolveForwardOrigin('text-1', {recipientIds: [], type: ChannelTypes.GUILD_TEXT})).toEqual({
- id: 'text-1',
- type: 'channel',
- });
- expect(resolveForwardOrigin('gdm-1', {recipientIds: ['user-1', 'user-9'], type: ChannelTypes.GROUP_DM})).toEqual({
- id: 'gdm-1',
- type: 'channel',
- });
- expect(resolveForwardOrigin('text-1', null)).toEqual({id: 'text-1', type: 'channel'});
- });
-});
-
-describe('filterForwardSearchRows', () => {
- it('drops invalid rows and duplicate ids without a cap or origin exclusion', () => {
- const results: ReadonlyArray<ForwardRowIdentity> = [
- {id: 'user-1', type: 'user'},
- {id: 'text-blocked', type: 'text_channel'},
- {id: 'text-1', type: 'text_channel'},
- {id: 'text-1', type: 'voice_channel'},
- ...channelIds('text-x', 30).map((id): ForwardRowIdentity => ({id, type: 'text_channel'})),
- ];
- const rows: ReadonlyArray<ForwardDestinationRow> = filterForwardSearchRows(results, isValid);
- expect(rows).toHaveLength(32);
- expect(rows.slice(0, 2)).toEqual([
- {destination: {id: 'user-1', type: 'user'}, id: 'user-1', type: 'user'},
- {destination: {id: 'text-1', type: 'channel'}, id: 'text-1', type: 'text_channel'},
- ]);
- });
-});
diff --git a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationQuery.test.ts b/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationQuery.test.ts
deleted file mode 100644
index 3d8a39a4b..000000000
--- a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationQuery.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {parseForwardDestinationQuery} from '@app/features/app/components/dialogs/shared/ForwardDestinationQuery';
-import {describe, expect, it} from 'vitest';
-
-const ALL_TYPES = ['user', 'text_channel', 'voice_channel', 'group_dm'];
-
-describe('parseForwardDestinationQuery', () => {
- it('searches every destination type without a sigil', () => {
- expect(parseForwardDestinationQuery('general')).toEqual({mode: null, query: 'general', resultTypes: ALL_TYPES});
- expect(parseForwardDestinationQuery('')).toEqual({mode: null, query: '', resultTypes: ALL_TYPES});
- });
-
- it('narrows to one type for the @, # and ! sigils', () => {
- expect(parseForwardDestinationQuery('@bob')).toEqual({mode: 'user', query: 'bob', resultTypes: ['user']});
- expect(parseForwardDestinationQuery('#gen')).toEqual({
- mode: 'text_channel',
- query: 'gen',
- resultTypes: ['text_channel'],
- });
- expect(parseForwardDestinationQuery('!lounge')).toEqual({
- mode: 'voice_channel',
- query: 'lounge',
- resultTypes: ['voice_channel'],
- });
- });
-
- it('keeps a bare sigil as a mode with an empty query', () => {
- expect(parseForwardDestinationQuery('#')).toEqual({mode: 'text_channel', query: '', resultTypes: ['text_channel']});
- });
-
- it('strips the guild, game and global user sigils without narrowing', () => {
- expect(parseForwardDestinationQuery('*guild')).toEqual({mode: null, query: 'guild', resultTypes: ALL_TYPES});
- expect(parseForwardDestinationQuery('$game')).toEqual({mode: null, query: 'game', resultTypes: ALL_TYPES});
- expect(parseForwardDestinationQuery('@@bob')).toEqual({mode: null, query: 'bob', resultTypes: ALL_TYPES});
- });
-
- it('strips only a leading @ but the first other sigil anywhere', () => {
- expect(parseForwardDestinationQuery('a@b')).toEqual({mode: null, query: 'a@b', resultTypes: ALL_TYPES});
- expect(parseForwardDestinationQuery('foo#bar#baz')).toEqual({
- mode: null,
- query: 'foobar#baz',
- resultTypes: ALL_TYPES,
- });
- expect(parseForwardDestinationQuery('@#x')).toEqual({mode: 'user', query: '#x', resultTypes: ['user']});
- });
-});
diff --git a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSearch.test.ts b/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSearch.test.ts
deleted file mode 100644
index 6bee31bef..000000000
--- a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSearch.test.ts
+++ /dev/null
@@ -1,326 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ForwardResultType} from '@app/features/app/components/dialogs/shared/ForwardDestinationQuery';
-import {
- buildForwardSearchBoosters,
- type ForwardChannelCandidate,
- type ForwardGroupDMCandidate,
- type ForwardSearchBoosters,
- type ForwardSearchResult,
- type ForwardUserCandidate,
- searchForwardDestinations,
-} from '@app/features/app/components/dialogs/shared/ForwardDestinationSearch';
-import {loadUnicodeConfusables} from '@app/features/search/utils/SearchTextMatching';
-import {beforeAll, describe, expect, it} from 'vitest';
-
-const ALL_TYPES: ReadonlyArray<ForwardResultType> = ['user', 'text_channel', 'voice_channel', 'group_dm'];
-const NO_BOOSTERS = buildForwardSearchBoosters({dmUserIds: [], frequent: [], friendIds: []});
-let confusables: ReadonlyMap<string, string> = new Map();
-
-beforeAll(async () => {
- confusables = await loadUnicodeConfusables();
-});
-
-interface SearchOverrides {
- readonly blacklist?: ReadonlySet<string>;
- readonly boosters?: ForwardSearchBoosters;
- readonly channels?: ReadonlyArray<ForwardChannelCandidate>;
- readonly confusables?: ReadonlyMap<string, string>;
- readonly groupDMs?: ReadonlyArray<ForwardGroupDMCandidate>;
- readonly limit?: number;
- readonly resultTypes?: ReadonlyArray<ForwardResultType>;
- readonly users?: ReadonlyArray<ForwardUserCandidate>;
-}
-
-function search(query: string, overrides: SearchOverrides = {}): ReadonlyArray<ForwardSearchResult> {
- return searchForwardDestinations({
- blacklist: new Set(),
- boosters: NO_BOOSTERS,
- channels: [],
- confusables,
- groupDMs: [],
- limit: 20,
- resultTypes: ALL_TYPES,
- users: [],
- ...overrides,
- query,
- });
-}
-
-function channel(id: string, name: string, overrides: Partial<ForwardChannelCandidate> = {}): ForwardChannelCandidate {
- return {canAccess: true, guildName: null, hasFrecency: false, id, kind: 'text', name, parentName: null, ...overrides};
-}
-
-function user(id: string, username: string, overrides: Partial<ForwardUserCandidate> = {}): ForwardUserCandidate {
- return {friendNickname: null, globalName: null, id, nicknames: [], username, ...overrides};
-}
-
-function groupDM(id: string, name: string, memberFields: ReadonlyArray<string> = []): ForwardGroupDMCandidate {
- return {id, memberFields, name};
-}
-
-function tier(results: ReadonlyArray<ForwardSearchResult>): number | null {
- return results.length === 0 ? null : results[0].score / 1000;
-}
-
-function channelTier(
- query: string,
- candidate: ForwardChannelCandidate,
- resultTypes: ReadonlyArray<ForwardResultType> = ['text_channel'],
-): number | null {
- return tier(search(query, {channels: [candidate], resultTypes}));
-}
-
-function userTier(query: string, candidate: ForwardUserCandidate, overrides: SearchOverrides = {}): number | null {
- return tier(search(query, {resultTypes: ['user'], users: [candidate], ...overrides}));
-}
-
-function summarize(results: ReadonlyArray<ForwardSearchResult>): ReadonlyArray<string> {
- return results.map((result) => `${result.type}:${result.id}:${result.score}`);
-}
-
-describe('forward destination channel search', () => {
- const general = channel('general', 'general');
-
- it('scores exact, prefix, contains and fuzzy name matches', () => {
- expect(channelTier('general', general)).toBe(10);
- expect(channelTier('gen', general)).toBe(7);
- expect(channelTier('eral', general)).toBe(5);
- expect(channelTier('gnrl', general)).toBe(1);
- });
-
- it('adds the frecency bonus up to the tier cap', () => {
- expect(channelTier('gen', channel('general', 'general', {hasFrecency: true}))).toBe(10);
- expect(channelTier('eral', channel('general', 'general', {hasFrecency: true}))).toBe(7);
- });
-
- it('matches a full phrase across a dash', () => {
- expect(channelTier('general chat', channel('general-chat', 'general-chat'))).toBe(7);
- });
-
- it('rejects words in the wrong order', () => {
- expect(channelTier('chat general', channel('general-chat', 'general-chat'))).toBeNull();
- });
-
- it('lets leftover words match the guild name at half weight, capped at 6', () => {
- expect(channelTier('general foo', channel('general', 'general', {guildName: 'Foo Server'}))).toBe(6);
- });
-
- it('rejects a query that leaves more than one word unmatched', () => {
- expect(channelTier('gen my server', channel('general', 'general', {guildName: 'My Server'}))).toBeNull();
- });
-
- it('needs the channel name itself to match', () => {
- expect(channelTier('foo', channel('general', 'general', {guildName: 'foo'}))).toBeNull();
- });
-
- it('caps a query with a stray space at 6', () => {
- const inGuild = channel('general', 'general', {guildName: 'Foo Server'});
- expect(channelTier('general ', inGuild)).toBe(6);
- expect(channelTier(' general', inGuild)).toBe(6);
- });
-
- it('penalises voice channels found by the text search only', () => {
- const lounge = channel('lounge', 'lounge', {kind: 'voice'});
- expect(search('lounge', {channels: [lounge], resultTypes: ['text_channel']})).toEqual([
- {comparator: 'lounge', id: 'lounge', score: 9000, type: 'voice_channel'},
- ]);
- expect(channelTier('lounge', lounge, ['voice_channel'])).toBe(10);
- });
-
- it('keeps the penalised text-search copy of a voice channel when both searches find it', () => {
- const lounge = channel('lounge', 'lounge', {kind: 'voice'});
- const boosters = buildForwardSearchBoosters({
- dmUserIds: [],
- frequent: [{id: 'lounge', kind: 'voice', score: 10}],
- friendIds: [],
- });
- expect(summarize(search('lounge', {boosters, channels: [lounge], resultTypes: ['voice_channel']}))).toEqual([
- 'voice_channel:lounge:20000',
- ]);
- expect(summarize(search('lounge', {boosters, channels: [lounge]}))).toEqual(['voice_channel:lounge:9000']);
- });
-
- it('does not fold diacritics in channel names', () => {
- expect(channelTier('cafe', channel('cafe', 'café'))).toBeNull();
- });
-
- it('skips channels the reader cannot access', () => {
- expect(channelTier('general', channel('general', 'general', {canAccess: false}))).toBeNull();
- });
-
- it('keeps candidate order between channels with equal scores', () => {
- const channels = [channel('z', 'general-z'), channel('a', 'general-a'), channel('m', 'general')];
- expect(search('general', {channels, resultTypes: ['text_channel']}).map((result) => result.id)).toEqual([
- 'm',
- 'z',
- 'a',
- ]);
- });
-
- it('truncates each category to the limit before merging', () => {
- const channels = Array.from({length: 25}, (_, index) => channel(`c${index}`, `general-${index}`));
- const results = search('general', {channels, limit: 20});
- expect(results.map((result) => result.id)).toEqual(channels.slice(0, 20).map((candidate) => candidate.id));
- });
-});
-
-describe('forward destination user search', () => {
- it('ranks a case-insensitive prefix at 10 and a substring at 5', () => {
- const bobby = user('1', 'bobby');
- expect(userTier('Bob', bobby)).toBe(10);
- expect(userTier('ob', bobby)).toBe(5);
- });
-
- it('folds diacritics in the field but not in the query', () => {
- expect(userTier('jose', user('1', 'José'))).toBe(1);
- expect(userTier('josé', user('1', 'jose99'))).toBeNull();
- });
-
- it('matches look-alike characters once the confusables table is loaded', () => {
- expect(userTier('b0b', user('1', 'bob'))).toBe(1);
- expect(userTier('b0b', user('1', 'bob'), {confusables: new Map()})).toBeNull();
- });
-
- it('does not trim the query', () => {
- expect(userTier('john ', user('1', 'john'))).toBeNull();
- });
-
- it('matches the exact user id', () => {
- expect(userTier('123456789012345678', user('123456789012345678', 'ada'))).toBe(10);
- });
-
- it('matches community nicknames, friend nicknames and global names', () => {
- expect(userTier('mods', user('1', 'ada', {nicknames: ['Mods Team']}))).toBe(10);
- expect(userTier('count', user('1', 'ada', {friendNickname: 'Countess'}))).toBe(10);
- expect(userTier('love', user('1', 'ada', {globalName: 'Ada Lovelace'}))).toBe(5);
- });
-
- it('reports the first field that produced the best score', () => {
- const [strongest] = search('love', {
- users: [user('1', 'ada', {globalName: 'Lovelace', nicknames: ['Ada Lovelace']})],
- });
- expect(strongest.comparator).toBe('Lovelace');
- const [first] = search('ada', {users: [user('1', 'ada_x', {globalName: 'Ada'})]});
- expect(first.comparator).toBe('ada_x');
- });
-
- it('skips blacklisted users', () => {
- expect(userTier('ada', user('me', 'ada'), {blacklist: new Set(['me'])})).toBeNull();
- });
-
- it('multiplies by the user booster', () => {
- const boosters = buildForwardSearchBoosters({dmUserIds: [], frequent: [], friendIds: ['1']});
- expect(userTier('bob', user('1', 'bob'), {boosters})).toBeCloseTo(12);
- });
-
- it('breaks ties alphabetically by the matched name', () => {
- const users = [user('1', 'Bob_b'), user('2', 'bob_a'), user('3', 'bob_c')];
- expect(search('bob', {users}).map((result) => result.id)).toEqual(['2', '1', '3']);
- });
-});
-
-describe('forward destination group DM search', () => {
- it('folds diacritics and look-alikes in the name', () => {
- expect(tier(search('cafe', {groupDMs: [groupDM('g', 'Café Crew')]}))).toBe(7);
- expect(tier(search('rnovie', {groupDMs: [groupDM('g', 'movie night')]}))).toBe(7);
- });
-
- it('caps member matches at 5', () => {
- expect(tier(search('alice', {groupDMs: [groupDM('g', 'Weekend', ['alice', 'Alice A.'])]}))).toBe(5);
- });
-
- it('prefers a stronger name match over a member match', () => {
- expect(tier(search('weekend', {groupDMs: [groupDM('g', 'Weekend', ['weekend_fan'])]}))).toBe(10);
- });
-});
-
-describe('forward destination search merge', () => {
- it('returns nothing for a blank query', () => {
- expect(search(' ', {channels: [channel('general', 'general')]})).toEqual([]);
- });
-
- it('only searches the requested result types', () => {
- const results = search('general', {
- channels: [channel('general', 'general')],
- groupDMs: [groupDM('g', 'general')],
- resultTypes: ['user'],
- users: [user('1', 'general')],
- });
- expect(summarize(results)).toEqual(['user:1:10000']);
- });
-
- it('orders equal scores as users, group DMs, text channels, then voice channels', () => {
- const results = search('general', {
- channels: [channel('v', 'general', {kind: 'voice'}), channel('t', 'general')],
- groupDMs: [groupDM('g', 'general')],
- users: [user('1', 'general')],
- });
- expect(summarize(results)).toEqual([
- 'user:1:10000',
- 'group_dm:g:10000',
- 'text_channel:t:10000',
- 'voice_channel:v:9000',
- ]);
- });
-
- it('sorts higher scores first across types', () => {
- const results = search('gen', {
- channels: [channel('t', 'general', {hasFrecency: true})],
- users: [user('1', 'xgen')],
- });
- expect(summarize(results)).toEqual(['text_channel:t:10000', 'user:1:5000']);
- });
-});
-
-describe('buildForwardSearchBoosters', () => {
- it('scales frecency against the highest score and adds friend and open DM boosts', () => {
- const boosters = buildForwardSearchBoosters({
- dmUserIds: ['user-1', 'user-3'],
- frequent: [
- {id: 'guild-1', kind: 'other', score: 200},
- {id: 'dm-1', kind: 'dm', recipientId: 'user-1', score: 100},
- {id: 'text-1', kind: 'text', score: 50},
- {id: 'voice-1', kind: 'voice', score: 150},
- {id: 'gdm-1', kind: 'group_dm', score: 20},
- ],
- friendIds: ['user-1', 'user-2'],
- });
- expect(boosters.users.get('user-1')).toBeCloseTo(1.8);
- expect(boosters.users.get('user-2')).toBeCloseTo(1.2);
- expect(boosters.users.get('user-3')).toBeCloseTo(1.1);
- expect(boosters.users.has('dm-1')).toBe(false);
- expect(boosters.textChannels.get('text-1')).toBe(1.25);
- expect(boosters.voiceChannels.get('voice-1')).toBe(1.75);
- expect(boosters.groupDMs.get('gdm-1')).toBeCloseTo(1.1);
- expect(boosters.textChannels.has('guild-1')).toBe(false);
- });
-
- it('falls back to a boost of 1 when every frecency score is zero', () => {
- const boosters = buildForwardSearchBoosters({
- dmUserIds: [],
- frequent: [{id: 'text-1', kind: 'text', score: 0}],
- friendIds: [],
- });
- expect(boosters.textChannels.get('text-1')).toBe(1);
- });
-
- it('boosts text channels only in the text search and voice channels only in the voice search', () => {
- const boosters = buildForwardSearchBoosters({
- dmUserIds: [],
- frequent: [
- {id: 't', kind: 'text', score: 10},
- {id: 'v', kind: 'voice', score: 10},
- ],
- friendIds: [],
- });
- const channels = [channel('t', 'general'), channel('v', 'general', {kind: 'voice'})];
- expect(summarize(search('general', {boosters, channels, resultTypes: ['text_channel']}))).toEqual([
- 'text_channel:t:20000',
- 'voice_channel:v:9000',
- ]);
- expect(summarize(search('general', {boosters, channels, resultTypes: ['voice_channel']}))).toEqual([
- 'voice_channel:v:20000',
- ]);
- });
-});
diff --git a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSelection.test.ts b/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSelection.test.ts
deleted file mode 100644
index 3766de772..000000000
--- a/fluxer_app/src/features/app/components/dialogs/shared/ForwardDestinationSelection.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildForwardDefaultDestinations,
- type ForwardDestination,
- type ForwardRowIdentity,
-} from '@app/features/app/components/dialogs/shared/ForwardDefaultDestinations';
-import {
- type ForwardPinnedDestinations,
- forwardDestinationKey,
- MAX_FORWARD_DESTINATIONS,
- pinForwardDestinations,
- toggleForwardDestination,
-} from '@app/features/app/components/dialogs/shared/ForwardDestinationSelection';
-import {describe, expect, it} from 'vitest';
-
-const UNPINNED: ForwardPinnedDestinations = {engineQuery: null, pinned: []};
-const HISTORY: ReadonlyArray<string> = ['text-1', 'text-2', 'text-3'];
-
-function channel(id: string): ForwardDestination {
- return {id, type: 'channel'};
-}
-
-function user(id: string): ForwardDestination {
- return {id, type: 'user'};
-}
-
-function resolveChannel(channelId: string): ForwardRowIdentity {
- return {id: channelId, type: 'text_channel'};
-}
-
-function resolveDestination(destination: ForwardDestination): ForwardRowIdentity {
- if (destination.type === 'user') return {id: destination.id, type: 'user'};
- return resolveChannel(destination.id);
-}
-
-interface PickerState {
- readonly engineQuery: string;
- readonly pinned: ForwardPinnedDestinations;
- readonly selected: ReadonlyArray<ForwardDestination>;
-}
-
-interface PickerRender {
- readonly rows: ReadonlyArray<string>;
- readonly state: PickerState;
-}
-
-function renderPicker(state: PickerState): PickerRender {
- const pinned = pinForwardDestinations(state.pinned, state.engineQuery, state.selected);
- const rows = buildForwardDefaultDestinations({
- frequentIds: [],
- history: HISTORY,
- isValid: () => true,
- mode: null,
- origin: null,
- pinned: pinned.pinned,
- resolveChannel,
- resolveDestination,
- selected: state.selected,
- });
- return {rows: rows.map((row) => row.id), state: {...state, pinned}};
-}
-
-function togglePicker(state: PickerState, destination: ForwardDestination): PickerState {
- const selected = toggleForwardDestination(state.selected, destination);
- const engineQuery = selected.length > state.selected.length ? '' : state.engineQuery;
- return {...state, engineQuery, selected};
-}
-
-describe('toggleForwardDestination', () => {
- it('puts the newest pick first and removes a pick in place', () => {
- const picked = toggleForwardDestination(toggleForwardDestination([], channel('text-1')), user('user-1'));
- expect(picked).toEqual([user('user-1'), channel('text-1')]);
- expect(toggleForwardDestination(picked, channel('text-1'))).toEqual([user('user-1')]);
- });
-
- it('tells a user apart from a channel with the same id', () => {
- expect(forwardDestinationKey(user('1'))).toBe('user:1');
- expect(forwardDestinationKey(channel('1'))).toBe('channel:1');
- expect(toggleForwardDestination([channel('1')], user('1'))).toEqual([user('1'), channel('1')]);
- });
-
- it('refuses a new pick at the cap but still removes one', () => {
- const full = Array.from({length: MAX_FORWARD_DESTINATIONS}, (_, index) => channel(`text-${index}`));
- expect(toggleForwardDestination(full, channel('text-extra'))).toBe(full);
- expect(toggleForwardDestination(full, channel('text-0'))).toHaveLength(MAX_FORWARD_DESTINATIONS - 1);
- });
-});
-
-describe('pinForwardDestinations', () => {
- it('pins the live selection on the first render', () => {
- const selected = [channel('text-1')];
- expect(pinForwardDestinations(UNPINNED, '', selected)).toEqual({engineQuery: '', pinned: selected});
- });
-
- it('keeps the snapshot while the engine query stays the same', () => {
- const snapshot = pinForwardDestinations(UNPINNED, '', []);
- expect(pinForwardDestinations(snapshot, '', [channel('text-1')])).toBe(snapshot);
- });
-
- it('pins the live selection again when the engine query changes', () => {
- const snapshot = pinForwardDestinations(UNPINNED, '', []);
- const selected = [user('user-1'), channel('text-1')];
- expect(pinForwardDestinations(snapshot, 'abc', selected)).toEqual({engineQuery: 'abc', pinned: selected});
- });
-});
-
-describe('forward default list while selecting', () => {
- it('keeps rows in place until a search clears, then pins the selection newest first', () => {
- const opened = renderPicker({engineQuery: '', pinned: UNPINNED, selected: []});
- expect(opened.rows).toEqual(['text-1', 'text-2', 'text-3']);
-
- const pickedWithoutQuery = renderPicker(togglePicker(opened.state, channel('text-3')));
- expect(pickedWithoutQuery.state.selected).toEqual([channel('text-3')]);
- expect(pickedWithoutQuery.rows).toEqual(['text-1', 'text-2', 'text-3']);
-
- const searching = renderPicker({...pickedWithoutQuery.state, engineQuery: 'ada'});
- const pickedFromSearch = renderPicker(togglePicker(searching.state, user('user-9')));
- expect(pickedFromSearch.state.engineQuery).toBe('');
- expect(pickedFromSearch.rows).toEqual(['user-9', 'text-3', 'text-1', 'text-2']);
-
- const removed = renderPicker(togglePicker(pickedFromSearch.state, channel('text-3')));
- expect(removed.state.selected).toEqual([user('user-9')]);
- expect(removed.rows).toEqual(['user-9', 'text-3', 'text-1', 'text-2']);
- });
-
- it('re-pins the live selection when a typed query is cleared by hand', () => {
- const opened = renderPicker({engineQuery: '', pinned: UNPINNED, selected: []});
- const picked = renderPicker(togglePicker(opened.state, channel('text-2')));
- const searching = renderPicker({...picked.state, engineQuery: 'x'});
- const cleared = renderPicker({...searching.state, engineQuery: ''});
- expect(cleared.rows).toEqual(['text-2', 'text-1', 'text-3']);
- });
-});
diff --git a/fluxer_app/src/features/app/components/floating/UnreadChannelOrder.test.ts b/fluxer_app/src/features/app/components/floating/UnreadChannelOrder.test.ts
deleted file mode 100644
index 57c31152d..000000000
--- a/fluxer_app/src/features/app/components/floating/UnreadChannelOrder.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {selectFrozenUnreadChannels} from '@app/features/app/components/floating/UnreadChannelOrder';
-import {describe, expect, it} from 'vitest';
-
-function ids(channels: ReadonlyArray<{id: string}>): Array<string> {
- return channels.map((channel) => channel.id);
-}
-
-describe('selectFrozenUnreadChannels', () => {
- it('keeps channels in their frozen position while the list is open', () => {
- const order = new Map([
- ['a', 0],
- ['b', 1],
- ['c', 2],
- ]);
- expect(ids(selectFrozenUnreadChannels(order, [{id: 'c'}, {id: 'a'}, {id: 'b'}]))).toEqual(['a', 'b', 'c']);
- });
-
- it('hides a channel that becomes unread after the order was frozen', () => {
- const order = new Map([['a', 0]]);
- expect(ids(selectFrozenUnreadChannels(order, [{id: 'a'}, {id: 'late'}]))).toEqual(['a']);
- });
-
- it('never grows the list when every live channel is new to the order', () => {
- const order = new Map([['a', 0]]);
- expect(ids(selectFrozenUnreadChannels(order, [{id: 'x'}, {id: 'y'}, {id: 'z'}]))).toEqual([]);
- });
-
- it('yields nothing for an empty order', () => {
- expect(ids(selectFrozenUnreadChannels(new Map<string, number>(), [{id: 'x'}]))).toEqual([]);
- });
-
- it('does not resurrect channels that are no longer unread', () => {
- const order = new Map([
- ['a', 0],
- ['gone', 1],
- ]);
- expect(ids(selectFrozenUnreadChannels(order, [{id: 'a'}]))).toEqual(['a']);
- });
-
- it('does not mutate the order it was given', () => {
- const order = new Map([['a', 0]]);
- selectFrozenUnreadChannels(order, [{id: 'a'}, {id: 'late'}]);
- expect([...order.keys()]).toEqual(['a']);
- });
-});
diff --git a/fluxer_app/src/features/app/components/floating/UnreadPreviewBudget.test.ts b/fluxer_app/src/features/app/components/floating/UnreadPreviewBudget.test.ts
deleted file mode 100644
index d083f5ef8..000000000
--- a/fluxer_app/src/features/app/components/floating/UnreadPreviewBudget.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- BULK_PREVIEW_CHANNEL_BATCH_SIZE,
- UNREAD_PREVIEW_MESSAGE_LIMIT,
-} from '@app/features/app/components/floating/UnreadPreviewBudget';
-import {BulkMessageFetchRequest} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
-import {describe, expect, it} from 'vitest';
-
-const buildBatch = (limit: number) => ({
- requests: Array.from({length: BULK_PREVIEW_CHANNEL_BATCH_SIZE}, (_, index) => ({
- channel_id: String(1000000000000000000n + BigInt(index)),
- limit,
- })),
-});
-
-describe('unread preview fetch budget', () => {
- it('keeps the anchored window inside the bulk fetch schema', () => {
- expect(() => BulkMessageFetchRequest.parse(buildBatch(UNREAD_PREVIEW_MESSAGE_LIMIT * 2))).not.toThrow();
- });
-
- it('keeps the unanchored window inside the bulk fetch schema', () => {
- expect(() => BulkMessageFetchRequest.parse(buildBatch(UNREAD_PREVIEW_MESSAGE_LIMIT))).not.toThrow();
- });
-
- it('rejects a batch one channel wider than the client sends', () => {
- const oversized = buildBatch(UNREAD_PREVIEW_MESSAGE_LIMIT * 2);
- oversized.requests.push({channel_id: '1000000000000000099', limit: UNREAD_PREVIEW_MESSAGE_LIMIT * 2});
- expect(() => BulkMessageFetchRequest.parse(oversized)).toThrow();
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/GuildBannerCollapse.test.ts b/fluxer_app/src/features/app/components/layout/GuildBannerCollapse.test.ts
deleted file mode 100644
index 5cb629af4..000000000
--- a/fluxer_app/src/features/app/components/layout/GuildBannerCollapse.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- GUILD_BANNER_HEADER_GLASS_DISTANCE,
- GUILD_BANNER_HEADER_GLASS_MAX_OPACITY,
- isGuildBannerHeaderFrosted,
- resolveGuildBannerCollapseProgress,
- resolveGuildBannerGeometry,
- resolveGuildBannerHeaderGlassOpacity,
-} from '@app/features/app/components/layout/GuildBannerCollapse';
-import {describe, expect, it} from 'vitest';
-
-describe('resolveGuildBannerGeometry', () => {
- it('sizes the banner from the sidebar width and the banner aspect ratio', () => {
- const geometry = resolveGuildBannerGeometry({
- containerWidth: 320,
- viewportHeight: 1000,
- headerHeight: 56,
- aspectRatio: 16 / 9,
- });
- expect(geometry.bannerHeight).toBeCloseTo(180);
- expect(geometry.collapseDistance).toBeCloseTo(124);
- expect(geometry.heightCapped).toBe(false);
- });
-
- it('caps the banner at a fraction of the viewport height', () => {
- const geometry = resolveGuildBannerGeometry({
- containerWidth: 480,
- viewportHeight: 500,
- headerHeight: 56,
- aspectRatio: 1,
- });
- expect(geometry.bannerHeight).toBeCloseTo(150);
- expect(geometry.collapseDistance).toBeCloseTo(94);
- expect(geometry.heightCapped).toBe(true);
- });
-
- it('never collapses below the header height', () => {
- const geometry = resolveGuildBannerGeometry({
- containerWidth: 200,
- viewportHeight: 120,
- headerHeight: 56,
- aspectRatio: 21 / 9,
- });
- expect(geometry.bannerHeight).toBe(56);
- expect(geometry.collapseDistance).toBe(0);
- });
-
- it('reports no banner height before the header is measured', () => {
- const geometry = resolveGuildBannerGeometry({
- containerWidth: 0,
- viewportHeight: 0,
- headerHeight: 56,
- aspectRatio: 16 / 9,
- });
- expect(geometry.bannerHeight).toBe(56);
- expect(geometry.collapseDistance).toBe(0);
- });
-});
-
-describe('resolveGuildBannerCollapseProgress', () => {
- it('tracks scroll position across the collapse distance', () => {
- expect(resolveGuildBannerCollapseProgress(0, 80)).toBe(0);
- expect(resolveGuildBannerCollapseProgress(40, 80)).toBe(0.5);
- expect(resolveGuildBannerCollapseProgress(80, 80)).toBe(1);
- });
-
- it('clamps overscroll and bounce past both ends', () => {
- expect(resolveGuildBannerCollapseProgress(-30, 80)).toBe(0);
- expect(resolveGuildBannerCollapseProgress(4000, 80)).toBe(1);
- });
-
- it('stays expanded when there is nothing to collapse', () => {
- expect(resolveGuildBannerCollapseProgress(200, 0)).toBe(0);
- });
-});
-
-describe('resolveGuildBannerHeaderGlassOpacity', () => {
- it('ramps in over a fixed scroll distance regardless of banner height', () => {
- expect(resolveGuildBannerHeaderGlassOpacity(0)).toBe(0);
- expect(resolveGuildBannerHeaderGlassOpacity(GUILD_BANNER_HEADER_GLASS_DISTANCE / 2)).toBeCloseTo(
- GUILD_BANNER_HEADER_GLASS_MAX_OPACITY / 2,
- );
- expect(resolveGuildBannerHeaderGlassOpacity(GUILD_BANNER_HEADER_GLASS_DISTANCE)).toBeCloseTo(
- GUILD_BANNER_HEADER_GLASS_MAX_OPACITY,
- );
- });
-
- it('never exceeds the opaque header background', () => {
- expect(resolveGuildBannerHeaderGlassOpacity(5000)).toBe(GUILD_BANNER_HEADER_GLASS_MAX_OPACITY);
- });
-
- it('frosts the header once the glass is fully ramped in', () => {
- expect(isGuildBannerHeaderFrosted(0)).toBe(false);
- expect(isGuildBannerHeaderFrosted(GUILD_BANNER_HEADER_GLASS_DISTANCE - 1)).toBe(false);
- expect(isGuildBannerHeaderFrosted(GUILD_BANNER_HEADER_GLASS_DISTANCE)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/GuildHeader.test.tsx b/fluxer_app/src/features/app/components/layout/GuildHeader.test.tsx
deleted file mode 100644
index 41a6900bd..000000000
--- a/fluxer_app/src/features/app/components/layout/GuildHeader.test.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {GuildHeader} from '@app/features/app/components/layout/GuildHeader';
-import styles from '@app/features/app/components/layout/GuildHeader.module.css';
-import {useGuildBannerPresentation} from '@app/features/app/hooks/useGuildBannerPresentation';
-import {Guild} from '@app/features/guild/models/Guild';
-import {WINDOW_FOCUSED_CLASS} from '@app/features/ui/utils/WindowFocusInteractionGuard';
-import UserSettings from '@app/features/user/state/UserSettings';
-import type {Guild as WireGuild} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {setupI18n} from '@lingui/core';
-import {useMotionValue} from 'framer-motion';
-import {runInAction} from 'mobx';
-import {observer} from 'mobx-react-lite';
-import {act, useLayoutEffect} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterAll, afterEach, beforeAll, 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/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn()},
-}));
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown =>
- typeof value === 'string'
- ? {id: value, message: value}
- : {...(value as object), id: (value as {message: string}).message};
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- useLingui: () => ({i18n}),
-}));
-vi.mock('@app/features/guild/components/popouts/GuildHeaderPopout', () => ({GuildHeaderPopout: () => null}));
-vi.mock('@app/features/guild/components/bottomsheets/GuildHeaderBottomSheet', () => ({
- GuildHeaderBottomSheet: () => null,
-}));
-vi.mock('@app/features/ui/action_menu/GuildContextMenu', () => ({GuildContextMenu: () => null}));
-vi.mock('@app/features/app/hooks/useSkeletonLayoutMemoryCapture', () => ({
- useSkeletonLayoutReport: () => {},
- measureSkeletonTextWidthPx: () => 0,
-}));
-vi.mock('@app/features/messaging/utils/ImageCacheUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/messaging/utils/ImageCacheUtils')>()),
- hasImage: () => true,
-}));
-vi.mock('@app/features/user/utils/AvatarUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/user/utils/AvatarUtils')>()),
- getGuildBannerURL: ({id, banner}: {id: string; banner: string | null}, animated: boolean) =>
- banner == null ? null : `https://media.test/banners/${id}/${banner}.${animated ? 'gif' : 'webp'}`,
-}));
-
-const i18n = setupI18n({locale: 'en-US', messages: {'en-US': {}}});
-const DEFAULT_GIF_AUTOPLAY = UserSettings.gifAutoPlay;
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const HEADER_ROW_HEIGHT = 56;
-const SIXTEEN_BY_NINE_SIDEBAR_BANNER_HEIGHT = 135;
-
-interface Frame {
- readonly headerHeight: number;
- readonly bannerHeight: number;
- readonly listTop: number;
-}
-
-const layout = {sidebarWidth: 240};
-const frames: Array<Frame> = [];
-const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
-const originalOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight');
-
-let container: HTMLDivElement;
-let root: Root;
-
-function createBannerGuild(): Guild {
- return new Guild({
- id: '1400000000000000000',
- name: 'Banner Community',
- icon: null,
- banner: 'b4nn3r',
- banner_width: 1600,
- banner_height: 900,
- features: [],
- roles: [],
- owner_id: '1400000000000000001',
- } as unknown as WireGuild);
-}
-
-function requireElement(selector: string): HTMLElement {
- const element = container.querySelector<HTMLElement>(selector);
- if (element == null) {
- throw new Error(`missing ${selector}`);
- }
- return element;
-}
-
-const Harness = observer(({guild}: {guild: Guild}) => {
- const scrollY = useMotionValue(0);
- const banner = useGuildBannerPresentation({guild, scrollY});
- useLayoutEffect(() => {
- const header = requireElement(`.${styles.headerContainer}`);
- const clip = container.querySelector<HTMLElement>('[data-flx="app.guild-header.banner-clip"]');
- frames.push({
- headerHeight: header.offsetHeight,
- bannerHeight: clip?.offsetHeight ?? 0,
- listTop: header.offsetHeight + banner.collapseDistance,
- });
- });
- return <GuildHeader guild={guild} banner={banner} />;
-});
-
-function mount(guild: Guild): void {
- act(() => {
- root.render(<Harness guild={guild} />);
- });
-}
-
-function lastFrame(): Frame {
- const frame = frames.at(-1);
- if (frame === undefined) {
- throw new Error('nothing rendered');
- }
- return frame;
-}
-
-beforeAll(() => {
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
- configurable: true,
- get() {
- return layout.sidebarWidth;
- },
- });
- Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
- configurable: true,
- get(this: HTMLElement) {
- const inlineHeight = Number.parseFloat(this.style.height);
- return Number.isFinite(inlineHeight) ? inlineHeight : HEADER_ROW_HEIGHT;
- },
- });
-});
-
-afterAll(() => {
- if (originalOffsetWidth) Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
- if (originalOffsetHeight) Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
-});
-
-beforeEach(() => {
- layout.sidebarWidth = 240;
- frames.length = 0;
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- container.remove();
- document.documentElement.classList.remove(WINDOW_FOCUSED_CLASS);
- vi.restoreAllMocks();
- runInAction(() => {
- UserSettings.gifAutoPlay = DEFAULT_GIF_AUTOPLAY;
- });
-});
-
-describe('GuildHeader banner geometry', () => {
- it('keeps the header at the row height with the list below the banner', () => {
- mount(createBannerGuild());
- expect(lastFrame()).toEqual({
- headerHeight: HEADER_ROW_HEIGHT,
- bannerHeight: SIXTEEN_BY_NINE_SIDEBAR_BANNER_HEIGHT,
- listTop: SIXTEEN_BY_NINE_SIDEBAR_BANNER_HEIGHT,
- });
- });
-
- it('shrinks the collapsing banner again when the sidebar narrows', () => {
- mount(createBannerGuild());
- layout.sidebarWidth = 160;
- act(() => {
- window.dispatchEvent(new Event('resize'));
- });
- expect(lastFrame()).toEqual({headerHeight: HEADER_ROW_HEIGHT, bannerHeight: 90, listTop: 90});
- });
-
- it('plays the animated banner on header hover when the banner is too short to collapse', async () => {
- layout.sidebarWidth = 80;
- runInAction(() => {
- UserSettings.gifAutoPlay = false;
- });
- document.documentElement.classList.add(WINDOW_FOCUSED_CLASS);
- mount(createBannerGuild());
- expect(lastFrame()).toEqual({
- headerHeight: HEADER_ROW_HEIGHT,
- bannerHeight: HEADER_ROW_HEIGHT,
- listTop: HEADER_ROW_HEIGHT,
- });
- const bannerImage = requireElement('[data-flx="app.guild-header.banner-image"]');
- expect(bannerImage.style.backgroundImage).toContain('b4nn3r.webp');
- const header = requireElement(`.${styles.headerContainer}`);
- const matches = header.matches.bind(header);
- vi.spyOn(header, 'matches').mockImplementation((selector: string) => selector === ':hover' || matches(selector));
- await act(async () => {
- header.dispatchEvent(new MouseEvent('mouseenter'));
- await new Promise((resolve) => setTimeout(resolve, 0));
- });
- expect(bannerImage.style.backgroundImage).toContain('b4nn3r.gif');
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/ScrollIndicatorStateMachine.test.ts b/fluxer_app/src/features/app/components/layout/ScrollIndicatorStateMachine.test.ts
deleted file mode 100644
index 4a32fa96a..000000000
--- a/fluxer_app/src/features/app/components/layout/ScrollIndicatorStateMachine.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createScrollIndicatorSnapshot,
- getScrollIndicatorStateValue,
- resolveActiveScrollIndicator,
- resolveScrollIndicatorEdgeCandidates,
- type ScrollIndicatorMeasurement,
- type ScrollIndicatorTargetMeasurement,
- selectActiveScrollIndicator,
- transitionScrollIndicatorSnapshot,
-} from '@app/features/app/components/layout/ScrollIndicatorStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function target(
- id: string,
- top: number,
- bottom: number,
- severity: ScrollIndicatorTargetMeasurement['severity'] = 'unread',
- order = 0,
-): ScrollIndicatorTargetMeasurement {
- return {id, top, bottom, severity, order};
-}
-
-function measurement(targets: Array<ScrollIndicatorTargetMeasurement>, scrollTop = 100): ScrollIndicatorMeasurement {
- return {
- scrollTop,
- viewportHeight: 200,
- targets,
- };
-}
-
-describe('ScrollIndicatorStateMachine', () => {
- it('hides when there are no offscreen unread targets', () => {
- const snapshot = createScrollIndicatorSnapshot();
- const next = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('visible', 120, 160)]),
- });
- expect(getScrollIndicatorStateValue(next)).toBe('hidden');
- expect(selectActiveScrollIndicator(next)).toBeNull();
- });
-
- it('treats partially visible targets as visible, not floating-pill targets', () => {
- const candidates = resolveScrollIndicatorEdgeCandidates(
- measurement([target('partly-above', 90, 120), target('partly-below', 290, 320)]),
- );
- expect(candidates.topIndicator).toBeNull();
- expect(candidates.bottomIndicator).toBeNull();
- });
-
- it('selects the nearest offscreen target at the same severity', () => {
- const active = resolveActiveScrollIndicator(
- measurement([
- target('far-above', 0, 40, 'unread', 0),
- target('near-above', 80, 90, 'unread', 1),
- target('far-below', 500, 540, 'unread', 2),
- ]),
- );
- expect(active?.direction).toBe('top');
- expect(active?.indicator.id).toBe('near-above');
- expect(active?.indicator.distance).toBe(10);
- });
-
- it('prioritizes mentions over plain unread targets regardless of distance', () => {
- const active = resolveActiveScrollIndicator(
- measurement([target('near-unread', 80, 90, 'unread', 0), target('far-mention', 600, 640, 'mention', 1)]),
- );
- expect(active?.direction).toBe('bottom');
- expect(active?.indicator.id).toBe('far-mention');
- });
-
- it('uses the latest scroll direction to break exact ties', () => {
- const active = resolveActiveScrollIndicator({
- ...measurement([target('above', 80, 90, 'unread', 0), target('below', 310, 320, 'unread', 1)]),
- preferredDirection: 'bottom',
- });
- expect(active?.direction).toBe('bottom');
- expect(active?.indicator.id).toBe('below');
- });
-
- it('does not keep a stale active target after collapse or read-state changes remove it', () => {
- let snapshot = createScrollIndicatorSnapshot();
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('unread-above', 80, 90)]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('visible');
- expect(selectActiveScrollIndicator(snapshot)?.indicator.id).toBe('unread-above');
-
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('hidden');
- expect(selectActiveScrollIndicator(snapshot)).toBeNull();
- });
-
- it('switches from an expanded folder child marker to the collapsed folder marker', () => {
- let snapshot = createScrollIndicatorSnapshot();
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('guild-inside-folder', 340, 380, 'mention')]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('visible');
- expect(selectActiveScrollIndicator(snapshot)?.indicator.id).toBe('guild-inside-folder');
-
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('folder-1', 340, 380, 'mention')]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('visible');
- expect(selectActiveScrollIndicator(snapshot)?.indicator.id).toBe('folder-1');
- });
-
- it('hides immediately when the previously offscreen target moves into the viewport', () => {
- let snapshot = createScrollIndicatorSnapshot();
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('unread-above', 80, 90)]),
- });
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('unread-above', 120, 160)]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('hidden');
- expect(selectActiveScrollIndicator(snapshot)).toBeNull();
- });
-
- it('resets when the scroll container is unavailable', () => {
- let snapshot = createScrollIndicatorSnapshot();
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {
- type: 'scrollIndicator.measured',
- measurement: measurement([target('unread-below', 320, 340)]),
- });
- expect(getScrollIndicatorStateValue(snapshot)).toBe('visible');
-
- snapshot = transitionScrollIndicatorSnapshot(snapshot, {type: 'scrollIndicator.reset'});
- expect(getScrollIndicatorStateValue(snapshot)).toBe('hidden');
- expect(selectActiveScrollIndicator(snapshot)).toBeNull();
- });
-});
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 26cd92c48..000000000
--- a/fluxer_app/src/features/app/components/layout/UserAreaState.test.ts
+++ /dev/null
@@ -1,88 +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';
-
-const baseSignals: UserAreaMicrophoneSignals = {
- effectiveAudioMuted: false,
- effectiveAudioDeafened: false,
- isGuildMuted: false,
- isGuildDeafened: false,
- isPermissionMuted: false,
- muteReason: null,
- isPushToTalkEffective: false,
- isPushToTalkHeld: false,
- isPushToMuteEffective: false,
- isPushToMuteHeld: false,
-};
-
-describe('selectUserAreaMicrophoneState', () => {
- it('follows normal effective mute state without transmit hold modes', () => {
- expect(selectUserAreaMicrophoneState(baseSignals)).toEqual({
- effectiveMuted: false,
- muteToggleLocked: false,
- });
- expect(selectUserAreaMicrophoneState({...baseSignals, effectiveAudioMuted: true})).toMatchObject({
- effectiveMuted: true,
- });
- });
-
- it('shows push-to-talk released as muted', () => {
- expect(selectUserAreaMicrophoneState({...baseSignals, isPushToTalkEffective: true})).toEqual({
- effectiveMuted: true,
- muteToggleLocked: true,
- });
- });
-
- it('treats push-to-talk without an effective binding as disabled', () => {
- expect(selectUserAreaMicrophoneState({...baseSignals, isPushToTalkEffective: false})).toEqual({
- effectiveMuted: false,
- muteToggleLocked: false,
- });
- });
-
- it('shows push-to-talk held as unmuted even with persisted self mute state', () => {
- expect(
- selectUserAreaMicrophoneState({
- ...baseSignals,
- effectiveAudioMuted: true,
- muteReason: 'self',
- isPushToTalkEffective: true,
- isPushToTalkHeld: true,
- }),
- ).toEqual({
- effectiveMuted: false,
- muteToggleLocked: true,
- });
- });
-
- it('does not show push-to-talk held as unmuted through hard mute states', () => {
- expect(
- selectUserAreaMicrophoneState({
- ...baseSignals,
- isPermissionMuted: true,
- isPushToTalkEffective: true,
- isPushToTalkHeld: true,
- }),
- ).toEqual({
- effectiveMuted: true,
- muteToggleLocked: true,
- });
- });
-
- it('shows push-to-mute held as muted while leaving the mute toggle available', () => {
- expect(
- selectUserAreaMicrophoneState({
- ...baseSignals,
- isPushToMuteEffective: true,
- isPushToMuteHeld: true,
- }),
- ).toEqual({
- effectiveMuted: true,
- muteToggleLocked: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderIntegration.test.ts b/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderIntegration.test.ts
deleted file mode 100644
index 0e43c34e0..000000000
--- a/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderIntegration.test.ts
+++ /dev/null
@@ -1,409 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelReorderRect,
- type ChannelReorderTarget,
- selectChannelReorderIntent,
-} from '@app/features/app/components/layout/dnd/ChannelReorderStateMachine';
-import {type DragItem, DragItemType, type DropResult} from '@app/features/app/components/layout/types/DndTypes';
-import {
- type ChannelMoveOperation,
- createChannelMoveOperation,
-} from '@app/features/app/components/layout/utils/ChannelMoveOperation';
-import type {Channel} from '@app/features/channel/models/Channel';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {computeGuildChannelReorderPlan} from '@fluxer/schema/src/domains/channel/GuildChannelOrdering';
-import {describe, expect, it} from 'vitest';
-
-const rect: ChannelReorderRect = {
- top: 100,
- bottom: 132,
- left: 0,
- right: 240,
-};
-
-function point(y: number) {
- return {
- x: 120,
- y,
- };
-}
-
-function channel(id: string, type: number, position: number, parentId: string | null = null): Channel {
- return {
- id,
- type,
- position,
- parentId,
- } as Channel;
-}
-
-function channelsFixture(): Array<Channel> {
- return [
- channel('root-text', ChannelTypes.GUILD_TEXT, 10),
- channel('category-a', ChannelTypes.GUILD_CATEGORY, 20),
- channel('a-text-1', ChannelTypes.GUILD_TEXT, 30, 'category-a'),
- channel('a-text-2', ChannelTypes.GUILD_TEXT, 40, 'category-a'),
- channel('a-voice-1', ChannelTypes.GUILD_VOICE, 50, 'category-a'),
- channel('a-voice-2', ChannelTypes.GUILD_VOICE, 60, 'category-a'),
- channel('category-b', ChannelTypes.GUILD_CATEGORY, 70),
- channel('b-text-1', ChannelTypes.GUILD_TEXT, 80, 'category-b'),
- channel('b-link-1', ChannelTypes.GUILD_LINK, 90, 'category-b'),
- channel('b-voice-1', ChannelTypes.GUILD_VOICE, 100, 'category-b'),
- channel('root-voice', ChannelTypes.GUILD_VOICE, 110),
- ];
-}
-
-function requireChannel(channels: ReadonlyArray<Channel>, id: string): Channel {
- const found = channels.find((candidate) => candidate.id === id);
- if (!found) throw new Error(`Missing test channel ${id}`);
- return found;
-}
-
-function dragItemFrom(channel: Channel): DragItem {
- return {
- type: channel.type === ChannelTypes.GUILD_CATEGORY ? DragItemType.CATEGORY : DragItemType.CHANNEL,
- id: channel.id,
- channelType: channel.type,
- parentId: channel.parentId,
- guildId: 'guild-1',
- };
-}
-
-function targetFrom(channel: Channel): ChannelReorderTarget {
- return {
- id: channel.id,
- channelType: channel.type,
- parentId: channel.parentId,
- guildId: 'guild-1',
- };
-}
-
-function requireMachineDropResult(
- channels: ReadonlyArray<Channel>,
- sourceId: string,
- targetId: string,
- y: number,
-): DropResult {
- const source = requireChannel(channels, sourceId);
- const target = requireChannel(channels, targetId);
- const intent = selectChannelReorderIntent(dragItemFrom(source), targetFrom(target), point(y), rect);
- if (!intent) throw new Error(`Expected test drop intent from ${sourceId} to ${targetId} at y=${y}`);
- return intent.result;
-}
-
-function createOperation(
- channels: ReadonlyArray<Channel>,
- sourceId: string,
- dropResult: DropResult,
-): ChannelMoveOperation | null {
- return createChannelMoveOperation({
- channels,
- dragItem: dragItemFrom(requireChannel(channels, sourceId)),
- dropResult,
- });
-}
-
-function applyOperation(channels: ReadonlyArray<Channel>, operation: ChannelMoveOperation) {
- const plan = computeGuildChannelReorderPlan({
- channels,
- operation: {
- channelId: operation.channelId,
- parentId: operation.newParentId,
- precedingSiblingId: operation.precedingSiblingId,
- },
- });
- if (!plan.ok) throw new Error(`Unexpected invalid channel reorder plan: ${plan.code}`);
- return plan.plan;
-}
-
-function finalIds(channels: ReadonlyArray<Channel>, operation: ChannelMoveOperation): Array<string> {
- return applyOperation(channels, operation).finalChannels.map((ch) => ch.id);
-}
-
-function finalParent(
- channels: ReadonlyArray<Channel>,
- operation: ChannelMoveOperation,
- channelId: string,
-): string | null {
- return applyOperation(channels, operation).desiredParentById.get(channelId) ?? null;
-}
-
-describe('channel reorder decision integration', () => {
- it('turns a bottom-half category drop into a text channel move inside the category before voice siblings', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'root-text', 'category-a', rect.bottom - 1);
- expect(dropResult).toEqual({
- targetId: 'category-a',
- position: 'inside',
- targetParentId: 'category-a',
- });
- const operation = createOperation(channels, 'root-text', dropResult);
- expect(operation).toEqual({
- channelId: 'root-text',
- newParentId: 'category-a',
- precedingSiblingId: 'a-text-2',
- position: 2,
- });
- expect(finalParent(channels, operation!, 'root-text')).toBe('category-a');
- expect(finalIds(channels, operation!)).toEqual([
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'root-text',
- 'a-voice-1',
- 'a-voice-2',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- 'root-voice',
- ]);
- });
-
- it('turns a bottom-half category drop into a voice channel move after existing voice siblings', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'root-voice', 'category-a', rect.bottom - 1);
- const operation = createOperation(channels, 'root-voice', dropResult);
- expect(operation).toEqual({
- channelId: 'root-voice',
- newParentId: 'category-a',
- precedingSiblingId: 'a-voice-2',
- position: 4,
- });
- expect(finalParent(channels, operation!, 'root-voice')).toBe('category-a');
- expect(finalIds(channels, operation!)).toEqual([
- 'root-text',
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'a-voice-1',
- 'a-voice-2',
- 'root-voice',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- ]);
- });
-
- it('preserves text-before-voice ordering when a voice channel is dropped before text siblings', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'a-voice-1', 'a-text-1', rect.top + 1);
- expect(dropResult).toEqual({
- targetId: 'a-text-1',
- position: 'before',
- targetParentId: 'category-a',
- });
- expect(createOperation(channels, 'a-voice-1', dropResult)).toBeNull();
- });
-
- it('moves a voice channel after another voice sibling inside the same category', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'a-voice-1', 'a-voice-2', rect.bottom - 1);
- const operation = createOperation(channels, 'a-voice-1', dropResult);
- expect(operation).toEqual({
- channelId: 'a-voice-1',
- newParentId: 'category-a',
- precedingSiblingId: 'a-voice-2',
- position: 3,
- });
- expect(finalIds(channels, operation!)).toEqual([
- 'root-text',
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'a-voice-2',
- 'a-voice-1',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- 'root-voice',
- ]);
- });
-
- it('blocks text and link channel drops onto voice rows before they can produce move operations', () => {
- const channels = channelsFixture();
- const textIntent = selectChannelReorderIntent(
- dragItemFrom(requireChannel(channels, 'a-text-1')),
- targetFrom(requireChannel(channels, 'a-voice-1')),
- point(rect.top + 1),
- rect,
- );
- const linkIntent = selectChannelReorderIntent(
- dragItemFrom(requireChannel(channels, 'b-link-1')),
- targetFrom(requireChannel(channels, 'b-voice-1')),
- point(rect.bottom - 1),
- rect,
- );
- expect(textIntent).toBeNull();
- expect(linkIntent).toBeNull();
- });
-
- it('moves an entire category block before another category', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'category-b', 'category-a', rect.top + 1);
- const operation = createOperation(channels, 'category-b', dropResult);
- expect(operation).toEqual({
- channelId: 'category-b',
- newParentId: null,
- precedingSiblingId: 'root-text',
- position: 1,
- });
- expect(finalIds(channels, operation!)).toEqual([
- 'root-text',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'a-voice-1',
- 'a-voice-2',
- 'root-voice',
- ]);
- });
-
- it('moves an entire category block after another category block from the bottom half', () => {
- const channels = channelsFixture();
- const dropResult = requireMachineDropResult(channels, 'category-a', 'category-b', rect.bottom - 1);
- expect(dropResult).toEqual({
- targetId: 'category-b',
- position: 'after',
- targetParentId: null,
- });
- const operation = createOperation(channels, 'category-a', dropResult);
- expect(operation).toEqual({
- channelId: 'category-a',
- newParentId: null,
- precedingSiblingId: 'category-b',
- position: 2,
- });
- expect(finalIds(channels, operation!)).toEqual([
- 'root-text',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'a-voice-1',
- 'a-voice-2',
- 'root-voice',
- ]);
- });
-
- it('blocks category drops onto child channels before they can produce move operations', () => {
- const channels = channelsFixture();
- const intent = selectChannelReorderIntent(
- dragItemFrom(requireChannel(channels, 'category-b')),
- targetFrom(requireChannel(channels, 'a-text-1')),
- point(rect.top + 1),
- rect,
- );
- expect(intent).toBeNull();
- });
-
- it('moves nested channels to the top null-space as root channels', () => {
- const channels = channelsFixture();
- const operation = createOperation(channels, 'b-text-1', {
- targetId: 'null-space',
- position: 'before',
- targetParentId: null,
- });
- expect(operation).toEqual({
- channelId: 'b-text-1',
- newParentId: null,
- precedingSiblingId: null,
- position: 0,
- });
- expect(finalParent(channels, operation!, 'b-text-1')).toBeNull();
- expect(finalIds(channels, operation!)).toEqual([
- 'b-text-1',
- 'root-text',
- 'category-a',
- 'a-text-1',
- 'a-text-2',
- 'a-voice-1',
- 'a-voice-2',
- 'category-b',
- 'b-link-1',
- 'b-voice-1',
- 'root-voice',
- ]);
- });
-
- it('moves nested channels to trailing space as root channels after the final root sibling', () => {
- const channels = channelsFixture();
- const operation = createOperation(channels, 'a-text-1', {
- targetId: 'trailing-space',
- position: 'after',
- targetParentId: null,
- });
- expect(operation).toEqual({
- channelId: 'a-text-1',
- newParentId: null,
- precedingSiblingId: 'root-voice',
- position: 4,
- });
- expect(finalParent(channels, operation!, 'a-text-1')).toBeNull();
- expect(finalIds(channels, operation!)).toEqual([
- 'root-text',
- 'category-a',
- 'a-text-2',
- 'a-voice-1',
- 'a-voice-2',
- 'category-b',
- 'b-text-1',
- 'b-link-1',
- 'b-voice-1',
- 'root-voice',
- 'a-text-1',
- ]);
- });
-
- it('does not produce operations for current-position drops', () => {
- const channels = channelsFixture();
- expect(
- createOperation(
- channels,
- 'a-text-2',
- requireMachineDropResult(channels, 'a-text-2', 'a-text-1', rect.bottom - 1),
- ),
- ).toBeNull();
- expect(
- createOperation(
- channels,
- 'category-b',
- requireMachineDropResult(channels, 'category-b', 'category-a', rect.bottom - 1),
- ),
- ).toBeNull();
- });
-
- it('every machine-produced reorder result is accepted by the move-operation planner or resolves to a no-op', () => {
- const channels = channelsFixture();
- const sources = channels;
- for (const source of sources) {
- for (const target of channels) {
- for (const y of [rect.top + 1, rect.bottom - 1]) {
- const intent = selectChannelReorderIntent(dragItemFrom(source), targetFrom(target), point(y), rect);
- if (!intent) continue;
- const operation = createOperation(channels, source.id, intent.result);
- if (!operation) continue;
- const plan = computeGuildChannelReorderPlan({
- channels,
- operation: {
- channelId: operation.channelId,
- parentId: operation.newParentId,
- precedingSiblingId: operation.precedingSiblingId,
- },
- });
- expect(plan, `${source.id} -> ${target.id} @ ${y}`).toMatchObject({ok: true});
- }
- }
- }
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderStateMachine.test.ts b/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderStateMachine.test.ts
deleted file mode 100644
index 85ca6bf2d..000000000
--- a/fluxer_app/src/features/app/components/layout/dnd/ChannelReorderStateMachine.test.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelReorderRect,
- type ChannelReorderTarget,
- canChannelDropOnTarget,
- createChannelReorderSnapshot,
- getChannelReorderStateValue,
- resolveChannelReorderHover,
- selectChannelReorderIntent,
- selectChannelReorderResolution,
- transitionChannelReorderSnapshot,
-} from '@app/features/app/components/layout/dnd/ChannelReorderStateMachine';
-import {type DragItem, DragItemType} from '@app/features/app/components/layout/types/DndTypes';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it} from 'vitest';
-
-const rect: ChannelReorderRect = {
- top: 40,
- bottom: 72,
- left: 0,
- right: 240,
-};
-
-function point(y: number) {
- return {
- x: 80,
- y,
- };
-}
-
-function channelItem(
- id: string,
- channelType: number = ChannelTypes.GUILD_TEXT,
- parentId: string | null = null,
-): DragItem {
- return {
- type: DragItemType.CHANNEL,
- id,
- channelType,
- parentId,
- guildId: 'guild-1',
- };
-}
-
-function categoryItem(id = 'category-source'): DragItem {
- return {
- type: DragItemType.CATEGORY,
- id,
- channelType: ChannelTypes.GUILD_CATEGORY,
- parentId: null,
- guildId: 'guild-1',
- };
-}
-
-function voiceParticipantItem(id = 'user-1', currentChannelId = 'voice-source'): DragItem {
- return {
- type: DragItemType.VOICE_PARTICIPANT,
- id,
- channelType: ChannelTypes.GUILD_VOICE,
- parentId: null,
- guildId: 'guild-1',
- userId: id,
- currentChannelId,
- };
-}
-
-function target(
- id: string,
- channelType: number = ChannelTypes.GUILD_TEXT,
- parentId: string | null = null,
-): ChannelReorderTarget {
- return {
- id,
- channelType,
- parentId,
- guildId: 'guild-1',
- };
-}
-
-describe('ChannelReorderStateMachine', () => {
- it('starts idle and targets a valid channel hover', () => {
- let snapshot = createChannelReorderSnapshot();
- expect(getChannelReorderStateValue(snapshot)).toBe('idle');
- snapshot = transitionChannelReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: channelItem('source'),
- target: target('target'),
- clientOffset: point(42),
- targetRect: rect,
- });
- expect(getChannelReorderStateValue(snapshot)).toBe('targeting');
- expect(snapshot.context.intent?.indicator).toEqual({position: 'top', isValid: true});
- expect(snapshot.context.intent?.result).toEqual({
- targetId: 'target',
- position: 'before',
- targetParentId: null,
- });
- });
-
- it('clears targeting state on drop', () => {
- let snapshot = createChannelReorderSnapshot();
- snapshot = transitionChannelReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: channelItem('source'),
- target: target('target'),
- clientOffset: point(42),
- targetRect: rect,
- });
- snapshot = transitionChannelReorderSnapshot(snapshot, {type: 'drag.drop'});
- expect(getChannelReorderStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.intent).toBeNull();
- expect(snapshot.context.indicator).toBeNull();
- });
-
- it('blocks dragging an item onto itself and clears on leave', () => {
- let snapshot = createChannelReorderSnapshot();
- snapshot = transitionChannelReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: channelItem('same'),
- target: target('same'),
- clientOffset: point(42),
- targetRect: rect,
- });
- expect(getChannelReorderStateValue(snapshot)).toBe('blocked');
- expect(snapshot.context.blockedReason).toBe('same-source-and-target');
- expect(snapshot.context.indicator).toEqual({position: 'top', isValid: false});
- snapshot = transitionChannelReorderSnapshot(snapshot, {type: 'drag.leave'});
- expect(getChannelReorderStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.blockedReason).toBeNull();
- });
-
- it('covers every pixel of a valid regular channel target with a concrete reorder result', () => {
- const source = channelItem('source');
- const destination = target('target', ChannelTypes.GUILD_TEXT, 'category-1');
- for (let y = rect.top; y <= rect.bottom; y++) {
- const intent = selectChannelReorderIntent(source, destination, point(y), rect);
- expect(intent, `expected intent for y=${y}`).not.toBeNull();
- expect(['before', 'after']).toContain(intent?.result.position);
- expect(intent?.result.targetParentId).toBe('category-1');
- }
- });
-
- it('maps regular channel top and bottom halves to before and after', () => {
- const source = channelItem('source');
- const destination = target('target', ChannelTypes.GUILD_TEXT, 'category-1');
- expect(selectChannelReorderIntent(source, destination, point(41), rect)).toMatchObject({
- indicator: {position: 'top', isValid: true},
- result: {
- targetId: 'target',
- position: 'before',
- targetParentId: 'category-1',
- },
- });
- expect(selectChannelReorderIntent(source, destination, point(71), rect)).toMatchObject({
- indicator: {position: 'bottom', isValid: true},
- result: {
- targetId: 'target',
- position: 'after',
- targetParentId: 'category-1',
- },
- });
- });
-
- it('maps category top half to before-category and bottom half to inside-category', () => {
- const source = channelItem('source');
- const categoryTarget = target('category-1', ChannelTypes.GUILD_CATEGORY, null);
- expect(selectChannelReorderIntent(source, categoryTarget, point(41), rect)).toMatchObject({
- indicator: {position: 'top', isValid: true},
- result: {
- targetId: 'category-1',
- position: 'before',
- targetParentId: null,
- },
- });
- expect(selectChannelReorderIntent(source, categoryTarget, point(71), rect)).toMatchObject({
- indicator: {position: 'bottom', isValid: true},
- result: {
- targetId: 'category-1',
- position: 'inside',
- targetParentId: 'category-1',
- },
- });
- });
-
- it('allows voice channels to target text, voice, and category rows like the current move operation expects', () => {
- const source = channelItem('voice-source', ChannelTypes.GUILD_VOICE, 'category-1');
- expect(canChannelDropOnTarget(source, target('text-target', ChannelTypes.GUILD_TEXT, 'category-1'))).toBe(true);
- expect(canChannelDropOnTarget(source, target('voice-target', ChannelTypes.GUILD_VOICE, 'category-1'))).toBe(true);
- expect(canChannelDropOnTarget(source, target('category-1', ChannelTypes.GUILD_CATEGORY, null))).toBe(true);
- });
-
- it('blocks text channels from targeting voice rows and returns an invalid indicator', () => {
- const source = channelItem('text-source', ChannelTypes.GUILD_TEXT, 'category-1');
- const destination = target('voice-target', ChannelTypes.GUILD_VOICE, 'category-1');
- expect(canChannelDropOnTarget(source, destination)).toBe(false);
- expect(resolveChannelReorderHover(source, destination, point(71), rect)).toMatchObject({
- intent: null,
- indicator: {position: 'bottom', isValid: false},
- blockedReason: 'incompatible-channel-kind',
- isVoiceParticipantTransfer: false,
- });
- });
-
- it('blocks dragging a category onto a child channel', () => {
- const source = categoryItem();
- const childTarget = target('child', ChannelTypes.GUILD_TEXT, 'category-1');
- expect(canChannelDropOnTarget(source, childTarget)).toBe(false);
- expect(resolveChannelReorderHover(source, childTarget, point(41), rect)).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'category-into-child-channel',
- });
- });
-
- it('allows dragging a category before or after a top-level channel target', () => {
- const source = categoryItem();
- const topLevelTarget = target('root-channel', ChannelTypes.GUILD_TEXT, null);
- expect(selectChannelReorderIntent(source, topLevelTarget, point(41), rect)).toMatchObject({
- result: {
- targetId: 'root-channel',
- position: 'before',
- targetParentId: null,
- },
- });
- expect(selectChannelReorderIntent(source, topLevelTarget, point(71), rect)).toMatchObject({
- result: {
- targetId: 'root-channel',
- position: 'after',
- targetParentId: null,
- },
- });
- });
-
- it('maps category-to-category bottom drops to after instead of inside', () => {
- const source = categoryItem('category-source');
- const categoryTarget = target('category-target', ChannelTypes.GUILD_CATEGORY, null);
- expect(selectChannelReorderIntent(source, categoryTarget, point(71), rect)).toMatchObject({
- indicator: {position: 'bottom', isValid: true},
- result: {
- targetId: 'category-target',
- position: 'after',
- targetParentId: null,
- },
- });
- });
-
- it('treats voice participant drops onto voice channels as transfers, not reorder intents', () => {
- const resolution = selectChannelReorderResolution(
- voiceParticipantItem(),
- target('voice-target', ChannelTypes.GUILD_VOICE, 'category-1'),
- point(41),
- rect,
- );
- expect(resolution).toEqual({
- intent: null,
- indicator: null,
- blockedReason: null,
- isVoiceParticipantTransfer: true,
- });
- let snapshot = createChannelReorderSnapshot();
- snapshot = transitionChannelReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: voiceParticipantItem(),
- target: target('voice-target', ChannelTypes.GUILD_VOICE, 'category-1'),
- clientOffset: point(41),
- targetRect: rect,
- });
- expect(getChannelReorderStateValue(snapshot)).toBe('voiceParticipantTransfer');
- });
-
- it('blocks voice participant drops onto non-voice channels with an invalid indicator', () => {
- const resolution = selectChannelReorderResolution(
- voiceParticipantItem(),
- target('text-target', ChannelTypes.GUILD_TEXT, 'category-1'),
- point(71),
- rect,
- );
- expect(resolution).toMatchObject({
- intent: null,
- indicator: {position: 'bottom', isValid: false},
- blockedReason: 'incompatible-channel-kind',
- isVoiceParticipantTransfer: false,
- });
- });
-
- it('blocks zero-height target rects without manufacturing a drop result', () => {
- const emptyRect = {...rect, bottom: rect.top};
- expect(resolveChannelReorderHover(channelItem('source'), target('target'), point(rect.top), emptyRect)).toEqual({
- intent: null,
- indicator: null,
- blockedReason: 'empty-target-rect',
- isVoiceParticipantTransfer: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/dnd/GuildReorderStateMachine.test.ts b/fluxer_app/src/features/app/components/layout/dnd/GuildReorderStateMachine.test.ts
deleted file mode 100644
index f4c4b2fc7..000000000
--- a/fluxer_app/src/features/app/components/layout/dnd/GuildReorderStateMachine.test.ts
+++ /dev/null
@@ -1,334 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createGuildReorderSnapshot,
- GuildReorderBlockedReason,
- GuildReorderStateMachine,
- type GuildReorderTarget,
- GuildReorderTargetKind,
- resolveGuildReorderHover,
- transitionGuildReorderSnapshot,
-} from '@app/features/app/components/layout/dnd/GuildReorderStateMachine';
-import {
- DNDReorderState,
- DragItemType,
- DropPlacement,
- type GuildDragItem,
-} from '@app/features/app/components/layout/types/DndTypes';
-import {Edge} from '@app/features/ui/AxisOrientation';
-import type {VerticalDropRect} from '@app/features/ui/dnd/DropGeometry';
-import {RelativePosition} from '@app/features/ui/RelativePosition';
-import {describe, expect, it} from 'vitest';
-
-const rect: VerticalDropRect = {
- top: 100,
- bottom: 154,
-};
-
-function guildItem(id: string, folderId: number | null = null): GuildDragItem {
- return {
- type: DragItemType.GUILD_ITEM,
- id,
- isFolder: false,
- folderId,
- };
-}
-
-function folderItem(id = 'folder-1', folderId = 1): GuildDragItem {
- return {
- type: DragItemType.GUILD_FOLDER,
- id,
- isFolder: true,
- folderId,
- };
-}
-
-function rootGuildTarget(id = 'guild-target'): GuildReorderTarget {
- return {
- id,
- kind: GuildReorderTargetKind.TOP_LEVEL_GUILD,
- };
-}
-
-function folderGuildTarget(id = 'guild-target', isTerminal = false): GuildReorderTarget {
- return {
- id,
- kind: GuildReorderTargetKind.FOLDER_GUILD,
- folderId: 1,
- isTerminal,
- };
-}
-
-function folderTarget(id = 'folder-1'): GuildReorderTarget {
- return {
- id,
- kind: GuildReorderTargetKind.FOLDER,
- };
-}
-
-function point(y: number) {
- return {
- x: 36,
- y,
- };
-}
-
-describe('GuildReorderStateMachine', () => {
- it('starts idle and targets a valid top-level reorder hover', () => {
- let snapshot = createGuildReorderSnapshot();
- expect(snapshot.value).toBe(DNDReorderState.IDLE);
- snapshot = transitionGuildReorderSnapshot({
- snapshot,
- event: {
- type: 'drag.hover',
- item: guildItem('guild-source'),
- target: rootGuildTarget(),
- clientOffset: point(104),
- targetRect: rect,
- },
- });
- expect(snapshot.value).toBe(DNDReorderState.TARGETING);
- expect(snapshot.context.intent?.result).toMatchObject({
- targetId: 'guild-target',
- position: RelativePosition.BEFORE,
- targetIsFolder: false,
- });
- expect(snapshot.context.intent?.indicator).toBe(Edge.TOP);
- });
-
- it('moves to blocked state for invalid hovers and clears on leave', () => {
- let snapshot = createGuildReorderSnapshot();
- snapshot = transitionGuildReorderSnapshot({
- snapshot,
- event: {
- type: 'drag.hover',
- item: guildItem('guild-target'),
- target: rootGuildTarget('guild-target'),
- clientOffset: point(104),
- targetRect: rect,
- },
- });
- expect(snapshot.value).toBe(DNDReorderState.BLOCKED);
- expect(snapshot.context.blockedReason).toBe(GuildReorderBlockedReason.SAME_SOURCE_AND_TARGET);
- snapshot = transitionGuildReorderSnapshot({snapshot, event: {type: 'drag.leave'}});
- expect(snapshot.value).toBe(DNDReorderState.IDLE);
- expect(snapshot.context.intent).toBeNull();
- expect(snapshot.context.blockedReason).toBeNull();
- });
-
- it('clears targeting state after drop', () => {
- let snapshot = createGuildReorderSnapshot();
- snapshot = transitionGuildReorderSnapshot({
- snapshot,
- event: {
- type: 'drag.hover',
- item: guildItem('guild-source'),
- target: rootGuildTarget(),
- clientOffset: point(104),
- targetRect: rect,
- },
- });
- snapshot = transitionGuildReorderSnapshot({snapshot, event: {type: 'drag.drop'}});
- expect(snapshot.value).toBe(DNDReorderState.IDLE);
- expect(snapshot.context.intent).toBeNull();
- });
-
- it('covers every pixel of a top-level guild target with either reorder-before or combine', () => {
- const item = guildItem('guild-source');
- const target = rootGuildTarget();
- for (let y = rect.top; y <= rect.bottom; y++) {
- const intent = GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(y), targetRect: rect});
- expect(intent, `expected intent for y=${y}`).not.toBeNull();
- expect([RelativePosition.BEFORE, DropPlacement.COMBINE]).toContain(intent?.result.position);
- }
- });
-
- it('uses one top-level insertion target between adjacent guilds by never returning after from an item hover', () => {
- const item = guildItem('guild-source');
- const target = rootGuildTarget('guild-next');
- const upperEdgeIntent = GuildReorderStateMachine.selectIntent({
- item,
- target,
- clientOffset: point(101),
- targetRect: rect,
- });
- const middleIntent = GuildReorderStateMachine.selectIntent({
- item,
- target,
- clientOffset: point(130),
- targetRect: rect,
- });
- const lowerEdgeIntent = GuildReorderStateMachine.selectIntent({
- item,
- target,
- clientOffset: point(153),
- targetRect: rect,
- });
- expect(upperEdgeIntent?.result.position).toBe(RelativePosition.BEFORE);
- expect(middleIntent?.result.position).toBe(DropPlacement.COMBINE);
- expect(lowerEdgeIntent?.result.position).toBe(DropPlacement.COMBINE);
- expect(middleIntent?.result.position).not.toBe(RelativePosition.AFTER);
- expect(lowerEdgeIntent?.result.position).not.toBe(RelativePosition.AFTER);
- });
-
- it('maps root guild top edge to reorder and center/bottom to folder combine for guild sources', () => {
- const item = guildItem('guild-source');
- const target = rootGuildTarget();
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(100), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {position: RelativePosition.BEFORE},
- });
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(114), targetRect: rect}),
- ).toMatchObject({
- indicator: DropPlacement.COMBINE,
- combineSourceGuildId: 'guild-source',
- result: {position: DropPlacement.COMBINE},
- });
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(154), targetRect: rect}),
- ).toMatchObject({
- indicator: DropPlacement.COMBINE,
- combineSourceGuildId: 'guild-source',
- result: {position: DropPlacement.COMBINE},
- });
- });
-
- it('does not combine folders with root guilds while dragging a folder', () => {
- const item = folderItem();
- const target = rootGuildTarget();
- for (const y of [rect.top, 127, rect.bottom]) {
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(y), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {
- position: RelativePosition.BEFORE,
- targetIsFolder: false,
- },
- });
- }
- });
-
- it('uses a single before-target slot for non-terminal guilds inside a folder', () => {
- const item = guildItem('guild-source', 1);
- const target = folderGuildTarget('guild-middle', false);
- for (const y of [rect.top, 127, rect.bottom]) {
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(y), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {
- targetId: 'guild-middle',
- position: RelativePosition.BEFORE,
- targetIsFolder: false,
- targetFolderId: 1,
- },
- });
- }
- });
-
- it('allows the terminal guild inside a folder to own the final after slot', () => {
- const item = guildItem('guild-source', 1);
- const target = folderGuildTarget('guild-last', true);
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(101), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {
- targetId: 'guild-last',
- position: RelativePosition.BEFORE,
- targetFolderId: 1,
- },
- });
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(153), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.BOTTOM,
- result: {
- targetId: 'guild-last',
- position: RelativePosition.AFTER,
- targetFolderId: 1,
- },
- });
- });
-
- it('blocks dragging a folder onto a guild inside another folder', () => {
- const item = folderItem('folder-2', 2);
- const target = folderGuildTarget('guild-inside-folder', true);
- expect(GuildReorderStateMachine.canDrop({item, target})).toBe(false);
- expect(resolveGuildReorderHover({item, target, clientOffset: point(127), targetRect: rect})).toEqual({
- intent: null,
- blockedReason: GuildReorderBlockedReason.FOLDER_INTO_FOLDER_GUILD,
- });
- });
-
- it('uses top edge for reordering before a folder and the rest of a folder target for adding a guild inside', () => {
- const item = guildItem('guild-source');
- const target = folderTarget('folder-1');
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(101), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {
- targetId: 'folder-1',
- position: RelativePosition.BEFORE,
- targetIsFolder: true,
- },
- });
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(127), targetRect: rect}),
- ).toMatchObject({
- indicator: DropPlacement.INSIDE,
- result: {
- targetId: 'folder-1',
- position: DropPlacement.INSIDE,
- targetIsFolder: true,
- },
- });
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(153), targetRect: rect}),
- ).toMatchObject({
- indicator: DropPlacement.INSIDE,
- result: {
- targetId: 'folder-1',
- position: DropPlacement.INSIDE,
- targetIsFolder: true,
- },
- });
- });
-
- it('only reorders before a folder when dragging another folder', () => {
- const item = folderItem('folder-2', 2);
- const target = folderTarget('folder-1');
- for (const y of [rect.top, 127, rect.bottom]) {
- expect(
- GuildReorderStateMachine.selectIntent({item, target, clientOffset: point(y), targetRect: rect}),
- ).toMatchObject({
- indicator: Edge.TOP,
- result: {
- targetId: 'folder-1',
- position: RelativePosition.BEFORE,
- targetIsFolder: true,
- },
- });
- }
- });
-
- it('blocks zero-height target rects instead of producing a void result', () => {
- const emptyRect = {...rect, bottom: rect.top};
- expect(
- resolveGuildReorderHover({
- item: guildItem('guild-source'),
- target: rootGuildTarget(),
- clientOffset: point(rect.top),
- targetRect: emptyRect,
- }),
- ).toEqual({
- intent: null,
- blockedReason: GuildReorderBlockedReason.EMPTY_TARGET_RECT,
- });
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/utils/ChannelListVisibility.test.ts b/fluxer_app/src/features/app/components/layout/utils/ChannelListVisibility.test.ts
deleted file mode 100644
index 6dc2ca36a..000000000
--- a/fluxer_app/src/features/app/components/layout/utils/ChannelListVisibility.test.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- shouldShowCategoryWhenHidingMutedChannels,
- shouldShowChannelInCollapsedCategory,
- shouldShowChannelWhenHidingMutedChannels,
-} from '@app/features/app/components/layout/utils/ChannelListVisibility';
-import {describe, expect, it} from 'vitest';
-
-describe('shouldShowChannelWhenHidingMutedChannels', () => {
- it('keeps muted channels with visible unread state so mentions are findable', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: false,
- isChannelMuted: true,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: true,
- }),
- ).toBe(true);
- });
-
- it('hides muted channels without visible unread state', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: false,
- isChannelMuted: true,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: false,
- }),
- ).toBe(false);
- });
-
- it('inherits the mute from a muted category', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: true,
- isChannelMuted: false,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: false,
- }),
- ).toBe(false);
- });
-
- it('keeps channels of a muted category that have visible unread state', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: true,
- isChannelMuted: false,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: true,
- }),
- ).toBe(true);
- });
-
- it('keeps selected and connected muted channels visible', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: true,
- isChannelMuted: true,
- isSelected: true,
- isConnected: false,
- hasVisibleUnread: false,
- }),
- ).toBe(true);
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: true,
- isChannelMuted: false,
- isSelected: false,
- isConnected: true,
- hasVisibleUnread: false,
- }),
- ).toBe(true);
- });
-
- it('keeps unmuted channels visible', () => {
- expect(
- shouldShowChannelWhenHidingMutedChannels({
- isCategoryMuted: false,
- isChannelMuted: false,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: false,
- }),
- ).toBe(true);
- });
-});
-
-describe('shouldShowCategoryWhenHidingMutedChannels', () => {
- it('keeps a category that has no channels at all', () => {
- expect(
- shouldShowCategoryWhenHidingMutedChannels({
- hasChannels: false,
- hasVisibleChannels: false,
- }),
- ).toBe(true);
- });
-
- it('hides a category whose channels were all filtered out as muted', () => {
- expect(
- shouldShowCategoryWhenHidingMutedChannels({
- hasChannels: true,
- hasVisibleChannels: false,
- }),
- ).toBe(false);
- });
-
- it('keeps a category that still has visible channels', () => {
- expect(
- shouldShowCategoryWhenHidingMutedChannels({
- hasChannels: true,
- hasVisibleChannels: true,
- }),
- ).toBe(true);
- });
-});
-
-describe('shouldShowChannelInCollapsedCategory', () => {
- it('keeps visible unread channels reachable in collapsed categories', () => {
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: false,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: true,
- hasMentions: false,
- }),
- ).toBe(true);
- });
-
- it('keeps selected and connected channels visible without unread state, even in muted categories', () => {
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: true,
- isSelected: true,
- isConnected: false,
- hasVisibleUnread: false,
- hasMentions: false,
- }),
- ).toBe(true);
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: true,
- isSelected: false,
- isConnected: true,
- hasVisibleUnread: false,
- hasMentions: false,
- }),
- ).toBe(true);
- });
-
- it('hides read channels in collapsed categories', () => {
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: false,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: false,
- hasMentions: false,
- }),
- ).toBe(false);
- });
-
- it('hides unread channels without mentions in muted collapsed categories', () => {
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: true,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: true,
- hasMentions: false,
- }),
- ).toBe(false);
- });
-
- it('keeps mentioned channels reachable in muted collapsed categories', () => {
- expect(
- shouldShowChannelInCollapsedCategory({
- isCategoryMuted: true,
- isSelected: false,
- isConnected: false,
- hasVisibleUnread: true,
- hasMentions: true,
- }),
- ).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadState.test.ts b/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadState.test.ts
deleted file mode 100644
index 39f686ce7..000000000
--- a/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadState.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getChannelUnreadState} from '@app/features/app/components/layout/utils/ChannelUnreadState';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('getChannelUnreadState', () => {
- it('shows a normal unread indicator for all-messages unread badges', () => {
- const state = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 3,
- mentionCount: 0,
- isMuted: false,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: MessageNotifications.ALL_MESSAGES,
- });
- expect(state.shouldShowUnreadIndicator).toBe(true);
- expect(state.isUnreadIndicatorMuted).toBe(false);
- expect(state.isHighlight).toBe(true);
- });
- it('shows a muted unread indicator for only-mentions unread badges without highlighting the channel', () => {
- const state = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 3,
- mentionCount: 0,
- isMuted: false,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: MessageNotifications.ONLY_MENTIONS,
- });
- expect(state.shouldShowUnreadIndicator).toBe(true);
- expect(state.isUnreadIndicatorMuted).toBe(true);
- expect(state.isHighlight).toBe(false);
- });
- it('hides unread and mention surfaces when unread badges are disabled', () => {
- const state = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 3,
- mentionCount: 1,
- isMuted: false,
- showFadedUnreadOnMutedChannels: true,
- unreadBadgesLevel: MessageNotifications.NO_MESSAGES,
- });
- expect(state.shouldShowUnreadIndicator).toBe(false);
- expect(state.hasMentions).toBe(false);
- expect(state.hasVisibleUnread).toBe(false);
- });
- it('keeps legacy muted-channel fading for channels without an unread-badges level', () => {
- const hiddenState = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 3,
- mentionCount: 0,
- isMuted: true,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: null,
- });
- const fadedState = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 3,
- mentionCount: 0,
- isMuted: true,
- showFadedUnreadOnMutedChannels: true,
- unreadBadgesLevel: null,
- });
- expect(hiddenState.shouldShowUnreadIndicator).toBe(false);
- expect(fadedState.shouldShowUnreadIndicator).toBe(true);
- expect(fadedState.isUnreadIndicatorMuted).toBe(true);
- });
- it('shows the indicator from the unread flag rather than the message count', () => {
- const state = getChannelUnreadState({
- hasUnread: true,
- unreadCount: 0,
- mentionCount: 0,
- isMuted: false,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: null,
- });
- expect(state.shouldShowUnreadIndicator).toBe(true);
- });
- it('hides the indicator for a read channel even if a stale count survives', () => {
- const state = getChannelUnreadState({
- hasUnread: false,
- unreadCount: 7,
- mentionCount: 0,
- isMuted: false,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: null,
- });
- expect(state.shouldShowUnreadIndicator).toBe(false);
- expect(state.hasVisibleUnread).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadStateMachine.test.ts b/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadStateMachine.test.ts
deleted file mode 100644
index 6053059b2..000000000
--- a/fluxer_app/src/features/app/components/layout/utils/ChannelUnreadStateMachine.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ChannelUnreadStateInput} from '@app/features/app/components/layout/utils/ChannelUnreadState';
-import {
- type ChannelUnreadStateValue,
- createChannelUnreadSnapshot,
- selectChannelUnreadState,
- transitionChannelUnreadSnapshot,
-} from '@app/features/app/components/layout/utils/ChannelUnreadStateMachine';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<ChannelUnreadStateInput> = {}): ChannelUnreadStateInput {
- return {
- hasUnread: false,
- unreadCount: 0,
- mentionCount: 0,
- isMuted: false,
- showFadedUnreadOnMutedChannels: false,
- unreadBadgesLevel: null,
- ...overrides,
- };
-}
-
-function expectState(overrides: Partial<ChannelUnreadStateInput>, expected: ChannelUnreadStateValue): void {
- const snapshot = createChannelUnreadSnapshot(input(overrides));
- expect(snapshot.value).toBe(expected);
-}
-
-describe('channelUnreadStateMachine', () => {
- it('routes each unread badge policy to an explicit state', () => {
- expectState({unreadBadgesLevel: MessageNotifications.NO_MESSAGES}, 'disabled');
- expectState({unreadBadgesLevel: MessageNotifications.ONLY_MENTIONS}, 'onlyMentions');
- expectState({unreadBadgesLevel: MessageNotifications.ALL_MESSAGES}, 'allMessages');
- expectState({unreadBadgesLevel: null}, 'legacy');
- });
-
- it('suppresses all visible unread surfaces when badges are disabled', () => {
- const snapshot = createChannelUnreadSnapshot(
- input({
- unreadBadgesLevel: MessageNotifications.NO_MESSAGES,
- hasUnread: true,
- unreadCount: 1,
- mentionCount: 1,
- }),
- );
-
- expect(selectChannelUnreadState(snapshot)).toMatchObject({
- hasUnreadMessages: true,
- hasMentions: false,
- isHighlight: false,
- shouldShowUnreadIndicator: false,
- hasVisibleUnread: false,
- });
- });
-
- it('transitions without preserving stale policy output', () => {
- const legacySnapshot = createChannelUnreadSnapshot(
- input({
- hasUnread: true,
- unreadCount: 2,
- isMuted: true,
- showFadedUnreadOnMutedChannels: false,
- }),
- );
- expect(selectChannelUnreadState(legacySnapshot).shouldShowUnreadIndicator).toBe(false);
-
- const allMessagesSnapshot = transitionChannelUnreadSnapshot(legacySnapshot, {
- type: 'channelUnread.updated',
- input: input({
- unreadBadgesLevel: MessageNotifications.ALL_MESSAGES,
- hasUnread: true,
- unreadCount: 2,
- isMuted: true,
- }),
- });
-
- expect(allMessagesSnapshot.value).toBe('allMessages');
- expect(selectChannelUnreadState(allMessagesSnapshot)).toMatchObject({
- isHighlight: true,
- shouldShowUnreadIndicator: true,
- isUnreadIndicatorMuted: false,
- });
- });
-});
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 8965e6711..000000000
--- a/fluxer_app/src/features/app/components/setup/SetupWizardStateMachine.test.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createSetupWizardSnapshot,
- type SetupWizardMachineEvent,
- type SetupWizardSnapshot,
- selectSetupWizardModel,
- transitionSetupWizardSnapshot,
-} from '@app/features/app/components/setup/SetupWizardStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function transition(snapshot: SetupWizardSnapshot, event: SetupWizardMachineEvent): SetupWizardSnapshot {
- return transitionSetupWizardSnapshot(snapshot, event);
-}
-
-function sync(snapshot: SetupWizardSnapshot, isAuthenticated: boolean, hasConfig: boolean): SetupWizardSnapshot {
- return transition(snapshot, {type: 'wizard.sync', isAuthenticated, hasConfig});
-}
-
-describe('setupWizardStateMachine', () => {
- it('starts unauthenticated in the register phase on the welcome step', () => {
- const model = selectSetupWizardModel(createSetupWizardSnapshot());
-
- expect(model).toMatchObject({phase: 'register', step: 'welcome', direction: 0, stepIndex: 0});
- });
-
- it('advances and retreats within the register phase by step identity', () => {
- let snapshot = createSetupWizardSnapshot();
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot)).toMatchObject({step: 'theme', direction: 1});
-
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('admin_intro');
-
- snapshot = transition(snapshot, {type: 'wizard.back'});
- expect(selectSetupWizardModel(snapshot)).toMatchObject({step: 'theme', direction: -1});
- });
-
- it('does not advance past the last register step', () => {
- let snapshot = createSetupWizardSnapshot();
- for (let index = 0; index < 8; index += 1) {
- snapshot = transition(snapshot, {type: 'wizard.next'});
- }
-
- expect(selectSetupWizardModel(snapshot).step).toBe('admin_account');
- });
-
- it('does not retreat before the first step', () => {
- const snapshot = transition(createSetupWizardSnapshot(), {type: 'wizard.back'});
-
- expect(selectSetupWizardModel(snapshot).step).toBe('welcome');
- });
-
- it('routes to the loading phase once authenticated before the config loads', () => {
- let snapshot = createSetupWizardSnapshot();
- snapshot = transition(snapshot, {type: 'wizard.next'});
- snapshot = transition(snapshot, {type: 'wizard.next'});
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('admin_account');
-
- snapshot = sync(snapshot, true, false);
-
- expect(selectSetupWizardModel(snapshot)).toMatchObject({phase: 'loading', step: 'loading', direction: 0});
- });
-
- it('lands on branding then registration after registering, never skipping them', () => {
- let snapshot = createSetupWizardSnapshot();
- snapshot = transition(snapshot, {type: 'wizard.next'});
- snapshot = transition(snapshot, {type: 'wizard.next'});
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('admin_account');
-
- snapshot = sync(snapshot, true, false);
- snapshot = sync(snapshot, true, true);
-
- expect(selectSetupWizardModel(snapshot)).toMatchObject({phase: 'configure', step: 'welcome', direction: 0});
-
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('branding');
-
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('registration');
-
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('community');
- });
-
- it('enters the configure phase at welcome when already authenticated with config', () => {
- const snapshot = sync(createSetupWizardSnapshot(), true, true);
-
- expect(selectSetupWizardModel(snapshot)).toMatchObject({phase: 'configure', step: 'welcome'});
- });
-
- it('preserves the current step when a redundant sync keeps the same phase', () => {
- let snapshot = sync(createSetupWizardSnapshot(), true, true);
- snapshot = transition(snapshot, {type: 'wizard.next'});
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('registration');
-
- snapshot = sync(snapshot, true, true);
-
- expect(selectSetupWizardModel(snapshot).step).toBe('registration');
- });
-
- it('does not advance past the final configure step', () => {
- let snapshot = sync(createSetupWizardSnapshot(), true, true);
- for (let index = 0; index < 20; index += 1) {
- snapshot = transition(snapshot, {type: 'wizard.next'});
- }
-
- expect(selectSetupWizardModel(snapshot).step).toBe('finish');
- });
-
- it('falls back to the register phase when authentication is lost', () => {
- let snapshot = sync(createSetupWizardSnapshot(), true, true);
- snapshot = transition(snapshot, {type: 'wizard.next'});
- expect(selectSetupWizardModel(snapshot).step).toBe('branding');
-
- snapshot = sync(snapshot, false, false);
-
- expect(selectSetupWizardModel(snapshot)).toMatchObject({phase: 'register', step: 'welcome'});
- });
-});
diff --git a/fluxer_app/src/features/app/components/setup/SetupWizardWelcomeRotation.test.ts b/fluxer_app/src/features/app/components/setup/SetupWizardWelcomeRotation.test.ts
deleted file mode 100644
index 2b36ed509..000000000
--- a/fluxer_app/src/features/app/components/setup/SetupWizardWelcomeRotation.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createRandomWelcomeRotationState,
- createWelcomeRotationState,
- WELCOME_ROTATION,
- type WelcomeRotationState,
-} from '@app/features/app/components/setup/SetupWizardWelcomeRotation';
-import {describe, expect, it} from 'vitest';
-
-function constantRandom(value: number): () => number {
- return () => value;
-}
-
-function welcomeTexts(state: WelcomeRotationState): ReadonlyArray<string> {
- return state.order.map((index) => WELCOME_ROTATION[index]?.text ?? '');
-}
-
-function firstWelcomeIndexForCode(code: string): number {
- return WELCOME_ROTATION.findIndex((entry) => entry.code === code);
-}
-
-describe('setup wizard welcome rotation', () => {
- it('starts with the selected locale welcome text', () => {
- const state = createWelcomeRotationState('sv-SE', constantRandom(0));
- const firstText = WELCOME_ROTATION[state.order[0] ?? 0]?.text;
-
- expect(firstText).toBe('Välkommen');
- });
-
- it('shows each rendered welcome text once per locale-seeded pass', () => {
- for (const code of ['en-US', 'en-GB', 'es-419', 'da', 'no']) {
- const texts = welcomeTexts(createWelcomeRotationState(code, constantRandom(0)));
-
- expect(new Set(texts).size).toBe(texts.length);
- }
- });
-
- it('shows each rendered welcome text once per random pass', () => {
- const previousIndex = firstWelcomeIndexForCode('en-US');
- const texts = welcomeTexts(createRandomWelcomeRotationState(previousIndex, constantRandom(0)));
-
- expect(new Set(texts).size).toBe(texts.length);
- });
-
- it('does not restart a random pass with the previous rendered welcome text', () => {
- const previousIndex = firstWelcomeIndexForCode('en-US');
- const state = createRandomWelcomeRotationState(previousIndex, constantRandom(0));
- const previousText = WELCOME_ROTATION[previousIndex]?.text;
- const nextText = WELCOME_ROTATION[state.order[0] ?? 0]?.text;
-
- expect(nextText).not.toBe(previousText);
- });
-});
diff --git a/fluxer_app/src/features/app/components/shared/custom_status_display/CustomStatusDisplay.test.tsx b/fluxer_app/src/features/app/components/shared/custom_status_display/CustomStatusDisplay.test.tsx
deleted file mode 100644
index d6c1c7a60..000000000
--- a/fluxer_app/src/features/app/components/shared/custom_status_display/CustomStatusDisplay.test.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {act, createElement, type ReactNode} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/expressions/utils/CustomEmojiImageUrl', () => ({
- buildCustomEmojiURL: ({id, animated}: {id: string; animated: boolean}) =>
- `https://cdn.test/emojis/${id}.${animated ? 'gif' : 'png'}`,
-}));
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: () => 'https://cdn.test/twemoji.svg'}));
-vi.mock('@app/features/expressions/utils/UnicodeEmojis', () => ({
- default: {
- normalizeEmojiNameToSurrogate: (value: string) => value,
- nameForSurrogate: (_surrogate: string, _colons: boolean, fallback: string) => fallback,
- },
-}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getEmojiById: () => null}}));
-vi.mock('@app/features/ui/state/MobileLayout', () => ({default: {enabled: false}}));
-vi.mock('@app/features/app/hooks/useShouldAnimate', () => ({useShouldAnimate: () => true}));
-vi.mock('@app/features/presence/hooks/usePresenceCustomStatus', () => ({usePresenceCustomStatus: () => null}));
-vi.mock('@app/features/ui/hooks/useTextOverflow', () => ({useTextOverflow: () => false}));
-vi.mock('@app/features/theme/layout/RemFromPx', () => ({remFromPx: (value: number) => value}));
-vi.mock('@app/features/ui/focus_ring/FocusRing', () => ({
- default: ({children}: {children?: ReactNode}) => children,
-}));
-vi.mock('@lingui/react/macro', () => ({Trans: ({children}: {children?: ReactNode}) => children}));
-vi.mock('@phosphor-icons/react', () => ({
- PencilIcon: () => createElement('span'),
- SmileyIcon: () => createElement('span'),
-}));
-vi.mock('@app/features/ui/tooltip/Tooltip', () => ({
- Tooltip: ({text, children}: {text?: unknown; children?: ReactNode}) =>
- createElement('div', {'data-simple-tooltip': String(text ?? '')}, children),
-}));
-
-const {CustomStatusDisplay} = await import(
- '@app/features/app/components/shared/custom_status_display/CustomStatusDisplay'
-);
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const STATUS = {text: null, expiresAt: null, emojiId: '4001', emojiName: 'partyblob', emojiAnimated: false};
-
-let container: HTMLDivElement;
-let root: Root;
-
-beforeEach(() => {
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => root.unmount());
- container.remove();
-});
-
-function render(): void {
- act(() => {
- root.render(createElement(CustomStatusDisplay, {customStatus: STATUS, showTooltip: true}));
- });
-}
-
-describe('CustomStatusDisplay status emoji tooltip', () => {
- it('renders the emoji name tooltip', () => {
- render();
-
- expect(container.querySelector('[data-simple-tooltip=":partyblob:"]')).not.toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/app/hooks/HoverStateMachine.test.ts b/fluxer_app/src/features/app/hooks/HoverStateMachine.test.ts
deleted file mode 100644
index ec619c35e..000000000
--- a/fluxer_app/src/features/app/hooks/HoverStateMachine.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createHoverStateSnapshot,
- getHoverStateValue,
- selectIsHovering,
- transitionHoverStateSnapshot,
-} from '@app/features/app/hooks/HoverStateMachine';
-import {describe, expect, it} from 'vitest';
-
-describe('HoverStateMachine', () => {
- it('transitions between idle and hovering', () => {
- let snapshot = createHoverStateSnapshot();
- expect(getHoverStateValue(snapshot)).toBe('idle');
- expect(selectIsHovering(snapshot)).toBe(false);
-
- snapshot = transitionHoverStateSnapshot(snapshot, {type: 'hover.enter'});
- expect(getHoverStateValue(snapshot)).toBe('hovering');
- expect(selectIsHovering(snapshot)).toBe(true);
-
- snapshot = transitionHoverStateSnapshot(snapshot, {type: 'hover.leave'});
- expect(getHoverStateValue(snapshot)).toBe('idle');
- expect(selectIsHovering(snapshot)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/app/hooks/useAntiShiftFloating.test.tsx b/fluxer_app/src/features/app/hooks/useAntiShiftFloating.test.tsx
deleted file mode 100644
index c30baedeb..000000000
--- a/fluxer_app/src/features/app/hooks/useAntiShiftFloating.test.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {useAntiShiftFloating} from '@app/features/app/hooks/useAntiShiftFloating';
-import {act, createElement, useLayoutEffect, useState} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-let host: HTMLDivElement;
-let root: Root;
-let target: HTMLDivElement;
-
-function PortalLikeFloating({onReady}: {onReady: (isReady: boolean) => void}) {
- const {setFloating, state} = useAntiShiftFloating(target, true, {placement: 'top'});
- const [mounted, setMounted] = useState(false);
- useLayoutEffect(() => {
- setMounted(true);
- }, []);
- onReady(state.isReady);
- return mounted ? createElement('div', {ref: setFloating, 'data-testid': 'floating'}) : null;
-}
-
-async function settle(): Promise<void> {
- for (let attempt = 0; attempt < 20; attempt += 1) {
- await act(async () => {
- await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
- await Promise.resolve();
- });
- }
-}
-
-beforeEach(() => {
- host = document.createElement('div');
- target = document.createElement('div');
- document.body.append(host, target);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
-});
-
-describe('useAntiShiftFloating', () => {
- it('positions a floating element that mounts after the first commit', async () => {
- const readyStates: Array<boolean> = [];
- act(() => {
- root.render(createElement(PortalLikeFloating, {onReady: (isReady) => readyStates.push(isReady)}));
- });
- await settle();
- expect(readyStates.at(-1)).toBe(true);
- expect(host.querySelector<HTMLElement>('[data-testid="floating"]')?.style.visibility).toBe('visible');
- });
-});
diff --git a/fluxer_app/src/features/app/keybindings/KeybindManager.test.ts b/fluxer_app/src/features/app/keybindings/KeybindManager.test.ts
deleted file mode 100644
index 172688b07..000000000
--- a/fluxer_app/src/features/app/keybindings/KeybindManager.test.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- keyboardEventCanRecoverStaleMacMetaPress,
- keyboardEventMatchesCombo,
- keyboardEventReleasesComboModifier,
- keyboardEventStartsComboPress,
- keyboardEventTriggerMatchesCombo,
- shouldAllowLocalShortcutForChannelTextarea,
-} from '@app/features/app/keybindings/KeybindEventUtils';
-import {
- isKeybindAllowedDuringVoiceCallFullscreen,
- isKeybindBlockedByCompactVoiceCallView,
-} from '@app/features/app/keybindings/KeybindScopeUtils';
-import {comboToCombokeysStrings} from '@app/features/app/keybindings/utils/ComboShortcutStrings';
-import {keyNameForGlobalHook, physicalKeyNameForGlobalHook} from '@app/features/app/keybindings/utils/GlobalHookKeys';
-import {hookShortcutIdForKeybind} from '@app/features/app/keybindings/utils/HookShortcutIds';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it} from 'vitest';
-
-const keyEvent = (
- overrides: Partial<{
- key: string;
- code: string;
- ctrlKey: boolean;
- altKey: boolean;
- shiftKey: boolean;
- metaKey: boolean;
- repeat: boolean;
- }>,
-) => ({
- key: '',
- code: '',
- ctrlKey: false,
- altKey: false,
- shiftKey: false,
- metaKey: false,
- repeat: false,
- ...overrides,
-});
-const runtimeKeybind = (combo: {key: string; code?: string; ctrlOrMeta?: boolean; shift?: boolean; global?: boolean}) =>
- ({
- action: 'voice_toggle_mute',
- combo,
- }) as const;
-
-describe('KeybindManager editable shortcut matching', () => {
- it('matches Ctrl+Shift+U exactly for the upload shortcut on non-mac platforms', () => {
- expect(
- keyboardEventMatchesCombo(
- {key: 'u', ctrlOrMeta: true, shift: true},
- keyEvent({key: 'U', code: 'KeyU', ctrlKey: true, shiftKey: true}),
- {isMacOS: false},
- ),
- ).toBe(true);
- });
- it('treats Command keyup as releasing a macOS ctrlOrMeta shortcut latch', () => {
- expect(
- keyboardEventReleasesComboModifier({key: 'g', ctrlOrMeta: true}, keyEvent({key: 'Meta', code: 'MetaLeft'}), {
- isMacOS: true,
- }),
- ).toBe(true);
- expect(
- keyboardEventReleasesComboModifier({key: 'g', ctrlOrMeta: true}, keyEvent({key: 'Meta', code: 'MetaLeft'}), {
- isMacOS: false,
- }),
- ).toBe(false);
- });
- it('treats a fresh Command+G keydown as a shortcut start while Command remains held', () => {
- expect(
- keyboardEventStartsComboPress({key: 'g', ctrlOrMeta: true}, keyEvent({key: 'g', code: 'KeyG', metaKey: true}), {
- isMacOS: true,
- }),
- ).toBe(true);
- expect(
- keyboardEventStartsComboPress(
- {key: 'g', ctrlOrMeta: true},
- keyEvent({key: 'g', code: 'KeyG', metaKey: true, repeat: true}),
- {isMacOS: true},
- ),
- ).toBe(false);
- });
- it('only allows stale press recovery for macOS Command shortcuts', () => {
- expect(
- keyboardEventCanRecoverStaleMacMetaPress(
- {key: 'g', ctrlOrMeta: true},
- keyEvent({key: 'g', code: 'KeyG', metaKey: true}),
- {isMacOS: true},
- ),
- ).toBe(true);
- expect(
- keyboardEventCanRecoverStaleMacMetaPress(
- {key: 'd', ctrlOrMeta: true, shift: true},
- keyEvent({key: 'd', code: 'KeyD', ctrlKey: true, shiftKey: true}),
- {isMacOS: false},
- ),
- ).toBe(false);
- expect(
- keyboardEventCanRecoverStaleMacMetaPress(
- {key: 'd', ctrlOrMeta: true, shift: true},
- keyEvent({key: 'd', code: 'KeyD', metaKey: true, shiftKey: true, repeat: true}),
- {isMacOS: true},
- ),
- ).toBe(false);
- });
- it('matches repeated trigger-key presses while macOS modifiers stay held', () => {
- const combo = {key: 'd', ctrlOrMeta: true, shift: true};
- const keyDown = keyEvent({key: 'd', code: 'KeyD', metaKey: true, shiftKey: true});
- const keyUp = keyEvent({key: 'd', code: 'KeyD', metaKey: true, shiftKey: true});
- expect(keyboardEventStartsComboPress(combo, keyDown, {isMacOS: true})).toBe(true);
- expect(keyboardEventTriggerMatchesCombo(combo, keyUp)).toBe(true);
- expect(keyboardEventStartsComboPress(combo, keyDown, {isMacOS: true})).toBe(true);
- });
- it('treats Control keyup as releasing a non-mac ctrlOrMeta shortcut latch', () => {
- expect(
- keyboardEventReleasesComboModifier(
- {key: 'g', ctrlOrMeta: true},
- keyEvent({key: 'Control', code: 'ControlLeft'}),
- {isMacOS: false},
- ),
- ).toBe(true);
- expect(
- keyboardEventReleasesComboModifier(
- {key: 'g', ctrlOrMeta: true},
- keyEvent({key: 'Control', code: 'ControlLeft'}),
- {isMacOS: true},
- ),
- ).toBe(false);
- });
- it('does not let extra Shift make Ctrl+U match Ctrl+Shift+U', () => {
- expect(
- keyboardEventMatchesCombo(
- {key: 'u', ctrlOrMeta: true},
- keyEvent({key: 'U', code: 'KeyU', ctrlKey: true, shiftKey: true}),
- {isMacOS: false},
- ),
- ).toBe(false);
- });
- it('allows Shift when a layout needs it to produce a printable punctuation shortcut', () => {
- expect(
- keyboardEventMatchesCombo(
- {key: '/', ctrlOrMeta: true},
- keyEvent({key: '/', code: 'Digit7', metaKey: true, shiftKey: true}),
- {isMacOS: true},
- ),
- ).toBe(true);
- expect(
- keyboardEventMatchesCombo(
- {key: '1', ctrlOrMeta: true},
- keyEvent({key: '!', code: 'Digit1', metaKey: true, shiftKey: true}),
- {isMacOS: true},
- ),
- ).toBe(false);
- });
- it('matches printable shortcuts by layout key before physical code', () => {
- const combo = {key: 'Z', code: 'KeyZ', ctrlOrMeta: true, shift: true};
- expect(
- keyboardEventMatchesCombo(combo, keyEvent({key: 'Z', code: 'KeyY', ctrlKey: true, shiftKey: true}), {
- isMacOS: false,
- }),
- ).toBe(true);
- expect(
- keyboardEventMatchesCombo(combo, keyEvent({key: 'Y', code: 'KeyZ', ctrlKey: true, shiftKey: true}), {
- isMacOS: false,
- }),
- ).toBe(false);
- });
- it('falls back to physical code for Ctrl+Alt printable shortcuts when the layout key is transformed', () => {
- expect(
- keyboardEventMatchesCombo(
- {key: 'v', code: 'KeyV', ctrlOrMeta: true, alt: true},
- keyEvent({key: '@', code: 'KeyV', ctrlKey: true, altKey: true}),
- {isMacOS: false},
- ),
- ).toBe(true);
- expect(
- keyboardEventMatchesCombo(
- {key: 'v', code: 'KeyB', ctrlOrMeta: true, alt: true},
- keyEvent({key: '@', code: 'KeyV', ctrlKey: true, altKey: true}),
- {isMacOS: false},
- ),
- ).toBe(false);
- });
- it('serializes printable global shortcuts with the layout-aware key', () => {
- const combo = {key: 'Z', code: 'KeyY', ctrlOrMeta: true, shift: true, global: true};
- expect(comboToCombokeysStrings(combo)).toEqual(['mod+shift+z']);
- expect(keyNameForGlobalHook(combo)).toBe('Z');
- expect(physicalKeyNameForGlobalHook(combo)).toBe('Y');
- expect(hookShortcutIdForKeybind(runtimeKeybind(combo))).toBe('key:voice_toggle_mute:mod+shift:KeyY:Z');
- });
- it('keeps numpad global hook names code-based', () => {
- expect(keyNameForGlobalHook({key: '1', code: 'Numpad1', ctrlOrMeta: true})).toBe('Numpad1');
- });
- it('maps a CapsLock hold combo to the name the native hooks emit', () => {
- const combo = {key: 'CapsLock', code: 'CapsLock', enabled: true, global: true};
- expect(keyNameForGlobalHook(combo)).toBe('CapsLock');
- expect(physicalKeyNameForGlobalHook(combo)).toBe('CapsLock');
- });
- it('normalizes Pause and Break for global hook registration and matching', () => {
- const combo = {key: 'Pause', code: 'Pause', ctrlOrMeta: true, global: true};
- expect(comboToCombokeysStrings(combo)).toEqual(['mod+pause']);
- expect(keyNameForGlobalHook(combo)).toBe('Pause');
- expect(keyNameForGlobalHook({key: 'Break', code: 'Pause'})).toBe('Pause');
- expect(hookShortcutIdForKeybind(runtimeKeybind(combo))).toBe('key:voice_toggle_mute:mod:Pause:Pause');
- expect(
- keyboardEventMatchesCombo(combo, keyEvent({key: 'Break', code: 'Pause', ctrlKey: true}), {isMacOS: false}),
- ).toBe(true);
- expect(keyboardEventTriggerMatchesCombo(combo, keyEvent({key: 'Break', code: 'Pause'}))).toBe(true);
- });
- it('serializes special numpad, media, and native-only keys for the native global hook', () => {
- expect(keyNameForGlobalHook({key: '0', code: 'Numpad0'})).toBe('Numpad0');
- expect(keyNameForGlobalHook({key: 'AudioVolumeMute', code: 'AudioVolumeMute'})).toBe('AudioVolumeMute');
- expect(keyNameForGlobalHook({key: 'BrowserBack', code: 'BrowserBack'})).toBe('BrowserBack');
- });
- it('allows page-scroll shortcuts from an empty channel textarea only', () => {
- expect(shouldAllowLocalShortcutForChannelTextarea({editableFocusBehavior: 'allow_when_empty'}, '')).toBe(true);
- expect(shouldAllowLocalShortcutForChannelTextarea({editableFocusBehavior: 'allow_when_empty'}, 'draft')).toBe(
- false,
- );
- });
- it('allows explicit editable-focus shortcuts even when the textarea has content', () => {
- expect(shouldAllowLocalShortcutForChannelTextarea({editableFocusBehavior: 'allow'}, 'draft')).toBe(true);
- });
- it('limits fullscreen voice call shortcuts to voice controls', () => {
- expect(isKeybindAllowedDuringVoiceCallFullscreen('voice_toggle_mute')).toBe(true);
- expect(isKeybindAllowedDuringVoiceCallFullscreen('voice_disconnect')).toBe(true);
- expect(isKeybindAllowedDuringVoiceCallFullscreen('voice_toggle_compact_call_view')).toBe(false);
- expect(isKeybindAllowedDuringVoiceCallFullscreen('nav_channel_next')).toBe(false);
- expect(isKeybindAllowedDuringVoiceCallFullscreen('chat_toggle_inbox')).toBe(false);
- });
- it('blocks textarea-scoped shortcuts while compact call chat is hidden', () => {
- expect(
- isKeybindBlockedByCompactVoiceCallView({
- action: 'chat_focus_textarea',
- channelType: ChannelTypes.GUILD_VOICE,
- isPrivateChannel: false,
- isGuildVoiceCallExpanded: true,
- isConnectedToPrivateCall: false,
- isPrivateCompactCallExpanded: false,
- }),
- ).toBe(true);
- expect(
- isKeybindBlockedByCompactVoiceCallView({
- action: 'chat_toggle_emoji',
- channelType: ChannelTypes.GROUP_DM,
- isPrivateChannel: true,
- isGuildVoiceCallExpanded: false,
- isConnectedToPrivateCall: true,
- isPrivateCompactCallExpanded: true,
- }),
- ).toBe(true);
- expect(
- isKeybindBlockedByCompactVoiceCallView({
- action: 'chat_toggle_emoji',
- channelType: ChannelTypes.GROUP_DM,
- isPrivateChannel: true,
- isGuildVoiceCallExpanded: false,
- isConnectedToPrivateCall: true,
- isPrivateCompactCallExpanded: false,
- }),
- ).toBe(false);
- expect(
- isKeybindBlockedByCompactVoiceCallView({
- action: 'voice_toggle_mute',
- channelType: ChannelTypes.GUILD_VOICE,
- isPrivateChannel: false,
- isGuildVoiceCallExpanded: true,
- isConnectedToPrivateCall: false,
- isPrivateCompactCallExpanded: false,
- }),
- ).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.test.ts b/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.test.ts
deleted file mode 100644
index 2a62f461d..000000000
--- a/fluxer_app/src/features/app/keybindings/utils/RuntimeKeybinds.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildCustomRuntimeKeybinds,
- buildDefaultRuntimeKeybinds,
- getCustomActionOverrides,
-} from '@app/features/app/keybindings/utils/RuntimeKeybinds';
-import type {CustomKeybindEntry, KeybindCommand, KeybindConfig, KeyCombo} from '@app/features/input/state/InputKeybind';
-import {describe, expect, it} from 'vitest';
-
-const action: KeybindCommand = 'voice_toggle_deafen';
-const keybind = (combo: KeyCombo): KeybindConfig => ({
- action,
- label: 'Deafen',
- combo,
- section: 'voice_and_video',
-});
-const custom = (combo: KeyCombo, enabled: boolean): CustomKeybindEntry => ({
- id: 'custom-1',
- action,
- combo,
- enabled,
-});
-const resolver =
- (defaults: ReadonlyArray<KeybindConfig>) =>
- (candidate: KeybindCommand): KeybindConfig | null =>
- defaults.find((entry) => entry.action === candidate) ?? null;
-
-describe('runtime keybind resolution', () => {
- it('treats disabled custom bindings as default action overrides', () => {
- const defaults = [keybind({key: 'd', ctrlOrMeta: true, shift: true})];
- const customs = [custom({key: ''}, false)];
- const overriddenActions = getCustomActionOverrides(customs);
- expect(buildDefaultRuntimeKeybinds(defaults, overriddenActions)).toEqual([]);
- expect(buildCustomRuntimeKeybinds(customs, resolver(defaults))).toEqual([]);
- });
- it('builds enabled custom runtime keybinds from the default action metadata', () => {
- const defaults = [keybind({key: 'd', ctrlOrMeta: true, shift: true})];
- const override = custom({key: 'm', ctrlOrMeta: true, global: true}, true);
- expect(buildCustomRuntimeKeybinds([override], resolver(defaults))).toEqual([
- {
- ...defaults[0],
- combo: override.combo,
- },
- ]);
- });
- it('keeps a local-only default local while an enabled custom replacement can be global', () => {
- const defaults = [{...keybind({key: 'd', ctrlOrMeta: true, shift: true, global: false}), allowGlobal: true}];
- const override = custom({key: 'F13', code: 'F13', global: true}, true);
-
- expect(buildDefaultRuntimeKeybinds(defaults, new Set())).toEqual(defaults);
- expect(buildDefaultRuntimeKeybinds(defaults, getCustomActionOverrides([override]))).toEqual([]);
- expect(buildCustomRuntimeKeybinds([override], resolver(defaults))).toEqual([
- {
- ...defaults[0],
- combo: override.combo,
- },
- ]);
- });
-});
diff --git a/fluxer_app/src/features/app/state/GifProviderConfig.test.ts b/fluxer_app/src/features/app/state/GifProviderConfig.test.ts
deleted file mode 100644
index 782be6768..000000000
--- a/fluxer_app/src/features/app/state/GifProviderConfig.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {normalizeGifProviderInfo} from '@app/features/app/state/GifProviderConfig';
-import {describe, expect, it} from 'vitest';
-
-describe('normalizeGifProviderInfo', () => {
- it('uses Klipy as the default GIF provider display name', () => {
- expect(normalizeGifProviderInfo()).toEqual({
- name: 'klipy',
- displayName: 'Klipy',
- attributionRequired: false,
- });
- });
-
- it('uses the canonical Tenor display name for the tenor provider', () => {
- expect(normalizeGifProviderInfo({provider: 'tenor', attributionRequired: false})).toEqual({
- name: 'tenor',
- displayName: 'Tenor',
- attributionRequired: false,
- });
- });
-
- it('falls back unknown provider names to Klipy', () => {
- expect(normalizeGifProviderInfo({name: 'other'})).toEqual({
- name: 'klipy',
- displayName: 'Klipy',
- attributionRequired: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/app/state/Updater.test.ts b/fluxer_app/src/features/app/state/Updater.test.ts
deleted file mode 100644
index 215e2deec..000000000
--- a/fluxer_app/src/features/app/state/Updater.test.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {UpdaterDownloadOption} from '@app/features/platform/types/Electron';
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {UpdaterEvent} from '@app/types/electron.d';
-import {afterEach, describe, expect, test, vi} from 'vitest';
-
-interface ManualUpdatePrompt {
- options: ReadonlyArray<UpdaterDownloadOption>;
- onDownload: (option: UpdaterDownloadOption) => void | Promise<void>;
-}
-
-const {
- pushManualUpdateAvailableModal,
- pushUnsupportedUpdateModal,
- pushUpdateCheckFailedModal,
- pushUpdateReadyModal,
- pushUpToDateModal,
-} = vi.hoisted(() => ({
- pushManualUpdateAvailableModal: vi.fn<(prompt: ManualUpdatePrompt) => void>(),
- pushUnsupportedUpdateModal: vi.fn(),
- pushUpdateCheckFailedModal: vi.fn(),
- pushUpdateReadyModal: vi.fn(),
- pushUpToDateModal: vi.fn(),
-}));
-
-vi.mock('@app/features/updater/commands/UpdaterModalCommands', () => ({
- pushDesktopUpdateDownloadFailedModal: vi.fn(),
- pushDesktopUpdateInstallFailedModal: vi.fn(),
- pushManualUpdateAvailableModal,
- pushUnsupportedUpdateModal,
- pushUpdateAvailableModal: vi.fn(),
- pushUpdateCheckFailedModal,
- pushUpdateReadyModal,
- pushUpToDateModal,
-}));
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: {message: string}) => descriptor,
-}));
-
-vi.mock('@app/features/platform/utils/ClientInfo', () => ({
- getClientInfo: () =>
- Promise.resolve({desktopVersion: '1.0.0', desktopChannel: 'canary', desktopArch: 'x64', arch: 'x64'}),
-}));
-
-installVoiceMenuTestBootstrap();
-
-const REPORTED_VERSION = '2026.908.173325';
-const NEWER_VERSION = '2026.909.202036';
-const CANARY_X64 = 'https://api.canary.fluxer.app/dl/desktop/canary/linux/x64';
-const REPORTED_DEB_DOWNLOAD = [
- `${CANARY_X64}/${REPORTED_VERSION}/deb`,
- `Fluxer-Canary-${REPORTED_VERSION}-linux-amd64.deb`,
-];
-const NEWER_DEB_DOWNLOAD = [`${CANARY_X64}/${NEWER_VERSION}/deb`, `Fluxer-Canary-${NEWER_VERSION}-linux-amd64.deb`];
-
-let nativeEventListener: ((event: UpdaterEvent) => void) | null = null;
-let onUpdaterCheck: ((context: string) => void | Promise<void>) | null = null;
-let loadedUpdater: {dispose: () => void} | null = null;
-
-const updaterCheck = vi.fn((context: string) => Promise.resolve(onUpdaterCheck?.(context)));
-const downloadFile = vi.fn<(url: string, suggestedName: string) => Promise<{success: boolean}>>(() =>
- Promise.resolve({success: true}),
-);
-const openExternal = vi.fn<(url: string) => Promise<void>>(() => Promise.resolve());
-
-function installElectronApi(platform: string): void {
- nativeEventListener = null;
- onUpdaterCheck = null;
- (window as unknown as {electron: unknown}).electron = {
- platform,
- buildChannel: 'canary',
- onUpdaterEvent: (listener: (event: UpdaterEvent) => void) => {
- nativeEventListener = listener;
- return () => {
- nativeEventListener = null;
- };
- },
- updaterCheck,
- updaterDownload: () => Promise.resolve(),
- updaterInstall: () => Promise.resolve(),
- downloadFile,
- openExternal,
- };
-}
-
-function emit(event: UpdaterEvent): void {
- if (!nativeEventListener) throw new Error('Updater never subscribed to native updater events');
- nativeEventListener(event);
-}
-
-async function loadUpdater(platform = 'win32') {
- vi.resetModules();
- installElectronApi(platform);
- const {default: Updater} = await import('@app/features/app/state/Updater');
- loadedUpdater = Updater;
- await vi.waitFor(() => {
- expect(nativeEventListener).not.toBeNull();
- expect(Updater.lastCheckedAt).not.toBeNull();
- });
- vi.clearAllMocks();
- return Updater;
-}
-
-function emitUserDownloadCompletion(version: string): void {
- emit({type: 'available', context: 'user', version, downloadSize: 1000, downloadStarted: true});
- emit({type: 'downloaded', context: 'user', version});
-}
-
-function emitLinuxManualUpdate(context: 'user' | 'background', version: string): void {
- emit({
- type: 'available',
- context,
- version,
- downloadStarted: false,
- downloadUrl: `${CANARY_X64}/latest/appimage`,
- downloadOptions: [
- {
- format: 'deb',
- label: 'DEB package',
- url: `${CANARY_X64}/latest/deb`,
- suggestedName: `Fluxer-Canary-${version}-linux-amd64.deb`,
- sha256: `deb-${version}`,
- },
- ],
- });
-}
-
-async function openLinuxManualUpdatePrompt() {
- const Updater = await loadUpdater('linux');
- emitLinuxManualUpdate('background', REPORTED_VERSION);
- await Updater.applyUpdate();
- const prompt = pushManualUpdateAvailableModal.mock.lastCall?.[0];
- const debOption = prompt?.options.find((option) => option.format === 'deb');
- if (!prompt || !debOption) throw new Error('Manual update prompt never offered a deb package');
- return {Updater, download: () => Promise.resolve(prompt.onDownload(debOption))};
-}
-
-afterEach(() => {
- vi.useRealTimers();
- loadedUpdater?.dispose();
- loadedUpdater = null;
-});
-
-describe('updater update-ready surface', () => {
- test('does not push a blocking modal when a user-initiated download finishes outside a check', async () => {
- const Updater = await loadUpdater();
- emitUserDownloadCompletion('2.0.0');
- expect(Updater.nativeUpdateReady).toBe(true);
- expect(pushUpdateReadyModal).not.toHaveBeenCalled();
- });
-
- test('announces the ready update through a dismissible nagbar instead', async () => {
- const Updater = await loadUpdater();
- expect(Updater.shouldShowUpdateReadyNagbar).toBe(false);
- emitUserDownloadCompletion('2.0.0');
- expect(Updater.shouldShowUpdateReadyNagbar).toBe(true);
- Updater.dismissUpdateReadyNagbar();
- expect(Updater.shouldShowUpdateReadyNagbar).toBe(false);
- emit({type: 'downloaded', context: 'background', version: '2.1.0'});
- expect(Updater.shouldShowUpdateReadyNagbar).toBe(true);
- });
-
- test('still answers a user-initiated check with the update ready modal', async () => {
- const Updater = await loadUpdater();
- emitUserDownloadCompletion('2.0.0');
- pushUpdateReadyModal.mockClear();
- onUpdaterCheck = () => emit({type: 'available', context: 'user', version: '2.0.0', downloadStarted: false});
- await Updater.checkForUpdates(true, true);
- expect(pushUpdateReadyModal).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('updater manual Linux package download', () => {
- test('refreshes the check as the user and saves a newer build under its own name', async () => {
- const {Updater, download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => {
- emit({type: 'checking', context: 'user'});
- emitLinuxManualUpdate('user', NEWER_VERSION);
- };
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([NEWER_DEB_DOWNLOAD]);
- expect(pushManualUpdateAvailableModal).toHaveBeenCalledTimes(1);
- expect(Updater.displayVersion).toBe(NEWER_VERSION);
- expect(Updater.isChecking).toBe(false);
- });
-
- test('saves the build the prompt named when the refresh fails', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => emit({type: 'error', context: 'user', message: 'fetch failed'});
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- expect(pushUpdateCheckFailedModal).not.toHaveBeenCalled();
- });
-
- test('saves the build the prompt named when the refresh finds no update', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => emit({type: 'not-available', context: 'user'});
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- expect(pushUpToDateModal).not.toHaveBeenCalled();
- });
-
- test('saves the build the prompt named when the refresh reports an unsupported install', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => emit({type: 'unsupported', context: 'user', reason: 'managed-package'});
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- expect(pushUnsupportedUpdateModal).not.toHaveBeenCalled();
- });
-
- test('saves the build the prompt named when the refresh does not answer in time', async () => {
- const {Updater, download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => new Promise<void>(() => {});
- vi.useFakeTimers();
- const downloaded = download();
- await vi.advanceTimersByTimeAsync(5_000);
- await downloaded;
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- expect(Updater.isChecking).toBe(false);
- });
-
- test.each([
- ['a newer build', () => emitLinuxManualUpdate('user', NEWER_VERSION)],
- ['no update', () => emit({type: 'not-available', context: 'user'})],
- ['a failure', () => emit({type: 'error', context: 'user', message: 'fetch failed'})],
- ])('stays quiet when a timed out refresh answers with %s after the download', async (_answer, answerLate) => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => new Promise<void>(() => {});
- vi.useFakeTimers();
- const downloaded = download();
- await vi.advanceTimersByTimeAsync(5_000);
- await downloaded;
- answerLate();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- expect(pushManualUpdateAvailableModal).toHaveBeenCalledTimes(1);
- expect(pushUpToDateModal).not.toHaveBeenCalled();
- expect(pushUpdateCheckFailedModal).not.toHaveBeenCalled();
- });
-
- test('saves the refreshed build when a late failure from an earlier refresh lands inside the next one', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => new Promise<void>(() => {});
- vi.useFakeTimers();
- const firstDownload = download();
- await vi.advanceTimersByTimeAsync(5_000);
- await firstDownload;
- onUpdaterCheck = () => {
- emit({type: 'error', context: 'user', message: 'fetch failed'});
- emitLinuxManualUpdate('user', NEWER_VERSION);
- };
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user'], ['user']]);
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD, NEWER_DEB_DOWNLOAD]);
- expect(pushManualUpdateAvailableModal).toHaveBeenCalledTimes(1);
- expect(pushUpdateCheckFailedModal).not.toHaveBeenCalled();
- });
-
- test('still shows the failure of a user check made while a package is being saved', async () => {
- const {Updater, download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => emitLinuxManualUpdate('user', REPORTED_VERSION);
- downloadFile.mockImplementationOnce(() => new Promise<{success: boolean}>(() => {}));
- void download();
- await vi.waitFor(() => expect(downloadFile).toHaveBeenCalledTimes(1));
- onUpdaterCheck = () => emit({type: 'error', context: 'user', message: 'fetch failed'});
- await Updater.checkForUpdates(true, true);
- expect(updaterCheck.mock.calls).toEqual([['user'], ['user']]);
- expect(pushUpdateCheckFailedModal).toHaveBeenCalledTimes(1);
- });
-
- test('does not refresh when a check is already running at the click', async () => {
- const {Updater, download} = await openLinuxManualUpdatePrompt();
- void Updater.checkForUpdates(true);
- await download();
- expect(updaterCheck).not.toHaveBeenCalled();
- expect(downloadFile.mock.calls).toEqual([REPORTED_DEB_DOWNLOAD]);
- });
-
- test('saves one package when the button is pressed twice during the refresh', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- let answerRefresh = () => {};
- onUpdaterCheck = () =>
- new Promise<void>((resolve) => {
- answerRefresh = () => {
- emitLinuxManualUpdate('user', NEWER_VERSION);
- resolve();
- };
- });
- const firstClick = download();
- const secondClick = download();
- answerRefresh();
- await Promise.all([firstClick, secondClick]);
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(downloadFile.mock.calls).toEqual([NEWER_DEB_DOWNLOAD]);
- });
-
- test('opens the pinned link and never the download page when saving fails', async () => {
- const {download} = await openLinuxManualUpdatePrompt();
- onUpdaterCheck = () => emitLinuxManualUpdate('user', REPORTED_VERSION);
- downloadFile.mockResolvedValueOnce({success: false});
- await download();
- expect(updaterCheck.mock.calls).toEqual([['user']]);
- expect(openExternal.mock.calls).toEqual([[`${CANARY_X64}/${REPORTED_VERSION}/deb`]]);
- });
-});
diff --git a/fluxer_app/src/features/app/utils/UpdaterPlatformUtils.test.ts b/fluxer_app/src/features/app/utils/UpdaterPlatformUtils.test.ts
deleted file mode 100644
index 5376d1b9a..000000000
--- a/fluxer_app/src/features/app/utils/UpdaterPlatformUtils.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- shouldShowNativeDesktopUpdateDownloadProgress,
- shouldShowNativeDesktopUpdateInApp,
-} from '@app/features/app/utils/UpdaterPlatformUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('UpdaterPlatformUtils', () => {
- it('surfaces native desktop update availability in-app on Linux, macOS, and Windows', () => {
- expect(shouldShowNativeDesktopUpdateInApp('linux')).toBe(true);
- expect(shouldShowNativeDesktopUpdateInApp('darwin')).toBe(true);
- expect(shouldShowNativeDesktopUpdateInApp('win32')).toBe(true);
- });
- it('does not surface native desktop update availability for unknown renderers', () => {
- expect(shouldShowNativeDesktopUpdateInApp(undefined)).toBe(false);
- expect(shouldShowNativeDesktopUpdateInApp(null)).toBe(false);
- });
- it('only surfaces native desktop download progress on Windows', () => {
- expect(shouldShowNativeDesktopUpdateDownloadProgress('win32')).toBe(true);
- expect(shouldShowNativeDesktopUpdateDownloadProgress('darwin')).toBe(false);
- expect(shouldShowNativeDesktopUpdateDownloadProgress('linux')).toBe(false);
- expect(shouldShowNativeDesktopUpdateDownloadProgress(undefined)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionErrorMessages.test.ts b/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionErrorMessages.test.ts
deleted file mode 100644
index e40c83786..000000000
--- a/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionErrorMessages.test.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {setupI18n} from '@lingui/core';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/app/components/alerts/GenericErrorModalCommands', () => ({showGenericErrorModal: vi.fn()}));
-vi.mock('@app/features/app/components/dialogs/Modal', () => ({}));
-vi.mock('@app/features/app/components/shared/ExternalLink', () => ({ExternalLink: () => null}));
-vi.mock('@app/features/ui/button/Button', () => ({Button: () => null}));
-vi.mock('@app/features/ui/commands/ToastCommands', () => ({showToast: vi.fn()}));
-vi.mock('@app/features/ui/components/form/Form', () => ({Form: () => null}));
-vi.mock('@app/features/ui/components/form/FormInput', () => ({Input: () => null}));
-vi.mock('@app/features/auth/state/SudoPrompt', () => ({isAbortError: () => false}));
-
-const {APIErrorCodes} = await import('@fluxer/constants/src/ApiErrorCodes');
-const {HttpError} = await import('@app/features/platform/types/EndpointError');
-const {resolveRequiredActionErrorMessage} = await import(
- '@app/features/auth/components/modals/required_action/RequiredActionShared'
-);
-const {
- ENTER_VALID_PHONE_DESCRIPTOR,
- PHONE_CANNOT_BE_USED_DESCRIPTOR,
- PHONE_COUNTRY_NOT_SUPPORTED_DESCRIPTOR,
- PHONE_INBOUND_REQUIRED_DESCRIPTOR,
- PHONE_LOOKUP_UNAVAILABLE_DESCRIPTOR,
- PHONE_NEEDS_REVIEW_DESCRIPTOR,
- PHONE_NOT_IN_SERVICE_DESCRIPTOR,
- PHONE_NOT_MOBILE_DESCRIPTOR,
- SOMETHING_WENT_WRONG_TRY_AGAIN_DESCRIPTOR,
- TOO_MANY_ATTEMPTS_DESCRIPTOR,
-} = await import('@app/features/auth/components/modals/required_action/RequiredActionDescriptors');
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-
-function apiError(code: string, body: Record<string, unknown> = {}) {
- return new HttpError({
- method: 'POST',
- path: '/auth/verify-phone',
- status: 400,
- body: {code, message: 'server message', ...body},
- responseHeaders: {},
- });
-}
-
-const PHONE_REJECTION_CASES = [
- [APIErrorCodes.PHONE_COUNTRY_NOT_SUPPORTED, PHONE_COUNTRY_NOT_SUPPORTED_DESCRIPTOR],
- [APIErrorCodes.PHONE_NUMBER_NOT_IN_SERVICE, PHONE_NOT_IN_SERVICE_DESCRIPTOR],
- [APIErrorCodes.PHONE_NUMBER_NOT_MOBILE, PHONE_NOT_MOBILE_DESCRIPTOR],
- [APIErrorCodes.PHONE_LOOKUP_UNAVAILABLE, PHONE_LOOKUP_UNAVAILABLE_DESCRIPTOR],
- [APIErrorCodes.PHONE_INBOUND_VERIFICATION_REQUIRED, PHONE_INBOUND_REQUIRED_DESCRIPTOR],
- [APIErrorCodes.PHONE_VERIFICATION_NEEDS_REVIEW, PHONE_NEEDS_REVIEW_DESCRIPTOR],
-] as const;
-
-describe('resolveRequiredActionErrorMessage', () => {
- for (const [code, descriptor] of PHONE_REJECTION_CASES) {
- for (const context of ['phone-number', 'phone-code'] as const) {
- it(`explains ${code} on the ${context} step`, () => {
- const message = resolveRequiredActionErrorMessage(i18n, apiError(code), context);
- expect(message).toBe(i18n._(descriptor));
- expect(message).not.toBe(i18n._(SOMETHING_WENT_WRONG_TRY_AGAIN_DESCRIPTOR));
- });
- }
- }
-
- it('never blames the number when our own lookup is down', () => {
- const message = resolveRequiredActionErrorMessage(
- i18n,
- apiError(APIErrorCodes.PHONE_LOOKUP_UNAVAILABLE),
- 'phone-number',
- );
- expect(message).not.toContain('invalid');
- expect(message).toContain('try the same number again');
- });
-
- it('keeps the fraud message free of any distinguishing detail', () => {
- const message = resolveRequiredActionErrorMessage(
- i18n,
- apiError(APIErrorCodes.PHONE_VERIFICATION_NEEDS_REVIEW),
- 'phone-number',
- );
- expect(message).toBe(i18n._(PHONE_NEEDS_REVIEW_DESCRIPTOR));
- expect(message).toContain('Contact support');
- });
-
- it('keeps the existing invalid-number copy per step', () => {
- expect(resolveRequiredActionErrorMessage(i18n, apiError(APIErrorCodes.INVALID_PHONE_NUMBER), 'phone-number')).toBe(
- i18n._(ENTER_VALID_PHONE_DESCRIPTOR),
- );
- expect(resolveRequiredActionErrorMessage(i18n, apiError(APIErrorCodes.INVALID_PHONE_NUMBER), 'phone-code')).toBe(
- i18n._(PHONE_CANNOT_BE_USED_DESCRIPTOR),
- );
- });
-
- it('still falls back to the generic message for a code nothing maps', () => {
- expect(resolveRequiredActionErrorMessage(i18n, apiError('SOME_UNMAPPED_CODE'), 'phone-number')).toBe(
- i18n._(SOMETHING_WENT_WRONG_TRY_AGAIN_DESCRIPTOR),
- );
- });
-
- it('lets a rate limit win over a new phone rejection code', () => {
- const message = resolveRequiredActionErrorMessage(
- i18n,
- apiError(APIErrorCodes.PHONE_VERIFICATION_NEEDS_REVIEW, {retry_after: 86400}),
- 'phone-number',
- );
- expect(message).toBe(i18n._(TOO_MANY_ATTEMPTS_DESCRIPTOR));
- });
-});
-
-const PHONE_GATE_CODES = [
- APIErrorCodes.INVALID_PHONE_NUMBER,
- APIErrorCodes.PHONE_COUNTRY_NOT_SUPPORTED,
- APIErrorCodes.PHONE_INBOUND_VERIFICATION_REQUIRED,
- APIErrorCodes.PHONE_LOOKUP_UNAVAILABLE,
- APIErrorCodes.PHONE_NUMBER_NOT_IN_SERVICE,
- APIErrorCodes.PHONE_NUMBER_NOT_MOBILE,
- APIErrorCodes.PHONE_VERIFICATION_NEEDS_REVIEW,
-] as const;
-
-describe('phone gate code coverage', () => {
- for (const context of ['phone-number', 'phone-code'] as const) {
- it(`no phone gate code falls through to the generic message on the ${context} step`, () => {
- const generic = i18n._(SOMETHING_WENT_WRONG_TRY_AGAIN_DESCRIPTOR);
- for (const code of PHONE_GATE_CODES) {
- expect(resolveRequiredActionErrorMessage(i18n, apiError(code), context)).not.toBe(generic);
- }
- });
- }
- it('gives each of the six new codes its own message', () => {
- const messages = PHONE_REJECTION_CASES.map(([code]) =>
- resolveRequiredActionErrorMessage(i18n, apiError(code), 'phone-number'),
- );
- expect(new Set(messages).size).toBe(PHONE_REJECTION_CASES.length);
- });
- it('never tells a user their working number is invalid for a benign rejection', () => {
- const benign = [
- APIErrorCodes.PHONE_COUNTRY_NOT_SUPPORTED,
- APIErrorCodes.PHONE_LOOKUP_UNAVAILABLE,
- APIErrorCodes.PHONE_INBOUND_VERIFICATION_REQUIRED,
- ];
- for (const code of benign) {
- const message = resolveRequiredActionErrorMessage(i18n, apiError(code), 'phone-number');
- expect(message).not.toBe(i18n._(ENTER_VALID_PHONE_DESCRIPTOR));
- expect(message).not.toBe(i18n._(PHONE_CANNOT_BE_USED_DESCRIPTOR));
- }
- });
- it('routes every dead-end rejection somewhere a person can act', () => {
- const routed = [
- APIErrorCodes.PHONE_COUNTRY_NOT_SUPPORTED,
- APIErrorCodes.PHONE_NUMBER_NOT_IN_SERVICE,
- APIErrorCodes.PHONE_NUMBER_NOT_MOBILE,
- APIErrorCodes.PHONE_VERIFICATION_NEEDS_REVIEW,
- ];
- for (const code of routed) {
- expect(resolveRequiredActionErrorMessage(i18n, apiError(code), 'phone-number')).toContain('support');
- }
- });
-});
diff --git a/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionEscapeCopy.test.ts b/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionEscapeCopy.test.ts
deleted file mode 100644
index 8107929e7..000000000
--- a/fluxer_app/src/features/auth/components/modals/required_action/RequiredActionEscapeCopy.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {setupI18n} from '@lingui/core';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-const {buildPhoneGateEscapeConfirmCopy, buildPhoneGateEscapeHint} = await import(
- '@app/features/auth/components/modals/required_action/RequiredActionEscapeCopy'
-);
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-
-function confirmCopy(overrides: Partial<Parameters<typeof buildPhoneGateEscapeConfirmCopy>[1]> = {}) {
- return buildPhoneGateEscapeConfirmCopy(i18n, {
- guildNames: [],
- ownedGuildNames: [],
- emailStepRemains: false,
- ...overrides,
- });
-}
-
-describe('buildPhoneGateEscapeHint', () => {
- it('promises no removal when the user is in no community the check applies to', () => {
- const hint = buildPhoneGateEscapeHint(i18n, 0);
- expect(hint).toContain('nothing is removed');
- expect(hint).not.toContain('leave');
- });
-
- it('counts the communities that will be left', () => {
- expect(buildPhoneGateEscapeHint(i18n, 1)).toContain('1 community');
- expect(buildPhoneGateEscapeHint(i18n, 4)).toContain('4 communities');
- });
-});
-
-describe('buildPhoneGateEscapeConfirmCopy', () => {
- it('never mentions leaving when nothing will be left', () => {
- const copy = confirmCopy();
- expect(copy.title).toBe('Set this check aside?');
- expect(copy.primaryText).toBe('Set this check aside');
- expect(copy.primaryVariant).toBe('primary');
- expect(copy.bodyLines).toHaveLength(2);
- for (const line of copy.bodyLines) {
- expect(line).not.toContain('leave');
- expect(line).not.toContain('join');
- }
- });
-
- it('uses the singular form and the destructive style for a single community', () => {
- const copy = confirmCopy({guildNames: ['Cat Fans']});
- expect(copy.title).toBe('Leave 1 community and set this check aside?');
- expect(copy.primaryText).toBe('Leave and set aside');
- expect(copy.primaryVariant).toBe('danger');
- expect(copy.bodyLines[1]).toContain('You will leave Cat Fans.');
- });
-
- it('names every community that will be left', () => {
- const copy = confirmCopy({guildNames: ['Cat Fans', 'Dog Fans', 'Bird Fans']});
- expect(copy.title).toBe('Leave 3 communities and set this check aside?');
- expect(copy.bodyLines[1]).toContain('You will leave Cat Fans, Dog Fans, and Bird Fans.');
- });
-
- it('explains kept communities without claiming anything is left', () => {
- const copy = confirmCopy({ownedGuildNames: ['My Server']});
- expect(copy.title).toBe('Set this check aside?');
- expect(copy.primaryVariant).toBe('primary');
- expect(copy.bodyLines[1]).toBe('You stay in My Server. Owners cannot leave their own community.');
- });
-
- it('states the leave line before the ownership line', () => {
- const copy = confirmCopy({guildNames: ['Cat Fans'], ownedGuildNames: ['My Server', 'My Other Server']});
- expect(copy.bodyLines[1]).toContain('You will leave Cat Fans.');
- expect(copy.bodyLines[2]).toBe(
- 'You stay in My Server and My Other Server. Owners cannot leave their own community.',
- );
- });
-
- it('warns about the remaining email step before the support line, which is always last', () => {
- const copy = confirmCopy({emailStepRemains: true});
- expect(copy.bodyLines.at(-2)).toBe('You will still need to finish the email step.');
- expect(copy.bodyLines.at(-1)).toBe('You can still email [email protected] for a human review at any time.');
- expect(confirmCopy().bodyLines.at(-1)).toBe(
- 'You can still email [email protected] for a human review at any time.',
- );
- });
-});
diff --git a/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/state/authorizeMachine.test.ts b/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/state/authorizeMachine.test.ts
deleted file mode 100644
index 9dc920ef3..000000000
--- a/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/state/authorizeMachine.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createAuthorizeSnapshot,
- getAuthorizeStateValue,
- selectAuthorizePhase,
- transitionAuthorizeSnapshot,
-} from '@app/features/auth/components/pages/oauth_authorize_page/state/authorizeMachine';
-import {describe, expect, it} from 'vitest';
-
-describe('authorizeMachine', () => {
- it('moves from loading into review and through bot invite success', () => {
- let snapshot = createAuthorizeSnapshot();
- expect(getAuthorizeStateValue(snapshot)).toBe('loading');
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'loading'});
-
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'INIT_OK', step: 'scopes'});
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'review', step: 'scopes'});
-
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'SET_REVIEW_STEP', step: 'permissions'});
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'review', step: 'permissions'});
-
- snapshot = transitionAuthorizeSnapshot(snapshot, {
- type: 'SUBMIT_BOT_INVITE_DONE',
- destinationName: 'Engineering',
- });
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'success', destinationName: 'Engineering'});
- });
-
- it('ignores review-only events outside the review state', () => {
- let snapshot = createAuthorizeSnapshot();
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'SET_REVIEW_STEP', step: 'community'});
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'loading'});
-
- snapshot = transitionAuthorizeSnapshot(snapshot, {
- type: 'SUBMIT_BOT_INVITE_DONE',
- destinationName: 'Engineering',
- });
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'loading'});
- });
-
- it('allows invalid request and session-expired terminal states from any phase', () => {
- let snapshot = createAuthorizeSnapshot();
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'INIT_OK'});
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'INIT_INVALID', message: 'Bad redirect_uri'});
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'invalid_request', message: 'Bad redirect_uri'});
-
- snapshot = transitionAuthorizeSnapshot(snapshot, {type: 'INIT_SESSION_EXPIRED'});
- expect(selectAuthorizePhase(snapshot)).toEqual({kind: 'session_expired'});
- });
-});
diff --git a/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsx b/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsx
deleted file mode 100644
index 66f11eda8..000000000
--- a/fluxer_app/src/features/channel/components/BlockedMessageGroups.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {act, createElement, type ReactNode} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const ChannelStreamType = {
- MESSAGE: 'MESSAGE',
- MESSAGE_GROUP_BLOCKED: 'MESSAGE_GROUP_BLOCKED',
- MESSAGE_GROUP_IGNORED: 'MESSAGE_GROUP_IGNORED',
- MESSAGE_GROUP_SPAMMER: 'MESSAGE_GROUP_SPAMMER',
- DIVIDER: 'DIVIDER',
-} as const;
-
-vi.mock('@app/features/messaging/utils/MessageGroupingUtils', () => ({ChannelStreamType}));
-
-vi.mock('@lingui/core/macro', () => ({msg: (value: unknown) => value}));
-vi.mock('@lingui/react/macro', () => ({useLingui: () => ({i18n: {_: () => 'blocked messages'}})}));
-vi.mock('@app/features/channel/components/ChannelDivider', () => ({
- Divider: ({children}: {children?: ReactNode}) => createElement('div', {'data-divider': true}, children),
-}));
-vi.mock('@app/features/channel/components/MessageGroup', () => ({
- MessageGroup: () => createElement('div', {'data-message-group': true}),
-}));
-
-const {BlockedMessageGroups} = await import('@app/features/channel/components/BlockedMessageGroups');
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const CHANNEL = {id: 'channel-1', guild_id: null} as never;
-const SPACER_SELECTOR = '[data-flx="channel.blocked-message-groups.group-spacer"]';
-
-let container: HTMLDivElement;
-let root: Root;
-let consoleError: ReturnType<typeof vi.spyOn>;
-
-function message(id: string): Record<string, unknown> {
- return {id, author: {id: 'author-1'}, blocked: true};
-}
-
-beforeEach(() => {
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
- consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
-});
-
-afterEach(() => {
- act(() => root.unmount());
- container.remove();
- consoleError.mockRestore();
-});
-
-function renderRevealedGroup(messageGroups: Array<unknown>): void {
- act(() => {
- root.render(
- createElement(BlockedMessageGroups, {
- channel: CHANNEL,
- messageGroups: messageGroups as never,
- onReveal: () => undefined,
- revealed: true,
- compact: false,
- messageGroupSpacing: 8,
- variant: 'blocked',
- }),
- );
- });
-}
-
-function duplicateKeyWarnings(): Array<unknown> {
- return consoleError.mock.calls.filter((call: Array<unknown>) => String(call[0]).includes('same key'));
-}
-
-const DIVIDER_INSIDE_GROUP = [
- {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},
- {type: ChannelStreamType.DIVIDER, content: '', unreadId: '200', contentKey: 'divider-200'},
- {type: ChannelStreamType.MESSAGE, content: message('200'), contentKey: '200', groupId: 'g2'},
-];
-
-describe('BlockedMessageGroups', () => {
- it('keys an unread divider apart from the message group below it', () => {
- renderRevealedGroup(DIVIDER_INSIDE_GROUP);
-
- expect(duplicateKeyWarnings()).toEqual([]);
- expect(container.querySelectorAll('[data-message-group]')).toHaveLength(2);
- });
-
- it('skips a divider that leads the revealed group', () => {
- renderRevealedGroup([
- {type: ChannelStreamType.DIVIDER, content: '', unreadId: '100', contentKey: 'divider-100'},
- {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},
- ]);
-
- expect(duplicateKeyWarnings()).toEqual([]);
- expect(container.querySelectorAll('[data-message-group]')).toHaveLength(1);
- expect(container.querySelectorAll('[data-divider]')).toHaveLength(0);
- });
-
- it('spaces consecutive groups apart inside the revealed block', () => {
- renderRevealedGroup([
- {type: ChannelStreamType.MESSAGE, content: message('100'), contentKey: '100', groupId: 'g1'},
- {type: ChannelStreamType.MESSAGE, content: message('200'), contentKey: '200', groupId: 'g2'},
- {type: ChannelStreamType.MESSAGE, content: message('300'), contentKey: '300', groupId: 'g3'},
- ]);
-
- expect(container.querySelectorAll('[data-message-group]')).toHaveLength(3);
- expect(container.querySelectorAll(SPACER_SELECTOR)).toHaveLength(2);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/ChannelMessageFocusTarget.test.ts b/fluxer_app/src/features/channel/components/ChannelMessageFocusTarget.test.ts
deleted file mode 100644
index de04fa70e..000000000
--- a/fluxer_app/src/features/channel/components/ChannelMessageFocusTarget.test.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type MessageFocusCandidate,
- resolveBottommostFocusableMessageId,
-} from '@app/features/channel/components/ChannelMessageFocusTarget';
-import {describe, expect, it} from 'vitest';
-
-function candidate(messageId: string, top: number, height: number): MessageFocusCandidate {
- return {messageId, top, bottom: top + height, height};
-}
-
-const VIEWPORT_TOP = 0;
-const VIEWPORT_BOTTOM = 600;
-
-describe('resolveBottommostFocusableMessageId', () => {
- it('picks the bottom-most mostly visible message', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('a', 10, 100), candidate('b', 150, 100), candidate('c', 300, 100)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('c');
- });
-
- it('skips a message that is mostly scrolled past the bottom edge', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('a', 10, 100), candidate('b', 150, 100), candidate('c', 550, 100)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('b');
- });
-
- it('falls back to the most visible message when nothing clears the visibility threshold', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('a', -900, 1000), candidate('b', 200, 1000)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('b');
- });
-
- it('prefers the most visible message over the last one in the DOM below the viewport', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('tall', -100, 1000), candidate('offscreen', 2000, 50)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('tall');
- });
-
- it('breaks a tie on visible height by taking the bottom-most message', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('a', -800, 900), candidate('b', 500, 900)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('b');
- });
-
- it('falls back to the last message when nothing overlaps the viewport at all', () => {
- const result = resolveBottommostFocusableMessageId(
- [candidate('a', 900, 100), candidate('b', 1200, 100)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- );
- expect(result).toBe('b');
- });
-
- it('falls back to the last message when the newest one is hidden behind the composer', () => {
- const result = resolveBottommostFocusableMessageId([candidate('only', 400, 400)], VIEWPORT_TOP, VIEWPORT_BOTTOM);
- expect(result).toBe('only');
- });
-
- it('ignores zero-height rows when scoring visibility', () => {
- expect(
- resolveBottommostFocusableMessageId(
- [candidate('a', 10, 100), candidate('b', 200, 0)],
- VIEWPORT_TOP,
- VIEWPORT_BOTTOM,
- ),
- ).toBe('a');
- });
-
- it('returns null when there are no candidates', () => {
- expect(resolveBottommostFocusableMessageId([], VIEWPORT_TOP, VIEWPORT_BOTTOM)).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/channel/components/ChannelMessageStreamUtils.test.ts b/fluxer_app/src/features/channel/components/ChannelMessageStreamUtils.test.ts
deleted file mode 100644
index 0fd5a2f64..000000000
--- a/fluxer_app/src/features/channel/components/ChannelMessageStreamUtils.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getUnreadDividerBeforeMessageId} from '@app/features/channel/components/ChannelMessageStreamUtils';
-import type {Message} from '@app/features/messaging/models/MessagingMessage';
-import type {ChannelStreamItem} from '@app/features/messaging/utils/MessageGroupingUtils';
-import {describe, expect, it} from 'vitest';
-
-function item(messageId: string, showUnreadDividerBefore = false): ChannelStreamItem {
- return {
- type: 'MESSAGE',
- content: {id: messageId} as Message,
- groupId: 'group-1',
- showUnreadDividerBefore,
- };
-}
-
-describe('ChannelMessageStreamUtils', () => {
- it('returns the first pending message with a visible unread divider', () => {
- expect(getUnreadDividerBeforeMessageId([item('a'), item('b', true), item('c', true)])).toBe('b');
- });
-
- it('returns null when unread indicators are suppressed', () => {
- expect(getUnreadDividerBeforeMessageId([item('a', true)], true)).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageAttachmentUtils.test.ts b/fluxer_app/src/features/channel/components/MessageAttachmentUtils.test.ts
deleted file mode 100644
index e0bb8a887..000000000
--- a/fluxer_app/src/features/channel/components/MessageAttachmentUtils.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {splitMediaAndFileAttachments} from '@app/features/channel/components/MessageAttachmentUtils';
-import type {MessageAttachment} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-const baseAttachment = {
- id: 'attachment-1',
- filename: 'file.bin',
- size: 1,
- url: 'https://example.com/file.bin',
- proxy_url: 'https://example.com/file.bin',
- flags: 0,
-} satisfies MessageAttachment;
-
-function attachment(overrides: Partial<MessageAttachment>): MessageAttachment {
- return {
- ...baseAttachment,
- ...overrides,
- };
-}
-
-describe('Message attachment utils', () => {
- it('does not put audio attachments in the mosaic media bucket', () => {
- const audio = attachment({
- id: 'audio-1',
- filename: 'same-channel-message.mp3',
- content_type: 'audio/mpeg',
- width: 0,
- height: 0,
- duration: 1,
- });
- const {mediaAttachments, fileAttachments} = splitMediaAndFileAttachments([audio]);
- expect(mediaAttachments).toEqual([]);
- expect(fileAttachments).toEqual([audio]);
- });
- it('puts positive-dimension visual attachments in the mosaic media bucket', () => {
- const image = attachment({
- id: 'image-1',
- filename: 'image.png',
- content_type: 'image/png',
- width: 640,
- height: 480,
- });
- const video = attachment({
- id: 'video-1',
- filename: 'video.mp4',
- content_type: 'video/mp4',
- width: 1280,
- height: 720,
- });
- const {mediaAttachments, fileAttachments} = splitMediaAndFileAttachments([image, video]);
- expect(mediaAttachments).toEqual([image, video]);
- expect(fileAttachments).toEqual([]);
- });
- it('does not put zero-dimension visual attachments in the mosaic media bucket', () => {
- const image = attachment({
- id: 'image-1',
- filename: 'image.png',
- content_type: 'image/png',
- width: 0,
- height: 0,
- });
- const {mediaAttachments, fileAttachments} = splitMediaAndFileAttachments([image]);
- expect(mediaAttachments).toEqual([]);
- expect(fileAttachments).toEqual([image]);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageAttachments.test.tsx b/fluxer_app/src/features/channel/components/MessageAttachments.test.tsx
deleted file mode 100644
index 6bbfb60fe..000000000
--- a/fluxer_app/src/features/channel/components/MessageAttachments.test.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {MessageViewContextProvider} from '@app/features/channel/components/MessageViewContext';
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type React from 'react';
-import {act, cloneElement, useState} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const matureMedia = vi.hoisted(() => ({blurred: false, canReveal: true, blocked: false}));
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: ({children}: {children?: React.ReactNode}) => <span data-flx="test.trans">{children}</span>,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/messaging/hooks/useMatureMedia', () => ({
- useMatureMedia: () => {
- const [isRevealed, setIsRevealed] = useState(false);
- return {
- shouldBlur: matureMedia.blurred && !isRevealed,
- shouldBlock: matureMedia.blocked,
- canReveal: matureMedia.canReveal,
- gateReason: 'none',
- reveal: () => {
- if (matureMedia.canReveal) setIsRevealed(true);
- },
- };
- },
-}));
-vi.mock('@app/features/ui/popover/PopoverPopout', () => ({
- openPopout: vi.fn(),
- Popout: ({
- children,
- render,
- tooltip,
- shouldOpenOnClick,
- }: {
- children: React.ReactElement<{onClick?: (event: React.MouseEvent<HTMLElement>) => void}>;
- render?: (props: {popoutKey: number; onClose: () => void}) => React.ReactNode;
- tooltip?: string | (() => React.ReactNode);
- shouldOpenOnClick?: (event: React.MouseEvent<HTMLElement>) => boolean;
- }) => {
- const [isOpen, setIsOpen] = useState(false);
- return (
- <span data-test-popout="true" data-flx="test.popout">
- {cloneElement(children, {
- onClick: (event: React.MouseEvent<HTMLElement>) => {
- if (shouldOpenOnClick?.(event) ?? true) setIsOpen(true);
- },
- })}
- <span data-test-popout-tooltip="true" data-flx="test.popout-tooltip">
- {typeof tooltip === 'function' ? tooltip() : tooltip}
- </span>
- {isOpen ? (
- <span data-test-popout-card="true" data-flx="test.popout-card">
- {render?.({popoutKey: 1, onClose: () => setIsOpen(false)})}
- </span>
- ) : null}
- </span>
- );
- },
-}));
-vi.mock('@app/features/expressions/components/ExpressionInfoCard', () => ({
- ExpressionInfoCard: ({displayName}: {displayName: string}) => (
- <span data-test-info-card={displayName} data-flx="test.info-card" />
- ),
-}));
-vi.mock('@app/features/expressions/components/bottomsheets/ExpressionInfoBottomSheet', () => ({
- ExpressionInfoBottomSheet: ({isOpen}: {isOpen: boolean}) => (
- <span data-test-bottom-sheet={String(isOpen)} data-flx="test.bottom-sheet" />
- ),
-}));
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {updatePresence: vi.fn()},
- setLocalPresenceUserSettings: vi.fn(),
- ACCOUNT_PRESENCE_INTENT_MAX_AGE_MS: 60_000,
-}));
-vi.mock('@app/features/ui/commands/ContextMenuCommands', () => ({openFromEvent: vi.fn()}));
-vi.mock('@app/features/ui/action_menu/MessageContextMenu', () => ({MessageContextMenu: () => null}));
-vi.mock('@app/features/ui/action_menu/items/StickerContextMenuItems', () => ({StickerInlineMenuItems: () => null}));
-vi.mock('@app/features/channel/components/MessageReactions', () => ({MessageReactions: () => null}));
-vi.mock('@app/features/channel/components/embeds/ChannelEmbed', () => ({Embed: () => null}));
-vi.mock('@app/features/channel/components/embeds/attachments/Attachment', () => ({Attachment: () => null}));
-vi.mock('@app/features/channel/components/embeds/attachments/AttachmentMosaic', () => ({AttachmentMosaic: () => null}));
-vi.mock('@app/features/channel/components/InviteEmbed', () => ({InviteEmbed: () => null}));
-vi.mock('@app/features/channel/components/GiftEmbed', () => ({GiftEmbed: () => null}));
-vi.mock('@app/features/channel/components/ThemeEmbed', () => ({ThemeEmbed: () => null}));
-vi.mock('@app/features/messaging/components/markdown', () => ({SafeMarkdown: () => null}));
-vi.mock('@app/features/channel/components/TimestampWithTooltip', () => ({TimestampWithTooltip: () => null}));
-vi.mock('@app/features/ui/components/Avatar', () => ({Avatar: () => null}));
-vi.mock('@app/features/app/components/shared/GroupDMAvatar', () => ({GroupDMAvatar: () => null}));
-vi.mock('@app/features/app/components/shared/SpoilerOverlay', () => ({SpoilerOverlay: () => null}));
-vi.mock('@app/features/messaging/utils/MessageNavigator', () => ({goToMessage: vi.fn()}));
-vi.mock('@app/features/messaging/utils/MessageCopyTextUtils', () => ({buildMessageSnapshotCopyText: () => ''}));
-
-installVoiceMenuTestBootstrap();
-
-const {MessageAttachments} = await import('@app/features/channel/components/MessageAttachments');
-
-const STICKER_NAME = 'blobsticker';
-const message = {
- id: '1',
- channelId: '2',
- content: '',
- attachments: [],
- embeds: [],
- invites: [],
- themes: [],
- gifts: [],
- stickers: [{id: '20', name: STICKER_NAME, format_type: 1}],
- messageSnapshots: null,
- suppressEmbeds: false,
-};
-
-let host: HTMLDivElement;
-let root: Root;
-
-function renderMessage(): void {
- act(() => {
- root.render(
- <MessageViewContextProvider
- value={
- {
- channel: {id: '2'},
- message,
- shouldGroup: false,
- isHovering: false,
- messageDisplayCompact: false,
- handleDelete: () => {},
- } as never
- }
- data-flx="test.message-view-context-provider"
- >
- <MessageAttachments data-flx="test.message-attachments" />
- </MessageViewContextProvider>,
- );
- });
-}
-
-function stickerButton(): HTMLButtonElement {
- const button = host.querySelector<HTMLButtonElement>('button[data-message-sticker="true"]');
- if (button == null) throw new Error('sticker trigger is missing');
- return button;
-}
-
-function clickSticker(): void {
- const button = stickerButton();
- act(() => {
- button.dispatchEvent(new MouseEvent('click', {bubbles: true}));
- });
-}
-
-function isBlurred(): boolean {
- return host.querySelector('img')?.className.includes('matureStickerBlurred') === true;
-}
-
-function isCardOpen(): boolean {
- return host.querySelector('[data-test-popout-card]') != null;
-}
-
-function tooltipText(): string {
- return host.querySelector('[data-test-popout-tooltip]')?.textContent ?? '';
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- matureMedia.blurred = false;
- matureMedia.canReveal = true;
- matureMedia.blocked = false;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- host.remove();
-});
-
-describe('message stickers', () => {
- it('renders the sticker as an info card trigger', () => {
- renderMessage();
- expect(host.querySelector('[data-test-popout]')).not.toBeNull();
- expect(stickerButton().getAttribute('aria-label')).toBe(STICKER_NAME);
- expect(isCardOpen()).toBe(false);
- });
-
- it('opens the info card on the first activation when nothing is blurred', () => {
- renderMessage();
- clickSticker();
- expect(isCardOpen()).toBe(true);
- expect(host.querySelector(`[data-test-info-card="${STICKER_NAME}"]`)).not.toBeNull();
- });
-
- it('reveals instead of opening the card while the sticker is blurred', () => {
- matureMedia.blurred = true;
- renderMessage();
- expect(isBlurred()).toBe(true);
- clickSticker();
- expect(isBlurred()).toBe(false);
- expect(isCardOpen()).toBe(false);
- });
-
- it('opens the info card once the blurred sticker has been revealed', () => {
- matureMedia.blurred = true;
- renderMessage();
- clickSticker();
- clickSticker();
- expect(isCardOpen()).toBe(true);
- });
-
- it('neither reveals nor opens the card when the blur cannot be revealed', () => {
- matureMedia.blurred = true;
- matureMedia.canReveal = false;
- renderMessage();
- clickSticker();
- expect(isBlurred()).toBe(true);
- expect(isCardOpen()).toBe(false);
- });
-
- it('hides the card hint from the hover tooltip while the sticker is blurred', () => {
- matureMedia.blurred = true;
- renderMessage();
- expect(tooltipText()).toBe(STICKER_NAME);
- clickSticker();
- expect(tooltipText()).toContain(STICKER_NAME);
- expect(tooltipText()).toContain('Click to learn more');
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageFocusRingContract.test.ts b/fluxer_app/src/features/channel/components/MessageFocusRingContract.test.ts
deleted file mode 100644
index ef340b1fa..000000000
--- a/fluxer_app/src/features/channel/components/MessageFocusRingContract.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {fileURLToPath} from 'node:url';
-import {describe, expect, it} from 'vitest';
-
-function readSource(relativePath: string): string {
- return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8');
-}
-
-const messageCss = readSource('../../theme/styles/Message.module.css');
-const actionBarCss = readSource('./MessageActionBar.module.css');
-const focusRingCss = readSource('../../ui/focus_ring/FocusRing.module.css');
-const channelMessageSource = readSource('./ChannelMessage.tsx');
-const channelMessagesSource = readSource('./ChannelMessages.tsx');
-const messageFocusRing = channelMessageSource.match(/<FocusRing\b[^>]*>/)?.[0] ?? '';
-
-interface CssRule {
- readonly selector: string;
- readonly body: string;
-}
-
-function parseCssRules(css: string): Array<CssRule> {
- const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const rules: Array<CssRule> = [];
- for (const match of withoutComments.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
- rules.push({selector: match[1].replace(/\s+/g, ' ').trim(), body: match[2].trim()});
- }
- return rules;
-}
-
-const messageRules = parseCssRules(messageCss);
-
-describe('message focus ring contract', () => {
- it('never draws a ring from a bare :focus selector on a message row', () => {
- expect(messageCss).not.toMatch(/\.message(Compact)?:focus(?!-visible)/);
- });
-
- it('routes the row ring through the FocusRing framework', () => {
- expect(channelMessageSource).toMatch(/from '@app\/features\/ui\/focus_ring\/FocusRing'/);
- expect(messageFocusRing).not.toBe('');
- });
-
- it('only enables the ring in keyboard navigation mode', () => {
- expect(messageFocusRing).toMatch(/enabled=\{keyboardModeEnabled\}/);
- });
-
- it('leaves focused descendants their own rings instead of drawing the row ring over them', () => {
- expect(messageFocusRing).not.toMatch(/\bwithin\b/);
- });
-
- it('scopes message list rings inside the scroll content', () => {
- const scopedList = channelMessagesSource.match(
- /<FocusRingScope containerRef=\{scrollerInnerRef\}[^>]*>\s*<NearViewportSurfaceContext\.Provider[\s\S]*?\{scrollerInner\}[\s\S]*?<\/FocusRingScope>/,
- );
- expect(scopedList).not.toBeNull();
- });
-
- it('insets the ring inside the row', () => {
- expect(focusRingCss).toMatch(/pointer-events:\s*none/);
- expect(messageFocusRing).toMatch(/offset=\{-2\}/);
- });
-
- it('stacks the ring below the action bar', () => {
- expect(actionBarCss).toMatch(/z-index:\s*var\(--z-index-elevated-1\)/);
- expect(messageFocusRing).not.toMatch(/zIndex=/);
- });
-
- it('measures the ring from an anchor inset by the row bleed', () => {
- expect(messageFocusRing).toMatch(/ringTarget=\{focusRingAnchorRef\}/);
- expect(channelMessageSource).toMatch(/className=\{styles\.focusRingAnchor\}/);
- const anchor = messageRules.find((rule) => rule.selector === '.focusRingAnchor');
- expect(anchor).toBeDefined();
- expect(anchor?.body).toMatch(/position:\s*absolute/);
- expect(anchor?.body).toMatch(/inset-inline:\s*var\(--message-inline-bleed/);
- expect(anchor?.body).toMatch(/pointer-events:\s*none/);
- });
-
- it('derives every message row bleed from the shared bleed variable', () => {
- const bleedingRows = messageRules.filter(
- (rule) => /^\.message(Compact|Preview)?$/.test(rule.selector) && /margin-inline\s*:/.test(rule.body),
- );
- expect(bleedingRows.length).toBeGreaterThan(0);
- for (const rule of bleedingRows) {
- const margin = rule.body.match(/margin-inline:\s*([^;]+)/)?.[1]?.trim();
- expect(margin).toBeDefined();
- expect(margin === '0' || margin === 'calc(-1 * var(--message-inline-bleed))').toBe(true);
- }
- });
-
- it('falls back to a system outline under forced colors', () => {
- const forcedColors = focusRingCss.match(/@media \(forced-colors: active\) \{\n\t\.focusRing \{([^{}]*)\}/)?.[1];
- expect(forcedColors).toBeDefined();
- expect(forcedColors).toMatch(/box-shadow:\s*none/);
- expect(forcedColors).toMatch(/outline-color:\s*Highlight/);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.ts b/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.ts
deleted file mode 100644
index 6850589d4..000000000
--- a/fluxer_app/src/features/channel/components/MessageHoverStyleContract.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {fileURLToPath} from 'node:url';
-import {describe, expect, it} from 'vitest';
-
-interface CssRule {
- readonly selector: string;
- readonly body: string;
-}
-
-function readSource(relativePath: string): string {
- return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), 'utf8');
-}
-
-function parseCssRules(css: string): Array<CssRule> {
- const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const rules: Array<CssRule> = [];
- for (const match of withoutComments.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
- rules.push({selector: match[1].replace(/\s+/g, ''), body: match[2].trim()});
- }
- return rules;
-}
-
-const actionBarCss = readSource('./MessageActionBar.module.css');
-const messageCss = readSource('../../theme/styles/Message.module.css');
-const channelMessageSource = readSource('./ChannelMessage.tsx');
-const hoverStateSource = readSource('./MessageHoverState.ts');
-
-const actionBarContainerRules = parseCssRules(actionBarCss).filter((rule) =>
- rule.selector.includes('.actionBarContainer'),
-);
-const revealingRules = actionBarContainerRules.filter((rule) => /visibility:\s*visible/.test(rule.body));
-
-describe('message hover style contract', () => {
- it('reveals the action bar from the tracked hover state', () => {
- const hoverRevealRules = revealingRules.filter((rule) => !rule.selector.includes(':focus-visible'));
- expect(hoverRevealRules.length).toBeGreaterThan(0);
- for (const rule of hoverRevealRules) {
- expect(rule.selector).not.toMatch(/:hover/);
- expect(rule.selector).toMatch(/data-flx-action-bar-active/);
- }
- });
-
- it('paints the row highlight from the class React drives', () => {
- const highlightRules = parseCssRules(messageCss).filter(
- (rule) =>
- rule.selector.includes('.messageHovered') &&
- !rule.selector.includes(':hover') &&
- /(background-color|opacity):/.test(rule.body),
- );
- expect(highlightRules.length).toBeGreaterThan(0);
- });
-
- it('derives the row highlight and the action bar from the same hover state', () => {
- const highlightSource = channelMessageSource.match(/(\w+) && !isPreview && styles\.messageHovered/)?.[1];
- const actionBarSourceState = channelMessageSource.match(/const isActionBarActive = (\w+) \|\|/)?.[1];
- expect(highlightSource).toBeDefined();
- expect(actionBarSourceState).toBe(highlightSource);
- expect(channelMessageSource).toMatch(
- /data-flx-action-bar-active=\{shouldShowActionBar && isActionBarActive \? 'true' : undefined\}/,
- );
- });
-
- it('resolves the tracked hover state without the :hover chain', () => {
- expect(readSource('./MessageHoverTracking.ts')).not.toMatch(/matches\(':hover'\)/);
- expect(hoverStateSource).not.toMatch(/matches\(':hover'\)/);
- expect(hoverStateSource).toMatch(/registerMessageHoverTarget\(element, setDesktopHoverState\)/);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageHoverTracking.test.ts b/fluxer_app/src/features/channel/components/MessageHoverTracking.test.ts
deleted file mode 100644
index 2d23928db..000000000
--- a/fluxer_app/src/features/channel/components/MessageHoverTracking.test.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- refreshMessageHoverTargets,
- registerMessageHoverTarget,
- resetMessageHoverTrackingForTests,
-} from '@app/features/channel/components/MessageHoverTracking';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-let hitTarget: Element | null = null;
-let elementFromPointSpy: ReturnType<typeof vi.spyOn>;
-let matchesSpy: ReturnType<typeof vi.spyOn>;
-
-function nextFrame(): Promise<void> {
- return new Promise((resolve) => {
- requestAnimationFrame(() => resolve());
- });
-}
-
-function createRow(): {row: HTMLElement; content: HTMLElement} {
- const row = document.createElement('div');
- const content = document.createElement('span');
- row.append(content);
- document.body.append(row);
- return {row, content};
-}
-
-function movePointerTo(target: Element | null, x = 10, y = 10): void {
- hitTarget = target;
- window.dispatchEvent(new MouseEvent('pointermove', {clientX: x, clientY: y, bubbles: true}));
-}
-
-function scrollTo(target: Element | null): void {
- hitTarget = target;
- window.dispatchEvent(new Event('scroll'));
-}
-
-beforeEach(() => {
- hitTarget = null;
- elementFromPointSpy = vi.spyOn(document, 'elementFromPoint').mockImplementation(() => hitTarget);
- matchesSpy = vi.spyOn(Element.prototype, 'matches');
-});
-
-afterEach(() => {
- vi.useRealTimers();
- resetMessageHoverTrackingForTests();
- elementFromPointSpy.mockRestore();
- matchesSpy.mockRestore();
- document.body.replaceChildren();
-});
-
-describe('MessageHoverTracking', () => {
- it('arms the row that owns the element under the pointer', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
- await nextFrame();
- expect(listener).not.toHaveBeenCalled();
-
- movePointerTo(content);
- await nextFrame();
-
- expect(listener).toHaveBeenLastCalledWith(true);
- });
-
- it('keeps at most one row armed when the pointer moves between adjacent rows', async () => {
- const first = createRow();
- const second = createRow();
- const firstListener = vi.fn();
- const secondListener = vi.fn();
- registerMessageHoverTarget(first.row, firstListener);
- registerMessageHoverTarget(second.row, secondListener);
-
- movePointerTo(first.content);
- await nextFrame();
- expect(firstListener).toHaveBeenLastCalledWith(true);
- expect(secondListener).not.toHaveBeenCalled();
-
- movePointerTo(second.content);
- await nextFrame();
- expect(firstListener).toHaveBeenLastCalledWith(false);
- expect(secondListener).toHaveBeenLastCalledWith(true);
- });
-
- it('does not re-arm a row on window refocus when the pointer left during the blur', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- movePointerTo(content);
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(true);
-
- window.dispatchEvent(new Event('blur'));
- expect(listener).toHaveBeenLastCalledWith(false);
-
- window.dispatchEvent(new Event('focus'));
- refreshMessageHoverTargets();
- await nextFrame();
- await nextFrame();
-
- expect(listener).toHaveBeenLastCalledWith(false);
- expect(listener.mock.calls.filter(([isHovered]) => isHovered === true)).toHaveLength(1);
- });
-
- it('never consults the retained :hover chain as a hover oracle', async () => {
- const {row, content} = createRow();
- registerMessageHoverTarget(row, vi.fn());
-
- movePointerTo(content);
- await nextFrame();
- window.dispatchEvent(new Event('blur'));
- window.dispatchEvent(new Event('focus'));
- refreshMessageHoverTargets();
- await nextFrame();
-
- expect(matchesSpy.mock.calls.flat()).not.toContain(':hover');
- });
-
- it('disarms and does not re-arm while rows scroll under a stationary pointer', async () => {
- const first = createRow();
- const second = createRow();
- const firstListener = vi.fn();
- const secondListener = vi.fn();
- registerMessageHoverTarget(first.row, firstListener);
- registerMessageHoverTarget(second.row, secondListener);
-
- movePointerTo(first.content);
- await nextFrame();
- expect(firstListener).toHaveBeenLastCalledWith(true);
-
- scrollTo(second.content);
- await nextFrame();
-
- expect(firstListener).toHaveBeenLastCalledWith(false);
- expect(secondListener).not.toHaveBeenCalled();
- });
-
- it('arms the row under the pointer once scrolling settles', async () => {
- vi.useFakeTimers();
- const first = createRow();
- const second = createRow();
- const firstListener = vi.fn();
- const secondListener = vi.fn();
- registerMessageHoverTarget(first.row, firstListener);
- registerMessageHoverTarget(second.row, secondListener);
-
- hitTarget = first.content;
- window.dispatchEvent(new MouseEvent('pointermove', {clientX: 10, clientY: 10, bubbles: true}));
- await vi.advanceTimersByTimeAsync(20);
- expect(firstListener).toHaveBeenLastCalledWith(true);
-
- scrollTo(second.content);
- await vi.advanceTimersByTimeAsync(20);
- expect(secondListener).not.toHaveBeenCalled();
-
- await vi.advanceTimersByTimeAsync(200);
- expect(secondListener).toHaveBeenLastCalledWith(true);
- });
-
- it('stays suspended for as long as momentum keeps firing scroll events', async () => {
- vi.useFakeTimers();
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- hitTarget = content;
- window.dispatchEvent(new MouseEvent('pointermove', {clientX: 10, clientY: 10, bubbles: true}));
- await vi.advanceTimersByTimeAsync(20);
- expect(listener).toHaveBeenLastCalledWith(true);
-
- scrollTo(content);
- await vi.advanceTimersByTimeAsync(20);
- expect(listener).toHaveBeenLastCalledWith(false);
-
- for (let i = 0; i < 6; i++) {
- await vi.advanceTimersByTimeAsync(100);
- scrollTo(content);
- }
- expect(listener).toHaveBeenLastCalledWith(false);
-
- await vi.advanceTimersByTimeAsync(200);
- expect(listener).toHaveBeenLastCalledWith(true);
- });
-
- it('re-arms immediately when the pointer actually moves during a scroll', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- scrollTo(content);
- await nextFrame();
- expect(listener).not.toHaveBeenCalledWith(true);
-
- movePointerTo(content);
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(true);
- });
-
- it('does not let a scroll-driven pointerover re-arm a row', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- scrollTo(content);
- await nextFrame();
-
- hitTarget = content;
- window.dispatchEvent(new MouseEvent('pointerover', {clientX: 10, clientY: 10, bubbles: true}));
- await nextFrame();
-
- expect(listener).not.toHaveBeenCalledWith(true);
- });
-
- it('re-arms the row underneath after an overlay that covered it is dismissed', async () => {
- const {row, content} = createRow();
- const overlay = document.createElement('div');
- document.body.append(overlay);
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- movePointerTo(content);
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(true);
-
- hitTarget = overlay;
- refreshMessageHoverTargets();
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(false);
-
- overlay.remove();
- hitTarget = content;
- refreshMessageHoverTargets();
- await nextFrame();
-
- expect(listener).toHaveBeenLastCalledWith(true);
- });
-
- it('does not treat a touch contact as hover', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- hitTarget = content;
- window.dispatchEvent(new PointerEvent('pointerdown', {clientX: 10, clientY: 10, pointerType: 'touch'}));
- await nextFrame();
-
- expect(listener).not.toHaveBeenCalledWith(true);
- });
-
- it('disarms when the pointer leaves the window', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- registerMessageHoverTarget(row, listener);
-
- movePointerTo(content);
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(true);
-
- window.dispatchEvent(new MouseEvent('pointerout', {relatedTarget: null}));
-
- expect(listener).toHaveBeenLastCalledWith(false);
- });
-
- it('releases ownership when an armed row unregisters', async () => {
- const {row, content} = createRow();
- const listener = vi.fn();
- const unregister = registerMessageHoverTarget(row, listener);
- const other = createRow();
- const otherListener = vi.fn();
- registerMessageHoverTarget(other.row, otherListener);
-
- movePointerTo(content);
- await nextFrame();
- expect(listener).toHaveBeenLastCalledWith(true);
-
- unregister();
- hitTarget = other.content;
- await nextFrame();
-
- expect(otherListener).toHaveBeenLastCalledWith(true);
- expect(listener).not.toHaveBeenLastCalledWith(true);
- });
-
- it('detaches every global listener once the last row unregisters', () => {
- const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
- const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');
- const {row} = createRow();
-
- const unregister = registerMessageHoverTarget(row, vi.fn());
- const added = addEventListenerSpy.mock.calls.map(([type, listener]) => ({type, listener}));
- unregister();
- const removed = removeEventListenerSpy.mock.calls.map(([type, listener]) => ({type, listener}));
-
- expect(added.length).toBeGreaterThan(0);
- for (const addedListener of added) {
- expect(
- removed.some(
- (removedListener) =>
- removedListener.type === addedListener.type && removedListener.listener === addedListener.listener,
- ),
- ).toBe(true);
- }
-
- addEventListenerSpy.mockRestore();
- removeEventListenerSpy.mockRestore();
- });
-});
diff --git a/fluxer_app/src/features/channel/components/MessageReactions.test.tsx b/fluxer_app/src/features/channel/components/MessageReactions.test.tsx
deleted file mode 100644
index bf90079bc..000000000
--- a/fluxer_app/src/features/channel/components/MessageReactions.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type React from 'react';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, plural: () => '', t: descriptor};
-});
-vi.mock('@lingui/react/macro', () => ({
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/app/components/LongPressable', () => ({
- LongPressable: ({children, onLongPress}: {children?: React.ReactNode; onLongPress?: () => void}) => (
- <div data-flx="test.long-pressable">
- <button type="button" data-test-long-press="true" onClick={onLongPress} data-flx="test.long-press">
- {'press'}
- </button>
- {children}
- </div>
- ),
-}));
-vi.mock('@app/features/expressions/components/bottomsheets/ExpressionInfoBottomSheet', () => ({
- ExpressionInfoBottomSheet: ({isOpen}: {isOpen: boolean}) => (
- <span data-test-expression-sheet={String(isOpen)} data-flx="test.expression-sheet" />
- ),
-}));
-vi.mock('@app/features/ui/state/MobileLayout', () => ({default: {isMobileLayout: () => true, enabled: true}}));
-vi.mock('@app/features/channel/components/MessageActionUtils', () => ({
- createMessageActionHandlers: () => ({handleEmojiSelect: vi.fn()}),
- isClientSystemMessage: () => false,
- useMessagePermissions: () => ({canAddReactions: false, channel: null}),
-}));
-vi.mock('@app/features/messaging/hooks/useMessageReactionStore', () => ({
- useMessageReactions: () => [{emoji: {id: '30', name: 'blob', animated: false}, count: 1, me: false}],
-}));
-vi.mock('@app/features/messaging/hooks/useMatureMedia', () => ({
- useMatureMedia: () => ({shouldBlur: false, shouldBlock: false, canReveal: true, gateReason: 'none', reveal: vi.fn()}),
-}));
-vi.mock('@app/features/messaging/utils/ReactionUtils', () => ({
- getEmojiName: () => ':blob:',
- getReactionKey: () => 'reaction-key',
- useEmojiURL: () => 'https://cdn.test/blob.webp',
-}));
-vi.mock('@app/features/messaging/components/ReactionImage', () => ({ReactionImage: () => null}));
-vi.mock('@app/features/messaging/components/popouts/ReactionTooltip', () => ({
- ReactionTooltip: ({children}: {children?: React.ReactNode}) => (
- <span data-flx="test.reaction-tooltip">{children}</span>
- ),
-}));
-vi.mock('@app/features/emoji/components/popouts/EmojiPickerPopout', () => ({EmojiPickerPopout: () => null}));
-vi.mock('@app/features/expressions/components/modals/ExpressionPickerSheet', () => ({
- ExpressionPickerSheet: () => null,
-}));
-vi.mock('@app/features/ui/popover/PopoverPopout', () => ({Popout: () => null, openPopout: vi.fn()}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getEmojiById: () => null}}));
-vi.mock('@app/features/ui/commands/ContextMenuCommands', () => ({openFromEvent: vi.fn()}));
-vi.mock('@app/features/ui/action_menu/items/EmojiContextMenuItems', () => ({EmojiContextMenuItems: () => null}));
-vi.mock('@app/features/accessibility/state/Accessibility', () => ({default: {useReducedMotion: true}}));
-vi.mock('@app/features/ui/state/KeyboardMode', () => ({default: {keyboardModeEnabled: false}}));
-
-installVoiceMenuTestBootstrap();
-
-const {MessageReactions} = await import('@app/features/channel/components/MessageReactions');
-
-const message = {id: '1', channelId: '2'} as never;
-
-let host: HTMLDivElement;
-let root: Root;
-
-function renderReactions(): void {
- act(() => {
- root.render(<MessageReactions message={message} onPopoutToggle={() => {}} data-flx="test.message-reactions" />);
- });
-}
-
-function longPress(): void {
- const trigger = host.querySelector<HTMLButtonElement>('[data-test-long-press="true"]');
- if (trigger == null) throw new Error('long press trigger is missing');
- act(() => {
- trigger.dispatchEvent(new MouseEvent('click', {bubbles: true}));
- });
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- host.remove();
-});
-
-describe('reaction long press', () => {
- it('opens the expression info sheet', () => {
- renderReactions();
- expect(host.querySelector('[data-test-expression-sheet="true"]')).toBeNull();
- longPress();
- expect(host.querySelector('[data-test-expression-sheet="true"]')).not.toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/channel/components/SearchResultGrouping.test.ts b/fluxer_app/src/features/channel/components/SearchResultGrouping.test.ts
deleted file mode 100644
index d59ceb9f0..000000000
--- a/fluxer_app/src/features/channel/components/SearchResultGrouping.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildSearchResultGroups,
- buildSearchResultGroupsByMessageId,
- countSearchResultChannels,
-} from '@app/features/channel/components/SearchResultGrouping';
-import type {Message} from '@app/features/messaging/models/MessagingMessage';
-import {describe, expect, it} from 'vitest';
-
-const message = (id: string, channelId: string): Message => ({id, channelId}) as Message;
-
-describe('SearchResultGrouping', () => {
- it('keeps the order the server returned instead of bucketing per channel', () => {
- const groups = buildSearchResultGroups([
- message('500', 'general'),
- message('400', 'random'),
- message('300', 'general'),
- ]);
- expect(groups.map((group) => group.messages.map((result) => result.id))).toEqual([['500'], ['400'], ['300']]);
- expect(groups.map((group) => group.channelId)).toEqual(['general', 'random', 'general']);
- });
-
- it('merges consecutive results from the same channel into one group', () => {
- const groups = buildSearchResultGroups([
- message('500', 'general'),
- message('490', 'general'),
- message('400', 'random'),
- ]);
- expect(groups).toHaveLength(2);
- expect(groups[0].messages.map((result) => result.id)).toEqual(['500', '490']);
- expect(groups[1].messages.map((result) => result.id)).toEqual(['400']);
- });
-
- it('gives every group a unique key even when a channel appears more than once', () => {
- const groups = buildSearchResultGroups([
- message('500', 'general'),
- message('400', 'random'),
- message('300', 'general'),
- ]);
- expect(new Set(groups.map((group) => group.key)).size).toBe(3);
- });
-
- it('indexes each message to the group it renders in', () => {
- const groups = buildSearchResultGroups([
- message('500', 'general'),
- message('400', 'random'),
- message('300', 'general'),
- ]);
- const groupsByMessageId = buildSearchResultGroupsByMessageId(groups);
- expect(groupsByMessageId.get('500')).toBe(groups[0]);
- expect(groupsByMessageId.get('400')).toBe(groups[1]);
- expect(groupsByMessageId.get('300')).toBe(groups[2]);
- });
-
- it('counts distinct channels rather than groups', () => {
- const groups = buildSearchResultGroups([
- message('500', 'general'),
- message('400', 'random'),
- message('300', 'general'),
- ]);
- expect(countSearchResultChannels(groups)).toBe(2);
- expect(countSearchResultChannels(buildSearchResultGroups([]))).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/SearchScopeResolution.test.ts b/fluxer_app/src/features/channel/components/SearchScopeResolution.test.ts
deleted file mode 100644
index 2308f5594..000000000
--- a/fluxer_app/src/features/channel/components/SearchScopeResolution.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolveSearchScope} from '@app/features/channel/components/SearchScopeResolution';
-import type {MessageSearchScope} from '@app/features/search/utils/SearchUtils';
-import {describe, expect, it} from 'vitest';
-
-const GUILD_SCOPE_OPTIONS = new Set<MessageSearchScope>([
- 'current',
- 'all_guilds',
- 'all_dms',
- 'open_dms',
- 'all',
- 'open_dms_and_all_guilds',
-]);
-
-describe('resolveSearchScope', () => {
- it('uses an explicit control override before captured active scope', () => {
- expect(
- resolveSearchScope({
- activeScope: 'current',
- fallbackScope: 'current',
- scopeOverride: 'all_guilds',
- scopeOptionValues: GUILD_SCOPE_OPTIONS,
- }),
- ).toBe('all_guilds');
- });
- it('uses a parsed query scope when there is no control override', () => {
- expect(
- resolveSearchScope({
- activeScope: 'current',
- fallbackScope: 'current',
- parsedScope: 'all',
- scopeOptionValues: GUILD_SCOPE_OPTIONS,
- }),
- ).toBe('all');
- });
- it('falls back when the selected scope is not valid for the current channel', () => {
- expect(
- resolveSearchScope({
- activeScope: 'all_guilds',
- fallbackScope: 'current',
- scopeOptionValues: new Set<MessageSearchScope>(['current', 'all_dms', 'open_dms']),
- }),
- ).toBe('current');
- });
-});
diff --git a/fluxer_app/src/features/channel/components/SearchStateMachine.test.ts b/fluxer_app/src/features/channel/components/SearchStateMachine.test.ts
deleted file mode 100644
index 1c0d39e68..000000000
--- a/fluxer_app/src/features/channel/components/SearchStateMachine.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createSearchMachineSnapshot,
- selectSearchMachineState,
- transitionSearchMachineSnapshot,
-} from '@app/features/channel/components/SearchStateMachine';
-import {describe, expect, it} from 'vitest';
-
-describe('SearchStateMachine', () => {
- it('starts idle and transitions through loading to success', () => {
- let snapshot = createSearchMachineSnapshot();
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'idle'});
-
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.loading'});
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'loading'});
-
- snapshot = transitionSearchMachineSnapshot(snapshot, {
- type: 'channelSearch.succeeded',
- results: [],
- channels: [],
- total: 0,
- hitsPerPage: 25,
- page: 1,
- });
- expect(selectSearchMachineState(snapshot)).toEqual({
- status: 'success',
- results: [],
- channels: [],
- total: 0,
- hitsPerPage: 25,
- page: 1,
- });
- });
-
- it('tracks indexing poll attempts in machine context', () => {
- let snapshot = createSearchMachineSnapshot();
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.indexingStarted'});
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'indexing', pollCount: 0});
-
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.indexingPolled'});
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.indexingPolled'});
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'indexing', pollCount: 2});
- });
-
- it('clears retained context on reset', () => {
- let snapshot = createSearchMachineSnapshot();
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.failed', error: 'Search failed'});
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'error', error: 'Search failed'});
-
- snapshot = transitionSearchMachineSnapshot(snapshot, {type: 'channelSearch.reset'});
- expect(selectSearchMachineState(snapshot)).toEqual({status: 'idle'});
- });
-});
diff --git a/fluxer_app/src/features/channel/components/TypingUsers.test.tsx b/fluxer_app/src/features/channel/components/TypingUsers.test.tsx
deleted file mode 100644
index 9dd10e035..000000000
--- a/fluxer_app/src/features/channel/components/TypingUsers.test.tsx
+++ /dev/null
@@ -1,377 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Channel} from '@app/features/channel/models/Channel';
-import messageStyles from '@app/features/theme/styles/Message.module.css';
-import {runInAction} from 'mobx';
-import {act, createElement, Fragment, Profiler, type ReactNode} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = await vi.hoisted(async () => {
- const {observable} = await import('mobx');
- return {
- auth: observable({currentUserId: 'me' as string | null}),
- developerOptions: observable({showMyselfTyping: false}),
- blockedUserIds: observable.set<string>(),
- users: observable.map<string, {id: string; username: string}>(),
- };
-});
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: {message: string}) => descriptor}));
-vi.mock('@lingui/react/macro', async () => {
- const {createElement: create, Fragment: ReactFragment} = await import('react');
- return {
- Trans: ({children}: {children?: ReactNode}) => create(ReactFragment, null, children),
- useLingui: () => ({
- i18n: {
- locale: 'en-US',
- _: (descriptor: {message: string}, values: Record<string, string> = {}) =>
- descriptor.message.replace(/\{(\w+)\}/g, (_placeholder, name: string) => values[name] ?? ''),
- },
- }),
- };
-});
-vi.mock('@app/features/auth/state/Authentication', () => ({default: doubles.auth}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: doubles.developerOptions}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({
- default: {isBlocked: (userId: string) => doubles.blockedUserIds.has(userId)},
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getUser: (userId: string) => doubles.users.get(userId)},
-}));
-vi.mock('@app/features/user/utils/NicknameUtils', () => ({
- getNickname: (user: {username: string}) => user.username,
-}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => undefined}}));
-vi.mock('@app/features/channel/components/ChannelTyping', async () => {
- const {createElement: create} = await import('react');
- return {Typing: () => create('svg')};
-});
-vi.mock('@app/features/ui/avatars/AvatarStack', async () => {
- const {createElement: create} = await import('react');
- return {
- AvatarStack: ({className, users}: {className?: string; users: ReadonlyArray<unknown>}) =>
- create('div', {className, 'data-avatar-count': users.length}),
- };
-});
-
-const {TypingAnnouncer, TypingUsers} = await import('@app/features/channel/components/TypingUsers');
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-class StubResizeObserver {
- static instances: Array<StubResizeObserver> = [];
- readonly targets: Array<Element> = [];
- disconnected = false;
-
- constructor(private readonly callback: () => void) {
- StubResizeObserver.instances.push(this);
- }
-
- observe(target: Element): void {
- this.targets.push(target);
- }
-
- disconnect(): void {
- this.disconnected = true;
- }
-
- trigger(): void {
- this.callback();
- }
-}
-
-const CHANNEL = {id: 'channel', guildId: 'guild'} as unknown as Channel;
-const TYPIST_IDS = ['alice', 'bob', 'carol', 'dave', 'erin'];
-
-let host: HTMLDivElement;
-let root: Root;
-let overflowContainer: HTMLElement;
-let overflowContainerRef: {current: HTMLElement | null};
-
-function setWidth(element: Element, property: 'clientWidth' | 'scrollWidth', width: number): void {
- Object.defineProperty(element, property, {configurable: true, value: width});
-}
-
-function render(node: ReactNode): void {
- act(() => {
- root.render(node);
- });
-}
-
-function renderRow(props: {showAvatars?: boolean} = {}): void {
- render(
- createElement(
- Fragment,
- null,
- createElement(TypingUsers, {channel: CHANNEL, overflowContainerRef, showAvatars: props.showAvatars}),
- createElement(TypingAnnouncer, {channel: CHANNEL}),
- ),
- );
-}
-
-function startTyping(...userIds: Array<string>): void {
- act(() => {
- for (const userId of userIds) {
- RollingTypingStore.start(CHANNEL.id, userId, userId === 'me' ? 'local' : 'gateway');
- }
- });
-}
-
-function query(flx: string): HTMLElement | null {
- return host.querySelector<HTMLElement>(`[data-flx="${flx}"]`);
-}
-
-function visibleText(): string | null {
- return query('channel.typing-users.span')?.textContent ?? null;
-}
-
-function announcer(): HTMLElement {
- return query('channel.typing-users.announcer')!;
-}
-
-function measure(): HTMLElement | null {
- return query('channel.typing-users.measure');
-}
-
-function activeResizeObservers(): Array<StubResizeObserver> {
- return StubResizeObserver.instances.filter((instance) => !instance.disconnected);
-}
-
-function remeasure(): void {
- act(() => {
- for (const instance of activeResizeObservers()) {
- instance.trigger();
- }
- });
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- StubResizeObserver.instances = [];
- vi.stubGlobal('ResizeObserver', StubResizeObserver);
- host = document.createElement('div');
- overflowContainer = document.createElement('div');
- document.body.append(overflowContainer, host);
- setWidth(overflowContainer, 'clientWidth', 1000);
- overflowContainerRef = {current: overflowContainer};
- root = createRoot(host);
- runInAction(() => {
- doubles.auth.currentUserId = 'me';
- doubles.developerOptions.showMyselfTyping = false;
- doubles.blockedUserIds.clear();
- doubles.users.clear();
- for (const id of ['me', ...TYPIST_IDS]) {
- doubles.users.set(id, {id, username: id});
- }
- });
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- RollingTypingStore.reset();
- document.body.replaceChildren();
- vi.unstubAllGlobals();
-});
-
-describe('TypingUsers', () => {
- it('hides the current user from the typing row', () => {
- renderRow();
- startTyping('me', 'alice');
-
- expect(visibleText()).toBe('alice is typing...');
- expect(host.querySelector('[data-avatar-count]')?.getAttribute('data-avatar-count')).toBe('1');
- });
-
- it('shows the current user when the developer option is on', () => {
- runInAction(() => {
- doubles.developerOptions.showMyselfTyping = true;
- });
- renderRow();
- startTyping('me', 'alice');
-
- expect(visibleText()).toBe('me and alice are typing...');
- });
-
- it('hides blocked users from the typing row', () => {
- runInAction(() => {
- doubles.blockedUserIds.add('bob');
- });
- renderRow();
- startTyping('bob', 'alice');
-
- expect(visibleText()).toBe('alice is typing...');
- });
-
- it('skips typists missing from the user cache', () => {
- renderRow();
- startTyping('stranger', 'alice');
-
- expect(RollingTypingStore.countTypists(CHANNEL.id)).toBe(2);
- expect(visibleText()).toBe('alice is typing...');
- });
-
- it('renders nothing visible when only self is typing', () => {
- renderRow();
- startTyping('me');
-
- expect(query('channel.typing-users.div')).toBeNull();
- expect(announcer().textContent).toBe('');
- });
-
- it('marks the visible text as hidden from assistive technology', () => {
- renderRow();
- startTyping('alice');
-
- const visible = query('channel.typing-users.span')!;
- expect(visible.getAttribute('aria-hidden')).toBe('true');
- expect(visible.hasAttribute('aria-live')).toBe(false);
- expect(measure()?.getAttribute('aria-hidden')).toBe('true');
- });
-
- it('keeps the announcer mounted when nobody is typing', () => {
- renderRow();
- const mounted = announcer();
- expect(mounted.textContent).toBe('');
-
- startTyping('alice');
- expect(announcer()).toBe(mounted);
- expect(mounted.textContent).toBe('alice is typing...');
-
- act(() => {
- RollingTypingStore.remove(CHANNEL.id, 'alice');
- });
- expect(announcer()).toBe(mounted);
- expect(mounted.textContent).toBe('');
- });
-
- it('announces through a polite atomic live region', () => {
- renderRow();
- startTyping('alice', 'bob', 'carol', 'dave');
-
- expect(announcer().getAttribute('aria-live')).toBe('polite');
- expect(announcer().getAttribute('aria-atomic')).toBe('true');
- expect(announcer().textContent).toBe('Several people are typing...');
- });
-
- it('swaps to multiple people when the measured text plus 48 px exceeds the available width', () => {
- setWidth(overflowContainer, 'clientWidth', 300);
- renderRow({showAvatars: false});
- startTyping('alice', 'bob');
- expect(visibleText()).toBe('alice and bob are typing...');
-
- setWidth(measure()!, 'scrollWidth', 253);
- remeasure();
-
- expect(visibleText()).toBe('Multiple people are typing...');
- expect(measure()?.textContent).toBe('alice and bob are typing...');
- });
-
- it('keeps the names when they fit with 48 px to spare', () => {
- setWidth(overflowContainer, 'clientWidth', 300);
- renderRow({showAvatars: false});
- startTyping('alice', 'bob');
-
- setWidth(measure()!, 'scrollWidth', 252);
- remeasure();
-
- expect(visibleText()).toBe('alice and bob are typing...');
- });
-
- it('keeps the full string in the announcer while the visible text overflows', () => {
- setWidth(overflowContainer, 'clientWidth', 300);
- renderRow({showAvatars: false});
- startTyping('alice', 'bob', 'carol');
-
- setWidth(measure()!, 'scrollWidth', 400);
- remeasure();
-
- expect(visibleText()).toBe('Multiple people are typing...');
- expect(announcer().textContent).toBe('alice, bob and carol are typing...');
- });
-
- it('restores the names when the container grows again', () => {
- setWidth(overflowContainer, 'clientWidth', 300);
- renderRow({showAvatars: false});
- startTyping('alice');
- setWidth(measure()!, 'scrollWidth', 280);
- remeasure();
- expect(visibleText()).toBe('Multiple people are typing...');
-
- setWidth(overflowContainer, 'clientWidth', 400);
- remeasure();
-
- expect(visibleText()).toBe('alice is typing...');
- });
-
- it('does not measure overflow with four or more typists', () => {
- setWidth(overflowContainer, 'clientWidth', 10);
- renderRow();
- startTyping('alice', 'bob', 'carol');
- expect(visibleText()).toBe('Multiple people are typing...');
- expect(activeResizeObservers()).toHaveLength(1);
-
- startTyping('dave');
-
- expect(visibleText()).toBe('Several people are typing...');
- expect(measure()).toBeNull();
- expect(activeResizeObservers()).toHaveLength(0);
- });
-
- it('subtracts the avatar stack width from the available width', () => {
- setWidth(overflowContainer, 'clientWidth', 300);
- renderRow({showAvatars: true});
- startTyping('alice');
- setWidth(measure()!, 'scrollWidth', 200);
- remeasure();
- expect(visibleText()).toBe('alice is typing...');
-
- const avatarStack = host.querySelector(`.${messageStyles.typingAvatarContainer}`)!;
- avatarStack.getBoundingClientRect = () => ({width: 60}) as DOMRect;
- remeasure();
-
- expect(visibleText()).toBe('Multiple people are typing...');
- });
-
- it('disconnects the resize observer on unmount', () => {
- renderRow();
- startTyping('alice');
- const [resizeObserver] = activeResizeObservers();
- expect(resizeObserver?.targets).toEqual([overflowContainer, measure()]);
-
- act(() => {
- root.unmount();
- });
- root = createRoot(host);
-
- expect(resizeObserver?.disconnected).toBe(true);
- expect(activeResizeObservers()).toHaveLength(0);
- });
-
- it("does not re-render on the current user's own typing", () => {
- const onRender = vi.fn();
- render(
- createElement(
- Profiler,
- {id: 'typing-row', onRender},
- createElement(TypingUsers, {channel: CHANNEL, overflowContainerRef}),
- ),
- );
- startTyping('alice');
- const commits = onRender.mock.calls.length;
-
- startTyping('me');
- act(() => {
- RollingTypingStore.start(CHANNEL.id, 'me', 'gateway');
- RollingTypingStore.start(CHANNEL.id, 'alice', 'gateway');
- });
- act(() => {
- RollingTypingStore.remove(CHANNEL.id, 'me');
- });
-
- expect(onRender).toHaveBeenCalledTimes(commits);
- expect(visibleText()).toBe('alice is typing...');
- });
-});
diff --git a/fluxer_app/src/features/channel/components/embeds/EmbedRenderUtils.test.ts b/fluxer_app/src/features/channel/components/embeds/EmbedRenderUtils.test.ts
deleted file mode 100644
index a54e576da..000000000
--- a/fluxer_app/src/features/channel/components/embeds/EmbedRenderUtils.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- BLUESKY_EMBED_MEDIA_FALLBACK_OUTER_WIDTH,
- BLUESKY_EMBED_MIN_CONTENT_WIDTH,
- calculateBlueskyMediaContainerWidth,
- calculateBlueskyOuterMaxWidth,
- EMBED_TEXT_OUTER_WIDTH,
- formatResponsiveEmbedWidth,
-} from '@app/features/channel/components/embeds/EmbedRenderUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('formatResponsiveEmbedWidth', () => {
- it('caps in rem so the width tracks the root font size at any zoom', () => {
- expect(formatResponsiveEmbedWidth(EMBED_TEXT_OUTER_WIDTH)).toBe('min(100%, 32.25rem)');
- expect(formatResponsiveEmbedWidth(BLUESKY_EMBED_MEDIA_FALLBACK_OUTER_WIDTH)).toBe('min(100%, 27rem)');
- });
-
- it('rounds to whole pixels before converting', () => {
- expect(formatResponsiveEmbedWidth(400.4)).toBe('min(100%, 25rem)');
- });
-
- it('clamps non-positive and non-finite widths', () => {
- expect(formatResponsiveEmbedWidth(0)).toBe('min(100%, 0rem)');
- expect(formatResponsiveEmbedWidth(Number.NaN)).toBe('min(100%, 0rem)');
- });
-});
-
-describe('calculateBlueskyOuterMaxWidth', () => {
- it('falls back to the shared text width when there is no media', () => {
- expect(calculateBlueskyOuterMaxWidth({hasMedia: false, chromeWidth: 29})).toBe(EMBED_TEXT_OUTER_WIDTH);
- });
-
- it('adds chrome around the media container width', () => {
- expect(calculateBlueskyOuterMaxWidth({mediaWidth: 480, hasMedia: true, chromeWidth: 29})).toBe(509);
- });
-
- it('never goes below the minimum content width', () => {
- expect(calculateBlueskyMediaContainerWidth(120)).toBe(BLUESKY_EMBED_MIN_CONTENT_WIDTH);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.test.ts b/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.test.ts
deleted file mode 100644
index d422b1a57..000000000
--- a/fluxer_app/src/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildCsvTableNode,
- isCsvAttachment,
- parseCsvRows,
-} from '@app/features/channel/components/embeds/attachments/CsvAttachmentPreviewUtils';
-import {TableAlignment} from '@app/features/messaging/utils/markdown/parser/Enums';
-import type {MessageAttachment} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-function attachmentFixture(fields: Partial<MessageAttachment>): MessageAttachment {
- return fields as MessageAttachment;
-}
-
-describe('CSV attachment preview utils', () => {
- it('detects CSV attachments by extension or content type', () => {
- expect(
- isCsvAttachment(attachmentFixture({id: '1', filename: 'data.csv', content_type: 'application/octet-stream'})),
- ).toBe(true);
- expect(
- isCsvAttachment(attachmentFixture({id: '2', filename: 'data.txt', content_type: 'text/csv; charset=utf-8'})),
- ).toBe(true);
- expect(isCsvAttachment(attachmentFixture({id: '3', filename: 'data.txt', content_type: 'text/plain'}))).toBe(false);
- });
-
- it('parses quoted values, escaped quotes, and CRLF rows', () => {
- expect(parseCsvRows('name,note\r\n"Ada, Lovelace","said ""hello"""\r\nGrace,Compiler')).toEqual([
- ['name', 'note'],
- ['Ada, Lovelace', 'said "hello"'],
- ['Grace', 'Compiler'],
- ]);
- });
-
- it('preserves empty cells and ignores one trailing row break', () => {
- expect(parseCsvRows('a,,c\n1,2,\n')).toEqual([
- ['a', '', 'c'],
- ['1', '2', ''],
- ]);
- });
-
- it('normalizes ragged rows into a markdown table node', () => {
- expect(buildCsvTableNode([['a'], ['1', '2']])).toEqual({
- type: 'Table',
- header: {
- type: 'TableRow',
- cells: [
- {type: 'TableCell', children: [{type: 'Text', content: 'a'}]},
- {type: 'TableCell', children: [{type: 'Text', content: ''}]},
- ],
- },
- alignments: [TableAlignment.None, TableAlignment.None],
- rows: [
- {
- type: 'TableRow',
- cells: [
- {type: 'TableCell', children: [{type: 'Text', content: '1'}]},
- {type: 'TableCell', children: [{type: 'Text', content: '2'}]},
- ],
- },
- ],
- });
- });
-});
diff --git a/fluxer_app/src/features/channel/components/embeds/media/VideoDimensionUtils.test.ts b/fluxer_app/src/features/channel/components/embeds/media/VideoDimensionUtils.test.ts
deleted file mode 100644
index 63bc5cda3..000000000
--- a/fluxer_app/src/features/channel/components/embeds/media/VideoDimensionUtils.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getEffectiveVideoLayoutDimensions,
- hasDifferentAspectRatio,
- isInlinePlayableVideoSize,
- resolveVideoLayout,
-} from '@app/features/channel/components/embeds/media/VideoDimensionUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('getEffectiveVideoLayoutDimensions', () => {
- it('prefers decoded dimensions over declared upload dimensions', () => {
- expect(getEffectiveVideoLayoutDimensions({width: 1280, height: 700}, {width: 1920, height: 700})).toEqual({
- width: 1920,
- height: 700,
- });
- });
-
- it('prefers decoded dimensions for rotated portrait video', () => {
- expect(getEffectiveVideoLayoutDimensions({width: 1920, height: 1080}, {width: 1080, height: 1920})).toEqual({
- width: 1080,
- height: 1920,
- });
- });
-
- it('falls back to declared dimensions until metadata decodes', () => {
- expect(getEffectiveVideoLayoutDimensions({width: 640, height: 360}, null)).toEqual({width: 640, height: 360});
- });
-
- it('falls back to a 16:9 default when nothing is known', () => {
- expect(getEffectiveVideoLayoutDimensions(null, null)).toEqual({width: 16, height: 9});
- });
-
- it('ignores invalid decoded dimensions', () => {
- expect(getEffectiveVideoLayoutDimensions({width: 640, height: 360}, {width: 0, height: 0})).toEqual({
- width: 640,
- height: 360,
- });
- });
-});
-
-describe('poster aspect-ratio mismatch detection', () => {
- it('flags an anamorphic thumbnail as mismatched against the decoded video', () => {
- expect(hasDifferentAspectRatio({width: 1920, height: 700}, {width: 1280, height: 700}, 0.05)).toBe(true);
- });
-
- it('flags a rotated (inverted) thumbnail as mismatched', () => {
- expect(hasDifferentAspectRatio({width: 1080, height: 1920}, {width: 1920, height: 1080}, 0.05)).toBe(true);
- });
-
- it('treats a matching thumbnail as consistent within tolerance', () => {
- expect(hasDifferentAspectRatio({width: 1920, height: 1080}, {width: 1280, height: 720}, 0.05)).toBe(false);
- });
-});
-
-describe('resolveVideoLayout', () => {
- it('produces an aspect ratio matching the decoded display dimensions', () => {
- const {aspectRatio} = resolveVideoLayout({width: 1920, height: 700}, {maxWidth: 400, maxHeight: 400});
- const [w, h] = aspectRatio.split(' / ').map(Number);
- expect(w / h).toBeCloseTo(1920 / 700, 1);
- });
-});
-
-describe('isInlinePlayableVideoSize', () => {
- it('accepts a landscape source sitting exactly on both edges', () => {
- expect(isInlinePlayableVideoSize({width: 6016, height: 3384})).toBe(true);
- });
-
- it('accepts a portrait source sitting exactly on the swapped edges', () => {
- expect(isInlinePlayableVideoSize({width: 3384, height: 6016})).toBe(true);
- });
-
- it('rejects one pixel past the landscape long edge', () => {
- expect(isInlinePlayableVideoSize({width: 6017, height: 3384})).toBe(false);
- });
-
- it('rejects one pixel past the landscape short edge', () => {
- expect(isInlinePlayableVideoSize({width: 6016, height: 3385})).toBe(false);
- });
-
- it('rejects one pixel past the portrait long edge', () => {
- expect(isInlinePlayableVideoSize({width: 3384, height: 6017})).toBe(false);
- });
-
- it('rejects one pixel past the portrait short edge', () => {
- expect(isInlinePlayableVideoSize({width: 3385, height: 6016})).toBe(false);
- });
-
- it('accepts a source that only fits the swapped clause', () => {
- expect(isInlinePlayableVideoSize({width: 3000, height: 5000})).toBe(true);
- });
-
- it('rejects a square source larger than the short edge', () => {
- expect(isInlinePlayableVideoSize({width: 4000, height: 4000})).toBe(false);
- });
-
- it('accepts a square source on the short edge', () => {
- expect(isInlinePlayableVideoSize({width: 3384, height: 3384})).toBe(true);
- });
-
- it('accepts unknown dimensions so metadata gaps never silence playback', () => {
- expect(isInlinePlayableVideoSize(null)).toBe(true);
- expect(isInlinePlayableVideoSize({width: 0, height: 0})).toBe(true);
- expect(isInlinePlayableVideoSize({width: Number.NaN, height: Number.NaN})).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/pickers/gif/FavoriteGifSlimming.test.ts b/fluxer_app/src/features/channel/components/pickers/gif/FavoriteGifSlimming.test.ts
deleted file mode 100644
index 4fd3fe6d6..000000000
--- a/fluxer_app/src/features/channel/components/pickers/gif/FavoriteGifSlimming.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type FavoriteGifEntry,
- slimFavoriteGifEntry,
-} from '@app/features/channel/components/pickers/gif/FavoriteGifTypes';
-import {describe, expect, it} from 'vitest';
-
-function format(src: string, width: number) {
- return {src, proxy_src: `https://media.test/external/sig/${src}`, width, height: Math.round(width * 0.84)};
-}
-
-const FAT: FavoriteGifEntry = {
- url: 'https://klipy.com/gifs/reaction',
- proxy_url: 'https://media.test/external/sig/tiny.webm',
- width: 220,
- height: 185,
- media: {
- nanowebm: format('nano.webm', 90),
- tinywebm: format('tiny.webm', 220),
- mediumwebm: format('medium.webm', 320),
- webm: format('full.webm', 498),
- gif: format('full.gif', 498),
- },
- content_type: 'video/webm',
- placeholder: 'placeholder',
-};
-
-describe('slimFavoriteGifEntry', () => {
- it('drops the media map so a favorite is cheap to sync', () => {
- expect(slimFavoriteGifEntry(FAT).media).toEqual({});
- });
-
- it('promotes a preview that covers a 200px tile at 2x into the top-level fields', () => {
- const slim = slimFavoriteGifEntry(FAT);
- expect(slim.proxy_url).toBe(FAT.media.webm.proxy_src);
- expect(slim.width).toBe(498);
- expect(slim.content_type).toBe('video/webm');
- });
-
- it('keeps url and placeholder untouched', () => {
- const slim = slimFavoriteGifEntry(FAT);
- expect(slim.url).toBe(FAT.url);
- expect(slim.placeholder).toBe(FAT.placeholder);
- });
-
- it('is idempotent so the synced roundtrip stays stable', () => {
- const once = slimFavoriteGifEntry(FAT);
- expect(slimFavoriteGifEntry(once)).toEqual(once);
- });
-
- it('leaves an entry that already carries no media alone', () => {
- const urlOnly: FavoriteGifEntry = {...FAT, media: {}};
- expect(slimFavoriteGifEntry(urlOnly)).toBe(urlOnly);
- });
-
- it('does not invent a preview when every format is unusable', () => {
- const broken: FavoriteGifEntry = {...FAT, media: {webm: {src: '', proxy_src: '', width: 0, height: 0}}};
- const slim = slimFavoriteGifEntry(broken);
- expect(slim.media).toEqual({});
- expect(slim.proxy_url).toBe(FAT.proxy_url);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerGridData.test.ts b/fluxer_app/src/features/channel/components/pickers/gif/GifPickerGridData.test.ts
deleted file mode 100644
index 4654388f9..000000000
--- a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerGridData.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {FavoriteGifEntry} from '@app/features/channel/components/pickers/gif/FavoriteGifTypes';
-import {buildGifPickerGridData} from '@app/features/channel/components/pickers/gif/GifPickerGridData';
-import type {FavoriteAwareGif} from '@app/features/channel/components/pickers/gif/GifPickerTypes';
-import {describe, expect, it} from 'vitest';
-
-function gif(id: string, width = 200, height = 120): FavoriteAwareGif {
- return {
- id,
- slug: id,
- provider: 'klipy',
- title: id,
- url: `https://example.test/${id}`,
- src: `https://cdn.example.test/${id}.webp`,
- proxy_src: `https://proxy.example.test/${id}.webp`,
- width,
- height,
- media: {},
- };
-}
-
-const OPAQUE_PROXY_URL =
- 'https://media.test/external/sig/v2/aHR0cHM6Ly9zdGF0aWMua2xpcHkuY29tL2lpLzhjLzZhL2E4LzVsU2U1SFBCLndlYm0';
-
-function slimFavorite(overrides: Partial<FavoriteGifEntry> = {}): FavoriteGifEntry {
- return {
- url: 'https://klipy.com/gifs/doc-brown-bttf',
- proxy_url: OPAQUE_PROXY_URL,
- width: 640,
- height: 360,
- media: {},
- content_type: 'video/webm',
- placeholder: null,
- ...overrides,
- };
-}
-
-describe('GifPickerGridData', () => {
- it('carries the stored content type of a slimmed favorite into its tile', () => {
- const data = buildGifPickerGridData({
- surface: 'favorites',
- loading: false,
- columns: 3,
- provider: 'klipy',
- featured: {gifs: [], categories: []},
- gifs: [],
- favoriteGifs: [slimFavorite()],
- favoriteMemes: [],
- useSavedMediaForGifFavorites: false,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data[0]).toMatchObject({
- type: 'gif',
- gif: {proxy_src: OPAQUE_PROXY_URL, contentType: 'video/webm'},
- });
- });
-
- it('carries the stored content type of a slimmed favorite into the featured favorites tile', () => {
- const data = buildGifPickerGridData({
- surface: 'featured',
- loading: false,
- columns: 3,
- provider: 'klipy',
- featured: {gifs: [gif('featured')], categories: []},
- gifs: [],
- favoriteGifs: [slimFavorite()],
- favoriteMemes: [],
- useSavedMediaForGifFavorites: false,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data[0]).toMatchObject({
- type: 'category',
- previewProxySrc: OPAQUE_PROXY_URL,
- previewContentType: 'video/webm',
- });
- });
-
- it('takes the content type of the saved media standing in for an empty favorites tile', () => {
- const data = buildGifPickerGridData({
- surface: 'featured',
- loading: false,
- columns: 3,
- provider: 'klipy',
- featured: {gifs: [gif('featured')], categories: []},
- gifs: [],
- favoriteGifs: [],
- favoriteMemes: [{contentType: 'video/mp4', url: 'meme-0'}],
- useSavedMediaForGifFavorites: true,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data[0]).toMatchObject({type: 'category', previewProxySrc: 'meme-0', previewContentType: 'video/mp4'});
- });
-
- it('keeps featured data deterministic while choosing preview tiles', () => {
- const data = buildGifPickerGridData({
- surface: 'featured',
- loading: false,
- columns: 3,
- provider: 'klipy',
- featured: {
- gifs: [gif('featured')],
- categories: [{name: 'cats', src: 'cat-src', proxy_src: 'cat-proxy', gif: null}],
- },
- gifs: [],
- favoriteGifs: [],
- favoriteMemes: [
- {contentType: 'video/mp4', url: 'meme-0'},
- {contentType: 'image/png', url: 'ignored'},
- {contentType: 'image/gif', url: 'meme-1'},
- ],
- useSavedMediaForGifFavorites: true,
- featuredFavoritePreviewSeed: 0.75,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data.map((item) => item.key)).toEqual(['favorites', 'trending', 'cats']);
- expect(data[0]).toMatchObject({type: 'category', previewUrl: 'meme-1', previewProxySrc: 'meme-1'});
- expect(data[1]).toMatchObject({type: 'category', previewUrl: 'https://cdn.example.test/featured.webp'});
- });
-
- it('omits the favorites tile when includeFavoritesTile is false', () => {
- const data = buildGifPickerGridData({
- surface: 'featured',
- loading: false,
- columns: 3,
- provider: 'klipy',
- featured: {
- gifs: [gif('featured')],
- categories: [{name: 'cats', src: 'cat-src', proxy_src: 'cat-proxy', gif: null}],
- },
- gifs: [],
- favoriteGifs: [],
- favoriteMemes: [],
- useSavedMediaForGifFavorites: false,
- includeFavoritesTile: false,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data.map((item) => item.key)).toEqual(['trending', 'cats']);
- });
-
- it('builds skeletons only when result data is empty during loading', () => {
- const data = buildGifPickerGridData({
- surface: 'results',
- loading: true,
- columns: 4,
- provider: 'klipy',
- featured: {gifs: [], categories: []},
- gifs: [],
- favoriteGifs: [],
- favoriteMemes: [],
- useSavedMediaForGifFavorites: false,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data).toHaveLength(12);
- expect(data.every((item) => item.type === 'skeleton')).toBe(true);
- });
-
- it('keeps old result items instead of skeletonizing while a newer query is loading', () => {
- const data = buildGifPickerGridData({
- surface: 'results',
- loading: true,
- columns: 4,
- provider: 'klipy',
- featured: {gifs: [], categories: []},
- gifs: [gif('old-result')],
- favoriteGifs: [],
- favoriteMemes: [],
- useSavedMediaForGifFavorites: false,
- featuredFavoritePreviewSeed: 0,
- favoriteTitle: 'Favorites',
- trendingTitle: 'Trending',
- });
- expect(data).toEqual([{type: 'gif', key: 'old-result', gif: gif('old-result')}]);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerLoadingSkeletonGridLayout.test.ts b/fluxer_app/src/features/channel/components/pickers/gif/GifPickerLoadingSkeletonGridLayout.test.ts
deleted file mode 100644
index 5d168d581..000000000
--- a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerLoadingSkeletonGridLayout.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {buildGifPickerLoadingSkeletonLayout} from '@app/features/channel/components/pickers/gif/GifPickerLoadingSkeletonGridLayout';
-import {describe, expect, it} from 'vitest';
-
-describe('buildGifPickerLoadingSkeletonLayout', () => {
- it('lays out GIF-like placeholders with the same masonry constraints as the real grid', () => {
- const layout = buildGifPickerLoadingSkeletonLayout({
- viewportWidth: 436,
- viewportHeight: 1200,
- });
- expect(layout.length).toBeGreaterThan(12);
- expect(layout[0]).toMatchObject({
- key: 'square-255',
- column: 0,
- left: 12,
- top: 12,
- renderedWidth: 202,
- renderedHeight: 202,
- });
- const wideItem = layout.find((item) => item.key === 'wide-640-358');
- const portraitItem = layout.find((item) => item.key === 'portrait-325-498');
- expect(wideItem).toBeDefined();
- expect(portraitItem).toBeDefined();
- expect(wideItem!.renderedHeight / wideItem!.renderedWidth).toBeCloseTo(358 / 640, 4);
- expect(portraitItem!.renderedHeight / portraitItem!.renderedWidth).toBeCloseTo(498 / 325, 4);
- for (const item of layout) {
- expect(item.left).toBeGreaterThanOrEqual(12);
- expect(item.left + item.renderedWidth).toBeLessThanOrEqual(436 - 12);
- expect(item.top).toBeGreaterThanOrEqual(12);
- }
- });
-
- it('returns no placeholders before the skeleton viewport has measurable dimensions', () => {
- expect(buildGifPickerLoadingSkeletonLayout({viewportWidth: 0, viewportHeight: 600})).toEqual([]);
- expect(buildGifPickerLoadingSkeletonLayout({viewportWidth: 436, viewportHeight: 0})).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerMediaKind.test.ts b/fluxer_app/src/features/channel/components/pickers/gif/GifPickerMediaKind.test.ts
deleted file mode 100644
index 492e7e177..000000000
--- a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerMediaKind.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolvesToVideo} from '@app/features/channel/components/pickers/gif/GifPickerMediaKind';
-import {describe, expect, it} from 'vitest';
-
-const OPAQUE_PROXY_SRC =
- 'https://media.test/external/sig/v2/aHR0cHM6Ly9zdGF0aWMua2xpcHkuY29tL2lpLzhjLzZhL2E4LzVsU2U1SFBCLndlYm0';
-const PLAIN_PROXY_SRC = 'https://media.test/external/sig/https/static.klipy.com/ii/8c/6a/a8/5lSe5HPB.webm';
-
-describe('resolvesToVideo', () => {
- it('trusts a stored video content type when no url states its kind', () => {
- expect(resolvesToVideo('video/webm', OPAQUE_PROXY_SRC, OPAQUE_PROXY_SRC)).toBe(true);
- });
-
- it('trusts a stored image content type when no url states its kind', () => {
- expect(resolvesToVideo('image/gif', OPAQUE_PROXY_SRC, OPAQUE_PROXY_SRC)).toBe(false);
- });
-
- it('falls back to an image when nothing states the kind', () => {
- expect(resolvesToVideo('', OPAQUE_PROXY_SRC, OPAQUE_PROXY_SRC)).toBe(false);
- });
-
- it('reads the extension off a plain proxy path', () => {
- expect(resolvesToVideo('', PLAIN_PROXY_SRC, null)).toBe(true);
- });
-
- it('reads the extension off the media source when the proxy path is opaque', () => {
- expect(resolvesToVideo('', OPAQUE_PROXY_SRC, 'https://static.klipy.com/ii/8c/6a/a8/5lSe5HPB.webm')).toBe(true);
- });
-
- it('keeps images as images when the proxy path states its kind', () => {
- expect(resolvesToVideo('', 'https://media.test/external/sig/https/cdn.test/a.gif', null)).toBe(false);
- });
-
- it('ignores a query string when reading the extension', () => {
- expect(resolvesToVideo('', 'https://media.test/external/sig/https/cdn.test/a.mp4?width=200', null)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerStateMachine.test.ts b/fluxer_app/src/features/channel/components/pickers/gif/GifPickerStateMachine.test.ts
deleted file mode 100644
index ec9e1b74a..000000000
--- a/fluxer_app/src/features/channel/components/pickers/gif/GifPickerStateMachine.test.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createGifPickerRequestId,
- createGifPickerSnapshot,
- selectGifPickerModel,
- transitionGifPickerSnapshot,
-} from '@app/features/channel/components/pickers/gif/GifPickerStateMachine';
-import {describe, expect, it} from 'vitest';
-
-describe('GifPickerStateMachine', () => {
- it('starts on the featured surface without showing a loading state', () => {
- const model = selectGifPickerModel(createGifPickerSnapshot());
- expect(model.view).toBe('default');
- expect(model.isShowingFeatured).toBe(true);
- expect(model.initialFeaturedLoading).toBe(false);
- expect(model.shouldShowNoResults).toBe(false);
- });
-
- it('shows the initial spinner only while the first featured request has no cached content', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.featuredRequested',
- requestId: createGifPickerRequestId(1),
- hasContent: false,
- });
- expect(selectGifPickerModel(snapshot).initialFeaturedLoading).toBe(true);
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.featuredSucceeded',
- requestId: createGifPickerRequestId(1),
- hasContent: true,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.initialFeaturedLoading).toBe(false);
- expect(model.isShowingFeatured).toBe(true);
- });
-
- it('keeps featured content visible while a new search is pending', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.featuredSucceeded',
- requestId: createGifPickerRequestId(1),
- hasContent: true,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'cats',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(2),
- term: 'cats',
- showLoadingSkeleton: false,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.searchTerm).toBe('cats');
- expect(model.pendingSearchTerm).toBe('cats');
- expect(model.isResultsLoading).toBe(true);
- expect(model.isShowingFeatured).toBe(true);
- expect(model.isShowingResults).toBe(false);
- });
-
- it('keeps old search results visible until the newer query succeeds', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'cats',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchSucceeded',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- resultCount: 20,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'dogs',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(2),
- term: 'dogs',
- showLoadingSkeleton: false,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.searchTerm).toBe('dogs');
- expect(model.committedSearchTerm).toBe('cats');
- expect(model.isResultsLoading).toBe(true);
- expect(model.isShowingResults).toBe(true);
- expect(model.shouldShowNoResults).toBe(false);
- });
-
- it('ignores stale search completions after the term changes', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'cats',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'dogs',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchSucceeded',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- resultCount: 20,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.searchTerm).toBe('dogs');
- expect(model.committedSearchTerm).toBe('');
- expect(model.isResultsLoading).toBe(true);
- expect(model.isShowingFeatured).toBe(true);
- });
-
- it('shows no-results only after an authoritative empty result succeeds', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'zzzzzz',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(1),
- term: 'zzzzzz',
- showLoadingSkeleton: false,
- });
- expect(selectGifPickerModel(snapshot).shouldShowNoResults).toBe(false);
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchSucceeded',
- requestId: createGifPickerRequestId(1),
- term: 'zzzzzz',
- resultCount: 0,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.isShowingResults).toBe(true);
- expect(model.shouldShowNoResults).toBe(true);
- expect(model.shouldShowError).toBe(false);
- });
-
- it('keeps old results visible when a newer search fails', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'cats',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchSucceeded',
- requestId: createGifPickerRequestId(1),
- term: 'cats',
- resultCount: 20,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'dogs',
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(2),
- term: 'dogs',
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchFailed',
- requestId: createGifPickerRequestId(2),
- term: 'dogs',
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.isShowingResults).toBe(true);
- expect(model.committedSearchTerm).toBe('cats');
- expect(model.shouldShowNoResults).toBe(false);
- expect(model.shouldShowError).toBe(false);
- });
-
- it('shows an error state when trending fails without any retained results', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.trendingRequested',
- requestId: createGifPickerRequestId(1),
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.trendingFailed',
- requestId: createGifPickerRequestId(1),
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.isLoading).toBe(false);
- expect(model.shouldShowError).toBe(true);
- expect(model.errorKind).toBe('trending');
- });
-
- it('can replace the current surface with a loading skeleton immediately for uncached trending results', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.trendingRequested',
- requestId: createGifPickerRequestId(1),
- showLoadingSkeleton: true,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.isResultsLoading).toBe(true);
- expect(model.shouldShowLoadingSkeleton).toBe(true);
- expect(model.shouldShowNoResults).toBe(false);
- expect(model.shouldShowError).toBe(false);
- });
-
- it('keeps featured content visible until a delayed search skeleton event matches the active request', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.featuredSucceeded',
- requestId: createGifPickerRequestId(1),
- hasContent: true,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'cats',
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchRequested',
- requestId: createGifPickerRequestId(2),
- term: 'cats',
- showLoadingSkeleton: false,
- });
- expect(selectGifPickerModel(snapshot).shouldShowLoadingSkeleton).toBe(false);
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.loadingSkeletonElapsed',
- requestId: createGifPickerRequestId(99),
- kind: 'search',
- term: 'cats',
- });
- expect(selectGifPickerModel(snapshot).shouldShowLoadingSkeleton).toBe(false);
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.loadingSkeletonElapsed',
- requestId: createGifPickerRequestId(2),
- kind: 'search',
- term: 'cats',
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.isShowingFeatured).toBe(true);
- expect(model.shouldShowLoadingSkeleton).toBe(true);
- });
-
- it('shows the skeleton immediately when typing from a cleared non-search results surface', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.trendingRequested',
- requestId: createGifPickerRequestId(1),
- showLoadingSkeleton: false,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.trendingSucceeded',
- requestId: createGifPickerRequestId(1),
- resultCount: 20,
- });
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.searchTermChanged',
- term: 'dogs',
- showLoadingSkeleton: true,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.view).toBe('default');
- expect(model.resultKind).toBe('trending');
- expect(model.isResultsLoading).toBe(true);
- expect(model.shouldShowLoadingSkeleton).toBe(true);
- });
-
- it('opens cached category results without showing a loading skeleton', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {
- type: 'gifPicker.categoryCacheOpened',
- term: 'cats',
- resultCount: 12,
- });
- const model = selectGifPickerModel(snapshot);
- expect(model.searchTerm).toBe('cats');
- expect(model.committedSearchTerm).toBe('cats');
- expect(model.isShowingResults).toBe(true);
- expect(model.isResultsLoading).toBe(false);
- expect(model.shouldShowLoadingSkeleton).toBe(false);
- });
-
- it('moves to favorites as an explicit non-fetching surface', () => {
- let snapshot = createGifPickerSnapshot();
- snapshot = transitionGifPickerSnapshot(snapshot, {type: 'gifPicker.favoritesOpened'});
- const model = selectGifPickerModel(snapshot);
- expect(model.view).toBe('favorites');
- expect(model.isShowingFavorites).toBe(true);
- expect(model.isLoading).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/channel/components/textarea/MobileTextareaButtonStateMachine.test.ts b/fluxer_app/src/features/channel/components/textarea/MobileTextareaButtonStateMachine.test.ts
deleted file mode 100644
index 45223491f..000000000
--- a/fluxer_app/src/features/channel/components/textarea/MobileTextareaButtonStateMachine.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type MobileTextareaButtonSignals,
- transitionMobileTextareaButtonState,
-} from '@app/features/channel/components/textarea/MobileTextareaButtonStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<MobileTextareaButtonSignals> = {}): MobileTextareaButtonSignals {
- return {
- disabled: false,
- canRecordVoice: true,
- value: '',
- isSlowmodeActive: false,
- isOverCharacterLimit: false,
- isEditingMessage: false,
- hasContent: false,
- hasAttachments: false,
- hasPendingSticker: false,
- ...overrides,
- };
-}
-
-function state(overrides: Partial<MobileTextareaButtonSignals> = {}) {
- return transitionMobileTextareaButtonState(signals(overrides));
-}
-
-describe('MobileTextareaButtonStateMachine', () => {
- it('shows the voice button for an empty normal composer', () => {
- expect(state()).toMatchObject({
- mode: 'voice',
- visibleButton: 'voice',
- sendButton: {disabled: true},
- voiceButton: {disabled: false},
- hasSubmissionContent: false,
- });
- });
-
- it('shows an enabled send button as soon as raw visible textarea text exists', () => {
- expect(state({value: 'hello', hasContent: false})).toMatchObject({
- mode: 'sendReady',
- visibleButton: 'send',
- sendButton: {disabled: false},
- hasTypedText: true,
- hasTextContent: true,
- hasSubmissionContent: true,
- });
- });
-
- it('keeps the voice button for whitespace and invisible-only textarea content', () => {
- expect(state({value: ' \n\t\u200b'})).toMatchObject({
- mode: 'voice',
- visibleButton: 'voice',
- hasTypedText: false,
- hasSubmissionContent: false,
- });
- });
-
- it('shows send for attachment and sticker payloads without text', () => {
- expect(state({hasAttachments: true})).toMatchObject({
- mode: 'sendReady',
- visibleButton: 'send',
- sendButton: {disabled: false},
- hasSubmissionContent: true,
- });
- expect(state({hasPendingSticker: true})).toMatchObject({
- mode: 'sendReady',
- visibleButton: 'send',
- sendButton: {disabled: false},
- hasSubmissionContent: true,
- });
- });
-
- it('shows send while blocked by slowmode or character limits', () => {
- expect(state({value: 'hello', isSlowmodeActive: true})).toMatchObject({
- mode: 'sendBlocked',
- visibleButton: 'send',
- sendButton: {disabled: true},
- });
- expect(state({value: 'hello', isOverCharacterLimit: true})).toMatchObject({
- mode: 'sendBlocked',
- visibleButton: 'send',
- sendButton: {disabled: true},
- });
- });
-
- it('keeps edit mode on send even when the edited content is empty', () => {
- expect(state({isEditingMessage: true})).toMatchObject({
- mode: 'sendReady',
- visibleButton: 'send',
- sendButton: {disabled: false},
- });
- });
-
- it('falls back to a disabled send button when voice recording is unavailable and the composer is empty', () => {
- expect(state({canRecordVoice: false})).toMatchObject({
- mode: 'sendBlocked',
- visibleButton: 'send',
- sendButton: {disabled: true},
- });
- });
-});
diff --git a/fluxer_app/src/features/channel/components/useChannelComposerDraftFocusRestore.test.tsx b/fluxer_app/src/features/channel/components/useChannelComposerDraftFocusRestore.test.tsx
deleted file mode 100644
index 18d04c690..000000000
--- a/fluxer_app/src/features/channel/components/useChannelComposerDraftFocusRestore.test.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ComposerHandle} from '@app/features/lexical/composer/ComposerHandle';
-import {act, useRef} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const {canFocusTextareaMock} = vi.hoisted(() => ({canFocusTextareaMock: vi.fn(() => true)}));
-
-vi.mock('@app/features/platform/utils/InputFocusManager', () => ({
- canFocusTextarea: canFocusTextareaMock,
-}));
-
-const {useChannelComposerDraftFocusRestore} = await import(
- '@app/features/channel/components/useChannelComposerDraftFocusRestore'
-);
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-let container: HTMLDivElement;
-let root: Root;
-let focusSpy: ReturnType<typeof vi.fn>;
-
-interface HarnessProps {
- initialDraft: string;
- textareaInputDisabled?: boolean;
- inlineEditActive?: boolean;
-}
-
-function Harness({initialDraft, textareaInputDisabled = false, inlineEditActive = false}: HarnessProps) {
- const handleRef = useRef<ComposerHandle | null>(null);
- handleRef.current = {focus: focusSpy} as unknown as ComposerHandle;
- const editableRef = useRef<HTMLDivElement | null>(null);
- useChannelComposerDraftFocusRestore({
- handleRef,
- editableRef,
- initialDraft,
- textareaInputDisabled,
- inlineEditActive,
- });
- return (
- <div
- ref={editableRef}
- contentEditable
- suppressContentEditableWarning
- data-flx="channel.use-channel-composer-draft-focus-restore-test.harness.div"
- />
- );
-}
-
-function render(props: HarnessProps): void {
- act(() => {
- root.render(<Harness data-flx="channel.use-channel-composer-draft-focus-restore-test.harness" {...props} />);
- });
-}
-
-beforeEach(() => {
- focusSpy = vi.fn();
- canFocusTextareaMock.mockReturnValue(true);
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- container.remove();
- canFocusTextareaMock.mockReset();
-});
-
-describe('useChannelComposerDraftFocusRestore', () => {
- test('focuses the composer when the channel is entered with a pending draft', () => {
- render({initialDraft: 'half written'});
- expect(focusSpy).toHaveBeenCalledTimes(1);
- });
-
- test('leaves focus alone when there is no pending draft', () => {
- render({initialDraft: ''});
- expect(focusSpy).not.toHaveBeenCalled();
- });
-
- test('yields to an active inline message edit', () => {
- render({initialDraft: 'half written', inlineEditActive: true});
- expect(focusSpy).not.toHaveBeenCalled();
- });
-
- test('does nothing when composer input is disabled', () => {
- render({initialDraft: 'half written', textareaInputDisabled: true});
- expect(focusSpy).not.toHaveBeenCalled();
- });
-
- test('respects the shared focus guard that blocks mobile, modals and popouts', () => {
- canFocusTextareaMock.mockReturnValue(false);
- render({initialDraft: 'half written'});
- expect(focusSpy).not.toHaveBeenCalled();
- });
-
- test('restores focus only on the channel mount, not on every re-render', () => {
- render({initialDraft: 'half written'});
- render({initialDraft: 'half written'});
- render({initialDraft: 'half written more'});
- expect(focusSpy).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_app/src/features/channel/state/ChannelDisplayNameTracking.test.ts b/fluxer_app/src/features/channel/state/ChannelDisplayNameTracking.test.ts
deleted file mode 100644
index ea2261ee5..000000000
--- a/fluxer_app/src/features/channel/state/ChannelDisplayNameTracking.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type TrackedRecipientSnapshot,
- type TrackedRecipientUser,
- trackedRecipientNameKey,
-} from '@app/features/channel/state/ChannelDisplayNameTracking';
-import {autorun, observable, runInAction} from 'mobx';
-import {describe, expect, it} from 'vitest';
-
-const snapshots = (entries: Record<string, ReadonlyArray<string>>): ReadonlyMap<string, TrackedRecipientSnapshot> =>
- new Map(Object.entries(entries).map(([id, recipientIds]) => [id, {recipientIds}]));
-
-const userTable = (count: number): Record<string, TrackedRecipientUser> => {
- const users: Record<string, TrackedRecipientUser> = {};
- for (let i = 0; i < count; i++) {
- users[`u${i}`] = {username: `user${i}`, globalName: null};
- }
- return users;
-};
-
-/** Wraps a user table so we can count exactly which keys get read. */
-const countingUsers = (
- users: Record<string, TrackedRecipientUser | undefined>,
-): {proxy: Record<string, TrackedRecipientUser | undefined>; reads: Array<string>} => {
- const reads: Array<string> = [];
- const proxy = new Proxy(users, {
- get(target, key, receiver) {
- if (typeof key === 'string') reads.push(key);
- return Reflect.get(target, key, receiver);
- },
- });
- return {proxy, reads};
-};
-
-describe('trackedRecipientNameKey', () => {
- it('reads only the recipients of tracked group DMs, not the whole user cache', () => {
- const {proxy, reads} = countingUsers(userTable(10_000));
- trackedRecipientNameKey(snapshots({c1: ['u1', 'u2'], c2: ['u3']}), proxy);
-
- // The cost must be a function of tracked recipients, never of cache size.
- expect(reads).toEqual(['u1', 'u2', 'u3']);
- });
-
- it('cost is independent of how large the user cache grows', () => {
- const small = countingUsers(userTable(10));
- const huge = countingUsers(userTable(100_000));
- const tracked = snapshots({c1: ['u1', 'u2']});
-
- trackedRecipientNameKey(tracked, small.proxy);
- trackedRecipientNameKey(tracked, huge.proxy);
-
- expect(small.reads.length).toBe(2);
- expect(huge.reads.length).toBe(2);
- });
-
- it('changes when a tracked recipient is renamed', () => {
- const users = userTable(3);
- const tracked = snapshots({c1: ['u1']});
- const before = trackedRecipientNameKey(tracked, users);
-
- users.u1 = {username: 'renamed', globalName: null};
-
- expect(trackedRecipientNameKey(tracked, users)).not.toBe(before);
- });
-
- it('does not change when an untracked user is renamed', () => {
- const users = userTable(3);
- const tracked = snapshots({c1: ['u1']});
- const before = trackedRecipientNameKey(tracked, users);
-
- users.u2 = {username: 'unrelated-change', globalName: 'also changed'};
-
- expect(trackedRecipientNameKey(tracked, users)).toBe(before);
- });
-
- it('distinguishes a missing recipient from one that arrives later', () => {
- const users: Record<string, TrackedRecipientUser | undefined> = {};
- const tracked = snapshots({c1: ['u1']});
- const before = trackedRecipientNameKey(tracked, users);
-
- users.u1 = {username: 'arrived', globalName: null};
-
- expect(trackedRecipientNameKey(tracked, users)).not.toBe(before);
- });
-
- it('is not confused by usernames containing the separator characters', () => {
- const tracked = snapshots({c1: ['a', 'b']});
- const collidingLeft: Record<string, TrackedRecipientUser> = {
- a: {username: 'x", "y', globalName: null},
- b: {username: '', globalName: null},
- };
- const collidingRight: Record<string, TrackedRecipientUser> = {
- a: {username: '', globalName: null},
- b: {username: 'x", "y', globalName: null},
- };
-
- expect(trackedRecipientNameKey(tracked, collidingLeft)).not.toBe(trackedRecipientNameKey(tracked, collidingRight));
- });
-
- it('drives a MobX reaction on tracked renames but stays quiet on untracked ones', () => {
- const users = observable.object<Record<string, TrackedRecipientUser | undefined>>({
- u1: {username: 'one', globalName: null},
- u2: {username: 'two', globalName: null},
- });
- const tracked = snapshots({c1: ['u1']});
-
- let runs = 0;
- const dispose = autorun(() => {
- trackedRecipientNameKey(tracked, users);
- runs++;
- });
- expect(runs).toBe(1);
-
- // An untracked user changing must not wake the reaction.
- runInAction(() => {
- users.u2 = {username: 'two-renamed', globalName: null};
- });
- expect(runs).toBe(1);
-
- // A tracked user changing must.
- runInAction(() => {
- users.u1 = {username: 'one-renamed', globalName: null};
- });
- expect(runs).toBe(2);
-
- dispose();
- });
-});
diff --git a/fluxer_app/src/features/channel/state/ChannelFrecency.test.ts b/fluxer_app/src/features/channel/state/ChannelFrecency.test.ts
deleted file mode 100644
index 4a73f8e9a..000000000
--- a/fluxer_app/src/features/channel/state/ChannelFrecency.test.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {autorun, runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface FakeChannel {
- readonly id: string;
- readonly type: number;
- readonly recipientIds: ReadonlyArray<string>;
-}
-
-type ChannelFrecencyStore = typeof import('@app/features/channel/state/ChannelFrecency')['default'];
-
-interface SyncedFieldFake {
- seed: Record<string, {totalUses: number; recentUsesMs: Array<bigint>}> | null;
- toMessage: (() => {usage: Record<string, {totalUses: number; recentUsesMs: Array<bigint>}>}) | null;
-}
-
-const fakes = await vi.hoisted(async () => {
- const {observable} = await import('mobx');
- return {
- navigation: observable({guildId: null as string | null, channelId: null as string | null}),
- voice: observable({
- guildId: null as string | null,
- channelId: null as string | null,
- localDisconnectReason: null as string | null,
- }),
- guildIds: new Set<string>(),
- channels: new Map<string, FakeChannel>(),
- synced: {seed: null, toMessage: null} as SyncedFieldFake,
- };
-});
-
-vi.mock('@app/features/user/state/SyncedField', () => ({
- makeSyncedField: async (
- store: object,
- config: {
- toMessage: (store: never) => {usage: Record<string, {totalUses: number; recentUsesMs: Array<bigint>}>};
- applyMessage: (store: never, message: {usage: Record<string, unknown>}) => void;
- },
- ) => {
- fakes.synced.toMessage = () => config.toMessage(store as never);
- if (fakes.synced.seed !== null) {
- config.applyMessage(store as never, {usage: fakes.synced.seed});
- }
- },
-}));
-
-vi.mock('@app/features/navigation/state/Navigation', () => ({default: fakes.navigation}));
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({default: fakes.voice}));
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {getGuild: (guildId: string) => (fakes.guildIds.has(guildId) ? {id: guildId} : undefined)},
-}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {
- getChannel: (channelId: string) => fakes.channels.get(channelId),
- getPrivateChannels: () => Array.from(fakes.channels.values()),
- },
-}));
-
-const HOUR_MS = 3_600_000;
-const DAY_MS = 24 * HOUR_MS;
-const T0 = Date.UTC(2026, 6, 15, 12);
-const GUILD_ID = '1400000000000000100';
-const OTHER_GUILD_ID = '1400000000000000200';
-const TEXT_CHANNEL_ID = '1400000000000000101';
-const OTHER_TEXT_CHANNEL_ID = '1400000000000000102';
-const VOICE_CHANNEL_ID = '1400000000000000103';
-const OTHER_VOICE_CHANNEL_ID = '1400000000000000104';
-const OTHER_GUILD_VOICE_CHANNEL_ID = '1400000000000000201';
-const DM_CHANNEL_ID = '1400000000000000301';
-const FRIEND_ID = '1400000000000000401';
-
-async function startChannelFrecency(
- synced?: ReadonlyArray<readonly [string, {totalUses: number; recentUses: ReadonlyArray<number>}]>,
-): Promise<ChannelFrecencyStore> {
- vi.resetModules();
- fakes.synced.seed =
- synced === undefined
- ? null
- : Object.fromEntries(
- synced.map(([key, entry]) => [
- key,
- {totalUses: entry.totalUses, recentUsesMs: entry.recentUses.map((use) => BigInt(use))},
- ]),
- );
- const {default: ChannelFrecency} = await import('@app/features/channel/state/ChannelFrecency');
- await vi.advanceTimersByTimeAsync(0);
- return ChannelFrecency;
-}
-
-function navigate(guildId: string | null, channelId: string | null): void {
- runInAction(() => {
- fakes.navigation.guildId = guildId;
- fakes.navigation.channelId = channelId;
- });
-}
-
-function setVoiceChannel(guildId: string | null, channelId: string | null): void {
- runInAction(() => {
- fakes.voice.localDisconnectReason = channelId == null ? 'user' : null;
- fakes.voice.guildId = guildId;
- fakes.voice.channelId = channelId;
- });
-}
-
-function moveVoiceChannel(guildId: string | null, channelId: string): void {
- runInAction(() => {
- fakes.voice.localDisconnectReason = 'channelMove';
- fakes.voice.guildId = null;
- fakes.voice.channelId = null;
- });
- setVoiceChannel(guildId, channelId);
-}
-
-function totalUses(store: ChannelFrecencyStore, key: string): number {
- return store.usageHistory.get(key)?.totalUses ?? 0;
-}
-
-function keyFor(index: number): string {
- return `1400000000000000${String(index).padStart(3, '0')}`;
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(T0);
- navigate(null, null);
- setVoiceChannel(null, null);
- runInAction(() => {
- fakes.voice.localDisconnectReason = null;
- });
- fakes.guildIds.clear();
- fakes.channels.clear();
-});
-
-afterEach(() => {
- vi.useRealTimers();
-});
-
-describe('ChannelFrecency tracking', () => {
- it('counts the landing channel and its guild once when tracking starts', async () => {
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- const store = await startChannelFrecency();
- expect(totalUses(store, TEXT_CHANNEL_ID)).toBe(1);
- expect(totalUses(store, GUILD_ID)).toBe(1);
- expect(store.getScore(TEXT_CHANNEL_ID)).toBe(100);
- });
-
- it('counts a channel again after a page without a channel but not a guild the user stays in', async () => {
- const store = await startChannelFrecency();
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- navigate(GUILD_ID, OTHER_TEXT_CHANNEL_ID);
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- expect(totalUses(store, TEXT_CHANNEL_ID)).toBe(2);
- expect(totalUses(store, GUILD_ID)).toBe(1);
- navigate(null, null);
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- expect(totalUses(store, TEXT_CHANNEL_ID)).toBe(3);
- expect(totalUses(store, GUILD_ID)).toBe(2);
- });
-
- it('treats direct messages as guildless and never stores ids that are not snowflakes', async () => {
- const store = await startChannelFrecency();
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- navigate('@me', DM_CHANNEL_ID);
- navigate(GUILD_ID, 'settings');
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- expect([...store.usageHistory.keys()]).toEqual([TEXT_CHANNEL_ID, GUILD_ID, DM_CHANNEL_ID]);
- expect(totalUses(store, TEXT_CHANNEL_ID)).toBe(2);
- expect(totalUses(store, GUILD_ID)).toBe(2);
- expect(totalUses(store, DM_CHANNEL_ID)).toBe(1);
- });
-
- it('counts voice joins through the same last selection as navigation', async () => {
- const store = await startChannelFrecency();
- navigate(GUILD_ID, VOICE_CHANNEL_ID);
- setVoiceChannel(GUILD_ID, VOICE_CHANNEL_ID);
- expect(totalUses(store, VOICE_CHANNEL_ID)).toBe(1);
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- setVoiceChannel(GUILD_ID, OTHER_VOICE_CHANNEL_ID);
- navigate(GUILD_ID, OTHER_VOICE_CHANNEL_ID);
- expect(totalUses(store, OTHER_VOICE_CHANNEL_ID)).toBe(1);
- setVoiceChannel(null, null);
- setVoiceChannel(GUILD_ID, OTHER_VOICE_CHANNEL_ID);
- expect(totalUses(store, OTHER_VOICE_CHANNEL_ID)).toBe(2);
- setVoiceChannel(OTHER_GUILD_ID, OTHER_GUILD_VOICE_CHANNEL_ID);
- expect(totalUses(store, OTHER_GUILD_VOICE_CHANNEL_ID)).toBe(1);
- expect(totalUses(store, OTHER_GUILD_ID)).toBe(1);
- expect(totalUses(store, GUILD_ID)).toBe(2);
- });
-
- it('counts a move between voice channels in one guild as a single guild use', async () => {
- const store = await startChannelFrecency();
- setVoiceChannel(GUILD_ID, VOICE_CHANNEL_ID);
- moveVoiceChannel(GUILD_ID, OTHER_VOICE_CHANNEL_ID);
- expect(totalUses(store, VOICE_CHANNEL_ID)).toBe(1);
- expect(totalUses(store, OTHER_VOICE_CHANNEL_ID)).toBe(1);
- expect(totalUses(store, GUILD_ID)).toBe(1);
- });
-
- it('keeps at most 100 keys and drops the one used longest ago', async () => {
- const store = await startChannelFrecency();
- for (let index = 0; index <= 100; index++) {
- store.track(keyFor(index), T0 + index);
- }
- expect(store.usageHistory.size).toBe(100);
- expect(store.usageHistory.has(keyFor(0))).toBe(false);
- expect(store.usageHistory.has(keyFor(100))).toBe(true);
- });
-});
-
-describe('ChannelFrecency account sync', () => {
- it('re-derives persisted frecency against the current time on start', async () => {
- const store = await startChannelFrecency([
- [TEXT_CHANNEL_ID, {totalUses: 5, recentUses: [T0 - 8 * DAY_MS - HOUR_MS, T0 - 8 * DAY_MS]}],
- [GUILD_ID, {totalUses: 1, recentUses: []}],
- ]);
- expect(store.getScore(TEXT_CHANNEL_ID)).toBe(50);
- expect(store.usageHistory.has(GUILD_ID)).toBe(false);
- });
-
- it('re-derives frecency again as a long session ages', async () => {
- const store = await startChannelFrecency([[TEXT_CHANNEL_ID, {totalUses: 3, recentUses: [T0 - DAY_MS]}]]);
- expect(store.getScore(TEXT_CHANNEL_ID)).toBe(210);
- await vi.advanceTimersByTimeAsync(6 * DAY_MS);
- expect(store.getScore(TEXT_CHANNEL_ID)).toBe(30);
- });
-
- it('hands the account sync only the uses, not the derived scores', async () => {
- await startChannelFrecency();
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- await vi.advanceTimersByTimeAsync(1_000);
- expect(fakes.synced.toMessage?.()).toEqual({
- usage: {
- [TEXT_CHANNEL_ID]: {totalUses: 1, recentUsesMs: [BigInt(T0)]},
- [GUILD_ID]: {totalUses: 1, recentUsesMs: [BigInt(T0)]},
- },
- });
- });
-});
-
-describe('ChannelFrecency ranking', () => {
- it('ranks resolvable guild, channel and direct message keys by frecency', async () => {
- fakes.guildIds.add(GUILD_ID);
- fakes.channels.set(TEXT_CHANNEL_ID, {id: TEXT_CHANNEL_ID, type: ChannelTypes.GUILD_TEXT, recipientIds: []});
- fakes.channels.set(DM_CHANNEL_ID, {id: DM_CHANNEL_ID, type: ChannelTypes.DM, recipientIds: [FRIEND_ID]});
- const store = await startChannelFrecency();
- store.track(GUILD_ID);
- store.track(FRIEND_ID);
- store.track(OTHER_TEXT_CHANNEL_ID);
- store.track(TEXT_CHANNEL_ID);
- store.track(TEXT_CHANNEL_ID);
- expect(store.frequentIds).toEqual([TEXT_CHANNEL_ID, GUILD_ID, DM_CHANNEL_ID]);
- expect(store.getScore(TEXT_CHANNEL_ID)).toBe(200);
- expect(store.getScore(DM_CHANNEL_ID)).toBe(0);
- });
-
- it('lets observers follow the ranking as the user moves around', async () => {
- fakes.guildIds.add(GUILD_ID);
- fakes.channels.set(TEXT_CHANNEL_ID, {id: TEXT_CHANNEL_ID, type: ChannelTypes.GUILD_TEXT, recipientIds: []});
- const store = await startChannelFrecency();
- const seen: Array<ReadonlyArray<string>> = [];
- const dispose = autorun(() => {
- seen.push(store.frequentIds);
- });
- navigate(GUILD_ID, TEXT_CHANNEL_ID);
- dispose();
- expect(seen[0]).toEqual([]);
- expect(seen.at(-1)).toEqual([TEXT_CHANNEL_ID, GUILD_ID]);
- });
-});
diff --git a/fluxer_app/src/features/channel/utils/ChannelFrecencyCalculator.test.ts b/fluxer_app/src/features/channel/utils/ChannelFrecencyCalculator.test.ts
deleted file mode 100644
index 9ab222270..000000000
--- a/fluxer_app/src/features/channel/utils/ChannelFrecencyCalculator.test.ts
+++ /dev/null
@@ -1,305 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelFrecencyEntry,
- type ChannelFrecencyHistory,
- capChannelFrecencyHistory,
- channelFrecencyDayDiff,
- channelFrecencyHistoryFromWire,
- channelFrecencyHistoryToWire,
- channelFrecencyWeight,
- computeChannelFrecency,
- mergeChannelFrecencyWireUsage,
- rankFrequentChannelIds,
- restoreChannelFrecencyHistory,
- trackChannelUse,
-} from '@app/features/channel/utils/ChannelFrecencyCalculator';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const HOUR_MS = 3_600_000;
-const DAY_MS = 24 * HOUR_MS;
-const NOW = Date.UTC(2026, 6, 15, 12);
-const CHANNEL_ID = '1400000000000000001';
-const STOCKHOLM_SUMMER_TIME_START = Date.UTC(2026, 2, 29, 1);
-const STOCKHOLM_SUMMER_TIME_END = Date.UTC(2026, 9, 25, 1);
-
-function useStockholmClock(): void {
- vi.spyOn(Date.prototype, 'getTimezoneOffset').mockImplementation(function (this: Date) {
- const time = this.getTime();
- return time >= STOCKHOLM_SUMMER_TIME_START && time < STOCKHOLM_SUMMER_TIME_END ? -120 : -60;
- });
-}
-
-function computedEntry(frecency: number): ChannelFrecencyEntry {
- return {totalUses: 1, recentUses: [NOW], frecency, score: frecency};
-}
-
-function keyFor(index: number): string {
- return `1400000000000000${String(index).padStart(3, '0')}`;
-}
-
-afterEach(() => {
- vi.restoreAllMocks();
- vi.useRealTimers();
-});
-
-describe('channelFrecencyWeight', () => {
- it.each([
- [0, 100],
- [1, 70],
- [2, 50],
- [3, 50],
- [4, 30],
- [6, 30],
- [7, 10],
- [365, 10],
- [-1, 1],
- [-3, 1],
- ])('weights an age of %i days as %i', (dayDiff, weight) => {
- expect(channelFrecencyWeight(dayDiff)).toBe(weight);
- });
-});
-
-describe('channelFrecencyDayDiff', () => {
- it('counts whole elapsed days and truncates toward zero', () => {
- expect(channelFrecencyDayDiff(NOW, NOW - 23 * HOUR_MS)).toBe(0);
- expect(channelFrecencyDayDiff(NOW, NOW - 25 * HOUR_MS)).toBe(1);
- expect(channelFrecencyDayDiff(NOW, NOW - 6 * DAY_MS - 23 * HOUR_MS)).toBe(6);
- expect(channelFrecencyDayDiff(NOW, NOW + 12 * HOUR_MS)).toBe(0);
- expect(channelFrecencyDayDiff(NOW, NOW + 36 * HOUR_MS)).toBe(-1);
- });
-
- it('counts noon to noon across the spring clock change as one day although only 23 hours pass', () => {
- useStockholmClock();
- const saturdayNoon = Date.UTC(2026, 2, 28, 11);
- const sundayNoon = Date.UTC(2026, 2, 29, 10);
- expect(sundayNoon - saturdayNoon).toBe(23 * HOUR_MS);
- expect(channelFrecencyDayDiff(sundayNoon, saturdayNoon)).toBe(1);
- expect(channelFrecencyWeight(channelFrecencyDayDiff(sundayNoon, saturdayNoon))).toBe(70);
- });
-
- it('keeps 24.5 hours across the autumn clock change inside the same day', () => {
- useStockholmClock();
- const saturdayNoon = Date.UTC(2026, 9, 24, 10);
- const sundayHalfPastEleven = Date.UTC(2026, 9, 25, 10, 30);
- expect(sundayHalfPastEleven - saturdayNoon).toBe(24.5 * HOUR_MS);
- expect(channelFrecencyDayDiff(sundayHalfPastEleven, saturdayNoon)).toBe(0);
- });
-});
-
-describe('trackChannelUse', () => {
- it('starts a new key with one uncomputed use', () => {
- const history: ChannelFrecencyHistory = new Map();
- trackChannelUse(history, CHANNEL_ID, NOW);
- expect(history.get(CHANNEL_ID)).toEqual({totalUses: 1, recentUses: [NOW], frecency: -1, score: 0});
- });
-
- it('keeps arrival order for untimed uses and sorts when a timestamp is given', () => {
- vi.useFakeTimers();
- const history: ChannelFrecencyHistory = new Map();
- vi.setSystemTime(NOW);
- trackChannelUse(history, CHANNEL_ID);
- vi.setSystemTime(NOW - HOUR_MS);
- trackChannelUse(history, CHANNEL_ID);
- expect(history.get(CHANNEL_ID)?.recentUses).toEqual([NOW, NOW - HOUR_MS]);
- trackChannelUse(history, CHANNEL_ID, NOW - 2 * HOUR_MS);
- expect(history.get(CHANNEL_ID)?.recentUses).toEqual([NOW - 2 * HOUR_MS, NOW - HOUR_MS, NOW]);
- expect(history.get(CHANNEL_ID)?.totalUses).toBe(3);
- });
-});
-
-describe('computeChannelFrecency', () => {
- it('scores 12 uses whose last 10 are 4 today, 3 yesterday and 3 five days ago as 840', () => {
- const history: ChannelFrecencyHistory = new Map();
- const uses = [
- NOW - 20 * DAY_MS,
- NOW - 20 * DAY_MS,
- NOW - 5 * DAY_MS - HOUR_MS,
- NOW - 5 * DAY_MS - 2 * HOUR_MS,
- NOW - 5 * DAY_MS - 3 * HOUR_MS,
- NOW - DAY_MS - HOUR_MS,
- NOW - DAY_MS - 2 * HOUR_MS,
- NOW - DAY_MS - 3 * HOUR_MS,
- NOW - HOUR_MS,
- NOW - 2 * HOUR_MS,
- NOW - 3 * HOUR_MS,
- NOW - 4 * HOUR_MS,
- ];
- for (const use of uses) {
- trackChannelUse(history, CHANNEL_ID, use);
- }
- computeChannelFrecency(history, NOW);
- expect(history.get(CHANNEL_ID)).toEqual({
- totalUses: 12,
- recentUses: [
- NOW - 5 * DAY_MS - 3 * HOUR_MS,
- NOW - 5 * DAY_MS - 2 * HOUR_MS,
- NOW - 5 * DAY_MS - HOUR_MS,
- NOW - DAY_MS - 3 * HOUR_MS,
- NOW - DAY_MS - 2 * HOUR_MS,
- NOW - DAY_MS - HOUR_MS,
- NOW - 4 * HOUR_MS,
- NOW - 3 * HOUR_MS,
- NOW - 2 * HOUR_MS,
- NOW - HOUR_MS,
- ],
- frecency: 840,
- score: 700,
- });
- });
-
- it('leaves computed entries alone until the key is used again', () => {
- const history: ChannelFrecencyHistory = new Map();
- trackChannelUse(history, CHANNEL_ID, NOW - 8 * DAY_MS);
- computeChannelFrecency(history, NOW - 8 * DAY_MS);
- const computed = history.get(CHANNEL_ID);
- expect(computed?.frecency).toBe(100);
- computeChannelFrecency(history, NOW);
- expect(history.get(CHANNEL_ID)).toBe(computed);
- trackChannelUse(history, CHANNEL_ID, NOW);
- computeChannelFrecency(history, NOW);
- expect(history.get(CHANNEL_ID)).toEqual({
- totalUses: 2,
- recentUses: [NOW - 8 * DAY_MS, NOW],
- frecency: 110,
- score: 110,
- });
- });
-});
-
-describe('capChannelFrecencyHistory', () => {
- it('drops the key whose last use is oldest once there are more than 100 keys', () => {
- const history: ChannelFrecencyHistory = new Map();
- trackChannelUse(history, keyFor(0), NOW - 10 * DAY_MS);
- trackChannelUse(history, keyFor(0), NOW + 500);
- for (let index = 1; index <= 100; index++) {
- trackChannelUse(history, keyFor(index), NOW + index);
- }
- capChannelFrecencyHistory(history);
- expect(history.size).toBe(100);
- expect(history.has(keyFor(0))).toBe(true);
- expect(history.has(keyFor(1))).toBe(false);
- });
-
- it('drops the earlier key when two share the oldest last use', () => {
- const history: ChannelFrecencyHistory = new Map();
- trackChannelUse(history, keyFor(0), NOW);
- trackChannelUse(history, keyFor(1), NOW);
- for (let index = 2; index <= 100; index++) {
- trackChannelUse(history, keyFor(index), NOW + index);
- }
- capChannelFrecencyHistory(history);
- expect(history.has(keyFor(0))).toBe(false);
- expect(history.has(keyFor(1))).toBe(true);
- });
-});
-
-describe('rankFrequentChannelIds', () => {
- it('sorts resolved ids by frecency, keeps key order on ties and drops unresolved keys', () => {
- const history: ChannelFrecencyHistory = new Map([
- ['a', computedEntry(100)],
- ['b', computedEntry(300)],
- ['c', computedEntry(100)],
- ['user', computedEntry(200)],
- ['gone', computedEntry(999)],
- ]);
- const resolved = new Map([
- ['a', 'a'],
- ['b', 'b'],
- ['c', 'c'],
- ['user', 'dm-channel'],
- ]);
- expect(rankFrequentChannelIds(history, (key) => resolved.get(key) ?? null)).toEqual(['b', 'dm-channel', 'a', 'c']);
- });
-
- it('returns at most 100 ids', () => {
- const history: ChannelFrecencyHistory = new Map();
- for (let index = 0; index < 150; index++) {
- history.set(keyFor(index), computedEntry(100));
- }
- const ranked = rankFrequentChannelIds(history, (key) => key);
- expect(ranked).toHaveLength(100);
- expect(ranked[99]).toBe(keyFor(99));
- });
-});
-
-describe('restoreChannelFrecencyHistory', () => {
- it('re-derives every persisted entry against now and drops unusable ones', () => {
- const persisted: ReadonlyArray<readonly [unknown, unknown]> = [
- ['a', {totalUses: 5, recentUses: [NOW - 8 * DAY_MS - HOUR_MS, NOW - 8 * DAY_MS], frecency: 999, score: 999}],
- ['b', {totalUses: 2, recentUses: [], frecency: 50, score: 50}],
- ['c', {totalUses: 'many', recentUses: [NOW]}],
- ['d', {totalUses: 1, recentUses: [NOW - HOUR_MS, 'soon', -5, null], frecency: 1, score: 1}],
- [42, {totalUses: 1, recentUses: [NOW]}],
- ['e', null],
- ];
- const restored = restoreChannelFrecencyHistory(persisted, NOW);
- expect([...restored.keys()]).toEqual(['a', 'd']);
- expect(restored.get('a')).toEqual({
- totalUses: 5,
- recentUses: [NOW - 8 * DAY_MS - HOUR_MS, NOW - 8 * DAY_MS],
- frecency: 50,
- score: 20,
- });
- expect(restored.get('d')).toEqual({totalUses: 1, recentUses: [NOW - HOUR_MS], frecency: 100, score: 100});
- });
-});
-
-describe('channel frecency account sync', () => {
- it('carries only the uses over the wire and re-derives on the way back', () => {
- const history: ChannelFrecencyHistory = new Map();
- trackChannelUse(history, 'a', NOW - HOUR_MS);
- trackChannelUse(history, 'a', NOW);
- computeChannelFrecency(history, NOW);
- const usage = channelFrecencyHistoryToWire(history);
- expect(usage).toEqual({a: {totalUses: 2, recentUsesMs: [BigInt(NOW - HOUR_MS), BigInt(NOW)]}});
- const restored = channelFrecencyHistoryFromWire(usage, NOW);
- expect(restored.get('a')).toEqual({
- totalUses: 2,
- recentUses: [NOW - HOUR_MS, NOW],
- frecency: 200,
- score: 200,
- });
- });
-
- it('drops wire entries whose uses have all aged out of scoring', () => {
- const restored = channelFrecencyHistoryFromWire({a: {totalUses: 3, recentUsesMs: []}}, NOW);
- expect(restored.size).toBe(0);
- });
-
- it('merges two devices by keeping the higher count and the newest ten uses', () => {
- const merged = mergeChannelFrecencyWireUsage(
- {
- a: {totalUses: 9, recentUsesMs: [BigInt(NOW - 2 * DAY_MS), BigInt(NOW - HOUR_MS)]},
- b: {totalUses: 1, recentUsesMs: [BigInt(NOW - HOUR_MS)]},
- },
- {
- a: {totalUses: 4, recentUsesMs: [BigInt(NOW - HOUR_MS), BigInt(NOW)]},
- c: {totalUses: 2, recentUsesMs: [BigInt(NOW)]},
- },
- NOW,
- );
- expect(merged.a).toEqual({
- totalUses: 9,
- recentUsesMs: [BigInt(NOW - 2 * DAY_MS), BigInt(NOW - HOUR_MS), BigInt(NOW)],
- });
- expect(Object.keys(merged).sort()).toEqual(['a', 'b', 'c']);
- });
-
- it('keeps at most ten uses and a hundred keys when merging', () => {
- const uses = Array.from({length: 8}, (_value, index) => BigInt(NOW - index * HOUR_MS));
- const local: Record<string, {totalUses: number; recentUsesMs: Array<bigint>}> = {};
- const incoming: Record<string, {totalUses: number; recentUsesMs: Array<bigint>}> = {};
- for (let index = 0; index < 60; index++) {
- local[keyFor(index)] = {totalUses: 1, recentUsesMs: [BigInt(NOW - index * HOUR_MS)]};
- }
- for (let index = 60; index < 130; index++) {
- incoming[keyFor(index)] = {totalUses: 1, recentUsesMs: [BigInt(NOW - index * HOUR_MS)]};
- }
- local.a = {totalUses: 20, recentUsesMs: uses};
- incoming.a = {totalUses: 20, recentUsesMs: [BigInt(NOW + HOUR_MS), BigInt(NOW + 2 * HOUR_MS), BigInt(NOW)]};
- const merged = mergeChannelFrecencyWireUsage(local, incoming, NOW);
- expect(merged.a.recentUsesMs).toHaveLength(10);
- expect(Object.keys(merged)).toHaveLength(100);
- });
-});
diff --git a/fluxer_app/src/features/channel/utils/ChannelSearchPolling.test.ts b/fluxer_app/src/features/channel/utils/ChannelSearchPolling.test.ts
deleted file mode 100644
index ede42ae13..000000000
--- a/fluxer_app/src/features/channel/utils/ChannelSearchPolling.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- CHANNEL_SEARCH_INDEXING_INITIAL_POLL_INTERVAL_MS,
- CHANNEL_SEARCH_INDEXING_MAX_POLL_INTERVAL_MS,
- getChannelSearchIndexingPollInterval,
-} from '@app/features/channel/utils/ChannelSearchPolling';
-import {describe, expect, it} from 'vitest';
-
-describe('getChannelSearchIndexingPollInterval', () => {
- it('starts with a short retry interval for newly indexing channels', () => {
- expect(getChannelSearchIndexingPollInterval(0)).toBe(CHANNEL_SEARCH_INDEXING_INITIAL_POLL_INTERVAL_MS);
- });
- it('backs off without exceeding the maximum interval', () => {
- expect(getChannelSearchIndexingPollInterval(1)).toBeGreaterThan(CHANNEL_SEARCH_INDEXING_INITIAL_POLL_INTERVAL_MS);
- expect(getChannelSearchIndexingPollInterval(100)).toBe(CHANNEL_SEARCH_INDEXING_MAX_POLL_INTERVAL_MS);
- });
- it('treats negative poll counts as the first poll', () => {
- expect(getChannelSearchIndexingPollInterval(-1)).toBe(CHANNEL_SEARCH_INDEXING_INITIAL_POLL_INTERVAL_MS);
- });
-});
diff --git a/fluxer_app/src/features/code_highlighting/utils/ArboriumThemeBridge.test.ts b/fluxer_app/src/features/code_highlighting/utils/ArboriumThemeBridge.test.ts
deleted file mode 100644
index f8ae4c236..000000000
--- a/fluxer_app/src/features/code_highlighting/utils/ArboriumThemeBridge.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync, statSync} from 'node:fs';
-import {createRequire} from 'node:module';
-import {fileURLToPath} from 'node:url';
-import {describe, expect, it} from 'vitest';
-
-const require = createRequire(import.meta.url);
-const bridgeCss = readFileSync(new URL('./ArboriumThemeBridge.css', import.meta.url), 'utf8');
-const highlightingSource = readFileSync(new URL('./ArboriumHighlighting.ts', import.meta.url), 'utf8');
-const upstreamBaseCss = readFileSync(require.resolve('@arborium/arborium/themes/base.css'), 'utf8');
-
-function escapeRegExp(value: string): string {
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-}
-
-function getRuleBody(selector: string): string {
- const match = new RegExp(`(?:^|\\n)${escapeRegExp(selector)} \\{\\n([\\s\\S]*?)\\n\\}`, 'u').exec(bridgeCss);
- expect(match).not.toBeNull();
- return match?.[1] ?? '';
-}
-
-function listCssFiles(directory: URL): Array<string> {
- const absoluteDirectory = fileURLToPath(directory);
- const files: Array<string> = [];
- for (const entry of readdirSync(absoluteDirectory)) {
- const absoluteEntry = `${absoluteDirectory}/${entry}`;
- const stat = statSync(absoluteEntry);
- if (stat.isDirectory()) {
- files.push(...listCssFiles(new URL(`${entry}/`, directory)));
- continue;
- }
- if (entry.endsWith('.css')) {
- files.push(absoluteEntry);
- }
- }
- return files;
-}
-
-function listSelectors(css: string, pattern: RegExp): Array<string> {
- return Array.from(new Set(Array.from(css.matchAll(pattern), (match) => match[1] as string))).sort((left, right) =>
- left.localeCompare(right),
- );
-}
-
-describe('ArboriumThemeBridge', () => {
- it('does not use Arborium system color-scheme switching', () => {
- expect(highlightingSource).not.toContain('@arborium/arborium/themes/base.css');
- expect(bridgeCss).not.toContain('prefers-color-scheme');
- expect(bridgeCss).not.toContain('theme-dark');
- expect(bridgeCss).not.toContain('data-theme');
- });
-
- it('keeps app CSS off system dark-mode media queries', () => {
- const cssFiles = listCssFiles(new URL('../../../', import.meta.url));
- expect(cssFiles.length).toBeGreaterThan(0);
- for (const file of cssFiles) {
- expect(readFileSync(file, 'utf8'), file).not.toContain('prefers-color-scheme: dark');
- }
- });
-
- it('uses dark token styles by default and light styles only under theme-light', () => {
- expect(getRuleBody('a-s')).toContain('color: var(--arb-s-dark);');
- expect(getRuleBody('html.theme-light a-s')).toContain('color: var(--arb-s-light);');
- });
-
- it('keeps every default token selector covered by a theme-light override', () => {
- const defaultSelectors = listSelectors(bridgeCss, /^(a-[\w-]+) \{/gm);
- const lightSelectors = listSelectors(bridgeCss, /^html\.theme-light (a-[\w-]+) \{/gm);
- const upstreamSelectors = listSelectors(upstreamBaseCss, /^\s*(a-[\w-]+) \{/gm);
-
- expect(defaultSelectors.length).toBeGreaterThan(0);
- expect(defaultSelectors).toEqual(upstreamSelectors);
- expect(lightSelectors).toEqual(upstreamSelectors);
- });
-});
diff --git a/fluxer_app/src/features/discovery/state/Discovery.test.ts b/fluxer_app/src/features/discovery/state/Discovery.test.ts
deleted file mode 100644
index 33ed6b121..000000000
--- a/fluxer_app/src/features/discovery/state/Discovery.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {DiscoveryGuild, DiscoverySearchResponse} from '@app/features/discovery/commands/DiscoveryCommands';
-import * as DiscoveryCommands from '@app/features/discovery/commands/DiscoveryCommands';
-import Discovery from '@app/features/discovery/state/Discovery';
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/discovery/commands/DiscoveryCommands', () => ({
- searchGuilds: vi.fn(),
- getCategories: vi.fn(),
-}));
-
-function guild(id: string, memberCount: number): DiscoveryGuild {
- return {
- id,
- name: `Guild ${id}`,
- icon: null,
- banner: null,
- description: null,
- category_type: 0,
- primary_language: null,
- custom_tags: [],
- member_count: memberCount,
- online_count: 0,
- features: [],
- verification_level: 0,
- };
-}
-
-function page(guilds: Array<DiscoveryGuild>, total: number): DiscoverySearchResponse {
- return {guilds, total, categoryCounts: null};
-}
-
-describe('Discovery.search', () => {
- beforeEach(() => {
- vi.mocked(DiscoveryCommands.searchGuilds).mockReset();
- Discovery.reset();
- });
-
- test('does not append a guild that a previous page already returned', async () => {
- vi.mocked(DiscoveryCommands.searchGuilds)
- .mockResolvedValueOnce(page([guild('1', 50), guild('2', 40)], 4))
- .mockResolvedValueOnce(page([guild('2', 40), guild('3', 30)], 4));
- await Discovery.search({limit: 2, offset: 0});
- await Discovery.search({limit: 2, offset: Discovery.loadedCount});
- expect(Discovery.guilds.map((entry) => entry.id)).toEqual(['1', '2', '3']);
- });
-
- test('advances the pagination offset by what the server returned, not by what survived deduping', async () => {
- vi.mocked(DiscoveryCommands.searchGuilds)
- .mockResolvedValueOnce(page([guild('1', 50), guild('2', 40)], 4))
- .mockResolvedValueOnce(page([guild('2', 40), guild('3', 30)], 4));
- await Discovery.search({limit: 2, offset: 0});
- await Discovery.search({limit: 2, offset: Discovery.loadedCount});
- expect(Discovery.loadedCount).toBe(4);
- });
-});
diff --git a/fluxer_app/src/features/emoji/state/EmojiSearchIndex.test.ts b/fluxer_app/src/features/emoji/state/EmojiSearchIndex.test.ts
deleted file mode 100644
index 6e0006d32..000000000
--- a/fluxer_app/src/features/emoji/state/EmojiSearchIndex.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createEmojiSearchIndex} from '@app/features/emoji/state/EmojiSearchIndex';
-import type {FlatEmoji} from '@app/features/emoji/types/EmojiTypes';
-import {describe, expect, test} from 'vitest';
-
-function emoji(name: string, options: Partial<FlatEmoji> = {}): FlatEmoji {
- return {
- name,
- uniqueName: options.uniqueName ?? name,
- allNamesString: `:${name}:`,
- keywords: options.keywords,
- id: options.id,
- guildId: options.guildId,
- };
-}
-
-describe('EmojiSearchIndex', () => {
- test('orders exact, prefix, boundary, contains, and keyword matches', () => {
- const index = createEmojiSearchIndex([
- emoji('black_heart'),
- emoji('heart'),
- emoji('red_heart'),
- emoji('party_parrot', {keywords: ['celebration', 'heartfelt']}),
- ]);
-
- expect(index.search('heart').map((result) => result.name)).toEqual([
- 'heart',
- 'black_heart',
- 'red_heart',
- 'party_parrot',
- ]);
- });
-
- test('uses n-gram candidates for short and long substring queries', () => {
- const index = createEmojiSearchIndex([emoji('party_parrot'), emoji('rocket'), emoji('sparkles')]);
-
- expect(index.search('ar').map((result) => result.name)).toEqual(['party_parrot', 'sparkles']);
- expect(index.search('rro').map((result) => result.name)).toEqual(['party_parrot']);
- });
-
- test('applies availability filtering before top-k ranking', () => {
- const index = createEmojiSearchIndex([
- emoji('party_a', {id: '1', guildId: 'guild'}),
- emoji('party_b', {id: '2', guildId: 'guild'}),
- emoji('party_c', {id: '3', guildId: 'guild'}),
- ]);
-
- const results = index.search('party', {
- count: 2,
- canUse: (result) => result.id !== '2',
- getFrecencyScore: (result) => (result.id === '3' ? 10 : 1),
- });
-
- expect(results.map((result) => result.id)).toEqual(['3', '1']);
- });
-
- test('reports compact index stats for benchmarks and regression checks', () => {
- const index = createEmojiSearchIndex([
- emoji('thumbsup', {keywords: ['approve', 'yes']}),
- emoji('thumbsdown', {keywords: ['reject', 'no']}),
- ]);
-
- expect(index.getStats()).toMatchObject({
- emojiCount: 2,
- });
- expect(index.getStats().gramCount).toBeGreaterThan(0);
- expect(index.getStats().postingCount).toBeGreaterThanOrEqual(index.getStats().gramCount);
- });
-});
diff --git a/fluxer_app/src/features/emoji/state/UsageFrecency.test.ts b/fluxer_app/src/features/emoji/state/UsageFrecency.test.ts
deleted file mode 100644
index 6024cc162..000000000
--- a/fluxer_app/src/features/emoji/state/UsageFrecency.test.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- bumpUsageEntry,
- dedupeBoundedIds,
- isValidUsageKey,
- MAX_TRACKED_USAGE_KEYS,
- MAX_USAGE_COUNT,
- MAX_USAGE_KEY_LENGTH,
- mergeWireUsageMaps,
- rankUsageMap,
- sanitizeUsageEntry,
- sanitizeUsageMap,
- USAGE_FRECENCY_HALF_LIFE_MS,
- type UsageEntry,
- usageFrecencyScore,
-} from '@app/features/emoji/state/UsageFrecency';
-import {describe, expect, it} from 'vitest';
-
-const NOW = 1_750_000_000_000;
-
-function entry(count: number, lastUsed: number): UsageEntry {
- return {count, lastUsed};
-}
-
-describe('usageFrecencyScore', () => {
- it('scores higher counts above lower counts at equal recency', () => {
- expect(usageFrecencyScore(entry(10, NOW), NOW)).toBeGreaterThan(usageFrecencyScore(entry(2, NOW), NOW));
- });
-
- it('scores recent use above stale use at equal counts', () => {
- const fresh = usageFrecencyScore(entry(5, NOW), NOW);
- const stale = usageFrecencyScore(entry(5, NOW - 30 * 24 * 60 * 60 * 1000), NOW);
- expect(fresh).toBeGreaterThan(stale);
- });
-
- it('halves the score after one half-life', () => {
- const fresh = usageFrecencyScore(entry(5, NOW), NOW);
- const aged = usageFrecencyScore(entry(5, NOW - USAGE_FRECENCY_HALF_LIFE_MS), NOW);
- expect(aged).toBeCloseTo(fresh / 2, 10);
- });
-
- it('treats future timestamps as zero age', () => {
- expect(usageFrecencyScore(entry(5, NOW + 60_000), NOW)).toBe(usageFrecencyScore(entry(5, NOW), NOW));
- });
-
- it('is deterministic for a fixed now', () => {
- const a = usageFrecencyScore(entry(7, NOW - 1234), NOW);
- const b = usageFrecencyScore(entry(7, NOW - 1234), NOW);
- expect(a).toBe(b);
- });
-});
-
-describe('sanitizeUsageEntry', () => {
- it('passes through sane entries unchanged', () => {
- expect(sanitizeUsageEntry(entry(3, NOW - 1000), NOW)).toEqual(entry(3, NOW - 1000));
- });
-
- it('drops non-finite and non-positive counts', () => {
- expect(sanitizeUsageEntry(entry(Number.NaN, NOW), NOW)).toBeNull();
- expect(sanitizeUsageEntry(entry(Number.POSITIVE_INFINITY, NOW), NOW)).toBeNull();
- expect(sanitizeUsageEntry(entry(0, NOW), NOW)).toBeNull();
- expect(sanitizeUsageEntry(entry(-5, NOW), NOW)).toBeNull();
- });
-
- it('drops entries with non-finite timestamps', () => {
- expect(sanitizeUsageEntry(entry(3, Number.NaN), NOW)).toBeNull();
- });
-
- it('clamps counts to the maximum', () => {
- expect(sanitizeUsageEntry(entry(MAX_USAGE_COUNT * 2, NOW), NOW)?.count).toBe(MAX_USAGE_COUNT);
- });
-
- it('clamps future timestamps to now and negative timestamps to zero', () => {
- expect(sanitizeUsageEntry(entry(3, NOW + 999_999), NOW)?.lastUsed).toBe(NOW);
- expect(sanitizeUsageEntry(entry(3, -50), NOW)?.lastUsed).toBe(0);
- });
-
- it('is idempotent', () => {
- const once = sanitizeUsageEntry(entry(3.7, NOW + 5000), NOW);
- expect(once).not.toBeNull();
- expect(sanitizeUsageEntry(once!, NOW)).toEqual(once);
- });
-});
-
-describe('bumpUsageEntry', () => {
- it('starts at one for unseen keys', () => {
- expect(bumpUsageEntry(undefined, NOW)).toEqual(entry(1, NOW));
- });
-
- it('increments and refreshes recency', () => {
- expect(bumpUsageEntry(entry(4, NOW - 1000), NOW)).toEqual(entry(5, NOW));
- });
-
- it('saturates at the maximum count', () => {
- expect(bumpUsageEntry(entry(MAX_USAGE_COUNT, NOW - 1000), NOW)).toEqual(entry(MAX_USAGE_COUNT, NOW));
- });
-});
-
-describe('sanitizeUsageMap', () => {
- it('drops invalid keys and entries', () => {
- const sanitized = sanitizeUsageMap(
- {
- '': entry(3, NOW),
- ['x'.repeat(MAX_USAGE_KEY_LENGTH + 1)]: entry(3, NOW),
- 'unicode:bad': entry(0, NOW),
- 'unicode:good': entry(2, NOW - 500),
- },
- NOW,
- );
- expect(Object.keys(sanitized)).toEqual(['unicode:good']);
- });
-
- it('prunes the lowest-scoring entries beyond the cap', () => {
- const usage: Record<string, UsageEntry> = {};
- for (let i = 0; i < MAX_TRACKED_USAGE_KEYS + 50; i++) {
- usage[`unicode:e${i}`] = entry(i + 1, NOW - i * 1000);
- }
- const sanitized = sanitizeUsageMap(usage, NOW);
- expect(Object.keys(sanitized)).toHaveLength(MAX_TRACKED_USAGE_KEYS);
- expect(sanitized[`unicode:e${MAX_TRACKED_USAGE_KEYS + 49}`]).toBeDefined();
- expect(sanitized['unicode:e0']).toBeUndefined();
- });
-
- it('is idempotent on already-sane maps', () => {
- const usage = {
- 'unicode:a': entry(3, NOW - 100),
- 'unicode:b': entry(9, NOW - 50),
- };
- const once = sanitizeUsageMap(usage, NOW);
- expect(sanitizeUsageMap(once, NOW + 1000)).toEqual(once);
- });
-});
-
-describe('rankUsageMap', () => {
- it('ranks by score descending', () => {
- const ranking = rankUsageMap(
- {
- 'unicode:rare': entry(1, NOW - 20 * 24 * 60 * 60 * 1000),
- 'unicode:hot': entry(20, NOW),
- 'unicode:warm': entry(5, NOW - 1000),
- },
- NOW,
- 1,
- );
- expect(ranking.rankedKeys).toEqual(['unicode:hot', 'unicode:warm', 'unicode:rare']);
- expect(ranking.version).toBe(1);
- expect(ranking.scoreByKey.get('unicode:hot')).toBeGreaterThan(ranking.scoreByKey.get('unicode:warm')!);
- });
-
- it('breaks score ties by recency, then count, then key', () => {
- const ranking = rankUsageMap(
- {
- 'unicode:b': entry(3, NOW),
- 'unicode:a': entry(3, NOW),
- 'unicode:newer': entry(3, NOW + 1),
- },
- NOW,
- 1,
- );
- expect(ranking.rankedKeys[0]).toBe('unicode:newer');
- expect(ranking.rankedKeys.slice(1)).toEqual(['unicode:a', 'unicode:b']);
- });
-
- it('produces identical rankings for identical inputs', () => {
- const usage = {
- 'unicode:a': entry(3, NOW - 5000),
- 'unicode:b': entry(7, NOW - 9000),
- 'unicode:c': entry(1, NOW - 100),
- };
- const first = rankUsageMap(usage, NOW, 1);
- const second = rankUsageMap(usage, NOW, 2);
- expect(second.rankedKeys).toEqual(first.rankedKeys);
- });
-
- it('returns frozen rankings', () => {
- const ranking = rankUsageMap({'unicode:a': entry(1, NOW)}, NOW, 1);
- expect(Object.isFrozen(ranking)).toBe(true);
- expect(Object.isFrozen(ranking.rankedKeys)).toBe(true);
- });
-});
-
-describe('mergeWireUsageMaps', () => {
- it('takes the maximum count and recency per key', () => {
- const merged = mergeWireUsageMaps(
- {
- 'unicode:a': {count: 5, lastUsedMs: BigInt(NOW - 1000)},
- 'unicode:local': {count: 2, lastUsedMs: BigInt(NOW)},
- },
- {
- 'unicode:a': {count: 3, lastUsedMs: BigInt(NOW)},
- 'unicode:remote': {count: 9, lastUsedMs: BigInt(NOW - 50)},
- },
- NOW,
- );
- expect(merged['unicode:a']).toEqual({count: 5, lastUsedMs: BigInt(NOW)});
- expect(merged['unicode:local']).toEqual({count: 2, lastUsedMs: BigInt(NOW)});
- expect(merged['unicode:remote']).toEqual({count: 9, lastUsedMs: BigInt(NOW - 50)});
- });
-
- it('is idempotent when merging a map with itself', () => {
- const map = {
- 'unicode:a': {count: 5, lastUsedMs: BigInt(NOW - 1000)},
- 'unicode:b': {count: 1, lastUsedMs: BigInt(NOW - 2000)},
- };
- expect(mergeWireUsageMaps(map, map, NOW)).toEqual(map);
- });
-
- it('bounds the merged result', () => {
- const local: Record<string, {count: number; lastUsedMs: bigint}> = {};
- const incoming: Record<string, {count: number; lastUsedMs: bigint}> = {};
- for (let i = 0; i < MAX_TRACKED_USAGE_KEYS; i++) {
- local[`unicode:l${i}`] = {count: i + 1, lastUsedMs: BigInt(NOW)};
- incoming[`unicode:r${i}`] = {count: i + 1, lastUsedMs: BigInt(NOW)};
- }
- const merged = mergeWireUsageMaps(local, incoming, NOW);
- expect(Object.keys(merged)).toHaveLength(MAX_TRACKED_USAGE_KEYS);
- });
-
- it('drops junk entries from either side', () => {
- const merged = mergeWireUsageMaps(
- {'unicode:ok': {count: 1, lastUsedMs: BigInt(NOW)}},
- {'': {count: 1, lastUsedMs: BigInt(NOW)}, 'unicode:zero': {count: 0, lastUsedMs: BigInt(NOW)}},
- NOW,
- );
- expect(Object.keys(merged)).toEqual(['unicode:ok']);
- });
-});
-
-describe('isValidUsageKey', () => {
- it('rejects empty and oversized keys', () => {
- expect(isValidUsageKey('')).toBe(false);
- expect(isValidUsageKey('x'.repeat(MAX_USAGE_KEY_LENGTH))).toBe(true);
- expect(isValidUsageKey('x'.repeat(MAX_USAGE_KEY_LENGTH + 1))).toBe(false);
- });
-});
-
-describe('dedupeBoundedIds', () => {
- it('preserves order, removes duplicates, and applies the cap', () => {
- expect(dedupeBoundedIds(['a', 'b', 'a', 'c', 'b', 'd'], 3)).toEqual(['a', 'b', 'c']);
- });
-
- it('drops empty and oversized ids', () => {
- expect(dedupeBoundedIds(['', 'ok', 'x'.repeat(MAX_USAGE_KEY_LENGTH + 1)], 10)).toEqual(['ok']);
- });
-});
diff --git a/fluxer_app/src/features/expressions/commands/ExpressionSourceCommands.test.ts b/fluxer_app/src/features/expressions/commands/ExpressionSourceCommands.test.ts
deleted file mode 100644
index f29b06f98..000000000
--- a/fluxer_app/src/features/expressions/commands/ExpressionSourceCommands.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const {getMock} = vi.hoisted(() => ({getMock: vi.fn()}));
-
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {get: getMock},
-}));
-vi.mock('@app/features/platform/utils/ResponseInspection', () => ({
- failureCode: (error: unknown) => (error as {code?: string}).code,
-}));
-
-const {fetchExpressionSource} = await import('@app/features/expressions/commands/ExpressionSourceCommands');
-
-const SOURCE_BODY = {id: '20', name: 'Blob Club', icon: 'hash', features: ['DISCOVERABLE']};
-
-describe('fetchExpressionSource', () => {
- afterEach(() => {
- getMock.mockReset();
- });
-
- it.each([
- ['emoji', '/emojis/10/source'],
- ['sticker', '/stickers/10/source'],
- ] as const)('returns the %s source community from its endpoint', async (kind, path) => {
- getMock.mockResolvedValue({body: SOURCE_BODY});
- await expect(fetchExpressionSource(kind, '10')).resolves.toEqual({available: true, guild: SOURCE_BODY});
- expect(getMock).toHaveBeenCalledWith(path);
- });
-
- it('defaults a missing icon to null', async () => {
- getMock.mockResolvedValue({body: {id: '20', name: 'Blob Club', features: []}});
- await expect(fetchExpressionSource('emoji', '10')).resolves.toEqual({
- available: true,
- guild: {id: '20', name: 'Blob Club', icon: null, features: []},
- });
- });
-
- it('reports an unknown guild as unavailable instead of failing', async () => {
- getMock.mockRejectedValue({code: APIErrorCodes.UNKNOWN_GUILD});
- await expect(fetchExpressionSource('sticker', '10')).resolves.toEqual({available: false});
- });
-
- it('rethrows any other failure', async () => {
- const failure = new Error('gateway timeout');
- getMock.mockRejectedValue(failure);
- await expect(fetchExpressionSource('emoji', '10')).rejects.toBe(failure);
- });
-});
diff --git a/fluxer_app/src/features/expressions/components/ExpressionInfoCard.test.tsx b/fluxer_app/src/features/expressions/components/ExpressionInfoCard.test.tsx
deleted file mode 100644
index d9da4c708..000000000
--- a/fluxer_app/src/features/expressions/components/ExpressionInfoCard.test.tsx
+++ /dev/null
@@ -1,348 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ExpressionKind} from '@app/features/expressions/commands/ExpressionMetadataCommands';
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
-import type React from 'react';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface RemoteGuild {
- id: string;
- name: string;
- icon: string | null;
- features: Array<string>;
-}
-
-interface LocalGuild {
- id: string;
- name: string;
- icon: string | null;
- features: Set<string>;
-}
-
-type SourceState =
- | {status: 'idle'}
- | {status: 'loading'}
- | {status: 'available'; guild: RemoteGuild}
- | {status: 'unavailable'};
-
-const state = vi.hoisted(() => ({
- localGuilds: [] as Array<{id: string; name: string; icon: string | null; features: Set<string>}>,
- memberGuildIds: [] as Array<string>,
- globalExpressions: false,
- source: {status: 'idle'} as {status: string; guild?: unknown},
- selectGuild: vi.fn(),
- joinDiscoveryGuild: vi.fn(() => Promise.resolve()),
- pushWithKey: vi.fn(),
-}));
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: ({children}: {children?: React.ReactNode}) => <span data-flx="test.trans">{children}</span>,
- useLingui: () => ({
- i18n: {
- locale: 'en',
- _: (descriptor: {message?: string}, values?: Record<string, unknown>) =>
- (descriptor.message ?? '').replace(/\{(\w+)\}/gu, (_match, key: string) => String(values?.[key] ?? `{${key}}`)),
- },
- }),
-}));
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {getGuild: (id: string) => state.localGuilds.find((guild) => guild.id === id)},
-}));
-vi.mock('@app/features/guild/state/GuildList', () => ({
- default: {
- get guilds() {
- return state.memberGuildIds.map((id) => ({id}));
- },
- },
-}));
-vi.mock('@app/features/expressions/state/ExpressionSource', () => ({
- default: {
- getSource: () => state.source,
- fetchSource: vi.fn(() => Promise.resolve()),
- },
-}));
-vi.mock('@app/features/expressions/utils/ExpressionPermissionUtils', () => ({
- hasGlobalExpressionsEnabled: () => state.globalExpressions,
-}));
-vi.mock('@app/features/guild/components/popouts/GuildIcon', () => ({
- GuildIcon: ({name}: {name: string}) => <span data-test-guild-icon={name} data-flx="test.guild-icon" />,
-}));
-vi.mock('@app/features/guild/components/GuildBadge', () => ({
- GuildBadge: ({features}: {features: ReadonlyArray<string>}) => (
- <span data-test-guild-badge={[...features].join(',')} data-flx="test.guild-badge" />
- ),
-}));
-vi.mock('@app/features/navigation/commands/NavigationCommands', () => ({selectGuild: state.selectGuild}));
-vi.mock('@app/features/discovery/commands/DiscoveryJoinCommands', () => ({
- joinDiscoveryGuild: state.joinDiscoveryGuild,
-}));
-vi.mock('@app/features/ui/commands/ModalCommands', () => ({
- pushWithKey: state.pushWithKey,
- modal: (render: () => React.ReactElement) => render,
-}));
-vi.mock('@app/features/app/components/dialogs/ConfirmModal', () => ({
- ConfirmModal: ({
- title,
- description,
- primaryText,
- }: {
- title: React.ReactNode;
- description: React.ReactNode;
- primaryText: React.ReactNode;
- }) => (
- <div data-test-confirm-modal="true" data-flx="test.confirm-modal">
- <span data-test-confirm-title="true" data-flx="test.confirm-title">
- {title}
- </span>
- {description}
- <span data-test-confirm-primary="true" data-flx="test.confirm-primary">
- {primaryText}
- </span>
- </div>
- ),
-}));
-
-installVoiceMenuTestBootstrap();
-
-const {ExpressionInfoCard} = await import('@app/features/expressions/components/ExpressionInfoCard');
-
-const GUILD_ID = '20';
-const GUILD_NAME = 'Blob Club';
-const EXPRESSION_ID = '10';
-const DISPLAY_NAMES: Record<ExpressionKind, string> = {emoji: ':blob:', sticker: 'blobsticker'};
-function localGuild(features: Array<string>): LocalGuild {
- return {id: GUILD_ID, name: GUILD_NAME, icon: null, features: new Set(features)};
-}
-
-function setSource(source: SourceState): void {
- state.source = source;
-}
-
-function joinedCommunity(features: Array<string>): void {
- state.localGuilds = [localGuild(features)];
- state.memberGuildIds = [GUILD_ID];
-}
-
-function foreignCommunity(features: Array<string>): void {
- state.localGuilds = [];
- state.memberGuildIds = [];
- setSource({status: 'available', guild: {id: GUILD_ID, name: GUILD_NAME, icon: null, features}});
-}
-
-function renderCard(kind: ExpressionKind, guildId: string | null): string {
- return renderToStaticMarkup(
- <ExpressionInfoCard
- kind={kind}
- expressionId={EXPRESSION_ID}
- guildId={guildId}
- displayName={DISPLAY_NAMES[kind]}
- previewUrl={null}
- data-flx="test.expression-info-card"
- />,
- );
-}
-
-beforeEach(() => {
- state.localGuilds = [];
- state.memberGuildIds = [];
- state.globalExpressions = false;
- setSource({status: 'idle'});
- state.selectGuild.mockClear();
- state.joinDiscoveryGuild.mockClear();
- state.pushWithKey.mockClear();
-});
-
-describe('ExpressionInfoCard description', () => {
- it('describes a default emoji as usable anywhere', () => {
- const markup = renderToStaticMarkup(
- <ExpressionInfoCard
- kind="default_emoji"
- displayName=":smile:"
- previewUrl={null}
- data-flx="test.expression-info-card.default"
- />,
- );
- expect(markup).toContain('A default emoji. You can use it anywhere on Fluxer.');
- });
-
- for (const kind of ['emoji', 'sticker'] as const) {
- it(`describes a ${kind} from a joined community as usable anywhere when global expressions are on`, () => {
- joinedCommunity([]);
- state.globalExpressions = true;
- expect(renderCard(kind, GUILD_ID)).toContain(
- `A custom ${kind} from this community. You can use it anywhere on Fluxer.`,
- );
- });
-
- it(`describes a ${kind} from a joined community as community-only when global expressions are off`, () => {
- joinedCommunity([]);
- expect(renderCard(kind, GUILD_ID)).toContain(
- `A custom ${kind} from this community. You can use it in this community.`,
- );
- });
-
- it(`describes a ${kind} from a discoverable community the viewer has not joined`, () => {
- foreignCommunity([GuildFeatures.DISCOVERABLE]);
- const markup = renderCard(kind, null);
- expect(markup).toContain(`This is a custom ${kind} from a community.`);
- expect(markup).not.toContain('Ask the author');
- });
-
- it(`describes a ${kind} from an invite-only community the viewer has not joined without repeating the footer`, () => {
- foreignCommunity([]);
- const markup = renderCard(kind, null);
- expect(markup).toContain(`This is a custom ${kind} from a community.`);
- expect(markup).not.toContain('Ask the author');
- expect(markup).toContain('Invite-only community');
- });
-
- it(`reports a ${kind} source community that is invite-only or unavailable without naming it`, () => {
- setSource({status: 'unavailable'});
- const markup = renderCard(kind, null);
- expect(markup).toContain(`This is a custom ${kind} from a community.`);
- expect(markup).toContain(kind === 'emoji' ? 'This emoji is from' : 'This sticker is from');
- expect(markup).toContain('A community that is either invite-only or unavailable.');
- expect(markup).not.toContain(GUILD_NAME);
- expect(markup).not.toContain('guild-icon');
- });
-
- it(`labels the source community section for a ${kind}`, () => {
- foreignCommunity([GuildFeatures.DISCOVERABLE]);
- const markup = renderCard(kind, null);
- expect(markup).toContain(kind === 'emoji' ? 'This emoji is from' : 'This sticker is from');
- expect(markup).not.toContain(kind === 'emoji' ? 'This sticker is from' : 'This emoji is from');
- });
-
- it(`keeps the ${kind} description identical while the source community resolves`, () => {
- const expected = `This is a custom ${kind} from a community.`;
- setSource({status: 'loading'});
- const resolving = renderCard(kind, null);
- expect(resolving).toContain(DISPLAY_NAMES[kind]);
- expect(resolving).toContain(expected);
- foreignCommunity([]);
- expect(renderCard(kind, null)).toContain(expected);
- });
- }
-
- it('does not colon-wrap a sticker display name', () => {
- joinedCommunity([]);
- const markup = renderCard('sticker', GUILD_ID);
- expect(markup).toContain('>blobsticker<');
- expect(markup).not.toContain(':blobsticker:');
- });
-});
-
-describe('ExpressionInfoCard community subtitle', () => {
- for (const isMember of [true, false]) {
- const membership = isMember ? 'a joined' : 'a foreign';
- it(`calls ${membership} discoverable community discoverable`, () => {
- if (isMember) {
- joinedCommunity([GuildFeatures.DISCOVERABLE]);
- } else {
- foreignCommunity([GuildFeatures.DISCOVERABLE]);
- }
- const markup = renderCard('emoji', isMember ? GUILD_ID : null);
- expect(markup).toContain('Discoverable community');
- expect(markup).not.toContain('Invite-only community');
- });
-
- it(`calls ${membership} non-discoverable community invite-only`, () => {
- if (isMember) {
- joinedCommunity([]);
- } else {
- foreignCommunity([]);
- }
- const markup = renderCard('emoji', isMember ? GUILD_ID : null);
- expect(markup).toContain('Invite-only community');
- expect(markup).not.toContain('Discoverable community');
- });
- }
-});
-
-describe('ExpressionInfoCard community row', () => {
- let host: HTMLDivElement;
- let root: Root;
-
- function render(guildId: string | null, onClose: () => void): void {
- act(() => {
- root.render(
- <ExpressionInfoCard
- kind="emoji"
- expressionId={EXPRESSION_ID}
- guildId={guildId}
- displayName=":blob:"
- previewUrl={null}
- onClose={onClose}
- data-flx="test.expression-info-card.row"
- />,
- );
- });
- }
-
- beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- });
-
- afterEach(() => {
- act(() => {
- root.unmount();
- });
- host.remove();
- });
-
- it('jumps to a community the viewer is a member of', () => {
- joinedCommunity([GuildFeatures.DISCOVERABLE]);
- const onClose = vi.fn();
- render(GUILD_ID, onClose);
- const button = host.querySelector('button');
- expect(button?.getAttribute('aria-label')).toBe(`Go to ${GUILD_NAME}`);
- act(() => {
- button?.dispatchEvent(new MouseEvent('click', {bubbles: true}));
- });
- expect(state.selectGuild).toHaveBeenCalledWith(GUILD_ID);
- expect(state.pushWithKey).not.toHaveBeenCalled();
- expect(onClose).toHaveBeenCalled();
- });
-
- it('confirms before joining a discoverable community the viewer is not in', async () => {
- foreignCommunity([GuildFeatures.DISCOVERABLE]);
- const onClose = vi.fn();
- render(null, onClose);
- const button = host.querySelector('button');
- expect(button?.getAttribute('aria-label')).toBe(`Join ${GUILD_NAME}`);
- act(() => {
- button?.dispatchEvent(new MouseEvent('click', {bubbles: true}));
- });
- expect(state.selectGuild).not.toHaveBeenCalled();
- expect(onClose).toHaveBeenCalled();
- expect(state.pushWithKey).toHaveBeenCalledTimes(1);
- expect(state.joinDiscoveryGuild).not.toHaveBeenCalled();
- const [renderModal, modalKey] = state.pushWithKey.mock.calls[0] as [() => React.ReactElement, string];
- expect(modalKey).toBe(`expression-source-guild-join-${GUILD_ID}`);
- const modal = renderModal();
- expect(renderToStaticMarkup(modal)).toContain(`Do you want to join ${GUILD_NAME}?`);
- const {onPrimary} = modal.props as {onPrimary: () => Promise<void>};
- await onPrimary();
- expect(state.joinDiscoveryGuild).toHaveBeenCalledWith(GUILD_ID);
- });
-
- it('leaves an invite-only community the viewer is not in unclickable', () => {
- foreignCommunity([]);
- render(null, vi.fn());
- expect(host.querySelector('button')).toBeNull();
- expect(host.querySelector('[tabindex]')).toBeNull();
- expect(host.innerHTML).toContain(GUILD_NAME);
- });
-});
diff --git a/fluxer_app/src/features/expressions/state/ExpressionSource.test.ts b/fluxer_app/src/features/expressions/state/ExpressionSource.test.ts
deleted file mode 100644
index 4bb928b6e..000000000
--- a/fluxer_app/src/features/expressions/state/ExpressionSource.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const {fetchMock} = vi.hoisted(() => ({fetchMock: vi.fn()}));
-
-vi.mock('@app/features/expressions/commands/ExpressionSourceCommands', () => ({
- fetchExpressionSource: fetchMock,
-}));
-
-const {default: ExpressionSource} = await import('@app/features/expressions/state/ExpressionSource');
-
-const GUILD = {id: '20', name: 'Blob Club', icon: null, features: ['DISCOVERABLE']};
-
-describe('ExpressionSource', () => {
- afterEach(() => {
- fetchMock.mockReset();
- });
-
- it('starts idle', () => {
- expect(ExpressionSource.getSource('emoji', 'idle')).toEqual({status: 'idle'});
- });
-
- it('loads and then exposes an available source community', async () => {
- let resolve: (value: unknown) => void = () => undefined;
- fetchMock.mockReturnValue(
- new Promise((next) => {
- resolve = next;
- }),
- );
- const pending = ExpressionSource.fetchSource('emoji', 'available');
- expect(ExpressionSource.getSource('emoji', 'available')).toEqual({status: 'loading'});
- resolve({available: true, guild: GUILD});
- await pending;
- expect(ExpressionSource.getSource('emoji', 'available')).toEqual({status: 'available', guild: GUILD});
- });
-
- it('marks an unavailable source community', async () => {
- fetchMock.mockResolvedValue({available: false});
- await ExpressionSource.fetchSource('sticker', 'unavailable');
- expect(ExpressionSource.getSource('sticker', 'unavailable')).toEqual({status: 'unavailable'});
- });
-
- it('treats a failed lookup as unavailable', async () => {
- fetchMock.mockRejectedValue(new Error('gateway timeout'));
- await ExpressionSource.fetchSource('emoji', 'failed');
- expect(ExpressionSource.getSource('emoji', 'failed')).toEqual({status: 'unavailable'});
- });
-
- it('does not refetch a source community that is loading or resolved', async () => {
- fetchMock.mockResolvedValue({available: true, guild: GUILD});
- await Promise.all([
- ExpressionSource.fetchSource('emoji', 'dedupe'),
- ExpressionSource.fetchSource('emoji', 'dedupe'),
- ]);
- await ExpressionSource.fetchSource('emoji', 'dedupe');
- expect(fetchMock).toHaveBeenCalledTimes(1);
- });
-
- it('keeps emoji and sticker sources with the same id apart', async () => {
- fetchMock.mockResolvedValueOnce({available: true, guild: GUILD}).mockResolvedValueOnce({available: false});
- await ExpressionSource.fetchSource('emoji', 'shared');
- await ExpressionSource.fetchSource('sticker', 'shared');
- expect(ExpressionSource.getSource('emoji', 'shared').status).toBe('available');
- expect(ExpressionSource.getSource('sticker', 'shared').status).toBe('unavailable');
- });
-});
diff --git a/fluxer_app/src/features/expressions/utils/AssetImageGeometry.test.ts b/fluxer_app/src/features/expressions/utils/AssetImageGeometry.test.ts
deleted file mode 100644
index 64b4f4026..000000000
--- a/fluxer_app/src/features/expressions/utils/AssetImageGeometry.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clampWideAssetAspectRatio,
- getAspectRatioRange,
- isAspectRatioInRange,
- isOriginalImageWithinAssetBounds,
- WIDE_ASSET_ASPECT_RATIO_RANGE,
-} from '@app/features/expressions/utils/AssetImageGeometry';
-import {describe, expect, it} from 'vitest';
-
-describe('AssetImageGeometry', () => {
- it('builds the flexible wide asset range from the crop height limits', () => {
- expect(WIDE_ASSET_ASPECT_RATIO_RANGE.min).toBeCloseTo(16 / 9);
- expect(WIDE_ASSET_ASPECT_RATIO_RANGE.max).toBeCloseTo(32 / 9);
- });
-
- it('rejects original images that would bypass crop bounds', () => {
- expect(
- isOriginalImageWithinAssetBounds({width: 540, height: 4320}, WIDE_ASSET_ASPECT_RATIO_RANGE, 2048, 1152),
- ).toBe(false);
- expect(
- isOriginalImageWithinAssetBounds({width: 2048, height: 1152}, WIDE_ASSET_ASPECT_RATIO_RANGE, 2048, 1152),
- ).toBe(true);
- expect(
- isOriginalImageWithinAssetBounds({width: 4096, height: 2304}, WIDE_ASSET_ASPECT_RATIO_RANGE, 2048, 1152),
- ).toBe(false);
- });
-
- it('allows a small tolerance for strict square assets', () => {
- const range = getAspectRatioRange(1);
- expect(isAspectRatioInRange(1, range)).toBe(true);
- expect(isAspectRatioInRange(1.005, range)).toBe(true);
- expect(isAspectRatioInRange(1.05, range)).toBe(false);
- });
-
- it('clamps legacy wide asset ratios into the renderable range', () => {
- expect(clampWideAssetAspectRatio(540 / 4320)).toBeCloseTo(16 / 9);
- expect(clampWideAssetAspectRatio(10)).toBeCloseTo(32 / 9);
- });
-});
diff --git a/fluxer_app/src/features/expressions/utils/ImageUploadFileUtils.test.ts b/fluxer_app/src/features/expressions/utils/ImageUploadFileUtils.test.ts
deleted file mode 100644
index 593ac9c25..000000000
--- a/fluxer_app/src/features/expressions/utils/ImageUploadFileUtils.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getImageUploadMimeType,
- isSvgFile,
- isSvgMimeType,
- normalizeImageMimeType,
-} from '@app/features/expressions/utils/ImageUploadFileUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('ImageUploadFileUtils', () => {
- it('normalizes image MIME type parameters', () => {
- expect(normalizeImageMimeType('IMAGE/SVG+XML; charset=utf-8')).toBe('image/svg+xml');
- });
- it('detects SVG files by MIME type or filename', () => {
- expect(isSvgMimeType('image/svg+xml; charset=utf-8')).toBe(true);
- expect(isSvgFile({type: 'image/svg', name: 'vector'})).toBe(true);
- expect(isSvgFile({type: '', name: 'vector.SVG'})).toBe(true);
- expect(isSvgFile({type: 'image/png', name: 'vector.png'})).toBe(false);
- });
- it('uses a canonical SVG MIME type for uploads', () => {
- expect(getImageUploadMimeType({type: 'image/svg', name: 'vector'})).toBe('image/svg+xml');
- expect(getImageUploadMimeType({type: 'image/webp; charset=utf-8', name: 'image.webp'})).toBe('image/webp');
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayDispatchScheduling.test.ts b/fluxer_app/src/features/gateway/transport/GatewayDispatchScheduling.test.ts
deleted file mode 100644
index cecd6ea3e..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayDispatchScheduling.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- DISPATCH_IDLE_MIN_BUDGET_MS,
- isCriticalGatewayDispatch,
- selectGatewayDispatchFlushMode,
- shouldRetryIdleWait,
- shouldSkipIdleWait,
-} from '@app/features/gateway/transport/GatewayDispatchScheduling';
-import {describe, expect, it} from 'vitest';
-
-describe('selectGatewayDispatchFlushMode', () => {
- it('flushes transport events that carry no dispatch type immediately', () => {
- expect(selectGatewayDispatchFlushMode(null)).toBe('immediate');
- });
-
- it('flushes the session-establishing dispatches immediately', () => {
- expect(selectGatewayDispatchFlushMode('READY')).toBe('immediate');
- expect(selectGatewayDispatchFlushMode('RESUMED')).toBe('immediate');
- });
-
- it('defers ordinary dispatches so an in-flight REST page commits first', () => {
- expect(selectGatewayDispatchFlushMode('MESSAGE_CREATE')).toBe('deferred');
- expect(selectGatewayDispatchFlushMode('TYPING_START')).toBe('deferred');
- expect(selectGatewayDispatchFlushMode('PRESENCE_UPDATE')).toBe('deferred');
- });
-});
-
-describe('isCriticalGatewayDispatch', () => {
- it('treats voice and call dispatches as critical', () => {
- expect(isCriticalGatewayDispatch('VOICE_STATE_UPDATE')).toBe(true);
- expect(isCriticalGatewayDispatch('VOICE_SERVER_UPDATE')).toBe(true);
- expect(isCriticalGatewayDispatch('CALL_CREATE')).toBe(true);
- expect(isCriticalGatewayDispatch('SESSIONS_REPLACE')).toBe(true);
- });
-
- it('does not treat ordinary dispatches as critical', () => {
- expect(isCriticalGatewayDispatch('MESSAGE_CREATE')).toBe(false);
- expect(isCriticalGatewayDispatch('TYPING_START')).toBe(false);
- expect(isCriticalGatewayDispatch(null)).toBe(false);
- });
-});
-
-describe('shouldSkipIdleWait', () => {
- it('skips the idle wait when critical work is queued', () => {
- expect(shouldSkipIdleWait(true, true)).toBe(true);
- });
-
- it('skips the idle wait when the environment has no idle callback', () => {
- expect(shouldSkipIdleWait(false, false)).toBe(true);
- });
-
- it('waits for idle for ordinary work in a capable environment', () => {
- expect(shouldSkipIdleWait(false, true)).toBe(false);
- });
-});
-
-describe('shouldRetryIdleWait', () => {
- it('does not retry once the idle callback has timed out', () => {
- expect(shouldRetryIdleWait(true, 0)).toBe(false);
- });
-
- it('retries when the granted budget is below the minimum', () => {
- expect(shouldRetryIdleWait(false, DISPATCH_IDLE_MIN_BUDGET_MS / 2)).toBe(true);
- });
-
- it('flushes when the granted budget is sufficient', () => {
- expect(shouldRetryIdleWait(false, DISPATCH_IDLE_MIN_BUDGET_MS)).toBe(false);
- expect(shouldRetryIdleWait(false, 50)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.fixtures.ts b/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.fixtures.ts
deleted file mode 100644
index 24bb918be..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.fixtures.ts
+++ /dev/null
@@ -1,1474 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {GatewayTimings, RpcTimings} from '@app/features/gateway/transport/GatewayTimingsFormatter';
-
-export const RPC_TIMINGS_FIXTURE: RpcTimings = {
- node_name: 'api-b6478896-6mkw5',
- pod_name: 'api-b6478896-6mkw5',
- role: 'api',
- steps: {
- build_rate_limit_bucket_key: {duration_us: 0},
- build_rtc_regions: {duration_us: 46},
- build_session_response_payload: {
- duration_us: 6193,
- steps: {
- encode_read_state_proto: {duration_us: 5119},
- map_auth_session_id_hash: {duration_us: 37},
- map_favorite_memes: {duration_us: 38},
- map_notes: {duration_us: 7},
- map_pinned_dms: {duration_us: 2},
- map_read_states: {duration_us: 275},
- map_user: {duration_us: 222},
- map_user_guild_settings: {duration_us: 314},
- map_user_settings: {duration_us: 150},
- map_webauthn_credentials: {duration_us: 1},
- },
- },
- check_session_rate_limit: {duration_us: 794},
- compute_token_hash_prefix: {duration_us: 1},
- ensure_personal_notes_channel: {duration_us: 2036},
- ensure_private_channels_within_limit: {duration_us: 64, steps: {resolve_private_channel_limit: {duration_us: 57}}},
- hash_session_token: {duration_us: 39},
- load_user_data: {
- duration_us: 43545,
- steps: {
- find_all_guild_settings: {duration_us: 7296},
- find_settings: {duration_us: 6735},
- find_user: {duration_us: 3136},
- get_pinned_dms: {duration_us: 4093},
- get_read_states: {duration_us: 21124},
- get_user_guild_ids: {duration_us: 5144},
- get_user_notes: {duration_us: 3716},
- list_favorite_memes: {duration_us: 3676},
- list_private_channels: {duration_us: 40274},
- list_relationships: {duration_us: 6678},
- list_webauthn_credentials: {duration_us: 3709},
- },
- },
- log_session_handling_completed: {duration_us: 10},
- log_session_handling_started: {duration_us: 5},
- lookup_geoip: {duration_us: 139},
- map_geoip_result: {duration_us: 10},
- map_ready_payloads: {
- duration_us: 17544,
- steps: {
- map_guild_ids: {duration_us: 10},
- map_private_channels: {duration_us: 592},
- map_relationships: {duration_us: 394},
- preload_user_partials: {
- duration_us: 16941,
- steps: {collect_user_partial_ids: {duration_us: 43}, users_service_request: {duration_us: 16783}},
- },
- },
- },
- normalize_session_token: {duration_us: 3},
- parse_token_type: {duration_us: 1},
- process_session_start: {
- duration_us: 123,
- steps: {
- apply_high_risk_country_inbound_phone_requirement: {
- duration_us: 25,
- steps: {check_bot_user: {duration_us: 0}, check_verified_phone: {duration_us: 0}},
- },
- build_session_flag_patch: {duration_us: 0},
- clear_expired_custom_status: {duration_us: 0},
- compute_session_and_premium_flags: {duration_us: 9},
- queue_country_sighting_record: {duration_us: 43},
- },
- },
- queue_payment_reconciliation: {duration_us: 0},
- queue_stripe_premium_state_reconciliation: {duration_us: 1},
- sync_repaired_user_data: {duration_us: 0},
- validate_user_session_token: {duration_us: 2860},
- },
- total_us: 73513,
- unit: 'microseconds',
-};
-
-export const GATEWAY_TIMINGS_FIXTURE: GatewayTimings = {
- pod_name: 'gateway-77d76684d9-hvvrm',
- total_us: 567480,
- trace: [
- {
- duration_us: 139,
- name: 'gateway_handler_identify:validate_identify_data/1',
- },
- {
- children: [
- {
- duration_us: 6,
- name: 'gateway_concurrency:try_acquire_session_start/0',
- },
- {
- duration_us: 83795,
- name: 'session_manager_shard_drain:fetch_rpc_data/2',
- remote: {
- operation: 'api',
- pod_name: 'api-b6478896-6mkw5',
- },
- },
- ],
- duration_us: 84009,
- name: 'session_manager_shard_lifecycle:acquire_and_fetch/2',
- },
- {
- duration_us: 115,
- name: 'session_manager_shard_start:validate_identify_payload/1',
- },
- {
- duration_us: 80,
- name: 'gateway_rollout_config:is_session_eligible/1',
- },
- {
- duration_us: 76,
- name: 'session_abuse_protection:check_user_session_limit/1',
- },
- {
- duration_us: 4055,
- name: 'session_manager_shard_drain:build_session_data/7',
- },
- {
- duration_us: 633,
- name: 'session_init:build_state/1',
- },
- {
- duration_us: 14010,
- name: 'session_init:schedule_timers/1',
- },
- {
- duration_us: 1767,
- name: 'presence_manager:start_or_lookup/1',
- remote: {
- operation: 'presence_manager',
- pod_name: 'gateway-presence-1',
- },
- },
- {
- duration_us: 1462,
- name: 'presence_session:handle_session_connect/3',
- remote: {
- operation: 'presence',
- pod_name: 'gateway-presence-1',
- },
- },
- {
- duration_us: 706,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 670,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 748,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 813,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 235,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 236,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 218,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 957,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 204,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 1191,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1149,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1255,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 136,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 1348,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 1280,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 1371,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1317,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 154,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 1747,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1738,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2024,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 1916,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2044,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2103,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 2048,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 2128,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 2142,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 303,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 2153,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2164,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 923,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 321,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2405,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 368,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2467,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 211,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 493,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2608,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2735,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2839,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2709,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 546,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 196,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 412,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 552,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 2872,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2844,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2973,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 2883,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 343,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 275,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 174,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2952,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2972,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3107,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3120,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 3072,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3095,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3068,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 3103,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3161,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 3102,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3095,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 3186,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3131,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3086,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 132,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 172,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 3451,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 277,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 207,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3501,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 436,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3579,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 448,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 345,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 246,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 3623,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 366,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 3685,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3709,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3791,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3716,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3778,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 4822,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 4845,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 4871,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 174,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 232,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 5193,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 5254,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 275,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 5280,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 5346,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 126,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 5611,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 697,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 805,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 740,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 154,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 218,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-6',
- },
- },
- {
- duration_us: 1105,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 998,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 1086,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 355,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 1482,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1329,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 1403,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 372,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 384,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 1566,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 1745,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 1598,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 1891,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2038,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 1932,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 1930,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 357,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-7',
- },
- },
- {
- duration_us: 2146,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 667,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-10',
- },
- },
- {
- duration_us: 2294,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 2281,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 314,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 2275,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2288,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 267,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 2504,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2698,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 139,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2703,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 800,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-0',
- },
- },
- {
- duration_us: 2707,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2672,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2863,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 2721,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2665,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 2727,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 2712,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 238,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3083,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 206,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 3013,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 236,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2959,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 183,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 258,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 379,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 3229,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 274,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 3199,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3287,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3195,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 1011,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-11',
- },
- },
- {
- duration_us: 3541,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 3382,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3379,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3425,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 3632,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 251,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-2',
- },
- },
- {
- duration_us: 3493,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 3371,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3386,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 3544,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3535,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 3502,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 3539,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 728,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-1',
- },
- },
- {
- duration_us: 3545,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 549,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 262,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-8',
- },
- },
- {
- duration_us: 127,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 245,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 248,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 4051,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3908,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 664,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 4090,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 3950,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 267,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-4',
- },
- },
- {
- duration_us: 4062,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 326,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 4281,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 202,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 4165,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 321,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-5',
- },
- },
- {
- duration_us: 3982,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 4127,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 4185,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 4197,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2013,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 2128,
- name: 'session_connection_guild_resolve:do_remote_guild_connect_attempt/4',
- remote: {
- operation: 'guild_manager',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 259,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-9',
- },
- },
- {
- duration_us: 275,
- name: 'session_connection_guild_resolve:send_connect_cast/5',
- remote: {
- operation: 'guild',
- pod_name: 'gateway-guilds-3',
- },
- },
- {
- duration_us: 2634,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- duration_us: 2609,
- name: 'session_connection_guild:do_guild_connect/1',
- },
- {
- children: [
- {
- duration_us: 76883,
- name: 'session_ready_collect:collect_ready_presences/2',
- },
- {
- duration_us: 651,
- name: 'session_ready_collect:collect_ready_users/2',
- },
- {
- duration_us: 243,
- name: 'session_ready_dispatch:build_final_ready_data/9',
- },
- ],
- duration_us: 77988,
- name: 'session_ready_dispatch:dispatch_ready_to_socket/1',
- },
- ],
- unit: 'microseconds',
-};
diff --git a/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.test.ts b/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.test.ts
deleted file mode 100644
index d0d567d59..000000000
--- a/fluxer_app/src/features/gateway/transport/GatewayTimingsFormatter.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- formatGatewayReadyTimings,
- type GatewayTimings,
- type RpcTimings,
-} from '@app/features/gateway/transport/GatewayTimingsFormatter';
-import {
- GATEWAY_TIMINGS_FIXTURE,
- RPC_TIMINGS_FIXTURE,
-} from '@app/features/gateway/transport/GatewayTimingsFormatter.fixtures';
-import {describe, expect, it} from 'vitest';
-
-describe('formatGatewayReadyTimings', () => {
- it('returns null when neither payload is present', () => {
- expect(formatGatewayReadyTimings(undefined, undefined)).toBeNull();
- });
-
- it('renders the gateway pod as the root line in milliseconds', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE);
- expect(tree).not.toBeNull();
- const lines = (tree as string).split('\n');
- expect(lines[1]).toBe('gateway-77d76684d9-hvvrm: 567.48');
- });
-
- it('converts microseconds to milliseconds and trims trailing zeros', () => {
- const gw: GatewayTimings = {
- pod_name: 'gw-1',
- total_us: 441305,
- unit: 'microseconds',
- trace: [
- {name: 'id_created', duration_us: 437},
- {name: 'session_lookup_finished', duration_us: 11},
- {name: 'sessions', duration_us: 433340},
- ],
- };
- const tree = formatGatewayReadyTimings(gw, undefined);
- expect(tree).toBe(
- [
- 'slowest: sessions (433.34), id_created (0.437), session_lookup_finished (0.011)',
- 'gw-1: 441.305',
- '| id_created: 0.437',
- '| session_lookup_finished: 0.011',
- '| sessions: 433.34',
- ].join('\n'),
- );
- });
-
- it('indents nested gateway children with "| " per depth', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- const lines = tree.split('\n');
- const idx = lines.findIndex((l) => l.includes('acquire_and_fetch/2'));
- expect(lines[idx]).toBe('| session_manager_shard_lifecycle:acquire_and_fetch/2: 84.009');
- expect(lines[idx + 1]).toBe('| | gateway_concurrency:try_acquire_session_start/0: 0.006');
- expect(lines[idx + 2]).toBe('| | session_manager_shard_drain:fetch_rpc_data/2 -> api-b6478896-6mkw5: 83.795');
- });
-
- it('grafts the RPC breakdown beneath the api remote hop', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- const lines = tree.split('\n');
- const hopIdx = lines.findIndex((l) => l.includes('fetch_rpc_data/2 -> api-b6478896-6mkw5'));
- expect(lines[hopIdx + 1]).toBe('| | | api-b6478896-6mkw5 (api): 73.513');
- expect(lines[hopIdx + 2]).toBe('| | | | build_rate_limit_bucket_key: 0');
- });
-
- it('renders deeply nested RPC steps (load_user_data -> children)', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- const lines = tree.split('\n');
- const parentIdx = lines.findIndex((l) => l.includes('load_user_data'));
- expect(lines[parentIdx]).toBe('| | | | load_user_data: 43.545');
- expect(lines[parentIdx + 1]).toBe('| | | | | find_all_guild_settings: 7.296');
- expect(lines.some((l) => l === '| | | | | list_private_channels: 40.274')).toBe(true);
- });
-
- it('renders three levels of RPC nesting (map_ready_payloads -> preload -> request)', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- expect(tree).toContain('| | | | map_ready_payloads: 17.544');
- expect(tree).toContain('| | | | | preload_user_partials: 16.941');
- expect(tree).toContain('| | | | | | users_service_request: 16.783');
- });
-
- it('grafts the RPC tree only once even though the trace has many remote hops', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- const occurrences = tree.split('\n').filter((l) => l.includes('(api): 73.513')).length;
- expect(occurrences).toBe(1);
- });
-
- it('still surfaces RPC timings when the gateway trace never references the rpc pod', () => {
- const orphanRpc: RpcTimings = {
- pod_name: 'api-orphan',
- role: 'api',
- total_us: 1000,
- steps: {only_step: {duration_us: 1000}},
- };
- const gw: GatewayTimings = {pod_name: 'gw-1', total_us: 2000, trace: [{name: 'noop', duration_us: 2000}]};
- const tree = formatGatewayReadyTimings(gw, orphanRpc) as string;
- const lines = tree.split('\n');
- expect(lines).toEqual([
- 'slowest: noop (2), only_step (1)',
- 'gw-1: 2',
- '| noop: 2',
- '| api-orphan (api): 1',
- '| | only_step: 1',
- ]);
- });
-
- it('renders an RPC-only payload rooted at depth 0', () => {
- const tree = formatGatewayReadyTimings(undefined, RPC_TIMINGS_FIXTURE) as string;
- const lines = tree.split('\n');
- expect(lines[0]).toBe(
- 'slowest: list_private_channels (40.274), get_read_states (21.124), users_service_request (16.783)',
- );
- expect(lines[1]).toBe('api-b6478896-6mkw5 (api): 73.513');
- expect(lines[2]).toBe('| build_rate_limit_bucket_key: 0');
- });
-
- it('prepends a one-line summary of the slowest leaf spans', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE) as string;
- const lines = tree.split('\n');
- expect(lines[0]).toBe(
- 'slowest: session_ready_collect:collect_ready_presences/2 (76.883), list_private_channels (40.274), get_read_states (21.124)',
- );
- expect(lines[1]).toBe('gateway-77d76684d9-hvvrm: 567.48');
- });
-
- it('matches the full combined snapshot for the captured production payloads', () => {
- const tree = formatGatewayReadyTimings(GATEWAY_TIMINGS_FIXTURE, RPC_TIMINGS_FIXTURE);
- expect(tree).toMatchSnapshot();
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/GuildActivationTarget.test.ts b/fluxer_app/src/features/gateway/transport/GuildActivationTarget.test.ts
deleted file mode 100644
index fa257a27c..000000000
--- a/fluxer_app/src/features/gateway/transport/GuildActivationTarget.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {selectGuildActivationTarget} from '@app/features/gateway/transport/GuildActivationTarget';
-import {FAVORITES_GUILD_ID} from '@fluxer/constants/src/AppConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('selectGuildActivationTarget', () => {
- it('returns the selected guild on a guild route', () => {
- expect(selectGuildActivationTarget({selectedGuildId: '1', openChannelGuildId: '1'})).toBe('1');
- });
-
- it('returns the selected guild when no channel is open', () => {
- expect(selectGuildActivationTarget({selectedGuildId: '1', openChannelGuildId: null})).toBe('1');
- });
-
- it('returns the owning guild of a channel opened from the favorites route', () => {
- expect(selectGuildActivationTarget({selectedGuildId: null, openChannelGuildId: '1'})).toBe('1');
- });
-
- it('ignores the favorites pseudo guild and falls through to the open channel', () => {
- expect(selectGuildActivationTarget({selectedGuildId: FAVORITES_GUILD_ID, openChannelGuildId: '1'})).toBe('1');
- });
-
- it('returns null on the favorites route while no channel is open', () => {
- expect(selectGuildActivationTarget({selectedGuildId: FAVORITES_GUILD_ID, openChannelGuildId: null})).toBeNull();
- });
-
- it('returns null for a private channel', () => {
- expect(selectGuildActivationTarget({selectedGuildId: null, openChannelGuildId: null})).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/gateway/transport/__snapshots__/GatewayTimingsFormatter.test.ts.snap b/fluxer_app/src/features/gateway/transport/__snapshots__/GatewayTimingsFormatter.test.ts.snap
deleted file mode 100644
index 7ba1d1e5c..000000000
--- a/fluxer_app/src/features/gateway/transport/__snapshots__/GatewayTimingsFormatter.test.ts.snap
+++ /dev/null
@@ -1,274 +0,0 @@
-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
-
-exports[`formatGatewayReadyTimings > matches the full combined snapshot for the captured production payloads 1`] = `
-"slowest: session_ready_collect:collect_ready_presences/2 (76.883), list_private_channels (40.274), get_read_states (21.124)
-gateway-77d76684d9-hvvrm: 567.48
-| gateway_handler_identify:validate_identify_data/1: 0.139
-| session_manager_shard_lifecycle:acquire_and_fetch/2: 84.009
-| | gateway_concurrency:try_acquire_session_start/0: 0.006
-| | session_manager_shard_drain:fetch_rpc_data/2 -> api-b6478896-6mkw5: 83.795
-| | | api-b6478896-6mkw5 (api): 73.513
-| | | | build_rate_limit_bucket_key: 0
-| | | | build_rtc_regions: 0.046
-| | | | build_session_response_payload: 6.193
-| | | | | encode_read_state_proto: 5.119
-| | | | | map_auth_session_id_hash: 0.037
-| | | | | map_favorite_memes: 0.038
-| | | | | map_notes: 0.007
-| | | | | map_pinned_dms: 0.002
-| | | | | map_read_states: 0.275
-| | | | | map_user: 0.222
-| | | | | map_user_guild_settings: 0.314
-| | | | | map_user_settings: 0.15
-| | | | | map_webauthn_credentials: 0.001
-| | | | check_session_rate_limit: 0.794
-| | | | compute_token_hash_prefix: 0.001
-| | | | ensure_personal_notes_channel: 2.036
-| | | | ensure_private_channels_within_limit: 0.064
-| | | | | resolve_private_channel_limit: 0.057
-| | | | hash_session_token: 0.039
-| | | | load_user_data: 43.545
-| | | | | find_all_guild_settings: 7.296
-| | | | | find_settings: 6.735
-| | | | | find_user: 3.136
-| | | | | get_pinned_dms: 4.093
-| | | | | get_read_states: 21.124
-| | | | | get_user_guild_ids: 5.144
-| | | | | get_user_notes: 3.716
-| | | | | list_favorite_memes: 3.676
-| | | | | list_private_channels: 40.274
-| | | | | list_relationships: 6.678
-| | | | | list_webauthn_credentials: 3.709
-| | | | log_session_handling_completed: 0.01
-| | | | log_session_handling_started: 0.005
-| | | | lookup_geoip: 0.139
-| | | | map_geoip_result: 0.01
-| | | | map_ready_payloads: 17.544
-| | | | | map_guild_ids: 0.01
-| | | | | map_private_channels: 0.592
-| | | | | map_relationships: 0.394
-| | | | | preload_user_partials: 16.941
-| | | | | | collect_user_partial_ids: 0.043
-| | | | | | users_service_request: 16.783
-| | | | normalize_session_token: 0.003
-| | | | parse_token_type: 0.001
-| | | | process_session_start: 0.123
-| | | | | apply_high_risk_country_inbound_phone_requirement: 0.025
-| | | | | | check_bot_user: 0
-| | | | | | check_verified_phone: 0
-| | | | | build_session_flag_patch: 0
-| | | | | clear_expired_custom_status: 0
-| | | | | compute_session_and_premium_flags: 0.009
-| | | | | queue_country_sighting_record: 0.043
-| | | | queue_payment_reconciliation: 0
-| | | | queue_stripe_premium_state_reconciliation: 0.001
-| | | | sync_repaired_user_data: 0
-| | | | validate_user_session_token: 2.86
-| session_manager_shard_start:validate_identify_payload/1: 0.115
-| gateway_rollout_config:is_session_eligible/1: 0.08
-| session_abuse_protection:check_user_session_limit/1: 0.076
-| session_manager_shard_drain:build_session_data/7: 4.055
-| session_init:build_state/1: 0.633
-| session_init:schedule_timers/1: 14.01
-| presence_manager:start_or_lookup/1 -> gateway-presence-1: 1.767
-| presence_session:handle_session_connect/3 -> gateway-presence-1: 1.462
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-10: 0.706
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-6: 0.67
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-6: 0.748
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-6: 0.813
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-10: 0.235
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-6: 0.236
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-6: 0.218
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-11: 0.957
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-6: 0.204
-| session_connection_guild:do_guild_connect/1: 1.191
-| session_connection_guild:do_guild_connect/1: 1.149
-| session_connection_guild:do_guild_connect/1: 1.255
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-11: 0.136
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-7: 1.348
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-7: 1.28
-| session_connection_guild:do_guild_connect/1: 1.371
-| session_connection_guild:do_guild_connect/1: 1.317
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-7: 0.154
-| session_connection_guild:do_guild_connect/1: 1.747
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-2: 1.738
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-8: 2.024
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-2: 1.916
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-2: 2.044
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 2.103
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 2.048
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-0: 2.128
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-0: 2.142
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-8: 0.303
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.153
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.164
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-7: 0.923
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-2: 0.321
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 2.405
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-2: 0.368
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.467
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-0: 0.211
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-2: 0.493
-| session_connection_guild:do_guild_connect/1: 2.608
-| session_connection_guild:do_guild_connect/1: 2.735
-| session_connection_guild:do_guild_connect/1: 2.839
-| session_connection_guild:do_guild_connect/1: 2.709
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.546
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.196
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-0: 0.412
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.552
-| session_connection_guild:do_guild_connect/1: 2.872
-| session_connection_guild:do_guild_connect/1: 2.844
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-0: 2.973
-| session_connection_guild:do_guild_connect/1: 2.883
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.343
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.275
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.174
-| session_connection_guild:do_guild_connect/1: 2.952
-| session_connection_guild:do_guild_connect/1: 2.972
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 3.107
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 3.12
-| session_connection_guild:do_guild_connect/1: 3.072
-| session_connection_guild:do_guild_connect/1: 3.095
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-8: 3.068
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 3.103
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 3.161
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 3.102
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 3.095
-| session_connection_guild:do_guild_connect/1: 3.186
-| session_connection_guild:do_guild_connect/1: 3.131
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 3.086
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-0: 0.132
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.172
-| session_connection_guild:do_guild_connect/1: 3.451
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.277
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.207
-| session_connection_guild:do_guild_connect/1: 3.501
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.436
-| session_connection_guild:do_guild_connect/1: 3.579
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-8: 0.448
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.345
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.246
-| session_connection_guild:do_guild_connect/1: 3.623
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.366
-| session_connection_guild:do_guild_connect/1: 3.685
-| session_connection_guild:do_guild_connect/1: 3.709
-| session_connection_guild:do_guild_connect/1: 3.791
-| session_connection_guild:do_guild_connect/1: 3.716
-| session_connection_guild:do_guild_connect/1: 3.778
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 4.822
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 4.845
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 4.871
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.174
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.232
-| session_connection_guild:do_guild_connect/1: 5.193
-| session_connection_guild:do_guild_connect/1: 5.254
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.275
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 5.28
-| session_connection_guild:do_guild_connect/1: 5.346
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.126
-| session_connection_guild:do_guild_connect/1: 5.611
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-6: 0.697
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-6: 0.805
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-11: 0.74
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-6: 0.154
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-6: 0.218
-| session_connection_guild:do_guild_connect/1: 1.105
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-11: 0.998
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-10: 1.086
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-11: 0.355
-| session_connection_guild:do_guild_connect/1: 1.482
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-10: 1.329
-| session_connection_guild:do_guild_connect/1: 1.403
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-10: 0.372
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-11: 0.384
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-7: 1.566
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-0: 1.745
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-11: 1.598
-| session_connection_guild:do_guild_connect/1: 1.891
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-2: 2.038
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 1.932
-| session_connection_guild:do_guild_connect/1: 1.93
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-7: 0.357
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-2: 2.146
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-10: 0.667
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 2.294
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.281
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-2: 0.314
-| session_connection_guild:do_guild_connect/1: 2.275
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-9: 2.288
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.267
-| session_connection_guild:do_guild_connect/1: 2.504
-| session_connection_guild:do_guild_connect/1: 2.698
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.139
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-1: 2.703
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-0: 0.8
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.707
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.672
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-8: 2.863
-| session_connection_guild:do_guild_connect/1: 2.721
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-8: 2.665
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 2.727
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 2.712
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.238
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 3.083
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-9: 0.206
-| session_connection_guild:do_guild_connect/1: 3.013
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.236
-| session_connection_guild:do_guild_connect/1: 2.959
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.183
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-8: 0.258
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.379
-| session_connection_guild:do_guild_connect/1: 3.229
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.274
-| session_connection_guild:do_guild_connect/1: 3.199
-| session_connection_guild:do_guild_connect/1: 3.287
-| session_connection_guild:do_guild_connect/1: 3.195
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-11: 1.011
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-8: 3.541
-| session_connection_guild:do_guild_connect/1: 3.382
-| session_connection_guild:do_guild_connect/1: 3.379
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-9: 3.425
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 3.632
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-2: 0.251
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 3.493
-| session_connection_guild:do_guild_connect/1: 3.371
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-4: 3.386
-| session_connection_guild:do_guild_connect/1: 3.544
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 3.535
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 3.502
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-5: 3.539
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-1: 0.728
-| session_connection_guild:do_guild_connect/1: 3.545
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-8: 0.549
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-8: 0.262
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.127
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.245
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-9: 0.248
-| session_connection_guild:do_guild_connect/1: 4.051
-| session_connection_guild:do_guild_connect/1: 3.908
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.664
-| session_connection_guild:do_guild_connect/1: 4.09
-| session_connection_guild:do_guild_connect/1: 3.95
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-4: 0.267
-| session_connection_guild:do_guild_connect/1: 4.062
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.326
-| session_connection_guild:do_guild_connect/1: 4.281
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.202
-| session_connection_guild:do_guild_connect/1: 4.165
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-5: 0.321
-| session_connection_guild:do_guild_connect/1: 3.982
-| session_connection_guild:do_guild_connect/1: 4.127
-| session_connection_guild:do_guild_connect/1: 4.185
-| session_connection_guild:do_guild_connect/1: 4.197
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-9: 2.013
-| session_connection_guild_resolve:do_remote_guild_connect_attempt/4 -> gateway-guilds-3: 2.128
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-9: 0.259
-| session_connection_guild_resolve:send_connect_cast/5 -> gateway-guilds-3: 0.275
-| session_connection_guild:do_guild_connect/1: 2.634
-| session_connection_guild:do_guild_connect/1: 2.609
-| session_ready_dispatch:dispatch_ready_to_socket/1: 77.988
-| | session_ready_collect:collect_ready_presences/2: 76.883
-| | session_ready_collect:collect_ready_users/2: 0.651
-| | session_ready_dispatch:build_final_ready_data/9: 0.243"
-`;
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogSentence.test.tsx b/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogSentence.test.tsx
deleted file mode 100644
index 0997dc97c..000000000
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogSentence.test.tsx
+++ /dev/null
@@ -1,412 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {GuildAuditLogSentence} from '@app/features/guild/components/modals/guild_tabs/GuildAuditLogSentence';
-import type {AuditLogSentence} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentationTypes';
-import {AppI18nProvider} from '@app/features/i18n/components/AppI18nProvider';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {type MessageDescriptor, setupI18n} from '@lingui/core';
-import type React from 'react';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const fixtures = vi.hoisted(() => ({
- users: new Map<string, {id: string; displayName: string}>(),
- channels: new Map<string, {id: string; name?: string; type: number}>(),
- roles: new Map<string, {id: string; name: string}>(),
- emojis: new Map<string, {id: string; name: string; animated: boolean}>(),
-}));
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getUser: (id: string) => fixtures.users.get(id)},
-}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => fixtures.channels.get(id)},
-}));
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {getGuildRole: (_guildId: string, roleId: string) => fixtures.roles.get(roleId)},
-}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({
- default: {getEmojiById: (id: string) => fixtures.emojis.get(id)},
-}));
-vi.mock('@app/features/user/utils/AvatarUtils', () => ({
- getEmojiURL: ({id}: {id: string}) => `https://media.example.invalid/emojis/${id}.webp`,
-}));
-vi.mock('@app/features/user/utils/DateFormatting', () => ({
- getFormattedDateTime: (timestamp: number) => new Date(timestamp).toISOString(),
-}));
-vi.mock('@app/features/permissions/utils/PermissionUtils', () => ({
- formatPermissionLabel: (_i18n: unknown, permission: bigint) => `Permission ${permission}`,
-}));
-vi.mock('@app/features/guild/components/modals/guild_tabs/GuildAuditLogTabComponents', () => ({
- ClickableUser: ({user, 'data-flx': dataFlx}: {user: {id: string; displayName: string}; 'data-flx'?: string}) => (
- <span data-user-id={user.id} data-flx={dataFlx}>
- {user.displayName}
- </span>
- ),
- CopyIdInline: ({
- id,
- children,
- 'data-flx': dataFlx,
- }: {
- id: string;
- children?: React.ReactNode;
- 'data-flx'?: string;
- }) => (
- <span data-copy-id={id} data-flx={dataFlx}>
- {children}
- </span>
- ),
- InlineCode: ({
- children,
- title,
- 'data-flx': dataFlx,
- }: {
- children?: React.ReactNode;
- title?: string;
- 'data-flx'?: string;
- }) => (
- <code title={title} data-flx={dataFlx}>
- {children}
- </code>
- ),
- ColorDot: ({color, 'data-flx': dataFlx}: {color: string; 'data-flx'?: string}) => (
- <i data-color={color} data-flx={dataFlx} />
- ),
-}));
-
-const GUILD_ID = '1400000000000000000';
-const ACTOR_ID = '1400000000000000001';
-const CHANNEL_ID = '1400000000000000002';
-const ROLE_ID = '1400000000000000003';
-const EMOJI_ID = '1400000000000000004';
-const SENTENCE_DATA_FLX_PATTERN = /data-flx="(guild\.guild-tabs\.guild-audit-log-sentence\.[^"]+)"/g;
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-
-function descriptor(id: string, message: string): MessageDescriptor {
- return {id, message};
-}
-
-function renderSentence(sentence: AuditLogSentence): string {
- return renderToStaticMarkup(
- <AppI18nProvider i18n={i18n}>
- <GuildAuditLogSentence
- sentence={sentence}
- guildId={GUILD_ID}
- data-flx="guild.guild-tabs.guild-audit-log-sentence-test.render-sentence.guild-audit-log-sentence"
- />
- </AppI18nProvider>,
- );
-}
-
-function visibleText(html: string): string {
- return html.replace(/<[^>]+>/g, '');
-}
-
-function renderText(sentence: AuditLogSentence): string {
- return visibleText(renderSentence(sentence));
-}
-
-function channelSentence(channel: AuditLogSentence['values'][string]): AuditLogSentence {
- return {descriptor: descriptor('test.channel', 'Deleted {channel}'), values: {channel}};
-}
-
-function roleSentence(role: AuditLogSentence['values'][string]): AuditLogSentence {
- return {descriptor: descriptor('test.role', 'Deleted the role {role}'), values: {role}};
-}
-
-afterEach(() => {
- fixtures.users.clear();
- fixtures.channels.clear();
- fixtures.roles.clear();
- fixtures.emojis.clear();
-});
-
-describe('GuildAuditLogSentence', () => {
- it('renders a user chip and a channel chip inside one message', () => {
- fixtures.users.set(ACTOR_ID, {id: ACTOR_ID, displayName: 'Hampus'});
- fixtures.channels.set(CHANNEL_ID, {id: CHANNEL_ID, name: 'general', type: ChannelTypes.GUILD_TEXT});
- const html = renderSentence({
- descriptor: descriptor('test.message-delete', '{actor} deleted a message in {channel}'),
- values: {
- actor: {kind: 'user', id: ACTOR_ID},
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- },
- });
- expect(visibleText(html)).toBe('Hampus deleted a message in #general');
- const userChipIndex = html.indexOf(`data-user-id="${ACTOR_ID}"`);
- const channelChipIndex = html.indexOf(`data-copy-id="${CHANNEL_ID}"`);
- expect(userChipIndex).toBeGreaterThan(-1);
- expect(channelChipIndex).toBeGreaterThan(userChipIndex);
- });
-
- it.each([
- [1, 'Hampus deleted 1 message in #general'],
- [5, 'Hampus deleted 5 messages in #general'],
- ])('passes the number %i through to the plural', (count, expected) => {
- fixtures.users.set(ACTOR_ID, {id: ACTOR_ID, displayName: 'Hampus'});
- fixtures.channels.set(CHANNEL_ID, {id: CHANNEL_ID, name: 'general', type: ChannelTypes.GUILD_TEXT});
- expect(
- renderText({
- descriptor: descriptor(
- 'test.message-bulk-delete',
- '{actor} deleted {count, plural, one {# message} other {# messages}} in {channel}',
- ),
- values: {
- actor: {kind: 'user', id: ACTOR_ID},
- count,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- },
- }),
- ).toBe(expected);
- });
-
- it('shows the unknown user label when the user is not loaded', () => {
- const html = renderSentence({
- descriptor: descriptor('test.kick', '{actor} kicked {target}'),
- values: {actor: {kind: 'user', id: ACTOR_ID}, target: {kind: 'user', id: ''}},
- });
- expect(visibleText(html)).toBe('Unknown user kicked Unknown user');
- expect(html).not.toContain('data-user-id');
- });
-
- it('shows the System label for the system actor', () => {
- fixtures.users.set(ACTOR_ID, {id: ACTOR_ID, displayName: 'Hampus'});
- expect(
- renderText({
- descriptor: descriptor('test.system-role', '{actor} gave {target} the role {role}'),
- values: {
- actor: {kind: 'system'},
- target: {kind: 'user', id: ACTOR_ID},
- role: {kind: 'role', id: ROLE_ID, recordedName: 'Mods'},
- },
- }),
- ).toBe('System gave Hampus the role Mods');
- });
-
- describe('channel names', () => {
- it.each([
- [ChannelTypes.GUILD_TEXT, 'Deleted #general'],
- [ChannelTypes.GUILD_LINK, 'Deleted #general'],
- [ChannelTypes.GUILD_VOICE, 'Deleted general'],
- [ChannelTypes.GUILD_CATEGORY, 'Deleted general'],
- ])('prefixes # only for live text and link channels (type %i)', (type, expected) => {
- fixtures.channels.set(CHANNEL_ID, {id: CHANNEL_ID, name: 'general', type});
- expect(
- renderText(channelSentence({kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'})),
- ).toBe(expected);
- });
-
- it('prefers the recorded name over the live name', () => {
- fixtures.channels.set(CHANNEL_ID, {id: CHANNEL_ID, name: 'new-name', type: ChannelTypes.GUILD_TEXT});
- expect(
- renderText(channelSentence({kind: 'channel', id: CHANNEL_ID, recordedName: 'old-name', fallback: 'channel'})),
- ).toBe('Deleted #old-name');
- });
-
- it('shows the recorded name without a prefix when the channel is gone', () => {
- expect(
- renderText(channelSentence({kind: 'channel', id: CHANNEL_ID, recordedName: 'general', fallback: 'channel'})),
- ).toBe('Deleted general');
- });
-
- it('falls back to #deleted-channel for a missing channel', () => {
- const html = renderSentence(
- channelSentence({kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'}),
- );
- expect(visibleText(html)).toBe('Deleted #deleted-channel');
- expect(html).toContain(`data-copy-id="${CHANNEL_ID}"`);
- });
-
- it('falls back to deleted-category for a missing category', () => {
- expect(
- renderText(channelSentence({kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'category'})),
- ).toBe('Deleted deleted-category');
- });
- });
-
- describe('role names', () => {
- it('shows @everyone when the role id equals the community id', () => {
- expect(renderText(roleSentence({kind: 'role', id: GUILD_ID, recordedName: null}))).toBe(
- 'Deleted the role @everyone',
- );
- });
-
- it('prefers the recorded name over the live name', () => {
- fixtures.roles.set(ROLE_ID, {id: ROLE_ID, name: 'Moderators'});
- expect(renderText(roleSentence({kind: 'role', id: ROLE_ID, recordedName: 'Mods'}))).toBe('Deleted the role Mods');
- });
-
- it('uses the live name when no name was recorded', () => {
- fixtures.roles.set(ROLE_ID, {id: ROLE_ID, name: 'Moderators'});
- expect(renderText(roleSentence({kind: 'role', id: ROLE_ID, recordedName: null}))).toBe(
- 'Deleted the role Moderators',
- );
- });
-
- it('falls back to deleted-role for a missing role', () => {
- const html = renderSentence(roleSentence({kind: 'role', id: ROLE_ID, recordedName: null}));
- expect(visibleText(html)).toBe('Deleted the role deleted-role');
- expect(html).toContain(`data-copy-id="${ROLE_ID}"`);
- });
- });
-
- describe('text', () => {
- const textSentence = (value: string): AuditLogSentence => ({
- descriptor: descriptor('test.topic', 'Set the topic to {text}'),
- values: {text: {kind: 'text', value}},
- });
-
- it('keeps text of 200 code points whole without a tooltip', () => {
- const value = '😀'.repeat(200);
- const html = renderSentence(textSentence(value));
- expect(visibleText(html)).toBe(`Set the topic to ${value}`);
- expect(html).not.toContain('title=');
- });
-
- it('truncates text past 200 code points and puts the full text in the tooltip', () => {
- const value = '😀'.repeat(201);
- const html = renderSentence(textSentence(value));
- expect(visibleText(html)).toBe(`Set the topic to ${'😀'.repeat(200)}…`);
- expect(html).toContain(`title="${value}"`);
- });
- });
-
- describe('permissions', () => {
- const permissionSentence = (flags: Array<bigint>): AuditLogSentence => ({
- descriptor: descriptor('test.granted', 'Granted {permissions}'),
- values: {permissions: {kind: 'permissions', flags}},
- });
-
- it('lists up to 8 permissions by name', () => {
- expect(renderText(permissionSentence([1n, 2n, 4n, 8n, 16n, 32n, 64n, 128n]))).toBe(
- 'Granted Permission 1, Permission 2, Permission 4, Permission 8, Permission 16, Permission 32, Permission 64, and Permission 128',
- );
- });
-
- it('shows 7 names and a count when there are more than 8 permissions', () => {
- expect(renderText(permissionSentence([1n, 2n, 4n, 8n, 16n, 32n, 64n, 128n, 256n, 512n]))).toBe(
- 'Granted Permission 1, Permission 2, Permission 4, Permission 8, Permission 16, Permission 32, Permission 64, and 3 more permissions',
- );
- });
- });
-
- it.each([
- [5400, 'Set slowmode to 90 minutes'],
- [259200, 'Set slowmode to 3 days'],
- [1, 'Set slowmode to 1 second'],
- ])('formats a duration of %i seconds in its largest whole unit', (seconds, expected) => {
- expect(
- renderText({
- descriptor: descriptor('test.slowmode', 'Set slowmode to {duration}'),
- values: {duration: {kind: 'duration', seconds}},
- }),
- ).toBe(expected);
- });
-
- it('formats dates, labels and names', () => {
- const timestamp = Date.parse('2026-09-01T12:00:00.000Z');
- expect(
- renderText({
- descriptor: descriptor('test.mixed', '{name} changed {oldAlignment} on {date}'),
- values: {
- name: {kind: 'name', value: 'Captain Hook'},
- oldAlignment: {kind: 'label', descriptor: descriptor('test.centered', 'Centered')},
- date: {kind: 'date', timestamp},
- },
- }),
- ).toBe('Captain Hook changed Centered on 2026-09-01T12:00:00.000Z');
- });
-
- it('formats a color as uppercase hex with a color dot', () => {
- const html = renderSentence({
- descriptor: descriptor('test.color', 'Set the role color to {color}'),
- values: {color: {kind: 'color', value: 0xff8800}},
- });
- expect(visibleText(html)).toBe('Set the role color to #FF8800');
- expect(html).toContain('data-color="#FF8800"');
- });
-
- describe('emoji', () => {
- const emojiSentence = (id: string | null): AuditLogSentence => ({
- descriptor: descriptor('test.emoji', 'Added the emoji {emoji}'),
- values: {emoji: {kind: 'emoji', id, name: 'blobcat'}},
- });
-
- it('shows the emoji image when the emoji is loaded', () => {
- fixtures.emojis.set(EMOJI_ID, {id: EMOJI_ID, name: 'blobcat', animated: false});
- const html = renderSentence(emojiSentence(EMOJI_ID));
- expect(visibleText(html)).toBe('Added the emoji :blobcat:');
- expect(html).toContain(`src="https://media.example.invalid/emojis/${EMOJI_ID}.webp"`);
- });
-
- it.each([
- ['without an id', null],
- ['that is not loaded', EMOJI_ID],
- ])('shows only the name for an emoji %s', (_label, id) => {
- const html = renderSentence(emojiSentence(id));
- expect(visibleText(html)).toBe('Added the emoji :blobcat:');
- expect(html).not.toContain('<img');
- });
- });
-
- it('puts data-flx on each chip', () => {
- fixtures.users.set(ACTOR_ID, {id: ACTOR_ID, displayName: 'Hampus'});
- fixtures.channels.set(CHANNEL_ID, {id: CHANNEL_ID, name: 'general', type: ChannelTypes.GUILD_TEXT});
- fixtures.emojis.set(EMOJI_ID, {id: EMOJI_ID, name: 'blobcat', animated: false});
- const html = renderSentence({
- descriptor: descriptor(
- 'test.chips',
- '{user} {unknownUser} {system} {channel} {role} {name} {text} {longText} {loadedEmoji} {plainEmoji} {color}',
- ),
- values: {
- user: {kind: 'user', id: ACTOR_ID},
- unknownUser: {kind: 'user', id: ''},
- system: {kind: 'system'},
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- role: {kind: 'role', id: ROLE_ID, recordedName: 'Mods'},
- name: {kind: 'name', value: 'Captain Hook'},
- text: {kind: 'text', value: 'short'},
- longText: {kind: 'text', value: 'x'.repeat(201)},
- loadedEmoji: {kind: 'emoji', id: EMOJI_ID, name: 'blobcat'},
- plainEmoji: {kind: 'emoji', id: null, name: 'wave'},
- color: {kind: 'color', value: 0x00ff00},
- },
- });
- const dataFlxValues = Array.from(html.matchAll(SENTENCE_DATA_FLX_PATTERN), (match) => match[1]).sort();
- expect(dataFlxValues).toEqual(
- [
- 'guild.guild-tabs.guild-audit-log-sentence.render-user.clickable-user',
- 'guild.guild-tabs.guild-audit-log-sentence.render-user.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-system.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-channel.copy-id-inline',
- 'guild.guild-tabs.guild-audit-log-sentence.render-channel.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-role.copy-id-inline',
- 'guild.guild-tabs.guild-audit-log-sentence.render-role.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-name.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-text.inline-code',
- 'guild.guild-tabs.guild-audit-log-sentence.render-text.inline-code--2',
- 'guild.guild-tabs.guild-audit-log-sentence.render-emoji.inline-emoji',
- 'guild.guild-tabs.guild-audit-log-sentence.render-emoji.inline-emoji-image',
- 'guild.guild-tabs.guild-audit-log-sentence.render-emoji.strong--2',
- 'guild.guild-tabs.guild-audit-log-sentence.render-emoji.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-color.color-value',
- 'guild.guild-tabs.guild-audit-log-sentence.render-color.strong',
- 'guild.guild-tabs.guild-audit-log-sentence.render-color.color-dot',
- ].sort(),
- );
- });
-});
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogTab.test.tsx b/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogTab.test.tsx
deleted file mode 100644
index 1bca3719a..000000000
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/GuildAuditLogTab.test.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {AppI18nProvider} from '@app/features/i18n/components/AppI18nProvider';
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {setupI18n} from '@lingui/core';
-import type React from 'react';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const GUILD_ID = '1400000000000000000';
-const ACTOR_ID = '1400000000000000001';
-const ENTRY_ID = '1400000000000000002';
-
-const fixtures = vi.hoisted(() => ({
- users: new Map<string, {id: string; displayName: string}>(),
- entries: [] as Array<unknown>,
-}));
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn()},
-}));
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown =>
- typeof value === 'string'
- ? {id: value, message: value}
- : {...(value as object), id: (value as {message: string}).message};
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: ({children}: {children?: React.ReactNode}) => <>{children}</>,
- Plural: ({value}: {value: number}) => <>{value}</>,
- useLingui: () => ({i18n}),
-}));
-vi.mock('@app/features/guild/commands/GuildCommands', () => ({
- fetchGuildAuditLogs: vi.fn(async () => ({
- audit_log_entries: fixtures.entries,
- users: [],
- webhooks: [],
- })),
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getUser: (id: string) => fixtures.users.get(id), cacheUsers: vi.fn()},
-}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({
- default: {getMembers: () => [], ensureMembersLoaded: vi.fn(async () => undefined)},
-}));
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => undefined}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {
- getGuildRole: () => undefined,
- getGuild: () => undefined,
- getRoles: () => [],
- getGuildRoles: () => [],
- getGuildChannels: () => [],
- },
-}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getEmojiById: () => undefined}}));
-vi.mock('@app/features/emoji/state/EmojiSticker', () => ({default: {getStickerById: () => null}}));
-vi.mock('@app/features/messaging/utils/MessagingUrlUtils', () => ({
- setUrlQueryParams: (path: string) => path,
- setPathQueryParams: (path: string) => path,
- mediaUrl: (path: string) => `https://media.example.invalid${path}`,
- cdnUrl: (path: string) => `https://cdn.example.invalid${path}`,
- webhookUrl: (id: string, token: string) => `https://example.invalid/webhooks/${id}/${token}`,
- marketingUrl: (path: string) => `https://example.invalid${path}`,
- adminUrl: (path: string) => `https://example.invalid${path}`,
- webAppUrl: (path: string) => `https://example.invalid${path}`,
-}));
-vi.mock('@app/features/user/utils/AvatarUtils', () => ({
- getEmojiURL: ({id}: {id: string}) => `https://media.example.invalid/emojis/${id}.webp`,
-}));
-vi.mock('@app/features/user/utils/DateFormatting', () => ({
- getFormattedDateTime: (timestamp: number) => new Date(timestamp).toISOString(),
-}));
-vi.mock('@app/features/permissions/utils/PermissionUtils', () => ({
- formatPermissionLabel: (_i18n: unknown, permission: bigint) => `Permission ${permission}`,
-}));
-vi.mock('@app/features/guild/components/modals/guild_tabs/GuildAuditLogTabComponents', () => ({
- ClickableUser: ({user}: {user: {id: string; displayName: string}}) => (
- <span data-flx="guild.guild-tabs.guild-audit-log-tab-test.clickable-user.span">{user.displayName}</span>
- ),
- CopyIdInline: ({children}: {children?: React.ReactNode}) => (
- <span data-flx="guild.guild-tabs.guild-audit-log-tab-test.copy-id-inline.span">{children}</span>
- ),
- InlineCode: ({children}: {children?: React.ReactNode}) => (
- <code data-flx="guild.guild-tabs.guild-audit-log-tab-test.inline-code.code">{children}</code>
- ),
- ColorDot: ({color}: {color: string}) => (
- <i data-color={color} data-flx="guild.guild-tabs.guild-audit-log-tab-test.color-dot.i" />
- ),
-}));
-vi.mock('@app/features/ui/components/form/FormCombobox', () => ({
- Combobox: ({options}: {options: ReadonlyArray<{value: string; label: string}>}) => (
- <div data-testid="combobox" data-flx="guild.guild-tabs.guild-audit-log-tab-test.combobox.combobox">
- {options.map((option) => (
- <span key={option.value} data-flx="guild.guild-tabs.guild-audit-log-tab-test.combobox.span">
- {option.label}
- </span>
- ))}
- </div>
- ),
-}));
-vi.mock('@app/features/ui/components/Avatar', () => ({
- Avatar: ({user}: {user: {id: string}}) => (
- <span data-avatar={user.id} data-flx="guild.guild-tabs.guild-audit-log-tab-test.avatar.span" />
- ),
-}));
-vi.mock('@app/features/ui/components/MockAvatar', () => ({
- MockAvatar: ({userTag}: {userTag?: string}) => (
- <span data-mock-avatar={userTag} data-flx="guild.guild-tabs.guild-audit-log-tab-test.mock-avatar.span" />
- ),
-}));
-vi.mock('@app/features/ui/components/Spinner', () => ({
- Spinner: () => <span data-spinner data-flx="guild.guild-tabs.guild-audit-log-tab-test.spinner.span" />,
-}));
-vi.mock('@app/features/ui/button/Button', () => ({
- Button: ({children}: {children?: React.ReactNode}) => (
- <button type="button" data-flx="guild.guild-tabs.guild-audit-log-tab-test.button.button">
- {children}
- </button>
- ),
-}));
-vi.mock('@app/features/ui/focus_ring/FocusRing', () => ({
- default: ({children}: {children: React.ReactElement}) => children,
-}));
-vi.mock('@app/features/app/components/dialogs/shared/EmptySlate', () => ({
- EmptySlate: ({title, description}: {title: React.ReactNode; description: React.ReactNode}) => (
- <div data-flx="guild.guild-tabs.guild-audit-log-tab-test.empty-slate.div">
- {title}
- {description}
- </div>
- ),
-}));
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-
-installVoiceMenuTestBootstrap();
-
-const GuildAuditLogTab = (await import('@app/features/guild/components/modals/guild_tabs/GuildAuditLogTab')).default;
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-describe('GuildAuditLogTab', () => {
- let root: Root | null = null;
- let container: HTMLDivElement | null = null;
-
- beforeEach(() => {
- fixtures.users.set(ACTOR_ID, {id: ACTOR_ID, displayName: 'Moderator'});
- fixtures.entries = [
- {
- id: ENTRY_ID,
- action_type: AuditLogActionType.GUILD_UPDATE,
- user_id: ACTOR_ID,
- target_id: GUILD_ID,
- changes: [{key: 'name', old_value: 'Old name', new_value: 'New name'}],
- },
- ];
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
- });
-
- afterEach(() => {
- act(() => {
- root?.unmount();
- });
- root = null;
- container?.remove();
- container = null;
- fixtures.users.clear();
- fixtures.entries = [];
- });
-
- async function render(): Promise<string> {
- await act(async () => {
- root?.render(
- <AppI18nProvider i18n={i18n}>
- <GuildAuditLogTab
- guildId={GUILD_ID}
- data-flx="guild.guild-tabs.guild-audit-log-tab-test.guild-audit-log-tab"
- />
- </AppI18nProvider>,
- );
- });
- return container?.textContent ?? '';
- }
-
- it('renders each entry as its presenter sentence', async () => {
- const text = await render();
- expect(text).toContain('renamed the community from Old name to New name');
- expect(text).not.toContain('updated the community settings.');
- });
-
- it('lists the presenter action filters', async () => {
- const text = await render();
- expect(text).toContain('Permission override added');
- expect(text).not.toContain('Channel overwrite added');
- expect(text).not.toContain('Members pruned');
- });
-});
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleMoveOperation.test.ts b/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleMoveOperation.test.ts
deleted file mode 100644
index 823d53447..000000000
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleMoveOperation.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createRoleMovePreview} from '@app/features/guild/components/modals/guild_tabs/RoleMoveOperation';
-import type {GuildRole} from '@app/features/guild/models/GuildRole';
-import {describe, expect, it} from 'vitest';
-
-const guildId = 'guild-1';
-
-function role(id: string, position: number): GuildRole {
- return {
- id,
- guildId,
- position,
- get isEveryone() {
- return id === guildId;
- },
- } as GuildRole;
-}
-
-function roleIds(roles: ReadonlyArray<GuildRole>): Array<string> {
- return roles.map((role) => role.id);
-}
-
-describe('createRoleMovePreview', () => {
- const roles = [
- role('locked-admin', 5),
- role('locked-manager', 4),
- role('alpha', 3),
- role('beta', 2),
- role(guildId, 0),
- ];
- const lockedRoleIds = new Set(['locked-admin', 'locked-manager']);
- const isRoleLocked = (role: GuildRole) => lockedRoleIds.has(role.id);
-
- it('rejects moving @everyone or a locked source role', () => {
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: guildId,
- targetRoleId: 'alpha',
- position: 'before',
- isRoleLocked,
- }),
- ).toBeNull();
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: 'locked-manager',
- targetRoleId: 'alpha',
- position: 'before',
- isRoleLocked,
- }),
- ).toBeNull();
- });
-
- it('rejects moving a manageable role before locked roles', () => {
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: 'beta',
- targetRoleId: 'locked-manager',
- position: 'before',
- isRoleLocked,
- }),
- ).toBeNull();
- });
-
- it('allows moving manageable roles to the highest slot below the locked prefix', () => {
- const preview = createRoleMovePreview({
- roles,
- draggedRoleId: 'beta',
- targetRoleId: 'alpha',
- position: 'before',
- isRoleLocked,
- });
- expect(preview?.operation).toEqual({
- roleId: 'beta',
- precedingRoleId: 'locked-manager',
- });
- expect(roleIds(preview?.order ?? [])).toEqual(['locked-admin', 'locked-manager', 'beta', 'alpha', guildId]);
- });
-
- it('rejects after-@everyone moves and allows before-@everyone moves', () => {
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: 'alpha',
- targetRoleId: guildId,
- position: 'after',
- isRoleLocked,
- }),
- ).toBeNull();
- const preview = createRoleMovePreview({
- roles,
- draggedRoleId: 'alpha',
- targetRoleId: guildId,
- position: 'before',
- isRoleLocked,
- });
- expect(preview?.operation).toEqual({
- roleId: 'alpha',
- precedingRoleId: 'beta',
- });
- expect(roleIds(preview?.order ?? [])).toEqual(['locked-admin', 'locked-manager', 'beta', 'alpha', guildId]);
- });
-
- it('returns null for moves that keep the role in its current slot', () => {
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: 'alpha',
- targetRoleId: 'beta',
- position: 'before',
- isRoleLocked,
- }),
- ).toBeNull();
- });
-
- it('lets owners place a role at the absolute top when no role is locked', () => {
- const preview = createRoleMovePreview({
- roles,
- draggedRoleId: 'beta',
- targetRoleId: null,
- position: 'before',
- isRoleLocked: () => false,
- });
- expect(preview?.operation).toEqual({
- roleId: 'beta',
- precedingRoleId: null,
- });
- expect(roleIds(preview?.order ?? [])).toEqual(['beta', 'locked-admin', 'locked-manager', 'alpha', guildId]);
- });
-});
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderIntegration.test.ts b/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderIntegration.test.ts
deleted file mode 100644
index 546cb5318..000000000
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderIntegration.test.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createRoleMovePreview} from '@app/features/guild/components/modals/guild_tabs/RoleMoveOperation';
-import {
- type RoleReorderAccess,
- type RoleReorderDragItem,
- type RoleReorderRect,
- type RoleReorderTarget,
- selectRoleReorderResolution,
-} from '@app/features/guild/components/modals/guild_tabs/RoleReorderStateMachine';
-import type {GuildRole} from '@app/features/guild/models/GuildRole';
-import {describe, expect, it} from 'vitest';
-
-const guildId = 'guild-1';
-const rect: RoleReorderRect = {
- top: 10,
- bottom: 42,
- left: 0,
- right: 260,
-};
-const managerAccess: RoleReorderAccess = {
- canManageRoles: true,
- isGuildOwner: false,
-};
-
-function point(y: number) {
- return {
- x: 140,
- y,
- };
-}
-
-function role(id: string, position: number): GuildRole {
- return {
- id,
- guildId,
- position,
- get isEveryone() {
- return id === guildId;
- },
- } as GuildRole;
-}
-
-function roleIds(roles: ReadonlyArray<GuildRole>): Array<string> {
- return roles.map((role) => role.id);
-}
-
-function dragItem(role: GuildRole, isLocked: boolean): RoleReorderDragItem {
- return {
- id: role.id,
- isEveryone: role.isEveryone,
- isLocked,
- };
-}
-
-function target(role: GuildRole, isLocked: boolean, isTerminal: boolean): RoleReorderTarget {
- return {
- role: {
- id: role.id,
- isEveryone: role.isEveryone,
- isLocked,
- },
- isTerminal,
- };
-}
-
-describe('role reorder machine and move preview integration', () => {
- const roles = [
- role('locked-admin', 5),
- role('locked-manager', 4),
- role('alpha', 3),
- role('beta', 2),
- role('gamma', 1),
- role(guildId, 0),
- ];
- const lockedRoleIds = new Set(['locked-admin', 'locked-manager']);
- const isRoleLocked = (role: GuildRole) => lockedRoleIds.has(role.id);
- const isRoleIdLocked = (roleId: string) => lockedRoleIds.has(roleId);
-
- it('moves a manageable role to the highest legal slot below locked roles from any pixel on that target row', () => {
- const source = roles[4]!;
- const firstManageableTarget = target(roles[2]!, false, false);
- for (let y = rect.top; y <= rect.bottom; y++) {
- const resolution = selectRoleReorderResolution(
- dragItem(source, false),
- firstManageableTarget,
- managerAccess,
- point(y),
- rect,
- );
- expect(resolution.intent, `expected intent for y=${y}`).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'alpha',
- position: 'before',
- },
- });
- const preview = createRoleMovePreview({
- roles,
- draggedRoleId: source.id,
- targetRoleId: resolution.intent!.result.targetRoleId,
- position: resolution.intent!.result.position,
- isRoleLocked,
- });
- expect(preview?.operation).toEqual({
- roleId: 'gamma',
- precedingRoleId: 'locked-manager',
- });
- expect(roleIds(preview?.order ?? [])).toEqual([
- 'locked-admin',
- 'locked-manager',
- 'gamma',
- 'alpha',
- 'beta',
- guildId,
- ]);
- }
- });
-
- it('keeps locked targets fixed by rejecting machine hovers that would insert before them', () => {
- const source = roles[4]!;
- const lockedTarget = target(roles[1]!, true, false);
- const resolution = selectRoleReorderResolution(
- dragItem(source, false),
- lockedTarget,
- managerAccess,
- point(41),
- rect,
- );
- expect(resolution).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'target-before-locked-role',
- });
- });
-
- it('rejects machine intents for locked sources again in the move preview layer', () => {
- const lockedSource = roles[1]!;
- const manageableTarget = target(roles[2]!, false, false);
- const resolution = selectRoleReorderResolution(
- dragItem(lockedSource, true),
- manageableTarget,
- managerAccess,
- point(20),
- rect,
- );
- expect(resolution).toMatchObject({
- intent: null,
- blockedReason: 'source-is-locked',
- });
- expect(
- createRoleMovePreview({
- roles,
- draggedRoleId: lockedSource.id,
- targetRoleId: 'alpha',
- position: 'before',
- isRoleLocked,
- }),
- ).toBeNull();
- });
-
- it('maps every machine-produced target for a manageable source into a preview that preserves locked prefix and @everyone', () => {
- const source = roles[4]!;
- for (let targetIndex = 0; targetIndex < roles.length; targetIndex++) {
- const destination = roles[targetIndex]!;
- const resolution = selectRoleReorderResolution(
- dragItem(source, false),
- target(destination, isRoleIdLocked(destination.id), targetIndex === roles.length - 1),
- managerAccess,
- point(targetIndex === roles.length - 1 ? 41 : 20),
- rect,
- );
- if (!resolution.intent) {
- expect(['target-before-locked-role', 'same-source-and-target']).toContain(resolution.blockedReason);
- continue;
- }
- const preview = createRoleMovePreview({
- roles,
- draggedRoleId: source.id,
- targetRoleId: resolution.intent.result.targetRoleId,
- position: resolution.intent.result.position,
- isRoleLocked,
- });
- if (!preview) {
- expect(destination.id).toBe(guildId);
- expect(resolution.intent.result).toEqual({
- targetRoleId: guildId,
- position: 'before',
- });
- continue;
- }
- expect(preview, `expected preview for target ${destination.id}`).not.toBeNull();
- expect(roleIds(preview.order).slice(0, 2)).toEqual(['locked-admin', 'locked-manager']);
- expect(roleIds(preview.order).at(-1)).toBe(guildId);
- expect(new Set(roleIds(preview.order))).toEqual(new Set(roleIds(roles)));
- }
- });
-
- it('supports terminal hoist-list after drops without using @everyone as a target', () => {
- const hoistedRoles = [role('alpha', 3), role('beta', 2), role('gamma', 1)];
- const source = hoistedRoles[0]!;
- const terminalTarget = target(hoistedRoles[2]!, false, true);
- const resolution = selectRoleReorderResolution(
- dragItem(source, false),
- terminalTarget,
- managerAccess,
- point(41),
- rect,
- );
- expect(resolution.intent).toEqual({
- indicator: {position: 'bottom', isValid: true},
- result: {
- targetRoleId: 'gamma',
- position: 'after',
- },
- });
- const preview = createRoleMovePreview({
- roles: hoistedRoles,
- draggedRoleId: source.id,
- targetRoleId: resolution.intent!.result.targetRoleId,
- position: resolution.intent!.result.position,
- isRoleLocked: () => false,
- });
- expect(roleIds(preview?.order ?? [])).toEqual(['beta', 'gamma', 'alpha']);
- expect(preview?.operation).toEqual({
- roleId: 'alpha',
- precedingRoleId: 'gamma',
- });
- });
-});
diff --git a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderStateMachine.test.ts b/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderStateMachine.test.ts
deleted file mode 100644
index e854c26d4..000000000
--- a/fluxer_app/src/features/guild/components/modals/guild_tabs/RoleReorderStateMachine.test.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- canRoleDropOnTarget,
- createRoleReorderSnapshot,
- getRoleReorderStateValue,
- type RoleReorderAccess,
- type RoleReorderDragItem,
- type RoleReorderRect,
- type RoleReorderTarget,
- resolveRoleReorderHover,
- selectRoleReorderIntent,
- transitionRoleReorderSnapshot,
-} from '@app/features/guild/components/modals/guild_tabs/RoleReorderStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const rect: RoleReorderRect = {
- top: 20,
- bottom: 52,
- left: 0,
- right: 240,
-};
-
-const managerAccess: RoleReorderAccess = {
- canManageRoles: true,
- isGuildOwner: false,
-};
-
-const ownerAccess: RoleReorderAccess = {
- canManageRoles: true,
- isGuildOwner: true,
-};
-
-function point(y: number) {
- return {
- x: 120,
- y,
- };
-}
-
-function item(id: string, options: Partial<RoleReorderDragItem> = {}): RoleReorderDragItem {
- return {
- id,
- isEveryone: false,
- isLocked: false,
- ...options,
- };
-}
-
-function target(
- id: string,
- options: {
- isEveryone?: boolean;
- isLocked?: boolean;
- isTerminal?: boolean;
- } = {},
-): RoleReorderTarget {
- return {
- role: {
- id,
- isEveryone: options.isEveryone ?? false,
- isLocked: options.isLocked ?? false,
- },
- isTerminal: options.isTerminal ?? false,
- };
-}
-
-function topTarget(): RoleReorderTarget {
- return {
- role: null,
- isTerminal: false,
- };
-}
-
-describe('RoleReorderStateMachine', () => {
- it('starts idle and targets a valid role hover', () => {
- let snapshot = createRoleReorderSnapshot();
- expect(getRoleReorderStateValue(snapshot)).toBe('idle');
- snapshot = transitionRoleReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: item('source'),
- target: target('target'),
- access: managerAccess,
- clientOffset: point(22),
- targetRect: rect,
- });
- expect(getRoleReorderStateValue(snapshot)).toBe('targeting');
- expect(snapshot.context.intent).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'target',
- position: 'before',
- },
- });
- });
-
- it('clears targeting state on drop', () => {
- let snapshot = createRoleReorderSnapshot();
- snapshot = transitionRoleReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: item('source'),
- target: target('target'),
- access: managerAccess,
- clientOffset: point(22),
- targetRect: rect,
- });
- snapshot = transitionRoleReorderSnapshot(snapshot, {type: 'drag.drop'});
- expect(getRoleReorderStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.intent).toBeNull();
- expect(snapshot.context.indicator).toBeNull();
- });
-
- it('uses one canonical before-target slot for every pixel of a non-terminal role', () => {
- const source = item('source');
- const destination = target('target');
- for (let y = rect.top; y <= rect.bottom; y++) {
- const intent = selectRoleReorderIntent(source, destination, managerAccess, point(y), rect);
- expect(intent, `expected intent for y=${y}`).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'target',
- position: 'before',
- },
- });
- }
- });
-
- it('allows the terminal non-everyone role to own the final after slot', () => {
- const source = item('source');
- const terminal = target('last-role', {isTerminal: true});
- expect(selectRoleReorderIntent(source, terminal, managerAccess, point(21), rect)).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'last-role',
- position: 'before',
- },
- });
- expect(selectRoleReorderIntent(source, terminal, managerAccess, point(51), rect)).toEqual({
- indicator: {position: 'bottom', isValid: true},
- result: {
- targetRoleId: 'last-role',
- position: 'after',
- },
- });
- });
-
- it('always maps @everyone to before-@everyone and never manufactures an after-everyone drop', () => {
- const source = item('source');
- const everyone = target('guild-1', {isEveryone: true, isTerminal: true});
- for (let y = rect.top; y <= rect.bottom; y++) {
- expect(selectRoleReorderIntent(source, everyone, managerAccess, point(y), rect)).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'guild-1',
- position: 'before',
- },
- });
- }
- });
-
- it('blocks impossible sources before producing reorder intents', () => {
- const destination = target('target');
- expect(canRoleDropOnTarget(item('source'), destination, {...managerAccess, canManageRoles: false})).toBe(false);
- expect(
- resolveRoleReorderHover(item('source'), destination, {...managerAccess, canManageRoles: false}, point(22), rect),
- ).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'missing-manage-roles-permission',
- });
- expect(
- resolveRoleReorderHover(item('guild-1', {isEveryone: true}), destination, managerAccess, point(22), rect),
- ).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'source-is-everyone',
- });
- expect(
- resolveRoleReorderHover(item('locked', {isLocked: true}), destination, managerAccess, point(22), rect),
- ).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'source-is-locked',
- });
- });
-
- it('blocks dropping a role onto itself', () => {
- let snapshot = createRoleReorderSnapshot();
- snapshot = transitionRoleReorderSnapshot(snapshot, {
- type: 'drag.hover',
- item: item('same'),
- target: target('same'),
- access: managerAccess,
- clientOffset: point(22),
- targetRect: rect,
- });
- expect(getRoleReorderStateValue(snapshot)).toBe('blocked');
- expect(snapshot.context.blockedReason).toBe('same-source-and-target');
- expect(snapshot.context.indicator).toEqual({position: 'top', isValid: false});
- });
-
- it('blocks inserting before a locked role for non-owners but allows owners', () => {
- const source = item('source');
- const lockedTarget = target('locked-target', {isLocked: true});
- expect(resolveRoleReorderHover(source, lockedTarget, managerAccess, point(22), rect)).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'target-before-locked-role',
- });
- expect(selectRoleReorderIntent(source, lockedTarget, ownerAccess, point(22), rect)).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: 'locked-target',
- position: 'before',
- },
- });
- });
-
- it('only lets owners use an explicit top target', () => {
- const source = item('source');
- expect(resolveRoleReorderHover(source, topTarget(), managerAccess, point(22), rect)).toMatchObject({
- intent: null,
- indicator: {position: 'top', isValid: false},
- blockedReason: 'top-target-requires-owner',
- });
- expect(selectRoleReorderIntent(source, topTarget(), ownerAccess, point(22), rect)).toEqual({
- indicator: {position: 'top', isValid: true},
- result: {
- targetRoleId: null,
- position: 'before',
- },
- });
- });
-
- it('blocks zero-height target rects without manufacturing an indicator or result', () => {
- const emptyRect = {...rect, bottom: rect.top};
- expect(
- resolveRoleReorderHover(item('source'), target('target'), managerAccess, point(rect.top), emptyRect),
- ).toEqual({
- intent: null,
- indicator: null,
- blockedReason: 'empty-target-rect',
- });
- });
-});
diff --git a/fluxer_app/src/features/guild/models/Guild.test.ts b/fluxer_app/src/features/guild/models/Guild.test.ts
deleted file mode 100644
index ff118831f..000000000
--- a/fluxer_app/src/features/guild/models/Guild.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Guild} from '@app/features/guild/models/Guild';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
-import type {Guild as WireGuild} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-
-const createGuild = (features: Array<string>): Guild =>
- new Guild({
- id: '1',
- name: 'Test Community',
- icon: null,
- features,
- roles: [],
- owner_id: '2',
- } as unknown as WireGuild);
-
-describe('Guild clone permissions', () => {
- test('no features means cloning is not allowed', () => {
- const guild = createGuild([]);
- expect(guild.cloneEmojiAllowed).toBe(false);
- expect(guild.cloneStickerAllowed).toBe(false);
- });
-
- test('the enabled features allow cloning', () => {
- const guild = createGuild([GuildFeatures.CLONE_EMOJI_ENABLED, GuildFeatures.CLONE_STICKER_ENABLED]);
- expect(guild.cloneEmojiAllowed).toBe(true);
- expect(guild.cloneStickerAllowed).toBe(true);
- });
-
- test('each enabled feature only allows its own kind', () => {
- const emojiOnly = createGuild([GuildFeatures.CLONE_EMOJI_ENABLED]);
- expect(emojiOnly.cloneEmojiAllowed).toBe(true);
- expect(emojiOnly.cloneStickerAllowed).toBe(false);
- const stickerOnly = createGuild([GuildFeatures.CLONE_STICKER_ENABLED]);
- expect(stickerOnly.cloneEmojiAllowed).toBe(false);
- expect(stickerOnly.cloneStickerAllowed).toBe(true);
- });
-
- test('the deprecated disabled features do not allow cloning', () => {
- const guild = createGuild([GuildFeatures.CLONE_EMOJI_DISABLED, GuildFeatures.CLONE_STICKER_DISABLED]);
- expect(guild.cloneEmojiAllowed).toBe(false);
- expect(guild.cloneStickerAllowed).toBe(false);
- });
-
- test('the deprecated disabled features do not override the enabled features', () => {
- const guild = createGuild([
- GuildFeatures.CLONE_EMOJI_DISABLED,
- GuildFeatures.CLONE_STICKER_DISABLED,
- GuildFeatures.CLONE_EMOJI_ENABLED,
- GuildFeatures.CLONE_STICKER_ENABLED,
- ]);
- expect(guild.cloneEmojiAllowed).toBe(true);
- expect(guild.cloneStickerAllowed).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/guild/state/GuildReadStateContributionMachine.test.ts b/fluxer_app/src/features/guild/state/GuildReadStateContributionMachine.test.ts
deleted file mode 100644
index 4b74fe8f5..000000000
--- a/fluxer_app/src/features/guild/state/GuildReadStateContributionMachine.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createGuildReadStateContributionSnapshot,
- type GuildReadStateContributionInput,
- resolveGuildReadStateContribution,
- selectGuildReadStateContribution,
- transitionGuildReadStateContributionSnapshot,
-} from '@app/features/guild/state/GuildReadStateContributionMachine';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<GuildReadStateContributionInput> = {}): GuildReadStateContributionInput {
- return {
- isEligibleTextChannel: true,
- isPrivate: false,
- unreadBadgesLevel: null,
- isMutedForUnread: false,
- hasUnread: true,
- mentionCount: 2,
- ...overrides,
- };
-}
-
-describe('guildReadStateContributionMachine', () => {
- it('suppresses channels that cannot contribute to guild read state', () => {
- expect(resolveGuildReadStateContribution(input({isEligibleTextChannel: false}))).toMatchObject({
- mentionAllowed: false,
- unreadAllowed: false,
- });
- });
-
- it('keeps mention contribution when unread badges are disabled', () => {
- expect(
- resolveGuildReadStateContribution(input({unreadBadgesLevel: MessageNotifications.NO_MESSAGES})),
- ).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: false,
- });
- });
-
- it('applies unread badge policies before legacy mute behavior', () => {
- expect(
- resolveGuildReadStateContribution(input({unreadBadgesLevel: MessageNotifications.ONLY_MENTIONS})),
- ).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: false,
- });
- expect(
- resolveGuildReadStateContribution(input({unreadBadgesLevel: MessageNotifications.ALL_MESSAGES})),
- ).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: true,
- });
- });
-
- it('keeps legacy muted channels mention-only and unmuted channels fully contributing', () => {
- expect(resolveGuildReadStateContribution(input({isMutedForUnread: true}))).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: false,
- });
- expect(resolveGuildReadStateContribution(input({isMutedForUnread: false}))).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: true,
- });
- });
-
- it('always allows private unread contribution when unread exists', () => {
- expect(
- resolveGuildReadStateContribution(
- input({
- isEligibleTextChannel: false,
- isPrivate: true,
- unreadBadgesLevel: MessageNotifications.NO_MESSAGES,
- isMutedForUnread: true,
- }),
- ),
- ).toMatchObject({
- mentionAllowed: true,
- unreadAllowed: true,
- });
- });
-
- it('does not allow empty mentions or empty unread counts to contribute', () => {
- expect(resolveGuildReadStateContribution(input({mentionCount: 0, hasUnread: false}))).toEqual({
- mentionAllowed: false,
- unreadAllowed: false,
- mentionCount: 0,
- });
- });
-
- it('updates contribution policy from later channel input', () => {
- const mutedSnapshot = createGuildReadStateContributionSnapshot(input({isMutedForUnread: true}));
- expect(selectGuildReadStateContribution(mutedSnapshot)).toMatchObject({unreadAllowed: false});
-
- const unmutedSnapshot = transitionGuildReadStateContributionSnapshot(mutedSnapshot, {
- type: 'guildReadContribution.updated',
- input: input({isMutedForUnread: false}),
- });
-
- expect(selectGuildReadStateContribution(unmutedSnapshot)).toMatchObject({unreadAllowed: true});
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/GuildModerationCapabilityUtils.test.ts b/fluxer_app/src/features/guild/utils/GuildModerationCapabilityUtils.test.ts
deleted file mode 100644
index a07d42fb8..000000000
--- a/fluxer_app/src/features/guild/utils/GuildModerationCapabilityUtils.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolveGuildModerationCapabilities} from '@app/features/guild/utils/GuildModerationCapabilityUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('resolveGuildModerationCapabilities', () => {
- const baseOptions = {
- isCurrentUser: false,
- canManageTarget: true,
- canKickMembers: false,
- canBanMembers: false,
- canModerateMembers: true,
- targetHasAdministratorPermission: false,
- };
-
- it('allows timing out manageable non-administrator targets', () => {
- const capabilities = resolveGuildModerationCapabilities(baseOptions);
-
- expect(capabilities.canTimeout).toBe(true);
- });
-
- it('prevents timing out administrators', () => {
- const capabilities = resolveGuildModerationCapabilities({
- ...baseOptions,
- targetHasAdministratorPermission: true,
- });
-
- expect(capabilities.canTimeout).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogChannelPresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogChannelPresentation.test.ts
deleted file mode 100644
index 963bad90f..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogChannelPresentation.test.ts
+++ /dev/null
@@ -1,1034 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
- TEST_GUILD_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-type EntryFixture = Parameters<typeof makeEntry>[0];
-type ChangeFixture = NonNullable<EntryFixture['changes']>[number];
-
-const CHANNEL_ID = '1400000000000000200';
-const CATEGORY_ID = '1400000000000000201';
-const OTHER_CATEGORY_ID = '1400000000000000202';
-const ROLE_ID = '1400000000000000300';
-const MEMBER_ID = '1400000000000000400';
-const UNKNOWN_PERMISSION_BIT = 1n << 19n;
-const NAMES = {[TEST_ACTOR_ID]: 'Hampus', [MEMBER_ID]: 'ender'};
-const ACTOR = {kind: 'user', id: TEST_ACTOR_ID};
-const VOICE_DEFAULTS = {type: 2, name: 'Lounge', bitrate: 64000, user_limit: 0, voice_connection_limit: 5};
-
-const ROLE_OVERWRITE = {target_id: ROLE_ID, options: {channel_id: CHANNEL_ID, id: ROLE_ID, type: 0, role_name: 'Mods'}};
-const MEMBER_OVERWRITE = {target_id: MEMBER_ID, options: {channel_id: CHANNEL_ID, id: MEMBER_ID, type: 1}};
-const EVERYONE_OVERWRITE = {target_id: TEST_GUILD_ID, options: {channel_id: CHANNEL_ID, id: TEST_GUILD_ID, type: 0}};
-
-interface OverwriteTarget {
- target_id: string;
- options: Record<string, unknown>;
-}
-
-function present(fixture: EntryFixture) {
- const presentation = presentAuditLogEntry(makeEntry(fixture), fakeContext());
- return {...resultToText(presentation, NAMES), expandable: presentation.expandable};
-}
-
-function summaryValues(fixture: EntryFixture) {
- return presentAuditLogEntry(makeEntry(fixture), fakeContext()).summary.values;
-}
-
-function change(key: string, oldValue: unknown, newValue: unknown): ChangeFixture {
- return {key, old_value: oldValue, new_value: newValue};
-}
-
-function mask(...flags: Array<bigint>): string {
- return flags.reduce((all, flag) => all | flag, 0n).toString();
-}
-
-function channelSnapshot(values: Record<string, unknown>): Record<string, unknown> {
- return {
- channel_id: CHANNEL_ID,
- type: 0,
- name: 'general',
- topic: null,
- parent_id: null,
- position: 12,
- nsfw: null,
- content_warning_level: 0,
- content_warning_text: null,
- rate_limit_per_user: 0,
- user_limit: 0,
- voice_connection_limit: null,
- bitrate: 0,
- rtc_region: null,
- permission_overwrite_count: 0,
- ...values,
- };
-}
-
-function createFixture(values: Record<string, unknown> = {}): EntryFixture {
- const snapshot = channelSnapshot(values);
- return {
- action_type: AuditLogActionType.CHANNEL_CREATE,
- target_id: CHANNEL_ID,
- options: {type: snapshot.type},
- changes: Object.entries(snapshot).map(([key, value]) => ({key, new_value: value})),
- };
-}
-
-function updateFixture(changes: Array<ChangeFixture>, type?: unknown): EntryFixture {
- return {action_type: AuditLogActionType.CHANNEL_UPDATE, target_id: CHANNEL_ID, options: {type}, changes};
-}
-
-function deleteFixture(values: Record<string, unknown> = {}): EntryFixture {
- const snapshot = channelSnapshot(values);
- return {
- action_type: AuditLogActionType.CHANNEL_DELETE,
- target_id: CHANNEL_ID,
- options: {type: snapshot.type},
- changes: Object.entries(snapshot).map(([key, value]) => ({key, old_value: value})),
- };
-}
-
-function overwriteCreated(target: OverwriteTarget, allow: unknown, deny: unknown): EntryFixture {
- return {
- action_type: AuditLogActionType.CHANNEL_OVERWRITE_CREATE,
- ...target,
- changes: [
- {key: 'id', new_value: target.target_id},
- {key: 'type', new_value: String(target.options.type)},
- {key: 'allow', new_value: allow},
- {key: 'deny', new_value: deny},
- ],
- };
-}
-
-function overwriteUpdated(target: OverwriteTarget, changes: Array<ChangeFixture>): EntryFixture {
- return {action_type: AuditLogActionType.CHANNEL_OVERWRITE_UPDATE, ...target, changes};
-}
-
-function overwriteDeleted(target: OverwriteTarget, allow: unknown, deny: unknown): EntryFixture {
- return {
- action_type: AuditLogActionType.CHANNEL_OVERWRITE_DELETE,
- ...target,
- changes: [
- {key: 'id', old_value: target.target_id},
- {key: 'type', old_value: String(target.options.type)},
- {key: 'allow', old_value: allow},
- {key: 'deny', old_value: deny},
- ],
- };
-}
-
-describe('presentChannelCreate', () => {
- it('shows a text channel made from the create modal as a summary with nothing to expand', () => {
- expect(present(createFixture())).toEqual({
- summary: 'Hampus created the text channel #general',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each<[string, Record<string, unknown>]>([
- ['Hampus created the text channel #general', {type: 0}],
- [`Hampus created the text channel #general in #${CATEGORY_ID}`, {type: 0, parent_id: CATEGORY_ID}],
- ['Hampus created the voice channel #Lounge', VOICE_DEFAULTS],
- [`Hampus created the voice channel #Lounge in #${CATEGORY_ID}`, {...VOICE_DEFAULTS, parent_id: CATEGORY_ID}],
- ['Hampus created the link channel #general', {type: 998, url: null}],
- [`Hampus created the link channel #general in #${CATEGORY_ID}`, {type: 998, url: null, parent_id: CATEGORY_ID}],
- ['Hampus created the channel #general', {type: 13}],
- [`Hampus created the channel #general in #${CATEGORY_ID}`, {type: 13, parent_id: CATEGORY_ID}],
- ['Hampus created the category #Info', {type: 4, name: 'Info'}],
- ['Hampus created the category #Info', {type: 4, name: 'Info', parent_id: CATEGORY_ID}],
- ])('gives "%s"', (summary, values) => {
- expect(present(createFixture(values))).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('reads the type from the options when the changes lack it, including dispatch strings', () => {
- const {changes = []} = createFixture();
- expect(
- present({
- action_type: AuditLogActionType.CHANNEL_CREATE,
- target_id: CHANNEL_ID,
- options: {type: '998'},
- changes: changes.filter((candidate) => candidate.key !== 'type'),
- }).summary,
- ).toBe('Hampus created the link channel #general');
- expect(present({...createFixture({type: 2}), options: {type: 0}}).summary).toBe(
- 'Hampus created the voice channel #general',
- );
- expect(present({...createFixture({type: 'voice'}), options: undefined}).summary).toBe(
- 'Hampus created the channel #general',
- );
- });
-
- it('records the channel name and points the category chip at the category', () => {
- expect(summaryValues(createFixture({parent_id: CATEGORY_ID}))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: 'general', fallback: 'channel'},
- category: {kind: 'channel', id: CATEGORY_ID, recordedName: null, fallback: 'category'},
- });
- expect(summaryValues(createFixture({type: 4, name: 'Info'}))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: 'Info', fallback: 'category'},
- });
- });
-
- it('names the system as the actor of a channel it created', () => {
- expect(present({...createFixture(), user_id: '0'}).summary).toBe('System created the text channel #general');
- });
-
- it.each<[string, Record<string, unknown>, Array<string>]>([
- ['the link of a link channel', {type: 998, url: 'https://fluxer.app'}, ['~ Set the link to https://fluxer.app']],
- ['no link on a text channel', {type: 0, url: 'https://fluxer.app'}, []],
- ['no blank link', {type: 998, url: ' '}, []],
- ['the topic of a text channel', {type: 0, topic: 'Rules here'}, ['~ Set the topic to Rules here']],
- ['the topic of a voice channel', {...VOICE_DEFAULTS, topic: 'Hang out'}, ['~ Set the topic to Hang out']],
- ['the topic of a link channel', {type: 998, topic: 'Docs'}, ['~ Set the topic to Docs']],
- ['no topic on a category', {type: 4, topic: 'Info'}, []],
- ['no blank topic', {topic: ' '}, []],
- ['a mature channel', {nsfw: true}, ['+ Marked the channel as containing mature content']],
- ['a channel marked not mature', {nsfw: false}, ['- Marked the channel as not containing mature content']],
- ['no maturity when it follows the community', {nsfw: null}, []],
- [
- 'a content warning with text',
- {content_warning_level: 1, content_warning_text: 'Spoilers'},
- ['+ Added a content warning with the text Spoilers'],
- ],
- ['a content warning without text', {content_warning_level: 1}, ['+ Added a content warning']],
- [
- 'a content warning with blank text',
- {content_warning_level: 1, content_warning_text: ' '},
- ['+ Added a content warning'],
- ],
- ['no content warning at level 0', {content_warning_level: 0, content_warning_text: 'Spoilers'}, []],
- ['no content warning on a category', {type: 4, content_warning_level: 1}, []],
- ['slowmode on a text channel', {rate_limit_per_user: 30}, ['~ Set slowmode to 30 seconds']],
- ['slowmode on a voice channel', {...VOICE_DEFAULTS, rate_limit_per_user: 3600}, ['~ Set slowmode to 1 hour']],
- ['no slowmode on a link channel', {type: 998, rate_limit_per_user: 30}, []],
- ['no slowmode on a category', {type: 4, rate_limit_per_user: 30}, []],
- ['no slowmode at 0', {rate_limit_per_user: 0}, []],
- ['the audio quality', {...VOICE_DEFAULTS, bitrate: 96000}, ['~ Set the audio quality to 96 kbps']],
- ['no audio quality at 0', {...VOICE_DEFAULTS, bitrate: 0}, []],
- ['no audio quality on a text channel', {bitrate: 96000}, []],
- ['a user limit of 1', {...VOICE_DEFAULTS, user_limit: 1}, ['~ Limited the channel to 1 user']],
- ['a user limit of 10', {...VOICE_DEFAULTS, user_limit: 10}, ['~ Limited the channel to 10 users']],
- ['no user limit on a text channel', {user_limit: 10}, []],
- [
- '1 connection per member',
- {...VOICE_DEFAULTS, voice_connection_limit: 1},
- ['~ Allowed up to 1 connection per member'],
- ],
- [
- '10 connections per member',
- {...VOICE_DEFAULTS, voice_connection_limit: 10},
- ['~ Allowed up to 10 connections per member'],
- ],
- ['no connection limit when it is null', {...VOICE_DEFAULTS, voice_connection_limit: null}, []],
- ['no connection limit on a text channel', {voice_connection_limit: 10}, []],
- ['the voice region', {...VOICE_DEFAULTS, rtc_region: 'rotterdam'}, ['~ Set the voice region to rotterdam']],
- ['no voice region on a text channel', {rtc_region: 'rotterdam'}, []],
- ])('shows %s', (_label, values, rows) => {
- const presentation = present(createFixture(values));
- expect({rows: presentation.rows, blocks: presentation.blocks, expandable: presentation.expandable}).toEqual({
- rows,
- blocks: [],
- expandable: rows.length > 0,
- });
- });
-
- it('gives no rows for the voice defaults', () => {
- expect(present(createFixture(VOICE_DEFAULTS))).toEqual({
- summary: 'Hampus created the voice channel #Lounge',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('lists every voice channel row in order whatever order the changes arrive in, after the reason', () => {
- const fixture = createFixture({
- ...VOICE_DEFAULTS,
- parent_id: CATEGORY_ID,
- topic: 'Hang out',
- nsfw: true,
- content_warning_level: 1,
- content_warning_text: 'Loud',
- rate_limit_per_user: 300,
- bitrate: 128000,
- user_limit: 10,
- voice_connection_limit: 2,
- rtc_region: 'rotterdam',
- });
- expect(present({...fixture, changes: [...(fixture.changes ?? [])].reverse(), reason: 'setup'})).toEqual({
- summary: `Hampus created the voice channel #Lounge in #${CATEGORY_ID}`,
- rows: [
- '~ Set the topic to Hang out',
- '+ Marked the channel as containing mature content',
- '+ Added a content warning with the text Loud',
- '~ Set slowmode to 5 minutes',
- '~ Set the audio quality to 128 kbps',
- '~ Limited the channel to 10 users',
- '~ Allowed up to 2 connections per member',
- '~ Set the voice region to rotterdam',
- ],
- blocks: [{kind: 'reason', text: 'setup'}],
- expandable: true,
- });
- });
-
- it('puts the link before the topic of a link channel', () => {
- expect(present(createFixture({type: 998, url: 'https://fluxer.app', topic: 'Docs'})).rows).toEqual([
- '~ Set the link to https://fluxer.app',
- '~ Set the topic to Docs',
- ]);
- });
-
- it('becomes expandable for a reason alone', () => {
- expect(present({...createFixture(), reason: 'Bot%20setup'})).toEqual({
- summary: 'Hampus created the text channel #general',
- rows: [],
- blocks: [{kind: 'reason', text: 'Bot setup'}],
- expandable: true,
- });
- });
-
- it('reads dispatch string values', () => {
- expect(
- present(
- createFixture({
- type: '2',
- name: 'Lounge',
- nsfw: 'true',
- bitrate: '96000',
- user_limit: '10',
- voice_connection_limit: '5',
- }),
- ),
- ).toEqual({
- summary: 'Hampus created the voice channel #Lounge',
- rows: [
- '+ Marked the channel as containing mature content',
- '~ Set the audio quality to 96 kbps',
- '~ Limited the channel to 10 users',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('prints no row whose value fails its reader', () => {
- expect(
- present({
- action_type: AuditLogActionType.CHANNEL_CREATE,
- target_id: 'not-a-snowflake',
- options: {type: 'voice'},
- changes: [
- {key: 'type', new_value: {}},
- {key: 'name', new_value: 42},
- {key: 'parent_id', new_value: 1400000000},
- {key: 'topic', new_value: ['Rules']},
- {key: 'nsfw', new_value: 'yes'},
- {key: 'content_warning_level', new_value: 'on'},
- {key: 'rate_limit_per_user', new_value: 'fast'},
- ],
- }),
- ).toEqual({summary: 'Hampus created the channel #', rows: [], blocks: [], expandable: false});
- });
-});
-
-describe('presentChannelUpdate', () => {
- it('shows the bot rename of a link channel as one sentence with nothing to expand', () => {
- expect(present(updateFixture([change('name', 'User count: 417,017', 'User count: 417,018')], 998))).toEqual({
- summary: 'Hampus renamed the link channel User count: 417,017 to User count: 417,018',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each<[string, unknown]>([
- ['Hampus renamed the text channel old-name to new-name', 0],
- ['Hampus renamed the voice channel old-name to new-name', 2],
- ['Hampus renamed the link channel old-name to new-name', 998],
- ['Hampus renamed the category old-name to new-name', 4],
- ['Hampus renamed the category old-name to new-name', '4'],
- ['Hampus renamed the channel old-name to new-name', 13],
- ['Hampus renamed the channel old-name to new-name', undefined],
- ])('gives "%s" for a rename alone', (summary, type) => {
- expect(present(updateFixture([change('name', 'old-name', 'new-name')], type))).toEqual({
- summary,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('keeps a rename alone expandable when it has a reason', () => {
- expect(present({...updateFixture([change('name', 'old-name', 'new-name')], 0), reason: 'cleanup'})).toEqual({
- summary: 'Hampus renamed the text channel old-name to new-name',
- rows: [],
- blocks: [{kind: 'reason', text: 'cleanup'}],
- expandable: true,
- });
- });
-
- it.each<[string, unknown]>([
- [`Hampus changed the permission overrides of the text channel #${CHANNEL_ID}`, 0],
- [`Hampus changed the permission overrides of the voice channel #${CHANNEL_ID}`, 2],
- [`Hampus changed the permission overrides of the link channel #${CHANNEL_ID}`, 998],
- [`Hampus changed the permission overrides of the category #${CHANNEL_ID}`, 4],
- [`Hampus changed the permission overrides of the channel #${CHANNEL_ID}`, 13],
- ])('gives "%s" for a legacy overwrite count change alone', (summary, type) => {
- expect(present(updateFixture([change('permission_overwrite_count', 2, 3)], type))).toEqual({
- summary,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each<[string, unknown]>([
- [`Hampus updated the text channel #${CHANNEL_ID}`, 0],
- [`Hampus updated the voice channel #${CHANNEL_ID}`, 2],
- [`Hampus updated the link channel #${CHANNEL_ID}`, 998],
- [`Hampus updated the category #${CHANNEL_ID}`, 4],
- [`Hampus updated the channel #${CHANNEL_ID}`, 13],
- ])('gives "%s" for other changes', (summary, type) => {
- expect(present(updateFixture([change('topic', null, 'Welcome')], type))).toEqual({
- summary,
- rows: ['+ Set the topic to Welcome'],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each<[string, Array<ChangeFixture>]>([
- ['no changes', []],
- [
- 'only keys it never shows',
- [change('channel_id', CHANNEL_ID, CHANNEL_ID), change('type', 0, 2), change('position', 3, 4)],
- ],
- ['values that read as equal', [change('topic', ' ', null), change('rtc_region', '', null)]],
- ['an overwrite count that did not change', [change('permission_overwrite_count', 3, 3)]],
- ['an overwrite count it cannot read', [change('permission_overwrite_count', 'three', 4)]],
- ])('gives the plain summary with nothing to expand for %s', (_label, changes) => {
- expect(present(updateFixture(changes, 0))).toEqual({
- summary: `Hampus updated the text channel #${CHANNEL_ID}`,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('leaves the channel chip without a recorded name when the channel was not renamed', () => {
- expect(summaryValues(updateFixture([change('topic', null, 'Welcome')], 0))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- });
- expect(summaryValues(updateFixture([change('permission_overwrite_count', 0, 1)], 4))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'category'},
- });
- });
-
- it('uses the new name and a name row when a rename comes with other changes', () => {
- expect(
- present(updateFixture([change('name', 'old-name', 'new-name'), change('permission_overwrite_count', 1, 2)], 0)),
- ).toEqual({
- summary: 'Hampus updated the text channel #new-name',
- rows: ['~ Changed the name from old-name to new-name'],
- blocks: [],
- expandable: true,
- });
- expect(
- summaryValues(updateFixture([change('name', 'old-name', 'new-name'), change('nsfw', null, true)], 0)),
- ).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: 'new-name', fallback: 'channel'},
- });
- });
-
- it.each<[string, Array<ChangeFixture>, Array<string>]>([
- [
- 'a move into a category',
- [change('parent_id', null, CATEGORY_ID)],
- [`~ Moved the channel into the category #${CATEGORY_ID}`],
- ],
- [
- 'a move out of a category',
- [change('parent_id', CATEGORY_ID, null)],
- [`~ Removed the channel from the category #${CATEGORY_ID}`],
- ],
- [
- 'a move between categories',
- [change('parent_id', CATEGORY_ID, OTHER_CATEGORY_ID)],
- [`~ Moved the channel from the category #${CATEGORY_ID} to the category #${OTHER_CATEGORY_ID}`],
- ],
- ['a link that was set', [change('url', null, 'https://fluxer.app')], ['+ Set the link to https://fluxer.app']],
- [
- 'a link that changed',
- [change('url', 'https://fluxer.app', 'https://docs.fluxer.app')],
- ['~ Changed the link from https://fluxer.app to https://docs.fluxer.app'],
- ],
- ['a link that was removed', [change('url', 'https://fluxer.app', null)], ['- Removed the link']],
- ['a topic that was set', [change('topic', null, 'Welcome')], ['+ Set the topic to Welcome']],
- ['a topic that was set from blank', [change('topic', ' ', 'Welcome')], ['+ Set the topic to Welcome']],
- ['a topic that was removed', [change('topic', 'Welcome', null)], ['- Removed the topic Welcome']],
- ['a topic that changed', [change('topic', 'Welcome', 'Hello')], ['~ Changed the topic from Welcome to Hello']],
- [
- 'a channel marked mature from the community setting',
- [change('nsfw', null, true)],
- ['+ Marked the channel as containing mature content'],
- ],
- [
- 'a channel marked mature from not mature',
- [change('nsfw', false, true)],
- ['+ Marked the channel as containing mature content'],
- ],
- [
- 'a channel marked not mature from the community setting',
- [change('nsfw', null, false)],
- ['- Marked the channel as not containing mature content'],
- ],
- [
- 'a channel marked not mature from mature',
- [change('nsfw', true, false)],
- ['- Marked the channel as not containing mature content'],
- ],
- [
- 'a mature channel that follows the community again',
- [change('nsfw', true, null)],
- ['~ Made the channel inherit its mature content setting'],
- ],
- [
- 'a not mature channel that follows the community again',
- [change('nsfw', false, null)],
- ['~ Made the channel inherit its mature content setting'],
- ],
- ['no maturity row for a value it cannot read', [change('nsfw', true, 'yes')], []],
- ['slowmode that was turned on', [change('rate_limit_per_user', 0, 30)], ['+ Set slowmode to 30 seconds']],
- [
- 'slowmode that changed',
- [change('rate_limit_per_user', 30, 3600)],
- ['~ Changed slowmode from 30 seconds to 1 hour'],
- ],
- ['slowmode that was turned off', [change('rate_limit_per_user', 3600, 0)], ['- Turned off slowmode']],
- ['slowmode sent as dispatch strings', [change('rate_limit_per_user', '0', '10')], ['+ Set slowmode to 10 seconds']],
- ['no slowmode row for a value it cannot read', [change('rate_limit_per_user', 30, 'fast')], []],
- [
- 'an audio quality change',
- [change('bitrate', 64000, 96000)],
- ['~ Changed the audio quality from 64 kbps to 96 kbps'],
- ],
- ['no audio quality row from 0', [change('bitrate', 0, 64000)], []],
- ['a user limit of 1', [change('user_limit', 0, 1)], ['~ Limited the channel to 1 user']],
- ['a user limit of 10', [change('user_limit', 0, 10)], ['~ Limited the channel to 10 users']],
- ['a user limit that changed', [change('user_limit', 10, 20)], ['~ Changed the user limit from 10 to 20']],
- ['a user limit that was removed', [change('user_limit', 10, 0)], ['~ Removed the user limit']],
- [
- 'a connection limit that changed',
- [change('voice_connection_limit', 5, 10)],
- ['~ Changed the connections per member from 5 to 10'],
- ],
- ['no connection limit row from null', [change('voice_connection_limit', null, 5)], []],
- ['a voice region that was set', [change('rtc_region', null, 'rotterdam')], ['~ Set the voice region to rotterdam']],
- [
- 'a voice region back to automatic',
- [change('rtc_region', 'rotterdam', null)],
- ['~ Set the voice region to automatic'],
- ],
- [
- 'a voice region that changed',
- [change('rtc_region', 'rotterdam', 'frankfurt')],
- ['~ Changed the voice region from rotterdam to frankfurt'],
- ],
- ])('shows %s', (_label, changes, rows) => {
- expect(present(updateFixture(changes, 2))).toEqual({
- summary: `Hampus updated the voice channel #${CHANNEL_ID}`,
- rows,
- blocks: [],
- expandable: rows.length > 0,
- });
- });
-
- it.each<[string, Array<ChangeFixture>, Array<string>]>([
- [
- 'a content warning added with text',
- [change('content_warning_level', 0, 1), change('content_warning_text', null, 'Spoilers')],
- ['+ Added a content warning with the text Spoilers'],
- ],
- [
- 'a content warning added without a text change',
- [change('content_warning_level', 0, 1)],
- ['+ Added a content warning'],
- ],
- [
- 'a content warning added with blank text',
- [change('content_warning_level', 0, 1), change('content_warning_text', null, ' ')],
- ['+ Added a content warning'],
- ],
- [
- 'a content warning added from a level it cannot read',
- [change('content_warning_level', null, 1)],
- ['+ Added a content warning'],
- ],
- [
- 'a content warning removed with its text',
- [change('content_warning_level', 1, 0), change('content_warning_text', 'Spoilers', null)],
- ['- Removed the content warning'],
- ],
- ['a content warning removed alone', [change('content_warning_level', 1, 0)], ['- Removed the content warning']],
- [
- 'content warning text that was set',
- [change('content_warning_text', null, 'Spoilers')],
- ['~ Set the content warning text to Spoilers'],
- ],
- [
- 'content warning text that changed',
- [change('content_warning_text', 'Spoilers', 'Gore')],
- ['~ Changed the content warning text from Spoilers to Gore'],
- ],
- [
- 'content warning text that was removed',
- [change('content_warning_text', 'Spoilers', null)],
- ['~ Removed the content warning text'],
- ],
- ['no row for an unknown level alone', [change('content_warning_level', 0, 2)], []],
- [
- 'a text change next to an unknown level',
- [change('content_warning_level', 0, 2), change('content_warning_text', null, 'Spoilers')],
- ['~ Set the content warning text to Spoilers'],
- ],
- ])('shows %s', (_label, changes, rows) => {
- expect(present(updateFixture(changes, 0))).toEqual({
- summary: `Hampus updated the text channel #${CHANNEL_ID}`,
- rows,
- blocks: [],
- expandable: rows.length > 0,
- });
- });
-
- it('lists the rows of an overview save in order', () => {
- expect(
- present(
- updateFixture(
- [change('rate_limit_per_user', 0, 10), change('topic', null, 'Hi'), change('name', 'old-name', 'new-name')],
- 0,
- ),
- ),
- ).toEqual({
- summary: 'Hampus updated the text channel #new-name',
- rows: ['~ Changed the name from old-name to new-name', '+ Set the topic to Hi', '+ Set slowmode to 10 seconds'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('orders every row kind the same way whatever order the changes arrive in', () => {
- const changes = [
- change('name', 'old-name', 'new-name'),
- change('parent_id', null, CATEGORY_ID),
- change('url', null, 'https://fluxer.app'),
- change('topic', 'Welcome', null),
- change('nsfw', null, true),
- change('content_warning_level', 1, 0),
- change('rate_limit_per_user', 30, 0),
- change('bitrate', 64000, 96000),
- change('user_limit', 0, 10),
- change('voice_connection_limit', 5, 10),
- change('rtc_region', null, 'rotterdam'),
- change('permission_overwrite_count', 0, 2),
- change('position', 1, 2),
- ];
- expect(present(updateFixture([...changes].reverse(), 2))).toEqual({
- summary: 'Hampus updated the voice channel #new-name',
- rows: [
- '~ Changed the name from old-name to new-name',
- `~ Moved the channel into the category #${CATEGORY_ID}`,
- '+ Set the link to https://fluxer.app',
- '- Removed the topic Welcome',
- '+ Marked the channel as containing mature content',
- '- Removed the content warning',
- '- Turned off slowmode',
- '~ Changed the audio quality from 64 kbps to 96 kbps',
- '~ Limited the channel to 10 users',
- '~ Changed the connections per member from 5 to 10',
- '~ Set the voice region to rotterdam',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('gives a rename with an old name it cannot read the plain summary with the new name', () => {
- expect(present(updateFixture([change('name', 42, 'new-name')], 0))).toEqual({
- summary: 'Hampus updated the text channel #new-name',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('presentChannelDelete', () => {
- it.each<[string, Record<string, unknown>]>([
- ['Hampus deleted the text channel #general', {type: 0}],
- ['Hampus deleted the voice channel #Lounge', VOICE_DEFAULTS],
- ['Hampus deleted the link channel #Docs', {type: 998, name: 'Docs', url: 'https://fluxer.app'}],
- ['Hampus deleted the category #Info', {type: 4, name: 'Info'}],
- ['Hampus deleted the channel #general', {type: 13}],
- ])('gives "%s" with no rows', (summary, values) => {
- expect(present(deleteFixture(values))).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('reads the type from the changes when the options lack it, and prefers the options', () => {
- expect(present({...deleteFixture(VOICE_DEFAULTS), options: undefined}).summary).toBe(
- 'Hampus deleted the voice channel #Lounge',
- );
- expect(present({...deleteFixture({type: 0, name: 'Info'}), options: {type: '4'}}).summary).toBe(
- 'Hampus deleted the category #Info',
- );
- });
-
- it('records the deleted name and picks the deleted label by type', () => {
- expect(summaryValues(deleteFixture({type: 4, name: 'Info'}))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: 'Info', fallback: 'category'},
- });
- expect(summaryValues(deleteFixture({name: null}))).toEqual({
- actor: ACTOR,
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- });
- });
-
- it('becomes expandable for a reason alone', () => {
- expect(present({...deleteFixture(), reason: 'Old channel'})).toEqual({
- summary: 'Hampus deleted the text channel #general',
- rows: [],
- blocks: [{kind: 'reason', text: 'Old channel'}],
- expandable: true,
- });
- });
-});
-
-describe('channel permission override presenters', () => {
- it.each<[string, EntryFixture]>([
- [
- `Hampus added a permission override for the role @Mods in #${CHANNEL_ID}`,
- overwriteCreated(ROLE_OVERWRITE, '0', '0'),
- ],
- [`Hampus added a permission override for ender in #${CHANNEL_ID}`, overwriteCreated(MEMBER_OVERWRITE, '0', '0')],
- [
- `Hampus added a permission override for @everyone in #${CHANNEL_ID}`,
- overwriteCreated(EVERYONE_OVERWRITE, '0', '0'),
- ],
- [
- `Hampus updated the permission override for the role @Mods in #${CHANNEL_ID}`,
- overwriteUpdated(ROLE_OVERWRITE, []),
- ],
- [`Hampus updated the permission override for ender in #${CHANNEL_ID}`, overwriteUpdated(MEMBER_OVERWRITE, [])],
- [
- `Hampus updated the permission override for @everyone in #${CHANNEL_ID}`,
- overwriteUpdated(EVERYONE_OVERWRITE, []),
- ],
- [
- `Hampus removed the permission override for the role @Mods from #${CHANNEL_ID}`,
- overwriteDeleted(ROLE_OVERWRITE, '0', '0'),
- ],
- [
- `Hampus removed the permission override for ender from #${CHANNEL_ID}`,
- overwriteDeleted(MEMBER_OVERWRITE, '0', '0'),
- ],
- [
- `Hampus removed the permission override for @everyone from #${CHANNEL_ID}`,
- overwriteDeleted(EVERYONE_OVERWRITE, '0', '0'),
- ],
- ])('gives "%s" with no rows for an empty override', (summary, fixture) => {
- expect(present(fixture)).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('passes the role, member and channel chips', () => {
- const channel = {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'};
- expect(summaryValues(overwriteCreated(ROLE_OVERWRITE, '0', '0'))).toEqual({
- actor: ACTOR,
- role: {kind: 'role', id: ROLE_ID, recordedName: 'Mods'},
- channel,
- });
- expect(summaryValues(overwriteUpdated(MEMBER_OVERWRITE, []))).toEqual({
- actor: ACTOR,
- user: {kind: 'user', id: MEMBER_ID},
- channel,
- });
- expect(summaryValues(overwriteDeleted(EVERYONE_OVERWRITE, '0', '0'))).toEqual({actor: ACTOR, channel});
- });
-
- it('gives a role without a recorded name an empty recorded name', () => {
- const fixture = overwriteCreated({target_id: ROLE_ID, options: {channel_id: CHANNEL_ID, type: 0}}, '0', '0');
- expect(summaryValues(fixture)).toEqual({
- actor: ACTOR,
- role: {kind: 'role', id: ROLE_ID, recordedName: null},
- channel: {kind: 'channel', id: CHANNEL_ID, recordedName: null, fallback: 'channel'},
- });
- expect(present(fixture).summary).toBe(
- `Hampus added a permission override for the role @${ROLE_ID} in #${CHANNEL_ID}`,
- );
- });
-
- it('reads the target kind from the changes when the options lack it', () => {
- expect(present({...overwriteCreated(MEMBER_OVERWRITE, '0', '0'), options: {channel_id: CHANNEL_ID}}).summary).toBe(
- `Hampus added a permission override for ender in #${CHANNEL_ID}`,
- );
- expect(present({...overwriteDeleted(MEMBER_OVERWRITE, '0', '0'), options: {channel_id: CHANNEL_ID}}).summary).toBe(
- `Hampus removed the permission override for ender from #${CHANNEL_ID}`,
- );
- expect(
- present({
- action_type: AuditLogActionType.CHANNEL_OVERWRITE_UPDATE,
- target_id: MEMBER_ID,
- options: {channel_id: CHANNEL_ID},
- changes: [change('type', '0', '1')],
- }).summary,
- ).toBe(`Hampus updated the permission override for ender in #${CHANNEL_ID}`);
- });
-
- it('treats a missing target kind as a role, and a member on the community id as a member', () => {
- expect(
- present({
- action_type: AuditLogActionType.CHANNEL_OVERWRITE_CREATE,
- target_id: ROLE_ID,
- options: {channel_id: CHANNEL_ID},
- }).summary,
- ).toBe(`Hampus added a permission override for the role @${ROLE_ID} in #${CHANNEL_ID}`);
- expect(
- present(overwriteCreated({target_id: TEST_GUILD_ID, options: {channel_id: CHANNEL_ID, type: '1'}}, '0', '0'))
- .summary,
- ).toBe(`Hampus added a permission override for @${TEST_GUILD_ID} in #${CHANNEL_ID}`);
- });
-
- it('gives an empty channel chip when the options lack the channel', () => {
- const fixture = {...overwriteDeleted(ROLE_OVERWRITE, '0', '0'), options: {type: 0, role_name: 'Mods'}};
- expect(summaryValues(fixture).channel).toEqual({kind: 'channel', id: '', recordedName: null, fallback: 'channel'});
- expect(present(fixture).summary).toBe('Hampus removed the permission override for the role @Mods from #');
- });
-
- it('keeps the reason block from the request header', () => {
- expect(
- present({...overwriteCreated(EVERYONE_OVERWRITE, '0', mask(Permissions.VIEW_CHANNEL)), reason: 'setup'}),
- ).toEqual({
- summary: `Hampus added a permission override for @everyone in #${CHANNEL_ID}`,
- rows: ['- Denied View channel'],
- blocks: [{kind: 'reason', text: 'setup'}],
- expandable: true,
- });
- });
-
- it.each<[string, EntryFixture, Array<string>]>([
- [
- 'allowed permissions',
- overwriteCreated(ROLE_OVERWRITE, mask(Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES), '0'),
- ['+ Allowed View channel and Send messages'],
- ],
- [
- 'denied permissions',
- overwriteCreated(ROLE_OVERWRITE, '0', mask(Permissions.SEND_MESSAGES)),
- ['- Denied Send messages'],
- ],
- [
- 'allowed and denied permissions in that order',
- overwriteCreated(
- ROLE_OVERWRITE,
- mask(Permissions.VIEW_CHANNEL),
- mask(Permissions.ATTACH_FILES, Permissions.SEND_MESSAGES),
- ),
- ['+ Allowed View channel', '- Denied Send messages and Attach files'],
- ],
- [
- 'numeric allow and deny',
- overwriteCreated(ROLE_OVERWRITE, Number(Permissions.VIEW_CHANNEL), Number(Permissions.SEND_MESSAGES)),
- ['+ Allowed View channel', '- Denied Send messages'],
- ],
- ['unknown bits only', overwriteCreated(ROLE_OVERWRITE, UNKNOWN_PERMISSION_BIT.toString(), '0'), []],
- [
- 'known bits next to unknown bits',
- overwriteCreated(ROLE_OVERWRITE, (UNKNOWN_PERMISSION_BIT | Permissions.VIEW_CHANNEL).toString(), '0'),
- ['+ Allowed View channel'],
- ],
- [
- 'a readable deny next to an allow it cannot read',
- overwriteCreated(ROLE_OVERWRITE, 'everything', mask(Permissions.SEND_MESSAGES)),
- ['- Denied Send messages'],
- ],
- ['no allow or deny at all', {...overwriteCreated(ROLE_OVERWRITE, '0', '0'), changes: []}, []],
- ])('shows %s on an added override', (_label, fixture, rows) => {
- expect(present(fixture)).toEqual({
- summary: `Hampus added a permission override for the role @Mods in #${CHANNEL_ID}`,
- rows,
- blocks: [],
- expandable: rows.length > 0,
- });
- });
-
- it('caps a long permission list at seven names and a count', () => {
- const flags = [
- Permissions.ADD_REACTIONS,
- Permissions.VIEW_CHANNEL,
- Permissions.SEND_MESSAGES,
- Permissions.MANAGE_MESSAGES,
- Permissions.EMBED_LINKS,
- Permissions.ATTACH_FILES,
- Permissions.READ_MESSAGE_HISTORY,
- Permissions.CONNECT,
- Permissions.SPEAK,
- ];
- const presentation = presentAuditLogEntry(
- makeEntry(overwriteCreated(MEMBER_OVERWRITE, mask(...flags), '0')),
- fakeContext(),
- );
- expect(presentation.rows.map((row) => row.sentence.values)).toEqual([{permissions: {kind: 'permissions', flags}}]);
- expect(resultToText(presentation, NAMES).rows).toEqual([
- '+ Allowed Add reactions, View channel, Send messages, Manage messages, Embed links, Attach files, Read message history, and 2 more permissions',
- ]);
- });
-
- it.each<[string, Array<ChangeFixture>, Array<string>]>([
- [
- 'a newly allowed permission',
- [change('allow', mask(Permissions.VIEW_CHANNEL), mask(Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES))],
- ['+ Allowed Send messages'],
- ],
- ['a newly denied permission', [change('deny', '0', mask(Permissions.ATTACH_FILES))], ['- Denied Attach files']],
- [
- 'an allowed permission back to default',
- [change('allow', mask(Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES), mask(Permissions.VIEW_CHANNEL))],
- ['~ Removed the override for Send messages'],
- ],
- [
- 'a denied permission back to default',
- [change('deny', mask(Permissions.ATTACH_FILES), '0')],
- ['~ Removed the override for Attach files'],
- ],
- [
- 'a flip from allowed to denied',
- [change('allow', mask(Permissions.SEND_MESSAGES), '0'), change('deny', '0', mask(Permissions.SEND_MESSAGES))],
- ['- Denied Send messages'],
- ],
- [
- 'a flip from denied to allowed',
- [change('allow', '0', mask(Permissions.SEND_MESSAGES)), change('deny', mask(Permissions.SEND_MESSAGES), '0')],
- ['+ Allowed Send messages'],
- ],
- [
- 'every kind of change in order',
- [
- change('deny', mask(Permissions.EMBED_LINKS), mask(Permissions.SEND_MESSAGES)),
- change('allow', mask(Permissions.ATTACH_FILES), mask(Permissions.VIEW_CHANNEL)),
- ],
- ['+ Allowed View channel', '- Denied Send messages', '~ Removed the override for Embed links and Attach files'],
- ],
- ['numeric values', [change('allow', 0, Number(Permissions.VIEW_CHANNEL))], ['+ Allowed View channel']],
- ['a change to unknown bits only', [change('allow', '0', UNKNOWN_PERMISSION_BIT.toString())], []],
- ['a value it cannot read', [change('allow', mask(Permissions.VIEW_CHANNEL), 'everything')], []],
- ])('shows %s on an updated override', (_label, changes, rows) => {
- expect(present(overwriteUpdated(ROLE_OVERWRITE, changes))).toEqual({
- summary: `Hampus updated the permission override for the role @Mods in #${CHANNEL_ID}`,
- rows,
- blocks: [],
- expandable: rows.length > 0,
- });
- });
-
- it('gives a type flip alone the summary only', () => {
- expect(present(overwriteUpdated(MEMBER_OVERWRITE, [change('type', '0', '1')]))).toEqual({
- summary: `Hampus updated the permission override for ender in #${CHANNEL_ID}`,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each<[string, EntryFixture, string, Array<string>]>([
- [
- 'allowed and denied permissions',
- overwriteDeleted(ROLE_OVERWRITE, mask(Permissions.VIEW_CHANNEL), mask(Permissions.SEND_MESSAGES)),
- `Hampus removed the permission override for the role @Mods from #${CHANNEL_ID}`,
- ['~ The override allowed View channel', '~ The override denied Send messages'],
- ],
- [
- 'allowed permissions',
- overwriteDeleted(MEMBER_OVERWRITE, mask(Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES), '0'),
- `Hampus removed the permission override for ender from #${CHANNEL_ID}`,
- ['~ The override allowed View channel and Send messages'],
- ],
- [
- 'numeric denied permissions',
- overwriteDeleted(EVERYONE_OVERWRITE, 0, Number(Permissions.VIEW_CHANNEL)),
- `Hampus removed the permission override for @everyone from #${CHANNEL_ID}`,
- ['~ The override denied View channel'],
- ],
- [
- 'unknown bits only',
- overwriteDeleted(EVERYONE_OVERWRITE, UNKNOWN_PERMISSION_BIT.toString(), '0'),
- `Hampus removed the permission override for @everyone from #${CHANNEL_ID}`,
- [],
- ],
- ])('shows %s on a removed override', (_label, fixture, summary, rows) => {
- expect(present(fixture)).toEqual({summary, rows, blocks: [], expandable: rows.length > 0});
- });
-});
-
-describe('channel presenters on junk input', () => {
- it.each<[string, AuditLogActionType]>([
- ['CHANNEL_CREATE', AuditLogActionType.CHANNEL_CREATE],
- ['CHANNEL_UPDATE', AuditLogActionType.CHANNEL_UPDATE],
- ['CHANNEL_DELETE', AuditLogActionType.CHANNEL_DELETE],
- ['CHANNEL_OVERWRITE_CREATE', AuditLogActionType.CHANNEL_OVERWRITE_CREATE],
- ['CHANNEL_OVERWRITE_UPDATE', AuditLogActionType.CHANNEL_OVERWRITE_UPDATE],
- ['CHANNEL_OVERWRITE_DELETE', AuditLogActionType.CHANNEL_OVERWRITE_DELETE],
- ])('never throws for %s', (_name, actionType) => {
- const fixtures: Array<EntryFixture> = [
- {action_type: actionType},
- {action_type: actionType, target_id: null, user_id: null, options: {}, changes: []},
- {
- action_type: actionType,
- target_id: 'not-a-snowflake',
- options: {type: {}, channel_id: 5, role_name: 7},
- changes: [
- {key: 'name'},
- {key: 'type', old_value: [], new_value: {}},
- {key: 'allow', old_value: -1, new_value: 1.5},
- {key: 'deny', new_value: 'NaN'},
- {key: 'parent_id', old_value: 1, new_value: true},
- {key: 'nsfw', new_value: 0},
- {key: 'content_warning_level', old_value: '1', new_value: 'x'},
- {key: 'user_limit', old_value: '10', new_value: -3},
- {key: 'bitrate', old_value: Number.NaN, new_value: '64k'},
- ],
- },
- ];
- for (const fixture of fixtures) {
- expect(() => present(fixture)).not.toThrow();
- }
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogExpressionMessagePresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogExpressionMessagePresentation.test.ts
deleted file mode 100644
index 0f2b3b044..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogExpressionMessagePresentation.test.ts
+++ /dev/null
@@ -1,645 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import type {AuditLogPresentationContext} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentationTypes';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-type EntryFixture = Parameters<typeof makeEntry>[0];
-
-const OTHER_USER_ID = '1400000000000000100';
-const EMOJI_ID = '1400000000000000200';
-const STICKER_ID = '1400000000000000300';
-const CHANNEL_ID = '1400000000000000400';
-const MESSAGE_ID = '1400000000000000500';
-const USER_NAMES = {[TEST_ACTOR_ID]: 'Hampus', [OTHER_USER_ID]: 'ender'};
-const EXPRESSION_MESSAGE_ACTION_TYPES = [
- AuditLogActionType.EMOJI_CREATE,
- AuditLogActionType.EMOJI_UPDATE,
- AuditLogActionType.EMOJI_DELETE,
- AuditLogActionType.STICKER_CREATE,
- AuditLogActionType.STICKER_UPDATE,
- AuditLogActionType.STICKER_DELETE,
- AuditLogActionType.MESSAGE_DELETE,
- AuditLogActionType.MESSAGE_BULK_DELETE,
- AuditLogActionType.MESSAGE_PIN,
- AuditLogActionType.MESSAGE_UNPIN,
-];
-
-function present(fixture: EntryFixture, context: AuditLogPresentationContext = fakeContext()) {
- const presentation = presentAuditLogEntry(makeEntry(fixture), context);
- return {...resultToText(presentation, USER_NAMES), expandable: presentation.expandable};
-}
-
-function summaryOnly(summary: string) {
- return {summary, rows: [], blocks: [], expandable: false};
-}
-
-function emojiSnapshot(side: 'old_value' | 'new_value', name: unknown, creatorId: unknown = TEST_ACTOR_ID) {
- return [
- {key: 'emoji_id', [side]: EMOJI_ID},
- {key: 'name', [side]: name},
- {key: 'animated', [side]: false},
- {key: 'creator_id', [side]: creatorId},
- ];
-}
-
-function stickerSnapshot(
- side: 'old_value' | 'new_value',
- name: unknown,
- description: unknown,
- creatorId: unknown = TEST_ACTOR_ID,
-) {
- return [
- {key: 'sticker_id', [side]: STICKER_ID},
- {key: 'name', [side]: name},
- {key: 'description', [side]: description},
- {key: 'animated', [side]: true},
- {key: 'creator_id', [side]: creatorId},
- ];
-}
-
-describe('presentEmojiCreate', () => {
- it('names the added emoji from the snapshot and shows its image by id', () => {
- const fixture = {
- action_type: AuditLogActionType.EMOJI_CREATE,
- target_id: EMOJI_ID,
- changes: emojiSnapshot('new_value', 'blobcat'),
- };
- expect(present(fixture)).toEqual(summaryOnly('Hampus added the emoji :blobcat:'));
- expect(presentAuditLogEntry(makeEntry(fixture), fakeContext()).summary.values.emoji).toEqual({
- kind: 'emoji',
- id: EMOJI_ID,
- name: 'blobcat',
- });
- });
-
- it('uses the unnamed summary when the name is missing, blank or not a string', () => {
- for (const name of [undefined, null, ' ', 42]) {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_CREATE,
- target_id: EMOJI_ID,
- changes: emojiSnapshot('new_value', name),
- }),
- ).toEqual(summaryOnly('Hampus added an emoji'));
- }
- expect(present({action_type: AuditLogActionType.EMOJI_CREATE, target_id: EMOJI_ID})).toEqual(
- summaryOnly('Hampus added an emoji'),
- );
- });
-
- it('keeps the name but drops the image id when the target is not a snowflake', () => {
- const presentation = presentAuditLogEntry(
- makeEntry({
- action_type: AuditLogActionType.EMOJI_CREATE,
- target_id: 'blobcat',
- changes: emojiSnapshot('new_value', 'blobcat'),
- }),
- fakeContext(),
- );
- expect(presentation.summary.values.emoji).toEqual({kind: 'emoji', id: null, name: 'blobcat'});
- });
-
- it('is expandable only for the Reason block', () => {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_CREATE,
- target_id: EMOJI_ID,
- reason: 'Event%20emoji',
- changes: emojiSnapshot('new_value', 'blobcat'),
- }),
- ).toEqual({
- summary: 'Hampus added the emoji :blobcat:',
- rows: [],
- blocks: [{kind: 'reason', text: 'Event emoji'}],
- expandable: true,
- });
- });
-});
-
-describe('presentEmojiUpdate', () => {
- it('renames from the old name without an image to the new emoji', () => {
- const fixture = {
- action_type: AuditLogActionType.EMOJI_UPDATE,
- target_id: EMOJI_ID,
- changes: [{key: 'name', old_value: 'blob', new_value: 'blobcat'}],
- };
- expect(present(fixture, fakeContext({emojis: {[EMOJI_ID]: 'ignored'}}))).toEqual(
- summaryOnly('Hampus renamed the emoji :blob: to :blobcat:'),
- );
- const {values} = presentAuditLogEntry(makeEntry(fixture), fakeContext()).summary;
- expect(values.oldEmoji).toEqual({kind: 'emoji', id: null, name: 'blob'});
- expect(values.newEmoji).toEqual({kind: 'emoji', id: EMOJI_ID, name: 'blobcat'});
- });
-
- it('names a legacy no-op from the emoji store', () => {
- expect(
- present(
- {action_type: AuditLogActionType.EMOJI_UPDATE, target_id: EMOJI_ID},
- fakeContext({emojis: {[EMOJI_ID]: 'blobcat'}}),
- ),
- ).toEqual(summaryOnly('Hampus updated the emoji :blobcat:'));
- });
-
- it('uses the unnamed summary for a legacy no-op the emoji store does not know', () => {
- expect(present({action_type: AuditLogActionType.EMOJI_UPDATE, target_id: EMOJI_ID})).toEqual(
- summaryOnly('Hampus updated an emoji'),
- );
- expect(
- present(
- {action_type: AuditLogActionType.EMOJI_UPDATE, target_id: null},
- fakeContext({emojis: {[EMOJI_ID]: 'blobcat'}}),
- ),
- ).toEqual(summaryOnly('Hampus updated an emoji'));
- });
-
- it('treats names that are equal after trimming as no rename', () => {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_UPDATE,
- target_id: EMOJI_ID,
- changes: [{key: 'name', old_value: 'blobcat ', new_value: 'blobcat'}],
- }),
- ).toEqual(summaryOnly('Hampus updated the emoji :blobcat:'));
- });
-
- it('names the emoji from the recorded new name when the old name is unreadable', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.EMOJI_UPDATE,
- target_id: EMOJI_ID,
- changes: [{key: 'name', old_value: null, new_value: 'blobcat'}],
- },
- fakeContext({emojis: {[EMOJI_ID]: 'stale'}}),
- ),
- ).toEqual(summaryOnly('Hampus updated the emoji :blobcat:'));
- });
-});
-
-describe('presentEmojiDelete', () => {
- it('shows no rows when the actor uploaded the emoji', () => {
- const fixture = {
- action_type: AuditLogActionType.EMOJI_DELETE,
- target_id: EMOJI_ID,
- changes: emojiSnapshot('old_value', 'blobcat'),
- };
- expect(present(fixture)).toEqual(summaryOnly('Hampus deleted the emoji :blobcat:'));
- expect(presentAuditLogEntry(makeEntry(fixture), fakeContext()).summary.values.emoji).toEqual({
- kind: 'emoji',
- id: null,
- name: 'blobcat',
- });
- });
-
- it('names the uploader when someone else uploaded the emoji', () => {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_DELETE,
- target_id: EMOJI_ID,
- changes: emojiSnapshot('old_value', 'blobcat', OTHER_USER_ID),
- }),
- ).toEqual({
- summary: 'Hampus deleted the emoji :blobcat:',
- rows: ['~ The emoji was uploaded by ender'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names the uploader when the system deleted the emoji', () => {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_DELETE,
- user_id: '0',
- target_id: EMOJI_ID,
- changes: emojiSnapshot('old_value', 'blobcat', TEST_ACTOR_ID),
- }),
- ).toEqual({
- summary: 'System deleted the emoji :blobcat:',
- rows: ['~ The emoji was uploaded by Hampus'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('omits the uploader row when the uploader is not a snowflake, and the name when it is missing', () => {
- for (const creatorId of [null, 1400, 'ender', '']) {
- expect(
- present({
- action_type: AuditLogActionType.EMOJI_DELETE,
- target_id: EMOJI_ID,
- changes: emojiSnapshot('old_value', undefined, creatorId),
- }),
- ).toEqual(summaryOnly('Hampus deleted an emoji'));
- }
- });
-});
-
-describe('presentStickerCreate', () => {
- it('sets the description when one was given', () => {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_CREATE,
- target_id: STICKER_ID,
- changes: stickerSnapshot('new_value', 'Wave', 'hello there'),
- }),
- ).toEqual({
- summary: 'Hampus added the sticker Wave',
- rows: ['~ Set the description to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows no rows without a description', () => {
- for (const description of [null, '', ' ', 7]) {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_CREATE,
- target_id: STICKER_ID,
- changes: stickerSnapshot('new_value', 'Wave', description),
- }),
- ).toEqual(summaryOnly('Hampus added the sticker Wave'));
- }
- });
-
- it('uses the unnamed summary when the name is missing', () => {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_CREATE,
- target_id: STICKER_ID,
- changes: stickerSnapshot('new_value', null, 'hello there'),
- }),
- ).toEqual({
- summary: 'Hampus added a sticker',
- rows: ['~ Set the description to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-});
-
-describe('presentStickerUpdate', () => {
- const context = fakeContext({stickers: {[STICKER_ID]: 'Wave'}});
-
- it('renames with no rows when only the name changed', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'name', old_value: 'Wave', new_value: 'Hello'}],
- },
- context,
- ),
- ).toEqual(summaryOnly('Hampus renamed the sticker Wave to Hello'));
- });
-
- it('adds a description', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'description', old_value: null, new_value: 'hello there'}],
- },
- context,
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Wave',
- rows: ['+ Set the description to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('changes a description', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'description', old_value: 'hi', new_value: 'hello there'}],
- },
- context,
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Wave',
- rows: ['~ Changed the description from hi to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('removes a description, treating blank as removed', () => {
- for (const newValue of [null, '', ' ']) {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'description', old_value: 'hello there', new_value: newValue}],
- },
- context,
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Wave',
- rows: ['- Removed the description hello there'],
- blocks: [],
- expandable: true,
- });
- }
- });
-
- it('lists the name before the description and names the sticker from the new name', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [
- {key: 'description', old_value: 'hi', new_value: 'hello there'},
- {key: 'name', old_value: 'Wave', new_value: 'Hello'},
- ],
- },
- context,
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Hello',
- rows: ['~ Changed the name from Wave to Hello', '~ Changed the description from hi to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names the sticker from the sticker store when the name did not change', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'description', old_value: 'hi', new_value: 'hello there'}],
- },
- fakeContext({stickers: {[STICKER_ID]: 'Stored name'}}),
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Stored name',
- rows: ['~ Changed the description from hi to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('uses the unnamed summary when the sticker name is unknown', () => {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [{key: 'description', old_value: null, new_value: 'hello there'}],
- }),
- ).toEqual({
- summary: 'Hampus updated a sticker',
- rows: ['+ Set the description to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows the summary alone for a legacy no-op or unchanged values', () => {
- expect(present({action_type: AuditLogActionType.STICKER_UPDATE, target_id: STICKER_ID})).toEqual(
- summaryOnly('Hampus updated a sticker'),
- );
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [
- {key: 'description', old_value: '', new_value: null},
- {key: 'tags', old_value: ['a'], new_value: ['b']},
- {key: 'animated', old_value: false, new_value: true},
- ],
- },
- context,
- ),
- ).toEqual(summaryOnly('Hampus updated the sticker Wave'));
- });
-
- it('omits the name row when either name is unreadable', () => {
- expect(
- present(
- {
- action_type: AuditLogActionType.STICKER_UPDATE,
- target_id: STICKER_ID,
- changes: [
- {key: 'name', old_value: 5, new_value: 'Hello'},
- {key: 'description', old_value: 'hi', new_value: 'hello there'},
- ],
- },
- context,
- ),
- ).toEqual({
- summary: 'Hampus updated the sticker Hello',
- rows: ['~ Changed the description from hi to hello there'],
- blocks: [],
- expandable: true,
- });
- });
-});
-
-describe('presentStickerDelete', () => {
- it('shows no rows when the actor uploaded the sticker', () => {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_DELETE,
- target_id: STICKER_ID,
- changes: stickerSnapshot('old_value', 'Wave', 'hello there'),
- }),
- ).toEqual(summaryOnly('Hampus deleted the sticker Wave'));
- });
-
- it('names the uploader when someone else uploaded the sticker', () => {
- expect(
- present({
- action_type: AuditLogActionType.STICKER_DELETE,
- target_id: STICKER_ID,
- changes: stickerSnapshot('old_value', 'Wave', null, OTHER_USER_ID),
- }),
- ).toEqual({
- summary: 'Hampus deleted the sticker Wave',
- rows: ['~ The sticker was uploaded by ender'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('uses the unnamed summary when the name is missing', () => {
- expect(present({action_type: AuditLogActionType.STICKER_DELETE, target_id: STICKER_ID})).toEqual(
- summaryOnly('Hampus deleted a sticker'),
- );
- });
-});
-
-describe('presentMessageDelete, presentMessagePin and presentMessageUnpin', () => {
- const cases = [
- {
- actionType: AuditLogActionType.MESSAGE_DELETE,
- inChannel: `Hampus deleted a message in #${CHANNEL_ID}`,
- withoutChannel: 'Hampus deleted a message',
- },
- {
- actionType: AuditLogActionType.MESSAGE_PIN,
- inChannel: `Hampus pinned a message in #${CHANNEL_ID}`,
- withoutChannel: 'Hampus pinned a message',
- },
- {
- actionType: AuditLogActionType.MESSAGE_UNPIN,
- inChannel: `Hampus unpinned a message in #${CHANNEL_ID}`,
- withoutChannel: 'Hampus unpinned a message',
- },
- ];
-
- for (const {actionType, inChannel, withoutChannel} of cases) {
- describe(AuditLogActionType[actionType], () => {
- it('names the channel', () => {
- const fixture = {
- action_type: actionType,
- target_id: MESSAGE_ID,
- options: {channel_id: CHANNEL_ID, message_id: MESSAGE_ID},
- };
- expect(present(fixture)).toEqual(summaryOnly(inChannel));
- expect(presentAuditLogEntry(makeEntry(fixture), fakeContext()).summary.values.channel).toEqual({
- kind: 'channel',
- id: CHANNEL_ID,
- recordedName: null,
- fallback: 'channel',
- });
- });
-
- it('leaves the channel out when it is missing or not a snowflake', () => {
- for (const options of [undefined, {}, {channel_id: null}, {channel_id: 1400}, {channel_id: 'general'}]) {
- expect(present({action_type: actionType, target_id: MESSAGE_ID, options})).toEqual(
- summaryOnly(withoutChannel),
- );
- }
- });
-
- it('is expandable only for the Reason block', () => {
- expect(
- present({
- action_type: actionType,
- target_id: MESSAGE_ID,
- reason: 'Off topic',
- options: {channel_id: CHANNEL_ID},
- }),
- ).toEqual({summary: inChannel, rows: [], blocks: [{kind: 'reason', text: 'Off topic'}], expandable: true});
- });
- });
- }
-});
-
-describe('presentMessageBulkDelete', () => {
- it('counts one message in a channel', () => {
- expect(
- present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {channel_id: CHANNEL_ID, count: 1}}),
- ).toEqual(summaryOnly(`Hampus deleted 1 message in #${CHANNEL_ID}`));
- });
-
- it('counts five messages in a channel, from a REST number or a dispatch string', () => {
- for (const count of [5, '5']) {
- expect(
- present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {channel_id: CHANNEL_ID, count}}),
- ).toEqual(summaryOnly(`Hampus deleted 5 messages in #${CHANNEL_ID}`));
- }
- });
-
- it('says some messages when the count is missing or not a positive whole number', () => {
- for (const count of [undefined, null, 0, -3, 2.5, 'many', '']) {
- expect(
- present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {channel_id: CHANNEL_ID, count}}),
- ).toEqual(summaryOnly(`Hampus deleted some messages in #${CHANNEL_ID}`));
- }
- });
-
- it('leaves the channel out when it is missing', () => {
- expect(present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {count: 5}})).toEqual(
- summaryOnly('Hampus deleted 5 messages'),
- );
- expect(present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {count: 1}})).toEqual(
- summaryOnly('Hampus deleted 1 message'),
- );
- expect(present({action_type: AuditLogActionType.MESSAGE_BULK_DELETE})).toEqual(
- summaryOnly('Hampus deleted some messages'),
- );
- });
-
- it('passes the count through as a number for the plural', () => {
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MESSAGE_BULK_DELETE, options: {channel_id: CHANNEL_ID, count: '12'}}),
- fakeContext(),
- );
- expect(presentation.summary.values.count).toBe(12);
- });
-
- it('is expandable only for the Reason block', () => {
- expect(
- present({
- action_type: AuditLogActionType.MESSAGE_BULK_DELETE,
- reason: 'Spam wave',
- options: {channel_id: CHANNEL_ID, count: 40},
- }),
- ).toEqual({
- summary: `Hampus deleted 40 messages in #${CHANNEL_ID}`,
- rows: [],
- blocks: [{kind: 'reason', text: 'Spam wave'}],
- expandable: true,
- });
- });
-});
-
-describe('junk input', () => {
- it('never throws and renders only summaries for every expression and message action', () => {
- const junkFixtures: Array<Omit<EntryFixture, 'action_type'>> = [
- {user_id: null, target_id: null},
- {
- target_id: 'not-a-snowflake',
- options: {channel_id: {}, count: [], message_id: 5},
- changes: [
- {key: 'name', old_value: {}, new_value: []},
- {key: 'description', old_value: 12, new_value: false},
- {key: 'creator_id', old_value: 1400, new_value: null},
- ],
- },
- ];
- for (const actionType of EXPRESSION_MESSAGE_ACTION_TYPES) {
- for (const fixture of junkFixtures) {
- const result = present({...fixture, action_type: actionType});
- expect(result.rows).toEqual([]);
- expect(result.blocks).toEqual([]);
- expect(result.expandable).toBe(false);
- }
- }
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogGuildPresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogGuildPresentation.test.ts
deleted file mode 100644
index 99c86c430..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogGuildPresentation.test.ts
+++ /dev/null
@@ -1,754 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentGuildUpdate} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogGuildPresentation';
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
- TEST_GUILD_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-interface ChangeFixture {
- key: string;
- old_value?: unknown;
- new_value?: unknown;
-}
-
-interface RowCase {
- title: string;
- changes: Array<ChangeFixture>;
- rows: Array<string>;
-}
-
-const NEW_OWNER_ID = '1400000000000000200';
-const FIRST_CHANNEL_ID = '1400000000000000300';
-const SECOND_CHANNEL_ID = '1400000000000000301';
-const USER_NAMES = {[TEST_ACTOR_ID]: 'Hampus', [NEW_OWNER_ID]: 'ender'};
-const SETTINGS_SUMMARY = 'Hampus updated the community settings';
-const STAFF_FEATURES = ['VANITY_URL', 'VERIFIED'];
-
-function change(key: string, oldValue: unknown, newValue: unknown): ChangeFixture {
- return {key, old_value: oldValue, new_value: newValue};
-}
-
-function featureChange(previous: Array<string>, next: Array<string>): ChangeFixture {
- return change('features', [...STAFF_FEATURES, ...previous], [...STAFF_FEATURES, ...next]);
-}
-
-const REQUIRE_2FA_CHANGE = change('mfa_level', 0, 1);
-const REQUIRE_2FA_ROW = '+ Required 2FA for moderation actions';
-
-function present(changes: Array<ChangeFixture> | undefined, fixture: {user_id?: string; reason?: string} = {}) {
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.GUILD_UPDATE, target_id: TEST_GUILD_ID, changes, ...fixture}),
- fakeContext(),
- );
- return {...resultToText(presentation, USER_NAMES), expandable: presentation.expandable};
-}
-
-function settingsUpdate(...rows: Array<string>) {
- return {summary: SETTINGS_SUMMARY, rows, blocks: [], expandable: true};
-}
-
-function summaryOnly(summary: string) {
- return {summary, rows: [], blocks: [], expandable: false};
-}
-
-const ROW_CASES: Array<RowCase> = [
- {
- title: 'row 1 renames the community',
- changes: [REQUIRE_2FA_CHANGE, change('name', 'Old Name', 'New Name')],
- rows: ['~ Renamed the community from Old Name to New Name', REQUIRE_2FA_ROW],
- },
- {
- title: 'row 2 adds a community icon',
- changes: [change('icon_hash', null, 'a_1f2e')],
- rows: ['+ Added a community icon'],
- },
- {
- title: 'row 2 changes the community icon',
- changes: [change('icon_hash', '1f2e', 'a_3c4d')],
- rows: ['~ Changed the community icon'],
- },
- {
- title: 'row 2 removes the community icon',
- changes: [change('icon_hash', '1f2e', null)],
- rows: ['- Removed the community icon'],
- },
- {
- title: 'row 3 adds a community banner',
- changes: [
- change('banner_hash', null, '5b6a'),
- change('banner_width', null, 960),
- change('banner_height', null, 540),
- ],
- rows: ['+ Added a community banner'],
- },
- {
- title: 'row 3 changes the community banner',
- changes: [change('banner_hash', '5b6a', '6c7b')],
- rows: ['~ Changed the community banner'],
- },
- {
- title: 'row 3 removes the community banner',
- changes: [
- change('banner_hash', '5b6a', null),
- change('banner_width', 960, null),
- change('banner_height', 540, null),
- ],
- rows: ['- Removed the community banner'],
- },
- {
- title: 'row 4 turns on the detached banner',
- changes: [featureChange([], ['DETACHED_BANNER'])],
- rows: ['+ Turned on the detached banner'],
- },
- {
- title: 'row 4 turns off the detached banner',
- changes: [featureChange(['DETACHED_BANNER'], [])],
- rows: ['- Turned off the detached banner'],
- },
- {
- title: 'row 5 adds an invite background',
- changes: [change('splash_hash', null, '7c8d')],
- rows: ['+ Added an invite background'],
- },
- {
- title: 'row 5 changes the invite background',
- changes: [change('splash_hash', '7c8d', '9e0f')],
- rows: ['~ Changed the invite background'],
- },
- {
- title: 'row 5 removes the invite background',
- changes: [change('splash_hash', '7c8d', null)],
- rows: ['- Removed the invite background'],
- },
- {
- title: 'row 6 changes the invite background alignment away from centered',
- changes: [change('splash_card_alignment', 0, 1)],
- rows: ['~ Changed the invite background alignment from Centered to Left aligned'],
- },
- {
- title: 'row 6 changes the invite background alignment back to centered',
- changes: [change('splash_card_alignment', 2, 0)],
- rows: ['~ Changed the invite background alignment from Right aligned to Centered'],
- },
- {
- title: 'row 7 adds a chat embed background',
- changes: [change('embed_splash_hash', null, '2a3b')],
- rows: ['+ Added a chat embed background'],
- },
- {
- title: 'row 7 changes the chat embed background',
- changes: [change('embed_splash_hash', '2a3b', '4c5d')],
- rows: ['~ Changed the chat embed background'],
- },
- {
- title: 'row 7 removes the chat embed background',
- changes: [change('embed_splash_hash', '2a3b', null)],
- rows: ['- Removed the chat embed background'],
- },
- {
- title: 'row 8 sets the system channel',
- changes: [change('system_channel_id', null, FIRST_CHANNEL_ID)],
- rows: [`+ Set the system channel to #${FIRST_CHANNEL_ID}`],
- },
- {
- title: 'row 8 changes the system channel',
- changes: [change('system_channel_id', FIRST_CHANNEL_ID, SECOND_CHANNEL_ID)],
- rows: [`~ Changed the system channel from #${FIRST_CHANNEL_ID} to #${SECOND_CHANNEL_ID}`],
- },
- {
- title: 'row 8 removes the system channel',
- changes: [change('system_channel_id', FIRST_CHANNEL_ID, null)],
- rows: ['- Removed the system channel'],
- },
- {
- title: 'row 9 hides join messages',
- changes: [change('system_channel_flags', 0, 1)],
- rows: ['~ Hid join messages in the system channel'],
- },
- {
- title: 'row 9 stops hiding join messages',
- changes: [change('system_channel_flags', 1, 0)],
- rows: ['~ Stopped hiding join messages in the system channel'],
- },
- {
- title: 'row 10 changes the default notifications to mentions only',
- changes: [change('default_message_notifications', 0, 1)],
- rows: ['~ Changed the default notification setting from All messages to Mentions only'],
- },
- {
- title: 'row 10 changes the default notifications to all messages',
- changes: [change('default_message_notifications', 1, 0)],
- rows: ['~ Changed the default notification setting from Mentions only to All messages'],
- },
- {
- title: 'row 11 sets the AFK channel',
- changes: [change('afk_channel_id', null, FIRST_CHANNEL_ID)],
- rows: [`+ Set the AFK channel to #${FIRST_CHANNEL_ID}`],
- },
- {
- title: 'row 11 changes the AFK channel',
- changes: [change('afk_channel_id', FIRST_CHANNEL_ID, SECOND_CHANNEL_ID)],
- rows: [`~ Changed the AFK channel from #${FIRST_CHANNEL_ID} to #${SECOND_CHANNEL_ID}`],
- },
- {
- title: 'row 11 removes the AFK channel',
- changes: [change('afk_channel_id', FIRST_CHANNEL_ID, null)],
- rows: ['- Removed the AFK channel'],
- },
- {
- title: 'row 12 lengthens the AFK timeout',
- changes: [change('afk_timeout', 300, 900)],
- rows: ['~ Changed the AFK timeout from 5 minutes to 15 minutes'],
- },
- {
- title: 'row 12 shortens the AFK timeout',
- changes: [change('afk_timeout', 900, 300)],
- rows: ['~ Changed the AFK timeout from 15 minutes to 5 minutes'],
- },
- {
- title: 'row 13 allows flexible text channel names',
- changes: [featureChange([], ['TEXT_CHANNEL_FLEXIBLE_NAMES'])],
- rows: ['+ Allowed flexible text channel names'],
- },
- {
- title: 'row 13 stops allowing flexible text channel names',
- changes: [featureChange(['TEXT_CHANNEL_FLEXIBLE_NAMES'], [])],
- rows: ['- Stopped allowing flexible text channel names'],
- },
- {
- title: 'row 14 hides the owner crown',
- changes: [featureChange([], ['HIDE_OWNER_CROWN'])],
- rows: ['~ Hid the community owner crown'],
- },
- {
- title: 'row 14 stops hiding the owner crown',
- changes: [featureChange(['HIDE_OWNER_CROWN'], [])],
- rows: ['~ Stopped hiding the community owner crown'],
- },
- {
- title: 'row 15 sets the message history threshold',
- changes: [change('message_history_cutoff', null, '2026-08-01T00:00:00.000Z')],
- rows: ['+ Set the message history threshold to 2026-08-01T00:00:00.000Z'],
- },
- {
- title: 'row 15 changes the message history threshold',
- changes: [change('message_history_cutoff', '2026-08-01T00:00:00.000Z', '2026-08-15T09:30:00.000Z')],
- rows: ['~ Changed the message history threshold from 2026-08-01T00:00:00.000Z to 2026-08-15T09:30:00.000Z'],
- },
- {
- title: 'row 15 removes the message history threshold',
- changes: [change('message_history_cutoff', '2026-08-01T00:00:00.000Z', null)],
- rows: ['- Removed the message history threshold'],
- },
- {
- title: 'row 16 pauses invites',
- changes: [REQUIRE_2FA_CHANGE, featureChange([], ['INVITES_DISABLED'])],
- rows: ['- Paused invites', REQUIRE_2FA_ROW],
- },
- {
- title: 'row 16 resumes invites',
- changes: [REQUIRE_2FA_CHANGE, featureChange(['INVITES_DISABLED'], [])],
- rows: ['+ Resumed invites', REQUIRE_2FA_ROW],
- },
- {
- title: 'row 17 allows others to clone emojis',
- changes: [featureChange([], ['CLONE_EMOJI_ENABLED'])],
- rows: ["+ Allowed others to clone this community's emojis"],
- },
- {
- title: 'row 17 stops allowing others to clone emojis',
- changes: [featureChange(['CLONE_EMOJI_ENABLED'], [])],
- rows: ["- Stopped allowing others to clone this community's emojis"],
- },
- {
- title: 'row 18 allows others to clone stickers',
- changes: [featureChange([], ['CLONE_STICKER_ENABLED'])],
- rows: ["+ Allowed others to clone this community's stickers"],
- },
- {
- title: 'row 18 stops allowing others to clone stickers',
- changes: [featureChange(['CLONE_STICKER_ENABLED'], [])],
- rows: ["- Stopped allowing others to clone this community's stickers"],
- },
- {
- title: 'row 19 raises the verification level',
- changes: [change('verification_level', 0, 2)],
- rows: ['~ Changed the verification level from None to Medium'],
- },
- {
- title: 'row 19 lowers the verification level',
- changes: [change('verification_level', 4, 1)],
- rows: ['~ Changed the verification level from Very high to Low'],
- },
- {
- title: 'row 20 turns on the explicit content filter',
- changes: [change('explicit_content_filter', 0, 1)],
- rows: ['~ Changed the explicit content filter from Off to Filter members without roles'],
- },
- {
- title: 'row 20 turns off the explicit content filter',
- changes: [change('explicit_content_filter', 2, 0)],
- rows: ['~ Changed the explicit content filter from Filter everyone to Off'],
- },
- {
- title: 'row 21 turns on mature content',
- changes: [change('nsfw_level', 0, 3), change('nsfw', false, true)],
- rows: ['+ Turned on mature content'],
- },
- {
- title: 'row 21 turns off mature content',
- changes: [change('nsfw_level', 3, 0), change('nsfw', true, false)],
- rows: ['- Turned off mature content'],
- },
- {
- title: 'row 22 turns on the content warning',
- changes: [change('content_warning_level', 0, 1)],
- rows: ['+ Turned on the content warning'],
- },
- {
- title: 'row 22 turns off the content warning',
- changes: [change('content_warning_level', 1, 0)],
- rows: ['- Turned off the content warning'],
- },
- {
- title: 'row 23 sets the custom warning text',
- changes: [change('content_warning_text', null, 'Spoilers ahead')],
- rows: ['+ Set the custom warning text to Spoilers ahead'],
- },
- {
- title: 'row 23 changes the custom warning text',
- changes: [change('content_warning_text', 'Spoilers ahead', 'Graphic content')],
- rows: ['~ Changed the custom warning text from Spoilers ahead to Graphic content'],
- },
- {
- title: 'row 23 removes the custom warning text',
- changes: [change('content_warning_text', 'Spoilers ahead', null)],
- rows: ['- Removed the custom warning text'],
- },
- {title: 'row 24 requires 2FA for moderation', changes: [REQUIRE_2FA_CHANGE], rows: [REQUIRE_2FA_ROW]},
- {
- title: 'row 24 stops requiring 2FA for moderation',
- changes: [change('mfa_level', 1, 0)],
- rows: ['- Stopped requiring 2FA for moderation actions'],
- },
- {
- title: 'row 25 transfers ownership next to another change',
- changes: [change('owner_id', TEST_ACTOR_ID, NEW_OWNER_ID), REQUIRE_2FA_CHANGE],
- rows: [REQUIRE_2FA_ROW, '~ Transferred community ownership to ender'],
- },
- {
- title: 'row 26 sets the vanity URL next to another change',
- changes: [change('vanity_url_code', null, 'fluxer'), REQUIRE_2FA_CHANGE],
- rows: [REQUIRE_2FA_ROW, '+ Set the vanity URL to fluxer'],
- },
- {
- title: 'row 26 changes the vanity URL next to another change',
- changes: [change('vanity_url_code', 'fluxer', 'fluxerhq'), REQUIRE_2FA_CHANGE],
- rows: [REQUIRE_2FA_ROW, '~ Changed the vanity URL from fluxer to fluxerhq'],
- },
- {
- title: 'row 26 removes the vanity URL next to another change',
- changes: [change('vanity_url_code', 'fluxer', null), REQUIRE_2FA_CHANGE],
- rows: [REQUIRE_2FA_ROW, '- Removed the vanity URL fluxer'],
- },
-];
-
-const EVERY_ROW_CHANGES: Array<ChangeFixture> = [
- change('name', 'Old Name', 'New Name'),
- change('icon_hash', null, 'a_1f2e'),
- change('banner_hash', '5b6a', null),
- featureChange(
- [],
- [
- 'CLONE_EMOJI_ENABLED',
- 'CLONE_STICKER_ENABLED',
- 'DETACHED_BANNER',
- 'HIDE_OWNER_CROWN',
- 'INVITES_DISABLED',
- 'TEXT_CHANNEL_FLEXIBLE_NAMES',
- ],
- ),
- change('splash_hash', '7c8d', '9e0f'),
- change('splash_card_alignment', 0, 1),
- change('embed_splash_hash', null, '2a3b'),
- change('system_channel_id', null, FIRST_CHANNEL_ID),
- change('system_channel_flags', 0, 1),
- change('default_message_notifications', 0, 1),
- change('afk_channel_id', FIRST_CHANNEL_ID, SECOND_CHANNEL_ID),
- change('afk_timeout', 300, 900),
- change('message_history_cutoff', null, '2026-08-01T00:00:00.000Z'),
- change('verification_level', 1, 3),
- change('explicit_content_filter', 0, 2),
- change('nsfw', false, true),
- change('content_warning_level', 0, 1),
- change('content_warning_text', null, 'Spoilers ahead'),
- change('mfa_level', 0, 1),
- change('owner_id', TEST_ACTOR_ID, NEW_OWNER_ID),
- change('vanity_url_code', 'fluxer', 'fluxerhq'),
-];
-
-describe('presentGuildUpdate summaries', () => {
- it('names the new owner when ownership transfer is the only change', () => {
- expect(present([change('owner_id', TEST_ACTOR_ID, NEW_OWNER_ID)])).toEqual(
- summaryOnly('Hampus transferred community ownership to ender'),
- );
- });
-
- it('keeps the Reason block on a summary that has no rows', () => {
- expect(present([change('owner_id', TEST_ACTOR_ID, NEW_OWNER_ID)], {reason: 'Stepping%20down'})).toEqual({
- summary: 'Hampus transferred community ownership to ender',
- rows: [],
- blocks: [{kind: 'reason', text: 'Stepping down'}],
- expandable: true,
- });
- });
-
- it('summarizes a lone vanity URL change in every direction', () => {
- expect(present([change('vanity_url_code', null, 'fluxer')])).toEqual(
- summaryOnly('Hampus set the vanity URL to fluxer'),
- );
- expect(present([change('vanity_url_code', 'fluxer', 'fluxerhq')])).toEqual(
- summaryOnly('Hampus changed the vanity URL from fluxer to fluxerhq'),
- );
- expect(present([change('vanity_url_code', 'fluxer', null)])).toEqual(
- summaryOnly('Hampus removed the vanity URL fluxer'),
- );
- });
-
- it('summarizes pausing and resuming invites when that is the only change', () => {
- expect(present([featureChange([], ['INVITES_DISABLED'])])).toEqual(summaryOnly('Hampus paused invites'));
- expect(present([featureChange(['INVITES_DISABLED'], [])])).toEqual(summaryOnly('Hampus resumed invites'));
- });
-
- it('summarizes a lone rename', () => {
- expect(present([change('name', 'Old Name', 'New Name')])).toEqual(
- summaryOnly('Hampus renamed the community from Old Name to New Name'),
- );
- });
-
- it('keeps a single-change summary when ignored keys change alongside it', () => {
- expect(
- present([
- change('guild_id', TEST_GUILD_ID, TEST_GUILD_ID),
- featureChange([], ['INVITES_DISABLED', 'DISCOVERABLE']),
- change('member_count', 10, 11),
- ]),
- ).toEqual(summaryOnly('Hampus paused invites'));
- });
-
- it('names the system as the actor', () => {
- expect(present([featureChange([], ['INVITES_DISABLED'])], {user_id: '0'})).toEqual(
- summaryOnly('System paused invites'),
- );
- expect(present([REQUIRE_2FA_CHANGE], {user_id: '0'})).toEqual({
- ...settingsUpdate(REQUIRE_2FA_ROW),
- summary: 'System updated the community settings',
- });
- });
-
- it('uses the settings summary with no rows when nothing changed', () => {
- expect(present(undefined)).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('adds the Reason block under the settings summary', () => {
- expect(present([REQUIRE_2FA_CHANGE], {reason: 'Raid protection'})).toEqual({
- ...settingsUpdate(REQUIRE_2FA_ROW),
- blocks: [{kind: 'reason', text: 'Raid protection'}],
- });
- });
-});
-
-describe('presentGuildUpdate rows', () => {
- it.each(ROW_CASES)('$title', ({changes, rows}) => {
- expect(present(changes)).toEqual(settingsUpdate(...rows));
- });
-
- it('orders every row by the settings layout, not by the stored order', () => {
- expect(present([...EVERY_ROW_CHANGES].reverse())).toEqual(
- settingsUpdate(
- '~ Renamed the community from Old Name to New Name',
- '+ Added a community icon',
- '- Removed the community banner',
- '+ Turned on the detached banner',
- '~ Changed the invite background',
- '~ Changed the invite background alignment from Centered to Left aligned',
- '+ Added a chat embed background',
- `+ Set the system channel to #${FIRST_CHANNEL_ID}`,
- '~ Hid join messages in the system channel',
- '~ Changed the default notification setting from All messages to Mentions only',
- `~ Changed the AFK channel from #${FIRST_CHANNEL_ID} to #${SECOND_CHANNEL_ID}`,
- '~ Changed the AFK timeout from 5 minutes to 15 minutes',
- '+ Allowed flexible text channel names',
- '~ Hid the community owner crown',
- '+ Set the message history threshold to 2026-08-01T00:00:00.000Z',
- '- Paused invites',
- "+ Allowed others to clone this community's emojis",
- "+ Allowed others to clone this community's stickers",
- '~ Changed the verification level from Low to High',
- '~ Changed the explicit content filter from Off to Filter everyone',
- '+ Turned on mature content',
- '+ Turned on the content warning',
- '+ Set the custom warning text to Spoilers ahead',
- REQUIRE_2FA_ROW,
- '~ Transferred community ownership to ender',
- '~ Changed the vanity URL from fluxer to fluxerhq',
- ),
- );
- });
-
- it('gives every row a distinct id', () => {
- const result = presentGuildUpdate(
- makeEntry({action_type: AuditLogActionType.GUILD_UPDATE, changes: EVERY_ROW_CHANGES}),
- );
- expect(new Set(result.rows.map((row) => row.id)).size).toBe(26);
- });
-
- it('renders the overview save example in settings order', () => {
- expect(
- present([
- change('name', 'Old Name', 'New Name'),
- change('icon_hash', '1f2e', 'a_3c4d'),
- featureChange([], ['HIDE_OWNER_CROWN']),
- change('system_channel_flags', 0, 1),
- change('afk_timeout', 300, 900),
- ]),
- ).toEqual(
- settingsUpdate(
- '~ Renamed the community from Old Name to New Name',
- '~ Changed the community icon',
- '~ Hid join messages in the system channel',
- '~ Changed the AFK timeout from 5 minutes to 15 minutes',
- '~ Hid the community owner crown',
- ),
- );
- });
-
- it('renders the moderation save example in settings order', () => {
- expect(
- present([
- change('nsfw_level', 0, 3),
- change('nsfw', false, true),
- change('content_warning_level', 0, 1),
- change('content_warning_text', null, 'Spoilers ahead'),
- ]),
- ).toEqual(
- settingsUpdate(
- '+ Turned on mature content',
- '+ Turned on the content warning',
- '+ Set the custom warning text to Spoilers ahead',
- ),
- );
- });
-
- it('renders 60 seconds and 3600 seconds in their largest whole unit', () => {
- expect(present([change('afk_timeout', 60, 3600)])).toEqual(
- settingsUpdate('~ Changed the AFK timeout from 1 minute to 1 hour'),
- );
- });
-
- it('reads values sent as strings', () => {
- expect(
- present([
- change('splash_card_alignment', '0', '2'),
- change('system_channel_flags', '0', '1'),
- change('afk_timeout', '300', '600'),
- change('nsfw', 'false', 'true'),
- change('mfa_level', '1', '0'),
- ]),
- ).toEqual(
- settingsUpdate(
- '~ Changed the invite background alignment from Centered to Right aligned',
- '~ Hid join messages in the system channel',
- '~ Changed the AFK timeout from 5 minutes to 10 minutes',
- '+ Turned on mature content',
- '- Stopped requiring 2FA for moderation actions',
- ),
- );
- });
-});
-
-describe('presentGuildUpdate legacy and ignored values', () => {
- it('reads legacy CLONE_*_DISABLED features with the inverse meaning', () => {
- expect(present([featureChange([], ['CLONE_EMOJI_DISABLED'])])).toEqual(
- settingsUpdate("- Stopped allowing others to clone this community's emojis"),
- );
- expect(present([featureChange(['CLONE_EMOJI_DISABLED'], [])])).toEqual(
- settingsUpdate("+ Allowed others to clone this community's emojis"),
- );
- expect(present([featureChange([], ['CLONE_STICKER_DISABLED'])])).toEqual(
- settingsUpdate("- Stopped allowing others to clone this community's stickers"),
- );
- expect(present([featureChange(['CLONE_STICKER_DISABLED'], [])])).toEqual(
- settingsUpdate("+ Allowed others to clone this community's stickers"),
- );
- });
-
- it('gives one cloning row decided by the ENABLED feature when both forms change', () => {
- expect(present([featureChange(['CLONE_EMOJI_DISABLED'], ['CLONE_EMOJI_ENABLED'])])).toEqual(
- settingsUpdate("+ Allowed others to clone this community's emojis"),
- );
- expect(present([featureChange(['CLONE_EMOJI_DISABLED', 'CLONE_EMOJI_ENABLED'], [])])).toEqual(
- settingsUpdate("- Stopped allowing others to clone this community's emojis"),
- );
- expect(present([featureChange(['CLONE_STICKER_DISABLED', 'CLONE_STICKER_ENABLED'], [])])).toEqual(
- settingsUpdate("- Stopped allowing others to clone this community's stickers"),
- );
- });
-
- it('ignores a change to untracked features only', () => {
- expect(present([featureChange([], ['DISCOVERABLE', 'UNLIMITED_EMOJI'])])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('ignores a change to image dimensions only', () => {
- expect(
- present([
- change('banner_width', null, 960),
- change('banner_height', null, 540),
- change('splash_width', 1280, 1920),
- change('splash_height', 720, 1080),
- change('embed_splash_width', null, 640),
- change('embed_splash_height', null, 360),
- ]),
- ).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('ignores rules_channel_id, disabled_operations, region, guild_id, member_count and unlisted keys', () => {
- expect(
- present([
- change('rules_channel_id', FIRST_CHANNEL_ID, null),
- change('disabled_operations', 0, 1),
- change('region', 'us-east', 'eu-west'),
- change('guild_id', null, TEST_GUILD_ID),
- change('member_count', 10, 11),
- change('discovery_splash_hash', null, '1a2b'),
- ]),
- ).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('reads mature content from nsfw_level when nsfw is absent', () => {
- expect(present([change('nsfw_level', 0, 3)])).toEqual(settingsUpdate('+ Turned on mature content'));
- expect(present([change('nsfw_level', 3, 0)])).toEqual(settingsUpdate('- Turned off mature content'));
- });
-
- it('ignores nsfw_level values other than 0 and 3', () => {
- expect(present([change('nsfw_level', 0, 1)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('nsfw_level', 2, 3)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('ignores nsfw_level when nsfw is present', () => {
- expect(present([change('nsfw_level', 0, 3), change('nsfw', true, false)])).toEqual(
- settingsUpdate('- Turned off mature content'),
- );
- expect(present([change('nsfw_level', 0, 3), change('nsfw', true, true)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('reads only the join messages bit of system_channel_flags', () => {
- expect(present([change('system_channel_flags', 1, 3)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('system_channel_flags', 2, 3)])).toEqual(
- settingsUpdate('~ Hid join messages in the system channel'),
- );
- });
-
- it('omits a verification level outside the label table', () => {
- expect(present([change('verification_level', 3, 5)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('verification_level', 3, 5), REQUIRE_2FA_CHANGE])).toEqual(settingsUpdate(REQUIRE_2FA_ROW));
- });
-
- it('omits alignment, notification and filter values outside their label tables', () => {
- expect(
- present([
- change('splash_card_alignment', 0, 3),
- change('default_message_notifications', 1, 2),
- change('explicit_content_filter', 2, 3),
- ]),
- ).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('omits content warning and 2FA values other than 0 and 1', () => {
- expect(present([change('content_warning_level', 0, 2), change('mfa_level', 2, 1)])).toEqual(
- summaryOnly(SETTINGS_SUMMARY),
- );
- });
-
- it('omits an unparseable message history threshold', () => {
- expect(present([change('message_history_cutoff', null, 'not a date')])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('message_history_cutoff', 'not a date', '2026-08-01T00:00:00.000Z')])).toEqual(
- summaryOnly(SETTINGS_SUMMARY),
- );
- });
-
- it('gives the settings summary without rows when the new owner cannot be read', () => {
- expect(present([change('owner_id', TEST_ACTOR_ID, 'not-a-snowflake')])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('owner_id', TEST_ACTOR_ID, null)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('owner_id', TEST_ACTOR_ID, Number(NEW_OWNER_ID))])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('owner_id', TEST_ACTOR_ID, TEST_ACTOR_ID)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- });
-
- it('treats blank text as empty and skips values that are equal after reading', () => {
- expect(
- present([
- change('name', 'Same Name', ' Same Name '),
- change('icon_hash', '', null),
- change('vanity_url_code', ' ', null),
- change('content_warning_text', 'Spoilers', 'Spoilers '),
- change('afk_timeout', 300, 300.2),
- change('system_channel_id', FIRST_CHANNEL_ID, FIRST_CHANNEL_ID),
- ]),
- ).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('content_warning_text', 'Spoilers', ' ')])).toEqual(
- settingsUpdate('- Removed the custom warning text'),
- );
- });
-
- it('omits every row whose values fail their readers without throwing', () => {
- expect(
- present([
- change('name', 5, 'New Name'),
- change('icon_hash', 7, 'a_1f2e'),
- change('banner_hash', null, {hash: '5b6a'}),
- change('features', 'DETACHED_BANNER', ['DETACHED_BANNER']),
- change('splash_hash', ['7c8d'], null),
- change('splash_card_alignment', 'left', 1),
- change('embed_splash_hash', true, null),
- change('system_channel_id', 'general', FIRST_CHANNEL_ID),
- change('system_channel_flags', -1, 1),
- change('default_message_notifications', null, 1),
- change('afk_channel_id', null, Number(FIRST_CHANNEL_ID)),
- change('afk_timeout', 'soon', 900),
- change('verification_level', 1.5, 2),
- change('explicit_content_filter', {}, 0),
- change('nsfw', 'yes', true),
- change('content_warning_level', null, 1),
- change('content_warning_text', 42, 'Spoilers ahead'),
- change('mfa_level', 'required', 1),
- change('vanity_url_code', null, 1234),
- ]),
- ).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([change('afk_timeout', -300, 900)])).toEqual(summaryOnly(SETTINGS_SUMMARY));
- expect(present([{key: 'name'}, {key: 'features', new_value: ['INVITES_DISABLED']}])).toEqual(
- summaryOnly(SETTINGS_SUMMARY),
- );
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogInviteWebhookPresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogInviteWebhookPresentation.test.ts
deleted file mode 100644
index 7e3b2948a..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogInviteWebhookPresentation.test.ts
+++ /dev/null
@@ -1,641 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import type {AuditLogPresentationContext} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentationTypes';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
- TEST_GUILD_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-type EntryFixture = Parameters<typeof makeEntry>[0];
-type ChangeFixture = NonNullable<EntryFixture['changes']>;
-
-const ALICE_ID = '1400000000000000002';
-const CHANNEL_ID = '1400000000000000200';
-const OTHER_CHANNEL_ID = '1400000000000000201';
-const WEBHOOK_ID = '1400000000000000300';
-const INVITE_CODE = 'aB3dE9xZ';
-const USER_NAMES = {[TEST_ACTOR_ID]: 'Hampus', [ALICE_ID]: 'Alice'};
-
-function present(fixture: EntryFixture, context: AuditLogPresentationContext = fakeContext()) {
- const presentation = presentAuditLogEntry(makeEntry(fixture), context);
- return {...resultToText(presentation, USER_NAMES), expandable: presentation.expandable};
-}
-
-function snapshot(side: 'old_value' | 'new_value', values: Record<string, unknown>): ChangeFixture {
- return Object.entries(values).map(([key, value]) => ({key, [side]: value}));
-}
-
-interface InviteSettingsFixture {
- max_age: number;
- max_uses: number;
- temporary: boolean;
-}
-
-function inviteCreate(settings: InviteSettingsFixture): EntryFixture {
- return {
- action_type: AuditLogActionType.INVITE_CREATE,
- target_id: INVITE_CODE,
- options: {...settings, channel_id: CHANNEL_ID, inviter_id: TEST_ACTOR_ID},
- changes: snapshot('new_value', {
- code: INVITE_CODE,
- channel_id: CHANNEL_ID,
- guild_id: TEST_GUILD_ID,
- inviter_id: TEST_ACTOR_ID,
- uses: 0,
- ...settings,
- created_at: '2026-09-01T11:59:59.990Z',
- }),
- };
-}
-
-interface InviteDeleteFixture extends InviteSettingsFixture {
- user_id?: string;
- inviter_id: string;
- uses: number;
- created_at?: string;
-}
-
-function inviteDelete({user_id, inviter_id, uses, created_at, ...settings}: InviteDeleteFixture): EntryFixture {
- return {
- action_type: AuditLogActionType.INVITE_DELETE,
- user_id: user_id ?? TEST_ACTOR_ID,
- target_id: INVITE_CODE,
- options: {...settings, channel_id: CHANNEL_ID, inviter_id},
- changes: snapshot('old_value', {
- code: INVITE_CODE,
- channel_id: CHANNEL_ID,
- guild_id: TEST_GUILD_ID,
- inviter_id,
- uses,
- ...settings,
- ...(created_at === undefined ? {} : {created_at}),
- }),
- };
-}
-
-function webhookSnapshot(side: 'old_value' | 'new_value', creatorId: string): ChangeFixture {
- return snapshot(side, {
- id: WEBHOOK_ID,
- guild_id: TEST_GUILD_ID,
- channel_id: CHANNEL_ID,
- name: 'Captain Hook',
- creator_id: creatorId,
- avatar_hash: null,
- type: 1,
- });
-}
-
-function webhookUpdate(changes: ChangeFixture | undefined): EntryFixture {
- return {
- action_type: AuditLogActionType.WEBHOOK_UPDATE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- changes,
- };
-}
-
-const WEBHOOK_NAMES = fakeContext({webhooks: {[WEBHOOK_ID]: 'Captain Hook'}});
-
-describe('presentInviteCreate', () => {
- it('describes an invite created with the app defaults', () => {
- expect(present(inviteCreate({max_age: 604800, max_uses: 0, temporary: false}))).toEqual({
- summary: `Hampus created the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: ['~ The invite was set to expire after 7 days', '~ The invite was set to allow unlimited uses'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('describes a 30 minute single use invite that grants temporary membership', () => {
- expect(present(inviteCreate({max_age: 1800, max_uses: 1, temporary: true}))).toEqual({
- summary: `Hampus created the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was set to expire after 30 minutes',
- '~ The invite was limited to 1 use',
- '~ The invite was set to grant temporary membership',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('renders a 5400 second expiry as 90 minutes and pluralizes the use limit', () => {
- expect(present(inviteCreate({max_age: 5400, max_uses: 25, temporary: false})).rows).toEqual([
- '~ The invite was set to expire after 90 minutes',
- '~ The invite was limited to 25 uses',
- ]);
- });
-
- it('reads the dispatch string form of the options', () => {
- expect(
- present({
- action_type: AuditLogActionType.INVITE_CREATE,
- target_id: INVITE_CODE,
- options: {
- max_uses: '10',
- max_age: '0',
- temporary: 'true',
- channel_id: CHANNEL_ID,
- inviter_id: TEST_ACTOR_ID,
- },
- }),
- ).toEqual({
- summary: `Hampus created the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was set to never expire',
- '~ The invite was limited to 10 uses',
- '~ The invite was set to grant temporary membership',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('leaves the channel out of the summary when no channel id was recorded', () => {
- const {options, changes, ...fixture} = inviteCreate({max_age: 604800, max_uses: 0, temporary: false});
- const {channel_id: _channelId, ...optionsWithoutChannel} = options ?? {};
- expect(
- present({
- ...fixture,
- options: optionsWithoutChannel,
- changes: changes?.filter((change) => change.key !== 'channel_id'),
- }),
- ).toEqual({
- summary: 'Hampus created the invite aB3dE9xZ',
- rows: ['~ The invite was set to expire after 7 days', '~ The invite was set to allow unlimited uses'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('falls back to the changes for the code, channel and settings when options are missing', () => {
- const {options: _options, ...fixture} = inviteCreate({max_age: 3600, max_uses: 5, temporary: true});
- expect(present({...fixture, target_id: null})).toEqual({
- summary: `Hampus created the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was set to expire after 1 hour',
- '~ The invite was limited to 5 uses',
- '~ The invite was set to grant temporary membership',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('omits the channel and every row whose value cannot be read', () => {
- expect(
- present({
- action_type: AuditLogActionType.INVITE_CREATE,
- user_id: '0',
- target_id: INVITE_CODE,
- options: {max_age: -60, max_uses: 1.5, temporary: 'yes', channel_id: 'general'},
- changes: [
- {key: 'max_age', new_value: 'forever'},
- {key: 'max_uses', new_value: null},
- {key: 'temporary', new_value: 1},
- {key: 'channel_id', new_value: 42},
- ],
- }),
- ).toEqual({
- summary: 'System created the invite aB3dE9xZ',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('presentInviteUpdate', () => {
- it('summarizes the invite without rows', () => {
- expect(
- present({
- action_type: AuditLogActionType.INVITE_UPDATE,
- target_id: INVITE_CODE,
- options: {max_age: 0, max_uses: 3, channel_id: CHANNEL_ID},
- }),
- ).toEqual({
- summary: 'Hampus updated the invite aB3dE9xZ',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('presentInviteDelete', () => {
- it('describes an own invite deleted after 3 uses with its expiry date', () => {
- expect(
- present(
- inviteDelete({
- inviter_id: TEST_ACTOR_ID,
- uses: 3,
- max_uses: 0,
- max_age: 604800,
- temporary: false,
- created_at: '2026-08-30T12:00:00.000Z',
- }),
- ),
- ).toEqual({
- summary: `Hampus deleted the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was created on 2026-08-30T12:00:00.000Z',
- '~ The invite was used 3 times',
- '~ The invite was scheduled to expire on 2026-09-06T12:00:00.000Z',
- '~ The invite was set to allow unlimited uses',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it("names the creator when a moderator deletes another member's temporary invite", () => {
- expect(
- present(
- inviteDelete({
- inviter_id: ALICE_ID,
- uses: 1,
- max_uses: 5,
- max_age: 0,
- temporary: true,
- created_at: '2026-08-31T08:30:00.000Z',
- }),
- ),
- ).toEqual({
- summary: `Hampus deleted the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was created by Alice on 2026-08-31T08:30:00.000Z',
- '~ The invite was used 1 time',
- '~ The invite was set to never expire',
- '~ The invite was limited to 5 uses',
- '~ The invite was set to grant temporary membership',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names the creator without a date and gives the expiry as a duration when created_at is missing', () => {
- expect(
- present(inviteDelete({inviter_id: ALICE_ID, uses: 0, max_uses: 1, max_age: 86400, temporary: false})),
- ).toEqual({
- summary: `Hampus deleted the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was created by Alice',
- '~ The invite was never used',
- '~ The invite was set to expire after 1 day',
- '~ The invite was limited to 1 use',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('gives no creator row for an own invite without created_at and says a max_age of 0 never expires', () => {
- expect(
- present(inviteDelete({inviter_id: TEST_ACTOR_ID, uses: 0, max_uses: 0, max_age: 0, temporary: false})).rows,
- ).toEqual([
- '~ The invite was never used',
- '~ The invite was set to never expire',
- '~ The invite was set to allow unlimited uses',
- ]);
- });
-
- it('reads the dispatch string form of the options', () => {
- expect(
- present({
- action_type: AuditLogActionType.INVITE_DELETE,
- target_id: INVITE_CODE,
- options: {
- max_uses: '2',
- max_age: '3600',
- temporary: 'false',
- channel_id: CHANNEL_ID,
- inviter_id: ALICE_ID,
- },
- changes: [
- {key: 'uses', old_value: 2},
- {key: 'created_at', old_value: '2026-09-01T10:00:00.000Z'},
- ],
- }).rows,
- ).toEqual([
- '~ The invite was created by Alice on 2026-09-01T10:00:00.000Z',
- '~ The invite was used 2 times',
- '~ The invite was scheduled to expire on 2026-09-01T11:00:00.000Z',
- '~ The invite was limited to 2 uses',
- ]);
- });
-
- it('falls back to the changes for the code, channel, inviter and settings when options are missing', () => {
- const {options: _options, ...fixture} = inviteDelete({
- inviter_id: ALICE_ID,
- uses: 4,
- max_uses: 10,
- max_age: 1800,
- temporary: true,
- created_at: '2026-09-01T11:00:00.000Z',
- });
- expect(present({...fixture, target_id: null})).toEqual({
- summary: `Hampus deleted the invite aB3dE9xZ for #${CHANNEL_ID}`,
- rows: [
- '~ The invite was created by Alice on 2026-09-01T11:00:00.000Z',
- '~ The invite was used 4 times',
- '~ The invite was scheduled to expire on 2026-09-01T11:30:00.000Z',
- '~ The invite was limited to 10 uses',
- '~ The invite was set to grant temporary membership',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('omits the channel and every row whose value cannot be read', () => {
- expect(
- present({
- action_type: AuditLogActionType.INVITE_DELETE,
- target_id: INVITE_CODE,
- options: {inviter_id: 'alice', max_age: 'never', channel_id: ''},
- changes: [
- {key: 'uses', old_value: 'many'},
- {key: 'created_at', old_value: 'yesterday'},
- {key: 'inviter_id', old_value: 42},
- {key: 'max_uses', old_value: -1},
- {key: 'temporary', old_value: 'maybe'},
- ],
- }),
- ).toEqual({
- summary: 'Hampus deleted the invite aB3dE9xZ',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('presentWebhookCreate', () => {
- it('names the webhook and its channel', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_CREATE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- changes: webhookSnapshot('new_value', TEST_ACTOR_ID),
- }),
- ).toEqual({
- summary: `Hampus created the webhook Captain Hook in #${CHANNEL_ID}`,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('names the webhook without a channel when none was recorded', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_CREATE,
- target_id: WEBHOOK_ID,
- changes: webhookSnapshot('new_value', TEST_ACTOR_ID).filter((change) => change.key !== 'channel_id'),
- }).summary,
- ).toBe('Hampus created the webhook Captain Hook');
- });
-
- it('says a webhook was created when no name was recorded', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_CREATE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- }),
- ).toEqual({summary: 'Hampus created a webhook', rows: [], blocks: [], expandable: false});
- });
-
- it('takes the channel from the changes when the option is missing', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_CREATE,
- target_id: WEBHOOK_ID,
- changes: webhookSnapshot('new_value', TEST_ACTOR_ID),
- }).summary,
- ).toBe(`Hampus created the webhook Captain Hook in #${CHANNEL_ID}`);
- });
-
- it('is expandable only for the decoded Reason block', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_CREATE,
- target_id: WEBHOOK_ID,
- reason: 'Release%20notes',
- options: {channel_id: CHANNEL_ID},
- changes: webhookSnapshot('new_value', TEST_ACTOR_ID),
- }),
- ).toEqual({
- summary: `Hampus created the webhook Captain Hook in #${CHANNEL_ID}`,
- rows: [],
- blocks: [{kind: 'reason', text: 'Release notes'}],
- expandable: true,
- });
- });
-});
-
-describe('presentWebhookUpdate', () => {
- it('summarizes a rename alone without rows', () => {
- expect(present(webhookUpdate([{key: 'name', old_value: 'Hook A', new_value: 'Hook B'}]), WEBHOOK_NAMES)).toEqual({
- summary: 'Hampus renamed the webhook Hook A to Hook B',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('marks an added avatar', () => {
- expect(
- present(webhookUpdate([{key: 'avatar_hash', old_value: null, new_value: 'a1b2c3d4'}]), WEBHOOK_NAMES),
- ).toEqual({
- summary: 'Hampus updated the webhook Captain Hook',
- rows: ['+ Added an avatar'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('marks a replaced avatar', () => {
- expect(
- present(webhookUpdate([{key: 'avatar_hash', old_value: 'a1b2c3d4', new_value: 'a_9f8e7d6c'}]), WEBHOOK_NAMES)
- .rows,
- ).toEqual(['~ Changed the avatar']);
- });
-
- it('marks a removed avatar', () => {
- expect(
- present(webhookUpdate([{key: 'avatar_hash', old_value: 'a1b2c3d4', new_value: null}]), WEBHOOK_NAMES).rows,
- ).toEqual(['- Removed the avatar']);
- });
-
- it('describes a move between channels', () => {
- expect(
- present(webhookUpdate([{key: 'channel_id', old_value: CHANNEL_ID, new_value: OTHER_CHANNEL_ID}]), WEBHOOK_NAMES),
- ).toEqual({
- summary: 'Hampus updated the webhook Captain Hook',
- rows: [`~ Moved from #${CHANNEL_ID} to #${OTHER_CHANNEL_ID}`],
- blocks: [],
- expandable: true,
- });
- });
-
- it('lists every change of a multi-field update in name, channel and avatar order under the new name', () => {
- expect(
- present(
- webhookUpdate([
- {key: 'channel_id', old_value: CHANNEL_ID, new_value: OTHER_CHANNEL_ID},
- {key: 'name', old_value: 'Hook A', new_value: 'Hook B'},
- {key: 'avatar_hash', old_value: 'a1b2c3d4', new_value: null},
- ]),
- WEBHOOK_NAMES,
- ),
- ).toEqual({
- summary: 'Hampus updated the webhook Hook B',
- rows: [
- '~ Changed the name from Hook A to Hook B',
- `~ Moved from #${CHANNEL_ID} to #${OTHER_CHANNEL_ID}`,
- '- Removed the avatar',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('takes the name from the context when the name did not change', () => {
- expect(present(webhookUpdate(undefined), WEBHOOK_NAMES)).toEqual({
- summary: 'Hampus updated the webhook Captain Hook',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('says a webhook was updated when the name is unknown', () => {
- expect(present(webhookUpdate([{key: 'avatar_hash', old_value: null, new_value: 'a1b2c3d4'}]))).toEqual({
- summary: 'Hampus updated a webhook',
- rows: ['+ Added an avatar'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('omits rows for unchanged or unreadable values', () => {
- expect(
- present(
- webhookUpdate([
- {key: 'name', old_value: 'Hook', new_value: ' Hook '},
- {key: 'channel_id', old_value: CHANNEL_ID, new_value: 'general'},
- {key: 'avatar_hash', old_value: 12345, new_value: null},
- ]),
- ),
- ).toEqual({summary: 'Hampus updated the webhook Hook', rows: [], blocks: [], expandable: false});
- expect(
- present(
- webhookUpdate([
- {key: 'channel_id', old_value: CHANNEL_ID, new_value: CHANNEL_ID},
- {key: 'avatar_hash', old_value: '', new_value: null},
- ]),
- ),
- ).toEqual({summary: 'Hampus updated a webhook', rows: [], blocks: [], expandable: false});
- });
-
- it('does not use the rename summary when the previous name cannot be read', () => {
- expect(present(webhookUpdate([{key: 'name', old_value: ' ', new_value: 'Hook B'}]), WEBHOOK_NAMES)).toEqual({
- summary: 'Hampus updated the webhook Hook B',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('presentWebhookDelete', () => {
- it('describes an own webhook deleted from its channel without rows', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_DELETE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- changes: webhookSnapshot('old_value', TEST_ACTOR_ID),
- }),
- ).toEqual({
- summary: `Hampus deleted the webhook Captain Hook from #${CHANNEL_ID}`,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it("names the creator of another member's webhook", () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_DELETE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- changes: webhookSnapshot('old_value', ALICE_ID),
- }),
- ).toEqual({
- summary: `Hampus deleted the webhook Captain Hook from #${CHANNEL_ID}`,
- rows: ['~ The webhook was created by Alice'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('leaves the channel out when none was recorded', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_DELETE,
- target_id: WEBHOOK_ID,
- changes: webhookSnapshot('old_value', ALICE_ID).filter((change) => change.key !== 'channel_id'),
- }),
- ).toEqual({
- summary: 'Hampus deleted the webhook Captain Hook',
- rows: ['~ The webhook was created by Alice'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('says a webhook was deleted when no name was recorded and ignores an unreadable creator', () => {
- expect(
- present({
- action_type: AuditLogActionType.WEBHOOK_DELETE,
- target_id: WEBHOOK_ID,
- options: {channel_id: CHANNEL_ID},
- changes: [{key: 'creator_id', old_value: 1400}],
- }),
- ).toEqual({summary: 'Hampus deleted a webhook', rows: [], blocks: [], expandable: false});
- });
-
- it('ignores a name from the context for a deleted webhook', () => {
- expect(
- present(
- {action_type: AuditLogActionType.WEBHOOK_DELETE, target_id: WEBHOOK_ID, options: {channel_id: CHANNEL_ID}},
- WEBHOOK_NAMES,
- ).summary,
- ).toBe('Hampus deleted a webhook');
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.test.ts
deleted file mode 100644
index 5393653ad..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation.test.ts
+++ /dev/null
@@ -1,1249 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- presentMemberBanAdd,
- presentMemberBanRemove,
- presentMemberDisconnect,
- presentMemberMove,
- presentMemberRoleUpdate,
- presentMemberUpdate,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation';
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-type EntryFixture = Parameters<typeof makeEntry>[0];
-type ChangeFixture = NonNullable<EntryFixture['changes']>[number];
-type PresentedText = ReturnType<typeof resultToText> & {expandable: boolean};
-
-const TARGET_ID = '1400000000000000100';
-const MODERATOR_ID = '1400000000000000101';
-const BOT_ID = '1400000000000000102';
-const ROLE_A = '1400000000000000200';
-const ROLE_B = '1400000000000000201';
-const ROLE_C = '1400000000000000202';
-const CHANNEL_A = '1400000000000000300';
-const CHANNEL_B = '1400000000000000301';
-const EARLIER_PAST = '2026-08-30T12:00:00.000Z';
-const PAST = '2026-08-31T12:00:00.000Z';
-const ENTRY_TIME = '2026-09-01T12:00:00.000Z';
-const BAN_TIME = '2026-09-01T12:00:00.007Z';
-const FUTURE = '2026-09-02T12:00:00.000Z';
-const LATER_FUTURE = '2026-09-03T18:30:00.000Z';
-const USER_NAMES: Readonly<Record<string, string>> = {
- [TEST_ACTOR_ID]: 'Hampus',
- [TARGET_ID]: 'ender',
- [MODERATOR_ID]: 'Mira',
- [BOT_ID]: 'MyBot',
-};
-
-function present(fixture: EntryFixture): PresentedText {
- const presentation = presentAuditLogEntry(makeEntry(fixture), fakeContext());
- return {...resultToText(presentation, USER_NAMES), expandable: presentation.expandable};
-}
-
-function change(key: string, oldValue: unknown, newValue: unknown): ChangeFixture {
- return {key, old_value: oldValue, new_value: newValue};
-}
-
-function memberUpdate(changes: Array<ChangeFixture>, targetId: string = TARGET_ID): EntryFixture {
- return {action_type: AuditLogActionType.MEMBER_UPDATE, target_id: targetId, changes};
-}
-
-function banAdd(changes: Array<ChangeFixture>, extra: Partial<EntryFixture> = {}): EntryFixture {
- return {action_type: AuditLogActionType.MEMBER_BAN_ADD, target_id: TARGET_ID, changes, ...extra};
-}
-
-function banSnapshot(fields: {
- bannedAt?: string;
- expiresAt?: string | null;
- reason?: string | null;
-}): Array<ChangeFixture> {
- return [
- {key: 'user_id', new_value: TARGET_ID},
- {key: 'moderator_id', new_value: TEST_ACTOR_ID},
- {key: 'banned_at', new_value: fields.bannedAt ?? BAN_TIME},
- {key: 'expires_at', new_value: fields.expiresAt ?? null},
- {key: 'reason', new_value: fields.reason ?? null},
- ];
-}
-
-function banRemove(changes: Array<ChangeFixture>, extra: Partial<EntryFixture> = {}): EntryFixture {
- return {action_type: AuditLogActionType.MEMBER_BAN_REMOVE, target_id: TARGET_ID, changes, ...extra};
-}
-
-function roleUpdate(changes: Array<ChangeFixture>, extra: Partial<EntryFixture> = {}): EntryFixture {
- return {action_type: AuditLogActionType.MEMBER_ROLE_UPDATE, target_id: TARGET_ID, changes, ...extra};
-}
-
-describe('presentMemberKick', () => {
- it('summarizes a kick with no rows', () => {
- expect(present({action_type: AuditLogActionType.MEMBER_KICK, target_id: TARGET_ID})).toEqual({
- summary: 'Hampus kicked ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('shows the decoded header reason as the only detail', () => {
- expect(
- present({action_type: AuditLogActionType.MEMBER_KICK, target_id: TARGET_ID, reason: 'Posting%20scam%20links'}),
- ).toEqual({
- summary: 'Hampus kicked ender',
- rows: [],
- blocks: [{kind: 'reason', text: 'Posting scam links'}],
- expandable: true,
- });
- });
-});
-
-describe('presentMemberPrune', () => {
- it('summarizes a prune and ignores stray prune options and changes', () => {
- expect(
- present({
- action_type: AuditLogActionType.MEMBER_PRUNE,
- options: {members_removed: 3, delete_member_days: '7'},
- changes: [{key: 'prune_delete_days', new_value: 7}],
- }),
- ).toEqual({summary: 'Hampus pruned inactive members', rows: [], blocks: [], expandable: false});
- });
-});
-
-describe('presentMemberBanAdd', () => {
- it('shows the screenshot 1 legacy row as a bare summary', () => {
- expect(present(banAdd(banSnapshot({}), {options: {delete_member_days: '0'}}))).toEqual({
- summary: 'Hampus banned ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('shows a body reason that the API resolved into the entry reason once', () => {
- expect(
- present(banAdd(banSnapshot({reason: 'Spamming invites'}), {reason: 'Spamming invites', options: {}})),
- ).toEqual({
- summary: 'Hampus banned ender',
- rows: [],
- blocks: [{kind: 'reason', text: 'Spamming invites'}],
- expandable: true,
- });
- });
-
- it('shows a body-only reason as a ban reason block when the entry has no reason', () => {
- expect(present(banAdd(banSnapshot({reason: 'Spamming invites'})))).toEqual({
- summary: 'Hampus banned ender',
- rows: [],
- blocks: [{kind: 'ban_reason', text: 'Spamming invites'}],
- expandable: true,
- });
- });
-
- it('adds a ban reason block after the Reason block when the two reasons differ', () => {
- expect(present(banAdd(banSnapshot({reason: 'Spamming invites'}), {reason: 'Raid%20cleanup'}))).toEqual({
- summary: 'Hampus banned ender',
- rows: [],
- blocks: [
- {kind: 'reason', text: 'Raid cleanup'},
- {kind: 'ban_reason', text: 'Spamming invites'},
- ],
- expandable: true,
- });
- });
-
- it('adds no ban reason block when both reasons decode to the same text', () => {
- expect(present(banAdd(banSnapshot({reason: ' Raid%20cleanup '}), {reason: 'Raid cleanup'}))).toEqual({
- summary: 'Hampus banned ender',
- rows: [],
- blocks: [{kind: 'reason', text: 'Raid cleanup'}],
- expandable: true,
- });
- });
-
- it('adds no ban reason block for a blank ban reason', () => {
- expect(present(banAdd(banSnapshot({reason: ' '}))).blocks).toEqual([]);
- });
-
- it.each([
- {name: 'a 3-day ban', expiresAt: '2026-09-04T12:00:00.000Z', summary: 'Hampus banned ender for 3 days'},
- {name: 'a 12-hour ban', expiresAt: '2026-09-02T00:00:00.000Z', summary: 'Hampus banned ender for 12 hours'},
- {name: 'a 90-minute ban', expiresAt: '2026-09-01T13:30:00.000Z', summary: 'Hampus banned ender for 90 minutes'},
- ])('gives the length of $name measured from banned_at', ({expiresAt, summary}) => {
- expect(present(banAdd(banSnapshot({expiresAt})))).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('measures a temporary ban from the entry time when banned_at is missing', () => {
- expect(present(banAdd([change('expires_at', null, FUTURE)])).summary).toBe('Hampus banned ender for 1 day');
- });
-
- it.each([
- {name: 'an unparseable expiry', expiresAt: 'soon'},
- {name: 'an expiry equal to banned_at', expiresAt: BAN_TIME},
- {name: 'an expiry before banned_at', expiresAt: PAST},
- ])('treats $name as a permanent ban', ({expiresAt}) => {
- expect(present(banAdd(banSnapshot({expiresAt}))).summary).toBe('Hampus banned ender');
- });
-
- it.each([
- {
- name: 'numeric delete_message_seconds',
- options: {delete_message_seconds: 3600},
- row: "- Deleted 1 hour of the member's recent message history",
- },
- {
- name: 'dispatch string delete_message_seconds',
- options: {delete_message_seconds: '43200'},
- row: "- Deleted 12 hours of the member's recent message history",
- },
- {
- name: 'delete_message_seconds over legacy days',
- options: {delete_message_seconds: 21600, delete_member_days: '7'},
- row: "- Deleted 6 hours of the member's recent message history",
- },
- {
- name: 'legacy delete_member_days "7"',
- options: {delete_member_days: '7'},
- row: "- Deleted 7 days of the member's recent message history",
- },
- {
- name: 'legacy days when delete_message_seconds is 0',
- options: {delete_message_seconds: 0, delete_member_days: '2'},
- row: "- Deleted 2 days of the member's recent message history",
- },
- ])('lists deleted messages from $name', ({options, row}) => {
- expect(present(banAdd(banSnapshot({}), {options}))).toEqual({
- summary: 'Hampus banned ender',
- rows: [row],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {delete_member_days: '0'},
- {delete_member_days: 'x'},
- {delete_member_days: '1.5'},
- {delete_member_days: '-2'},
- {delete_member_days: ''},
- {delete_message_seconds: 'lots'},
- {},
- ])('adds no deletion row for options %j', (options) => {
- expect(present(banAdd(banSnapshot({}), {options})).rows).toEqual([]);
- });
-
- it('combines a temporary ban, both reasons and a deletion', () => {
- expect(
- present(
- banAdd(banSnapshot({expiresAt: '2026-09-08T12:00:00.000Z', reason: 'Spamming invites'}), {
- reason: 'Raid cleanup',
- options: {delete_message_seconds: 86400},
- }),
- ),
- ).toEqual({
- summary: 'Hampus banned ender for 7 days',
- rows: ["- Deleted 1 day of the member's recent message history"],
- blocks: [
- {kind: 'reason', text: 'Raid cleanup'},
- {kind: 'ban_reason', text: 'Spamming invites'},
- ],
- expandable: true,
- });
- });
-
- it('passes the ban length and deletion window as durations', () => {
- const result = presentMemberBanAdd(
- makeEntry(
- banAdd(banSnapshot({expiresAt: '2026-09-04T12:00:00.000Z'}), {options: {delete_message_seconds: 3600}}),
- ),
- );
- expect(result.summary.values.duration).toEqual({kind: 'duration', seconds: 259200});
- expect(result.rows[0]?.sentence.values.duration).toEqual({kind: 'duration', seconds: 3600});
- });
-});
-
-describe('presentMemberBanRemove', () => {
- it.each([
- {
- name: 'a ban by another moderator with its date',
- changes: [
- {key: 'moderator_id', old_value: MODERATOR_ID},
- {key: 'banned_at', old_value: '2026-08-20T08:30:00.000Z'},
- ],
- rows: ['~ Originally banned by Mira on 2026-08-20T08:30:00.000Z'],
- },
- {
- name: 'a ban by the same moderator with its date',
- changes: [
- {key: 'moderator_id', old_value: TEST_ACTOR_ID},
- {key: 'banned_at', old_value: '2026-08-20T08:30:00.000Z'},
- ],
- rows: ['~ Originally banned on 2026-08-20T08:30:00.000Z'],
- },
- {
- name: 'a ban with its date and no moderator',
- changes: [{key: 'banned_at', old_value: '2026-08-20T08:30:00.000Z'}],
- rows: ['~ Originally banned on 2026-08-20T08:30:00.000Z'],
- },
- {
- name: 'a ban by another moderator without a date',
- changes: [{key: 'moderator_id', old_value: MODERATOR_ID}],
- rows: ['~ Originally banned by Mira'],
- },
- ])('describes the origin of $name', ({changes, rows}) => {
- expect(present(banRemove(changes))).toEqual({
- summary: 'Hampus unbanned ender',
- rows,
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {name: 'the same moderator without a date', changes: [{key: 'moderator_id', old_value: TEST_ACTOR_ID}]},
- {name: 'nothing recorded', changes: []},
- {
- name: 'junk values',
- changes: [
- {key: 'moderator_id', old_value: 1400000000000000},
- {key: 'banned_at', old_value: 'yesterday'},
- {key: 'expires_at', old_value: 42},
- {key: 'reason', old_value: 7},
- ],
- },
- ])('shows only the summary for $name', ({changes}) => {
- expect(present(banRemove(changes))).toEqual({
- summary: 'Hampus unbanned ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each([
- {name: 'a future expiry', expiresAt: LATER_FUTURE, row: `~ The ban was scheduled to expire on ${LATER_FUTURE}`},
- {name: 'a past expiry', expiresAt: PAST, row: `~ The ban had already expired on ${PAST}`},
- {
- name: 'an expiry at the entry time',
- expiresAt: ENTRY_TIME,
- row: `~ The ban had already expired on ${ENTRY_TIME}`,
- },
- ])('describes $name', ({expiresAt, row}) => {
- expect(present(banRemove([{key: 'expires_at', old_value: expiresAt}])).rows).toEqual([row]);
- });
-
- it('shows the full removed snapshot with the unban reason and the original ban reason', () => {
- expect(
- present(
- banRemove(
- [
- {key: 'user_id', old_value: TARGET_ID},
- {key: 'moderator_id', old_value: MODERATOR_ID},
- {key: 'banned_at', old_value: EARLIER_PAST},
- {key: 'expires_at', old_value: FUTURE},
- {key: 'reason', old_value: 'Spamming%20invites'},
- ],
- {reason: 'Appeal accepted'},
- ),
- ),
- ).toEqual({
- summary: 'Hampus unbanned ender',
- rows: [`~ Originally banned by Mira on ${EARLIER_PAST}`, `~ The ban was scheduled to expire on ${FUTURE}`],
- blocks: [
- {kind: 'reason', text: 'Appeal accepted'},
- {kind: 'ban_reason', text: 'Spamming invites'},
- ],
- expandable: true,
- });
- });
-
- it('shows a ban reason block even without other rows', () => {
- expect(present(banRemove([{key: 'reason', old_value: 'Spam'}]))).toEqual({
- summary: 'Hampus unbanned ender',
- rows: [],
- blocks: [{kind: 'ban_reason', text: 'Spam'}],
- expandable: true,
- });
- });
-
- it('passes the original moderator as a user and the dates as dates', () => {
- const result = presentMemberBanRemove(
- makeEntry(
- banRemove([
- {key: 'moderator_id', old_value: MODERATOR_ID},
- {key: 'banned_at', old_value: EARLIER_PAST},
- ]),
- ),
- );
- expect(result.rows[0]?.sentence.values).toEqual({
- user: {kind: 'user', id: MODERATOR_ID},
- date: {kind: 'date', timestamp: Date.parse(EARLIER_PAST)},
- });
- });
-});
-
-describe('presentMemberUpdate', () => {
- it.each([
- {
- name: 'a nickname set for another member',
- targetId: TARGET_ID,
- changes: [change('nick', null, 'Ender')],
- summary: 'Hampus set the nickname of ender to Ender',
- },
- {
- name: 'a blank nickname replaced for another member',
- targetId: TARGET_ID,
- changes: [change('nick', ' ', 'Ender')],
- summary: 'Hampus set the nickname of ender to Ender',
- },
- {
- name: 'a nickname changed for another member',
- targetId: TARGET_ID,
- changes: [change('nick', 'Ender', 'Endy')],
- summary: 'Hampus changed the nickname of ender from Ender to Endy',
- },
- {
- name: 'a nickname removed from another member',
- targetId: TARGET_ID,
- changes: [change('nick', 'Endy', null)],
- summary: 'Hampus removed the nickname Endy from ender',
- },
- {
- name: 'an own nickname set',
- targetId: TEST_ACTOR_ID,
- changes: [change('nick', null, 'Hamp')],
- summary: 'Hampus set their nickname to Hamp',
- },
- {
- name: 'an own nickname changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('nick', 'Hamp', 'H')],
- summary: 'Hampus changed their nickname from Hamp to H',
- },
- {
- name: 'an own nickname removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('nick', 'H', null)],
- summary: 'Hampus removed their nickname H',
- },
- {
- name: 'a timeout set',
- targetId: TARGET_ID,
- changes: [change('communication_disabled_until', null, FUTURE)],
- summary: `Hampus timed out ender until ${FUTURE}`,
- },
- {
- name: 'a timeout set over an expired one',
- targetId: TARGET_ID,
- changes: [change('communication_disabled_until', PAST, FUTURE)],
- summary: `Hampus timed out ender until ${FUTURE}`,
- },
- {
- name: 'a timeout set on the actor',
- targetId: TEST_ACTOR_ID,
- changes: [change('communication_disabled_until', null, FUTURE)],
- summary: `Hampus timed out Hampus until ${FUTURE}`,
- },
- {
- name: 'a running timeout changed',
- targetId: TARGET_ID,
- changes: [change('communication_disabled_until', FUTURE, LATER_FUTURE)],
- summary: `Hampus changed ender's block on sending messages, reacting and joining voice to end at ${LATER_FUTURE}`,
- },
- {
- name: 'a running timeout removed',
- targetId: TARGET_ID,
- changes: [change('communication_disabled_until', FUTURE, null)],
- summary: 'Hampus removed the timeout for ender',
- },
- {
- name: 'a running timeout ended with a past time',
- targetId: TARGET_ID,
- changes: [change('communication_disabled_until', FUTURE, PAST)],
- summary: 'Hampus removed the timeout for ender',
- },
- {
- name: 'a community mute applied',
- targetId: TARGET_ID,
- changes: [change('mute', false, true)],
- summary: "Hampus turned off ender's microphone in this community",
- },
- {
- name: 'a community mute removed',
- targetId: TARGET_ID,
- changes: [change('mute', true, false)],
- summary: "Hampus turned ender's microphone back on in this community",
- },
- {
- name: 'a community mute applied to the actor',
- targetId: TEST_ACTOR_ID,
- changes: [change('mute', false, true)],
- summary: "Hampus turned off Hampus's microphone in this community",
- },
- {
- name: 'a community deafen applied',
- targetId: TARGET_ID,
- changes: [change('deaf', false, true)],
- summary: 'Hampus stopped ender from hearing others in this community',
- },
- {
- name: 'a community deafen removed',
- targetId: TARGET_ID,
- changes: [change('deaf', true, false)],
- summary: 'Hampus let ender hear others in this community again',
- },
- {
- name: 'a community deafen removed from the actor',
- targetId: TEST_ACTOR_ID,
- changes: [change('deaf', true, false)],
- summary: 'Hampus let Hampus hear others in this community again',
- },
- {
- name: 'one role added',
- targetId: TARGET_ID,
- changes: [change('roles', [ROLE_A], [ROLE_A, ROLE_B])],
- summary: `Hampus gave ender the role @${ROLE_B}`,
- },
- {
- name: 'one role removed',
- targetId: TARGET_ID,
- changes: [change('roles', [ROLE_A, ROLE_B], [ROLE_B])],
- summary: `Hampus removed the role @${ROLE_A} from ender`,
- },
- {
- name: 'one role added to the actor',
- targetId: TEST_ACTOR_ID,
- changes: [change('roles', [], [ROLE_A])],
- summary: `Hampus gave Hampus the role @${ROLE_A}`,
- },
- {
- name: 'an own community avatar set',
- targetId: TEST_ACTOR_ID,
- changes: [change('avatar_hash', null, 'a1')],
- summary: 'Hampus set their community profile avatar',
- },
- {
- name: 'an own community avatar changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('avatar_hash', 'a1', 'a2')],
- summary: 'Hampus changed their community profile avatar',
- },
- {
- name: 'an own community avatar removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('avatar_hash', 'a2', null)],
- summary: 'Hampus removed their community profile avatar',
- },
- {
- name: 'an own community banner set',
- targetId: TEST_ACTOR_ID,
- changes: [change('banner_hash', null, 'b1')],
- summary: 'Hampus set their community profile banner',
- },
- {
- name: 'an own community banner changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('banner_hash', 'b1', 'b2')],
- summary: 'Hampus changed their community profile banner',
- },
- {
- name: 'an own community banner removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('banner_hash', 'b2', null)],
- summary: 'Hampus removed their community profile banner',
- },
- {
- name: 'an own community bio set',
- targetId: TEST_ACTOR_ID,
- changes: [change('bio', null, 'Hello there')],
- summary: 'Hampus set their community profile bio to Hello there',
- },
- {
- name: 'an own community bio changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('bio', 'Hello there', 'Back soon')],
- summary: 'Hampus changed their community profile bio to Back soon',
- },
- {
- name: 'an own community bio removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('bio', 'Back soon', null)],
- summary: 'Hampus removed their community profile bio',
- },
- {
- name: 'own community pronouns set',
- targetId: TEST_ACTOR_ID,
- changes: [change('pronouns', null, 'he/him')],
- summary: 'Hampus set their community profile pronouns to he/him',
- },
- {
- name: 'own community pronouns changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('pronouns', 'he/him', 'they/them')],
- summary: 'Hampus set their community profile pronouns to they/them',
- },
- {
- name: 'own community pronouns removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('pronouns', 'they/them', null)],
- summary: 'Hampus removed their community profile pronouns',
- },
- {
- name: 'an own community accent color set',
- targetId: TEST_ACTOR_ID,
- changes: [change('accent_color', null, 16711680)],
- summary: 'Hampus set their community profile accent color to #FF0000',
- },
- {
- name: 'an own community accent color changed',
- targetId: TEST_ACTOR_ID,
- changes: [change('accent_color', 16711680, 255)],
- summary: 'Hampus set their community profile accent color to #0000FF',
- },
- {
- name: 'an own community accent color removed',
- targetId: TEST_ACTOR_ID,
- changes: [change('accent_color', 255, null)],
- summary: 'Hampus removed their community profile accent color',
- },
- ])('gives a specific summary for $name', ({targetId, changes, summary}) => {
- expect(present(memberUpdate(changes, targetId))).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it.each([
- {
- name: 'a community avatar set',
- changes: [change('avatar_hash', null, 'a1')],
- row: "+ Added the member's community profile avatar",
- },
- {
- name: 'a community avatar changed',
- changes: [change('avatar_hash', 'a1', 'a2')],
- row: "~ Changed the member's community profile avatar",
- },
- {
- name: 'a community avatar removed',
- changes: [change('avatar_hash', 'a2', null)],
- row: "- Removed the member's community profile avatar",
- },
- {
- name: 'a community banner set',
- changes: [change('banner_hash', null, 'b1')],
- row: "+ Added the member's community profile banner",
- },
- {
- name: 'a community banner changed',
- changes: [change('banner_hash', 'b1', 'b2')],
- row: "~ Changed the member's community profile banner",
- },
- {
- name: 'a community banner removed',
- changes: [change('banner_hash', 'b2', null)],
- row: "- Removed the member's community profile banner",
- },
- {
- name: 'a community bio set',
- changes: [change('bio', null, 'Hello there')],
- row: "+ Set the member's community profile bio to Hello there",
- },
- {
- name: 'a community bio changed',
- changes: [change('bio', 'Hello there', 'Back soon')],
- row: "~ Changed the member's community profile bio to Back soon",
- },
- {
- name: 'a community bio removed',
- changes: [change('bio', 'Back soon', null)],
- row: "- Removed the member's community profile bio",
- },
- {
- name: 'community pronouns set',
- changes: [change('pronouns', null, 'he/him')],
- row: "~ Set the member's community profile pronouns to he/him",
- },
- {
- name: 'community pronouns changed',
- changes: [change('pronouns', 'he/him', 'they/them')],
- row: "~ Set the member's community profile pronouns to they/them",
- },
- {
- name: 'community pronouns removed',
- changes: [change('pronouns', 'they/them', null)],
- row: "- Removed the member's community profile pronouns",
- },
- {
- name: 'a community accent color set',
- changes: [change('accent_color', null, 16711680)],
- row: "~ Set the member's community profile accent color to #FF0000",
- },
- {
- name: 'a community accent color changed',
- changes: [change('accent_color', 16711680, 255)],
- row: "~ Set the member's community profile accent color to #0000FF",
- },
- {
- name: 'a community accent color removed',
- changes: [change('accent_color', 255, null)],
- row: "- Removed the member's community profile accent color",
- },
- ])('uses the generic summary and a row for $name on another member', ({changes, row}) => {
- expect(present(memberUpdate(changes))).toEqual({
- summary: 'Hampus updated ender',
- rows: [row],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {name: 'a nickname set', groupChange: change('nick', null, 'Ender'), row: '+ Set the nickname to Ender'},
- {
- name: 'a nickname changed',
- groupChange: change('nick', 'Ender', 'Endy'),
- row: '~ Changed the nickname from Ender to Endy',
- },
- {name: 'a nickname removed', groupChange: change('nick', 'Endy', null), row: '- Removed the nickname Endy'},
- {name: 'a role added', groupChange: change('roles', [], [ROLE_A]), row: `+ Added the role @${ROLE_A}`},
- {name: 'a role removed', groupChange: change('roles', [ROLE_A], []), row: `- Removed the role @${ROLE_A}`},
- {
- name: 'a timeout set',
- groupChange: change('communication_disabled_until', null, FUTURE),
- row: `+ Blocked the member from sending messages, reacting and joining voice until ${FUTURE}`,
- },
- {
- name: 'a timeout changed',
- groupChange: change('communication_disabled_until', FUTURE, LATER_FUTURE),
- row: `~ Changed the block on sending messages, reacting and joining voice to end at ${LATER_FUTURE}`,
- },
- {
- name: 'a timeout removed',
- groupChange: change('communication_disabled_until', FUTURE, null),
- row: '- Removed the timeout',
- },
- {
- name: 'a community mute applied',
- groupChange: change('mute', false, true),
- row: "+ Turned off the member's microphone in this community",
- },
- {
- name: 'a community mute removed',
- groupChange: change('mute', true, false),
- row: "- Turned the member's microphone back on in this community",
- },
- {
- name: 'a community deafen applied',
- groupChange: change('deaf', false, true),
- row: '+ Stopped the member from hearing others in this community',
- },
- {
- name: 'a community deafen removed',
- groupChange: change('deaf', true, false),
- row: '- Let the member hear others in this community again',
- },
- ])('renders the row for $name under the generic summary', ({groupChange, row}) => {
- expect(present(memberUpdate([change('accent_color', null, 255), groupChange]))).toEqual({
- summary: 'Hampus updated ender',
- rows: [row, "~ Set the member's community profile accent color to #0000FF"],
- blocks: [],
- expandable: true,
- });
- });
-
- it('orders every group row under the generic summary regardless of the stored key order', () => {
- expect(
- present(
- memberUpdate([
- change('temporary', true, false),
- change('accent_color', null, 255),
- change('pronouns', null, 'he/him'),
- change('bio', null, 'Hello'),
- change('banner_hash', 'b1', null),
- change('avatar_hash', 'a1', 'a2'),
- change('deaf', false, true),
- change('mute', true, false),
- change('communication_disabled_until', null, FUTURE),
- change('roles', [ROLE_A], [ROLE_B, ROLE_C]),
- change('nick', null, 'Ender'),
- change('user_id', TARGET_ID, TARGET_ID),
- ]),
- ),
- ).toEqual({
- summary: 'Hampus updated ender',
- rows: [
- '+ Set the nickname to Ender',
- `+ Added the role @${ROLE_B}`,
- `+ Added the role @${ROLE_C}`,
- `- Removed the role @${ROLE_A}`,
- `+ Blocked the member from sending messages, reacting and joining voice until ${FUTURE}`,
- "- Turned the member's microphone back on in this community",
- '+ Stopped the member from hearing others in this community',
- "~ Changed the member's community profile avatar",
- "- Removed the member's community profile banner",
- "+ Set the member's community profile bio to Hello",
- "~ Set the member's community profile pronouns to he/him",
- "~ Set the member's community profile accent color to #0000FF",
- '~ The member is no longer temporary',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('summarizes an own profile save with several changes as a community profile update', () => {
- expect(
- present(
- memberUpdate(
- [
- change('nick', 'Hampus', 'Hamp'),
- change('avatar_hash', null, 'a1'),
- change('bio', null, 'Building Fluxer'),
- change('pronouns', null, 'he/him'),
- change('accent_color', null, 16711680),
- ],
- TEST_ACTOR_ID,
- ),
- ),
- ).toEqual({
- summary: 'Hampus updated their community profile',
- rows: [
- '~ Changed the nickname from Hampus to Hamp',
- "+ Added the member's community profile avatar",
- "+ Set the member's community profile bio to Building Fluxer",
- "~ Set the member's community profile pronouns to he/him",
- "~ Set the member's community profile accent color to #FF0000",
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('uses the roles summary with a row per role when several roles change', () => {
- expect(present(memberUpdate([change('roles', [ROLE_A], [ROLE_B, ROLE_C])]))).toEqual({
- summary: 'Hampus updated the roles of ender',
- rows: [`+ Added the role @${ROLE_B}`, `+ Added the role @${ROLE_C}`, `- Removed the role @${ROLE_A}`],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names a deleted role by its id and never by a role_name option', () => {
- const entry = makeEntry({...memberUpdate([change('roles', [], [ROLE_A])]), options: {role_name: 'Moderators'}});
- expect(presentMemberUpdate(entry).summary.values.role).toEqual({kind: 'role', id: ROLE_A, recordedName: null});
- expect(
- present({...memberUpdate([change('roles', [], [ROLE_A])]), options: {role_name: 'Moderators'}}).summary,
- ).toBe(`Hampus gave ender the role @${ROLE_A}`);
- });
-
- it('adds the temporary row to a specific summary', () => {
- expect(present(memberUpdate([change('roles', [], [ROLE_A]), change('temporary', true, false)]))).toEqual({
- summary: `Hampus gave ender the role @${ROLE_A}`,
- rows: ['~ The member is no longer temporary'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('adds the temporary row after the role rows of the roles summary', () => {
- expect(present(memberUpdate([change('roles', [ROLE_A], [ROLE_B]), change('temporary', true, false)]))).toEqual({
- summary: 'Hampus updated the roles of ender',
- rows: [`+ Added the role @${ROLE_B}`, `- Removed the role @${ROLE_A}`, '~ The member is no longer temporary'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows a lone temporary change under the generic summary and ignores the reverse direction', () => {
- expect(present(memberUpdate([change('temporary', true, false)]))).toEqual({
- summary: 'Hampus updated ender',
- rows: ['~ The member is no longer temporary'],
- blocks: [],
- expandable: true,
- });
- expect(present(memberUpdate([change('temporary', false, true)])).rows).toEqual([]);
- });
-
- it('treats a timeout that moved from one past time to another as no change', () => {
- expect(present(memberUpdate([change('communication_disabled_until', EARLIER_PAST, PAST)]))).toEqual({
- summary: 'Hampus updated ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each([
- {name: 'another member', targetId: TARGET_ID, summary: 'Hampus updated ender'},
- {name: 'the actor', targetId: TEST_ACTOR_ID, summary: 'Hampus updated their community profile'},
- ])('gives the generic summary for an empty update of $name', ({targetId, summary}) => {
- const empty = {summary, rows: [], blocks: [], expandable: false};
- expect(present({action_type: AuditLogActionType.MEMBER_UPDATE, target_id: targetId})).toEqual(empty);
- expect(present(memberUpdate([], targetId))).toEqual(empty);
- });
-
- it('shows the timeout reason from the entry reason and never reads options', () => {
- expect(
- present({
- ...memberUpdate([change('communication_disabled_until', null, FUTURE)]),
- reason: 'Cool off',
- options: {timeout_reason: 'Ignored', communication_disabled_until: LATER_FUTURE},
- }),
- ).toEqual({
- summary: `Hampus timed out ender until ${FUTURE}`,
- rows: [],
- blocks: [{kind: 'reason', text: 'Cool off'}],
- expandable: true,
- });
- });
-
- it('omits groups whose values fail their readers or do not differ', () => {
- expect(
- present(
- memberUpdate([
- change('nick', 'Ender', ' Ender '),
- change('nick', null, 'ignored duplicate'),
- change('roles', 'R1', [ROLE_A, 5]),
- change('communication_disabled_until', 'soon', 'later'),
- change('mute', 'yes', true),
- change('deaf', true, true),
- change('avatar_hash', 5, null),
- change('banner_hash', 'b1', 'b1'),
- change('bio', null, ' '),
- change('pronouns', ['he/him'], null),
- change('accent_color', null, 'red'),
- change('temporary', 'true', 'false'),
- change('user_id', TARGET_ID, MODERATOR_ID),
- ]),
- ),
- ).toEqual({
- summary: 'Hampus updated ender',
- rows: ['~ The member is no longer temporary'],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {name: 'a fraction', value: 1.5},
- {name: 'a negative number', value: -1},
- {name: 'a value above white', value: 0x1000000},
- {name: 'a string', value: 'red'},
- ])('ignores an accent color that is $name', ({value}) => {
- expect(present(memberUpdate([change('accent_color', null, value)])).rows).toEqual([]);
- });
-
- it('ignores role ids that are not snowflakes', () => {
- expect(present(memberUpdate([change('roles', ['everyone'], ['everyone', 'admins'])]))).toEqual({
- summary: 'Hampus updated ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('passes nicknames as names, profile text as boxed text, colors and dates to the renderer', () => {
- const values = (changes: Array<ChangeFixture>) =>
- presentMemberUpdate(makeEntry(memberUpdate(changes, TEST_ACTOR_ID))).summary.values;
- expect(values([change('nick', null, 'Hamp')]).nick).toEqual({kind: 'name', value: 'Hamp'});
- expect(values([change('bio', null, 'Hello')]).text).toEqual({kind: 'text', value: 'Hello'});
- expect(values([change('pronouns', null, 'he/him')]).text).toEqual({kind: 'text', value: 'he/him'});
- expect(values([change('accent_color', null, '255')]).color).toEqual({kind: 'color', value: 255});
- expect(values([change('communication_disabled_until', null, FUTURE)]).date).toEqual({
- kind: 'date',
- timestamp: Date.parse(FUTURE),
- });
- });
-});
-
-describe('presentMemberRoleUpdate', () => {
- it('names the added role by its recorded name', () => {
- expect(
- present(roleUpdate([change('roles', [ROLE_A], [ROLE_A, ROLE_B])], {options: {role_name: 'Moderators'}})),
- ).toEqual({summary: 'Hampus gave ender the role @Moderators', rows: [], blocks: [], expandable: false});
- });
-
- it('names the removed role by its recorded name', () => {
- expect(
- present(roleUpdate([change('roles', [ROLE_A, ROLE_B], [ROLE_A])], {options: {role_name: 'Moderators'}})),
- ).toEqual({summary: 'Hampus removed the role @Moderators from ender', rows: [], blocks: [], expandable: false});
- });
-
- it('uses the system sentences when the system gave or removed a role', () => {
- expect(
- present(roleUpdate([change('roles', [], [ROLE_A])], {user_id: '0', options: {role_name: 'Visionary'}})).summary,
- ).toBe('The system gave ender the role @Visionary');
- expect(
- present(roleUpdate([change('roles', [ROLE_A], [])], {user_id: '0', options: {role_name: 'Visionary'}})).summary,
- ).toBe('The system removed the role @Visionary from ender');
- });
-
- it('falls back to the role id when no role name was recorded', () => {
- const fixture = roleUpdate([change('roles', [], [ROLE_A])], {options: {role_name: ' '}});
- expect(presentMemberRoleUpdate(makeEntry(fixture)).summary.values.role).toEqual({
- kind: 'role',
- id: ROLE_A,
- recordedName: null,
- });
- expect(present(fixture).summary).toBe(`Hampus gave ender the role @${ROLE_A}`);
- });
-
- it('gives the roles summary for an empty legacy row and ignores its role_id and action options', () => {
- expect(present(roleUpdate([], {options: {role_id: ROLE_A, action: 'add'}}))).toEqual({
- summary: 'Hampus updated the roles of ender',
- rows: [],
- blocks: [],
- expandable: false,
- });
- expect(present({action_type: AuditLogActionType.MEMBER_ROLE_UPDATE, target_id: TARGET_ID}).summary).toBe(
- 'Hampus updated the roles of ender',
- );
- });
-
- it('adds the temporary row to a single role change', () => {
- expect(
- present(
- roleUpdate([change('roles', [], [ROLE_A]), change('temporary', true, false)], {
- options: {role_name: 'Moderators'},
- }),
- ),
- ).toEqual({
- summary: 'Hampus gave ender the role @Moderators',
- rows: ['~ The member is no longer temporary'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('lists each role by id when several roles differ and ignores role_name', () => {
- expect(
- present(
- roleUpdate([change('roles', [ROLE_A], [ROLE_B, ROLE_C]), change('temporary', true, false)], {
- user_id: '0',
- options: {role_name: 'Moderators'},
- }),
- ),
- ).toEqual({
- summary: 'System updated the roles of ender',
- rows: [
- `+ Added the role @${ROLE_B}`,
- `+ Added the role @${ROLE_C}`,
- `- Removed the role @${ROLE_A}`,
- '~ The member is no longer temporary',
- ],
- blocks: [],
- expandable: true,
- });
- });
-});
-
-describe('presentMemberMove', () => {
- const move = (targetId: string, changes: Array<ChangeFixture> | undefined, options?: Record<string, unknown>) =>
- present({action_type: AuditLogActionType.MEMBER_MOVE, target_id: targetId, changes, options});
-
- it.each([
- {
- name: 'another member between two channels',
- targetId: TARGET_ID,
- changes: [change('channel_id', CHANNEL_A, CHANNEL_B)],
- options: {channel_id: CHANNEL_B, count: 1},
- summary: `Hampus moved ender from #${CHANNEL_A} to #${CHANNEL_B}`,
- },
- {
- name: 'another member from an unknown channel',
- targetId: TARGET_ID,
- changes: [{key: 'channel_id', new_value: CHANNEL_B}],
- options: undefined,
- summary: `Hampus moved ender to #${CHANNEL_B}`,
- },
- {
- name: 'another member to the options channel',
- targetId: TARGET_ID,
- changes: undefined,
- options: {channel_id: CHANNEL_B, count: '1'},
- summary: `Hampus moved ender to #${CHANNEL_B}`,
- },
- {
- name: 'another member with no channels',
- targetId: TARGET_ID,
- changes: undefined,
- options: undefined,
- summary: 'Hampus moved ender to a different voice channel',
- },
- {
- name: 'another member away from a known channel only',
- targetId: TARGET_ID,
- changes: [{key: 'channel_id', old_value: CHANNEL_A}],
- options: undefined,
- summary: 'Hampus moved ender to a different voice channel',
- },
- {
- name: 'the actor between two channels',
- targetId: TEST_ACTOR_ID,
- changes: [change('channel_id', CHANNEL_A, CHANNEL_B)],
- options: {channel_id: CHANNEL_B},
- summary: `Hampus moved from #${CHANNEL_A} to #${CHANNEL_B}`,
- },
- {
- name: 'the actor from an unknown channel',
- targetId: TEST_ACTOR_ID,
- changes: [{key: 'channel_id', new_value: CHANNEL_B}],
- options: undefined,
- summary: `Hampus moved to #${CHANNEL_B}`,
- },
- {
- name: 'the actor with no channels',
- targetId: TEST_ACTOR_ID,
- changes: undefined,
- options: undefined,
- summary: 'Hampus moved to a different voice channel',
- },
- ])('summarizes a move of $name', ({targetId, changes, options, summary}) => {
- expect(move(targetId, changes, options)).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('passes both channels as channel chips that fall back to a deleted channel', () => {
- const result = presentMemberMove(
- makeEntry({
- action_type: AuditLogActionType.MEMBER_MOVE,
- target_id: TARGET_ID,
- changes: [change('channel_id', CHANNEL_A, CHANNEL_B)],
- }),
- );
- expect(result.summary.values.oldChannel).toEqual({
- kind: 'channel',
- id: CHANNEL_A,
- recordedName: null,
- fallback: 'channel',
- });
- expect(result.summary.values.newChannel).toEqual({
- kind: 'channel',
- id: CHANNEL_B,
- recordedName: null,
- fallback: 'channel',
- });
- });
-});
-
-describe('presentMemberDisconnect', () => {
- const disconnect = (targetId: string, changes: Array<ChangeFixture> | undefined, options?: Record<string, unknown>) =>
- present({action_type: AuditLogActionType.MEMBER_DISCONNECT, target_id: targetId, changes, options});
-
- it.each([
- {
- name: 'another member from a known channel',
- targetId: TARGET_ID,
- changes: [{key: 'channel_id', old_value: CHANNEL_A}],
- options: {channel_id: CHANNEL_A, count: 1},
- summary: `Hampus disconnected ender from #${CHANNEL_A}`,
- },
- {
- name: 'another member from the options channel',
- targetId: TARGET_ID,
- changes: undefined,
- options: {channel_id: CHANNEL_A},
- summary: `Hampus disconnected ender from #${CHANNEL_A}`,
- },
- {
- name: 'another member from an unknown channel',
- targetId: TARGET_ID,
- changes: undefined,
- options: undefined,
- summary: 'Hampus disconnected ender from voice',
- },
- {
- name: 'the actor from a known channel',
- targetId: TEST_ACTOR_ID,
- changes: [{key: 'channel_id', old_value: CHANNEL_A}],
- options: undefined,
- summary: `Hampus disconnected from #${CHANNEL_A}`,
- },
- {
- name: 'the actor from an unknown channel',
- targetId: TEST_ACTOR_ID,
- changes: [{key: 'channel_id', old_value: 'voice'}],
- options: undefined,
- summary: 'Hampus disconnected from voice',
- },
- ])('summarizes a disconnect of $name', ({targetId, changes, options, summary}) => {
- expect(disconnect(targetId, changes, options)).toEqual({summary, rows: [], blocks: [], expandable: false});
- });
-
- it('passes the channel as a channel chip', () => {
- const result = presentMemberDisconnect(
- makeEntry({
- action_type: AuditLogActionType.MEMBER_DISCONNECT,
- target_id: TARGET_ID,
- changes: [{key: 'channel_id', old_value: CHANNEL_A}],
- }),
- );
- expect(result.summary.values.channel).toEqual({
- kind: 'channel',
- id: CHANNEL_A,
- recordedName: null,
- fallback: 'channel',
- });
- });
-});
-
-describe('presentBotAdd', () => {
- it.each([
- {name: 'temporary false', options: {temporary: false}, summary: 'Hampus added the bot MyBot'},
- {name: 'no options', options: undefined, summary: 'Hampus added the bot MyBot'},
- {name: 'a junk temporary value', options: {temporary: 'yes'}, summary: 'Hampus added the bot MyBot'},
- {name: 'temporary true', options: {temporary: true}, summary: 'Hampus added the bot MyBot as a temporary member'},
- {
- name: 'the dispatch string "true"',
- options: {temporary: 'true'},
- summary: 'Hampus added the bot MyBot as a temporary member',
- },
- ])('summarizes a bot add with $name', ({options, summary}) => {
- expect(present({action_type: AuditLogActionType.BOT_ADD, target_id: BOT_ID, options})).toEqual({
- summary,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-});
-
-describe('member presenters', () => {
- it('render a target that is missing or not a snowflake as an unknown user chip', () => {
- for (const target_id of [null, 'not-a-user']) {
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MEMBER_KICK, target_id}),
- fakeContext(),
- );
- expect(presentation.summary.values.target).toEqual({kind: 'user', id: ''});
- }
- });
-
- it('never treat a missing actor and a missing target as the same member', () => {
- expect(
- present({
- action_type: AuditLogActionType.MEMBER_UPDATE,
- user_id: null,
- target_id: null,
- changes: [change('nick', null, 'Ender')],
- }).summary,
- ).toBe('@ set the nickname of @ to Ender');
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMessagesLint.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMessagesLint.test.ts
deleted file mode 100644
index d57468129..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogMessagesLint.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import * as ChannelMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogChannelMessages';
-import * as ExpressionMessageMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogExpressionMessageMessages';
-import * as GuildMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogGuildMessages';
-import * as InviteWebhookMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogInviteWebhookMessages';
-import * as MemberMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogMemberMessages';
-import * as RoleMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogRoleMessages';
-import * as SharedMessages from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogSharedMessages';
-import {toText} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {type MessageDescriptor, setupI18n} from '@lingui/core';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-const MESSAGE_MODULES: Record<string, Record<string, unknown>> = {
- AuditLogChannelMessages: ChannelMessages,
- AuditLogExpressionMessageMessages: ExpressionMessageMessages,
- AuditLogGuildMessages: GuildMessages,
- AuditLogInviteWebhookMessages: InviteWebhookMessages,
- AuditLogMemberMessages: MemberMessages,
- AuditLogRoleMessages: RoleMessages,
- AuditLogSharedMessages: SharedMessages,
-};
-
-const ARGUMENT_PATTERN = /\{\s*(\w+)\s*[,}]/g;
-const NUMERIC_ARGUMENT_PATTERN = /\{\s*(\w+)\s*,\s*(?:plural|selectordinal)\s*,/g;
-const VAGUE_SET_PATTERN = /^(Set|Updated) \{\w+\} (to|from)/;
-const DASH_OR_SEMICOLON_PATTERN = /[–—;]/;
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-
-const DESCRIPTORS = Object.entries(MESSAGE_MODULES).flatMap(([moduleName, exports]) =>
- Object.entries(exports).map(([exportName, descriptor]) => ({
- name: `${moduleName}.${exportName}`,
- descriptor: descriptor as MessageDescriptor,
- })),
-);
-
-function sampleValues(message: string): Record<string, string | number> {
- const numeric = new Set(Array.from(message.matchAll(NUMERIC_ARGUMENT_PATTERN), (match) => match[1]));
- const values: Record<string, string | number> = {};
- for (const match of message.matchAll(ARGUMENT_PATTERN)) {
- const name = match[1];
- values[name] = numeric.has(name) ? 2 : `sample ${name}`;
- }
- return values;
-}
-
-describe('audit log messages', () => {
- it('finds the descriptors of every Messages file', () => {
- for (const [moduleName, exports] of Object.entries(MESSAGE_MODULES)) {
- expect(Object.keys(exports).length, moduleName).toBeGreaterThan(0);
- }
- });
-
- it.each(DESCRIPTORS)('$name is a descriptor with a message and a translator comment', ({descriptor}) => {
- expect(typeof descriptor.message).toBe('string');
- expect(descriptor.message?.trim()).not.toBe('');
- expect(typeof descriptor.comment).toBe('string');
- expect(descriptor.comment?.trim()).not.toBe('');
- });
-
- it.each(DESCRIPTORS)('$name formats with sample values and leaves no braces', ({descriptor}) => {
- const message = descriptor.message ?? '';
- const formatted = i18n._(descriptor, sampleValues(message));
- expect(formatted).not.toBe('');
- expect(formatted).not.toContain('{');
- expect(formatted).not.toContain('}');
- });
-
- it.each(DESCRIPTORS)('$name names every placeholder in its translator comment', ({descriptor}) => {
- const comment = descriptor.comment ?? '';
- for (const match of (descriptor.message ?? '').matchAll(ARGUMENT_PATTERN)) {
- expect(comment, match[1]).toContain(`{${match[1]}}`);
- }
- });
-
- it.each(DESCRIPTORS)('$name has no dash or semicolon in its message or translator comment', ({descriptor}) => {
- expect(descriptor.message ?? '').not.toMatch(DASH_OR_SEMICOLON_PATTERN);
- expect(descriptor.comment ?? '').not.toMatch(DASH_OR_SEMICOLON_PATTERN);
- });
-
- it.each(DESCRIPTORS)('$name does not use the vague set or updated pattern', ({descriptor}) => {
- const message = descriptor.message ?? '';
- expect(message).not.toMatch(VAGUE_SET_PATTERN);
- expect(message).not.toContain('Value for');
- });
-
- it('rejects a sentence whose values do not match its message placeholders', () => {
- const descriptor = ChannelMessages.CHANNEL_NAME_CHANGED_ROW;
- expect(() => toText({descriptor, values: {oldName: {kind: 'name', value: 'a'}}})).toThrow('Not passed: [newName]');
- expect(() =>
- toText({
- descriptor,
- values: {
- oldName: {kind: 'name', value: 'a'},
- newName: {kind: 'name', value: 'b'},
- name: {kind: 'name', value: 'c'},
- },
- }),
- ).toThrow('Not in the message: [name]');
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation.test.ts
deleted file mode 100644
index f23d7fb30..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation.test.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentMemberBanAdd} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation';
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import type {
- AuditLogDomainResult,
- AuditLogPlaceholder,
- AuditLogSentence,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentationTypes';
-import {
- CENTERED_LABEL,
- UNKNOWN_ACTION_SUMMARY,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogSharedMessages';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
- TEST_GUILD_ID,
- toText,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-vi.mock('@app/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation', async (importOriginal) => {
- const actual =
- await importOriginal<typeof import('@app/features/guild/utils/guild_tabs/audit_log/AuditLogMemberPresentation')>();
- return {...actual, presentMemberBanAdd: vi.fn(actual.presentMemberBanAdd)};
-});
-
-const ACTION_TYPES = Object.values(AuditLogActionType).filter(
- (value): value is AuditLogActionType => typeof value === 'number',
-);
-const UNKNOWN_ACTION_TYPE = 999 as AuditLogActionType;
-const ACTOR: AuditLogPlaceholder = {kind: 'user', id: TEST_ACTOR_ID};
-
-function sentence(message: string, values: AuditLogSentence['values']): AuditLogSentence {
- return {descriptor: {id: message, message}, values};
-}
-
-function domainResult(overrides: Partial<AuditLogDomainResult>): AuditLogDomainResult {
- return {summary: sentence('{actor} did a test action', {actor: ACTOR}), rows: [], blocks: [], ...overrides};
-}
-
-describe('presentAuditLogEntry', () => {
- it('gives every action type a summary other than the unknown action summary', () => {
- const unpresented = ACTION_TYPES.filter(
- (actionType) =>
- presentAuditLogEntry(makeEntry({action_type: actionType}), fakeContext()).summary.descriptor.message ===
- UNKNOWN_ACTION_SUMMARY.message,
- ).map((actionType) => AuditLogActionType[actionType]);
- expect(unpresented).toEqual([]);
- });
-
- it('formats the summary of every action type with placeholders that match its message', () => {
- for (const actionType of ACTION_TYPES) {
- const presentation = presentAuditLogEntry(makeEntry({action_type: actionType}), fakeContext());
- expect(() => resultToText(presentation)).not.toThrow();
- }
- });
-
- it('uses the unknown action summary for an action type this version does not know', () => {
- const presentation = presentAuditLogEntry(makeEntry({action_type: UNKNOWN_ACTION_TYPE}), fakeContext());
- expect(presentation.summary.descriptor).toBe(UNKNOWN_ACTION_SUMMARY);
- expect({...resultToText(presentation), expandable: presentation.expandable}).toEqual({
- summary: `@${TEST_ACTOR_ID} made a change that this version of the app cannot show`,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('names the system as the actor of an unknown action it wrote', () => {
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: UNKNOWN_ACTION_TYPE, user_id: '0'}),
- fakeContext(),
- );
- expect(resultToText(presentation).summary).toBe('System made a change that this version of the app cannot show');
- });
-
- it('passes the entry and context to the presenter for its action type', () => {
- const entry = makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD, target_id: '1400000000000000100'});
- const context = fakeContext();
- presentAuditLogEntry(entry, context);
- expect(presentMemberBanAdd).toHaveBeenLastCalledWith(entry, context);
- });
-
- it('puts the decoded Reason block before the domain blocks and becomes expandable', () => {
- vi.mocked(presentMemberBanAdd).mockReturnValueOnce(
- domainResult({blocks: [{kind: 'ban_reason', text: 'Raiding the server'}]}),
- );
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD, reason: ' Raid%20cleanup '}),
- fakeContext(),
- );
- expect(presentation.blocks).toEqual([
- {kind: 'reason', text: 'Raid cleanup'},
- {kind: 'ban_reason', text: 'Raiding the server'},
- ]);
- expect(presentation.expandable).toBe(true);
- });
-
- it('adds no Reason block for a blank reason', () => {
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: UNKNOWN_ACTION_TYPE, reason: ' '}),
- fakeContext(),
- );
- expect(presentation.blocks).toEqual([]);
- expect(presentation.expandable).toBe(false);
- });
-
- it('is expandable when the domain returns rows and no blocks', () => {
- vi.mocked(presentMemberBanAdd).mockReturnValueOnce(
- domainResult({
- rows: [{id: 'row', tone: 'remove', sentence: sentence('Deleted a test row', {})}],
- }),
- );
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD}),
- fakeContext(),
- );
- expect({...resultToText(presentation), expandable: presentation.expandable}).toEqual({
- summary: `@${TEST_ACTOR_ID} did a test action`,
- rows: ['- Deleted a test row'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('is expandable when the domain returns only blocks', () => {
- vi.mocked(presentMemberBanAdd).mockReturnValueOnce(domainResult({blocks: [{kind: 'ban_reason', text: 'Spam'}]}));
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD}),
- fakeContext(),
- );
- expect(presentation.blocks).toEqual([{kind: 'ban_reason', text: 'Spam'}]);
- expect(presentation.expandable).toBe(true);
- });
-
- it('is not expandable with no rows and no blocks', () => {
- vi.mocked(presentMemberBanAdd).mockReturnValueOnce(domainResult({}));
- const presentation = presentAuditLogEntry(
- makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD}),
- fakeContext(),
- );
- expect(presentation.expandable).toBe(false);
- });
-});
-
-describe('fakeContext', () => {
- it('resolves only the names it was given', () => {
- const context = fakeContext({webhooks: {'1': 'Deploy bot'}, emojis: {'2': 'blobcat'}, stickers: {'3': 'wave'}});
- expect(context.guildId).toBe(TEST_GUILD_ID);
- expect(context.getWebhookName('1')).toBe('Deploy bot');
- expect(context.getEmojiName('2')).toBe('blobcat');
- expect(context.getStickerName('3')).toBe('wave');
- expect(context.getWebhookName('2')).toBeNull();
- expect(fakeContext().getEmojiName('2')).toBeNull();
- });
-});
-
-describe('toText', () => {
- it('renders users by id or by the given names, and the system by its label', () => {
- const text = sentence('{actor} kicked {target}', {actor: {kind: 'system'}, target: {kind: 'user', id: '42'}});
- expect(toText(text)).toBe('System kicked @42');
- expect(toText(text, {'42': 'ender'})).toBe('System kicked ender');
- });
-
- it('renders channels and roles from the recorded name, else the id, and @everyone for the guild id', () => {
- const text = sentence('{channel} {category} {role} {deletedRole} {everyone}', {
- channel: {kind: 'channel', id: '10', recordedName: 'general', fallback: 'channel'},
- category: {kind: 'channel', id: '11', recordedName: null, fallback: 'category'},
- role: {kind: 'role', id: '20', recordedName: 'Moderators'},
- deletedRole: {kind: 'role', id: '21', recordedName: null},
- everyone: {kind: 'role', id: TEST_GUILD_ID, recordedName: '@everyone'},
- });
- expect(toText(text, {'10': 'ignored', '20': 'ignored'})).toBe('#general #11 @Moderators @21 @everyone');
- });
-
- it('renders names, text, emojis, dates, colors and labels', () => {
- const text = sentence('{name}|{text}|{emoji}|{date}|{color}|{shortColor}|{label}', {
- name: {kind: 'name', value: 'Deploy bot'},
- text: {kind: 'text', value: 'Be nice'},
- emoji: {kind: 'emoji', id: null, name: 'blobcat'},
- date: {kind: 'date', timestamp: Date.parse('2026-09-01T12:00:00.000Z')},
- color: {kind: 'color', value: 0x5865f2},
- shortColor: {kind: 'color', value: 0xff},
- label: {kind: 'label', descriptor: CENTERED_LABEL},
- });
- expect(toText(text)).toBe('Deploy bot|Be nice|:blobcat:|2026-09-01T12:00:00.000Z|#5865F2|#0000FF|Centered');
- });
-
- it('renders durations in the largest whole unit', () => {
- const text = (seconds: number) => toText(sentence('{duration}', {duration: {kind: 'duration', seconds}}));
- expect(text(300)).toBe('5 minutes');
- expect(text(60)).toBe('1 minute');
- expect(text(90)).toBe('90 seconds');
- expect(text(3600)).toBe('1 hour');
- expect(text(259199.993)).toBe('3 days');
- });
-
- it('renders permission titles as a list and caps lists longer than eight', () => {
- const text = (flags: Array<bigint>) =>
- toText(sentence('Allowed {permissions}', {permissions: {kind: 'permissions', flags}}));
- expect(text([Permissions.VIEW_CHANNEL])).toBe('Allowed View channel');
- expect(text([Permissions.VIEW_CHANNEL, Permissions.SEND_MESSAGES])).toBe('Allowed View channel and Send messages');
- const flags = Object.values(Permissions);
- expect(text(flags.slice(0, 8))).toBe(
- 'Allowed Create invite links, Kick members, Ban members, Administrator, Manage channels, Manage community, Add reactions, and View activity log',
- );
- expect(text(flags.slice(0, 9))).toBe(
- 'Allowed Create invite links, Kick members, Ban members, Administrator, Manage channels, Manage community, Add reactions, and 2 more permissions',
- );
- });
-
- it('passes numbers through to ICU plurals', () => {
- const text = (count: number) =>
- toText(sentence('{actor} deleted {count, plural, one {# message} other {# messages}}', {actor: ACTOR, count}));
- expect(text(1)).toBe(`@${TEST_ACTOR_ID} deleted 1 message`);
- expect(text(5)).toBe(`@${TEST_ACTOR_ID} deleted 5 messages`);
- });
-
- it('throws when the passed placeholders do not match the message', () => {
- expect(() =>
- toText(
- sentence('{actor} pinned a message', {
- actor: ACTOR,
- channel: {kind: 'channel', id: '1', recordedName: null, fallback: 'channel'},
- }),
- ),
- ).toThrow(/Not in the message: \[channel\]/);
- expect(() => toText(sentence('{actor} pinned a message in {channel}', {actor: ACTOR}))).toThrow(
- /Not passed: \[channel\]/,
- );
- });
-});
-
-describe('resultToText', () => {
- it('marks rows by tone and keeps blocks', () => {
- expect(
- resultToText(
- domainResult({
- rows: [
- {id: 'add', tone: 'add', sentence: sentence('Added {name}', {name: {kind: 'name', value: 'a'}})},
- {id: 'remove', tone: 'remove', sentence: sentence('Removed {name}', {name: {kind: 'name', value: 'b'}})},
- {id: 'neutral', tone: 'neutral', sentence: sentence('Changed {name}', {name: {kind: 'name', value: 'c'}})},
- ],
- blocks: [{kind: 'reason', text: 'Cleanup'}],
- }),
- {[TEST_ACTOR_ID]: 'Hampus'},
- ),
- ).toEqual({
- summary: 'Hampus did a test action',
- rows: ['+ Added a', '- Removed b', '~ Changed c'],
- blocks: [{kind: 'reason', text: 'Cleanup'}],
- });
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogRolePresentation.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogRolePresentation.test.ts
deleted file mode 100644
index acf77df35..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogRolePresentation.test.ts
+++ /dev/null
@@ -1,649 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {presentAuditLogEntry} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentation';
-import {
- presentRoleCreate,
- presentRoleDelete,
- presentRoleUpdate,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogRolePresentation';
-import {
- fakeContext,
- makeEntry,
- resultToText,
- TEST_ACTOR_ID,
- TEST_GUILD_ID,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {DEFAULT_PERMISSIONS, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-type EntryFixture = Parameters<typeof makeEntry>[0];
-type ChangesFixture = NonNullable<EntryFixture['changes']>;
-
-const ROLE_ID = '1400000000000000200';
-const USER_NAMES = {[TEST_ACTOR_ID]: 'Hampus'};
-const ORANGE = 0xe67e22;
-const BLUE = 0x3498db;
-const UNKNOWN_PERMISSION_BIT = 1n << 19n;
-
-const APP_CREATE_SNAPSHOT: Record<string, unknown> = {
- role_id: ROLE_ID,
- name: 'New role',
- permissions: DEFAULT_PERMISSIONS.toString(),
- position: 1,
- hoist_position: null,
- color: 0,
- icon_hash: null,
- unicode_emoji: null,
- hoist: false,
- mentionable: false,
-};
-
-const DELETE_SNAPSHOT: Record<string, unknown> = {
- role_id: ROLE_ID,
- name: 'Mods',
- permissions: (Permissions.KICK_MEMBERS | Permissions.BAN_MEMBERS | Permissions.MANAGE_MESSAGES).toString(),
- position: 3,
- hoist_position: null,
- color: ORANGE,
- icon_hash: null,
- unicode_emoji: '🔥',
- hoist: true,
- mentionable: false,
-};
-
-function present(fixture: EntryFixture) {
- const presentation = presentAuditLogEntry(makeEntry(fixture), fakeContext());
- return {...resultToText(presentation, USER_NAMES), expandable: presentation.expandable};
-}
-
-function createdRole(snapshot: Record<string, unknown>, fixture: Partial<EntryFixture> = {}) {
- return present({
- action_type: AuditLogActionType.ROLE_CREATE,
- target_id: ROLE_ID,
- changes: Object.entries({...APP_CREATE_SNAPSHOT, ...snapshot}).map(([key, value]) => ({key, new_value: value})),
- ...fixture,
- });
-}
-
-function updatedRole(changes: ChangesFixture, fixture: Partial<EntryFixture> = {}) {
- return present({
- action_type: AuditLogActionType.ROLE_UPDATE,
- target_id: ROLE_ID,
- options: {role_name: 'Mods'},
- changes,
- ...fixture,
- });
-}
-
-function deletedRole(snapshot: Record<string, unknown>, fixture: Partial<EntryFixture> = {}) {
- return present({
- action_type: AuditLogActionType.ROLE_DELETE,
- target_id: ROLE_ID,
- changes: Object.entries({...DELETE_SNAPSHOT, ...snapshot}).map(([key, value]) => ({key, old_value: value})),
- ...fixture,
- });
-}
-
-const GENERIC_UPDATE_WITHOUT_ROWS = {
- summary: 'Hampus updated the role @Mods',
- rows: [],
- blocks: [],
- expandable: false,
-};
-
-describe('presentRoleCreate', () => {
- it('shows one Granted row for a role created from the app', () => {
- expect(createdRole({})).toEqual({
- summary: 'Hampus created the role @New role',
- rows: [
- '+ Granted Create invite links, Add reactions, Stream video, View channel, Send messages, Embed links, Attach files, and 8 more permissions',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows nothing to expand for a role created without permissions', () => {
- expect(createdRole({permissions: '0'})).toEqual({
- summary: 'Hampus created the role @New role',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each([
- {label: 'a color', snapshot: {color: ORANGE}, row: '~ Set the role color to #E67E22'},
- {
- label: 'members displayed separately',
- snapshot: {hoist: true},
- row: '+ Showed members with this role in their own section in the member list',
- },
- {label: 'mentions allowed', snapshot: {mentionable: true}, row: '+ Allowed all members to mention this role'},
- {label: 'an emoji icon', snapshot: {unicode_emoji: '🔥'}, row: '+ Set the role icon to 🔥'},
- {label: 'a custom icon', snapshot: {icon_hash: 'a1b2c3'}, row: '+ Set a custom role icon'},
- ])('shows a row for $label', ({snapshot, row}) => {
- expect(createdRole({permissions: '0', ...snapshot})).toEqual({
- summary: 'Hampus created the role @New role',
- rows: [row],
- blocks: [],
- expandable: true,
- });
- });
-
- it('orders every row of a fully customized role', () => {
- expect(
- createdRole({
- name: 'Moderators',
- permissions: (Permissions.MANAGE_MESSAGES | Permissions.SEND_MESSAGES).toString(),
- color: BLUE,
- icon_hash: 'a1b2c3',
- unicode_emoji: '🛡️',
- hoist: true,
- mentionable: true,
- }),
- ).toEqual({
- summary: 'Hampus created the role @Moderators',
- rows: [
- '+ Granted Send messages and Manage messages',
- '~ Set the role color to #3498DB',
- '+ Showed members with this role in their own section in the member list',
- '+ Allowed all members to mention this role',
- '+ Set the role icon to 🛡️',
- '+ Set a custom role icon',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('reads gateway string and number forms', () => {
- expect(
- createdRole({
- permissions: Number(Permissions.SEND_MESSAGES),
- color: String(ORANGE),
- hoist: 'true',
- mentionable: 'false',
- }),
- ).toEqual({
- summary: 'Hampus created the role @New role',
- rows: [
- '+ Granted Send messages',
- '~ Set the role color to #E67E22',
- '+ Showed members with this role in their own section in the member list',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {permissions: '12abc'},
- {permissions: '-4'},
- {permissions: String(UNKNOWN_PERMISSION_BIT)},
- {color: -1},
- {color: 1.5},
- {color: 0x1000000},
- {color: 'orange'},
- {hoist: 'yes'},
- {mentionable: 1},
- {unicode_emoji: ' '},
- {icon_hash: 42},
- {icon_hash: ''},
- ])('omits the row for %o', (snapshot) => {
- expect(createdRole({permissions: '0', ...snapshot}).rows).toEqual([]);
- });
-
- it('adds the decoded Reason block', () => {
- expect(createdRole({permissions: '0'}, {reason: 'Event%20staff'})).toEqual({
- summary: 'Hampus created the role @New role',
- rows: [],
- blocks: [{kind: 'reason', text: 'Event staff'}],
- expandable: true,
- });
- });
-
- it('leaves the recorded name empty when the name does not read', () => {
- expect(createdRole({name: ' '}).summary).toBe(`Hampus created the role @${ROLE_ID}`);
- expect(
- presentRoleCreate(makeEntry({action_type: AuditLogActionType.ROLE_CREATE, target_id: 'role', changes: []}))
- .summary.values.role,
- ).toEqual({kind: 'role', id: '', recordedName: null});
- });
-});
-
-describe('presentRoleUpdate', () => {
- it.each([
- {direction: 'up', oldValue: 2, newValue: 5, summary: 'Hampus moved the role @Mods up in the role list'},
- {direction: 'down', oldValue: 5, newValue: 2, summary: 'Hampus moved the role @Mods down in the role list'},
- ])('summarizes a role moved $direction in the role list', ({oldValue, newValue, summary}) => {
- expect(updatedRole([{key: 'position', old_value: oldValue, new_value: newValue}])).toEqual({
- summary,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('uses the generic summary for a position that did not change', () => {
- expect(updatedRole([{key: 'position', old_value: 3, new_value: 3}])).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it.each([
- {label: 'set', oldValue: null, newValue: 4, summary: 'Hampus set a member list position for the role @Mods'},
- {label: 'reset', oldValue: 4, newValue: null, summary: 'Hampus reset the member list position for the role @Mods'},
- {label: 'moved up', oldValue: 2, newValue: 5, summary: 'Hampus moved the role @Mods up in the member list'},
- {label: 'moved down', oldValue: 5, newValue: 2, summary: 'Hampus moved the role @Mods down in the member list'},
- ])('summarizes a member list position that was $label', ({oldValue, newValue, summary}) => {
- expect(updatedRole([{key: 'hoist_position', old_value: oldValue, new_value: newValue}])).toEqual({
- summary,
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each([
- {oldValue: 3, newValue: 3},
- {oldValue: null, newValue: null},
- {oldValue: 'top', newValue: 3},
- {oldValue: 3, newValue: 'bottom'},
- ])('ignores a member list position from $oldValue to $newValue', ({oldValue, newValue}) => {
- expect(updatedRole([{key: 'hoist_position', old_value: oldValue, new_value: newValue}])).toEqual(
- GENERIC_UPDATE_WITHOUT_ROWS,
- );
- });
-
- it('summarizes a rename with no rows', () => {
- expect(
- updatedRole([{key: 'name', old_value: 'Mods', new_value: 'Moderators'}], {options: {role_name: 'Moderators'}}),
- ).toEqual({
- summary: 'Hampus renamed the role Mods to Moderators',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it('uses the generic summary for an entry with no changes', () => {
- expect(updatedRole([])).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- expect(
- present({action_type: AuditLogActionType.ROLE_UPDATE, target_id: ROLE_ID, options: {role_name: 'Mods'}}),
- ).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it.each([
- {
- label: 'a granted permission',
- previous: Permissions.VIEW_CHANNEL,
- next: Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES,
- diff: {added: ['SEND_MESSAGES'], removed: []},
- rows: ['+ Granted Send messages'],
- },
- {
- label: 'a revoked permission',
- previous: Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES,
- next: Permissions.VIEW_CHANNEL,
- diff: {added: [], removed: ['SEND_MESSAGES']},
- rows: ['- Revoked Send messages'],
- },
- {
- label: 'granted and revoked permissions',
- previous: Permissions.KICK_MEMBERS,
- next: Permissions.BAN_MEMBERS | Permissions.MANAGE_MESSAGES,
- diff: {added: ['BAN_MEMBERS', 'MANAGE_MESSAGES'], removed: ['KICK_MEMBERS']},
- rows: ['+ Granted Ban members and Manage messages', '- Revoked Kick members'],
- },
- ])('shows $label from the permissions pair and not permissions_diff', ({previous, next, diff, rows}) => {
- expect(
- updatedRole([
- {key: 'permissions', old_value: previous.toString(), new_value: next.toString()},
- {key: 'permissions_diff', new_value: diff},
- ]),
- ).toEqual({summary: 'Hampus updated the role @Mods', rows, blocks: [], expandable: true});
- });
-
- it('reads legacy permissions_diff names when the permissions pair is absent', () => {
- expect(
- updatedRole([
- {
- key: 'permissions_diff',
- new_value: {added: ['MANAGE_MESSAGES', 'SEND_MESSAGES', 'NOT_A_PERMISSION'], removed: ['KICK_MEMBERS']},
- },
- ]),
- ).toEqual({
- summary: 'Hampus updated the role @Mods',
- rows: ['+ Granted Send messages and Manage messages', '- Revoked Kick members'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('does not fall back to permissions_diff when the permissions pair does not read', () => {
- expect(
- updatedRole([
- {key: 'permissions', old_value: 'abc', new_value: Permissions.VIEW_CHANNEL.toString()},
- {key: 'permissions_diff', new_value: {added: ['VIEW_CHANNEL'], removed: []}},
- ]),
- ).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it('shows nothing for permissions that differ only in bits the app does not know', () => {
- expect(
- updatedRole([
- {
- key: 'permissions',
- old_value: Permissions.VIEW_CHANNEL.toString(),
- new_value: (Permissions.VIEW_CHANNEL | UNKNOWN_PERMISSION_BIT).toString(),
- },
- ]),
- ).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it.each([
- {label: 'set', oldValue: 0, newValue: ORANGE, row: '+ Set the role color to #E67E22'},
- {label: 'removed', oldValue: ORANGE, newValue: 0, row: '- Removed the role color'},
- {label: 'changed', oldValue: ORANGE, newValue: BLUE, row: '~ Changed the role color from #E67E22 to #3498DB'},
- ])('shows a role color that was $label', ({oldValue, newValue, row}) => {
- expect(updatedRole([{key: 'color', old_value: oldValue, new_value: newValue}])).toEqual({
- summary: 'Hampus updated the role @Mods',
- rows: [row],
- blocks: [],
- expandable: true,
- });
- });
-
- it.each([
- {key: 'hoist', oldValue: false, newValue: true, row: '+ Started displaying members with this role separately'},
- {key: 'hoist', oldValue: true, newValue: false, row: '- Stopped displaying members with this role separately'},
- {key: 'mentionable', oldValue: false, newValue: true, row: '+ Allowed all members to mention this role'},
- {
- key: 'mentionable',
- oldValue: true,
- newValue: false,
- row: '- Limited mentions of this role to members with permission to mention any role',
- },
- {key: 'unicode_emoji', oldValue: null, newValue: '🔥', row: '+ Set the role icon to 🔥'},
- {key: 'unicode_emoji', oldValue: '🔥', newValue: '⭐', row: '~ Changed the role icon from 🔥 to ⭐'},
- {key: 'unicode_emoji', oldValue: '🔥', newValue: null, row: '- Removed the role icon'},
- {key: 'icon_hash', oldValue: null, newValue: 'a1b2c3', row: '+ Set a custom role icon'},
- {key: 'icon_hash', oldValue: 'a1b2c3', newValue: 'd4e5f6', row: '~ Changed the custom role icon'},
- {key: 'icon_hash', oldValue: 'a1b2c3', newValue: null, row: '- Removed the custom role icon'},
- ])('shows $key from $oldValue to $newValue', ({key, oldValue, newValue, row}) => {
- expect(updatedRole([{key, old_value: oldValue, new_value: newValue}])).toEqual({
- summary: 'Hampus updated the role @Mods',
- rows: [row],
- blocks: [],
- expandable: true,
- });
- });
-
- it('treats blank icons as no icon', () => {
- expect(
- updatedRole([
- {key: 'unicode_emoji', old_value: ' ', new_value: null},
- {key: 'icon_hash', old_value: null, new_value: ''},
- ]),
- ).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it.each([
- {change: {key: 'position', old_value: 2, new_value: 5}, row: '~ Moved the role up in the role list'},
- {change: {key: 'position', old_value: 5, new_value: 2}, row: '~ Moved the role down in the role list'},
- {change: {key: 'hoist_position', old_value: null, new_value: 4}, row: '~ Set a member list position for the role'},
- {
- change: {key: 'hoist_position', old_value: 4, new_value: null},
- row: '~ Reset the member list position for the role',
- },
- {change: {key: 'hoist_position', old_value: 2, new_value: 5}, row: '~ Moved the role up in the member list'},
- {change: {key: 'hoist_position', old_value: 5, new_value: 2}, row: '~ Moved the role down in the member list'},
- ])('shows $change.key as a row when it comes with another change', ({change, row}) => {
- expect(updatedRole([change, {key: 'color', old_value: 0, new_value: ORANGE}])).toEqual({
- summary: 'Hampus updated the role @Mods',
- rows: ['+ Set the role color to #E67E22', row],
- blocks: [],
- expandable: true,
- });
- });
-
- it('lists every change in a fixed order under the generic summary', () => {
- expect(
- updatedRole(
- [
- {key: 'hoist_position', old_value: null, new_value: 3},
- {key: 'position', old_value: 2, new_value: 4},
- {key: 'icon_hash', old_value: 'a1b2c3', new_value: null},
- {key: 'unicode_emoji', old_value: null, new_value: '🔥'},
- {key: 'mentionable', old_value: true, new_value: false},
- {key: 'hoist', old_value: false, new_value: true},
- {key: 'color', old_value: ORANGE, new_value: BLUE},
- {key: 'permissions_diff', new_value: {added: ['MANAGE_MESSAGES'], removed: ['KICK_MEMBERS']}},
- {
- key: 'permissions',
- old_value: Permissions.KICK_MEMBERS.toString(),
- new_value: Permissions.MANAGE_MESSAGES.toString(),
- },
- {key: 'name', old_value: 'Mods', new_value: 'Moderators'},
- {key: 'role_id', new_value: ROLE_ID},
- ],
- {options: {role_name: 'Moderators'}},
- ),
- ).toEqual({
- summary: 'Hampus updated the role @Moderators',
- rows: [
- '~ Changed the name from Mods to Moderators',
- '+ Granted Manage messages',
- '- Revoked Kick members',
- '~ Changed the role color from #E67E22 to #3498DB',
- '+ Started displaying members with this role separately',
- '- Limited mentions of this role to members with permission to mention any role',
- '+ Set the role icon to 🔥',
- '- Removed the custom role icon',
- '~ Moved the role up in the role list',
- '~ Set a member list position for the role',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names the role by its new name before the recorded role name', () => {
- expect(
- updatedRole(
- [
- {key: 'name', old_value: 'Mods', new_value: 'Moderators'},
- {key: 'hoist', old_value: false, new_value: true},
- ],
- {options: {role_name: 'Staff'}},
- ),
- ).toEqual({
- summary: 'Hampus updated the role @Moderators',
- rows: ['~ Changed the name from Mods to Moderators', '+ Started displaying members with this role separately'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows @everyone for the default role', () => {
- const entry = makeEntry({
- action_type: AuditLogActionType.ROLE_UPDATE,
- target_id: TEST_GUILD_ID,
- options: {role_name: '@everyone'},
- changes: [
- {
- key: 'permissions',
- old_value: Permissions.VIEW_CHANNEL.toString(),
- new_value: (Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES).toString(),
- },
- ],
- });
- expect(presentRoleUpdate(entry).summary.values.role).toEqual({
- kind: 'role',
- id: TEST_GUILD_ID,
- recordedName: '@everyone',
- });
- expect(present({...entry, action_type: AuditLogActionType.ROLE_UPDATE})).toEqual({
- summary: 'Hampus updated the role @everyone',
- rows: ['+ Granted Send messages'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('names a deleted role by the recorded role name', () => {
- expect(updatedRole([{key: 'position', old_value: 1, new_value: 3}], {options: {role_name: 'Old staff'}})).toEqual({
- summary: 'Hampus moved the role @Old staff up in the role list',
- rows: [],
- blocks: [],
- expandable: false,
- });
- expect(
- presentRoleUpdate(
- makeEntry({
- action_type: AuditLogActionType.ROLE_UPDATE,
- target_id: ROLE_ID,
- changes: [{key: 'position', old_value: 1, new_value: 3}],
- }),
- ).summary.values.role,
- ).toEqual({kind: 'role', id: ROLE_ID, recordedName: null});
- });
-
- it('reads gateway string forms', () => {
- expect(
- updatedRole([
- {key: 'color', old_value: '0', new_value: String(ORANGE)},
- {key: 'hoist', old_value: 'false', new_value: 'true'},
- {key: 'position', old_value: '4', new_value: '2'},
- ]),
- ).toEqual({
- summary: 'Hampus updated the role @Mods',
- rows: [
- '+ Set the role color to #E67E22',
- '+ Started displaying members with this role separately',
- '~ Moved the role down in the role list',
- ],
- blocks: [],
- expandable: true,
- });
- });
-
- it('omits changes whose values do not read', () => {
- expect(
- updatedRole(
- [
- {key: 'name', old_value: 42, new_value: 'Mods'},
- {key: 'permissions', old_value: '-1', new_value: Permissions.VIEW_CHANNEL.toString()},
- {key: 'color', old_value: 'red', new_value: ORANGE},
- {key: 'hoist', old_value: 'yes', new_value: true},
- {key: 'mentionable', new_value: true},
- {key: 'unicode_emoji', old_value: 5, new_value: '🔥'},
- {key: 'icon_hash', old_value: null, new_value: {}},
- {key: 'position', old_value: null, new_value: 3},
- {key: 'hoist_position', old_value: 'top', new_value: 3},
- ],
- {options: {role_name: 'Staff'}},
- ),
- ).toEqual(GENERIC_UPDATE_WITHOUT_ROWS);
- });
-
- it('adds the decoded Reason block to a summary-only entry', () => {
- expect(updatedRole([{key: 'position', old_value: 2, new_value: 5}], {reason: 'Reorder%20pass'})).toEqual({
- summary: 'Hampus moved the role @Mods up in the role list',
- rows: [],
- blocks: [{kind: 'reason', text: 'Reorder pass'}],
- expandable: true,
- });
- });
-
- it('names the system as the actor', () => {
- expect(updatedRole([{key: 'position', old_value: 2, new_value: 5}], {user_id: '0'}).summary).toBe(
- 'System moved the role @Mods up in the role list',
- );
- });
-});
-
-describe('presentRoleDelete', () => {
- it('lists the permissions the deleted role granted', () => {
- expect(deletedRole({})).toEqual({
- summary: 'Hampus deleted the role @Mods',
- rows: ['- The role granted Kick members, Ban members, and Manage messages'],
- blocks: [],
- expandable: true,
- });
- });
-
- it('shows nothing to expand for a deleted role without permissions', () => {
- expect(deletedRole({permissions: '0'})).toEqual({
- summary: 'Hampus deleted the role @Mods',
- rows: [],
- blocks: [],
- expandable: false,
- });
- });
-
- it.each([String(UNKNOWN_PERMISSION_BIT), 'abc', null])('shows no row for the permissions %o', (permissions) => {
- expect(deletedRole({permissions}).rows).toEqual([]);
- });
-
- it('caps a long permission list', () => {
- expect(deletedRole({permissions: DEFAULT_PERMISSIONS.toString()}).rows).toEqual([
- '- The role granted Create invite links, Add reactions, Stream video, View channel, Send messages, Embed links, Attach files, and 8 more permissions',
- ]);
- });
-
- it('adds the decoded Reason block', () => {
- expect(deletedRole({permissions: '0'}, {reason: 'No%20longer%20needed'})).toEqual({
- summary: 'Hampus deleted the role @Mods',
- rows: [],
- blocks: [{kind: 'reason', text: 'No longer needed'}],
- expandable: true,
- });
- });
-
- it('leaves the recorded name empty when the name does not read', () => {
- expect(deletedRole({name: null}).summary).toBe(`Hampus deleted the role @${ROLE_ID}`);
- });
-});
-
-describe('role presenters with junk entries', () => {
- it.each([
- {presenter: presentRoleCreate, actionType: AuditLogActionType.ROLE_CREATE},
- {presenter: presentRoleUpdate, actionType: AuditLogActionType.ROLE_UPDATE},
- {presenter: presentRoleDelete, actionType: AuditLogActionType.ROLE_DELETE},
- ])('never throws and shows no rows for action type $actionType', ({presenter, actionType}) => {
- const entry = makeEntry({
- action_type: actionType,
- target_id: 'role',
- user_id: null,
- options: {role_name: 7},
- changes: [
- {key: 'name'},
- {key: 'permissions', old_value: [], new_value: {added: 1}},
- {key: 'permissions_diff', new_value: {added: 'SEND_MESSAGES', removed: [1]}},
- {key: 'color', old_value: Number.NaN, new_value: Number.POSITIVE_INFINITY},
- {key: 'hoist', old_value: null, new_value: null},
- {key: 'unicode_emoji', old_value: ['🔥'], new_value: ['⭐']},
- {key: 'position', old_value: {}, new_value: []},
- ],
- });
- const result = presenter(entry);
- expect(() => resultToText(result)).not.toThrow();
- expect(result.rows).toEqual([]);
- expect(result.summary.values.role).toEqual({kind: 'role', id: '', recordedName: null});
- });
-});
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils.ts
deleted file mode 100644
index d0ec3ea6b..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- AuditLogBlock,
- AuditLogDomainResult,
- AuditLogPlaceholder,
- AuditLogPresentationContext,
- AuditLogSentence,
- AuditLogTone,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogPresentationTypes';
-import {
- MORE_PERMISSIONS_DESCRIPTOR,
- SYSTEM_ACTOR_LABEL,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogSharedMessages';
-import {largestDurationUnit} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogValues';
-import {
- DAYS_DURATION_PLURAL_DESCRIPTOR,
- HOURS_DURATION_PLURAL_DESCRIPTOR,
- MINUTES_DURATION_PLURAL_DESCRIPTOR,
- SECONDS_DURATION_PLURAL_DESCRIPTOR,
-} from '@app/features/i18n/utils/CommonMessageDescriptors';
-import {getPermissionTitleDescriptor} from '@app/features/permissions/utils/PermissionLabelDescriptors';
-import type {GuildAuditLogEntryResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';
-import * as SnowflakeUtils from '@fluxer/snowflake/src/SnowflakeUtils';
-import {setupI18n} from '@lingui/core';
-
-export const TEST_GUILD_ID = '1400000000000000000';
-export const TEST_ACTOR_ID = '1400000000000000001';
-export const TEST_ENTRY_TIME = Date.parse('2026-09-01T12:00:00.000Z');
-
-const TEST_ENTRY_ID = SnowflakeUtils.fromTimestamp(TEST_ENTRY_TIME);
-const PERMISSION_LIST_LIMIT = 8;
-const PERMISSION_LIST_SHOWN = 7;
-const MESSAGE_ARGUMENT_PATTERN = /\{\s*(\w+)\s*[,}]/g;
-const TONE_MARKS: Record<AuditLogTone, string> = {add: '+', remove: '-', neutral: '~'};
-
-const i18n = setupI18n({locale: 'en', messages: {en: {}}});
-const listFormatter = new Intl.ListFormat('en', {type: 'conjunction', style: 'long'});
-
-interface AuditLogEntryFixture {
- action_type: number;
- id?: string;
- user_id?: string | null;
- target_id?: string | null;
- reason?: string;
- options?: Record<string, unknown>;
- changes?: Array<{key: string; old_value?: unknown; new_value?: unknown}>;
-}
-
-interface FakeContextNames {
- webhooks?: Readonly<Record<string, string>>;
- emojis?: Readonly<Record<string, string>>;
- stickers?: Readonly<Record<string, string>>;
-}
-
-interface AuditLogResultText {
- summary: string;
- rows: Array<string>;
- blocks: Array<AuditLogBlock>;
-}
-
-export function makeEntry(fixture: AuditLogEntryFixture): GuildAuditLogEntryResponse {
- return {id: TEST_ENTRY_ID, user_id: TEST_ACTOR_ID, target_id: null, ...fixture} as GuildAuditLogEntryResponse;
-}
-
-export function fakeContext(names: FakeContextNames = {}): AuditLogPresentationContext {
- return {
- guildId: TEST_GUILD_ID,
- getWebhookName: (id) => names.webhooks?.[id] ?? null,
- getEmojiName: (id) => names.emojis?.[id] ?? null,
- getStickerName: (id) => names.stickers?.[id] ?? null,
- };
-}
-
-function formatDuration(seconds: number): string {
- const {unit, value} = largestDurationUnit(seconds);
- switch (unit) {
- case 'days':
- return i18n._(DAYS_DURATION_PLURAL_DESCRIPTOR, {days: value});
- case 'hours':
- return i18n._(HOURS_DURATION_PLURAL_DESCRIPTOR, {hours: value});
- case 'minutes':
- return i18n._(MINUTES_DURATION_PLURAL_DESCRIPTOR, {minutes: value});
- case 'seconds':
- return i18n._(SECONDS_DURATION_PLURAL_DESCRIPTOR, {seconds: value});
- }
-}
-
-function formatPermissions(flags: ReadonlyArray<bigint>): string {
- const titles = flags.map((flag) => {
- const descriptor = getPermissionTitleDescriptor(flag);
- return descriptor ? i18n._(descriptor) : flag.toString();
- });
- if (titles.length <= PERMISSION_LIST_LIMIT) return listFormatter.format(titles);
- return listFormatter.format([
- ...titles.slice(0, PERMISSION_LIST_SHOWN),
- i18n._(MORE_PERMISSIONS_DESCRIPTOR, {count: titles.length - PERMISSION_LIST_SHOWN}),
- ]);
-}
-
-function formatColor(value: number): string {
- return `#${value.toString(16).padStart(6, '0').toUpperCase()}`;
-}
-
-function placeholderToText(placeholder: AuditLogPlaceholder, userNames: Readonly<Record<string, string>>): string {
- switch (placeholder.kind) {
- case 'user':
- return userNames[placeholder.id] ?? `@${placeholder.id}`;
- case 'system':
- return i18n._(SYSTEM_ACTOR_LABEL);
- case 'channel':
- return `#${placeholder.recordedName ?? placeholder.id}`;
- case 'role':
- return placeholder.id === TEST_GUILD_ID ? '@everyone' : `@${placeholder.recordedName ?? placeholder.id}`;
- case 'name':
- case 'text':
- return placeholder.value;
- case 'emoji':
- return `:${placeholder.name}:`;
- case 'date':
- return new Date(placeholder.timestamp).toISOString();
- case 'duration':
- return formatDuration(placeholder.seconds);
- case 'permissions':
- return formatPermissions(placeholder.flags);
- case 'color':
- return formatColor(placeholder.value);
- case 'label':
- return i18n._(placeholder.descriptor);
- }
-}
-
-export function toText(sentence: AuditLogSentence, userNames: Readonly<Record<string, string>> = {}): string {
- const message = sentence.descriptor.message ?? '';
- const argumentNames = new Set(Array.from(message.matchAll(MESSAGE_ARGUMENT_PATTERN), (match) => match[1]));
- const passedNames = Object.keys(sentence.values);
- const unused = passedNames.filter((name) => !argumentNames.has(name));
- const missing = [...argumentNames].filter((name) => !Object.hasOwn(sentence.values, name));
- if (unused.length > 0 || missing.length > 0) {
- throw new Error(
- `Placeholders do not match "${message}". Not in the message: [${unused.join(', ')}]. Not passed: [${missing.join(', ')}].`,
- );
- }
- const values: Record<string, string | number> = {};
- for (const [name, value] of Object.entries(sentence.values)) {
- values[name] = typeof value === 'number' ? value : placeholderToText(value, userNames);
- }
- return i18n._(sentence.descriptor, values);
-}
-
-export function resultToText(
- result: AuditLogDomainResult,
- userNames: Readonly<Record<string, string>> = {},
-): AuditLogResultText {
- return {
- summary: toText(result.summary, userNames),
- rows: result.rows.map((row) => `${TONE_MARKS[row.tone]} ${toText(row.sentence, userNames)}`),
- blocks: result.blocks,
- };
-}
diff --git a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogValues.test.ts b/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogValues.test.ts
deleted file mode 100644
index eccdc7bb1..000000000
--- a/fluxer_app/src/features/guild/utils/guild_tabs/audit_log/AuditLogValues.test.ts
+++ /dev/null
@@ -1,380 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- makeEntry,
- TEST_ACTOR_ID,
- TEST_ENTRY_TIME,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogTestUtils';
-import {
- actorPlaceholder,
- channelNoun,
- decodeAuditReason,
- diffBitfields,
- diffOverwriteStates,
- entryTime,
- featureDelta,
- largestDurationUnit,
- permissionFlagsIn,
- readBitfield,
- readBoolean,
- readChange,
- readNumber,
- readOption,
- readSnowflake,
- readString,
- readStringArray,
- readTimestamp,
- roleIdDiff,
-} from '@app/features/guild/utils/guild_tabs/audit_log/AuditLogValues';
-import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {ALL_PERMISSIONS, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-const UNKNOWN_BIT = 1n << 62n;
-const JUNK: Array<unknown> = [null, undefined, true, [], {}, Number.NaN];
-
-describe('readString', () => {
- it('trims and keeps non-blank strings', () => {
- expect(readString(' general ')).toBe('general');
- expect(readString('0')).toBe('0');
- });
-
- it('treats blank strings and non-strings as missing', () => {
- for (const junk of ['', ' ', 5, ...JUNK]) {
- expect(readString(junk)).toBeNull();
- }
- });
-});
-
-describe('readNumber', () => {
- it('reads REST numbers and dispatch numeric strings', () => {
- expect(readNumber(3600)).toBe(3600);
- expect(readNumber(0)).toBe(0);
- expect(readNumber('3600')).toBe(3600);
- expect(readNumber(' 7 ')).toBe(7);
- expect(readNumber('-1.5')).toBe(-1.5);
- });
-
- it('rejects junk', () => {
- for (const junk of ['', ' ', 'x', '7 days', '0x10', Number.POSITIVE_INFINITY, ...JUNK]) {
- expect(readNumber(junk)).toBeNull();
- }
- });
-});
-
-describe('readBoolean', () => {
- it('reads REST booleans and dispatch boolean strings', () => {
- expect(readBoolean(true)).toBe(true);
- expect(readBoolean(false)).toBe(false);
- expect(readBoolean('true')).toBe(true);
- expect(readBoolean('false')).toBe(false);
- });
-
- it('rejects junk', () => {
- for (const junk of ['1', '0', 1, 0, 'yes', 'TRUE', '', null, undefined, {}]) {
- expect(readBoolean(junk)).toBeNull();
- }
- });
-});
-
-describe('readTimestamp', () => {
- it('parses date strings', () => {
- expect(readTimestamp('2026-09-01T12:00:00.000Z')).toBe(Date.parse('2026-09-01T12:00:00.000Z'));
- expect(readTimestamp('2026-09-01T12:00:00+00:00')).toBe(Date.parse('2026-09-01T12:00:00.000Z'));
- });
-
- it('rejects unparseable strings and non-strings', () => {
- for (const junk of ['not-a-date', '', ' ', 1788264000000, ...JUNK]) {
- expect(readTimestamp(junk)).toBeNull();
- }
- });
-});
-
-describe('readBitfield', () => {
- it('reads decimal strings and safe integers', () => {
- expect(readBitfield('8')).toBe(8n);
- expect(readBitfield('0')).toBe(0n);
- expect(readBitfield(8)).toBe(8n);
- expect(readBitfield((1n << 51n).toString())).toBe(Permissions.PIN_MESSAGES);
- });
-
- it('rejects junk', () => {
- for (const junk of ['-8', '8.5', ' 8', 'abc', '', 1.5, -1, 2 ** 53, 8n, ...JUNK]) {
- expect(readBitfield(junk)).toBeNull();
- }
- });
-});
-
-describe('readSnowflake', () => {
- it('reads snowflake strings', () => {
- expect(readSnowflake('1400000000000000123')).toBe('1400000000000000123');
- });
-
- it('rejects junk', () => {
- for (const junk of ['', 'abc', '12a', ' 123', '123456789012345678901', 1400000000000000000, ...JUNK]) {
- expect(readSnowflake(junk)).toBeNull();
- }
- });
-});
-
-describe('readStringArray', () => {
- it('reads arrays of strings', () => {
- expect(readStringArray(['a', 'b'])).toEqual(['a', 'b']);
- expect(readStringArray([])).toEqual([]);
- });
-
- it('rejects arrays holding anything but strings, and non-arrays', () => {
- for (const junk of [['a', 1], [null], 'a', ...JUNK.filter((value) => !Array.isArray(value))]) {
- expect(readStringArray(junk)).toBeNull();
- }
- });
-});
-
-describe('readChange', () => {
- it('reports presence from the keys that exist, counting explicit nulls', () => {
- const entry = makeEntry({
- action_type: AuditLogActionType.MEMBER_UPDATE,
- changes: [
- {key: 'nick', new_value: 'Hampus'},
- {key: 'avatar_hash', old_value: 'abc'},
- {key: 'banner_hash', old_value: null, new_value: null},
- ],
- });
- expect(readChange(entry, 'nick')).toEqual({hasOld: false, hasNew: true, oldValue: null, newValue: 'Hampus'});
- expect(readChange(entry, 'avatar_hash')).toEqual({hasOld: true, hasNew: false, oldValue: 'abc', newValue: null});
- expect(readChange(entry, 'banner_hash')).toEqual({hasOld: true, hasNew: true, oldValue: null, newValue: null});
- });
-
- it('uses the first occurrence of a key', () => {
- const entry = makeEntry({
- action_type: AuditLogActionType.CHANNEL_UPDATE,
- changes: [
- {key: 'name', old_value: 'first-old', new_value: 'first-new'},
- {key: 'name', old_value: 'second-old', new_value: 'second-new'},
- ],
- });
- expect(readChange(entry, 'name')).toEqual({
- hasOld: true,
- hasNew: true,
- oldValue: 'first-old',
- newValue: 'first-new',
- });
- });
-
- it('returns null for a missing key or missing changes', () => {
- const entry = makeEntry({action_type: AuditLogActionType.CHANNEL_UPDATE, changes: [{key: 'name', new_value: 'a'}]});
- expect(readChange(entry, 'topic')).toBeNull();
- expect(readChange(makeEntry({action_type: AuditLogActionType.MEMBER_KICK}), 'name')).toBeNull();
- });
-});
-
-describe('readOption', () => {
- it('returns REST typed values and raw dispatch strings as stored', () => {
- const rest = makeEntry({
- action_type: AuditLogActionType.INVITE_CREATE,
- options: {max_age: 604800, temporary: false, channel_id: '1400000000000000200'},
- });
- const dispatch = makeEntry({
- action_type: AuditLogActionType.INVITE_CREATE,
- options: {max_age: '604800', temporary: 'false'},
- });
- expect(readOption(rest, 'max_age')).toBe(604800);
- expect(readOption(rest, 'temporary')).toBe(false);
- expect(readOption(rest, 'channel_id')).toBe('1400000000000000200');
- expect(readNumber(readOption(dispatch, 'max_age'))).toBe(604800);
- expect(readBoolean(readOption(dispatch, 'temporary'))).toBe(false);
- });
-
- it('returns null for a missing key or missing options', () => {
- expect(readOption(makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD, options: {}}), 'count')).toBeNull();
- expect(readOption(makeEntry({action_type: AuditLogActionType.MEMBER_BAN_ADD}), 'count')).toBeNull();
- });
-});
-
-describe('entryTime', () => {
- it('reads the time from the entry snowflake', () => {
- expect(entryTime(makeEntry({action_type: AuditLogActionType.MEMBER_KICK}))).toBe(TEST_ENTRY_TIME);
- });
-});
-
-describe('actorPlaceholder', () => {
- it('is the acting user', () => {
- expect(actorPlaceholder(makeEntry({action_type: AuditLogActionType.MEMBER_KICK}))).toEqual({
- kind: 'user',
- id: TEST_ACTOR_ID,
- });
- });
-
- it('is the system when user_id is "0"', () => {
- expect(actorPlaceholder(makeEntry({action_type: AuditLogActionType.MEMBER_ROLE_UPDATE, user_id: '0'}))).toEqual({
- kind: 'system',
- });
- });
-});
-
-describe('decodeAuditReason', () => {
- it('keeps plain reasons, including a lone percent sign', () => {
- expect(decodeAuditReason('Spamming invites')).toBe('Spamming invites');
- expect(decodeAuditReason('Banned for 100% spam')).toBe('Banned for 100% spam');
- });
-
- it('decodes percent-encoded UTF-8', () => {
- expect(decodeAuditReason('Spamming%20invites')).toBe('Spamming invites');
- expect(decodeAuditReason('Caf%C3%A9%20raid%20%E7%A6%81%E6%AD%A2')).toBe('Café raid 禁止');
- });
-
- it('keeps a malformed sequence raw', () => {
- expect(decodeAuditReason('bad %E0%A4%A sequence')).toBe('bad %E0%A4%A sequence');
- });
-
- it('trims, and treats whitespace and missing reasons as null', () => {
- expect(decodeAuditReason(' padded ')).toBe('padded');
- expect(decodeAuditReason(' ')).toBeNull();
- expect(decodeAuditReason('')).toBeNull();
- expect(decodeAuditReason('%20%20')).toBeNull();
- expect(decodeAuditReason(null)).toBeNull();
- expect(decodeAuditReason(undefined)).toBeNull();
- });
-});
-
-describe('largestDurationUnit', () => {
- it.each([
- [30, {unit: 'seconds', value: 30}],
- [90, {unit: 'seconds', value: 90}],
- [300, {unit: 'minutes', value: 5}],
- [3600, {unit: 'hours', value: 1}],
- [5400, {unit: 'minutes', value: 90}],
- [86400, {unit: 'days', value: 1}],
- [604800, {unit: 'days', value: 7}],
- [259199.993, {unit: 'days', value: 3}],
- [0, {unit: 'seconds', value: 0}],
- ])('expresses %s seconds in the largest whole unit', (seconds, expected) => {
- expect(largestDurationUnit(seconds)).toEqual(expected);
- });
-});
-
-describe('permissionFlagsIn', () => {
- it('lists known flags in the Permissions declaration order', () => {
- expect(permissionFlagsIn(ALL_PERMISSIONS | UNKNOWN_BIT)).toEqual(Object.values(Permissions));
- expect(permissionFlagsIn(Permissions.MANAGE_ROLES | Permissions.KICK_MEMBERS | UNKNOWN_BIT)).toEqual([
- Permissions.KICK_MEMBERS,
- Permissions.MANAGE_ROLES,
- ]);
- expect(permissionFlagsIn(0n)).toEqual([]);
- });
-});
-
-describe('diffBitfields', () => {
- it('lists added and removed known flags in declaration order', () => {
- expect(
- diffBitfields(
- Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES | UNKNOWN_BIT,
- Permissions.SEND_MESSAGES | Permissions.MANAGE_ROLES | Permissions.ADMINISTRATOR,
- ),
- ).toEqual({added: [Permissions.ADMINISTRATOR, Permissions.MANAGE_ROLES], removed: [Permissions.VIEW_CHANNEL]});
- });
-
- it('is empty for equal masks and unknown bits', () => {
- expect(diffBitfields(Permissions.SPEAK, Permissions.SPEAK)).toEqual({added: [], removed: []});
- expect(diffBitfields(0n, UNKNOWN_BIT)).toEqual({added: [], removed: []});
- });
-});
-
-describe('diffOverwriteStates', () => {
- it('reports an allow to deny flip as denied only', () => {
- expect(
- diffOverwriteStates({allow: Permissions.SEND_MESSAGES, deny: 0n}, {allow: 0n, deny: Permissions.SEND_MESSAGES}),
- ).toEqual({allowed: [], denied: [Permissions.SEND_MESSAGES], cleared: []});
- });
-
- it('reports an allow that is no longer set as cleared', () => {
- expect(
- diffOverwriteStates(
- {allow: Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES, deny: 0n},
- {allow: Permissions.VIEW_CHANNEL, deny: 0n},
- ),
- ).toEqual({allowed: [], denied: [], cleared: [Permissions.SEND_MESSAGES]});
- });
-
- it('reports a deny that is no longer set as cleared', () => {
- expect(diffOverwriteStates({allow: 0n, deny: Permissions.ATTACH_FILES}, {allow: 0n, deny: 0n})).toEqual({
- allowed: [],
- denied: [],
- cleared: [Permissions.ATTACH_FILES],
- });
- });
-
- it('reports new allows and denies in declaration order', () => {
- expect(
- diffOverwriteStates(
- {allow: 0n, deny: 0n},
- {
- allow: Permissions.SPEAK | Permissions.VIEW_CHANNEL,
- deny: Permissions.MENTION_EVERYONE | Permissions.ADD_REACTIONS,
- },
- ),
- ).toEqual({
- allowed: [Permissions.VIEW_CHANNEL, Permissions.SPEAK],
- denied: [Permissions.ADD_REACTIONS, Permissions.MENTION_EVERYONE],
- cleared: [],
- });
- });
-
- it('ignores unknown bits', () => {
- expect(diffOverwriteStates({allow: UNKNOWN_BIT, deny: 1n << 61n}, {allow: 1n << 61n, deny: UNKNOWN_BIT})).toEqual({
- allowed: [],
- denied: [],
- cleared: [],
- });
- });
-});
-
-describe('roleIdDiff', () => {
- it('lists added ids in new order and removed ids in old order', () => {
- expect(roleIdDiff(['a', 'b', 'c', 'f'], ['e', 'c', 'd', 'a'])).toEqual({added: ['e', 'd'], removed: ['b', 'f']});
- expect(roleIdDiff(['x', 'b', 'y'], [])).toEqual({added: [], removed: ['x', 'b', 'y']});
- });
-
- it('lists each id once', () => {
- expect(roleIdDiff([], ['a', 'a'])).toEqual({added: ['a'], removed: []});
- });
-});
-
-describe('channelNoun', () => {
- it.each([
- [0, 'text'],
- [2, 'voice'],
- [998, 'link'],
- [4, 'category'],
- [1, 'generic'],
- [3, 'generic'],
- [null, 'generic'],
- ] as const)('maps channel type %s to %s', (type, noun) => {
- expect(channelNoun(type)).toBe(noun);
- });
-});
-
-describe('featureDelta', () => {
- it('reports whether one feature was added or removed', () => {
- const feature = GuildFeatures.INVITES_DISABLED;
- expect(featureDelta([], [feature], feature)).toBe('added');
- expect(featureDelta([feature, 'OTHER'], ['OTHER'], feature)).toBe('removed');
- expect(featureDelta([feature], [feature], feature)).toBeNull();
- expect(featureDelta(['OTHER'], [], feature)).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/i18n/testing/TranslatorSimulation.test.tsx b/fluxer_app/src/features/i18n/testing/TranslatorSimulation.test.tsx
deleted file mode 100644
index 22cb54c1d..000000000
--- a/fluxer_app/src/features/i18n/testing/TranslatorSimulation.test.tsx
+++ /dev/null
@@ -1,232 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {commitUnderTranslation, isTranslationDomCrash} from '@app/features/i18n/testing/TranslationCommitHarness';
-import {
- chromeFaithfulCompoundPipeline,
- findTranslationUnsafeTextNodes,
- TRANSLATION_MARKER,
- TRANSLATOR_PIPELINE_NAMES,
- TranslatorPipelines,
-} from '@app/features/i18n/testing/TranslatorSimulation';
-import {createElement, Fragment, type ReactNode} from 'react';
-import {afterEach, describe, expect, it} from 'vitest';
-
-const badge = (on: boolean): ReactNode => (on ? createElement('b', null, '!') : null);
-const tail = createElement('i', null, 'x');
-
-const BareLabel = (): ReactNode => 'Hello';
-const WrappedLabel = (): ReactNode => createElement('flx-i18n', null, 'Hello');
-
-const wrap = (text: string): ReactNode => createElement('flx-i18n', null, text);
-const row = (...children: Array<ReactNode>): ReactNode => createElement('div', null, ...children);
-
-const visibleText = (html: string): string => html.replace(/<[^>]+>/g, '').replaceAll(TRANSLATION_MARKER, '');
-
-interface Scenario {
- name: string;
- unsafe: (on: boolean) => ReactNode;
- fixed: (on: boolean) => ReactNode;
- beforeState: boolean;
- afterState: boolean;
- expectedText: string;
- expectedFirstTag: string;
-}
-
-const scenarios: Array<Scenario> = [
- {
- name: 'placement before a bare text sibling',
- unsafe: (on) => row(badge(on), 'Hello', tail),
- fixed: (on) => row(badge(on), wrap('Hello'), tail),
- beforeState: false,
- afterState: true,
- expectedText: '!Hellox',
- expectedFirstTag: 'B',
- },
- {
- name: 'deletion of a bare text sibling',
- unsafe: (on) => row(on ? 'Hello' : null, tail),
- fixed: (on) => row(on ? wrap('Hello') : null, tail),
- beforeState: true,
- afterState: false,
- expectedText: 'x',
- expectedFirstTag: 'I',
- },
- {
- name: 'placement between adjacent text nodes',
- unsafe: (on) => row('A', badge(on), 'B', tail),
- fixed: (on) => row(wrap('A'), badge(on), wrap('B'), tail),
- beforeState: false,
- afterState: true,
- expectedText: 'A!Bx',
- expectedFirstTag: 'FLX-I18N',
- },
- {
- name: 'placement before text inside a fragment',
- unsafe: (on) => row(createElement(Fragment, null, badge(on), 'Hello'), tail),
- fixed: (on) => row(createElement(Fragment, null, badge(on), wrap('Hello')), tail),
- beforeState: false,
- afterState: true,
- expectedText: '!Hellox',
- expectedFirstTag: 'B',
- },
- {
- name: 'placement before a component that returns a bare string',
- unsafe: (on) => row(badge(on), createElement(BareLabel), tail),
- fixed: (on) => row(badge(on), createElement(WrappedLabel), tail),
- beforeState: false,
- afterState: true,
- expectedText: '!Hellox',
- expectedFirstTag: 'B',
- },
-];
-
-afterEach(() => {
- document.body.replaceChildren();
-});
-
-for (const pipelineName of TRANSLATOR_PIPELINE_NAMES) {
- const pipeline = TranslatorPipelines[pipelineName];
- describe(`${pipelineName} pipeline`, () => {
- for (const scenario of scenarios) {
- it(`throws the production DOM error on ${scenario.name}`, () => {
- const result = commitUnderTranslation({
- before: scenario.unsafe(scenario.beforeState),
- after: scenario.unsafe(scenario.afterState),
- pipeline,
- });
- expect(result.unsafeTextNodesBeforeTranslation).toBeGreaterThan(0);
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(isTranslationDomCrash(result.error)).toBe(true);
- });
-
- if (pipelineName === 'chromeCompound') {
- it(`leaves the compound pipeline no text-and-element parent to rewrite in ${scenario.name}`, () => {
- const unsafe = commitUnderTranslation({
- before: scenario.unsafe(scenario.beforeState),
- after: scenario.unsafe(scenario.beforeState),
- pipeline,
- });
- expect(unsafe.unsafeTextNodesBeforeTranslation).toBeGreaterThan(0);
- expect(unsafe.htmlAfterTranslation).not.toBe(unsafe.htmlBeforeTranslation);
-
- const fixed = commitUnderTranslation({
- before: scenario.fixed(scenario.beforeState),
- after: scenario.fixed(scenario.afterState),
- pipeline,
- });
- expect(fixed.unsafeTextNodesBeforeTranslation).toBe(0);
- expect(fixed.htmlAfterTranslation).toBe(fixed.htmlBeforeTranslation);
- expect(fixed.error).toBeNull();
- });
- continue;
- }
-
- it(`survives ${scenario.name} once the text is a sole child`, () => {
- let firstTag: string | null = null;
- let unsafeTextNodes = -1;
- const result = commitUnderTranslation({
- before: scenario.fixed(scenario.beforeState),
- after: scenario.fixed(scenario.afterState),
- pipeline,
- inspect: (host) => {
- firstTag = host.querySelector('div')?.firstElementChild?.tagName ?? null;
- unsafeTextNodes = findTranslationUnsafeTextNodes(host).length;
- },
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.htmlAfterTranslation).toContain(TRANSLATION_MARKER);
- expect(result.error).toBeNull();
- expect(result.unsafeTextNodesBeforeTranslation).toBe(0);
- expect(unsafeTextNodes).toBe(0);
- expect(firstTag).toBe(scenario.expectedFirstTag);
- expect(visibleText(result.htmlAfterCommit)).toBe(scenario.expectedText);
- });
- }
- });
-}
-
-describe('faithful compound pipeline', () => {
- const inlineWrap = (text: string): ReactNode => createElement('span', null, text);
- const contentsWrap = (text: string): ReactNode => createElement('flx-i18n', {style: {display: 'contents'}}, text);
-
- it('defeats a bare text sibling', () => {
- const result = commitUnderTranslation({
- before: row(badge(false), 'Hello', tail),
- after: row(badge(true), 'Hello', tail),
- pipeline: chromeFaithfulCompoundPipeline,
- });
- expect(isTranslationDomCrash(result.error)).toBe(true);
- });
-
- it('defeats an inline sole-child wrapper', () => {
- const result = commitUnderTranslation({
- before: row(badge(false), inlineWrap('Hello'), tail),
- after: row(badge(true), inlineWrap('Hello'), tail),
- pipeline: chromeFaithfulCompoundPipeline,
- });
- expect(isTranslationDomCrash(result.error)).toBe(true);
- });
-
- it('defeats the display:contents wrapper the app ships', () => {
- const result = commitUnderTranslation({
- before: row(badge(false), contentsWrap('Hello'), tail),
- after: row(badge(true), contentsWrap('Hello'), tail),
- pipeline: chromeFaithfulCompoundPipeline,
- });
- expect(isTranslationDomCrash(result.error)).toBe(true);
- });
-
- it('defeats a pure element tree that holds no text node of its own', () => {
- let reassembledChildren = false;
- const pureElementRow = (on: boolean): ReactNode =>
- row(badge(on), createElement('i', null, 'a'), createElement('em', null, 'y'));
- const result = commitUnderTranslation({
- before: pureElementRow(false),
- after: pureElementRow(true),
- pipeline: (host) => {
- const before = Array.from(host.querySelector('div')?.childNodes ?? []);
- chromeFaithfulCompoundPipeline(host);
- const after = Array.from(host.querySelector('div')?.childNodes ?? []);
- reassembledChildren = before.some((node, index) => node !== after[index]);
- },
- });
- expect(reassembledChildren).toBe(true);
- expect(result.unsafeTextNodesBeforeTranslation).toBe(0);
- expect(isTranslationDomCrash(result.error)).toBe(true);
- });
-
- it('is survived only by translate="no"', () => {
- const result = commitUnderTranslation({
- before: createElement('div', {translate: 'no'}, badge(false), contentsWrap('Hello'), tail),
- after: createElement('div', {translate: 'no'}, badge(true), contentsWrap('Hello'), tail),
- pipeline: chromeFaithfulCompoundPipeline,
- });
- expect(result.htmlAfterTranslation).toBe(result.htmlBeforeTranslation);
- expect(result.error).toBeNull();
- expect(result.htmlAfterCommit).toContain('<b>!</b>');
- expect(visibleText(result.htmlAfterCommit)).toBe('!Hellox');
- });
-});
-
-describe('shapes that were never at risk', () => {
- it('does not throw when only elements are siblings', () => {
- const result = commitUnderTranslation({
- before: row(badge(false), createElement('i', null, 'a')),
- after: row(badge(true), createElement('i', null, 'a')),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.error).toBeNull();
- });
-
- it('does not throw when a sibling is appended after the text', () => {
- const result = commitUnderTranslation({
- before: row('Hello', badge(false)),
- after: row('Hello', badge(true)),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- });
- expect(result.htmlAfterTranslation).not.toBe(result.htmlBeforeTranslation);
- expect(result.error).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/i18n/utils/TranslationDomGuard.test.ts b/fluxer_app/src/features/i18n/utils/TranslationDomGuard.test.ts
deleted file mode 100644
index 900fc2501..000000000
--- a/fluxer_app/src/features/i18n/utils/TranslationDomGuard.test.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {commitUnderTranslation, isTranslationDomCrash} from '@app/features/i18n/testing/TranslationCommitHarness';
-import {TranslatorPipelines} from '@app/features/i18n/testing/TranslatorSimulation';
-import {createElement, type ReactNode} from 'react';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-type GuardModule = typeof import('@app/features/i18n/utils/TranslationDomGuard');
-type DeveloperOptionsModule = typeof import('@app/features/devtools/state/DeveloperOptions');
-
-interface LoadedGuard {
- guard: GuardModule;
- developerOptions: DeveloperOptionsModule['default'];
-}
-
-let loaded: LoadedGuard | null = null;
-let originalInsertBefore: typeof Node.prototype.insertBefore;
-let originalRemoveChild: typeof Node.prototype.removeChild;
-
-async function loadGuard(options: {electron?: boolean; disabled?: boolean} = {}): Promise<LoadedGuard> {
- vi.resetModules();
- const {Platform} = await import('@app/features/platform/types/Platform');
- Platform.isElectron = options.electron === true;
- const developerOptions = (await import('@app/features/devtools/state/DeveloperOptions')).default;
- developerOptions.updateOption('disableTranslationDomGuard', options.disabled === true);
- const guard = await import('@app/features/i18n/utils/TranslationDomGuard');
- loaded = {guard, developerOptions};
- return loaded;
-}
-
-function translatorDisplacedText(): {container: HTMLElement; text: Text} {
- const container = document.createElement('div');
- container.setAttribute('data-flx', 'guard-fixture');
- const outer = document.createElement('font');
- const inner = document.createElement('font');
- const text = document.createTextNode('Hello');
- inner.appendChild(text);
- outer.appendChild(inner);
- container.appendChild(outer);
- document.body.appendChild(container);
- return {container, text};
-}
-
-function detachedTranslatedText(): {container: HTMLElement; text: Text} {
- const container = document.createElement('div');
- const outer = document.createElement('font');
- const inner = document.createElement('font');
- const text = document.createTextNode('Hello');
- inner.appendChild(text);
- outer.appendChild(inner);
- container.appendChild(outer);
- document.body.appendChild(container);
- document.documentElement.classList.add('translated-ltr');
- outer.replaceChildren();
- inner.replaceChildren();
- return {container, text};
-}
-
-function unrelatedSubtreeText(): {container: HTMLElement; other: HTMLElement; text: Text} {
- const container = document.createElement('div');
- const other = document.createElement('div');
- other.id = 'other';
- const font = document.createElement('font');
- const text = document.createTextNode('Hello');
- font.appendChild(text);
- other.appendChild(font);
- document.body.append(container, other);
- return {container, other, text};
-}
-
-function foreignParentText(): {container: HTMLElement; text: Text} {
- const container = document.createElement('div');
- const elsewhere = document.createElement('div');
- const text = document.createTextNode('Hello');
- elsewhere.appendChild(text);
- document.body.append(container, elsewhere);
- return {container, text};
-}
-
-const badge = (on: boolean): ReactNode => (on ? createElement('b', null, '!') : null);
-const tail = createElement('i', null, 'x');
-const unsafeRow = (on: boolean): ReactNode =>
- createElement('div', null, badge(on), 'Hello', createElement('i', null, 'x'));
-
-beforeEach(() => {
- originalInsertBefore = Node.prototype.insertBefore;
- originalRemoveChild = Node.prototype.removeChild;
-});
-
-afterEach(() => {
- loaded?.guard.uninstallTranslationDomGuard();
- loaded?.developerOptions.updateOption('disableTranslationDomGuard', false);
- loaded = null;
- Node.prototype.insertBefore = originalInsertBefore;
- Node.prototype.removeChild = originalRemoveChild;
- document.body.replaceChildren();
- document.documentElement.className = '';
- vi.restoreAllMocks();
-});
-
-describe('installation', () => {
- it('patches both prototype methods and restores them by identity on uninstall', async () => {
- const {guard} = await loadGuard();
- guard.installTranslationDomGuard();
- expect(Node.prototype.insertBefore).not.toBe(originalInsertBefore);
- expect(Node.prototype.removeChild).not.toBe(originalRemoveChild);
- expect(guard.getTranslationDomGuardStats().installed).toBe(true);
-
- guard.installTranslationDomGuard();
- expect(guard.uninstallTranslationDomGuard()).toBe(true);
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- expect(Node.prototype.removeChild).toBe(originalRemoveChild);
- expect(guard.uninstallTranslationDomGuard()).toBe(false);
- expect(guard.getTranslationDomGuardStats().installed).toBe(false);
- });
-
- it('never installs in Electron', async () => {
- const {guard} = await loadGuard({electron: true});
- guard.installTranslationDomGuard();
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- expect(guard.getTranslationDomGuardStats().installed).toBe(false);
- });
-
- it('never installs when the Electron native context is unavailable', async () => {
- vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue(
- 'Mozilla/5.0 (Macintosh) fluxer/1.0.0 Chrome/140.0.0.0 Electron/38.2.1 Safari/537.36',
- );
- const {guard} = await loadGuard({electron: false});
- guard.installTranslationDomGuard();
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- expect(Node.prototype.removeChild).toBe(originalRemoveChild);
- expect(guard.getTranslationDomGuardStats().installed).toBe(false);
- });
-
- it('never patches while the kill switch is already set', async () => {
- const {guard} = await loadGuard({disabled: true});
- guard.installTranslationDomGuard();
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- expect(guard.getTranslationDomGuardStats().installed).toBe(false);
- });
-
- it('uninstalls and reinstalls live when the kill switch is toggled', async () => {
- const {guard, developerOptions} = await loadGuard();
- guard.installTranslationDomGuard();
- expect(guard.getTranslationDomGuardStats().installed).toBe(true);
-
- developerOptions.updateOption('disableTranslationDomGuard', true);
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- expect(guard.getTranslationDomGuardStats().installed).toBe(false);
-
- developerOptions.updateOption('disableTranslationDomGuard', false);
- expect(Node.prototype.insertBefore).not.toBe(originalInsertBefore);
- expect(guard.getTranslationDomGuardStats().installed).toBe(true);
- });
-
- it('exposes stats and a live uninstall on the debug object', async () => {
- const {guard} = await loadGuard();
- guard.installTranslationDomGuard();
- const debug = window.__FLUXER_DEBUG__;
- const getStats = debug?.getTranslationDomGuardStats as
- | (() => ReturnType<GuardModule['getTranslationDomGuardStats']>)
- | undefined;
- expect(getStats?.().installed).toBe(true);
- expect(debug?.uninstallTranslationDomGuard?.()).toBe(true);
- expect(Node.prototype.insertBefore).toBe(originalInsertBefore);
- });
-});
-
-describe('reporting', () => {
- it('counts and logs every repaired insertBefore', async () => {
- const {guard} = await loadGuard();
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- const {container, text} = translatorDisplacedText();
-
- expect(() => container.insertBefore(document.createElement('b'), text)).not.toThrow();
-
- const stats = guard.getTranslationDomGuardStats();
- expect(stats.insertBefore).toBe(1);
- expect(stats.removeChild).toBe(0);
- expect(stats.declined).toBe(0);
- expect(stats.firstFireAt).not.toBeNull();
- expect(stats.lastPath).toBe('guard-fixture');
- const logged = consoleError.mock.calls.flat().join(' ');
- expect(logged).toContain('TranslationDomGuard');
- expect(logged).toContain('insertBefore');
- });
-
- it('counts and logs every repaired removeChild', async () => {
- const {guard} = await loadGuard();
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- const {container, text} = translatorDisplacedText();
-
- expect(() => container.removeChild(text)).not.toThrow();
-
- const stats = guard.getTranslationDomGuardStats();
- expect(stats.removeChild).toBe(1);
- expect(stats.insertBefore).toBe(0);
- expect(text.parentNode).toBeNull();
- expect(container.innerHTML).toBe('');
- expect(consoleError.mock.calls.flat().join(' ')).toContain('removeChild');
- });
-
- it('keeps counting after it stops logging', async () => {
- const {guard} = await loadGuard();
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- for (let attempt = 0; attempt < 5; attempt += 1) {
- const {container, text} = translatorDisplacedText();
- container.insertBefore(document.createElement('b'), text);
- }
- expect(guard.getTranslationDomGuardStats().insertBefore).toBe(5);
- expect(consoleError).toHaveBeenCalledTimes(3);
- });
-
- it('leaves calls on the original path alone', async () => {
- const {guard} = await loadGuard();
- guard.installTranslationDomGuard();
- const parent = document.createElement('div');
- const child = document.createElement('span');
- parent.appendChild(child);
- parent.insertBefore(document.createElement('b'), child);
- parent.removeChild(child);
- expect(parent.innerHTML).toBe('<b></b>');
- const stats = guard.getTranslationDomGuardStats();
- expect(stats.insertBefore).toBe(0);
- expect(stats.removeChild).toBe(0);
- expect(stats.declined).toBe(0);
- });
-
- it('declines to repair a displacement no translator caused', async () => {
- const {guard} = await loadGuard();
- guard.installTranslationDomGuard();
- const {container, text} = foreignParentText();
-
- expect(() => container.insertBefore(document.createElement('b'), text)).toThrow(
- /Failed to execute 'insertBefore' on 'Node'/,
- );
- expect(() => container.removeChild(text)).toThrow(/Failed to execute 'removeChild' on 'Node'/);
-
- const stats = guard.getTranslationDomGuardStats();
- expect(stats.insertBefore).toBe(0);
- expect(stats.removeChild).toBe(0);
- expect(stats.declined).toBe(2);
- });
-});
-
-describe('the guard behind the structural fix', () => {
- it('turns the production crash into a reported fire', async () => {
- const {guard} = await loadGuard();
- vi.spyOn(console, 'error').mockImplementation(() => {});
- const unguarded = commitUnderTranslation({
- before: unsafeRow(false),
- after: unsafeRow(true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- });
- expect(isTranslationDomCrash(unguarded.error)).toBe(true);
-
- guard.installTranslationDomGuard();
- const guarded = commitUnderTranslation({
- before: unsafeRow(false),
- after: unsafeRow(true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- });
- expect(guarded.error).toBeNull();
- expect(guard.getTranslationDomGuardStats().insertBefore).toBeGreaterThan(0);
- });
-
- it('repairs the placement at the position the translator displaced', async () => {
- const {guard} = await loadGuard();
- vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- let firstTag: string | null = null;
- const result = commitUnderTranslation({
- before: unsafeRow(false),
- after: unsafeRow(true),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- inspect: (host) => {
- firstTag = host.querySelector('div')?.firstElementChild?.tagName ?? null;
- },
- });
- expect(result.error).toBeNull();
- expect(firstTag).toBe('B');
- expect(result.htmlAfterCommit.replace(/<[^>]+>/g, '')).toBe('!~Hello~x');
- });
-
- it('leaves no empty husk behind after a repaired deletion', async () => {
- const {guard} = await loadGuard();
- vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- let html = '';
- let fontCount = -1;
- let emptyFontCount = -1;
- const result = commitUnderTranslation({
- before: createElement('div', null, 'Hello', tail),
- after: createElement('div', null, null, tail),
- pipeline: TranslatorPipelines.chromeLegacyFont,
- inspect: (host) => {
- html = host.innerHTML;
- const fonts = Array.from(host.querySelectorAll('font'));
- fontCount = fonts.length;
- emptyFontCount = fonts.filter((font) => font.childNodes.length === 0).length;
- },
- });
- expect(result.error).toBeNull();
- expect(guard.getTranslationDomGuardStats().removeChild).toBeGreaterThan(0);
- expect(html.replace(/<[^>]+>/g, '')).toBe('~x');
- expect(html).not.toContain('Hello');
- expect(emptyFontCount).toBe(0);
- expect(fontCount).toBe(2);
- });
-
- it('no-ops a removeChild of a node the translator already detached', async () => {
- const {guard} = await loadGuard();
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- const {container, text} = detachedTranslatedText();
- expect(text.parentNode).toBeNull();
-
- expect(container.removeChild(text)).toBe(text);
-
- expect(text.parentNode).toBeNull();
- expect(guard.getTranslationDomGuardStats().removeChild).toBe(1);
- expect(consoleError.mock.calls.flat().join(' ')).toContain('removeChild');
- });
-
- it('does not unwind husks outside the container the removal was addressed to', async () => {
- const {guard} = await loadGuard();
- vi.spyOn(console, 'error').mockImplementation(() => {});
- guard.installTranslationDomGuard();
- const {container, other, text} = unrelatedSubtreeText();
-
- expect(container.removeChild(text)).toBe(text);
-
- expect(text.parentNode).toBeNull();
- expect(other.parentNode).toBe(document.body);
- expect(document.getElementById('other')).toBe(other);
- expect(other.innerHTML).toBe('<font></font>');
- expect(guard.getTranslationDomGuardStats().removeChild).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/input/components/KeybindRecorderCapture.test.ts b/fluxer_app/src/features/input/components/KeybindRecorderCapture.test.ts
deleted file mode 100644
index 33499c0c5..000000000
--- a/fluxer_app/src/features/input/components/KeybindRecorderCapture.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- beginGlobalKeyCapture,
- type GlobalKeyCaptureApi,
- globalKeyEventToCombo,
- isGlobalKeyEventModifierKey,
-} from '@app/features/input/components/KeybindRecorderCapture';
-import type {GlobalKeyEvent} from '@app/features/platform/types/Electron';
-import {describe, expect, it} from 'vitest';
-
-const keyEvent = (event: Partial<GlobalKeyEvent>): GlobalKeyEvent => ({
- type: 'keydown',
- keycode: 0,
- keyName: 'A',
- backend: 'native',
- altKey: false,
- ctrlKey: false,
- shiftKey: false,
- metaKey: false,
- ...event,
-});
-
-describe('globalKeyEventToCombo', () => {
- it('records Caps Lock from native global key events', () => {
- expect(globalKeyEventToCombo(keyEvent({keyName: 'CapsLock'}))).toMatchObject({
- key: 'CapsLock',
- code: 'CapsLock',
- });
- });
-
- it('normalizes spaced Caps Lock aliases from platform hooks', () => {
- expect(globalKeyEventToCombo(keyEvent({keyName: 'Caps Lock'}))).toMatchObject({
- key: 'CapsLock',
- code: 'CapsLock',
- });
- });
-
- it('records letters with physical DOM-style codes', () => {
- expect(globalKeyEventToCombo(keyEvent({keyName: 'A'}))).toMatchObject({
- key: 'a',
- code: 'KeyA',
- });
- expect(globalKeyEventToCombo(keyEvent({keyName: 'A', shiftKey: true}))).toMatchObject({
- key: 'A',
- code: 'KeyA',
- shift: true,
- });
- });
-
- it('recognizes side-specific native modifier names', () => {
- expect(isGlobalKeyEventModifierKey(keyEvent({keyName: 'ShiftRight'}))).toBe(true);
- expect(
- globalKeyEventToCombo(keyEvent({keyName: 'ShiftRight', shiftKey: true}), {modifierOnly: true}),
- ).toMatchObject({
- key: 'Shift',
- code: 'ShiftRight',
- shift: true,
- modifierOnly: true,
- });
- });
-});
-
-const flushMicrotasks = async (): Promise<void> => {
- await Promise.resolve();
- await Promise.resolve();
-};
-
-interface CaptureApiHarness {
- api: GlobalKeyCaptureApi;
- calls: Array<string>;
- listeners: Array<(event: GlobalKeyEvent) => void>;
- resolveStart: (started: boolean) => void;
- rejectStart: (error: Error) => void;
-}
-
-const createCaptureApi = (): CaptureApiHarness => {
- const calls: Array<string> = [];
- const listeners: Array<(event: GlobalKeyEvent) => void> = [];
- let resolveStart: (started: boolean) => void = () => {};
- let rejectStart: (error: Error) => void = () => {};
- const api: GlobalKeyCaptureApi = {
- globalKeyHookStart: () => {
- calls.push('start');
- return new Promise<boolean>((resolve, reject) => {
- resolveStart = resolve;
- rejectStart = reject;
- });
- },
- globalKeyHookStop: () => {
- calls.push('stop');
- return Promise.resolve();
- },
- onGlobalKeyEvent: (callback) => {
- listeners.push(callback);
- return () => {
- const index = listeners.indexOf(callback);
- if (index !== -1) listeners.splice(index, 1);
- };
- },
- };
- return {
- api,
- calls,
- listeners,
- resolveStart: (started) => resolveStart(started),
- rejectStart: (error) => rejectStart(error),
- };
-};
-
-describe('beginGlobalKeyCapture', () => {
- it('subscribes, starts the hook, and pairs cancel with exactly one stop', async () => {
- const harness = createCaptureApi();
- const events: Array<GlobalKeyEvent> = [];
- const cancel = beginGlobalKeyCapture(harness.api, (event) => events.push(event));
- expect(harness.listeners).toHaveLength(1);
- harness.resolveStart(true);
- await flushMicrotasks();
- harness.listeners[0]?.(keyEvent({keyName: 'CapsLock'}));
- expect(events).toHaveLength(1);
- cancel();
- cancel();
- await flushMicrotasks();
- expect(harness.listeners).toHaveLength(0);
- expect(harness.calls).toEqual(['start', 'stop']);
- });
-
- it('never stops the hook when the start was rejected or unsuccessful', async () => {
- const failed = createCaptureApi();
- const cancelFailed = beginGlobalKeyCapture(failed.api, () => {});
- failed.resolveStart(false);
- await flushMicrotasks();
- expect(failed.listeners).toHaveLength(0);
- cancelFailed();
- await flushMicrotasks();
- expect(failed.calls).toEqual(['start']);
-
- const thrown = createCaptureApi();
- const cancelThrown = beginGlobalKeyCapture(thrown.api, () => {});
- thrown.rejectStart(new Error('denied'));
- await flushMicrotasks();
- expect(thrown.listeners).toHaveLength(0);
- cancelThrown();
- await flushMicrotasks();
- expect(thrown.calls).toEqual(['start']);
- });
-
- it('stops the hook after a late start resolution when cancelled early', async () => {
- const harness = createCaptureApi();
- const cancel = beginGlobalKeyCapture(harness.api, () => {});
- cancel();
- expect(harness.listeners).toHaveLength(0);
- harness.resolveStart(true);
- await flushMicrotasks();
- expect(harness.calls).toEqual(['start', 'stop']);
- });
-
- it('is a no-op without a complete capture api', () => {
- expect(beginGlobalKeyCapture(null, () => {})).toBeTypeOf('function');
- expect(beginGlobalKeyCapture({}, () => {})).toBeTypeOf('function');
- beginGlobalKeyCapture(null, () => {})();
- beginGlobalKeyCapture({}, () => {})();
- });
-});
diff --git a/fluxer_app/src/features/input/state/KeybindResolution.test.ts b/fluxer_app/src/features/input/state/KeybindResolution.test.ts
deleted file mode 100644
index e31066f1a..000000000
--- a/fluxer_app/src/features/input/state/KeybindResolution.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {CustomKeybindEntry, KeybindCommand, KeybindConfig, KeyCombo} from '@app/features/input/state/InputKeybind';
-import {
- getActiveCombosForResolvedAction,
- getDisplayKeybindForResolvedAction,
-} from '@app/features/input/state/KeybindResolution';
-import {describe, expect, it} from 'vitest';
-
-const action: KeybindCommand = 'voice_toggle_deafen';
-const keybind = (combo: KeyCombo, overrides: Partial<KeybindConfig> = {}): KeybindConfig => ({
- action,
- label: 'Deafen',
- combo,
- section: 'voice_and_video',
- ...overrides,
-});
-const custom = (combo: KeyCombo, enabled: boolean): CustomKeybindEntry => ({
- id: 'custom-1',
- action,
- combo,
- enabled,
-});
-
-describe('keybind action resolution', () => {
- it('uses the default combo when there is no custom override', () => {
- const base = keybind({key: 'd', ctrlOrMeta: true, shift: true});
- expect(getActiveCombosForResolvedAction(base, [])).toEqual([base.combo]);
- expect(getDisplayKeybindForResolvedAction(base, []).combo).toEqual(base.combo);
- });
- it('suppresses the default combo when an override is disabled and empty', () => {
- const base = keybind({key: 'd', ctrlOrMeta: true, shift: true});
- const bindings = [custom({key: ''}, false)];
- expect(getActiveCombosForResolvedAction(base, bindings)).toEqual([]);
- expect(getDisplayKeybindForResolvedAction(base, bindings).combo).toEqual({key: ''});
- });
- it('suppresses the default combo when an override is enabled but empty', () => {
- const base = keybind({key: 'd', ctrlOrMeta: true, shift: true});
- const bindings = [custom({key: ''}, true)];
- expect(getActiveCombosForResolvedAction(base, bindings)).toEqual([]);
- expect(getDisplayKeybindForResolvedAction(base, bindings).combo).toEqual({key: ''});
- });
- it('uses enabled custom combos instead of the default combo', () => {
- const base = keybind({key: 'd', ctrlOrMeta: true, shift: true});
- const override = custom({key: 'm', ctrlOrMeta: true}, true);
- expect(getActiveCombosForResolvedAction(base, [override])).toEqual([override.combo]);
- expect(getDisplayKeybindForResolvedAction(base, [override]).combo).toEqual(override.combo);
- });
-});
diff --git a/fluxer_app/src/features/input/utils/KeyboardShortcutLayoutUtils.test.ts b/fluxer_app/src/features/input/utils/KeyboardShortcutLayoutUtils.test.ts
deleted file mode 100644
index 34d3644ff..000000000
--- a/fluxer_app/src/features/input/utils/KeyboardShortcutLayoutUtils.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- DEFAULT_KEYBOARD_SHORTCUTS_OVERLAY_COMBO,
- getKeyboardShortcutsOverlayComboForLayoutMap,
- type KeyboardLayoutMapReader,
- keyboardLayoutHasDirectSlashKey,
- SHIFTED_SLASH_FALLBACK_KEYBOARD_SHORTCUTS_OVERLAY_COMBO,
- shouldUseKeyboardShortcutsOverlayFallbackFromEvent,
-} from '@app/features/input/utils/KeyboardShortcutLayoutUtils';
-import {describe, expect, it} from 'vitest';
-
-const layoutMap = (entries: Array<[string, string]>): KeyboardLayoutMapReader => {
- const map = new Map(entries);
- return {
- get: (code) => map.get(code),
- };
-};
-
-describe('KeyboardShortcutLayoutUtils', () => {
- it('keeps Ctrl/Cmd+/ when the keyboard layout has a direct slash key', () => {
- const usLayout = layoutMap([
- ['Slash', '/'],
- ['Digit7', '7'],
- ]);
-
- expect(keyboardLayoutHasDirectSlashKey(usLayout)).toBe(true);
- expect(getKeyboardShortcutsOverlayComboForLayoutMap(usLayout)).toEqual(DEFAULT_KEYBOARD_SHORTCUTS_OVERLAY_COMBO);
- });
-
- it('uses Ctrl/Cmd+. when slash is only available through a shifted layout key', () => {
- const swedishLayout = layoutMap([
- ['Slash', '-'],
- ['Digit7', '7'],
- ['NumpadDivide', '/'],
- ]);
-
- expect(keyboardLayoutHasDirectSlashKey(swedishLayout)).toBe(false);
- expect(getKeyboardShortcutsOverlayComboForLayoutMap(swedishLayout)).toEqual(
- SHIFTED_SLASH_FALLBACK_KEYBOARD_SHORTCUTS_OVERLAY_COMBO,
- );
- });
-
- it('detects shifted slash events from numbered keyboard layouts', () => {
- expect(shouldUseKeyboardShortcutsOverlayFallbackFromEvent({key: '/', code: 'Digit7', shiftKey: true})).toBe(true);
- expect(shouldUseKeyboardShortcutsOverlayFallbackFromEvent({key: '/', code: 'Slash', shiftKey: false})).toBe(false);
- expect(shouldUseKeyboardShortcutsOverlayFallbackFromEvent({key: '/', code: 'NumpadDivide', shiftKey: false})).toBe(
- false,
- );
- });
-});
diff --git a/fluxer_app/src/features/input/utils/KeyboardUtils.test.ts b/fluxer_app/src/features/input/utils/KeyboardUtils.test.ts
deleted file mode 100644
index b6f1783c0..000000000
--- a/fluxer_app/src/features/input/utils/KeyboardUtils.test.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isKeyboardActivationKey} from '@app/features/input/utils/KeyboardUtils';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-describe('KeyboardUtils', () => {
- it('recognizes common keyboard activation key values', () => {
- expect(isKeyboardActivationKey('Enter')).toBe(true);
- expect(isKeyboardActivationKey(' ')).toBe(true);
- expect(isKeyboardActivationKey('Space')).toBe(true);
- expect(isKeyboardActivationKey('Spacebar')).toBe(true);
- expect(isKeyboardActivationKey('ArrowDown')).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerBlockquote.test.ts b/fluxer_app/src/features/lexical/composer/ComposerBlockquote.test.ts
deleted file mode 100644
index 48c04cec3..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerBlockquote.test.ts
+++ /dev/null
@@ -1,2448 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {BlockquoteLine} from '@app/features/lexical/composer/blockquoteLines';
-import {registerComposerBlockquote} from '@app/features/lexical/composer/ComposerBlockquote';
-import {
- $getComposerClipboardSelection,
- $insertComposerClipboardSlice,
- $insertComposerPastedText,
- COMPOSER_CLIPBOARD_MAX_TRUSTED_PAYLOADS,
- FLUXER_COMPOSER_CLIPBOARD_MIME,
- parseComposerClipboardSlice,
- registerComposerClipboardCommands,
-} from '@app/features/lexical/composer/ComposerClipboard';
-import {registerComposerCodeIndent} from '@app/features/lexical/composer/ComposerCodeIndent';
-import {registerComposerEmojiShortcode} from '@app/features/lexical/composer/ComposerEmojiShortcode';
-import type {ComposerHandle} from '@app/features/lexical/composer/ComposerHandle';
-import {registerComposerMarkdownHighlight} from '@app/features/lexical/composer/ComposerMarkdownHighlight';
-import {registerComposerMarkdownShortcuts} from '@app/features/lexical/composer/ComposerMarkdownShortcuts';
-import {$hydrateComposerFromDraft, $projectComposer} from '@app/features/lexical/composer/ComposerSerialization';
-import {registerComposerSoftWrapDeletion} from '@app/features/lexical/composer/ComposerSoftWrapDeletion';
-import {
- $getComposerBlockquoteState,
- $queryComposerSelectionWrappers,
- $selectComposerRange,
- $wrapComposerSelection,
-} from '@app/features/lexical/composer/composerOffsets';
-import {DEFAULT_COMPOSER_MARKDOWN_FLAGS} from '@app/features/lexical/composer/markdownSpans';
-import {
- $isComposerBlockquoteLineNode,
- ComposerBlockquoteLineNode,
-} from '@app/features/lexical/composer/nodes/ComposerBlockquoteLineNode';
-import {
- $isComposerBlockquoteMarkerNode,
- ComposerBlockquoteMarkerNode,
-} from '@app/features/lexical/composer/nodes/ComposerBlockquoteMarkerNode';
-import {ComposerCommandNode} from '@app/features/lexical/composer/nodes/ComposerCommandNode';
-import {
- $isComposerCustomEmojiNode,
- ComposerCustomEmojiNode,
-} from '@app/features/lexical/composer/nodes/ComposerCustomEmojiNode';
-import {$isComposerMentionNode, ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {ComposerPlainSegmentNode} from '@app/features/lexical/composer/nodes/ComposerPlainSegmentNode';
-import {
- $isComposerStandardEmojiNode,
- ComposerStandardEmojiNode,
-} from '@app/features/lexical/composer/nodes/ComposerStandardEmojiNode';
-import {SlashOptionalHintNode} from '@app/features/lexical/composer/nodes/SlashOptionalHintNode';
-import {SlashSeparatorNode} from '@app/features/lexical/composer/nodes/SlashSeparatorNode';
-import {SlashSlotNode} from '@app/features/lexical/composer/nodes/SlashSlotNode';
-import {SlashSlotPlaceholderNode} from '@app/features/lexical/composer/nodes/SlashSlotPlaceholderNode';
-import {$createSyntaxMarkerNode, SyntaxMarkerNode} from '@app/features/lexical/composer/nodes/SyntaxMarkerNode';
-import {ParserFlags} from '@app/features/messaging/utils/markdown/parser/Enums';
-import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
-import type {ResolvedTypedEmoji} from '@app/features/messaging/utils/TypedEmojiShortcodeUtils';
-import {createEmptyHistoryState, registerHistory} from '@lexical/history';
-import {
- $createParagraphNode,
- $getNodeByKey,
- $getRoot,
- $getSelection,
- $isElementNode,
- $isLineBreakNode,
- $isRangeSelection,
- $isTextNode,
- $setCompositionKey,
- COMMAND_PRIORITY_EDITOR,
- COMMAND_PRIORITY_HIGH,
- COMPOSITION_START_COMMAND,
- CONTROLLED_TEXT_INSERTION_COMMAND,
- COPY_COMMAND,
- createEditor,
- DELETE_CHARACTER_COMMAND,
- DELETE_LINE_COMMAND,
- DELETE_WORD_COMMAND,
- DRAGSTART_COMMAND,
- DROP_COMMAND,
- HISTORY_MERGE_TAG,
- INSERT_LINE_BREAK_COMMAND,
- INSERT_PARAGRAPH_COMMAND,
- KEY_ARROW_LEFT_COMMAND,
- KEY_ARROW_RIGHT_COMMAND,
- KEY_DOWN_COMMAND,
- KEY_TAB_COMMAND,
- type LexicalCommand,
- type LexicalEditor,
- PASTE_COMMAND,
- REDO_COMMAND,
- SELECTION_CHANGE_COMMAND,
- UNDO_COMMAND,
-} from 'lexical';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/SlashOptionalHintPill', () => ({SlashOptionalHintPill: () => null}));
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-const platform = vi.hoisted(() => ({apple: false}));
-const dropOffset = vi.hoisted(() => ({value: null as number | null}));
-
-vi.mock('lexical', async (importOriginal) => {
- const actual = await importOriginal<typeof import('lexical')>();
- return {
- ...actual,
- get IS_APPLE() {
- return platform.apple;
- },
- };
-});
-
-vi.mock('@app/features/lexical/composer/composerOffsets', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@app/features/lexical/composer/composerOffsets')>();
- return {...actual, $getComposerDropOffset: () => dropOffset.value};
-});
-
-const NODES = [
- ComposerMentionNode,
- ComposerCustomEmojiNode,
- ComposerStandardEmojiNode,
- ComposerPlainSegmentNode,
- ComposerCommandNode,
- SlashSlotNode,
- SlashSlotPlaceholderNode,
- SlashSeparatorNode,
- SlashOptionalHintNode,
- SyntaxMarkerNode,
- ComposerBlockquoteLineNode,
- ComposerBlockquoteMarkerNode,
-];
-
-const NO_BLOCKQUOTE_FLAGS =
- DEFAULT_COMPOSER_MARKDOWN_FLAGS & ~(ParserFlags.ALLOW_BLOCKQUOTES | ParserFlags.ALLOW_MULTILINE_BLOCKQUOTES);
-const NO_MULTILINE_FLAGS = DEFAULT_COMPOSER_MARKDOWN_FLAGS & ~ParserFlags.ALLOW_MULTILINE_BLOCKQUOTES;
-const BIO_LIKE_FLAGS =
- DEFAULT_COMPOSER_MARKDOWN_FLAGS &
- ~(
- ParserFlags.ALLOW_HEADINGS |
- ParserFlags.ALLOW_CODE_BLOCKS |
- ParserFlags.ALLOW_ROLE_MENTIONS |
- ParserFlags.ALLOW_EVERYONE_MENTIONS |
- ParserFlags.ALLOW_SUBTEXT |
- ParserFlags.ALLOW_TABLES |
- ParserFlags.ALLOW_ALERTS
- );
-
-const COMPOSITION_EVENT = {timeStamp: Number.MAX_SAFE_INTEGER, data: ''} as unknown as CompositionEvent;
-
-const GRINNING: ResolvedTypedEmoji = {
- kind: 'standard',
- name: 'grinning',
- surrogate: '😀',
- url: null,
- display: ':grinning:',
-};
-
-function parserFlagsHandle(flags: number): ComposerHandle {
- return {getMarkdownParserFlags: () => flags} as unknown as ComposerHandle;
-}
-
-const RTL_ELEMENT = {
- ownerDocument: {defaultView: {getComputedStyle: () => ({direction: 'rtl'})}},
-} as unknown as HTMLElement;
-
-const disposers: Array<() => void> = [];
-
-afterEach(() => {
- while (disposers.length > 0) {
- disposers.pop()!();
- }
- platform.apple = false;
- dropOffset.value = null;
- vi.unstubAllGlobals();
-});
-
-function createBareEditor(): LexicalEditor {
- return createEditor({
- namespace: 'composer-blockquote-test',
- nodes: NODES,
- onError: (error) => {
- throw error;
- },
- });
-}
-
-function registerPlainTextFallbacks(editor: LexicalEditor): void {
- disposers.push(
- editor.registerCommand(
- INSERT_LINE_BREAK_COMMAND,
- (selectStart) => {
- const selection = $getSelection();
- if (!$isRangeSelection(selection)) {
- return false;
- }
- selection.insertLineBreak(selectStart);
- return true;
- },
- COMMAND_PRIORITY_EDITOR,
- ),
- editor.registerCommand(
- CONTROLLED_TEXT_INSERTION_COMMAND,
- (payload) => {
- const selection = $getSelection();
- if (!$isRangeSelection(selection) || typeof payload !== 'string') {
- return false;
- }
- selection.insertText(payload);
- return true;
- },
- COMMAND_PRIORITY_EDITOR,
- ),
- );
-}
-
-function createHarness(options: {flags?: number; history?: boolean; maxWireLength?: number} = {}): LexicalEditor {
- const editor = createBareEditor();
- disposers.push(
- registerComposerMarkdownHighlight(editor, options.flags, false, options.maxWireLength),
- registerComposerBlockquote(editor, options.flags),
- );
- registerPlainTextFallbacks(editor);
- if (options.history === true) {
- disposers.push(registerHistory(editor, createEmptyHistoryState(), 0));
- }
- return editor;
-}
-
-function createFormattingHarness(flags = DEFAULT_COMPOSER_MARKDOWN_FLAGS): LexicalEditor {
- const editor = createHarness({flags});
- disposers.push(
- registerComposerMarkdownShortcuts(editor),
- registerComposerCodeIndent(editor, {current: false}),
- registerComposerClipboardCommands(editor, {
- getPlainText: () => false,
- isEditable: () => true,
- getMarkdownParserFlags: () => flags,
- }),
- );
- return editor;
-}
-
-function update(editor: LexicalEditor, fn: () => void): void {
- editor.update(fn, {discrete: true});
-}
-
-function setComposer(
- editor: LexicalEditor,
- text: string,
- anchor?: number,
- focus?: number,
- segments: ReadonlyArray<MentionSegment> = [],
-): void {
- update(editor, () => {
- $hydrateComposerFromDraft(text, segments);
- if (anchor != null) {
- $selectComposerRange(anchor, focus == null ? anchor : focus);
- }
- });
-}
-
-function select(editor: LexicalEditor, anchor: number, focus = anchor): void {
- update(editor, () => {
- $selectComposerRange(anchor, focus);
- });
-}
-
-function type(editor: LexicalEditor, text: string): void {
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertText(text);
- }
- });
-}
-
-function run<T>(editor: LexicalEditor, command: LexicalCommand<T>, payload: T): boolean {
- let handled = false;
- update(editor, () => {
- handled = editor.dispatchCommand(command, payload);
- });
- return handled;
-}
-
-function historyStep(editor: LexicalEditor, command: typeof UNDO_COMMAND | typeof REDO_COMMAND): void {
- editor.dispatchCommand(command, undefined);
- update(editor, () => {});
-}
-
-interface Snapshot {
- wire: string;
- selection: {anchor: number; focus: number} | null;
- lines: Array<BlockquoteLine>;
- wrappers: number;
- markers: Array<string>;
- breaksInsideWrappers: number;
- hasSelection: boolean;
-}
-
-function snapshot(editor: LexicalEditor): Snapshot {
- return editor.getEditorState().read(
- () => {
- const state = $getComposerBlockquoteState();
- const paragraph = $getRoot().getFirstChild();
- const children = $isElementNode(paragraph) ? paragraph.getChildren() : [];
- const wrappers = children.filter($isComposerBlockquoteLineNode);
- return {
- wire: $projectComposer().wire,
- selection: state.selection,
- lines: state.lines,
- wrappers: wrappers.length,
- markers: wrappers.map((wrapper) => {
- const first = wrapper.getFirstChild();
- return $isComposerBlockquoteMarkerNode(first) ? first.getTextContent() : '<none>';
- }),
- breaksInsideWrappers: wrappers.reduce(
- (count, wrapper) => count + wrapper.getChildren().filter($isLineBreakNode).length,
- 0,
- ),
- hasSelection: $getSelection() !== null,
- };
- },
- {editor},
- );
-}
-
-function expectedQuoteLines(text: string): number {
- return text.split('\n').filter((line) => /^[ \t]*> /.test(line)).length;
-}
-
-function caretInsideMarker(state: Snapshot): boolean {
- const caret = state.selection == null ? null : state.selection.anchor;
- return caret != null && state.lines.some((line) => line.start <= caret && caret < line.contentStart);
-}
-
-function keyEvent(overrides: Record<string, unknown> = {}): KeyboardEvent & {preventDefault: ReturnType<typeof vi.fn>} {
- return {
- key: 'ArrowLeft',
- keyCode: 37,
- shiftKey: false,
- altKey: false,
- ctrlKey: false,
- metaKey: false,
- isComposing: false,
- preventDefault: vi.fn(),
- ...overrides,
- } as unknown as KeyboardEvent & {preventDefault: ReturnType<typeof vi.fn>};
-}
-
-function compositionKey(editor: LexicalEditor): string | null {
- return (editor as unknown as {_compositionKey: string | null})._compositionKey;
-}
-
-function selectFirstMarkerText(editor: LexicalEditor, offset: number): string {
- let key = '';
- update(editor, () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- const marker = $isComposerBlockquoteLineNode(wrapper) ? wrapper.getFirstChild() : null;
- if (!$isComposerBlockquoteMarkerNode(marker)) {
- throw new Error('expected a quote marker');
- }
- marker.select(offset, offset);
- key = marker.getKey();
- });
- return key;
-}
-
-describe('blockquote line splits', () => {
- it('moves the whole content down when the caret is at content start', () => {
- const editor = createHarness();
- setComposer(editor, '> test', 2);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: '> \n> test',
- selection: {anchor: 5, focus: 5},
- wrappers: 2,
- breaksInsideWrappers: 0,
- });
- });
-
- it('moves the tail to the new quote line when the caret is mid line', () => {
- const editor = createHarness();
- setComposer(editor, '> test', 4);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: '> te\n> st',
- selection: {anchor: 7, focus: 7},
- wrappers: 2,
- breaksInsideWrappers: 0,
- });
- });
-
- it('keeps text order when insertLineBreak runs over a range inside a quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 3, 5);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertLineBreak();
- }
- });
- expect(snapshot(editor)).toMatchObject({wire: '> a\nd', wrappers: 1, breaksInsideWrappers: 0});
- });
-
- it('declines a range selection and falls back to a plain break in order', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 3, 5);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '> a\nd', wrappers: 1, breaksInsideWrappers: 0});
- });
-
- it('keeps text order when raw text with a newline is inserted mid quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertRawText('x\ny');
- }
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> abx\nycd',
- wrappers: 1,
- breaksInsideWrappers: 0,
- selection: {anchor: 7, focus: 7},
- });
- });
-
- it('continues the quote when a clipboard slice with a newline lands mid quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- update(editor, () => {
- $insertComposerClipboardSlice({display: 'x\ny', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> abx\n> ycd',
- wrappers: 2,
- breaksInsideWrappers: 0,
- selection: {anchor: 9, focus: 9},
- });
- });
-
- it('leaves the tail on the first line when insertNewAfter returns null', () => {
- const spy = vi
- .spyOn(ComposerBlockquoteLineNode.prototype, 'insertNewAfter')
- .mockImplementation(() => null as unknown as ComposerBlockquoteLineNode);
- try {
- const editor = createHarness();
- setComposer(editor, '> test', 4);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('> test\n> ');
- } finally {
- spy.mockRestore();
- }
- });
-});
-
-describe('blockquote paste', () => {
- function pasteEvent(text: string): {clipboardData: DataTransfer; preventDefault: ReturnType<typeof vi.fn>} {
- return {
- clipboardData: {getData: (type: string) => (type === 'text/plain' ? text : '')} as unknown as DataTransfer,
- preventDefault: vi.fn(),
- };
- }
-
- function paste(editor: LexicalEditor, text: string): {handled: boolean; prevented: boolean} {
- const event = pasteEvent(text);
- const handled = run(editor, PASTE_COMMAND, event as unknown as ClipboardEvent);
- return {handled, prevented: event.preventDefault.mock.calls.length > 0};
- }
-
- function createRawPasteHarness(): LexicalEditor {
- const editor = createHarness();
- disposers.push(
- editor.registerCommand(
- PASTE_COMMAND,
- (event) => {
- const selection = $getSelection();
- const data = (event as ClipboardEvent).clipboardData;
- if (!$isRangeSelection(selection) || data == null) {
- return false;
- }
- selection.insertRawText(data.getData('text/plain'));
- return true;
- },
- COMMAND_PRIORITY_EDITOR,
- ),
- );
- return editor;
- }
-
- const PASTE_ROWS: Array<[string, number, number, string, string, number]> = [
- ['> abcd', 4, 4, 'x\ny', '> abx\n> ycd', 9],
- ['> abcd', 2, 2, 'x\ny', '> x\n> yabcd', 7],
- ['> ', 2, 2, 'x\ny', '> x\n> y', 7],
- [' > a', 5, 5, 'x\ny', ' > ax\n> y', 10],
- ['> abcd', 4, 4, 'x\n\ny', '> abx\n> \n> ycd', 12],
- ['> abcd', 6, 6, '\n', '> abcd\n> ', 9],
- ['> a\n> ', 6, 6, '\n', '> a\n> \n> ', 9],
- ['> abcd', 6, 6, 'x\r\ny', '> abcdx\n> y', 11],
- ['> ab\n> cd', 3, 8, 'x\ny', '> ax\n> yd', 8],
- ['> ', 2, 2, '> x\n> y', '> x\n> y', 7],
- ['> ', 2, 2, '> x', '> x', 3],
- ['x\n> ', 4, 4, ' > a\r\n> b', 'x\n> a\n> b', 9],
- ['> ab', 2, 2, '> x', '> xab', 3],
- ['> ab', 2, 4, '> x\n> y', '> x\n> y', 7],
- ];
-
- it.each(
- PASTE_ROWS,
- )('on %j at %i..%i pasting %j gives %j with the caret at %i', (text, anchor, focus, pasted, wire, caret) => {
- const editor = createHarness();
- setComposer(editor, text, anchor, focus);
- expect(paste(editor, pasted)).toEqual({handled: true, prevented: true});
- expect(snapshot(editor)).toMatchObject({
- wire,
- selection: {anchor: caret, focus: caret},
- wrappers: expectedQuoteLines(wire),
- breaksInsideWrappers: 0,
- });
- });
-
- const DECLINE_ROWS: Array<[string, number, number, string]> = [
- ['abcd', 2, 2, 'x\ny'],
- ['> abcd', 4, 4, 'xy'],
- ['```\n> a', 7, 7, 'x\ny'],
- ['> ab', 4, 4, 'x\n> y'],
- ['> ```', 5, 5, 'x\ny'],
- ['> ab', 4, 4, '> x'],
- ['> ', 2, 2, 'x'],
- ];
-
- it.each(DECLINE_ROWS)('declines %j at %i..%i pasting %j', (text, anchor, focus, pasted) => {
- const editor = createHarness();
- setComposer(editor, text, anchor, focus);
- expect(paste(editor, pasted)).toEqual({handled: false, prevented: false});
- expect(snapshot(editor).wire).toBe(text);
- });
-
- it('declines a paste inside a quote line without ALLOW_BLOCKQUOTES', () => {
- const editor = createHarness({flags: NO_BLOCKQUOTE_FLAGS});
- setComposer(editor, '> abcd', 4);
- expect(paste(editor, 'x\ny')).toEqual({handled: false, prevented: false});
- expect(snapshot(editor)).toMatchObject({wire: '> abcd', wrappers: 0});
- });
-
- it('plans a paste below a quoted fence with the flags the handler was registered with', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```', 5);
- expect(paste(editor, 'x\ny')).toEqual({handled: true, prevented: true});
- expect(snapshot(editor)).toMatchObject({
- wire: '> ```x\n> y',
- selection: {anchor: 10, focus: 10},
- wrappers: 2,
- });
- });
-
- const BARE_PREFIX_ROWS: Array<[string, number, number, string, string, number]> = [
- ['> ', 2, 2, '> ', '> ', 2],
- ['> ab', 2, 4, '> ', '> ', 2],
- [' > ab', 4, 6, ' > ', ' > ', 4],
- ['> ab', 2, 4, '\t> ', '> ', 2],
- ];
-
- it.each(
- BARE_PREFIX_ROWS,
- )('on %j at %i..%i pasting the bare prefix %j gives %j with the caret at %i', (text, anchor, focus, pasted, wire, caret) => {
- const editor = createHarness();
- setComposer(editor, text, anchor, focus);
- expect(paste(editor, pasted)).toEqual({handled: true, prevented: true});
- expect(snapshot(editor)).toMatchObject({
- wire,
- selection: {anchor: caret, focus: caret},
- wrappers: expectedQuoteLines(wire),
- });
- });
-
- it.each<[string, number, number, string, number]>([
- ['> ', 2, 2, '> ', 2],
- ['> ab', 2, 4, '> ', 2],
- ])('inserts a bare prefix slice over %j at %i..%i, giving %j with the caret at %i', (text, anchor, focus, wire, caret) => {
- const editor = createHarness();
- setComposer(editor, text, anchor, focus);
- let inserted = false;
- update(editor, () => {
- inserted = $insertComposerClipboardSlice({display: '> ', segments: []}, false);
- });
- expect(inserted).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire, selection: {anchor: caret, focus: caret}, wrappers: 1});
- });
-
- it('removes the selected range when a dropped bare prefix plans to nothing', () => {
- const editor = createHarness();
- setComposer(editor, '> ab', 2, 4);
- const payload = {dataTransfer: {getData: () => '> '}} as unknown as InputEvent;
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, payload)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ', selection: {anchor: 2, focus: 2}, wrappers: 1});
- });
-
- it('keeps every line quoted when multi-line text is inserted at the cursor inside a quote', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- let inserted = false;
- update(editor, () => {
- inserted = $insertComposerClipboardSlice({display: 'x\ny\nz', segments: []}, false);
- });
- expect(inserted).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: '> abx\n> y\n> zcd',
- selection: {anchor: 13, focus: 13},
- wrappers: 3,
- });
- });
-
- it.each<[string, number, string, string, number]>([
- ['> ab', 4, 'x\n> y', '> abx\n> y', 9],
- ['> ```', 5, 'x\ny', '> ```x\ny', 8],
- ['> ab', 4, '> x', '> ab> x', 7],
- ])('leaves %j at %i pasting %j to lexical, giving %j and the caret at %i', (text, caret, pasted, wire, after) => {
- const editor = createRawPasteHarness();
- setComposer(editor, text, caret);
- expect(paste(editor, pasted)).toEqual({handled: true, prevented: false});
- expect(snapshot(editor)).toMatchObject({
- wire,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(wire),
- });
- });
-
- it('continues the quote when text is dropped on a quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- const payload = {dataTransfer: {getData: () => 'x\ny'}} as unknown as InputEvent;
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, payload)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: '> abx\n> ycd',
- selection: {anchor: 9, focus: 9},
- wrappers: 2,
- });
- });
-
- it('merges a dropped quote line into an empty quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- const payload = {dataTransfer: {getData: () => '> x'}} as unknown as InputEvent;
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, payload)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> x', selection: {anchor: 3, focus: 3}, wrappers: 1});
- });
-
- it('drops the quote prefix of the first slice line at a quote content start and shifts its mention', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start: 2,
- end: 7,
- };
- update(editor, () => {
- $insertComposerClipboardSlice({display: '> @name\n> b', segments: [segment]}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> <@1>\n> b', selection: {anchor: 11, focus: 11}, wrappers: 2});
- expect(editor.getEditorState().read(() => $projectComposer(), {editor}).segments).toMatchObject([
- {start: 2, end: 7},
- ]);
- });
-
- it('deletes forward from the quote content start a pasted trailing newline leaves the caret at', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- expect(paste(editor, 'x\n').handled).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> abx\n> cd', selection: {anchor: 8, focus: 8}});
- expect(run(editor, DELETE_CHARACTER_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> abx\n> d', selection: {anchor: 8, focus: 8}, wrappers: 2});
- });
-
- it('declines a paste and a drop while composing', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- update(editor, () => {
- $setCompositionKey($getRoot().getAllTextNodes()[1]!.getKey());
- });
- expect(editor.isComposing()).toBe(true);
- expect(paste(editor, 'x\ny')).toEqual({handled: false, prevented: false});
- const payload = {dataTransfer: {getData: () => 'x\ny'}} as unknown as InputEvent;
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, payload)).toBe(false);
- expect(snapshot(editor).wire).toBe('> abcd');
- });
-
- it('leaves a controlled insertion without a data transfer to the editor fallback', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, {dataTransfer: null} as unknown as InputEvent)).toBe(false);
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, 'xy')).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> abxycd', wrappers: 1});
- });
-
- it('remaps a mention on a continued slice line', () => {
- const editor = createHarness();
- setComposer(editor, '> abcd', 4);
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start: 3,
- end: 8,
- };
- update(editor, () => {
- $insertComposerClipboardSlice({display: 'x\r\n@name y', segments: [segment]}, false);
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> abx\n> <@1> ycd',
- selection: {anchor: 15, focus: 15},
- wrappers: 2,
- });
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toMatchObject({
- display: '> abx\n> @name ycd',
- segments: [{...segment, start: 8, end: 13}],
- });
- });
-
- it('quotes both slice lines when a mention lands on each', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- const mention = (start: number): MentionSegment => ({
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start,
- end: start + 5,
- });
- update(editor, () => {
- $insertComposerClipboardSlice({display: '@name\n@name', segments: [mention(0), mention(6)]}, false);
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> <@1>\n> <@1>',
- selection: {anchor: 15, focus: 15},
- wrappers: 2,
- });
- expect(editor.getEditorState().read(() => $projectComposer(), {editor}).segments).toMatchObject([
- {start: 2, end: 7},
- {start: 10, end: 15},
- ]);
- });
-
- it('keeps a mention quoted after a blank slice line', () => {
- const editor = createHarness();
- setComposer(editor, '> ab', 4);
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start: 3,
- end: 8,
- };
- update(editor, () => {
- $insertComposerClipboardSlice({display: 'x\n\n@name', segments: [segment]}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> abx\n> \n> <@1>', wrappers: 3});
- expect(editor.getEditorState().read(() => $projectComposer(), {editor}).segments).toMatchObject([
- {start: 11, end: 16},
- ]);
- });
-
- it('continues the quote when a slice replaces a range across two quote lines', () => {
- const editor = createHarness();
- setComposer(editor, '> ab\n> cd', 3, 8);
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start: 2,
- end: 7,
- };
- update(editor, () => {
- $insertComposerClipboardSlice({display: 'x\n@name', segments: [segment]}, false);
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> ax\n> <@1>d',
- selection: {anchor: 12, focus: 12},
- wrappers: 2,
- });
- expect(editor.getEditorState().read(() => $projectComposer(), {editor}).segments).toMatchObject([
- {start: 7, end: 12},
- ]);
- });
-
- it('drops carriage returns from a slice so a pasted blank quote line exits like a typed one', () => {
- const editor = createHarness();
- setComposer(editor, '', 0);
- update(editor, () => {
- $insertComposerClipboardSlice({display: '> a\r\n> \r\n> b', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> \n> b', wrappers: 3});
- select(editor, 6);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> a\n\n> b', wrappers: 2});
- });
-
- it('restores both quote lines when a cut slice is pasted back', () => {
- const editor = createHarness();
- setComposer(editor, '> ab\n> cd', 3, 8);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.removeText();
- }
- });
- update(editor, () => {
- $insertComposerClipboardSlice({display: 'b\n> c', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({
- wire: '> ab\n> cd',
- selection: {anchor: 8, focus: 8},
- wrappers: 2,
- });
- });
-
- it('reverts a whole paste in one undo step', () => {
- const editor = createHarness({history: true});
- setComposer(editor, '> abcd', 4);
- type(editor, 'q');
- expect(paste(editor, 'x\ny').handled).toBe(true);
- expect(snapshot(editor).wire).toBe('> abqx\n> ycd');
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '> abqcd', selection: {anchor: 5, focus: 5}, wrappers: 1});
- });
-
- it('plans pasted text with the parser flags its composer handle carries', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```', 5);
- let inserted = false;
- update(editor, () => {
- inserted = $insertComposerPastedText('x\ny', [], false, parserFlagsHandle(BIO_LIKE_FLAGS));
- });
- expect(inserted).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: '> ```x\n> y',
- selection: {anchor: 10, focus: 10},
- wrappers: 2,
- });
- });
-
- it('plans pasted text with the default flags when no composer handle is mounted', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```', 5);
- update(editor, () => {
- $insertComposerPastedText('x\ny', [], false, null);
- });
- expect(snapshot(editor).wire).toBe('> ```x\ny');
- });
-
- it('maps detected segment offsets from the pasted text onto the display', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- update(editor, () => {
- $insertComposerPastedText(
- 'hi <@1>!',
- [{type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 3, end: 7}],
- false,
- null,
- );
- });
- expect(snapshot(editor).wire).toBe('> hi <@1>!');
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toMatchObject({
- display: '> hi @name!',
- segments: [{start: 5, end: 10, actualText: '<@1>'}],
- });
- });
-
- it('quotes every line of a 200 line paste', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- expect(paste(editor, Array.from({length: 200}, (_, index) => `line ${index}`).join('\n')).handled).toBe(true);
- const state = snapshot(editor);
- expect(state.wrappers).toBe(200);
- expect(state.selection).toEqual({anchor: state.wire.length, focus: state.wire.length});
- });
-});
-
-describe('blockquote drag and drop', () => {
- function dropEvent(data: Record<string, string>): {
- clientX: number;
- clientY: number;
- dataTransfer: DataTransfer;
- preventDefault: ReturnType<typeof vi.fn>;
- } {
- return {
- clientX: 0,
- clientY: 0,
- dataTransfer: {getData: (type: string) => data[type] ?? ''} as unknown as DataTransfer,
- preventDefault: vi.fn(),
- };
- }
-
- function drop(editor: LexicalEditor, data: Record<string, string>): {handled: boolean; prevented: boolean} {
- const event = dropEvent(data);
- const handled = run(editor, DROP_COMMAND, event as unknown as DragEvent);
- return {handled, prevented: event.preventDefault.mock.calls.length > 0};
- }
-
- function ownMarker(editor: LexicalEditor): string {
- return JSON.stringify({editorKey: editor.getKey()});
- }
-
- function createDragHarness(): LexicalEditor {
- const editor = createHarness();
- disposers.push(
- registerComposerClipboardCommands(editor, {
- getPlainText: () => false,
- isEditable: () => true,
- getMarkdownParserFlags: () => DEFAULT_COMPOSER_MARKDOWN_FLAGS,
- }),
- );
- return editor;
- }
-
- function copy(editor: LexicalEditor): Record<string, string> {
- const data: Record<string, string> = {};
- const clipboardData = {
- getData: (type: string) => data[type] ?? '',
- setData: (type: string, value: string) => {
- data[type] = value;
- },
- } as unknown as DataTransfer;
- run(editor, COPY_COMMAND, {clipboardData, preventDefault: vi.fn()} as unknown as ClipboardEvent);
- return data;
- }
-
- function dragStart(editor: LexicalEditor, moved: string): Record<string, string> {
- const data: Record<string, string> = {};
- const dataTransfer = {
- getData: (type: string) => data[type] ?? '',
- setData: (type: string, value: string) => {
- data[type] = value;
- },
- } as unknown as DataTransfer;
- run(editor, DRAGSTART_COMMAND, {dataTransfer} as unknown as DragEvent);
- data['text/plain'] = moved;
- data['application/x-lexical-drag'] = ownMarker(editor);
- return data;
- }
-
- it('declines a drop carrying no lexical drag marker', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 0, 7);
- dropOffset.value = 10;
- expect(drop(editor, {'text/plain': 'one\ntwo'})).toEqual({handled: false, prevented: false});
- expect(snapshot(editor).wire).toBe('one\ntwo\n> alpha');
- });
-
- it('declines a drop whose lexical marker is unreadable', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 0, 7);
- dropOffset.value = 10;
- for (const marker of ['not json', JSON.stringify({}), JSON.stringify({editorKey: 7})]) {
- expect(drop(editor, {'text/plain': 'one\ntwo', 'application/x-lexical-drag': marker}).handled).toBe(false);
- }
- expect(snapshot(editor).wire).toBe('one\ntwo\n> alpha');
- });
-
- it('declines a cross-editor drop whose source editor root is not on the page', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 0, 7);
- dropOffset.value = 10;
- expect(
- drop(editor, {'text/plain': 'one\ntwo', 'application/x-lexical-drag': JSON.stringify({editorKey: 'other'})}),
- ).toEqual({handled: false, prevented: false});
- expect(snapshot(editor).wire).toBe('one\ntwo\n> alpha');
- });
-
- it('keeps a dragged mention a mention by preferring the composer payload over text/plain', () => {
- const editor = createDragHarness();
- setComposer(editor, 'hello @name world', 6, 11, [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 6, end: 11},
- ]);
- const data = dragStart(editor, '@name');
- expect(parseComposerClipboardSlice(data[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '')).toMatchObject({
- display: '@name',
- segments: [{start: 0, end: 5, actualText: '<@1>'}],
- });
- dropOffset.value = 17;
- expect(drop(editor, data)).toEqual({handled: true, prevented: true});
- expect(snapshot(editor).wire).toBe('hello world<@1>');
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toMatchObject({
- display: 'hello world@name',
- segments: [{start: 12, end: 17, actualText: '<@1>'}],
- });
- });
-
- it('continues the quote and keeps the segment offsets when a mention is dragged into a quote line', () => {
- const editor = createDragHarness();
- setComposer(editor, 'hi @name\n> quoted', 3, 8, [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 3, end: 8},
- ]);
- const data = dragStart(editor, '@name');
- dropOffset.value = 11;
- expect(drop(editor, data).handled).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: 'hi \n> <@1>quoted', wrappers: 1});
- expect(editor.getEditorState().read(() => $projectComposer(), {editor}).segments).toMatchObject([
- {start: 6, end: 11, actualText: '<@1>'},
- ]);
- });
-
- it('keeps a dragged standard emoji an emoji where its shortcode would not convert back', () => {
- const editor = createDragHarness();
- disposers.push(registerComposerEmojiShortcode(editor, (name) => (name === 'grinning' ? GRINNING : null)));
- setComposer(editor, 'hi :grinning:\n> quoted', 3, 13);
- expect(snapshot(editor).wire).toBe('hi 😀\n> quoted');
- const data = dragStart(editor, ':grinning:');
- expect(parseComposerClipboardSlice(data[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '')).toMatchObject({
- display: ':grinning:',
- segments: [{type: 'emoji', id: 'grinning', actualText: '😀', start: 0, end: 10}],
- });
- dropOffset.value = 16;
- expect(drop(editor, data).handled).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: 'hi \n> 😀quoted', wrappers: 1});
- const emojiInWrapper = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getLastChild() : null;
- return $isComposerBlockquoteLineNode(wrapper) && wrapper.getChildren().some($isComposerStandardEmojiNode);
- },
- {editor},
- );
- expect(emojiInWrapper).toBe(true);
- });
-
- it('falls back to text/plain when the drag carries no composer payload', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 0, 7);
- dropOffset.value = 10;
- expect(drop(editor, {'text/plain': 'one\ntwo', 'application/x-lexical-drag': ownMarker(editor)}).handled).toBe(
- true,
- );
- expect(snapshot(editor)).toMatchObject({wire: '\n> one\n> twoalpha', wrappers: 2});
- });
-
- it('trusts only the newest drag payload', () => {
- const editor = createDragHarness();
- setComposer(editor, 'alpha', 0, 5);
- const oldest = dragStart(editor, 'alpha')[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '';
- expect(parseComposerClipboardSlice(oldest)).not.toBeNull();
- const newest = dragStart(editor, 'alpha')[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '';
- expect(parseComposerClipboardSlice(oldest)).toBeNull();
- expect(parseComposerClipboardSlice(newest)).not.toBeNull();
- });
-
- it('keeps a copied slice trusted while more drags than the cache holds accumulate', () => {
- const editor = createDragHarness();
- setComposer(editor, 'hello @name world', 6, 11, [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 6, end: 11},
- ]);
- const copied = copy(editor)[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '';
- expect(parseComposerClipboardSlice(copied)).toMatchObject({display: '@name', segments: [{actualText: '<@1>'}]});
- let dragged = '';
- for (let index = 0; index < COMPOSER_CLIPBOARD_MAX_TRUSTED_PAYLOADS + 8; index += 1) {
- dragged = dragStart(editor, '@name')[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '';
- }
- expect(parseComposerClipboardSlice(copied)).toMatchObject({display: '@name', segments: [{actualText: '<@1>'}]});
- expect(parseComposerClipboardSlice(dragged)).not.toBeNull();
- });
-
- it('keeps the copied payload cache bounded', () => {
- const editor = createDragHarness();
- setComposer(editor, 'alpha', 0, 5);
- const oldest = copy(editor)[FLUXER_COMPOSER_CLIPBOARD_MIME] ?? '';
- expect(parseComposerClipboardSlice(oldest)).not.toBeNull();
- for (let index = 0; index < COMPOSER_CLIPBOARD_MAX_TRUSTED_PAYLOADS; index += 1) {
- copy(editor);
- }
- expect(parseComposerClipboardSlice(oldest)).toBeNull();
- });
-
- it('declines a same-editor drag from a collapsed selection', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 4);
- expect(drop(editor, {'text/plain': 'one\ntwo', 'application/x-lexical-drag': ownMarker(editor)}).handled).toBe(
- false,
- );
- expect(snapshot(editor).wire).toBe('one\ntwo\n> alpha');
- });
-
- it('keeps the dragged range when the drop caret cannot be resolved', () => {
- const editor = createHarness();
- setComposer(editor, 'one\ntwo\n> alpha', 0, 7);
- expect(drop(editor, {'text/plain': 'one\ntwo', 'application/x-lexical-drag': ownMarker(editor)})).toEqual({
- handled: false,
- prevented: false,
- });
- expect(snapshot(editor).wire).toBe('one\ntwo\n> alpha');
- expect(snapshot(editor).selection).toEqual({anchor: 0, focus: 7});
- });
-});
-
-describe('blockquote line breaks', () => {
- const LINE_BREAK_ROWS: Array<[string, number, string, number]> = [
- ['> test', 6, '> test\n> ', 9],
- ['> test', 4, '> te\n> st', 7],
- ['> test', 2, '> \n> test', 5],
- ['> ', 2, '> \n> ', 5],
- ['x\n> ', 4, 'x\n> \n> ', 7],
- ['> test\n> ', 9, '> test\n', 7],
- ['> \n> ', 5, '', 0],
- ['> \n> \n> ', 8, '', 0],
- ['> a\n> \n> ', 9, '> a\n', 4],
- ['> a\n> \n> b', 6, '> a\n\n> b', 4],
- ['x\n> \n> ', 7, 'x\n', 2],
- ['> ', 3, '> \n> ', 6],
- [' > a', 5, ' > a\n> ', 8],
- ];
-
- it.each(LINE_BREAK_ROWS)('on %j at %i gives %j with the caret at %i', (text, before, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, before);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- const state = snapshot(editor);
- expect(state).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- breaksInsideWrappers: 0,
- });
- expect(caretInsideMarker(state)).toBe(false);
- });
-
- it('treats INSERT_PARAGRAPH_COMMAND like a line break', () => {
- const editor = createHarness();
- setComposer(editor, '> test', 6);
- expect(run(editor, INSERT_PARAGRAPH_COMMAND, undefined)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n> ', selection: {anchor: 9, focus: 9}});
- });
-
- it('removes the whole quote when an empty quote is left twice', () => {
- const editor = createHarness();
- setComposer(editor, '', 0);
- type(editor, '>');
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({
- wire: '> ',
- selection: {anchor: 2, focus: 2},
- wrappers: 1,
- markers: ['> '],
- });
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '> \n> ', selection: {anchor: 5, focus: 5}, wrappers: 2});
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '', selection: {anchor: 0, focus: 0}, wrappers: 0});
- });
-
- it('leaves a plain line below the quote when the empty continuation is left', () => {
- const editor = createHarness();
- setComposer(editor, '', 0);
- for (const character of '> test') {
- type(editor, character);
- }
- expect(snapshot(editor)).toMatchObject({wire: '> test', selection: {anchor: 6, focus: 6}, wrappers: 1});
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n> ', selection: {anchor: 9, focus: 9}, wrappers: 2});
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n', selection: {anchor: 7, focus: 7}, wrappers: 1});
- type(editor, 'x');
- expect(snapshot(editor)).toMatchObject({wire: '> test\nx', wrappers: 1});
- });
-
- it('declines outside quote lines, with selectStart, and while composing', () => {
- const editor = createHarness();
- setComposer(editor, 'abc', 3);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('abc\n');
- setComposer(editor, '> test', 6);
- run(editor, INSERT_LINE_BREAK_COMMAND, true);
- expect(snapshot(editor).wire).toBe('> test\n');
- setComposer(editor, '> test', 6);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- $setCompositionKey(selection.anchor.key);
- }
- });
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('> test\n');
- update(editor, () => {
- $setCompositionKey(null);
- });
- });
-});
-
-describe('blockquote backspace', () => {
- const BACKSPACE_ROWS: Array<[string, number, string, number]> = [
- ['> test', 2, 'test', 0],
- ['> ', 2, '', 0],
- ['> \n> ', 5, '> \n', 3],
- ['> \n', 3, '', 0],
- ['> \nabc', 3, 'abc', 0],
- ['a\n> \nb', 5, 'a\nb', 2],
- [' > a', 4, 'a', 0],
- ['x\n> test', 4, 'x\ntest', 2],
- ];
-
- it.each(BACKSPACE_ROWS)('on %j at %i gives %j with the caret at %i', (text, before, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, before);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- });
- });
-
- it.each(
- BACKSPACE_ROWS,
- )('removes the same text on a backward word delete on %j at %i, giving %j with the caret at %i', (text, before, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, before);
- expect(run(editor, DELETE_WORD_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- });
- });
-
- it('removes two empty quote lines with two presses', () => {
- const editor = createHarness();
- setComposer(editor, '> \n> ', 5);
- run(editor, DELETE_CHARACTER_COMMAND, true);
- expect(snapshot(editor)).toMatchObject({wire: '> \n', selection: {anchor: 3, focus: 3}, wrappers: 1});
- run(editor, DELETE_CHARACTER_COMMAND, true);
- expect(snapshot(editor)).toMatchObject({wire: '', selection: {anchor: 0, focus: 0}, wrappers: 0});
- });
-
- it.each<[string, number]>([
- ['> a\nb', 4],
- ['> test', 4],
- ['> ', 3],
- ['abc', 3],
- ['```\n> a', 6],
- ])('declines a backspace on %j with the caret at %i', (text, caret) => {
- const editor = createHarness();
- setComposer(editor, text, caret);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(false);
- });
-
- it('declines a backspace over a range inside a quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> test', 2, 4);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(false);
- });
-
- it('declines every delete while composing', () => {
- const editor = createHarness();
- setComposer(editor, '> test', 2);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- $setCompositionKey(selection.anchor.key);
- }
- });
- for (const command of [DELETE_CHARACTER_COMMAND, DELETE_WORD_COMMAND, DELETE_LINE_COMMAND]) {
- expect(run(editor, command, true)).toBe(false);
- expect(run(editor, command, false)).toBe(false);
- }
- expect(snapshot(editor).wire).toBe('> test');
- update(editor, () => {
- $setCompositionKey(null);
- });
- });
-
- it.each(['before', 'after'])('wins over a high priority delete handler registered %s it', (order) => {
- const editor = createBareEditor();
- const spy = vi.fn(() => true);
- const registerCompetitors = () => {
- disposers.push(
- registerComposerSoftWrapDeletion(editor),
- editor.registerCommand(DELETE_CHARACTER_COMMAND, spy, COMMAND_PRIORITY_HIGH),
- );
- };
- if (order === 'before') {
- registerCompetitors();
- }
- disposers.push(registerComposerMarkdownHighlight(editor), registerComposerBlockquote(editor));
- if (order === 'after') {
- registerCompetitors();
- }
- setComposer(editor, '> test', 2);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(true);
- expect(spy).not.toHaveBeenCalled();
- expect(snapshot(editor).wire).toBe('test');
- });
-});
-
-describe('blockquote forward delete', () => {
- const FORWARD_DELETE_COMMANDS = {
- character: DELETE_CHARACTER_COMMAND,
- word: DELETE_WORD_COMMAND,
- line: DELETE_LINE_COMMAND,
- };
-
- const FORWARD_DELETE_ROWS: Array<[string, number, string, number]> = [
- ['> a\n> b', 3, '> ab', 3],
- ['a\n> b', 1, 'ab', 1],
- ['> a\n> ', 3, '> a', 3],
- ['> \n> b', 2, '> b', 2],
- ['a\n> \n> b', 4, 'a\n> b', 4],
- ['> \nb', 2, 'b', 0],
- ['a\n> \nb', 4, 'a\nb', 2],
- ];
-
- it.each(FORWARD_DELETE_ROWS)('on %j at %i gives %j with the caret at %i', (text, before, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, before);
- expect(run(editor, DELETE_CHARACTER_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- });
- });
-
- it('removes an empty quote line when the caret sits at the end of its marker text', () => {
- const editor = createHarness();
- setComposer(editor, '> \n> b');
- selectFirstMarkerText(editor, 2);
- expect(run(editor, DELETE_CHARACTER_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> b', selection: {anchor: 2, focus: 2}, wrappers: 1});
- });
-
- it('plans line deletes that start at a quote line boundary', () => {
- const editor = createHarness();
- setComposer(editor, '> a\n> b', 3);
- expect(run(editor, DELETE_LINE_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ab', selection: {anchor: 3, focus: 3}, wrappers: 1});
- setComposer(editor, '> \nabc', 3);
- expect(run(editor, DELETE_LINE_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: 'abc', selection: {anchor: 0, focus: 0}, wrappers: 0});
- });
-
- it.each<[keyof typeof FORWARD_DELETE_COMMANDS, string, number, string, number]>([
- ['character', '> ab', 2, '> b', 2],
- ['character', 'x\n> ab', 4, 'x\n> b', 4],
- ['character', '> \u{1F468}\u200D\u{1F469}\u200D\u{1F467}x', 2, '> x', 2],
- ['character', '> e\u0301x', 2, '> ex', 3],
- ['word', '> ab ef', 2, '> ef', 2],
- ['word', 'x\n> ab\n> cd', 4, 'x\n> \n> cd', 4],
- ['word', '> \n> cd', 2, '> \n> cd', 2],
- ['line', 'x\n> ab ef\n> gh', 4, 'x\n> \n> gh', 4],
- ])('deletes forward by %s from the quote content start of %j at %i, giving %j with the caret at %i', (unit, text, before, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, before);
- expect(run(editor, FORWARD_DELETE_COMMANDS[unit], false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- });
- });
-
- it.each<[keyof typeof FORWARD_DELETE_COMMANDS, string, Array<number>, string]>([
- ['character', 'x\n> @name@name y', [4, 9], 'x\n> <@1> y'],
- ['word', 'x\n> @name@name y', [4, 9], 'x\n> <@1> y'],
- ['line', 'x\n> @name@name y', [4, 9], 'x\n> '],
- ['word', 'x\n> ab@name y', [6], 'x\n> y'],
- ])('deletes forward by %s over whole mentions from the quote content start of %j', (unit, text, starts, wire) => {
- const editor = createHarness();
- const segments = starts.map(
- (start): MentionSegment => ({
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start,
- end: start + 5,
- }),
- );
- setComposer(editor, text, 4, 4, segments);
- expect(run(editor, FORWARD_DELETE_COMMANDS[unit], false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire, selection: {anchor: 4, focus: 4}, wrappers: 1});
- });
-
- it('restores the text of a forward delete at a quote content start in one undo step', () => {
- const editor = createHarness({history: true});
- setComposer(editor, 'x\n> ab ef', 4);
- expect(run(editor, DELETE_WORD_COMMAND, false)).toBe(true);
- expect(snapshot(editor).wire).toBe('x\n> ef');
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: 'x\n> ab ef', selection: {anchor: 4, focus: 4}, wrappers: 1});
- });
-
- function expectForwardDeleteDeclined(text: string, anchor: number, focus?: number): void {
- const editor = createHarness();
- setComposer(editor, text, anchor, focus);
- for (const command of Object.values(FORWARD_DELETE_COMMANDS)) {
- expect(run(editor, command, false)).toBe(false);
- }
- expect(snapshot(editor).wire).toBe(text);
- }
-
- it.each<[string, number]>([
- ['\n> b', 0],
- ['a\n\n> b', 2],
- ['> a\nb', 3],
- ['> test', 4],
- ['> ', 2],
- ['```\n> a\n> b', 7],
- ])('declines every forward delete on %j with the caret at %i', (text, caret) => {
- expectForwardDeleteDeclined(text, caret);
- });
-
- it.each<[string, number, number]>([
- ['> a\n> b', 3, 6],
- ['> a\n> b', 2, 3],
- ])('declines every forward delete on %j over the range %i..%i', (text, anchor, focus) => {
- expectForwardDeleteDeclined(text, anchor, focus);
- });
-});
-
-describe('blockquote history', () => {
- it('treats one line break exit and one backspace as single steps', () => {
- const editor = createHarness({history: true});
- setComposer(editor, '> test\n> ', 9);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n', selection: {anchor: 7, focus: 7}});
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n> ', selection: {anchor: 9, focus: 9}, wrappers: 2});
- historyStep(editor, REDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n', selection: {anchor: 7, focus: 7}, wrappers: 1});
- select(editor, 2);
- run(editor, DELETE_CHARACTER_COMMAND, true);
- expect(snapshot(editor).wire).toBe('test\n');
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '> test\n', wrappers: 1});
- historyStep(editor, REDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: 'test\n', wrappers: 0});
- });
-});
-
-describe('blockquote caret, typing and composition', () => {
- it.each([
- ['> test', 0, 2],
- ['> test', 1, 2],
- ['ab\n> cd', 3, 5],
- ['ab\n> cd', 4, 5],
- ['> test', 3, 3],
- ])('moves the caret on %j from %i to %i on a selection change', (text, before, after) => {
- const editor = createHarness();
- setComposer(editor, text);
- select(editor, before);
- expect(run(editor, SELECTION_CHANGE_COMMAND, undefined)).toBe(false);
- expect(snapshot(editor).selection).toEqual({anchor: after, focus: after});
- });
-
- it('keeps a range that starts at the start of a quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> test');
- select(editor, 0, 4);
- run(editor, SELECTION_CHANGE_COMMAND, undefined);
- expect(snapshot(editor).selection).toEqual({anchor: 0, focus: 4});
- });
-
- it.each([
- ['ab\n> cd', 1, 3, 1, 5],
- ['ab\n> cd', 4, 1, 5, 1],
- ['ab\n> cd', 4, 7, 5, 7],
- ['ab\n> cd', 3, 7, 3, 7],
- ['> a\n> b', 0, 7, 0, 7],
- ])('moves range endpoints on %j from %i..%i to %i..%i on a selection change', (text, anchor, focus, expectedAnchor, expectedFocus) => {
- const editor = createHarness();
- setComposer(editor, text);
- select(editor, anchor, focus);
- run(editor, SELECTION_CHANGE_COMMAND, undefined);
- expect(snapshot(editor).selection).toEqual({anchor: expectedAnchor, focus: expectedFocus});
- });
-
- it('snaps a text point inside the marker to content start', () => {
- const editor = createHarness();
- setComposer(editor, '> ');
- selectFirstMarkerText(editor, 1);
- run(editor, SELECTION_CHANGE_COMMAND, undefined);
- expect(snapshot(editor).selection).toEqual({anchor: 2, focus: 2});
- });
-
- it('moves the caret out of a marker the highlight pass has just created', () => {
- const editor = createHarness();
- setComposer(editor, 'x> test', 1);
- update(editor, () => {
- $selectComposerRange(0, 1);
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertText('');
- }
- });
- expect(snapshot(editor)).toMatchObject({wire: '> test', selection: {anchor: 2, focus: 2}, wrappers: 1});
- });
-
- it('creates a sibling content node when typing at the end of the marker text', () => {
- const editor = createHarness();
- setComposer(editor, '> ');
- selectFirstMarkerText(editor, 2);
- type(editor, 'x');
- expect(snapshot(editor)).toMatchObject({
- wire: '> x',
- wrappers: 1,
- markers: ['> '],
- selection: {anchor: 3, focus: 3},
- });
- });
-
- it('creates a content node when typing at the element point after the marker', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- type(editor, 'x');
- expect(snapshot(editor)).toMatchObject({wire: '> x', wrappers: 1, markers: ['> ']});
- });
-
- it('refuses text inserted before or after the marker', () => {
- const editor = createHarness();
- setComposer(editor, '> ');
- const guards = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- const marker = $isComposerBlockquoteLineNode(wrapper) ? wrapper.getFirstChild() : null;
- if (!$isComposerBlockquoteMarkerNode(marker)) {
- throw new Error('expected a quote marker');
- }
- return {before: marker.canInsertTextBefore(), after: marker.canInsertTextAfter()};
- },
- {editor},
- );
- expect(guards).toEqual({before: false, after: false});
- });
-
- it('diverts a composition that starts at the end of the marker text', () => {
- const editor = createHarness();
- setComposer(editor, '> ');
- const markerKey = selectFirstMarkerText(editor, 2);
- run(editor, COMPOSITION_START_COMMAND, COMPOSITION_EVENT);
- const key = compositionKey(editor);
- expect(key).not.toBeNull();
- expect(key).not.toBe(markerKey);
- update(editor, () => {
- const node = $getNodeByKey(key!);
- if ($isTextNode(node)) {
- node.setTextContent('あ');
- node.select(1, 1);
- }
- });
- expect(editor.isComposing()).toBe(true);
- expect(snapshot(editor).markers).toEqual(['> ']);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(false);
- update(editor, () => {
- $setCompositionKey(null);
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- }
- });
- expect(snapshot(editor)).toMatchObject({wire: '> あ', wrappers: 1, markers: ['> ']});
- });
-
- it('diverts a composition that starts at the element point after the marker', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- run(editor, COMPOSITION_START_COMMAND, COMPOSITION_EVENT);
- const key = compositionKey(editor);
- const target = editor.getEditorState().read(() => $getNodeByKey(key!), {editor});
- expect(target).not.toBeNull();
- expect($isComposerBlockquoteMarkerNode(target)).toBe(false);
- update(editor, () => {
- $setCompositionKey(null);
- });
- });
-
- it('lets a plain syntax marker take both the typed text and the composition', () => {
- const editor = createBareEditor();
- registerPlainTextFallbacks(editor);
- let markerKey = '';
- update(editor, () => {
- const paragraph = $createParagraphNode();
- const marker = $createSyntaxMarkerNode('> ');
- paragraph.append(marker);
- $getRoot().clear().append(paragraph);
- marker.select(2, 2);
- markerKey = marker.getKey();
- });
- run(editor, COMPOSITION_START_COMMAND, COMPOSITION_EVENT);
- expect(compositionKey(editor)).toBe(markerKey);
- update(editor, () => {
- $setCompositionKey(null);
- const marker = $getNodeByKey(markerKey);
- if ($isTextNode(marker)) {
- marker.select(2, 2);
- }
- });
- type(editor, 'x');
- expect(editor.getEditorState().read(() => $getNodeByKey(markerKey)?.getTextContent(), {editor})).toBe('> x');
- });
-
- it('jumps over the hidden marker on ArrowLeft', () => {
- const editor = createHarness();
- setComposer(editor, 'ab\n> cd', 5);
- const event = keyEvent();
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, event)).toBe(true);
- expect(event.preventDefault).toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor: 2, focus: 2});
- setComposer(editor, '> test', 2);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 2, focus: 2});
- });
-
- it('declines ArrowLeft while composing and away from content start', () => {
- const editor = createHarness();
- setComposer(editor, 'ab\n> cd', 5);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent({isComposing: true}))).toBe(false);
- setComposer(editor, '> test', 4);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(false);
- });
-
- it.each<[boolean, Record<string, boolean>, string, number, number, number]>([
- [true, {altKey: true}, 'ab\n> cd', 5, 2, 2],
- [false, {ctrlKey: true}, 'ab\n> cd', 5, 2, 2],
- [true, {altKey: true, shiftKey: true}, 'ab\n> cd', 5, 5, 2],
- [false, {ctrlKey: true, shiftKey: true}, 'ab\n> cd', 5, 5, 2],
- [true, {altKey: true}, '> a\n> cd', 6, 3, 3],
- [true, {altKey: true}, '> cd', 2, 2, 2],
- [true, {altKey: true, shiftKey: true}, '> cd', 2, 2, 2],
- ])('with apple=%s and %j moves a word back from the quote content start of %j at %i to %i..%i', (apple, modifiers, text, caret, anchor, focus) => {
- platform.apple = apple;
- const editor = createHarness();
- setComposer(editor, text, caret);
- const event = keyEvent(modifiers);
- expect(run(editor, KEY_DOWN_COMMAND, event)).toBe(true);
- expect(event.preventDefault).toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor, focus});
- });
-
- it.each<[boolean, Record<string, unknown>, string, number]>([
- [true, {ctrlKey: true}, 'ab\n> cd', 5],
- [false, {altKey: true}, 'ab\n> cd', 5],
- [true, {altKey: true, metaKey: true}, 'ab\n> cd', 5],
- [false, {ctrlKey: true, altKey: true}, 'ab\n> cd', 5],
- [true, {altKey: true, key: 'ArrowRight', keyCode: 39}, 'ab\n> cd', 2],
- [true, {altKey: true, shiftKey: true, key: 'ArrowRight', keyCode: 39}, 'ab\n> cd', 2],
- [true, {altKey: true}, 'ab\n> cd', 6],
- [true, {altKey: true, isComposing: true}, 'ab\n> cd', 5],
- [true, {altKey: true, key: 'b', keyCode: 66}, 'ab\n> cd', 5],
- ])('with apple=%s leaves %j on %j at %i to the browser', (apple, overrides, text, caret) => {
- platform.apple = apple;
- const editor = createHarness();
- setComposer(editor, text, caret);
- const event = keyEvent(overrides);
- run(editor, KEY_DOWN_COMMAND, event);
- expect(event.preventDefault).not.toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor: caret, focus: caret});
- });
-
- it('replaces a word selection extended over the hidden marker without leaving marker text', () => {
- platform.apple = false;
- const editor = createHarness();
- setComposer(editor, 'ab\n> cd', 5);
- expect(run(editor, KEY_DOWN_COMMAND, keyEvent({ctrlKey: true, shiftKey: true}))).toBe(true);
- type(editor, 'y');
- expect(snapshot(editor)).toMatchObject({wire: 'abycd', selection: {anchor: 3, focus: 3}, wrappers: 0});
- });
-
- it('moves a word back on the arrow that points backward in right-to-left text', () => {
- platform.apple = true;
- const editor = createHarness();
- vi.spyOn(editor, 'getElementByKey').mockReturnValue(RTL_ELEMENT);
- setComposer(editor, 'سطر\n> مرحبا', 6);
- const forward = keyEvent({altKey: true});
- run(editor, KEY_DOWN_COMMAND, forward);
- expect(forward.preventDefault).not.toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor: 6, focus: 6});
- expect(run(editor, KEY_DOWN_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39, altKey: true}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 3, focus: 3});
- });
-
- it('jumps over the hidden marker on ArrowRight at the end of the line above', () => {
- const editor = createHarness();
- setComposer(editor, 'ab\n> cd', 2);
- const event = keyEvent({key: 'ArrowRight', keyCode: 39});
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, event)).toBe(true);
- expect(event.preventDefault).toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor: 5, focus: 5});
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39}))).toBe(false);
- });
-
- it('extends a shift selection over the hidden marker and back', () => {
- const editor = createHarness();
- setComposer(editor, 'x\n> ab', 4);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent({shiftKey: true}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 4, focus: 1});
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39, shiftKey: true}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 4, focus: 4});
- });
-
- it.each<[string, number, 'left' | 'right', number, string, string, number]>([
- ['x\n> ab', 4, 'left', 1, 'y', 'xyab', 2],
- ['> a\n> b', 3, 'right', 6, 'x', '> axb', 4],
- ])('replaces a shift selection on %j from %i without leaving marker text', (text, caret, direction, extended, typed, expected, after) => {
- const editor = createHarness();
- setComposer(editor, text, caret);
- const command = direction === 'left' ? KEY_ARROW_LEFT_COMMAND : KEY_ARROW_RIGHT_COMMAND;
- expect(run(editor, command, keyEvent({shiftKey: true}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: caret, focus: extended});
- type(editor, typed);
- expect(snapshot(editor)).toMatchObject({
- wire: expected,
- selection: {anchor: after, focus: after},
- wrappers: expectedQuoteLines(expected),
- });
- });
-
- it('keeps a shift selection at content start of the first quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> ab', 2);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent({shiftKey: true}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 2, focus: 2});
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: 'ab', selection: {anchor: 0, focus: 0}, wrappers: 0});
- });
-
- it('swaps the arrow keys in right-to-left text', () => {
- const editor = createHarness();
- vi.spyOn(editor, 'getElementByKey').mockReturnValue(RTL_ELEMENT);
- setComposer(editor, 'سطر\n> مرحبا', 6);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(false);
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 3, focus: 3});
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39}))).toBe(false);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 6, focus: 6});
- setComposer(editor, '> مرحبا', 2);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(false);
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39}))).toBe(true);
- expect(snapshot(editor).selection).toEqual({anchor: 2, focus: 2});
- });
-});
-
-describe('multi-line blockquote markers', () => {
- it('rewrites a typed ">>> " to "> " and restores it on undo', () => {
- const editor = createHarness({history: true});
- setComposer(editor, '>>>', 3);
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({wire: '> ', selection: {anchor: 2, focus: 2}, wrappers: 1});
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '>>>', selection: {anchor: 3, focus: 3}, wrappers: 0});
- historyStep(editor, REDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '> ', selection: {anchor: 2, focus: 2}, wrappers: 1});
- });
-
- it('rewrites when the completing character is a ">"', () => {
- const editor = createHarness();
- setComposer(editor, '>> a', 1);
- type(editor, '>');
- expect(snapshot(editor)).toMatchObject({wire: '> a', selection: {anchor: 2, focus: 2}, wrappers: 1});
- });
-
- it.each<[string, number, string, number, number]>([
- ['a\n>>>\nb', 5, 'a\n> \n> b', 4, 2],
- ['>>>\nb\nc', 3, '> \n> b\n> c', 2, 3],
- ])('quotes every line below a marker typed on %j at %i and restores it on undo', (text, caret, wire, after, wrappers) => {
- const editor = createHarness({history: true});
- setComposer(editor, text, caret);
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({wire, selection: {anchor: after, focus: after}, wrappers});
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: text, selection: {anchor: caret, focus: caret}});
- });
-
- it.each<[string, number, string, number]>([
- ['>>>\n> b', 3, '>>> \n> b', 4],
- ['> x\n>>>\nb', 7, '> x\n>>> \nb', 8],
- ])('leaves a marker typed on %j at %i as text because line quotes would change the rendered message', (text, caret, wire, after) => {
- const editor = createHarness();
- setComposer(editor, text, caret);
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({wire, selection: {anchor: after, focus: after}});
- });
-
- it('quotes every line below a pasted ">>> "', () => {
- const editor = createHarness();
- setComposer(editor, 'a\nb', 0);
- update(editor, () => {
- $insertComposerClipboardSlice({display: '>>> ', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', selection: {anchor: 2, focus: 2}, wrappers: 2});
- });
-
- it('leaves a ">>> " pasted on the last line below a quote as text instead of taking the typed branch', () => {
- const editor = createHarness();
- setComposer(editor, '> x\n', 4);
- update(editor, () => {
- $insertComposerClipboardSlice({display: '>>> ', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> x\n>>> ', selection: {anchor: 8, focus: 8}});
- });
-
- it('keeps the rendered meaning of arrived text and creates no selection', () => {
- const editor = createHarness();
- update(editor, () => {
- $hydrateComposerFromDraft('>>> a\n\nb', []);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> \n> b', wrappers: 3, hasSelection: false});
- });
-
- it('keeps a caret placed at the end after hydration', () => {
- const editor = createHarness();
- setComposer(editor, '>>> a\nb', 7);
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', selection: {anchor: 7, focus: 7}, wrappers: 2});
- });
-
- it('keeps the rendered meaning of pasted text', () => {
- const editor = createHarness();
- setComposer(editor, '', 0);
- update(editor, () => {
- $insertComposerClipboardSlice({display: '>>> a\nb', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', selection: {anchor: 7, focus: 7}, wrappers: 2});
- });
-
- it('keeps the indent of an indented marker', () => {
- const editor = createHarness();
- update(editor, () => {
- $hydrateComposerFromDraft(' >>> a', []);
- });
- expect(snapshot(editor)).toMatchObject({wire: ' > a', wrappers: 1, markers: [' > '], hasSelection: false});
- });
-
- it('leaves an arrived alert marker alone so the stored text keeps its meaning', () => {
- const editor = createHarness();
- update(editor, () => {
- $hydrateComposerFromDraft('>>> [!NOTE]\nbody', []);
- });
- expect(snapshot(editor)).toMatchObject({wire: '>>> [!NOTE]\nbody', wrappers: 0});
- });
-
- it.each<[string, number]>([
- ['>>> a\n> b', 0],
- ['>>> > a\nb', 0],
- ['>>> a\n>>> b', 0],
- ['>>> a\n> [!NOTE]\n> b', 0],
- ['> x\n>>> a\nb', 1],
- ['> [!NOTE]\n>>> a\nb', 1],
- ['||s\n>>> a\nb||\nc', 0],
- ])('leaves arrived %j as text because line quotes would change the rendered message', (text, wrappers) => {
- const editor = createHarness();
- update(editor, () => {
- $hydrateComposerFromDraft(text, []);
- });
- expect(snapshot(editor)).toMatchObject({wire: text, wrappers});
- });
-
- it('leaves a pasted ">>> " block that holds a quote line as text', () => {
- const editor = createHarness();
- setComposer(editor, '', 0);
- update(editor, () => {
- $insertComposerClipboardSlice({display: '>>> a\n> b', segments: []}, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n> b', selection: {anchor: 9, focus: 9}, wrappers: 0});
- });
-
- it('inserts a plain line break inside an arrived block that stays text', () => {
- const editor = createHarness();
- setComposer(editor, '>>> a\n> b', 5);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n\n> b', wrappers: 0});
- });
-
- it('rewrites every line once an edit removes the nested quote line', () => {
- const editor = createHarness();
- setComposer(editor, '>>> a\n> b', 6, 8);
- type(editor, '');
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', selection: {anchor: 6, focus: 6}, wrappers: 2});
- });
-
- it.each([2, 4])('rewrites every line when the transforms register over a caret at %i on the marker', (caret) => {
- const editor = createBareEditor();
- setComposer(editor, '>>> a\nb\nc', caret);
- disposers.push(registerComposerMarkdownHighlight(editor), registerComposerBlockquote(editor));
- editor.update(
- () => {
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- }
- },
- {discrete: true, tag: HISTORY_MERGE_TAG},
- );
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b\n> c', selection: {anchor: 2, focus: 2}, wrappers: 3});
- });
-
- it('keeps an arrived block that stays text when a pass runs with the caret on its marker', () => {
- const editor = createHarness();
- setComposer(editor, '>>> a\n> b');
- select(editor, 4);
- update(editor, () => {
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- }
- });
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n> b', selection: {anchor: 4, focus: 4}, wrappers: 0});
- });
-
- it('rewrites a marker typed on the last line where an arrived block would stay text', () => {
- const editor = createHarness();
- setComposer(editor, '> x\n>>>', 7);
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({wire: '> x\n> ', selection: {anchor: 6, focus: 6}});
- });
-
- it.each<[number, string]>([
- [10, '>>> a\nb\nc'],
- [11, '> a\n> b\n> c'],
- ])('with a max wire length of %i turns arrived ">>> a\\nb\\nc" into %j', (maxWireLength, wire) => {
- const editor = createHarness({maxWireLength});
- update(editor, () => {
- $hydrateComposerFromDraft('>>> a\nb\nc', []);
- });
- expect(snapshot(editor).wire).toBe(wire);
- });
-
- it.each<[number, string]>([
- [10, '>>> a\nb\nc'],
- [11, '> a\n> b\n> c'],
- ])('with a max wire length of %i the mount pass over a hydrated ">>> a\\nb\\nc" gives %j', (maxWireLength, wire) => {
- const editor = createBareEditor();
- update(editor, () => {
- $hydrateComposerFromDraft('>>> a\nb\nc', []);
- });
- disposers.push(
- registerComposerMarkdownHighlight(editor, undefined, false, maxWireLength),
- registerComposerBlockquote(editor),
- );
- editor.update(
- () => {
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- }
- },
- {discrete: true, tag: HISTORY_MERGE_TAG},
- );
- expect(snapshot(editor).wire).toBe(wire);
- });
-
- it.each([1, 2, 3, 4])('leaves arrived ">>> a\\n> b" as text when the hydrate places the caret at %i', (caret) => {
- const editor = createHarness();
- setComposer(editor, '>>> a\n> b', caret);
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n> b', selection: {anchor: caret, focus: caret}, wrappers: 0});
- });
-
- it('leaves an arrived block as text when deleting its first character leaves the caret after the marker', () => {
- const editor = createHarness();
- setComposer(editor, '>>> za\n> b', 4, 5);
- type(editor, '');
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n> b', selection: {anchor: 4, focus: 4}, wrappers: 0});
- });
-
- it.each<[number, number, string]>([
- [4, 4, 'z'],
- [3, 4, ''],
- ])('keeps arrived ">>> a\\n> b" as text after undoing an edit over %i..%i', (anchor, focus, text) => {
- const editor = createHarness({history: true});
- setComposer(editor, '>>> a\n> b');
- select(editor, 4);
- update(editor, () => {
- $selectComposerRange(anchor, focus);
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertText(text);
- }
- });
- historyStep(editor, UNDO_COMMAND);
- expect(snapshot(editor)).toMatchObject({wire: '>>> a\n> b', selection: {anchor: 4, focus: 4}, wrappers: 0});
- });
-
- it('leaves ">>> a" as text without ALLOW_MULTILINE_BLOCKQUOTES', () => {
- const editor = createHarness({flags: NO_MULTILINE_FLAGS});
- update(editor, () => {
- $hydrateComposerFromDraft('>>> a', []);
- });
- expect(snapshot(editor)).toMatchObject({wire: '>>> a', wrappers: 0});
- });
-});
-
-describe('blockquote transform convergence', () => {
- it.each([
- '> > a',
- '> [!NOTE]\n> body',
- '> >>> a',
- '> a\n> \n> b',
- '```\n> a',
- '> ',
- '> a\n\nb',
- '>>> a\n> b',
- '> x\n>>> a\nb',
- ])('reaches a fixed point on %j', (text) => {
- const editor = createHarness();
- setComposer(editor, text);
- const before = JSON.stringify(editor.getEditorState().toJSON());
- const wire = snapshot(editor).wire;
- const updates: Array<{intentionalElements: number; leaves: number}> = [];
- disposers.push(
- editor.registerUpdateListener(({dirtyElements, dirtyLeaves}) => {
- updates.push({
- intentionalElements: [...dirtyElements].filter(([key, intentional]) => intentional && key !== 'root').length,
- leaves: dirtyLeaves.size,
- });
- }),
- );
- update(editor, () => {});
- expect(updates.every((entry) => entry.intentionalElements === 0 && entry.leaves === 0)).toBe(true);
- let marked = 0;
- update(editor, () => {
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- marked += 1;
- }
- });
- expect(JSON.stringify(editor.getEditorState().toJSON())).toBe(before);
- expect(updates[updates.length - 1]).toEqual({intentionalElements: 0, leaves: marked});
- expect(snapshot(editor).wire).toBe(wire);
- });
-
- it('keeps nested and alert quotes in a single wrapper per line', () => {
- const editor = createHarness();
- setComposer(editor, '> > a');
- expect(snapshot(editor)).toMatchObject({wire: '> > a', wrappers: 1, markers: ['> ']});
- setComposer(editor, '> [!NOTE]\n> body');
- expect(snapshot(editor)).toMatchObject({wrappers: 2, markers: ['> ', '> ']});
- setComposer(editor, '> >>> a');
- expect(snapshot(editor)).toMatchObject({wire: '> >>> a', wrappers: 1, markers: ['> ']});
- });
-
- it('keeps whitespace typed after the prefix as content of the same quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> ', 2);
- type(editor, ' ');
- expect(snapshot(editor)).toMatchObject({
- wire: '> ',
- markers: ['> '],
- lines: [{start: 0, contentStart: 2, end: 3}],
- selection: {anchor: 3, focus: 3},
- });
- });
-});
-
-describe('blockquote code blocks', () => {
- it('gives no wrapper to lines inside closed and unclosed fences', () => {
- const editor = createHarness();
- setComposer(editor, '```\n> a', 7);
- expect(snapshot(editor).wrappers).toBe(0);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('```\n> a\n');
- setComposer(editor, '```\n> a\n```');
- expect(snapshot(editor).wrappers).toBe(0);
- });
-
- it('keeps a quote line that follows a closed fence', () => {
- const editor = createHarness();
- setComposer(editor, '```\nx\n```\n> a');
- expect(snapshot(editor)).toMatchObject({wrappers: 1, lines: [{start: 10, contentStart: 12, end: 13}]});
- });
-
- it('does not continue the quote from a fence opened on a quote line', () => {
- const editor = createHarness();
- setComposer(editor, '> ```', 5);
- expect(snapshot(editor).wrappers).toBe(1);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('> ```\n');
- });
-
- it('keeps the wrapper only on the opening line of a fence closed inside a quote', () => {
- const editor = createHarness();
- setComposer(editor, '> ```\n> code\n> ```');
- expect(snapshot(editor)).toMatchObject({wrappers: 1, lines: [{start: 0, contentStart: 2, end: 5}]});
- });
-});
-
-describe('blockquote parser flags', () => {
- it('makes no quote markers without ALLOW_BLOCKQUOTES, so every handler finds no quote line', () => {
- const editor = createHarness({flags: NO_BLOCKQUOTE_FLAGS});
- setComposer(editor, '> a', 2);
- expect(snapshot(editor).wrappers).toBe(0);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(false);
- expect(run(editor, KEY_ARROW_LEFT_COMMAND, keyEvent())).toBe(false);
- select(editor, 0);
- run(editor, SELECTION_CHANGE_COMMAND, undefined);
- expect(snapshot(editor).selection).toEqual({anchor: 0, focus: 0});
- select(editor, 3);
- run(editor, INSERT_LINE_BREAK_COMMAND, false);
- expect(snapshot(editor).wire).toBe('> a\n');
- setComposer(editor, '> a\n> b', 3);
- expect(run(editor, DELETE_CHARACTER_COMMAND, false)).toBe(false);
- expect(run(editor, DELETE_LINE_COMMAND, false)).toBe(false);
- expect(run(editor, KEY_ARROW_RIGHT_COMMAND, keyEvent({key: 'ArrowRight', keyCode: 39}))).toBe(false);
- select(editor, 6);
- expect(run(editor, DELETE_WORD_COMMAND, false)).toBe(false);
- expect(run(editor, DELETE_WORD_COMMAND, true)).toBe(false);
- platform.apple = true;
- const wordMove = keyEvent({altKey: true});
- run(editor, KEY_DOWN_COMMAND, wordMove);
- expect(wordMove.preventDefault).not.toHaveBeenCalled();
- expect(snapshot(editor).selection).toEqual({anchor: 6, focus: 6});
- const payload = {dataTransfer: {getData: () => 'x\ny'}} as unknown as InputEvent;
- expect(run(editor, CONTROLLED_TEXT_INSERTION_COMMAND, payload)).toBe(false);
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', wrappers: 0});
- });
-
- it('continues quotes under bio style flags', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> a', 3);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> ', selection: {anchor: 6, focus: 6}});
- });
-
- it('treats a fence as text under bio style flags, so every quoted line keeps its wrapper', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```\n> b\n> ```');
- expect(snapshot(editor)).toMatchObject({wrappers: 3, breaksInsideWrappers: 0});
- });
-
- it('continues the quote on and below a quoted fence under bio style flags', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```', 5);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\n> ', selection: {anchor: 8, focus: 8}, wrappers: 2});
- setComposer(editor, '> ```\n> b', 9);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\n> b\n> ', selection: {anchor: 12, focus: 12}, wrappers: 3});
- });
-
- it('removes only the marker below a quoted fence under bio style flags', () => {
- const editor = createHarness({flags: BIO_LIKE_FLAGS});
- setComposer(editor, '> ```\n> b', 8);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\nb', selection: {anchor: 6, focus: 6}, wrappers: 1});
- });
-});
-
-describe('formatting over hidden quote markers', () => {
- const LINK = 'https://fluxer.app';
-
- function wrap(editor: LexicalEditor, wrapper: string): void {
- update(editor, () => {
- $wrapComposerSelection(wrapper, wrapper);
- });
- }
-
- function wrappedFlags(editor: LexicalEditor, wrappers: ReadonlyArray<string>): Array<boolean> {
- return editor
- .getEditorState()
- .read(
- () => $queryComposerSelectionWrappers(wrappers.map((wrapper) => ({prefix: wrapper, suffix: wrapper}))).wrapped,
- {editor},
- );
- }
-
- function pasteLink(editor: LexicalEditor): boolean {
- return run(editor, PASTE_COMMAND, {
- clipboardData: {getData: (type: string) => (type === 'text/plain' ? LINK : '')},
- preventDefault: vi.fn(),
- } as unknown as ClipboardEvent);
- }
-
- it.each<[string, number, number, string, string, number, number, number]>([
- ['> hello', 0, 7, '**', '> **hello**', 4, 9, 1],
- ['> hello', 7, 0, '**', '> **hello**', 9, 4, 1],
- ['> hello', 0, 7, '`', '> `hello`', 3, 8, 1],
- ['> a\n> b', 4, 7, '~~', '> a\n> ~~b~~', 8, 9, 2],
- ['> a\n> b', 2, 4, '**', '> **a\n> **b', 4, 8, 2],
- ])('wraps only the content of %j selected from %i to %i with %j', (text, anchor, focus, wrapper, wire, expectedAnchor, expectedFocus, wrappers) => {
- const editor = createFormattingHarness();
- setComposer(editor, text, anchor, focus);
- wrap(editor, wrapper);
- expect(snapshot(editor)).toMatchObject({
- wire,
- selection: {anchor: expectedAnchor, focus: expectedFocus},
- wrappers,
- });
- });
-
- it.each<[string, string]>([
- ['> *hi*', '*'],
- ['> **hi**', '**'],
- ])('reports %j selected from its line start as wrapped in %j', (text, wrapper) => {
- const editor = createFormattingHarness();
- setComposer(editor, text, 0, text.length);
- expect(wrappedFlags(editor, [wrapper])).toEqual([true]);
- });
-
- it('removes the bold of a quote line selected from its line start', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> **hi**', 0, 8);
- wrap(editor, '**');
- expect(snapshot(editor)).toMatchObject({wire: '> hi', selection: {anchor: 2, focus: 4}, wrappers: 1});
- });
-
- it('bolds only the content on Ctrl+B over a select all', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> hello', 0, 7);
- run(editor, KEY_DOWN_COMMAND, keyEvent({key: 'b', ctrlKey: true}));
- expect(snapshot(editor).wire).toBe('> **hello**');
- });
-
- it('leaves the text alone on Ctrl+B over a range that covers only the marker', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> hello', 2, 0);
- run(editor, KEY_DOWN_COMMAND, keyEvent({key: 'b', ctrlKey: true}));
- expect(snapshot(editor).wire).toBe('> hello');
- });
-
- it.each<[number, number]>([
- [2, 7],
- [0, 7],
- ])('declines the code block toggle over quote lines selected from %i to %i', (anchor, focus) => {
- const editor = createFormattingHarness();
- setComposer(editor, '> a\n> b', anchor, focus);
- expect(wrappedFlags(editor, ['`'])).toEqual([false]);
- wrap(editor, '`');
- expect(snapshot(editor)).toMatchObject({wire: '> a\n> b', selection: {anchor, focus}, wrappers: 2});
- });
-
- it('indents the code of selected quoted fence lines and unindents it again', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> ```\n> a\n> b\n> ```', 6, 13);
- expect(run(editor, KEY_TAB_COMMAND, keyEvent({key: 'Tab'}))).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\n> \ta\n> \tb\n> ```', selection: {anchor: 9, focus: 15}});
- expect(run(editor, KEY_TAB_COMMAND, keyEvent({key: 'Tab', shiftKey: true}))).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\n> a\n> b\n> ```', selection: {anchor: 8, focus: 13}});
- });
-
- it('unindents the code of a selected indented quoted fence line', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> ```\n> \tcode\n> ```', 6, 13);
- expect(run(editor, KEY_TAB_COMMAND, keyEvent({key: 'Tab', shiftKey: true}))).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> ```\n> code\n> ```', selection: {anchor: 8, focus: 12}});
- });
-
- it.each<[string, number, number, string, number]>([
- ['> hello world', 0, 13, `> [hello world](<${LINK}>)`, 37],
- ['intro\n> hello world', 6, 19, `intro\n> [hello world](<${LINK}>)`, 43],
- ['> hello world', 13, 8, `> hello [world](<${LINK}>)`, 37],
- ])('keeps the quote outside a link label pasted over %j from %i to %i', (text, anchor, focus, wire, caret) => {
- const editor = createFormattingHarness();
- setComposer(editor, text, anchor, focus);
- expect(pasteLink(editor)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire, selection: {anchor: caret, focus: caret}, wrappers: 1});
- });
-
- it('declines a link paste over a range that covers only the marker', () => {
- const editor = createFormattingHarness();
- setComposer(editor, '> hello world', 2, 0);
- expect(pasteLink(editor)).toBe(false);
- expect(snapshot(editor).wire).toBe('> hello world');
- });
-
- it('formats the literal "> " without ALLOW_BLOCKQUOTES', () => {
- const editor = createFormattingHarness(NO_BLOCKQUOTE_FLAGS);
- setComposer(editor, '> a', 0, 3);
- wrap(editor, '**');
- expect(snapshot(editor)).toMatchObject({wire: '**> a**', selection: {anchor: 2, focus: 5}, wrappers: 0});
- setComposer(editor, '> a\n> b', 0, 7);
- wrap(editor, '`');
- expect(snapshot(editor).wire).toBe('```\n> a\n> b\n```');
- });
-});
-
-describe('nodes inside quote lines', () => {
- it('converts emoji shortcodes inside a quote line', () => {
- const editor = createHarness();
- disposers.push(
- registerComposerEmojiShortcode(editor, (name) =>
- name === 'blob' ? {kind: 'custom', emojiId: '1', animated: false, display: ':blob:', wire: '<:blob:1>'} : null,
- ),
- );
- setComposer(editor, '> hi :blob:', 11);
- expect(snapshot(editor)).toMatchObject({wire: '> hi <:blob:1>', wrappers: 1});
- const emojiInWrapper = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- return $isComposerBlockquoteLineNode(wrapper) && wrapper.getChildren().some($isComposerCustomEmojiNode);
- },
- {editor},
- );
- expect(emojiInWrapper).toBe(true);
- });
-
- it('continues the quote when a mention display name holds a fence', () => {
- const editor = createHarness();
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@a```b',
- actualText: '<@1>',
- start: 2,
- end: 8,
- };
- setComposer(editor, '> @a```b', 8, 8, [segment]);
- expect(run(editor, INSERT_LINE_BREAK_COMMAND, false)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> <@1>\n> ', selection: {anchor: 11, focus: 11}, wrappers: 2});
- });
-
- it('removes the marker below a mention display name holding a fence', () => {
- const editor = createHarness();
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@a```b',
- actualText: '<@1>',
- start: 2,
- end: 8,
- };
- setComposer(editor, '> @a```b\n> q', 11, 11, [segment]);
- expect(run(editor, DELETE_CHARACTER_COMMAND, true)).toBe(true);
- expect(snapshot(editor)).toMatchObject({wire: '> <@1>\nq', selection: {anchor: 9, focus: 9}, wrappers: 1});
- });
-
- it('projects a standard emoji inside a quote line and copies its surrogate', () => {
- const editor = createHarness();
- disposers.push(registerComposerEmojiShortcode(editor, (name) => (name === 'grinning' ? GRINNING : null)));
- setComposer(editor, '> :grinning:', 12, 12);
- const projection = editor.getEditorState().read(() => $projectComposer(), {editor});
- expect(projection).toEqual({
- display: '> :grinning:',
- wire: '> 😀',
- segments: [{type: 'emoji', id: 'grinning', displayText: ':grinning:', actualText: '😀', start: 2, end: 12}],
- });
- select(editor, 2, 12);
- const copied = editor.getEditorState().read(() => $getComposerClipboardSelection(), {editor});
- expect(copied).toMatchObject({display: ':grinning:', textPlain: '😀'});
- setComposer(editor, projection.display, undefined, undefined, projection.segments);
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toEqual(projection);
- const emojiInWrapper = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- return $isComposerBlockquoteLineNode(wrapper) && wrapper.getChildren().some($isComposerStandardEmojiNode);
- },
- {editor},
- );
- expect(emojiInWrapper).toBe(true);
- });
-
- it.each<[string, string]>([
- ['zero', '0️⃣'],
- ['one', '1️⃣'],
- ['two', '2️⃣'],
- ['three', '3️⃣'],
- ['four', '4️⃣'],
- ['five', '5️⃣'],
- ['six', '6️⃣'],
- ['seven', '7️⃣'],
- ['eight', '8️⃣'],
- ['nine', '9️⃣'],
- ['hash', '#️⃣'],
- ['asterisk', '*️⃣'],
- ])('keeps the keycap emoji :%s: an emoji when it is copied into the middle of a quoted word', (name, surrogate) => {
- const editor = createHarness();
- const display = `:${name}:`;
- disposers.push(
- registerComposerEmojiShortcode(editor, (shortcode) =>
- shortcode === name ? {kind: 'standard', name, surrogate, url: null, display} : null,
- ),
- );
- setComposer(editor, `> ${display} word`, 2, 2 + display.length);
- const copied = editor.getEditorState().read(() => $getComposerClipboardSelection(), {editor});
- expect(copied).toMatchObject({
- display,
- textPlain: surrogate,
- segments: [{type: 'emoji', displayText: display, actualText: surrogate, start: 0, end: display.length}],
- });
- select(editor, display.length + 5);
- update(editor, () => {
- $insertComposerClipboardSlice(copied!, false);
- });
- expect(snapshot(editor)).toMatchObject({wire: `> ${surrogate} wo${surrogate}rd`, wrappers: 1});
- const emojiWires = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- return $isComposerBlockquoteLineNode(wrapper)
- ? wrapper
- .getChildren()
- .filter($isComposerStandardEmojiNode)
- .map((node) => node.getWireText())
- : [];
- },
- {editor},
- );
- expect(emojiWires).toEqual([surrogate, surrogate]);
- });
-
- it.each([
- '*😀*',
- '😀<@1>',
- '`😀`',
- '1😀',
- '#😀',
- ':one:',
- ])('keeps an emoji segment whose wire %j is shaped like markup as text', (actualText) => {
- const editor = createHarness();
- setComposer(editor, '> :x:', undefined, undefined, [
- {type: 'emoji', id: 'x', displayText: ':x:', actualText, start: 2, end: 5},
- ]);
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toEqual({
- display: '> :x:',
- wire: '> :x:',
- segments: [],
- });
- });
-
- it('projects a mention inside a quote line and survives a round trip', () => {
- const editor = createHarness();
- const segment: MentionSegment = {
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start: 2,
- end: 7,
- };
- setComposer(editor, '> @name', 7, 7, [segment]);
- const projection = editor.getEditorState().read(() => $projectComposer(), {editor});
- expect(projection).toEqual({display: '> @name', wire: '> <@1>', segments: [segment]});
- const mentionInWrapper = editor.getEditorState().read(
- () => {
- const paragraph = $getRoot().getFirstChild();
- const wrapper = $isElementNode(paragraph) ? paragraph.getFirstChild() : null;
- return $isComposerBlockquoteLineNode(wrapper) && wrapper.getChildren().some($isComposerMentionNode);
- },
- {editor},
- );
- expect(mentionInWrapper).toBe(true);
- setComposer(editor, projection.display, undefined, undefined, projection.segments);
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toEqual(projection);
- expect(snapshot(editor).wrappers).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerCodeIndent.test.ts b/fluxer_app/src/features/lexical/composer/ComposerCodeIndent.test.ts
deleted file mode 100644
index 36e345b28..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerCodeIndent.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {registerComposerCodeIndent} from '@app/features/lexical/composer/ComposerCodeIndent';
-import {
- $getComposerDisplayText,
- $replaceComposerRange,
- $selectComposerRange,
-} from '@app/features/lexical/composer/composerOffsets';
-import {ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {createEditor, KEY_TAB_COMMAND} from 'lexical';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-
-describe('registerComposerCodeIndent', () => {
- it('indents a block opened after a mention whose name holds a backtick', () => {
- const editor = createEditor({
- namespace: 'composer-code-indent-test',
- nodes: [ComposerMentionNode],
- onError: (error) => {
- throw error;
- },
- });
- registerComposerCodeIndent(editor, {current: false});
- editor.update(
- () => {
- $replaceComposerRange(
- 0,
- 0,
- {kind: 'mention', mentionType: 'user', id: '1', display: '@`bob', wire: '<@1>'},
- {trailing: false},
- );
- $replaceComposerRange(5, 5, {kind: 'text', text: ' hi ```js\ncode'}, {leading: false, trailing: false});
- $selectComposerRange(19, 19);
- },
- {discrete: true},
- );
- const event = Object.assign(new Event('keydown', {cancelable: true}), {shiftKey: false}) as KeyboardEvent;
- expect(editor.dispatchCommand(KEY_TAB_COMMAND, event)).toBe(true);
- expect(editor.read(() => $getComposerDisplayText())).toBe('@`bob hi ```js\ncode\t');
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerCrossEditorDrop.test.ts b/fluxer_app/src/features/lexical/composer/ComposerCrossEditorDrop.test.ts
deleted file mode 100644
index aed5ee49e..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerCrossEditorDrop.test.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {registerComposerBlockquote} from '@app/features/lexical/composer/ComposerBlockquote';
-import {registerComposerClipboardCommands} from '@app/features/lexical/composer/ComposerClipboard';
-import {registerComposerMarkdownHighlight} from '@app/features/lexical/composer/ComposerMarkdownHighlight';
-import {
- $hydrateComposerFromDraft,
- $projectComposer,
- type ComposerProjection,
-} from '@app/features/lexical/composer/ComposerSerialization';
-import {$selectComposerRange} from '@app/features/lexical/composer/composerOffsets';
-import {DEFAULT_COMPOSER_MARKDOWN_FLAGS} from '@app/features/lexical/composer/markdownSpans';
-import {ComposerBlockquoteLineNode} from '@app/features/lexical/composer/nodes/ComposerBlockquoteLineNode';
-import {ComposerBlockquoteMarkerNode} from '@app/features/lexical/composer/nodes/ComposerBlockquoteMarkerNode';
-import {ComposerCommandNode} from '@app/features/lexical/composer/nodes/ComposerCommandNode';
-import {ComposerCustomEmojiNode} from '@app/features/lexical/composer/nodes/ComposerCustomEmojiNode';
-import {ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {ComposerPlainSegmentNode} from '@app/features/lexical/composer/nodes/ComposerPlainSegmentNode';
-import {ComposerStandardEmojiNode} from '@app/features/lexical/composer/nodes/ComposerStandardEmojiNode';
-import {SlashOptionalHintNode} from '@app/features/lexical/composer/nodes/SlashOptionalHintNode';
-import {SlashSeparatorNode} from '@app/features/lexical/composer/nodes/SlashSeparatorNode';
-import {SlashSlotNode} from '@app/features/lexical/composer/nodes/SlashSlotNode';
-import {SlashSlotPlaceholderNode} from '@app/features/lexical/composer/nodes/SlashSlotPlaceholderNode';
-import {SyntaxMarkerNode} from '@app/features/lexical/composer/nodes/SyntaxMarkerNode';
-import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
-import {
- $getSelection,
- $isRangeSelection,
- COMMAND_PRIORITY_EDITOR,
- createEditor,
- DRAGSTART_COMMAND,
- DROP_COMMAND,
- type LexicalEditor,
- REMOVE_TEXT_COMMAND,
-} from 'lexical';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-vi.hoisted(() => {
- if (!('getTargetRanges' in InputEvent.prototype)) {
- Object.defineProperty(InputEvent.prototype, 'getTargetRanges', {configurable: true, value: () => []});
- }
-});
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/SlashOptionalHintPill', () => ({SlashOptionalHintPill: () => null}));
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-const dropOffset = vi.hoisted(() => ({value: null as number | null}));
-
-vi.mock('@app/features/lexical/composer/composerOffsets', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@app/features/lexical/composer/composerOffsets')>();
- return {...actual, $getComposerDropOffset: () => dropOffset.value};
-});
-
-const NODES = [
- ComposerMentionNode,
- ComposerCustomEmojiNode,
- ComposerStandardEmojiNode,
- ComposerPlainSegmentNode,
- ComposerCommandNode,
- SlashSlotNode,
- SlashSlotPlaceholderNode,
- SlashSeparatorNode,
- SlashOptionalHintNode,
- SyntaxMarkerNode,
- ComposerBlockquoteLineNode,
- ComposerBlockquoteMarkerNode,
-];
-
-const LEXICAL_DRAG_MIME = 'application/x-lexical-drag';
-
-interface MountedComposer {
- editor: LexicalEditor;
- element: HTMLDivElement;
- removals: {count: number};
-}
-
-const disposers: Array<() => void> = [];
-
-afterEach(() => {
- while (disposers.length > 0) {
- disposers.pop()!();
- }
- dropOffset.value = null;
- document.body.replaceChildren();
-});
-
-function mount(
- text: string,
- anchor: number,
- focus: number,
- segments: ReadonlyArray<MentionSegment> = [],
-): MountedComposer {
- const element = document.createElement('div');
- element.contentEditable = 'true';
- document.body.append(element);
- const editor = createEditor({
- namespace: 'composer-cross-editor-drop-test',
- nodes: NODES,
- onError: (error) => {
- throw error;
- },
- });
- editor.setRootElement(element);
- const removals = {count: 0};
- disposers.push(
- () => editor.setRootElement(null),
- registerComposerMarkdownHighlight(editor, DEFAULT_COMPOSER_MARKDOWN_FLAGS, false),
- registerComposerBlockquote(editor, DEFAULT_COMPOSER_MARKDOWN_FLAGS),
- registerComposerClipboardCommands(editor, {
- getPlainText: () => false,
- isEditable: () => true,
- getMarkdownParserFlags: () => DEFAULT_COMPOSER_MARKDOWN_FLAGS,
- }),
- editor.registerCommand(
- REMOVE_TEXT_COMMAND,
- () => {
- const selection = $getSelection();
- if (!$isRangeSelection(selection)) {
- return false;
- }
- removals.count += 1;
- selection.removeText();
- return true;
- },
- COMMAND_PRIORITY_EDITOR,
- ),
- );
- editor.update(
- () => {
- $hydrateComposerFromDraft(text, segments);
- $selectComposerRange(anchor, focus);
- },
- {discrete: true},
- );
- return {editor, element, removals};
-}
-
-function projection(composer: MountedComposer): ComposerProjection {
- return composer.editor.read(() => $projectComposer());
-}
-
-function dragStart(source: MountedComposer, moved: string): Record<string, string> {
- const data: Record<string, string> = {};
- const dataTransfer = {
- getData: (type: string) => data[type] ?? '',
- setData: (type: string, value: string) => {
- data[type] = value;
- },
- } as unknown as DataTransfer;
- source.editor.update(
- () => {
- source.editor.dispatchCommand(DRAGSTART_COMMAND, {dataTransfer} as unknown as DragEvent);
- },
- {discrete: true},
- );
- data['text/plain'] = moved;
- data[LEXICAL_DRAG_MIME] = JSON.stringify({editorKey: source.editor.getKey()});
- return data;
-}
-
-function drop(target: MountedComposer, data: Record<string, string>, offset: number): boolean {
- dropOffset.value = offset;
- const event = {
- clientX: 0,
- clientY: 0,
- dataTransfer: {getData: (type: string) => data[type] ?? ''} as unknown as DataTransfer,
- preventDefault: vi.fn(),
- };
- let handled = false;
- target.editor.update(
- () => {
- handled = target.editor.dispatchCommand(DROP_COMMAND, event as unknown as DragEvent);
- },
- {discrete: true},
- );
- return handled && event.preventDefault.mock.calls.length > 0;
-}
-
-describe('drops carrying another composer as their drag source', () => {
- it('continues the quote in the target and removes the dragged range from the source once', () => {
- const target = mount('> alpha', 2, 2);
- const source = mount('one\ntwo keep', 0, 7);
- expect(drop(target, dragStart(source, 'one\ntwo'), 2)).toBe(true);
- expect(projection(target).wire).toBe('> one\n> twoalpha');
- expect(projection(source).wire).toBe(' keep');
- expect(source.removals.count).toBe(1);
- expect(target.removals.count).toBe(0);
- });
-
- it('keeps a mention dragged out of another composer a mention', () => {
- const target = mount('> quoted', 2, 2);
- const source = mount('hi @name', 3, 8, [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 3, end: 8},
- ]);
- expect(drop(target, dragStart(source, '@name'), 2)).toBe(true);
- expect(projection(target).wire).toBe('> <@1>quoted');
- expect(projection(target).segments).toMatchObject([{type: 'user', id: '1', start: 2, end: 7}]);
- expect(projection(source).wire).toBe('hi ');
- expect(source.removals.count).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerEnter.test.ts b/fluxer_app/src/features/lexical/composer/ComposerEnter.test.ts
deleted file mode 100644
index e6e54436e..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerEnter.test.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import assert from 'node:assert/strict';
-import {registerComposerEnter} from '@app/features/lexical/composer/ComposerEnter';
-import {$replaceComposerRange, $selectComposerRange} from '@app/features/lexical/composer/composerOffsets';
-import {ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {ComposerPlainSegmentNode} from '@app/features/lexical/composer/nodes/ComposerPlainSegmentNode';
-import {
- $createSlashSlotNode,
- $isSlashSlotNode,
- SlashSlotNode,
-} from '@app/features/lexical/composer/nodes/SlashSlotNode';
-import {SlashSlotPlaceholderNode} from '@app/features/lexical/composer/nodes/SlashSlotPlaceholderNode';
-import {$getRoot, $isElementNode, $setSelection, createEditor, KEY_ENTER_COMMAND, type LexicalEditor} from 'lexical';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-interface EnterOptions {
- modifiers?: Partial<Pick<KeyboardEvent, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'>>;
- submitOnEnter?: boolean;
- typeaheadActive?: boolean;
-}
-
-const NEWLINE = {handled: false, prevented: false, sent: 0};
-const SENT = {handled: true, prevented: true, sent: 1};
-
-function createComposer(seed: () => void): LexicalEditor {
- const editor = createEditor({
- namespace: 'composer-enter-test',
- nodes: [ComposerMentionNode, ComposerPlainSegmentNode, SlashSlotNode, SlashSlotPlaceholderNode],
- onError: (error) => {
- throw error;
- },
- });
- editor.update(seed, {discrete: true});
- return editor;
-}
-
-function typed(text: string, anchor: number, focus = anchor): LexicalEditor {
- return createComposer(() => {
- $replaceComposerRange(0, 0, {kind: 'text', text}, {leading: false, trailing: false});
- $selectComposerRange(anchor, focus);
- });
-}
-
-function typedWithRequiredSlot(text: string, offset: number): LexicalEditor {
- return createComposer(() => {
- $replaceComposerRange(0, 0, {kind: 'text', text}, {leading: false, trailing: false});
- const slot = $createSlashSlotNode('value', 'string', true);
- const paragraph = $getRoot().getFirstChildOrThrow();
- assert($isElementNode(paragraph), 'Expected composer paragraph');
- paragraph.append(slot);
- slot.ensurePlaceholder();
- $selectComposerRange(offset, offset);
- });
-}
-
-function slotValidity(editor: LexicalEditor): string {
- return editor.read(() => {
- const paragraph = $getRoot().getFirstChildOrThrow();
- assert($isElementNode(paragraph), 'Expected composer paragraph');
- const slot = paragraph.getLastChildOrThrow();
- assert($isSlashSlotNode(slot), 'Expected required slash command slot');
- return slot.getValidity();
- });
-}
-
-function pressEnter(
- editor: LexicalEditor,
- {modifiers = {}, submitOnEnter = true, typeaheadActive = false}: EnterOptions = {},
-): typeof SENT {
- const onEnter = vi.fn();
- registerComposerEnter(editor, {
- typeaheadActiveState: {current: typeaheadActive},
- getSubmitOnEnter: () => submitOnEnter,
- getOnEnter: () => onEnter,
- });
- const event = Object.assign(
- new Event('keydown', {cancelable: true}),
- {altKey: false, ctrlKey: false, metaKey: false, shiftKey: false},
- modifiers,
- ) as KeyboardEvent;
- const handled = editor.dispatchCommand(KEY_ENTER_COMMAND, event);
- return {handled, prevented: event.defaultPrevented, sent: onEnter.mock.calls.length};
-}
-
-describe('registerComposerEnter', () => {
- it.each([
- ['after a lone opening fence', '```\ncode', 8],
- ['on the empty line after an opening fence', '```\n', 4],
- ['right before the closing fence', '```\ncode\n```', 9],
- ])('inserts a newline %s without preventing the key', (_label, text, offset) => {
- expect(pressEnter(typed(text, offset))).toEqual(NEWLINE);
- });
-
- it('sends after the closing fence', () => {
- expect(pressEnter(typed('```\ncode\n```', 12))).toEqual(SENT);
- });
-
- it('still sends plain text', () => {
- expect(pressEnter(typed('hello', 5))).toEqual(SENT);
- });
-
- it('still sends on Ctrl+Enter inside a block', () => {
- expect(pressEnter(typed('```\ncode', 8), {modifiers: {ctrlKey: true}})).toEqual(SENT);
- });
-
- it('still sends on Cmd+Enter inside a block', () => {
- expect(pressEnter(typed('```\ncode', 8), {modifiers: {metaKey: true}})).toEqual(SENT);
- });
-
- it('inserts a newline on Alt+Enter inside a block', () => {
- expect(pressEnter(typed('```\ncode', 8), {modifiers: {altKey: true}})).toEqual(NEWLINE);
- });
-
- it('still leaves Shift+Enter to the line break', () => {
- expect(pressEnter(typed('hello', 5), {modifiers: {shiftKey: true}})).toEqual(NEWLINE);
- });
-
- it('still leaves Shift+Enter to the line break inside a block', () => {
- expect(pressEnter(typed('```\ncode', 8), {modifiers: {shiftKey: true}})).toEqual(NEWLINE);
- });
-
- it('sends on a list item line that holds a fence', () => {
- expect(pressEnter(typed('- ```', 5))).toEqual(SENT);
- });
-
- it('sends in prose that holds an unmatched fence', () => {
- expect(pressEnter(typed('use ``` for code blocks', 23))).toEqual(SENT);
- });
-
- it('decides on the start of a backward selection inside a block', () => {
- expect(pressEnter(typed('```\ncode', 7, 5))).toEqual(NEWLINE);
- });
-
- it('sends when the selection starts before the opening fence', () => {
- expect(pressEnter(typed('```\ncode', 0, 8))).toEqual(SENT);
- });
-
- it('sends when nothing is selected', () => {
- const editor = createComposer(() => {
- $replaceComposerRange(0, 0, {kind: 'text', text: '```\ncode'}, {leading: false, trailing: false});
- $setSelection(null);
- });
- expect(pressEnter(editor)).toEqual(SENT);
- });
-
- it('still lets an open typeahead take Enter inside a block', () => {
- expect(pressEnter(typed('```\ncode', 8), {typeaheadActive: true})).toEqual(NEWLINE);
- });
-
- it('still inserts a newline on plain Enter when submit on Enter is off', () => {
- expect(pressEnter(typed('```\ncode', 8), {submitOnEnter: false})).toEqual(NEWLINE);
- });
-
- it('still sends on Ctrl+Enter inside a block when submit on Enter is off', () => {
- expect(pressEnter(typed('```\ncode', 8), {submitOnEnter: false, modifiers: {ctrlKey: true}})).toEqual(SENT);
- });
-
- it('inserts a newline inside a block without flagging an empty required slash slot', () => {
- const editor = typedWithRequiredSlot('```\ncode', 8);
- expect(pressEnter(editor)).toEqual(NEWLINE);
- expect(slotValidity(editor)).toBe('neutral');
- });
-
- it('still flags an empty required slash slot instead of sending outside a block', () => {
- const editor = typedWithRequiredSlot('hello', 5);
- expect(pressEnter(editor)).toEqual({handled: true, prevented: true, sent: 0});
- expect(slotValidity(editor)).toBe('invalid');
- });
-
- it.each([
- ['a mention', false],
- ['a plain text mention', true],
- ])('reads %s as filler so a backtick in its name cannot hide a fence', (_label, plainText) => {
- const editor = createComposer(() => {
- $replaceComposerRange(
- 0,
- 0,
- {kind: 'mention', mentionType: 'user', id: '1', display: '@`bob', wire: '<@1>'},
- {trailing: false},
- plainText,
- );
- $replaceComposerRange(5, 5, {kind: 'text', text: ' hi ```js'}, {leading: false, trailing: false});
- $selectComposerRange(14, 14);
- });
- expect(pressEnter(editor)).toEqual(NEWLINE);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerLinkPaste.test.ts b/fluxer_app/src/features/lexical/composer/ComposerLinkPaste.test.ts
deleted file mode 100644
index 6595d7a61..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerLinkPaste.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildMaskedLink,
- canWrapSelectionAsLink,
- parsePastedUrl,
- resolvePastedLinkInsertion,
-} from '@app/features/lexical/composer/ComposerLinkPaste';
-import {DEFAULT_COMPOSER_MARKDOWN_FLAGS} from '@app/features/lexical/composer/markdownSpans';
-import {MarkdownContext} from '@app/features/messaging/components/markdown/renderers/RendererTypes';
-import {getParserFlagsForContext} from '@app/features/messaging/utils/markdown/MarkdownParserFlags';
-import {ParserFlags} from '@app/features/messaging/utils/markdown/parser/Enums';
-import {describe, expect, it} from 'vitest';
-
-describe('parsePastedUrl', () => {
- it('accepts http and https urls', () => {
- expect(parsePastedUrl('https://fluxer.app/download')).toBe('https://fluxer.app/download');
- expect(parsePastedUrl(' http://example.test/a?b=c#d ')).toBe('http://example.test/a?b=c#d');
- });
-
- it('rejects non-web protocols', () => {
- for (const value of ['javascript:alert(1)', 'data:text/html,<b>x</b>', 'file:///etc/passwd', 'mailto:[email protected]']) {
- expect(parsePastedUrl(value)).toBeNull();
- }
- });
-
- it('rejects prose that merely contains a url', () => {
- expect(parsePastedUrl('see https://fluxer.app for more')).toBeNull();
- });
-
- it('rejects angle brackets that would break the masked link', () => {
- expect(parsePastedUrl('https://fluxer.app/<script>')).toBeNull();
- });
-
- it('rejects empty and oversized input', () => {
- expect(parsePastedUrl('')).toBeNull();
- expect(parsePastedUrl(null)).toBeNull();
- expect(parsePastedUrl(`https://fluxer.app/${'a'.repeat(4000)}`)).toBeNull();
- });
-});
-
-describe('canWrapSelectionAsLink', () => {
- it('accepts ordinary selected words', () => {
- expect(canWrapSelectionAsLink('the download page')).toBe(true);
- });
-
- it('rejects blank or multiline selections', () => {
- expect(canWrapSelectionAsLink(' ')).toBe(false);
- expect(canWrapSelectionAsLink('first\nsecond')).toBe(false);
- });
-
- it('rejects selections containing markdown link brackets', () => {
- expect(canWrapSelectionAsLink('already [linked]')).toBe(false);
- });
-
- it('rejects replacing a url with a url', () => {
- expect(canWrapSelectionAsLink('https://example.test')).toBe(false);
- });
-});
-
-describe('buildMaskedLink', () => {
- it('uses the escaped destination form so parentheses survive', () => {
- expect(buildMaskedLink('wiki', 'https://en.wikipedia.org/wiki/Foo_(bar)')).toBe(
- '[wiki](<https://en.wikipedia.org/wiki/Foo_(bar)>)',
- );
- });
-});
-
-describe('resolvePastedLinkInsertion', () => {
- it('wraps a selection when a bare url is pasted over it', () => {
- expect(resolvePastedLinkInsertion('https://fluxer.app/download', 'the download page')).toBe(
- '[the download page](<https://fluxer.app/download>)',
- );
- });
-
- it('wraps a message link the same way a plain url is wrapped', () => {
- const messageLink = 'https://fluxer.app/channels/1234567890/9876543210/1122334455';
- expect(resolvePastedLinkInsertion(messageLink, 'this message')).toBe(`[this message](<${messageLink}>)`);
- });
-
- it('declines when the pasted text is not a url', () => {
- expect(resolvePastedLinkInsertion('just some text', 'selected')).toBeNull();
- });
-
- it('declines when the selection cannot be wrapped', () => {
- expect(resolvePastedLinkInsertion('https://fluxer.app', ' ')).toBeNull();
- expect(resolvePastedLinkInsertion('https://fluxer.app', 'https://example.test')).toBeNull();
- });
-
- it('declines a non-web protocol so pasting cannot forge a link', () => {
- expect(resolvePastedLinkInsertion('javascript:alert(1)', 'click me')).toBeNull();
- });
-});
-
-describe('masked link support across composer surfaces', () => {
- const surfaces: Array<[string, number]> = [
- ['channel composer', DEFAULT_COMPOSER_MARKDOWN_FLAGS],
- ['message edit / forward', getParserFlagsForContext(MarkdownContext.STANDARD_WITH_JUMBO)],
- ['channel topic', getParserFlagsForContext(MarkdownContext.STANDARD_WITHOUT_JUMBO)],
- ['user bio', getParserFlagsForContext(MarkdownContext.RESTRICTED_USER_BIO)],
- ];
-
- it.each(surfaces)('%s allows masked links, so pasting a link must wrap', (_name, flags) => {
- expect(flags & ParserFlags.ALLOW_MASKED_LINKS).not.toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerSilentMessagePrefix.test.ts b/fluxer_app/src/features/lexical/composer/ComposerSilentMessagePrefix.test.ts
deleted file mode 100644
index 14c11b187..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerSilentMessagePrefix.test.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import assert from 'node:assert/strict';
-import {registerComposerMarkdownHighlight} from '@app/features/lexical/composer/ComposerMarkdownHighlight';
-import {$hydrateComposerFromDraft, $projectComposer} from '@app/features/lexical/composer/ComposerSerialization';
-import {$getComposerSelectionRange, $selectComposerRange} from '@app/features/lexical/composer/composerOffsets';
-import {
- computeMarkdownHighlightSpans,
- DEFAULT_COMPOSER_MARKDOWN_FLAGS,
- MarkdownHl,
- markSilentMessagePrefix,
-} from '@app/features/lexical/composer/markdownSpans';
-import {
- $isComposerMentionNode,
- ComposerMentionNode,
- ComposerMentionPresentation,
-} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {SyntaxMarkerNode} from '@app/features/lexical/composer/nodes/SyntaxMarkerNode';
-import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
-import {
- $createParagraphNode,
- $createTextNode,
- $getRoot,
- $getSelection,
- $isElementNode,
- $isTextNode,
- createEditor,
- type LexicalEditor,
- type RangeSelection,
-} from 'lexical';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-const SILENT_STYLE = 'color:var(--markup-mention-text);font-weight:500';
-
-function createComposer(silentMessagePrefix: boolean): {editor: LexicalEditor; unregister: () => void} {
- const editor = createEditor({
- namespace: 'test',
- nodes: [ComposerMentionNode, SyntaxMarkerNode],
- onError: (error) => {
- throw error;
- },
- });
- const unregister = registerComposerMarkdownHighlight(editor, DEFAULT_COMPOSER_MARKDOWN_FLAGS, silentMessagePrefix);
- return {editor, unregister};
-}
-
-function hydrate(editor: LexicalEditor, display: string, segments: Array<MentionSegment> = []): void {
- editor.update(() => $hydrateComposerFromDraft(display, segments), {discrete: true});
-}
-
-function edit(editor: LexicalEditor, start: number, end: number, text: string): void {
- editor.update(
- () => {
- $selectComposerRange(start, end);
- ($getSelection() as RangeSelection).insertText(text);
- },
- {discrete: true},
- );
-}
-
-function readLines(editor: LexicalEditor): Array<Array<[string, string] | string>> {
- return editor.getEditorState().read(
- () =>
- $getRoot()
- .getChildren()
- .map((block) =>
- $isElementNode(block)
- ? block
- .getChildren()
- .map((node) => ($isTextNode(node) ? [node.getTextContent(), node.getStyle()] : node.getType()))
- : [],
- ),
- {editor},
- );
-}
-
-function readSelection(editor: LexicalEditor): {start: number; end: number} | null {
- return editor.getEditorState().read(() => $getComposerSelectionRange(), {editor});
-}
-
-describe('markSilentMessagePrefix', () => {
- it('marks @silent at the start of the message', () => {
- const source = '@silent hello';
- expect(markSilentMessagePrefix(computeMarkdownHighlightSpans(source), source)).toEqual([
- {start: 0, end: 7, role: 'content', format: MarkdownHl.silent},
- {start: 7, end: 13, role: 'content', format: MarkdownHl.none},
- ]);
- });
-
- it('marks @silent on its own', () => {
- const source = '@silent';
- expect(markSilentMessagePrefix(computeMarkdownHighlightSpans(source), source)).toEqual([
- {start: 0, end: 7, role: 'content', format: MarkdownHl.silent},
- ]);
- });
-
- it('marks @silent after leading whitespace', () => {
- const source = ' @silent hi';
- expect(markSilentMessagePrefix(computeMarkdownHighlightSpans(source), source)).toEqual([
- {start: 0, end: 2, role: 'content', format: MarkdownHl.none},
- {start: 2, end: 9, role: 'content', format: MarkdownHl.silent},
- {start: 9, end: 12, role: 'content', format: MarkdownHl.none},
- ]);
- });
-
- it('marks @silent before a line break', () => {
- const source = '@silent\nhello';
- expect(markSilentMessagePrefix(computeMarkdownHighlightSpans(source), source)).toEqual([
- {start: 0, end: 7, role: 'content', format: MarkdownHl.silent},
- {start: 7, end: 13, role: 'content', format: MarkdownHl.none},
- ]);
- });
-
- it('keeps markdown formats after @silent', () => {
- const source = '@silent **hi**';
- expect(markSilentMessagePrefix(computeMarkdownHighlightSpans(source), source)).toEqual([
- {start: 0, end: 7, role: 'content', format: MarkdownHl.silent},
- {start: 7, end: 8, role: 'content', format: MarkdownHl.none},
- {start: 8, end: 10, role: 'marker', format: MarkdownHl.bold},
- {start: 10, end: 12, role: 'content', format: MarkdownHl.bold},
- {start: 12, end: 14, role: 'marker', format: MarkdownHl.bold},
- ]);
- });
-
- it('adds the silent bit to every span the token overlaps', () => {
- expect(
- markSilentMessagePrefix(
- [
- {start: 0, end: 3, role: 'content', format: MarkdownHl.none},
- {start: 3, end: 10, role: 'content', format: MarkdownHl.bold},
- ],
- '@silent hi',
- ),
- ).toEqual([
- {start: 0, end: 3, role: 'content', format: MarkdownHl.silent},
- {start: 3, end: 7, role: 'content', format: MarkdownHl.bold | MarkdownHl.silent},
- {start: 7, end: 10, role: 'content', format: MarkdownHl.bold},
- ]);
- });
-
- it.each(['@silently hello', '@Silent hello', 'hello @silent', ''])('returns the spans unchanged for %j', (source) => {
- const spans = computeMarkdownHighlightSpans(source);
- expect(markSilentMessagePrefix(spans, source)).toBe(spans);
- });
-});
-
-describe('registerComposerMarkdownHighlight with silentMessagePrefix', () => {
- it('styles @silent at the start of the message without changing what is sent', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '@silent hello');
- expect(readLines(editor)).toEqual([
- [
- ['@silent', SILENT_STYLE],
- [' hello', ''],
- ],
- ]);
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toEqual({
- display: '@silent hello',
- segments: [],
- wire: '@silent hello',
- });
- });
-
- it('styles @silent on its own', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '@silent');
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE]]]);
- });
-
- it('styles @silent before a line break', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '@silent\nhello');
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE], 'linebreak', ['hello', '']]]);
- });
-
- it('styles @silent after leading whitespace', () => {
- const {editor} = createComposer(true);
- hydrate(editor, ' @silent hello');
- expect(readLines(editor)).toEqual([
- [
- [' ', ''],
- ['@silent', SILENT_STYLE],
- [' hello', ''],
- ],
- ]);
- });
-
- it('styles @silent after a leading line break', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '\n@silent hello');
- expect(readLines(editor)).toEqual([['linebreak', ['@silent', SILENT_STYLE], [' hello', '']]]);
- });
-
- it('leaves @silent unstyled when the prefix is off', () => {
- const {editor} = createComposer(false);
- hydrate(editor, '@silent hello');
- expect(readLines(editor)).toEqual([[['@silent hello', '']]]);
- });
-
- it('leaves @silent unstyled when it is not at the start', () => {
- const {editor} = createComposer(true);
- hydrate(editor, 'hello @silent');
- expect(readLines(editor)).toEqual([[['hello @silent', '']]]);
- });
-
- it('styles only the first paragraph', () => {
- const {editor} = createComposer(true);
- editor.update(
- () => {
- $getRoot()
- .clear()
- .append(
- $createParagraphNode().append($createTextNode('@silent hi')),
- $createParagraphNode().append($createTextNode('@silent hi')),
- );
- },
- {discrete: true},
- );
- expect(readLines(editor)).toEqual([
- [
- ['@silent', SILENT_STYLE],
- [' hi', ''],
- ],
- [['@silent hi', '']],
- ]);
- });
-
- it('restyles the token as it is typed, broken and repaired', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '@silen');
- edit(editor, 6, 6, 't');
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE]]]);
- expect(readSelection(editor)).toEqual({start: 7, end: 7});
- edit(editor, 7, 7, 'l');
- expect(readLines(editor)).toEqual([[['@silentl', '']]]);
- expect(readSelection(editor)).toEqual({start: 8, end: 8});
- edit(editor, 7, 8, '');
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE]]]);
- expect(readSelection(editor)).toEqual({start: 7, end: 7});
- });
-
- it('styles @silent typed in front of existing text', () => {
- const {editor} = createComposer(true);
- hydrate(editor, 'hello');
- edit(editor, 0, 0, '@silent ');
- expect(readLines(editor)).toEqual([
- [
- ['@silent', SILENT_STYLE],
- [' hello', ''],
- ],
- ]);
- expect(readSelection(editor)).toEqual({start: 8, end: 8});
- });
-
- it('keeps an autocompleted @everyone mention after @silent', () => {
- const segment: MentionSegment = {
- type: 'special',
- id: '@everyone',
- displayText: '@everyone',
- actualText: '@everyone',
- start: 8,
- end: 17,
- };
- const {editor} = createComposer(true);
- hydrate(editor, '@silent @everyone', [segment]);
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE], [' ', ''], 'composer-mention']]);
- expect(editor.getEditorState().read(() => $projectComposer(), {editor})).toEqual({
- display: '@silent @everyone',
- segments: [segment],
- wire: '@silent @everyone',
- });
- });
-
- it('keeps a user mention after @silent as a plain pill', () => {
- const {editor} = createComposer(true);
- hydrate(editor, '@silent @name', [
- {type: 'user', id: '123', displayText: '@name', actualText: '<@123>', start: 8, end: 13},
- ]);
- expect(readLines(editor)).toEqual([[['@silent', SILENT_STYLE], [' ', ''], 'composer-mention']]);
- const mention = editor.getEditorState().read(() => {
- const paragraph = $getRoot().getFirstChildOrThrow();
- assert($isElementNode(paragraph), 'Expected composer paragraph');
- const pill = paragraph.getLastChild();
- return $isComposerMentionNode(pill) ? {literal: pill.isLiteral(), presentation: pill.getPresentation()} : null;
- });
- expect(mention).toEqual({literal: false, presentation: ComposerMentionPresentation.none});
- });
-
- it('removes the style when the prefix is switched off', () => {
- const {editor, unregister} = createComposer(true);
- hydrate(editor, '@silent hello');
- unregister();
- registerComposerMarkdownHighlight(editor, DEFAULT_COMPOSER_MARKDOWN_FLAGS, false);
- editor.update(
- () => {
- for (const node of $getRoot().getAllTextNodes()) {
- node.markDirty();
- }
- },
- {discrete: true},
- );
- expect(readLines(editor)).toEqual([[['@silent hello', '']]]);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/ComposerSpecialMention.test.ts b/fluxer_app/src/features/lexical/composer/ComposerSpecialMention.test.ts
deleted file mode 100644
index b65eaa3e8..000000000
--- a/fluxer_app/src/features/lexical/composer/ComposerSpecialMention.test.ts
+++ /dev/null
@@ -1,681 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import assert from 'node:assert/strict';
-import {
- $getComposerClipboardSelection,
- $insertComposerClipboardSlice,
-} from '@app/features/lexical/composer/ComposerClipboard';
-import {resetComposerHistory} from '@app/features/lexical/composer/ComposerHistory';
-import {registerComposerMarkdownHighlight} from '@app/features/lexical/composer/ComposerMarkdownHighlight';
-import {registerComposerPlainText} from '@app/features/lexical/composer/ComposerPlainText';
-import {
- $hydrateComposerFromDraft,
- $projectComposer,
- isValidComposerSegment,
-} from '@app/features/lexical/composer/ComposerSerialization';
-import {
- COMPOSER_RESCAN_TAG,
- registerComposerSpecialMention,
-} from '@app/features/lexical/composer/ComposerSpecialMention';
-import {
- $captureSelectionOffsets,
- $replaceComposerRange,
- $selectComposerOffset,
- $selectComposerRange,
-} from '@app/features/lexical/composer/composerOffsets';
-import {
- $createComposerCommandNode,
- ComposerCommandNode,
-} from '@app/features/lexical/composer/nodes/ComposerCommandNode';
-import {ComposerCustomEmojiNode} from '@app/features/lexical/composer/nodes/ComposerCustomEmojiNode';
-import {$isComposerMentionNode, ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {ComposerPlainSegmentNode} from '@app/features/lexical/composer/nodes/ComposerPlainSegmentNode';
-import {$createSlashSlotNode, SlashSlotNode} from '@app/features/lexical/composer/nodes/SlashSlotNode';
-import {SlashSlotPlaceholderNode} from '@app/features/lexical/composer/nodes/SlashSlotPlaceholderNode';
-import {SyntaxMarkerNode} from '@app/features/lexical/composer/nodes/SyntaxMarkerNode';
-import {createSpecialMentionPayload, type SpecialMentionKind} from '@app/features/lexical/composer/specialMentions';
-import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
-import {createEmptyHistoryState, registerHistory} from '@lexical/history';
-import {
- $addUpdateTag,
- $createParagraphNode,
- $createRangeSelection,
- $createTextNode,
- $getRoot,
- $getSelection,
- $isElementNode,
- $isRangeSelection,
- $setCompositionKey,
- $setSelection,
- createEditor,
- type ElementNode,
- HISTORY_MERGE_TAG,
- type LexicalEditor,
- type LexicalNode,
- PASTE_TAG,
- REDO_COMMAND,
- UNDO_COMMAND,
-} from 'lexical';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-const ALICE: MentionSegment = {type: 'user', id: '1', displayText: '@Alice', actualText: '<@1>', start: 0, end: 6};
-
-function specialSegment(kind: SpecialMentionKind, start: number): MentionSegment {
- return {type: 'special', id: kind, displayText: kind, actualText: kind, start, end: start + kind.length};
-}
-
-function update(editor: LexicalEditor, fn: () => void, tag?: string): void {
- editor.update(fn, {discrete: true, tag});
-}
-
-function createComposer(
- display: string,
- segments: ReadonlyArray<MentionSegment> = [],
- plainText = false,
-): LexicalEditor {
- const editor = createEditor({
- namespace: 'test',
- nodes: [
- ComposerMentionNode,
- ComposerCustomEmojiNode,
- ComposerPlainSegmentNode,
- ComposerCommandNode,
- SlashSlotNode,
- SlashSlotPlaceholderNode,
- SyntaxMarkerNode,
- ],
- onError: (error) => {
- throw error;
- },
- });
- update(editor, () => {
- $hydrateComposerFromDraft(display, segments, plainText);
- $selectComposerOffset(display.length);
- });
- return editor;
-}
-
-function register(editor: LexicalEditor, allowed: boolean, plainText = false): () => void {
- const unregister = registerComposerSpecialMention(editor, allowed, plainText);
- editor.read(() => undefined);
- return unregister;
-}
-
-function type(editor: LexicalEditor, text: string): void {
- for (const character of text) {
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertText(character);
- }
- });
- }
-}
-
-function insertLineBreak(editor: LexicalEditor): void {
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertLineBreak();
- }
- });
-}
-
-function paste(editor: LexicalEditor, insert: () => void): void {
- update(editor, () => {
- insert();
- $addUpdateTag(PASTE_TAG);
- });
-}
-
-function insertRawText(text: string): void {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertRawText(text);
- }
-}
-
-function describeNode(node: LexicalNode): string {
- return `${node.getType()}:${node.getTextContent()}`;
-}
-
-function $paragraph(): ElementNode {
- const paragraph = $getRoot().getFirstChildOrThrow();
- assert($isElementNode(paragraph), 'Expected composer paragraph');
- return paragraph;
-}
-
-function children(editor: LexicalEditor): Array<string> {
- return editor.read(() => $paragraph().getChildren().map(describeNode));
-}
-
-function snapshot(editor: LexicalEditor) {
- return editor.read(() => ({
- children: $paragraph().getChildren().map(describeNode),
- projection: $projectComposer(),
- selection: $captureSelectionOffsets(),
- }));
-}
-
-function childrenJSON(editor: LexicalEditor) {
- return editor.read(() =>
- $paragraph()
- .getChildren()
- .map((node) => node.exportJSON()),
- );
-}
-
-describe('typed special mentions', () => {
- it('converts @everyone once a space follows it', () => {
- const editor = createComposer('');
- register(editor, true);
- type(editor, 'hi @everyone ');
- expect(snapshot(editor)).toEqual({
- children: ['text:hi ', 'composer-mention:@everyone', 'text: '],
- projection: {display: 'hi @everyone ', segments: [specialSegment('@everyone', 3)], wire: 'hi @everyone '},
- selection: {anchor: 13, focus: 13},
- });
- });
-
- it('produces exactly the nodes and projection the autocomplete inserts', () => {
- const typed = createComposer('');
- register(typed, true);
- type(typed, 'hi @everyone ');
- const picked = createComposer('hi @every');
- register(picked, true);
- update(picked, () => $replaceComposerRange(3, 9, createSpecialMentionPayload('@everyone')));
- expect(childrenJSON(typed)).toEqual(childrenJSON(picked));
- expect(snapshot(typed)).toEqual(snapshot(picked));
- });
-
- it('keeps a token at the caret as text, so @herenow never converts', () => {
- const editor = createComposer('');
- register(editor, true);
- type(editor, 'hi @here');
- expect(snapshot(editor)).toEqual({
- children: ['text:hi @here'],
- projection: {display: 'hi @here', segments: [], wire: 'hi @here'},
- selection: {anchor: 8, focus: 8},
- });
- type(editor, 'now ');
- expect(snapshot(editor)).toEqual({
- children: ['text:hi @herenow '],
- projection: {display: 'hi @herenow ', segments: [], wire: 'hi @herenow '},
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('converts a finished token when a line break follows it', () => {
- const editor = createComposer('');
- register(editor, true);
- type(editor, 'hi @everyone');
- insertLineBreak(editor);
- expect(snapshot(editor)).toEqual({
- children: ['text:hi ', 'composer-mention:@everyone', 'linebreak:\n'],
- projection: {display: 'hi @everyone\n', segments: [specialSegment('@everyone', 3)], wire: 'hi @everyone\n'},
- selection: {anchor: 13, focus: 13},
- });
- });
-
- it('does not convert when only the caret moves away, and converts on the next edit', () => {
- const editor = createComposer('');
- register(editor, true);
- type(editor, '@here');
- update(editor, () => $selectComposerOffset(0));
- expect(children(editor)).toEqual(['text:@here']);
- type(editor, ' ');
- expect(snapshot(editor)).toEqual({
- children: ['text: ', 'composer-mention:@here'],
- projection: {display: ' @here', segments: [specialSegment('@here', 1)], wire: ' @here'},
- selection: {anchor: 1, focus: 1},
- });
- });
-
- it('converts a token completed with the caret inside it and moves the caret past the mention', () => {
- const editor = createComposer('@hre');
- register(editor, true);
- update(editor, () => $selectComposerOffset(2));
- type(editor, 'e');
- expect(snapshot(editor)).toEqual({
- children: ['composer-mention:@here'],
- projection: {display: '@here', segments: [specialSegment('@here', 0)], wire: '@here'},
- selection: {anchor: 5, focus: 5},
- });
- });
-
- it('treats a preceding or following mention or emoji as a boundary', () => {
- const emoji: MentionSegment = {
- type: 'emoji',
- id: '2',
- displayText: ':wave:',
- actualText: '<:wave:2>',
- start: 0,
- end: 6,
- };
- const alice = {...ALICE, start: 6, end: 12};
- const editor = createComposer(':wave:@Alice', [emoji, alice]);
- register(editor, true);
- type(editor, '@here ');
- expect(snapshot(editor).projection).toEqual({
- display: ':wave:@Alice@here ',
- segments: [emoji, alice, specialSegment('@here', 12)],
- wire: '<:wave:2><@1>@here ',
- });
- const before = createComposer('@here@Alice', [{...ALICE, start: 5, end: 11}]);
- register(before, true);
- expect(children(before)).toEqual(['composer-mention:@here', 'composer-mention:@Alice']);
- });
-
- it('treats a preceding special mention pill or slash command as a boundary', () => {
- const editor = createComposer('@here', [specialSegment('@here', 0)]);
- register(editor, true);
- type(editor, '@everyone ');
- expect(snapshot(editor).projection).toEqual({
- display: '@here@everyone ',
- segments: [specialSegment('@here', 0), specialSegment('@everyone', 5)],
- wire: '@here@everyone ',
- });
- const command = createComposer('');
- update(command, () => {
- $paragraph().append($createComposerCommandNode('/giphy'), $createTextNode('@here '));
- });
- register(command, true);
- expect(children(command)).toEqual(['composer-command:/giphy', 'composer-mention:@here', 'text: ']);
- });
-
- it('converts a token in a second paragraph', () => {
- const editor = createComposer('a');
- register(editor, true);
- update(editor, () => {
- const paragraph = $createParagraphNode();
- paragraph.append($createTextNode('@everyone x'));
- $getRoot().append(paragraph);
- });
- expect(snapshot(editor).projection).toEqual({
- display: 'a\n@everyone x',
- segments: [specialSegment('@everyone', 2)],
- wire: 'a\n@everyone x',
- });
- });
-
- it('keeps the caret after a later pill when a conversion splits the text before it', () => {
- const editor = createComposer('@here @Alice', [{...ALICE, start: 6, end: 12}]);
- register(editor, true);
- expect(snapshot(editor)).toEqual({
- children: ['composer-mention:@here', 'text: ', 'composer-mention:@Alice'],
- projection: {
- display: '@here @Alice',
- segments: [specialSegment('@here', 0), {...ALICE, start: 6, end: 12}],
- wire: '@here <@1>',
- },
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('keeps an element caret between a pill and the text a conversion splits', () => {
- const editor = createComposer('@Alice@here x', [ALICE]);
- update(editor, () => {
- const selection = $createRangeSelection();
- selection.anchor.set($paragraph().getKey(), 1, 'element');
- selection.focus.set($paragraph().getKey(), 1, 'element');
- $setSelection(selection);
- });
- register(editor, true);
- expect(snapshot(editor)).toEqual({
- children: ['composer-mention:@Alice', 'composer-mention:@here', 'text: x'],
- projection: {
- display: '@Alice@here x',
- segments: [ALICE, specialSegment('@here', 6)],
- wire: '<@1>@here x',
- },
- selection: {anchor: 6, focus: 6},
- });
- });
-
- it('gives the conversion one undo entry that restores the text before the keystroke, and redo restores it', () => {
- const editor = createComposer('');
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 1000);
- register(editor, true);
- type(editor, 'hi @everyone');
- const depth = history.undoStack.length;
- type(editor, ' ');
- expect(history.undoStack).toHaveLength(depth + 1);
- editor.dispatchCommand(UNDO_COMMAND, undefined);
- expect(snapshot(editor)).toEqual({
- children: ['text:hi @everyone'],
- projection: {display: 'hi @everyone', segments: [], wire: 'hi @everyone'},
- selection: {anchor: 12, focus: 12},
- });
- editor.dispatchCommand(REDO_COMMAND, undefined);
- expect(snapshot(editor)).toEqual({
- children: ['text:hi ', 'composer-mention:@everyone', 'text: '],
- projection: {display: 'hi @everyone ', segments: [specialSegment('@everyone', 3)], wire: 'hi @everyone '},
- selection: {anchor: 13, focus: 13},
- });
- });
-
- it('leaves a token at the caret alone when the mention menu opens or closes', () => {
- const editor = createComposer('');
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 1000);
- register(editor, true);
- type(editor, 'hi @here');
- const depth = history.undoStack.length;
- update(editor, () => $getRoot().markDirty(), HISTORY_MERGE_TAG);
- expect(children(editor)).toEqual(['text:hi @here']);
- expect(history.undoStack).toHaveLength(depth);
- });
-
- it('converts a token at the caret when the transform is registered, without adding an undo entry', () => {
- const editor = createComposer('hi @here');
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 1000);
- const depth = history.undoStack.length;
- register(editor, true);
- expect(children(editor)).toEqual(['text:hi ', 'composer-mention:@here']);
- expect(history.undoStack).toHaveLength(depth);
- });
-
- it('converts a hydrated draft whose token ends at the caret without resetting the history', () => {
- const editor = createComposer('');
- register(editor, true);
- update(
- editor,
- () => {
- $hydrateComposerFromDraft('hi @everyone', []);
- $selectComposerOffset(12);
- },
- COMPOSER_RESCAN_TAG,
- );
- expect(snapshot(editor)).toEqual({
- children: ['text:hi ', 'composer-mention:@everyone'],
- projection: {display: 'hi @everyone', segments: [specialSegment('@everyone', 3)], wire: 'hi @everyone'},
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('converts a token at the caret after a render mode switch', () => {
- const editor = createComposer('');
- const unregister = register(editor, true);
- type(editor, '@here');
- unregister();
- update(
- editor,
- () => {
- const selection = $captureSelectionOffsets()!;
- const projection = $projectComposer();
- $hydrateComposerFromDraft(projection.display, projection.segments, true);
- $selectComposerRange(selection.anchor, selection.focus);
- },
- 'composer-render-mode',
- );
- resetComposerHistory(editor);
- registerComposerPlainText(editor);
- register(editor, true, true);
- expect(snapshot(editor)).toEqual({
- children: ['composer-plain-segment:@here'],
- projection: {display: '@here', segments: [specialSegment('@here', 0)], wire: '@here'},
- selection: {anchor: 5, focus: 5},
- });
- });
-
- it('converts to the plain segment the autocomplete inserts in plain text mode', () => {
- const typed = createComposer('', [], true);
- registerComposerPlainText(typed);
- register(typed, true, true);
- type(typed, 'hi @everyone ');
- const picked = createComposer('hi @every', [], true);
- registerComposerPlainText(picked);
- register(picked, true, true);
- update(picked, () => $replaceComposerRange(3, 9, createSpecialMentionPayload('@everyone'), undefined, true));
- expect(childrenJSON(typed)).toEqual(childrenJSON(picked));
- expect(snapshot(typed)).toEqual({
- children: ['text:hi ', 'composer-plain-segment:@everyone', 'text: '],
- projection: {display: 'hi @everyone ', segments: [specialSegment('@everyone', 3)], wire: 'hi @everyone '},
- selection: {anchor: 13, focus: 13},
- });
- });
-
- it('converts a pasted token at the caret and several pasted tokens at once', () => {
- const tail = createComposer('ping ');
- register(tail, true);
- paste(tail, () => insertRawText('@here'));
- expect(snapshot(tail)).toEqual({
- children: ['text:ping ', 'composer-mention:@here'],
- projection: {display: 'ping @here', segments: [specialSegment('@here', 5)], wire: 'ping @here'},
- selection: {anchor: 10, focus: 10},
- });
- const several = createComposer('');
- register(several, true);
- paste(several, () => insertRawText('@everyone and @here'));
- expect(snapshot(several)).toEqual({
- children: ['composer-mention:@everyone', 'text: and ', 'composer-mention:@here'],
- projection: {
- display: '@everyone and @here',
- segments: [specialSegment('@everyone', 0), specialSegment('@here', 14)],
- wire: '@everyone and @here',
- },
- selection: {anchor: 19, focus: 19},
- });
- });
-
- it('converts typed tokens beside wire mentions in a channel paste slice', () => {
- const editor = createComposer('hi ');
- register(editor, true);
- paste(editor, () => $insertComposerClipboardSlice({display: '@Alice @everyone', segments: [ALICE]}, false));
- expect(snapshot(editor)).toEqual({
- children: ['text:hi ', 'composer-mention:@Alice', 'text: ', 'composer-mention:@everyone'],
- projection: {
- display: 'hi @Alice @everyone',
- segments: [{...ALICE, start: 3, end: 9}, specialSegment('@everyone', 10)],
- wire: 'hi <@1> @everyone',
- },
- selection: {anchor: 19, focus: 19},
- });
- });
-
- it('gives a channel paste its own undo entry once it carries the paste tag', () => {
- const editor = createComposer('');
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 1000);
- register(editor, true);
- type(editor, 'a');
- paste(editor, () => $insertComposerClipboardSlice({display: 'b', segments: []}, false));
- type(editor, 'c');
- editor.dispatchCommand(UNDO_COMMAND, undefined);
- expect(editor.read(() => $projectComposer().display)).toBe('ab');
- editor.dispatchCommand(UNDO_COMMAND, undefined);
- expect(editor.read(() => $projectComposer().display)).toBe('a');
- });
-
- it('waits for IME composition to end before converting', () => {
- const editor = createComposer('hi ');
- register(editor, true);
- update(editor, () => {
- const selection = $getSelection();
- if ($isRangeSelection(selection)) {
- selection.insertText('@everyone ');
- $setCompositionKey(selection.anchor.key);
- }
- });
- expect(children(editor)).toEqual(['text:hi @everyone ']);
- update(editor, () => $setCompositionKey(null));
- expect(children(editor)).toEqual(['text:hi ', 'composer-mention:@everyone', 'text: ']);
- });
-
- it('leaves code formatted text and slash command slot text alone', () => {
- const editor = createComposer('');
- register(editor, true);
- update(editor, () => {
- const code = $createTextNode('@everyone ').toggleFormat('code');
- const slot = $createSlashSlotNode('message', 'string', true).append($createTextNode('@here '));
- $paragraph().append(code, slot);
- code.select(10, 10);
- });
- expect(editor.read(() => $paragraph().getChildren().map(describeNode))).toEqual([
- 'text:@everyone ',
- 'slash-slot:@here ',
- ]);
- expect(
- editor.read(() => {
- const slot = $paragraph().getLastChildOrThrow();
- assert($isElementNode(slot), 'Expected slash command slot element');
- return slot.getChildren().map(describeNode);
- }),
- ).toEqual(['text:@here ']);
- });
-
- it('restores a draft special mention and projects it back unchanged', () => {
- const segments = [specialSegment('@everyone', 0)];
- const editor = createComposer('@everyone hi', segments);
- expect(snapshot(editor)).toEqual({
- children: ['composer-mention:@everyone', 'text: hi'],
- projection: {display: '@everyone hi', segments, wire: '@everyone hi'},
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('includes the special segment in the clipboard selection', () => {
- const editor = createComposer('');
- register(editor, true);
- type(editor, 'hi @everyone ');
- update(editor, () => $selectComposerRange(0, 13));
- expect(editor.read(() => $getComposerClipboardSelection())).toEqual({
- display: 'hi @everyone ',
- segments: [specialSegment('@everyone', 3)],
- textPlain: 'hi @everyone ',
- });
- });
-});
-
-describe('typed special mentions with the markdown highlight', () => {
- function createHighlightedComposer(): LexicalEditor {
- const editor = createComposer('');
- registerComposerMarkdownHighlight(editor);
- register(editor, true);
- return editor;
- }
-
- it.each([
- ['an escaped token', '\\@everyone '],
- ['closed inline code', '`@everyone` '],
- ['open inline code', '`@everyone '],
- ['a url', 'https://fluxer.app/@everyone '],
- ])('leaves %s as text', (_name, text) => {
- const editor = createHighlightedComposer();
- type(editor, text);
- expect(snapshot(editor).projection).toEqual({display: text, segments: [], wire: text});
- });
-
- it('leaves a token inside a fenced code block as text and converts one after it', () => {
- const editor = createHighlightedComposer();
- type(editor, '```');
- insertLineBreak(editor);
- type(editor, '@everyone ');
- insertLineBreak(editor);
- type(editor, '```');
- insertLineBreak(editor);
- type(editor, '@here ');
- expect(snapshot(editor).projection).toEqual({
- display: '```\n@everyone \n```\n@here ',
- segments: [specialSegment('@here', 19)],
- wire: '```\n@everyone \n```\n@here ',
- });
- });
-
- it('converts a bold token into a pill that is not literal', () => {
- const editor = createHighlightedComposer();
- type(editor, '**@everyone** ');
- expect(snapshot(editor).projection).toEqual({
- display: '**@everyone** ',
- segments: [specialSegment('@everyone', 2)],
- wire: '**@everyone** ',
- });
- expect(
- editor.read(() =>
- $paragraph()
- .getChildren()
- .filter($isComposerMentionNode)
- .map((node) => node.isLiteral()),
- ),
- ).toEqual([false]);
- });
-});
-
-describe('special mentions where they are not allowed', () => {
- it('turns a restored special mention into text', () => {
- const editor = createComposer('@everyone hi', [specialSegment('@everyone', 0)]);
- register(editor, false);
- expect(snapshot(editor)).toEqual({
- children: ['text:@everyone hi'],
- projection: {display: '@everyone hi', segments: [], wire: '@everyone hi'},
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('turns a pasted special mention into text', () => {
- const editor = createComposer('hi ');
- register(editor, false);
- paste(editor, () =>
- $insertComposerClipboardSlice({display: '@here', segments: [specialSegment('@here', 0)]}, false),
- );
- expect(snapshot(editor)).toEqual({
- children: ['text:hi @here'],
- projection: {display: 'hi @here', segments: [], wire: 'hi @here'},
- selection: {anchor: 8, focus: 8},
- });
- });
-
- it('turns a restored special mention into text in plain text mode', () => {
- const editor = createComposer('@everyone hi', [specialSegment('@everyone', 0)], true);
- registerComposerPlainText(editor);
- register(editor, false, true);
- expect(snapshot(editor)).toEqual({
- children: ['text:@everyone hi'],
- projection: {display: '@everyone hi', segments: [], wire: '@everyone hi'},
- selection: {anchor: 12, focus: 12},
- });
- });
-
- it('turns a pasted special mention into text in plain text mode', () => {
- const editor = createComposer('hi ', [], true);
- registerComposerPlainText(editor);
- register(editor, false, true);
- paste(editor, () =>
- $insertComposerClipboardSlice({display: '@here', segments: [specialSegment('@here', 0)]}, true),
- );
- expect(snapshot(editor)).toEqual({
- children: ['text:hi @here'],
- projection: {display: 'hi @here', segments: [], wire: 'hi @here'},
- selection: {anchor: 8, focus: 8},
- });
- });
-
- it('leaves typed tokens as text, then converts them once special mentions become allowed', () => {
- const editor = createComposer('');
- const unregister = register(editor, false);
- type(editor, '@here ');
- expect(children(editor)).toEqual(['text:@here ']);
- unregister();
- register(editor, true);
- expect(children(editor)).toEqual(['composer-mention:@here', 'text: ']);
- });
-});
-
-describe('isValidComposerSegment', () => {
- it('accepts the special mention ids the autocomplete writes', () => {
- expect(isValidComposerSegment('@everyone hi', specialSegment('@everyone', 0))).toBe(true);
- expect(isValidComposerSegment('hi @here', specialSegment('@here', 3))).toBe(true);
- });
-
- it('rejects the bare id form and a mismatched id', () => {
- expect(isValidComposerSegment('@everyone hi', {...specialSegment('@everyone', 0), id: 'everyone'})).toBe(false);
- expect(isValidComposerSegment('@everyone hi', {...specialSegment('@everyone', 0), id: '@here'})).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/LexicalRichInput.test.tsx b/fluxer_app/src/features/lexical/composer/LexicalRichInput.test.tsx
deleted file mode 100644
index 40784b5b5..000000000
--- a/fluxer_app/src/features/lexical/composer/LexicalRichInput.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {FlatEmoji} from '@app/features/emoji/types/EmojiTypes';
-import {LexicalRichInput, type LexicalRichInputHandle} from '@app/features/lexical/composer/LexicalRichInput';
-import type {I18n} from '@lingui/core';
-import {act, createElement, createRef} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const stub = vi.hoisted(() => ({
- handle: {
- getDisplayValue: () => '',
- getSegments: () => [],
- getSelection: () => ({start: 0, end: 0}),
- getMarkdownParserFlags: () => 0,
- replaceRange: () => undefined,
- },
- composerMaxWireLength: undefined as number | undefined,
- autocompleteMaxActualLength: undefined as number | undefined,
- emojiLimits: [] as Array<{maxWireLength?: number}>,
-}));
-
-vi.mock('@app/features/lexical/composer/LexicalComposerInput', () => ({
- LexicalComposerInput: (props: {maxWireLength?: number; handleRef: {current: unknown}}) => {
- stub.composerMaxWireLength = props.maxWireLength;
- props.handleRef.current = stub.handle;
- return null;
- },
-}));
-
-vi.mock('@app/features/lexical/composer/useLexicalAutocomplete', () => ({
- useLexicalAutocomplete: (params: {maxActualLength?: number}) => {
- stub.autocompleteMaxActualLength = params.maxActualLength;
- return {
- autocompleteQuery: '',
- autocompleteOptions: [],
- autocompleteType: null,
- isSlotMenu: false,
- onCursorMove: () => undefined,
- handleSelect: () => undefined,
- specialMentionsAllowed: true,
- };
- },
-}));
-
-vi.mock('@app/features/lexical/composer/ComposerInsertion', () => ({
- insertComposerEmoji: (_handle: unknown, _emoji: unknown, limit: {maxWireLength?: number}) => {
- stub.emojiLimits.push(limit);
- return true;
- },
-}));
-
-vi.mock('@app/features/messaging/utils/TypedEmojiShortcodeUtils', () => ({resolveTypedEmojiToken: () => null}));
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const I18N = {} as I18n;
-const EMOJI = {} as FlatEmoji;
-
-describe('LexicalRichInput length limits', () => {
- let host: HTMLDivElement;
- let root: Root;
-
- beforeEach(() => {
- stub.composerMaxWireLength = undefined;
- stub.autocompleteMaxActualLength = undefined;
- stub.emojiLimits.length = 0;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- });
-
- afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
- });
-
- it.each<[string, {maxLength?: number; maxWireLength?: number}, number, number | undefined]>([
- ['only maxWireLength', {maxWireLength: 40}, 40, undefined],
- ['only maxLength', {maxLength: 40}, 40, 40],
- ['both', {maxLength: 30, maxWireLength: 40}, 40, 30],
- ])('budgets the composer by maxWireLength and caps autocomplete and emoji inserts by maxLength when a host passes %s', (_name, props, composerLimit, insertLimit) => {
- const richInputRef = createRef<LexicalRichInputHandle>();
- act(() => {
- root.render(createElement(LexicalRichInput, {placeholder: 'placeholder', i18n: I18N, richInputRef, ...props}));
- });
- expect(stub.composerMaxWireLength).toBe(composerLimit);
- expect(stub.autocompleteMaxActualLength).toBe(insertLimit);
- act(() => {
- richInputRef.current?.insertEmoji(EMOJI);
- });
- expect(stub.emojiLimits).toEqual([{maxWireLength: insertLimit, onExceedMaxLength: undefined}]);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/blockquoteLines.test.ts b/fluxer_app/src/features/lexical/composer/blockquoteLines.test.ts
deleted file mode 100644
index 5bf1d6590..000000000
--- a/fluxer_app/src/features/lexical/composer/blockquoteLines.test.ts
+++ /dev/null
@@ -1,607 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type BlockquoteDeleteUnit,
- type BlockquoteEdit,
- type BlockquoteLine,
- blockquoteContentRange,
- dropTrailingEmptyBlockquoteLines,
- findBlockquoteMarkers,
- planBlockquoteBackspace,
- planBlockquoteContentStartDelete,
- planBlockquoteDropCaret,
- planBlockquoteForwardDelete,
- planBlockquoteLineBreak,
- planBlockquoteMove,
- planBlockquotePaste,
- resolveBlockquoteSelection,
-} from '@app/features/lexical/composer/blockquoteLines';
-import {
- computeMarkdownHighlightSpans,
- DEFAULT_COMPOSER_MARKDOWN_FLAGS,
-} from '@app/features/lexical/composer/markdownSpans';
-import {ParserFlags} from '@app/features/messaging/utils/markdown/parser/Enums';
-import {parseMarkdownAstWithWasm} from '@app/features/messaging/utils/markdown/parser/MarkdownParserWasm';
-import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
-import {describe, expect, it} from 'vitest';
-
-const QUOTE_PREFIX_RE = /^[ \t]*> /;
-const NO_CODE_BLOCK_FLAGS = DEFAULT_COMPOSER_MARKDOWN_FLAGS & ~ParserFlags.ALLOW_CODE_BLOCKS;
-
-function quoteLines(text: string): Array<BlockquoteLine> {
- const lines: Array<BlockquoteLine> = [];
- let start = 0;
- for (const line of text.split('\n')) {
- const prefix = QUOTE_PREFIX_RE.exec(line);
- if (prefix != null) {
- lines.push({start, contentStart: start + prefix[0].length, end: start + line.length});
- }
- start += line.length + 1;
- }
- return lines;
-}
-
-function applyEdit(text: string, edit: BlockquoteEdit | null): string | null {
- return edit == null ? null : `${text.slice(0, edit.start)}${edit.text}${text.slice(edit.end)}`;
-}
-
-describe('planBlockquoteLineBreak', () => {
- const ROWS: Array<[string, number, string, number]> = [
- ['> test', 6, '> test\n> ', 9],
- ['> test', 4, '> te\n> st', 7],
- ['> test', 2, '> \n> test', 5],
- ['> ', 2, '> \n> ', 5],
- ['x\n> ', 4, 'x\n> \n> ', 7],
- ['> test\n> ', 9, '> test\n', 7],
- ['> \n> ', 5, '', 0],
- ['> \n> \n> ', 8, '', 0],
- ['> a\n> \n> ', 9, '> a\n', 4],
- ['> a\n> \n> b', 6, '> a\n\n> b', 4],
- ['x\n> \n> ', 7, 'x\n', 2],
- ['> ', 3, '> \n> ', 6],
- [' > a', 5, ' > a\n> ', 8],
- ];
-
- it.each(ROWS)('on %j at %i gives %j with the caret at %i', (text, caret, expected, expectedCaret) => {
- const edit = planBlockquoteLineBreak(text, quoteLines(text), caret);
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(expectedCaret);
- });
-
- it.each<[string, number]>([
- ['abc', 3],
- ['', 0],
- ['> test', 1],
- ['x\n> a', 1],
- ])('declines on %j at %i because the caret is not on a quote line', (text, caret) => {
- expect(planBlockquoteLineBreak(text, quoteLines(text), caret)).toBeNull();
- });
-
- it.each<[string, number]>([
- ['```\n> a', 7],
- ['> ```', 5],
- ['```\n> a\n```', 6],
- ])('declines on %j at %i because the caret is inside a code block', (text, caret) => {
- expect(planBlockquoteLineBreak(text, quoteLines(text), caret)).toBeNull();
- });
-
- it.each<[string, number, string, number]>([
- ['> ```', 5, '> ```\n> ', 8],
- ['> ```\n> b', 9, '> ```\n> b\n> ', 12],
- ])('continues %j at %i into %j with the caret at %i when code blocks are off', (text, caret, expected, caretAfter) => {
- expect(planBlockquoteLineBreak(text, quoteLines(text), caret)).toBeNull();
- const edit = planBlockquoteLineBreak(text, quoteLines(text), caret, NO_CODE_BLOCK_FLAGS);
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(caretAfter);
- });
-});
-
-describe('planBlockquoteBackspace', () => {
- const ROWS: Array<[string, number, string, number]> = [
- ['> test', 2, 'test', 0],
- ['> ', 2, '', 0],
- ['> \n> ', 5, '> \n', 3],
- ['> \n', 3, '', 0],
- ['> \nabc', 3, 'abc', 0],
- ['a\n> \nb', 5, 'a\nb', 2],
- [' > a', 4, 'a', 0],
- ['x\n> test', 4, 'x\ntest', 2],
- ];
-
- it.each(ROWS)('on %j at %i gives %j with the caret at %i', (text, caret, expected, expectedCaret) => {
- const edit = planBlockquoteBackspace(text, quoteLines(text), caret);
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(expectedCaret);
- });
-
- it.each<[string, number]>([
- ['> a\nb', 4],
- ['> test', 4],
- ['> ', 3],
- ['abc', 3],
- ['> \n> ', 3],
- ['```\n> a', 6],
- ])('declines on %j at %i', (text, caret) => {
- expect(planBlockquoteBackspace(text, quoteLines(text), caret)).toBeNull();
- });
-
- it('removes the marker below a quoted fence when code blocks are off', () => {
- const text = '> ```\n> b';
- expect(planBlockquoteBackspace(text, quoteLines(text), 8)).toBeNull();
- const edit = planBlockquoteBackspace(text, quoteLines(text), 8, NO_CODE_BLOCK_FLAGS);
- expect(applyEdit(text, edit)).toBe('> ```\nb');
- expect(edit?.caret).toBe(6);
- });
-});
-
-describe('planBlockquoteForwardDelete', () => {
- const ROWS: Array<[string, number, string, number]> = [
- ['> a\n> b', 3, '> ab', 3],
- ['a\n> b', 1, 'ab', 1],
- ['> a\n> ', 3, '> a', 3],
- [' > a\n> b', 5, ' > ab', 5],
- ['> \n> b', 2, '> b', 2],
- ['a\n> \n> b', 4, 'a\n> b', 4],
- ['> \nb', 2, 'b', 0],
- ['> \n', 2, '', 0],
- ['a\n> \nb', 4, 'a\nb', 2],
- ];
-
- it.each(ROWS)('on %j at %i gives %j with the caret at %i', (text, caret, expected, expectedCaret) => {
- const edit = planBlockquoteForwardDelete(text, quoteLines(text), caret);
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(expectedCaret);
- });
-
- it.each<[string, number]>([
- ['\n> b', 0],
- ['a\n\n> b', 2],
- ['> a\nb', 3],
- ['> test', 4],
- ['> ', 2],
- ['abc', 1],
- ['```\n> a\n> b', 7],
- ])('declines on %j at %i', (text, caret) => {
- expect(planBlockquoteForwardDelete(text, quoteLines(text), caret)).toBeNull();
- });
-
- it('joins the line below a quoted fence when code blocks are off', () => {
- const text = '> ```\n> b';
- expect(planBlockquoteForwardDelete(text, quoteLines(text), 5)).toBeNull();
- const edit = planBlockquoteForwardDelete(text, quoteLines(text), 5, NO_CODE_BLOCK_FLAGS);
- expect(applyEdit(text, edit)).toBe('> ```b');
- expect(edit?.caret).toBe(5);
- });
-});
-
-describe('planBlockquoteContentStartDelete', () => {
- function plan(
- text: string,
- caret: number,
- unit: BlockquoteDeleteUnit,
- atoms: Array<{start: number; end: number}> = [],
- ) {
- return planBlockquoteContentStartDelete(text, quoteLines(text), atoms, caret, unit);
- }
-
- it.each<[string, number, string, number]>([
- ['> ab', 2, '> b', 2],
- ['x\n> ab', 4, 'x\n> b', 4],
- [' > ab', 4, ' > b', 4],
- ['> e\u0301x', 2, '> ex', 3],
- ['> a\u0301\u0302x', 2, '> a\u0301x', 4],
- ['> क\u093Fx', 2, '> कx', 3],
- ['> क\u094Dषx', 2, '> क\u094Dx', 4],
- ['> \u1100\u1161x', 2, '> \u1100x', 3],
- ['> 가각', 2, '> 각', 2],
- ['> a\u200Db', 2, '> ab', 3],
- ['> \u{1F468}\u200D\u{1F469}\u200D\u{1F467}x', 2, '> x', 2],
- ['> \u{1F44B}\u200D\u{1F3FF}x', 2, '> x', 2],
- ['> \u{1F44D}\u{1F3FD}x', 2, '> x', 2],
- ['> \u{1F1F8}\u{1F1EA}\u{1F1F3}\u{1F1F4}', 2, '> \u{1F1F3}\u{1F1F4}', 2],
- ['> #\uFE0F\u20E3x', 2, '> x', 2],
- ['> ❤\uFE0Fx', 2, '> x', 2],
- ['> 1\uFE0Fx', 2, '> x', 2],
- ['> \u{1D4B3}x', 2, '> x', 2],
- ])('deletes one character from the content start of %j at %i, giving %j with the caret at %i', (text, caret, expected, expectedCaret) => {
- const edit = plan(text, caret, 'character');
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(expectedCaret);
- });
-
- it.each<[string, number, string]>([
- ['> ab ef', 2, '> ef'],
- ['> ab', 2, '> '],
- ['> ab cd', 2, '> cd'],
- ['> \tab c', 2, '> c'],
- ['> foo.bar baz', 2, '> .bar baz'],
- ["> don't stop", 2, '> stop'],
- ['> it’s x', 2, '> x'],
- ["> ab' x", 2, "> ' x"],
- ['> a_b c', 2, '> c'],
- ['> a-b c', 2, '> -b c'],
- ['> 3.14 x', 2, '> x'],
- ['> ...ab cd', 2, '> ab cd'],
- ['> 日本語テキスト x', 2, '> テキスト x'],
- ['> \u{1F600} ab', 2, '> ab'],
- ['> ab\u{1F600}cd x', 2, '> \u{1F600}cd x'],
- ['> #\uFE0F\u20E3x', 2, '> x'],
- ['> क\u094Dषx y', 2, '> y'],
- ['> ', 2, '> '],
- ['x\n> ab\n> cd', 4, 'x\n> \n> cd'],
- ])('deletes one word from the content start of %j at %i, giving %j', (text, caret, expected) => {
- const edit = plan(text, caret, 'word');
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(caret);
- });
-
- it.each<[string, number, string]>([
- ['> ab ef', 2, '> '],
- ['x\n> ab ef\n> gh', 4, 'x\n> \n> gh'],
- ])('deletes to the line end from the content start of %j at %i, giving %j', (text, caret, expected) => {
- const edit = plan(text, caret, 'line');
- expect(applyEdit(text, edit)).toBe(expected);
- expect(edit?.caret).toBe(caret);
- });
-
- it.each<[BlockquoteDeleteUnit, string, Array<{start: number; end: number}>, string]>([
- [
- 'character',
- 'x\n> xxxxxxxxxx y',
- [
- {start: 4, end: 9},
- {start: 9, end: 14},
- ],
- 'x\n> xxxxx y',
- ],
- [
- 'word',
- 'x\n> xxxxxxxxxx y',
- [
- {start: 4, end: 9},
- {start: 9, end: 14},
- ],
- 'x\n> xxxxx y',
- ],
- [
- 'line',
- 'x\n> xxxxxxxxxx y',
- [
- {start: 4, end: 9},
- {start: 9, end: 14},
- ],
- 'x\n> ',
- ],
- ['word', 'x\n> abxxxxx y', [{start: 6, end: 11}], 'x\n> y'],
- ])('deletes by %s over whole atoms from the content start of %j', (unit, text, atoms, expected) => {
- expect(applyEdit(text, plan(text, 4, unit, atoms))).toBe(expected);
- });
-
- it.each<[string, number]>([
- ['> ab', 3],
- ['> ab', 1],
- ['> ab', 0],
- ['> ', 2],
- ['ab\n> cd', 2],
- ['abc', 0],
- ])('declines on %j at %i', (text, caret) => {
- for (const unit of ['character', 'word', 'line'] as const) {
- expect(plan(text, caret, unit)).toBeNull();
- }
- });
-});
-
-describe('planBlockquotePaste', () => {
- function plan(text: string, start: number, end: number, display: string, parserFlags?: number): string {
- return planBlockquotePaste(text, quoteLines(text), start, end, {display, segments: []}, parserFlags).display;
- }
-
- const ROWS: Array<[string, number, number, string, string]> = [
- ['> abcd', 4, 4, 'x\ny', 'x\n> y'],
- ['> abcd', 2, 2, 'x\ny', 'x\n> y'],
- ['> ', 2, 2, 'x\n\ny', 'x\n> \n> y'],
- [' > a', 5, 5, 'x\ny', 'x\n> y'],
- ['> abcd', 6, 6, '\n', '\n> '],
- ['> abcd', 6, 6, 'x\n', 'x\n> '],
- ['> ab\n> cd', 3, 8, 'x\ny', 'x\n> y'],
- ['> ab\ncd', 3, 6, 'x\ny', 'x\n> y'],
- ['> ab', 4, 4, 'x\n>>> y', 'x\n> >>> y'],
- ['> ab', 4, 4, 'x\n```\ncode\n```\ny', 'x\n> ```\ncode\n```\ny'],
- ['```\nx\n```\n> a', 13, 13, 'x\ny', 'x\n> y'],
- ['> abcd', 4, 4, 'x\r\ny', 'x\n> y'],
- ['abcd', 2, 2, 'x\r\ny', 'x\ny'],
- ['> ', 2, 2, '> x\n> y', 'x\n> y'],
- ['> ', 2, 2, '> x', 'x'],
- ['> ', 2, 2, '> > x', '> x'],
- ['> ab', 2, 2, '\t> x', 'x'],
- ['x\n> ', 4, 4, '> x\r\n> y', 'x\n> y'],
- ['> ab\n> cd', 2, 8, '> x\ny', 'x\n> y'],
- ];
-
- it.each(ROWS)('on %j at %i..%i pasting %j gives %j', (text, start, end, display, expected) => {
- expect(plan(text, start, end, display)).toBe(expected);
- });
-
- const UNCHANGED_ROWS: Array<[string, number, number, string]> = [
- ['> ab', 4, 4, 'b\n> c'],
- ['> ab', 4, 4, 'x\n > y'],
- ['abcd', 2, 2, 'x\ny'],
- ['> abcd', 1, 1, 'x\ny'],
- ['> ```', 5, 5, 'x\ny'],
- ['```\n> a', 7, 7, 'x\ny'],
- ['> ab', 4, 4, 'x\r'],
- ['> ab', 4, 4, '> x'],
- ['> ', 1, 1, '> x'],
- ['abcd', 0, 0, '> x'],
- ];
-
- it.each(UNCHANGED_ROWS)('on %j at %i..%i leaves %j as it is', (text, start, end, display) => {
- expect(plan(text, start, end, display)).toBe(display);
- });
-
- it.each<[string, number, string, string, string]>([
- ['> ab', 4, 'x\n```\ncode\n```\ny', 'x\n> ```\ncode\n```\ny', 'x\n> ```\n> code\n> ```\n> y'],
- ['> ```', 5, 'x\ny', 'x\ny', 'x\n> y'],
- ])('on %j at %i pasting %j gives %j and %j when code blocks are off', (text, caret, display, expected, offValue) => {
- expect(plan(text, caret, caret, display)).toBe(expected);
- expect(plan(text, caret, caret, display, NO_CODE_BLOCK_FLAGS)).toBe(offValue);
- });
-
- it('shifts mention segments and hides mention text from the fence scan', () => {
- const segments: Array<MentionSegment> = [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 3, end: 8},
- {type: 'user', id: '2', displayText: '@a```b', actualText: '<@2>', start: 12, end: 18},
- ];
- expect(
- planBlockquotePaste('> abcd', quoteLines('> abcd'), 4, 4, {display: 'x\r\n@name y\n\n@a```b', segments}),
- ).toEqual({
- display: 'x\n> @name y\n> \n> @a```b',
- segments: [
- {type: 'user', id: '1', displayText: '@name', actualText: '<@1>', start: 4, end: 9},
- {type: 'user', id: '2', displayText: '@a```b', actualText: '<@2>', start: 17, end: 23},
- ],
- });
- });
-
- it('shifts a mention on a first line whose quote prefix is dropped', () => {
- const mention = (start: number): MentionSegment => ({
- type: 'user',
- id: '1',
- displayText: '@name',
- actualText: '<@1>',
- start,
- end: start + 5,
- });
- expect(
- planBlockquotePaste('> ', quoteLines('> '), 2, 2, {
- display: '> @name\n@name',
- segments: [mention(2), mention(8)],
- }),
- ).toEqual({display: '@name\n> @name', segments: [mention(0), mention(8)]});
- });
-
- it('quotes every line of a 200 line paste', () => {
- const display = Array.from({length: 200}, (_, index) => `line ${index}`).join('\n');
- const lines = `> ${plan('> ', 2, 2, display)}`.split('\n');
- expect(lines).toHaveLength(200);
- expect(lines.filter((line) => QUOTE_PREFIX_RE.test(line))).toHaveLength(200);
- });
-});
-
-describe('planBlockquoteDropCaret', () => {
- const ROWS: Array<[number, number, number, number | null]> = [
- [0, 7, 10, 3],
- [0, 7, 0, 0],
- [0, 7, 7, 0],
- [4, 11, 2, 2],
- [0, 7, 4, null],
- [0, 4, 10, 6],
- [0, 5, 5, 0],
- [2, 7, 7, 2],
- [0, 8, 12, 4],
- [0, 10, 12, 2],
- ];
-
- it.each(ROWS)('maps a drop of the range %i-%i at %i', (start, end, dropped, expected) => {
- expect(planBlockquoteDropCaret(start, end, dropped)).toBe(expected);
- });
-});
-
-describe('resolveBlockquoteSelection', () => {
- it.each<[string, number, number]>([
- ['> test', 0, 2],
- ['> test', 1, 2],
- ['> test', 2, 2],
- ['> test', 5, 5],
- [' > a', 3, 4],
- ['ab\n> cd', 3, 5],
- ['ab\n> cd', 4, 5],
- ['ab\n> cd', 1, 1],
- ])('maps the caret on %j at %i to %i', (text, caret, expected) => {
- expect(resolveBlockquoteSelection(quoteLines(text), caret, caret)).toEqual({anchor: expected, focus: expected});
- });
-
- it.each<[string, number, number, number, number]>([
- ['ab\n> cd', 1, 3, 1, 5],
- ['ab\n> cd', 3, 1, 5, 1],
- ['ab\n> cd', 1, 4, 1, 5],
- ['ab\n> cd', 4, 7, 5, 7],
- ['ab\n> cd', 3, 7, 3, 7],
- ['> a\n> b', 0, 7, 0, 7],
- ['x\n> ab', 4, 1, 4, 1],
- ])('maps the range on %j from %i..%i to %i..%i', (text, anchor, focus, expectedAnchor, expectedFocus) => {
- expect(resolveBlockquoteSelection(quoteLines(text), anchor, focus)).toEqual({
- anchor: expectedAnchor,
- focus: expectedFocus,
- });
- });
-});
-
-describe('blockquoteContentRange', () => {
- it.each<[string, number, number, number, number]>([
- ['> hello', 0, 7, 2, 7],
- ['> a\n> b', 2, 4, 2, 6],
- ['> a\n> b', 4, 7, 6, 7],
- ['ab\n> cd', 1, 4, 1, 5],
- ['> test', 2, 2, 2, 2],
- ['abc', 0, 3, 0, 3],
- ])('clamps %j from %i..%i to %i..%i', (text, start, end, expectedStart, expectedEnd) => {
- expect(blockquoteContentRange(quoteLines(text), start, end)).toEqual({start: expectedStart, end: expectedEnd});
- });
-});
-
-describe('planBlockquoteMove', () => {
- it.each<[string, number, boolean, number]>([
- ['ab\n> cd', 5, true, 2],
- ['> test', 2, true, 2],
- ['ab\n> cd', 2, false, 5],
- ['> a\n> b', 3, false, 6],
- ['\n> b', 0, false, 3],
- ])('moves across the marker on %j from %i backward %s to %i', (text, offset, isBackward, expected) => {
- expect(planBlockquoteMove(quoteLines(text), offset, isBackward)).toBe(expected);
- });
-
- it.each<[string, number, boolean]>([
- ['> test', 4, true],
- ['> test', 0, true],
- ['abc', 2, true],
- ['> test', 2, false],
- ['ab\n> cd', 1, false],
- ['abc', 3, false],
- ])('declines on %j at %i backward %s', (text, offset, isBackward) => {
- expect(planBlockquoteMove(quoteLines(text), offset, isBackward)).toBeNull();
- });
-});
-
-describe('findBlockquoteMarkers marker ends', () => {
- function markerEnds(text: string, parserFlags = DEFAULT_COMPOSER_MARKDOWN_FLAGS): Array<number> {
- return findBlockquoteMarkers(text, computeMarkdownHighlightSpans(text, parserFlags), parserFlags).markerEnds;
- }
-
- it.each<[string, Array<number>]>([
- ['> a', [2]],
- [' > a', [4]],
- ['> ', [2]],
- ['>>> a\nb', [0, 0]],
- ['>>> [!NOTE]\nbody', [0, 0]],
- [' >>> [!tip] x\nbody', [0, 0]],
- ['> > a', [2]],
- ['> >>> a', [2]],
- ['> [!NOTE]\n> body', [2, 2]],
- ['> a\n> b', [2, 2]],
- ['>a', [0]],
- ['\\> a', [0]],
- ['`> a`', [0]],
- ['```\n> a', [0, 0]],
- ['```\n> a\n```', [0, 0, 0]],
- ['```\nx\n```\n> a', [0, 0, 0, 2]],
- ])('gives %j the marker ends %j', (text, ends) => {
- expect(markerEnds(text)).toEqual(ends);
- });
-
- it('marks every line of a quoted fence when code blocks are off', () => {
- const text = '> ```\n> b\n> ```';
- expect(markerEnds(text)).toEqual([2, 0, 0]);
- expect(markerEnds(text, NO_CODE_BLOCK_FLAGS)).toEqual([2, 2, 2]);
- });
-
- it('treats whitespace after the prefix as content rather than marker', () => {
- expect(computeMarkdownHighlightSpans('> ').find((span) => span.start === 2)).toMatchObject({
- role: 'content',
- end: 3,
- });
- });
-});
-
-describe('findBlockquoteMarkers', () => {
- function findMarker(text: string, maxWireLength?: number) {
- return findBlockquoteMarkers(
- text,
- computeMarkdownHighlightSpans(text),
- DEFAULT_COMPOSER_MARKDOWN_FLAGS,
- maxWireLength,
- ).multiline;
- }
-
- function splitIntoLineQuotes(text: string, line: number, indent: number): string {
- return text
- .split('\n')
- .map((source, index) => {
- if (index < line) {
- return source;
- }
- return index === line ? `${source.slice(0, indent)}> ${source.slice(indent + 4)}` : `> ${source}`;
- })
- .join('\n');
- }
-
- function renderedNodes(text: string): string {
- return JSON.stringify(parseMarkdownAstWithWasm(text, DEFAULT_COMPOSER_MARKDOWN_FLAGS).nodes);
- }
-
- it.each<[string, number, number]>([
- ['>>> a\nb', 0, 0],
- [' >>> a\n b', 0, 2],
- ['x\n>>> a\nb', 1, 0],
- ['>>> a\n\nb', 0, 0],
- ['>>> a\n\\> b', 0, 0],
- ['>>> a\n`> b`', 0, 0],
- ['>>> a\n>b', 0, 0],
- ['> x\n\n>>> a\nb', 2, 0],
- ])('splits %j at line %i with indent %i and keeps the rendered message', (text, line, indent) => {
- expect(findMarker(text)).toEqual({line, indent, splits: true});
- expect(renderedNodes(splitIntoLineQuotes(text, line, indent))).toBe(renderedNodes(text));
- });
-
- it.each<[string, number]>([
- ['>>> a\n> b', 0],
- ['>>> intro\n> quoted reply\nclosing words', 0],
- ['>>> > a\nb', 0],
- ['>>> a\n> [!NOTE]\n> b', 0],
- ['>>> a\n>>> b', 0],
- ['>>> a\n > b', 0],
- ['>>> a\n\t> b', 0],
- ['> x\n>>> a\nb', 1],
- ['> [!NOTE]\n>>> a\nb', 1],
- ['||s\n>>> a\nb||\nc', 1],
- ['>>> a\n', 0],
- ['>>> a\nb\n', 0],
- ])('does not split %j because line quotes would change the rendered message', (text, line) => {
- expect(findMarker(text)).toEqual({line, indent: 0, splits: false});
- expect(renderedNodes(splitIntoLineQuotes(text, line, 0))).not.toBe(renderedNodes(text));
- });
-
- it.each<[number, boolean]>([
- [10, false],
- [11, true],
- ])('splits ">>> a\\nb\\nc" under a max wire length of %i: %s', (maxWireLength, splits) => {
- expect(findMarker('>>> a\nb\nc', maxWireLength)).toMatchObject({splits});
- });
-
- it.each(['> a', '>>>a', '>>> [!NOTE]\nbody', '```\n>>> a', '> >>> a'])('finds no marker in %j', (text) => {
- expect(findMarker(text)).toBeNull();
- });
-});
-
-describe('dropTrailingEmptyBlockquoteLines', () => {
- it.each<[string, string]>([
- ['> test\n> ', '> test'],
- ['> ', ''],
- ['> test\n> \n', '> test'],
- ['> test\n', '> test'],
- ['> \n> ', ''],
- ['a\n > ', 'a'],
- ['> a\n> ', '> a'],
- ['> a\n>', '> a\n>'],
- ['```\n> ', '```\n> '],
- ['> a\n> b', '> a\n> b'],
- ['', ''],
- ])('turns %j into %j', (content, expected) => {
- expect(dropTrailingEmptyBlockquoteLines(content)).toBe(expected);
- });
-
- it('drops a trailing empty quote line below a quoted fence when code blocks are off', () => {
- expect(dropTrailingEmptyBlockquoteLines('> ```\n> ')).toBe('> ```\n> ');
- expect(dropTrailingEmptyBlockquoteLines('> ```\n> ', NO_CODE_BLOCK_FLAGS)).toBe('> ```');
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/codeBlockIndent.test.ts b/fluxer_app/src/features/lexical/composer/codeBlockIndent.test.ts
deleted file mode 100644
index c3bd03fe5..000000000
--- a/fluxer_app/src/features/lexical/composer/codeBlockIndent.test.ts
+++ /dev/null
@@ -1,442 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- analyzeCodeIndent,
- type CodeIndentPlan,
- isOffsetInsideCodeBlock,
- scanCodeBlocks,
-} from '@app/features/lexical/composer/codeBlockIndent';
-import {
- computeMarkdownHighlightSpans,
- DEFAULT_COMPOSER_MARKDOWN_FLAGS,
- MarkdownHl,
-} from '@app/features/lexical/composer/markdownSpans';
-import {parseMarkdownAstWithWasm} from '@app/features/messaging/utils/markdown/parser/MarkdownParserWasm';
-import type {CodeBlockNode, Node} from '@app/features/messaging/utils/markdown/parser/Nodes';
-import {describe, expect, it} from 'vitest';
-
-type OffsetRow = [label: string, text: string, offset: number, expected: boolean];
-
-const OFFSET_ROWS: Array<OffsetRow> = [
- ['a caret right after a lone opening fence is inside', '```', 3, true],
- ['a caret before the opening fence is outside', '```', 0, false],
- ['a caret within the opening backtick run is outside', '```', 2, false],
- ['two backticks do not open a block', '``', 2, false],
- ['a caret after the language of an unclosed fence is inside', '```js', 5, true],
- ['a caret between the fence and its language is inside', '```js', 3, true],
- ['the empty line after an opening fence is inside', '```\n', 4, true],
- ['the end of an unclosed block is inside', '```js\nconst a = 1', 17, true],
- ['a fence indented by four spaces opens a block', ' ```\ncode', 12, true],
- ['a tab-indented fence opens a block', '\t```\ncode', 9, true],
- ['a caret after the language on the opening line of a closed block is inside', '```js\ncode\n```', 5, true],
- ['a caret in the body of a closed block is inside', '```\ncode\n```', 6, true],
- ['the start of the closing fence line is inside', '```\ncode\n```', 9, true],
- ['a caret within the closing backtick run is outside', '```\ncode\n```', 10, false],
- ['a caret after the closing fence is outside', '```\ncode\n```', 12, false],
- ['trailing spaces after the closing fence stay outside', '```\ncode\n``` ', 14, false],
- ['the indent before an indented closing fence is inside', '```\ncode\n ```', 11, true],
- ['a caret after an indented closing fence is outside', '```\ncode\n ```', 14, false],
- ['content before a closing fence on the same line is inside', '```\ncode ```', 9, true],
- ['a caret after a closing fence that follows content is outside', '```\ncode ```', 12, false],
- ['a fence followed by text does not close the block', '```\ncode\n```x', 13, true],
- ['a longer backtick run closes the block', '```\ncode\n````', 13, false],
- ['a caret right after a closing fence with text after it is outside', '```\na\n``` x ```', 9, false],
- ['text after a closing fence can open a new block', '```\na\n``` x ```', 15, true],
- ['a caret inside a one-line block is inside', '```hello```', 5, true],
- ['a caret after a one-line block is outside', '```hello```', 11, false],
- ['the line after a one-line block is outside', '```hello```\nmore', 16, false],
- ['a one-line block inside prose holds the caret', 'use ```foo``` here', 9, true],
- ['prose after a one-line block is outside', 'use ```foo``` here', 18, false],
- ['a backtick left over after a one-line block is outside', '```a````', 8, false],
- ['a caret after a midline opening fence is inside', 'label```js\ncode', 15, true],
- ['a caret before a midline opening fence is outside', 'label```js\ncode', 5, false],
- ['a caret before the midline fence of a closed block is outside', 'label```js\ncode\n```', 5, false],
- ['an unclosed fence after text on the same line is inside', 'hello ```', 9, true],
- ['a sentence that mentions a fence stays outside', 'type ``` to start a block', 25, false],
- ['prose that holds an unmatched fence stays outside', 'use ``` for code blocks', 23, false],
- ['an unclosed fence whose info is not a language opens a block at the start of a line', '```js hello', 11, true],
- ['a lone fence followed by a space is inside', '``` ', 4, true],
- ['a midline fence after a preceding line holds its body', 'intro line\nlabel```rust\nfn main() {}\n```', 29, true],
- [
- 'a caret after a midline block that follows a line is outside',
- 'intro line\nlabel```rust\nfn main() {}\n```',
- 40,
- false,
- ],
- ['an escaped fence does not open a block', '\\```js\ncode', 11, false],
- ['an escaped backslash leaves the fence live', '\\\\```js\ncode', 12, true],
- ['a one-line block after an escaped backslash holds the caret', '\\\\```hello```', 7, true],
- ['a caret after a one-line block that follows an escaped backslash is outside', '\\\\```hello```', 13, false],
- ['a longer escaped fence stays text', '\\````hello````', 7, false],
- ['the end of a longer escaped fence stays outside', '\\````hello````', 14, false],
- ['an escaped midline fence stays text', 'label\\```rust\nfn main() {}\n```', 19, false],
- ['a fence inside inline code does not open a block', '`` ``` ``\ncode', 14, false],
- ['a fence inside inline code in prose does not open a block', 'use `` ``` `` to open a block', 29, false],
- ['a caret on a fence inside inline code is outside', 'use `` ``` `` to open a block', 8, false],
- ['a fence after closed inline code opens a block', '`code` ```js\nx', 14, true],
- ['a block opened after closed inline code holds its body', '`code` ```js\nxy\n```', 14, true],
- ['a caret after a block opened after closed inline code is outside', '`code` ```js\nxy\n```', 19, false],
- ['three backticks do not close a four-backtick fence', '````\ncode\n```\nmore', 18, true],
- ['a four-backtick block holds a three-backtick line', '````\ncode\n```\nmore\n````', 16, true],
- ['a caret after a four-backtick block is outside', '````\ncode\n```\nmore\n````', 23, false],
- [
- 'an unclosed longer outer fence wins over a closed inner block because the user is still writing the outer block',
- '````\ncode\n```\nmore\n```',
- 22,
- true,
- ],
- ['the end of the first closing fence line is outside', '```\na\n```\ntext\n```\nb\n```', 9, false],
- ['text between two blocks is outside', '```\na\n```\ntext\n```\nb\n```', 12, false],
- ['the end of the text between two blocks is outside', '```\na\n```\ntext\n```\nb\n```', 14, false],
- ['the body of the second of two blocks is inside', '```\na\n```\ntext\n```\nb\n```', 20, true],
- ['a caret after the second of two blocks is outside', '```\na\n```\ntext\n```\nb\n```', 24, false],
- ['a block that opens after a closed block is inside', '```\na\n```\n```\n', 14, true],
- ['the caret after the opening fence of an empty block is inside', '```\n```', 3, true],
- ['the body of an empty block is inside', '```\n```', 4, true],
- ['the closing fence of an empty block reopens a block, as the parser reads it', '```\n```', 7, true],
- ['the empty middle line of an empty block is inside', '```\n\n```', 4, true],
- ['a closed block inside a block spoiler holds the caret', '||```\ncode\n```||', 10, true],
- ['a caret after a block spoiler around a closed block is outside', '||```\ncode\n```||', 16, false],
- ['a fence in an unclosed block spoiler opens a block', '||```\ncode', 10, true],
- ['an unclosed quoted fence ends with its quote', '> ```\ncode\n```', 10, false],
- ['an unquoted fence after a quoted fence opens another block', '> ```\ncode\n```', 14, true],
- ['a block closed on a quoted line holds the caret', '> ```\n> code\n> ```', 12, true],
- ['a caret after a block closed on a quoted line is outside', '> ```\n> code\n> ```', 18, false],
- ['a multiline quote holds a closed block', '>>> ```\ncode\n```', 12, true],
- ['a caret after a closed block in a multiline quote is outside', '>>> ```\ncode\n```', 16, false],
- ['an unclosed quoted fence does not hold the text after the quote', '> ```\ncode\nnormal text', 22, false],
- ['an unclosed quoted fence does not hold a later unquoted line', '> ```\n> code\nplain', 18, false],
- ['an unclosed spoilered fence does not hold the text after the spoiler', '||```\ncode|| after', 18, false],
- ['a fence on a list item line does not open a block', '- ```', 5, false],
- ['a fence on a numbered list item line does not open a block', '1. ```\ncode', 11, false],
- ['a closed block written on a list item line does not open a block', '- ```\ncode\n```', 8, false],
- ['a fence in prose on a list item line does not open a block', '- use ``` for code', 18, false],
- ['a fence on the line after a list item opens a block', '- a\n```\ncode\n```', 9, true],
- ['empty text is outside', '', 0, false],
- ['plain text is outside', 'hello', 5, false],
-];
-
-type BodyRow = [label: string, text: string, bodies: ReturnType<typeof scanCodeBlocks>];
-
-const BODY_ROWS: Array<BodyRow> = [
- ['a closed block', '```\ncode\n```', [{start: 3, end: 9, rendered: true}]],
- ['an unclosed block runs to the end of the text', '```js\ncode', [{start: 3, end: 10, rendered: false}]],
- [
- 'an empty block is not rendered and its closing fence opens another block',
- '```\n\n```',
- [
- {start: 3, end: 5, rendered: false},
- {start: 8, end: 8, rendered: false},
- ],
- ],
- [
- 'an unclosed outer fence and the closed block inside it',
- '````\ncode\n```\nmore\n```',
- [
- {start: 4, end: 22, rendered: false},
- {start: 13, end: 19, rendered: true},
- ],
- ],
- [
- 'a closed block inside an unclosed block spoiler is not rendered',
- '||```\ncode\n```',
- [{start: 5, end: 11, rendered: false}],
- ],
- ['a closed block inside a block spoiler', '||```\ncode\n```||', [{start: 5, end: 11, rendered: true}]],
- ['a fence written on a list item line', '- ```\ncode\n```', [{start: 14, end: 14, rendered: false}]],
- ['an unclosed quoted fence bounded by its quote', '> ```\ncode\nnormal text', [{start: 5, end: 5, rendered: false}]],
- ['an unclosed spoilered fence bounded by its spoiler', '||```\ncode|| after', [{start: 5, end: 10, rendered: false}]],
- ['prose that holds an unmatched fence', 'use ``` for code blocks', []],
-];
-
-type IndentRow = [
- label: string,
- text: string,
- selectionStart: number,
- selectionEnd: number,
- unindent: boolean,
- expected: CodeIndentPlan | null,
-];
-
-function tabAt(offset: number): CodeIndentPlan {
- return {edits: [{start: offset, end: offset, text: '\t'}], selectionStart: offset + 1, selectionEnd: offset + 1};
-}
-
-const INDENT_ROWS: Array<IndentRow> = [
- ['still indents the caret in the body of a closed block', '```\ncode\n```', 4, 4, false, tabAt(4)],
- ['still ignores a caret on the closing fence line', '```\ncode\n```', 12, 12, false, null],
- ['still indents the caret at the end of an unclosed block', '```\ncode', 8, 8, false, tabAt(8)],
- [
- 'still unindents a tab in the body',
- '```\n\tcode\n```',
- 5,
- 5,
- true,
- {edits: [{start: 4, end: 5, text: ''}], selectionStart: 4, selectionEnd: 4},
- ],
- [
- 'still indents every selected body line',
- '```\na\nb\n```',
- 4,
- 7,
- false,
- {
- edits: [
- {start: 4, end: 4, text: '\t'},
- {start: 6, end: 6, text: '\t'},
- ],
- selectionStart: 5,
- selectionEnd: 9,
- },
- ],
- ['still ignores an indented closing fence line', '```\ncode\n ```', 14, 14, false, null],
- ['still treats content before a closing fence on its line as code', '```\ncode ```', 8, 8, false, tabAt(8)],
- ['no longer treats the line after a one-line block as code', '```hello```\nmore', 16, 16, false, null],
- [
- 'no longer lets three backticks close a four-backtick fence',
- '````\ncode\n```\nmore\n````',
- 18,
- 18,
- false,
- tabAt(18),
- ],
- ['recognises a midline opening fence', 'label```js\ncode\n```', 15, 15, false, tabAt(15)],
- ['recognises a fence indented by four spaces', ' ```\ncode', 12, 12, false, tabAt(12)],
- ['no longer indents the line after an unclosed quoted fence', '> ```\ncode\nnormal text', 22, 22, false, null],
- ['no longer indents the line after a fence on a list item line', '- ```\ncode', 10, 10, false, null],
- [
- 'indents the code after the quote prefix on a selected quoted line',
- '> ```\n> code\n> ```',
- 6,
- 12,
- false,
- {edits: [{start: 8, end: 8, text: '\t'}], selectionStart: 9, selectionEnd: 13},
- ],
- [
- 'indents every selected quoted body line after its prefix',
- '> ```\n> a\n> b\n> ```',
- 6,
- 13,
- false,
- {
- edits: [
- {start: 8, end: 8, text: '\t'},
- {start: 12, end: 12, text: '\t'},
- ],
- selectionStart: 9,
- selectionEnd: 15,
- },
- ],
- [
- 'unindents a tab after the quote prefix',
- '> ```\n> \tcode\n> ```',
- 6,
- 13,
- true,
- {edits: [{start: 8, end: 9, text: ''}], selectionStart: 8, selectionEnd: 12},
- ],
- [
- 'unindents four spaces after the quote prefix',
- '> ```\n> code\n> ```',
- 6,
- 16,
- true,
- {edits: [{start: 8, end: 12, text: ''}], selectionStart: 8, selectionEnd: 12},
- ],
- [
- 'indents after an indented quote prefix',
- ' > ```\n > a\n > ```',
- 8,
- 13,
- false,
- {edits: [{start: 12, end: 12, text: '\t'}], selectionStart: 13, selectionEnd: 14},
- ],
- [
- 'keeps "> " as code inside a multiline quote fence',
- '>>> ```\n> a\n```',
- 8,
- 11,
- false,
- {edits: [{start: 8, end: 8, text: '\t'}], selectionStart: 9, selectionEnd: 12},
- ],
- ['ignores a caret at the start of a quoted closing fence', '> ```\n> code\n> ```', 15, 15, false, null],
- ['ignores a caret at the end of a quoted closing fence', '> ```\n> code\n> ```', 18, 18, false, null],
- [
- 'collapses a selection inside a quote prefix onto the indented content',
- '> ```\n> a\n> ```',
- 6,
- 7,
- false,
- {edits: [{start: 8, end: 8, text: '\t'}], selectionStart: 9, selectionEnd: 9},
- ],
- [
- 'collapses a caret inside a quote prefix onto the unindented content',
- '> ```\n> \ta\n> b\n> ```',
- 7,
- 7,
- true,
- {edits: [{start: 8, end: 9, text: ''}], selectionStart: 8, selectionEnd: 8},
- ],
-];
-
-const HIGHLIGHT_ROWS: Array<[text: string, offset: number, expected: boolean]> = [
- ['```\ncode\n```', 6, true],
- ['```hello```', 5, true],
- ['use ```foo``` here', 9, true],
- ['intro line\nlabel```rust\nfn main() {}\n```', 29, true],
- ['\\\\```hello```', 7, true],
- ['`code` ```js\nxy\n```', 14, true],
- ['````\ncode\n```\nmore\n````', 16, true],
- ['```\na\n```\ntext\n```\nb\n```', 20, true],
- ['```\na\n```\ntext\n```\nb\n```', 12, false],
- ['\\````hello````', 7, false],
- ['label\\```rust\nfn main() {}\n```', 19, false],
- ['use `` ``` `` to open a block', 8, false],
-];
-
-const CONTAINER_FIXTURES = [
- 'hi\n||```\ncode\n```||',
- '||a||\n```\ncode\n```',
- '||\n```\ncode\n```\n||',
- '> > ```\n> code\n> ```',
- '>>> a\n> ```\n> code\n> ```',
- '> [!NOTE]\n> ```\n> code\n> ```',
- '- a\n```\ncode\n```',
- '```\n```\ncode\n```',
- '```js title\ncode\n```',
-];
-
-const INVISIBLE_CONTENT_FIXTURES = [
- '```\n\u200b\n```',
- '```\n\u00a0\u3164\n```',
- '```\u034f```',
- '```\na\u034f\n```',
- '```\n\ufe0f\n```\ncode\n```',
- '||\u200b\n```\n||',
-];
-
-const CORPUS_PIECES = [
- '```',
- '```',
- '`',
- '\\',
- ' ',
- ' ',
- '\t',
- '\n',
- '\n',
- '\n',
- '> ',
- '>>> ',
- '||',
- '|',
- '>',
- '- ',
- '* ',
- '1. ',
- 'a',
- 'x',
-];
-const CORPUS_SIZE = 5000;
-const CORPUS_MAX_PIECES = 24;
-
-function createCorpus(): Array<string> {
- let state = 0x2545f491;
- const nextIndex = (bound: number): number => {
- state ^= state << 13;
- state ^= state >>> 17;
- state ^= state << 5;
- return (state >>> 0) % bound;
- };
- return Array.from({length: CORPUS_SIZE}, () =>
- Array.from({length: 1 + nextIndex(CORPUS_MAX_PIECES)}, () => CORPUS_PIECES[nextIndex(CORPUS_PIECES.length)]).join(
- '',
- ),
- );
-}
-
-function collectCodeBlocks(nodes: ReadonlyArray<Node>): Array<CodeBlockNode> {
- return nodes.flatMap((node) => {
- if (node.type === 'CodeBlock') {
- return [node];
- }
- if (node.type === 'List') {
- return node.items.flatMap((item) => collectCodeBlocks(item.children));
- }
- return 'children' in node ? collectCodeBlocks(node.children) : [];
- });
-}
-
-function withoutQuoteMarkersOrWhitespace(value: string): string {
- return value.replace(/[\s>]/g, '');
-}
-
-function parserCodeBlocks(text: string): Array<string> {
- return collectCodeBlocks(parseMarkdownAstWithWasm(text, DEFAULT_COMPOSER_MARKDOWN_FLAGS).nodes).map((node) =>
- withoutQuoteMarkersOrWhitespace(`${node.language ?? ''}${node.content}`),
- );
-}
-
-function scannedCodeBlocks(text: string): Array<string> {
- return scanCodeBlocks(text)
- .filter((body) => body.rendered)
- .map((body) => withoutQuoteMarkersOrWhitespace(text.slice(body.start, body.end)));
-}
-
-describe('isOffsetInsideCodeBlock', () => {
- it.each(OFFSET_ROWS)('%s', (_label, text, offset, expected) => {
- expect(isOffsetInsideCodeBlock(text, offset)).toBe(expected);
- });
-});
-
-describe('scanCodeBlocks', () => {
- it.each(BODY_ROWS)('reports %s', (_label, text, bodies) => {
- expect(scanCodeBlocks(text)).toEqual(bodies);
- });
-});
-
-describe('scanCodeBlocks against the markdown parser', () => {
- const fixtures = new Set([
- ...OFFSET_ROWS.map(([, text]) => text),
- ...BODY_ROWS.map(([, text]) => text),
- ...INDENT_ROWS.map(([, text]) => text),
- ...CONTAINER_FIXTURES,
- ...INVISIBLE_CONTENT_FIXTURES,
- ]);
-
- it.each([...fixtures])('closes the same blocks as the parser in %j', (text) => {
- expect(scannedCodeBlocks(text)).toEqual(parserCodeBlocks(text));
- });
-
- it('closes the same blocks as the parser across a seeded generated corpus', () => {
- const containers = new Set<string>();
- for (const text of createCorpus()) {
- for (const node of parseMarkdownAstWithWasm(text, DEFAULT_COMPOSER_MARKDOWN_FLAGS).nodes) {
- if (collectCodeBlocks([node]).length > 0) {
- containers.add(node.type);
- }
- }
- expect({text, blocks: scannedCodeBlocks(text)}).toEqual({text, blocks: parserCodeBlocks(text)});
- }
- expect([...containers.keys()].sort()).toEqual(['Blockquote', 'CodeBlock', 'List', 'Spoiler']);
- });
-
- it.each(HIGHLIGHT_ROWS)('agrees with the composer highlight in %j at %i', (text, offset, expected) => {
- expect(isOffsetInsideCodeBlock(text, offset)).toBe(expected);
- expect(
- computeMarkdownHighlightSpans(text).some(
- (span) =>
- span.role === 'content' &&
- (span.format & MarkdownHl.codeBlock) !== 0 &&
- span.start < offset &&
- offset < span.end,
- ),
- ).toBe(expected);
- });
-});
-
-describe('analyzeCodeIndent', () => {
- it.each(INDENT_ROWS)('%s', (_label, text, selectionStart, selectionEnd, unindent, expected) => {
- expect(analyzeCodeIndent(text, selectionStart, selectionEnd, unindent)).toEqual(expected);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/codeBlockWrap.test.ts b/fluxer_app/src/features/lexical/composer/codeBlockWrap.test.ts
deleted file mode 100644
index 60a92fcda..000000000
--- a/fluxer_app/src/features/lexical/composer/codeBlockWrap.test.ts
+++ /dev/null
@@ -1,619 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import assert from 'node:assert/strict';
-import {registerComposerMarkdownHighlight} from '@app/features/lexical/composer/ComposerMarkdownHighlight';
-import {type CodeBlockWrapPlan, planCodeBlockWrap} from '@app/features/lexical/composer/codeBlockWrap';
-import {
- $captureSelectionOffsets,
- $getComposerDisplayText,
- $isComposerSelectionWrapped,
- $replaceComposerRange,
- $selectComposerRange,
- $wrapComposerSelection,
-} from '@app/features/lexical/composer/composerOffsets';
-import {DEFAULT_COMPOSER_MARKDOWN_FLAGS} from '@app/features/lexical/composer/markdownSpans';
-import {ComposerBlockquoteLineNode} from '@app/features/lexical/composer/nodes/ComposerBlockquoteLineNode';
-import {ComposerBlockquoteMarkerNode} from '@app/features/lexical/composer/nodes/ComposerBlockquoteMarkerNode';
-import {
- $isComposerCustomEmojiNode,
- ComposerCustomEmojiNode,
-} from '@app/features/lexical/composer/nodes/ComposerCustomEmojiNode';
-import {$isComposerMentionNode, ComposerMentionNode} from '@app/features/lexical/composer/nodes/ComposerMentionNode';
-import {$isSyntaxMarkerNode, SyntaxMarkerNode} from '@app/features/lexical/composer/nodes/SyntaxMarkerNode';
-import {parseMarkdownAstWithWasm} from '@app/features/messaging/utils/markdown/parser/MarkdownParserWasm';
-import type {CodeBlockNode, Node} from '@app/features/messaging/utils/markdown/parser/Nodes';
-import {createEmptyHistoryState, registerHistory} from '@lexical/history';
-import {
- $getNodeByKey,
- $getRoot,
- $isElementNode,
- createEditor,
- type LexicalEditor,
- type NodeKey,
- REDO_COMMAND,
- UNDO_COMMAND,
-} from 'lexical';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/lexical/composer/nodes/ComposerMentionPill', () => ({ComposerMentionPill: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerCustomEmoji', () => ({ComposerCustomEmoji: () => null}));
-vi.mock('@app/features/lexical/composer/nodes/ComposerStandardEmoji', () => ({ComposerStandardEmoji: () => null}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-
-interface PlanResult {
- wrapped: boolean;
- text: string;
- selection: [number, number];
-}
-
-type PlanRow = [label: string, text: string, start: number, end: number, expected: PlanResult | null];
-
-function applyPlan(
- text: string,
- {wrapped, opening, closing, selectionStart, selectionEnd}: CodeBlockWrapPlan,
-): PlanResult {
- const head = text.slice(0, opening.start);
- const middle = text.slice(opening.end, closing.start);
- return {
- wrapped,
- text: `${head}${opening.text}${middle}${closing.text}${text.slice(closing.end)}`,
- selection: [selectionStart, selectionEnd],
- };
-}
-
-function planned(text: string, start: number, end: number): PlanResult | null {
- const plan = planCodeBlockWrap(text, start, end);
- return plan == null ? null : applyPlan(text, plan);
-}
-
-const PLAN_ROWS: Array<PlanRow> = [
- ['keeps inline code for a single-line selection', 'say hello there', 4, 9, null],
- ['keeps inline code for a single-line selection beside a block', '```\na\n```\nhello there', 10, 15, null],
- ['keeps inline code for a collapsed caret', 'a\nb', 1, 1, null],
- ['keeps inline code for one line inside a block', '```\na\nb\n```', 4, 5, null],
- ['declines a selection of newlines only', 'a\n\nb', 1, 3, null],
- ['declines part of a block body', '```\na\nb\nc\n```', 4, 7, null],
- ['declines a selection that ends inside a block', 'x\n```\na\nb\n```', 0, 7, null],
- ['declines a block whose opening line holds content rather than a language', '```a b\nc\nd\n```', 7, 10, null],
- ['declines a fenced block inside a quote', '> ```\n> a\n> b\n> ```', 6, 13, null],
- ['declines a block inside a spoiler that never closed', '||\n```\na\nb\n```', 7, 10, null],
- ['declines whitespace-only lines the parser would not render as a block', ' \n ', 0, 3, null],
- ['declines a selection across a block, text and another block', '```\na\n```\nmid\n```\nb\n```', 4, 19, null],
- [
- 'wraps a multiline selection inside a block that is still open',
- '```\na\nb',
- 4,
- 7,
- {wrapped: false, text: '```\n```\na\nb\n```', selection: [8, 11]},
- ],
- ['wraps a whole two-line message', 'a\nb', 0, 3, {wrapped: false, text: '```\na\nb\n```', selection: [4, 7]}],
- [
- 'wraps whole lines in the middle without inserting breaks',
- 'x\na\nb\ny',
- 2,
- 5,
- {wrapped: false, text: 'x\n```\na\nb\n```\ny', selection: [6, 9]},
- ],
- [
- 'inserts a break before the opening fence when the selection starts mid-line',
- 'hi a\nb',
- 3,
- 6,
- {wrapped: false, text: 'hi \n```\na\nb\n```', selection: [8, 11]},
- ],
- [
- 'inserts a break after the closing fence when the selection ends mid-line',
- 'a\nb bye',
- 0,
- 3,
- {wrapped: false, text: '```\na\nb\n```\n bye', selection: [4, 7]},
- ],
- [
- 'inserts a break at both edges when the selection starts and ends mid-line',
- 'hi a\nb bye',
- 3,
- 6,
- {wrapped: false, text: 'hi \n```\na\nb\n```\n bye', selection: [8, 11]},
- ],
- [
- 'keeps a selected trailing newline outside the block',
- 'a\nb\nc',
- 0,
- 4,
- {wrapped: false, text: '```\na\nb\n```\nc', selection: [4, 7]},
- ],
- [
- 'keeps a selected leading newline outside the block',
- 'x\na\nb',
- 1,
- 5,
- {wrapped: false, text: 'x\n```\na\nb\n```', selection: [6, 9]},
- ],
- [
- 'keeps several selected edge newlines outside the block',
- 'x\n\na\nb\n\ny',
- 1,
- 8,
- {wrapped: false, text: 'x\n\n```\na\nb\n```\n\ny', selection: [7, 10]},
- ],
- [
- 'treats one line with its selected line break as a block',
- 'foo\nbar',
- 0,
- 4,
- {wrapped: false, text: '```\nfoo\n```\nbar', selection: [4, 7]},
- ],
- [
- 'wraps the lines between two blocks',
- '```\nA\n```\nB\nC\n```\nD\n```',
- 10,
- 13,
- {wrapped: false, text: '```\nA\n```\n```\nB\nC\n```\n```\nD\n```', selection: [14, 17]},
- ],
- [
- 'wraps a multiline selection of inline code that never closed',
- '`a\nb`',
- 0,
- 5,
- {wrapped: false, text: '```\n`a\nb`\n```', selection: [4, 9]},
- ],
- [
- 'wraps two whole blocks in a longer fence',
- '```\na\n```\n```\nb\n```',
- 0,
- 19,
- {wrapped: false, text: '````\n```\na\n```\n```\nb\n```\n````', selection: [5, 24]},
- ],
- [
- 'wraps content that already holds a fence in a longer fence',
- 'x\n```\ny\n```\nz',
- 0,
- 13,
- {wrapped: false, text: '````\nx\n```\ny\n```\nz\n````', selection: [5, 18]},
- ],
- [
- 'unwraps when the block content is selected',
- '```\na\nb\n```',
- 4,
- 7,
- {wrapped: true, text: 'a\nb', selection: [0, 3]},
- ],
- [
- 'unwraps a block and leaves the text around it alone',
- 'x\n```\na\nb\n```\ny',
- 6,
- 9,
- {wrapped: true, text: 'x\na\nb\ny', selection: [2, 5]},
- ],
- [
- 'unwraps a block that is followed by a line the wrap kept outside',
- '```\na\nb\n```\nc',
- 4,
- 7,
- {wrapped: true, text: 'a\nb\nc', selection: [0, 3]},
- ],
- [
- 'unwraps a block whose content is a single line',
- '```\nfoo\n```\nbar',
- 4,
- 7,
- {wrapped: true, text: 'foo\nbar', selection: [0, 3]},
- ],
- [
- 'unwraps when the fences are selected too',
- '```\na\nb\n```',
- 0,
- 11,
- {wrapped: true, text: 'a\nb', selection: [0, 3]},
- ],
- [
- 'unwraps when the fences and the newlines around them are selected',
- 'x\n```\na\nb\n```\ny',
- 1,
- 14,
- {wrapped: true, text: 'x\na\nb\ny', selection: [2, 5]},
- ],
- ['unwraps a block with a language fence', '```js\na\nb\n```', 6, 9, {wrapped: true, text: 'a\nb', selection: [0, 3]}],
- [
- 'unwraps a block that follows an escaped fence',
- '\\```\n```\na\nb\n```',
- 9,
- 12,
- {wrapped: true, text: '\\```\na\nb', selection: [5, 8]},
- ],
- [
- 'unwraps a block written with a longer fence',
- '````\nx\n```\ny\n```\nz\n````',
- 5,
- 18,
- {wrapped: true, text: 'x\n```\ny\n```\nz', selection: [0, 13]},
- ],
- [
- 'unwraps a block whose closing fence has trailing spaces',
- '```\na\nb\n``` ',
- 4,
- 7,
- {wrapped: true, text: 'a\nb', selection: [0, 3]},
- ],
- ['declines a block whose closing fence is longer than its opening fence', '```\na\nb\n`````', 4, 7, null],
- ['declines a block whose opening fence is followed by spaces', '``` \na\nb\n```', 6, 9, null],
-];
-
-const ROUND_TRIP_ROWS: Array<[text: string, start: number, end: number]> = [
- ['a\nb', 0, 3],
- ['x\na\nb\ny', 2, 5],
- ['a\nb\nc', 0, 4],
- ['x\na\nb', 1, 5],
- ['x\n\na\nb\n\ny', 1, 8],
- ['foo\nbar', 0, 4],
- ['```\nA\n```\nB\nC\n```\nD\n```', 10, 13],
- ['`a\nb`', 0, 5],
- ['```\na\n```\n```\nb\n```', 0, 19],
- ['x\n```\ny\n```\nz', 0, 13],
- ['```\na\nb', 4, 7],
- ['> a\n> b', 0, 7],
-];
-
-const PARSER_ROWS: Array<[text: string, start: number, end: number, content: string]> = [
- ['a\nb', 0, 3, 'a\nb\n'],
- ['hi a\nb bye', 3, 6, 'a\nb\n'],
- ['```\na\nb', 4, 7, 'a\nb\n'],
- ['x\n```\ny\n```\nz', 0, 13, 'x\n```\ny\n```\nz\n'],
- ['> a\n> b', 0, 7, '> a\n> b\n'],
-];
-
-function createComposer(): LexicalEditor {
- const editor = createEditor({
- namespace: 'code-block-wrap-test',
- nodes: [
- ComposerBlockquoteLineNode,
- ComposerBlockquoteMarkerNode,
- ComposerCustomEmojiNode,
- ComposerMentionNode,
- SyntaxMarkerNode,
- ],
- onError: (error) => {
- throw error;
- },
- });
- registerComposerMarkdownHighlight(editor);
- return editor;
-}
-
-function seeded(text: string, anchor: number, focus: number): LexicalEditor {
- const editor = createComposer();
- editor.update(
- () => {
- $replaceComposerRange(0, 0, {kind: 'text', text}, {leading: false, trailing: false});
- $selectComposerRange(anchor, focus);
- },
- {discrete: true},
- );
- return editor;
-}
-
-function clickFormat(editor: LexicalEditor, wrapper: string): void {
- editor.update(() => $wrapComposerSelection(wrapper, wrapper), {discrete: true});
-}
-
-function composerState(editor: LexicalEditor): {
- text: string;
- selection: {anchor: number; focus: number} | null;
- pressed: boolean;
-} {
- return editor.read(() => ({
- text: $getComposerDisplayText(),
- selection: $captureSelectionOffsets(),
- pressed: $isComposerSelectionWrapped('`', '`'),
- }));
-}
-
-function atomicKeys(editor: LexicalEditor): Array<NodeKey> {
- return editor.read(() => {
- const paragraph = $getRoot().getFirstChildOrThrow();
- assert($isElementNode(paragraph), 'Expected composer paragraph');
- return paragraph
- .getChildren()
- .filter((node) => $isComposerMentionNode(node) || $isComposerCustomEmojiNode(node))
- .map((node) => node.getKey());
- });
-}
-
-function atomicState(editor: LexicalEditor, keys: Array<NodeKey>): Array<{attached: boolean; literal: boolean} | null> {
- return editor.read(() =>
- keys.map((key) => {
- const node = $getNodeByKey(key);
- if (!$isComposerMentionNode(node) && !$isComposerCustomEmojiNode(node)) {
- return null;
- }
- return {attached: node.isAttached(), literal: node.isLiteral()};
- }),
- );
-}
-
-function markerTexts(editor: LexicalEditor): Array<string> {
- return editor.read(() =>
- $getRoot()
- .getAllTextNodes()
- .filter($isSyntaxMarkerNode)
- .map((node) => node.getTextContent()),
- );
-}
-
-describe('planCodeBlockWrap', () => {
- it.each(PLAN_ROWS)('%s', (_label, text, start, end, expected) => {
- expect(planned(text, start, end)).toEqual(expected);
- });
-
- it.each(ROUND_TRIP_ROWS)('round trips %j selected from %i to %i', (text, start, end) => {
- const wrapped = planned(text, start, end);
- const unwrapped = wrapped == null ? null : planned(wrapped.text, ...wrapped.selection);
- expect({wrapped: unwrapped?.wrapped, text: unwrapped?.text}).toEqual({wrapped: true, text});
- });
-
- it('keeps the breaks a mid-line wrap inserted when the block is unwrapped again', () => {
- const wrapped = planned('hi a\nb bye', 3, 6);
- expect(wrapped).toEqual({wrapped: false, text: 'hi \n```\na\nb\n```\n bye', selection: [8, 11]});
- expect(wrapped == null ? null : planned(wrapped.text, ...wrapped.selection)).toEqual({
- wrapped: true,
- text: 'hi \na\nb\n bye',
- selection: [4, 7],
- });
- });
-});
-
-function collectCodeBlocks(nodes: ReadonlyArray<Node>): Array<CodeBlockNode> {
- return nodes.flatMap((node) => {
- if (node.type === 'CodeBlock') {
- return [node];
- }
- if (node.type === 'List') {
- return node.items.flatMap((item) => collectCodeBlocks(item.children));
- }
- return 'children' in node ? collectCodeBlocks(node.children) : [];
- });
-}
-
-function parsedCodeBlocks(text: string): Array<string> {
- return collectCodeBlocks(parseMarkdownAstWithWasm(text, DEFAULT_COMPOSER_MARKDOWN_FLAGS).nodes).map(
- (node) => node.content,
- );
-}
-
-describe('planCodeBlockWrap against the markdown parser', () => {
- it.each(PARSER_ROWS)('wraps %j from %i to %i into one block the parser renders', (text, start, end, content) => {
- expect(parsedCodeBlocks(planned(text, start, end)?.text ?? '')).toEqual([content]);
- });
-});
-
-describe('the composer code option', () => {
- it('wraps a mid-line multiline selection in fence lines', () => {
- const editor = seeded('hi a\nb bye', 3, 6);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: 'hi \n```\na\nb\n```\n bye',
- selection: {anchor: 8, focus: 11},
- pressed: true,
- });
- expect(markerTexts(editor)).toEqual(['```', '```']);
- });
-
- it('restores the text when it is used twice on whole lines', () => {
- const editor = seeded('x\na\nb\ny', 2, 5);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: 'x\n```\na\nb\n```\ny',
- selection: {anchor: 6, focus: 9},
- pressed: true,
- });
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'x\na\nb\ny', selection: {anchor: 2, focus: 5}, pressed: false});
- });
-
- it('keeps a backward selection backward through both clicks', () => {
- const editor = seeded('a\nb', 3, 0);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '```\na\nb\n```',
- selection: {anchor: 7, focus: 4},
- pressed: true,
- });
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'a\nb', selection: {anchor: 3, focus: 0}, pressed: false});
- });
-
- it('unwraps a block whose fences are selected as well', () => {
- const editor = seeded('```\na\nb\n```', 0, 11);
- expect(composerState(editor).pressed).toBe(true);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'a\nb', selection: {anchor: 0, focus: 3}, pressed: false});
- });
-
- it('unwraps a block with a language fence', () => {
- const editor = seeded('```js\na\nb\n```', 6, 9);
- expect(composerState(editor).pressed).toBe(true);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'a\nb', selection: {anchor: 0, focus: 3}, pressed: false});
- });
-
- it('still writes inline code for a single-line selection', () => {
- const editor = seeded('say hello there', 4, 9);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: 'say `hello` there',
- selection: {anchor: 5, focus: 10},
- pressed: true,
- });
- });
-
- it('still leaves other wrappers symmetric on a multiline selection', () => {
- const editor = seeded('a\nb', 0, 3);
- clickFormat(editor, '**');
- expect(composerState(editor)).toEqual({text: '**a\nb**', selection: {anchor: 2, focus: 5}, pressed: false});
- });
-
- it('wraps a multiline selection inside a block that is still open', () => {
- const editor = seeded('```\na\nb', 4, 7);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '```\n```\na\nb\n```',
- selection: {anchor: 8, focus: 11},
- pressed: true,
- });
- });
-
- it('makes no change for a multiline selection inside a block', () => {
- const editor = seeded('```\na\nb\nc\n```', 4, 7);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '```\na\nb\nc\n```',
- selection: {anchor: 4, focus: 7},
- pressed: false,
- });
- });
-
- it('makes no change for a multiline selection inside a quoted block', () => {
- const editor = seeded('> ```\n> a\n> b\n> ```', 6, 13);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '> ```\n> a\n> b\n> ```',
- selection: {anchor: 6, focus: 13},
- pressed: false,
- });
- });
-
- it('makes no change for whitespace-only lines however often it is used', () => {
- const editor = seeded(' \n ', 0, 3);
- clickFormat(editor, '`');
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: ' \n ', selection: {anchor: 0, focus: 3}, pressed: false});
- });
-
- it('removes single backticks left around a multiline selection', () => {
- const editor = seeded('`a\nb`', 1, 4);
- expect(composerState(editor).pressed).toBe(true);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'a\nb', selection: {anchor: 0, focus: 3}, pressed: false});
- });
-
- it('undoes the unwrap in one step', async () => {
- const editor = createComposer();
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 300);
- editor.update(
- () => {
- $replaceComposerRange(0, 0, {kind: 'text', text: '```\na\nb\n```'}, {leading: false, trailing: false});
- $selectComposerRange(4, 7);
- },
- {discrete: true},
- );
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: 'a\nb', selection: {anchor: 0, focus: 3}, pressed: false});
- expect(history.undoStack).toHaveLength(1);
- editor.dispatchCommand(UNDO_COMMAND, undefined);
- await Promise.resolve();
- expect(composerState(editor)).toEqual({
- text: '```\na\nb\n```',
- selection: {anchor: 4, focus: 7},
- pressed: true,
- });
- });
-
- it('keeps mention and emoji nodes when it wraps and unwraps them', () => {
- const editor = createComposer();
- editor.update(
- () => {
- $replaceComposerRange(
- 0,
- 0,
- {kind: 'mention', mentionType: 'user', id: '1', display: '@alice', wire: '<@1>'},
- {trailing: false},
- );
- $replaceComposerRange(6, 6, {kind: 'text', text: '\n'}, {leading: false, trailing: false});
- $replaceComposerRange(
- 7,
- 7,
- {kind: 'customEmoji', emojiId: '2', animated: false, display: ':blob:', wire: '<:blob:2>'},
- {trailing: false},
- );
- $selectComposerRange(0, 13);
- },
- {discrete: true},
- );
- const keys = atomicKeys(editor);
- expect(atomicState(editor, keys)).toEqual([
- {attached: true, literal: false},
- {attached: true, literal: false},
- ]);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '```\n@alice\n:blob:\n```',
- selection: {anchor: 4, focus: 17},
- pressed: true,
- });
- expect(atomicState(editor, keys)).toEqual([
- {attached: true, literal: true},
- {attached: true, literal: true},
- ]);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({
- text: '@alice\n:blob:',
- selection: {anchor: 0, focus: 13},
- pressed: false,
- });
- expect(atomicState(editor, keys)).toEqual([
- {attached: true, literal: false},
- {attached: true, literal: false},
- ]);
- });
-
- it('reads a mention as filler so backticks in its name cannot hide the block', () => {
- const editor = createComposer();
- editor.update(
- () => {
- $replaceComposerRange(0, 0, {kind: 'text', text: '```\n'}, {leading: false, trailing: false});
- $replaceComposerRange(
- 4,
- 4,
- {kind: 'mention', mentionType: 'user', id: '1', display: '@```', wire: '<@1>'},
- {trailing: false},
- );
- $replaceComposerRange(8, 8, {kind: 'text', text: '\n```'}, {leading: false, trailing: false});
- $selectComposerRange(4, 8);
- },
- {discrete: true},
- );
- expect(composerState(editor).pressed).toBe(true);
- clickFormat(editor, '`');
- expect(composerState(editor)).toEqual({text: '@```', selection: {anchor: 0, focus: 4}, pressed: false});
- });
-
- it('undoes the wrap in one step and redoes it', async () => {
- const editor = createComposer();
- const history = createEmptyHistoryState();
- registerHistory(editor, history, 300);
- editor.update(
- () => {
- $replaceComposerRange(0, 0, {kind: 'text', text: 'hi a\nb bye'}, {leading: false, trailing: false});
- $selectComposerRange(3, 6);
- },
- {discrete: true},
- );
- clickFormat(editor, '`');
- expect(history.undoStack).toHaveLength(1);
- editor.dispatchCommand(UNDO_COMMAND, undefined);
- await Promise.resolve();
- expect(composerState(editor)).toEqual({
- text: 'hi a\nb bye',
- selection: {anchor: 3, focus: 6},
- pressed: false,
- });
- editor.dispatchCommand(REDO_COMMAND, undefined);
- await Promise.resolve();
- expect(composerState(editor)).toEqual({
- text: 'hi \n```\na\nb\n```\n bye',
- selection: {anchor: 8, focus: 11},
- pressed: true,
- });
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/nodes/ComposerBlockquoteLineNode.test.ts b/fluxer_app/src/features/lexical/composer/nodes/ComposerBlockquoteLineNode.test.ts
deleted file mode 100644
index b1fd4e77f..000000000
--- a/fluxer_app/src/features/lexical/composer/nodes/ComposerBlockquoteLineNode.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- $createComposerBlockquoteLineNode,
- $getComposerLineNodes,
- $isComposerBlockquoteLineNode,
- ComposerBlockquoteLineNode,
-} from '@app/features/lexical/composer/nodes/ComposerBlockquoteLineNode';
-import {
- $createParagraphNode,
- $createRangeSelection,
- $createTextNode,
- $getRoot,
- createEditor,
- type EditorConfig,
- type LexicalEditor,
-} from 'lexical';
-import {describe, expect, it} from 'vitest';
-
-const CONFIG: EditorConfig = {namespace: 'blockquote-line-test', theme: {composerBlockquoteLine: 'quote-line'}};
-
-function createTestEditor(): LexicalEditor {
- return createEditor({
- namespace: 'blockquote-line-test',
- nodes: [ComposerBlockquoteLineNode],
- onError: (error) => {
- throw error;
- },
- });
-}
-
-describe('ComposerBlockquoteLineNode', () => {
- it('creates a span carrying the theme class', () => {
- const editor = createTestEditor();
- let dom: HTMLElement | null = null;
- editor.update(
- () => {
- dom = $createComposerBlockquoteLineNode().createDOM(CONFIG);
- },
- {discrete: true},
- );
- expect(dom).not.toBeNull();
- expect(dom!.tagName).toBe('SPAN');
- expect(dom!.className).toBe('quote-line');
- });
-
- it('is an inline node that cannot be left empty', () => {
- const editor = createTestEditor();
- let shape: {inline: boolean; canBeEmpty: boolean} | null = null;
- editor.update(
- () => {
- const wrapper = $createComposerBlockquoteLineNode();
- shape = {inline: wrapper.isInline(), canBeEmpty: wrapper.canBeEmpty()};
- },
- {discrete: true},
- );
- expect(shape).toEqual({inline: true, canBeEmpty: false});
- });
-
- it('inserts an attached empty sibling wrapper on insertNewAfter', () => {
- const editor = createTestEditor();
- let result: {isWrapper: boolean; attached: boolean; children: number; isNextSibling: boolean} | null = null;
- editor.update(
- () => {
- const paragraph = $createParagraphNode();
- const wrapper = $createComposerBlockquoteLineNode();
- wrapper.append($createTextNode('a'));
- paragraph.append(wrapper);
- $getRoot().clear().append(paragraph);
- const next = wrapper.insertNewAfter($createRangeSelection(), false);
- result = {
- isWrapper: $isComposerBlockquoteLineNode(next),
- attached: next.isAttached(),
- children: next.getChildrenSize(),
- isNextSibling: next.is(wrapper.getNextSibling()),
- };
- },
- {discrete: true},
- );
- expect(result).toEqual({isWrapper: true, attached: true, children: 0, isNextSibling: true});
- });
-});
-
-describe('$getComposerLineNodes', () => {
- it('expands wrappers in document order and leaves other children alone', () => {
- const editor = createTestEditor();
- let texts: Array<string> = [];
- let keysMatch = false;
- editor.update(
- () => {
- const paragraph = $createParagraphNode();
- const lead = $createTextNode('a');
- const wrapper = $createComposerBlockquoteLineNode();
- const marker = $createTextNode('> ');
- const body = $createTextNode('b');
- wrapper.append(marker, body);
- const tail = $createTextNode('c');
- paragraph.append(lead, wrapper, tail);
- $getRoot().clear().append(paragraph);
- const nodes = $getComposerLineNodes(paragraph);
- texts = nodes.map((node) => node.getTextContent());
- keysMatch = nodes.every((node, index) => node.is([lead, marker, body, tail][index]));
- },
- {discrete: true},
- );
- expect(texts).toEqual(['a', '> ', 'b', 'c']);
- expect(keysMatch).toBe(true);
- });
-
- it('returns the children unchanged when there is no wrapper', () => {
- const editor = createTestEditor();
- let texts: Array<string> = [];
- editor.update(
- () => {
- const paragraph = $createParagraphNode();
- paragraph.append($createTextNode('a'), $createTextNode('b'));
- $getRoot().clear().append(paragraph);
- texts = $getComposerLineNodes(paragraph).map((node) => node.getTextContent());
- },
- {discrete: true},
- );
- expect(texts).toEqual(['a', 'b']);
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/nodes/ComposerEmojiTooltip.test.tsx b/fluxer_app/src/features/lexical/composer/nodes/ComposerEmojiTooltip.test.tsx
deleted file mode 100644
index 3115a7cb0..000000000
--- a/fluxer_app/src/features/lexical/composer/nodes/ComposerEmojiTooltip.test.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type React from 'react';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/app/hooks/useShouldAnimate', () => ({useShouldAnimate: () => false}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getEmojiById: () => null}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: () => null}}));
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: (surrogate: string) => `url:${surrogate}`}));
-vi.mock('@app/features/messaging/utils/markdown/EmojiDetector', () => ({
- getEmojiRenderUrl: () => 'https://example.invalid/emoji.png',
-}));
-vi.mock('@app/features/ui/tooltip/Tooltip', () => ({
- Tooltip: ({text, children}: {text: unknown; children: React.ReactNode}) => (
- <span data-test-tooltip={typeof text === 'string' ? text : 'render-prop'} data-flx="test.tooltip">
- {children}
- </span>
- ),
-}));
-
-const {ComposerCustomEmoji} = await import('@app/features/lexical/composer/nodes/ComposerCustomEmoji');
-const {ComposerStandardEmoji} = await import('@app/features/lexical/composer/nodes/ComposerStandardEmoji');
-
-function renderCustom(): string {
- return renderToStaticMarkup(
- <ComposerCustomEmoji emojiId="10" animated={false} display=":blob:" data-flx="test.composer-custom-emoji" />,
- );
-}
-
-function renderStandard(): string {
- return renderToStaticMarkup(
- <ComposerStandardEmoji
- surrogate="🙂"
- url="https://example.invalid/slight_smile.png"
- display=":slight_smile:"
- data-flx="test.composer-standard-emoji"
- />,
- );
-}
-
-describe('ComposerCustomEmoji', () => {
- it('renders the plain name tooltip', () => {
- expect(renderCustom()).toContain('data-test-tooltip=":blob:"');
- });
-});
-
-describe('ComposerStandardEmoji', () => {
- it('renders the plain name tooltip', () => {
- expect(renderStandard()).toContain('data-test-tooltip=":slight_smile:"');
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/nodes/ComposerStandardEmoji.test.tsx b/fluxer_app/src/features/lexical/composer/nodes/ComposerStandardEmoji.test.tsx
deleted file mode 100644
index 24907fe75..000000000
--- a/fluxer_app/src/features/lexical/composer/nodes/ComposerStandardEmoji.test.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {ComposerStandardEmoji} from '@app/features/lexical/composer/nodes/ComposerStandardEmoji';
-import type React from 'react';
-import {act, createElement} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({getEmojiURL: (surrogate: string) => `url:${surrogate}`}));
-
-vi.mock('@app/features/ui/tooltip/Tooltip', () => ({
- Tooltip: ({children}: {children: React.ReactNode}) => children,
-}));
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-describe('ComposerStandardEmoji', () => {
- let host: HTMLDivElement;
- let root: Root;
-
- beforeEach(() => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- });
-
- afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
- });
-
- function render(url: string | null): HTMLImageElement | null {
- act(() => {
- root.render(createElement(ComposerStandardEmoji, {surrogate: '😀', url, display: ':grinning:'}));
- });
- return host.querySelector('img');
- }
-
- it('keeps the image the node was created with', () => {
- expect(render('url:given')?.getAttribute('src')).toBe('url:given');
- });
-
- it('derives the image from the surrogate for a node created without one', () => {
- expect(render(null)?.getAttribute('src')).toBe('url:😀');
- });
-});
diff --git a/fluxer_app/src/features/lexical/composer/specialMentions.test.ts b/fluxer_app/src/features/lexical/composer/specialMentions.test.ts
deleted file mode 100644
index 4313719f4..000000000
--- a/fluxer_app/src/features/lexical/composer/specialMentions.test.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {DEFAULT_COMPOSER_MARKDOWN_FLAGS} from '@app/features/lexical/composer/markdownSpans';
-import {
- areSpecialMentionsAllowed,
- createSpecialMentionPayload,
- findTypedSpecialMention,
- hasOpenCodeFence,
- isSpecialMentionKind,
- type SpecialMentionKind,
- type TypedSpecialMention,
-} from '@app/features/lexical/composer/specialMentions';
-import {parseMarkdownAstWithWasm} from '@app/features/messaging/utils/markdown/parser/MarkdownParserWasm';
-import {describe, expect, it} from 'vitest';
-
-const GUILD_CHANNEL = {guildId: '1', isPersonalNotes: () => false};
-const DM_CHANNEL = {guildId: undefined, isPersonalNotes: () => false};
-const PERSONAL_NOTES = {guildId: undefined, isPersonalNotes: () => true};
-
-function typedSpecialMentions(text: string): Array<SpecialMentionKind> {
- const kinds: Array<SpecialMentionKind> = [];
- let match = findTypedSpecialMention(text, 0, text.length, null);
- while (match != null) {
- kinds.push(match.kind);
- match = findTypedSpecialMention(text, match.end, text.length, null);
- }
- return kinds;
-}
-
-function collectParsedSpecialMentions(value: unknown, kinds: Array<SpecialMentionKind>): Array<SpecialMentionKind> {
- if (Array.isArray(value)) {
- for (const item of value) {
- collectParsedSpecialMentions(item, kinds);
- }
- } else if (typeof value === 'object' && value != null) {
- if ('type' in value && value.type === 'Mention' && 'kind' in value) {
- const mention = JSON.stringify(value.kind);
- if (mention === '{"kind":"Everyone"}') {
- kinds.push('@everyone');
- } else if (mention === '{"kind":"Here"}') {
- kinds.push('@here');
- }
- }
- for (const child of Object.values(value)) {
- collectParsedSpecialMentions(child, kinds);
- }
- }
- return kinds;
-}
-
-describe('findTypedSpecialMention', () => {
- it.each<[string, string, number | null, TypedSpecialMention]>([
- ['@everyone followed by a space', '@everyone ', 10, {start: 0, end: 9, kind: '@everyone'}],
- ['@here followed by a space', '@here ', 6, {start: 0, end: 5, kind: '@here'}],
- ['a finished token with no caret', 'hi @everyone', null, {start: 3, end: 12, kind: '@everyone'}],
- ['a finished token with the caret before it', 'hi @everyone', 0, {start: 3, end: 12, kind: '@everyone'}],
- ['a finished token with the caret inside it', '@here', 3, {start: 0, end: 5, kind: '@here'}],
- ['a token inside parentheses', '(@everyone)', null, {start: 1, end: 10, kind: '@everyone'}],
- ['a token inside bold markers', '**@everyone** ', 14, {start: 2, end: 11, kind: '@everyone'}],
- ['a token inside underline markers', '__@here__ ', 10, {start: 2, end: 7, kind: '@here'}],
- ['a token followed by an apostrophe', "@here's ", 8, {start: 0, end: 5, kind: '@here'}],
- ['a token followed by an underscore', '@here_now ', null, {start: 0, end: 5, kind: '@here'}],
- ['a token after a second @', '@@everyone ', null, {start: 1, end: 10, kind: '@everyone'}],
- ['a token after a mention wire', '<@1>@here ', null, {start: 4, end: 9, kind: '@here'}],
- ['a token after closed inline code', '`x` @everyone ', null, {start: 4, end: 13, kind: '@everyone'}],
- ['a token after a closed fence', '```\ncode\n```\n@everyone ', null, {start: 13, end: 22, kind: '@everyone'}],
- ['a token on a new line after an inline code line', '`x`\n@here ', null, {start: 4, end: 9, kind: '@here'}],
- ])('converts %s', (_name, text, caret, expected) => {
- expect(findTypedSpecialMention(text, 0, text.length, caret)).toEqual(expected);
- });
-
- it.each<[string, string, number | null]>([
- ['a token whose end is the caret', 'hi @everyone', 12],
- ['a token joined to a following word', '@herenow ', 9],
- ['a token with a trailing letter', '@everyones ', 11],
- ['a token with a leading word', 'foo@everyone ', 13],
- ['a token inside an email address', 'mail [email protected] ', null],
- ['a token touching a digit', '1@here 2', null],
- ['a token touching a non-latin letter', 'café@here ', null],
- ['a token after one backslash', '\\@everyone ', null],
- ['a token after two backslashes', '\\\\@everyone ', null],
- ['a token inside open inline code', '`@everyone ', null],
- ['a token inside double backtick code', '`` @everyone ``', null],
- ['a token inside an open fence', '```\n@everyone \n', null],
- ['a token inside a url', 'https://fluxer.app/@everyone ', null],
- ['a spaced @ and word', '@ everyone ', null],
- ])('leaves %s alone', (_name, text, caret) => {
- expect(findTypedSpecialMention(text, 0, text.length, caret)).toBeNull();
- });
-
- it('only considers tokens that start at from and end by to', () => {
- expect(findTypedSpecialMention('@everyone and @here ', 10, 20, 20)).toEqual({start: 14, end: 19, kind: '@here'});
- expect(findTypedSpecialMention('@everyone ', 0, 5, null)).toBeNull();
- });
-});
-
-describe('findTypedSpecialMention against the markdown parser', () => {
- it.each<[string, Array<SpecialMentionKind>, Array<SpecialMentionKind>]>([
- ['@everyone ', ['@everyone'], ['@everyone']],
- ['@here ', ['@here'], ['@here']],
- ['(@everyone)', ['@everyone'], ['@everyone']],
- ['**@everyone** ', ['@everyone'], ['@everyone']],
- ['__@here__ ', ['@here'], ['@here']],
- ["@here's ", ['@here'], ['@here']],
- ['@here_now ', ['@here'], ['@here']],
- ['@@everyone ', ['@everyone'], ['@everyone']],
- ['<@1>@here ', ['@here'], ['@here']],
- ['`x` @everyone ', ['@everyone'], ['@everyone']],
- ['```\ncode\n```\n@everyone ', ['@everyone'], ['@everyone']],
- ['\\@everyone ', [], []],
- ['\\\\@everyone ', [], []],
- ['`` @everyone ``', [], []],
- ['https://fluxer.app/@everyone ', [], []],
- ['@ everyone ', [], []],
- ['@herenow ', [], ['@here']],
- ['@everyones ', [], ['@everyone']],
- ['foo@everyone ', [], ['@everyone']],
- ['mail [email protected] ', [], ['@here']],
- ['café@here ', [], ['@here']],
- ['@everyone@here', ['@everyone'], ['@everyone', '@here']],
- ['`@everyone ', [], ['@everyone']],
- ['```\n@everyone \n', [], ['@everyone']],
- ])('%j converts %j where the parser pings %j', (text, typed, parsed) => {
- expect(typedSpecialMentions(text)).toEqual(typed);
- expect(
- collectParsedSpecialMentions(parseMarkdownAstWithWasm(text, DEFAULT_COMPOSER_MARKDOWN_FLAGS).nodes, []),
- ).toEqual(parsed);
- });
-});
-
-describe('areSpecialMentionsAllowed', () => {
- it.each<[string, Parameters<typeof areSpecialMentionsAllowed>, boolean]>([
- ['a guild channel with permission', [GUILD_CHANNEL, undefined, undefined, true], true],
- ['a guild channel without permission', [GUILD_CHANNEL, undefined, undefined, false], false],
- ['a direct message', [DM_CHANNEL, undefined, undefined, false], true],
- ['personal notes', [PERSONAL_NOTES, undefined, undefined, true], false],
- ['a composer with no channel', [null, true, ['emoji'], true], false],
- ['a guild channel with special mentions switched off', [GUILD_CHANNEL, false, undefined, true], false],
- ['a direct message with special mentions switched off', [DM_CHANNEL, false, undefined, false], false],
- ['a guild channel without the mention trigger', [GUILD_CHANNEL, true, ['emoji'], true], false],
- [
- 'a guild channel with the rich input triggers',
- [GUILD_CHANNEL, true, ['emoji', 'mention', 'channel'], true],
- true,
- ],
- ])('answers for %s', (_name, args, expected) => {
- expect(areSpecialMentionsAllowed(...args)).toBe(expected);
- });
-});
-
-describe('createSpecialMentionPayload', () => {
- it('builds the autocomplete mention payload', () => {
- expect(createSpecialMentionPayload('@everyone')).toEqual({
- kind: 'mention',
- mentionType: 'special',
- id: '@everyone',
- display: '@everyone',
- wire: '@everyone',
- });
- });
-});
-
-describe('isSpecialMentionKind', () => {
- it('recognises only @everyone and @here', () => {
- expect(['@everyone', '@here', 'here', '@someone'].map(isSpecialMentionKind)).toEqual([true, true, false, false]);
- });
-});
-
-describe('hasOpenCodeFence', () => {
- it('reports an odd number of fences', () => {
- expect(['```js\nconst a', '```a```', ''].map(hasOpenCodeFence)).toEqual([true, false, false]);
- });
-});
diff --git a/fluxer_app/src/features/member/state/MemberListViewportStateMachine.test.ts b/fluxer_app/src/features/member/state/MemberListViewportStateMachine.test.ts
deleted file mode 100644
index d60ca847f..000000000
--- a/fluxer_app/src/features/member/state/MemberListViewportStateMachine.test.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMemberListViewportSnapshot,
- getMemberListViewportStateValue,
- resolveMemberListViewportModel,
- selectMemberListViewportModel,
- transitionMemberListViewportSnapshot,
-} from '@app/features/member/state/MemberListViewportStateMachine';
-import {MEMBER_LIST_RANGE_MAX_END} from '@fluxer/constants/src/GatewayConstants';
-import {describe, expect, it} from 'vitest';
-
-const INITIAL_RANGE: Array<[number, number]> = [[0, 99]];
-
-describe('MemberListViewportStateMachine', () => {
- it('starts in initial loading before the first gateway payload', () => {
- const snapshot = createMemberListViewportSnapshot({requestedRanges: INITIAL_RANGE});
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('initialLoading');
- expect(model.isInitialLoading).toBe(true);
- expect(model.hasStableVirtualHeight).toBe(false);
- expect(model.requestedRanges).toEqual(INITIAL_RANGE);
- expect(model.renderRanges).toEqual([]);
- });
-
- it('enters virtualized mode after the first gateway payload and renders only the requested render ranges', () => {
- let snapshot = createMemberListViewportSnapshot({requestedRanges: INITIAL_RANGE});
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: true,
- subscribedRanges: [[0, 99]],
- totalRows: 500,
- });
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.rangesRequested',
- requestedRanges: [
- [300, 399],
- [200, 299],
- ],
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('virtualized');
- expect(model.isInitialLoading).toBe(false);
- expect(model.hasStableVirtualHeight).toBe(true);
- expect(model.totalRows).toBe(500);
- expect(model.renderRanges).toEqual([
- [200, 299],
- [300, 399],
- ]);
- });
-
- it('keeps virtualized mode when a scrollbar drag requests an unloaded window', () => {
- let snapshot = createMemberListViewportSnapshot({requestedRanges: INITIAL_RANGE});
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: true,
- subscribedRanges: [[0, 99]],
- totalRows: 500,
- });
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.rangesRequested',
- requestedRanges: [[400, 499]],
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('virtualized');
- expect(model.isInitialLoading).toBe(false);
- expect(model.renderRanges).toEqual([[400, 499]]);
- });
-
- it('remains virtualized after the store prunes the previous rows for the requested window', () => {
- let snapshot = createMemberListViewportSnapshot({requestedRanges: INITIAL_RANGE});
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: true,
- subscribedRanges: [[0, 99]],
- totalRows: 500,
- });
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.rangesRequested',
- requestedRanges: [[400, 499]],
- });
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: true,
- subscribedRanges: [[400, 499]],
- totalRows: 500,
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('virtualized');
- expect(model.isInitialLoading).toBe(false);
- expect(model.requestedRanges).toEqual([[400, 499]]);
- expect(model.renderRanges).toEqual([[400, 499]]);
- });
-
- it('does not treat an empty current store window as initial loading once payload metadata exists', () => {
- const model = resolveMemberListViewportModel({
- hasReceivedInitialPayload: true,
- requestedRanges: [[400, 499]],
- subscribedRanges: [],
- totalRows: 500,
- });
- expect(model.isInitialLoading).toBe(false);
- expect(model.hasStableVirtualHeight).toBe(true);
- expect(model.renderRanges).toEqual([[400, 499]]);
- });
-
- it('returns to initial loading when the store reports that no initial payload is present', () => {
- let snapshot = createMemberListViewportSnapshot({
- hasReceivedInitialPayload: true,
- requestedRanges: [[400, 499]],
- subscribedRanges: [[400, 499]],
- totalRows: 500,
- });
- expect(getMemberListViewportStateValue(snapshot)).toBe('virtualized');
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: false,
- subscribedRanges: [],
- totalRows: 0,
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('initialLoading');
- expect(model.renderRanges).toEqual([]);
- expect(model.totalRows).toBe(0);
- });
-
- it('reset clears payload state and subscribed ranges while preserving the caller-provided initial request', () => {
- let snapshot = createMemberListViewportSnapshot({
- hasReceivedInitialPayload: true,
- requestedRanges: [[400, 499]],
- subscribedRanges: [[400, 499]],
- totalRows: 500,
- });
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.reset',
- requestedRanges: [
- [100, 199],
- [0, 99],
- ],
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('initialLoading');
- expect(model.requestedRanges).toEqual([
- [0, 99],
- [100, 199],
- ]);
- expect(model.renderRanges).toEqual([]);
- expect(model.totalRows).toBe(0);
- });
-
- it('normalizes ranges and sanitizes total row counts at the state boundary', () => {
- const snapshot = createMemberListViewportSnapshot({
- hasReceivedInitialPayload: true,
- requestedRanges: [
- [80, 160],
- [-10, 20],
- [MEMBER_LIST_RANGE_MAX_END + 1, MEMBER_LIST_RANGE_MAX_END + 99],
- ],
- subscribedRanges: [[220.9, 250.2]],
- totalRows: 12.9,
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(model.totalRows).toBe(12);
- expect(model.requestedRanges).toEqual([
- [0, 20],
- [80, 160],
- ]);
- expect(model.renderRanges).toEqual([
- [0, 20],
- [80, 160],
- ]);
- });
-
- it('stress: repeated scrollbar window requests never collapse back to initial loading after payload', () => {
- let snapshot = createMemberListViewportSnapshot({requestedRanges: INITIAL_RANGE});
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.storeUpdated',
- hasReceivedInitialPayload: true,
- subscribedRanges: [[0, 99]],
- totalRows: 10_000,
- });
- for (let i = 0; i < 1_000; i += 1) {
- const page = (i * 37) % 100;
- const start = page * 100;
- const end = start + 99;
- snapshot = transitionMemberListViewportSnapshot(snapshot, {
- type: 'memberList.rangesRequested',
- requestedRanges: [[start, end]],
- });
- const model = selectMemberListViewportModel(snapshot);
- expect(getMemberListViewportStateValue(snapshot)).toBe('virtualized');
- expect(model.isInitialLoading).toBe(false);
- expect(model.renderRanges.some(([rangeStart, rangeEnd]) => rangeStart <= start && rangeEnd >= end)).toBe(true);
- }
- });
-});
diff --git a/fluxer_app/src/features/member/state/MemberSidebar.test.ts b/fluxer_app/src/features/member/state/MemberSidebar.test.ts
deleted file mode 100644
index 140899564..000000000
--- a/fluxer_app/src/features/member/state/MemberSidebar.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {GuildMemberData} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
-import type {Guild} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@app/features/gateway/transport/GatewayConnection', () => ({default: {socket: null}}));
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => null}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {
- getGuild: (guildId: string) => ({
- id: guildId,
- disabledOperations: 0,
- roles: {
- '10': {id: '10', permissions: 0n, position: 0},
- '20': {id: '20', permissions: 0n, position: 5},
- '30': {id: '30', permissions: 0n, position: 9},
- },
- }),
- },
-}));
-
-installVoiceMenuTestBootstrap();
-
-const {canManageTargetUser} = await import('@app/features/permissions/utils/PermissionUtils');
-const {default: GuildMembers} = await import('@app/features/member/state/GuildMembers');
-const {default: MemberSidebar} = await import('@app/features/member/state/MemberSidebar');
-
-const MODERATOR_ROLE = {id: '20', permissions: 0n, position: 5};
-
-let nextGuildId = 0;
-
-function makeMember(userId: string, roles: Array<string>, nick: string | null = null): GuildMemberData {
- return {
- user: {
- id: userId,
- username: `user-${userId}`,
- discriminator: '0001',
- global_name: null,
- avatar: null,
- avatar_color: null,
- flags: 0,
- },
- nick,
- roles,
- joined_at: '2026-01-01T00:00:00.000Z',
- };
-}
-
-function makeGuild(guildId: string): Guild {
- return {id: guildId, owner_id: 'owner'} as unknown as Guild;
-}
-
-function syncMemberList(guildId: string, channelId: string, members: Array<GuildMemberData>): void {
- MemberSidebar.subscribeToChannel(guildId, channelId, [[0, 99]]);
- MemberSidebar.handleListUpdate({
- guildId,
- listId: 'everyone',
- channelId,
- memberCount: members.length,
- onlineCount: members.length,
- groups: [{id: 'online', count: members.length}],
- ops: [
- {
- op: 'SYNC',
- range: [0, members.length],
- items: [{group: {id: 'online', count: members.length}}, ...members.map((member) => ({member}))],
- },
- ],
- });
-}
-
-function setupGuild(members: Array<GuildMemberData>): string {
- const guildId = `guild-${++nextGuildId}`;
- syncMemberList(guildId, `channel-${guildId}`, members);
- return guildId;
-}
-
-describe('MemberSidebar member list hydration', () => {
- it('makes membership known for members that only ever appeared in the member list', () => {
- const guildId = setupGuild([makeMember('target-low', []), makeMember('target-high', ['30'])]);
- expect(GuildMembers.isMembershipKnown(guildId, 'target-low')).toBe(true);
- expect(GuildMembers.getMember(guildId, 'target-high')?.roles.has('30')).toBe(true);
- });
-
- it('lets the role hierarchy check pass for a sidebar member who has never posted', () => {
- const guildId = setupGuild([makeMember('target-low', [])]);
- expect(canManageTargetUser(makeGuild(guildId), 'me', MODERATOR_ROLE, 'target-low')).toBe(true);
- });
-
- it('still refuses a sidebar member who outranks you', () => {
- const guildId = setupGuild([makeMember('target-high', ['30'])]);
- expect(canManageTargetUser(makeGuild(guildId), 'me', MODERATOR_ROLE, 'target-high')).toBe(false);
- });
-
- it('does not create members for group header rows', () => {
- const guildId = setupGuild([makeMember('target-low', []), makeMember('target-high', ['30'])]);
- expect(GuildMembers.getMemberCount(guildId)).toBe(2);
- });
-
- it('leaves an already known member untouched', () => {
- const guildId = `guild-${++nextGuildId}`;
- GuildMembers.hydrateIfMissing(guildId, makeMember('target-low', ['20'], 'authoritative'));
- syncMemberList(guildId, `channel-${guildId}`, [makeMember('target-low', [], 'stale')]);
- expect(GuildMembers.getMember(guildId, 'target-low')?.nick).toBe('authoritative');
- });
-});
diff --git a/fluxer_app/src/features/member/utils/MemberListRangeUtils.test.ts b/fluxer_app/src/features/member/utils/MemberListRangeUtils.test.ts
deleted file mode 100644
index 25c6a9d54..000000000
--- a/fluxer_app/src/features/member/utils/MemberListRangeUtils.test.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- areMemberListRangesCovered,
- areMemberListRangesEqual,
- areNormalizedMemberListRangesCovered,
- areNormalizedMemberListRangesEqual,
- buildMemberListRangeWindow,
- buildMemberListRenderWindow,
- normalizeMemberListRanges,
-} from '@app/features/member/utils/MemberListRangeUtils';
-import {MEMBER_LIST_RANGE_MAX_SPAN} from '@fluxer/constants/src/GatewayConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('MemberListRangeUtils', () => {
- it('compares ranges after normalization and page splitting', () => {
- expect(areMemberListRangesEqual([[0, MEMBER_LIST_RANGE_MAX_SPAN]], [[0, MEMBER_LIST_RANGE_MAX_SPAN]])).toBe(true);
- expect(areMemberListRangesEqual([[0, MEMBER_LIST_RANGE_MAX_SPAN + 1]], [[0, MEMBER_LIST_RANGE_MAX_SPAN]])).toBe(
- false,
- );
- });
-
- it('detects whether a requested window is still covered by local ranges', () => {
- expect(
- areMemberListRangesCovered(
- [
- [0, 99],
- [100, 199],
- ],
- [[0, 199]],
- ),
- ).toBe(true);
- expect(areMemberListRangesCovered([[100, 199]], [[0, 299]])).toBe(true);
- expect(areMemberListRangesCovered([[0, 299]], [[100, 399]])).toBe(false);
- });
-
- it('compares branded normalized ranges without re-normalizing them', () => {
- const requested = normalizeMemberListRanges([[100, 199]]);
- const subscribed = normalizeMemberListRanges([[0, 299]]);
- expect(areNormalizedMemberListRangesEqual(requested, subscribed)).toBe(false);
- expect(areNormalizedMemberListRangesEqual(requested, normalizeMemberListRanges([[100, 199]]))).toBe(true);
- expect(areNormalizedMemberListRangesCovered(requested, subscribed)).toBe(true);
- });
-
- it('builds a bounded, overscanned page window from scroll metrics and keeps the head page subscribed', () => {
- expect(
- buildMemberListRangeWindow({
- scrollTop: 44 * 250,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 24,
- totalRows: 500,
- }),
- ).toEqual([
- [0, 99],
- [100, 199],
- [200, 299],
- [300, 399],
- ]);
- });
-
- it('keeps scrollbar-dragged bottom windows clamped to the last known page', () => {
- expect(
- buildMemberListRangeWindow({
- scrollTop: 44 * 490,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 24,
- totalRows: 500,
- }),
- ).toEqual([
- [0, 99],
- [300, 399],
- [400, 499],
- ]);
- });
-
- it('allows callers to disable page overscan for memory-constrained member-list surfaces', () => {
- expect(
- buildMemberListRangeWindow({
- scrollTop: 44 * 250,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 12,
- overscanPages: 0,
- totalRows: 500,
- }),
- ).toEqual([
- [0, 99],
- [200, 299],
- ]);
- });
-
- it('omits a duplicate head page when the window already starts at the top of the list', () => {
- expect(
- buildMemberListRangeWindow({
- scrollTop: 0,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 12,
- overscanPages: 0,
- totalRows: 500,
- }),
- ).toEqual([[0, 99]]);
- });
-
- it('keeps page ends aligned so a changing member count does not resubscribe', () => {
- const options = {
- scrollTop: 44 * 250,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 12,
- overscanPages: 0,
- };
- expect(buildMemberListRangeWindow({...options, totalRows: 450})).toEqual([
- [0, 99],
- [200, 299],
- ]);
- expect(buildMemberListRangeWindow({...options, totalRows: 451})).toEqual([
- [0, 99],
- [200, 299],
- ]);
- });
-
- it('builds a tight render window instead of rendering whole subscription pages', () => {
- expect(
- buildMemberListRenderWindow({
- scrollTop: 44 * 250,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 8,
- totalRows: 500,
- }),
- ).toEqual([[242, 268]]);
- });
-
- it('returns no render rows for an empty known list', () => {
- expect(
- buildMemberListRenderWindow({
- scrollTop: 0,
- clientHeight: 44 * 10,
- rowHeight: 44,
- bufferRows: 8,
- totalRows: 0,
- }),
- ).toEqual([]);
- });
-
- it('resolves the visible row range from variable-height offsets when rowOffsets is provided', () => {
- const rowOffsets = [0, 30, 74, 118, 162, 206, 236, 280, 324, 368, 412];
- expect(
- buildMemberListRenderWindow({
- scrollTop: 206,
- clientHeight: 88,
- rowHeight: 44,
- rowOffsets,
- bufferRows: 0,
- totalRows: 10,
- }),
- ).toEqual([[5, 7]]);
- });
-
- it('does not let a uniform rowHeight skew the variable-height window', () => {
- const rowOffsets = [0, 30, 74, 118, 162, 206, 236, 280, 324, 368, 412];
- const offsetWindow = buildMemberListRenderWindow({
- scrollTop: 206,
- clientHeight: 44,
- rowHeight: 44,
- rowOffsets,
- bufferRows: 0,
- totalRows: 10,
- });
- const uniformWindow = buildMemberListRenderWindow({
- scrollTop: 206,
- clientHeight: 44,
- rowHeight: 44,
- bufferRows: 0,
- totalRows: 10,
- });
- expect(offsetWindow).toEqual([[5, 6]]);
- expect(uniformWindow).toEqual([[4, 6]]);
- });
-});
diff --git a/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.test.ts b/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.test.ts
deleted file mode 100644
index 8fdc2d09c..000000000
--- a/fluxer_app/src/features/messaging/commands/MessageFetchStateMachine.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMessageFetchExecutionSnapshot,
- createMessageFetchPreflightSnapshot,
- type MessageFetchExecutionInput,
- type MessageFetchPreflightInput,
- resolveMessageFetchExecutionDecision,
- resolveMessageFetchPreflightDecision,
- resolveMessageFetchWindowCached,
- selectMessageFetchExecutionDecision,
- selectMessageFetchPreflightDecision,
- transitionMessageFetchExecutionSnapshot,
- transitionMessageFetchPreflightSnapshot,
-} from '@app/features/messaging/commands/MessageFetchStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function preflight(overrides: Partial<MessageFetchPreflightInput> = {}): MessageFetchPreflightInput {
- return {
- hasInFlightRequest: false,
- shouldBlockForGate: false,
- cacheHit: null,
- ...overrides,
- };
-}
-
-function execution(overrides: Partial<MessageFetchExecutionInput> = {}): MessageFetchExecutionInput {
- return {
- forceFailure: false,
- ...overrides,
- };
-}
-
-describe('messageFetchPreflightMachine', () => {
- it('prioritizes in-flight requests before gate and cache decisions', () => {
- expect(
- resolveMessageFetchPreflightDecision(
- preflight({
- hasInFlightRequest: true,
- shouldBlockForGate: true,
- cacheHit: 'before',
- }),
- ),
- ).toEqual({type: 'useInFlightRequest'});
- });
-
- it('blocks gated channels before consulting cache hits', () => {
- expect(resolveMessageFetchPreflightDecision(preflight({shouldBlockForGate: true, cacheHit: 'jump'}))).toEqual({
- type: 'blockForGate',
- });
- });
-
- it('returns the specific cache hit when cached messages can satisfy the request', () => {
- expect(resolveMessageFetchPreflightDecision(preflight({cacheHit: 'jump'}))).toEqual({
- type: 'useCache',
- cacheHit: 'jump',
- });
- expect(resolveMessageFetchPreflightDecision(preflight({cacheHit: 'before'}))).toEqual({
- type: 'useCache',
- cacheHit: 'before',
- });
- expect(resolveMessageFetchPreflightDecision(preflight({cacheHit: 'after'}))).toEqual({
- type: 'useCache',
- cacheHit: 'after',
- });
- });
-
- it('starts a network fetch when no preflight condition resolves the request', () => {
- expect(resolveMessageFetchPreflightDecision(preflight())).toEqual({type: 'startFetch'});
- });
-
- it('re-routes when preflight inputs change', () => {
- const cachedSnapshot = createMessageFetchPreflightSnapshot(preflight({cacheHit: 'after'}));
- expect(selectMessageFetchPreflightDecision(cachedSnapshot)).toEqual({type: 'useCache', cacheHit: 'after'});
-
- const networkSnapshot = transitionMessageFetchPreflightSnapshot(cachedSnapshot, {
- type: 'messageFetch.preflightChanged',
- input: preflight(),
- });
-
- expect(selectMessageFetchPreflightDecision(networkSnapshot)).toEqual({type: 'startFetch'});
- });
-});
-
-describe('messageFetchExecutionMachine', () => {
- it('requests the network by default', () => {
- expect(resolveMessageFetchExecutionDecision(execution())).toEqual({type: 'requestNetwork'});
- });
-
- it('routes developer-forced failures before network fetch', () => {
- expect(resolveMessageFetchExecutionDecision(execution({forceFailure: true}))).toEqual({
- type: 'simulateFailure',
- });
- });
-
- it('re-routes when execution inputs change', () => {
- const forcedSnapshot = createMessageFetchExecutionSnapshot(execution({forceFailure: true}));
- expect(selectMessageFetchExecutionDecision(forcedSnapshot)).toEqual({type: 'simulateFailure'});
-
- const networkSnapshot = transitionMessageFetchExecutionSnapshot(forcedSnapshot, {
- type: 'messageFetch.executionChanged',
- input: execution({forceFailure: false}),
- });
-
- expect(selectMessageFetchExecutionDecision(networkSnapshot)).toEqual({type: 'requestNetwork'});
- });
-});
-
-describe('resolveMessageFetchWindowCached', () => {
- function trust(overrides: Partial<Parameters<typeof resolveMessageFetchWindowCached>[0]> = {}) {
- return {
- connectedAtRequest: true,
- connectedAtResponse: true,
- epochAtRequest: 7,
- epochAtResponse: 7,
- ...overrides,
- };
- }
-
- it('trusts a window loaded inside one uninterrupted connection', () => {
- expect(resolveMessageFetchWindowCached(trust())).toBe(false);
- });
-
- it('distrusts a window whose request left while the socket was down', () => {
- expect(resolveMessageFetchWindowCached(trust({connectedAtRequest: false}))).toBe(true);
- });
-
- it('distrusts a window whose response landed while the socket was down', () => {
- expect(resolveMessageFetchWindowCached(trust({connectedAtResponse: false}))).toBe(true);
- });
-
- it('distrusts a window whose connection epoch moved under it', () => {
- expect(resolveMessageFetchWindowCached(trust({epochAtResponse: 8}))).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/messaging/commands/MessagePageStateMachine.test.ts b/fluxer_app/src/features/messaging/commands/MessagePageStateMachine.test.ts
deleted file mode 100644
index 11341142e..000000000
--- a/fluxer_app/src/features/messaging/commands/MessagePageStateMachine.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMessagePageStateSnapshot,
- type MessagePageStateInput,
- resolveMessagePageState,
- selectMessagePageState,
- transitionMessagePageStateSnapshot,
-} from '@app/features/messaging/commands/MessagePageStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<MessagePageStateInput> = {}): MessagePageStateInput {
- return {
- before: null,
- after: null,
- limit: 50,
- messageCount: 0,
- aroundMessageId: null,
- aroundTargetIndex: -1,
- newestFetchedMessageId: null,
- knownLatestMessageId: null,
- ...overrides,
- };
-}
-
-describe('messagePageStateMachine', () => {
- it('opens older pagination for full replacement pages', () => {
- expect(resolveMessagePageState(input({messageCount: 50}))).toMatchObject({
- isBefore: false,
- isAfter: false,
- hasMoreBefore: true,
- hasMoreAfter: false,
- shouldWarnMissingAroundTarget: false,
- aroundDebug: null,
- });
- });
-
- it('routes directional pages from before and after cursors', () => {
- expect(resolveMessagePageState(input({before: 'm-1', messageCount: 50}))).toMatchObject({
- isBefore: true,
- isAfter: false,
- hasMoreBefore: true,
- hasMoreAfter: false,
- });
- expect(resolveMessagePageState(input({after: 'm-1', messageCount: 50}))).toMatchObject({
- isBefore: false,
- isAfter: true,
- hasMoreBefore: false,
- hasMoreAfter: true,
- });
- });
-
- it('closes pagination for partial non-around pages', () => {
- expect(resolveMessagePageState(input({before: 'm-1', messageCount: 10}))).toMatchObject({
- hasMoreBefore: false,
- hasMoreAfter: false,
- });
- expect(resolveMessagePageState(input({after: 'm-1', messageCount: 10}))).toMatchObject({
- hasMoreBefore: false,
- hasMoreAfter: false,
- });
- });
-
- it('keeps around pagination open when the target is missing', () => {
- expect(
- resolveMessagePageState(
- input({
- aroundMessageId: 'target',
- aroundTargetIndex: -1,
- messageCount: 25,
- }),
- ),
- ).toMatchObject({
- hasMoreBefore: true,
- hasMoreAfter: true,
- shouldWarnMissingAroundTarget: true,
- aroundDebug: null,
- });
- });
-
- it('uses around-window pagination when the target is present', () => {
- expect(
- resolveMessagePageState(
- input({
- aroundMessageId: 'target',
- aroundTargetIndex: 25,
- messageCount: 50,
- newestFetchedMessageId: 'newest',
- knownLatestMessageId: 'latest',
- }),
- ),
- ).toMatchObject({
- hasMoreBefore: true,
- hasMoreAfter: true,
- shouldWarnMissingAroundTarget: false,
- aroundDebug: {
- messagesNewerThanTarget: 25,
- messagesOlderThanTarget: 24,
- expectedNewer: 25,
- expectedOlder: 24,
- pageFilled: true,
- },
- });
- });
-
- it('closes newer around pagination when the response reaches the known latest message', () => {
- expect(
- resolveMessagePageState(
- input({
- aroundMessageId: 'target',
- aroundTargetIndex: 0,
- messageCount: 25,
- newestFetchedMessageId: 'latest',
- knownLatestMessageId: 'latest',
- }),
- ),
- ).toMatchObject({
- hasMoreBefore: true,
- hasMoreAfter: false,
- });
- });
-
- it('re-routes when page inputs change', () => {
- const aroundSnapshot = createMessagePageStateSnapshot(
- input({
- aroundMessageId: 'target',
- aroundTargetIndex: -1,
- }),
- );
- expect(selectMessagePageState(aroundSnapshot)).toMatchObject({shouldWarnMissingAroundTarget: true});
-
- const standardSnapshot = transitionMessagePageStateSnapshot(aroundSnapshot, {
- type: 'messagePageState.updated',
- input: input({after: 'm-1', messageCount: 50}),
- });
-
- expect(selectMessagePageState(standardSnapshot)).toMatchObject({
- isAfter: true,
- hasMoreAfter: true,
- shouldWarnMissingAroundTarget: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/messaging/components/markdown/renderers/EmojiRenderer.test.tsx b/fluxer_app/src/features/messaging/components/markdown/renderers/EmojiRenderer.test.tsx
deleted file mode 100644
index 1431edb32..000000000
--- a/fluxer_app/src/features/messaging/components/markdown/renderers/EmojiRenderer.test.tsx
+++ /dev/null
@@ -1,252 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {MarkdownRenderOptions} from '@app/features/messaging/components/markdown/renderers/RendererTypes';
-import {MarkdownContext} from '@app/features/messaging/components/markdown/renderers/RendererTypes';
-import type {EmojiNode} from '@app/features/messaging/utils/markdown/parser/Nodes';
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {I18n, MessageDescriptor} from '@lingui/core';
-import {runInAction} from 'mobx';
-import type React from 'react';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: ({children}: {children?: React.ReactNode}) => <span data-flx="test.trans">{children}</span>,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/ui/tooltip/Tooltip', () => ({
- Tooltip: ({text, children}: {text: unknown; children: React.ReactNode}) => (
- <span data-test-tooltip={typeof text === 'string' ? text : 'render-prop'} data-flx="test.tooltip">
- {children}
- </span>
- ),
-}));
-vi.mock('@app/features/ui/popover/PopoverPopout', () => ({
- openPopout: vi.fn(),
- Popout: ({children}: {children: React.ReactNode}) => (
- <span data-test-popout="true" data-flx="test.popout">
- {children}
- </span>
- ),
-}));
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {updatePresence: vi.fn()},
- setLocalPresenceUserSettings: vi.fn(),
- ACCOUNT_PRESENCE_INTENT_MAX_AGE_MS: 60_000,
-}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({default: {getMessage: () => null}}));
-vi.mock('@app/features/channel/components/MessageActionUtils', () => ({requestDeleteMessage: vi.fn()}));
-vi.mock('@app/features/ui/commands/ContextMenuCommands', () => ({openFromEvent: vi.fn()}));
-vi.mock('@app/features/ui/action_menu/MessageContextMenu', () => ({MessageContextMenu: () => null}));
-vi.mock('@app/features/ui/action_menu/items/EmojiContextMenuItems', () => ({
- EmojiContextMenuItems: () => null,
- EmojiInlineMenuItems: () => null,
-}));
-vi.mock('@app/features/expressions/components/ExpressionInfoCard', () => ({
- ExpressionInfoCard: ({displayName}: {displayName: string}) => (
- <span data-test-info-card={displayName} data-flx="test.info-card" />
- ),
-}));
-vi.mock('@app/features/expressions/components/bottomsheets/ExpressionInfoBottomSheet', () => ({
- ExpressionInfoBottomSheet: ({isOpen}: {isOpen: boolean}) => (
- <span data-test-bottom-sheet={String(isOpen)} data-flx="test.bottom-sheet" />
- ),
-}));
-
-installVoiceMenuTestBootstrap();
-
-const {EmojiRenderer} = await import('@app/features/messaging/components/markdown/renderers/EmojiRenderer');
-const {default: MobileLayout} = await import('@app/features/ui/state/MobileLayout');
-
-const i18n = {
- locale: 'en',
- _: (descriptor: MessageDescriptor, values?: Record<string, unknown>) =>
- (descriptor.message ?? '').replace(/\{(\w+)\}/gu, (_match, key: string) => String(values?.[key] ?? `{${key}}`)),
-} as unknown as I18n;
-
-const BASE_OPTIONS: MarkdownRenderOptions = {
- context: MarkdownContext.STANDARD_WITH_JUMBO,
- shouldJumboEmojis: false,
- i18n,
-};
-
-const CUSTOM_EMOJI = {
- type: 'Emoji',
- kind: {kind: 'Custom', name: 'blob', id: '10', animated: false},
-} as unknown as EmojiNode;
-const STANDARD_EMOJI = {
- type: 'Emoji',
- kind: {kind: 'Standard', raw: '🙂', codepoints: '1f642', name: 'slight_smile'},
-} as unknown as EmojiNode;
-
-const PLAIN_FLAGS = ['disableInteractions', 'disableEmojiInteractions'] as const;
-
-function renderEmoji(node: EmojiNode, overrides: Partial<MarkdownRenderOptions> = {}): string {
- return renderToStaticMarkup(
- <EmojiRenderer
- node={node}
- id="emoji-key"
- renderChildren={() => null}
- options={{...BASE_OPTIONS, ...overrides}}
- data-flx="test.emoji-renderer"
- />,
- );
-}
-
-function expectNoTooltip(markup: string): void {
- expect(markup).not.toContain('data-test-tooltip');
-}
-
-function expectNoCard(markup: string): void {
- expect(markup).not.toContain('data-test-popout');
- expect(markup).not.toContain('data-emoji-interactive');
-}
-
-function expectNoTabStop(markup: string): void {
- expect(markup).not.toContain('tabindex');
- expect(markup).not.toContain('role="button"');
-}
-
-describe('EmojiRenderer on desktop', () => {
- it('renders the interactive info card trigger by default', () => {
- const markup = renderEmoji(CUSTOM_EMOJI);
- expect(markup).toContain('data-test-popout="true"');
- expect(markup).toContain('role="button"');
- expect(markup).toContain('tabindex="0"');
- expect(markup).toContain('data-emoji-interactive="true"');
- expect(markup).toContain('aria-label=":blob:"');
- expectNoTooltip(markup);
- });
-
- for (const flag of PLAIN_FLAGS) {
- it(`renders a completely plain emoji when ${flag} is set`, () => {
- const markup = renderEmoji(CUSTOM_EMOJI, {[flag]: true});
- expectNoTooltip(markup);
- expectNoCard(markup);
- expectNoTabStop(markup);
- expect(markup).toContain('aria-label=":blob:"');
- });
- }
-
- it('renders the plain name tooltip and no card when disableEmojiInfoCard is set', () => {
- const markup = renderEmoji(CUSTOM_EMOJI, {disableEmojiInfoCard: true});
- expect(markup).toContain('data-test-tooltip=":blob:"');
- expectNoCard(markup);
- expectNoTabStop(markup);
- expect(markup).toContain('aria-label=":blob:"');
- });
-
- it('keeps disableEmojiInfoCard distinct from the two plain flags', () => {
- const infoCardOff = renderEmoji(CUSTOM_EMOJI, {disableEmojiInfoCard: true});
- for (const flag of PLAIN_FLAGS) {
- expect(renderEmoji(CUSTOM_EMOJI, {[flag]: true})).not.toBe(infoCardOff);
- }
- });
-});
-
-describe('EmojiRenderer on mobile', () => {
- beforeEach(() => {
- runInAction(() => {
- MobileLayout.enabled = true;
- });
- });
-
- afterEach(() => {
- runInAction(() => {
- MobileLayout.enabled = false;
- });
- });
-
- it('opens the info bottom sheet by default', () => {
- const markup = renderEmoji(CUSTOM_EMOJI);
- expect(markup).toContain('role="button"');
- expect(markup).toContain('tabindex="0"');
- expect(markup).toContain('data-test-bottom-sheet="false"');
- expect(markup).not.toContain('data-test-popout');
- });
-
- it('keeps the tap-to-sheet handler when disableEmojiInfoCard is set', () => {
- const markup = renderEmoji(CUSTOM_EMOJI, {disableEmojiInfoCard: true});
- expect(markup).toContain('role="button"');
- expect(markup).toContain('tabindex="0"');
- expect(markup).toContain('data-test-bottom-sheet="false"');
- });
-
- for (const flag of PLAIN_FLAGS) {
- it(`renders no tap handler when ${flag} is set`, () => {
- const markup = renderEmoji(CUSTOM_EMOJI, {[flag]: true});
- expect(markup).not.toContain('data-test-bottom-sheet');
- expectNoTabStop(markup);
- expectNoTooltip(markup);
- });
- }
-});
-
-describe('EmojiRenderer accessible name', () => {
- for (const overrides of [
- {},
- {disableEmojiInfoCard: true},
- {disableInteractions: true},
- {disableEmojiInteractions: true},
- ]) {
- const label = Object.keys(overrides)[0] ?? 'the default branch';
- it(`names the custom emoji in ${label}`, () => {
- expect(renderEmoji(CUSTOM_EMOJI, overrides)).toContain('aria-label=":blob:"');
- });
-
- it(`names the unicode emoji fallback in ${label}`, () => {
- const markup = renderEmoji(STANDARD_EMOJI, overrides);
- expect(markup).toContain('role="img"');
- expect(markup).toContain('aria-label=":slight_smile:"');
- });
- }
-});
-
-describe('EmojiRenderer failed-to-load wording', () => {
- let host: HTMLDivElement;
- let root: Root;
-
- beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- });
-
- afterEach(() => {
- act(() => {
- root.unmount();
- });
- host.remove();
- });
-
- for (const overrides of [{}, {disableEmojiInfoCard: true}, {disableInteractions: true}]) {
- const label = Object.keys(overrides)[0] ?? 'the default branch';
- it(`switches the accessible name to the failed wording in ${label}`, () => {
- act(() => {
- root.render(
- <EmojiRenderer
- node={CUSTOM_EMOJI}
- id="emoji-key"
- renderChildren={() => null}
- options={{...BASE_OPTIONS, ...overrides}}
- data-flx="test.emoji-renderer.failed"
- />,
- );
- });
- const image = host.querySelector('img');
- expect(image?.getAttribute('aria-label')).toBe(':blob:');
- act(() => {
- image?.dispatchEvent(new Event('error'));
- });
- expect(host.querySelector('img')?.getAttribute('aria-label')).toBe(':blob: (failed to load)');
- });
- }
-});
diff --git a/fluxer_app/src/features/messaging/components/modals/ForwardMessagePreviewContent.test.ts b/fluxer_app/src/features/messaging/components/modals/ForwardMessagePreviewContent.test.ts
deleted file mode 100644
index d4e18f33f..000000000
--- a/fluxer_app/src/features/messaging/components/modals/ForwardMessagePreviewContent.test.ts
+++ /dev/null
@@ -1,350 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildForwardMessagePreviewThumbnailURL,
- type ForwardMessagePreviewMessage,
- type ForwardMessagePreviewThumbnail,
- resolveForwardMessagePreviewContent,
-} from '@app/features/messaging/components/modals/ForwardMessagePreviewContent';
-import {EmbedMediaFlags, MessageAttachmentFlags, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {MessageEmbed} from '@fluxer/schema/src/domains/message/EmbedSchemas';
-import type {MessageAttachment, MessageSnapshot} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-function attachment(id: string, overrides: Partial<MessageAttachment> = {}): MessageAttachment {
- return {
- id,
- filename: `${id}.bin`,
- size: 1024,
- url: `https://cdn.example.com/attachments/${id}`,
- proxy_url: `https://media.example.com/attachments/${id}`,
- flags: 0,
- ...overrides,
- };
-}
-
-function image(id: string, overrides: Partial<MessageAttachment> = {}): MessageAttachment {
- return attachment(id, {content_type: 'image/png', width: 800, height: 600, ...overrides});
-}
-
-function video(id: string, overrides: Partial<MessageAttachment> = {}): MessageAttachment {
- return attachment(id, {content_type: 'video/mp4', width: 1920, height: 1080, ...overrides});
-}
-
-function file(id: string): MessageAttachment {
- return attachment(id, {content_type: 'application/pdf'});
-}
-
-function embed(overrides: Partial<MessageEmbed> = {}): MessageEmbed {
- return {type: 'link', ...overrides};
-}
-
-function snapshot(overrides: Partial<MessageSnapshot> = {}): MessageSnapshot {
- return {type: MessageTypes.DEFAULT, content: '', timestamp: '2026-09-01T12:00:00.000Z', ...overrides};
-}
-
-function message(overrides: Partial<ForwardMessagePreviewMessage> = {}): ForwardMessagePreviewMessage {
- return {
- attachments: [],
- content: '',
- editedTimestamp: null,
- embeds: [],
- mentionChannels: [],
- messageSnapshots: undefined,
- ...overrides,
- };
-}
-
-function thumbnail(overrides: Partial<ForwardMessagePreviewThumbnail> = {}): ForwardMessagePreviewThumbnail {
- return {
- proxyUrl: 'https://media.example.com/attachments/a',
- isVideo: false,
- showsPlayIcon: false,
- showsFilePlaceholder: false,
- isSensitive: false,
- width: null,
- height: null,
- ...overrides,
- };
-}
-
-function searchParams(url: string): Record<string, string> {
- return Object.fromEntries(new URL(url).searchParams.entries());
-}
-
-describe('forward message preview content', () => {
- it('previews plain message text with no attachment row or thumbnail', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({content: 'Lunch at noon?'}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(preview.text).toBe('Lunch at noon?');
- expect(preview.isEdited).toBe(false);
- expect(preview.attachmentSummary).toBeNull();
- expect(preview.thumbnail).toBeNull();
- expect(preview.overflowCount).toBe(0);
- });
-
- it('previews the first snapshot of a forwarded message', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({
- messageSnapshots: [
- snapshot({content: 'Original words', attachments: [image('a')]}),
- snapshot({content: 'Second snapshot'}),
- ],
- }),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(preview.text).toBe('Original words');
- expect(preview.attachmentSummary).toEqual({kind: 'images', count: 1});
- expect(preview.thumbnail?.proxyUrl).toBe('https://media.example.com/attachments/a');
- });
-
- it('marks the preview edited only when the forwarded message itself has text it edited', () => {
- const editedMessage = resolveForwardMessagePreviewContent({
- message: message({content: 'Fixed typo', editedTimestamp: new Date('2026-09-02T08:00:00.000Z')}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(editedMessage.isEdited).toBe(true);
- const editedWithoutContent = resolveForwardMessagePreviewContent({
- message: message({
- editedTimestamp: new Date('2026-09-02T08:00:00.000Z'),
- embeds: [embed({url: 'https://example.com/a'})],
- }),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(editedWithoutContent.isEdited).toBe(false);
- const forwardOfEditedMessage = resolveForwardMessagePreviewContent({
- message: message({
- messageSnapshots: [snapshot({content: 'Edited', edited_timestamp: '2026-09-02T08:00:00.000Z'})],
- }),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(forwardOfEditedMessage.isEdited).toBe(false);
- });
-
- it('keeps only the selected attachments and hides the text for an attachment selection', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({
- content: 'Holiday photos',
- attachments: [image('a'), image('b'), image('c')],
- embeds: [
- embed({
- url: 'https://example.com/trip',
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/x', flags: 0},
- }),
- ],
- }),
- mediaSelection: {attachmentIds: ['b']},
- canEmbedLinks: true,
- });
- expect(preview.text).toBeNull();
- expect(preview.attachmentSummary).toEqual({kind: 'images', count: 1});
- expect(preview.thumbnail?.proxyUrl).toBe('https://media.example.com/attachments/b');
- expect(preview.overflowCount).toBe(0);
- });
-
- it('previews the selected embed urls for an embed selection', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({
- content: 'Two links',
- attachments: [image('a')],
- embeds: [
- embed({url: 'https://example.com/first'}),
- embed({
- url: 'https://example.com/second',
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/second-thumb', flags: 0},
- }),
- ],
- }),
- mediaSelection: {embedIndices: [1]},
- canEmbedLinks: true,
- });
- expect(preview.text).toBe('https://example.com/second');
- expect(preview.attachmentSummary).toBeNull();
- expect(preview.thumbnail?.proxyUrl).toBe('https://media.example.com/second-thumb');
- expect(preview.overflowCount).toBe(0);
- });
-
- it('falls back to the embed urls when the source has no text', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({embeds: [embed({url: 'https://example.com/a'}), embed({url: 'https://example.com/b'})]}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(preview.text).toBe('https://example.com/a\nhttps://example.com/b');
- });
-
- it('falls back to the first embed description when no embed has a url', () => {
- const preview = resolveForwardMessagePreviewContent({
- message: message({embeds: [embed({type: 'rich', description: 'Weekly notes'})]}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- expect(preview.text).toBe('Weekly notes');
- });
-
- it('drops embeds when the destination cannot embed links and the message has content', () => {
- const linkEmbed = embed({
- url: 'https://example.com/a',
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/a-thumb', flags: 0},
- });
- const withContent = resolveForwardMessagePreviewContent({
- message: message({content: 'See https://example.com/a', embeds: [linkEmbed]}),
- mediaSelection: undefined,
- canEmbedLinks: false,
- });
- expect(withContent.text).toBe('See https://example.com/a');
- expect(withContent.thumbnail).toBeNull();
- const withoutContent = resolveForwardMessagePreviewContent({
- message: message({embeds: [linkEmbed]}),
- mediaSelection: undefined,
- canEmbedLinks: false,
- });
- expect(withoutContent.text).toBe('https://example.com/a');
- expect(withoutContent.thumbnail?.proxyUrl).toBe('https://media.example.com/a-thumb');
- });
-});
-
-describe('forward message preview attachment summary', () => {
- function summarize(attachments: ReadonlyArray<MessageAttachment>) {
- return resolveForwardMessagePreviewContent({
- message: message({attachments}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- }).attachmentSummary;
- }
-
- it('counts images and videos together when both are present', () => {
- expect(summarize([image('a'), video('b'), image('c'), file('d')])).toEqual({
- kind: 'images_and_videos',
- imageCount: 2,
- videoCount: 1,
- });
- });
-
- it('counts only the videos when there are no images', () => {
- expect(summarize([video('a'), file('b')])).toEqual({kind: 'videos', count: 1});
- });
-
- it('counts only the images when there are no videos', () => {
- expect(summarize([image('a'), image('b'), file('c')])).toEqual({kind: 'images', count: 2});
- });
-
- it('counts every attachment as a file when none is a displayable image or video', () => {
- expect(summarize([file('a'), file('b'), image('c', {width: undefined, height: undefined})])).toEqual({
- kind: 'files',
- count: 3,
- });
- });
-});
-
-describe('forward message preview thumbnail', () => {
- function preview(attachments: ReadonlyArray<MessageAttachment>, embeds: ReadonlyArray<MessageEmbed> = []) {
- return resolveForwardMessagePreviewContent({
- message: message({attachments, embeds}),
- mediaSelection: undefined,
- canEmbedLinks: true,
- });
- }
-
- it('shows a playable still frame when every attachment is a video', () => {
- const result = preview([video('a'), video('b')]);
- expect(result.thumbnail).toMatchObject({
- proxyUrl: 'https://media.example.com/attachments/a',
- isVideo: true,
- showsPlayIcon: true,
- width: 1920,
- height: 1080,
- });
- expect(result.overflowCount).toBe(1);
- });
-
- it('shows the first attachment without a play icon when the attachments are mixed', () => {
- const result = preview([video('a'), image('b'), file('c')]);
- expect(result.thumbnail).toMatchObject({isVideo: true, showsPlayIcon: false});
- expect(result.overflowCount).toBe(2);
- });
-
- it('keeps the box and the overflow badge when the first attachment is not displayable media', () => {
- const result = preview([file('a'), image('b')]);
- expect(result.thumbnail).toMatchObject({
- proxyUrl: 'https://media.example.com/attachments/a',
- showsFilePlaceholder: true,
- isVideo: false,
- showsPlayIcon: false,
- });
- expect(result.overflowCount).toBe(1);
- const unsized = preview([image('a', {width: undefined, height: undefined}), image('b')]);
- expect(unsized.thumbnail).toMatchObject({showsFilePlaceholder: true});
- expect(unsized.overflowCount).toBe(1);
- });
-
- it('uses only the first embed thumbnail when there are no attachments', () => {
- const result = preview(
- [],
- [
- embed({url: 'https://example.com/a'}),
- embed({
- url: 'https://example.com/b',
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/b', flags: 0},
- }),
- ],
- );
- expect(result.thumbnail).toBeNull();
- const withThumbnail = preview(
- [],
- [
- embed({
- url: 'https://example.com/a',
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/a', flags: 0},
- }),
- ],
- );
- expect(withThumbnail.thumbnail).toMatchObject({proxyUrl: 'https://media.example.com/a', isVideo: false});
- });
-
- it('marks spoiler and explicit media as sensitive', () => {
- expect(preview([image('a', {flags: MessageAttachmentFlags.IS_SPOILER})]).thumbnail?.isSensitive).toBe(true);
- expect(preview([image('a', {flags: MessageAttachmentFlags.CONTAINS_EXPLICIT_MEDIA})]).thumbnail?.isSensitive).toBe(
- true,
- );
- expect(preview([image('a', {nsfw: true})]).thumbnail?.isSensitive).toBe(true);
- expect(preview([image('a')]).thumbnail?.isSensitive).toBe(false);
- const explicitEmbed = embed({
- thumbnail: {url: 'x', proxy_url: 'https://media.example.com/x', flags: EmbedMediaFlags.CONTAINS_EXPLICIT_MEDIA},
- });
- expect(preview([], [explicitEmbed]).thumbnail?.isSensitive).toBe(true);
- });
-});
-
-describe('forward message preview thumbnail url', () => {
- it('requests a square webp crop for images', () => {
- const url = buildForwardMessagePreviewThumbnailURL(thumbnail());
- expect(searchParams(url)).toEqual({format: 'webp', width: '56', height: '56'});
- });
-
- it('requests a still frame wide enough to cover the square for landscape video', () => {
- const url = buildForwardMessagePreviewThumbnailURL(thumbnail({isVideo: true, width: 1920, height: 1080}));
- expect(searchParams(url)).toEqual({format: 'webp', width: '100'});
- });
-
- it('requests a still frame at the square width for portrait or unsized video', () => {
- const portrait = buildForwardMessagePreviewThumbnailURL(thumbnail({isVideo: true, width: 1080, height: 1920}));
- expect(searchParams(portrait)).toEqual({format: 'webp', width: '56'});
- const unsized = buildForwardMessagePreviewThumbnailURL(thumbnail({isVideo: true}));
- expect(searchParams(unsized)).toEqual({format: 'webp', width: '56'});
- });
-
- it('replaces media params already on the proxy url and keeps the rest', () => {
- const url = buildForwardMessagePreviewThumbnailURL(
- thumbnail({proxyUrl: 'https://media.example.com/attachments/a?ex=abc&width=10&format=png&animated=true'}),
- );
- expect(searchParams(url)).toEqual({ex: 'abc', format: 'webp', width: '56', height: '56'});
- });
-});
diff --git a/fluxer_app/src/features/messaging/components/modals/ForwardModal.test.ts b/fluxer_app/src/features/messaging/components/modals/ForwardModal.test.ts
deleted file mode 100644
index 65d14546a..000000000
--- a/fluxer_app/src/features/messaging/components/modals/ForwardModal.test.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {shouldNavigateAfterForward} from '@app/features/messaging/components/modals/ForwardModalUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('ForwardModal', () => {
- it('navigates only for an unmodified single-destination forward', () => {
- expect(shouldNavigateAfterForward(false, 1)).toBe(true);
- expect(shouldNavigateAfterForward(true, 1)).toBe(false);
- expect(shouldNavigateAfterForward(false, 2)).toBe(false);
- expect(shouldNavigateAfterForward(false, 0)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaRotationMath.test.ts b/fluxer_app/src/features/messaging/components/modals/media_modal/MediaRotationMath.test.ts
deleted file mode 100644
index bfe78df2e..000000000
--- a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaRotationMath.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getNearestDefaultRotationDegrees,
- isDefaultRotationDegrees,
- isSidewaysRotationDegrees,
- normalizeRotationDegrees,
- rotateAnticlockwiseDegrees,
- rotateClockwiseDegrees,
-} from '@app/features/messaging/components/modals/media_modal/MediaRotationMath';
-import {describe, expect, it} from 'vitest';
-
-describe('MediaRotationMath', () => {
- it('keeps clockwise animation continuous through a full turn', () => {
- let rotation = 0;
- rotation = rotateClockwiseDegrees(rotation);
- expect(rotation).toBe(90);
- rotation = rotateClockwiseDegrees(rotation);
- expect(rotation).toBe(180);
- rotation = rotateClockwiseDegrees(rotation);
- expect(rotation).toBe(270);
- rotation = rotateClockwiseDegrees(rotation);
- expect(rotation).toBe(360);
- });
-
- it('keeps anticlockwise animation continuous from the default orientation', () => {
- expect(rotateAnticlockwiseDegrees(0)).toBe(-90);
- expect(normalizeRotationDegrees(-90)).toBe(270);
- });
-
- it('normalizes orientation for layout and default-state decisions', () => {
- expect(isSidewaysRotationDegrees(-90)).toBe(true);
- expect(isSidewaysRotationDegrees(450)).toBe(true);
- expect(isDefaultRotationDegrees(360)).toBe(true);
- expect(isDefaultRotationDegrees(-360)).toBe(true);
- });
-
- it('resets to the nearest default-equivalent angle', () => {
- expect(getNearestDefaultRotationDegrees(270)).toBe(360);
- expect(getNearestDefaultRotationDegrees(-270)).toBe(-360);
- expect(getNearestDefaultRotationDegrees(450)).toBe(360);
- expect(getNearestDefaultRotationDegrees(360)).toBe(360);
- });
-});
diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaViewerPanZoomStability.test.ts b/fluxer_app/src/features/messaging/components/modals/media_modal/MediaViewerPanZoomStability.test.ts
deleted file mode 100644
index 466d7a067..000000000
--- a/fluxer_app/src/features/messaging/components/modals/media_modal/MediaViewerPanZoomStability.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {describe, expect, it} from 'vitest';
-
-function sourceFile(relativePath: string): string {
- return readFileSync(new URL(relativePath, import.meta.url), 'utf8');
-}
-
-describe('media viewer pan zoom stability', () => {
- it('keeps the custom pan-zoom surface independent from message observables', () => {
- const surfaceSource = sourceFile('pan_zoom/PanZoomSurface.tsx');
- const hookSource = sourceFile('pan_zoom/usePanZoomSurface.ts');
- const viewerSource = sourceFile('MediaViewers.tsx');
- expect(`${surfaceSource}\n${hookSource}`).not.toMatch(/mobx|mobx-react-lite|observer\(/);
- expect(viewerSource).toMatch(/memo\(\s*forwardRef<[^>]+>\(function DesktopMediaViewer/);
- expect(viewerSource).toMatch(/memo\(\s*forwardRef<[^>]+>\(function MobileMediaViewer/);
- expect(viewerSource).not.toMatch(/observer\(/);
- });
- it('does not reintroduce the removed zoom dependency at the media viewer call sites', () => {
- const mediaViewerSource = sourceFile('MediaViewers.tsx');
- const mobileVideoSource = sourceFile('../../../../voice/components/modals/MobileVideoViewer.tsx');
- const removedPackageName = ['react', 'zoom', 'pan', 'pinch'].join('-');
- expect(mediaViewerSource).not.toContain(removedPackageName);
- expect(mobileVideoSource).not.toContain(removedPackageName);
- });
- it('keeps the media viewport stable while zoom state changes', () => {
- const modalCss = sourceFile('../MediaModal.module.css');
- expect(modalCss).not.toMatch(/data-zoom-state=['"]zoomed['"][^{]*\.mediaArea/);
- });
- it('keeps parent mobile actions out of the fullscreen mobile video player', () => {
- const modalSource = sourceFile('../MediaModal.tsx');
- expect(modalSource).toContain('const isMobileVideo = Boolean(isMobile && mediaType ===');
- expect(modalSource).toContain('{isMobile && !isMobileVideo ? (');
- });
- it('stamps the pan-zoom measured-box marker on the rotation container', () => {
- const hookSource = sourceFile('pan_zoom/usePanZoomSurface.ts');
- const modalSource = sourceFile('../MediaModal.tsx');
- const selectorMatch = hookSource.match(/MEASURED_BOX_SELECTOR = '\[([a-z-]+)\]'/);
- expect(selectorMatch).not.toBeNull();
- const markerAttribute = selectorMatch?.[1] ?? 'missing-marker';
- expect(modalSource).toMatch(new RegExp(`styles\\.mediaContainer[^<]*\\b${markerAttribute}=`));
- });
- it('floors the media-fit clamps with a length-typed zero so they resolve to valid lengths', () => {
- const modalCss = sourceFile('../MediaModal.module.css');
- expect(modalCss).toMatch(/--media-fit-max-width:\s*max\(0px,/);
- expect(modalCss).toMatch(/--media-fit-max-height:\s*max\(0px,/);
- expect(modalCss).not.toMatch(/max\(\s*0\s*,/);
- });
-});
diff --git a/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomMath.test.ts b/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomMath.test.ts
deleted file mode 100644
index 6f67efcc2..000000000
--- a/fluxer_app/src/features/messaging/components/modals/media_modal/pan_zoom/PanZoomMath.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clampPanForScale,
- clampScale,
- DEFAULT_ZOOM_SCALE,
- getAnchoredZoomPoint,
- getCentroid,
- getDistance,
- isDefaultTransform,
- MIN_ZOOM_SCALE,
- type PanZoomMetrics,
- TAP_MOVE_THRESHOLD,
-} from '@app/features/messaging/components/modals/media_modal/pan_zoom/PanZoomMath';
-import {describe, expect, it} from 'vitest';
-
-const METRICS: PanZoomMetrics = {
- viewportWidth: 800,
- viewportHeight: 600,
- contentWidth: 400,
- contentHeight: 300,
-};
-const UNCAPPED_METRICS: PanZoomMetrics = {
- viewportWidth: 800,
- viewportHeight: 600,
- contentWidth: 800,
- contentHeight: 600,
-};
-
-describe('PanZoomMath', () => {
- it('measures pinch distance and centroid without rounding drift', () => {
- const first = {x: 10, y: 20};
- const second = {x: 70, y: 100};
- expect(getDistance(first, second)).toBe(100);
- expect(getCentroid(first, second)).toEqual({x: 40, y: 60});
- });
- it('recenters pan when scale returns to the fitted view', () => {
- expect(clampPanForScale({x: 300, y: -180}, MIN_ZOOM_SCALE, METRICS)).toEqual({x: 0, y: 0});
- });
- it('clamps stepped zoom scales to configured limits', () => {
- expect(clampScale(0.6, 1, 5)).toBe(1);
- expect(clampScale(2.5, 1, 5)).toBe(2.5);
- expect(clampScale(8, 1, 5)).toBe(5);
- });
- it('treats a drag under twenty pixels as a tap', () => {
- expect(TAP_MOVE_THRESHOLD).toBe(20);
- });
- it('pins an axis whose zoomed content still fits inside the viewport', () => {
- const portrait: PanZoomMetrics = {viewportWidth: 800, viewportHeight: 600, contentWidth: 300, contentHeight: 600};
- expect(clampPanForScale({x: 400, y: 600}, 2.5, portrait)).toEqual({x: 0, y: 450});
- });
- it('detects the centered default transform with a small epsilon', () => {
- expect(isDefaultTransform({scale: 1.005, x: 0.004, y: -0.003})).toBe(true);
- expect(isDefaultTransform({scale: 1.05, x: 0, y: 0})).toBe(false);
- expect(isDefaultTransform({scale: 1, x: 3, y: 0})).toBe(false);
- });
- it('clamps pan to the transformed content bounds', () => {
- expect(clampPanForScale({x: 500, y: -500}, 4, METRICS)).toEqual({x: 400, y: -300});
- expect(clampPanForScale({x: -240, y: 120}, 2, METRICS)).toEqual({x: 0, y: 0});
- });
- it('keeps the zoom origin visually anchored while zooming in', () => {
- const nextPoint = getAnchoredZoomPoint({
- origin: {x: 120, y: -80},
- current: {x: 0, y: 0},
- currentScale: MIN_ZOOM_SCALE,
- nextScale: DEFAULT_ZOOM_SCALE,
- metrics: UNCAPPED_METRICS,
- });
- expect(nextPoint).toEqual({x: -180, y: 120});
- });
- it('clamps anchored zoom to the available pan range for edge origins', () => {
- const nextPoint = getAnchoredZoomPoint({
- origin: {x: -390, y: 290},
- current: {x: 0, y: 0},
- currentScale: MIN_ZOOM_SCALE,
- nextScale: 5,
- metrics: METRICS,
- });
- expect(nextPoint).toEqual({x: 600, y: -450});
- });
- it('resets pan when an anchored zoom resolves back to fit', () => {
- const nextPoint = getAnchoredZoomPoint({
- origin: {x: 200, y: 100},
- current: {x: -80, y: 60},
- currentScale: DEFAULT_ZOOM_SCALE,
- nextScale: MIN_ZOOM_SCALE,
- metrics: METRICS,
- });
- expect(nextPoint).toEqual({x: 0, y: 0});
- });
-});
diff --git a/fluxer_app/src/features/messaging/hooks/useMessageListKeyboardNavigation.test.tsx b/fluxer_app/src/features/messaging/hooks/useMessageListKeyboardNavigation.test.tsx
deleted file mode 100644
index 7835cbbfc..000000000
--- a/fluxer_app/src/features/messaging/hooks/useMessageListKeyboardNavigation.test.tsx
+++ /dev/null
@@ -1,264 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {CHANNEL_MESSAGE_ID_PREFIX, findMessageElement} from '@app/features/messaging/utils/MessageNodeSelectors';
-import {act, createElement, type RefObject} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const keyboardModeMock = {keyboardModeEnabled: true};
-const messageFocusMock = {focusedMessageId: null as string | null};
-
-vi.mock('@app/features/ui/state/KeyboardMode', () => ({default: keyboardModeMock}));
-vi.mock('@app/features/messaging/state/MessageFocus', () => ({default: messageFocusMock}));
-
-const {useMessageListKeyboardNavigation} = await import(
- '@app/features/messaging/hooks/useMessageListKeyboardNavigation'
-);
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const CHANNEL_ID = '900000000000000001';
-
-interface RowSpec {
- messageId: string;
- idPrefix: string;
-}
-
-let viewport: HTMLElement;
-let host: HTMLDivElement;
-let root: Root;
-
-function mountRows(specs: ReadonlyArray<RowSpec>): void {
- for (const spec of specs) {
- const row = document.createElement('div');
- row.id = `${spec.idPrefix}-${CHANNEL_ID}-${spec.messageId}`;
- row.dataset.messageId = spec.messageId;
- row.dataset.channelId = CHANNEL_ID;
- row.tabIndex = -1;
- viewport.append(row);
- }
-}
-
-function focusedRowId(): string | null {
- const active = document.activeElement;
- return active instanceof HTMLElement ? (active.dataset.messageId ?? null) : null;
-}
-
-interface EdgeOptions {
- onNavigatePastNewest?: () => void;
- onLoadMoreAfter?: () => void;
- hasMoreAfter?: boolean;
-}
-
-function render(onFocusMessage?: (messageId: string) => void, edge: EdgeOptions = {}): void {
- const containerRef: RefObject<HTMLElement | null> = {current: viewport};
- function Harness(): null {
- useMessageListKeyboardNavigation({
- containerRef,
- channelId: CHANNEL_ID,
- onFocusMessage,
- allowWhenInactive: true,
- ...edge,
- });
- return null;
- }
- act(() => {
- root.render(createElement(Harness));
- });
-}
-
-function pressArrow(key: 'ArrowUp' | 'ArrowDown'): void {
- act(() => {
- window.dispatchEvent(new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}));
- });
-}
-
-beforeEach(() => {
- keyboardModeMock.keyboardModeEnabled = true;
- messageFocusMock.focusedMessageId = null;
- viewport = document.createElement('div');
- document.body.append(viewport);
- viewport.addEventListener('focusin', (event) => {
- const target = event.target;
- if (target instanceof HTMLElement && target.dataset.messageId) {
- messageFocusMock.focusedMessageId = target.dataset.messageId;
- }
- });
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
- vi.restoreAllMocks();
-});
-
-describe('useMessageListKeyboardNavigation', () => {
- it('walks from the newest message up through a revealed blocked group', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: 'blocked-messages'},
- {messageId: '3', idPrefix: 'blocked-messages'},
- {messageId: '4', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
-
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('4');
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('3');
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('2');
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('1');
- });
-
- it('walks back down out of a revealed blocked group', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: 'blocked-messages'},
- {messageId: '3', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
-
- pressArrow('ArrowDown');
- expect(focusedRowId()).toBe('1');
- pressArrow('ArrowDown');
- expect(focusedRowId()).toBe('2');
- pressArrow('ArrowDown');
- expect(focusedRowId()).toBe('3');
- });
-
- it('keeps navigating when the focus delegate cannot resolve the target element', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: 'blocked-messages'},
- {messageId: '3', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- const onFocusMessage = vi.fn<(messageId: string) => void>();
- render(onFocusMessage);
-
- pressArrow('ArrowUp');
- expect(onFocusMessage).toHaveBeenLastCalledWith('3');
- expect(focusedRowId()).toBe('3');
- pressArrow('ArrowUp');
- expect(onFocusMessage).toHaveBeenLastCalledWith('2');
- expect(focusedRowId()).toBe('2');
- });
-
- it('leaves scrolling to the delegate when the delegate did move focus', () => {
- mountRows([{messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX}]);
- const scrollIntoView = vi.fn();
- vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(scrollIntoView);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
-
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('1');
- expect(scrollIntoView).not.toHaveBeenCalled();
- });
-
- it('scrolls the target into view itself when the delegate did nothing', () => {
- mountRows([{messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX}]);
- const scrollIntoView = vi.fn();
- vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(scrollIntoView);
- render(vi.fn());
-
- pressArrow('ArrowUp');
- expect(scrollIntoView).toHaveBeenCalledTimes(1);
- });
-
- it('keeps navigating while a checkbox inside the list holds focus', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- const checkbox = document.createElement('input');
- checkbox.type = 'checkbox';
- viewport.append(checkbox);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
- checkbox.focus();
-
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('2');
- });
-
- it('stops navigating while a text input inside the list holds focus', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- const textInput = document.createElement('input');
- textInput.type = 'text';
- viewport.append(textInput);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
- textInput.focus();
-
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBeNull();
- });
-
- it('skips messages that a collapsed group has removed from the DOM', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '4', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- render((messageId) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- });
-
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('4');
- pressArrow('ArrowUp');
- expect(focusedRowId()).toBe('1');
- });
-});
-
-describe('useMessageListKeyboardNavigation past the newest message', () => {
- const focusRow = (messageId: string) => {
- findMessageElement(document, viewport, CHANNEL_ID, messageId)?.focus({preventScroll: true});
- };
-
- it('hands focus to the composer when stepping down past the newest message', () => {
- mountRows([
- {messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- {messageId: '2', idPrefix: CHANNEL_MESSAGE_ID_PREFIX},
- ]);
- const onNavigatePastNewest = vi.fn();
- render(focusRow, {onNavigatePastNewest});
-
- pressArrow('ArrowDown');
- pressArrow('ArrowDown');
- expect(focusedRowId()).toBe('2');
- expect(onNavigatePastNewest).not.toHaveBeenCalled();
-
- pressArrow('ArrowDown');
- expect(onNavigatePastNewest).toHaveBeenCalledTimes(1);
- });
-
- it('loads newer messages instead of leaving the list while more exist after it', () => {
- mountRows([{messageId: '1', idPrefix: CHANNEL_MESSAGE_ID_PREFIX}]);
- const onNavigatePastNewest = vi.fn();
- const onLoadMoreAfter = vi.fn();
- render(focusRow, {onNavigatePastNewest, onLoadMoreAfter, hasMoreAfter: true});
-
- pressArrow('ArrowDown');
- pressArrow('ArrowDown');
- expect(onLoadMoreAfter).toHaveBeenCalledTimes(1);
- expect(onNavigatePastNewest).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/messaging/hooks/useMessageSubmission.test.tsx b/fluxer_app/src/features/messaging/hooks/useMessageSubmission.test.tsx
deleted file mode 100644
index 7f15c0655..000000000
--- a/fluxer_app/src/features/messaging/hooks/useMessageSubmission.test.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Channel} from '@app/features/channel/models/Channel';
-import {type SendMessageFunction, useMessageSubmission} from '@app/features/messaging/hooks/useMessageSubmission';
-import {TypingUtils} from '@app/features/typing/utils/TypingUtils';
-import {MessageFlags} from '@fluxer/constants/src/ChannelConstants';
-import {act, createElement} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const messageCommands = vi.hoisted(() => ({
- reserveSend: vi.fn(() => true),
- send: vi.fn(() => Promise.resolve(null)),
- createOptimistic: vi.fn(),
- stopReply: vi.fn(),
-}));
-const draftCommands = vi.hoisted(() => ({deleteDraft: vi.fn()}));
-const cloudUpload = vi.hoisted(() => ({
- getTextareaAttachments: vi.fn((): Array<unknown> => []),
- claimAttachmentsForMessage: vi.fn(() => []),
-}));
-
-vi.mock('@app/features/messaging/commands/MessageCommands', () => messageCommands);
-vi.mock('@app/features/messaging/commands/DraftCommands', () => draftCommands);
-vi.mock('@app/features/messaging/upload/CloudUpload', () => ({CloudUpload: cloudUpload}));
-vi.mock('@app/features/messaging/models/MessagingMessage', () => ({
- Message: class {
- constructor(data: object) {
- Object.assign(this, data);
- }
- toJSON(): object {
- return {...this};
- }
- },
-}));
-vi.mock('@app/features/messaging/state/ChatInputSettings', () => ({default: {convertEmoticons: false}}));
-vi.mock('@app/features/user/state/UserSettings', () => ({default: {getSanitizeUrls: () => false}}));
-vi.mock('@app/features/messaging/utils/EmoticonConversionUtils', () => ({
- convertEmoticonsToEmoji: (content: string) => content,
-}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getCurrentUser: () => ({toJSON: () => ({id: 'me'})})}}));
-vi.mock('@app/features/permissions/state/Permission', () => ({default: {can: () => true}}));
-vi.mock('@app/features/slowmode/state/Slowmode', () => ({default: {getSlowmodeRemaining: () => 0}}));
-vi.mock('@app/features/slowmode/commands/SlowmodeCommands', () => ({
- prepareMessageSend: vi.fn(),
- recordPendingMessageSend: vi.fn(() => null),
- confirmMessageSend: vi.fn(),
- discardPendingMessageSend: vi.fn(),
-}));
-vi.mock('@app/features/slowmode/components/alerts/SlowmodeRateLimitedModal', () => ({
- SlowmodeRateLimitedModal: () => null,
-}));
-vi.mock('@app/features/ui/commands/ModalCommands', () => ({modal: (render: unknown) => render, push: vi.fn()}));
-vi.mock('@app/features/typing/utils/TypingUtils', () => ({TypingUtils: {handleOwnMessageSent: vi.fn()}}));
-vi.mock('@app/features/platform/utils/ComponentBus', () => ({ComponentBus: {dispatch: vi.fn()}}));
-vi.mock('@lingui/core/macro', () => ({msg: (value: unknown) => value}));
-vi.mock('@lingui/react/macro', () => ({useLingui: () => ({i18n: {_: () => ''}})}));
-
-const channel = {id: 'c'} as unknown as Channel;
-
-let host: HTMLDivElement;
-let root: Root;
-
-function renderSubmission(): ReturnType<typeof useMessageSubmission> {
- let submission: ReturnType<typeof useMessageSubmission> | null = null;
- const Probe = () => {
- submission = useMessageSubmission({channel, referencedMessage: null, replyingMessage: null});
- return null;
- };
- act(() => {
- root.render(createElement(Probe));
- });
- return submission!;
-}
-
-function renderSendMessage(): SendMessageFunction {
- return renderSubmission().sendMessage;
-}
-
-beforeEach(() => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
- vi.clearAllMocks();
- cloudUpload.getTextareaAttachments.mockReturnValue([]);
- messageCommands.reserveSend.mockReturnValue(true);
-});
-
-describe('useMessageSubmission', () => {
- it('sends nothing and keeps the draft for a message that is only @silent', () => {
- const sendMessage = renderSendMessage();
- expect(sendMessage('@silent', false)).toBe(false);
- expect(messageCommands.reserveSend).not.toHaveBeenCalled();
- expect(draftCommands.deleteDraft).not.toHaveBeenCalled();
- expect(messageCommands.send).not.toHaveBeenCalled();
- });
-
- it('sends nothing and keeps the draft for a /tts command that is only @silent', () => {
- const sendMessage = renderSendMessage();
- expect(sendMessage('@silent', false, true)).toBe(false);
- expect(messageCommands.reserveSend).not.toHaveBeenCalled();
- expect(draftCommands.deleteDraft).not.toHaveBeenCalled();
- expect(messageCommands.send).not.toHaveBeenCalled();
- });
-
- it('sends nothing and keeps the draft for a sticker send that is only @silent', () => {
- const sendMessage = renderSendMessage();
- expect(sendMessage('@silent', false, [])).toBe(false);
- expect(messageCommands.reserveSend).not.toHaveBeenCalled();
- expect(draftCommands.deleteDraft).not.toHaveBeenCalled();
- });
-
- it('sends an attachment captioned only by @silent with no content and the silent flag', () => {
- cloudUpload.getTextareaAttachments.mockReturnValue([{id: 1}]);
- const sendMessage = renderSendMessage();
- expect(sendMessage('@silent', false)).toBe(true);
- expect(draftCommands.deleteDraft).toHaveBeenCalledWith('c');
- expect(messageCommands.send).toHaveBeenCalledWith(
- 'c',
- expect.objectContaining({content: '', flags: MessageFlags.SUPPRESS_NOTIFICATIONS}),
- );
- });
-
- it('tells typing that its own message was sent before creating the optimistic message', () => {
- const handleOwnMessageSent = vi.mocked(TypingUtils.handleOwnMessageSent);
- const {sendMessage, sendOptimisticMessage} = renderSubmission();
-
- expect(sendMessage('hello', false)).toBe(true);
- sendOptimisticMessage({content: 'a sticker caption'}, {hasAttachments: false});
-
- expect(handleOwnMessageSent.mock.calls).toEqual([['c'], ['c']]);
- expect(messageCommands.createOptimistic).toHaveBeenCalledTimes(2);
- const typingOrder = handleOwnMessageSent.mock.invocationCallOrder;
- const optimisticOrder = messageCommands.createOptimistic.mock.invocationCallOrder;
- expect(typingOrder[0]!).toBeLessThan(optimisticOrder[0]!);
- expect(optimisticOrder[0]!).toBeLessThan(typingOrder[1]!);
- expect(typingOrder[1]!).toBeLessThan(optimisticOrder[1]!);
- });
-
- it('sends the text after @silent with the silent flag', () => {
- const sendMessage = renderSendMessage();
- expect(sendMessage('@silent hi', false)).toBe(true);
- expect(draftCommands.deleteDraft).toHaveBeenCalledWith('c');
- expect(messageCommands.send).toHaveBeenCalledWith(
- 'c',
- expect.objectContaining({content: 'hi', flags: MessageFlags.SUPPRESS_NOTIFICATIONS}),
- );
- });
-});
diff --git a/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx b/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx
deleted file mode 100644
index 4557d69ae..000000000
--- a/fluxer_app/src/features/messaging/hooks/useTextareaDraftAndTyping.test.tsx
+++ /dev/null
@@ -1,196 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Endpoints} from '@app/features/app/constants/Endpoints';
-import {act, createElement, useRef, useState} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = vi.hoisted(() => ({
- post: vi.fn((_path: string) => Promise.resolve({ok: true})),
-}));
-
-vi.mock('@app/features/messaging/commands/DraftCommands', () => ({createDraft: vi.fn(), deleteDraft: vi.fn()}));
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {get: vi.fn(), post: doubles.post}}));
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: {showMyselfTyping: false}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: () => undefined}}));
-
-const {useTextareaDraftAndTyping} = await import('@app/features/messaging/hooks/useTextareaDraftAndTyping');
-const {default: RollingTypingSender} = await import('@app/features/typing/rolling/RollingTypingSender');
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-interface ComposerProps {
- channelId: string;
- draft?: string | null;
- enabled?: boolean;
- typingEnabled?: boolean;
- isEditingMessageInComposer?: boolean;
-}
-
-let host: HTMLDivElement;
-let root: Root;
-let setComposerValue: (value: string) => void = () => undefined;
-
-function Composer({
- channelId,
- draft = null,
- enabled = true,
- typingEnabled,
- isEditingMessageInComposer = false,
-}: ComposerProps) {
- const [value, setValue] = useState('');
- const previousValueRef = useRef('');
- setComposerValue = setValue;
- useTextareaDraftAndTyping({
- channelId,
- value,
- setValue,
- draft,
- previousValueRef,
- enabled,
- typingEnabled,
- isEditingMessageInComposer,
- });
- return null;
-}
-
-function render(props: ComposerProps): void {
- act(() => {
- root.render(createElement(Composer, props));
- });
-}
-
-function type(value: string): void {
- act(() => {
- setComposerValue(value);
- });
-}
-
-function advance(ms: number): void {
- act(() => {
- vi.advanceTimersByTime(ms);
- });
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- vi.useFakeTimers();
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- RollingTypingSender.reset();
- RollingTypingStore.reset();
- document.body.replaceChildren();
- vi.useRealTimers();
- vi.clearAllMocks();
-});
-
-describe('useTextareaDraftAndTyping', () => {
- it('sends typing once for a burst of keystrokes', () => {
- render({channelId: 'c1'});
-
- let draft = '';
- for (const character of 'hello there, how are you') {
- draft += character;
- type(draft);
- advance(150);
- }
- advance(3000);
-
- expect(doubles.post).toHaveBeenCalledExactlyOnceWith(Endpoints.CHANNEL_TYPING('c1'));
- });
-
- it('never sends typing when entering mobile edit mode', () => {
- render({channelId: 'c1'});
-
- act(() => {
- root.render(createElement(Composer, {channelId: 'c1', isEditingMessageInComposer: true}));
- setComposerValue('the message being edited');
- });
- type('the message being edited again');
- advance(20000);
- render({channelId: 'c1', isEditingMessageInComposer: false});
- render({channelId: 'c1', isEditingMessageInComposer: true});
- type('a later edit keystroke');
- advance(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(RollingTypingStore.isTyping('c1', 'me')).toBe(false);
- });
-
- it('sends nothing for a draft present at mount', () => {
- render({channelId: 'c1', draft: 'saved draft'});
- advance(0);
- render({channelId: 'c1', draft: 'saved draft', typingEnabled: false});
- render({channelId: 'c1', draft: 'saved draft', typingEnabled: true});
- advance(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('sends nothing for a draft restored after mount', () => {
- render({channelId: 'c1'});
- advance(1000);
-
- render({channelId: 'c1', draft: 'synced from another device'});
- advance(0);
- render({channelId: 'c1', draft: 'synced from another device', typingEnabled: false});
- render({channelId: 'c1', draft: 'synced from another device', typingEnabled: true});
- advance(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('does not cancel a pending send when the channel changes', () => {
- render({channelId: 'c1'});
- type('hello');
- advance(500);
-
- render({channelId: 'c2'});
- advance(1000);
-
- expect(doubles.post).toHaveBeenCalledExactlyOnceWith(Endpoints.CHANNEL_TYPING('c1'));
- advance(20000);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('cancels a pending send when the composer becomes disabled', () => {
- render({channelId: 'c1'});
- type('hello');
- advance(500);
-
- render({channelId: 'c1', enabled: false});
- advance(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(RollingTypingStore.isTyping('c1', 'me')).toBe(false);
- });
-
- it('posts nothing for a spaces-only draft', () => {
- render({channelId: 'c1'});
-
- type(' ');
- type(' ');
- type('\t ');
- advance(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(RollingTypingStore.isTyping('c1', 'me')).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/ChannelIncomingMessageStateMachine.test.ts b/fluxer_app/src/features/messaging/state/ChannelIncomingMessageStateMachine.test.ts
deleted file mode 100644
index ce6bf2a5a..000000000
--- a/fluxer_app/src/features/messaging/state/ChannelIncomingMessageStateMachine.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelIncomingMessageInput,
- createChannelIncomingMessageSnapshot,
- resolveChannelIncomingMessageDecision,
- selectChannelIncomingMessageDecision,
- transitionChannelIncomingMessageSnapshot,
-} from '@app/features/messaging/state/ChannelIncomingMessageStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<ChannelIncomingMessageInput> = {}): ChannelIncomingMessageInput {
- return {
- hasNonceMatch: false,
- isUploadPlaceholder: false,
- hasMoreAfter: false,
- afterBufferAtBoundary: false,
- ...overrides,
- };
-}
-
-describe('channelIncomingMessageMachine', () => {
- it('completes upload placeholders before any other placement rule', () => {
- expect(
- resolveChannelIncomingMessageDecision(
- input({
- hasNonceMatch: true,
- isUploadPlaceholder: true,
- hasMoreAfter: true,
- afterBufferAtBoundary: true,
- }),
- ),
- ).toEqual({type: 'completeUploadPlaceholder'});
- });
-
- it('replaces matching nonce messages before checking the visible window', () => {
- expect(
- resolveChannelIncomingMessageDecision(
- input({
- hasNonceMatch: true,
- isUploadPlaceholder: false,
- hasMoreAfter: true,
- }),
- ),
- ).toEqual({type: 'replaceNonceMessage'});
- });
-
- it('ignores incoming messages past the visible window and reports boundary clearing intent', () => {
- expect(
- resolveChannelIncomingMessageDecision(
- input({
- hasMoreAfter: true,
- afterBufferAtBoundary: true,
- }),
- ),
- ).toEqual({
- type: 'ignorePastVisibleWindow',
- shouldClearAfterBoundary: true,
- });
- expect(resolveChannelIncomingMessageDecision(input({hasMoreAfter: true}))).toEqual({
- type: 'ignorePastVisibleWindow',
- shouldClearAfterBoundary: false,
- });
- });
-
- it('appends messages when no cache-placement rule intercepts them', () => {
- expect(resolveChannelIncomingMessageDecision(input())).toEqual({type: 'appendIncoming'});
- });
-
- it('re-routes when incoming message inputs change', () => {
- const staleWindowSnapshot = createChannelIncomingMessageSnapshot(input({hasMoreAfter: true}));
- expect(selectChannelIncomingMessageDecision(staleWindowSnapshot)).toEqual({
- type: 'ignorePastVisibleWindow',
- shouldClearAfterBoundary: false,
- });
-
- const appendSnapshot = transitionChannelIncomingMessageSnapshot(staleWindowSnapshot, {
- type: 'channelIncomingMessage.updated',
- input: input(),
- });
-
- expect(selectChannelIncomingMessageDecision(appendSnapshot)).toEqual({type: 'appendIncoming'});
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/ChannelMessagesLoadStateMachine.test.ts b/fluxer_app/src/features/messaging/state/ChannelMessagesLoadStateMachine.test.ts
deleted file mode 100644
index 9d3fbfbd6..000000000
--- a/fluxer_app/src/features/messaging/state/ChannelMessagesLoadStateMachine.test.ts
+++ /dev/null
@@ -1,412 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelMessagesLoadInput,
- type ChannelMessagesWindowInput,
- type ChannelMessagesWindowStatus,
- createChannelMessagesLoadSnapshot,
- createChannelMessagesWindowSnapshot,
- resolveChannelMessagesLoadDecision,
- resolveChannelMessagesWindowStatus,
- selectChannelMessagesFillerVisible,
- selectChannelMessagesLoadDecision,
- selectChannelMessagesLoadRestoresTrust,
- selectChannelMessagesSpacerHeight,
- selectChannelMessagesWindowBar,
- selectChannelMessagesWindowStatus,
- transitionChannelMessagesLoadSnapshot,
- transitionChannelMessagesWindowSnapshot,
-} from '@app/features/messaging/state/ChannelMessagesLoadStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<ChannelMessagesLoadInput> = {}): ChannelMessagesLoadInput {
- return {
- isBefore: false,
- isAfter: false,
- hasJump: false,
- wasReady: true,
- ...overrides,
- };
-}
-
-describe('channelMessagesLoadMachine', () => {
- it('replaces the visible window for initial, replacement, and jump loads', () => {
- expect(resolveChannelMessagesLoadDecision(input({wasReady: false, isBefore: true}))).toMatchObject({
- mode: 'replace',
- trimTop: false,
- trimBottom: false,
- preserveHasMoreBefore: false,
- preserveHasMoreAfter: false,
- });
- expect(resolveChannelMessagesLoadDecision(input())).toMatchObject({mode: 'replace'});
- expect(resolveChannelMessagesLoadDecision(input({hasJump: true, isAfter: true}))).toMatchObject({
- mode: 'replace',
- });
- });
-
- it('merges before-pages by prepending and trimming the bottom side', () => {
- expect(resolveChannelMessagesLoadDecision(input({isBefore: true}))).toEqual({
- mode: 'mergeBefore',
- prepend: true,
- trimTop: false,
- trimBottom: true,
- preserveHasMoreBefore: false,
- preserveHasMoreAfter: true,
- });
- });
-
- it('merges after-pages by appending and trimming the top side', () => {
- expect(resolveChannelMessagesLoadDecision(input({isAfter: true}))).toEqual({
- mode: 'mergeAfter',
- prepend: false,
- trimTop: true,
- trimBottom: false,
- preserveHasMoreBefore: true,
- preserveHasMoreAfter: false,
- });
- });
-
- it('gives before-pages precedence when both directional flags are present', () => {
- expect(resolveChannelMessagesLoadDecision(input({isBefore: true, isAfter: true}))).toMatchObject({
- mode: 'mergeBefore',
- });
- });
-
- it('re-routes when load inputs change', () => {
- const beforeSnapshot = createChannelMessagesLoadSnapshot(input({isBefore: true}));
- expect(selectChannelMessagesLoadDecision(beforeSnapshot)).toMatchObject({mode: 'mergeBefore'});
-
- const replacementSnapshot = transitionChannelMessagesLoadSnapshot(beforeSnapshot, {
- type: 'channelMessagesLoad.updated',
- input: input({hasJump: true}),
- });
-
- expect(selectChannelMessagesLoadDecision(replacementSnapshot)).toMatchObject({mode: 'replace'});
- });
-});
-
-function windowInput(overrides: Partial<ChannelMessagesWindowInput> = {}): ChannelMessagesWindowInput {
- return {
- ready: false,
- loading: false,
- failed: false,
- messageCount: 0,
- hasMoreBefore: true,
- hasMoreAfter: false,
- ...overrides,
- };
-}
-
-function drawsAFiller(status: ChannelMessagesWindowStatus): boolean {
- return status.olderPageAvailable || status.newerPageAvailable;
-}
-
-describe('channelMessagesWindowMachine', () => {
- it('holds a fresh channel in the placeholder phase and asks for a page', () => {
- expect(resolveChannelMessagesWindowStatus(windowInput())).toEqual({
- phase: 'placeholder',
- olderPageAvailable: true,
- newerPageAvailable: false,
- needsPage: true,
- retryVisible: false,
- });
- expect(resolveChannelMessagesWindowStatus(windowInput({loading: true}))).toEqual({
- phase: 'placeholder',
- olderPageAvailable: true,
- newerPageAvailable: false,
- needsPage: false,
- retryVisible: false,
- });
- });
-
- it('streams a loaded page with its own paging edges', () => {
- expect(
- resolveChannelMessagesWindowStatus(
- windowInput({ready: true, messageCount: 50, hasMoreBefore: true, hasMoreAfter: true}),
- ),
- ).toEqual({
- phase: 'stream',
- olderPageAvailable: true,
- newerPageAvailable: true,
- needsPage: false,
- retryVisible: false,
- });
- expect(selectChannelMessagesWindowBar(resolveChannelMessagesWindowStatus(windowInput({ready: true})))).toBe('none');
- });
-
- it('streams a fully loaded empty channel so the welcome header keeps rendering', () => {
- const status = resolveChannelMessagesWindowStatus(
- windowInput({ready: true, hasMoreBefore: false, hasMoreAfter: false}),
- );
- expect(status).toEqual({
- phase: 'stream',
- olderPageAvailable: false,
- newerPageAvailable: false,
- needsPage: false,
- retryVisible: false,
- });
- expect(drawsAFiller(status)).toBe(false);
- expect(selectChannelMessagesWindowBar(status)).toBe('none');
- });
-
- it('prefers the retry phase over a placeholder when the page failed with nothing loaded', () => {
- const status = resolveChannelMessagesWindowStatus(windowInput({failed: true, hasMoreAfter: true}));
- expect(status).toEqual({
- phase: 'retry',
- olderPageAvailable: true,
- newerPageAvailable: true,
- needsPage: false,
- retryVisible: true,
- });
- expect(drawsAFiller(status)).toBe(true);
- expect(selectChannelMessagesWindowBar(status)).toBe('retry');
- });
-
- it('keeps a loaded page visible when a follow-up page fails and swaps the bar for retry', () => {
- const status = resolveChannelMessagesWindowStatus(
- windowInput({ready: true, failed: true, messageCount: 50, hasMoreAfter: true}),
- );
- expect(status).toEqual({
- phase: 'stream',
- olderPageAvailable: true,
- newerPageAvailable: true,
- needsPage: false,
- retryVisible: true,
- });
- expect(selectChannelMessagesWindowBar(status)).toBe('retry');
- });
-
- it('decides the filler from the paging edges alone, never from the phase', () => {
- for (const ready of [false, true]) {
- for (const loading of [false, true]) {
- for (const failed of [false, true]) {
- for (const messageCount of [0, 50]) {
- for (const hasMoreBefore of [false, true]) {
- for (const hasMoreAfter of [false, true]) {
- const status = resolveChannelMessagesWindowStatus({
- ready,
- loading,
- failed,
- messageCount,
- hasMoreBefore,
- hasMoreAfter,
- });
- expect(drawsAFiller(status)).toBe(hasMoreBefore || hasMoreAfter);
- expect(status.phase === 'placeholder' && selectChannelMessagesWindowBar(status) !== 'none').toBe(false);
- }
- }
- }
- }
- }
- }
- });
-
- it('collapses the empty around-page reply into a placeholder that asks for a page', () => {
- let snapshot = createChannelMessagesWindowSnapshot(windowInput());
- expect(selectChannelMessagesWindowStatus(snapshot)).toEqual({
- phase: 'placeholder',
- olderPageAvailable: true,
- newerPageAvailable: false,
- needsPage: true,
- retryVisible: false,
- });
-
- snapshot = transitionChannelMessagesWindowSnapshot(snapshot, {
- type: 'channelMessagesWindow.updated',
- input: windowInput({loading: true}),
- });
- expect(selectChannelMessagesWindowStatus(snapshot)).toEqual({
- phase: 'placeholder',
- olderPageAvailable: true,
- newerPageAvailable: false,
- needsPage: false,
- retryVisible: false,
- });
-
- snapshot = transitionChannelMessagesWindowSnapshot(snapshot, {
- type: 'channelMessagesWindow.updated',
- input: windowInput({ready: true, messageCount: 0, hasMoreBefore: true, hasMoreAfter: true}),
- });
- const afterEmptyAroundPage = selectChannelMessagesWindowStatus(snapshot);
- expect(afterEmptyAroundPage).toEqual({
- phase: 'placeholder',
- olderPageAvailable: true,
- newerPageAvailable: true,
- needsPage: true,
- retryVisible: false,
- });
- expect(drawsAFiller(afterEmptyAroundPage)).toBe(true);
- expect(selectChannelMessagesWindowBar(afterEmptyAroundPage)).toBe('none');
-
- snapshot = transitionChannelMessagesWindowSnapshot(snapshot, {
- type: 'channelMessagesWindow.updated',
- input: windowInput({ready: true, messageCount: 0, hasMoreBefore: false, hasMoreAfter: false}),
- });
- expect(selectChannelMessagesWindowStatus(snapshot)).toEqual({
- phase: 'stream',
- olderPageAvailable: false,
- newerPageAvailable: false,
- needsPage: false,
- retryVisible: false,
- });
- });
-});
-
-const FILLER_HEIGHT = 240;
-
-function loadedWindowInput(overrides: Partial<ChannelMessagesWindowInput> = {}): ChannelMessagesWindowInput {
- return {
- ready: true,
- loading: false,
- failed: false,
- messageCount: 40,
- hasMoreBefore: false,
- hasMoreAfter: false,
- ...overrides,
- };
-}
-
-function spacerFor(overrides: Partial<ChannelMessagesWindowInput> = {}): number {
- return selectChannelMessagesSpacerHeight(
- resolveChannelMessagesWindowStatus(loadedWindowInput(overrides)),
- FILLER_HEIGHT,
- );
-}
-
-describe('selectChannelMessagesSpacerHeight', () => {
- it('reports the filler height during retry too, because retry now draws the same list', () => {
- const status = resolveChannelMessagesWindowStatus(
- loadedWindowInput({ready: false, failed: true, messageCount: 0, hasMoreBefore: true, hasMoreAfter: true}),
- );
- expect(status.phase).toBe('retry');
- expect(selectChannelMessagesSpacerHeight(status, FILLER_HEIGHT)).toBe(FILLER_HEIGHT);
- });
-
- it('withholds the filler height during retry once both paging edges are closed', () => {
- const status = resolveChannelMessagesWindowStatus(
- loadedWindowInput({ready: false, failed: true, messageCount: 0, hasMoreBefore: false, hasMoreAfter: false}),
- );
- expect(status.phase).toBe('retry');
- expect(selectChannelMessagesSpacerHeight(status, FILLER_HEIGHT)).toBe(0);
- });
-
- it('withholds the filler height from a stream with both paging edges closed', () => {
- expect(spacerFor({hasMoreBefore: false, hasMoreAfter: false})).toBe(0);
- });
-
- it('reports the filler height for whichever single stream edge is still open', () => {
- expect(spacerFor({hasMoreBefore: true, hasMoreAfter: false})).toBe(FILLER_HEIGHT);
- expect(spacerFor({hasMoreBefore: false, hasMoreAfter: true})).toBe(FILLER_HEIGHT);
- expect(spacerFor({hasMoreBefore: true, hasMoreAfter: true})).toBe(FILLER_HEIGHT);
- });
-
- it('reports the filler height for a placeholder whose older edge is open', () => {
- expect(spacerFor({ready: false, messageCount: 0, hasMoreBefore: true})).toBe(FILLER_HEIGHT);
- expect(spacerFor({ready: false, loading: true, messageCount: 0, hasMoreBefore: true})).toBe(FILLER_HEIGHT);
- });
-
- it('withholds it from a placeholder with both paging edges closed, which draws no filler', () => {
- expect(spacerFor({ready: false, messageCount: 0, hasMoreBefore: false, hasMoreAfter: false})).toBe(0);
- });
-
- it('is the filler height exactly when a paging edge is open, in every phase', () => {
- const seen = new Set<string>();
- let zeroCases = 0;
- let fillerCases = 0;
- for (const ready of [false, true]) {
- for (const loading of [false, true]) {
- for (const failed of [false, true]) {
- for (const messageCount of [0, 40]) {
- for (const hasMoreBefore of [false, true]) {
- for (const hasMoreAfter of [false, true]) {
- const input = {ready, loading, failed, messageCount, hasMoreBefore, hasMoreAfter};
- const status = resolveChannelMessagesWindowStatus(input);
- const height = selectChannelMessagesSpacerHeight(status, FILLER_HEIGHT);
- expect(height).toBe(hasMoreBefore || hasMoreAfter ? FILLER_HEIGHT : 0);
- seen.add(status.phase);
- if (height === 0) zeroCases += 1;
- else fillerCases += 1;
- }
- }
- }
- }
- }
- }
- expect([...seen].sort()).toEqual(['placeholder', 'retry', 'stream']);
- expect(zeroCases).toBeGreaterThan(0);
- expect(fillerCases).toBeGreaterThan(0);
- });
-});
-
-describe('selectChannelMessagesFillerVisible', () => {
- it('always draws the filler when motion is not reduced', () => {
- for (const scrollManagerInitialized of [false, true]) {
- for (const ready of [false, true]) {
- expect(selectChannelMessagesFillerVisible({reducedMotion: false, scrollManagerInitialized, ready})).toBe(true);
- }
- }
- });
-
- it('holds the filler back under reduced motion until the manager is initialized or the page is ready', () => {
- expect(
- selectChannelMessagesFillerVisible({reducedMotion: true, scrollManagerInitialized: false, ready: false}),
- ).toBe(false);
- expect(
- selectChannelMessagesFillerVisible({reducedMotion: true, scrollManagerInitialized: true, ready: false}),
- ).toBe(true);
- expect(
- selectChannelMessagesFillerVisible({reducedMotion: true, scrollManagerInitialized: false, ready: true}),
- ).toBe(true);
- expect(selectChannelMessagesFillerVisible({reducedMotion: true, scrollManagerInitialized: true, ready: true})).toBe(
- true,
- );
- });
-
- it('cannot suppress the stream filler, because the stream phase is only reachable when the page is ready', () => {
- let streamCases = 0;
- for (const ready of [false, true]) {
- for (const loading of [false, true]) {
- for (const failed of [false, true]) {
- for (const messageCount of [0, 40]) {
- for (const hasMoreBefore of [false, true]) {
- for (const hasMoreAfter of [false, true]) {
- const input = {ready, loading, failed, messageCount, hasMoreBefore, hasMoreAfter};
- if (resolveChannelMessagesWindowStatus(input).phase !== 'stream') continue;
- streamCases += 1;
- expect(input.ready).toBe(true);
- expect(
- selectChannelMessagesFillerVisible({
- reducedMotion: true,
- scrollManagerInitialized: false,
- ready: input.ready,
- }),
- ).toBe(true);
- }
- }
- }
- }
- }
- }
- expect(streamCases).toBeGreaterThan(0);
- });
-});
-
-describe('selectChannelMessagesLoadRestoresTrust', () => {
- it('trusts a window a replacement load rebuilt from scratch', () => {
- expect(selectChannelMessagesLoadRestoresTrust({mode: 'replace', isAfter: false, hasMoreAfter: false})).toBe(true);
- });
-
- it('trusts a window whose tail merge caught up to the live edge', () => {
- expect(selectChannelMessagesLoadRestoresTrust({mode: 'mergeAfter', isAfter: true, hasMoreAfter: false})).toBe(true);
- });
-
- it('keeps distrusting a tail merge that stopped short of the live edge', () => {
- expect(selectChannelMessagesLoadRestoresTrust({mode: 'mergeAfter', isAfter: true, hasMoreAfter: true})).toBe(false);
- });
-
- it('keeps distrusting a page of older history', () => {
- expect(selectChannelMessagesLoadRestoresTrust({mode: 'mergeBefore', isAfter: false, hasMoreAfter: false})).toBe(
- false,
- );
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/MentionConfirmationStateMachine.test.ts b/fluxer_app/src/features/messaging/state/MentionConfirmationStateMachine.test.ts
deleted file mode 100644
index d22060d05..000000000
--- a/fluxer_app/src/features/messaging/state/MentionConfirmationStateMachine.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMentionConfirmationSnapshot,
- type MentionConfirmationInfo,
- selectMentionConfirmationModel,
- transitionMentionConfirmationSnapshot,
-} from '@app/features/messaging/state/MentionConfirmationStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function confirmation(overrides: Partial<MentionConfirmationInfo> = {}): MentionConfirmationInfo {
- return {
- mentionType: '@everyone',
- memberCount: 80,
- content: '@everyone hello',
- sourceContent: '@everyone hello',
- ...overrides,
- };
-}
-
-describe('MentionConfirmationStateMachine', () => {
- it('shows a current confirmation request', () => {
- const info = confirmation();
- const snapshot = transitionMentionConfirmationSnapshot(createMentionConfirmationSnapshot(), {
- type: 'mentionConfirmation.requested',
- info,
- currentSourceContent: info.sourceContent,
- });
-
- expect(selectMentionConfirmationModel(snapshot)).toEqual({
- visible: true,
- pending: info,
- });
- });
-
- it('ignores a stale confirmation request after the composer changed', () => {
- const info = confirmation();
- const snapshot = transitionMentionConfirmationSnapshot(createMentionConfirmationSnapshot(), {
- type: 'mentionConfirmation.requested',
- info,
- currentSourceContent: 'edited text',
- });
-
- expect(selectMentionConfirmationModel(snapshot)).toEqual({
- visible: false,
- pending: null,
- });
- });
-
- it('dismisses the visible warning when the composer source changes', () => {
- const info = confirmation();
- let snapshot = transitionMentionConfirmationSnapshot(createMentionConfirmationSnapshot(), {
- type: 'mentionConfirmation.requested',
- info,
- currentSourceContent: info.sourceContent,
- });
-
- snapshot = transitionMentionConfirmationSnapshot(snapshot, {
- type: 'mentionConfirmation.composerChanged',
- sourceContent: '',
- });
-
- expect(selectMentionConfirmationModel(snapshot)).toEqual({
- visible: false,
- pending: null,
- });
- });
-
- it('keeps the visible warning while the composer source still matches', () => {
- const info = confirmation();
- let snapshot = transitionMentionConfirmationSnapshot(createMentionConfirmationSnapshot(), {
- type: 'mentionConfirmation.requested',
- info,
- currentSourceContent: info.sourceContent,
- });
-
- snapshot = transitionMentionConfirmationSnapshot(snapshot, {
- type: 'mentionConfirmation.composerChanged',
- sourceContent: info.sourceContent,
- });
-
- expect(selectMentionConfirmationModel(snapshot)).toEqual({
- visible: true,
- pending: info,
- });
- });
-
- it('clears the visible warning on confirm, dismiss, or reset', () => {
- const info = confirmation();
- for (const eventType of [
- 'mentionConfirmation.confirmed',
- 'mentionConfirmation.dismissed',
- 'mentionConfirmation.reset',
- ] as const) {
- let snapshot = transitionMentionConfirmationSnapshot(createMentionConfirmationSnapshot(), {
- type: 'mentionConfirmation.requested',
- info,
- currentSourceContent: info.sourceContent,
- });
-
- snapshot = transitionMentionConfirmationSnapshot(snapshot, {type: eventType});
-
- expect(selectMentionConfirmationModel(snapshot)).toEqual({
- visible: false,
- pending: null,
- });
- }
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/MessageQueueStateMachine.test.ts b/fluxer_app/src/features/messaging/state/MessageQueueStateMachine.test.ts
deleted file mode 100644
index aff972a34..000000000
--- a/fluxer_app/src/features/messaging/state/MessageQueueStateMachine.test.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMessageLocalSendRateLimitSnapshot,
- createMessageQueuePayloadRouteSnapshot,
- createMessageQueueRequestOutcomeSnapshot,
- createMessageQueueSendExecutionSnapshot,
- type MessageLocalSendRateLimitInput,
- resolveMessageLocalSendRateLimitDecision,
- resolveMessageQueuePayloadRouteDecision,
- resolveMessageQueueRequestOutcomeDecision,
- resolveMessageQueueSendExecutionDecision,
- selectMessageLocalSendRateLimitDecision,
- selectMessageQueuePayloadRouteDecision,
- selectMessageQueueRequestOutcomeDecision,
- selectMessageQueueSendExecutionDecision,
- transitionMessageLocalSendRateLimitSnapshot,
- transitionMessageQueuePayloadRouteSnapshot,
- transitionMessageQueueRequestOutcomeSnapshot,
- transitionMessageQueueSendExecutionSnapshot,
-} from '@app/features/messaging/state/MessageQueueStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function localLimiter(overrides: Partial<MessageLocalSendRateLimitInput> = {}): MessageLocalSendRateLimitInput {
- return {
- now: 1_000,
- windowStartedAt: null,
- sentCount: 0,
- blockedUntil: null,
- maxSends: 5,
- windowMs: 2_000,
- blockMs: 3_000,
- ...overrides,
- };
-}
-
-describe('messageQueuePayloadRouteMachine', () => {
- it('routes known queue payload types', () => {
- expect(resolveMessageQueuePayloadRouteDecision({payloadType: 'send'})).toEqual({type: 'send'});
- expect(resolveMessageQueuePayloadRouteDecision({payloadType: 'edit'})).toEqual({type: 'edit'});
- });
-
- it('routes unknown payload types to an explicit fallback', () => {
- expect(resolveMessageQueuePayloadRouteDecision({payloadType: 'delete'})).toEqual({type: 'unknown'});
- expect(resolveMessageQueuePayloadRouteDecision({})).toEqual({type: 'unknown'});
- });
-
- it('re-routes when the payload type changes', () => {
- const sendSnapshot = createMessageQueuePayloadRouteSnapshot({payloadType: 'send'});
- expect(selectMessageQueuePayloadRouteDecision(sendSnapshot)).toEqual({type: 'send'});
-
- const editSnapshot = transitionMessageQueuePayloadRouteSnapshot(sendSnapshot, {
- type: 'messageQueue.payloadChanged',
- input: {payloadType: 'edit'},
- });
-
- expect(selectMessageQueuePayloadRouteDecision(editSnapshot)).toEqual({type: 'edit'});
- });
-});
-
-describe('messageQueueSendExecutionMachine', () => {
- it('requests the network by default', () => {
- expect(resolveMessageQueueSendExecutionDecision({forceFailure: false})).toEqual({type: 'requestNetwork'});
- });
-
- it('routes developer-forced failures before network requests', () => {
- expect(resolveMessageQueueSendExecutionDecision({forceFailure: true})).toEqual({type: 'simulateFailure'});
- });
-
- it('re-routes when execution inputs change', () => {
- const forcedSnapshot = createMessageQueueSendExecutionSnapshot({forceFailure: true});
- expect(selectMessageQueueSendExecutionDecision(forcedSnapshot)).toEqual({type: 'simulateFailure'});
-
- const networkSnapshot = transitionMessageQueueSendExecutionSnapshot(forcedSnapshot, {
- type: 'messageQueue.sendExecutionChanged',
- input: {forceFailure: false},
- });
-
- expect(selectMessageQueueSendExecutionDecision(networkSnapshot)).toEqual({type: 'requestNetwork'});
- });
-});
-
-describe('messageQueueRequestOutcomeMachine', () => {
- it('routes request outcomes into queue actions', () => {
- expect(resolveMessageQueueRequestOutcomeDecision({status: 'success'})).toEqual({type: 'completeSuccess'});
- expect(resolveMessageQueueRequestOutcomeDecision({status: 'rateLimit'})).toEqual({type: 'retryRateLimit'});
- expect(resolveMessageQueueRequestOutcomeDecision({status: 'failure'})).toEqual({type: 'completeFailure'});
- });
-
- it('re-routes when the outcome status changes', () => {
- const failureSnapshot = createMessageQueueRequestOutcomeSnapshot({status: 'failure'});
- expect(selectMessageQueueRequestOutcomeDecision(failureSnapshot)).toEqual({type: 'completeFailure'});
-
- const successSnapshot = transitionMessageQueueRequestOutcomeSnapshot(failureSnapshot, {
- type: 'messageQueue.requestOutcomeChanged',
- input: {status: 'success'},
- });
-
- expect(selectMessageQueueRequestOutcomeDecision(successSnapshot)).toEqual({type: 'completeSuccess'});
- });
-});
-
-describe('messageLocalSendRateLimitMachine', () => {
- it('allows the first send and starts a local send window', () => {
- expect(resolveMessageLocalSendRateLimitDecision(localLimiter())).toEqual({
- type: 'allow',
- next: {
- windowStartedAt: 1_000,
- sentCount: 1,
- blockedUntil: null,
- },
- });
- });
-
- it('increments allowed sends within the active window', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 1_500,
- windowStartedAt: 1_000,
- sentCount: 2,
- }),
- ),
- ).toEqual({
- type: 'allow',
- next: {
- windowStartedAt: 1_000,
- sentCount: 3,
- blockedUntil: null,
- },
- });
- });
-
- it('blocks the first attempt above the max send count', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 1_800,
- windowStartedAt: 1_000,
- sentCount: 5,
- }),
- ),
- ).toEqual({
- type: 'block',
- retryAfterMs: 3_000,
- next: {
- windowStartedAt: 1_800,
- sentCount: 0,
- blockedUntil: 4_800,
- },
- });
- });
-
- it('keeps blocking attempts while a local block is active', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 2_500,
- windowStartedAt: 1_800,
- sentCount: 0,
- blockedUntil: 4_800,
- }),
- ),
- ).toEqual({
- type: 'block',
- retryAfterMs: 2_300,
- next: {
- windowStartedAt: 1_800,
- sentCount: 0,
- blockedUntil: 4_800,
- },
- });
- });
-
- it('allows sends after the local block timer expires', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 5_000,
- windowStartedAt: 1_800,
- sentCount: 0,
- blockedUntil: 4_800,
- }),
- ),
- ).toEqual({
- type: 'allow',
- next: {
- windowStartedAt: 5_000,
- sentCount: 1,
- blockedUntil: null,
- },
- });
- });
-
- it('allows sends from an empty limiter state', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 5_000,
- windowStartedAt: null,
- sentCount: 0,
- blockedUntil: null,
- }),
- ),
- ).toEqual({
- type: 'allow',
- next: {
- windowStartedAt: 5_000,
- sentCount: 1,
- blockedUntil: null,
- },
- });
- });
-
- it('resets the counter when the send window expires before the max is reached', () => {
- expect(
- resolveMessageLocalSendRateLimitDecision(
- localLimiter({
- now: 3_100,
- windowStartedAt: 1_000,
- sentCount: 4,
- }),
- ),
- ).toEqual({
- type: 'allow',
- next: {
- windowStartedAt: 3_100,
- sentCount: 1,
- blockedUntil: null,
- },
- });
- });
-
- it('re-routes when limiter inputs change', () => {
- const allowedSnapshot = createMessageLocalSendRateLimitSnapshot(localLimiter());
- expect(selectMessageLocalSendRateLimitDecision(allowedSnapshot)).toMatchObject({type: 'allow'});
-
- const blockedSnapshot = transitionMessageLocalSendRateLimitSnapshot(allowedSnapshot, {
- type: 'messageQueue.localSendAttempted',
- input: localLimiter({
- windowStartedAt: 1_000,
- sentCount: 5,
- }),
- });
-
- expect(selectMessageLocalSendRateLimitDecision(blockedSnapshot)).toMatchObject({
- type: 'block',
- retryAfterMs: 3_000,
- });
- });
-});
diff --git a/fluxer_app/src/features/messaging/state/SavedMessages.test.ts b/fluxer_app/src/features/messaging/state/SavedMessages.test.ts
deleted file mode 100644
index 5d7598122..000000000
--- a/fluxer_app/src/features/messaging/state/SavedMessages.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {SavedMessageEntry} from '@app/features/messaging/models/SavedMessageEntry';
-import SavedMessages from '@app/features/messaging/state/SavedMessages';
-import {SAVED_MESSAGES_PAGE_SIZE} from '@fluxer/constants/src/LimitConstants';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/messaging/models/MessagingMessage', () => ({
- Message: class {
- readonly id: string;
- constructor(data: {id: string}) {
- this.id = data.id;
- }
- },
-}));
-
-function entryPage(startId: number, count: number): Array<SavedMessageEntry> {
- return Array.from({length: count}, (_unused, index) =>
- SavedMessageEntry.fromResponse({
- id: String(startId - index),
- channel_id: '10',
- message_id: String(startId - index),
- status: 'missing_permissions',
- message: null,
- }),
- );
-}
-
-describe('SavedMessages pagination', () => {
- beforeEach(() => {
- SavedMessages.handleGatewayReady();
- });
-
- it('reports more pages while a full page comes back and tracks the oldest entry', () => {
- const requestId = SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(requestId, entryPage(1000, SAVED_MESSAGES_PAGE_SIZE), false);
- expect(SavedMessages.getHasMore()).toBe(true);
- expect(SavedMessages.getIsLoadingMore()).toBe(false);
- expect(SavedMessages.getCursor()).toBe(String(1000 - (SAVED_MESSAGES_PAGE_SIZE - 1)));
- });
-
- it('appends the next page instead of replacing the loaded one', () => {
- const first = SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(first, entryPage(1000, SAVED_MESSAGES_PAGE_SIZE), false);
- const second = SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(second, entryPage(900, 10), true);
- expect(SavedMessages.getMissingEntries()).toHaveLength(SAVED_MESSAGES_PAGE_SIZE + 10);
- expect(SavedMessages.getHasMore()).toBe(false);
- expect(SavedMessages.getCursor()).toBe('891');
- });
-
- it('ignores a page that a newer request has superseded', () => {
- const stale = SavedMessages.handleFetchPending();
- SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(stale, entryPage(1000, 5), false);
- expect(SavedMessages.fetched).toBe(false);
- expect(SavedMessages.getMissingEntries()).toHaveLength(0);
- });
-
- it('keeps the loaded pages when loading more fails', () => {
- const first = SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(first, entryPage(1000, SAVED_MESSAGES_PAGE_SIZE), false);
- const second = SavedMessages.handleFetchPending();
- SavedMessages.fetchError(second, true);
- expect(SavedMessages.getMissingEntries()).toHaveLength(SAVED_MESSAGES_PAGE_SIZE);
- expect(SavedMessages.getIsLoadingMore()).toBe(false);
- expect(SavedMessages.fetched).toBe(true);
- });
-
- it('clears everything when the first page fails', () => {
- const first = SavedMessages.handleFetchPending();
- SavedMessages.fetchSuccess(first, entryPage(1000, 5), false);
- const retry = SavedMessages.handleFetchPending();
- SavedMessages.fetchError(retry, false);
- expect(SavedMessages.getMissingEntries()).toHaveLength(0);
- expect(SavedMessages.fetched).toBe(false);
- expect(SavedMessages.getCursor()).toBeNull();
- expect(SavedMessages.getHasMore()).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/ChannelShared.test.ts b/fluxer_app/src/features/messaging/utils/ChannelShared.test.ts
deleted file mode 100644
index 0180c6c77..000000000
--- a/fluxer_app/src/features/messaging/utils/ChannelShared.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {filterViewableChannels, pickDefaultGuildChannelId} from '@app/features/messaging/utils/ChannelShared';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('filterViewableChannels', () => {
- it('excludes link channels from default navigation fallbacks', () => {
- const channels = [
- {id: 'link', type: ChannelTypes.GUILD_LINK, position: 0, guildId: 'guild'},
- {id: 'text', type: ChannelTypes.GUILD_TEXT, position: 1, guildId: 'guild'},
- {id: 'voice', type: ChannelTypes.GUILD_VOICE, position: 2, guildId: 'guild'},
- {id: 'category', type: ChannelTypes.GUILD_CATEGORY, position: 3, guildId: 'guild'},
- ];
- expect(filterViewableChannels(channels).map((channel) => channel.id)).toEqual(['text', 'voice']);
- });
-});
-
-describe('pickDefaultGuildChannelId', () => {
- const channels = [
- {id: 'category', type: ChannelTypes.GUILD_CATEGORY, position: 1, guildId: 'guild'},
- {id: 'link', type: ChannelTypes.GUILD_LINK, position: 2, guildId: 'guild'},
- {id: 'rules', type: ChannelTypes.GUILD_TEXT, position: 3, guildId: 'guild'},
- {id: 'general', type: ChannelTypes.GUILD_TEXT, position: 4, guildId: 'guild'},
- {id: 'voice', type: ChannelTypes.GUILD_VOICE, position: 5, guildId: 'guild'},
- ];
-
- it('returns null while the guild has no channels yet', () => {
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels: []})).toBeNull();
- });
-
- it('picks the first channel by position, skipping categories and links', () => {
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels})).toBe('rules');
- });
-
- it('keeps the remembered channel for the guild', () => {
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels, selectedChannelId: 'general'})).toBe('general');
- });
-
- it('falls back when the remembered channel is gone', () => {
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels, selectedChannelId: 'deleted'})).toBe('rules');
- });
-
- it('falls back when the remembered channel is not navigable', () => {
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels, selectedChannelId: 'link'})).toBe('rules');
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels, selectedChannelId: 'category'})).toBe('rules');
- });
-
- it('falls back when the remembered channel belongs to another guild', () => {
- const withForeign = [...channels, {id: 'other', type: ChannelTypes.GUILD_TEXT, position: 0, guildId: 'other'}];
- expect(pickDefaultGuildChannelId({guildId: 'guild', channels: withForeign, selectedChannelId: 'other'})).toBe(
- 'rules',
- );
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/ChannelTextareaFocusUtils.test.ts b/fluxer_app/src/features/messaging/utils/ChannelTextareaFocusUtils.test.ts
deleted file mode 100644
index 40040e1e4..000000000
--- a/fluxer_app/src/features/messaging/utils/ChannelTextareaFocusUtils.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {fileURLToPath} from 'node:url';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const dispatch = vi.fn();
-
-vi.mock('@app/features/platform/utils/ComponentBus', () => ({ComponentBus: {dispatch}}));
-
-const {focusChannelTextareaFromKeybind} = await import('@app/features/messaging/utils/ChannelTextareaFocusUtils');
-
-const CHANNEL_ID = '900000000000000001';
-
-beforeEach(() => {
- dispatch.mockReset();
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('focusChannelTextareaFromKeybind', () => {
- it('keeps keyboard mode on when the keybind focuses the composer', () => {
- focusChannelTextareaFromKeybind(CHANNEL_ID);
- expect(dispatch).toHaveBeenCalledWith('FOCUS_TEXTAREA', {channelId: CHANNEL_ID, enterKeyboardMode: true});
- });
-
- it('is what the Tab bound chat_focus_textarea action runs', () => {
- const handlers = readFileSync(
- fileURLToPath(new URL('../../app/keybindings/keybind_manager/handlers/defaultHandlers.ts', import.meta.url)),
- 'utf8',
- );
- const handler = handlers.match(/host\.register\('chat_focus_textarea'[\s\S]*?\n\t\}\);/)?.[0];
- expect(handler).toBeDefined();
- expect(handler).toMatch(/focusChannelTextareaFromKeybind\(channelId\)/);
- expect(handler).not.toMatch(/ComponentBus\.dispatch/);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/ClipboardFilePasteUtils.test.ts b/fluxer_app/src/features/messaging/utils/ClipboardFilePasteUtils.test.ts
deleted file mode 100644
index 5b1d55190..000000000
--- a/fluxer_app/src/features/messaging/utils/ClipboardFilePasteUtils.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createClipboardImageFile,
- getClipboardDataFiles,
- readClipboardImageFiles,
-} from '@app/features/messaging/utils/ClipboardFilePasteUtils';
-import {describe, expect, it} from 'vitest';
-
-function fileList(files: Array<File>): FileList {
- return Object.assign([...files], {
- item: (index: number) => files[index] ?? null,
- }) as unknown as FileList;
-}
-
-describe('ClipboardFilePasteUtils', () => {
- it('extracts usable files from paste event clipboard data', () => {
- const image = new File(['image'], 'photo.png', {type: 'image/png'});
- const emptyAnonymousFile = new File([], '', {type: ''});
- const clipboardData = {files: fileList([image, emptyAnonymousFile])} as DataTransfer;
-
- expect(getClipboardDataFiles(clipboardData)).toEqual([image]);
- });
-
- it('creates named files for async clipboard image blobs', () => {
- const file = createClipboardImageFile(new Blob(['image'], {type: 'image/webp'}), 1, 'image/webp');
-
- expect(file.name).toBe('clipboard-image-2.webp');
- expect(file.type).toBe('image/webp');
- expect(file.size).toBe(5);
- });
-
- it('reads image blobs from the async clipboard and ignores non-image data', async () => {
- const pngBlob = new Blob(['png'], {type: 'image/png'});
- const clipboard = {
- read: async () => [
- {
- types: ['text/plain'],
- getType: async () => new Blob(['text'], {type: 'text/plain'}),
- },
- {
- types: ['image/png', 'image/jpeg'],
- getType: async (type: string) => (type === 'image/png' ? pngBlob : new Blob([], {type})),
- },
- ],
- };
-
- const files = await readClipboardImageFiles(clipboard);
-
- expect(files).toHaveLength(1);
- expect(files[0]?.name).toBe('clipboard-image-1.png');
- expect(files[0]?.type).toBe('image/png');
- expect(files[0]?.size).toBe(3);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.test.ts b/fluxer_app/src/features/messaging/utils/CodeLinkUtils.test.ts
deleted file mode 100644
index bf33004c7..000000000
--- a/fluxer_app/src/features/messaging/utils/CodeLinkUtils.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {type CodeLinkConfig, findCodes, findSpoileredCodeMatches} from '@app/features/messaging/utils/CodeLinkUtils';
-import {describe, expect, it} from 'vitest';
-
-const INVITE_CONFIG: CodeLinkConfig = {
- path: 'invite',
- urlBases: ['https://fluxer.app/invite', 'https://fluxer.gg', 'https://fluxer.gg/invite'],
-};
-
-describe('CodeLinkUtils', () => {
- it('finds spoilered code-link matches with the same URL rules as code extraction', () => {
- const content = [
- 'https://fluxer.app/invite/visible',
- '||https://fluxer.app/invite/secret||',
- '||fluxer.gg/short||',
- '||https://fluxer.gg/invite/pathlink||',
- '||https://fluxer.app/invite/secret https://fluxer.gg/secret||',
- '||<https://fluxer.app/invite/suppressed>||',
- ].join(' ');
- expect(findCodes(content, INVITE_CONFIG)).toEqual(['visible', 'secret', 'short', 'pathlink']);
- expect(findSpoileredCodeMatches(content, INVITE_CONFIG).map((match) => match.code)).toEqual([
- 'secret',
- 'short',
- 'pathlink',
- 'secret',
- 'secret',
- ]);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/EmbeddableCodeLinkContent.test.ts b/fluxer_app/src/features/messaging/utils/EmbeddableCodeLinkContent.test.ts
deleted file mode 100644
index 7e1011751..000000000
--- a/fluxer_app/src/features/messaging/utils/EmbeddableCodeLinkContent.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import * as CodeLinkUtils from '@app/features/messaging/utils/CodeLinkUtils';
-import {extractEmbeddableCodeLinkContent} from '@app/features/messaging/utils/EmbeddableCodeLinkContent';
-import {describe, expect, it} from 'vitest';
-
-const TEST_LINK_CONFIG: CodeLinkUtils.CodeLinkConfig = {
- path: 'invite',
- urlBases: ['https://fluxer.app/invite'],
-};
-
-function findCodes(content: string): Array<string> {
- return CodeLinkUtils.findCodes(extractEmbeddableCodeLinkContent(content), TEST_LINK_CONFIG);
-}
-
-function findSpoileredCodes(content: string): Array<string> {
- return CodeLinkUtils.findSpoileredCodeMatches(extractEmbeddableCodeLinkContent(content), TEST_LINK_CONFIG).map(
- (match) => match.code,
- );
-}
-
-describe('extractEmbeddableCodeLinkContent', () => {
- it('excludes inline and block code links from code-link detection', () => {
- const content = [
- 'https://fluxer.app/invite/visible',
- '`https://fluxer.app/invite/inline-code`',
- '```',
- 'https://fluxer.app/invite/block-code',
- '```',
- ].join('\n');
-
- expect(findCodes(content)).toEqual(['visible']);
- });
-
- it('keeps masked link URLs and preserves suppressed angle-link behavior', () => {
- const content = [
- '[Join](https://fluxer.app/invite/masked-link)',
- '<https://fluxer.app/invite/suppressed-link>',
- ].join('\n');
-
- expect(findCodes(content)).toEqual(['masked-link']);
- });
-
- it('preserves suppressed angle-link behavior after parsing markdown code', () => {
- const content = ['<https://fluxer.app/invite/suppressed-link>', '`not a link`'].join('\n');
-
- expect(findCodes(content)).toEqual([]);
- });
-
- it('excludes code links from spoilered code-link detection', () => {
- const content = [
- '||https://fluxer.app/invite/visible-spoiler||',
- '||`https://fluxer.app/invite/inline-spoiler`||',
- '```',
- '||https://fluxer.app/invite/block-spoiler||',
- '```',
- ].join('\n');
-
- expect(findSpoileredCodes(content)).toEqual(['visible-spoiler']);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/EmbeddableImageTypes.test.ts b/fluxer_app/src/features/messaging/utils/EmbeddableImageTypes.test.ts
deleted file mode 100644
index 32c58ba13..000000000
--- a/fluxer_app/src/features/messaging/utils/EmbeddableImageTypes.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isEmbeddableImageFile} from '@app/features/messaging/utils/EmbeddableImageTypes';
-import {describe, expect, it} from 'vitest';
-
-describe('isEmbeddableImageFile', () => {
- it('embeds common raster image mime types', () => {
- expect(isEmbeddableImageFile({type: 'image/png', name: 'a.png'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/jpeg', name: 'a.jpg'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/gif', name: 'a.gif'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/webp', name: 'a.webp'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/avif', name: 'a.avif'})).toBe(true);
- });
- it('embeds SVG files (media proxy sanitizes them server-side)', () => {
- expect(isEmbeddableImageFile({type: 'image/svg+xml', name: 'logo.svg'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/svg', name: 'logo.svg'})).toBe(true);
- expect(isEmbeddableImageFile({type: '', name: 'logo.svg'})).toBe(true);
- expect(isEmbeddableImageFile({type: 'image/svg+xml; charset=utf-8', name: 'logo.svg'})).toBe(true);
- });
- it('rejects non-image content types with no embeddable extension', () => {
- expect(isEmbeddableImageFile({type: 'application/pdf', name: 'doc.pdf'})).toBe(false);
- expect(isEmbeddableImageFile({type: 'text/html', name: 'page.html'})).toBe(false);
- expect(isEmbeddableImageFile({type: 'application/octet-stream', name: 'blob.bin'})).toBe(false);
- });
- it('falls back to the filename extension when the mime is missing', () => {
- expect(isEmbeddableImageFile({type: '', name: 'photo.png'})).toBe(true);
- expect(isEmbeddableImageFile({type: '', name: 'photo.unknown'})).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/ImageCacheUtils.test.ts b/fluxer_app/src/features/messaging/utils/ImageCacheUtils.test.ts
deleted file mode 100644
index 590dcb85f..000000000
--- a/fluxer_app/src/features/messaging/utils/ImageCacheUtils.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import * as ImageCacheUtils from '@app/features/messaging/utils/ImageCacheUtils';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const AVATAR_URL = 'https://fluxerusercontent.com/avatars/1471779547901222947/93e5e9b9.webp?size=160';
-
-class FailingImage {
- static created: Array<FailingImage> = [];
- decoding = '';
- complete = false;
- naturalWidth = 0;
- naturalHeight = 0;
- onload: (() => void) | null = null;
- onerror: (() => void) | null = null;
- private source = '';
-
- constructor() {
- FailingImage.created.push(this);
- }
-
- get src(): string {
- return this.source;
- }
-
- set src(value: string) {
- this.source = value;
- this.onerror?.();
- }
-}
-
-function failImageLoad(): void {
- const onError = vi.fn();
- ImageCacheUtils.loadImage(AVATAR_URL, () => {}, onError);
- vi.runAllTimers();
- expect(onError).toHaveBeenCalledTimes(1);
-}
-
-describe('ImageCacheUtils failure cooldown', () => {
- beforeEach(() => {
- FailingImage.created = [];
- vi.useFakeTimers();
- vi.stubGlobal('window', globalThis);
- vi.stubGlobal('Image', FailingImage);
- ImageCacheUtils._clearForTests();
- });
-
- afterEach(() => {
- ImageCacheUtils._clearForTests();
- vi.unstubAllGlobals();
- vi.useRealTimers();
- });
-
- it('gives up on a failing image after two retries', () => {
- failImageLoad();
- expect(FailingImage.created).toHaveLength(3);
- expect(ImageCacheUtils.hasFailedImage(AVATAR_URL)).toBe(true);
- });
-
- it('rejects new loads of a failed image without requesting it again during the cooldown', () => {
- failImageLoad();
- const onError = vi.fn();
- ImageCacheUtils.loadImage(AVATAR_URL, () => {}, onError);
- vi.advanceTimersByTime(59_000);
- ImageCacheUtils.loadImage(AVATAR_URL, () => {}, onError);
- expect(onError).toHaveBeenCalledTimes(2);
- expect(FailingImage.created).toHaveLength(3);
- });
-
- it('requests the image again once the cooldown has passed', () => {
- failImageLoad();
- vi.advanceTimersByTime(60_000);
- expect(ImageCacheUtils.hasFailedImage(AVATAR_URL)).toBe(false);
- failImageLoad();
- expect(FailingImage.created).toHaveLength(6);
- });
-
- it('requests the image again straight away after it is forgotten', () => {
- failImageLoad();
- ImageCacheUtils.forgetImage(AVATAR_URL);
- expect(ImageCacheUtils.hasFailedImage(AVATAR_URL)).toBe(false);
- ImageCacheUtils.loadImage(AVATAR_URL, () => {});
- expect(FailingImage.created).toHaveLength(4);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/LocalAttachmentPreviewUtils.test.ts b/fluxer_app/src/features/messaging/utils/LocalAttachmentPreviewUtils.test.ts
deleted file mode 100644
index 9ee717972..000000000
--- a/fluxer_app/src/features/messaging/utils/LocalAttachmentPreviewUtils.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getScaledMediaDimensions,
- hasRenderableLocalPreview,
- LOCAL_MEDIA_PREVIEW_MAX_BYTES,
- shouldEagerlyPreviewLocalImage,
- shouldEagerlyPreviewLocalVideo,
-} from '@app/features/messaging/utils/LocalAttachmentPreviewUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('Local attachment preview utils', () => {
- it('allows eager image previews at or below the local preview size cap', () => {
- expect(
- shouldEagerlyPreviewLocalImage({
- type: 'image/png',
- name: 'image.png',
- size: LOCAL_MEDIA_PREVIEW_MAX_BYTES,
- }),
- ).toBe(true);
- });
- it('skips eager image and video previews above the local preview size cap', () => {
- const size = LOCAL_MEDIA_PREVIEW_MAX_BYTES + 1;
- expect(shouldEagerlyPreviewLocalImage({type: 'image/png', name: 'image.png', size})).toBe(false);
- expect(shouldEagerlyPreviewLocalVideo({type: 'video/mp4', name: 'video.mp4', size})).toBe(false);
- });
- it('scales video thumbnail dimensions to the configured maximum edge', () => {
- expect(getScaledMediaDimensions(3840, 2160, 640)).toEqual({width: 640, height: 360});
- expect(getScaledMediaDimensions(720, 1280, 640)).toEqual({width: 360, height: 640});
- });
- it('keeps small thumbnail dimensions unchanged', () => {
- expect(getScaledMediaDimensions(320, 240, 640)).toEqual({width: 320, height: 240});
- });
-});
-
-describe('hasRenderableLocalPreview', () => {
- const videoFile = {name: 'clip.mov', size: 1024, type: 'video/quicktime'};
- const imageFile = {name: 'photo.jpg', size: 1024, type: 'image/jpeg'};
- const otherFile = {name: 'notes.txt', size: 1024, type: 'text/plain'};
-
- it('treats a video with a generated thumbnail as renderable media', () => {
- expect(hasRenderableLocalPreview({file: videoFile, previewURL: 'blob:preview', thumbnailURL: 'blob:thumb'})).toBe(
- true,
- );
- });
-
- it('does not treat a video whose thumbnail probe failed as renderable media', () => {
- expect(hasRenderableLocalPreview({file: videoFile, previewURL: 'blob:preview', thumbnailURL: null})).toBe(false);
- });
-
- it('treats an image with a preview URL as renderable media', () => {
- expect(hasRenderableLocalPreview({file: imageFile, previewURL: 'blob:preview', thumbnailURL: null})).toBe(true);
- });
-
- it('does not treat an image without a preview URL as renderable media', () => {
- expect(hasRenderableLocalPreview({file: imageFile, previewURL: null, thumbnailURL: null})).toBe(false);
- });
-
- it('does not treat a non-media file as renderable media', () => {
- expect(hasRenderableLocalPreview({file: otherFile, previewURL: 'blob:preview', thumbnailURL: 'blob:thumb'})).toBe(
- false,
- );
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageEditContentUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageEditContentUtils.test.ts
deleted file mode 100644
index 69cbe8dd9..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageEditContentUtils.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildExistingAttachmentEditReferences,
- canSubmitEmptyMessageEdit,
- isAttachmentOnlyMessage,
-} from '@app/features/messaging/utils/MessageEditContentUtils';
-import AdvancedSettings from '@app/features/user/state/AdvancedSettings';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('Message edit content utils', () => {
- afterEach(() => {
- AdvancedSettings.setKeepAttachmentsOnEmptyMessageEdit(false);
- });
- it('keeps empty edits delete-oriented for messages without attachments', () => {
- expect(canSubmitEmptyMessageEdit({attachments: []})).toBe(false);
- });
- it('keeps empty edits delete-oriented for messages with attachments by default', () => {
- expect(canSubmitEmptyMessageEdit({attachments: [{id: '123'}]})).toBe(false);
- });
- it('allows empty edits when existing attachments can keep the message non-empty', () => {
- AdvancedSettings.setKeepAttachmentsOnEmptyMessageEdit(true);
- expect(canSubmitEmptyMessageEdit({attachments: [{id: '123'}]})).toBe(true);
- });
- it('still deletes an attachment-free message when the setting is on', () => {
- AdvancedSettings.setKeepAttachmentsOnEmptyMessageEdit(true);
- expect(canSubmitEmptyMessageEdit({attachments: []})).toBe(false);
- });
- it('recognises a message that never had text to clear', () => {
- expect(isAttachmentOnlyMessage({content: '', attachments: [{id: '123'}]})).toBe(true);
- });
- it('keeps a cleared caption away from the untouched-edit path', () => {
- expect(isAttachmentOnlyMessage({content: 'caption', attachments: [{id: '123'}]})).toBe(false);
- });
- it('keeps an attachment-free empty message away from the untouched-edit path', () => {
- expect(isAttachmentOnlyMessage({content: '', attachments: []})).toBe(false);
- });
- it('builds attachment references that retain existing attachments during an empty edit', () => {
- expect(buildExistingAttachmentEditReferences({attachments: [{id: '123'}, {id: '456'}]})).toEqual([
- {id: '123'},
- {id: '456'},
- ]);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageGroupingUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageGroupingUtils.test.ts
deleted file mode 100644
index 0bcaae103..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageGroupingUtils.test.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Channel} from '@app/features/channel/models/Channel';
-import type {Message} from '@app/features/messaging/models/MessagingMessage';
-import type {ChannelMessages} from '@app/features/messaging/state/ChannelMessages';
-import {ChannelStreamType, createChannelStream} from '@app/features/messaging/utils/MessageGroupingUtils';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/features/moderation/state/LocalUserSpamOverride', () => ({
- default: {isUserMarkedAsSpammer: () => false},
-}));
-vi.mock('@app/features/user/utils/DateFormatting', () => ({
- getFormattedFullDate: (date: Date) => date.toISOString().slice(0, 10),
-}));
-
-const AUTHOR = {id: 'author-1', flags: 0} as Message['author'];
-
-const ID = {
- first: '1519773906704011264',
- second: '1519773906708205568',
- third: '1519773906712399872',
- fourth: '1519773906716594176',
-} as const;
-
-function message(id: string, minute: number, blocked = false): Message {
- return {
- id,
- author: AUTHOR,
- blocked,
- ignored: false,
- timestamp: new Date(Date.UTC(2026, 7, 27, 12, minute)),
- type: 0,
- webhookId: null,
- mentions: [],
- mentionRoles: [],
- mentionEveryone: false,
- isUserMessage: () => true,
- hasFlag: () => false,
- } as unknown as Message;
-}
-
-function channelMessages(messages: Array<Message>): ChannelMessages {
- return {
- forEach: (callback: (message: Message) => boolean | undefined) => {
- for (const entry of messages) {
- if (callback(entry) === false) return;
- }
- },
- jumpDestinationId: null,
- jumpHighlight: false,
- jumpTicket: null,
- } as unknown as ChannelMessages;
-}
-
-const channel = {id: 'channel-1', isPrivate: () => false, getGuildId: () => 'guild-1'} as unknown as Channel;
-
-function buildStream(messages: Array<Message>, oldestUnreadMessageId: string | null) {
- return createChannelStream({
- channel,
- messages: channelMessages(messages),
- oldestUnreadMessageId,
- treatSpam: false,
- });
-}
-
-function countUnreadMarkers(stream: Array<ReturnType<typeof buildStream>[number]>): number {
- let count = 0;
- for (const item of stream) {
- if (item.type === ChannelStreamType.DIVIDER && item.unreadId != null) count++;
- if (item.type === ChannelStreamType.MESSAGE && item.showUnreadDividerBefore) count++;
- if (Array.isArray(item.content)) {
- count += countUnreadMarkers(item.content as Array<ReturnType<typeof buildStream>[number]>);
- }
- }
- return count;
-}
-
-function findUnreadDivider(stream: Array<ReturnType<typeof buildStream>[number]>) {
- for (const item of stream) {
- if (item.type === ChannelStreamType.DIVIDER && item.unreadId != null) return item;
- if (item.type === ChannelStreamType.MESSAGE && item.showUnreadDividerBefore) return item;
- if (item.type === ChannelStreamType.MESSAGE_GROUP_BLOCKED) {
- const nested = item.content as Array<ReturnType<typeof buildStream>[number]>;
- const divider = nested.find((entry) => entry.type === ChannelStreamType.DIVIDER && entry.unreadId != null);
- if (divider) return divider;
- }
- }
- return null;
-}
-
-describe('createChannelStream unread divider', () => {
- it('marks the unread boundary on a plain message', () => {
- const messages = [message(ID.first, 0), message(ID.second, 1), message(ID.third, 2)];
- expect(findUnreadDivider(buildStream(messages, ID.second))).not.toBeNull();
- });
-
- it('emits a divider inside the collapsed group when the boundary is a blocked message', () => {
- const messages = [message(ID.first, 0), message(ID.second, 1, true), message(ID.third, 2, true)];
- const stream = buildStream(messages, ID.second);
- const group = stream.find((item) => item.type === ChannelStreamType.MESSAGE_GROUP_BLOCKED);
- expect(group).toBeDefined();
- const nested = group!.content as Array<(typeof stream)[number]>;
- expect(nested.some((item) => item.type === ChannelStreamType.DIVIDER && item.unreadId === ID.second)).toBe(true);
- expect(group!.hasUnread).toBe(true);
- });
-
- it('emits a divider inside the collapsed group when the stored boundary is no longer loaded', () => {
- const messages = [message(ID.third, 0, true), message(ID.fourth, 1, true)];
- const stream = buildStream(messages, ID.first);
- const group = stream.find((item) => item.type === ChannelStreamType.MESSAGE_GROUP_BLOCKED);
- expect(group).toBeDefined();
- const nested = group!.content as Array<(typeof stream)[number]>;
- expect(nested.some((item) => item.type === ChannelStreamType.DIVIDER && item.unreadId === ID.third)).toBe(true);
- });
-
- it('never leaves the boundary unrepresented when there is an unread message id', () => {
- const messages = [message(ID.first, 0), message(ID.second, 1, true), message(ID.third, 2)];
- expect(findUnreadDivider(buildStream(messages, ID.second))).not.toBeNull();
- });
-
- it('merges the boundary into the date divider when it is the first message of a day', () => {
- const dayOne = message(ID.first, 0);
- const dayTwo = message(ID.third, 1);
- (dayTwo as {timestamp: Date}).timestamp = new Date(Date.UTC(2026, 7, 28, 9, 0));
- const stream = buildStream([dayOne, dayTwo], ID.third);
- const dateDivider = stream.find((item) => item.type === ChannelStreamType.DIVIDER && item.unreadId === ID.third);
- expect(dateDivider).toBeDefined();
- expect(countUnreadMarkers(stream)).toBe(1);
- });
-
- it('marks the boundary exactly once', () => {
- const messages = [message(ID.first, 0), message(ID.second, 1, true), message(ID.third, 2)];
- expect(countUnreadMarkers(buildStream(messages, ID.second))).toBe(1);
- expect(countUnreadMarkers(buildStream([message(ID.first, 0), message(ID.second, 1)], ID.second))).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageMemberLoadUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageMemberLoadUtils.test.ts
deleted file mode 100644
index f782eeac8..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageMemberLoadUtils.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- collectMessageModelGuildMemberUserIds,
- collectWireMessageGuildMemberUserIds,
-} from '@app/features/messaging/utils/MessageMemberLoadUtils';
-import type {MessageMention, Message as WireMessage} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-interface MessageModelFixture {
- readonly id: string;
- readonly guildId: string;
- readonly author: {readonly id: string};
- readonly webhookId?: string;
- readonly mentions: ReadonlyArray<{readonly id: string}>;
- readonly messageSnapshots?: ReadonlyArray<{
- mentions?: ReadonlyArray<string>;
- type: number;
- content: string;
- timestamp: string;
- }>;
- readonly referencedMessage?: MessageModelFixture | null;
-}
-
-function wireMention(id: string): MessageMention {
- return {
- id,
- username: id,
- discriminator: '0',
- global_name: null,
- avatar: null,
- avatar_color: null,
- flags: 0,
- };
-}
-
-function wireMessage(id: string, authorId: string, overrides: Partial<WireMessage> = {}): WireMessage {
- return {
- id,
- channel_id: 'channel-1',
- guild_id: 'guild-1',
- author: wireMention(authorId),
- type: 0,
- flags: 0,
- pinned: false,
- tts: false,
- mention_everyone: false,
- content: '',
- timestamp: '2026-01-01T00:00:00.000Z',
- mentions: [],
- mention_roles: [],
- ...overrides,
- } as WireMessage;
-}
-
-function modelMessage(id: string, authorId: string, overrides: Partial<MessageModelFixture> = {}): MessageModelFixture {
- return {
- id,
- guildId: 'guild-1',
- author: {id: authorId},
- mentions: [],
- ...overrides,
- };
-}
-
-describe('MessageMemberLoadUtils', () => {
- it('collects wire message authors, mentions, snapshot mentions, and referenced-message users', () => {
- const userIds = collectWireMessageGuildMemberUserIds(
- [
- wireMessage('message-1', 'author-1', {
- mentions: [wireMention('mention-1'), wireMention('current-user')],
- message_snapshots: [{mentions: ['snapshot-mention'], type: 0, content: '', timestamp: ''}],
- referenced_message: wireMessage('message-2', 'referenced-author', {
- mentions: [wireMention('referenced-mention')],
- }),
- }),
- wireMessage('message-3', 'webhook-author', {
- webhook_id: 'webhook-1',
- mentions: [wireMention('webhook-mention')],
- }),
- wireMessage('message-4', 'current-user'),
- ],
- 'current-user',
- );
-
- expect(userIds).toEqual([
- 'author-1',
- 'mention-1',
- 'current-user',
- 'snapshot-mention',
- 'referenced-author',
- 'referenced-mention',
- 'webhook-mention',
- ]);
- });
-
- it('collects cached message model authors, mentions, snapshot mentions, and referenced-message users', () => {
- const userIds = collectMessageModelGuildMemberUserIds(
- [
- modelMessage('message-1', 'author-1', {
- mentions: [{id: 'mention-1'}, {id: 'author-1'}],
- messageSnapshots: [{mentions: ['snapshot-mention'], type: 0, content: '', timestamp: ''}],
- referencedMessage: modelMessage('message-2', 'referenced-author', {
- mentions: [{id: 'referenced-mention'}],
- }),
- }),
- modelMessage('message-3', 'webhook-author', {
- webhookId: 'webhook-1',
- mentions: [{id: 'webhook-mention'}],
- }),
- modelMessage('message-4', 'current-user'),
- ],
- 'current-user',
- );
-
- expect(userIds).toEqual([
- 'author-1',
- 'mention-1',
- 'snapshot-mention',
- 'referenced-author',
- 'referenced-mention',
- 'webhook-mention',
- ]);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageNodeSelectors.test.ts b/fluxer_app/src/features/messaging/utils/MessageNodeSelectors.test.ts
deleted file mode 100644
index dc41d36ac..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageNodeSelectors.test.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- CHANNEL_MESSAGE_ID_PREFIX,
- findMessageElement,
- getMessageSelector,
-} from '@app/features/messaging/utils/MessageNodeSelectors';
-import {afterEach, describe, expect, it} from 'vitest';
-
-const CHANNEL_ID = '900000000000000001';
-
-function messageRow(messageId: string, idPrefix: string): HTMLElement {
- const row = document.createElement('div');
- row.id = `${idPrefix}-${CHANNEL_ID}-${messageId}`;
- row.dataset.messageId = messageId;
- row.dataset.channelId = CHANNEL_ID;
- return row;
-}
-
-function viewport(): HTMLElement {
- const element = document.createElement('div');
- document.body.append(element);
- return element;
-}
-
-describe('MessageNodeSelectors', () => {
- afterEach(() => {
- document.body.replaceChildren();
- });
-
- it('resolves a normal stream row through the id fast path', () => {
- const scroller = viewport();
- const row = messageRow('1', CHANNEL_MESSAGE_ID_PREFIX);
- scroller.append(row);
-
- expect(findMessageElement(document, scroller, CHANNEL_ID, '1')).toBe(row);
- });
-
- it('resolves a revealed blocked group row that carries a different id prefix', () => {
- const scroller = viewport();
- scroller.append(messageRow('1', CHANNEL_MESSAGE_ID_PREFIX));
- const blockedRow = messageRow('2', 'blocked-messages');
- scroller.append(blockedRow);
-
- expect(document.getElementById(`${CHANNEL_MESSAGE_ID_PREFIX}-${CHANNEL_ID}-2`)).toBeNull();
- expect(findMessageElement(document, scroller, CHANNEL_ID, '2')).toBe(blockedRow);
- });
-
- it('resolves a revealed spammer group row', () => {
- const scroller = viewport();
- const spammerRow = messageRow('3', 'spammer-messages');
- scroller.append(spammerRow);
-
- expect(findMessageElement(document, scroller, CHANNEL_ID, '3')).toBe(spammerRow);
- });
-
- it('falls back to the viewport-scoped lookup and ignores rows outside it', () => {
- const scroller = viewport();
- const searchPanel = viewport();
- searchPanel.append(messageRow('4', 'blocked-messages'));
-
- expect(document.getElementById(`${CHANNEL_MESSAGE_ID_PREFIX}-${CHANNEL_ID}-4`)).toBeNull();
- expect(findMessageElement(document, scroller, CHANNEL_ID, '4')).toBeNull();
- });
-
- it('resolves a row through the document-wide id lookup even when it sits outside the viewport', () => {
- const scroller = viewport();
- const popout = viewport();
- const inPopout = messageRow('8', CHANNEL_MESSAGE_ID_PREFIX);
- popout.append(inPopout);
-
- expect(findMessageElement(document, scroller, CHANNEL_ID, '8')).toBe(inPopout);
- });
-
- it('prefers the row inside the viewport when neither row carries the canonical id', () => {
- const scroller = viewport();
- const inStream = messageRow('5', 'blocked-messages');
- scroller.append(inStream);
- const searchPanel = viewport();
- const inSearch = messageRow('5', 'search-messages');
- searchPanel.append(inSearch);
-
- expect(document.getElementById(`${CHANNEL_MESSAGE_ID_PREFIX}-${CHANNEL_ID}-5`)).toBeNull();
- expect(findMessageElement(document, scroller, CHANNEL_ID, '5')).toBe(inStream);
- });
-
- it('does not resolve a row belonging to another channel', () => {
- const scroller = viewport();
- const foreign = document.createElement('div');
- foreign.dataset.messageId = '6';
- foreign.dataset.channelId = '900000000000000002';
- scroller.append(foreign);
-
- expect(findMessageElement(document, scroller, CHANNEL_ID, '6')).toBeNull();
- });
-
- it('requires both data attributes so message group row wrappers are not candidates', () => {
- const scroller = viewport();
- const groupWrapper = document.createElement('div');
- groupWrapper.dataset.messageId = '7';
- const row = messageRow('7', CHANNEL_MESSAGE_ID_PREFIX);
- groupWrapper.append(row);
- scroller.append(groupWrapper);
-
- const matches = scroller.querySelectorAll<HTMLElement>(getMessageSelector(CHANNEL_ID));
- expect(Array.from(matches)).toEqual([row]);
- });
-
- it('leaves snowflake ids untouched instead of emitting identifier escapes', () => {
- expect(getMessageSelector(CHANNEL_ID, '900000000000000009')).toBe(
- '[data-channel-id="900000000000000001"][data-message-id="900000000000000009"]',
- );
- });
-
- it('escapes quotes and backslashes so an id can never break out of the attribute selector', () => {
- expect(getMessageSelector(undefined, 'a"]b')).toBe('[data-channel-id][data-message-id="a\\"]b"]');
- expect(getMessageSelector(undefined, 'a\\b')).toBe('[data-channel-id][data-message-id="a\\\\b"]');
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageRequestUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageRequestUtils.test.ts
deleted file mode 100644
index a383aee29..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageRequestUtils.test.ts
+++ /dev/null
@@ -1,204 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildMessageCreateRequest,
- buildMessageEditRequest,
- type ComposerSubmitSignals,
- canSubmitComposerContent,
- canSubmitMessage,
- getComposerMessageContent,
- hasVisibleMessageContent,
- normalizeMessageContent,
-} from '@app/features/messaging/utils/MessageRequestUtils';
-import {MessageFlags} from '@fluxer/constants/src/ChannelConstants';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const chatInputSettings = vi.hoisted(() => ({convertEmoticons: false}));
-
-vi.mock('@app/features/messaging/state/ChatInputSettings', () => ({default: chatInputSettings}));
-vi.mock('@app/features/user/state/UserSettings', () => ({default: {getSanitizeUrls: () => false}}));
-vi.mock('@app/features/messaging/utils/EmoticonConversionUtils', () => ({
- convertEmoticonsToEmoji: (content: string) => content.replaceAll(':)', '\u{1F642}'),
-}));
-
-afterEach(() => {
- chatInputSettings.convertEmoticons = false;
-});
-
-describe('normalizeMessageContent', () => {
- it('still strips @silent followed by a space and suppresses notifications', () => {
- expect(normalizeMessageContent('@silent hello')).toEqual({
- content: 'hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it('strips @silent on its own and suppresses notifications', () => {
- expect(normalizeMessageContent('@silent')).toEqual({content: '', flags: MessageFlags.SUPPRESS_NOTIFICATIONS});
- });
-
- it.each([
- ['a newline', '\n'],
- ['a no-break space', '\u00a0'],
- ['a tab', '\t'],
- ])('strips @silent followed by %s and suppresses notifications', (_name, whitespace) => {
- expect(normalizeMessageContent(`@silent${whitespace}hello`)).toEqual({
- content: 'hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it('strips leading whitespace before @silent', () => {
- expect(normalizeMessageContent(' @silent hello')).toEqual({
- content: 'hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it('still strips only one whitespace character and one @silent', () => {
- expect(normalizeMessageContent('@silent hello')).toEqual({
- content: ' hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- expect(normalizeMessageContent('@silent @silent hello')).toEqual({
- content: '@silent hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it('still drops invisible content left after @silent', () => {
- expect(normalizeMessageContent('@silent \u200b')).toEqual({
- content: '',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it.each([
- '@silently hello',
- '@Silent hello',
- 'hello @silent',
- 'hello',
- ])('still leaves %j as it is with no flags', (content) => {
- expect(normalizeMessageContent(content)).toEqual({content, flags: 0});
- });
-
- it('still converts emoticons after stripping @silent', () => {
- chatInputSettings.convertEmoticons = true;
- expect(normalizeMessageContent('@silent :)')).toEqual({
- content: '\u{1F642}',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-});
-
-describe('canSubmitMessage', () => {
- it('rejects a message that is only @silent', () => {
- expect(canSubmitMessage('@silent', false)).toBe(false);
- expect(canSubmitMessage('@silent\n', false)).toBe(false);
- expect(canSubmitMessage('@silent \u200b', false)).toBe(false);
- });
-
- it('rejects blank content with nothing attached', () => {
- expect(canSubmitMessage(' ', false)).toBe(false);
- });
-
- it('accepts @silent with attachments, a sticker or a favourite meme', () => {
- expect(canSubmitMessage('@silent', true)).toBe(true);
- });
-
- it('accepts visible content with or without @silent', () => {
- expect(canSubmitMessage('@silent hi', false)).toBe(true);
- expect(canSubmitMessage('hello', false)).toBe(true);
- });
-});
-
-function composerSignals(overrides: Partial<ComposerSubmitSignals> = {}): ComposerSubmitSignals {
- return {
- inputDisabled: false,
- isSubmissionBlockedBySlowmode: false,
- isOverCharacterLimit: false,
- hasMessageContent: false,
- hasAttachments: false,
- hasPendingSticker: false,
- isEditingMessageOnMobile: false,
- ...overrides,
- };
-}
-
-describe('canSubmitComposerContent', () => {
- it('refuses an empty composer that is not editing anything', () => {
- expect(canSubmitComposerContent(composerSignals())).toBe(false);
- });
-
- it('accepts text, attachments and stickers on their own', () => {
- expect(canSubmitComposerContent(composerSignals({hasMessageContent: true}))).toBe(true);
- expect(canSubmitComposerContent(composerSignals({hasAttachments: true}))).toBe(true);
- expect(canSubmitComposerContent(composerSignals({hasPendingSticker: true}))).toBe(true);
- });
-
- it('accepts an emptied edit on mobile so that it can ask to delete the message', () => {
- expect(canSubmitComposerContent(composerSignals({isEditingMessageOnMobile: true}))).toBe(true);
- });
-
- it('refuses a disabled, slowed or over-long composer even while editing on mobile', () => {
- expect(canSubmitComposerContent(composerSignals({isEditingMessageOnMobile: true, inputDisabled: true}))).toBe(
- false,
- );
- expect(
- canSubmitComposerContent(composerSignals({isEditingMessageOnMobile: true, isSubmissionBlockedBySlowmode: true})),
- ).toBe(false);
- expect(
- canSubmitComposerContent(composerSignals({isEditingMessageOnMobile: true, isOverCharacterLimit: true})),
- ).toBe(false);
- });
-});
-
-describe('getComposerMessageContent', () => {
- it('measures the content that will be sent when not editing on mobile', () => {
- expect(getComposerMessageContent('@silent', false)).toBe('');
- expect(getComposerMessageContent('@silent hello', false)).toBe('hello');
- expect(hasVisibleMessageContent(getComposerMessageContent('@silent', false))).toBe(false);
- });
-
- it('strips @silent without running the outgoing conversions', () => {
- chatInputSettings.convertEmoticons = true;
- expect(getComposerMessageContent('@silent :)', false)).toBe(':)');
- });
-
- it('keeps @silent as text when editing on mobile', () => {
- expect(getComposerMessageContent('@silent', true)).toBe('@silent');
- expect(getComposerMessageContent('@silent hello', true)).toBe('@silent hello');
- expect(hasVisibleMessageContent(getComposerMessageContent('@silent', true))).toBe(true);
- });
-});
-
-describe('buildMessageCreateRequest', () => {
- it('still omits empty content but keeps the silent flag for an attachment-only message', () => {
- const attachment = {id: '1', filename: 'a.png', title: 'a.png'};
- expect(
- buildMessageCreateRequest({
- content: '',
- nonce: 'n',
- attachments: [attachment],
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- }),
- ).toEqual({nonce: 'n', attachments: [attachment], flags: MessageFlags.SUPPRESS_NOTIFICATIONS});
- });
-
- it('still sends a /tts message after @silent as silent text-to-speech', () => {
- const {content, flags} = normalizeMessageContent('@silent hi');
- expect(buildMessageCreateRequest({content, nonce: 'n', flags, tts: true})).toEqual({
- content: 'hi',
- nonce: 'n',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- tts: true,
- });
- });
-});
-
-describe('buildMessageEditRequest', () => {
- it('still sends @silent verbatim in an edit with no flags', () => {
- expect(buildMessageEditRequest({content: '@silent hello'})).toEqual({content: '@silent hello'});
- expect(buildMessageEditRequest({content: '@silent'})).toEqual({content: '@silent'});
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageSelectionCopyUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageSelectionCopyUtils.test.ts
deleted file mode 100644
index 604b2b3b7..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageSelectionCopyUtils.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {buildMessageSelectionCopyTextForRange} from '@app/features/messaging/utils/MessageSelectionCopyUtils';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('Message selection copy utils', () => {
- afterEach(() => {
- document.body.replaceChildren();
- });
- it('uses markdown table copy text when a rendered table is selected cell-by-cell', () => {
- const tableCopyText = ['| Name | Status |', '| --- | --- |', '| Alpha | Ready |'].join('\n');
- document.body.innerHTML = `
- <div data-message-selection-root="true">
- <div data-message-id="message-1" data-is-group-start="true">
- <div data-message-copy-block="true" data-message-copy-table="true"></div>
- </div>
- </div>
- `;
- const copyBlock = document.querySelector<HTMLElement>('[data-message-copy-block="true"]');
- if (!copyBlock) {
- throw new Error('Missing copy block fixture');
- }
- copyBlock.dataset.messageCopyText = tableCopyText;
- copyBlock.innerHTML = `
- <table>
- <thead>
- <tr><th>Name</th><th>Status</th></tr>
- </thead>
- <tbody>
- <tr><td>Alpha</td><td>Ready</td></tr>
- </tbody>
- </table>
- `;
- const root = document.querySelector<HTMLElement>('[data-message-selection-root="true"]');
- const firstCell = copyBlock.querySelector<HTMLElement>('th');
- const lastCell = Array.from(copyBlock.querySelectorAll<HTMLElement>('td')).at(-1);
- if (!root || !firstCell?.firstChild || !lastCell?.firstChild) {
- throw new Error('Missing table selection fixture');
- }
- const range = document.createRange();
- range.setStart(firstCell.firstChild, 0);
- range.setEnd(lastCell.firstChild, 'Ready'.length);
- expect(buildMessageSelectionCopyTextForRange({rootElement: root, selectionRange: range})).toBe(tableCopyText);
- });
- it('does not duplicate a block message header when a bot badge is selected with the body', () => {
- const messageContent = 'App Canary Deployed\n\nVersion: 2026.519.3\nImage: 2026.519.3';
- document.body.innerHTML = [
- '<div data-message-selection-root="true">',
- '<div data-message-id="message-1" data-is-group-start="true">',
- '<h3>',
- '<span><span data-user-id="user-1">Canary Releases</span><span>Bot</span></span>',
- '<span><time><span aria-hidden="true"> — </span>Today at 4:10</time></span>',
- '</h3>',
- '<div data-message-copy-block="true"><h2><span>App Canary Deployed</span></h2><span>Version: </span>',
- '<code>2026.519.3</code><span>\nImage: </span><code>2026.519.3</code></div>',
- '</div>',
- '</div>',
- ].join('');
- const copyBlock = document.querySelector<HTMLElement>('[data-message-copy-block="true"]');
- if (!copyBlock) {
- throw new Error('Missing message copy block fixture');
- }
- copyBlock.dataset.messageCopyText = messageContent;
- const root = document.querySelector<HTMLElement>('[data-message-selection-root="true"]');
- const username = document.querySelector<HTMLElement>('[data-user-id="user-1"]')?.firstChild;
- const imageVersion = Array.from(document.querySelectorAll<HTMLElement>('code')).at(-1)?.firstChild;
- if (!root || !username || !imageVersion) {
- throw new Error('Missing block message selection fixture');
- }
- const range = document.createRange();
- range.setStart(username, 0);
- range.setEnd(imageVersion, '2026.519.3'.length);
- expect(buildMessageSelectionCopyTextForRange({rootElement: root, selectionRange: range})).toBe(
- ['Canary Releases — Today at 4:10', messageContent].join('\n'),
- );
- });
- it('does not duplicate a compact message prefix when a bot badge is selected with the body', () => {
- document.body.innerHTML = [
- '<div data-message-selection-root="true">',
- '<div data-message-id="message-1" data-is-group-start="true">',
- '<span><time><span>[</span>4:10<span>]</span></time></span>',
- '<span data-compact-message-prefix="true"><span> </span><span>Bot</span>',
- '<span data-user-id="user-1">Canary Releases</span><span>: </span></span>',
- '<span>Hello from canary.</span>',
- '</div>',
- '</div>',
- ].join('');
- const root = document.querySelector<HTMLElement>('[data-message-selection-root="true"]');
- const timestamp = document.querySelector<HTMLElement>('time')?.firstChild;
- const body = document.querySelector<HTMLElement>('[data-compact-message-prefix="true"] + span')?.firstChild;
- if (!root || !timestamp || !body) {
- throw new Error('Missing compact message selection fixture');
- }
- const range = document.createRange();
- range.setStart(timestamp, 0);
- range.setEnd(body, 'Hello from canary.'.length);
- expect(buildMessageSelectionCopyTextForRange({rootElement: root, selectionRange: range})).toBe(
- '[4:10] Canary Releases: Hello from canary.',
- );
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/MessageSubmitUtils.test.ts b/fluxer_app/src/features/messaging/utils/MessageSubmitUtils.test.ts
deleted file mode 100644
index 4d9de4931..000000000
--- a/fluxer_app/src/features/messaging/utils/MessageSubmitUtils.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Message} from '@app/features/messaging/models/MessagingMessage';
-import {claimMessageAttachments, createOptimisticMessage} from '@app/features/messaging/utils/MessageSubmitUtils';
-import type {User} from '@app/features/user/models/User';
-import {MessageFlags, MessageStates, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {MessageAttachment} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {describe, expect, it, vi} from 'vitest';
-
-const claimAttachmentsForMessage = vi.hoisted(() => vi.fn(() => []));
-
-vi.mock('@app/features/messaging/models/MessagingMessage', () => ({
- Message: class {
- constructor(data: object) {
- Object.assign(this, data);
- }
- },
-}));
-vi.mock('@app/features/messaging/upload/CloudUpload', () => ({CloudUpload: {claimAttachmentsForMessage}}));
-vi.mock('@app/features/messaging/state/ChatInputSettings', () => ({default: {convertEmoticons: false}}));
-vi.mock('@app/features/user/state/UserSettings', () => ({default: {getSanitizeUrls: () => false}}));
-vi.mock('@app/features/messaging/utils/EmoticonConversionUtils', () => ({
- convertEmoticonsToEmoji: (content: string) => content,
-}));
-
-const currentUser = {toJSON: () => ({id: 'me'})} as unknown as User;
-const referencedMessage = {id: 'ref', author: {toJSON: () => ({id: 'other'})}} as unknown as Message;
-
-describe('createOptimisticMessage', () => {
- it('still strips @silent followed by a space and marks the message silent', () => {
- expect(
- createOptimisticMessage({content: '@silent hello', channelId: 'c', nonce: 'n', currentUser}, []),
- ).toMatchObject({
- content: 'hello',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- type: MessageTypes.DEFAULT,
- state: MessageStates.SENDING,
- });
- });
-
- it('strips @silent before a line break and marks the message silent', () => {
- expect(
- createOptimisticMessage({content: '@silent\nhello', channelId: 'c', nonce: 'n', currentUser}, []),
- ).toMatchObject({content: 'hello', flags: MessageFlags.SUPPRESS_NOTIFICATIONS});
- });
-
- it('marks an attachment captioned only by @silent as silent with no content', () => {
- const attachment = {id: 'upload'} as MessageAttachment;
- expect(
- createOptimisticMessage({content: '@silent', channelId: 'c', nonce: 'n', currentUser}, [attachment]),
- ).toMatchObject({content: '', flags: MessageFlags.SUPPRESS_NOTIFICATIONS, attachments: [attachment]});
- });
-
- it('still marks a silent reply', () => {
- expect(
- createOptimisticMessage(
- {content: '@silent hi', channelId: 'c', nonce: 'n', currentUser, referencedMessage, replyMentioning: true},
- [],
- ),
- ).toMatchObject({
- content: 'hi',
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- type: MessageTypes.REPLY,
- message_reference: {channel_id: 'c', message_id: 'ref', type: 0},
- _allowedMentions: {replied_user: true},
- });
- });
-
- it('still leaves @silent later in the message as text', () => {
- expect(
- createOptimisticMessage({content: 'hello @silent', channelId: 'c', nonce: 'n', currentUser}, []),
- ).toMatchObject({content: 'hello @silent', flags: 0});
- });
-});
-
-describe('claimMessageAttachments', () => {
- it('claims attachments captioned only by @silent as silent with no content', () => {
- claimMessageAttachments('c', 'n', '@silent');
- expect(claimAttachmentsForMessage).toHaveBeenLastCalledWith('c', 'n', undefined, {
- content: '',
- messageReference: undefined,
- allowedMentions: {replied_user: true},
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-
- it('claims attachments with the caption after @silent and a line break', () => {
- claimMessageAttachments('c', 'n', '@silent\ncaption');
- expect(claimAttachmentsForMessage).toHaveBeenLastCalledWith('c', 'n', undefined, {
- content: 'caption',
- messageReference: undefined,
- allowedMentions: {replied_user: true},
- flags: MessageFlags.SUPPRESS_NOTIFICATIONS,
- });
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/ReactionTooltipCatalog.test.ts b/fluxer_app/src/features/messaging/utils/ReactionTooltipCatalog.test.ts
deleted file mode 100644
index a2b71ae1e..000000000
--- a/fluxer_app/src/features/messaging/utils/ReactionTooltipCatalog.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync} from 'node:fs';
-import {dirname, join} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {i18n} from '@lingui/core';
-import {describe, expect, it} from 'vitest';
-
-const REACTED_BY_ID =
- '{reactorCount, plural, one {{emojiName} reacted by {reactors}} other {{emojiName} reacted by {reactors}}}';
-
-const localesDir = join(dirname(fileURLToPath(import.meta.url)), '../../i18n/locales');
-
-function readTranslation(locale: string): string {
- const source = readFileSync(join(localesDir, locale, 'messages.po'), 'utf8');
- const escaped = REACTED_BY_ID.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- const match = source.match(new RegExp(`^msgid "${escaped}"\\nmsgstr ((?:"(?:[^"\\\\]|\\\\.)*"\\n?)+)`, 'm'));
- if (!match?.[1]) {
- throw new Error(`missing reaction tooltip translation for ${locale}`);
- }
- return match[1]
- .split('\n')
- .map((line) => line.trim())
- .filter((line) => line.startsWith('"'))
- .map((line) => JSON.parse(line) as string)
- .join('');
-}
-
-function render(locale: string, reactors: string, reactorCount: number): string {
- i18n.load(locale, {[REACTED_BY_ID]: readTranslation(locale)});
- i18n.activate(locale);
- return i18n._({id: REACTED_BY_ID, message: REACTED_BY_ID}, {emojiName: ':100:', reactors, reactorCount});
-}
-
-const locales = readdirSync(localesDir, {withFileTypes: true})
- .filter((entry) => entry.isDirectory())
- .map((entry) => entry.name)
- .sort();
-
-describe('reaction tooltip catalog', () => {
- it('ships a translation for every locale', () => {
- expect(locales.length).toBeGreaterThan(30);
- for (const locale of locales) {
- expect(readTranslation(locale).length).toBeGreaterThan(0);
- }
- });
-
- it('keeps both placeholders in every plural branch of every locale', () => {
- for (const locale of locales) {
- for (const count of [1, 5]) {
- const output = render(locale, 'alex', count);
- expect(output, `${locale} @ ${count}`).toContain(':100:');
- expect(output, `${locale} @ ${count}`).toContain('alex');
- expect(output, `${locale} @ ${count}`).not.toContain('{');
- }
- }
- });
-
- it('agrees with the reactor count in French, the locale the bug was reported in', () => {
- expect(render('fr', 'test', 1)).toBe('test a réagi avec :100:');
- expect(render('fr', 'test, alex et 3 autres', 5)).toBe('test, alex et 3 autres ont réagi avec :100:');
- });
-
- it('never makes the emoji the subject of an active verb in the reported locales', () => {
- expect(render('es-ES', 'test', 1)).toBe('test ha reaccionado con :100:');
- expect(render('es-ES', 'test y alex', 2)).toBe('test y alex han reaccionado con :100:');
- expect(render('nl', 'test', 1)).toBe('test reageerde met :100:');
- expect(render('nl', 'test en alex', 2)).toBe('test en alex reageerden met :100:');
- expect(render('pt-BR', 'test', 1)).toBe('test reagiu com :100:');
- expect(render('de', 'test', 1)).toBe('test hat mit :100: reagiert');
- });
-
- it('leaves English as the emoji-first phrasing the design intends', () => {
- expect(render('en-US', 'test', 1)).toBe(':100: reacted by test');
- expect(render('en-GB', 'test and alex', 2)).toBe(':100: reacted by test and alex');
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/RetryAfterUtils.test.ts b/fluxer_app/src/features/messaging/utils/RetryAfterUtils.test.ts
deleted file mode 100644
index f3cdb26ea..000000000
--- a/fluxer_app/src/features/messaging/utils/RetryAfterUtils.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolveRetryAfterMs} from '@app/features/messaging/utils/RetryAfterUtils';
-import {HttpError} from '@app/features/platform/types/EndpointError';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {describe, expect, it} from 'vitest';
-
-function slowmodeRejection(body: unknown, responseHeaders: Record<string, string>): HttpError {
- return new HttpError({
- method: 'POST',
- path: '/channels/1234567890123456789/messages',
- status: 400,
- body,
- responseHeaders,
- });
-}
-
-describe('resolveRetryAfterMs', () => {
- it('uses the decimal seconds from the body instead of the Retry-After header', () => {
- const error = slowmodeRejection(
- {code: APIErrorCodes.SLOWMODE_RATE_LIMITED, retry_after: 4.44},
- {'retry-after': '5'},
- );
- expect(resolveRetryAfterMs(error)).toBe(4440);
- });
-
- it('never multiplies a millisecond Retry-After header into a longer window than the body', () => {
- const error = slowmodeRejection(
- {code: APIErrorCodes.SLOWMODE_RATE_LIMITED, retry_after: 4.7},
- {'retry-after': '4700'},
- );
- expect(resolveRetryAfterMs(error)).toBe(4700);
- });
-
- it('prefers a nested retry window over every other source', () => {
- const error = slowmodeRejection(
- {code: APIErrorCodes.SLOWMODE_RATE_LIMITED, retry_after: 30, details: {retry: {after_seconds: 2.5}}},
- {'retry-after': '30'},
- );
- expect(resolveRetryAfterMs(error)).toBe(2500);
- });
-
- it('falls back to the Retry-After header when the body carries no window', () => {
- const error = slowmodeRejection({code: APIErrorCodes.SLOWMODE_RATE_LIMITED}, {'retry-after': '3'});
- expect(resolveRetryAfterMs(error)).toBe(3000);
- });
-
- it('falls back to the reset-after header when nothing else is present', () => {
- const error = slowmodeRejection({code: APIErrorCodes.RATE_LIMITED}, {'x-ratelimit-reset-after': '1.25'});
- expect(resolveRetryAfterMs(error)).toBe(1250);
- });
-
- it('reads an HTTP date Retry-After header as a remaining duration', () => {
- const deadline = new Date(Date.now() + 4000).toUTCString();
- const error = slowmodeRejection({code: APIErrorCodes.SLOWMODE_RATE_LIMITED}, {'retry-after': deadline});
- const retryAfterMs = resolveRetryAfterMs(error);
- expect(retryAfterMs).not.toBeNull();
- expect(retryAfterMs!).toBeGreaterThan(0);
- expect(retryAfterMs!).toBeLessThanOrEqual(4000);
- });
-
- it('returns null when no retry window is advertised', () => {
- expect(resolveRetryAfterMs(slowmodeRejection({code: APIErrorCodes.SLOWMODE_RATE_LIMITED}, {}))).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/SilentMessagePrefix.test.ts b/fluxer_app/src/features/messaging/utils/SilentMessagePrefix.test.ts
deleted file mode 100644
index 13acf989c..000000000
--- a/fluxer_app/src/features/messaging/utils/SilentMessagePrefix.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {parseSilentMessagePrefix} from '@app/features/messaging/utils/SilentMessagePrefix';
-import {describe, expect, it} from 'vitest';
-
-describe('parseSilentMessagePrefix', () => {
- it('matches @silent followed by a space', () => {
- expect(parseSilentMessagePrefix('@silent hello')).toEqual({tokenStart: 0, tokenEnd: 7, end: 8});
- });
-
- it('matches @silent on its own, with or without a trailing space', () => {
- expect(parseSilentMessagePrefix('@silent')).toEqual({tokenStart: 0, tokenEnd: 7, end: 7});
- expect(parseSilentMessagePrefix('@silent ')).toEqual({tokenStart: 0, tokenEnd: 7, end: 8});
- });
-
- it.each([
- ['a newline', '\n'],
- ['a tab', '\t'],
- ['a no-break space', '\u00a0'],
- ])('matches @silent followed by %s', (_name, whitespace) => {
- expect(parseSilentMessagePrefix(`@silent${whitespace}hello`)).toEqual({tokenStart: 0, tokenEnd: 7, end: 8});
- });
-
- it('consumes only one whitespace character after the token', () => {
- expect(parseSilentMessagePrefix('@silent hello')).toEqual({tokenStart: 0, tokenEnd: 7, end: 8});
- });
-
- it('skips leading whitespace before the token', () => {
- expect(parseSilentMessagePrefix(' @silent hello')).toEqual({tokenStart: 2, tokenEnd: 9, end: 10});
- expect(parseSilentMessagePrefix('\n@silent hello')).toEqual({tokenStart: 1, tokenEnd: 8, end: 9});
- });
-
- it.each([
- '',
- 'hello',
- 'hello @silent',
- '@silently hello',
- '@Silent hello',
- '@silent@everyone',
- '`@silent` hello',
- '> @silent hello',
- ])('does not match %j', (content) => {
- expect(parseSilentMessagePrefix(content)).toBeNull();
- });
-
- it.each([
- '@silent hello',
- ' @silent hello',
- '\n@silent hello',
- '\t@silent hello',
- '\u00a0@silent hello',
- '\u3000@silent hello',
- '\ufeff@silent hello',
- '\u200b@silent hello',
- '@silent',
- '@silent ',
- '@silent\u00a0',
- '@silent\u200b',
- '@silently hello',
- 'hello @silent',
- ' ',
- ])('matches %j the same way before and after trimming', (content) => {
- expect(parseSilentMessagePrefix(content) != null).toBe(parseSilentMessagePrefix(content.trim()) != null);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/TextareaKeyboardNavigationUtils.test.ts b/fluxer_app/src/features/messaging/utils/TextareaKeyboardNavigationUtils.test.ts
deleted file mode 100644
index 0bc6efbf7..000000000
--- a/fluxer_app/src/features/messaging/utils/TextareaKeyboardNavigationUtils.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getPreviousVisualLineCaretPositionFromPoints,
- getPreviousWordBoundaryAcrossLineStart,
-} from '@app/features/messaging/utils/TextareaKeyboardNavigationUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('TextareaKeyboardNavigationUtils', () => {
- it('moves a stuck Shift+ArrowUp focus edge to the previous visual row', () => {
- const points = [
- {position: 0, left: 0, top: 0},
- {position: 40, left: 340, top: 0},
- {position: 42, left: 356, top: 0},
- {position: 43, left: 370, top: 0},
- {position: 45, left: 0, top: 22},
- {position: 86, left: 315, top: 22},
- {position: 87, left: 331, top: 22},
- {position: 88, left: 341, top: 22},
- {position: 89, left: 346, top: 22},
- {position: 90, left: 0, top: 44},
- {position: 131, left: 357, top: 44},
- ];
-
- expect(getPreviousVisualLineCaretPositionFromPoints(points, 89, 357)).toBe(42);
- expect(getPreviousVisualLineCaretPositionFromPoints(points, 42, 357)).toBe(0);
- });
-
- it('uses the previous visual row start for a left-edge goal column', () => {
- const points = [
- {position: 0, left: 0, top: 0},
- {position: 10, left: 100, top: 0},
- {position: 11, left: 0, top: 22},
- {position: 20, left: 90, top: 22},
- {position: 21, left: 0, top: 44},
- ];
-
- expect(getPreviousVisualLineCaretPositionFromPoints(points, 21, 0)).toBe(11);
- });
-
- it('returns null when the focus point is unavailable', () => {
- expect(getPreviousVisualLineCaretPositionFromPoints([{position: 0, left: 0, top: 0}], 5, 0)).toBeNull();
- });
-
- it('skips whitespace before a hard line break for Ctrl+ArrowLeft fallback', () => {
- expect(getPreviousWordBoundaryAcrossLineStart('hello\n ', 9)).toBe(5);
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/TextareaSegmentManager.test.ts b/fluxer_app/src/features/messaging/utils/TextareaSegmentManager.test.ts
deleted file mode 100644
index 803f3871e..000000000
--- a/fluxer_app/src/features/messaging/utils/TextareaSegmentManager.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {type MentionSegment, TextareaSegmentManager} from '@app/features/messaging/utils/TextareaSegmentManager';
-import {describe, expect, it} from 'vitest';
-
-function userSegment(overrides: Partial<MentionSegment> = {}): MentionSegment {
- return {
- type: 'user',
- id: '1000',
- displayText: '@Zacy',
- actualText: '<@1000>',
- start: 0,
- end: 5,
- ...overrides,
- };
-}
-
-describe('TextareaSegmentManager', () => {
- it('uses the pre-edit selection to keep mention segments when inserting matching text before them', () => {
- const manager = new TextareaSegmentManager();
- manager.setSegments([userSegment()]);
-
- const oldValue = '@Zacy ';
- const newValue = '@@Zacy ';
- const change = TextareaSegmentManager.detectChange(oldValue, newValue, {
- selectionStart: 0,
- selectionEnd: 0,
- inputType: 'insertText',
- });
-
- manager.updateSegmentsForTextChange(change.changeStart, change.changeEnd, change.replacementLength);
-
- expect(change).toEqual({changeStart: 0, changeEnd: 0, replacementLength: 1});
- expect(manager.getSegments()).toEqual([userSegment({start: 1, end: 6})]);
- expect(manager.displayToActual(newValue)).toBe('@<@1000> ');
- });
-
- it('falls back to text diffing when no selection hint is available', () => {
- const change = TextareaSegmentManager.detectChange('@Zacy ', '@@Zacy ');
-
- expect(change).toEqual({changeStart: 1, changeEnd: 1, replacementLength: 1});
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/TextareaSelectionUtils.test.ts b/fluxer_app/src/features/messaging/utils/TextareaSelectionUtils.test.ts
deleted file mode 100644
index 8bcb79010..000000000
--- a/fluxer_app/src/features/messaging/utils/TextareaSelectionUtils.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-// @vitest-environment happy-dom
-
-import {
- normalizeTextareaSelectionSnapshot,
- restoreTextareaSelection,
- type TextareaSelectionSnapshot,
-} from '@app/features/messaging/utils/TextareaSelectionUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('TextareaSelectionUtils', () => {
- it('clamps saved selections to the current textarea value', () => {
- const snapshot: TextareaSelectionSnapshot = {
- selectionStart: 10,
- selectionEnd: 12,
- selectionDirection: 'backward',
- };
-
- expect(normalizeTextareaSelectionSnapshot(snapshot, 5)).toEqual({
- selectionStart: 5,
- selectionEnd: 5,
- selectionDirection: 'backward',
- });
- });
-
- it('restores selection direction when applying a snapshot', () => {
- const textarea = document.createElement('textarea');
- textarea.value = 'hello world';
- document.body.append(textarea);
-
- restoreTextareaSelection(textarea, {
- selectionStart: 2,
- selectionEnd: 7,
- selectionDirection: 'backward',
- });
-
- expect(textarea.selectionStart).toBe(2);
- expect(textarea.selectionEnd).toBe(7);
- expect(textarea.selectionDirection).toBe('backward');
-
- textarea.remove();
- });
-});
diff --git a/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasm.test.ts b/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasm.test.ts
deleted file mode 100644
index e5269248e..000000000
--- a/fluxer_app/src/features/messaging/utils/markdown/parser/MarkdownParserWasm.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {initializeEmojiParser} from '@app/features/messaging/utils/markdown/EmojiProviderSetup';
-import {ParserFlags} from '@app/features/messaging/utils/markdown/parser/Enums';
-import {parseMarkdownAstWithWasm} from '@app/features/messaging/utils/markdown/parser/MarkdownParserWasm';
-import {beforeAll, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/expressions/utils/EmojiUtils', () => ({
- getEmojiURL: () => null,
-}));
-
-vi.mock('@lingui/core/macro', () => ({
- msg: (descriptor: unknown) => descriptor,
-}));
-
-describe('markdown parser wasm blockquotes', () => {
- it('preserves consecutive empty blockquote lines', () => {
- expect(parseMarkdownAstWithWasm('> \n> \nsome text', ParserFlags.ALLOW_BLOCKQUOTES)).toEqual({
- nodes: [
- {
- type: 'Blockquote',
- children: [],
- blankLines: 2,
- },
- {
- type: 'Text',
- content: 'some text',
- },
- ],
- });
- });
-
- it('keeps a bare greater-than line as text', () => {
- expect(parseMarkdownAstWithWasm('> \n>', ParserFlags.ALLOW_BLOCKQUOTES)).toEqual({
- nodes: [
- {
- type: 'Blockquote',
- children: [],
- blankLines: 1,
- },
- {
- type: 'Text',
- content: '>',
- },
- ],
- });
- });
-});
-
-describe('markdown parser wasm headings', () => {
- it('preserves presentation-only heading lines as block headings', () => {
- expect(parseMarkdownAstWithWasm('# ‎ \n# ‎', ParserFlags.ALLOW_HEADINGS)).toEqual({
- nodes: [
- {
- type: 'Heading',
- level: 1,
- children: [{type: 'Text', content: '‎ '}],
- },
- {
- type: 'Heading',
- level: 1,
- children: [{type: 'Text', content: '‎'}],
- },
- ],
- });
- });
-
- it('keeps ordinary whitespace-only heading syntax as text', () => {
- expect(parseMarkdownAstWithWasm('# ', ParserFlags.ALLOW_HEADINGS)).toEqual({
- nodes: [{type: 'Text', content: '# '}],
- });
- });
-});
-
-describe('markdown parser wasm default-presentation emoji', () => {
- beforeAll(() => {
- initializeEmojiParser();
- });
-
- it.each([
- ['⌚', 'watch', '231a'],
- ['⌛', 'hourglass', '231b'],
- ['⏩', 'fast_forward', '23e9'],
- ['⏪', 'rewind', '23ea'],
- ['⏫', 'arrow_double_up', '23eb'],
- ['⏬', 'arrow_double_down', '23ec'],
- ['⏰', 'alarm_clock', '23f0'],
- ['⏳', 'hourglass_flowing_sand', '23f3'],
- ])('renders %s as an emoji without a variation selector', (raw, name, codepoints) => {
- expect(parseMarkdownAstWithWasm(raw, 0)).toEqual({
- nodes: [{type: 'Emoji', kind: {kind: 'Standard', raw, codepoints, name}}],
- });
- });
-
- it('keeps text-presentation symbols as plain text when typed bare', () => {
- expect(parseMarkdownAstWithWasm('❤', 0)).toEqual({
- nodes: [{type: 'Text', content: '❤'}],
- });
- });
-
- it('still renders text-presentation symbols carrying a variation selector', () => {
- expect(parseMarkdownAstWithWasm('❤️', 0)).toEqual({
- nodes: [{type: 'Emoji', kind: {kind: 'Standard', raw: '❤️', codepoints: '2764', name: 'heart'}}],
- });
- });
-});
diff --git a/fluxer_app/src/features/moderation/components/report/ReportState.test.ts b/fluxer_app/src/features/moderation/components/report/ReportState.test.ts
deleted file mode 100644
index 10cf4c58a..000000000
--- a/fluxer_app/src/features/moderation/components/report/ReportState.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReportSnapshot,
- selectReportState,
- transitionReportSnapshot,
-} from '@app/features/moderation/components/report/ReportState';
-import {describe, expect, it} from 'vitest';
-
-describe('ReportState machine', () => {
- it('moves through the public report flow while preserving context', () => {
- let snapshot = createReportSnapshot();
- expect(selectReportState(snapshot).flowStep).toBe('selection');
-
- snapshot = transitionReportSnapshot(snapshot, {type: 'SELECT_TYPE', reportType: 'message'});
- let state = selectReportState(snapshot);
- expect(state.flowStep).toBe('email');
- expect(state.selectedType).toBe('message');
-
- snapshot = transitionReportSnapshot(snapshot, {type: 'SET_EMAIL', email: '[email protected]'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'GO_TO_VERIFICATION'});
- state = selectReportState(snapshot);
- expect(state.flowStep).toBe('verification');
- expect(state.email).toBe('[email protected]');
-
- snapshot = transitionReportSnapshot(snapshot, {type: 'SET_TICKET', ticket: 'ticket-1'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'GO_TO_DETAILS'});
- state = selectReportState(snapshot);
- expect(state.flowStep).toBe('details');
- expect(state.ticket).toBe('ticket-1');
- });
-
- it('clears step-local verification state when returning to email', () => {
- let snapshot = createReportSnapshot();
- snapshot = transitionReportSnapshot(snapshot, {type: 'SELECT_TYPE', reportType: 'user'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'SET_VERIFICATION_CODE', code: 'ABCD-1234'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'SET_TICKET', ticket: 'ticket-1'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'VERIFYING', value: true});
- snapshot = transitionReportSnapshot(snapshot, {type: 'START_RESEND_COOLDOWN', seconds: 30});
- snapshot = transitionReportSnapshot(snapshot, {type: 'GO_TO_EMAIL'});
-
- const state = selectReportState(snapshot);
- expect(state.flowStep).toBe('email');
- expect(state.verificationCode).toBe('');
- expect(state.ticket).toBeNull();
- expect(state.isVerifying).toBe(false);
- expect(state.resendCooldownSeconds).toBe(0);
- });
-
- it('updates form fields and clears individual field errors', () => {
- let snapshot = createReportSnapshot();
- snapshot = transitionReportSnapshot(snapshot, {
- type: 'SET_FIELD_ERRORS',
- errors: {messageLink: 'Message link is invalid'},
- });
- snapshot = transitionReportSnapshot(snapshot, {
- type: 'SET_FORM_FIELD',
- field: 'messageLink',
- value: 'https://fluxer.app/channels/1/2/3',
- });
- let state = selectReportState(snapshot);
- expect(state.formValues.messageLink).toBe('https://fluxer.app/channels/1/2/3');
- expect(state.fieldErrors.messageLink).toBeUndefined();
-
- snapshot = transitionReportSnapshot(snapshot, {
- type: 'SET_FIELD_ERRORS',
- errors: {messageLink: 'Message link is invalid', category: 'Category required'},
- });
- snapshot = transitionReportSnapshot(snapshot, {type: 'CLEAR_FIELD_ERROR', field: 'messageLink'});
- state = selectReportState(snapshot);
- expect(state.fieldErrors.messageLink).toBeUndefined();
- expect(state.fieldErrors.category).toBe('Category required');
- });
-
- it('enters complete on submit success and reset returns to a fresh selection state', () => {
- let snapshot = createReportSnapshot();
- snapshot = transitionReportSnapshot(snapshot, {type: 'SELECT_TYPE', reportType: 'guild'});
- snapshot = transitionReportSnapshot(snapshot, {type: 'SUBMITTING', value: true});
- snapshot = transitionReportSnapshot(snapshot, {type: 'SUBMIT_SUCCESS', reportId: 'report-1'});
- let state = selectReportState(snapshot);
- expect(state.flowStep).toBe('complete');
- expect(state.successReportId).toBe('report-1');
- expect(state.isSubmitting).toBe(false);
-
- snapshot = transitionReportSnapshot(snapshot, {type: 'RESET_ALL'});
- state = selectReportState(snapshot);
- expect(state.flowStep).toBe('selection');
- expect(state.selectedType).toBeNull();
- expect(state.successReportId).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/notification/state/NotificationAutoAckStateMachine.test.ts b/fluxer_app/src/features/notification/state/NotificationAutoAckStateMachine.test.ts
deleted file mode 100644
index 05ffa86df..000000000
--- a/fluxer_app/src/features/notification/state/NotificationAutoAckStateMachine.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type AutoAckWindowConditions,
- createAutoAckWindowSnapshot,
- selectAutoAckWindowCommands,
- transitionAutoAckWindowSnapshot,
-} from '@app/features/notification/state/NotificationAutoAckStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function conditions(overrides: Partial<AutoAckWindowConditions> = {}): AutoAckWindowConditions {
- return {
- channelId: null,
- isAtBottom: false,
- canAutoAck: false,
- ...overrides,
- };
-}
-
-function transition(overrides: Partial<AutoAckWindowConditions>) {
- return transitionAutoAckWindowSnapshot(createAutoAckWindowSnapshot(), {
- type: 'autoAck.conditionsChanged',
- conditions: conditions(overrides),
- });
-}
-
-describe('autoAckWindowStateMachine', () => {
- it('does not emit commands when there is no selected channel', () => {
- const snapshot = transition({});
- expect(snapshot.value).toBe('noChannel');
- expect(selectAutoAckWindowCommands(snapshot)).toEqual([]);
- });
-
- it('enables automatic ack only when the channel is visible at bottom', () => {
- const snapshot = transition({channelId: 'channel-1', isAtBottom: true, canAutoAck: true});
-
- expect(snapshot.value).toBe('enabled');
- expect(selectAutoAckWindowCommands(snapshot)).toEqual([{type: 'enable', channelId: 'channel-1'}]);
- });
-
- it('disables the current channel when auto-ack conditions fail', () => {
- const snapshot = transition({channelId: 'channel-1', isAtBottom: false, canAutoAck: true});
-
- expect(snapshot.value).toBe('disabled');
- expect(selectAutoAckWindowCommands(snapshot)).toEqual([{type: 'disable', channelId: 'channel-1'}]);
- });
-
- it('disables the previous channel before enabling a new channel', () => {
- const firstSnapshot = transition({channelId: 'channel-1', isAtBottom: true, canAutoAck: true});
- const secondSnapshot = transitionAutoAckWindowSnapshot(firstSnapshot, {
- type: 'autoAck.conditionsChanged',
- conditions: conditions({channelId: 'channel-2', isAtBottom: true, canAutoAck: true}),
- });
-
- expect(secondSnapshot.value).toBe('enabled');
- expect(selectAutoAckWindowCommands(secondSnapshot)).toEqual([
- {type: 'disable', channelId: 'channel-1'},
- {type: 'enable', channelId: 'channel-2'},
- ]);
- });
-
- it('disables the previous channel when selection clears', () => {
- const firstSnapshot = transition({channelId: 'channel-1', isAtBottom: true, canAutoAck: true});
- const secondSnapshot = transitionAutoAckWindowSnapshot(firstSnapshot, {
- type: 'autoAck.conditionsChanged',
- conditions: conditions({channelId: null}),
- });
-
- expect(secondSnapshot.value).toBe('noChannel');
- expect(selectAutoAckWindowCommands(secondSnapshot)).toEqual([{type: 'disable', channelId: 'channel-1'}]);
- });
-
- it('disables automatic ack while the media viewer suppresses auto-ack', () => {
- const enabledSnapshot = transition({channelId: 'channel-1', isAtBottom: true, canAutoAck: true});
- const viewerOpenSnapshot = transitionAutoAckWindowSnapshot(enabledSnapshot, {
- type: 'autoAck.conditionsChanged',
- conditions: conditions({channelId: 'channel-1', isAtBottom: true, canAutoAck: false}),
- });
-
- expect(viewerOpenSnapshot.value).toBe('disabled');
- expect(selectAutoAckWindowCommands(viewerOpenSnapshot)).toEqual([{type: 'disable', channelId: 'channel-1'}]);
- });
-
- it('re-enables automatic ack at the bottom once the media viewer no longer suppresses it', () => {
- const viewerOpenSnapshot = transition({channelId: 'channel-1', isAtBottom: true, canAutoAck: false});
- const viewerClosedSnapshot = transitionAutoAckWindowSnapshot(viewerOpenSnapshot, {
- type: 'autoAck.conditionsChanged',
- conditions: conditions({channelId: 'channel-1', isAtBottom: true, canAutoAck: true}),
- });
-
- expect(viewerClosedSnapshot.value).toBe('enabled');
- expect(selectAutoAckWindowCommands(viewerClosedSnapshot)).toEqual([{type: 'enable', channelId: 'channel-1'}]);
- });
-});
diff --git a/fluxer_app/src/features/notification/utils/AutoAckVisibility.test.ts b/fluxer_app/src/features/notification/utils/AutoAckVisibility.test.ts
deleted file mode 100644
index 6c93a2e19..000000000
--- a/fluxer_app/src/features/notification/utils/AutoAckVisibility.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getDirectCallFullscreenScopeKey,
- isTextChatVisibleForAutoAck,
- isVoiceCallFullscreenScopeForChannel,
-} from '@app/features/notification/utils/AutoAckVisibility';
-import {getGuildVoiceCallExpansionKey} from '@app/features/voice/state/CompactVoiceCallHeight';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('isTextChatVisibleForAutoAck', () => {
- it('allows normal text channels to auto-ack when no fullscreen call view is active', () => {
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'text-1',
- channelType: ChannelTypes.GUILD_TEXT,
- isGuildVoiceCallExpanded: true,
- activeVoiceCallFullscreenScopeKey: null,
- }),
- ).toBe(true);
- });
- it('blocks guild voice auto-ack while the call view has hidden chat', () => {
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'voice-1',
- channelType: ChannelTypes.GUILD_VOICE,
- isGuildVoiceCallExpanded: true,
- activeVoiceCallFullscreenScopeKey: null,
- }),
- ).toBe(false);
- });
- it('allows guild voice auto-ack when chat is visible', () => {
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'voice-1',
- channelType: ChannelTypes.GUILD_VOICE,
- isGuildVoiceCallExpanded: false,
- activeVoiceCallFullscreenScopeKey: null,
- }),
- ).toBe(true);
- });
- it('blocks auto-ack when the selected channel is in a fullscreen call view', () => {
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'voice-1',
- channelType: ChannelTypes.GUILD_VOICE,
- isGuildVoiceCallExpanded: false,
- activeVoiceCallFullscreenScopeKey: getGuildVoiceCallExpansionKey('voice-1'),
- }),
- ).toBe(false);
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'dm-1',
- channelType: ChannelTypes.DM,
- isGuildVoiceCallExpanded: false,
- activeVoiceCallFullscreenScopeKey: getDirectCallFullscreenScopeKey('dm-1'),
- }),
- ).toBe(false);
- });
- it('ignores fullscreen call scopes for other channels', () => {
- expect(isVoiceCallFullscreenScopeForChannel('voice-1', getGuildVoiceCallExpansionKey('voice-2'))).toBe(false);
- expect(
- isTextChatVisibleForAutoAck({
- channelId: 'voice-1',
- channelType: ChannelTypes.GUILD_VOICE,
- isGuildVoiceCallExpanded: false,
- activeVoiceCallFullscreenScopeKey: getGuildVoiceCallExpansionKey('voice-2'),
- }),
- ).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/notification/utils/MentionFeedFilters.test.ts b/fluxer_app/src/features/notification/utils/MentionFeedFilters.test.ts
deleted file mode 100644
index e2f0fc09f..000000000
--- a/fluxer_app/src/features/notification/utils/MentionFeedFilters.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type MentionFilters,
- messageMatchesMentionTypeFilters,
-} from '@app/features/notification/utils/MentionFeedFilters';
-import {describe, expect, it} from 'vitest';
-
-const DIRECT_ONLY = {mention_everyone: false, mention_roles: []};
-const EVERYONE_ONLY = {mention_everyone: true, mention_roles: []};
-const ROLE_ONLY = {mention_everyone: false, mention_roles: ['10']};
-const EVERYONE_AND_ROLE = {mention_everyone: true, mention_roles: ['10']};
-
-function filters(overrides: Partial<MentionFilters>): MentionFilters {
- return {
- includeEveryone: true,
- includeRoles: true,
- includeGuilds: true,
- ...overrides,
- };
-}
-
-describe('messageMatchesMentionTypeFilters', () => {
- it('keeps direct user mentions regardless of mass mention filters', () => {
- expect(messageMatchesMentionTypeFilters(DIRECT_ONLY, filters({includeEveryone: false, includeRoles: false}))).toBe(
- true,
- );
- });
- it('excludes role mentions when role mentions are disabled', () => {
- expect(messageMatchesMentionTypeFilters(ROLE_ONLY, filters({includeRoles: false}))).toBe(false);
- });
- it('excludes everyone mentions when everyone mentions are disabled', () => {
- expect(messageMatchesMentionTypeFilters(EVERYONE_ONLY, filters({includeEveryone: false}))).toBe(false);
- });
- it('excludes mixed mass mentions when either matching mass mention type is disabled', () => {
- expect(messageMatchesMentionTypeFilters(EVERYONE_AND_ROLE, filters({includeEveryone: false}))).toBe(false);
- expect(messageMatchesMentionTypeFilters(EVERYONE_AND_ROLE, filters({includeRoles: false}))).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/components/router/RouterCore.test.ts b/fluxer_app/src/features/platform/components/router/RouterCore.test.ts
deleted file mode 100644
index 89b80b7a6..000000000
--- a/fluxer_app/src/features/platform/components/router/RouterCore.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createRootRoute, createRoute} from '@app/features/platform/components/router/RouterBuilder';
-import {createRouter} from '@app/features/platform/components/router/RouterCore';
-import {createMemoryHistory} from '@app/features/platform/components/router/RouterHistory';
-import {describe, expect, it} from 'vitest';
-
-function createTestRouter(initialHref = 'http://localhost/') {
- const rootRoute = createRootRoute();
- const homeRoute = createRoute({id: 'home', path: '/'});
- const oauthRoute = createRoute({id: 'oauthAuthorize', path: '/oauth2/authorize'});
- const channelRoute = createRoute({id: 'channel', path: '/channels/:guildId/:channelId'});
- const notFoundRoute = createRoute({id: '__notFound', path: '/__notfound'});
- return createRouter({
- routes: rootRoute.addChildren([homeRoute, oauthRoute, channelRoute, notFoundRoute]).build(),
- history: createMemoryHistory(initialHref),
- notFoundRouteId: '__notFound',
- });
-}
-
-describe('RouterCore', () => {
- it('reports only real SPA routes as client-handled destinations', () => {
- const router = createTestRouter('http://localhost/login');
-
- expect(router.canHandle('/oauth2/authorize?client_id=1')).toBe(true);
- expect(router.canHandle('/channels/123/456')).toBe(true);
- expect(router.canHandle('/admin/auth/start')).toBe(false);
- expect(router.canHandle('/marketing')).toBe(false);
- expect(router.canHandle('https://example.com/oauth2/authorize')).toBe(false);
-
- router.destroy();
- });
-});
diff --git a/fluxer_app/src/features/platform/notifications/NotificationAlertOptions.test.ts b/fluxer_app/src/features/platform/notifications/NotificationAlertOptions.test.ts
deleted file mode 100644
index 02545738f..000000000
--- a/fluxer_app/src/features/platform/notifications/NotificationAlertOptions.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getNotificationAlertOptions,
- isIOSMobileOrTabletUserAgent,
- isMobileOrTabletUserAgent,
- NOTIFICATION_VIBRATION_PATTERN,
-} from '@app/features/platform/notifications/NotificationAlertOptions';
-import {describe, expect, it} from 'vitest';
-
-describe('NotificationAlertOptions', () => {
- it('uses vibration instead of silent notifications on mobile devices', () => {
- const options = getNotificationAlertOptions({mobileOrTablet: true, silentOnNonMobile: true});
- expect(options.silent).toBeUndefined();
- expect(options.vibrate).toEqual([...NOTIFICATION_VIBRATION_PATTERN]);
- });
- it('keeps explicitly silent notification behavior for non-mobile devices', () => {
- const options = getNotificationAlertOptions({mobileOrTablet: false, silentOnNonMobile: true});
- expect(options).toEqual({silent: true});
- });
- it('leaves background desktop push notifications to the platform default alert behavior', () => {
- const options = getNotificationAlertOptions({mobileOrTablet: false, silentOnNonMobile: false});
- expect(options).toEqual({});
- });
- it('detects mobile and tablet user agents used by PWA installs', () => {
- expect(isMobileOrTabletUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X)')).toBe(true);
- expect(isMobileOrTabletUserAgent('Mozilla/5.0 (Linux; Android 13; Pixel 7)')).toBe(true);
- expect(isMobileOrTabletUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)', 5)).toBe(true);
- expect(isMobileOrTabletUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7)')).toBe(false);
- });
- it('separates iOS mobile and tablet user agents from Android', () => {
- expect(isIOSMobileOrTabletUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X)')).toBe(true);
- expect(isIOSMobileOrTabletUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)', 5)).toBe(true);
- expect(isIOSMobileOrTabletUserAgent('Mozilla/5.0 (Linux; Android 13; Pixel 7)')).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.test.ts b/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.test.ts
deleted file mode 100644
index f50847ab5..000000000
--- a/fluxer_app/src/features/platform/service_worker/WorkerCacheCleanup.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {shouldDeleteWorkerCache} from '@app/features/platform/service_worker/WorkerCacheCleanup';
-import {describe, expect, it} from 'vitest';
-
-describe('WorkerCacheCleanup', () => {
- const expectedCaches = new Set(['fluxer-precache-current', 'fluxer-navigation-current']);
-
- it('reclaims every cache the current worker no longer writes to', () => {
- expect(shouldDeleteWorkerCache('fluxer-assets-current', expectedCaches)).toBe(true);
- expect(shouldDeleteWorkerCache('fluxer-assets-previous', expectedCaches)).toBe(true);
- expect(shouldDeleteWorkerCache('fluxer-expression-assets', expectedCaches)).toBe(true);
- expect(shouldDeleteWorkerCache('fluxer-expression-assets-2026.604', expectedCaches)).toBe(true);
- expect(shouldDeleteWorkerCache('fluxer-precache-previous', expectedCaches)).toBe(true);
- expect(shouldDeleteWorkerCache('fluxer-navigation-previous', expectedCaches)).toBe(true);
- });
-
- it('keeps the current caches and anything the worker does not own', () => {
- expect(shouldDeleteWorkerCache('fluxer-precache-current', expectedCaches)).toBe(false);
- expect(shouldDeleteWorkerCache('fluxer-navigation-current', expectedCaches)).toBe(false);
- expect(shouldDeleteWorkerCache('third-party-cache', expectedCaches)).toBe(false);
- expect(shouldDeleteWorkerCache('fluxer', expectedCaches)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/service_worker/WorkerNavigation.test.ts b/fluxer_app/src/features/platform/service_worker/WorkerNavigation.test.ts
deleted file mode 100644
index a804c00be..000000000
--- a/fluxer_app/src/features/platform/service_worker/WorkerNavigation.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isAppNavigationPath} from '@app/features/platform/service_worker/WorkerNavigation';
-import {describe, expect, it} from 'vitest';
-
-describe('WorkerNavigation', () => {
- it('allows only SPA paths to use the service worker navigation fallback', () => {
- expect(isAppNavigationPath('/')).toBe(true);
- expect(isAppNavigationPath('/login')).toBe(true);
- expect(isAppNavigationPath('/oauth2/authorize')).toBe(true);
- expect(isAppNavigationPath('/channels/@me')).toBe(true);
- expect(isAppNavigationPath('/channels/123/456')).toBe(true);
- expect(isAppNavigationPath('/invite/example')).toBe(true);
-
- expect(isAppNavigationPath('/admin')).toBe(false);
- expect(isAppNavigationPath('/admin/auth/start')).toBe(false);
- expect(isAppNavigationPath('/marketing')).toBe(false);
- expect(isAppNavigationPath('/api/users/@me')).toBe(false);
- expect(isAppNavigationPath('/media/avatars/1.png')).toBe(false);
- expect(isAppNavigationPath('/unknown')).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/service_worker/WorkerPushPayload.test.ts b/fluxer_app/src/features/platform/service_worker/WorkerPushPayload.test.ts
deleted file mode 100644
index c50d32941..000000000
--- a/fluxer_app/src/features/platform/service_worker/WorkerPushPayload.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getBadgeCount,
- getPushNotificationClientState,
- isNotificationClearPayload,
- matchesPushChannelNotification,
- normalizePushPayload,
- resolvePushChannelId,
- resolvePushNotificationTag,
- shouldSilenceNonMobilePushNotification,
-} from '@app/features/platform/service_worker/WorkerPushPayload';
-import {describe, expect, it} from 'vitest';
-
-describe('WorkerPushPayload', () => {
- it('normalizes encrypted Web Push payloads without losing navigation data', () => {
- const payload = normalizePushPayload({
- web_push: 8030,
- notification: {
- title: 'New message',
- tag: 'channel:123',
- navigate: '/channels/@me/123/456',
- data: {
- channel_id: '123',
- },
- },
- });
- expect(payload.title).toBe('New message');
- expect(payload.tag).toBe('channel:123');
- expect(payload.data).toMatchObject({
- channel_id: '123',
- url: '/channels/@me/123/456',
- });
- });
- it('detects clear packets from the root payload and data payload', () => {
- expect(
- isNotificationClearPayload({
- type: 'notification_clear',
- data: {
- channel_id: '123',
- },
- }),
- ).toBe(true);
- expect(
- isNotificationClearPayload({
- data: {
- action: 'clear_channel',
- },
- }),
- ).toBe(true);
- expect(isNotificationClearPayload({title: 'Visible notification'})).toBe(false);
- });
- it('resolves notification tags from explicit tags, notification tags, and channel ids', () => {
- expect(resolvePushNotificationTag({tag: 'channel:from-root'})).toBe('channel:from-root');
- expect(resolvePushNotificationTag({data: {tag: 'channel:123:456'}})).toBe('channel:123:456');
- expect(resolvePushNotificationTag({data: {notification_tag: 'channel:from-data'}})).toBe('channel:from-data');
- expect(resolvePushNotificationTag({data: {channel_id: '987'}})).toBe('channel:987');
- expect(resolvePushNotificationTag({data: {channel_id: ''}})).toBeUndefined();
- });
- it('resolves channel ids and matches channel notifications for clear-on-read', () => {
- expect(resolvePushChannelId({data: {channel_id: '123'}})).toBe('123');
- expect(resolvePushChannelId({})).toBeUndefined();
- const channelNotification = {
- tag: 'channel:123:456',
- data: {channel_id: '123'},
- } as Notification;
- const legacyChannelNotification = {tag: 'channel:123'} as Notification;
- const otherChannelNotification = {
- tag: 'channel:999:456',
- data: {channel_id: '999'},
- } as Notification;
- const samePrefixOtherChannelNotification = {tag: 'channel:1234:456'} as Notification;
- const malformedDataNotification = {tag: 'channel:123:789', data: 'not-record'} as unknown as Notification;
- expect(matchesPushChannelNotification(channelNotification, '123')).toBe(true);
- expect(matchesPushChannelNotification(legacyChannelNotification, '123')).toBe(true);
- expect(matchesPushChannelNotification(otherChannelNotification, '123')).toBe(false);
- expect(matchesPushChannelNotification(samePrefixOtherChannelNotification, '123')).toBe(false);
- expect(matchesPushChannelNotification(malformedDataNotification, '123')).toBe(true);
- expect(matchesPushChannelNotification(channelNotification, '')).toBe(false);
- });
- it('parses badge counts from numeric and string data values', () => {
- expect(getBadgeCount({data: {badge_count: 5}})).toBe(5);
- expect(getBadgeCount({data: {badge_count: '0'}})).toBe(0);
- expect(getBadgeCount({data: {badge_count: 'not-a-number'}})).toBeNull();
- expect(getBadgeCount({})).toBeNull();
- });
- it('silences non-mobile push notifications when any app client is open', () => {
- const hiddenClientState = getPushNotificationClientState([{visibilityState: 'hidden'}]);
- expect(hiddenClientState).toEqual({hasWindowClient: true, hasVisibleClient: false});
- expect(shouldSilenceNonMobilePushNotification(hiddenClientState)).toBe(true);
- const noClientState = getPushNotificationClientState([]);
- expect(noClientState).toEqual({hasWindowClient: false, hasVisibleClient: false});
- expect(shouldSilenceNonMobilePushNotification(noClientState)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/platform/state/auth_session/AuthSessionStateMachine.test.ts b/fluxer_app/src/features/platform/state/auth_session/AuthSessionStateMachine.test.ts
deleted file mode 100644
index 52b19df0e..000000000
--- a/fluxer_app/src/features/platform/state/auth_session/AuthSessionStateMachine.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type Account,
- createAuthSessionSnapshot,
- getAuthSessionStateValue,
- SessionState,
- selectAuthSessionAccounts,
- selectAuthSessionCanSwitch,
- transitionAuthSessionSnapshot,
-} from '@app/features/platform/state/auth_session/AuthSessionStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function account(userId: string, lastActive = 1): Account {
- return {
- userId,
- token: `token-${userId}`,
- lastActive,
- isValid: true,
- };
-}
-
-describe('AuthSessionStateMachine', () => {
- it('initializes without a token and records that initialization completed', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'initialize.start'});
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Initializing);
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'initialize.noToken'});
-
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Idle);
- expect(snapshot.context.isInitialized).toBe(true);
- expect(snapshot.context.token).toBeNull();
- expect(snapshot.context.userId).toBeNull();
- });
-
- it('loads stored accounts and sorts them by last activity', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'accounts.loaded',
- accounts: [account('older', 1), account('newer', 3), account('middle', 2)],
- });
-
- expect(selectAuthSessionAccounts(snapshot).map((storedAccount) => storedAccount.userId)).toEqual([
- 'newer',
- 'middle',
- 'older',
- ]);
- });
-
- it('moves through authenticated, connecting, and connected states', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'initialize.tokenLoaded',
- token: 'token-a',
- userId: 'user-a',
- });
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Authenticated);
- expect(selectAuthSessionCanSwitch(snapshot)).toBe(true);
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'connection.start'});
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Connecting);
- expect(selectAuthSessionCanSwitch(snapshot)).toBe(false);
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'connection.ready'});
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Connected);
- expect(selectAuthSessionCanSwitch(snapshot)).toBe(true);
- });
-
- it('keeps account bookkeeping separate from switch state', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'account.login',
- account: account('user-a'),
- });
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'account.switch.start'});
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Switching);
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'account.upsert',
- account: account('user-a', 5),
- });
-
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Switching);
- expect(snapshot.context.accounts.get('user-a')?.lastActive).toBe(5);
- });
-
- it('completes switches and invalidates sessions with credential cleanup', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'account.login',
- account: account('user-a'),
- });
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'account.switch.start'});
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'account.switch.complete',
- account: account('user-b', 10),
- });
-
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Authenticated);
- expect(snapshot.context.userId).toBe('user-b');
- expect(snapshot.context.token).toBe('token-user-b');
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'session.invalidated'});
-
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Idle);
- expect(snapshot.context.userId).toBeNull();
- expect(snapshot.context.token).toBeNull();
- });
-
- it('clears active credentials when logout completes', () => {
- let snapshot = createAuthSessionSnapshot();
- snapshot = transitionAuthSessionSnapshot(snapshot, {
- type: 'account.login',
- account: account('user-a'),
- });
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'logout.start'});
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.LoggingOut);
-
- snapshot = transitionAuthSessionSnapshot(snapshot, {type: 'logout.complete'});
-
- expect(getAuthSessionStateValue(snapshot)).toBe(SessionState.Idle);
- expect(snapshot.context.token).toBeNull();
- expect(snapshot.context.userId).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/platform/utils/IsTextInputKeyEvent.test.ts b/fluxer_app/src/features/platform/utils/IsTextInputKeyEvent.test.ts
deleted file mode 100644
index 002aa24b2..000000000
--- a/fluxer_app/src/features/platform/utils/IsTextInputKeyEvent.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-let nativeMacOS = false;
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- isNativeMacOS: () => nativeMacOS,
-}));
-
-const {isTextInputKeyEvent} = await import('@app/features/platform/utils/IsTextInputKeyEvent');
-
-const keyEvent = (init: Partial<KeyboardEvent>): KeyboardEvent =>
- ({key: '', ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...init}) as KeyboardEvent;
-
-beforeEach(() => {
- nativeMacOS = false;
-});
-
-describe('isTextInputKeyEvent', () => {
- test('Alt+digit is a shortcut chord, not typing, off macOS', () => {
- for (const key of ['1', '2', '3', '4', '5', '6', '7', '8', '9']) {
- expect(isTextInputKeyEvent(keyEvent({key, altKey: true}))).toBe(false);
- }
- });
-
- test('Alt+letter is a shortcut chord, not typing, off macOS', () => {
- expect(isTextInputKeyEvent(keyEvent({key: 'a', altKey: true}))).toBe(false);
- });
-
- test('Option-composed characters stay typing on macOS', () => {
- nativeMacOS = true;
- expect(isTextInputKeyEvent(keyEvent({key: '¡', altKey: true}))).toBe(true);
- expect(isTextInputKeyEvent(keyEvent({key: '@', altKey: true}))).toBe(true);
- });
-
- test('a bare printable key is still typing', () => {
- expect(isTextInputKeyEvent(keyEvent({key: 'a'}))).toBe(true);
- expect(isTextInputKeyEvent(keyEvent({key: '1'}))).toBe(true);
- });
-
- test('ctrl and meta chords and named keys are still not typing', () => {
- expect(isTextInputKeyEvent(keyEvent({key: '1', ctrlKey: true}))).toBe(false);
- expect(isTextInputKeyEvent(keyEvent({key: '1', metaKey: true}))).toBe(false);
- expect(isTextInputKeyEvent(keyEvent({key: 'ArrowUp'}))).toBe(false);
- expect(isTextInputKeyEvent(keyEvent({key: 'ArrowUp', altKey: true}))).toBe(false);
- });
-
- test('a dead key still counts as typing while Alt is held', () => {
- expect(isTextInputKeyEvent(keyEvent({key: 'Dead', altKey: true}))).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/platform/utils/LibFluxcoreWasm.test.ts b/fluxer_app/src/features/platform/utils/LibFluxcoreWasm.test.ts
deleted file mode 100644
index 01116bbdd..000000000
--- a/fluxer_app/src/features/platform/utils/LibFluxcoreWasm.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {
- create_zstd_stream_decoder,
- crop_rotate_rgba,
- decompress_zstd_frame,
- decompress_zstd_stream_chunk,
- free_zstd_stream_decoder,
- initSync,
- is_animated_image,
-} from '@pkgs/libfluxcore/libfluxcore';
-import {describe, expect, it} from 'vitest';
-
-const wasmBytes = readFileSync(new URL('../../../../pkgs/libfluxcore/libfluxcore_bg.wasm', import.meta.url));
-
-initSync({module: wasmBytes});
-
-function rgba(values: Array<number>): Uint8Array {
- return new Uint8Array(values.flatMap((value) => [value, 0, 0, 255]));
-}
-
-describe('libfluxcore WASM package', () => {
- it('rotates RGBA pixels through the generated JS ABI', () => {
- const output = crop_rotate_rgba(rgba([1, 2, 3, 4, 5, 6]), 2, 3, 0, 0, 2, 3, 90, null, null);
- expect(output.width).toBe(3);
- expect(output.height).toBe(2);
- expect(Array.from(output.rgba)).toEqual(Array.from(rgba([5, 3, 1, 6, 4, 2])));
- });
- it('detects animated image containers without decoding the image payload', () => {
- const twoFrameGif = new Uint8Array([
- 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 1, 0, 1, 0, 0, 0, 0, 0x2c, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 0, 0x2c, 0, 0, 0, 0,
- 1, 0, 1, 0, 0, 2, 0, 0x3b,
- ]);
- const apng = new Uint8Array([
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 8, 0x61, 0x63, 0x54, 0x4c, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
- 0, 0,
- ]);
- expect(is_animated_image(twoFrameGif)).toBe(true);
- expect(is_animated_image(apng)).toBe(true);
- expect(is_animated_image(new Uint8Array([0x47, 0x49, 0x46]))).toBe(false);
- });
- it('decompresses a zstd gateway frame through the generated JS ABI', () => {
- const compressed = new Uint8Array([
- 40, 181, 47, 253, 4, 88, 177, 0, 0, 104, 101, 108, 108, 111, 32, 102, 114, 111, 109, 32, 108, 105, 98, 102, 108,
- 117, 120, 99, 111, 114, 101, 57, 102, 208, 44,
- ]);
- expect(new TextDecoder().decode(decompress_zstd_frame(compressed))).toBe('hello from libfluxcore');
- });
- it('keeps zstd stream decoder state between chunks', () => {
- const compressed = new Uint8Array([
- 40, 181, 47, 253, 4, 88, 177, 0, 0, 104, 101, 108, 108, 111, 32, 102, 114, 111, 109, 32, 108, 105, 98, 102, 108,
- 117, 120, 99, 111, 114, 101, 57, 102, 208, 44,
- ]);
- const decoder = create_zstd_stream_decoder();
- try {
- const first = decompress_zstd_stream_chunk(decoder, compressed.slice(0, 8));
- const second = decompress_zstd_stream_chunk(decoder, compressed.slice(8));
- const decoded = new Uint8Array(first.length + second.length);
- decoded.set(first, 0);
- decoded.set(second, first.length);
- expect(new TextDecoder().decode(decoded)).toBe('hello from libfluxcore');
- } finally {
- free_zstd_stream_decoder(decoder);
- }
- });
-});
diff --git a/fluxer_app/src/features/platform/utils/scroll_manager/shared.test.ts b/fluxer_app/src/features/platform/utils/scroll_manager/shared.test.ts
deleted file mode 100644
index 29f872192..000000000
--- a/fluxer_app/src/features/platform/utils/scroll_manager/shared.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- CENTRE_ALIGNMENT_LIFT,
- InitialScrollIntent,
- MESSAGE_REVEAL_PADDING,
- resolveContainerResizeShift,
- resolveInitialScrollIntent,
- type ScrollerState,
- shouldAnimateMessageJump,
-} from '@app/features/platform/utils/scroll_manager/shared';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {JumpTypes} from '@fluxer/constants/src/JumpConstants';
-import {NEW_MESSAGES_BAR_BUFFER} from '@fluxer/constants/src/LimitConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('the scroll geometry constants', () => {
- it('lifts a centred node by exactly eight pixels', () => {
- expect(CENTRE_ALIGNMENT_LIFT).toBe(8);
- });
-
- it('keeps the two centre paddings distinct, with the unread buffer the larger of the two', () => {
- expect(MESSAGE_REVEAL_PADDING).toBe(16);
- expect(NEW_MESSAGES_BAR_BUFFER).toBe(32);
- expect(NEW_MESSAGES_BAR_BUFFER).toBeGreaterThan(MESSAGE_REVEAL_PADDING);
- });
-});
-
-describe('shouldAnimateMessageJump', () => {
- it('animates only for explicit ANIMATED jumps', () => {
- expect(shouldAnimateMessageJump(JumpTypes.ANIMATED)).toBe(true);
- expect(shouldAnimateMessageJump(JumpTypes.INSTANT)).toBe(false);
- expect(shouldAnimateMessageJump(JumpTypes.NONE)).toBe(false);
- });
-});
-
-describe('resolveContainerResizeShift', () => {
- const state = (scrollTop: number, offsetHeight: number, scrollHeight: number): ScrollerState => ({
- scrollTop,
- offsetHeight,
- scrollHeight,
- });
- const resolve = (
- heightDelta: number,
- scrollerState: ScrollerState,
- overrides?: {isPinned?: boolean; editIsActive?: boolean},
- ) =>
- resolveContainerResizeShift({
- heightDelta,
- isPinned: overrides?.isPinned ?? false,
- editIsActive: overrides?.editIsActive ?? false,
- state: scrollerState,
- });
-
- it('does nothing when the container height is unchanged', () => {
- expect(resolve(0, state(500, 400, 2000), {isPinned: true})).toEqual({kind: 'none'});
- });
-
- it('re-pins to the bottom when pinned, regardless of edit state or direction', () => {
- expect(resolve(40, state(1600, 400, 2000), {isPinned: true})).toEqual({kind: 'pin'});
- expect(resolve(-40, state(1600, 400, 2000), {isPinned: true})).toEqual({kind: 'pin'});
- expect(resolve(40, state(1600, 400, 2000), {isPinned: true, editIsActive: true})).toEqual({kind: 'pin'});
- });
-
- it('does nothing while an inline edit is active and not pinned', () => {
- expect(resolve(40, state(1590, 400, 2000), {editIsActive: true})).toEqual({kind: 'none'});
- });
-
- it('shifts by the delta when near the bottom so the bottom edge stays stable', () => {
- expect(resolve(40, state(1540, 400, 2000))).toEqual({kind: 'shift', targetScrollTop: 1580});
- expect(resolve(-40, state(1590, 400, 2040))).toEqual({kind: 'shift', targetScrollTop: 1550});
- });
-
- it('clamps the shifted target into the scrollable range', () => {
- expect(resolve(100, state(1590, 400, 2000))).toEqual({kind: 'shift', targetScrollTop: 1600});
- expect(resolve(-100, state(30, 400, 480))).toEqual({kind: 'shift', targetScrollTop: 0});
- });
-
- it('does nothing when far from the bottom', () => {
- expect(resolve(40, state(100, 400, 2000))).toEqual({kind: 'none'});
- expect(resolve(-40, state(100, 400, 2000))).toEqual({kind: 'none'});
- });
-
- it('widens the stick threshold for large deltas', () => {
- expect(resolve(200, state(1400, 400, 2000))).toEqual({kind: 'shift', targetScrollTop: 1600});
- expect(resolve(10, state(1400, 400, 2000))).toEqual({kind: 'none'});
- });
-});
-
-describe('resolveInitialScrollIntent', () => {
- it('anchors to the unread boundary only when the divider is expected on screen', () => {
- expect(
- resolveInitialScrollIntent({
- channelType: ChannelTypes.GUILD_TEXT,
- rememberedScrollTop: 900,
- hasPendingUnreads: true,
- }),
- ).toBe(InitialScrollIntent.UNREAD_BOUNDARY);
- expect(
- resolveInitialScrollIntent({
- channelType: ChannelTypes.GUILD_TEXT,
- rememberedScrollTop: 900,
- hasPendingUnreads: false,
- }),
- ).toBe(InitialScrollIntent.SAVED_OFFSET);
- });
-
- it('falls back to the bottom rather than the top when there is no unread boundary and no saved offset', () => {
- expect(
- resolveInitialScrollIntent({
- channelType: ChannelTypes.GUILD_TEXT,
- rememberedScrollTop: null,
- hasPendingUnreads: false,
- }),
- ).toBe(InitialScrollIntent.BOTTOM);
- });
-
- it('never anchors to the unread boundary in voice channels', () => {
- expect(
- resolveInitialScrollIntent({
- channelType: ChannelTypes.GUILD_VOICE,
- rememberedScrollTop: null,
- hasPendingUnreads: true,
- }),
- ).toBe(InitialScrollIntent.BOTTOM);
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/ReadStatesAckBatching.test.ts b/fluxer_app/src/features/read_state/state/ReadStatesAckBatching.test.ts
deleted file mode 100644
index edf503990..000000000
--- a/fluxer_app/src/features/read_state/state/ReadStatesAckBatching.test.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Endpoints} from '@app/features/app/constants/Endpoints';
-import {Channel} from '@app/features/channel/models/Channel';
-import {ACK_BATCH_DELAY_MS, type GatewayReadState} from '@app/features/read_state/state/read_states/shared';
-import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {Channel as WireChannel} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import type {Message as WireMessage} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import type {UserPartial} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const channels = new Map<string, Channel>();
-const guilds = new Map<string, {joinedAt: string | null}>();
-let pinnedToEnd = false;
-let automaticAck = false;
-const loadedMessages: Array<{id: string; author: {id: string}}> = [];
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => channels.get(id)},
-}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {
- getMessages: () => ({
- get hasMoreBefore() {
- return false;
- },
- get length() {
- return loadedMessages.length;
- },
- jumpDestinationId: null,
- hasNewestMessages: () => true,
- has: (id: string) => loadedMessages.some((m) => m.id === id),
- last: () => loadedMessages[loadedMessages.length - 1],
- forEachBuffered: (cb: (m: unknown) => void) => {
- for (const m of loadedMessages) cb(m);
- },
- }),
- },
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getCurrentUser: () => ({id: 'me'}), cacheUsers: () => {}},
-}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: (id: string) => guilds.get(id)}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => null}}));
-vi.mock('@app/features/user/state/UserGuildSettings', () => ({
- default: {
- isEveryoneMentionSuppressed: () => false,
- isRoleMentionSuppressed: () => false,
- isGuildOrChannelMuted: () => false,
- },
-}));
-vi.mock('@app/features/ui/state/Dimension', () => ({default: {channelPinnedToEnd: () => pinnedToEnd}}));
-vi.mock('@app/features/notification/state/NotificationAutoAck', () => ({
- default: {isAutomaticAckEnabled: () => automaticAck, disableForChannel: () => {}},
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {post: vi.fn(async () => ({body: {read_states: []}})), get: vi.fn()},
-}));
-
-const {default: ReadStates} = await import('@app/features/read_state/state/ReadStates');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-
-const CHANNEL = '1485064866382176262';
-const MESSAGE = {
- acked: '1547700000000000000',
- unread: '1547743000000000000',
-};
-
-function user(id: string): UserPartial {
- return {id, username: id, discriminator: '0', global_name: null, avatar: null, avatar_color: null, flags: 0};
-}
-
-function guildText(lastMessageId: string): WireChannel {
- return {id: CHANNEL, type: ChannelTypes.GUILD_TEXT, guild_id: 'guild-1', last_message_id: lastMessageId};
-}
-
-function readState(ackMessageId: string): GatewayReadState {
- return {id: CHANNEL, last_message_id: ackMessageId, mention_count: 0, version: '1'};
-}
-
-function ready(): void {
- channels.clear();
- channels.set(CHANNEL, new Channel(guildText(MESSAGE.unread)));
- ReadStates.handleGatewayReady({readState: [readState(MESSAGE.acked)], channels: [guildText(MESSAGE.unread)]});
-}
-
-function wireMessage(id: string, authorId: string): WireMessage {
- return {
- id,
- channel_id: CHANNEL,
- author: user(authorId),
- type: MessageTypes.DEFAULT,
- flags: 0,
- pinned: false,
- tts: false,
- mention_everyone: false,
- content: 'test',
- timestamp: '2026-09-11T00:00:00.000Z',
- mentions: [],
- mention_roles: [],
- } as unknown as WireMessage;
-}
-
-function openChannel(): void {
- loadedMessages.push({id: MESSAGE.unread, author: {id: 'tuna'}});
- ReadStates.handleLoadMessages({channelId: CHANNEL, isAfter: false, messages: [{id: MESSAGE.unread}] as never});
- pinnedToEnd = true;
- automaticAck = true;
- ReadStates.handleChannelAckWithStickyUnread({channelId: CHANNEL});
-}
-
-describe('ReadStates ack batching', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- loadedMessages.length = 0;
- pinnedToEnd = false;
- automaticAck = false;
- vi.mocked(http.post).mockClear();
- });
-
- afterEach(() => {
- ReadStates.clearAll();
- vi.useRealTimers();
- });
-
- it('sends the ack one batch delay after a quiet channel is read', async () => {
- ready();
- expect(ReadStates.hasUnread(CHANNEL)).toBe(true);
- openChannel();
- expect(ReadStates.hasUnread(CHANNEL)).toBe(false);
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS - 1);
- expect(http.post).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(1);
- expect(http.post).toHaveBeenCalledWith(Endpoints.READ_STATES_ACK, {
- body: {read_states: [{channel_id: CHANNEL, message_id: MESSAGE.unread}]},
- });
- });
-
- it('keeps the batch window anchored to the first ack while messages keep arriving', async () => {
- ready();
- openChannel();
- let messageId = 1547743900000000000n;
- for (let i = 0; i < 3; i++) {
- await vi.advanceTimersByTimeAsync(900);
- messageId += 1000000n;
- ReadStates.handleIncomingMessage({channelId: CHANNEL, message: wireMessage(messageId.toString(), 'tuna')});
- }
- expect(http.post).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS - 2700);
- expect(http.post).toHaveBeenCalledTimes(1);
- expect(http.post).toHaveBeenCalledWith(Endpoints.READ_STATES_ACK, {
- body: {read_states: [{channel_id: CHANNEL, message_id: messageId.toString()}]},
- });
- });
-
- it('keeps acking a channel read for a long stretch of steady traffic', async () => {
- ready();
- openChannel();
- let messageId = 1547743900000000000n;
- for (let i = 0; i < 22; i++) {
- await vi.advanceTimersByTimeAsync(900);
- messageId += 1000000n;
- ReadStates.handleIncomingMessage({channelId: CHANNEL, message: wireMessage(messageId.toString(), 'tuna')});
- }
- expect(vi.mocked(http.post).mock.calls.length).toBeGreaterThanOrEqual(3);
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/ReadStatesDeletedTailMessage.test.ts b/fluxer_app/src/features/read_state/state/ReadStatesDeletedTailMessage.test.ts
deleted file mode 100644
index 906b09789..000000000
--- a/fluxer_app/src/features/read_state/state/ReadStatesDeletedTailMessage.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Endpoints} from '@app/features/app/constants/Endpoints';
-import {Channel} from '@app/features/channel/models/Channel';
-import {ACK_BATCH_DELAY_MS, type GatewayReadState} from '@app/features/read_state/state/read_states/shared';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {Channel as WireChannel} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const channels = new Map<string, Channel>();
-const guilds = new Map<string, {joinedAt: string | null}>();
-let pinnedToEnd = false;
-let automaticAck = false;
-let hasNewest = true;
-const loadedMessages: Array<{id: string; author: {id: string}}> = [];
-
-vi.mock('@app/features/app/state/RuntimeConfig', () => ({default: {localInstanceDomain: 'fluxer.test'}}));
-vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: (id: string) => channels.get(id)}}));
-vi.mock('@app/features/messaging/state/MessagingMessages', () => ({
- default: {
- getMessages: () => ({
- get hasMoreBefore() {
- return false;
- },
- get length() {
- return loadedMessages.length;
- },
- jumpDestinationId: null,
- hasNewestMessages: () => hasNewest,
- has: (id: string) => loadedMessages.some((m) => m.id === id),
- last: () => loadedMessages[loadedMessages.length - 1],
- forEachBuffered: (cb: (m: unknown) => void) => {
- for (const m of loadedMessages) cb(m);
- },
- }),
- },
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getCurrentUser: () => ({id: 'me'}), cacheUsers: () => {}},
-}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/guild/state/Guilds', () => ({default: {getGuild: (id: string) => guilds.get(id)}}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => null}}));
-vi.mock('@app/features/user/state/UserGuildSettings', () => ({
- default: {
- isEveryoneMentionSuppressed: () => false,
- isRoleMentionSuppressed: () => false,
- isGuildOrChannelMuted: () => false,
- },
-}));
-vi.mock('@app/features/ui/state/Dimension', () => ({default: {channelPinnedToEnd: () => pinnedToEnd}}));
-vi.mock('@app/features/notification/state/NotificationAutoAck', () => ({
- default: {isAutomaticAckEnabled: () => automaticAck, disableForChannel: () => {}},
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({
- http: {post: vi.fn(async () => ({body: {read_states: []}})), get: vi.fn()},
-}));
-
-const {default: ReadStates} = await import('@app/features/read_state/state/ReadStates');
-const {http} = await import('@app/features/platform/transport/RestTransport');
-
-const CHANNEL = '1431490439357088063';
-const PHANTOM = '1547836192152621056';
-const REAL = '1546984669772255232';
-const OLD_ACK = '1546000000000000000';
-
-function guildText(lastMessageId: string): WireChannel {
- return {id: CHANNEL, type: ChannelTypes.GUILD_TEXT, guild_id: '1431490056488128806', last_message_id: lastMessageId};
-}
-
-function readState(ackMessageId: string): GatewayReadState {
- return {id: CHANNEL, last_message_id: ackMessageId, mention_count: 0, version: '1'};
-}
-
-function ready(ackMessageId: string): void {
- channels.clear();
- channels.set(CHANNEL, new Channel(guildText(PHANTOM)));
- ReadStates.handleGatewayReady({readState: [readState(ackMessageId)], channels: [guildText(PHANTOM)]});
-}
-
-function lastAckedMessageId(): string | null {
- const calls = vi.mocked(http.post).mock.calls;
- if (calls.length === 0) return null;
- const body = calls[calls.length - 1][1] as {body: {read_states: Array<{message_id: string}>}};
- return body.body.read_states[0].message_id;
-}
-
-describe('channel whose newest message was deleted', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- loadedMessages.length = 0;
- pinnedToEnd = false;
- automaticAck = false;
- hasNewest = true;
- vi.mocked(http.post).mockClear();
- });
-
- afterEach(() => {
- ReadStates.clearAll();
- vi.useRealTimers();
- });
-
- it('acks up to the channel watermark rather than the newest surviving message', async () => {
- ready(OLD_ACK);
- expect(ReadStates.hasUnread(CHANNEL)).toBe(true);
- loadedMessages.push({id: REAL, author: {id: 'tuna'}});
- ReadStates.handleLoadMessages({channelId: CHANNEL, isAfter: false, messages: [{id: REAL}] as never});
- ReadStates.handleLoadMessages({channelId: CHANNEL, isAfter: true, messages: []});
- expect(ReadStates.lastMessageId(CHANNEL)).toBe(PHANTOM);
- pinnedToEnd = true;
- automaticAck = true;
- ReadStates.handleChannelAckWithStickyUnread({channelId: CHANNEL});
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS);
- expect(http.post).toHaveBeenCalledWith(Endpoints.READ_STATES_ACK, {
- body: {read_states: [{channel_id: CHANNEL, message_id: PHANTOM}]},
- });
- expect(ReadStates.hasUnread(CHANNEL)).toBe(false);
- });
-
- it('stays read after a reload', async () => {
- ready(OLD_ACK);
- loadedMessages.push({id: REAL, author: {id: 'tuna'}});
- ReadStates.handleLoadMessages({channelId: CHANNEL, isAfter: false, messages: [{id: REAL}] as never});
- ReadStates.handleLoadMessages({channelId: CHANNEL, isAfter: true, messages: []});
- pinnedToEnd = true;
- automaticAck = true;
- ReadStates.handleChannelAckWithStickyUnread({channelId: CHANNEL});
- await vi.advanceTimersByTimeAsync(ACK_BATCH_DELAY_MS);
- const acked = lastAckedMessageId();
- expect(acked).not.toBeNull();
- ReadStates.clearAll();
- ready(acked as string);
- expect(ReadStates.hasUnread(CHANNEL)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateAckMachine.test.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateAckMachine.test.ts
deleted file mode 100644
index 84ef8cb1d..000000000
--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateAckMachine.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReadStateAckSnapshot,
- type ReadStateAckInput,
- resolveReadStateAckDecision,
- selectReadStateAckDecision,
- transitionReadStateAckSnapshot,
-} from '@app/features/read_state/state/read_states/ReadStateAckMachine';
-import {fromTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';
-import {describe, expect, it} from 'vitest';
-
-const BASE_TIMESTAMP = Date.UTC(2024, 0, 1);
-const OLDER_ID = fromTimestamp(BASE_TIMESTAMP + 1000);
-const ACK_ID = fromTimestamp(BASE_TIMESTAMP + 2000);
-const NEWER_ID = fromTimestamp(BASE_TIMESTAMP + 3000);
-
-function input(overrides: Partial<ReadStateAckInput> = {}): ReadStateAckInput {
- return {
- requestedMessageId: NEWER_ID,
- lastMessageId: NEWER_ID,
- ackMessageId: ACK_ID,
- ackedManually: false,
- messagesLoaded: true,
- supportsUnreadTracking: true,
- hasMentions: false,
- hasOldestUnreadMessage: false,
- hasStickyUnreadMessage: false,
- local: false,
- force: false,
- isExplicitUserAction: false,
- preserveStickyUnread: false,
- ...overrides,
- };
-}
-
-describe('readStateAckMachine', () => {
- it('allows a loaded tracked channel to acknowledge the requested message', () => {
- expect(resolveReadStateAckDecision(input({hasMentions: true}))).toEqual({
- type: 'ack',
- messageId: NEWER_ID,
- hadMentions: true,
- shouldPreserveStickyUnread: false,
- shouldClearManualAck: false,
- });
- });
-
- it('falls back to the last message when no requested message is provided', () => {
- expect(resolveReadStateAckDecision(input({requestedMessageId: null, lastMessageId: NEWER_ID}))).toMatchObject({
- type: 'ack',
- messageId: NEWER_ID,
- });
- });
-
- it('blocks automatic ack while manual ack is held, messages are unloaded, or the channel is untracked', () => {
- expect(resolveReadStateAckDecision(input({ackedManually: true}))).toEqual({
- type: 'ignored',
- reason: 'manualAck',
- });
- expect(resolveReadStateAckDecision(input({messagesLoaded: false}))).toEqual({
- type: 'ignored',
- reason: 'notLoaded',
- });
- expect(resolveReadStateAckDecision(input({supportsUnreadTracking: false}))).toEqual({
- type: 'ignored',
- reason: 'untracked',
- });
- });
-
- it('lets local, forced, and explicit user acknowledgements override automatic ack guards', () => {
- expect(resolveReadStateAckDecision(input({ackedManually: true, isExplicitUserAction: true}))).toMatchObject({
- type: 'ack',
- shouldClearManualAck: true,
- });
- expect(resolveReadStateAckDecision(input({messagesLoaded: false, local: true}))).toMatchObject({
- type: 'ack',
- shouldClearManualAck: true,
- });
- expect(resolveReadStateAckDecision(input({supportsUnreadTracking: false, force: true}))).toMatchObject({
- type: 'ack',
- shouldClearManualAck: true,
- });
- });
-
- it('rejects missing and older message acknowledgements unless forced', () => {
- expect(resolveReadStateAckDecision(input({requestedMessageId: null, lastMessageId: null}))).toEqual({
- type: 'ignored',
- reason: 'missingMessage',
- });
- expect(resolveReadStateAckDecision(input({requestedMessageId: OLDER_ID}))).toEqual({
- type: 'ignored',
- reason: 'olderThanCurrentAck',
- });
- expect(resolveReadStateAckDecision(input({requestedMessageId: OLDER_ID, force: true}))).toMatchObject({
- type: 'ack',
- messageId: OLDER_ID,
- });
- });
-
- it('preserves sticky unread only when requested and no sticky unread already exists', () => {
- expect(
- resolveReadStateAckDecision(
- input({
- preserveStickyUnread: true,
- hasOldestUnreadMessage: true,
- hasStickyUnreadMessage: false,
- }),
- ),
- ).toMatchObject({
- type: 'ack',
- shouldPreserveStickyUnread: true,
- });
- expect(
- resolveReadStateAckDecision(
- input({
- preserveStickyUnread: true,
- hasOldestUnreadMessage: true,
- hasStickyUnreadMessage: true,
- }),
- ),
- ).toMatchObject({
- type: 'ack',
- shouldPreserveStickyUnread: false,
- });
- });
-
- it('updates the decision from later ack input', () => {
- const ignoredSnapshot = createReadStateAckSnapshot(input({ackedManually: true}));
- expect(selectReadStateAckDecision(ignoredSnapshot)).toEqual({type: 'ignored', reason: 'manualAck'});
-
- const ackSnapshot = transitionReadStateAckSnapshot(ignoredSnapshot, {
- type: 'readStateAck.updated',
- input: input({ackedManually: false}),
- });
-
- expect(selectReadStateAckDecision(ackSnapshot)).toMatchObject({
- type: 'ack',
- messageId: NEWER_ID,
- });
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateEntryStatusMachine.test.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateEntryStatusMachine.test.ts
deleted file mode 100644
index db8f0b344..000000000
--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateEntryStatusMachine.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReadStateEntryStatusSnapshot,
- type ReadStateEntryStatusInput,
- type ReadStateEntryStatusValue,
- resolveReadStateEntryStatus,
- selectReadStateEntryStatusModel,
- transitionReadStateEntryStatusSnapshot,
-} from '@app/features/read_state/state/read_states/ReadStateEntryStatusMachine';
-import {fromTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';
-import {describe, expect, it} from 'vitest';
-
-const BASE_TIMESTAMP = Date.UTC(2024, 0, 1);
-const ACK_ID = fromTimestamp(BASE_TIMESTAMP + 1000);
-const LAST_ID = fromTimestamp(BASE_TIMESTAMP + 2000);
-const ACK_TS = BASE_TIMESTAMP + 1000;
-const LAST_TS = BASE_TIMESTAMP + 2000;
-
-function input(overrides: Partial<ReadStateEntryStatusInput> = {}): ReadStateEntryStatusInput {
- return {
- supportsUnreadTracking: true,
- hasBlockedDirectMessageRecipient: false,
- lastMessageId: LAST_ID,
- ackMessageId: LAST_ID,
- ackTimestamp: LAST_TS,
- lastMessageTimestamp: LAST_TS,
- mentionCount: 0,
- ...overrides,
- };
-}
-
-function expectResolvedState(overrides: Partial<ReadStateEntryStatusInput>, expected: ReadStateEntryStatusValue): void {
- expect(resolveReadStateEntryStatus(input(overrides)).state).toBe(expected);
-}
-
-describe('readStateEntryStatusMachine', () => {
- it('routes the read-state status by priority', () => {
- expectResolvedState({supportsUnreadTracking: false, mentionCount: 1, ackMessageId: ACK_ID}, 'untracked');
- expectResolvedState({hasBlockedDirectMessageRecipient: true, mentionCount: 1, ackMessageId: ACK_ID}, 'blocked');
- expectResolvedState({lastMessageId: null, ackMessageId: ACK_ID}, 'read');
- expectResolvedState({ackMessageId: null, ackTimestamp: ACK_TS}, 'unread');
- expectResolvedState({ackMessageId: null, ackTimestamp: LAST_TS}, 'read');
- expectResolvedState({ackMessageId: ACK_ID}, 'unread');
- expectResolvedState({ackMessageId: LAST_ID}, 'read');
- });
-
- it('derives unread and mention capabilities from the routed state', () => {
- expect(resolveReadStateEntryStatus(input({ackMessageId: ACK_ID, mentionCount: 2}))).toMatchObject({
- state: 'unread',
- canBeUnread: true,
- supportsMentions: true,
- hasUnread: true,
- hasMentions: true,
- isUnreadOrMentioned: true,
- });
- expect(resolveReadStateEntryStatus(input({hasBlockedDirectMessageRecipient: true, mentionCount: 2}))).toMatchObject(
- {
- state: 'blocked',
- canBeUnread: true,
- supportsMentions: false,
- hasUnread: false,
- hasMentions: true,
- isUnreadOrMentioned: false,
- },
- );
- expect(resolveReadStateEntryStatus(input({supportsUnreadTracking: false, mentionCount: 2}))).toMatchObject({
- state: 'untracked',
- canBeUnread: false,
- supportsMentions: false,
- hasUnread: false,
- hasMentions: true,
- isUnreadOrMentioned: false,
- });
- });
-
- it('re-routes when entry inputs change', () => {
- const readSnapshot = createReadStateEntryStatusSnapshot(input());
- expect(selectReadStateEntryStatusModel(readSnapshot).state).toBe('read');
-
- const unreadSnapshot = transitionReadStateEntryStatusSnapshot(readSnapshot, {
- type: 'readStateEntry.updated',
- input: input({ackMessageId: ACK_ID, mentionCount: 1}),
- });
-
- expect(selectReadStateEntryStatusModel(unreadSnapshot)).toMatchObject({
- state: 'unread',
- isUnreadOrMentioned: true,
- });
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.test.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.test.ts
deleted file mode 100644
index aae1a9cd6..000000000
--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateIncomingMessageMachine.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReadStateIncomingMessageSnapshot,
- type ReadStateIncomingMessageInput,
- resolveReadStateIncomingMessageDecision,
- selectReadStateIncomingMessageDecision,
- transitionReadStateIncomingMessageSnapshot,
-} from '@app/features/read_state/state/read_states/ReadStateIncomingMessageMachine';
-import {fromTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';
-import {describe, expect, it} from 'vitest';
-
-const BASE_TIMESTAMP = Date.UTC(2024, 0, 1);
-const PREVIOUS_ID = fromTimestamp(BASE_TIMESTAMP + 1000);
-const ACK_ID = fromTimestamp(BASE_TIMESTAMP + 2000);
-const MESSAGE_ID = fromTimestamp(BASE_TIMESTAMP + 3000);
-
-function input(overrides: Partial<ReadStateIncomingMessageInput> = {}): ReadStateIncomingMessageInput {
- return {
- isCurrentUserAuthor: false,
- automaticAckEnabled: false,
- isAtBottom: false,
- authorBlocked: false,
- hadUnreadOrMentions: false,
- messageId: MESSAGE_ID,
- ackMessageId: ACK_ID,
- coveredByLastMessage: false,
- ...overrides,
- };
-}
-
-describe('readStateIncomingMessageMachine', () => {
- it('prioritizes current-user and automatic acknowledgements before unread recording', () => {
- expect(
- resolveReadStateIncomingMessageDecision(
- input({
- isCurrentUserAuthor: true,
- automaticAckEnabled: true,
- isAtBottom: true,
- authorBlocked: true,
- }),
- ),
- ).toEqual({type: 'ackCurrentUserMessage'});
- expect(resolveReadStateIncomingMessageDecision(input({automaticAckEnabled: true, isAtBottom: true}))).toEqual({
- type: 'ackAutomaticMessage',
- });
- });
-
- it('handles blocked authors without disturbing existing unread state', () => {
- expect(resolveReadStateIncomingMessageDecision(input({authorBlocked: true, hadUnreadOrMentions: false}))).toEqual({
- type: 'ackBlockedMessage',
- });
- expect(resolveReadStateIncomingMessageDecision(input({authorBlocked: true, hadUnreadOrMentions: true}))).toEqual({
- type: 'ignoreBlockedMessage',
- });
- });
-
- it('treats known and unknown read-state acknowledgements as coverage', () => {
- expect(resolveReadStateIncomingMessageDecision(input({messageId: ACK_ID, ackMessageId: ACK_ID}))).toEqual({
- type: 'coveredByAck',
- });
- expect(
- resolveReadStateIncomingMessageDecision(
- input({
- messageId: PREVIOUS_ID,
- ackMessageId: null,
- }),
- ),
- ).toEqual({type: 'recordUnread', coveredByLastMessage: false});
- });
-
- it('records unread and reports whether the message is already covered by the watermark', () => {
- expect(resolveReadStateIncomingMessageDecision(input())).toEqual({
- type: 'recordUnread',
- coveredByLastMessage: false,
- });
- expect(resolveReadStateIncomingMessageDecision(input({coveredByLastMessage: true}))).toEqual({
- type: 'recordUnread',
- coveredByLastMessage: true,
- });
- });
-
- it('updates the decision from later message input', () => {
- const unreadSnapshot = createReadStateIncomingMessageSnapshot(input());
- expect(selectReadStateIncomingMessageDecision(unreadSnapshot)).toEqual({
- type: 'recordUnread',
- coveredByLastMessage: false,
- });
-
- const autoAckSnapshot = transitionReadStateIncomingMessageSnapshot(unreadSnapshot, {
- type: 'incomingMessage.updated',
- input: input({automaticAckEnabled: true, isAtBottom: true}),
- });
-
- expect(selectReadStateIncomingMessageDecision(autoAckSnapshot)).toEqual({type: 'ackAutomaticMessage'});
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateMentionMachine.test.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateMentionMachine.test.ts
deleted file mode 100644
index 0677935dc..000000000
--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateMentionMachine.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReadStateMentionSnapshot,
- type ReadStateMentionInput,
- type ReadStateMentionReason,
- resolveReadStateMention,
- selectReadStateMentionModel,
- transitionReadStateMentionSnapshot,
-} from '@app/features/read_state/state/read_states/ReadStateMentionMachine';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<ReadStateMentionInput> = {}): ReadStateMentionInput {
- return {
- authorBlocked: false,
- hasUserMention: false,
- hasEveryoneMention: false,
- hasRoleMention: false,
- isPrivate: false,
- isMuted: false,
- ...overrides,
- };
-}
-
-const mentionCases: Array<[Partial<ReadStateMentionInput>, ReadStateMentionReason, boolean]> = [
- [{authorBlocked: true, hasUserMention: true}, 'blocked', false],
- [{hasUserMention: true, hasEveryoneMention: true}, 'user', true],
- [{hasEveryoneMention: true, hasRoleMention: true}, 'everyone', true],
- [{hasRoleMention: true}, 'role', true],
- [{isPrivate: true, isMuted: false}, 'private', true],
- [{isPrivate: true, isMuted: true}, 'none', false],
- [{}, 'none', false],
-];
-
-describe('readStateMentionMachine', () => {
- it.each(mentionCases)('routes %# to %s', (overrides, reason, shouldMention) => {
- expect(resolveReadStateMention(input(overrides))).toEqual({reason, shouldMention});
- });
-
- it('updates the mention reason from later input', () => {
- const noneSnapshot = createReadStateMentionSnapshot(input());
- expect(selectReadStateMentionModel(noneSnapshot)).toEqual({reason: 'none', shouldMention: false});
-
- const roleSnapshot = transitionReadStateMentionSnapshot(noneSnapshot, {
- type: 'readStateMention.updated',
- input: input({hasRoleMention: true}),
- });
-
- expect(selectReadStateMentionModel(roleSnapshot)).toEqual({reason: 'role', shouldMention: true});
- });
-});
diff --git a/fluxer_app/src/features/read_state/state/read_states/ReadStateServerAckMachine.test.ts b/fluxer_app/src/features/read_state/state/read_states/ReadStateServerAckMachine.test.ts
deleted file mode 100644
index 401511c1f..000000000
--- a/fluxer_app/src/features/read_state/state/read_states/ReadStateServerAckMachine.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createReadStateServerAckSnapshot,
- type ReadStateServerAckInput,
- resolveReadStateServerAckDecision,
- selectReadStateServerAckDecision,
- transitionReadStateServerAckSnapshot,
-} from '@app/features/read_state/state/read_states/ReadStateServerAckMachine';
-import {fromTimestamp} from '@fluxer/snowflake/src/SnowflakeUtils';
-import {describe, expect, it} from 'vitest';
-
-const BASE_TIMESTAMP = Date.UTC(2024, 0, 1);
-const OLDER_ID = fromTimestamp(BASE_TIMESTAMP + 1000);
-const ACK_ID = fromTimestamp(BASE_TIMESTAMP + 2000);
-const NEWER_ID = fromTimestamp(BASE_TIMESTAMP + 3000);
-
-function input(overrides: Partial<ReadStateServerAckInput> = {}): ReadStateServerAckInput {
- return {
- messageId: NEWER_ID,
- ackMessageId: ACK_ID,
- version: '3',
- serverVersion: '2',
- manual: false,
- readStateWasKnown: true,
- hasMentionCount: false,
- ...overrides,
- };
-}
-
-describe('readStateServerAckMachine', () => {
- it('ignores stale versions before applying any other server ack policy', () => {
- expect(resolveReadStateServerAckDecision(input({version: '1', manual: true}))).toEqual({
- type: 'ignoreStaleVersion',
- });
- });
-
- it('routes manual server acknowledgements separately', () => {
- expect(resolveReadStateServerAckDecision(input({manual: true}))).toEqual({type: 'applyManualAck'});
- });
-
- it('marks older automatic acknowledgements as read-state-known without advancing ack state', () => {
- expect(resolveReadStateServerAckDecision(input({messageId: OLDER_ID}))).toEqual({
- type: 'ignoreOlderMessage',
- shouldMarkReadStateKnown: true,
- });
- });
-
- it('refreshes an existing ack only when read-state knowledge or mention count changes', () => {
- expect(
- resolveReadStateServerAckDecision(
- input({
- messageId: ACK_ID,
- readStateWasKnown: true,
- hasMentionCount: false,
- }),
- ),
- ).toEqual({
- type: 'refreshCurrentAck',
- shouldMarkReadStateKnown: true,
- shouldUpdateMentionCount: false,
- shouldRefreshUnreadEstimate: false,
- shouldNotify: false,
- });
- expect(
- resolveReadStateServerAckDecision(
- input({
- messageId: ACK_ID,
- readStateWasKnown: false,
- hasMentionCount: true,
- }),
- ),
- ).toEqual({
- type: 'refreshCurrentAck',
- shouldMarkReadStateKnown: true,
- shouldUpdateMentionCount: true,
- shouldRefreshUnreadEstimate: true,
- shouldNotify: true,
- });
- });
-
- it('advances newer automatic acknowledgements and carries mention update intent', () => {
- expect(resolveReadStateServerAckDecision(input({messageId: NEWER_ID, hasMentionCount: true}))).toEqual({
- type: 'advanceAck',
- shouldMarkReadStateKnown: true,
- shouldUpdateMentionCount: true,
- });
- });
-
- it('updates the decision from later server ack input', () => {
- const olderSnapshot = createReadStateServerAckSnapshot(input({messageId: OLDER_ID}));
- expect(selectReadStateServerAckDecision(olderSnapshot)).toEqual({
- type: 'ignoreOlderMessage',
- shouldMarkReadStateKnown: true,
- });
-
- const newerSnapshot = transitionReadStateServerAckSnapshot(olderSnapshot, {
- type: 'readStateServerAck.updated',
- input: input({messageId: NEWER_ID}),
- });
-
- expect(selectReadStateServerAckDecision(newerSnapshot)).toEqual({
- type: 'advanceAck',
- shouldMarkReadStateKnown: true,
- shouldUpdateMentionCount: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/read_state/utils/AutoAckPredicate.test.ts b/fluxer_app/src/features/read_state/utils/AutoAckPredicate.test.ts
deleted file mode 100644
index 648b44723..000000000
--- a/fluxer_app/src/features/read_state/utils/AutoAckPredicate.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {shouldAutoAck} from '@app/features/read_state/utils/AutoAckPredicate';
-import {describe, expect, it} from 'vitest';
-
-function conditions(overrides: Partial<Parameters<typeof shouldAutoAck>[0]> = {}): Parameters<typeof shouldAutoAck>[0] {
- return {
- channelActive: true,
- windowFocused: true,
- atBottom: true,
- textChatVisible: true,
- manualAck: false,
- blockingModalOpen: false,
- ...overrides,
- };
-}
-
-describe('shouldAutoAck', () => {
- it('returns true when all positive conditions hold and nothing blocks', () => {
- expect(shouldAutoAck(conditions())).toBe(true);
- });
-
- it('returns false when a blocking modal is open', () => {
- expect(shouldAutoAck(conditions({blockingModalOpen: true}))).toBe(false);
- });
-
- it('returns false when not at the bottom', () => {
- expect(shouldAutoAck(conditions({atBottom: false}))).toBe(false);
- });
-
- it('returns false during manual ack', () => {
- expect(shouldAutoAck(conditions({manualAck: true}))).toBe(false);
- });
-
- it('returns false when the window is not focused', () => {
- expect(shouldAutoAck(conditions({windowFocused: false}))).toBe(false);
- });
-
- it('returns false when the text chat is not visible', () => {
- expect(shouldAutoAck(conditions({textChatVisible: false}))).toBe(false);
- });
-
- it('returns false when the channel is not active', () => {
- expect(shouldAutoAck(conditions({channelActive: false}))).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/search/state/QuickSwitcherSelection.test.ts b/fluxer_app/src/features/search/state/QuickSwitcherSelection.test.ts
deleted file mode 100644
index 2b92e62f1..000000000
--- a/fluxer_app/src/features/search/state/QuickSwitcherSelection.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {hasSameResultIdentity, resolveRecomputedSelectedIndex} from '@app/features/search/state/QuickSwitcherSelection';
-import type {QuickSwitcherResult} from '@app/features/search/state/QuickSwitcherTypes';
-import {QuickSwitcherResultTypes} from '@fluxer/constants/src/QuickSwitcherConstants';
-import {describe, expect, it} from 'vitest';
-
-const result = (type: QuickSwitcherResult['type'], id: string) => ({type, id}) as QuickSwitcherResult;
-
-const labelled = (type: QuickSwitcherResult['type'], id: string, title: string, subtitle?: string) =>
- ({type, id, title, subtitle}) as QuickSwitcherResult;
-
-describe('resolveRecomputedSelectedIndex', () => {
- it('follows the focused result when the list is reordered', () => {
- const previous = result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c3');
- const results = [
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c3'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2'),
- ];
- expect(resolveRecomputedSelectedIndex(previous, results, 0)).toBe(0);
- });
-
- it('keeps the focused result when entries are inserted above it', () => {
- const previous = result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2');
- const results = [
- result(QuickSwitcherResultTypes.HEADER, 'h1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c9'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2'),
- ];
- expect(resolveRecomputedSelectedIndex(previous, results, 1)).toBe(2);
- });
-
- it('falls back when the focused result disappears', () => {
- const previous = result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'gone');
- const results = [result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1')];
- expect(resolveRecomputedSelectedIndex(previous, results, 0)).toBe(0);
- });
-
- it('does not confuse ids that repeat across result types', () => {
- const previous = result(QuickSwitcherResultTypes.GUILD, '42');
- const results = [result(QuickSwitcherResultTypes.TEXT_CHANNEL, '42'), result(QuickSwitcherResultTypes.GUILD, '42')];
- expect(resolveRecomputedSelectedIndex(previous, results, 0)).toBe(1);
- });
-
- it('uses the fallback when nothing was focused', () => {
- expect(resolveRecomputedSelectedIndex(undefined, [result(QuickSwitcherResultTypes.GUILD, 'g')], 0)).toBe(0);
- });
-});
-
-describe('hasSameResultIdentity', () => {
- it('treats a rebuilt list of the same rows in the same order as unchanged', () => {
- const previous = [
- result(QuickSwitcherResultTypes.HEADER, 'people'),
- result(QuickSwitcherResultTypes.USER, 'u1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- ];
- const next = [
- result(QuickSwitcherResultTypes.HEADER, 'people'),
- result(QuickSwitcherResultTypes.USER, 'u1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- ];
- expect(hasSameResultIdentity(previous, next)).toBe(true);
- });
-
- it('detects a reorder', () => {
- const previous = [
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2'),
- ];
- const next = [
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- ];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('detects an insertion', () => {
- const previous = [result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1')];
- const next = [
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1'),
- result(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c2'),
- ];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('detects a row whose type changed under the same id', () => {
- const previous = [result(QuickSwitcherResultTypes.TEXT_CHANNEL, '42')];
- const next = [result(QuickSwitcherResultTypes.VOICE_CHANNEL, '42')];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('treats two empty lists as unchanged', () => {
- expect(hasSameResultIdentity([], [])).toBe(true);
- });
-
- it('detects a renamed row so the open list repaints', () => {
- const previous = [labelled(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1', 'general')];
- const next = [labelled(QuickSwitcherResultTypes.TEXT_CHANNEL, 'c1', 'general-chat')];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('detects a changed subtitle under an unchanged title', () => {
- const previous = [labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada', 'ada#0001')];
- const next = [labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada', 'ada#0002')];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('detects a subtitle that appeared where there was none', () => {
- const previous = [labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada')];
- const next = [labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada', 'ada#0001')];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('detects a renamed section header', () => {
- const previous = [labelled(QuickSwitcherResultTypes.HEADER, 'people', 'People')];
- const next = [labelled(QuickSwitcherResultTypes.HEADER, 'people', 'Personnes')];
- expect(hasSameResultIdentity(previous, next)).toBe(false);
- });
-
- it('still treats an identically labelled rebuild as unchanged', () => {
- const previous = [
- labelled(QuickSwitcherResultTypes.HEADER, 'people', 'People'),
- labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada', 'ada#0001'),
- ];
- const next = [
- labelled(QuickSwitcherResultTypes.HEADER, 'people', 'People'),
- labelled(QuickSwitcherResultTypes.USER, 'u1', 'ada', 'ada#0001'),
- ];
- expect(hasSameResultIdentity(previous, next)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/search/utils/SearchTextMatching.test.ts b/fluxer_app/src/features/search/utils/SearchTextMatching.test.ts
deleted file mode 100644
index 168171dc4..000000000
--- a/fluxer_app/src/features/search/utils/SearchTextMatching.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildChannelSearchTerms,
- consumeBestSearchTerm,
- createSearchTerm,
- escapeSearchPattern,
- fuzzySearch,
- getLoadedUnicodeConfusables,
- loadUnicodeConfusables,
- scoreSearchTerm,
- stripCombiningMarks,
- toConfusableSkeleton,
-} from '@app/features/search/utils/SearchTextMatching';
-import {describe, expect, it} from 'vitest';
-
-const PATTERN_SPECIAL_CHARACTERS = '-[]/{}()*+?.\\^$|';
-
-describe('escapeSearchPattern', () => {
- it('escapes every regex special character', () => {
- const expected = [...PATTERN_SPECIAL_CHARACTERS].map((character) => `\\${character}`).join('');
- expect(escapeSearchPattern(PATTERN_SPECIAL_CHARACTERS)).toBe(expected);
- });
-
- it('leaves whitespace and other punctuation alone', () => {
- expect(escapeSearchPattern('a b\tc#,!@&')).toBe('a b\tc#,!@&');
- });
-
- it('produces a pattern that matches the literal text', () => {
- const text = `gen (${PATTERN_SPECIAL_CHARACTERS}) chat`;
- expect(new RegExp(`^${escapeSearchPattern(text)}$`).test(text)).toBe(true);
- });
-});
-
-describe('stripCombiningMarks', () => {
- it('removes combining diacritics from precomposed and decomposed text', () => {
- expect(stripCombiningMarks('José')).toBe('Jose');
- expect(stripCombiningMarks('cafe\u{301}')).toBe('cafe');
- });
-
- it('keeps marks outside the combining diacritical block', () => {
- expect(stripCombiningMarks('x\u{483}')).toBe('x\u{483}');
- });
-});
-
-describe('fuzzySearch', () => {
- it('matches an in-order subsequence', () => {
- expect(fuzzySearch('gnrl', 'general')).toBe(true);
- expect(fuzzySearch('lrg', 'general')).toBe(false);
- });
-
- it('requires equality when the lengths match', () => {
- expect(fuzzySearch('gen', 'gen')).toBe(true);
- expect(fuzzySearch('abc', 'abd')).toBe(false);
- });
-
- it('rejects a needle longer than the haystack', () => {
- expect(fuzzySearch('general', 'gen')).toBe(false);
- });
-
- it('is case-sensitive', () => {
- expect(fuzzySearch('G', 'general')).toBe(false);
- });
-
- it('compares UTF-16 code units', () => {
- expect(fuzzySearch('\u{1f600}', 'a\u{1f600}b')).toBe(true);
- });
-});
-
-describe('scoreSearchTerm', () => {
- it('ranks exact, prefix, contains, every word and fuzzy matches', () => {
- expect(scoreSearchTerm('general', createSearchTerm('general'))).toBe(10);
- expect(scoreSearchTerm('general-chat', createSearchTerm('general'))).toBe(7);
- expect(scoreSearchTerm('my-general', createSearchTerm('general'))).toBe(5);
- expect(scoreSearchTerm('general-chat', createSearchTerm('chat general'))).toBe(3);
- expect(scoreSearchTerm('general', createSearchTerm('gnrl'))).toBe(1);
- expect(scoreSearchTerm('general', createSearchTerm('xyz'))).toBe(0);
- });
-
- it('skips the fuzzy tier when fuzzy matching is off', () => {
- expect(scoreSearchTerm('general', createSearchTerm('gnrl'), false)).toBe(0);
- });
-
- it('splits words on commas and spaces', () => {
- expect(scoreSearchTerm('alice and bob', createSearchTerm('bob,alice'))).toBe(3);
- });
-});
-
-describe('buildChannelSearchTerms', () => {
- it('builds one term per word and drops empty tokens', () => {
- const terms = buildChannelSearchTerms('general');
- expect(terms.map((term) => [term.queryLower, term.isFullMatch])).toEqual([['general', false]]);
- });
-
- it('puts a full-phrase term first when the query has a space', () => {
- const terms = buildChannelSearchTerms(' General Chat');
- expect(terms.map((term) => [term.queryLower, term.isFullMatch])).toEqual([
- [' general chat', true],
- ['general', false],
- ['chat', false],
- ]);
- });
-
- it('lets only the first space of the full phrase match a dash', () => {
- const [fullPhrase] = buildChannelSearchTerms('a b c');
- expect(fullPhrase.exactQuery.test('a-b c')).toBe(true);
- expect(fullPhrase.exactQuery.test('a b c')).toBe(true);
- expect(fullPhrase.exactQuery.test('a b-c')).toBe(false);
- });
-});
-
-describe('consumeBestSearchTerm', () => {
- it('removes the winning word term and returns its score', () => {
- const terms = [...buildChannelSearchTerms('chat general')];
- expect(consumeBestSearchTerm('general-chat', terms, true)).toBe(7);
- expect(terms.map((term) => term.queryLower)).toEqual(['chat general', 'chat']);
- });
-
- it('empties the terms when the full phrase wins', () => {
- const terms = [...buildChannelSearchTerms('general chat')];
- expect(consumeBestSearchTerm('general-chat', terms, true)).toBe(7);
- expect(terms).toEqual([]);
- });
-
- it('keeps the terms when nothing matches', () => {
- const terms = [...buildChannelSearchTerms('xyz')];
- expect(consumeBestSearchTerm('general', terms, true)).toBe(0);
- expect(terms).toHaveLength(1);
- });
-});
-
-describe('unicode confusables', () => {
- it('has no table before it loads', () => {
- expect(getLoadedUnicodeConfusables()).toBeNull();
- });
-
- it('loads the full Unicode 15.1 table once', async () => {
- const confusables = await loadUnicodeConfusables();
- expect(confusables.size).toBe(6311);
- expect(await loadUnicodeConfusables()).toBe(confusables);
- expect(getLoadedUnicodeConfusables()).toBe(confusables);
- });
-
- it('maps known look-alikes', async () => {
- const confusables = await loadUnicodeConfusables();
- expect(confusables.get('0')).toBe('O');
- expect(confusables.get('1')).toBe('l');
- expect(confusables.get('I')).toBe('l');
- expect(confusables.get('m')).toBe('rn');
- expect(confusables.get('\u{1d7ce}')).toBe('O');
- });
-
- it('builds lowercase skeletons', async () => {
- const confusables = await loadUnicodeConfusables();
- expect(toConfusableSkeleton('b0b', confusables)).toBe('bob');
- expect(toConfusableSkeleton('Il1|', confusables)).toBe('llll');
- expect(toConfusableSkeleton('mod', confusables)).toBe('rnod');
- });
-
- it('only lowercases and decomposes without a table', () => {
- expect(toConfusableSkeleton('B0B', new Map())).toBe('b0b');
- expect(toConfusableSkeleton('É', new Map())).toBe('e\u{301}');
- });
-});
diff --git a/fluxer_app/src/features/slowmode/state/SlowmodePendingSend.test.ts b/fluxer_app/src/features/slowmode/state/SlowmodePendingSend.test.ts
deleted file mode 100644
index a32a650ff..000000000
--- a/fluxer_app/src/features/slowmode/state/SlowmodePendingSend.test.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolveRetryAfterMs} from '@app/features/messaging/utils/RetryAfterUtils';
-import {HttpError} from '@app/features/platform/types/EndpointError';
-import {Logger} from '@app/features/platform/utils/AppLogger';
-import type {PendingMessageSend} from '@app/features/slowmode/commands/SlowmodeCommands';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface SlowmodeStore {
- clearChannel(channelId: string): void;
- getLastSendTimestamp(channelId: string): number | null;
- getSlowmodeRemaining(channelId: string, rateLimitPerUser: number): number;
-}
-
-interface SlowmodeCommandModule {
- clampSlowmodeRetryAfterMs(retryAfterMs: number | null): number;
- confirmMessageSend(channelId: string, sentAt: string, pending?: PendingMessageSend): void;
- discardPendingMessageSend(channelId: string, pending: PendingMessageSend): void;
- recordPendingMessageSend(channelId: string): PendingMessageSend;
- updateSlowmodeRemaining(channelId: string, retryAfterMs: number): void;
-}
-
-let Slowmode: SlowmodeStore;
-let SlowmodeCommands: SlowmodeCommandModule;
-
-beforeAll(async () => {
- const debug = vi.spyOn(Logger.prototype, 'debug').mockImplementation(() => undefined);
- try {
- const [slowmodeModule, commandModule, persistenceModule] = await Promise.all([
- import('@app/features/slowmode/state/Slowmode'),
- import('@app/features/slowmode/commands/SlowmodeCommands'),
- import('@app/features/platform/utils/MobXPersistence'),
- ]);
- Slowmode = slowmodeModule.default;
- SlowmodeCommands = commandModule;
- await persistenceModule.awaitHydration('Slowmode');
- expect(debug).toHaveBeenCalledExactlyOnceWith('Store Slowmode hydrated from AppStorage and is now persisting.');
- } finally {
- debug.mockRestore();
- }
-});
-
-const CHANNEL_ID = '1234567890123456789';
-const RATE_LIMIT_PER_USER = 5;
-const SLOWMODE_WINDOW_MS = RATE_LIMIT_PER_USER * 1000;
-const T0 = Date.UTC(2026, 7, 20, 12, 0, 0);
-
-function at(offsetMs: number): void {
- vi.setSystemTime(T0 + offsetMs);
-}
-
-function shownRemainingMs(): number {
- return Slowmode.getSlowmodeRemaining(CHANNEL_ID, RATE_LIMIT_PER_USER);
-}
-
-function shownCountdownSeconds(): number {
- return Math.ceil(shownRemainingMs() / 1000);
-}
-
-function composerBlocksSend(): boolean {
- return shownRemainingMs() > 0;
-}
-
-function serverTimestamp(offsetMs: number): string {
- return new Date(T0 + offsetMs).toISOString();
-}
-
-function slowmodeRejection(retryAfterDecimalSeconds: number, retryAfterHeader: string): HttpError {
- return new HttpError({
- method: 'POST',
- path: `/channels/${CHANNEL_ID}/messages`,
- status: 400,
- body: {code: APIErrorCodes.SLOWMODE_RATE_LIMITED, retry_after: retryAfterDecimalSeconds},
- responseHeaders: {'retry-after': retryAfterHeader},
- });
-}
-
-function applySlowmodeRejection(error: HttpError): number {
- const retryAfterMs = SlowmodeCommands.clampSlowmodeRetryAfterMs(resolveRetryAfterMs(error));
- SlowmodeCommands.updateSlowmodeRemaining(CHANNEL_ID, retryAfterMs);
- return retryAfterMs;
-}
-
-describe('slowmode while an earlier send is still pending', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- at(0);
- Slowmode.clearChannel(CHANNEL_ID);
- });
- afterEach(() => {
- Slowmode.clearChannel(CHANNEL_ID);
- vi.useRealTimers();
- });
-
- it('blocks the second message while the first one is still pending', () => {
- at(0);
- expect(composerBlocksSend()).toBe(false);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(120);
- expect(composerBlocksSend()).toBe(true);
- expect(shownRemainingMs()).toBe(SLOWMODE_WINDOW_MS - 120);
- });
-
- it('anchors the window to the timestamp the server assigned the message', () => {
- at(0);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(450);
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverTimestamp(200));
- expect(Slowmode.getLastSendTimestamp(CHANNEL_ID)).toBe(T0 + 200);
- expect(shownRemainingMs()).toBe(SLOWMODE_WINDOW_MS - 250);
- });
-
- it('never shows more than the channel setting across the reported ordering', () => {
- const countdown: Array<{atMs: number; shownMs: number; shownSeconds: number}> = [];
- const sample = (offsetMs: number): void => {
- at(offsetMs);
- countdown.push({atMs: offsetMs, shownMs: shownRemainingMs(), shownSeconds: shownCountdownSeconds()});
- };
- at(0);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- sample(0);
- sample(120);
- sample(449);
- at(450);
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverTimestamp(200));
- sample(450);
- sample(2000);
- sample(5199);
- sample(5200);
- sample(10200);
- for (const entry of countdown) {
- expect(entry.shownMs).toBeLessThanOrEqual(SLOWMODE_WINDOW_MS);
- expect(entry.shownSeconds).toBeLessThanOrEqual(RATE_LIMIT_PER_USER);
- }
- for (let index = 1; index < countdown.length; index++) {
- expect(countdown[index]!.shownSeconds).toBeLessThanOrEqual(countdown[index - 1]!.shownSeconds);
- }
- expect(countdown.at(-3)!.shownMs).toBeGreaterThan(0);
- expect(countdown.at(-2)!.shownMs).toBe(0);
- expect(countdown.at(-1)!.shownMs).toBe(0);
- });
-
- it('keeps a server slowmode rejection inside the channel setting', () => {
- at(0);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(450);
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverTimestamp(200));
- at(759);
- const beforeRejection = shownRemainingMs();
- at(760);
- const storedMs = applySlowmodeRejection(slowmodeRejection(4.44, '5'));
- expect(storedMs).toBe(4440);
- expect(shownRemainingMs()).toBe(SLOWMODE_WINDOW_MS - 560);
- expect(shownRemainingMs()).toBeLessThan(beforeRejection);
- at(5200);
- expect(shownRemainingMs()).toBe(0);
- expect(composerBlocksSend()).toBe(false);
- });
-
- it('does not inflate the window when the rejection header carries milliseconds', () => {
- at(0);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(450);
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverTimestamp(200));
- at(760);
- const storedMs = applySlowmodeRejection(slowmodeRejection(4.7, '4700'));
- expect(storedMs).toBe(4700);
- expect(shownRemainingMs()).toBeLessThanOrEqual(SLOWMODE_WINDOW_MS);
- at(5460);
- expect(shownRemainingMs()).toBe(0);
- });
-
- it('releases the window when the pending send never reaches the server', () => {
- at(0);
- const pendingSend = SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(120);
- expect(composerBlocksSend()).toBe(true);
- at(300);
- SlowmodeCommands.discardPendingMessageSend(CHANNEL_ID, pendingSend);
- expect(Slowmode.getLastSendTimestamp(CHANNEL_ID)).toBeNull();
- expect(composerBlocksSend()).toBe(false);
- });
-
- it('keeps a rejection window when the rejected send releases its own guess', () => {
- at(0);
- const pendingSend = SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(760);
- applySlowmodeRejection(slowmodeRejection(4.44, '5'));
- SlowmodeCommands.discardPendingMessageSend(CHANNEL_ID, pendingSend);
- expect(Slowmode.getLastSendTimestamp(CHANNEL_ID)).toBeNull();
- expect(shownRemainingMs()).toBe(4440);
- });
-
- it('ignores an anchor from a clock that runs behind the server', () => {
- at(0);
- SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- at(450);
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverTimestamp(30_000));
- expect(shownRemainingMs()).toBeLessThanOrEqual(SLOWMODE_WINDOW_MS);
- at(5450);
- expect(shownRemainingMs()).toBe(0);
- });
-});
-
-describe('clock skew on the send anchor', () => {
- const CHANNEL_ID = '900000000000000001';
- const RATE_LIMIT_SECONDS = 5;
-
- beforeEach(() => {
- vi.useFakeTimers();
- Slowmode.clearChannel(CHANNEL_ID);
- });
-
- afterEach(() => {
- Slowmode.clearChannel(CHANNEL_ID);
- vi.useRealTimers();
- });
-
- const remainingAfterAck = (clientAheadMs: number): number => {
- vi.setSystemTime(new Date(1_000_000));
- const pending = SlowmodeCommands.recordPendingMessageSend(CHANNEL_ID);
- const serverAcceptedAt = new Date(1_000_000 - clientAheadMs).toISOString();
- vi.setSystemTime(new Date(1_000_450));
- SlowmodeCommands.confirmMessageSend(CHANNEL_ID, serverAcceptedAt, pending);
- return Slowmode.getSlowmodeRemaining(CHANNEL_ID, RATE_LIMIT_SECONDS);
- };
-
- it('does not shorten the window when the client clock runs ahead of the server', () => {
- for (const aheadMs of [0, 250, 1_000, 2_500, 4_800, 30_000, 3_600_000]) {
- expect(remainingAfterAck(aheadMs)).toBe(4_550);
- }
- });
-
- it('never lets the local guard reach zero while the window is live', () => {
- for (const aheadMs of [4_800, 30_000, 3_600_000]) {
- expect(remainingAfterAck(aheadMs)).toBeGreaterThan(0);
- }
- });
-});
diff --git a/fluxer_app/src/features/theme/fonts/ScriptFontLoader.test.ts b/fluxer_app/src/features/theme/fonts/ScriptFontLoader.test.ts
deleted file mode 100644
index 158dc031f..000000000
--- a/fluxer_app/src/features/theme/fonts/ScriptFontLoader.test.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {join} from 'node:path';
-import {
- hanChunkForLanguage,
- noteLocale,
- noteText,
- requestedScriptChunks,
- resetScriptFontLoaderForTests,
- type ScriptChunk,
- whenScriptChunksSettled,
-} from '@app/features/theme/fonts/ScriptFontLoader';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-const FONTS_CSS = join(process.cwd(), '..', 'packages', 'fonts', 'css');
-
-function chunks(): Array<ScriptChunk> {
- return [...requestedScriptChunks()].sort();
-}
-
-beforeEach(() => {
- resetScriptFontLoaderForTests();
- document.documentElement.lang = '';
-});
-
-afterEach(async () => {
- await whenScriptChunksSettled();
-});
-
-describe('script font loading gate', () => {
- it('requests nothing for text that is entirely Latin, which is the whole point of the split', () => {
- noteText('Hello there, this is an ordinary English message with punctuation: 1, 2, 3!');
- noteText('Ça va? Grüße! Añadir — naïve café résumé');
- expect(chunks()).toEqual([]);
- });
-
- it('requests nothing for empty or absent text', () => {
- noteText('');
- noteText(null);
- noteText(undefined);
- expect(chunks()).toEqual([]);
- });
-
- it('requests the JP chunk on kana, which no other bundled family covers', () => {
- noteText('こんにちは');
- expect(chunks()).toEqual(['jp']);
- });
-
- it('requests the KR chunk on hangul', () => {
- noteText('안녕하세요');
- expect(chunks()).toEqual(['kr']);
- });
-
- it('requests only the family the cascade would select for Han, not all three', () => {
- noteText('你好世界');
- expect(chunks()).toEqual(['sc']);
- });
-
- it('breaks the Han tie with the document language, never with it deciding whether to load', () => {
- document.documentElement.lang = 'ja';
- noteText('漢字');
- expect(chunks()).toEqual(['jp']);
-
- resetScriptFontLoaderForTests();
- document.documentElement.lang = 'zh-TW';
- noteText('漢字');
- expect(chunks()).toEqual(['tc']);
-
- resetScriptFontLoaderForTests();
- document.documentElement.lang = 'zh-CN';
- noteText('汉字');
- expect(chunks()).toEqual(['sc']);
- });
-
- it('serves mixed-script text from a Latin locale, which is what a locale gate would get wrong', () => {
- document.documentElement.lang = 'en-US';
- noteText('Hey ソラ, did 김민준 see 你好?');
- expect(chunks()).toEqual(['jp', 'kr', 'sc']);
- });
-
- it('never withholds a chunk because of the locale: a Japanese UI still loads Korean text', () => {
- document.documentElement.lang = 'ja';
- noteText('안녕하세요');
- expect(chunks()).toEqual(['kr']);
- });
-
- it('requests each chunk once, so a busy render path cannot storm the network', () => {
- noteText('こんにちは');
- const first = requestedScriptChunks().size;
- for (let i = 0; i < 100; i += 1) noteText('こんにちは');
- expect(requestedScriptChunks().size).toBe(first);
- });
-
- it('brings a CJK locale forward at activation without waiting for a codepoint', () => {
- noteLocale('ko');
- expect(chunks()).toEqual(['kr']);
-
- resetScriptFontLoaderForTests();
- noteLocale('en-US');
- expect(chunks()).toEqual([]);
- });
-
- it('takes the tie-break on ideograph-adjacent text that is not itself an ideograph', () => {
- for (const [label, text] of [
- ['iteration mark', '々'],
- ['ideographic zero', '〇'],
- ['kangxi radical', '⼀'],
- ['ideographic full stop', '。'],
- ['fullwidth exclamation', '!'],
- ['ideographic space', ' '],
- ] as const) {
- resetScriptFontLoaderForTests();
- document.documentElement.lang = 'en-US';
- noteText(text);
- expect(chunks(), `${label} announced no family`).toEqual(['sc']);
- }
- });
-
- it('routes ideograph-adjacent text through the same tie-break as Han, not a fixed family', () => {
- document.documentElement.lang = 'ja';
- noteText('。');
- expect(chunks()).toEqual(['jp']);
-
- resetScriptFontLoaderForTests();
- document.documentElement.lang = 'zh-TW';
- noteText('()');
- expect(chunks()).toEqual(['tc']);
- });
-
- it('keeps halfwidth katakana on JP alone rather than also taking the Han tie-break', () => {
- document.documentElement.lang = 'en-US';
- noteText('ソラ');
- expect(chunks()).toEqual(['jp']);
- });
-
- it('still requests nothing for ordinary Latin punctuation, which shares no block with CJK', () => {
- document.documentElement.lang = 'en-US';
- noteText('!?()[]{}<>@#$%^&*-_=+/\\|~`"\'.,;: 「」');
- resetScriptFontLoaderForTests();
- noteText('!?()[]{}<>@#$%^&*-_=+/\\|~`"\'.,;: ');
- expect(chunks()).toEqual([]);
- });
-
- it('resolves the Han tie-break the same way the base --font-sans chain orders the families', () => {
- expect(hanChunkForLanguage('ja')).toBe('jp');
- expect(hanChunkForLanguage('ja-JP')).toBe('jp');
- expect(hanChunkForLanguage('zh-TW')).toBe('tc');
- expect(hanChunkForLanguage('zh-HK')).toBe('tc');
- expect(hanChunkForLanguage('zh-Hant')).toBe('tc');
- expect(hanChunkForLanguage('zh-CN')).toBe('sc');
- expect(hanChunkForLanguage('zh')).toBe('sc');
- expect(hanChunkForLanguage('en-US')).toBe('sc');
- expect(hanChunkForLanguage(null)).toBe('sc');
- });
-});
-
-describe('the ingest points that feed the gate', () => {
- const SRC = join(process.cwd(), 'src');
- const INGEST: Array<[string, string]> = [
- ['features/guild/models/Guild.ts', 'guild names'],
- ['features/guild/models/GuildRole.ts', 'role names'],
- ['features/channel/models/Channel.ts', 'channel names'],
- ['features/channel/state/ChannelDisplayName.ts', 'computed channel display names'],
- ['features/user/utils/NicknameUtils.ts', 'display names and nicknames'],
- ['features/messaging/components/markdown/index.tsx', 'message content'],
- ];
-
- for (const [path, what] of INGEST) {
- it(`observes ${what} at ingest (${path})`, () => {
- const source = readFileSync(join(SRC, path), 'utf8');
- expect(source).toContain("from '@app/features/theme/fonts/ScriptFontLoader'");
- expect(source).toMatch(/\bnoteText\(/);
- });
- }
-});
-
-describe('the cascade the gate is computed from', () => {
- const variables = readFileSync(join(FONTS_CSS, 'variables.css'), 'utf8');
- const fallbacks = readFileSync(join(FONTS_CSS, 'locale-fallbacks.css'), 'utf8');
-
- it('names every gated family in the base --font-sans, or the gate could never select them', () => {
- const chain = /--font-sans:([^;]*);/.exec(variables)?.[1] ?? '';
- for (const family of ['Fluxer Sans SC', 'Fluxer Sans TC', 'Fluxer Sans JP', 'Fluxer Sans KR']) {
- expect(chain).toContain(family);
- }
- });
-
- it('orders the base chain SC before TC before JP, which is the no-signal Han tie-break', () => {
- const chain = /--font-sans:([^;]*);/.exec(variables)?.[1] ?? '';
- expect(chain.indexOf('Fluxer Sans SC')).toBeLessThan(chain.indexOf('Fluxer Sans TC'));
- expect(chain.indexOf('Fluxer Sans TC')).toBeLessThan(chain.indexOf('Fluxer Sans JP'));
- });
-
- it('leaves kana to JP, so the Han tie-break cannot claim text that is only ever Japanese', () => {
- for (const sheet of ['script-sc.css', 'script-tc.css']) {
- const text = readFileSync(join(FONTS_CSS, sheet), 'utf8');
- for (const [, value] of text.matchAll(/unicode-range:([^;]*);/g)) {
- for (const part of value.split(',')) {
- const [start, end] = part.trim().replace('U+', '').split('-');
- const from = Number.parseInt(start, 16);
- const to = end === undefined ? from : Number.parseInt(end, 16);
- expect(from > 0x30ff || to < 0x3040, `${sheet} claims ${part.trim()}`).toBe(true);
- }
- }
- }
- });
-
- it('hoists the family hanChunkForLanguage picks, for every locale rule that exists', () => {
- const expected: Record<string, string> = {
- ja: 'Fluxer Sans JP',
- ko: 'Fluxer Sans KR',
- 'zh-CN': 'Fluxer Sans SC',
- 'zh-TW': 'Fluxer Sans TC',
- };
- for (const [tag, family] of Object.entries(expected)) {
- const rule = new RegExp(`:root:lang\\(${tag}\\)[^{]*\\{([^}]*)\\}`).exec(fallbacks);
- expect(rule, `no :root:lang(${tag}) rule in locale-fallbacks.css`).not.toBeNull();
- const chain = rule![1];
- const hoisted = /'(Fluxer Sans (?:SC|TC|JP|KR))'/.exec(chain)?.[1];
- expect(hoisted, `:root:lang(${tag}) hoists the wrong family`).toBe(family);
- }
- });
-});
diff --git a/fluxer_app/src/features/theme/layout/MessageLayoutSpec.test.ts b/fluxer_app/src/features/theme/layout/MessageLayoutSpec.test.ts
deleted file mode 100644
index 05a031735..000000000
--- a/fluxer_app/src/features/theme/layout/MessageLayoutSpec.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getMessageLayoutCssVariables, MESSAGE_LAYOUT_SPEC} from '@app/features/theme/layout/MessageLayoutSpec';
-import {describe, expect, it} from 'vitest';
-
-function collectStringValues(value: unknown, acc: Array<string>): void {
- if (typeof value === 'string') {
- acc.push(value);
- return;
- }
- if (value && typeof value === 'object') {
- for (const nested of Object.values(value)) {
- collectStringValues(nested, acc);
- }
- }
-}
-
-describe('MESSAGE_LAYOUT_SPEC', () => {
- it('declares every length in rem so message layout scales with zoom', () => {
- const values: Array<string> = [];
- collectStringValues(MESSAGE_LAYOUT_SPEC, values);
- expect(values.length).toBeGreaterThan(0);
- for (const value of values) {
- expect(value === '100%' || /^-?\d+(?:\.\d+)?rem$/.test(value)).toBe(true);
- }
- });
-
- it('emits CSS variables free of raw px lengths', () => {
- for (const value of Object.values(getMessageLayoutCssVariables())) {
- if (value.startsWith('calc(') || value.startsWith('clamp(')) {
- continue;
- }
- expect(value).not.toMatch(/\d+px/);
- }
- });
-});
diff --git a/fluxer_app/src/features/theme/layout/RemFromPx.test.ts b/fluxer_app/src/features/theme/layout/RemFromPx.test.ts
deleted file mode 100644
index c3e84b415..000000000
--- a/fluxer_app/src/features/theme/layout/RemFromPx.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearRemScaleCache,
- getRemScaleForDocument,
- REM_BASE_PX,
- remFromPx,
- startRemScaleTracking,
-} from '@app/features/theme/layout/RemFromPx';
-import {describe, expect, it} from 'vitest';
-
-interface StubDocumentHarness {
- ownerDocument: Document;
- setRootFontSize: (fontSize: string) => void;
- getComputedStyleCallCount: () => number;
- animationFrameRequestCount: () => number;
- resizeListenerCount: () => number;
- resolutionListenerCount: () => number;
- watchedResolutionQueries: () => Array<string>;
- dispatchResize: () => void;
- setDevicePixelRatio: (devicePixelRatio: number) => void;
- setInnerWidth: (innerWidth: number) => void;
- setResolutionQueryMatches: (matches: boolean) => void;
- dispatchResolutionChange: () => void;
-}
-
-function createStubDocumentHarness(initialRootFontSize: string): StubDocumentHarness {
- let rootFontSize = initialRootFontSize;
- let getComputedStyleCallCount = 0;
- let animationFrameRequestCount = 0;
- let resolutionQueryMatches = true;
- const resizeListeners = new Set<() => void>();
- const resolutionQueries = new Map<string, Set<() => void>>();
- const documentElement = {} as HTMLElement;
- const ownerWindow = {
- devicePixelRatio: 1,
- innerWidth: 1280,
- getComputedStyle: () => {
- getComputedStyleCallCount += 1;
- return {fontSize: rootFontSize} as CSSStyleDeclaration;
- },
- requestAnimationFrame: () => {
- animationFrameRequestCount += 1;
- return 0;
- },
- cancelAnimationFrame: () => {},
- addEventListener: (type: string, listener: () => void) => {
- if (type !== 'resize') return;
- resizeListeners.add(listener);
- },
- removeEventListener: (type: string, listener: () => void) => {
- if (type !== 'resize') return;
- resizeListeners.delete(listener);
- },
- matchMedia: (media: string) => {
- const listeners = resolutionQueries.get(media) ?? new Set<() => void>();
- resolutionQueries.set(media, listeners);
- return {
- media,
- matches: resolutionQueryMatches,
- addEventListener: (_type: string, listener: () => void) => listeners.add(listener),
- removeEventListener: (_type: string, listener: () => void) => listeners.delete(listener),
- } as unknown as MediaQueryList;
- },
- };
- const ownerDocument = {documentElement, defaultView: ownerWindow} as unknown as Document;
- return {
- ownerDocument,
- setRootFontSize: (fontSize) => {
- rootFontSize = fontSize;
- },
- getComputedStyleCallCount: () => getComputedStyleCallCount,
- animationFrameRequestCount: () => animationFrameRequestCount,
- resizeListenerCount: () => resizeListeners.size,
- resolutionListenerCount: () =>
- [...resolutionQueries.values()].reduce((total, listeners) => total + listeners.size, 0),
- watchedResolutionQueries: () =>
- [...resolutionQueries.entries()].filter(([, listeners]) => listeners.size > 0).map(([media]) => media),
- dispatchResize: () => {
- for (const listener of [...resizeListeners]) listener();
- },
- setDevicePixelRatio: (devicePixelRatio) => {
- ownerWindow.devicePixelRatio = devicePixelRatio;
- },
- setInnerWidth: (innerWidth) => {
- ownerWindow.innerWidth = innerWidth;
- },
- setResolutionQueryMatches: (matches) => {
- resolutionQueryMatches = matches;
- },
- dispatchResolutionChange: () => {
- for (const listeners of [...resolutionQueries.values()]) {
- for (const listener of [...listeners]) listener();
- }
- },
- };
-}
-
-describe('remFromPx', () => {
- it('uses a 16px base', () => {
- expect(REM_BASE_PX).toBe(16);
- });
-
- it('converts whole pixel sizes to rem', () => {
- expect(remFromPx(16)).toBe('1rem');
- expect(remFromPx(40)).toBe('2.5rem');
- expect(remFromPx(80)).toBe('5rem');
- expect(remFromPx(0)).toBe('0rem');
- });
-
- it('converts fractional pixel sizes without trailing-zero noise', () => {
- expect(remFromPx(10)).toBe('0.625rem');
- expect(remFromPx(3.2)).toBe('0.2rem');
- expect(remFromPx(4.8)).toBe('0.3rem');
- expect(remFromPx(2.5)).toBe('0.15625rem');
- });
-
- it('preserves the sign of negative offsets', () => {
- expect(remFromPx(-64.8)).toBe('-4.05rem');
- });
-
- it('always produces a value parseable as a rem length', () => {
- for (const px of [12, 14, 18, 24, 36, 55, 105, 140, 120]) {
- expect(remFromPx(px)).toMatch(/^-?\d+(?:\.\d+)?rem$/);
- }
- });
-});
-
-describe('getRemScaleForDocument', () => {
- it('reports the root font size relative to the rem base', () => {
- const defaultRoot = createStubDocumentHarness('16px');
- const scaledRoot = createStubDocumentHarness('20px');
- const zoomedRoot = createStubDocumentHarness('24px');
- expect(getRemScaleForDocument(defaultRoot.ownerDocument)).toBe(1);
- expect(getRemScaleForDocument(scaledRoot.ownerDocument)).toBe(1.25);
- expect(getRemScaleForDocument(zoomedRoot.ownerDocument)).toBe(1.5);
- });
-
- it('reads the computed root font size once for repeated calls', () => {
- const harness = createStubDocumentHarness('16px');
- for (let call = 0; call < 200; call += 1) {
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- }
- expect(harness.getComputedStyleCallCount()).toBe(1);
- });
-
- it('never schedules per-frame invalidation work', () => {
- const harness = createStubDocumentHarness('16px');
- getRemScaleForDocument(harness.ownerDocument);
- getRemScaleForDocument(harness.ownerDocument);
- expect(harness.animationFrameRequestCount()).toBe(0);
- });
-
- it('re-reads after a resize that changes the device pixel ratio', () => {
- const harness = createStubDocumentHarness('16px');
- startRemScaleTracking(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setRootFontSize('20px');
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setDevicePixelRatio(1.25);
- harness.dispatchResize();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1.25);
- expect(harness.watchedResolutionQueries()).toEqual(['(resolution: 1.25dppx)']);
- });
-
- it('re-reads after a resize that changes the viewport width', () => {
- const harness = createStubDocumentHarness('16px');
- startRemScaleTracking(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setRootFontSize('20px');
- harness.setInnerWidth(720);
- harness.dispatchResize();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1.25);
- });
-
- it('ignores resizes that change neither the device pixel ratio nor the viewport width', () => {
- const harness = createStubDocumentHarness('16px');
- startRemScaleTracking(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setRootFontSize('20px');
- for (let frame = 0; frame < 60; frame += 1) {
- harness.dispatchResize();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- }
- expect(harness.getComputedStyleCallCount()).toBe(1);
- });
-
- it('re-reads after a browser zoom changes the device pixel ratio', () => {
- const harness = createStubDocumentHarness('16px');
- startRemScaleTracking(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- expect(harness.watchedResolutionQueries()).toEqual(['(resolution: 1dppx)']);
- harness.setRootFontSize('24px');
- harness.setDevicePixelRatio(1.5);
- harness.dispatchResolutionChange();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1.5);
- expect(harness.watchedResolutionQueries()).toEqual(['(resolution: 1.5dppx)']);
- expect(harness.resolutionListenerCount()).toBe(1);
- });
-
- it('re-binds the resolution query from a resize when the query never matched', () => {
- const harness = createStubDocumentHarness('16px');
- harness.setResolutionQueryMatches(false);
- startRemScaleTracking(harness.ownerDocument);
- expect(harness.resolutionListenerCount()).toBe(0);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setRootFontSize('20px');
- harness.dispatchResize();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setDevicePixelRatio(1.5);
- harness.setResolutionQueryMatches(true);
- harness.dispatchResize();
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1.25);
- expect(harness.watchedResolutionQueries()).toEqual(['(resolution: 1.5dppx)']);
- expect(harness.resolutionListenerCount()).toBe(1);
- });
-
- it('re-reads after an explicit cache clear', () => {
- const harness = createStubDocumentHarness('16px');
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- harness.setRootFontSize('12px');
- clearRemScaleCache(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(0.75);
- expect(harness.getComputedStyleCallCount()).toBe(2);
- });
-
- it('releases every listener when tracking is disposed', () => {
- const harness = createStubDocumentHarness('16px');
- const stopTracking = startRemScaleTracking(harness.ownerDocument);
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1);
- expect(harness.resizeListenerCount()).toBe(1);
- expect(harness.resolutionListenerCount()).toBe(1);
- stopTracking();
- expect(harness.resizeListenerCount()).toBe(0);
- expect(harness.resolutionListenerCount()).toBe(0);
- harness.setRootFontSize('20px');
- expect(getRemScaleForDocument(harness.ownerDocument)).toBe(1.25);
- expect(harness.resizeListenerCount()).toBe(0);
- expect(harness.resolutionListenerCount()).toBe(0);
- });
-
- it('never registers listeners as a side effect of reading', () => {
- const harness = createStubDocumentHarness('16px');
- for (let call = 0; call < 5; call += 1) {
- getRemScaleForDocument(harness.ownerDocument);
- }
- expect(harness.resizeListenerCount()).toBe(0);
- expect(harness.resolutionListenerCount()).toBe(0);
- });
-
- it('invalidates every document when cleared without a target', () => {
- const main = createStubDocumentHarness('16px');
- const popout = createStubDocumentHarness('16px');
- expect(getRemScaleForDocument(main.ownerDocument)).toBe(1);
- expect(getRemScaleForDocument(popout.ownerDocument)).toBe(1);
- main.setRootFontSize('20px');
- popout.setRootFontSize('20px');
- clearRemScaleCache();
- expect(getRemScaleForDocument(main.ownerDocument)).toBe(1.25);
- expect(getRemScaleForDocument(popout.ownerDocument)).toBe(1.25);
- });
-
- it('falls back to the rem base when the document has no view or no usable root font size', () => {
- const detachedDocument = {documentElement: {} as HTMLElement, defaultView: null} as unknown as Document;
- const brokenRoot = createStubDocumentHarness('not-a-length');
- expect(getRemScaleForDocument(null)).toBe(1);
- expect(getRemScaleForDocument(detachedDocument)).toBe(1);
- expect(getRemScaleForDocument(brokenRoot.ownerDocument)).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/theme/styles/MessageBidiIsolation.test.ts b/fluxer_app/src/features/theme/styles/MessageBidiIsolation.test.ts
deleted file mode 100644
index fc855609c..000000000
--- a/fluxer_app/src/features/theme/styles/MessageBidiIsolation.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {fileURLToPath} from 'node:url';
-import {describe, expect, it} from 'vitest';
-
-const MESSAGE_CSS = readFileSync(fileURLToPath(new URL('./Message.module.css', import.meta.url)), 'utf8');
-
-const ISOLATED_NAMES = ['.messageUsername', '.repliedUsername'];
-const ISOLATED_TIMESTAMPS = [
- '.messageTimestamp',
- '.messageTimestampCompact',
- '.messageTimestampHover',
- '.messageTimestampCompactHover',
-];
-
-function rules(css: string): Array<{selector: string; declarations: string}> {
- const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const out: Array<{selector: string; declarations: string}> = [];
- const chain: Array<string> = [];
- let buffer = '';
- for (const char of source) {
- if (char === '{') {
- chain.push(buffer.split(/[;}]/).pop()?.trim().replace(/\s+/g, ' ') ?? '');
- buffer = '';
- } else if (char === '}') {
- if (chain.length > 0) {
- out.push({selector: chain.join(' '), declarations: buffer});
- chain.pop();
- }
- buffer = '';
- } else {
- buffer += char;
- }
- }
- return out;
-}
-
-function declaredBidi(className: string): Array<string> {
- const selectorPattern = new RegExp(`\\${className}(?![\\w-])`);
- const out: Array<string> = [];
- for (const rule of rules(MESSAGE_CSS)) {
- if (!rule.selector.split(',').some((selector) => selectorPattern.test(selector))) continue;
- const match = rule.declarations.match(/unicode-bidi\s*:\s*([^;]+)/);
- if (match) out.push(match[1].trim());
- }
- return out;
-}
-
-describe('message bidi isolation', () => {
- it.each(ISOLATED_NAMES)('resolves %s in its own bidi paragraph', (className) => {
- expect(declaredBidi(className)).toContain('plaintext');
- });
-
- it.each(ISOLATED_TIMESTAMPS)('keeps %s out of a neighbouring right-to-left run', (className) => {
- expect(declaredBidi(className)).toContain('isolate');
- });
-});
diff --git a/fluxer_app/src/features/theme/styles/TextRendering.test.ts b/fluxer_app/src/features/theme/styles/TextRendering.test.ts
deleted file mode 100644
index aed93b586..000000000
--- a/fluxer_app/src/features/theme/styles/TextRendering.test.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync} from 'node:fs';
-import {join} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {describe, expect, it} from 'vitest';
-
-const APP_SRC = fileURLToPath(new URL('../../../', import.meta.url));
-
-const FORBIDDEN_SMOOTHING_PROPERTIES = ['-webkit-font-smoothing', 'font-smooth', 'text-rendering'];
-const LAYER_PROMOTING_WILL_CHANGE = /transform|opacity|filter/;
-const WILL_CHANGE = /will-change\s*:\s*([^;]*)/;
-
-const ANIMATION_STATE_SELECTOR = /\[data-(dragging|state|animating)|:hover|:active|Animating|Animated|Dragging/;
-
-const NON_TEXT_WILL_CHANGE_ALLOWLIST = new Set([
- 'features/channel/components/GifPicker.module.css .loadingSkeletonBlob',
- 'features/channel/components/GuildMembersPage.module.css .progressBar',
- 'features/channel/components/direct_message/DMChannelView.module.css .callParticipantAvatar',
- 'features/messaging/components/modals/MediaModal.module.css .desktopViewerContent',
- 'features/ui/components/form/FormSwitch.module.css .switchThumb',
- 'features/ui/scroller/ScrollerTrack.module.css .thumb',
- 'features/user/components/profile/UserProfileLoadingSkeleton.module.css .pulse',
- 'features/voice/components/LiveRecordingWaveform.module.css .track',
- 'features/voice/components/PiPOverlay.module.css .container',
-]);
-
-function collectFiles(directory: string, extension: string, out: Array<string> = []): Array<string> {
- for (const entry of readdirSync(directory, {withFileTypes: true})) {
- const full = join(directory, entry.name);
- if (entry.isDirectory()) {
- collectFiles(full, extension, out);
- } else if (entry.name.endsWith(extension)) {
- out.push(full);
- }
- }
- return out;
-}
-
-function rules(css: string): Array<{selector: string; declarations: string}> {
- const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
- const out: Array<{selector: string; declarations: string}> = [];
- const chain: Array<string> = [];
- let buffer = '';
- for (const char of source) {
- if (char === '{') {
- chain.push(buffer.split(/[;}]/).pop()?.trim().replace(/\s+/g, ' ') ?? '');
- buffer = '';
- } else if (char === '}') {
- if (chain.length > 0) {
- out.push({selector: chain.join(' '), declarations: buffer});
- chain.pop();
- }
- buffer = '';
- } else {
- buffer += char;
- }
- }
- return out;
-}
-
-function relative(file: string): string {
- return file.slice(APP_SRC.length);
-}
-
-describe('text rendering', () => {
- const stylesheets = collectFiles(APP_SRC, '.css');
-
- it('finds the authored stylesheets it is meant to guard', () => {
- expect(stylesheets.length).toBeGreaterThan(100);
- });
-
- it('never overrides font smoothing, which would disable ClearType on Windows', () => {
- const offenders: Array<string> = [];
- for (const file of stylesheets) {
- const css = readFileSync(file, 'utf8');
- for (const property of FORBIDDEN_SMOOTHING_PROPERTIES) {
- if (css.includes(property)) {
- offenders.push(`${relative(file)}: ${property}`);
- }
- }
- }
- expect(offenders).toEqual([]);
- });
-
- it('only allows a layer-promoting will-change when it is animation-scoped or a reviewed non-text rule', () => {
- const offenders: Array<string> = [];
- for (const file of stylesheets) {
- for (const {selector, declarations} of rules(readFileSync(file, 'utf8'))) {
- const willChange = WILL_CHANGE.exec(declarations);
- if (willChange == null) continue;
- if (!LAYER_PROMOTING_WILL_CHANGE.test(willChange[1]!)) continue;
- if (ANIMATION_STATE_SELECTOR.test(selector)) continue;
- if (NON_TEXT_WILL_CHANGE_ALLOWLIST.has(`${relative(file)} ${selector}`)) continue;
- offenders.push(`${relative(file)} ${selector}: will-change:${willChange[1]!.trim()}`);
- }
- }
- expect(offenders).toEqual([]);
- });
-
- it('never promotes a layer with an inline willChange style, which the stylesheet guard cannot see', () => {
- const offenders: Array<string> = [];
- for (const file of collectFiles(APP_SRC, '.tsx')) {
- if (readFileSync(file, 'utf8').includes('willChange')) {
- offenders.push(relative(file));
- }
- }
- expect(offenders).toEqual([]);
- });
-});
-
-describe('popout text rendering', () => {
- it('shadows popouts with box-shadow, since any filter disables subpixel antialiasing', () => {
- const css = readFileSync(join(APP_SRC, 'features/ui/popover/PopoverPopout.module.css'), 'utf8');
- expect(css).toContain('box-shadow: 0 0.5rem 1rem var(--popout-shadow);');
- expect(css).not.toMatch(/(^|[\s;])filter\s*:/m);
- expect(css).not.toContain('popoutStableText');
- });
-});
-
-const FRACTIONAL_OPACITY = /(^|[;\s])opacity\s*:\s*(0?\.\d+)\s*(;|$)/;
-const TEXT_DECLARATION =
- /(^|[;\s])(color|font-size|font-weight|font-family|font-style|line-height|letter-spacing|text-transform|text-overflow|white-space)\s*:/;
-const TRANSIENT_STATE_SELECTOR =
- /:hover|:focus|:active|:disabled|::before|::after|\[data-|%|\bfrom\b|\bto\b|Animating|Animated|Dragging|Hover|Pressed|Selected/;
-
-const PERSISTENT_TEXT_OPACITY_ALLOWLIST = new Set([
- 'features/channel/components/ChannelDivider.module.css .unreadBadge',
- 'features/theme/styles/AttachmentFile.module.css .statusBadge',
- 'features/app/components/layout/sidebar_nav/GuildListDMItem.module.css .muted',
- 'features/app/components/layout/NativeTitlebar.module.css .left',
- 'features/app/components/layout/ChannelItem.module.css .channelItemMutedState',
- 'features/app/components/layout/FavoritesChannelListContent.module.css .favoriteItemMuted',
- 'features/channel/components/direct_message/DirectMessageList.module.css .dmItemMuted',
- 'features/channel/components/direct_message/DirectMessageList.module.css .dmItemMobileMuted',
- 'features/ui/action_menu/ContextMenu.module.css .item.disabled',
- 'features/ui/action_menu/MenuItem.module.css .sliderItem.disabled',
- 'features/app/components/dialogs/Modal.module.css .headerInner button',
- 'features/channel/components/active_now/ActiveNowSidebar.module.css .emptyIcon',
- 'features/channel/components/shared/MemberListUnavailableFallback.module.css .icon',
- 'features/messaging/components/markdown/renderers/MessageJumpLink.module.css .divider',
- 'features/search/components/search/SearchFilterChip.module.css .removeButton',
- 'features/theme/styles/AttachmentGridItem.module.css .audioPlaceholder svg',
- 'features/theme/styles/AttachmentMosaic.module.css .audioPlaceholder svg',
- 'features/user/components/modals/UserProfileModal.module.css .emptyStateIcon',
-]);
-
-describe('persistent text opacity', () => {
- it('dims text through colour, not through a layer opacity that would kill subpixel antialiasing', () => {
- const offenders: Array<string> = [];
- for (const file of collectFiles(APP_SRC, '.module.css')) {
- for (const {selector, declarations} of rules(readFileSync(file, 'utf8'))) {
- if (!FRACTIONAL_OPACITY.test(declarations)) continue;
- if (!TEXT_DECLARATION.test(declarations)) continue;
- if (TRANSIENT_STATE_SELECTOR.test(selector)) continue;
- const key = `${relative(file)} ${selector}`;
- if (PERSISTENT_TEXT_OPACITY_ALLOWLIST.has(key)) continue;
- offenders.push(key);
- }
- }
- expect(offenders).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/theme/utils/HolidayClassUtils.test.ts b/fluxer_app/src/features/theme/utils/HolidayClassUtils.test.ts
deleted file mode 100644
index 40cbbdeda..000000000
--- a/fluxer_app/src/features/theme/utils/HolidayClassUtils.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getActiveHolidaySlugs, millisecondsUntilNextLocalMidnight} from '@app/features/theme/utils/HolidayClassUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('getActiveHolidaySlugs', () => {
- it('fires christmas + christmastide on Dec 25', () => {
- const slugs = getActiveHolidaySlugs(new Date(2026, 11, 25));
- expect(slugs).toContain('christmas');
- expect(slugs).toContain('christmastide');
- });
- it('fires both boxing-day and christmastide on Dec 26', () => {
- const slugs = getActiveHolidaySlugs(new Date(2026, 11, 26));
- expect(slugs).toContain('boxing-day');
- expect(slugs).toContain('christmastide');
- expect(slugs).not.toContain('christmas');
- });
- it('co-fires india-independence-day and korea-liberation-day on Aug 15', () => {
- const slugs = getActiveHolidaySlugs(new Date(2026, 7, 15));
- expect(slugs).toContain('india-independence-day');
- expect(slugs).toContain('korea-liberation-day');
- });
- it('fires pride-month every day in June', () => {
- expect(getActiveHolidaySlugs(new Date(2026, 5, 1))).toContain('pride-month');
- expect(getActiveHolidaySlugs(new Date(2026, 5, 15))).toContain('pride-month');
- expect(getActiveHolidaySlugs(new Date(2026, 5, 30))).toContain('pride-month');
- expect(getActiveHolidaySlugs(new Date(2026, 4, 31))).not.toContain('pride-month');
- expect(getActiveHolidaySlugs(new Date(2026, 6, 1))).not.toContain('pride-month');
- });
- it('co-fires stonewall-day with pride-month on Jun 28', () => {
- const slugs = getActiveHolidaySlugs(new Date(2026, 5, 28));
- expect(slugs).toContain('stonewall-day');
- expect(slugs).toContain('pride-month');
- });
- it('fires juneteenth on Jun 19', () => {
- expect(getActiveHolidaySlugs(new Date(2026, 5, 19))).toContain('juneteenth');
- });
- it('fires back-to-the-future-day on Oct 21', () => {
- expect(getActiveHolidaySlugs(new Date(2026, 9, 21))).toContain('back-to-the-future-day');
- });
- it('returns empty on a quiet day', () => {
- expect(getActiveHolidaySlugs(new Date(2026, 1, 17))).toEqual([]);
- });
- it('handles leap day without crashing', () => {
- expect(() => getActiveHolidaySlugs(new Date(2028, 1, 29))).not.toThrow();
- expect(getActiveHolidaySlugs(new Date(2028, 1, 29))).toEqual([]);
- });
-});
-
-describe('millisecondsUntilNextLocalMidnight', () => {
- it('returns the gap to next local midnight', () => {
- const now = new Date(2026, 5, 15, 23, 59, 59, 0);
- const ms = millisecondsUntilNextLocalMidnight(now);
- expect(ms).toBeGreaterThanOrEqual(1000);
- expect(ms).toBeLessThanOrEqual(1000 + 999);
- });
- it('returns close to 24h at the start of a day', () => {
- const now = new Date(2026, 5, 15, 0, 0, 1, 0);
- const ms = millisecondsUntilNextLocalMidnight(now);
- expect(ms).toBeGreaterThan(23 * 60 * 60 * 1000);
- expect(ms).toBeLessThanOrEqual(24 * 60 * 60 * 1000);
- });
-});
diff --git a/fluxer_app/src/features/typing/rolling/RollingComposerTypingGate.test.ts b/fluxer_app/src/features/typing/rolling/RollingComposerTypingGate.test.ts
deleted file mode 100644
index 375d94b12..000000000
--- a/fluxer_app/src/features/typing/rolling/RollingComposerTypingGate.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {decideComposerTyping} from '@app/features/typing/rolling/RollingComposerTypingGate';
-import {describe, expect, it} from 'vitest';
-
-type ComposerTypingChange = Parameters<typeof decideComposerTyping>[0];
-
-function decide(change: Partial<ComposerTypingChange>): ReturnType<typeof decideComposerTyping> {
- return decideComposerTyping({
- previousValue: 'hell',
- value: 'hello',
- isEditingMessageInComposer: false,
- enabled: true,
- ...change,
- });
-}
-
-describe('decideComposerTyping', () => {
- it('starts typing when the value changes to non-empty text', () => {
- expect(decide({})).toBe('start');
- expect(decide({previousValue: '', value: 'h'})).toBe('start');
- expect(decide({previousValue: 'hello', value: 'hell'})).toBe('start');
- });
-
- it('stops typing for a whitespace-only draft', () => {
- expect(decide({previousValue: '', value: ' '})).toBe('stop');
- expect(decide({previousValue: 'hi', value: ' \n\t'})).toBe('stop');
- });
-
- it('stops typing when the value becomes exactly empty', () => {
- expect(decide({previousValue: 'h', value: ''})).toBe('stop');
- });
-
- it('does nothing when the value is unchanged', () => {
- expect(decide({previousValue: 'hello', value: 'hello'})).toBe('none');
- expect(decide({previousValue: '', value: ''})).toBe('none');
- });
-
- it('does nothing on the first run after mount', () => {
- expect(decide({previousValue: null, value: 'saved draft'})).toBe('none');
- });
-
- it('does nothing when the channel changed since the previous value', () => {
- expect(decide({previousValue: null, value: ''})).toBe('none');
- expect(decide({previousValue: null, value: 'draft in the next channel'})).toBe('none');
- });
-
- it('does nothing while editing a message in the composer', () => {
- expect(decide({isEditingMessageInComposer: true})).toBe('none');
- expect(decide({isEditingMessageInComposer: true, value: ''})).toBe('none');
- });
-
- it('does nothing while the composer is disabled', () => {
- expect(decide({enabled: false})).toBe('none');
- expect(decide({enabled: false, value: ''})).toBe('none');
- });
-
- it('suppresses a leading slash', () => {
- expect(decide({previousValue: '', value: '/'})).toBe('none');
- expect(decide({previousValue: '/gif', value: '/gif cats'})).toBe('none');
- });
-
- it('suppresses a bare plus', () => {
- expect(decide({previousValue: '', value: '+'})).toBe('none');
- expect(decide({previousValue: '+', value: '+1'})).toBe('start');
- });
-
- it('suppresses the plus colon emoji shorthand', () => {
- expect(decide({previousValue: '+', value: '+:'})).toBe('none');
- expect(decide({previousValue: '+:thumbsup', value: '+:thumbsup:'})).toBe('none');
- expect(decide({previousValue: '+:thumbs', value: '+:thumbs-up'})).toBe('none');
- });
-
- it('suppresses the reaction shorthand with leading whitespace', () => {
- expect(decide({previousValue: ' +:', value: ' +:smile'})).toBe('none');
- });
-
- it('suppresses a replace command', () => {
- expect(decide({previousValue: 's/teh/th', value: 's/teh/the/'})).toBe('none');
- expect(decide({previousValue: ' s/teh/th', value: ' s/teh/the '})).toBe('none');
- });
-
- it('starts typing while autocomplete is open', () => {
- expect(decide({previousValue: '@al', value: '@ali'})).toBe('start');
- expect(decide({previousValue: 'nice :smi', value: 'nice :smil'})).toBe('start');
- expect(decide({previousValue: '#gen', value: '#gene'})).toBe('start');
- });
-});
diff --git a/fluxer_app/src/features/typing/rolling/RollingTypingSender.test.ts b/fluxer_app/src/features/typing/rolling/RollingTypingSender.test.ts
deleted file mode 100644
index 8b80f1cb2..000000000
--- a/fluxer_app/src/features/typing/rolling/RollingTypingSender.test.ts
+++ /dev/null
@@ -1,372 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Endpoints} from '@app/features/app/constants/Endpoints';
-import {runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = await vi.hoisted(async () => {
- const {observable} = await import('mobx');
- return {
- auth: observable({currentUserId: 'me' as string | null}),
- post: vi.fn((_path: string) => Promise.resolve({ok: true})),
- logError: vi.fn(),
- };
-});
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = doubles.logError;
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {post: doubles.post}}));
-vi.mock('@app/features/auth/state/Authentication', () => ({default: doubles.auth}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: {showMyselfTyping: false}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: () => undefined}}));
-
-const {default: RollingTypingSender} = await import('@app/features/typing/rolling/RollingTypingSender');
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-const START_TIME = 1_000_000;
-const CHANNEL = 'channel';
-const OTHER_CHANNEL = 'other-channel';
-
-let postTimes: Array<number> = [];
-
-function elapsed(): number {
- return Date.now() - START_TIME;
-}
-
-function typeContinuously(durationMs: number): void {
- const startedAt = Date.now();
- while (Date.now() - startedAt < durationMs) {
- RollingTypingSender.startTyping(CHANNEL);
- vi.advanceTimersByTime(100);
- }
-}
-
-function advanceTo(elapsedMs: number): void {
- vi.advanceTimersByTime(elapsedMs - elapsed());
-}
-
-function startOtherTypists(count: number): void {
- for (let index = 0; index < count; index += 1) {
- RollingTypingStore.start(CHANNEL, `typist-${index}`, 'gateway');
- }
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(START_TIME);
- postTimes = [];
- doubles.post.mockImplementation((_path: string) => {
- postTimes.push(elapsed());
- return Promise.resolve({ok: true});
- });
-});
-
-afterEach(() => {
- RollingTypingSender.reset();
- RollingTypingStore.reset();
- runInAction(() => {
- doubles.auth.currentUserId = 'me';
- });
- vi.useRealTimers();
- vi.clearAllMocks();
-});
-
-describe('RollingTypingSender', () => {
- it('posts once 1500 ms after the first keystroke and not before', () => {
- RollingTypingSender.startTyping(CHANNEL);
-
- vi.advanceTimersByTime(1499);
- expect(doubles.post).not.toHaveBeenCalled();
-
- vi.advanceTimersByTime(1);
- expect(doubles.post).toHaveBeenCalledExactlyOnceWith(Endpoints.CHANNEL_TYPING(CHANNEL));
-
- vi.advanceTimersByTime(20000);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('does not push a pending send back on further keystrokes', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(500);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(1400);
- RollingTypingSender.startTyping(CHANNEL);
-
- advanceTo(1500);
-
- expect(postTimes).toEqual([1500]);
- });
-
- it('writes the self entry at schedule time', () => {
- RollingTypingSender.startTyping(CHANNEL);
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(true);
- expect(RollingTypingStore.isConfirmedTyping(CHANNEL, 'me')).toBe(false);
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('writes nothing on a throttled keystroke', () => {
- RollingTypingSender.startTyping(CHANNEL);
- RollingTypingStore.remove(CHANNEL, 'me');
- const timersBefore = vi.getTimerCount();
-
- advanceTo(700);
- RollingTypingSender.startTyping(CHANNEL);
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- expect(vi.getTimerCount()).toBe(timersBefore);
- });
-
- it('sends every 8000 ms while typing continuously', () => {
- typeContinuously(20000);
- vi.advanceTimersByTime(20000);
-
- expect(postTimes).toEqual([1500, 9500, 17500]);
- });
-
- it('posts the second time about 9500 ms after the first keystroke', () => {
- typeContinuously(12000);
-
- expect(postTimes[1]).toBe(9500);
- expect(postTimes[1]! - postTimes[0]!).toBe(8000);
- });
-
- it('posts immediately when typing resumes 16000 ms after the last schedule', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(16000);
-
- RollingTypingSender.startTyping(CHANNEL);
- vi.advanceTimersByTime(0);
-
- expect(postTimes).toEqual([1500, 16000]);
- });
-
- it('skips the post when six entries including self are typing', () => {
- startOtherTypists(5);
- RollingTypingSender.startTyping(CHANNEL);
-
- vi.advanceTimersByTime(1500);
-
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(6);
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('posts with five entries including self typing', () => {
- startOtherTypists(4);
- RollingTypingSender.startTyping(CHANNEL);
-
- vi.advanceTimersByTime(1500);
-
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(5);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('advances the throttle clock when the post is skipped', () => {
- startOtherTypists(5);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(1500);
- expect(doubles.post).not.toHaveBeenCalled();
-
- advanceTo(5000);
- for (let index = 0; index < 5; index += 1) {
- RollingTypingStore.remove(CHANNEL, `typist-${index}`);
- }
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(7999);
- expect(doubles.post).not.toHaveBeenCalled();
-
- advanceTo(8000);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(9500);
- expect(postTimes).toEqual([9500]);
- });
-
- it('does not retry a failed post', async () => {
- doubles.post.mockImplementationOnce(() => Promise.reject(new Error('Too many requests')));
- RollingTypingSender.startTyping(CHANNEL);
-
- await vi.advanceTimersByTimeAsync(1500);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- expect(doubles.logError).toHaveBeenCalledExactlyOnceWith(
- `Failed to send typing indicator to channel ${CHANNEL}:`,
- expect.any(Error),
- );
-
- await vi.advanceTimersByTimeAsync(30000);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('keeps the throttle after a failed post', async () => {
- doubles.post.mockImplementationOnce(() => Promise.reject(new Error('Network down')));
- RollingTypingSender.startTyping(CHANNEL);
- await vi.advanceTimersByTimeAsync(1500);
-
- advanceTo(3000);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(7999);
- expect(doubles.post).toHaveBeenCalledTimes(1);
-
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(8000);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(9500);
- expect(doubles.post).toHaveBeenCalledTimes(2);
- });
-
- it('drops the slot and cancels a pending send on a keystroke in another channel', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(500);
-
- RollingTypingSender.startTyping(OTHER_CHANNEL);
- vi.advanceTimersByTime(20000);
-
- expect(doubles.post).toHaveBeenCalledExactlyOnceWith(Endpoints.CHANNEL_TYPING(OTHER_CHANNEL));
- expect(postTimes).toEqual([2000]);
- });
-
- it('leaves the self entry in the previous channel when typing moves on', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(500);
-
- RollingTypingSender.startTyping(OTHER_CHANNEL);
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(true);
- expect(RollingTypingStore.isTyping(OTHER_CHANNEL, 'me')).toBe(true);
- advanceTo(10000);
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- expect(RollingTypingStore.isTyping(OTHER_CHANNEL, 'me')).toBe(true);
- });
-
- it('keeps a pending send alive across a plain channel switch', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(400);
-
- RollingTypingSender.stopTyping(OTHER_CHANNEL);
- advanceTo(1500);
-
- expect(doubles.post).toHaveBeenCalledExactlyOnceWith(Endpoints.CHANNEL_TYPING(CHANNEL));
- });
-
- it('cancels only a pending send and removes the self entry when the field is emptied', () => {
- RollingTypingSender.startTyping(CHANNEL);
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- advanceTo(500);
-
- RollingTypingSender.stopTyping(CHANNEL);
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
- expect(vi.getTimerCount()).toBe(1);
- vi.advanceTimersByTime(5000);
- expect(doubles.post).not.toHaveBeenCalled();
-
- RollingTypingSender.startTyping(CHANNEL);
- vi.advanceTimersByTime(1500);
- expect(postTimes).toEqual([7000]);
- });
-
- it('leaves the self entry and the throttle alone when emptied after the post fired', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(1500);
- expect(doubles.post).toHaveBeenCalledTimes(1);
-
- RollingTypingSender.stopTyping(CHANNEL);
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(true);
-
- advanceTo(3000);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(7999);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('drops the slot and the self entry on own message sent', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(500);
-
- RollingTypingSender.handleOwnMessageSent(CHANNEL);
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- expect(vi.getTimerCount()).toBe(0);
- vi.advanceTimersByTime(20000);
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('schedules a fresh 1500 ms send for a quick follow-up after own message sent', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(2000);
- RollingTypingSender.handleOwnMessageSent(CHANNEL);
-
- advanceTo(2100);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(3599);
- expect(postTimes).toEqual([1500]);
-
- advanceTo(3600);
- expect(postTimes).toEqual([1500, 3600]);
- });
-
- it('bails inside the timer when the signed in account changed', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(1000);
-
- runInAction(() => {
- doubles.auth.currentUserId = 'someone-else';
- });
- advanceTo(5000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('keeps the slot when the store is reset on reconnect', () => {
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(500);
-
- RollingTypingStore.reset();
- advanceTo(1500);
-
- expect(doubles.post).toHaveBeenCalledTimes(1);
- advanceTo(3000);
- RollingTypingSender.startTyping(CHANNEL);
- advanceTo(7999);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('sends no trailing post after a burst ends', () => {
- typeContinuously(3000);
-
- vi.advanceTimersByTime(60000);
-
- expect(postTimes).toEqual([1500]);
- });
-
- it('releases the pending timer on reset', () => {
- RollingTypingSender.startTyping(CHANNEL);
- const timersBefore = vi.getTimerCount();
-
- RollingTypingSender.reset();
-
- expect(vi.getTimerCount()).toBe(timersBefore - 1);
- vi.advanceTimersByTime(5000);
- expect(doubles.post).not.toHaveBeenCalled();
- });
-
- it('does nothing without a current user', () => {
- runInAction(() => {
- doubles.auth.currentUserId = null;
- });
-
- RollingTypingSender.startTyping(CHANNEL);
-
- expect(vi.getTimerCount()).toBe(0);
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(0);
- vi.advanceTimersByTime(5000);
- expect(doubles.post).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/typing/rolling/RollingTypingStore.test.ts b/fluxer_app/src/features/typing/rolling/RollingTypingStore.test.ts
deleted file mode 100644
index 9fb143c46..000000000
--- a/fluxer_app/src/features/typing/rolling/RollingTypingStore.test.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {autorun, runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = await vi.hoisted(async () => {
- const {observable} = await import('mobx');
- return {
- auth: observable({currentUserId: 'me' as string | null}),
- developerOptions: observable({showMyselfTyping: false}),
- blockedUserIds: observable.set<string>(),
- users: observable.map<string, {id: string}>(),
- };
-});
-
-vi.mock('@app/features/auth/state/Authentication', () => ({default: doubles.auth}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: doubles.developerOptions}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({
- default: {isBlocked: (userId: string) => doubles.blockedUserIds.has(userId)},
-}));
-vi.mock('@app/features/user/state/Users', () => ({
- default: {getUser: (userId: string) => doubles.users.get(userId)},
-}));
-
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-const CHANNEL = 'channel';
-
-beforeEach(() => {
- vi.useFakeTimers();
- runInAction(() => {
- doubles.auth.currentUserId = 'me';
- doubles.developerOptions.showMyselfTyping = false;
- doubles.blockedUserIds.clear();
- doubles.users.clear();
- for (const id of ['me', 'alice', 'bob', 'carol']) {
- doubles.users.set(id, {id});
- }
- });
-});
-
-afterEach(() => {
- RollingTypingStore.reset();
- vi.restoreAllMocks();
- vi.useRealTimers();
-});
-
-describe('RollingTypingStore', () => {
- it('arms a 10000 ms expiry for a new typist', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- expect(vi.getTimerCount()).toBe(1);
-
- vi.advanceTimersByTime(9999);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
-
- vi.advanceTimersByTime(1);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(false);
- expect(vi.getTimerCount()).toBe(0);
- });
-
- it('restarts the window on a repeated typing start', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- vi.advanceTimersByTime(6000);
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- expect(vi.getTimerCount()).toBe(1);
-
- vi.advanceTimersByTime(9999);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
-
- vi.advanceTimersByTime(1);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(false);
- });
-
- it('keeps insertion order when a typist refreshes', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- RollingTypingStore.start(CHANNEL, 'bob', 'gateway');
- RollingTypingStore.start(CHANNEL, 'carol', 'gateway');
- vi.advanceTimersByTime(3000);
-
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
-
- expect(RollingTypingStore.getTypingUserIds(CHANNEL)).toEqual(['alice', 'bob', 'carol']);
- });
-
- it('does not notify observers when an existing entry is refreshed', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- const runs = vi.fn();
- const dispose = autorun(() => {
- runs(
- RollingTypingStore.getTypingUserIds(CHANNEL),
- RollingTypingStore.countTypists(CHANNEL),
- RollingTypingStore.isTyping(CHANNEL, 'alice'),
- RollingTypingStore.isConfirmedTyping(CHANNEL, 'alice'),
- );
- });
- expect(runs).toHaveBeenCalledTimes(1);
-
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- RollingTypingStore.start(CHANNEL, 'alice', 'local');
- vi.advanceTimersByTime(9000);
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
-
- expect(runs).toHaveBeenCalledTimes(1);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
- dispose();
- });
-
- it('marks an entry confirmed only from a gateway typing start', () => {
- RollingTypingStore.start(CHANNEL, 'me', 'local');
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(true);
- expect(RollingTypingStore.isConfirmedTyping(CHANNEL, 'me')).toBe(false);
-
- RollingTypingStore.start(CHANNEL, 'me', 'gateway');
-
- expect(RollingTypingStore.isConfirmedTyping(CHANNEL, 'me')).toBe(true);
- });
-
- it('never lowers a confirmed entry on a local write', () => {
- RollingTypingStore.start(CHANNEL, 'me', 'gateway');
- RollingTypingStore.start(CHANNEL, 'me', 'local');
-
- expect(RollingTypingStore.isConfirmedTyping(CHANNEL, 'me')).toBe(true);
- });
-
- it('removes the author on message create for any author', () => {
- RollingTypingStore.start(CHANNEL, 'me', 'local');
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
-
- RollingTypingStore.remove(CHANNEL, 'alice');
- RollingTypingStore.remove(CHANNEL, 'me');
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(false);
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- expect(vi.getTimerCount()).toBe(0);
- });
-
- it('wipes every entry and clears every timer on reset', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- RollingTypingStore.start(CHANNEL, 'me', 'local');
- RollingTypingStore.start('other-channel', 'bob', 'gateway');
- expect(RollingTypingStore.getTypingUserIds(CHANNEL)).toEqual(['alice']);
- expect(vi.getTimerCount()).toBe(3);
-
- RollingTypingStore.reset();
-
- expect(vi.getTimerCount()).toBe(0);
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(0);
- expect(RollingTypingStore.countTypists('other-channel')).toBe(0);
- expect(RollingTypingStore.getTypingUserIds(CHANNEL)).toEqual([]);
- });
-
- it('does not let a timer from before a reset expire a fresh entry', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- vi.advanceTimersByTime(6000);
- RollingTypingStore.reset();
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
-
- vi.advanceTimersByTime(4000);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
-
- vi.advanceTimersByTime(5999);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
-
- vi.advanceTimersByTime(1);
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(false);
- });
-
- it('ignores an expiry callback whose handle has been replaced', () => {
- const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- const staleExpiry = setTimeoutSpy.mock.calls[0]![0] as () => void;
-
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- staleExpiry();
-
- expect(RollingTypingStore.isTyping(CHANNEL, 'alice')).toBe(true);
- expect(vi.getTimerCount()).toBe(1);
- });
-
- it('counts raw entries including self and blocked users', () => {
- runInAction(() => {
- doubles.blockedUserIds.add('bob');
- doubles.users.delete('carol');
- });
- RollingTypingStore.start(CHANNEL, 'me', 'local');
- RollingTypingStore.start(CHANNEL, 'bob', 'gateway');
- RollingTypingStore.start(CHANNEL, 'carol', 'gateway');
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
-
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(4);
- expect(RollingTypingStore.getTypingUserIds(CHANNEL)).toEqual(['alice']);
- });
-
- it('keeps no cap on tracked typists', () => {
- runInAction(() => {
- for (let index = 0; index < 50; index += 1) {
- doubles.users.set(`typist-${index}`, {id: `typist-${index}`});
- }
- });
- for (let index = 0; index < 50; index += 1) {
- RollingTypingStore.start(CHANNEL, `typist-${index}`, 'gateway');
- }
-
- expect(RollingTypingStore.countTypists(CHANNEL)).toBe(50);
- expect(RollingTypingStore.getTypingUserIds(CHANNEL)).toHaveLength(50);
- });
-
- it('drops the channel map when its last typist leaves', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- RollingTypingStore.start(CHANNEL, 'bob', 'gateway');
-
- RollingTypingStore.remove(CHANNEL, 'alice');
- expect(RollingTypingStore['entries'].has(CHANNEL)).toBe(true);
-
- RollingTypingStore.remove(CHANNEL, 'bob');
- expect(RollingTypingStore['entries'].has(CHANNEL)).toBe(false);
-
- RollingTypingStore.start(CHANNEL, 'carol', 'gateway');
- vi.advanceTimersByTime(10000);
- expect(RollingTypingStore['entries'].has(CHANNEL)).toBe(false);
- });
-
- it('notifies a member row reader only for its own user', () => {
- RollingTypingStore.start(CHANNEL, 'alice', 'gateway');
- const aliceRow = vi.fn();
- const bobRow = vi.fn();
- const disposeAliceRow = autorun(() => aliceRow(RollingTypingStore.isTyping(CHANNEL, 'alice')));
- const disposeBobRow = autorun(() => bobRow(RollingTypingStore.isTyping(CHANNEL, 'bob')));
-
- RollingTypingStore.start(CHANNEL, 'carol', 'gateway');
- RollingTypingStore.start(CHANNEL, 'me', 'local');
- RollingTypingStore.start(CHANNEL, 'me', 'gateway');
- RollingTypingStore.remove(CHANNEL, 'carol');
- expect(aliceRow).toHaveBeenCalledTimes(1);
- expect(bobRow).toHaveBeenCalledTimes(1);
-
- RollingTypingStore.start(CHANNEL, 'bob', 'gateway');
- expect(bobRow).toHaveBeenCalledTimes(2);
- expect(bobRow).toHaveBeenLastCalledWith(true);
- expect(aliceRow).toHaveBeenCalledTimes(1);
-
- RollingTypingStore.remove(CHANNEL, 'bob');
- expect(bobRow).toHaveBeenCalledTimes(3);
- expect(bobRow).toHaveBeenLastCalledWith(false);
- expect(aliceRow).toHaveBeenCalledTimes(1);
-
- disposeAliceRow();
- disposeBobRow();
- });
-});
diff --git a/fluxer_app/src/features/typing/rolling/RollingTypingText.test.tsx b/fluxer_app/src/features/typing/rolling/RollingTypingText.test.tsx
deleted file mode 100644
index 1853e6516..000000000
--- a/fluxer_app/src/features/typing/rolling/RollingTypingText.test.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {join} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import type {Channel} from '@app/features/channel/models/Channel';
-import type {User} from '@app/features/user/models/User';
-import type {I18n} from '@lingui/core';
-import {createElement, Fragment, type ReactNode} from 'react';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = vi.hoisted(() => ({
- getNickname: vi.fn((user: {id: string}, guildId: string | null) => `${user.id} in ${guildId ?? 'no guild'}`),
-}));
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: {message: string}) => descriptor}));
-vi.mock('@lingui/react/macro', async () => {
- const {createElement: create, Fragment: ReactFragment} = await import('react');
- return {Trans: ({children}: {children?: ReactNode}) => create(ReactFragment, null, children)};
-});
-vi.mock('@app/features/user/utils/NicknameUtils', () => ({getNickname: doubles.getNickname}));
-vi.mock('@app/features/member/state/GuildMembers', () => ({
- default: {getMember: () => ({getColorString: () => 'rgb(1, 2, 3)'})},
-}));
-
-const {getRollingTypingAnnouncement, getRollingTypingText} = await import(
- '@app/features/typing/rolling/RollingTypingText'
-);
-
-const APP_SRC = fileURLToPath(new URL('../../../', import.meta.url));
-const GUILD_CHANNEL = {id: 'channel', guildId: 'guild'} as unknown as Channel;
-const DM_CHANNEL = {id: 'dm'} as unknown as Channel;
-
-function i18nFor(locale: string): I18n {
- return {
- locale,
- _: (descriptor: {message: string}, values: Record<string, string> = {}) =>
- descriptor.message.replace(/\{(\w+)\}/g, (_placeholder, name: string) => values[name] ?? ''),
- } as unknown as I18n;
-}
-
-const EN_US = i18nFor('en-US');
-const DE = i18nFor('de');
-
-function typists(count: number): Array<User> {
- return Array.from({length: count}, (_, index) => ({id: `typist-${index + 1}`}) as unknown as User);
-}
-
-function markupOf(node: ReactNode): string {
- return renderToStaticMarkup(createElement(Fragment, null, node));
-}
-
-function textOf(node: ReactNode): string {
- return markupOf(node).replace(/<[^>]+>/g, '');
-}
-
-function transMessages(source: string): Array<string> {
- return [...source.matchAll(/<Trans>([\s\S]*?)<\/Trans>/g)].map((match) => match[1]!.replace(/\s+/g, ' ').trim());
-}
-
-function catalogueIds(locale: string): Set<string> {
- const catalogue = readFileSync(join(APP_SRC, `features/i18n/locales/${locale}/messages.po`), 'utf8');
- return new Set([...catalogue.matchAll(/^msgid "(.*)"$/gm)].map((match) => match[1]!));
-}
-
-afterEach(() => {
- doubles.getNickname.mockClear();
-});
-
-describe('getRollingTypingText', () => {
- it('names a single typist', () => {
- const node = getRollingTypingText(EN_US, typists(1), GUILD_CHANNEL, false);
-
- expect(textOf(node)).toBe('typist-1 in guild is typing...');
- expect(markupOf(node)).toContain('data-flx="channel.typing-users.get-typing-text.username"');
- expect(markupOf(node)).toContain('color:rgb(1, 2, 3)');
- });
-
- it('names two typists', () => {
- expect(textOf(getRollingTypingText(EN_US, typists(2), GUILD_CHANNEL, false))).toBe(
- 'typist-1 in guild and typist-2 in guild are typing...',
- );
- });
-
- it('names three typists without an Oxford comma', () => {
- expect(textOf(getRollingTypingText(EN_US, typists(3), GUILD_CHANNEL, false))).toBe(
- 'typist-1 in guild, typist-2 in guild and typist-3 in guild are typing...',
- );
- });
-
- it('collapses four typists to several people', () => {
- expect(getRollingTypingText(EN_US, typists(4), GUILD_CHANNEL, false)).toBe('Several people are typing...');
- expect(getRollingTypingText(DE, typists(4), GUILD_CHANNEL, false)).toBe('Several people are typing...');
- expect(doubles.getNickname).not.toHaveBeenCalled();
- });
-
- it('collapses twenty typists to several people', () => {
- expect(getRollingTypingText(DE, typists(20), GUILD_CHANNEL, false)).toBe('Several people are typing...');
- expect(getRollingTypingText(EN_US, typists(20), GUILD_CHANNEL, false)).toBe("Whoa, it's a typing apocalypse");
- });
-
- it('shows multiple people for one to three typists when overflowing', () => {
- for (const count of [1, 2, 3]) {
- expect(getRollingTypingText(EN_US, typists(count), GUILD_CHANNEL, true)).toBe('Multiple people are typing...');
- }
- });
-
- it('never shows the overflow string for four or more typists', () => {
- expect(getRollingTypingText(EN_US, typists(4), GUILD_CHANNEL, true)).toBe('Several people are typing...');
- expect(getRollingTypingText(DE, typists(12), GUILD_CHANNEL, true)).toBe('Several people are typing...');
- expect(getRollingTypingText(EN_US, typists(12), GUILD_CHANNEL, true)).toBe(
- 'A symphony of clacking keys is underway...',
- );
- });
-});
-
-describe('getRollingTypingAnnouncement', () => {
- it('announces the full count-based string for three typists', () => {
- expect(getRollingTypingAnnouncement(EN_US, typists(1), GUILD_CHANNEL)).toBe('typist-1 in guild is typing...');
- expect(getRollingTypingAnnouncement(EN_US, typists(2), GUILD_CHANNEL)).toBe(
- 'typist-1 in guild and typist-2 in guild are typing...',
- );
- expect(getRollingTypingAnnouncement(EN_US, typists(3), GUILD_CHANNEL)).toBe(
- 'typist-1 in guild, typist-2 in guild and typist-3 in guild are typing...',
- );
- });
-
- it('announces several people for four or more typists', () => {
- expect(getRollingTypingAnnouncement(EN_US, typists(4), GUILD_CHANNEL)).toBe('Several people are typing...');
- expect(getRollingTypingAnnouncement(DE, typists(4), GUILD_CHANNEL)).toBe('Several people are typing...');
- expect(getRollingTypingAnnouncement(DE, typists(16), GUILD_CHANNEL)).toBe('Several people are typing...');
- expect(getRollingTypingAnnouncement(EN_US, typists(16), GUILD_CHANNEL)).toBe(
- "It's a full-blown typing fiesta in here",
- );
- });
-
- it('announces nothing when nobody is typing', () => {
- expect(getRollingTypingAnnouncement(EN_US, [], GUILD_CHANNEL)).toBe('');
- expect(getRollingTypingText(EN_US, [], GUILD_CHANNEL, false)).toBeNull();
- });
-});
-
-describe('rolling typing catalogue', () => {
- it('keeps each named form in the source catalogue', () => {
- const rollingSource = readFileSync(join(APP_SRC, 'features/typing/rolling/RollingTypingText.tsx'), 'utf8');
- const namedForms = ['{a} is typing...', '{a} and {b} are typing...', '{a}, {b} and {c} are typing...'];
- const declaredMessages = [...rollingSource.matchAll(/message: '([^']*)'/g)].map((match) => match[1]);
-
- expect(transMessages(rollingSource)).toEqual(namedForms);
- expect(declaredMessages).toEqual([...namedForms, 'Multiple people are typing...']);
- const sourceCatalogue = catalogueIds('en-US');
- for (const message of [...namedForms, 'Several people are typing...']) {
- expect(sourceCatalogue.has(message), message).toBe(true);
- }
- });
-
- it('resolves guild nicknames for names', () => {
- const [typist] = typists(1);
-
- expect(textOf(getRollingTypingText(EN_US, [typist!], GUILD_CHANNEL, false))).toBe('typist-1 in guild is typing...');
- expect(getRollingTypingAnnouncement(EN_US, [typist!], DM_CHANNEL)).toBe('typist-1 in no guild is typing...');
- expect(doubles.getNickname.mock.calls).toEqual([
- [typist, 'guild'],
- [typist, null],
- ]);
- });
-});
diff --git a/fluxer_app/src/features/typing/rolling/TypingSendThrottle.test.ts b/fluxer_app/src/features/typing/rolling/TypingSendThrottle.test.ts
deleted file mode 100644
index 92eac90ba..000000000
--- a/fluxer_app/src/features/typing/rolling/TypingSendThrottle.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {planTypingSend, type TypingSendSlot} from '@app/features/typing/rolling/TypingSendThrottle';
-import {describe, expect, it} from 'vitest';
-
-const PREVIOUS_SEND = 100000;
-const PENDING_TIMEOUT = {} as NodeJS.Timeout;
-
-function slot(overrides: Partial<TypingSendSlot> = {}): TypingSendSlot {
- return {channelId: 'channel', userId: 'me', timeout: null, prevSend: PREVIOUS_SEND, ...overrides};
-}
-
-describe('planTypingSend', () => {
- it('schedules the first ever send after 1500 ms', () => {
- expect(planTypingSend(null, 'channel', 'me', PREVIOUS_SEND)).toEqual({
- dropSlot: false,
- action: 'schedule',
- delayMs: 1500,
- });
- });
-
- it('throttles while a send is pending', () => {
- expect(planTypingSend(slot({timeout: PENDING_TIMEOUT, prevSend: 0}), 'channel', 'me', PREVIOUS_SEND)).toEqual({
- dropSlot: false,
- action: 'throttled',
- });
- });
-
- it('throttles when the previous schedule is less than 8000 ms old', () => {
- expect(planTypingSend(slot(), 'channel', 'me', PREVIOUS_SEND + 7999)).toEqual({
- dropSlot: false,
- action: 'throttled',
- });
- });
-
- it('schedules exactly 8000 ms after the previous schedule', () => {
- expect(planTypingSend(slot(), 'channel', 'me', PREVIOUS_SEND + 8000)).toEqual({
- dropSlot: false,
- action: 'schedule',
- delayMs: 1500,
- });
- });
-
- it('schedules after 1500 ms when the previous schedule is less than 16000 ms old', () => {
- expect(planTypingSend(slot(), 'channel', 'me', PREVIOUS_SEND + 15999)).toEqual({
- dropSlot: false,
- action: 'schedule',
- delayMs: 1500,
- });
- });
-
- it('schedules after 0 ms when the previous schedule is exactly 16000 ms old', () => {
- expect(planTypingSend(slot(), 'channel', 'me', PREVIOUS_SEND + 16000)).toEqual({
- dropSlot: false,
- action: 'schedule',
- delayMs: 0,
- });
- });
-
- it('drops a slot for another channel and then schedules after 1500 ms', () => {
- expect(
- planTypingSend(slot({channelId: 'other', timeout: PENDING_TIMEOUT}), 'channel', 'me', PREVIOUS_SEND + 1),
- ).toEqual({dropSlot: true, action: 'schedule', delayMs: 1500});
- });
-
- it('drops a slot for another account before checking the throttle', () => {
- expect(
- planTypingSend(slot({userId: 'previous', timeout: PENDING_TIMEOUT}), 'channel', 'me', PREVIOUS_SEND + 1),
- ).toEqual({dropSlot: true, action: 'schedule', delayMs: 1500});
- });
-});
diff --git a/fluxer_app/src/features/typing/state/TypingIndicator.test.ts b/fluxer_app/src/features/typing/state/TypingIndicator.test.ts
deleted file mode 100644
index a57125843..000000000
--- a/fluxer_app/src/features/typing/state/TypingIndicator.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Message} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = vi.hoisted(() => ({
- post: vi.fn((_path: string) => Promise.resolve({ok: true})),
-}));
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {get: vi.fn(), post: doubles.post}}));
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: {showMyselfTyping: false}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: () => undefined}}));
-
-const {default: TypingIndicator} = await import('@app/features/typing/state/TypingIndicator');
-const {default: RollingTypingSender} = await import('@app/features/typing/rolling/RollingTypingSender');
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-const CHANNEL = 'channel';
-
-function messageFrom(authorId: string): Message {
- return {channel_id: CHANNEL, author: {id: authorId}} as unknown as Message;
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
-});
-
-afterEach(() => {
- RollingTypingSender.reset();
- RollingTypingStore.reset();
- vi.useRealTimers();
- vi.clearAllMocks();
-});
-
-describe('TypingIndicator', () => {
- it('records gateway typing starts as confirmed', () => {
- TypingIndicator.startRemoteTyping(CHANNEL, 'alice');
-
- expect(RollingTypingStore.isConfirmedTyping(CHANNEL, 'alice')).toBe(true);
- expect(TypingIndicator.isTyping(CHANNEL, 'alice')).toBe(true);
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'alice', 'me')).toBe(true);
- });
-
- it('reports self in the member list only after the server echo', () => {
- RollingTypingSender.startTyping(CHANNEL);
- expect(TypingIndicator.isTyping(CHANNEL, 'me')).toBe(true);
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'me', 'me')).toBe(false);
-
- vi.advanceTimersByTime(1500);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'me', 'me')).toBe(false);
-
- TypingIndicator.startRemoteTyping(CHANNEL, 'me');
-
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'me', 'me')).toBe(true);
- });
-
- it('keeps the self row dark when the post was skipped', () => {
- for (const userId of ['a', 'b', 'c', 'd', 'e']) {
- TypingIndicator.startRemoteTyping(CHANNEL, userId);
- }
-
- RollingTypingSender.startTyping(CHANNEL);
- vi.advanceTimersByTime(1500);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'me', 'me')).toBe(false);
- expect(TypingIndicator.isMemberListTyping(CHANNEL, 'a', 'me')).toBe(true);
- });
-
- it('keeps the send slot when the gateway resets', () => {
- TypingIndicator.startRemoteTyping(CHANNEL, 'alice');
- RollingTypingSender.startTyping(CHANNEL);
- vi.advanceTimersByTime(500);
-
- TypingIndicator.reset();
-
- expect(TypingIndicator.isTyping(CHANNEL, 'alice')).toBe(false);
- expect(TypingIndicator.isTyping(CHANNEL, 'me')).toBe(false);
- vi.advanceTimersByTime(1000);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('clears any author on message create', () => {
- TypingIndicator.startRemoteTyping(CHANNEL, 'alice');
- RollingTypingSender.startTyping(CHANNEL);
-
- TypingIndicator.stopTypingOnMessageCreate(messageFrom('alice'));
- TypingIndicator.stopTypingOnMessageCreate(messageFrom('me'));
-
- expect(TypingIndicator.isTyping(CHANNEL, 'alice')).toBe(false);
- expect(TypingIndicator.isTyping(CHANNEL, 'me')).toBe(false);
- vi.advanceTimersByTime(1500);
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_app/src/features/typing/utils/TypingTierText.test.ts b/fluxer_app/src/features/typing/utils/TypingTierText.test.ts
deleted file mode 100644
index c8999639d..000000000
--- a/fluxer_app/src/features/typing/utils/TypingTierText.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {I18n} from '@lingui/core';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: {message: string}) => descriptor}));
-
-const {getTypingTierText} = await import('@app/features/typing/utils/TypingTierText');
-
-function i18nFor(locale: string): I18n {
- return {locale, _: (descriptor: {message: string}) => `[${locale}] ${descriptor.message}`} as unknown as I18n;
-}
-
-describe('getTypingTierText', () => {
- it('uses the translatable several people line for exactly four typists in every locale', () => {
- for (const locale of ['en-US', 'en-GB', 'de', 'ja']) {
- expect(getTypingTierText(i18nFor(locale), 4)).toBe(`[${locale}] Several people are typing...`);
- }
- });
-
- it.each([
- ['en-US', 5, 'A handful of keyboard warriors are assembling...'],
- ['en-US', 9, 'A handful of keyboard warriors are assembling...'],
- ['en-GB', 10, 'A symphony of clacking keys is underway...'],
- ['en-US', 14, 'A symphony of clacking keys is underway...'],
- ['en-GB', 15, "It's a full-blown typing fiesta in here"],
- ['en-US', 19, "It's a full-blown typing fiesta in here"],
- ['en-GB', 20, "Whoa, it's a typing apocalypse"],
- ['en-US', 250, "Whoa, it's a typing apocalypse"],
- ])('keeps the untranslated joke line in %s for %i typists', (locale, count, line) => {
- expect(getTypingTierText(i18nFor(locale), count)).toBe(line);
- });
-
- it.each([
- 'ar',
- 'de',
- 'es-419',
- 'fr',
- 'ja',
- 'pt-BR',
- 'sv-SE',
- 'zh-TW',
- ])('collapses every crowd to the several people line in %s', (locale) => {
- for (const count of [5, 9, 10, 14, 15, 19, 20, 250]) {
- expect(getTypingTierText(i18nFor(locale), count)).toBe(`[${locale}] Several people are typing...`);
- }
- });
-
- it('treats a bare language code as a non-English locale', () => {
- expect(getTypingTierText(i18nFor('en'), 12)).toBe('[en] Several people are typing...');
- });
-});
diff --git a/fluxer_app/src/features/typing/utils/TypingUtils.test.ts b/fluxer_app/src/features/typing/utils/TypingUtils.test.ts
deleted file mode 100644
index 6aca0fa3a..000000000
--- a/fluxer_app/src/features/typing/utils/TypingUtils.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const doubles = vi.hoisted(() => ({
- post: vi.fn((_path: string) => Promise.resolve({ok: true})),
-}));
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-vi.mock('@app/features/platform/transport/RestTransport', () => ({http: {get: vi.fn(), post: doubles.post}}));
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'me'}}));
-vi.mock('@app/features/devtools/state/DeveloperOptions', () => ({default: {showMyselfTyping: false}}));
-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));
-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: () => undefined}}));
-
-const {TypingUtils} = await import('@app/features/typing/utils/TypingUtils');
-const {default: RollingTypingSender} = await import('@app/features/typing/rolling/RollingTypingSender');
-const {default: RollingTypingStore} = await import('@app/features/typing/rolling/RollingTypingStore');
-
-type ComposerTypingInput = Parameters<typeof TypingUtils.handleComposerChange>[0];
-
-const CHANNEL = 'channel';
-
-function composerChange(change: Partial<ComposerTypingInput>): ComposerTypingInput {
- return {
- channelId: CHANNEL,
- value: 'hello',
- previousValue: 'hell',
- enabled: true,
- typingEnabled: true,
- isEditingMessageInComposer: false,
- ...change,
- };
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
-});
-
-afterEach(() => {
- RollingTypingSender.reset();
- RollingTypingStore.reset();
- vi.useRealTimers();
- vi.clearAllMocks();
-});
-
-describe('TypingUtils', () => {
- it('cancels a pending send for clear', () => {
- TypingUtils.handleComposerChange(composerChange({}));
- vi.advanceTimersByTime(400);
-
- TypingUtils.clear(CHANNEL);
- vi.advanceTimersByTime(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- });
-
- it('drops the send slot on own message sent', () => {
- TypingUtils.handleComposerChange(composerChange({}));
- vi.advanceTimersByTime(1500);
- expect(doubles.post).toHaveBeenCalledTimes(1);
-
- TypingUtils.handleOwnMessageSent(CHANNEL);
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- vi.advanceTimersByTime(100);
- TypingUtils.handleComposerChange(composerChange({previousValue: '', value: 'n'}));
- vi.advanceTimersByTime(1500);
-
- expect(doubles.post).toHaveBeenCalledTimes(2);
- });
-
- it('starts typing while an autocomplete trigger is typed', () => {
- TypingUtils.handleComposerChange(composerChange({previousValue: '@al', value: '@ali'}));
- vi.advanceTimersByTime(1500);
-
- expect(doubles.post).toHaveBeenCalledTimes(1);
- });
-
- it('posts nothing for a spaces-only draft', () => {
- TypingUtils.handleComposerChange(composerChange({previousValue: '', value: ' '}));
- TypingUtils.handleComposerChange(composerChange({previousValue: ' ', value: ' '}));
- vi.advanceTimersByTime(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- expect(RollingTypingStore.isTyping(CHANNEL, 'me')).toBe(false);
- });
-
- it('treats a composer with typing turned off as disabled', () => {
- TypingUtils.handleComposerChange(composerChange({typingEnabled: false}));
- vi.advanceTimersByTime(20000);
-
- expect(doubles.post).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItems.test.tsx b/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItems.test.tsx
deleted file mode 100644
index a276bd5cf..000000000
--- a/fluxer_app/src/features/ui/action_menu/items/CloneExpressionMenuItems.test.tsx
+++ /dev/null
@@ -1,295 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {FlatEmoji} from '@app/features/emoji/types/EmojiTypes';
-import type React from 'react';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface MetadataRequestState {
- loading: boolean;
- error: Error | null;
- data: {id: string; guildId: string; name: string; animated: boolean; allowCloning: boolean} | null;
-}
-
-const emojiMetadataState: MetadataRequestState = {loading: false, error: null, data: null};
-const stickerMetadataState: MetadataRequestState = {loading: false, error: null, data: null};
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@phosphor-icons/react', () => ({CopyIcon: () => null}));
-vi.mock('@app/features/app/components/alerts/ExpressionCloneFailedModal', () => ({
- showExpressionCloneFailedModal: vi.fn(),
-}));
-vi.mock('@app/features/expressions/commands/GuildEmojiCommands', () => ({clone: vi.fn()}));
-vi.mock('@app/features/expressions/commands/GuildStickerCommands', () => ({clone: vi.fn()}));
-vi.mock('@app/features/emoji/state/Emoji', () => ({default: {getGuildEmoji: () => []}}));
-vi.mock('@app/features/emoji/state/EmojiSticker', () => ({default: {getGuildStickers: () => []}}));
-vi.mock('@app/features/expressions/state/ExpressionMetadata', () => ({
- default: {
- getEmojiMetadata: () => emojiMetadataState,
- fetchEmojiMetadata: vi.fn(),
- getStickerMetadata: () => stickerMetadataState,
- fetchStickerMetadata: vi.fn(),
- },
-}));
-vi.mock('@app/features/guild/components/popouts/GuildIcon', () => ({GuildIcon: () => null}));
-vi.mock('@app/features/permissions/state/Permission', () => ({default: {can: () => true}}));
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- error(): void {}
- },
-}));
-vi.mock('@app/lib/overlay/KeyedActionGuard', () => ({
- createKeyedActionGuard: () => ({begin: () => true, scheduleRelease: () => {}}),
-}));
-vi.mock('@app/features/ui/action_menu/MenuGroup', () => ({
- MenuGroup: ({children}: {children?: React.ReactNode}) => <div>{children}</div>,
-}));
-vi.mock('@app/features/ui/action_menu/MenuItem', () => ({
- MenuItem: ({children, hint}: {children?: React.ReactNode; hint?: string}) => <div data-hint={hint}>{children}</div>,
-}));
-vi.mock('@app/features/ui/action_menu/MenuItemSubmenu', () => ({
- MenuItemSubmenu: ({label, render}: {label: string; render?: () => React.ReactNode}) => (
- <div data-submenu="true">
- {label}
- {render?.()}
- </div>
- ),
-}));
-vi.mock('@app/features/ui/commands/ToastCommands', () => ({success: vi.fn()}));
-
-const sourceGuild = {
- id: '1',
- name: 'Source',
- icon: null,
- maxEmojis: 50,
- maxStickers: 50,
- cloneEmojiAllowed: false,
- cloneStickerAllowed: false,
-};
-const targetGuild = {id: '2', name: 'Target', icon: null, maxEmojis: 50, maxStickers: 50};
-const UNJOINED_GUILD_ID = '99';
-
-vi.mock('@app/features/guild/state/Guilds', () => ({
- default: {
- getGuild: (id: string) => (id === sourceGuild.id ? sourceGuild : id === targetGuild.id ? targetGuild : null),
- getGuilds: () => [sourceGuild, targetGuild],
- },
-}));
-
-const {default: AdvancedSettings} = await import('@app/features/user/state/AdvancedSettings');
-const {CloneEmojiMenuItem} = await import('@app/features/ui/action_menu/items/CloneEmojiMenuItem');
-const {CloneStickerMenuItem} = await import('@app/features/ui/action_menu/items/CloneStickerMenuItem');
-
-const emoji = {id: '10', guildId: sourceGuild.id, name: 'blob', uniqueName: 'blob'} as unknown as FlatEmoji;
-const unjoinedEmoji = {id: '11', guildId: UNJOINED_GUILD_ID, name: 'blob', uniqueName: 'blob'} as unknown as FlatEmoji;
-const sticker = {id: '20', guildId: sourceGuild.id, name: 'blobsticker', animated: false};
-const unjoinedSticker = {id: '21', guildId: UNJOINED_GUILD_ID, name: 'blobsticker', animated: false};
-
-const EMOJI_SUBMENU_LABEL = 'Clone emoji to...';
-const STICKER_SUBMENU_LABEL = 'Clone sticker to…';
-const LOADING_HINT = 'Checking access...';
-
-function renderEmojiItem(): string {
- return renderToStaticMarkup(<CloneEmojiMenuItem emoji={emoji} onClose={() => {}} />);
-}
-
-function renderUnjoinedEmojiItem(): string {
- return renderToStaticMarkup(<CloneEmojiMenuItem emoji={unjoinedEmoji} onClose={() => {}} />);
-}
-
-function renderStickerItem(): string {
- return renderToStaticMarkup(<CloneStickerMenuItem sticker={sticker} onClose={() => {}} />);
-}
-
-function renderUnjoinedStickerItem(): string {
- return renderToStaticMarkup(<CloneStickerMenuItem sticker={unjoinedSticker} onClose={() => {}} />);
-}
-
-function resolvedMetadata(allowCloning: boolean): MetadataRequestState['data'] {
- return {id: '11', guildId: UNJOINED_GUILD_ID, name: 'blob', animated: false, allowCloning};
-}
-
-type Outcome = 'submenu' | 'loading' | 'hidden';
-
-interface Scenario {
- name: string;
- outcome: Outcome;
- arrange: () => void;
- render: () => string;
-}
-
-interface Harness {
- kind: string;
- submenuLabel: string;
- setSourceGuildAllowed: (value: boolean) => void;
- metadata: MetadataRequestState;
- renderJoined: () => string;
- renderUnjoined: () => string;
-}
-
-const emojiHarness: Harness = {
- kind: 'emoji',
- submenuLabel: EMOJI_SUBMENU_LABEL,
- setSourceGuildAllowed: (value) => {
- sourceGuild.cloneEmojiAllowed = value;
- },
- metadata: emojiMetadataState,
- renderJoined: renderEmojiItem,
- renderUnjoined: renderUnjoinedEmojiItem,
-};
-
-const stickerHarness: Harness = {
- kind: 'sticker',
- submenuLabel: STICKER_SUBMENU_LABEL,
- setSourceGuildAllowed: (value) => {
- sourceGuild.cloneStickerAllowed = value;
- },
- metadata: stickerMetadataState,
- renderJoined: renderStickerItem,
- renderUnjoined: renderUnjoinedStickerItem,
-};
-
-function buildScenarios(harness: Harness): ReadonlyArray<Scenario> {
- return [
- {
- name: 'the source community is known and has opted in',
- outcome: 'submenu',
- arrange: () => harness.setSourceGuildAllowed(true),
- render: harness.renderJoined,
- },
- {
- name: 'the source community is known and has not opted in',
- outcome: 'hidden',
- arrange: () => harness.setSourceGuildAllowed(false),
- render: harness.renderJoined,
- },
- {
- name: 'the source community is unknown and metadata resolved with cloning allowed',
- outcome: 'submenu',
- arrange: () => {
- harness.metadata.data = resolvedMetadata(true);
- },
- render: harness.renderUnjoined,
- },
- {
- name: 'the source community is unknown and metadata resolved with cloning disallowed',
- outcome: 'hidden',
- arrange: () => {
- harness.metadata.data = resolvedMetadata(false);
- },
- render: harness.renderUnjoined,
- },
- {
- name: 'the source community is unknown and the metadata lookup errored',
- outcome: 'hidden',
- arrange: () => {
- harness.metadata.error = new Error('metadata lookup failed');
- },
- render: harness.renderUnjoined,
- },
- {
- name: 'the source community is unknown and the metadata lookup has not started',
- outcome: 'hidden',
- arrange: () => {},
- render: harness.renderUnjoined,
- },
- {
- name: 'the source community is unknown and the metadata lookup is still in flight',
- outcome: 'loading',
- arrange: () => {
- harness.metadata.loading = true;
- },
- render: harness.renderUnjoined,
- },
- ];
-}
-
-function expectOutcome(markup: string, outcome: Outcome, submenuLabel: string): void {
- if (outcome === 'hidden') {
- expect(markup).toBe('');
- return;
- }
- if (outcome === 'loading') {
- expect(markup).toContain(submenuLabel);
- expect(markup).toContain(LOADING_HINT);
- expect(markup).not.toContain('data-submenu');
- return;
- }
- expect(markup).toContain('data-submenu');
- expect(markup).toContain(submenuLabel);
- expect(markup).toContain(targetGuild.name);
- expect(markup).not.toContain(LOADING_HINT);
-}
-
-describe('Clone expression menu items', () => {
- beforeEach(() => {
- AdvancedSettings.setExpressionCloneShortcutsEnabled(false);
- sourceGuild.cloneEmojiAllowed = false;
- sourceGuild.cloneStickerAllowed = false;
- for (const state of [emojiMetadataState, stickerMetadataState]) {
- state.loading = false;
- state.error = null;
- state.data = null;
- }
- });
-
- it('defaults the user setting to off', () => {
- expect(AdvancedSettings.expressionCloneShortcutsEnabled).toBe(false);
- });
-
- it('hides both shortcuts when the user setting is off and the community allows cloning', () => {
- sourceGuild.cloneEmojiAllowed = true;
- sourceGuild.cloneStickerAllowed = true;
- expect(renderEmojiItem()).toBe('');
- expect(renderStickerItem()).toBe('');
- });
-
- it('hides both shortcuts when the user setting is on and the community does not allow cloning', () => {
- AdvancedSettings.setExpressionCloneShortcutsEnabled(true);
- expect(renderEmojiItem()).toBe('');
- expect(renderStickerItem()).toBe('');
- });
-
- it('shows both shortcuts when the user setting is on and the community allows cloning', () => {
- AdvancedSettings.setExpressionCloneShortcutsEnabled(true);
- sourceGuild.cloneEmojiAllowed = true;
- sourceGuild.cloneStickerAllowed = true;
- expect(renderEmojiItem()).toContain(EMOJI_SUBMENU_LABEL);
- expect(renderStickerItem()).toContain(STICKER_SUBMENU_LABEL);
- });
-});
-
-for (const harness of [emojiHarness, stickerHarness]) {
- describe(`Clone ${harness.kind} shortcut gating`, () => {
- beforeEach(() => {
- AdvancedSettings.setExpressionCloneShortcutsEnabled(false);
- sourceGuild.cloneEmojiAllowed = false;
- sourceGuild.cloneStickerAllowed = false;
- for (const state of [emojiMetadataState, stickerMetadataState]) {
- state.loading = false;
- state.error = null;
- state.data = null;
- }
- });
-
- for (const scenario of buildScenarios(harness)) {
- it(`renders the ${scenario.outcome} state when ${scenario.name}`, () => {
- AdvancedSettings.setExpressionCloneShortcutsEnabled(true);
- scenario.arrange();
- expectOutcome(scenario.render(), scenario.outcome, harness.submenuLabel);
- });
-
- it(`hides the shortcut with the user setting off when ${scenario.name}`, () => {
- scenario.arrange();
- expect(scenario.render()).toBe('');
- });
- }
- });
-}
diff --git a/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantMenuTypes.test.ts b/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantMenuTypes.test.ts
deleted file mode 100644
index 768d593b6..000000000
--- a/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantMenuTypes.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {describe, expect, it, vi} from 'vitest';
-
-const errors: Array<unknown> = [];
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- error(...args: Array<unknown>) {
- errors.push(args);
- }
- },
-}));
-
-const {normalizeVoiceParticipantMenuRequest} = await import(
- '@app/features/ui/action_menu/items/VoiceParticipantMenuTypes'
-);
-
-describe('normalizeVoiceParticipantMenuRequest', () => {
- it('passes participant sources through on every surface', () => {
- expect(normalizeVoiceParticipantMenuRequest({surface: 'participant-list', source: {kind: 'participant'}})).toEqual({
- kind: 'participant',
- });
- expect(
- normalizeVoiceParticipantMenuRequest({
- surface: 'stream-spectator-list',
- source: {kind: 'participant', focusSource: 'camera'},
- }),
- ).toEqual({kind: 'participant', focusSource: 'camera'});
- });
-
- it('keeps camera and screen-share sources on the call-tile surface', () => {
- expect(normalizeVoiceParticipantMenuRequest({surface: 'call-tile', source: {kind: 'camera'}})).toEqual({
- kind: 'camera',
- });
- const screenShare = {kind: 'screen-share', streamKey: 'guild:channel:conn', state: {kind: 'own'}} as const;
- expect(normalizeVoiceParticipantMenuRequest({surface: 'call-tile', source: screenShare})).toBe(screenShare);
- });
-
- it('degrades to a participant menu instead of throwing on a mismatched surface', () => {
- errors.length = 0;
- expect(normalizeVoiceParticipantMenuRequest({surface: 'call-avatar', source: {kind: 'camera'}})).toEqual({
- kind: 'participant',
- focusSource: 'camera',
- });
- expect(
- normalizeVoiceParticipantMenuRequest({
- surface: 'participant-list',
- source: {kind: 'screen-share', streamKey: 'guild:channel:conn', state: {kind: 'own'}},
- }),
- ).toEqual({kind: 'participant', focusSource: 'screen-share'});
- expect(errors).toHaveLength(2);
- });
-
- it('degrades to a participant menu when a screen-share source has an empty stream key', () => {
- errors.length = 0;
- expect(
- normalizeVoiceParticipantMenuRequest({
- surface: 'call-tile',
- source: {kind: 'screen-share', streamKey: '', state: {kind: 'own'}},
- }),
- ).toEqual({kind: 'participant', focusSource: 'screen-share'});
- expect(errors).toHaveLength(1);
- });
-});
diff --git a/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantStreamMenuBuilder.test.tsx b/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantStreamMenuBuilder.test.tsx
deleted file mode 100644
index a64853aba..000000000
--- a/fluxer_app/src/features/ui/action_menu/items/VoiceParticipantStreamMenuBuilder.test.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {VoiceParticipantMenuScreenShareSource} from '@app/features/ui/action_menu/items/VoiceParticipantMenuTypes';
-import type {I18n} from '@lingui/core';
-import {beforeEach, expect, test, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-vi.mock('@app/features/voice/components/ActiveScreenShareMenu', () => ({
- changeActiveScreenShare: vi.fn(async () => undefined),
- stopActiveScreenShare: vi.fn(async () => undefined),
-}));
-vi.mock('@app/features/voice/components/modals/ScreenSharePickerModal', () => ({
- openScreenSharePreviewPrivacyModal: vi.fn(),
-}));
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: {
- applyLocalAudioPreferencesForUser: vi.fn(),
- getVoiceStateByConnectionId: () => null,
- connectionId: null,
- },
-}));
-vi.mock('@app/features/voice/state/PopoutWindowManager', () => ({
- default: {openTilePopout: vi.fn()},
- isVoicePopoutSupported: () => false,
-}));
-vi.mock('@app/features/voice/state/StreamAudioPrefs', () => ({
- default: {setMuted: vi.fn(), setVolume: vi.fn()},
-}));
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {showMyOwnScreenShare: false, pauseOwnScreenSharePreviewOnUnfocus: false},
-}));
-vi.mock('@app/features/voice/commands/VoiceDiagnosticsCommands', () => ({
- copyVoiceDiagnostics: vi.fn(async () => undefined),
-}));
-vi.mock('@app/features/voice/commands/VoiceSettingsCommands', () => ({
- update: vi.fn(),
-}));
-
-installVoiceMenuTestBootstrap();
-
-const {buildVoiceParticipantStreamMenu} = await import(
- '@app/features/ui/action_menu/items/VoiceParticipantStreamMenuBuilder'
-);
-const {copyVoiceDiagnostics} = await import('@app/features/voice/commands/VoiceDiagnosticsCommands');
-
-const i18n = {
- locale: 'en',
- _: (descriptor: {message?: string}) => descriptor.message ?? '',
-} as unknown as I18n;
-
-interface MenuLeaf {
- label?: string;
- items?: Array<MenuLeaf>;
- onClick?: () => void;
-}
-
-function streamMenu(source: VoiceParticipantMenuScreenShareSource): Array<{items: Array<MenuLeaf>}> {
- return buildVoiceParticipantStreamMenu({
- i18n,
- userId: '111',
- channelId: null,
- participantIdentity: 'user_111_conn',
- displayName: 'Alice',
- isCurrentUserConnectedToVoice: false,
- source,
- streamVolume: 100,
- isStreamMuted: false,
- showMyOwnScreenShare: false,
- pauseOwnScreenSharePreviewOnUnfocus: false,
- onClose: () => undefined,
- }) as unknown as Array<{items: Array<MenuLeaf>}>;
-}
-
-function findLeaf(groups: Array<{items: Array<MenuLeaf>}>, label: string): MenuLeaf | null {
- for (const group of groups) {
- for (const item of group.items) {
- if (item.label === label) return item;
- for (const child of item.items ?? []) {
- if (child.label === label) return child;
- }
- }
- }
- return null;
-}
-
-const OWN_STREAM_SOURCE: VoiceParticipantMenuScreenShareSource = {
- kind: 'screen-share',
- streamKey: 'stream-key',
- state: {kind: 'own'},
-};
-
-const WATCHED_REMOTE_STREAM_SOURCE: VoiceParticipantMenuScreenShareSource = {
- kind: 'screen-share',
- streamKey: 'stream-key',
- state: {kind: 'remote-watched', hasAudio: true, onStopWatching: () => undefined},
-};
-
-const UNWATCHED_REMOTE_STREAM_SOURCE: VoiceParticipantMenuScreenShareSource = {
- kind: 'screen-share',
- streamKey: 'stream-key',
- state: {kind: 'remote-unwatched', onWatch: () => undefined},
-};
-
-beforeEach(() => {
- vi.mocked(copyVoiceDiagnostics).mockClear();
-});
-
-test('own stream keeps a More options submenu with the screen-share preferences', () => {
- const groups = streamMenu(OWN_STREAM_SOURCE);
- const moreOptions = findLeaf(groups, 'More options');
- expect(moreOptions).not.toBeNull();
- expect(findLeaf(groups, 'Show my screen share')).not.toBeNull();
- expect(findLeaf(groups, 'Copy stats JSON')).not.toBeNull();
- expect(findLeaf(groups, 'Report Problem')).toBeNull();
-});
-
-test('remote watched stream keeps a More options submenu with the diagnostics entry and audio controls', () => {
- const groups = streamMenu(WATCHED_REMOTE_STREAM_SOURCE);
- expect(findLeaf(groups, 'More options')).not.toBeNull();
- expect(findLeaf(groups, 'Copy stats JSON')).not.toBeNull();
- expect(findLeaf(groups, 'Mute')).not.toBeNull();
- expect(findLeaf(groups, 'Stream volume')).not.toBeNull();
- expect(findLeaf(groups, 'Report Problem')).toBeNull();
-});
-
-test('remote unwatched stream keeps the diagnostics entry', () => {
- const groups = streamMenu(UNWATCHED_REMOTE_STREAM_SOURCE);
- expect(findLeaf(groups, 'More options')).not.toBeNull();
- expect(findLeaf(groups, 'Copy stats JSON')).not.toBeNull();
-});
-
-test('the diagnostics entry on a remote stream copies voice diagnostics', () => {
- const groups = streamMenu(WATCHED_REMOTE_STREAM_SOURCE);
- const copyStats = findLeaf(groups, 'Copy stats JSON');
- expect(copyStats).not.toBeNull();
- copyStats?.onClick?.();
- expect(vi.mocked(copyVoiceDiagnostics)).toHaveBeenCalledTimes(1);
-});
diff --git a/fluxer_app/src/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap.ts b/fluxer_app/src/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap.ts
deleted file mode 100644
index d48bc07f7..000000000
--- a/fluxer_app/src/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-const HARNESS_ENDPOINT = 'https://primary.test/api';
-
-export function installVoiceMenuTestBootstrap(): void {
- const host = globalThis as unknown as {window?: Record<string, unknown>};
- if (typeof host.window === 'undefined') {
- host.window = host as unknown as Record<string, unknown>;
- }
- host.window.__FLUXER_BOOTSTRAP__ = {
- config: {
- releaseChannel: 'stable',
- bootstrapApiEndpoint: HARNESS_ENDPOINT,
- bootstrapApiPublicEndpoint: HARNESS_ENDPOINT,
- },
- instance: {
- api_code_version: Number.MAX_SAFE_INTEGER,
- endpoints: {
- api: HARNESS_ENDPOINT,
- api_client: HARNESS_ENDPOINT,
- api_public: HARNESS_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', hcaptcha_site_key: null, turnstile_site_key: null},
- features: {
- voice_enabled: false,
- stripe_enabled: false,
- self_hosted: false,
- presigned_attachment_uploads: false,
- emails_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},
- },
- },
- geoip: {
- countryCode: null,
- regionCode: null,
- latitude: null,
- longitude: null,
- ageRestrictedGeos: [],
- ageBlockedGeos: [],
- },
- };
-}
diff --git a/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.test.ts b/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.test.ts
deleted file mode 100644
index 9d75e1381..000000000
--- a/fluxer_app/src/features/ui/floating_pane/FloatingPaneMath.test.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- ALL_CORNERS,
- ALL_RESIZE_EDGES,
- type Corner,
- clampPoint,
- clampWidth,
- computeResize,
- DEFAULT_FLING_OPTIONS,
- type FloatingPaneGeometry,
- getCornerPoint,
- getDragBounds,
- getEffectiveWidthRange,
- getPaneHeight,
- pickCornerForFling,
- type ResizeEdge,
- reconcileToGeometry,
- snapPointToCorner,
-} from '@app/features/ui/floating_pane/FloatingPaneMath';
-import {describe, expect, it} from 'vitest';
-
-const BASE_GEOMETRY: FloatingPaneGeometry = {
- viewport: {width: 1000, height: 600},
- edgePadding: 12,
- topInset: 0,
- aspectRatio: 16 / 9,
- minWidth: 180,
- maxWidth: 420,
-};
-
-function withViewport(
- width: number,
- height: number,
- overrides: Partial<FloatingPaneGeometry> = {},
-): FloatingPaneGeometry {
- return {...BASE_GEOMETRY, viewport: {width, height}, ...overrides};
-}
-
-describe('getPaneHeight', () => {
- it('rounds width / aspect ratio', () => {
- expect(getPaneHeight(320, 16 / 9)).toBe(180);
- expect(getPaneHeight(200, 16 / 9)).toBe(113);
- });
- it('returns 0 for invalid input', () => {
- expect(getPaneHeight(Number.NaN, 16 / 9)).toBe(0);
- expect(getPaneHeight(320, 0)).toBe(0);
- expect(getPaneHeight(320, -1)).toBe(0);
- });
-});
-
-describe('getEffectiveWidthRange', () => {
- it('caps by maxWidth when viewport is generous', () => {
- const range = getEffectiveWidthRange(withViewport(2000, 1200));
- expect(range.max).toBe(420);
- expect(range.min).toBe(180);
- });
- it('caps by viewport width when viewport is narrow', () => {
- const range = getEffectiveWidthRange(withViewport(300, 600));
- expect(range.max).toBe(300 - 12 * 2);
- });
- it('caps by viewport height converted through aspect ratio when short', () => {
- const range = getEffectiveWidthRange(withViewport(1000, 120));
- const expected = (120 - 12 * 2) * (16 / 9);
- expect(range.max).toBeCloseTo(expected, 5);
- });
- it('pulls min down to max when room is tighter than min', () => {
- const range = getEffectiveWidthRange(withViewport(120, 120));
- expect(range.min).toBeLessThanOrEqual(range.max);
- expect(range.min).toBe(Math.max(0, Math.min(180, range.max)));
- });
- it('returns zero range when viewport is empty', () => {
- const range = getEffectiveWidthRange(withViewport(0, 0));
- expect(range.min).toBe(0);
- expect(range.max).toBe(0);
- });
- it('respects topInset by subtracting from available height', () => {
- const withInset = getEffectiveWidthRange(withViewport(1000, 200, {topInset: 100}));
- const sameHeightNoInset = getEffectiveWidthRange(withViewport(1000, 100));
- expect(withInset.max).toBeCloseTo(sameHeightNoInset.max, 5);
- });
-});
-
-describe('clampWidth', () => {
- it('rounds within range', () => {
- expect(clampWidth(220.4, BASE_GEOMETRY)).toBe(220);
- expect(clampWidth(220.6, BASE_GEOMETRY)).toBe(221);
- });
- it('clamps below min', () => {
- expect(clampWidth(50, BASE_GEOMETRY)).toBe(180);
- });
- it('clamps above max', () => {
- expect(clampWidth(9999, BASE_GEOMETRY)).toBe(420);
- });
- it('returns min for non-finite input', () => {
- expect(clampWidth(Number.NaN, BASE_GEOMETRY)).toBe(180);
- expect(clampWidth(Number.POSITIVE_INFINITY, BASE_GEOMETRY)).toBe(180);
- expect(clampWidth(Number.NEGATIVE_INFINITY, BASE_GEOMETRY)).toBe(180);
- });
-});
-
-describe('getDragBounds', () => {
- it('produces minX/minY at edgePadding (+topInset)', () => {
- const bounds = getDragBounds(withViewport(1000, 600, {topInset: 24}), 320);
- expect(bounds.minX).toBe(12);
- expect(bounds.minY).toBe(36);
- });
- it('produces maxX/maxY so that pane is inset by edgePadding on opposite side', () => {
- const bounds = getDragBounds(BASE_GEOMETRY, 320);
- const expectedHeight = getPaneHeight(320, 16 / 9);
- expect(bounds.maxX).toBe(1000 - 320 - 12);
- expect(bounds.maxY).toBe(600 - expectedHeight - 12);
- });
- it('collapses to minX = maxX when pane fills width', () => {
- const bounds = getDragBounds(withViewport(300, 600), 320);
- expect(bounds.maxX).toBe(bounds.minX);
- });
-});
-
-describe('clampPoint', () => {
- it('clamps each axis independently', () => {
- const bounds = {minX: 10, maxX: 100, minY: 5, maxY: 50};
- expect(clampPoint({x: -50, y: 999}, bounds)).toEqual({x: 10, y: 50});
- expect(clampPoint({x: 50, y: 25}, bounds)).toEqual({x: 50, y: 25});
- });
-});
-
-describe('getCornerPoint / snapPointToCorner', () => {
- const bounds = {minX: 10, maxX: 90, minY: 20, maxY: 80};
- it('returns the matching anchor point for each corner', () => {
- expect(getCornerPoint('top-left', bounds)).toEqual({x: 10, y: 20});
- expect(getCornerPoint('top-right', bounds)).toEqual({x: 90, y: 20});
- expect(getCornerPoint('bottom-right', bounds)).toEqual({x: 90, y: 80});
- expect(getCornerPoint('bottom-left', bounds)).toEqual({x: 10, y: 80});
- });
- it('snaps a point to its nearest corner by quadrant', () => {
- expect(snapPointToCorner({x: 15, y: 25}, bounds)).toBe('top-left');
- expect(snapPointToCorner({x: 85, y: 25}, bounds)).toBe('top-right');
- expect(snapPointToCorner({x: 85, y: 75}, bounds)).toBe('bottom-right');
- expect(snapPointToCorner({x: 15, y: 75}, bounds)).toBe('bottom-left');
- });
- it('snaps exactly on the midline towards the right/bottom side', () => {
- const midX = (bounds.minX + bounds.maxX) / 2;
- const midY = (bounds.minY + bounds.maxY) / 2;
- expect(snapPointToCorner({x: midX, y: midY}, bounds)).toBe('bottom-right');
- });
- it('round-trips corner -> point -> corner', () => {
- for (const corner of ALL_CORNERS) {
- const point = getCornerPoint(corner, bounds);
- expect(snapPointToCorner(point, bounds)).toBe(corner);
- }
- });
-});
-
-describe('pickCornerForFling', () => {
- const bounds = {minX: 0, maxX: 100, minY: 0, maxY: 100};
- it('falls back to nearest-corner snap below strong threshold', () => {
- const corner = pickCornerForFling({x: 20, y: 30}, {x: 0, y: 0}, bounds);
- expect(corner).toBe('top-left');
- });
- it('uses fling direction with strong horizontal velocity', () => {
- const corner = pickCornerForFling({x: 40, y: 40}, {x: 1200, y: 0}, bounds);
- expect(corner.endsWith('right')).toBe(true);
- });
- it('uses fling direction with strong vertical velocity', () => {
- const corner = pickCornerForFling({x: 40, y: 40}, {x: 0, y: -1200}, bounds);
- expect(corner.startsWith('top')).toBe(true);
- });
- it('respects axis velocity floor when fling is diagonal but one axis weak', () => {
- const corner = pickCornerForFling({x: 90, y: 50}, {x: -50, y: -1200}, bounds, {
- ...DEFAULT_FLING_OPTIONS,
- axisVelocityFloor: 200,
- });
- expect(corner).toBe('top-right');
- });
-});
-
-describe('computeResize', () => {
- const geometry = withViewport(1000, 600);
- function startState(edge: ResizeEdge, opts: {startWidth?: number; paneStartX?: number; paneStartY?: number} = {}) {
- const startWidth = opts.startWidth ?? 240;
- return {
- edge,
- startWidth,
- pointerStartX: 500,
- pointerStartY: 300,
- paneStartX: opts.paneStartX ?? 12,
- paneStartY: opts.paneStartY ?? 12,
- };
- }
- it('grows from right edge without moving anchor', () => {
- const start = startState('right');
- const result = computeResize(start, 540, 300, geometry);
- expect(result.width).toBeGreaterThan(start.startWidth);
- expect(result.offset).toEqual({x: 12, y: 12});
- });
- it('grows from bottom edge without moving anchor', () => {
- const start = startState('bottom');
- const result = computeResize(start, 500, 340, geometry);
- expect(result.width).toBeGreaterThan(start.startWidth);
- expect(result.offset.x).toBe(12);
- expect(result.offset.y).toBe(12);
- });
- it('keeps right edge anchored when resizing from left edge', () => {
- const start = startState('left', {paneStartX: 600, startWidth: 240});
- const result = computeResize(start, 460, 300, geometry);
- const appliedWidthDelta = result.width - start.startWidth;
- expect(result.offset.x).toBeCloseTo(start.paneStartX - appliedWidthDelta, 5);
- });
- it('keeps bottom edge anchored when resizing from top edge', () => {
- const start = startState('top', {paneStartY: 300, startWidth: 240});
- const result = computeResize(start, 500, 260, geometry);
- const appliedWidthDelta = result.width - start.startWidth;
- const appliedHeightDelta = appliedWidthDelta / (16 / 9);
- expect(result.offset.y).toBeCloseTo(start.paneStartY - appliedHeightDelta, 5);
- });
- it('keeps bottom-right anchor stationary when resizing from top-left', () => {
- const start = startState('top-left', {paneStartX: 600, paneStartY: 300, startWidth: 240});
- const initialRight = start.paneStartX + start.startWidth;
- const initialBottom = start.paneStartY + getPaneHeight(start.startWidth, 16 / 9);
- const result = computeResize(start, 460, 260, geometry);
- const resultRight = result.offset.x + result.width;
- const resultBottom = result.offset.y + getPaneHeight(result.width, 16 / 9);
- expect(resultRight).toBeCloseTo(initialRight, 0);
- expect(resultBottom).toBeCloseTo(initialBottom, 0);
- });
- it('shrinks when resizing from bottom-right inward', () => {
- const start = startState('bottom-right', {paneStartX: 12, paneStartY: 12, startWidth: 320});
- const result = computeResize(start, 460, 270, geometry);
- expect(result.width).toBeLessThan(start.startWidth);
- expect(result.offset).toEqual({x: 12, y: 12});
- });
- it('clamps width at the geometry min', () => {
- const start = startState('right', {startWidth: 220});
- const result = computeResize(start, 0, 300, geometry);
- expect(result.width).toBe(getEffectiveWidthRange(geometry).min);
- });
- it('clamps width at the geometry max', () => {
- const start = startState('right', {startWidth: 220});
- const result = computeResize(start, 9000, 300, geometry);
- expect(result.width).toBe(getEffectiveWidthRange(geometry).max);
- });
- it('never produces an offset outside drag bounds', () => {
- for (const edge of ALL_RESIZE_EDGES) {
- const start = startState(edge, {paneStartX: 12, paneStartY: 12, startWidth: 240});
- for (const dx of [-500, -50, 0, 50, 500]) {
- for (const dy of [-500, -50, 0, 50, 500]) {
- const result = computeResize(start, start.pointerStartX + dx, start.pointerStartY + dy, geometry);
- const bounds = getDragBounds(geometry, result.width);
- expect(result.offset.x).toBeGreaterThanOrEqual(bounds.minX);
- expect(result.offset.x).toBeLessThanOrEqual(bounds.maxX);
- expect(result.offset.y).toBeGreaterThanOrEqual(bounds.minY);
- expect(result.offset.y).toBeLessThanOrEqual(bounds.maxY);
- }
- }
- }
- });
-});
-
-describe('reconcileToGeometry', () => {
- it('returns the same corner regardless of viewport shrink/grow', () => {
- const before = reconcileToGeometry({
- corner: 'bottom-right',
- width: 320,
- geometry: withViewport(1000, 600),
- });
- const after = reconcileToGeometry({
- corner: 'bottom-right',
- width: 320,
- geometry: withViewport(500, 400),
- });
- expect(before.corner).toBe('bottom-right');
- expect(after.corner).toBe('bottom-right');
- });
- it('places offset at the chosen corner of the new bounds', () => {
- for (const corner of ALL_CORNERS) {
- const result = reconcileToGeometry({corner, width: 240, geometry: BASE_GEOMETRY});
- const expected = getCornerPoint(corner, getDragBounds(BASE_GEOMETRY, result.width));
- expect(result.offset).toEqual(expected);
- }
- });
- it('clamps width when the new viewport cannot fit it', () => {
- const result = reconcileToGeometry({
- corner: 'top-left' as Corner,
- width: 9999,
- geometry: withViewport(400, 300),
- });
- expect(result.width).toBeLessThanOrEqual(getEffectiveWidthRange(withViewport(400, 300)).max);
- });
-});
diff --git a/fluxer_app/src/features/ui/focus_ring/FocusRingScope.test.tsx b/fluxer_app/src/features/ui/focus_ring/FocusRingScope.test.tsx
deleted file mode 100644
index 5cebf4963..000000000
--- a/fluxer_app/src/features/ui/focus_ring/FocusRingScope.test.tsx
+++ /dev/null
@@ -1,382 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import FocusRing from '@app/features/ui/focus_ring/FocusRing';
-import FocusRingContext, {type FocusRingContextManager} from '@app/features/ui/focus_ring/FocusRingContext';
-import FocusRingManager from '@app/features/ui/focus_ring/FocusRingManager';
-import FocusRingScope from '@app/features/ui/focus_ring/FocusRingScope';
-import {act, useContext, useRef} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, test} from 'vitest';
-
-const RING_SELECTOR = '[data-flx="ui.focus-ring.focus-ring-scope.ring.focus-ring"]';
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-type Slot = 'primary' | 'secondary';
-
-let container: HTMLDivElement;
-let root: Root;
-let unmounted = false;
-const ringContexts: Partial<Record<Slot, FocusRingContextManager>> = {};
-const targets: Partial<Record<Slot, HTMLDivElement>> = {};
-
-function Capture({slot = 'primary'}: {slot?: Slot}) {
- ringContexts[slot] = useContext(FocusRingContext);
- return (
- <div
- ref={(element) => {
- if (element != null) targets[slot] = element;
- }}
- data-flx="ui.focus-ring.focus-ring-scope-test.capture.div"
- />
- );
-}
-
-function Harness({revision = 0}: {revision?: number}) {
- const containerRef = useRef<HTMLDivElement>(null);
- return (
- <div ref={containerRef} data-revision={revision} data-flx="ui.focus-ring.focus-ring-scope-test.harness.div">
- <FocusRingScope
- containerRef={containerRef}
- data-flx="ui.focus-ring.focus-ring-scope-test.harness.focus-ring-scope"
- >
- <Capture data-flx="ui.focus-ring.focus-ring-scope-test.harness.capture" />
- </FocusRingScope>
- </div>
- );
-}
-
-function ScopePair() {
- const primaryRef = useRef<HTMLDivElement>(null);
- const secondaryRef = useRef<HTMLDivElement>(null);
- return (
- <>
- <div ref={primaryRef} data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.div">
- <FocusRingScope
- containerRef={primaryRef}
- data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.focus-ring-scope"
- >
- <Capture slot="primary" data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.capture" />
- </FocusRingScope>
- </div>
- <div ref={secondaryRef} data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.div--2">
- <FocusRingScope
- containerRef={secondaryRef}
- data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.focus-ring-scope--2"
- >
- <Capture slot="secondary" data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair.capture--2" />
- </FocusRingScope>
- </div>
- </>
- );
-}
-
-function rings(): Array<Element> {
- return Array.from(container.querySelectorAll(RING_SELECTOR));
-}
-
-function ring(): Element | null {
- return container.querySelector(RING_SELECTOR);
-}
-
-function requireRing(): HTMLElement {
- const element = ring();
- if (element == null) throw new Error('The focus ring is not painted');
- return element as HTMLElement;
-}
-
-function requireRingContext(slot: Slot = 'primary'): FocusRingContextManager {
- const value = ringContexts[slot];
- if (value == null) throw new Error(`The focus ring context for ${slot} never rendered`);
- return value;
-}
-
-function requireTarget(slot: Slot = 'primary'): HTMLDivElement {
- const value = targets[slot];
- if (value == null) throw new Error(`The focus ring target for ${slot} never rendered`);
- return value;
-}
-
-function requireScopeContainer(): HTMLElement {
- const element = container.firstElementChild;
- if (element == null) throw new Error('The scope container never rendered');
- return element as HTMLElement;
-}
-
-function domRect(top: number, left: number, width: number, height: number): DOMRect {
- return {
- top,
- left,
- width,
- height,
- right: left + width,
- bottom: top + height,
- x: left,
- y: top,
- toJSON: () => ({}),
- } as DOMRect;
-}
-
-function stubBoundingRect(element: Element, read: () => DOMRect) {
- Object.defineProperty(element, 'getBoundingClientRect', {value: read, configurable: true});
-}
-
-function unmountRoot() {
- if (unmounted) return;
- unmounted = true;
- act(() => {
- root.unmount();
- });
-}
-
-beforeEach(() => {
- delete ringContexts.primary;
- delete ringContexts.secondary;
- delete targets.primary;
- delete targets.secondary;
- unmounted = false;
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- unmountRoot();
- container.remove();
- FocusRingManager.setRingsEnabled(true);
-});
-
-describe('FocusRingScope', () => {
- test('paints the ring once rings are enabled, without a second focus event', () => {
- FocusRingManager.setRingsEnabled(false);
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness" />);
- });
- act(() => {
- requireRingContext().showForElement(requireTarget());
- });
- expect(ring()).toBeNull();
- act(() => {
- FocusRingManager.setRingsEnabled(true);
- });
- expect(ring()).not.toBeNull();
- });
-
- test('restores the ring for a target that never blurred while rings were disabled', () => {
- FocusRingManager.setRingsEnabled(true);
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--2" />);
- });
- act(() => {
- requireRingContext().showForElement(requireTarget());
- });
- expect(ring()).not.toBeNull();
- act(() => {
- FocusRingManager.setRingsEnabled(false);
- });
- expect(ring()).toBeNull();
- act(() => {
- FocusRingManager.setRingsEnabled(true);
- });
- expect(ring()).not.toBeNull();
- });
-
- test('keeps the ring hidden when nothing is showing', () => {
- FocusRingManager.setRingsEnabled(false);
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--3" />);
- });
- act(() => {
- FocusRingManager.setRingsEnabled(true);
- });
- expect(ring()).toBeNull();
- });
-
- test('paints the ring on show and removes it on hide', () => {
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--4" />);
- });
- expect(ring()).toBeNull();
- act(() => {
- requireRingContext().showForElement(requireTarget());
- });
- expect(ring()).not.toBeNull();
- act(() => {
- requireRingContext().hide();
- });
- expect(ring()).toBeNull();
- });
-
- test('repositions the ring when a parent render moves a target that did not resize', () => {
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--5" />);
- });
- stubBoundingRect(requireScopeContainer(), () => domRect(0, 0, 800, 600));
- let targetTop = 200;
- stubBoundingRect(requireTarget(), () => domRect(targetTop, 0, 300, 40));
- act(() => {
- requireRingContext().showForElement(requireTarget());
- });
- expect(requireRing().style.top).toBe('200px');
- targetTop = 320;
- act(() => {
- root.render(<Harness revision={1} data-flx="ui.focus-ring.focus-ring-scope-test.harness--6" />);
- });
- expect(requireRing().style.top).toBe('320px');
- });
-
- test('repositions the ring when the target itself resizes, and stops observing on unmount', () => {
- const realResizeObserver = globalThis.ResizeObserver;
- const realRequestAnimationFrame = globalThis.requestAnimationFrame;
- const realCancelAnimationFrame = globalThis.cancelAnimationFrame;
- let notifyResize: (() => void) | null = null;
- let disconnectCount = 0;
- class StubResizeObserver {
- constructor(callback: () => void) {
- notifyResize = callback;
- }
- observe() {}
- unobserve() {}
- disconnect() {
- disconnectCount += 1;
- }
- }
- globalThis.ResizeObserver = StubResizeObserver as unknown as typeof ResizeObserver;
- globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {
- callback(0);
- return 1;
- }) as typeof requestAnimationFrame;
- globalThis.cancelAnimationFrame = (() => undefined) as typeof cancelAnimationFrame;
- try {
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--7" />);
- });
- stubBoundingRect(requireScopeContainer(), () => domRect(0, 0, 800, 600));
- let targetHeight = 40;
- stubBoundingRect(requireTarget(), () => domRect(100, 0, 300, targetHeight));
- act(() => {
- requireRingContext().showForElement(requireTarget());
- });
- expect(requireRing().style.height).toBe('40px');
- targetHeight = 90;
- act(() => {
- notifyResize?.();
- });
- expect(requireRing().style.height).toBe('90px');
- unmountRoot();
- expect(disconnectCount).toBe(1);
- } finally {
- globalThis.ResizeObserver = realResizeObserver;
- globalThis.requestAnimationFrame = realRequestAnimationFrame;
- globalThis.cancelAnimationFrame = realCancelAnimationFrame;
- }
- });
-
- test('drops the ring from the previous scope when another scope takes focus', () => {
- act(() => {
- root.render(<ScopePair data-flx="ui.focus-ring.focus-ring-scope-test.scope-pair" />);
- });
- act(() => {
- requireRingContext('primary').showForElement(requireTarget('primary'));
- });
- expect(rings()).toHaveLength(1);
- act(() => {
- requireRingContext('secondary').showForElement(requireTarget('secondary'));
- });
- expect(rings()).toHaveLength(1);
- expect(requireRingContext('primary').visible).toBe(false);
- expect(requireRingContext('secondary').visible).toBe(true);
- });
-
- test('keeps a positively inset ring inside the scope container the row bleeds out of', () => {
- act(() => {
- root.render(<Harness data-flx="ui.focus-ring.focus-ring-scope-test.harness--inset" />);
- });
- const scopeContainer = requireScopeContainer();
- stubBoundingRect(scopeContainer, () => domRect(0, 0, 500, 400));
- stubBoundingRect(requireTarget(), () => domRect(100, -16, 532, 40));
- act(() => {
- requireRingContext().showForElement(requireTarget(), {offset: -2});
- });
- const bleeding = requireRing();
- expect(Number.parseFloat(bleeding.style.left)).toBeLessThan(0);
- act(() => {
- requireRingContext().showForElement(requireTarget(), {offset: {top: -2, bottom: -2, left: 18, right: 18}});
- });
- const inset = requireRing();
- const left = Number.parseFloat(inset.style.left);
- const width = Number.parseFloat(inset.style.width);
- expect(left).toBeGreaterThan(0);
- expect(left + width).toBeLessThan(500);
- });
-});
-
-function NestedRings({outerWithin}: {outerWithin: boolean}) {
- const containerRef = useRef<HTMLDivElement>(null);
- return (
- <div ref={containerRef} data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.div">
- <FocusRingScope containerRef={containerRef} data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.scope">
- <Capture data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.capture" />
- <FocusRing within={outerWithin} data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.row-ring">
- <div tabIndex={-1} data-row="true" data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.row">
- <div
- style={{position: 'absolute', zIndex: 10}}
- data-bar="true"
- data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.bar"
- >
- <FocusRing data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.button-ring">
- <button type="button" data-flx="ui.focus-ring.focus-ring-scope-test.nested-rings.button">
- react
- </button>
- </FocusRing>
- </div>
- </div>
- </FocusRing>
- </FocusRingScope>
- </div>
- );
-}
-
-function requireElement(selector: string): HTMLElement {
- const element = container.querySelector<HTMLElement>(selector);
- if (element == null) throw new Error(`Missing ${selector}`);
- return element;
-}
-
-describe('FocusRing nested inside another ring', () => {
- test('a focus-within ring replaces the ring of a descendant that draws its own', () => {
- act(() => {
- root.render(<NestedRings outerWithin={true} />);
- });
- act(() => {
- requireElement('button').focus();
- });
- expect(requireRingContext().targetElement).toBe(requireElement('[data-row]'));
- });
-
- test('a ring without focus-within leaves the descendant its own ring', () => {
- act(() => {
- root.render(<NestedRings outerWithin={false} />);
- });
- act(() => {
- requireElement('button').focus();
- });
- expect(requireRingContext().targetElement).toBe(requireElement('button'));
- });
-
- test('stacks a descendant ring above an elevated bar and the row ring beneath it', () => {
- act(() => {
- root.render(<NestedRings outerWithin={false} />);
- });
- act(() => {
- requireElement('button').focus();
- });
- expect(requireRing().style.zIndex).toBe('11');
- act(() => {
- requireElement('[data-row]').focus();
- });
- expect(requireRingContext().targetElement).toBe(requireElement('[data-row]'));
- expect(requireRing().style.zIndex).toBe('');
- });
-});
diff --git a/fluxer_app/src/features/ui/overlay/PortalHostContext.test.ts b/fluxer_app/src/features/ui/overlay/PortalHostContext.test.ts
deleted file mode 100644
index f20c2dc7f..000000000
--- a/fluxer_app/src/features/ui/overlay/PortalHostContext.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {scopePortalHostToDocument} from '@app/features/ui/overlay/PortalHostContext';
-import {describe, expect, it} from 'vitest';
-
-describe('scopePortalHostToDocument', () => {
- it('keeps a host that belongs to the scoped document', () => {
- const host = document.createElement('div');
- expect(scopePortalHostToDocument(host, document)).toBe(host);
- });
-
- it('drops a host owned by another document', () => {
- const popoutDocument = document.implementation.createHTMLDocument('popout');
- const popoutHost = popoutDocument.createElement('div');
- expect(scopePortalHostToDocument(popoutHost, document)).toBeNull();
- expect(scopePortalHostToDocument(popoutHost, popoutDocument)).toBe(popoutHost);
- });
-
- it('passes a missing host through', () => {
- expect(scopePortalHostToDocument(null, document)).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/ui/popover/PopoverDragClickUtils.test.ts b/fluxer_app/src/features/ui/popover/PopoverDragClickUtils.test.ts
deleted file mode 100644
index 3b06d73bf..000000000
--- a/fluxer_app/src/features/ui/popover/PopoverDragClickUtils.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isPopoutDragClick} from '@app/features/ui/popover/PopoverDragClickUtils';
-import {describe, expect, it} from 'vitest';
-
-const PRESS = {x: 120, y: 240, button: 0};
-
-describe('isPopoutDragClick', () => {
- it('treats a click far from the press as a drag', () => {
- expect(isPopoutDragClick(PRESS, {detail: 1, button: 0, clientX: 160, clientY: 240})).toBe(true);
- });
-
- it('allows a click within the tolerance of the press', () => {
- expect(isPopoutDragClick(PRESS, {detail: 1, button: 0, clientX: 122, clientY: 242})).toBe(false);
- });
-
- it('allows a click from a different button than the press', () => {
- expect(isPopoutDragClick(PRESS, {detail: 1, button: 2, clientX: 900, clientY: 900})).toBe(false);
- });
-
- it('allows a click with no recorded press', () => {
- expect(isPopoutDragClick(null, {detail: 1, button: 0, clientX: 900, clientY: 900})).toBe(false);
- });
-
- it('allows a keyboard click even when a stale press is recorded', () => {
- expect(isPopoutDragClick(PRESS, {detail: 0, button: 0, clientX: 0, clientY: 0})).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/ui/popover/PopoverFocusManagerUtils.test.ts b/fluxer_app/src/features/ui/popover/PopoverFocusManagerUtils.test.ts
deleted file mode 100644
index 16525a78d..000000000
--- a/fluxer_app/src/features/ui/popover/PopoverFocusManagerUtils.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getPopoutFocusManagerInsideElements} from '@app/features/ui/popover/PopoverFocusManagerUtils';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('getPopoutFocusManagerInsideElements', () => {
- afterEach(() => {
- document.body.replaceChildren();
- });
-
- it('includes the popout reference so its focused ancestor is not aria-hidden', () => {
- const frame = document.createElement('div');
- const button = document.createElement('button');
- const nativeTitlebar = document.createElement('div');
- nativeTitlebar.setAttribute('data-native-titlebar', '');
- frame.append(button);
- document.body.append(frame, nativeTitlebar);
-
- expect(getPopoutFocusManagerInsideElements(button)).toEqual([button, nativeTitlebar]);
- });
-
- it('includes a distinct return-focus target', () => {
- const button = document.createElement('button');
- const textarea = document.createElement('textarea');
- document.body.append(button, textarea);
-
- expect(getPopoutFocusManagerInsideElements(button, textarea)).toEqual([button, textarea]);
- });
-
- it('deduplicates the reference and return-focus target', () => {
- const button = document.createElement('button');
- document.body.append(button);
-
- expect(getPopoutFocusManagerInsideElements(button, button)).toEqual([button]);
- });
-
- it('ignores disconnected elements', () => {
- const button = document.createElement('button');
- const textarea = document.createElement('textarea');
-
- expect(getPopoutFocusManagerInsideElements(button, textarea)).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/ui/popover/PopoverReturnFocusUtils.test.ts b/fluxer_app/src/features/ui/popover/PopoverReturnFocusUtils.test.ts
deleted file mode 100644
index f493f5410..000000000
--- a/fluxer_app/src/features/ui/popover/PopoverReturnFocusUtils.test.ts
+++ /dev/null
@@ -1,274 +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 {observePopoutKeyboardDismiss, resolvePopoutReturnFocus} from '@app/features/ui/popover/PopoverReturnFocusUtils';
-import {FloatingFocusManager, useFloating} from '@floating-ui/react';
-import {act, createElement, useLayoutEffect} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-const RETURN_FOCUS_REF = {current: null};
-const KEYBOARD_DISMISS_REF = {current: null};
-
-describe('resolvePopoutReturnFocus', () => {
- it('returns focus to the target when the open-time policy allows it', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: true,
- isKeyboardModeEnabled: false,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: true,
- }),
- ).toBe(true);
- });
-
- it('returns focus to the target when the viewer is navigating by keyboard', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: false,
- isKeyboardModeEnabled: true,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: true,
- }),
- ).toBe(true);
- });
-
- it('defers a pointer-driven popout to the late-bound keyboard-dismiss target', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: false,
- isKeyboardModeEnabled: false,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: true,
- }),
- ).toBe(KEYBOARD_DISMISS_REF);
- });
-
- it('prefers an explicit return-focus target over the popout target', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: false,
- isKeyboardModeEnabled: true,
- returnFocusRef: RETURN_FOCUS_REF,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: true,
- }),
- ).toBe(RETURN_FOCUS_REF);
- });
-
- it('defers an explicit return-focus target to the keyboard-dismiss target when no return is wanted', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: false,
- isKeyboardModeEnabled: false,
- returnFocusRef: RETURN_FOCUS_REF,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: true,
- }),
- ).toBe(KEYBOARD_DISMISS_REF);
- });
-
- it('does not return focus to a target that left the document', () => {
- expect(
- resolvePopoutReturnFocus({
- restoreFocusPolicy: true,
- isKeyboardModeEnabled: true,
- keyboardDismissRef: KEYBOARD_DISMISS_REF,
- isTargetInDOM: false,
- }),
- ).toBe(false);
- });
-});
-
-describe('observePopoutKeyboardDismiss', () => {
- let trigger: HTMLElement;
- let keyboardDismissRef: {current: HTMLElement | null};
- let dispose: (() => void) | null = null;
- let layerManagerStub: ((event: KeyboardEvent) => void) | null = null;
-
- const pressKey = (key: string): void => {
- document.body.dispatchEvent(new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}));
- };
-
- beforeEach(() => {
- trigger = document.createElement('button');
- document.body.append(trigger);
- keyboardDismissRef = {current: null};
- });
-
- afterEach(() => {
- dispose?.();
- dispose = null;
- if (layerManagerStub) {
- document.removeEventListener('keydown', layerManagerStub, {capture: true});
- layerManagerStub = null;
- }
- document.body.replaceChildren();
- });
-
- it('records the focus target when Escape is pressed', () => {
- dispose = observePopoutKeyboardDismiss({
- ownerWindow: window,
- keyboardDismissRef,
- resolveFocusTarget: () => trigger,
- });
-
- pressKey('Escape');
-
- expect(keyboardDismissRef.current).toBe(trigger);
- });
-
- it('records the focus target even though the layer manager stops immediate propagation first', () => {
- let didCloseTopLayer = false;
- layerManagerStub = (event: KeyboardEvent) => {
- if (event.key !== 'Escape') {
- return;
- }
- didCloseTopLayer = true;
- event.preventDefault();
- event.stopImmediatePropagation();
- };
- document.addEventListener('keydown', layerManagerStub, {capture: true});
- dispose = observePopoutKeyboardDismiss({
- ownerWindow: window,
- keyboardDismissRef,
- resolveFocusTarget: () => trigger,
- });
-
- pressKey('Escape');
-
- expect(didCloseTopLayer).toBe(true);
- expect(keyboardDismissRef.current).toBe(trigger);
- });
-
- it('ignores keys other than Escape', () => {
- dispose = observePopoutKeyboardDismiss({
- ownerWindow: window,
- keyboardDismissRef,
- resolveFocusTarget: () => trigger,
- });
-
- pressKey('Enter');
- pressKey('Tab');
-
- expect(keyboardDismissRef.current).toBeNull();
- });
-
- it('records nothing when the popout is not the layer Escape closes', () => {
- dispose = observePopoutKeyboardDismiss({
- ownerWindow: window,
- keyboardDismissRef,
- resolveFocusTarget: () => null,
- });
-
- pressKey('Escape');
-
- expect(keyboardDismissRef.current).toBeNull();
- });
-
- it('stops recording once disposed', () => {
- const stop = observePopoutKeyboardDismiss({
- ownerWindow: window,
- keyboardDismissRef,
- resolveFocusTarget: () => trigger,
- });
- stop();
-
- pressKey('Escape');
-
- expect(keyboardDismissRef.current).toBeNull();
- });
-});
-
-describe('FloatingFocusManager return-focus ref contract', () => {
- let host: HTMLDivElement;
- let trigger: HTMLButtonElement;
- let root: Root;
-
- function ReturnFocusHarness({
- reference,
- returnFocus,
- }: {
- reference: HTMLElement;
- returnFocus: {current: HTMLElement | null};
- }) {
- const {refs, context} = useFloating({open: true});
- useLayoutEffect(() => {
- refs.setReference(reference);
- }, [refs, reference]);
- return createElement(FloatingFocusManager, {
- context,
- returnFocus,
- initialFocus: refs.floating,
- children: createElement('div', {ref: refs.setFloating, tabIndex: -1, 'data-testid': 'floating'}),
- });
- }
-
- async function settle(): Promise<void> {
- for (let attempt = 0; attempt < 10; attempt += 1) {
- await act(async () => {
- await Promise.resolve();
- });
- }
- }
-
- beforeEach(() => {
- host = document.createElement('div');
- trigger = document.createElement('button');
- document.body.append(host, trigger);
- root = createRoot(host);
- });
-
- afterEach(() => {
- document.body.replaceChildren();
- });
-
- it('focuses a return target assigned after the popout opened', async () => {
- const returnFocus: {current: HTMLElement | null} = {current: null};
- await act(async () => {
- root.render(createElement(ReturnFocusHarness, {reference: trigger, returnFocus}));
- });
- await settle();
- host.querySelector<HTMLElement>('[data-testid="floating"]')?.focus();
-
- returnFocus.current = trigger;
- await act(async () => {
- root.unmount();
- });
- await settle();
-
- expect(document.activeElement).toBe(trigger);
- });
-
- it('leaves focus alone when no return target was assigned', async () => {
- const returnFocus: {current: HTMLElement | null} = {current: null};
- await act(async () => {
- root.render(createElement(ReturnFocusHarness, {reference: trigger, returnFocus}));
- });
- await settle();
- host.querySelector<HTMLElement>('[data-testid="floating"]')?.focus();
-
- await act(async () => {
- root.unmount();
- });
- await settle();
-
- expect(document.activeElement).not.toBe(trigger);
- });
-});
-
-describe('PopoverPopouts keyboard-dismiss wiring', () => {
- const source = readFileSync(resolve(process.cwd(), 'src/features/ui/popover/PopoverPopouts.tsx'), 'utf8');
-
- it('shares one ref between the Escape watcher and the return-focus resolver', () => {
- expect(source.split('keyboardDismissRef: keyboardDismissReturnRef').length - 1).toBe(2);
- expect(source).toContain('returnFocus={resolvePopoutReturnFocus({');
- expect(source).toContain('resolveFocusTarget: resolveKeyboardDismissFocusTarget');
- });
-
- it('only records Escape for the layer the layer manager would close', () => {
- expect(source).toContain("LayerManager.isTopLayer('popout', popoutKey)");
- });
-});
diff --git a/fluxer_app/src/features/ui/state/Idle.test.ts b/fluxer_app/src/features/ui/state/Idle.test.ts
deleted file mode 100644
index 55a8aaa15..000000000
--- a/fluxer_app/src/features/ui/state/Idle.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const IDLE_DURATION_MS = 600_000;
-const IDLE_CHECK_INTERVAL_MS = 30_000;
-
-vi.mock('@app/features/platform/types/Env', () => ({
- IS_DEV: false,
- IS_PROD: true,
- MODE: 'test',
-}));
-
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {updatePresence: vi.fn()},
-}));
-
-async function loadIdle(getSystemIdleTimeMs?: () => Promise<number>) {
- vi.resetModules();
- if (getSystemIdleTimeMs) {
- Object.defineProperty(window, 'electron', {value: {getSystemIdleTimeMs}, configurable: true, writable: true});
- } else {
- Reflect.deleteProperty(window as unknown as Record<string, unknown>, 'electron');
- }
- const {default: Idle} = await import('@app/features/ui/state/Idle');
- return Idle;
-}
-
-describe('Idle', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- Reflect.deleteProperty(window as unknown as Record<string, unknown>, 'electron');
- vi.useRealTimers();
- });
-
- it('goes idle once nothing has reported activity for the idle duration', async () => {
- const Idle = await loadIdle();
- await vi.advanceTimersByTimeAsync(IDLE_DURATION_MS - IDLE_CHECK_INTERVAL_MS);
- expect(Idle.isIdle()).toBe(false);
- await vi.advanceTimersByTimeAsync(IDLE_CHECK_INTERVAL_MS);
- expect(Idle.isIdle()).toBe(true);
- });
-
- it('stays active while the app keeps seeing input', async () => {
- const Idle = await loadIdle();
- for (let elapsed = 0; elapsed < IDLE_DURATION_MS * 2; elapsed += IDLE_CHECK_INTERVAL_MS) {
- Idle.recordActivity();
- await vi.advanceTimersByTimeAsync(IDLE_CHECK_INTERVAL_MS);
- }
- expect(Idle.isIdle()).toBe(false);
- });
-
- it('stays active while the app sees input even when the system idle clock keeps climbing', async () => {
- const startedAt = Date.now();
- const Idle = await loadIdle(async () => Date.now() - startedAt);
- for (let elapsed = 0; elapsed < IDLE_DURATION_MS * 2; elapsed += IDLE_CHECK_INTERVAL_MS) {
- Idle.recordActivity();
- await vi.advanceTimersByTimeAsync(IDLE_CHECK_INTERVAL_MS);
- }
- expect(Idle.isIdle()).toBe(false);
- });
-
- it('leaves idle as soon as the app sees input again', async () => {
- const startedAt = Date.now();
- const Idle = await loadIdle(async () => Date.now() - startedAt);
- await vi.advanceTimersByTimeAsync(IDLE_DURATION_MS);
- expect(Idle.isIdle()).toBe(true);
- Idle.recordActivity();
- expect(Idle.isIdle()).toBe(false);
- await vi.advanceTimersByTimeAsync(IDLE_CHECK_INTERVAL_MS);
- expect(Idle.isIdle()).toBe(false);
- });
-
- it('stays active while the system reports input the app never sees', async () => {
- const Idle = await loadIdle(async () => 0);
- await vi.advanceTimersByTimeAsync(IDLE_DURATION_MS * 2);
- expect(Idle.isIdle()).toBe(false);
- });
-
- it('goes idle when neither the app nor the system reports activity', async () => {
- const startedAt = Date.now();
- const Idle = await loadIdle(async () => Date.now() - startedAt);
- await vi.advanceTimersByTimeAsync(IDLE_DURATION_MS);
- expect(Idle.isIdle()).toBe(true);
- });
-
- it('falls back to app activity when the system idle clock is unreadable', async () => {
- const Idle = await loadIdle(async () => Number.NaN);
- await vi.advanceTimersByTimeAsync(IDLE_DURATION_MS);
- expect(Idle.isIdle()).toBe(true);
- Idle.recordActivity();
- await vi.advanceTimersByTimeAsync(IDLE_CHECK_INTERVAL_MS);
- expect(Idle.isIdle()).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/ui/state/MediaViewer.test.ts b/fluxer_app/src/features/ui/state/MediaViewer.test.ts
deleted file mode 100644
index 5e70f9023..000000000
--- a/fluxer_app/src/features/ui/state/MediaViewer.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import MediaViewer, {type MediaViewerItem} from '@app/features/ui/state/MediaViewer';
-import {afterEach, describe, expect, it} from 'vitest';
-
-const createItem = (overrides?: Partial<MediaViewerItem>): MediaViewerItem => ({
- src: 'https://cdn.example.test/media.png',
- originalSrc: 'https://example.test/media.png',
- naturalWidth: 640,
- naturalHeight: 480,
- type: 'image',
- ...overrides,
-});
-
-describe('MediaViewer state', () => {
- afterEach(() => {
- MediaViewer.close();
- });
- it('copies and freezes media items when opening the viewer', () => {
- const item = createItem({filename: 'original.png'});
- const items = [item];
- MediaViewer.open(items, 0);
- items[0] = createItem({filename: 'mutated.png'});
- (item as {filename: string}).filename = 'changed-after-open.png';
- expect(MediaViewer.items).toHaveLength(1);
- expect(MediaViewer.items[0]).not.toBe(item);
- expect(MediaViewer.items[0].filename).toBe('original.png');
- expect(Object.isFrozen(MediaViewer.items)).toBe(true);
- expect(Object.isFrozen(MediaViewer.items[0])).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/ui/state/Tick.test.ts b/fluxer_app/src/features/ui/state/Tick.test.ts
deleted file mode 100644
index 8d9f9532a..000000000
--- a/fluxer_app/src/features/ui/state/Tick.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {autorun} from 'mobx';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-async function loadTick() {
- vi.resetModules();
- const {Logger} = await import('@app/features/platform/utils/AppLogger');
- const debug = vi.spyOn(Logger.prototype, 'debug').mockImplementation(() => undefined);
- const {default: Window} = await import('@app/features/window/state/Window');
- const {default: Tick} = await import('@app/features/ui/state/Tick');
- return {debug, Tick, Window};
-}
-
-describe('Tick', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- vi.useRealTimers();
- });
-
- it('keeps counting while the window is visible but not focused', async () => {
- const {debug, Tick, Window} = await loadTick();
- const dispose = autorun(() => Tick.nowSecond);
- const started = Tick.nowSecond;
- Window.setFocused(false);
- expect(debug).toHaveBeenCalledExactlyOnceWith('Window focus changed: false');
- vi.advanceTimersByTime(3000);
- expect(Window.visible).toBe(true);
- expect(Tick.nowSecond).toBe(started + 3);
- dispose();
- });
-
- it('stops counting while the window is hidden', async () => {
- const {debug, Tick, Window} = await loadTick();
- const dispose = autorun(() => Tick.nowSecond);
- Window.setVisible(false);
- expect(debug).toHaveBeenCalledExactlyOnceWith('Window visibility changed: false');
- const stopped = Tick.nowSecond;
- vi.advanceTimersByTime(5000);
- expect(Tick.nowSecond).toBe(stopped);
- dispose();
- });
-
- it('resynchronises to wall clock as soon as the window becomes visible again', async () => {
- const {debug, Tick, Window} = await loadTick();
- const dispose = autorun(() => Tick.nowSecond);
- Window.setVisible(false);
- const stopped = Tick.nowSecond;
- vi.advanceTimersByTime(60_000);
- expect(Tick.nowSecond).toBe(stopped);
- Window.setVisible(true);
- expect(debug).toHaveBeenNthCalledWith(1, 'Window visibility changed: false');
- expect(debug).toHaveBeenNthCalledWith(2, 'Window visibility changed: true');
- expect(debug).toHaveBeenCalledTimes(2);
- expect(Tick.nowSecond).toBe(stopped + 60);
- dispose();
- });
-
- it('does not run an interval while nothing observes the clock', async () => {
- const {debug, Tick} = await loadTick();
- const idle = Tick.nowSecond;
- vi.advanceTimersByTime(5000);
- expect(Tick.nowSecond).toBe(idle);
- const dispose = autorun(() => Tick.nowSecond);
- expect(Tick.nowSecond).toBe(idle + 5);
- expect(debug).not.toHaveBeenCalled();
- dispose();
- });
-});
diff --git a/fluxer_app/src/features/ui/stepped_carousel/SteppedCarouselStateMachine.test.ts b/fluxer_app/src/features/ui/stepped_carousel/SteppedCarouselStateMachine.test.ts
deleted file mode 100644
index 2d496a434..000000000
--- a/fluxer_app/src/features/ui/stepped_carousel/SteppedCarouselStateMachine.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createSteppedCarouselSnapshot,
- getSteppedCarouselStateValue,
- resolveSteppedCarouselHeight,
- type SteppedCarouselMachineEvent,
- type SteppedCarouselSnapshot,
- selectSteppedCarouselModel,
- transitionSteppedCarouselSnapshot,
-} from '@app/features/ui/stepped_carousel/SteppedCarouselStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const STEPS = ['account', 'credentials', 'mfa'] as const;
-
-function transition(snapshot: SteppedCarouselSnapshot, event: SteppedCarouselMachineEvent): SteppedCarouselSnapshot {
- return transitionSteppedCarouselSnapshot(snapshot, event);
-}
-
-describe('steppedCarouselStateMachine', () => {
- it('starts unmeasured with automatic height and no transition direction', () => {
- const snapshot = createSteppedCarouselSnapshot({step: 'credentials', steps: STEPS});
-
- expect(getSteppedCarouselStateValue(snapshot)).toBe('unmeasured');
- expect(selectSteppedCarouselModel(snapshot)).toMatchObject({
- step: 'credentials',
- direction: 0,
- contentHeight: 'auto',
- focusRequestId: 0,
- });
- });
-
- it('resolves forward and backward directions from the configured step order', () => {
- let snapshot = createSteppedCarouselSnapshot({step: 'account', steps: STEPS});
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: STEPS,
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).direction).toBe(2);
-
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'credentials',
- steps: STEPS,
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).direction).toBe(-1);
- });
-
- it('keeps the current direction when props change without a step change', () => {
- let snapshot = createSteppedCarouselSnapshot({step: 'account', steps: STEPS});
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: STEPS,
- focusOnStepChange: false,
- });
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: [...STEPS],
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).direction).toBe(2);
- });
-
- it('lets explicit direction override derived direction', () => {
- const snapshot = transition(createSteppedCarouselSnapshot({step: 'account', steps: STEPS}), {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: STEPS,
- direction: -10,
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).direction).toBe(-10);
- });
-
- it('uses neutral direction when either step is not in the configured order', () => {
- const snapshot = transition(createSteppedCarouselSnapshot({step: 'missing', steps: STEPS}), {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: STEPS,
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).direction).toBe(0);
- });
-
- it('measures visible content height from the largest available DOM height', () => {
- let snapshot = createSteppedCarouselSnapshot({step: 'credentials', steps: STEPS});
- snapshot = transition(snapshot, {type: 'carousel.measured', offsetHeight: 120, scrollHeight: 180});
-
- expect(getSteppedCarouselStateValue(snapshot)).toBe('ready');
- expect(selectSteppedCarouselModel(snapshot).contentHeight).toBe(180);
-
- snapshot = transition(snapshot, {type: 'carousel.measured', offsetHeight: 220, scrollHeight: 200});
-
- expect(selectSteppedCarouselModel(snapshot).contentHeight).toBe(220);
- });
-
- it('keeps automatic height instead of clipping content when the first measurement is zero', () => {
- const snapshot = transition(createSteppedCarouselSnapshot({step: 'credentials', steps: STEPS}), {
- type: 'carousel.measured',
- offsetHeight: 0,
- scrollHeight: 0,
- });
-
- expect(getSteppedCarouselStateValue(snapshot)).toBe('ready');
- expect(selectSteppedCarouselModel(snapshot).contentHeight).toBe('auto');
- });
-
- it('requests focus only after the mounted carousel changes step with focus enabled', () => {
- let snapshot = createSteppedCarouselSnapshot({
- step: 'account',
- steps: STEPS,
- focusOnStepChange: true,
- });
-
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'account',
- steps: STEPS,
- focusOnStepChange: true,
- });
-
- expect(selectSteppedCarouselModel(snapshot).focusRequestId).toBe(0);
-
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'credentials',
- steps: STEPS,
- focusOnStepChange: true,
- });
-
- expect(selectSteppedCarouselModel(snapshot).focusRequestId).toBe(1);
-
- snapshot = transition(snapshot, {
- type: 'carousel.propsChanged',
- step: 'mfa',
- steps: STEPS,
- focusOnStepChange: false,
- });
-
- expect(selectSteppedCarouselModel(snapshot).focusRequestId).toBe(1);
- });
-});
-
-describe('resolveSteppedCarouselHeight', () => {
- it('falls back to auto for non-rendered panes', () => {
- expect(resolveSteppedCarouselHeight({offsetHeight: 0, scrollHeight: 0})).toBe('auto');
- });
-
- it('uses scrollHeight when transform or layout timing makes offsetHeight smaller', () => {
- expect(resolveSteppedCarouselHeight({offsetHeight: 0, scrollHeight: 320})).toBe(320);
- });
-});
diff --git a/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.test.ts b/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.test.ts
deleted file mode 100644
index f0944024e..000000000
--- a/fluxer_app/src/features/ui/tabs/TabKeyboardNavigation.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getNextTabIndex, getTabNavigationDirection} from '@app/features/ui/tabs/TabKeyboardNavigation';
-import {describe, expect, it} from 'vitest';
-
-describe('TabKeyboardNavigation', () => {
- it('maps horizontal tablist keys without stealing vertical scroll keys', () => {
- expect(getTabNavigationDirection('ArrowLeft', 'horizontal')).toBe('previous');
- expect(getTabNavigationDirection('ArrowRight', 'horizontal')).toBe('next');
- expect(getTabNavigationDirection('ArrowUp', 'horizontal')).toBeNull();
- expect(getTabNavigationDirection('ArrowDown', 'horizontal')).toBeNull();
- });
- it('maps vertical tablist keys without stealing horizontal keys', () => {
- expect(getTabNavigationDirection('ArrowUp', 'vertical')).toBe('previous');
- expect(getTabNavigationDirection('ArrowDown', 'vertical')).toBe('next');
- expect(getTabNavigationDirection('ArrowLeft', 'vertical')).toBeNull();
- expect(getTabNavigationDirection('ArrowRight', 'vertical')).toBeNull();
- });
- it('supports both axes for sidebar-style composites', () => {
- expect(getTabNavigationDirection('ArrowUp', 'both')).toBe('previous');
- expect(getTabNavigationDirection('ArrowLeft', 'both')).toBe('previous');
- expect(getTabNavigationDirection('ArrowDown', 'both')).toBe('next');
- expect(getTabNavigationDirection('ArrowRight', 'both')).toBe('next');
- });
- it('moves to first, last, next, and previous with wrapping', () => {
- expect(getNextTabIndex(1, 4, 'first')).toBe(0);
- expect(getNextTabIndex(1, 4, 'last')).toBe(3);
- expect(getNextTabIndex(3, 4, 'next')).toBe(0);
- expect(getNextTabIndex(0, 4, 'previous')).toBe(3);
- });
-});
diff --git a/fluxer_app/src/features/ui/tooltip/TooltipStateMachine.test.ts b/fluxer_app/src/features/ui/tooltip/TooltipStateMachine.test.ts
deleted file mode 100644
index 3bead0b7c..000000000
--- a/fluxer_app/src/features/ui/tooltip/TooltipStateMachine.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createTooltipSnapshot,
- DEFAULT_TOOLTIP_ENVIRONMENT,
- selectTooltipModel,
- type TooltipEnvironment,
- type TooltipMachineEvent,
- type TooltipModel,
- type TooltipSnapshot,
- tooltipSnapshotsAreEquivalent,
- transitionTooltipSnapshot,
-} from '@app/features/ui/tooltip/TooltipStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function environment(overrides: Partial<TooltipEnvironment> = {}): TooltipEnvironment {
- return {...DEFAULT_TOOLTIP_ENVIRONMENT, ...overrides};
-}
-
-function transition(snapshot: TooltipSnapshot, event: TooltipMachineEvent): TooltipSnapshot {
- return transitionTooltipSnapshot(snapshot, event);
-}
-
-function expectModel(snapshot: TooltipSnapshot, expected: Partial<TooltipModel>) {
- expect(selectTooltipModel(snapshot)).toMatchObject(expected);
-}
-
-describe('tooltipStateMachine', () => {
- it('starts hidden without a visibility driver', () => {
- const snapshot = createTooltipSnapshot();
-
- expectModel(snapshot, {
- state: 'hidden',
- shouldRender: false,
- hasVisibilityDriver: false,
- });
- });
-
- it('opens immediately from hover when the environment allows tooltips', () => {
- const snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'visible',
- hovered: true,
- delayPending: false,
- shouldRender: true,
- });
- });
-
- it('waits in the delayed state until the delay elapses', () => {
- let snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: true,
- });
-
- expectModel(snapshot, {
- state: 'delayed',
- delayPending: true,
- shouldRender: false,
- });
-
- snapshot = transition(snapshot, {type: 'tooltip.delayElapsed'});
-
- expectModel(snapshot, {
- state: 'visible',
- delayPending: false,
- shouldRender: true,
- });
- });
-
- it('cancels a pending delayed hover when hover leaves', () => {
- let snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: true,
- });
-
- snapshot = transition(snapshot, {
- type: 'tooltip.hoverChanged',
- hovered: false,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- hovered: false,
- delayPending: false,
- shouldRender: false,
- });
- });
-
- it('opens from focus only when keyboard mode is enabled', () => {
- let snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.focusChanged',
- focused: true,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- focused: true,
- dismissed: true,
- shouldRender: false,
- });
-
- snapshot = transition(
- createTooltipSnapshot({
- keyboardModeEnabled: true,
- }),
- {
- type: 'tooltip.focusChanged',
- focused: true,
- delay: false,
- },
- );
-
- expectModel(snapshot, {
- state: 'visible',
- focused: true,
- dismissed: false,
- shouldRender: true,
- });
- });
-
- it('keeps a hovered tooltip open when keyboard focus leaves', () => {
- let snapshot = createTooltipSnapshot({keyboardModeEnabled: true});
- snapshot = transition(snapshot, {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
- snapshot = transition(snapshot, {
- type: 'tooltip.focusChanged',
- focused: true,
- delay: false,
- });
- snapshot = transition(snapshot, {
- type: 'tooltip.focusChanged',
- focused: false,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'visible',
- hovered: true,
- focused: false,
- shouldRender: true,
- });
- });
-
- it('dismisses until a fresh hover enters again', () => {
- let snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
- snapshot = transition(snapshot, {type: 'tooltip.dismiss'});
-
- expectModel(snapshot, {
- state: 'hidden',
- hovered: true,
- dismissed: true,
- shouldRender: false,
- });
-
- snapshot = transition(snapshot, {
- type: 'tooltip.hoverChanged',
- hovered: false,
- delay: false,
- });
- snapshot = transition(snapshot, {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'visible',
- hovered: true,
- dismissed: false,
- shouldRender: true,
- });
- });
-
- it('hides and suppresses re-opening when the environment becomes blocked', () => {
- let snapshot = transition(createTooltipSnapshot(), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
-
- snapshot = transition(snapshot, {
- type: 'tooltip.environmentChanged',
- environment: environment({contextMenuOpen: true}),
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- hovered: true,
- dismissed: true,
- shouldRender: false,
- });
-
- snapshot = transition(snapshot, {
- type: 'tooltip.environmentChanged',
- environment: environment(),
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- hovered: true,
- dismissed: true,
- shouldRender: false,
- });
- });
-
- it.each([
- ['disabled', {disabled: true}],
- ['mobile layout', {mobileEnabled: true}],
- ['context menu', {contextMenuOpen: true}],
- ['blocked hover controls', {hoverControlsEnabled: false}],
- ['empty content', {hasRenderableContent: false}],
- ] satisfies Array<
- [string, Partial<TooltipEnvironment>]
- >)('does not open while %s blocks the environment', (_name, override) => {
- const snapshot = transition(createTooltipSnapshot(override), {
- type: 'tooltip.hoverChanged',
- hovered: true,
- delay: false,
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- hovered: true,
- shouldRender: false,
- });
- });
-
- it('hides a focus-only tooltip if keyboard mode turns off', () => {
- let snapshot = createTooltipSnapshot({keyboardModeEnabled: true});
- snapshot = transition(snapshot, {
- type: 'tooltip.focusChanged',
- focused: true,
- delay: false,
- });
- snapshot = transition(snapshot, {
- type: 'tooltip.environmentChanged',
- environment: environment({keyboardModeEnabled: false}),
- });
-
- expectModel(snapshot, {
- state: 'hidden',
- focused: true,
- dismissed: true,
- shouldRender: false,
- });
- });
-
- it('reports equivalent snapshots for no-op transitions', () => {
- const snapshot = createTooltipSnapshot();
- const nextSnapshot = transition(snapshot, {type: 'tooltip.delayElapsed'});
-
- expect(tooltipSnapshotsAreEquivalent(snapshot, nextSnapshot)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/ui/utils/AppZoomKeybindUtils.test.ts b/fluxer_app/src/features/ui/utils/AppZoomKeybindUtils.test.ts
deleted file mode 100644
index bd19aa6e5..000000000
--- a/fluxer_app/src/features/ui/utils/AppZoomKeybindUtils.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {KeybindCommand, KeyCombo} from '@app/features/input/state/InputKeybind';
-import {isWebReservedZoomShortcut} from '@app/features/ui/utils/AppZoomKeybindUtils';
-import {describe, expect, it} from 'vitest';
-
-const zoomShortcut = (action: KeybindCommand, combo: KeyCombo, isDesktop = false): boolean =>
- isWebReservedZoomShortcut(action, combo, {isDesktop});
-
-describe('AppZoomKeybindUtils', () => {
- it('reserves standard browser zoom shortcuts on web', () => {
- expect(zoomShortcut('system_zoom_in', {key: '=', ctrlOrMeta: true})).toBe(true);
- expect(zoomShortcut('system_zoom_out', {key: '-', ctrlOrMeta: true})).toBe(true);
- expect(zoomShortcut('system_zoom_reset', {key: '0', ctrlOrMeta: true})).toBe(true);
- });
-
- it('allows app zoom shortcuts on desktop', () => {
- expect(zoomShortcut('system_zoom_in', {key: '=', ctrlOrMeta: true}, true)).toBe(false);
- expect(zoomShortcut('system_zoom_out', {key: '-', ctrlOrMeta: true}, true)).toBe(false);
- expect(zoomShortcut('system_zoom_reset', {key: '0', ctrlOrMeta: true}, true)).toBe(false);
- });
-
- it('does not reserve unrelated shortcuts', () => {
- expect(zoomShortcut('misc_help', {key: '=', ctrlOrMeta: true})).toBe(false);
- expect(zoomShortcut('system_zoom_in', {key: '=', alt: true, ctrlOrMeta: true})).toBe(false);
- expect(zoomShortcut('system_zoom_in', {key: '='})).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/ui/utils/DimensionUtils.test.ts b/fluxer_app/src/features/ui/utils/DimensionUtils.test.ts
deleted file mode 100644
index 7ca360a26..000000000
--- a/fluxer_app/src/features/ui/utils/DimensionUtils.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createCalculator, fitMediaWithinBounds, mediaAspectRatioValue} from '@app/features/ui/utils/DimensionUtils';
-import {describe, expect, it} from 'vitest';
-
-const ATTACHMENT_CAPS = {maxWidth: 550, maxHeight: 350};
-
-describe('fitMediaWithinBounds', () => {
- it('fits the maintainer 797x118 case to 550x81', () => {
- expect(fitMediaWithinBounds({width: 797, height: 118, ...ATTACHMENT_CAPS})).toEqual({width: 550, height: 81});
- });
-
- it('binds on height in the second pass for a tall image', () => {
- expect(fitMediaWithinBounds({width: 400, height: 1200, ...ATTACHMENT_CAPS})).toEqual({width: 117, height: 350});
- expect(fitMediaWithinBounds({width: 1000, height: 3000, ...ATTACHMENT_CAPS})).toEqual({width: 117, height: 350});
- });
-
- it('never upscales media that is already under both caps', () => {
- expect(fitMediaWithinBounds({width: 200, height: 100, ...ATTACHMENT_CAPS})).toEqual({width: 200, height: 100});
- expect(fitMediaWithinBounds({width: 43, height: 48, maxWidth: 400, maxHeight: 300})).toEqual({
- width: 43,
- height: 48,
- });
- });
-
- it('rounds twice, once per pass, rather than applying a single combined scale', () => {
- const combined = (width: number, height: number, maxWidth: number, maxHeight: number) => {
- const scale = Math.min(1, maxWidth / width, maxHeight / height);
- return {width: Math.round(width * scale), height: Math.round(height * scale)};
- };
- for (const [width, height, twoPassWidth, combinedWidth] of [
- [551, 351, 550, 549],
- [800, 600, 466, 467],
- [1200, 900, 466, 467],
- ] as const) {
- expect(fitMediaWithinBounds({width, height, ...ATTACHMENT_CAPS})).toEqual({
- width: twoPassWidth,
- height: 350,
- });
- expect(combined(width, height, 550, 350)).toEqual({width: combinedWidth, height: 350});
- expect(twoPassWidth).not.toBe(combinedWidth);
- }
- expect(fitMediaWithinBounds({width: 797, height: 600, ...ATTACHMENT_CAPS})).toEqual({width: 465, height: 350});
- expect(fitMediaWithinBounds({width: 550, height: 350, ...ATTACHMENT_CAPS})).toEqual({width: 550, height: 350});
- });
-});
-
-describe('MediaDimensionCalculator', () => {
- it('caps the wrapper at the fitted width so small media is not stretched', () => {
- const calculator = createCalculator({maxWidth: 400, maxHeight: 300});
-
- const {dimensions, style} = calculator.calculate({width: 43, height: 48});
-
- expect(dimensions).toEqual({width: 43, height: 48});
- expect(style).toMatchObject({
- maxWidth: 'min(100%, 2.6875rem)',
- width: '100%',
- display: 'block',
- aspectRatio: 43 / 48,
- });
- });
-
- it('carries the aspect ratio as a unitless number for the maintainer case', () => {
- const calculator = createCalculator(ATTACHMENT_CAPS);
-
- const {dimensions, style} = calculator.calculate({width: 797, height: 118});
-
- expect(dimensions).toEqual({width: 550, height: 81});
- expect(style.aspectRatio).toBe(550 / 81);
- expect(style.aspectRatio).toBeCloseTo(6.79012, 5);
- expect(typeof style.aspectRatio).toBe('number');
- });
-
- it('scales tall media down to the height cap without an off-by-one', () => {
- const calculator = createCalculator(ATTACHMENT_CAPS);
-
- const {dimensions, style} = calculator.calculate({width: 400, height: 1200});
-
- expect(dimensions).toEqual({width: 117, height: 350});
- expect(style.maxHeight).toBe('21.875rem');
- expect(mediaAspectRatioValue(dimensions)).toBeCloseTo(0.334286, 6);
- });
-
- it('preserves an already fitted pair and still emits the numeric aspect ratio', () => {
- const calculator = createCalculator(ATTACHMENT_CAPS);
-
- const {dimensions, style} = calculator.calculate({width: 550, height: 81}, {preserve: true});
-
- expect(dimensions).toEqual({width: 550, height: 81});
- expect(style).toMatchObject({width: '34.375rem', maxWidth: '100%', aspectRatio: 550 / 81});
- });
-});
diff --git a/fluxer_app/src/features/ui/utils/PointerActivationFocus.test.ts b/fluxer_app/src/features/ui/utils/PointerActivationFocus.test.ts
deleted file mode 100644
index d09dade93..000000000
--- a/fluxer_app/src/features/ui/utils/PointerActivationFocus.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearPointerActivationFocusTargetForTests,
- getActivatableFocusTarget,
- recordPointerActivationFocusTarget,
- shouldRestoreFocusToTarget,
-} from '@app/features/ui/utils/PointerActivationFocus';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('PointerActivationFocus', () => {
- afterEach(() => {
- document.body.replaceChildren();
- clearPointerActivationFocusTargetForTests();
- });
-
- it('finds the nearest native or ARIA button from a child event target', () => {
- const button = document.createElement('button');
- const icon = document.createElement('span');
- button.append(icon);
- document.body.append(button);
-
- const ariaButton = document.createElement('div');
- ariaButton.setAttribute('role', 'button');
- const label = document.createElement('span');
- ariaButton.append(label);
- document.body.append(ariaButton);
-
- expect(getActivatableFocusTarget(icon)).toBe(button);
- expect(getActivatableFocusTarget(label)).toBe(ariaButton);
- expect(getActivatableFocusTarget(document.body)).toBeNull();
- });
-
- it('suppresses focus restoration to a pointer-activated control in pointer mode', () => {
- const button = document.createElement('button');
- document.body.append(button);
-
- recordPointerActivationFocusTarget(button);
-
- expect(shouldRestoreFocusToTarget(button, false)).toBe(false);
- expect(shouldRestoreFocusToTarget(button, true)).toBe(true);
- });
-
- it('allows focus restoration to unrelated targets and after the pointer target is cleared', () => {
- const button = document.createElement('button');
- const textarea = document.createElement('textarea');
- document.body.append(button, textarea);
-
- recordPointerActivationFocusTarget(button);
- expect(shouldRestoreFocusToTarget(textarea, false)).toBe(true);
-
- recordPointerActivationFocusTarget(null);
- expect(shouldRestoreFocusToTarget(button, false)).toBe(true);
- });
-
- it('suppresses restoration when the trigger wraps the pointer-activated button', () => {
- const wrapper = document.createElement('div');
- const button = document.createElement('button');
- wrapper.append(button);
- document.body.append(wrapper);
-
- recordPointerActivationFocusTarget(button);
-
- expect(shouldRestoreFocusToTarget(wrapper, false)).toBe(false);
- expect(shouldRestoreFocusToTarget(wrapper, true)).toBe(true);
- });
-
- it('suppresses restoration when the pointer-activated control wraps the trigger target', () => {
- const button = document.createElement('button');
- const inner = document.createElement('span');
- button.append(inner);
- document.body.append(button);
-
- recordPointerActivationFocusTarget(button);
-
- expect(shouldRestoreFocusToTarget(inner, false)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.ts b/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.ts
deleted file mode 100644
index f7c43eb99..000000000
--- a/fluxer_app/src/features/ui/utils/WindowFocusInteractionGuard.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- canUseWindowFocusedHoverControls,
- createWindowFocusInteractionGuard,
- isWindowFocusActivationGuardActive,
- subscribeWindowHoverControlsChange,
- WINDOW_FOCUSED_CLASS,
- type WindowFocusInteractionGuard,
-} from '@app/features/ui/utils/WindowFocusInteractionGuard';
-import {afterEach, describe, expect, it} from 'vitest';
-
-const GUARD_TIMEOUT_MS = 10;
-
-let activeGuard: WindowFocusInteractionGuard | null = null;
-let unsubscribe: (() => void) | null = null;
-
-function createFocusedGuard(): {guard: WindowFocusInteractionGuard; root: HTMLElement; observed: Array<boolean>} {
- const root = document.createElement('div');
- root.classList.add(WINDOW_FOCUSED_CLASS);
- document.body.append(root);
- const guard = createWindowFocusInteractionGuard({
- root,
- guardTimeoutMs: GUARD_TIMEOUT_MS,
- releaseClearDelayMs: 5,
- maxGuardTimeoutMs: 200,
- });
- activeGuard = guard;
- const observed: Array<boolean> = [];
- unsubscribe = subscribeWindowHoverControlsChange(() => observed.push(canUseWindowFocusedHoverControls(root)));
- return {guard, root, observed};
-}
-
-function wait(ms: number): Promise<void> {
- return new Promise((resolve) => {
- setTimeout(resolve, ms);
- });
-}
-
-afterEach(() => {
- unsubscribe?.();
- unsubscribe = null;
- activeGuard?.destroy();
- activeGuard = null;
- document.body.replaceChildren();
-});
-
-describe('WindowFocusInteractionGuard', () => {
- it('never publishes an enabled edge between refocus and the activation guard', async () => {
- const {guard, root, observed} = createFocusedGuard();
-
- guard.setFocused(false);
- guard.setFocused(true);
-
- expect(observed).toEqual([false]);
- expect(isWindowFocusActivationGuardActive(root)).toBe(true);
- expect(canUseWindowFocusedHoverControls(root)).toBe(false);
-
- await wait(GUARD_TIMEOUT_MS * 3);
-
- expect(observed).toEqual([false, true]);
- expect(canUseWindowFocusedHoverControls(root)).toBe(true);
- });
-
- it('does not publish an enabled edge while tearing down a guarded window', () => {
- const {guard, observed} = createFocusedGuard();
-
- guard.setFocused(false);
- guard.setFocused(true);
- observed.length = 0;
-
- guard.destroy();
- activeGuard = null;
-
- expect(observed).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/updater/state/UpdaterStateMachine.test.ts b/fluxer_app/src/features/updater/state/UpdaterStateMachine.test.ts
deleted file mode 100644
index 74c8928a4..000000000
--- a/fluxer_app/src/features/updater/state/UpdaterStateMachine.test.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {UpdaterDownloadOption} from '@app/features/platform/types/Electron';
-import {
- createUpdaterMachineSnapshot,
- getUpdaterDisplayVersion,
- getUpdaterMachineStateValue,
- getUpdaterUpdateType,
- hasManualNativeDownload,
- transitionUpdaterMachineSnapshot,
- type UpdaterMachineEvent,
- type UpdaterMachineSnapshot,
-} from '@app/features/updater/state/UpdaterStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const NOW = 1_700_000_000_000;
-
-const APPIMAGE_OPTION: UpdaterDownloadOption = {
- format: 'appimage',
- label: 'AppImage',
- url: 'https://api.fluxer.app/dl/desktop/stable/linux/x64/latest/appimage',
- suggestedName: 'Fluxer-1.2.3-linux-x86_64.AppImage',
- sha256: 'abc123',
-};
-
-const DEB_OPTION: UpdaterDownloadOption = {
- format: 'deb',
- label: 'DEB package',
- url: 'https://api.fluxer.app/dl/desktop/stable/linux/x64/latest/deb',
- suggestedName: 'Fluxer-1.2.3-linux-amd64.deb',
- sha256: 'def456',
-};
-
-function transition(snapshot: UpdaterMachineSnapshot, event: UpdaterMachineEvent): UpdaterMachineSnapshot {
- return transitionUpdaterMachineSnapshot(snapshot, event);
-}
-
-describe('updaterStateMachine', () => {
- it('starts idle with no update surface', () => {
- const snapshot = createUpdaterMachineSnapshot();
- expect(getUpdaterMachineStateValue(snapshot)).toBe('idle');
- expect(getUpdaterUpdateType(snapshot)).toBe(null);
- expect(hasManualNativeDownload(snapshot)).toBe(false);
- expect(snapshot.context.updateInfo.native.available).toBe(false);
- expect(snapshot.context.updateInfo.web.available).toBe(false);
- });
-
- it('keeps a downloaded native update pending restart when checks re-emit available or not-available', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '2.0.0',
- downloadSize: 1000,
- downloadStarted: true,
- downloadUrl: null,
- downloadOptions: [],
- });
- snapshot = transition(snapshot, {type: 'native.downloaded', version: '2.0.0'});
- expect(snapshot.context.updateInfo.native.downloaded).toBe(true);
-
- snapshot = transition(snapshot, {type: 'native.notAvailable', now: NOW});
- expect(snapshot.context.updateInfo.native.downloaded).toBe(true);
- expect(snapshot.context.updateInfo.native.available).toBe(true);
-
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: null,
- downloadSize: null,
- downloadStarted: true,
- downloadUrl: null,
- downloadOptions: [],
- });
- expect(snapshot.context.updateInfo.native.downloaded).toBe(true);
- expect(snapshot.context.updateInfo.native.downloading).toBe(false);
- expect(snapshot.context.updateInfo.native.version).toBe('2.0.0');
- });
-
- it('tracks check start and finish separately from available updates', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'check.started'});
- expect(getUpdaterMachineStateValue(snapshot)).toBe('checking');
- expect(snapshot.context.checkInProgress).toBe(true);
- snapshot = transition(snapshot, {type: 'check.finished', now: NOW});
- expect(getUpdaterMachineStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.checkInProgress).toBe(false);
- expect(snapshot.context.lastCheckedAt).toBe(NOW);
- });
-
- it('surfaces Linux manual native updates with package choices and versions', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '1.2.3',
- downloadSize: null,
- downloadStarted: false,
- downloadUrl: APPIMAGE_OPTION.url,
- downloadOptions: [APPIMAGE_OPTION, DEB_OPTION],
- });
- expect(getUpdaterMachineStateValue(snapshot)).toBe('available');
- expect(getUpdaterUpdateType(snapshot)).toBe('native');
- expect(getUpdaterDisplayVersion(snapshot)).toBe('1.2.3');
- expect(hasManualNativeDownload(snapshot)).toBe(true);
- expect(snapshot.context.nativeManualDownloadOptions).toEqual([APPIMAGE_OPTION, DEB_OPTION]);
- expect(snapshot.context.updateInfo.native).toMatchObject({
- available: true,
- downloaded: false,
- downloading: false,
- version: '1.2.3',
- });
- });
-
- it('keeps automatic desktop downloads separate from manual package downloads', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '2.0.0',
- downloadSize: 4096,
- downloadStarted: false,
- downloadUrl: null,
- downloadOptions: [],
- });
- expect(hasManualNativeDownload(snapshot)).toBe(false);
- snapshot = transition(snapshot, {type: 'native.download.started', progressSupported: true, total: 4096});
- expect(snapshot.context.updateInfo.native.downloading).toBe(true);
- expect(snapshot.context.downloadProgress).toEqual({
- percent: 0,
- transferred: 0,
- total: 4096,
- bytesPerSecond: 0,
- });
- snapshot = transition(snapshot, {
- type: 'native.progress',
- progress: {percent: 50, transferred: 2048, total: 4096, bytesPerSecond: 512},
- });
- expect(snapshot.context.downloadProgress?.percent).toBe(50);
- });
-
- it('marks downloaded desktop updates ready and clears manual download choices', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '1.2.3',
- downloadSize: null,
- downloadStarted: false,
- downloadUrl: APPIMAGE_OPTION.url,
- downloadOptions: [APPIMAGE_OPTION],
- });
- snapshot = transition(snapshot, {type: 'native.downloaded', version: '1.2.3'});
- expect(snapshot.context.updateInfo.native).toMatchObject({
- available: true,
- downloaded: true,
- downloading: false,
- });
- expect(hasManualNativeDownload(snapshot)).toBe(false);
- expect(snapshot.context.nativeManualDownloadOptions).toEqual([]);
- });
-
- it('prioritizes desktop updates when desktop and web updates are both available', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'web.checked', available: true, version: 'web-2026.05.31'});
- expect(getUpdaterUpdateType(snapshot)).toBe('web');
- expect(getUpdaterDisplayVersion(snapshot)).toBe('web-2026.05.31');
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '3.0.0',
- downloadSize: null,
- downloadStarted: false,
- downloadUrl: null,
- downloadOptions: [],
- });
- expect(getUpdaterUpdateType(snapshot)).toBe('both');
- expect(getUpdaterDisplayVersion(snapshot)).toBe('3.0.0');
- });
-
- it('hides Flatpak and other system-managed installs from the native update surface', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '1.2.3',
- downloadSize: null,
- downloadStarted: false,
- downloadUrl: APPIMAGE_OPTION.url,
- downloadOptions: [APPIMAGE_OPTION],
- });
- snapshot = transition(snapshot, {
- type: 'native.unsupported',
- reason: 'managed-package',
- downloadUrl: null,
- now: NOW,
- });
- expect(getUpdaterMachineStateValue(snapshot)).toBe('idle');
- expect(getUpdaterUpdateType(snapshot)).toBe(null);
- expect(snapshot.context.updateInfo.native.available).toBe(false);
- expect(snapshot.context.nativeUnsupported).toEqual({reason: 'managed-package', downloadUrl: null});
- });
-
- it('keeps an already-downloaded desktop update visible when a later check finds nothing newer', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'native.downloaded', version: '4.0.0'});
- snapshot = transition(snapshot, {type: 'native.notAvailable', now: NOW});
- expect(getUpdaterMachineStateValue(snapshot)).toBe('available');
- expect(snapshot.context.updateInfo.native.downloaded).toBe(true);
- expect(getUpdaterDisplayVersion(snapshot)).toBe('4.0.0');
- });
-
- it('does not discard existing update availability when a later check fails', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'web.checked', available: true, version: 'web-2026.05.31'});
- snapshot = transition(snapshot, {type: 'check.started'});
- snapshot = transition(snapshot, {type: 'check.failed', now: NOW});
- expect(getUpdaterMachineStateValue(snapshot)).toBe('available');
- expect(getUpdaterUpdateType(snapshot)).toBe('web');
- expect(snapshot.context.checkInProgress).toBe(false);
- });
-
- it('records native check errors and clears the flag on the next check', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'check.started'});
- snapshot = transition(snapshot, {type: 'native.error'});
- expect(snapshot.context.nativeCheckFailed).toBe(true);
- expect(snapshot.context.checkInProgress).toBe(false);
- snapshot = transition(snapshot, {type: 'check.started'});
- expect(snapshot.context.nativeCheckFailed).toBe(false);
- });
-
- it('tracks manual package download submission without changing update availability', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'native.available',
- version: '1.2.3',
- downloadSize: null,
- downloadStarted: false,
- downloadUrl: APPIMAGE_OPTION.url,
- downloadOptions: [APPIMAGE_OPTION],
- });
- snapshot = transition(snapshot, {type: 'manualDownload.started'});
- expect(snapshot.context.manualNativeDownloadInFlight).toBe(true);
- expect(getUpdaterUpdateType(snapshot)).toBe('native');
- snapshot = transition(snapshot, {type: 'manualDownload.finished'});
- expect(snapshot.context.manualNativeDownloadInFlight).toBe(false);
- expect(getUpdaterUpdateType(snapshot)).toBe('native');
- });
-
- it('reset clears all update state and in-flight flags', () => {
- let snapshot = createUpdaterMachineSnapshot();
- snapshot = transition(snapshot, {type: 'web.checked', available: true, version: 'web-2026.05.31'});
- snapshot = transition(snapshot, {type: 'manualDownload.started'});
- snapshot = transition(snapshot, {type: 'reset'});
- expect(getUpdaterMachineStateValue(snapshot)).toBe('idle');
- expect(getUpdaterUpdateType(snapshot)).toBe(null);
- expect(snapshot.context.manualNativeDownloadInFlight).toBe(false);
- expect(snapshot.context.lastCheckedAt).toBe(null);
- });
-});
diff --git a/fluxer_app/src/features/updater/utils/LinuxManualUpdateOptions.test.ts b/fluxer_app/src/features/updater/utils/LinuxManualUpdateOptions.test.ts
deleted file mode 100644
index d4d194e69..000000000
--- a/fluxer_app/src/features/updater/utils/LinuxManualUpdateOptions.test.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {UpdaterDownloadOption} from '@app/features/platform/types/Electron';
-import {buildLinuxManualUpdateOptions} from '@app/features/updater/utils/LinuxManualUpdateOptions';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/app/config/Config', () => ({
- default: {
- PUBLIC_BUILD_VERSION: 'test',
- PUBLIC_RELEASE_CHANNEL: 'canary',
- PUBLIC_BOOTSTRAP_API_ENDPOINT: 'https://example.invalid',
- PUBLIC_BOOTSTRAP_API_PUBLIC_ENDPOINT: 'https://example.invalid',
- },
-}));
-
-const REPORTED_VERSION = '2026.908.173325';
-const NEWER_VERSION = '2026.909.202036';
-const CANARY_X64 = 'https://api.canary.fluxer.app/dl/desktop/canary/linux/x64';
-const STABLE_X64 = 'https://api.fluxer.app/dl/desktop/stable/linux/x64';
-
-function desktopMainOptions(params: {
- linkBase: string;
- productName: string;
- version: string;
- linkVersion: string;
-}): Array<UpdaterDownloadOption> {
- const {linkBase, productName, version, linkVersion} = params;
- return [
- {
- format: 'appimage',
- label: 'AppImage',
- url: `${linkBase}/${linkVersion}/appimage`,
- suggestedName: `${productName}-${version}-linux-x86_64.AppImage`,
- sha256: `appimage-${version}`,
- },
- {
- format: 'deb',
- label: 'DEB package',
- url: `${linkBase}/${linkVersion}/deb`,
- suggestedName: `${productName}-${version}-linux-amd64.deb`,
- sha256: `deb-${version}`,
- },
- {
- format: 'rpm',
- label: 'RPM package',
- url: `${linkBase}/${linkVersion}/rpm`,
- suggestedName: `${productName}-${version}-linux-x86_64.rpm`,
- sha256: `rpm-${version}`,
- },
- {
- format: 'tar_gz',
- label: 'tar.gz archive',
- url: `${linkBase}/${linkVersion}/tar_gz`,
- suggestedName: `${productName}-${version}-linux-x64.tar.gz`,
- sha256: `tar_gz-${version}`,
- },
- ];
-}
-
-describe('buildLinuxManualUpdateOptions', () => {
- it('pins the link, file name and checksum of every format to the same version', () => {
- const options = buildLinuxManualUpdateOptions({channel: 'stable', arch: 'x64', version: REPORTED_VERSION});
- expect(options).toEqual([
- {
- format: 'appimage',
- label: 'AppImage',
- url: `${STABLE_X64}/${REPORTED_VERSION}/appimage`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-x86_64.AppImage`,
- sha256: null,
- },
- {
- format: 'deb',
- label: 'DEB package',
- url: `${STABLE_X64}/${REPORTED_VERSION}/deb`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-amd64.deb`,
- sha256: null,
- },
- {
- format: 'rpm',
- label: 'RPM package',
- url: `${STABLE_X64}/${REPORTED_VERSION}/rpm`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-x86_64.rpm`,
- sha256: null,
- },
- {
- format: 'tar_gz',
- label: 'tar.gz archive',
- url: `${STABLE_X64}/${REPORTED_VERSION}/tar_gz`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-x64.tar.gz`,
- sha256: null,
- },
- ]);
- });
-
- it('pins the latest links sent by current desktop builds to the announced version', () => {
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: `${CANARY_X64}/latest/appimage`,
- channel: 'canary',
- arch: 'x64',
- version: REPORTED_VERSION,
- knownOptions: desktopMainOptions({
- linkBase: CANARY_X64,
- productName: 'Fluxer-Canary',
- version: REPORTED_VERSION,
- linkVersion: 'latest',
- }),
- });
- expect(options).toEqual(
- desktopMainOptions({
- linkBase: CANARY_X64,
- productName: 'Fluxer-Canary',
- version: REPORTED_VERSION,
- linkVersion: REPORTED_VERSION,
- }),
- );
- });
-
- it('keeps the pinned links sent by newer desktop builds', () => {
- const pinnedOptions = desktopMainOptions({
- linkBase: CANARY_X64,
- productName: 'Fluxer-Canary',
- version: REPORTED_VERSION,
- linkVersion: REPORTED_VERSION,
- });
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: pinnedOptions[0].url,
- channel: 'canary',
- arch: 'x64',
- version: REPORTED_VERSION,
- knownOptions: pinnedOptions,
- });
- expect(options).toEqual(pinnedOptions);
- });
-
- it('only uses latest links and latest file names when no version is known', () => {
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: `${STABLE_X64}/latest/appimage`,
- channel: 'stable',
- arch: 'x64',
- version: null,
- knownOptions: desktopMainOptions({
- linkBase: STABLE_X64,
- productName: 'Fluxer',
- version: REPORTED_VERSION,
- linkVersion: 'latest',
- }),
- });
- expect(options.map(({url, suggestedName, sha256}) => ({url, suggestedName, sha256}))).toEqual([
- {url: `${STABLE_X64}/latest/appimage`, suggestedName: 'Fluxer-latest-linux-x86_64.AppImage', sha256: null},
- {url: `${STABLE_X64}/latest/deb`, suggestedName: 'Fluxer-latest-linux-amd64.deb', sha256: null},
- {url: `${STABLE_X64}/latest/rpm`, suggestedName: 'Fluxer-latest-linux-x86_64.rpm', sha256: null},
- {url: `${STABLE_X64}/latest/tar_gz`, suggestedName: 'Fluxer-latest-linux-x64.tar.gz', sha256: null},
- ]);
- });
-
- it('uses arm64 links and file name tokens on arm64 systems', () => {
- const expected = [
- {
- url: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/appimage`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-arm64.AppImage`,
- },
- {
- url: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/deb`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-arm64.deb`,
- },
- {
- url: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/rpm`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-aarch64.rpm`,
- },
- {
- url: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/tar_gz`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-arm64.tar.gz`,
- },
- ];
- const fromDesktopInfo = buildLinuxManualUpdateOptions({
- channel: 'stable',
- arch: 'aarch64',
- version: REPORTED_VERSION,
- });
- const fromLatestLink = buildLinuxManualUpdateOptions({
- downloadUrl: 'https://api.fluxer.app/dl/desktop/stable/linux/arm64/latest/appimage',
- version: REPORTED_VERSION,
- });
- const fromPinnedLink = buildLinuxManualUpdateOptions({
- downloadUrl: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/deb`,
- version: REPORTED_VERSION,
- });
- for (const options of [fromDesktopInfo, fromLatestLink, fromPinnedLink]) {
- expect(options.map(({url, suggestedName}) => ({url, suggestedName}))).toEqual(expected);
- }
- });
-
- it('preserves the query string of latest and pinned links', () => {
- const fromLatestLink = buildLinuxManualUpdateOptions({
- downloadUrl: `${CANARY_X64}/latest/appimage?test=1`,
- version: REPORTED_VERSION,
- });
- const fromPinnedLink = buildLinuxManualUpdateOptions({
- downloadUrl: `${CANARY_X64}/${REPORTED_VERSION}/appimage?test=1`,
- version: REPORTED_VERSION,
- });
- const expectedUrls = [
- `${CANARY_X64}/${REPORTED_VERSION}/appimage?test=1`,
- `${CANARY_X64}/${REPORTED_VERSION}/deb?test=1`,
- `${CANARY_X64}/${REPORTED_VERSION}/rpm?test=1`,
- `${CANARY_X64}/${REPORTED_VERSION}/tar_gz?test=1`,
- ];
- expect(fromLatestLink.map((option) => option.url)).toEqual(expectedUrls);
- expect(fromPinnedLink.map((option) => option.url)).toEqual(expectedUrls);
- });
-
- it('builds links on the stable and canary endpoints', () => {
- const stable = buildLinuxManualUpdateOptions({channel: 'stable', arch: 'x64', version: REPORTED_VERSION});
- const canary = buildLinuxManualUpdateOptions({channel: 'canary', arch: 'x64', version: REPORTED_VERSION});
- const configuredCanary = buildLinuxManualUpdateOptions({
- channel: 'canary',
- arch: 'x64',
- version: REPORTED_VERSION,
- apiEndpoint: 'https://web.canary.fluxer.app/api/',
- });
- const proxiedCanaryLink = buildLinuxManualUpdateOptions({
- downloadUrl: 'https://web.canary.fluxer.app/api/dl/desktop/canary/linux/x64/latest/deb',
- version: REPORTED_VERSION,
- apiEndpoint: 'https://api.fluxer.app',
- });
- expect(stable[1].url).toBe(`${STABLE_X64}/${REPORTED_VERSION}/deb`);
- expect(canary[1].url).toBe(`${CANARY_X64}/${REPORTED_VERSION}/deb`);
- expect(configuredCanary[1].url).toBe(
- `https://web.canary.fluxer.app/api/dl/desktop/canary/linux/x64/${REPORTED_VERSION}/deb`,
- );
- expect(proxiedCanaryLink[1].url).toBe(
- `https://web.canary.fluxer.app/api/dl/desktop/canary/linux/x64/${REPORTED_VERSION}/deb`,
- );
- });
-
- it('never points a prompt for 2026.908.173325 at a link that could serve another build', () => {
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: `${CANARY_X64}/latest/appimage`,
- channel: 'canary',
- arch: 'x64',
- version: REPORTED_VERSION,
- apiEndpoint: 'https://api.canary.fluxer.app',
- knownOptions: desktopMainOptions({
- linkBase: CANARY_X64,
- productName: 'Fluxer-Canary',
- version: REPORTED_VERSION,
- linkVersion: 'latest',
- }),
- });
- expect(options.find((option) => option.format === 'deb')).toMatchObject({
- url: `${CANARY_X64}/${REPORTED_VERSION}/deb`,
- suggestedName: `Fluxer-Canary-${REPORTED_VERSION}-linux-amd64.deb`,
- sha256: `deb-${REPORTED_VERSION}`,
- });
- for (const option of options) {
- expect(option.url).toContain(`/${REPORTED_VERSION}/`);
- expect(option.url).not.toContain('/latest/');
- expect(option.url).not.toContain(NEWER_VERSION);
- expect(option.suggestedName).toContain(REPORTED_VERSION);
- }
- });
-
- it.each([
- 'v2026.908.173325',
- '2026.908',
- '2026.908.173325-beta',
- ])('treats the off-shape version %s as unknown', (version) => {
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: `${STABLE_X64}/latest/appimage`,
- version,
- knownOptions: desktopMainOptions({
- linkBase: STABLE_X64,
- productName: 'Fluxer',
- version,
- linkVersion: 'latest',
- }),
- });
- expect(options[1]).toEqual({
- format: 'deb',
- label: 'DEB package',
- url: `${STABLE_X64}/latest/deb`,
- suggestedName: 'Fluxer-latest-linux-amd64.deb',
- sha256: null,
- });
- });
-
- it('ignores a download link that is not for Linux', () => {
- const options = buildLinuxManualUpdateOptions({
- downloadUrl: 'https://api.fluxer.app/dl/desktop/stable/darwin/arm64/latest/dmg?test=1',
- channel: 'canary',
- arch: 'x64',
- version: REPORTED_VERSION,
- });
- expect(options.map((option) => option.url)).toEqual([
- `${CANARY_X64}/${REPORTED_VERSION}/appimage`,
- `${CANARY_X64}/${REPORTED_VERSION}/deb`,
- `${CANARY_X64}/${REPORTED_VERSION}/rpm`,
- `${CANARY_X64}/${REPORTED_VERSION}/tar_gz`,
- ]);
- });
-
- it('reads the architecture of a known package from its pinned link before its file name', () => {
- const options = buildLinuxManualUpdateOptions({
- channel: 'stable',
- arch: 'x64',
- version: REPORTED_VERSION,
- knownOptions: [
- {
- format: 'deb',
- label: 'DEB package',
- url: `https://api.fluxer.app/dl/desktop/stable/linux/arm64/${REPORTED_VERSION}/deb`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-amd64.deb`,
- sha256: 'arm64-deb',
- },
- ],
- });
- expect(options[1]).toEqual({
- format: 'deb',
- label: 'DEB package',
- url: `${STABLE_X64}/${REPORTED_VERSION}/deb`,
- suggestedName: `Fluxer-${REPORTED_VERSION}-linux-amd64.deb`,
- sha256: null,
- });
- });
-});
diff --git a/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.test.ts b/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.test.ts
deleted file mode 100644
index ce8a6312c..000000000
--- a/fluxer_app/src/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- cssColorStringToHex,
- cssColorStringToNumber,
- numberToHex,
- updateCssForVariable,
-} from '@app/features/user/components/modals/tabs/appearance_tab/theme/ThemeUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('updateCssForVariable', () => {
- it('adds a token override when the CSS is empty', () => {
- expect(updateCssForVariable('', '--background-primary', '#ff00ff')).toBe(
- ':root { --background-primary: #ff00ff; }\n',
- );
- });
- it('updates an existing token override', () => {
- expect(updateCssForVariable(':root { --background-primary: #ffffff; }\n', '--background-primary', '#111111')).toBe(
- ':root { --background-primary: #111111; }\n',
- );
- });
- it('removes the empty root block after the last token override is cleared', () => {
- expect(updateCssForVariable(':root { --background-primary: #ffffff; }\n', '--background-primary', null)).toBe('');
- });
- it('keeps unrelated CSS when clearing a token override', () => {
- expect(
- updateCssForVariable(
- 'body { color: red; }\n:root { --background-primary: #ffffff; }\n',
- '--background-primary',
- null,
- ),
- ).toBe('body { color: red; }');
- });
-});
-
-describe('cssColorStringToNumber', () => {
- it('parses black as a real color', () => {
- expect(numberToHex(cssColorStringToNumber('#000000') ?? -1)).toBe('#000000');
- expect(numberToHex(cssColorStringToNumber('rgb(0, 0, 0)') ?? -1)).toBe('#000000');
- expect(numberToHex(cssColorStringToNumber('#000000 !important') ?? -1)).toBe('#000000');
- });
- it('does not turn invalid CSS values into black', () => {
- expect(cssColorStringToNumber('1px solid hsl(0, 0%, 0%)')).toBeNull();
- expect(cssColorStringToNumber('not-a-color')).toBeNull();
- });
- it('normalizes equivalent CSS colors to the same hex value', () => {
- expect(cssColorStringToHex('rgb(0, 0, 0)')).toBe('#000000');
- expect(cssColorStringToHex('#000000 !important')).toBe('#000000');
- });
-});
diff --git a/fluxer_app/src/features/user/components/modals/tabs/hooks/useMediaPermission.test.tsx b/fluxer_app/src/features/user/components/modals/tabs/hooks/useMediaPermission.test.tsx
deleted file mode 100644
index 409916262..000000000
--- a/fluxer_app/src/features/user/components/modals/tabs/hooks/useMediaPermission.test.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- EnsureVoiceDevicesOptions,
- VoiceDeviceState,
- VoiceMediaPermissionType,
-} from '@app/features/voice/utils/VoiceDeviceManager';
-import {act, createElement, useEffect} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const deviceManagerMock = vi.hoisted(() => {
- const idleState = (): VoiceDeviceState => ({
- inputDevices: [],
- outputDevices: [],
- videoDevices: [],
- permissionStatus: {audio: 'idle', video: 'idle'},
- });
- const listeners = new Set<(state: VoiceDeviceState) => void>();
- const mock = {
- state: idleState(),
- permissionRequests: [] as Array<ReadonlyArray<VoiceMediaPermissionType>>,
- pending: [] as Array<(state: VoiceDeviceState) => void>,
- reset(): void {
- mock.state = idleState();
- mock.permissionRequests = [];
- mock.pending = [];
- listeners.clear();
- },
- settlePendingWith(next: VoiceDeviceState): void {
- const pending = mock.pending;
- mock.pending = [];
- mock.state = next;
- for (const listener of listeners) listener(next);
- for (const resolve of pending) resolve(next);
- },
- manager: {
- getState: (): VoiceDeviceState => mock.state,
- subscribe: (listener: (state: VoiceDeviceState) => void): (() => void) => {
- listeners.add(listener);
- listener(mock.state);
- return () => listeners.delete(listener);
- },
- ensureDevices: (options: EnsureVoiceDevicesOptions = {}): Promise<VoiceDeviceState> => {
- const requestPermissionTypes =
- options.requestPermissionTypes ?? (options.requestPermissions === true ? ['audio', 'video'] : []);
- if (requestPermissionTypes.length === 0) return Promise.resolve(mock.state);
- mock.permissionRequests.push([...requestPermissionTypes]);
- return new Promise<VoiceDeviceState>((resolve) => {
- mock.pending.push(resolve);
- });
- },
- },
- };
- return mock;
-});
-
-const mediaPermissionMock = vi.hoisted(() => ({
- microphoneExplicitlyDenied: false,
- cameraExplicitlyDenied: false,
- microphonePermissionState: null as PermissionState | null,
- cameraPermissionState: null as PermissionState | null,
- isMicrophoneGranted: vi.fn(() => false),
- isCameraGranted: vi.fn(() => false),
- updateMicrophonePermissionGranted: vi.fn(),
- updateCameraPermissionGranted: vi.fn(),
- markMicrophoneExplicitlyDenied: vi.fn(),
- markCameraExplicitlyDenied: vi.fn(),
-}));
-
-const handleMediaPermissionBlocked = vi.hoisted(() => vi.fn());
-
-vi.mock('@app/features/voice/utils/VoiceDeviceManager', () => ({voiceDeviceManager: deviceManagerMock.manager}));
-vi.mock('@app/features/permissions/system/state/MediaPermission', () => ({default: mediaPermissionMock}));
-vi.mock('@app/features/permissions/system/commands/MacPermissionsModalCommands', () => ({
- handleMediaPermissionBlocked,
-}));
-
-const {useMediaPermission} = await import('@app/features/user/components/modals/tabs/hooks/useMediaPermission');
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const MICROPHONE: MediaDeviceInfo = {
- deviceId: 'mic-1',
- groupId: 'group-1',
- kind: 'audioinput',
- label: 'Microphone',
- toJSON: () => ({}),
-};
-
-const grantedState = (): VoiceDeviceState => ({
- inputDevices: [MICROPHONE],
- outputDevices: [],
- videoDevices: [],
- permissionStatus: {audio: 'granted', video: 'idle'},
-});
-
-const deniedState = (): VoiceDeviceState => ({
- inputDevices: [],
- outputDevices: [],
- videoDevices: [],
- permissionStatus: {audio: 'denied', video: 'idle'},
-});
-
-let host: HTMLDivElement;
-let root: Root;
-const requesters: Array<() => Promise<boolean>> = [];
-
-function Consumer(): null {
- const {requestPermission} = useMediaPermission('audio');
- useEffect(() => {
- requesters.push(requestPermission);
- return () => {
- const index = requesters.indexOf(requestPermission);
- if (index !== -1) requesters.splice(index, 1);
- };
- }, [requestPermission]);
- return null;
-}
-
-function renderConsumers(count: number): void {
- act(() => {
- root.render(Array.from({length: count}, (_, index) => createElement(Consumer, {key: index})));
- });
-}
-
-beforeEach(() => {
- deviceManagerMock.reset();
- requesters.length = 0;
- mediaPermissionMock.microphoneExplicitlyDenied = false;
- mediaPermissionMock.microphonePermissionState = null;
- mediaPermissionMock.isMicrophoneGranted.mockReturnValue(false);
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- document.body.replaceChildren();
- vi.clearAllMocks();
-});
-
-describe('useMediaPermission', () => {
- it('raises a single device permission request when two consumers ask at once', async () => {
- renderConsumers(2);
- expect(requesters).toHaveLength(2);
-
- const results = await act(async () => {
- const pending = Promise.all([requesters[0](), requesters[1]()]);
- await Promise.resolve();
- deviceManagerMock.settlePendingWith(grantedState());
- return pending;
- });
-
- expect(deviceManagerMock.permissionRequests).toEqual([['audio']]);
- expect(results).toEqual([true, true]);
- expect(mediaPermissionMock.updateMicrophonePermissionGranted).toHaveBeenCalledTimes(1);
- });
-
- it('reports a denied request through the shared permission state', async () => {
- renderConsumers(1);
-
- const granted = await act(async () => {
- const pending = requesters[0]();
- await Promise.resolve();
- deviceManagerMock.settlePendingWith(deniedState());
- return pending;
- });
-
- expect(granted).toBe(false);
- expect(mediaPermissionMock.markMicrophoneExplicitlyDenied).toHaveBeenCalledTimes(1);
- expect(handleMediaPermissionBlocked).toHaveBeenCalledWith('microphone');
- });
-});
diff --git a/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.test.ts b/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.test.ts
deleted file mode 100644
index 3bf38b6a9..000000000
--- a/fluxer_app/src/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine.test.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- assignProfileAssetUploadPatch,
- createGlobalProfileAssetRemoteState,
- createProfileAssetCustomizationSnapshot,
- createProfileAssetRemoteStateFromFlags,
- getProfileAssetUploadPatch,
- type ProfileAssetCustomizationEvent,
- type ProfileAssetCustomizationSnapshot,
- type ProfileAssetMode,
- type ProfileAssetRemoteState,
- selectProfileAssetCustomizationState,
- transitionProfileAssetCustomizationSnapshot,
-} from '@app/features/user/components/modals/tabs/my_profile_tab/ProfileAssetCustomizationStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const IDENTITY = 'user-1:guild-1';
-const OTHER_IDENTITY = 'user-1:guild-2';
-const DATA_URL = 'data:image/png;base64,AAA';
-
-function remote(mode: ProfileAssetMode, hasCustomAsset: boolean, identityKey = IDENTITY): ProfileAssetRemoteState {
- return {identityKey, mode, hasCustomAsset};
-}
-
-function transition(
- snapshot: ProfileAssetCustomizationSnapshot,
- event: ProfileAssetCustomizationEvent,
-): ProfileAssetCustomizationSnapshot {
- return transitionProfileAssetCustomizationSnapshot(snapshot, event);
-}
-
-function hydrate(remoteState: ProfileAssetRemoteState): ProfileAssetCustomizationSnapshot {
- return transition(createProfileAssetCustomizationSnapshot(), {type: 'asset.remoteApplied', remoteState});
-}
-
-describe('ProfileAssetCustomizationStateMachine', () => {
- it('derives per-community asset modes from custom hashes and unset flags', () => {
- expect(
- createProfileAssetRemoteStateFromFlags({
- identityKey: IDENTITY,
- hasCustomAsset: false,
- isUnset: false,
- }),
- ).toEqual(remote('inherit', false));
- expect(
- createProfileAssetRemoteStateFromFlags({
- identityKey: IDENTITY,
- hasCustomAsset: true,
- isUnset: false,
- }),
- ).toEqual(remote('custom', true));
- expect(
- createProfileAssetRemoteStateFromFlags({
- identityKey: IDENTITY,
- hasCustomAsset: true,
- isUnset: true,
- }),
- ).toEqual(remote('unset', false));
- });
-
- it('tracks an accepted upload as a dirty custom asset patch', () => {
- let snapshot = hydrate(remote('inherit', false));
- snapshot = transition(snapshot, {type: 'asset.uploaded', previewUrl: DATA_URL});
-
- const state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({
- state: 'dirty',
- mode: 'custom',
- initialMode: 'inherit',
- hasCustomAsset: true,
- previewUrl: DATA_URL,
- hasCleared: false,
- hasAsset: true,
- isDirty: true,
- });
- expect(getProfileAssetUploadPatch(state)).toEqual({value: DATA_URL});
- });
-
- it('sends null when a custom asset is changed back to inherit or unset', () => {
- let snapshot = hydrate(remote('custom', true));
- snapshot = transition(snapshot, {type: 'asset.modeSelected', mode: 'inherit'});
- let state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({state: 'dirty', mode: 'inherit', hasCleared: false});
- expect(getProfileAssetUploadPatch(state)).toEqual({value: null});
-
- snapshot = hydrate(remote('custom', true));
- snapshot = transition(snapshot, {type: 'asset.modeSelected', mode: 'unset'});
- state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({state: 'dirty', mode: 'unset', hasCleared: true});
- expect(getProfileAssetUploadPatch(state)).toEqual({value: null});
- });
-
- it('does not revert an accepted custom upload when a stale same-identity remote snapshot says inherit', () => {
- let snapshot = hydrate(remote('inherit', false));
- snapshot = transition(snapshot, {type: 'asset.uploaded', previewUrl: DATA_URL});
- snapshot = transition(snapshot, {type: 'asset.committed', remoteState: remote('custom', true)});
-
- let state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({
- state: 'committed',
- mode: 'custom',
- initialMode: 'custom',
- hasCustomAsset: true,
- previewUrl: null,
- isDirty: false,
- });
-
- snapshot = transition(snapshot, {type: 'asset.remoteApplied', remoteState: remote('inherit', false)});
- state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({
- state: 'committed',
- mode: 'custom',
- hasCustomAsset: true,
- isDirty: false,
- });
- expect(getProfileAssetUploadPatch(state)).toEqual({value: undefined});
-
- snapshot = transition(snapshot, {type: 'asset.remoteApplied', remoteState: remote('custom', true)});
- state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({state: 'clean', mode: 'custom', hasCustomAsset: true});
- });
-
- it('protects dirty local edits from same-identity remote refreshes but accepts identity changes', () => {
- let snapshot = hydrate(remote('inherit', false));
- snapshot = transition(snapshot, {type: 'asset.uploaded', previewUrl: DATA_URL});
- snapshot = transition(snapshot, {type: 'asset.remoteApplied', remoteState: remote('inherit', false)});
-
- let state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({state: 'dirty', mode: 'custom', previewUrl: DATA_URL});
-
- snapshot = transition(snapshot, {
- type: 'asset.remoteApplied',
- remoteState: remote('inherit', false, OTHER_IDENTITY),
- });
- state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({
- state: 'clean',
- identityKey: OTHER_IDENTITY,
- mode: 'inherit',
- previewUrl: null,
- isDirty: false,
- });
- });
-
- it('allows explicit same-identity resets to discard dirty local edits', () => {
- let snapshot = hydrate(remote('inherit', false));
- snapshot = transition(snapshot, {type: 'asset.uploaded', previewUrl: DATA_URL});
- snapshot = transition(snapshot, {
- type: 'asset.remoteApplied',
- remoteState: remote('inherit', false),
- force: true,
- });
-
- const state = selectProfileAssetCustomizationState(snapshot);
- expect(state).toMatchObject({
- state: 'clean',
- mode: 'inherit',
- previewUrl: null,
- hasCleared: false,
- isDirty: false,
- });
- });
-
- it('assigns upload patches without writing undefined fields', () => {
- const cleanState = selectProfileAssetCustomizationState(hydrate(remote('inherit', false)));
- const dirtyState = selectProfileAssetCustomizationState(
- transition(hydrate(remote('inherit', false)), {type: 'asset.uploaded', previewUrl: DATA_URL}),
- );
- const payload: {avatar?: string | null} = {};
- assignProfileAssetUploadPatch(payload, 'avatar', cleanState);
- expect(payload).toEqual({});
- assignProfileAssetUploadPatch(payload, 'avatar', dirtyState);
- expect(payload).toEqual({avatar: DATA_URL});
- });
-
- it('models global profile assets as custom or unset instead of inherit', () => {
- expect(createGlobalProfileAssetRemoteState({identityKey: 'user-1:global', hasCustomAsset: true})).toEqual({
- identityKey: 'user-1:global',
- mode: 'custom',
- hasCustomAsset: true,
- });
- expect(createGlobalProfileAssetRemoteState({identityKey: 'user-1:global', hasCustomAsset: false})).toEqual({
- identityKey: 'user-1:global',
- mode: 'unset',
- hasCustomAsset: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/user/components/settings_utils/SettingsMetadata.test.ts b/fluxer_app/src/features/user/components/settings_utils/SettingsMetadata.test.ts
deleted file mode 100644
index 27181e578..000000000
--- a/fluxer_app/src/features/user/components/settings_utils/SettingsMetadata.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isSettingsItemNew} from '@app/features/user/components/settings_utils/SettingsMetadata';
-import {describe, expect, it} from 'vitest';
-
-const NOW = new Date('2026-06-04T12:00:00.000Z');
-
-describe('SettingsMetadata new badges', () => {
- it('does not mark settings without an addedAt timestamp as new', () => {
- expect(isSettingsItemNew({}, NOW)).toBe(false);
- });
-
- it('marks settings added within the freshness window as new', () => {
- expect(isSettingsItemNew({addedAt: '2026-06-03T00:00:00.000Z'}, NOW)).toBe(true);
- });
-
- it('stops marking settings as new after 30 days', () => {
- expect(isSettingsItemNew({addedAt: '2026-05-01T00:00:00.000Z'}, NOW)).toBe(false);
- });
-
- it('does not mark settings as new for accounts created after the setting was added', () => {
- expect(isSettingsItemNew({addedAt: '2026-06-03T00:00:00.000Z'}, NOW, new Date('2026-06-04T00:00:00.000Z'))).toBe(
- false,
- );
- });
-
- it('does not mark future timestamps as new', () => {
- expect(isSettingsItemNew({addedAt: '2026-06-05T00:00:00.000Z'}, NOW)).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/user/constants/UserProfileSurfaceGeometry.test.ts b/fluxer_app/src/features/user/constants/UserProfileSurfaceGeometry.test.ts
deleted file mode 100644
index 8f8fb6474..000000000
--- a/fluxer_app/src/features/user/constants/UserProfileSurfaceGeometry.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- PROFILE_MODAL_BANNER_AVATAR_CUTOUT,
- PROFILE_MODAL_GEOMETRY,
- PROFILE_MODAL_GEOMETRY_STYLE,
- PROFILE_POPOUT_BANNER_AVATAR_CUTOUT,
- PROFILE_POPOUT_GEOMETRY,
- PROFILE_POPOUT_GEOMETRY_STYLE,
- PROFILE_POPOUT_OUTER_HEIGHT_PX,
- PROFILE_POPOUT_OUTER_WIDTH_PX,
-} from '@app/features/user/constants/UserProfileSurfaceGeometry';
-import {describe, expect, it} from 'vitest';
-
-function rem(value: string): number {
- const match = /^(-?\d+(?:\.\d+)?)rem$/.exec(value);
- if (!match) {
- throw new Error(`Expected rem length, got ${value}`);
- }
- return Number(match[1]) * 16;
-}
-
-describe('PROFILE_POPOUT_GEOMETRY', () => {
- it('derives the reserved outer width from content width plus both borders', () => {
- expect(PROFILE_POPOUT_OUTER_WIDTH_PX).toBe(
- PROFILE_POPOUT_GEOMETRY.contentWidthPx + PROFILE_POPOUT_GEOMETRY.borderWidthPx * 2,
- );
- });
-
- it('derives the reserved outer height from content height plus both borders', () => {
- expect(PROFILE_POPOUT_OUTER_HEIGHT_PX).toBe(
- PROFILE_POPOUT_GEOMETRY.contentHeightPx + PROFILE_POPOUT_GEOMETRY.borderWidthPx * 2,
- );
- });
-
- it('exports rem CSS variables that exactly represent the geometry constants', () => {
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-content-width'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.contentWidthPx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-content-height'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.contentHeightPx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-border-width'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.borderWidthPx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-avatar-size'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.avatarSizePx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-avatar-border'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.avatarBorderPx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-banner-height'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.bannerHeightPx,
- );
- expect(rem(PROFILE_POPOUT_GEOMETRY_STYLE['--profile-popout-header-height'])).toBeCloseTo(
- PROFILE_POPOUT_GEOMETRY.headerHeightPx,
- );
- });
-
- it('emits only rem lengths for both profile geometry surfaces', () => {
- for (const value of Object.values(PROFILE_POPOUT_GEOMETRY_STYLE)) {
- expect(value).toMatch(/^-?\d+(?:\.\d+)?rem$/);
- }
- for (const value of Object.values(PROFILE_MODAL_GEOMETRY_STYLE)) {
- expect(value).toMatch(/^-?\d+(?:\.\d+)?rem$/);
- }
- });
-
- it('represents the modal geometry constants as rem CSS variables', () => {
- expect(rem(PROFILE_MODAL_GEOMETRY_STYLE['--profile-modal-avatar-size'])).toBeCloseTo(
- PROFILE_MODAL_GEOMETRY.avatarSizePx,
- );
- expect(rem(PROFILE_MODAL_GEOMETRY_STYLE['--profile-modal-avatar-border'])).toBeCloseTo(
- PROFILE_MODAL_GEOMETRY.avatarBorderPx,
- );
- expect(rem(PROFILE_MODAL_GEOMETRY_STYLE['--profile-modal-avatar-left'])).toBeCloseTo(
- PROFILE_MODAL_GEOMETRY.avatarLeftPx,
- );
- expect(rem(PROFILE_MODAL_GEOMETRY_STYLE['--profile-modal-avatar-top'])).toBeCloseTo(
- PROFILE_MODAL_GEOMETRY.avatarTopPx,
- );
- });
-
- it('proves the skeleton loading shell reserves the declared content rectangle plus both borders', () => {
- const skeletonOuterWidth = PROFILE_POPOUT_GEOMETRY.contentWidthPx + PROFILE_POPOUT_GEOMETRY.borderWidthPx * 2;
- const skeletonOuterHeight = PROFILE_POPOUT_GEOMETRY.contentHeightPx + PROFILE_POPOUT_GEOMETRY.borderWidthPx * 2;
-
- expect(skeletonOuterWidth).toBe(PROFILE_POPOUT_OUTER_WIDTH_PX);
- expect(skeletonOuterHeight).toBe(PROFILE_POPOUT_OUTER_HEIGHT_PX);
- });
-
- it('uses avatar status gutter widths for profile banner avatar cutouts', () => {
- expect(PROFILE_POPOUT_GEOMETRY.avatarBorderPx).toBe(3.2);
- expect(PROFILE_MODAL_GEOMETRY.avatarBorderPx).toBe(4.8);
- expect(PROFILE_POPOUT_BANNER_AVATAR_CUTOUT.r).toBe(
- PROFILE_POPOUT_GEOMETRY.avatarSizePx / 2 + PROFILE_POPOUT_GEOMETRY.avatarBorderPx,
- );
- expect(PROFILE_MODAL_BANNER_AVATAR_CUTOUT.r).toBe(
- PROFILE_MODAL_GEOMETRY.avatarSizePx / 2 + PROFILE_MODAL_GEOMETRY.avatarBorderPx,
- );
- });
-});
diff --git a/fluxer_app/src/features/user/state/AdvancedSettings.test.ts b/fluxer_app/src/features/user/state/AdvancedSettings.test.ts
deleted file mode 100644
index 6ab735320..000000000
--- a/fluxer_app/src/features/user/state/AdvancedSettings.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import AppStorage from '@app/features/platform/state/PersistentStorage';
-import {describe, expect, it} from 'vitest';
-
-const KEEP_ATTACHMENTS_ON_EMPTY_MESSAGE_EDIT_STORAGE_KEY = 'AdvancedSettings:keepAttachmentsOnEmptyMessageEdit';
-
-AppStorage.setItem(KEEP_ATTACHMENTS_ON_EMPTY_MESSAGE_EDIT_STORAGE_KEY, JSON.stringify(true));
-
-const {default: AdvancedSettings} = await import('@app/features/user/state/AdvancedSettings');
-
-describe('Advanced settings', () => {
- it('rehydrates the stored attachment edit preference', () => {
- expect(AdvancedSettings.keepAttachmentsOnEmptyMessageEdit).toBe(true);
- });
-
- it('stores the attachment edit preference under its own key', () => {
- AdvancedSettings.setKeepAttachmentsOnEmptyMessageEdit(false);
- expect(AppStorage.getItem(KEEP_ATTACHMENTS_ON_EMPTY_MESSAGE_EDIT_STORAGE_KEY)).toBe('false');
- expect(AdvancedSettings.unreadBadgeCustomizationEnabled).toBe(false);
- expect(AppStorage.getItem('AdvancedSettings:unreadBadgeCustomizationEnabled')).toBeNull();
- });
-
- it('defaults the expression clone shortcuts preference to off and stores it under its own key', () => {
- expect(AdvancedSettings.expressionCloneShortcutsEnabled).toBe(false);
- AdvancedSettings.setExpressionCloneShortcutsEnabled(true);
- expect(AppStorage.getItem('AdvancedSettings:expressionCloneShortcutsEnabled')).toBe('true');
- });
-});
diff --git a/fluxer_app/src/features/user/state/SyncedFieldBudget.test.ts b/fluxer_app/src/features/user/state/SyncedFieldBudget.test.ts
deleted file mode 100644
index fd65992c0..000000000
--- a/fluxer_app/src/features/user/state/SyncedFieldBudget.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {decideOversizePush} from '@app/features/user/state/SyncedFieldBudget';
-import {describe, expect, it} from 'vitest';
-
-const MAX = 1000;
-
-describe('decideOversizePush', () => {
- it('accepts a payload inside the budget', () => {
- expect(decideOversizePush({encodedBytes: 999, maxEncodedBytes: MAX, lastPreparedBytes: null})).toBe(
- 'within-budget',
- );
- expect(decideOversizePush({encodedBytes: MAX, maxEncodedBytes: MAX, lastPreparedBytes: null})).toBe(
- 'within-budget',
- );
- });
-
- it('drops the first over-budget payload', () => {
- expect(decideOversizePush({encodedBytes: 1001, maxEncodedBytes: MAX, lastPreparedBytes: null})).toBe('drop');
- });
-
- it('drops an over-budget payload that grows', () => {
- expect(decideOversizePush({encodedBytes: 1200, maxEncodedBytes: MAX, lastPreparedBytes: 1100})).toBe('drop');
- });
-
- it('drops an over-budget payload that stays the same size', () => {
- expect(decideOversizePush({encodedBytes: 1100, maxEncodedBytes: MAX, lastPreparedBytes: 1100})).toBe('drop');
- });
-
- it('pushes an over-budget payload that shrinks so removals persist', () => {
- expect(decideOversizePush({encodedBytes: 1050, maxEncodedBytes: MAX, lastPreparedBytes: 1100})).toBe(
- 'push-shrinks',
- );
- });
-
- it('lets a run of removals drain back under the budget', () => {
- let last: number | null = null;
- const decisions: Array<string> = [];
- for (const bytes of [1300, 1200, 1100, 900]) {
- decisions.push(decideOversizePush({encodedBytes: bytes, maxEncodedBytes: MAX, lastPreparedBytes: last}));
- last = bytes;
- }
- expect(decisions).toEqual(['drop', 'push-shrinks', 'push-shrinks', 'within-budget']);
- });
-});
diff --git a/fluxer_app/src/features/user/state/SyncedFieldStateMachine.test.ts b/fluxer_app/src/features/user/state/SyncedFieldStateMachine.test.ts
deleted file mode 100644
index 50559fc4b..000000000
--- a/fluxer_app/src/features/user/state/SyncedFieldStateMachine.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createSyncedFieldMachineSnapshot,
- type SyncedFieldMachineEvent,
- type SyncedFieldMachineSnapshot,
- selectSyncedFieldMachineModel,
- transitionSyncedFieldMachineSnapshot,
-} from '@app/features/user/state/SyncedFieldStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const REMOTE_SNAPSHOT = Object.freeze({source: 'remote'});
-const LOCAL_CANDIDATE = Object.freeze({source: 'local'});
-
-function transition(snapshot: SyncedFieldMachineSnapshot, event: SyncedFieldMachineEvent): SyncedFieldMachineSnapshot {
- return transitionSyncedFieldMachineSnapshot(snapshot, event);
-}
-
-describe('SyncedFieldStateMachine', () => {
- it('starts active and idle without commands', () => {
- const model = selectSyncedFieldMachineModel(createSyncedFieldMachineSnapshot());
- expect(model.state).toBe('idle');
- expect(model.isActive).toBe(true);
- expect(model.command).toBeNull();
- expect(model.suppressPush).toBe(false);
- expect(model.failure).toBeNull();
- });
-
- it('skips missing or disabled remote snapshots', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.remoteObserved',
- enabled: true,
- snapshot: undefined,
- });
- expect(selectSyncedFieldMachineModel(snapshot).command).toBeNull();
-
- snapshot = transition(snapshot, {
- type: 'sync.remoteObserved',
- enabled: false,
- snapshot: REMOTE_SNAPSHOT,
- });
- const model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.command).toBeNull();
- });
-
- it('compares a remote snapshot before deciding whether to apply it', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.remoteObserved',
- enabled: true,
- snapshot: REMOTE_SNAPSHOT,
- });
-
- let model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('comparingRemote');
- expect(model.command).toEqual({type: 'compareRemote', snapshot: REMOTE_SNAPSHOT});
-
- snapshot = transition(snapshot, {type: 'sync.remoteMatched'});
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.command).toBeNull();
- });
-
- it('suppresses local pushes while a remote snapshot is being applied', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.remoteObserved',
- enabled: true,
- snapshot: REMOTE_SNAPSHOT,
- });
- snapshot = transition(snapshot, {type: 'sync.remoteNeedsApply'});
-
- let model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('applyingRemote');
- expect(model.suppressPush).toBe(true);
- expect(model.command).toEqual({type: 'applyRemote', snapshot: REMOTE_SNAPSHOT});
-
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: true,
- candidate: LOCAL_CANDIDATE,
- });
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('applyingRemote');
- expect(model.command).toEqual({type: 'applyRemote', snapshot: REMOTE_SNAPSHOT});
-
- snapshot = transition(snapshot, {type: 'sync.applyFinished'});
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.suppressPush).toBe(false);
- expect(model.command).toBeNull();
- });
-
- it('prepares and pushes a changed local candidate', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: true,
- candidate: LOCAL_CANDIDATE,
- });
-
- let model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('preparingPush');
- expect(model.command).toEqual({type: 'preparePush', candidate: LOCAL_CANDIDATE});
-
- snapshot = transition(snapshot, {type: 'sync.localReadyToPush'});
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('pushing');
- expect(model.command).toEqual({type: 'pushLocal', candidate: LOCAL_CANDIDATE});
-
- snapshot = transition(snapshot, {type: 'sync.commandHandled'});
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.command).toBeNull();
- });
-
- it('skips local candidates that are disabled, absent, or already synced', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: false,
- candidate: LOCAL_CANDIDATE,
- });
- expect(selectSyncedFieldMachineModel(snapshot).command).toBeNull();
-
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: true,
- candidate: null,
- });
- expect(selectSyncedFieldMachineModel(snapshot).command).toBeNull();
-
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: true,
- candidate: LOCAL_CANDIDATE,
- });
- snapshot = transition(snapshot, {type: 'sync.localAlreadySynced'});
-
- const model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.command).toBeNull();
- });
-
- it('suspends on terminal failures and ignores further sync events until reset', () => {
- let snapshot = createSyncedFieldMachineSnapshot();
- snapshot = transition(snapshot, {
- type: 'sync.failed',
- failure: {
- reason: 'payload-too-large',
- message: 'too large',
- },
- });
-
- let model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('suspended');
- expect(model.isActive).toBe(false);
- expect(model.failure?.reason).toBe('payload-too-large');
- expect(model.command).toBeNull();
-
- snapshot = transition(snapshot, {
- type: 'sync.localObserved',
- enabled: true,
- candidate: LOCAL_CANDIDATE,
- });
- expect(selectSyncedFieldMachineModel(snapshot).state).toBe('suspended');
- expect(selectSyncedFieldMachineModel(snapshot).command).toBeNull();
-
- snapshot = transition(snapshot, {type: 'sync.reset'});
- model = selectSyncedFieldMachineModel(snapshot);
- expect(model.state).toBe('idle');
- expect(model.isActive).toBe(true);
- expect(model.failure).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/user/state/UnreadInboxVisibility.test.ts b/fluxer_app/src/features/user/state/UnreadInboxVisibility.test.ts
deleted file mode 100644
index 11abc15ce..000000000
--- a/fluxer_app/src/features/user/state/UnreadInboxVisibility.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- resolveUnreadInboxVisibility,
- type UnreadInboxVisibilityInput,
-} from '@app/features/user/state/UnreadInboxVisibility';
-import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<UnreadInboxVisibilityInput> = {}): UnreadInboxVisibilityInput {
- return {
- unreadBadgesLevel: null,
- isMuted: false,
- hasUnread: true,
- hasMentions: false,
- ...overrides,
- };
-}
-
-describe('resolveUnreadInboxVisibility', () => {
- it('shows an unmuted channel with plain unread messages', () => {
- expect(resolveUnreadInboxVisibility(input())).toBe(true);
- });
-
- it('shows a channel in a large community, where notification level is forced to only-mentions', () => {
- expect(resolveUnreadInboxVisibility(input({unreadBadgesLevel: null, hasMentions: false}))).toBe(true);
- });
-
- it('hides a channel with nothing unread and no mentions', () => {
- expect(resolveUnreadInboxVisibility(input({hasUnread: false, hasMentions: false}))).toBe(false);
- });
-
- it('hides plain unread in a muted channel', () => {
- expect(resolveUnreadInboxVisibility(input({isMuted: true}))).toBe(false);
- });
-
- it('shows a muted channel when it has a mention', () => {
- expect(resolveUnreadInboxVisibility(input({isMuted: true, hasMentions: true}))).toBe(true);
- });
-
- it('hides a channel whose explicit unread badges level is nothing, even with a mention', () => {
- expect(
- resolveUnreadInboxVisibility(input({unreadBadgesLevel: MessageNotifications.NO_MESSAGES, hasMentions: true})),
- ).toBe(false);
- });
-
- it('hides plain unread when the explicit unread badges level is only-mentions', () => {
- expect(resolveUnreadInboxVisibility(input({unreadBadgesLevel: MessageNotifications.ONLY_MENTIONS}))).toBe(false);
- });
-
- it('shows a mention when the explicit unread badges level is only-mentions', () => {
- expect(
- resolveUnreadInboxVisibility(input({unreadBadgesLevel: MessageNotifications.ONLY_MENTIONS, hasMentions: true})),
- ).toBe(true);
- });
-
- it('shows plain unread when the explicit unread badges level is all messages', () => {
- expect(resolveUnreadInboxVisibility(input({unreadBadgesLevel: MessageNotifications.ALL_MESSAGES}))).toBe(true);
- });
-
- it('takes no notification-level input at all, so a forced community level cannot gate it', () => {
- const keys = Object.keys(input()).sort();
- expect(keys).toEqual(['hasMentions', 'hasUnread', 'isMuted', 'unreadBadgesLevel']);
- });
-});
diff --git a/fluxer_app/src/features/user/state/UserProfileCacheInvalidation.test.ts b/fluxer_app/src/features/user/state/UserProfileCacheInvalidation.test.ts
deleted file mode 100644
index d471d6743..000000000
--- a/fluxer_app/src/features/user/state/UserProfileCacheInvalidation.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {Profile} from '@app/features/user/models/Profile';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: null}}));
-
-const {default: UserProfile} = await import('@app/features/user/state/UserProfile');
-
-const GUILD_ID = '1000';
-const TARGET_ID = '2000';
-
-function cache(userId: string = TARGET_ID, guildId?: string): void {
- UserProfile.handleProfileCreate({
- userId,
- guildId: guildId ?? null,
- mutualGuilds: [{id: GUILD_ID, nick: null}],
- } as unknown as Profile);
-}
-
-describe('UserProfile cache invalidation', () => {
- afterEach(() => {
- UserProfile.handleGatewayReady();
- });
-
- it('drops every cached scope for a member removed from a community', () => {
- cache();
- cache(TARGET_ID, GUILD_ID);
- expect(UserProfile.getProfile(TARGET_ID)?.mutualGuilds).toHaveLength(1);
- UserProfile.handleGuildMemberRemove(TARGET_ID);
- expect(UserProfile.getProfile(TARGET_ID)).toBeNull();
- expect(UserProfile.getProfile(TARGET_ID, GUILD_ID)).toBeNull();
- });
-
- it('drops every cached scope for a member who joined a community', () => {
- cache();
- UserProfile.handleGuildMemberAdd(TARGET_ID);
- expect(UserProfile.getProfile(TARGET_ID)).toBeNull();
- });
-
- it('keeps other users cached when one member is removed', () => {
- cache();
- cache('3000');
- UserProfile.handleGuildMemberRemove(TARGET_ID);
- expect(UserProfile.getProfile(TARGET_ID)).toBeNull();
- expect(UserProfile.getProfile('3000')).not.toBeNull();
- });
-
- it('drops cached profiles when the viewer leaves a community', () => {
- cache();
- UserProfile.handleGuildDelete(false);
- expect(UserProfile.getProfile(TARGET_ID)).toBeNull();
- });
-
- it('keeps cached profiles when a community only goes unavailable', () => {
- cache();
- UserProfile.handleGuildDelete(true);
- expect(UserProfile.getProfile(TARGET_ID)).not.toBeNull();
- });
-
- it('drops cached profiles when the viewer joins a community', () => {
- cache();
- UserProfile.handleGuildCreate();
- expect(UserProfile.getProfile(TARGET_ID)).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/user/utils/FluxerTagDiscriminatorUtils.test.ts b/fluxer_app/src/features/user/utils/FluxerTagDiscriminatorUtils.test.ts
deleted file mode 100644
index d481a0b3c..000000000
--- a/fluxer_app/src/features/user/utils/FluxerTagDiscriminatorUtils.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isVisionaryDiscriminator0000Blocked} from '@app/features/user/utils/FluxerTagDiscriminatorUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('isVisionaryDiscriminator0000Blocked', () => {
- it('allows #0000 on self-hosted instances', () => {
- expect(
- isVisionaryDiscriminator0000Blocked({
- showPremium: false,
- isVisionary: false,
- discriminator: '0000',
- }),
- ).toBe(false);
- });
-
- it('blocks #0000 for non-visionary users on the main instance', () => {
- expect(
- isVisionaryDiscriminator0000Blocked({
- showPremium: true,
- isVisionary: false,
- discriminator: '0000',
- }),
- ).toBe(true);
- });
-
- it('allows #0000 for visionary users on the main instance', () => {
- expect(
- isVisionaryDiscriminator0000Blocked({
- showPremium: true,
- isVisionary: true,
- discriminator: '0000',
- }),
- ).toBe(false);
- });
-
- it('allows other discriminators on the main instance', () => {
- expect(
- isVisionaryDiscriminator0000Blocked({
- showPremium: true,
- isVisionary: false,
- discriminator: '1337',
- }),
- ).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/commands/VoiceSettingsCommands.test.ts b/fluxer_app/src/features/voice/commands/VoiceSettingsCommands.test.ts
deleted file mode 100644
index ab6f64b4f..000000000
--- a/fluxer_app/src/features/voice/commands/VoiceSettingsCommands.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const refreshMicrophoneFromSettings = vi.fn();
-const refreshCameraBackgroundFromSettings = vi.fn();
-const refreshCameraCaptureFromSettings = vi.fn();
-const refreshScreenShareCodecNegotiationFromSettings = vi.fn();
-
-const settings = {
- cameraResolution: 720,
- videoDeviceId: 'camera',
- screenshareResolution: 1080,
- videoFrameRate: 60,
- streamingMode: 'smooth',
- screenShareContentHint: 'auto',
- preferredScreenShareCodec: 'auto',
- screenShareAv1OptIn: true,
- screenShareHevcOptIn: false,
- screenShareEncoderMode: 'auto',
- screenShareSoftwareQuality: 'auto',
- screenShareScalabilityMode: 'auto',
- screenShareBackupCodecMode: 'auto',
- openH264Enabled: false,
-};
-
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: {
- room: null,
- refreshMicrophoneFromSettings,
- refreshCameraBackgroundFromSettings,
- refreshCameraCaptureFromSettings,
- refreshScreenShareCodecNegotiationFromSettings,
- setScreenShareAudioMuted: vi.fn(),
- applyAllLocalAudioPreferences: vi.fn(),
- applyLocalInputVolume: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/voice/engine/ScreenShareUnderperformance', () => ({
- noteDeliberateScreenShareQualityChange: vi.fn(),
-}));
-
-vi.mock('@app/features/voice/utils/VoiceProcessingProfile', () => ({
- getActiveInputDeviceLabel: () => null,
-}));
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- updateSettings: (patch: Record<string, unknown>) => Object.assign(settings, patch),
- get cameraResolution() {
- return settings.cameraResolution;
- },
- get videoDeviceId() {
- return settings.videoDeviceId;
- },
- getScreenshareResolution: () => settings.screenshareResolution,
- getVideoFrameRate: () => settings.videoFrameRate,
- getStreamingMode: () => settings.streamingMode,
- getScreenShareContentHint: () => settings.screenShareContentHint,
- getPreferredScreenShareCodec: () => settings.preferredScreenShareCodec,
- getScreenShareAv1OptIn: () => settings.screenShareAv1OptIn,
- getScreenShareHevcOptIn: () => settings.screenShareHevcOptIn,
- getScreenShareEncoderMode: () => settings.screenShareEncoderMode,
- getScreenShareSoftwareQuality: () => settings.screenShareSoftwareQuality,
- getScreenShareScalabilityMode: () => settings.screenShareScalabilityMode,
- getScreenShareBackupCodecMode: () => settings.screenShareBackupCodecMode,
- getOpenH264Enabled: () => settings.openH264Enabled,
- },
-}));
-
-const VoiceSettingsCommands = await import('@app/features/voice/commands/VoiceSettingsCommands');
-
-describe('screen-share codec settings reactions', () => {
- beforeEach(() => {
- settings.screenShareAv1OptIn = true;
- settings.screenShareHevcOptIn = false;
- settings.preferredScreenShareCodec = 'auto';
- refreshScreenShareCodecNegotiationFromSettings.mockClear();
- });
-
- it('renegotiates the live screen share when the AV1 opt-in is turned off', () => {
- VoiceSettingsCommands.update({screenShareAv1OptIn: false});
- expect(refreshScreenShareCodecNegotiationFromSettings).toHaveBeenCalledTimes(1);
- });
-
- it('renegotiates the live screen share when the HEVC opt-in changes', () => {
- VoiceSettingsCommands.update({screenShareHevcOptIn: true});
- expect(refreshScreenShareCodecNegotiationFromSettings).toHaveBeenCalledTimes(1);
- });
-
- it('renegotiates the live screen share when the preferred codec changes', () => {
- VoiceSettingsCommands.update({preferredScreenShareCodec: 'vp9'});
- expect(refreshScreenShareCodecNegotiationFromSettings).toHaveBeenCalledTimes(1);
- });
-
- it('leaves the negotiation alone for unrelated screen share settings', () => {
- VoiceSettingsCommands.update({videoFrameRate: 30});
- expect(refreshScreenShareCodecNegotiationFromSettings).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/voice/components/CallVolumeState.test.ts b/fluxer_app/src/features/voice/components/CallVolumeState.test.ts
deleted file mode 100644
index d5206bde1..000000000
--- a/fluxer_app/src/features/voice/components/CallVolumeState.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- CALL_VOLUME_DEFAULT_PERCENT,
- callVolumePercentToSliderVolume,
- resolveCallVolumeMuteToggle,
- resolveLastNonZeroCallVolume,
- sliderVolumeToCallVolumePercent,
-} from '@app/features/voice/components/CallVolumeState';
-import {describe, expect, it} from 'vitest';
-
-describe('callVolumePercentToSliderVolume', () => {
- it('maps percent to the slider scale', () => {
- expect(callVolumePercentToSliderVolume(0)).toBe(0);
- expect(callVolumePercentToSliderVolume(50)).toBe(0.5);
- expect(callVolumePercentToSliderVolume(100)).toBe(1);
- });
-
- it('falls back to the default for non-finite input', () => {
- expect(callVolumePercentToSliderVolume(Number.NaN)).toBe(1);
- });
-
- it('clamps negative percent to zero', () => {
- expect(callVolumePercentToSliderVolume(-10)).toBe(0);
- });
-
- it('reaches the boosted ceiling and clamps past it', () => {
- expect(callVolumePercentToSliderVolume(200)).toBe(2);
- expect(callVolumePercentToSliderVolume(250)).toBe(2);
- });
-});
-
-describe('sliderVolumeToCallVolumePercent', () => {
- it('maps slider values to whole percent', () => {
- expect(sliderVolumeToCallVolumePercent(0)).toBe(0);
- expect(sliderVolumeToCallVolumePercent(0.337)).toBe(34);
- expect(sliderVolumeToCallVolumePercent(1)).toBe(100);
- });
-
- it('clamps out-of-range slider values', () => {
- expect(sliderVolumeToCallVolumePercent(-0.5)).toBe(0);
- expect(sliderVolumeToCallVolumePercent(2.5)).toBe(200);
- });
-
- it('maps the boosted range above unity', () => {
- expect(sliderVolumeToCallVolumePercent(1.5)).toBe(150);
- expect(sliderVolumeToCallVolumePercent(2)).toBe(200);
- });
-
- it('falls back to the default for non-finite input', () => {
- expect(sliderVolumeToCallVolumePercent(Number.POSITIVE_INFINITY)).toBe(100);
- expect(sliderVolumeToCallVolumePercent(Number.NaN)).toBe(CALL_VOLUME_DEFAULT_PERCENT);
- });
-});
-
-describe('resolveLastNonZeroCallVolume', () => {
- it('tracks the latest non-zero volume', () => {
- expect(resolveLastNonZeroCallVolume(60, 30)).toBe(60);
- });
-
- it('keeps the previous value while muted', () => {
- expect(resolveLastNonZeroCallVolume(0, 30)).toBe(30);
- });
-
- it('falls back to the default when nothing was remembered', () => {
- expect(resolveLastNonZeroCallVolume(0, 0)).toBe(CALL_VOLUME_DEFAULT_PERCENT);
- });
-});
-
-describe('resolveCallVolumeMuteToggle', () => {
- it('mutes when the volume is above zero', () => {
- expect(resolveCallVolumeMuteToggle(75, 75)).toBe(0);
- });
-
- it('restores the remembered volume when muted', () => {
- expect(resolveCallVolumeMuteToggle(0, 40)).toBe(40);
- });
-
- it('restores the default when no volume was remembered', () => {
- expect(resolveCallVolumeMuteToggle(0, 0)).toBe(CALL_VOLUME_DEFAULT_PERCENT);
- });
-});
-
-describe('call volume round trip', () => {
- it('preserves a stored boosted volume through the slider', () => {
- expect(sliderVolumeToCallVolumePercent(callVolumePercentToSliderVolume(200))).toBe(200);
- });
-
- it('steps a boosted volume down by one keyboard step instead of collapsing to unity', () => {
- expect(sliderVolumeToCallVolumePercent(Math.max(0, callVolumePercentToSliderVolume(200) - 0.1))).toBe(190);
- });
-
- it('restores a boosted volume after a mute toggle', () => {
- expect(resolveCallVolumeMuteToggle(200, 200)).toBe(0);
- expect(resolveCallVolumeMuteToggle(0, resolveLastNonZeroCallVolume(0, 200))).toBe(200);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/IncomingCallManagerStateMachine.test.ts b/fluxer_app/src/features/voice/components/IncomingCallManagerStateMachine.test.ts
deleted file mode 100644
index 6776d4b69..000000000
--- a/fluxer_app/src/features/voice/components/IncomingCallManagerStateMachine.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createIncomingCallManagerSnapshot,
- type IncomingCallManagerSignals,
- resolveIncomingCallQueue,
- resolveIncomingRingCommand,
- selectIncomingCallManagerModel,
- shouldPlayIncomingRing,
- transitionIncomingCallManagerSnapshot,
-} from '@app/features/voice/components/IncomingCallManagerStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<IncomingCallManagerSignals> = {}): IncomingCallManagerSignals {
- return {
- incomingCallIds: [],
- hasRingingCalls: false,
- isVoiceConnected: false,
- isVoiceConnecting: false,
- ...overrides,
- };
-}
-
-describe('IncomingCallManagerStateMachine', () => {
- it('retains active queued calls before appending new incoming calls', () => {
- expect(resolveIncomingCallQueue(['b', 'a'], ['a', 'b', 'c'])).toEqual(['b', 'a', 'c']);
- });
-
- it('drops ended calls from the queue', () => {
- expect(resolveIncomingCallQueue(['a', 'b', 'c'], ['c'])).toEqual(['c']);
- });
-
- it('selects the first retained queued call as active', () => {
- let snapshot = createIncomingCallManagerSnapshot();
- snapshot = transitionIncomingCallManagerSnapshot(snapshot, {
- type: 'incomingCalls.update',
- signals: signals({incomingCallIds: ['a', 'b'], hasRingingCalls: true}),
- });
- snapshot = transitionIncomingCallManagerSnapshot(snapshot, {
- type: 'incomingCalls.update',
- signals: signals({incomingCallIds: ['b', 'c'], hasRingingCalls: true}),
- });
-
- expect(selectIncomingCallManagerModel(snapshot)).toMatchObject({
- callQueue: ['b', 'c'],
- activeCallId: 'b',
- shouldPlayIncomingRing: true,
- });
- });
-
- it('rings only while there are ringing calls and voice is not joining or connected', () => {
- expect(shouldPlayIncomingRing(signals({hasRingingCalls: true}))).toBe(true);
- expect(shouldPlayIncomingRing(signals({hasRingingCalls: true, isVoiceConnected: true}))).toBe(false);
- expect(shouldPlayIncomingRing(signals({hasRingingCalls: true, isVoiceConnecting: true}))).toBe(false);
- expect(shouldPlayIncomingRing(signals({hasRingingCalls: false}))).toBe(false);
- });
-
- it('starts the ring whenever ringing is wanted, enabled, and not already active', () => {
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: true, ringSoundEnabled: true, ringActive: false})).toBe(
- 'start',
- );
- });
-
- it('restarts the ring when the ring sound is re-enabled mid-call', () => {
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: true, ringSoundEnabled: false, ringActive: false})).toBe(
- 'none',
- );
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: true, ringSoundEnabled: true, ringActive: false})).toBe(
- 'start',
- );
- });
-
- it('does not restart a ring that is already active', () => {
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: true, ringSoundEnabled: true, ringActive: true})).toBe(
- 'none',
- );
- });
-
- it('stops the ring when ringing is no longer wanted', () => {
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: false, ringSoundEnabled: true, ringActive: true})).toBe(
- 'stop',
- );
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: false, ringSoundEnabled: false, ringActive: true})).toBe(
- 'stop',
- );
- });
-
- it('does nothing while idle without ringing calls', () => {
- expect(resolveIncomingRingCommand({shouldPlayIncomingRing: false, ringSoundEnabled: true, ringActive: false})).toBe(
- 'none',
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/components/MediaDeviceStartupPreloadManager.test.tsx b/fluxer_app/src/features/voice/components/MediaDeviceStartupPreloadManager.test.tsx
deleted file mode 100644
index 927e9a8c6..000000000
--- a/fluxer_app/src/features/voice/components/MediaDeviceStartupPreloadManager.test.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {act, createElement} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-const preload = vi.hoisted(() => ({
- start: vi.fn(),
- stop: vi.fn(),
-}));
-
-vi.mock('@app/features/voice/utils/MediaDeviceStartupPreload', () => ({
- startMediaDeviceStartupPreload: () => {
- preload.start();
- return preload.stop;
- },
-}));
-
-const {MediaDeviceStartupPreloadManager} = await import(
- '@app/features/voice/components/MediaDeviceStartupPreloadManager'
-);
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-let root: Root;
-
-beforeEach(() => {
- vi.clearAllMocks();
- document.body.replaceChildren();
- const host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
-});
-
-describe('MediaDeviceStartupPreloadManager', () => {
- test('starts the preload once loaded and stops it on unmount', async () => {
- act(() => {
- root.render(createElement(MediaDeviceStartupPreloadManager));
- });
- await vi.waitFor(() => expect(preload.start).toHaveBeenCalledTimes(1));
- expect(preload.stop).not.toHaveBeenCalled();
- act(() => {
- root.unmount();
- });
- expect(preload.stop).toHaveBeenCalledTimes(1);
- });
-
- test('never starts the preload when unmounted before it finishes loading', async () => {
- act(() => {
- root.render(createElement(MediaDeviceStartupPreloadManager));
- });
- act(() => {
- root.unmount();
- });
- await import('@app/features/voice/utils/MediaDeviceStartupPreload');
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(preload.start).not.toHaveBeenCalled();
- expect(preload.stop).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/voice/components/StreamSettingsMenuContentStateMachine.test.ts b/fluxer_app/src/features/voice/components/StreamSettingsMenuContentStateMachine.test.ts
deleted file mode 100644
index ca4ff7bcb..000000000
--- a/fluxer_app/src/features/voice/components/StreamSettingsMenuContentStateMachine.test.ts
+++ /dev/null
@@ -1,405 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type StreamSettingsAudioControlSignals,
- selectStreamSettingsAudioControlState,
- selectStreamSettingsAudioMenuState,
-} from '@app/features/voice/components/StreamSettingsMenuContentStateMachine';
-import type {NativeAudioAvailability} from '@app/types/electron.d';
-import {describe, expect, it} from 'vitest';
-
-function availableNativeAudio(overrides: Partial<NativeAudioAvailability> = {}): NativeAudioAvailability {
- return {
- available: true,
- capabilities: {
- process: true,
- system: true,
- },
- ...overrides,
- };
-}
-
-function signals(overrides: Partial<StreamSettingsAudioControlSignals> = {}): StreamSettingsAudioControlSignals {
- return {
- applyToLiveStream: true,
- shareContext: 'display',
- displayShareEnvironment: 'desktop-custom',
- supportsStreamAudio: true,
- captureAudioEnabled: false,
- hasLiveScreenShareAudioPublication: false,
- nativeAudioAvailability: null,
- platform: null,
- ...overrides,
- };
-}
-
-describe('StreamSettingsMenuContentStateMachine', () => {
- it('hides the audio control when stream audio capture is unavailable', () => {
- const state = selectStreamSettingsAudioMenuState(
- signals({
- supportsStreamAudio: false,
- }),
- );
-
- expect(state.control).toMatchObject({
- value: 'hidden',
- labelKey: 'captureDesktopAudio',
- });
- expect(state.showManualAudioSources).toBe(false);
- });
-
- it('models native audio support blocks before other display audio states', () => {
- const appState = selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'app',
- platform: 'win32',
- nativeAudioAvailability: availableNativeAudio({
- capabilities: {
- process: false,
- system: true,
- },
- }),
- }),
- );
- expect(appState.control).toMatchObject({
- value: 'unsupported',
- labelKey: 'captureAppAudio',
- });
-
- const displayState = selectStreamSettingsAudioMenuState(
- signals({
- displayShareEnvironment: 'web',
- platform: 'darwin',
- nativeAudioAvailability: availableNativeAudio({
- available: false,
- reason: 'os-version-too-old',
- }),
- }),
- );
- expect(displayState.control.value).toBe('unsupported');
- });
-
- it('disables prestart web desktop audio because the browser picker owns selection', () => {
- const state = selectStreamSettingsAudioMenuState(
- signals({
- applyToLiveStream: false,
- displayShareEnvironment: 'web',
- }),
- );
-
- expect(state.control).toMatchObject({
- value: 'prestartNativePickerOwned',
- labelKey: 'captureDesktopAudio',
- });
- });
-
- it('requires restart only when a live custom display share cannot add audio separately', () => {
- expect(selectStreamSettingsAudioControlState(signals({displayShareEnvironment: 'desktop-custom'}))).toBe(
- 'restartRequired',
- );
- expect(
- selectStreamSettingsAudioControlState(
- signals({
- displayShareEnvironment: 'desktop-custom',
- platform: 'darwin',
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ),
- ).toBe('toggle');
- expect(
- selectStreamSettingsAudioControlState(
- signals({
- displayShareEnvironment: 'desktop-custom',
- platform: 'linux',
- }),
- ),
- ).toBe('toggle');
- expect(
- selectStreamSettingsAudioControlState(
- signals({
- displayShareEnvironment: 'desktop-custom',
- hasLiveScreenShareAudioPublication: true,
- }),
- ),
- ).toBe('toggle');
- expect(
- selectStreamSettingsAudioControlState(
- signals({
- displayShareEnvironment: 'desktop-custom',
- captureAudioEnabled: true,
- }),
- ),
- ).toBe('toggle');
- expect(selectStreamSettingsAudioControlState(signals({displayShareEnvironment: 'web'}))).toBe('toggle');
- });
-
- it('offers manual audio sources on every desktop share type, window shares included', () => {
- for (const shareContext of ['app', 'device', 'display'] as const) {
- for (const displayShareEnvironment of ['desktop-custom', 'desktop-wayland'] as const) {
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- shareContext,
- displayShareEnvironment,
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(true);
- }
- }
- });
-
- it('leaves audio source selection to the browser picker on the web', () => {
- for (const shareContext of ['app', 'device', 'display'] as const) {
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- shareContext,
- displayShareEnvironment: 'web',
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- }
- });
-
- it('keeps manual audio sources off the platforms that cannot express a selection', () => {
- for (const platform of ['win32', 'darwin', 'freebsd']) {
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform,
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- }
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform: null,
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio({available: false, reason: 'no-pipewire'}),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: null,
- }),
- ).showManualAudioSources,
- ).toBe(false);
- });
-
- it('ties manual audio sources to the capture audio toggle and to stream audio support', () => {
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform: 'linux',
- captureAudioEnabled: false,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- platform: 'linux',
- supportsStreamAudio: false,
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- }),
- ).showManualAudioSources,
- ).toBe(false);
- });
-
- it('names the real scope on a window share instead of always saying app audio', () => {
- const common = {
- shareContext: 'app',
- displayShareEnvironment: 'desktop-custom',
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- } as const;
-
- expect(selectStreamSettingsAudioMenuState(signals(common)).control.labelKey).toBe('captureAppAudio');
- expect(selectStreamSettingsAudioMenuState(signals({...common, windowAudioScope: 'window'})).control.labelKey).toBe(
- 'captureAppAudio',
- );
- expect(selectStreamSettingsAudioMenuState(signals({...common, windowAudioScope: 'system'})).control.labelKey).toBe(
- 'captureSystemAudio',
- );
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- ...common,
- windowAudioScope: 'system',
- audioSourceMode: 'specific',
- selectedAudioSourceCount: 2,
- }),
- ).control.labelKey,
- ).toBe('captureAppAudio');
- expect(
- selectStreamSettingsAudioMenuState(signals({...common, windowAudioScope: 'system', audioSourceMode: 'none'}))
- .control.labelKey,
- ).toBe('captureAppAudio');
- });
-
- it('keeps saying app audio on a window share whose stored display selection it does not follow', () => {
- const common = {
- shareContext: 'app',
- displayShareEnvironment: 'desktop-custom',
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- windowAudioScope: 'window',
- } as const;
-
- for (const audioSourceMode of ['none', 'system', 'specific'] as const) {
- expect(
- selectStreamSettingsAudioMenuState(signals({...common, audioSourceMode, selectedAudioSourceCount: 2})).control
- .labelKey,
- ).toBe('captureAppAudio');
- }
- });
-
- it('never widens a Wayland window share label, because its window cannot be isolated', () => {
- expect(
- selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'app',
- displayShareEnvironment: 'desktop-wayland',
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- windowAudioScope: 'window',
- }),
- ).control.labelKey,
- ).toBe('captureSystemAudio');
- });
-
- it('keeps the audio device menu on a device share whether or not sources are routed', () => {
- const routed = selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'device',
- platform: 'linux',
- captureAudioEnabled: true,
- nativeAudioAvailability: availableNativeAudio(),
- audioSourceMode: 'specific',
- selectedAudioSourceCount: 2,
- }),
- );
- expect(routed.showManualAudioSources).toBe(true);
- expect(routed.showDeviceAudioMenu).toBe(true);
- });
-
- it('pins the audio menu shape for every share type on every platform', () => {
- const platforms = [
- {platform: 'linux', nativeAudioAvailability: availableNativeAudio(), manualCapable: true},
- {platform: 'win32', nativeAudioAvailability: availableNativeAudio(), manualCapable: false},
- {platform: 'darwin', nativeAudioAvailability: availableNativeAudio(), manualCapable: false},
- {platform: null, nativeAudioAvailability: null, manualCapable: false},
- ] as const;
- const expectedLabelKey = {
- app: 'captureAppAudio',
- device: 'captureDeviceAudio',
- display: 'captureDesktopAudio',
- } as const;
-
- for (const {platform, nativeAudioAvailability, manualCapable} of platforms) {
- for (const shareContext of ['app', 'device', 'display'] as const) {
- const state = selectStreamSettingsAudioMenuState(
- signals({
- shareContext,
- platform,
- nativeAudioAvailability,
- captureAudioEnabled: true,
- }),
- );
-
- expect(state.control).toMatchObject({
- value: 'toggle',
- checked: true,
- labelKey: expectedLabelKey[shareContext],
- });
- expect(state.showManualAudioSources).toBe(manualCapable);
- expect(state.showDeviceAudioMenu).toBe(shareContext === 'device');
- }
- }
- });
-
- it('resolves the same audio group whether the menu is pre-start or attached to a live stream', () => {
- for (const shareContext of ['app', 'device', 'display'] as const) {
- for (const windowAudioScope of ['window', 'system'] as const) {
- const common = {
- shareContext,
- platform: 'linux',
- nativeAudioAvailability: availableNativeAudio(),
- captureAudioEnabled: true,
- windowAudioScope,
- };
- const prestart = selectStreamSettingsAudioMenuState(signals({...common, applyToLiveStream: false}));
- const live = selectStreamSettingsAudioMenuState(signals({...common, applyToLiveStream: true}));
-
- expect(live.showManualAudioSources).toBe(prestart.showManualAudioSources);
- expect(live.showDeviceAudioMenu).toBe(prestart.showDeviceAudioMenu);
- expect(live.control.labelKey).toBe(prestart.control.labelKey);
- }
- }
- });
-
- it('keeps device audio menu visibility tied to the device share audio setting', () => {
- const disabledCapture = selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'device',
- captureAudioEnabled: false,
- }),
- );
- expect(disabledCapture.control).toMatchObject({
- value: 'toggle',
- labelKey: 'captureDeviceAudio',
- checked: false,
- });
- expect(disabledCapture.showDeviceAudioMenu).toBe(false);
-
- const enabledCapture = selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'device',
- captureAudioEnabled: true,
- }),
- );
- expect(enabledCapture.control).toMatchObject({
- value: 'toggle',
- labelKey: 'captureDeviceAudio',
- checked: true,
- });
- expect(enabledCapture.showDeviceAudioMenu).toBe(true);
-
- const unsupportedDeviceCapture = selectStreamSettingsAudioMenuState(
- signals({
- shareContext: 'device',
- supportsStreamAudio: false,
- captureAudioEnabled: true,
- }),
- );
- expect(unsupportedDeviceCapture.control.value).toBe('hidden');
- expect(unsupportedDeviceCapture.showDeviceAudioMenu).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VideoElementFrameState.test.ts b/fluxer_app/src/features/voice/components/VideoElementFrameState.test.ts
deleted file mode 100644
index 44cb5c7b3..000000000
--- a/fluxer_app/src/features/voice/components/VideoElementFrameState.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearVideoFrameWatchersForTests,
- getActiveVideoFrameWatcherCountForTests,
- watchVideoElementRenderedFrame,
-} from '@app/features/voice/components/VideoElementFrameState';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const POLL_TICK_MS = 125;
-
-interface FakeVideoOptions {
- supportsFrameCallback: boolean;
- readyState?: number;
- videoWidth?: number;
- videoHeight?: number;
-}
-
-interface FakeVideo {
- element: HTMLVideoElement;
- presentFrame: () => void;
- cancelledFrameCallbacks: Array<number>;
- listenerCount: () => number;
-}
-
-function createFakeVideo(options: FakeVideoOptions): FakeVideo {
- const listeners = new Map<string, Set<() => void>>();
- const frameCallbacks = new Map<number, () => void>();
- const cancelledFrameCallbacks: Array<number> = [];
- let nextFrameCallbackHandle = 1;
-
- const element: Record<string, unknown> = {
- readyState: options.readyState ?? 0,
- videoWidth: options.videoWidth ?? 0,
- videoHeight: options.videoHeight ?? 0,
- addEventListener: (type: string, listener: () => void): void => {
- const existing = listeners.get(type);
- if (existing) {
- existing.add(listener);
- return;
- }
- listeners.set(type, new Set([listener]));
- },
- removeEventListener: (type: string, listener: () => void): void => {
- listeners.get(type)?.delete(listener);
- },
- };
-
- if (options.supportsFrameCallback) {
- element.requestVideoFrameCallback = (callback: () => void): number => {
- const handle = nextFrameCallbackHandle;
- nextFrameCallbackHandle += 1;
- frameCallbacks.set(handle, callback);
- return handle;
- };
- element.cancelVideoFrameCallback = (handle: number): void => {
- cancelledFrameCallbacks.push(handle);
- frameCallbacks.delete(handle);
- };
- }
-
- return {
- element: element as unknown as HTMLVideoElement,
- presentFrame: (): void => {
- for (const [handle, callback] of frameCallbacks) {
- frameCallbacks.delete(handle);
- callback();
- }
- },
- cancelledFrameCallbacks,
- listenerCount: (): number => {
- let total = 0;
- for (const registered of listeners.values()) {
- total += registered.size;
- }
- return total;
- },
- };
-}
-
-describe('watchVideoElementRenderedFrame', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.stubGlobal('window', globalThis);
- clearVideoFrameWatchersForTests();
- });
-
- afterEach(() => {
- clearVideoFrameWatchersForTests();
- vi.unstubAllGlobals();
- vi.useRealTimers();
- });
-
- it('reports a frame from the element the ref switches to after watching starts', () => {
- const initial = createFakeVideo({supportsFrameCallback: true});
- const videoRef: {current: HTMLVideoElement | null} = {current: initial.element};
- const onFrame = vi.fn();
-
- const dispose = watchVideoElementRenderedFrame({videoRef, onFrame});
- videoRef.current = createFakeVideo({
- supportsFrameCallback: true,
- readyState: 2,
- videoWidth: 1280,
- videoHeight: 720,
- }).element;
-
- vi.advanceTimersByTime(POLL_TICK_MS);
-
- expect(onFrame).toHaveBeenCalledTimes(1);
- expect(getActiveVideoFrameWatcherCountForTests()).toBe(0);
-
- vi.advanceTimersByTime(POLL_TICK_MS * 4);
-
- expect(onFrame).toHaveBeenCalledTimes(1);
- dispose();
- });
-
- it('reports one frame and drops the poll target when the frame callback fires first', () => {
- const video = createFakeVideo({supportsFrameCallback: true});
- const videoRef: {current: HTMLVideoElement | null} = {current: video.element};
- const onFrame = vi.fn();
-
- const dispose = watchVideoElementRenderedFrame({videoRef, onFrame});
-
- expect(getActiveVideoFrameWatcherCountForTests()).toBe(1);
-
- video.presentFrame();
-
- expect(onFrame).toHaveBeenCalledTimes(1);
- expect(getActiveVideoFrameWatcherCountForTests()).toBe(0);
- expect(video.listenerCount()).toBe(0);
- expect(vi.getTimerCount()).toBe(0);
-
- vi.advanceTimersByTime(POLL_TICK_MS * 4);
-
- expect(onFrame).toHaveBeenCalledTimes(1);
- dispose();
- });
-
- it('reports nothing and leaves no interval running when disposed before any frame', () => {
- const video = createFakeVideo({supportsFrameCallback: true});
- const videoRef: {current: HTMLVideoElement | null} = {current: video.element};
- const onFrame = vi.fn();
-
- const dispose = watchVideoElementRenderedFrame({videoRef, onFrame});
- dispose();
-
- videoRef.current = createFakeVideo({
- supportsFrameCallback: false,
- readyState: 2,
- videoWidth: 1280,
- videoHeight: 720,
- }).element;
- vi.advanceTimersByTime(POLL_TICK_MS * 4);
-
- expect(onFrame).not.toHaveBeenCalled();
- expect(getActiveVideoFrameWatcherCountForTests()).toBe(0);
- expect(vi.getTimerCount()).toBe(0);
- expect(video.cancelledFrameCallbacks).toHaveLength(1);
- expect(video.listenerCount()).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.test.ts b/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.test.ts
deleted file mode 100644
index 82cdd1e33..000000000
--- a/fluxer_app/src/features/voice/components/VoiceCallLayoutPresentationStateMachine.test.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceCallLayoutPresentationSnapshot,
- getVoiceCallLayoutPresentationStateValue,
- resolveVoiceCallLayoutPresentationModel,
- selectVoiceCallLayoutPresentationModel,
- transitionVoiceCallLayoutPresentationSnapshot,
- type VoiceCallLayoutPresentationInput,
- type VoiceCallLayoutPresentationMachineSnapshot,
-} from '@app/features/voice/components/VoiceCallLayoutPresentationStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function input(overrides: Partial<VoiceCallLayoutPresentationInput> = {}): VoiceCallLayoutPresentationInput {
- return {
- layoutMode: 'focus',
- hasFocusMainTrack: true,
- secondaryFocusTrackCount: 1,
- compact: true,
- isVoiceCallAppFullscreen: true,
- membersRowVisible: false,
- hasScreenShare: false,
- ...overrides,
- };
-}
-
-function toggle(snapshot: VoiceCallLayoutPresentationMachineSnapshot): VoiceCallLayoutPresentationMachineSnapshot {
- return transitionVoiceCallLayoutPresentationSnapshot(snapshot, {type: 'participants.toggle'});
-}
-
-function update(
- snapshot: VoiceCallLayoutPresentationMachineSnapshot,
- nextInput: VoiceCallLayoutPresentationInput,
-): VoiceCallLayoutPresentationMachineSnapshot {
- return transitionVoiceCallLayoutPresentationSnapshot(snapshot, {type: 'presentation.update', input: nextInput});
-}
-
-describe('VoiceCallLayoutPresentationStateMachine', () => {
- it('models the compact fullscreen participant grid as collapsed until toggled open', () => {
- let snapshot = createVoiceCallLayoutPresentationSnapshot(input());
- expect(getVoiceCallLayoutPresentationStateValue(snapshot)).toBe('focusLayout');
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- canShowParticipantsGridPanel: true,
- participantsGridExpanded: false,
- isParticipantsExpanded: false,
- focusScrollerOverflow: 'hidden',
- });
-
- snapshot = toggle(snapshot);
- expect(getVoiceCallLayoutPresentationStateValue(snapshot)).toBe('focusParticipantsExpanded');
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- canShowParticipantsGridPanel: true,
- participantsGridExpanded: true,
- isParticipantsExpanded: true,
- showMembersRow: false,
- showMembersToggle: false,
- focusScrollerOverflow: 'auto',
- });
- });
-
- it('collapses expanded participants when the panel loses capability', () => {
- let snapshot = toggle(createVoiceCallLayoutPresentationSnapshot(input()));
- expect(selectVoiceCallLayoutPresentationModel(snapshot).isParticipantsExpanded).toBe(true);
-
- snapshot = update(snapshot, input({secondaryFocusTrackCount: 0}));
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- stateValue: 'focusLayout',
- canShowParticipantsGridPanel: false,
- participantsGridExpanded: false,
- isParticipantsExpanded: false,
- });
-
- snapshot = update(snapshot, input());
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- canShowParticipantsGridPanel: true,
- participantsGridExpanded: false,
- isParticipantsExpanded: false,
- });
- });
-
- it('preserves participant expansion while grid layout is selected without losing panel capability', () => {
- let snapshot = toggle(createVoiceCallLayoutPresentationSnapshot(input()));
- snapshot = update(snapshot, input({layoutMode: 'grid'}));
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- stateValue: 'gridLayout',
- mainLayout: 'grid',
- canShowParticipantsGridPanel: true,
- participantsGridExpanded: true,
- isParticipantsExpanded: false,
- });
-
- snapshot = update(snapshot, input({layoutMode: 'focus'}));
- expect(selectVoiceCallLayoutPresentationModel(snapshot)).toMatchObject({
- stateValue: 'focusParticipantsExpanded',
- mainLayout: 'focus',
- participantsGridExpanded: true,
- isParticipantsExpanded: true,
- });
- });
-
- it('selects the desktop fullscreen members row and toggle from secondary-track state', () => {
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- compact: false,
- membersRowVisible: true,
- }),
- ),
- ).toMatchObject({
- isFullscreenFocusLayout: true,
- hasSecondaryFocusTracks: true,
- canShowParticipantsGridPanel: false,
- showMembersRow: true,
- showMembersToggle: true,
- });
-
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- compact: false,
- membersRowVisible: false,
- }),
- ),
- ).toMatchObject({
- showMembersRow: false,
- showMembersToggle: true,
- });
- });
-
- it('falls back to the grid when focus has no main track and secondary tracks cannot render', () => {
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- hasFocusMainTrack: false,
- secondaryFocusTrackCount: 2,
- compact: false,
- isVoiceCallAppFullscreen: false,
- }),
- ),
- ).toMatchObject({
- stateValue: 'focusFallbackGrid',
- shouldRenderFocusFallbackGrid: true,
- });
-
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- hasFocusMainTrack: false,
- secondaryFocusTrackCount: 2,
- compact: true,
- isVoiceCallAppFullscreen: false,
- }),
- ),
- ).toMatchObject({
- stateValue: 'focusFallbackGrid',
- shouldRenderFocusFallbackGrid: true,
- });
-
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- hasFocusMainTrack: false,
- secondaryFocusTrackCount: 2,
- compact: false,
- isVoiceCallAppFullscreen: true,
- }),
- ),
- ).toMatchObject({
- stateValue: 'focusLayout',
- shouldRenderFocusFallbackGrid: false,
- });
-
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- hasFocusMainTrack: false,
- secondaryFocusTrackCount: 2,
- compact: true,
- isVoiceCallAppFullscreen: true,
- }),
- ),
- ).toMatchObject({
- stateValue: 'focusLayout',
- shouldRenderFocusFallbackGrid: false,
- });
- });
-
- it('selects fallback grid and screen-share wrapping conditions', () => {
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- hasFocusMainTrack: false,
- secondaryFocusTrackCount: 0,
- }),
- ),
- ).toMatchObject({
- stateValue: 'focusFallbackGrid',
- mainLayout: 'focus',
- shouldRenderFocusFallbackGrid: true,
- shouldRenderFocusLayout: false,
- });
-
- expect(
- resolveVoiceCallLayoutPresentationModel(
- input({
- layoutMode: 'grid',
- hasScreenShare: true,
- }),
- ),
- ).toMatchObject({
- stateValue: 'gridLayout',
- mainLayout: 'grid',
- shouldWrapScreenShareGrid: true,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.ts b/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.ts
deleted file mode 100644
index 09a06c3da..000000000
--- a/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- transitionVoiceControlBarState,
- type VoiceControlBarSignals,
-} from '@app/features/voice/components/VoiceControlBarStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<VoiceControlBarSignals> = {}): VoiceControlBarSignals {
- return {
- isDeafened: false,
- isGuildMuted: false,
- isGuildDeafened: false,
- isPermissionMuted: false,
- isPushToTalkEffective: false,
- effectiveMuted: false,
- canStream: true,
- isCameraEnabled: false,
- isCameraLimitReached: false,
- isCameraUserCapReached: false,
- isScreenShareEnabled: false,
- screenShareDisabled: false,
- ...overrides,
- };
-}
-
-describe('VoiceControlBarStateMachine', () => {
- it('allows normal mute and deafen toggles', () => {
- expect(transitionVoiceControlBarState(signals())).toMatchObject({
- mute: {disabled: false, pressed: false, label: 'mute'},
- deafen: {disabled: false, pressed: false, label: 'deafen'},
- });
- expect(
- transitionVoiceControlBarState(
- signals({
- effectiveMuted: true,
- isDeafened: true,
- }),
- ),
- ).toMatchObject({
- mute: {disabled: false, pressed: true, label: 'unmute'},
- deafen: {disabled: false, pressed: true, label: 'undeafen'},
- });
- });
-
- it('locks microphone controls for moderation, permission, and effective push-to-talk states', () => {
- expect(transitionVoiceControlBarState(signals({isGuildDeafened: true, effectiveMuted: true})).mute).toEqual({
- disabled: true,
- pressed: true,
- label: 'moderatorDeafened',
- });
- expect(transitionVoiceControlBarState(signals({isGuildMuted: true, effectiveMuted: true})).mute).toEqual({
- disabled: true,
- pressed: true,
- label: 'moderatorMuted',
- });
- expect(transitionVoiceControlBarState(signals({isPermissionMuted: true, effectiveMuted: true})).mute).toEqual({
- disabled: true,
- pressed: true,
- label: 'permissionMuted',
- });
- expect(transitionVoiceControlBarState(signals({isPushToTalkEffective: true})).mute).toMatchObject({
- disabled: true,
- label: 'pushToTalkHoldHint',
- });
- });
-
- it('locks deafen only when server deafened', () => {
- expect(transitionVoiceControlBarState(signals({isGuildDeafened: true})).deafen).toEqual({
- disabled: true,
- pressed: true,
- label: 'moderatorDeafened',
- });
- expect(transitionVoiceControlBarState(signals({isGuildMuted: true})).deafen).toMatchObject({
- disabled: false,
- pressed: false,
- label: 'deafen',
- });
- });
-
- it('models camera permission and participant limit states', () => {
- expect(transitionVoiceControlBarState(signals({canStream: false})).camera).toEqual({
- disabled: true,
- pressed: false,
- label: 'noPermission',
- });
- expect(transitionVoiceControlBarState(signals({canStream: false, isCameraEnabled: true})).camera).toEqual({
- disabled: false,
- pressed: true,
- label: 'turnOff',
- });
- expect(transitionVoiceControlBarState(signals({isCameraLimitReached: true})).camera).toEqual({
- disabled: true,
- pressed: false,
- label: 'limitReached',
- });
- });
-
- it('disables turning the camera on at the distinct camera user cap', () => {
- expect(transitionVoiceControlBarState(signals({isCameraUserCapReached: true})).camera).toEqual({
- disabled: true,
- pressed: false,
- label: 'userCapReached',
- });
- });
-
- it('never blocks turning the camera off at the camera user cap', () => {
- expect(
- transitionVoiceControlBarState(signals({isCameraUserCapReached: true, isCameraEnabled: true})).camera,
- ).toEqual({
- disabled: false,
- pressed: true,
- label: 'turnOff',
- });
- });
-
- it('models screen-share permission and active states', () => {
- expect(transitionVoiceControlBarState(signals({screenShareDisabled: true})).screenShare).toEqual({
- disabled: true,
- pressed: false,
- label: 'noPermission',
- });
- expect(transitionVoiceControlBarState(signals({isScreenShareEnabled: true})).screenShare).toEqual({
- disabled: false,
- pressed: true,
- label: 'end',
- });
- expect(transitionVoiceControlBarState(signals()).screenShare).toEqual({
- disabled: false,
- pressed: false,
- label: 'start',
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceFocusLayoutMetrics.test.ts b/fluxer_app/src/features/voice/components/VoiceFocusLayoutMetrics.test.ts
deleted file mode 100644
index adedca6dc..000000000
--- a/fluxer_app/src/features/voice/components/VoiceFocusLayoutMetrics.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {
- FOCUS_EXPANDED_MAIN_MIN_HEIGHT_PX,
- FOCUS_EXPANDED_MINI_COLUMN_RULES,
- FOCUS_EXPANDED_MINI_TILE_ASPECT_RATIO,
- getFocusExpandedMiniColumnCount,
- resolveFocusExpandedMainMetrics,
-} from '@app/features/voice/components/VoiceFocusLayoutMetrics';
-import {describe, expect, it} from 'vitest';
-
-function sourceFile(name: string): string {
- return readFileSync(new URL(name, import.meta.url), 'utf8');
-}
-
-describe('VoiceFocusLayoutMetrics', () => {
- it('matches the intended expanded-participant-grid column breakpoints', () => {
- expect(getFocusExpandedMiniColumnCount(619)).toBe(1);
- expect(getFocusExpandedMiniColumnCount(620)).toBe(2);
- expect(getFocusExpandedMiniColumnCount(759)).toBe(2);
- expect(getFocusExpandedMiniColumnCount(760)).toBe(3);
- expect(getFocusExpandedMiniColumnCount(1039)).toBe(3);
- expect(getFocusExpandedMiniColumnCount(1040)).toBe(4);
- });
- it('keeps expanded-focus main height deterministic and never below its CSS minimum', () => {
- const widths = [320, 619, 620, 759, 760, 1039, 1040, 1440, 1920];
- const heights = [220, 360, 520, 720, 1080];
- for (const containerWidth of widths) {
- for (const containerHeight of heights) {
- const metrics = resolveFocusExpandedMainMetrics({containerWidth, containerHeight});
- expect(metrics.mainMaxHeight).toBeGreaterThanOrEqual(FOCUS_EXPANDED_MAIN_MIN_HEIGHT_PX);
- expect(metrics.miniRowHeight).toBeCloseTo(
- Math.min(metrics.miniTileMaxWidth, metrics.miniColumnWidth) / FOCUS_EXPANDED_MINI_TILE_ASPECT_RATIO,
- 5,
- );
- expect(metrics.miniContentWidth).toBeLessThanOrEqual(metrics.miniSectionWidth);
- expect(
- metrics.miniColumnWidth * metrics.miniColumns + metrics.miniGridGap * (metrics.miniColumns - 1),
- ).toBeLessThanOrEqual(metrics.miniContentWidth + 0.001);
- }
- }
- });
- it('keeps the helper constants synchronized with the focus layout CSS', () => {
- const css = sourceFile('VoiceCallView.module.css');
- for (const rule of FOCUS_EXPANDED_MINI_COLUMN_RULES) {
- expect(css).toContain(`@container (min-width: ${rule.minWidth}px)`);
- expect(css).toContain(`--focus-expanded-mini-columns: ${rule.columns};`);
- }
- expect(css).toContain(
- '--focus-expanded-reserved-bottom-height: calc(44px + 2.5rem + var(--focus-expanded-mini-row-height));',
- );
- expect(css).toContain(`--focus-expanded-main-max-height: max(${FOCUS_EXPANDED_MAIN_MIN_HEIGHT_PX}px`);
- expect(css).toContain(
- `min-height: min(${FOCUS_EXPANDED_MAIN_MIN_HEIGHT_PX}px, var(--focus-expanded-main-max-height));`,
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceGridLayoutMetrics.test.ts b/fluxer_app/src/features/voice/components/VoiceGridLayoutMetrics.test.ts
deleted file mode 100644
index ed615f14f..000000000
--- a/fluxer_app/src/features/voice/components/VoiceGridLayoutMetrics.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {
- getVoiceGridColumnCount,
- getVoiceGridGap,
- getVoiceGridMinTileSize,
- getVoiceGridPadding,
- getVoiceGridRowStyle,
- getVoiceGridRowsByColumnCount,
- getVoiceGridVisibleTileCapacity,
- resolveVoiceGridLayoutMetrics,
- resolveVoiceGridPackedLayoutMetrics,
- VOICE_GRID_COLUMN_RULES,
- VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX,
- VOICE_GRID_MIN_TILE_WIDTH_PX,
- VOICE_GRID_TILE_ASPECT_RATIO,
-} from '@app/features/voice/components/VoiceGridLayoutMetrics';
-import {describe, expect, it} from 'vitest';
-
-const EPSILON_PX = 0.001;
-
-function sourceFile(name: string): string {
- return readFileSync(new URL(name, import.meta.url), 'utf8');
-}
-
-describe('VoiceGridLayoutMetrics', () => {
- it('emits stable row variables for every CSS-selected column count', () => {
- expect(getVoiceGridRowsByColumnCount(0)).toEqual({1: 1, 2: 1, 3: 1, 4: 1});
- expect(getVoiceGridRowsByColumnCount(1)).toEqual({1: 1, 2: 1, 3: 1, 4: 1});
- expect(getVoiceGridRowsByColumnCount(5)).toEqual({1: 5, 2: 3, 3: 2, 4: 2});
- expect(getVoiceGridRowsByColumnCount(10)).toEqual({1: 10, 2: 5, 3: 4, 4: 3});
- expect(getVoiceGridRowStyle(10)).toEqual({
- '--voice-grid-rows-1': '10',
- '--voice-grid-rows-2': '5',
- '--voice-grid-rows-3': '4',
- '--voice-grid-rows-4': '3',
- });
- });
- it('matches the intended column breakpoints exactly', () => {
- expect(getVoiceGridColumnCount({tileCount: 1, containerWidth: 1920, containerHeight: 1080})).toBe(1);
- expect(getVoiceGridColumnCount({tileCount: 2, containerWidth: 519, containerHeight: 800})).toBe(1);
- expect(getVoiceGridColumnCount({tileCount: 2, containerWidth: 520, containerHeight: 260})).toBe(2);
- expect(getVoiceGridColumnCount({tileCount: 5, containerWidth: 859, containerHeight: 800})).toBe(2);
- expect(getVoiceGridColumnCount({tileCount: 5, containerWidth: 860, containerHeight: 360})).toBe(3);
- expect(getVoiceGridColumnCount({tileCount: 10, containerWidth: 1179, containerHeight: 800})).toBe(3);
- expect(getVoiceGridColumnCount({tileCount: 10, containerWidth: 1180, containerHeight: 460})).toBe(4);
- });
- it('keeps all feasible grid layouts inside their viewport without post-paint measurement', () => {
- const widths = [240, 320, 419, 420, 519, 520, 759, 760, 859, 860, 1179, 1180, 1440, 1920];
- const heights = [180, 240, 259, 260, 359, 360, 459, 460, 519, 520, 720, 1080];
- const tileCounts = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32, 40, 64];
- for (const tileCount of tileCounts) {
- for (const containerWidth of widths) {
- for (const containerHeight of heights) {
- for (const compact of [false, true]) {
- for (const edgeToEdge of [false, true]) {
- const metrics = resolveVoiceGridLayoutMetrics({
- tileCount,
- containerWidth,
- containerHeight,
- compact,
- edgeToEdge,
- });
- const padding = getVoiceGridPadding({containerWidth, containerHeight, compact, edgeToEdge});
- const gap = getVoiceGridGap({tileCount, compact, containerHeight});
- const gapBudgetFits =
- padding.verticalPadding * 2 + gap * Math.max(0, metrics.rows - 1) <= containerHeight + EPSILON_PX;
- expect(
- metrics.tileWidth,
- `tile width for ${tileCount} tiles in ${containerWidth}x${containerHeight}`,
- ).toBeGreaterThanOrEqual(0);
- expect(
- metrics.tileHeight,
- `tile height for ${tileCount} tiles in ${containerWidth}x${containerHeight}`,
- ).toBeGreaterThanOrEqual(0);
- if (metrics.tileWidth > 0) {
- expect(metrics.tileWidth / metrics.tileHeight).toBeCloseTo(VOICE_GRID_TILE_ASPECT_RATIO, 5);
- }
- expect(metrics.contentWidth).toBeLessThanOrEqual(containerWidth + EPSILON_PX);
- if (gapBudgetFits) {
- expect(metrics.contentHeight).toBeLessThanOrEqual(containerHeight + EPSILON_PX);
- } else {
- expect(metrics.tileWidth).toBe(0);
- expect(metrics.tileHeight).toBe(0);
- }
- }
- }
- }
- }
- }
- });
- it('keeps compact single-tile layouts contained at 16:9 inside the safe grid frame', () => {
- const metrics = resolveVoiceGridLayoutMetrics({
- tileCount: 1,
- containerWidth: 1600,
- containerHeight: 500,
- compact: true,
- });
- expect(metrics.tileWidth).toBeLessThan(metrics.availableWidth);
- expect(metrics.tileWidth).toBeCloseTo(metrics.availableHeight * VOICE_GRID_TILE_ASPECT_RATIO, 5);
- expect(metrics.tileHeight).toBeCloseTo(metrics.availableHeight, 5);
- expect(metrics.tileWidth / metrics.tileHeight).toBeCloseTo(VOICE_GRID_TILE_ASPECT_RATIO, 5);
- expect(metrics.contentWidth).toBeLessThan(1600);
- expect(metrics.contentHeight).toBeCloseTo(500, 5);
- });
- it('limits visible tiles before they fall below the minimum readable size', () => {
- const capacity = getVoiceGridVisibleTileCapacity({
- tileCount: 64,
- containerWidth: 800,
- containerHeight: 450,
- });
- const minSize = getVoiceGridMinTileSize();
- const metrics = resolveVoiceGridPackedLayoutMetrics({
- tileCount: 64,
- containerWidth: 800,
- containerHeight: 450,
- });
- expect(capacity).toBeGreaterThan(0);
- expect(capacity).toBeLessThan(64);
- expect(metrics.visibleTileCount).toBe(capacity);
- expect(metrics.tileWidth).toBeGreaterThanOrEqual(minSize.minTileWidth - EPSILON_PX);
- expect(metrics.tileHeight).toBeGreaterThanOrEqual(minSize.minTileHeight - EPSILON_PX);
- const wideMetrics = resolveVoiceGridPackedLayoutMetrics({
- tileCount: 24,
- containerWidth: 1920,
- containerHeight: 1080,
- });
- expect(wideMetrics.visibleTileCount).toBe(24);
- expect(wideMetrics.columns).toBeGreaterThan(VOICE_GRID_COLUMN_RULES[0].columns);
- expect(
- getVoiceGridVisibleTileCapacity({
- tileCount: 10,
- containerWidth: VOICE_GRID_MIN_TILE_WIDTH_PX / 2,
- containerHeight: 90,
- }),
- ).toBe(0);
- });
- it('does not force an oversized fallback tile when the compact grid cannot fit one readable tile', () => {
- const metrics = resolveVoiceGridPackedLayoutMetrics({
- tileCount: 8,
- containerWidth: 640,
- containerHeight: 0,
- compact: true,
- });
- expect(metrics.visibleTileCount).toBe(0);
- expect(metrics.tileWidth).toBe(0);
- expect(metrics.tileHeight).toBe(0);
- });
- it('packs compact tiles across a wide short viewport before hiding overflow', () => {
- const metrics = resolveVoiceGridPackedLayoutMetrics({
- tileCount: 64,
- containerWidth: 1920,
- containerHeight: 120,
- compact: true,
- });
- expect(metrics.visibleTileCount).toBeGreaterThan(8);
- expect(metrics.columns).toBe(metrics.visibleTileCount);
- expect(metrics.rows).toBe(1);
- expect(metrics.tileWidth).toBeGreaterThanOrEqual(VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX - EPSILON_PX);
- expect(metrics.tileHeight).toBeGreaterThanOrEqual(
- VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX / VOICE_GRID_TILE_ASPECT_RATIO - EPSILON_PX,
- );
- expect(metrics.contentWidth).toBeLessThanOrEqual(1920 + EPSILON_PX);
- expect(metrics.contentHeight).toBeLessThanOrEqual(120 + EPSILON_PX);
- });
- it('packs compact tiles down a tall narrow viewport before hiding overflow', () => {
- const metrics = resolveVoiceGridPackedLayoutMetrics({
- tileCount: 64,
- containerWidth: 180,
- containerHeight: 1200,
- compact: true,
- });
- expect(metrics.visibleTileCount).toBeGreaterThan(8);
- expect(metrics.columns).toBe(1);
- expect(metrics.rows).toBe(metrics.visibleTileCount);
- expect(metrics.tileWidth).toBeGreaterThanOrEqual(VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX - EPSILON_PX);
- expect(metrics.tileHeight).toBeGreaterThanOrEqual(
- VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX / VOICE_GRID_TILE_ASPECT_RATIO - EPSILON_PX,
- );
- expect(metrics.contentWidth).toBeLessThanOrEqual(180 + EPSILON_PX);
- expect(metrics.contentHeight).toBeLessThanOrEqual(1200 + EPSILON_PX);
- });
- it('keeps the helper constants synchronized with the CSS module breakpoints', () => {
- const css = sourceFile('VoiceGridLayout.module.css');
- for (const rule of VOICE_GRID_COLUMN_RULES) {
- expect(css).toContain(
- `@container voice-grid (min-width: ${rule.minWidth}px) and (min-height: ${rule.minHeight}px)`,
- );
- expect(css).toContain(`--voice-grid-columns: ${rule.columns};`);
- }
- expect(css).toContain('--voice-grid-gap: 10px;');
- expect(css).toContain('--voice-grid-gap: 8px;');
- expect(css).toContain('--voice-grid-gap: 6px;');
- expect(css).toContain('--voice-grid-gap: 5px;');
- expect(css).toContain('--voice-grid-gap: 4px;');
- expect(css).toContain('--voice-grid-tile-width: var(--voice-grid-multi-tile-width);');
- expect(css).toContain('calc(var(--voice-grid-row-height) * 16 / 9)');
- expect(css).not.toContain('--voice-grid-tile-width: var(--voice-grid-available-width);');
- expect(css).not.toMatch(/\n\s*height: var\(--voice-grid-available-height\);/);
- expect(css).not.toContain('aspect-ratio: auto;');
- expect(css).toContain(`--voice-grid-min-tile-width: ${VOICE_GRID_MIN_TILE_WIDTH_PX}px;`);
- expect(css).toContain(`--voice-grid-min-tile-width: ${VOICE_GRID_COMPACT_MIN_TILE_WIDTH_PX}px;`);
- });
- it('centers non-full final rows through wrapping layout', () => {
- const css = sourceFile('VoiceGridLayout.module.css');
- expect(css).toContain('display: flex;');
- expect(css).toContain('flex-wrap: wrap;');
- expect(css).toContain('justify-content: center;');
- expect(css).toContain('align-content: center;');
- });
- it('keeps the grid surface non-scrolling while fit is handled by capacity', () => {
- const gridSource = sourceFile('VoiceGridLayout.tsx');
- const layoutSource = sourceFile('VoiceCallLayoutContent.tsx');
- expect(gridSource).toContain('resolveVoiceGridPackedLayoutMetrics');
- expect(layoutSource).toContain('overflow="hidden"');
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceLiveKitRoot.test.tsx b/fluxer_app/src/features/voice/components/VoiceLiveKitRoot.test.tsx
deleted file mode 100644
index ce46b87f4..000000000
--- a/fluxer_app/src/features/voice/components/VoiceLiveKitRoot.test.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {VoiceLiveKitRoot} from '@app/features/voice/components/VoiceLiveKitRoot';
-import {useRoomContext} from '@livekit/components-react';
-import {Room} from 'livekit-client';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-function RoomContextProbe({expectedRoom}: {expectedRoom: Room}) {
- const room = useRoomContext();
- return (
- <div data-testid="room-context" data-flx="voice.voice-live-kit-root-test.room-context-probe.room-context">
- {room === expectedRoom ? 'matched' : 'mismatched'}
- </div>
- );
-}
-
-describe('VoiceLiveKitRoot', () => {
- let root: Root | null = null;
- let container: HTMLDivElement | null = null;
-
- beforeEach(() => {
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
- });
-
- afterEach(() => {
- act(() => {
- root?.unmount();
- });
- root = null;
- container?.remove();
- container = null;
- });
-
- it('provides room context before the audio renderer bundle resolves', async () => {
- const room = new Room();
-
- act(() => {
- root?.render(
- <VoiceLiveKitRoot room={room} data-flx="voice.voice-live-kit-root-test.voice-live-kit-root">
- <RoomContextProbe expectedRoom={room} data-flx="voice.voice-live-kit-root-test.room-context-probe" />
- </VoiceLiveKitRoot>,
- );
- });
-
- expect(container?.querySelector('[data-testid="room-context"]')?.textContent).toBe('matched');
-
- await act(async () => {
- await Promise.resolve();
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceParticipantAvatarList.test.ts b/fluxer_app/src/features/voice/components/VoiceParticipantAvatarList.test.ts
deleted file mode 100644
index 65f61ae4b..000000000
--- a/fluxer_app/src/features/voice/components/VoiceParticipantAvatarList.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceState} from '@app/features/gateway/types/GatewayVoiceTypes';
-import {resolveVoiceParticipantAvatarEntryVoiceState} from '@app/features/voice/components/VoiceParticipantDisplayState';
-import type {LivekitParticipantSnapshot} from '@app/features/voice/engine/VoiceParticipantStateMachine';
-import {VoiceConnectionQuality} from '@app/features/voice/engine/VoiceTrackSource';
-import {describe, expect, it} from 'vitest';
-
-function createParticipantSnapshot(overrides: Partial<LivekitParticipantSnapshot> = {}): LivekitParticipantSnapshot {
- return {
- identity: 'user_100_connection-local',
- userId: '100',
- connectionId: 'connection-local',
- sid: 'PA_local',
- isLocal: true,
- isSpeaking: false,
- isAudioLevelSpeaking: true,
- connectionQuality: VoiceConnectionQuality.Excellent,
- attributes: {},
- audioTrackSids: [],
- videoTrackSids: [],
- isMicrophoneEnabled: true,
- isCameraEnabled: false,
- isScreenShareEnabled: false,
- isScreenShareAudioEnabled: false,
- joinedAt: null,
- lastSpokeAt: null,
- ...overrides,
- };
-}
-
-function createVoiceState(overrides: Partial<VoiceState> = {}): VoiceState {
- return {
- guild_id: 'guild-1',
- channel_id: 'channel-1',
- user_id: '100',
- connection_id: 'connection-local',
- mute: false,
- deaf: false,
- self_mute: false,
- self_deaf: false,
- self_video: false,
- self_stream: false,
- ...overrides,
- };
-}
-
-describe('resolveVoiceParticipantAvatarEntryVoiceState', () => {
- it('keeps local avatar stack speaking when stale voice state self mute is true but effective v2 mute is false', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot(),
- voiceState: createVoiceState({self_mute: true}),
- permissionMuted: false,
- localEffectiveSelfMute: false,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: true,
- selfMute: false,
- selfDeaf: false,
- });
- });
-
- it('suppresses local avatar stack speaking when effective v2 mute is true', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot(),
- voiceState: createVoiceState({self_mute: false}),
- permissionMuted: false,
- localEffectiveSelfMute: true,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: false,
- selfMute: true,
- });
- });
-
- it('keeps speaking when the native engine reports a stale disabled microphone flag', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot({isMicrophoneEnabled: false}),
- voiceState: createVoiceState(),
- permissionMuted: false,
- localEffectiveSelfMute: false,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: true,
- selfMute: false,
- });
- });
-
- it('keeps remote speaking when the stale microphone flag is false but voice state self mute is false', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot({
- identity: 'user_200_connection-remote',
- userId: '200',
- connectionId: 'connection-remote',
- sid: 'PA_remote',
- isLocal: false,
- isMicrophoneEnabled: false,
- }),
- voiceState: createVoiceState({
- user_id: '200',
- connection_id: 'connection-remote',
- self_mute: false,
- }),
- permissionMuted: false,
- localEffectiveSelfMute: false,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: true,
- selfMute: false,
- });
- });
-
- it('falls back to the microphone flag for remote mute when voice state is missing', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot({
- identity: 'user_200_connection-remote',
- userId: '200',
- connectionId: 'connection-remote',
- sid: 'PA_remote',
- isLocal: false,
- isMicrophoneEnabled: false,
- }),
- voiceState: null,
- permissionMuted: false,
- localEffectiveSelfMute: false,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: false,
- selfMute: true,
- });
- });
-
- it('continues to suppress remote avatar stack speaking from voice state self mute', () => {
- const state = resolveVoiceParticipantAvatarEntryVoiceState({
- snapshot: createParticipantSnapshot({
- identity: 'user_200_connection-remote',
- userId: '200',
- connectionId: 'connection-remote',
- sid: 'PA_remote',
- isLocal: false,
- }),
- voiceState: createVoiceState({
- user_id: '200',
- connection_id: 'connection-remote',
- self_mute: true,
- }),
- permissionMuted: false,
- localEffectiveSelfMute: false,
- localSelfDeaf: false,
- });
-
- expect(state).toMatchObject({
- speaking: false,
- selfMute: true,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceParticipantConsolidation.test.ts b/fluxer_app/src/features/voice/components/VoiceParticipantConsolidation.test.ts
deleted file mode 100644
index 966bdcde5..000000000
--- a/fluxer_app/src/features/voice/components/VoiceParticipantConsolidation.test.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {consolidateVoiceGridTracks} from '@app/features/voice/components/VoiceParticipantConsolidation';
-import {
- VoiceTrackSource,
- type VoiceTrackSource as VoiceTrackSourceType,
-} from '@app/features/voice/engine/VoiceTrackSource';
-import type {TrackReferenceOrPlaceholder} from '@livekit/components-react';
-import {describe, expect, it} from 'vitest';
-
-interface MakeTrackArgs {
- userId: string;
- connectionId: string;
- source?: VoiceTrackSourceType;
- muted?: boolean;
- placeholder?: boolean;
-}
-
-function makeTrack({
- userId,
- connectionId,
- source = VoiceTrackSource.Camera,
- muted = false,
- placeholder = false,
-}: MakeTrackArgs): TrackReferenceOrPlaceholder {
- const identity = `user_${userId}_${connectionId}`;
- const participant = {identity} as TrackReferenceOrPlaceholder['participant'];
- if (placeholder) {
- return {participant, source} as TrackReferenceOrPlaceholder;
- }
- return {
- participant,
- source,
- publication: {isMuted: muted, source} as TrackReferenceOrPlaceholder extends {publication: infer P} ? P : never,
- } as TrackReferenceOrPlaceholder;
-}
-
-const EMPTY: ReadonlySet<string> = new Set<string>();
-
-describe('consolidateVoiceGridTracks', () => {
- it('renders a single connection as a plain track entry with no hidden devices', () => {
- const tracks = [makeTrack({userId: '1', connectionId: 'a', muted: true})];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: EMPTY});
- expect(entries).toHaveLength(1);
- expect(entries[0]).toMatchObject({
- kind: 'track',
- hiddenConnectionCount: 0,
- deviceConnectionCount: 1,
- isDeviceGroupExpanded: false,
- userId: '1',
- });
- });
- it('shows the highest-priority passive track when none are active and hides the rest as a count', () => {
- const tracks = [
- makeTrack({userId: '1', connectionId: 'a', muted: true}),
- makeTrack({userId: '1', connectionId: 'b', muted: true}),
- makeTrack({userId: '1', connectionId: 'c', placeholder: true}),
- ];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: EMPTY});
- expect(entries).toHaveLength(1);
- expect(entries[0]).toMatchObject({
- kind: 'track',
- userId: '1',
- hiddenConnectionCount: 2,
- deviceConnectionCount: 3,
- isDeviceGroupExpanded: false,
- });
- expect(entries[0].trackRef.participant.identity).toBe('user_1_a');
- });
- it('keeps the lone active track and hides the rest as a badge count', () => {
- const tracks = [
- makeTrack({userId: '1', connectionId: 'a', muted: true}),
- makeTrack({userId: '1', connectionId: 'b'}),
- makeTrack({userId: '1', connectionId: 'c', muted: true}),
- makeTrack({userId: '1', connectionId: 'd', placeholder: true}),
- ];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: EMPTY});
- expect(entries).toHaveLength(1);
- expect(entries[0]).toMatchObject({kind: 'track', hiddenConnectionCount: 3, userId: '1'});
- expect(entries[0].kind === 'track' && entries[0].trackRef.participant.identity).toBe('user_1_b');
- });
- it('attaches the hidden badge only to the first active tile when several are active', () => {
- const tracks = [
- makeTrack({userId: '1', connectionId: 'a'}),
- makeTrack({userId: '1', connectionId: 'b', source: VoiceTrackSource.ScreenShare}),
- makeTrack({userId: '1', connectionId: 'c', muted: true}),
- makeTrack({userId: '1', connectionId: 'd', muted: true}),
- ];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: EMPTY});
- expect(entries).toHaveLength(2);
- expect(entries[0]).toMatchObject({kind: 'track', hiddenConnectionCount: 2});
- expect(entries[1]).toMatchObject({kind: 'track', hiddenConnectionCount: 0});
- });
- it('expands all connections for the user when they are in the expanded set', () => {
- const tracks = [
- makeTrack({userId: '1', connectionId: 'a', muted: true}),
- makeTrack({userId: '1', connectionId: 'b', muted: true}),
- makeTrack({userId: '1', connectionId: 'c', muted: true}),
- ];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: new Set(['1'])});
- expect(entries).toHaveLength(3);
- for (const entry of entries) {
- expect(entry.kind).toBe('track');
- expect(entry.hiddenConnectionCount).toBe(0);
- expect(entry.deviceConnectionCount).toBe(3);
- expect(entry.isDeviceGroupExpanded).toBe(true);
- }
- expect(entries.map((entry) => entry.isDeviceGroupPrimary ?? false)).toEqual([true, false, false]);
- });
- it('preserves the order of distinct users by first appearance', () => {
- const tracks = [
- makeTrack({userId: '1', connectionId: 'a', muted: true}),
- makeTrack({userId: '2', connectionId: 'a'}),
- makeTrack({userId: '1', connectionId: 'b', muted: true}),
- makeTrack({userId: '3', connectionId: 'a', muted: true}),
- makeTrack({userId: '2', connectionId: 'b', muted: true}),
- ];
- const entries = consolidateVoiceGridTracks({tracks, expandedUserIds: EMPTY});
- expect(entries.map((entry) => entry.userId)).toEqual(['1', '2', '3']);
- expect(entries[0]).toMatchObject({kind: 'track', userId: '1', hiddenConnectionCount: 1});
- expect(entries[1]).toMatchObject({kind: 'track', userId: '2', hiddenConnectionCount: 1});
- expect(entries[2]).toMatchObject({kind: 'track', userId: '3', hiddenConnectionCount: 0});
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceParticipantDisplayState.test.ts b/fluxer_app/src/features/voice/components/VoiceParticipantDisplayState.test.ts
deleted file mode 100644
index 88b0d8698..000000000
--- a/fluxer_app/src/features/voice/components/VoiceParticipantDisplayState.test.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceState} from '@app/features/gateway/types/GatewayVoiceTypes';
-import {
- resolveVoiceParticipantDisplayState,
- resolveVoiceParticipantSpeaking,
-} from '@app/features/voice/components/VoiceParticipantDisplayState';
-import {describe, expect, it} from 'vitest';
-
-function voiceState(overrides: Partial<VoiceState>): VoiceState {
- return overrides as VoiceState;
-}
-
-function speakingParticipant(isMicrophoneEnabled = true) {
- return {isSpeaking: false, isAudioLevelSpeaking: true, isMicrophoneEnabled};
-}
-
-describe('resolveVoiceParticipantSpeaking', () => {
- it('returns false when the participant is not speaking', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: {isSpeaking: false, isAudioLevelSpeaking: false},
- voiceState: voiceState({}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(false);
- });
-
- it('suppresses remote participants when gateway self mute is set', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: true}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(false);
- });
-
- it('lets the local connection ignore a stale gateway self mute echo', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: true}),
- isLocalConnection: true,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(true);
- });
-
- it('suppresses the local connection when the effective local mute is set', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: false}),
- isLocalConnection: true,
- localSelfMute: true,
- permissionMuted: false,
- }),
- ).toBe(false);
- });
-
- it('ignores a stale disabled microphone flag when gateway self mute is present', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(false),
- voiceState: voiceState({self_mute: false}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(true);
- });
-
- it('falls back to the microphone flag when gateway self mute is missing', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(false),
- voiceState: voiceState({}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(false);
- });
-
- it('suppresses moderator mute regardless of connection locality', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: false, mute: true}),
- isLocalConnection: true,
- localSelfMute: false,
- permissionMuted: false,
- }),
- ).toBe(false);
- });
-
- it('suppresses permission-muted participants', () => {
- expect(
- resolveVoiceParticipantSpeaking({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: false}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: true,
- }),
- ).toBe(false);
- });
-});
-
-describe('resolveVoiceParticipantDisplayState', () => {
- it('derives remote display state from the gateway voice state first', () => {
- const state = resolveVoiceParticipantDisplayState({
- participant: {
- isSpeaking: false,
- isAudioLevelSpeaking: false,
- isMicrophoneEnabled: true,
- isCameraEnabled: true,
- isScreenShareEnabled: true,
- },
- voiceState: voiceState({
- self_mute: true,
- self_deaf: true,
- self_video: false,
- self_stream: false,
- mute: true,
- deaf: true,
- }),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- });
-
- expect(state).toEqual({
- speaking: false,
- selfMute: true,
- selfDeaf: true,
- guildMute: true,
- guildDeaf: true,
- cameraOn: false,
- streaming: false,
- });
- });
-
- it('falls back to participant track flags when gateway fields are missing', () => {
- const state = resolveVoiceParticipantDisplayState({
- participant: {
- isSpeaking: false,
- isAudioLevelSpeaking: false,
- isMicrophoneEnabled: true,
- isCameraEnabled: true,
- isScreenShareEnabled: true,
- },
- voiceState: voiceState({}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- });
-
- expect(state).toMatchObject({
- selfMute: false,
- selfDeaf: false,
- cameraOn: true,
- streaming: true,
- });
- });
-
- it('uses the local overrides for the local connection', () => {
- const state = resolveVoiceParticipantDisplayState({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: true, self_deaf: true, self_video: false, self_stream: false}),
- isLocalConnection: true,
- localSelfMute: false,
- localSelfDeaf: false,
- localSelfVideo: true,
- localSelfStream: true,
- permissionMuted: false,
- });
-
- expect(state).toMatchObject({
- speaking: true,
- selfMute: false,
- selfDeaf: false,
- cameraOn: true,
- streaming: true,
- });
- });
-
- it('includes permission mute in the self mute display flag', () => {
- const state = resolveVoiceParticipantDisplayState({
- participant: speakingParticipant(),
- voiceState: voiceState({self_mute: false}),
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: true,
- });
-
- expect(state).toMatchObject({
- speaking: false,
- selfMute: true,
- });
- });
-
- it('handles a missing participant and missing voice state without throwing', () => {
- const state = resolveVoiceParticipantDisplayState({
- participant: null,
- voiceState: null,
- isLocalConnection: false,
- localSelfMute: false,
- permissionMuted: false,
- });
-
- expect(state).toEqual({
- speaking: false,
- selfMute: false,
- selfDeaf: false,
- guildMute: false,
- guildDeaf: false,
- cameraOn: false,
- streaming: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceParticipantTileStability.test.ts b/fluxer_app/src/features/voice/components/VoiceParticipantTileStability.test.ts
deleted file mode 100644
index 38d251cf2..000000000
--- a/fluxer_app/src/features/voice/components/VoiceParticipantTileStability.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {describe, expect, it} from 'vitest';
-
-function sourceFile(name: string): string {
- return readFileSync(new URL(name, import.meta.url), 'utf8');
-}
-
-function appSourceFile(pathFromAppSrc: string): string {
- return readFileSync(new URL(`../../../${pathFromAppSrc}`, import.meta.url), 'utf8');
-}
-
-describe('VoiceParticipantTile stability', () => {
- it('sizes participant avatars on first paint without a resize observer or transform correction pass', () => {
- const tileSource = sourceFile('VoiceParticipantTile.tsx');
- const hookSource = sourceFile('voice_participant_tile/hooks.ts');
- const sharedSource = sourceFile('voice_participant_tile/shared.ts');
- const css = sourceFile('VoiceParticipantTile.module.css');
- expect(tileSource).not.toContain('useAvatarScale');
- expect(hookSource).not.toContain('useAvatarScale');
- expect(hookSource).not.toContain('--tile-avatar-scale');
- expect(sharedSource).not.toContain('resolveAvatarSize');
- expect(tileSource).toContain('styles.tileAvatarRing');
- expect(css).toContain('--tile-avatar-size');
- expect(css).toContain('.tileAvatarRing');
- expect(css).toContain('32cqw');
- expect(css).toContain('32cqh');
- expect(css).not.toContain('--tile-avatar-scale');
- expect(css).not.toMatch(/transform:\s*scale/);
- expect(css).not.toContain('will-change: transform');
- });
- it('drives the tile avatar animation from the speaking signal so animated avatars play without hover', () => {
- const tileSource = sourceFile('VoiceParticipantTile.tsx');
- const avatarElement = tileSource.match(/<Avatar\b[\s\S]*?\/>/)?.[0];
- expect(avatarElement).toBeDefined();
- const forceAnimateExpression = avatarElement?.match(/forceAnimate=\{([^}]+)\}/)?.[1]?.trim();
- expect(forceAnimateExpression).toBeDefined();
- const animateFlagSource =
- forceAnimateExpression === 'isActuallySpeaking'
- ? 'isActuallySpeaking'
- : tileSource.match(new RegExp(`const ${forceAnimateExpression} = ([^;]+);`))?.[1];
- expect(animateFlagSource).toContain('isActuallySpeaking');
- expect(animateFlagSource).toContain('!Accessibility.useReducedMotion');
- expect(tileSource).toContain("import Accessibility from '@app/features/accessibility/state/Accessibility';");
- const afterAvatarElement = tileSource.slice(tileSource.indexOf(avatarElement!) + avatarElement!.length);
- const mediaNodeDeps = afterAvatarElement.match(/\}, \[([\s\S]*?)\]\);/)?.[1] ?? '';
- expect(mediaNodeDeps).toContain(forceAnimateExpression);
- });
- it('keeps the fullscreen call surface mounted while the media room catches up to a channel switch', () => {
- const voiceCallViewSource = sourceFile('VoiceCallView.tsx');
- const guildChannelViewSource = appSourceFile('features/channel/components/channel_view/GuildChannelView.tsx');
- expect(voiceCallViewSource).toContain('const VoiceCallPendingView');
- expect(voiceCallViewSource).toMatch(
- /if \(!hasValidRoomForVoiceCallView\(channel\)\) {\s+return \(\s+<VoiceCallPendingView/,
- );
- expect(voiceCallViewSource).not.toMatch(/if \(!hasValidRoomForVoiceCallView\(channel\)\) {\s+return null;/);
- expect(guildChannelViewSource).not.toContain('{isConnectedToThisChannel && room ? (');
- });
-});
diff --git a/fluxer_app/src/features/voice/components/VoiceParticipantTileStateMachine.test.ts b/fluxer_app/src/features/voice/components/VoiceParticipantTileStateMachine.test.ts
deleted file mode 100644
index 4583dee69..000000000
--- a/fluxer_app/src/features/voice/components/VoiceParticipantTileStateMachine.test.ts
+++ /dev/null
@@ -1,544 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- graphTileStateHoldsWatchIntent,
- selectScreenShareBufferingPresentation,
- selectVoiceParticipantTileCameraActive,
- selectVoiceParticipantTileScreenShareState,
- shouldShowCameraBuffering,
- shouldShowTileStreamAudioControls,
- shouldShowWatchFailed,
- type VoiceParticipantTileCameraActiveSignals,
- type VoiceParticipantTileCameraBufferingSignals,
- type VoiceParticipantTileScreenShareSignals,
- type VoiceParticipantTileStreamAudioSignals,
-} from '@app/features/voice/components/VoiceParticipantTileStateMachine';
-import {
- getAppliedScreenShareFrameRate,
- noteAppliedScreenShareFrameRate,
- type ScreenShareQualityLimitationReason,
- type ScreenShareUnderperformanceReason,
- ScreenShareUnderperformanceTracker,
-} from '@app/features/voice/engine/ScreenShareUnderperformance';
-import type {VoiceMediaGraphStreamTileState} from '@app/features/voice/engine/VoiceMediaGraphTileState';
-import {describe, expect, it} from 'vitest';
-
-const GRAPH_TILE_STATES: ReadonlyArray<VoiceMediaGraphStreamTileState> = [
- 'idle',
- 'watchDesired',
- 'publicationMissing',
- 'attaching',
- 'subscribedAwaitingFrame',
- 'rendering',
- 'recovering',
- 'failed',
-];
-
-const WATCH_INTENT_GRAPH_TILE_STATES: ReadonlyArray<VoiceMediaGraphStreamTileState> = [
- 'watchDesired',
- 'publicationMissing',
- 'attaching',
- 'subscribedAwaitingFrame',
- 'rendering',
- 'recovering',
- 'failed',
-];
-
-function signals(
- overrides: Partial<VoiceParticipantTileScreenShareSignals> = {},
-): VoiceParticipantTileScreenShareSignals {
- return {
- graphTileState: 'idle',
- isScreenShare: true,
- isOwnScreenShare: false,
- isFocusedPlaceholderTile: false,
- isFocusPresentationTile: false,
- isTrackReference: true,
- cameraLocallyDisabled: false,
- isRepublishGracePending: false,
- ...overrides,
- };
-}
-
-function cameraSignals(
- overrides: Partial<VoiceParticipantTileCameraBufferingSignals> = {},
-): VoiceParticipantTileCameraBufferingSignals {
- return {
- isScreenShare: false,
- isFocusedPlaceholderTile: false,
- cameraLocallyDisabled: false,
- isOwnCameraHidden: false,
- isCameraActive: true,
- hasVideo: false,
- hasRenderedVideoFrame: false,
- ...overrides,
- };
-}
-
-function cameraActiveSignals(
- overrides: Partial<VoiceParticipantTileCameraActiveSignals> = {},
-): VoiceParticipantTileCameraActiveSignals {
- return {
- isCameraTile: true,
- isOwnContent: false,
- isCameraPublicationActive: false,
- isParticipantCameraActive: false,
- isLocalCameraRequested: false,
- ...overrides,
- };
-}
-
-function streamAudioSignals(
- overrides: Partial<VoiceParticipantTileStreamAudioSignals> = {},
-): VoiceParticipantTileStreamAudioSignals {
- return {
- isScreenShare: true,
- isOwnScreenShare: false,
- isWatching: true,
- hasScreenShareAudio: true,
- isFocusedPlaceholderTile: false,
- presentation: 'grid',
- ...overrides,
- };
-}
-
-describe('VoiceParticipantTileStateMachine stream audio controls', () => {
- it('keeps the per-stream volume control on the watched stream once it becomes the focused tile', () => {
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({presentation: 'focus-main'}))).toBe(true);
- });
-
- it('shows the per-stream volume control on a watched grid tile', () => {
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({presentation: 'grid'}))).toBe(true);
- });
-
- it('leaves the control off carousel thumbnails, own shares, and placeholder tiles', () => {
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({presentation: 'focus-secondary'}))).toBe(false);
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({isOwnScreenShare: true}))).toBe(false);
- expect(
- shouldShowTileStreamAudioControls(
- streamAudioSignals({presentation: 'focus-main', isFocusedPlaceholderTile: true}),
- ),
- ).toBe(false);
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({isScreenShare: false}))).toBe(false);
- });
-
- it('leaves the control off streams that are not watched or carry no audio', () => {
- expect(shouldShowTileStreamAudioControls(streamAudioSignals({presentation: 'focus-main', isWatching: false}))).toBe(
- false,
- );
- expect(
- shouldShowTileStreamAudioControls(streamAudioSignals({presentation: 'focus-main', hasScreenShareAudio: false})),
- ).toBe(false);
- });
-});
-
-describe('VoiceParticipantTileStateMachine camera buffering state', () => {
- it('shows buffering while an active camera publication has no video', () => {
- expect(shouldShowCameraBuffering(cameraSignals())).toBe(true);
- });
-
- it('keeps buffering until the camera video element has rendered a frame', () => {
- expect(shouldShowCameraBuffering(cameraSignals({hasVideo: true, hasRenderedVideoFrame: false}))).toBe(true);
- });
-
- it('keeps non-camera, placeholder, hidden, disabled, inactive, and rendered camera tiles out of buffering', () => {
- expect(shouldShowCameraBuffering(cameraSignals({isScreenShare: true}))).toBe(false);
- expect(shouldShowCameraBuffering(cameraSignals({isFocusedPlaceholderTile: true}))).toBe(false);
- expect(shouldShowCameraBuffering(cameraSignals({cameraLocallyDisabled: true}))).toBe(false);
- expect(shouldShowCameraBuffering(cameraSignals({isOwnCameraHidden: true}))).toBe(false);
- expect(shouldShowCameraBuffering(cameraSignals({isCameraActive: false}))).toBe(false);
- expect(shouldShowCameraBuffering(cameraSignals({hasVideo: true, hasRenderedVideoFrame: true}))).toBe(false);
- });
-});
-
-describe('VoiceParticipantTileStateMachine camera active state', () => {
- it('preserves participant camera flags for remote camera tiles', () => {
- expect(selectVoiceParticipantTileCameraActive(cameraActiveSignals({isParticipantCameraActive: true}))).toBe(true);
- });
-
- it('treats a local capture request as an active own camera tile', () => {
- expect(
- selectVoiceParticipantTileCameraActive(cameraActiveSignals({isOwnContent: true, isLocalCameraRequested: true})),
- ).toBe(true);
- });
-
- it('keeps a camera tile inactive without a publication, participant flag, or local request', () => {
- expect(selectVoiceParticipantTileCameraActive(cameraActiveSignals())).toBe(false);
- expect(selectVoiceParticipantTileCameraActive(cameraActiveSignals({isCameraTile: false}))).toBe(false);
- });
-});
-
-describe('VoiceParticipantTileStateMachine graph-derived screen share state', () => {
- it('shows the watch prompt when the graph is idle for a published remote stream', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'idle'}))).toBe('watchPrompt');
- });
-
- it('stays idle when the graph is idle and no track reference exists', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'idle', isTrackReference: false}))).toBe(
- 'idle',
- );
- });
-
- it('shows buffering while watch is desired before a subscription entry exists', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'watchDesired'}))).toBe('buffering');
- });
-
- it('shows buffering while the publication is missing but a track reference remains', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'publicationMissing'}))).toBe(
- 'buffering',
- );
- });
-
- it('shows stream ended when the publication is missing and the track is gone', () => {
- expect(
- selectVoiceParticipantTileScreenShareState(
- signals({graphTileState: 'publicationMissing', isTrackReference: false}),
- ),
- ).toBe('streamEnded');
- });
-
- it('shows buffering instead of stream ended during the republish grace window', () => {
- expect(
- selectVoiceParticipantTileScreenShareState(
- signals({graphTileState: 'publicationMissing', isTrackReference: false, isRepublishGracePending: true}),
- ),
- ).toBe('buffering');
- });
-
- it('shows buffering while attaching', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'attaching'}))).toBe('buffering');
- });
-
- it('shows buffering while subscribed and awaiting the first frame', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'subscribedAwaitingFrame'}))).toBe(
- 'buffering',
- );
- });
-
- it('renders without overlays once the graph reports rendering', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'rendering'}))).toBe('idle');
- });
-
- it('shows buffering while screen share recovery is still running', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'recovering'}))).toBe('buffering');
- expect(
- selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'recovering', isTrackReference: false})),
- ).toBe('buffering');
- });
-
- it('holds the error code back until recovery has given up', () => {
- expect(shouldShowWatchFailed(signals({graphTileState: 'recovering'}))).toBe(false);
- expect(shouldShowWatchFailed(signals({graphTileState: 'failed'}))).toBe(true);
- });
-
- it('shows the watch failed overlay when the graph reports a failure', () => {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'failed'}))).toBe('watchFailed');
- expect(
- selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'failed', isTrackReference: false})),
- ).toBe('watchFailed');
- });
-
- it('never shows the watch prompt while the graph holds watch intent', () => {
- for (const graphTileState of WATCH_INTENT_GRAPH_TILE_STATES) {
- expect(graphTileStateHoldsWatchIntent(graphTileState)).toBe(true);
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState}))).not.toBe('watchPrompt');
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState, isTrackReference: false}))).not.toBe(
- 'watchPrompt',
- );
- }
- expect(graphTileStateHoldsWatchIntent('idle')).toBe(false);
- });
-
- it('never shows failure UI while the graph reports rendering', () => {
- expect(shouldShowWatchFailed(signals({graphTileState: 'rendering'}))).toBe(false);
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'rendering'}))).not.toBe('watchFailed');
- for (const graphTileState of GRAPH_TILE_STATES) {
- if (graphTileState === 'failed') continue;
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState}))).not.toBe('watchFailed');
- }
- });
-
- it('suppresses every overlay for local, focused-placeholder, and non-screen-share tiles', () => {
- for (const graphTileState of GRAPH_TILE_STATES) {
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState, isOwnScreenShare: true}))).toBe(
- 'idle',
- );
- expect(
- selectVoiceParticipantTileScreenShareState(signals({graphTileState, isFocusedPlaceholderTile: true})),
- ).toBe('idle');
- expect(selectVoiceParticipantTileScreenShareState(signals({graphTileState, isScreenShare: false}))).toBe('idle');
- }
- });
-
- it('suppresses buffering and the watch prompt while video is locally disabled', () => {
- expect(
- selectVoiceParticipantTileScreenShareState(
- signals({graphTileState: 'watchDesired', cameraLocallyDisabled: true}),
- ),
- ).toBe('idle');
- expect(
- selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'idle', cameraLocallyDisabled: true})),
- ).toBe('idle');
- });
-
- it('keeps the watch prompt and stream ended overlays off focus presentation tiles', () => {
- expect(
- selectVoiceParticipantTileScreenShareState(signals({graphTileState: 'idle', isFocusPresentationTile: true})),
- ).toBe('idle');
- expect(
- selectVoiceParticipantTileScreenShareState(
- signals({graphTileState: 'publicationMissing', isTrackReference: false, isFocusPresentationTile: true}),
- ),
- ).toBe('idle');
- });
-});
-
-describe('VoiceParticipantTileStateMachine buffering presentation', () => {
- it('shows the dimmed last frame while buffering with a retained frame', () => {
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'publicationMissing', isRepublishGracePending: true}),
- hasRetainedLastFrame: true,
- }),
- ).toBe('last-frame');
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'attaching'}),
- hasRetainedLastFrame: true,
- }),
- ).toBe('last-frame');
- });
-
- it('falls back to the spinner when the stream never produced a frame', () => {
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'watchDesired'}),
- hasRetainedLastFrame: false,
- }),
- ).toBe('spinner');
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'subscribedAwaitingFrame'}),
- hasRetainedLastFrame: false,
- }),
- ).toBe('spinner');
- });
-
- it('renders nothing when the tile is not buffering', () => {
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'rendering'}),
- hasRetainedLastFrame: true,
- }),
- ).toBeNull();
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'failed'}),
- hasRetainedLastFrame: true,
- }),
- ).toBeNull();
- expect(
- selectScreenShareBufferingPresentation({
- ...signals({graphTileState: 'attaching', isOwnScreenShare: true}),
- hasRetainedLastFrame: true,
- }),
- ).toBeNull();
- });
-});
-
-const UNDERPERFORMANCE_START_AT = 1_000_000;
-
-interface UnderperformanceFeed {
- encodeFrameRate: number;
- limitationReason: ScreenShareQualityLimitationReason;
- requestedFrameRate?: number;
- trackId?: string;
- qualityChangeAt?: number;
- startAt?: number;
-}
-
-function feedUnderperformance(
- tracker: ScreenShareUnderperformanceTracker,
- count: number,
- feed: UnderperformanceFeed,
-): ScreenShareUnderperformanceReason | null {
- let reason: ScreenShareUnderperformanceReason | null = null;
- const startAt = feed.startAt ?? UNDERPERFORMANCE_START_AT;
- for (let index = 0; index < count; index += 1) {
- reason = tracker.observe({
- sample: {encodeFrameRate: feed.encodeFrameRate, limitationReason: feed.limitationReason},
- requestedFrameRate: feed.requestedFrameRate ?? 30,
- trackId: feed.trackId ?? 'track-a',
- qualityChangeAt: feed.qualityChangeAt ?? 0,
- now: startAt + index * 1000,
- });
- }
- return reason;
-}
-
-describe('ScreenShareUnderperformanceTracker', () => {
- it('stays quiet until fifteen datapoints exist', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(tracker, 14, {encodeFrameRate: 5, limitationReason: 'cpu'})).toBeNull();
- expect(
- feedUnderperformance(tracker, 1, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- startAt: UNDERPERFORMANCE_START_AT + 14_000,
- }),
- ).toBe('cpu');
- });
-
- it('does not fire while the encoder holds at least half the requested rate', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(tracker, 30, {encodeFrameRate: 15, limitationReason: 'cpu'})).toBeNull();
- });
-
- it('uses an eight frame floor for low requested rates', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(
- feedUnderperformance(tracker, 15, {encodeFrameRate: 7, limitationReason: 'bandwidth', requestedFrameRate: 15}),
- ).toBe('bandwidth');
- const steady = new ScreenShareUnderperformanceTracker();
- expect(
- feedUnderperformance(steady, 15, {encodeFrameRate: 8, limitationReason: 'bandwidth', requestedFrameRate: 15}),
- ).toBeNull();
- });
-
- it('does not fire when nothing reports an active limitation', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(tracker, 30, {encodeFrameRate: 2, limitationReason: 'none'})).toBeNull();
- });
-
- it('needs a limitation on at least half of the window', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- feedUnderperformance(tracker, 8, {encodeFrameRate: 5, limitationReason: 'none'});
- expect(
- feedUnderperformance(tracker, 7, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- startAt: UNDERPERFORMANCE_START_AT + 8_000,
- }),
- ).toBeNull();
- expect(
- feedUnderperformance(tracker, 1, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- startAt: UNDERPERFORMANCE_START_AT + 15_000,
- }),
- ).toBe('cpu');
- });
-
- it('suppresses for twenty seconds after a deliberate quality change', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- const qualityChangeAt = UNDERPERFORMANCE_START_AT;
- expect(
- feedUnderperformance(tracker, 20, {encodeFrameRate: 5, limitationReason: 'cpu', qualityChangeAt}),
- ).toBeNull();
- expect(
- feedUnderperformance(tracker, 1, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- qualityChangeAt,
- startAt: UNDERPERFORMANCE_START_AT + 20_000,
- }),
- ).toBe('cpu');
- });
-
- it('adds no grace period of its own when tracking starts long after the last change', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(
- feedUnderperformance(tracker, 15, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- qualityChangeAt: UNDERPERFORMANCE_START_AT - 60_000,
- }),
- ).toBe('cpu');
- });
-
- it('starts over when the requested rate, the track or the change timestamp moves', () => {
- const byRate = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(byRate, 15, {encodeFrameRate: 5, limitationReason: 'cpu'})).toBe('cpu');
- expect(
- feedUnderperformance(byRate, 1, {encodeFrameRate: 5, limitationReason: 'cpu', requestedFrameRate: 60}),
- ).toBeNull();
- const byTrack = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(byTrack, 15, {encodeFrameRate: 5, limitationReason: 'cpu'})).toBe('cpu');
- expect(
- feedUnderperformance(byTrack, 1, {encodeFrameRate: 5, limitationReason: 'cpu', trackId: 'track-b'}),
- ).toBeNull();
- const byChange = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(byChange, 15, {encodeFrameRate: 5, limitationReason: 'cpu'})).toBe('cpu');
- expect(
- feedUnderperformance(byChange, 1, {
- encodeFrameRate: 5,
- limitationReason: 'cpu',
- qualityChangeAt: UNDERPERFORMANCE_START_AT - 60_000,
- }),
- ).toBeNull();
- });
-
- it('names the limitation reported most often', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- feedUnderperformance(tracker, 7, {encodeFrameRate: 5, limitationReason: 'cpu'});
- expect(
- feedUnderperformance(tracker, 8, {
- encodeFrameRate: 5,
- limitationReason: 'bandwidth',
- startAt: UNDERPERFORMANCE_START_AT + 7_000,
- }),
- ).toBe('bandwidth');
- const other = new ScreenShareUnderperformanceTracker();
- feedUnderperformance(other, 7, {encodeFrameRate: 5, limitationReason: 'bandwidth'});
- expect(
- feedUnderperformance(other, 8, {
- encodeFrameRate: 5,
- limitationReason: 'other',
- startAt: UNDERPERFORMANCE_START_AT + 7_000,
- }),
- ).toBe('other');
- });
-
- it('falls back to the long window when the short one is inconclusive', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- feedUnderperformance(tracker, 15, {encodeFrameRate: 2, limitationReason: 'cpu'});
- expect(
- feedUnderperformance(tracker, 15, {
- encodeFrameRate: 16,
- limitationReason: 'cpu',
- startAt: UNDERPERFORMANCE_START_AT + 15_000,
- }),
- ).toBe('cpu');
- });
-
- it('does not latch once the encoder recovers', () => {
- const tracker = new ScreenShareUnderperformanceTracker();
- expect(feedUnderperformance(tracker, 15, {encodeFrameRate: 5, limitationReason: 'cpu'})).toBe('cpu');
- expect(
- feedUnderperformance(tracker, 30, {
- encodeFrameRate: 30,
- limitationReason: 'none',
- startAt: UNDERPERFORMANCE_START_AT + 15_000,
- }),
- ).toBeNull();
- });
-});
-
-describe('applied screen share frame rate records', () => {
- it('returns the frame rate recorded for a track and nothing for other tracks', () => {
- noteAppliedScreenShareFrameRate('record-a', 60);
- expect(getAppliedScreenShareFrameRate('record-a')).toBe(60);
- expect(getAppliedScreenShareFrameRate('record-missing')).toBeNull();
- noteAppliedScreenShareFrameRate('record-a', 30);
- expect(getAppliedScreenShareFrameRate('record-a')).toBe(30);
- });
-
- it('keeps only the most recent records', () => {
- for (let index = 0; index < 9; index += 1) {
- noteAppliedScreenShareFrameRate(`record-prune-${index}`, 15 + index);
- }
- expect(getAppliedScreenShareFrameRate('record-prune-0')).toBeNull();
- expect(getAppliedScreenShareFrameRate('record-prune-1')).toBe(16);
- expect(getAppliedScreenShareFrameRate('record-prune-8')).toBe(23);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.test.ts b/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.test.ts
deleted file mode 100644
index 00ca7e0a5..000000000
--- a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- COMPACT_HEIGHT_CHAT_AREA_RESERVATION,
- COMPACT_HEIGHT_MIN,
- resolveCompactHeightMax,
- resolveCompactHeightMaxFromLayout,
-} from '@app/features/voice/components/compact_voice_call_view/CompactVoiceCallHeightBounds';
-import {describe, expect, it} from 'vitest';
-
-describe('resolveCompactHeightMax', () => {
- it('reserves chat area space below the call view so the composer remains visible', () => {
- const viewportHeight = 900;
- const max = resolveCompactHeightMax({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- viewportHeight,
- });
- expect(viewportHeight - max).toBeGreaterThanOrEqual(COMPACT_HEIGHT_CHAT_AREA_RESERVATION);
- });
- it('never goes below the minimum even in a tiny viewport', () => {
- const max = resolveCompactHeightMax({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- viewportHeight: 100,
- });
- expect(max).toBe(COMPACT_HEIGHT_MIN);
- });
- it('honors the hard cap on tall viewports', () => {
- const hardCap = 600;
- const max = resolveCompactHeightMax({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- viewportHeight: 4000,
- hardCap,
- });
- expect(max).toBe(hardCap);
- });
- it('takes the larger of viewport margin and chat reservation', () => {
- const viewportHeight = 800;
- const max = resolveCompactHeightMax({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- viewportHeight,
- chatAreaReservation: 10,
- viewportMargin: 250,
- });
- expect(viewportHeight - max).toBe(250);
- });
-});
-
-describe('resolveCompactHeightMaxFromLayout', () => {
- it('reserves the measured chat height so the composer stays visible', () => {
- const availableSpan = 900;
- const chatReservation = 420;
- const max = resolveCompactHeightMaxFromLayout({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- availableSpan,
- chatReservation,
- });
- expect(max).toBe(availableSpan - chatReservation);
- expect(availableSpan - max).toBeGreaterThanOrEqual(chatReservation);
- });
- it('never goes below the minimum when the chat reservation dominates', () => {
- const max = resolveCompactHeightMaxFromLayout({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- availableSpan: 500,
- chatReservation: 480,
- });
- expect(max).toBe(COMPACT_HEIGHT_MIN);
- });
- it('honors the hard cap on tall layouts', () => {
- const hardCap = 600;
- const max = resolveCompactHeightMaxFromLayout({
- compactHeightMin: COMPACT_HEIGHT_MIN,
- availableSpan: 4000,
- chatReservation: 200,
- hardCap,
- });
- expect(max).toBe(hardCap);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallLayoutMetrics.test.ts b/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallLayoutMetrics.test.ts
deleted file mode 100644
index e1b5f0f0d..000000000
--- a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallLayoutMetrics.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getCompactAudioAvatarLayoutStyle,
- resolveCompactAudioAvatarLayoutMetrics,
- resolveCompactControlGap,
- resolveCompactEdgeGradientExtension,
-} from '@app/features/voice/components/compact_voice_call_view/CompactVoiceCallLayoutMetrics';
-import {describe, expect, it} from 'vitest';
-
-describe('CompactVoiceCallLayoutMetrics', () => {
- it('keeps the avatar row out of the compact footer gradient when controls are visible', () => {
- const metrics = resolveCompactAudioAvatarLayoutMetrics({
- callHeight: 320,
- controlBarHeight: 84,
- hasControlBar: true,
- });
- expect(metrics.gradientExtension).toBeCloseTo(resolveCompactEdgeGradientExtension(320, true), 5);
- expect(metrics.controlGap).toBeCloseTo(resolveCompactControlGap(320), 5);
- expect(metrics.bottomPadding).toBeCloseTo(
- metrics.controlHeight + metrics.gradientExtension + metrics.controlGap,
- 5,
- );
- expect(metrics.bottomPadding).toBeGreaterThan(metrics.topPadding);
- expect(metrics.topPadding).toBeLessThan(metrics.bottomPadding * 0.35);
- });
- it('uses a modest top inset instead of mirroring the full control reserve', () => {
- for (const callHeight of [220, 280, 320, 420, 560]) {
- const metrics = resolveCompactAudioAvatarLayoutMetrics({
- callHeight,
- controlBarHeight: 88,
- hasControlBar: true,
- });
- expect(metrics.topPadding).toBeGreaterThanOrEqual(metrics.edgePadding);
- expect(metrics.topPadding).toBeLessThanOrEqual(28);
- expect(metrics.topPadding).toBeLessThan(metrics.bottomPadding / 2);
- }
- });
- it('keeps the compact footer fade short across resizable heights', () => {
- const extensions = [180, 240, 320, 480, 720].map(
- (callHeight) =>
- resolveCompactAudioAvatarLayoutMetrics({
- callHeight,
- controlBarHeight: 84,
- hasControlBar: true,
- }).gradientExtension,
- );
- expect(extensions[0]).toBe(14);
- expect(Math.max(...extensions)).toBeLessThanOrEqual(22);
- expect(extensions).toEqual([...extensions].sort((a, b) => a - b));
- });
- it('centers avatar fallback padding when there is no control bar overlay', () => {
- for (const callHeight of [220, 320, 640]) {
- const metrics = resolveCompactAudioAvatarLayoutMetrics({callHeight, hasControlBar: false});
- expect(metrics.controlHeight).toBe(0);
- expect(metrics.topPadding).toBe(metrics.bottomPadding);
- expect(metrics.gradientExtension).toBeLessThanOrEqual(20);
- }
- });
- it('accounts for safe-area bottom insets without making the fade taller', () => {
- const plain = resolveCompactAudioAvatarLayoutMetrics({
- callHeight: 320,
- hasControlBar: true,
- });
- const inset = resolveCompactAudioAvatarLayoutMetrics({
- callHeight: 320,
- hasControlBar: true,
- safeAreaBottom: 28,
- });
- expect(inset.controlHeight - plain.controlHeight).toBe(28);
- expect(inset.bottomPadding - plain.bottomPadding).toBeCloseTo(28, 5);
- expect(inset.gradientExtension).toBe(plain.gradientExtension);
- expect(inset.topPadding).toBe(plain.topPadding);
- });
- it('serializes stable CSS variables for the compact call container', () => {
- const metrics = resolveCompactAudioAvatarLayoutMetrics({
- callHeight: 320,
- controlBarHeight: 84,
- hasControlBar: true,
- });
- expect(getCompactAudioAvatarLayoutStyle(metrics)).toEqual({
- '--compact-call-audio-avatar-padding-top': '21px',
- '--compact-call-audio-avatar-padding-bottom': '112px',
- '--compact-call-edge-gradient-extension': '17px',
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallPresentationStateMachine.test.ts b/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallPresentationStateMachine.test.ts
deleted file mode 100644
index b980657f3..000000000
--- a/fluxer_app/src/features/voice/components/compact_voice_call_view/CompactVoiceCallPresentationStateMachine.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type CompactVoiceCallPresentationInput,
- type CompactVoiceCallPresentationMachineSnapshot,
- createCompactVoiceCallPresentationSnapshot,
- getCompactVoiceCallPresentationStateValue,
- resolveCompactVoiceCallPresentationModel,
- selectCompactVoiceCallPresentationModel,
- transitionCompactVoiceCallPresentationSnapshot,
-} from '@app/features/voice/components/compact_voice_call_view/CompactVoiceCallPresentationStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function update(
- snapshot: CompactVoiceCallPresentationMachineSnapshot,
- input: CompactVoiceCallPresentationInput,
-): CompactVoiceCallPresentationMachineSnapshot {
- return transitionCompactVoiceCallPresentationSnapshot(snapshot, {
- type: 'presentation.update',
- input,
- });
-}
-
-describe('CompactVoiceCallPresentationStateMachine', () => {
- it('renders compact call layout when live media is available', () => {
- const model = resolveCompactVoiceCallPresentationModel({
- hasRenderableCallMedia: true,
- showAvatarFallback: true,
- });
- expect(model).toEqual({
- stateValue: 'compactCallLayout',
- shouldRenderCallLayout: true,
- useFullHeightCallLayout: false,
- shouldShowAvatarFallback: false,
- shouldForceFloatingHudVisible: false,
- });
- });
-
- it('renders full-height call layout before media arrives when fillHeight owns the available space', () => {
- const snapshot = createCompactVoiceCallPresentationSnapshot({
- fillHeight: true,
- hasRenderableCallMedia: false,
- showAvatarFallback: true,
- });
- expect(getCompactVoiceCallPresentationStateValue(snapshot)).toBe('fullHeightCallLayout');
- expect(selectCompactVoiceCallPresentationModel(snapshot)).toMatchObject({
- shouldRenderCallLayout: true,
- useFullHeightCallLayout: true,
- shouldShowAvatarFallback: false,
- });
- });
-
- it('keeps audio-only calls on avatar fallback even when tracks or fillHeight are present', () => {
- const model = resolveCompactVoiceCallPresentationModel({
- audioOnly: true,
- fillHeight: true,
- hasRenderableCallMedia: true,
- showAvatarFallback: true,
- });
- expect(model.stateValue).toBe('avatarFallback');
- expect(model.shouldRenderCallLayout).toBe(false);
- expect(model.shouldShowAvatarFallback).toBe(true);
- expect(model.shouldForceFloatingHudVisible).toBe(true);
- });
-
- it('renders no media content when neither call layout nor avatar fallback is allowed', () => {
- const model = resolveCompactVoiceCallPresentationModel({
- hasRenderableCallMedia: false,
- showAvatarFallback: false,
- });
- expect(model).toEqual({
- stateValue: 'empty',
- shouldRenderCallLayout: false,
- useFullHeightCallLayout: false,
- shouldShowAvatarFallback: false,
- shouldForceFloatingHudVisible: false,
- });
- });
-
- it('reroutes when presentation inputs change', () => {
- let snapshot = createCompactVoiceCallPresentationSnapshot({
- showAvatarFallback: true,
- hasRenderableCallMedia: false,
- });
- expect(getCompactVoiceCallPresentationStateValue(snapshot)).toBe('avatarFallback');
- snapshot = update(snapshot, {
- showAvatarFallback: true,
- hasRenderableCallMedia: true,
- });
- expect(getCompactVoiceCallPresentationStateValue(snapshot)).toBe('compactCallLayout');
- snapshot = update(snapshot, {
- audioOnly: true,
- showAvatarFallback: false,
- hasRenderableCallMedia: true,
- });
- expect(selectCompactVoiceCallPresentationModel(snapshot)).toMatchObject({
- stateValue: 'empty',
- shouldRenderCallLayout: false,
- shouldShowAvatarFallback: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/components/media_player/MediaControlsVisibilityStateMachine.test.ts b/fluxer_app/src/features/voice/components/media_player/MediaControlsVisibilityStateMachine.test.ts
deleted file mode 100644
index 0167ae058..000000000
--- a/fluxer_app/src/features/voice/components/media_player/MediaControlsVisibilityStateMachine.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMediaControlsVisibilitySnapshot,
- getMediaControlsVisibilityValue,
- type MediaControlsVisibilityEvent,
- type MediaControlsVisibilitySignals,
- type MediaControlsVisibilitySnapshot,
- selectMediaControlsVisible,
- transitionMediaControlsVisibilitySnapshot,
-} from '@app/features/voice/components/media_player/MediaControlsVisibilityStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<MediaControlsVisibilitySignals> = {}): MediaControlsVisibilitySignals {
- return {
- disabled: false,
- isPlaying: true,
- isInteracting: false,
- ...overrides,
- };
-}
-
-function send(
- snapshot: MediaControlsVisibilitySnapshot,
- event: MediaControlsVisibilityEvent,
-): MediaControlsVisibilitySnapshot {
- return transitionMediaControlsVisibilitySnapshot(snapshot, event);
-}
-
-describe('MediaControlsVisibilityStateMachine', () => {
- it('starts visible and can be explicitly shown or hidden while media is playing', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(true);
-
- snapshot = send(snapshot, {type: 'controls.hide'});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('hidden');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(false);
-
- snapshot = send(snapshot, {type: 'controls.show'});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(true);
- });
-
- it('keeps controls visible when disabled, paused, or interacting', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- snapshot = send(snapshot, {type: 'controls.hide'});
-
- expect(selectMediaControlsVisible(snapshot, signals({disabled: true}))).toBe(true);
- expect(selectMediaControlsVisible(snapshot, signals({isPlaying: false}))).toBe(true);
- expect(selectMediaControlsVisible(snapshot, signals({isInteracting: true}))).toBe(true);
- });
-
- it('lets a resting pointer inside the player still lose the controls', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- snapshot = send(snapshot, {type: 'controls.mouseEnter'});
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(true);
-
- snapshot = send(snapshot, {type: 'controls.hide'});
-
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('hidden');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(false);
- });
-
- it('hides on pointer leave only while playback is active and not interacting', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- snapshot = send(snapshot, {type: 'controls.mouseLeave', signals: signals({isInteracting: true})});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
-
- snapshot = send(snapshot, {type: 'controls.mouseLeave', signals: signals({isPlaying: false})});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
-
- snapshot = send(snapshot, {type: 'controls.mouseLeave', signals: signals()});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('hidden');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(false);
- });
-
- it('reveals hidden controls on mouse move', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- snapshot = send(snapshot, {type: 'controls.hide'});
- snapshot = send(snapshot, {type: 'controls.mouseMove'});
-
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
- expect(selectMediaControlsVisible(snapshot, signals())).toBe(true);
- });
-
- it('toggles on touch while playing and otherwise reveals controls', () => {
- let snapshot = createMediaControlsVisibilitySnapshot();
- snapshot = send(snapshot, {type: 'controls.touchStart', signals: signals()});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('hidden');
-
- snapshot = send(snapshot, {type: 'controls.touchStart', signals: signals()});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
-
- snapshot = send(snapshot, {type: 'controls.touchStart', signals: signals({isInteracting: true})});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
-
- snapshot = send(snapshot, {type: 'controls.hide'});
- snapshot = send(snapshot, {type: 'controls.touchStart', signals: signals({isPlaying: false})});
- expect(getMediaControlsVisibilityValue(snapshot)).toBe('visible');
- });
-});
diff --git a/fluxer_app/src/features/voice/components/media_player/VideoPlayerRenderStateMachine.test.ts b/fluxer_app/src/features/voice/components/media_player/VideoPlayerRenderStateMachine.test.ts
deleted file mode 100644
index b2a3ced67..000000000
--- a/fluxer_app/src/features/voice/components/media_player/VideoPlayerRenderStateMachine.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVideoPlayerRenderSnapshot,
- selectVideoPlayerPlayPauseIndicator,
- selectVideoPlayerRenderModel,
- transitionVideoPlayerRenderSnapshot,
- type VideoPlayerRenderSignals,
- type VideoPlayerRenderSnapshot,
-} from '@app/features/voice/components/media_player/VideoPlayerRenderStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<VideoPlayerRenderSignals> = {}): VideoPlayerRenderSignals {
- return {
- autoPlay: false,
- hasPlayed: false,
- wantsMetadata: false,
- isPlaying: false,
- isPaused: true,
- isEnded: false,
- hasError: false,
- ...overrides,
- };
-}
-
-function observePlayback(
- snapshot: VideoPlayerRenderSnapshot,
- hasPlayed: boolean,
- isPlaying: boolean,
-): VideoPlayerRenderSnapshot {
- return transitionVideoPlayerRenderSnapshot(snapshot, {
- type: 'video.observePlayback',
- signals: {hasPlayed, isPlaying},
- });
-}
-
-describe('VideoPlayerRenderStateMachine', () => {
- it('keeps source detached and shows the poster before non-autoplay playback starts', () => {
- const model = selectVideoPlayerRenderModel(signals());
-
- expect(model.renderState).toBe('poster');
- expect(model.shouldAttachSource).toBe(false);
- expect(model.shouldHideVideo).toBe(true);
- expect(model.shouldShowPosterOverlay).toBe(true);
- expect(model.shouldShowControlsOverlay).toBe(false);
- });
-
- it('attaches source and controls after the initial play intent', () => {
- const model = selectVideoPlayerRenderModel(signals({hasPlayed: true}));
-
- expect(model.renderState).toBe('paused');
- expect(model.shouldAttachSource).toBe(true);
- expect(model.shouldHideVideo).toBe(false);
- expect(model.shouldShowPosterOverlay).toBe(false);
- expect(model.shouldShowControlsOverlay).toBe(true);
- });
-
- it('matches the existing autoplay prop branch before a played signal is recorded', () => {
- const model = selectVideoPlayerRenderModel(signals({autoPlay: true}));
-
- expect(model.renderState).toBe('paused');
- expect(model.shouldAttachSource).toBe(false);
- expect(model.shouldHideVideo).toBe(true);
- expect(model.shouldShowPosterOverlay).toBe(false);
- expect(model.shouldShowControlsOverlay).toBe(true);
- });
-
- it('prioritizes ended and error render states over base playback flags', () => {
- expect(selectVideoPlayerRenderModel(signals({hasPlayed: true, isPlaying: true})).renderState).toBe('playing');
- expect(selectVideoPlayerRenderModel(signals({hasPlayed: true, isPaused: true, isEnded: true})).renderState).toBe(
- 'ended',
- );
- const errorModel = selectVideoPlayerRenderModel(signals({hasPlayed: true, isPlaying: true, hasError: true}));
- expect(errorModel.renderState).toBe('error');
- });
-
- it('does not emit a play/pause indicator for the first playback observation', () => {
- const snapshot = observePlayback(createVideoPlayerRenderSnapshot(), true, false);
-
- expect(selectVideoPlayerPlayPauseIndicator(snapshot)).toBeNull();
- });
-
- it('emits play and pause indicators only after playback has started', () => {
- let snapshot = createVideoPlayerRenderSnapshot();
- snapshot = observePlayback(snapshot, true, false);
- snapshot = observePlayback(snapshot, true, true);
- expect(selectVideoPlayerPlayPauseIndicator(snapshot)).toBe('play');
-
- snapshot = observePlayback(snapshot, true, false);
- expect(selectVideoPlayerPlayPauseIndicator(snapshot)).toBe('pause');
- });
-
- it('updates the previous playback value without flashing before first play', () => {
- let snapshot = createVideoPlayerRenderSnapshot();
- snapshot = observePlayback(snapshot, false, false);
- snapshot = observePlayback(snapshot, false, true);
- expect(selectVideoPlayerPlayPauseIndicator(snapshot)).toBeNull();
-
- snapshot = observePlayback(snapshot, true, true);
- expect(selectVideoPlayerPlayPauseIndicator(snapshot)).toBeNull();
- });
-});
-
-describe('video player preload rungs', () => {
- it('holds a resting player at the bottom rung with nothing attached', () => {
- const model = selectVideoPlayerRenderModel(signals());
-
- expect(model.shouldAttachSource).toBe(false);
- expect(model.preloadAttribute).toBe('none');
- });
-
- it('climbs to the metadata rung on interest without committing to playback', () => {
- const model = selectVideoPlayerRenderModel(signals({wantsMetadata: true}));
-
- expect(model.shouldAttachSource).toBe(true);
- expect(model.preloadAttribute).toBe('metadata');
- expect(model.shouldHideVideo).toBe(true);
- expect(model.shouldShowPosterOverlay).toBe(true);
- });
-
- it('hands the element over to the browser once playback has started', () => {
- const model = selectVideoPlayerRenderModel(signals({hasPlayed: true, wantsMetadata: true}));
-
- expect(model.shouldAttachSource).toBe(true);
- expect(model.preloadAttribute).toBeUndefined();
- });
-
- it('does not climb back down when playback pauses', () => {
- const model = selectVideoPlayerRenderModel(
- signals({hasPlayed: true, wantsMetadata: true, isPlaying: false, isPaused: true}),
- );
-
- expect(model.shouldAttachSource).toBe(true);
- expect(model.preloadAttribute).toBeUndefined();
- });
-
- it('keeps an autoplaying player off the metadata rung, since it goes straight to playback', () => {
- const resting = selectVideoPlayerRenderModel(signals({autoPlay: true}));
- const playing = selectVideoPlayerRenderModel(signals({autoPlay: true, hasPlayed: true}));
-
- expect(resting.preloadAttribute).toBe('none');
- expect(playing.preloadAttribute).toBeUndefined();
- });
-
- it('separates the three rungs from one another', () => {
- const rungs = [
- selectVideoPlayerRenderModel(signals()).preloadAttribute,
- selectVideoPlayerRenderModel(signals({wantsMetadata: true})).preloadAttribute,
- selectVideoPlayerRenderModel(signals({hasPlayed: true})).preloadAttribute,
- ];
-
- expect(rungs).toEqual(['none', 'metadata', undefined]);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.test.ts b/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.test.ts
deleted file mode 100644
index c1cabb475..000000000
--- a/fluxer_app/src/features/voice/components/media_player/utils/MediaSeekUtils.test.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {isAutoplayBlockedError} from '@app/features/voice/components/media_player/hooks/useMediaPlayer';
-import {
- areBufferedSpanFractionsEqual,
- armPendingSeekTarget,
- clampMediaTime,
- clampPercentage,
- clearPendingSeekTarget,
- collectBufferedSpanFractions,
- detachMediaElementSource,
- getBufferedPercentage,
- getEffectiveMediaDuration,
- getSeekPercentageFromClientX,
- readPendingSeekTarget,
- resolveDoubleTapSeekDirection,
- stepPlayheadPrediction,
-} from '@app/features/voice/components/media_player/utils/MediaSeekUtils';
-import {afterEach, describe, expect, it} from 'vitest';
-
-function mediaWithBufferedRanges({
- duration,
- currentTime,
- ranges,
-}: {
- duration: number;
- currentTime: number;
- ranges: Array<[number, number]>;
-}): HTMLMediaElement {
- return {
- duration,
- currentTime,
- buffered: {
- length: ranges.length,
- start: (index: number) => ranges[index]![0],
- end: (index: number) => ranges[index]![1],
- },
- } as unknown as HTMLMediaElement;
-}
-
-describe('MediaSeekUtils', () => {
- it('clamps progress and time values', () => {
- expect(clampPercentage(-25)).toBe(0);
- expect(clampPercentage(42)).toBe(42);
- expect(clampPercentage(125)).toBe(100);
- expect(clampPercentage(Number.NaN)).toBe(0);
-
- expect(clampMediaTime(-5, 100)).toBe(0);
- expect(clampMediaTime(30, 100)).toBe(30);
- expect(clampMediaTime(130, 100)).toBe(100);
- });
-
- it('maps pointer coordinates to a clamped seek percentage', () => {
- const rect = {left: 20, width: 200};
-
- expect(getSeekPercentageFromClientX(20, rect)).toBe(0);
- expect(getSeekPercentageFromClientX(120, rect)).toBe(50);
- expect(getSeekPercentageFromClientX(260, rect)).toBe(100);
- expect(getSeekPercentageFromClientX(-10, rect)).toBe(0);
- });
-
- it('uses the active buffered range when available', () => {
- const media = mediaWithBufferedRanges({
- duration: 100,
- currentTime: 25,
- ranges: [
- [0, 10],
- [20, 40],
- [60, 80],
- ],
- });
-
- expect(getBufferedPercentage(media)).toBe(40);
- });
-
- it('falls back to the furthest buffered range outside the active range', () => {
- const media = mediaWithBufferedRanges({
- duration: 100,
- currentTime: 50,
- ranges: [
- [0, 10],
- [20, 40],
- [60, 80],
- ],
- });
-
- expect(getBufferedPercentage(media)).toBe(80);
- });
-
- it('detects same-side double taps for mobile video seeking', () => {
- const first = {x: 20, width: 100, time: 1000};
-
- expect(resolveDoubleTapSeekDirection(first, {x: 24, width: 100, time: 1200})).toBe('backward');
- expect(resolveDoubleTapSeekDirection({x: 90, width: 100, time: 1000}, {x: 84, width: 100, time: 1200})).toBe(
- 'forward',
- );
- expect(resolveDoubleTapSeekDirection(first, {x: 50, width: 100, time: 1200})).toBeNull();
- expect(resolveDoubleTapSeekDirection(first, {x: 24, width: 100, time: 1500})).toBeNull();
- });
-});
-
-describe('detachMediaElementSource', () => {
- const loadedElements: Array<HTMLMediaElement> = [];
- let restoreLoad: (() => void) | null = null;
-
- const stubLoad = (implementation: (element: HTMLMediaElement) => void): void => {
- const prototype = window.HTMLMediaElement.prototype;
- const original = Object.getOwnPropertyDescriptor(prototype, 'load');
- Object.defineProperty(prototype, 'load', {
- configurable: true,
- writable: true,
- value: function (this: HTMLMediaElement) {
- implementation(this);
- },
- });
- restoreLoad = () => {
- if (original) Object.defineProperty(prototype, 'load', original);
- else Reflect.deleteProperty(prototype as unknown as Record<string, unknown>, 'load');
- };
- };
-
- const buildVideoWithChildren = (): HTMLVideoElement => {
- const video = document.createElement('video');
- video.setAttribute('src', 'https://media.test/clip.mp4');
- const source = document.createElement('source');
- source.setAttribute('src', 'https://media.test/clip.webm');
- source.setAttribute('type', 'video/webm');
- const poster = document.createElement('img');
- poster.setAttribute('src', 'https://media.test/poster.webp');
- video.append(source, poster);
- document.body.append(video);
- return video;
- };
-
- afterEach(() => {
- loadedElements.length = 0;
- restoreLoad?.();
- restoreLoad = null;
- document.body.innerHTML = '';
- });
-
- it('strips every url off the element and its children and then reloads it', () => {
- stubLoad((element) => loadedElements.push(element));
- const video = buildVideoWithChildren();
-
- detachMediaElementSource(video);
-
- expect(video.getAttribute('src')).toBeNull();
- expect(video.querySelector('source')?.getAttribute('src')).toBeNull();
- expect(video.querySelector('source')?.getAttribute('type')).toBeNull();
- expect(video.querySelector('img')?.getAttribute('src')).toBeNull();
- expect(loadedElements).toEqual([video]);
- });
-
- it('still clears the urls when the element refuses to reload', () => {
- stubLoad(() => {
- throw new Error('load is not implemented');
- });
- const video = buildVideoWithChildren();
-
- expect(() => detachMediaElementSource(video)).not.toThrow();
- expect(video.getAttribute('src')).toBeNull();
- expect(video.querySelector('source')?.getAttribute('src')).toBeNull();
- });
-
- it('does nothing when there is no element left to release', () => {
- stubLoad((element) => loadedElements.push(element));
-
- expect(() => detachMediaElementSource(null)).not.toThrow();
- expect(loadedElements).toEqual([]);
- });
-});
-
-describe('buffered ranges shorter than a second', () => {
- it('ignores a sliver that would otherwise become the reported buffer', () => {
- const media = mediaWithBufferedRanges({
- duration: 100,
- currentTime: 50,
- ranges: [
- [0, 10],
- [60, 60.4],
- ],
- });
-
- expect(getBufferedPercentage(media)).toBe(10);
- });
-
- it('ignores a sliver even when the playhead sits inside it', () => {
- const media = mediaWithBufferedRanges({
- duration: 100,
- currentTime: 60.2,
- ranges: [
- [0, 10],
- [60, 60.4],
- ],
- });
-
- expect(getBufferedPercentage(media)).toBe(10);
- });
-});
-
-describe('isAutoplayBlockedError', () => {
- it('recognises only the browser refusing to start playback', () => {
- expect(isAutoplayBlockedError(new DOMException('blocked', 'NotAllowedError'))).toBe(true);
- expect(isAutoplayBlockedError(new DOMException('no source', 'NotSupportedError'))).toBe(false);
- expect(isAutoplayBlockedError(new Error('NotAllowedError'))).toBe(false);
- expect(isAutoplayBlockedError('NotAllowedError')).toBe(false);
- expect(isAutoplayBlockedError(null)).toBe(false);
- });
-});
-
-describe('collectBufferedSpanFractions', () => {
- it('emits one normalised span per disjoint buffered island, so the bar can leave the gap between them unpainted', () => {
- const media = mediaWithBufferedRanges({
- duration: 120,
- currentTime: 0,
- ranges: [
- [0, 30],
- [60, 90],
- ],
- });
-
- expect(collectBufferedSpanFractions(media)).toStrictEqual([
- {offset: 0, span: 0.25},
- {offset: 0.5, span: 0.25},
- ]);
- });
-
- it('drops a buffered island shorter than the minimum, so a sliver never paints as an island of its own', () => {
- const media = mediaWithBufferedRanges({
- duration: 120,
- currentTime: 0,
- ranges: [
- [0, 30],
- [60, 60.5],
- [90, 120],
- ],
- });
-
- expect(collectBufferedSpanFractions(media)).toStrictEqual([
- {offset: 0, span: 0.25},
- {offset: 0.75, span: 0.25},
- ]);
- });
-
- it('emits nothing while the duration is still unknown, so the bar does not paint against a NaN denominator', () => {
- const media = mediaWithBufferedRanges({duration: Number.NaN, currentTime: 0, ranges: [[0, 30]]});
-
- expect(collectBufferedSpanFractions(media)).toStrictEqual([]);
- });
-
- it('never lets a span run past the end of the track', () => {
- const media = mediaWithBufferedRanges({duration: 100, currentTime: 0, ranges: [[80, 400]]});
-
- const spans = collectBufferedSpanFractions(media);
-
- expect(spans).toHaveLength(1);
- expect(spans[0]!.offset + spans[0]!.span).toBe(1);
- });
-});
-
-describe('areBufferedSpanFractionsEqual', () => {
- it('reports two separately built span lists with the same contents as equal, so an unchanged buffer commits nothing', () => {
- expect(
- areBufferedSpanFractionsEqual(
- [
- {offset: 0, span: 0.25},
- {offset: 0.5, span: 0.25},
- ],
- [
- {offset: 0, span: 0.25},
- {offset: 0.5, span: 0.25},
- ],
- ),
- ).toBe(true);
- });
-
- it('reports a grown island as different, so real buffering progress still repaints', () => {
- expect(areBufferedSpanFractionsEqual([{offset: 0, span: 0.25}], [{offset: 0, span: 0.3}])).toBe(false);
- });
-
- it('reports a moved island as different, so a span that slid along the track still repaints', () => {
- expect(areBufferedSpanFractionsEqual([{offset: 0, span: 0.25}], [{offset: 0.1, span: 0.25}])).toBe(false);
- });
-
- it('reports a new island as different, so a second island appearing still repaints', () => {
- expect(
- areBufferedSpanFractionsEqual(
- [{offset: 0, span: 0.25}],
- [
- {offset: 0, span: 0.25},
- {offset: 0.5, span: 0.25},
- ],
- ),
- ).toBe(false);
- });
-});
-
-describe('the pending seek latch', () => {
- it('hands the armed target back to a reader that only holds the element', () => {
- const media = document.createElement('audio');
-
- armPendingSeekTarget(media, 42);
-
- expect(readPendingSeekTarget(media)).toBe(42);
- });
-
- it('keeps each element on its own latch, so seeking one player does not suppress another', () => {
- const seeking = document.createElement('audio');
- const idle = document.createElement('audio');
-
- armPendingSeekTarget(seeking, 42);
-
- expect(readPendingSeekTarget(idle)).toBeNull();
- });
-
- it('reads back null once the latch is cleared, so a settled seek stops suppressing time updates', () => {
- const media = document.createElement('audio');
- armPendingSeekTarget(media, 42);
-
- clearPendingSeekTarget(media);
-
- expect(readPendingSeekTarget(media)).toBeNull();
- });
-
- it('treats a target of zero as armed rather than as an empty latch', () => {
- const media = document.createElement('audio');
-
- armPendingSeekTarget(media, 0);
-
- expect(readPendingSeekTarget(media)).toBe(0);
- });
-});
-
-describe('stepPlayheadPrediction', () => {
- it('seeds the prediction from the element clock on the first frame, when there is nothing to predict from yet', () => {
- expect(stepPlayheadPrediction({predictedSeconds: null, actualSeconds: 12.25, elapsedSeconds: 0})).toBe(12.25);
- });
-
- it('advances the prediction by the wall-clock delta between frames while the element clock stands still', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10, elapsedSeconds: 0.1})).toBeCloseTo(
- 10.09,
- 10,
- );
- });
-
- it('scales the advance by the playback rate, so a double-speed frame predicts twice the wall-clock delta', () => {
- expect(
- stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10, elapsedSeconds: 0.1, playbackRate: 2}),
- ).toBeCloseTo(10.18, 10);
- });
-
- it('closes a tenth of a small error toward the element clock rather than jumping to it', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10.3, elapsedSeconds: 0.1})).toBeCloseTo(
- 10.12,
- 10,
- );
- });
-
- it('hard-snaps to the element clock when a seek moves it further than the snap threshold', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 40, elapsedSeconds: 0.016})).toBe(40);
- });
-
- it('hard-snaps a drift just over half a second rather than converging on it', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10.6, elapsedSeconds: 0})).toBe(10.6);
- });
-
- it('converges on a drift just under half a second rather than snapping to it', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10.4, elapsedSeconds: 0})).toBeCloseTo(
- 10.04,
- 10,
- );
- });
-
- it('converges on a drift sitting exactly on the snap threshold rather than snapping to it', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: 10.5, elapsedSeconds: 0})).toBeCloseTo(
- 10.05,
- 10,
- );
- });
-
- it('hard-snaps backwards too, so a seek to the head of the media does not creep back over many frames', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 30, actualSeconds: 0, elapsedSeconds: 0.016})).toBe(0);
- });
-
- it('keeps predicting from the last prediction when the element clock reads a non-finite value', () => {
- expect(stepPlayheadPrediction({predictedSeconds: 10, actualSeconds: Number.NaN, elapsedSeconds: 0.5})).toBeCloseTo(
- 10.5,
- 10,
- );
- });
-
- it('never predicts a negative playhead', () => {
- expect(stepPlayheadPrediction({predictedSeconds: null, actualSeconds: -5, elapsedSeconds: 0})).toBe(0);
- });
-});
-
-describe('getEffectiveMediaDuration', () => {
- it('reports the length the element itself knows, ignoring the supplied fallback', () => {
- expect(getEffectiveMediaDuration({duration: 90} as HTMLMediaElement, 120)).toBe(90);
- });
-
- it('falls back to the supplied length while the element still reports none, so a fresh element still has a scale', () => {
- expect(getEffectiveMediaDuration({duration: Number.NaN} as HTMLMediaElement, 120)).toBe(120);
- });
-
- it('reports no length at all when the fallback runs past every real value, rather than scaling against infinity', () => {
- expect(getEffectiveMediaDuration(null, Number.POSITIVE_INFINITY)).toBe(0);
- });
-
- it('reports no length at all when the fallback is negative, rather than scaling against a backwards duration', () => {
- expect(getEffectiveMediaDuration(null, -30)).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/ScreenSharePickerDisplayPermissionStateMachine.test.ts b/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/ScreenSharePickerDisplayPermissionStateMachine.test.ts
deleted file mode 100644
index dc6ce816f..000000000
--- a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/ScreenSharePickerDisplayPermissionStateMachine.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createScreenSharePickerDisplayPermissionSnapshot,
- selectScreenSharePickerDisplayPermissionPrompt,
- transitionScreenSharePickerDisplayPermissionSnapshot,
-} from '@app/features/voice/components/modals/screen_share_picker_modal/ScreenSharePickerDisplayPermissionStateMachine';
-import {describe, expect, it} from 'vitest';
-
-describe('ScreenSharePickerDisplayPermissionStateMachine', () => {
- it('shows the permission prompt until screen recording is granted', () => {
- let snapshot = createScreenSharePickerDisplayPermissionSnapshot();
-
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('none');
-
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {type: 'permission.check'});
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('checking');
-
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {
- type: 'permission.result',
- permission: 'denied',
- });
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('needs-permission');
-
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {type: 'permission.check'});
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {
- type: 'permission.result',
- permission: 'granted',
- });
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('none');
- });
-
- it('keeps showing restart required after settings were opened', () => {
- let snapshot = createScreenSharePickerDisplayPermissionSnapshot();
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {type: 'permission.check'});
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {
- type: 'permission.result',
- permission: 'denied',
- });
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {type: 'permission.settingsOpened'});
-
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('restart-required');
-
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {type: 'permission.check'});
- snapshot = transitionScreenSharePickerDisplayPermissionSnapshot(snapshot, {
- type: 'permission.result',
- permission: 'granted',
- });
-
- expect(selectScreenSharePickerDisplayPermissionPrompt(snapshot)).toBe('restart-required');
- });
-});
diff --git a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/shared.test.ts b/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/shared.test.ts
deleted file mode 100644
index 4f5590e7e..000000000
--- a/fluxer_app/src/features/voice/components/modals/screen_share_picker_modal/shared.test.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- findNativeCaptureSourceForDesktopSource,
- getDesktopSourceThumbnailStateKey,
- hasDesktopSourcesMissingThumbnails,
- isDisplaySource,
- mergeDesktopSources,
-} from '@app/features/voice/components/modals/screen_share_picker_modal/shared';
-import type {DesktopSource, NativeScreenCaptureSource} from '@app/types/electron.d';
-import {describe, expect, test} from 'vitest';
-
-const USABLE_IMAGE_DATA_URL = 'data:image/png;base64,aW1hZ2U=';
-
-function desktopSource(overrides: Partial<DesktopSource>): DesktopSource {
- return {
- id: 'window:100:0',
- name: 'App',
- ...overrides,
- };
-}
-
-function nativeSource(overrides: Partial<NativeScreenCaptureSource>): NativeScreenCaptureSource {
- return {
- kind: 'window',
- id: '100',
- name: 'App',
- width: 1280,
- height: 720,
- ...overrides,
- };
-}
-
-describe('findNativeCaptureSourceForDesktopSource', () => {
- test('matches the selected desktopCapturer window by native window id', () => {
- const selected = desktopSource({id: 'window:5050:0', name: 'Browser'});
- const nativeSources = [
- nativeSource({id: '4040', name: 'Control Centre'}),
- nativeSource({id: '5050', name: 'Browser'}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.name).toBe('Browser');
- });
- test('matches displays by display_id instead of the sequential desktop source token', () => {
- const selected = desktopSource({
- id: 'screen:0:0',
- name: 'Entire Screen',
- display_id: '69733248',
- });
- const nativeSources = [
- nativeSource({kind: 'screen', id: '123', name: 'Display 1'}),
- nativeSource({kind: 'screen', id: '69733248', name: 'Display 2'}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.name).toBe('Display 2');
- });
- test('does not match a desktop display card to a native game capture source', () => {
- const selected = desktopSource({
- id: 'screen:0:0',
- name: 'Primary monitor',
- display_id: '69733248',
- });
- const nativeSources = [
- nativeSource({kind: 'game', id: 'screen:0:0', name: 'Fullscreen game on Primary monitor'}),
- nativeSource({kind: 'window', id: 'window:5050:0', name: 'Browser'}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)).toBeUndefined();
- });
- test('normalizes numeric native ids without matching unrelated native sources', () => {
- const selected = desktopSource({id: 'window:0x10:0', name: 'Terminal'});
- const nativeSources = [nativeSource({id: '15', name: 'System UI'}), nativeSource({id: '16', name: 'Terminal'})];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.name).toBe('Terminal');
- });
- test('falls back to a unique native window name when desktopCapturer uses a different token', () => {
- const selected = desktopSource({id: 'window:123:0', name: 'Project Notes'});
- const nativeSources = [
- nativeSource({id: '9001', name: 'Browser - Project Notes', appName: 'Browser'}),
- nativeSource({id: '9002', name: 'Music', appName: 'Music'}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.id).toBe('9001');
- });
- test('does not use a name fallback when multiple native windows match', () => {
- const selected = desktopSource({id: 'window:123:0', name: 'Project Notes'});
- const nativeSources = [
- nativeSource({id: '9001', name: 'Browser - Project Notes', appName: 'Browser'}),
- nativeSource({id: '9002', name: 'Editor - Project Notes', appName: 'Editor'}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)).toBeUndefined();
- });
- test('falls back to a native display when display ids differ but dimensions line up', () => {
- const selected = desktopSource({
- id: 'screen:0:0',
- name: 'Built-in Retina Display',
- display_id: '42',
- nativeWidth: 3024,
- nativeHeight: 1964,
- });
- const nativeSources = [
- nativeSource({kind: 'screen', id: '9001', name: 'Built-in Retina Display', width: 3024, height: 1964}),
- nativeSource({kind: 'screen', id: '9002', name: 'Studio Display', width: 5120, height: 2880}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.id).toBe('9001');
- });
- test('falls back to the native display ordinal when display ids differ', () => {
- const selected = desktopSource({
- id: 'screen:1:0',
- name: 'Screen 2',
- display_id: '42',
- nativeWidth: 1920,
- nativeHeight: 1080,
- });
- const nativeSources = [
- nativeSource({kind: 'screen', id: '9001', name: 'Display 1', width: 1920, height: 1080}),
- nativeSource({kind: 'screen', id: '9002', name: 'Display 2', width: 1920, height: 1080}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.id).toBe('9002');
- });
- test('does not fall back to a native game capture display ordinal when display ids differ', () => {
- const selected = desktopSource({
- id: 'screen:1:0',
- name: 'Screen 2',
- display_id: '42',
- nativeWidth: 1920,
- nativeHeight: 1080,
- });
- const nativeSources = [
- nativeSource({kind: 'game', id: 'screen:0:0', name: 'Game Capture Display 1', width: 1920, height: 1080}),
- nativeSource({kind: 'game', id: 'screen:1:0', name: 'Game Capture Display 2', width: 1920, height: 1080}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)).toBeUndefined();
- });
- test('falls back to a unique native display by dimensions when ids and names differ', () => {
- const selected = desktopSource({
- id: 'screen:0:0',
- name: 'Entire Screen',
- display_id: '42',
- nativeWidth: 2560,
- nativeHeight: 1440,
- });
- const nativeSources = [
- nativeSource({kind: 'screen', id: '9001', name: 'Display 1', width: 1920, height: 1080}),
- nativeSource({kind: 'screen', id: '9002', name: 'Display 2', width: 2560, height: 1440}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)?.id).toBe('9002');
- });
- test('does not use a name fallback when native dimensions disagree', () => {
- const selected = desktopSource({
- id: 'window:123:0',
- name: 'Project Notes',
- nativeWidth: 1280,
- nativeHeight: 720,
- });
- const nativeSources = [
- nativeSource({id: '9001', name: 'Browser - Project Notes', appName: 'Browser', width: 1440, height: 900}),
- ];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)).toBeUndefined();
- });
- test('returns undefined when the native source list has no exact counterpart', () => {
- const selected = desktopSource({id: 'window:777:0', name: 'Editor'});
- const nativeSources = [nativeSource({id: '1', name: 'Menubar'}), nativeSource({id: '2', name: 'Control Centre'})];
- expect(findNativeCaptureSourceForDesktopSource(selected, nativeSources)).toBeUndefined();
- });
-});
-
-describe('desktop source thumbnails', () => {
- test('detects display cards missing preview thumbnails', () => {
- const sources = [
- desktopSource({id: 'window:100:0', thumbnailDataUrl: undefined}),
- desktopSource({id: 'screen:0:0', thumbnailDataUrl: undefined}),
- desktopSource({id: 'screen:1:0', thumbnailDataUrl: USABLE_IMAGE_DATA_URL}),
- ];
- expect(hasDesktopSourcesMissingThumbnails(sources, isDisplaySource)).toBe(true);
- expect(getDesktopSourceThumbnailStateKey(sources, isDisplaySource)).toBe('screen:0:0:missing|screen:1:0:thumbnail');
- });
-
- test('does not flag display cards after each display has a usable thumbnail', () => {
- const sources = [
- desktopSource({id: 'screen:0:0', thumbnailDataUrl: USABLE_IMAGE_DATA_URL}),
- desktopSource({id: 'screen:1:0', thumbnailDataUrl: USABLE_IMAGE_DATA_URL}),
- ];
- expect(hasDesktopSourcesMissingThumbnails(sources, isDisplaySource)).toBe(false);
- expect(getDesktopSourceThumbnailStateKey(sources, isDisplaySource)).toBe(
- 'screen:0:0:thumbnail|screen:1:0:thumbnail',
- );
- });
-
- test('preserves thumbnails when merging list-only source refreshes', () => {
- const previous = [
- desktopSource({
- id: 'screen:0:0',
- name: 'Entire Screen',
- thumbnailDataUrl: USABLE_IMAGE_DATA_URL,
- }),
- ];
- const next = [
- desktopSource({
- id: 'screen:0:0',
- name: 'Entire Screen',
- thumbnailDataUrl: undefined,
- }),
- ];
- expect(mergeDesktopSources(previous, next)[0]?.thumbnailDataUrl).toBe(USABLE_IMAGE_DATA_URL);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/popout/PoppedOutSurfaceStateMachine.test.ts b/fluxer_app/src/features/voice/components/popout/PoppedOutSurfaceStateMachine.test.ts
deleted file mode 100644
index 9aa15ae8c..000000000
--- a/fluxer_app/src/features/voice/components/popout/PoppedOutSurfaceStateMachine.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createPoppedOutSurfaceSnapshot,
- isPoppedOutSurfaceTransitioning,
- type PoppedOutSurfacePhase,
- selectPoppedOutOverlayTransition,
- shouldRenderPoppedOutOverlay,
- transitionPoppedOutSurfaceSnapshot,
-} from '@app/features/voice/components/popout/PoppedOutSurfaceStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function snapshotWithPhase(phase: PoppedOutSurfacePhase) {
- return {phase};
-}
-
-describe('PoppedOutSurfaceStateMachine', () => {
- it('creates a live snapshot when not popped out', () => {
- expect(createPoppedOutSurfaceSnapshot(false)).toEqual({phase: 'live'});
- });
-
- it('creates a popped snapshot when already popped out', () => {
- expect(createPoppedOutSurfaceSnapshot(true)).toEqual({phase: 'popped'});
- });
-
- it('enters popping-out from live when the popout opens', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('live'), {
- type: 'popout.update',
- isPoppedOut: true,
- });
- expect(next.phase).toBe('popping-out');
- });
-
- it('settles into popped when the enter transition completes', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('popping-out'), {
- type: 'popout.transition-end',
- });
- expect(next.phase).toBe('popped');
- });
-
- it('enters restoring from popped when the popout closes', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('popped'), {
- type: 'popout.update',
- isPoppedOut: false,
- });
- expect(next.phase).toBe('restoring');
- });
-
- it('settles into live when the exit transition completes', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('restoring'), {
- type: 'popout.transition-end',
- });
- expect(next.phase).toBe('live');
- });
-
- it('reverses a restore in flight when the popout reopens', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('restoring'), {
- type: 'popout.update',
- isPoppedOut: true,
- });
- expect(next.phase).toBe('popping-out');
- });
-
- it('reverses a pop-out in flight when the popout closes early', () => {
- const next = transitionPoppedOutSurfaceSnapshot(snapshotWithPhase('popping-out'), {
- type: 'popout.update',
- isPoppedOut: false,
- });
- expect(next.phase).toBe('restoring');
- });
-
- it('keeps the same snapshot for redundant updates', () => {
- const live = snapshotWithPhase('live');
- expect(transitionPoppedOutSurfaceSnapshot(live, {type: 'popout.update', isPoppedOut: false})).toBe(live);
- const popped = snapshotWithPhase('popped');
- expect(transitionPoppedOutSurfaceSnapshot(popped, {type: 'popout.update', isPoppedOut: true})).toBe(popped);
- });
-
- it('ignores transition-end outside of transitional phases', () => {
- const live = snapshotWithPhase('live');
- expect(transitionPoppedOutSurfaceSnapshot(live, {type: 'popout.transition-end'})).toBe(live);
- const popped = snapshotWithPhase('popped');
- expect(transitionPoppedOutSurfaceSnapshot(popped, {type: 'popout.transition-end'})).toBe(popped);
- });
-
- it('renders the overlay in every phase except live', () => {
- expect(shouldRenderPoppedOutOverlay(snapshotWithPhase('live'))).toBe(false);
- expect(shouldRenderPoppedOutOverlay(snapshotWithPhase('popping-out'))).toBe(true);
- expect(shouldRenderPoppedOutOverlay(snapshotWithPhase('popped'))).toBe(true);
- expect(shouldRenderPoppedOutOverlay(snapshotWithPhase('restoring'))).toBe(true);
- });
-
- it('selects the overlay transition for each phase', () => {
- expect(selectPoppedOutOverlayTransition(snapshotWithPhase('popping-out'))).toBe('enter');
- expect(selectPoppedOutOverlayTransition(snapshotWithPhase('popped'))).toBe('static');
- expect(selectPoppedOutOverlayTransition(snapshotWithPhase('restoring'))).toBe('exit');
- expect(selectPoppedOutOverlayTransition(snapshotWithPhase('live'))).toBe('static');
- });
-
- it('reports transitioning only for popping-out and restoring', () => {
- expect(isPoppedOutSurfaceTransitioning(snapshotWithPhase('popping-out'))).toBe(true);
- expect(isPoppedOutSurfaceTransitioning(snapshotWithPhase('restoring'))).toBe(true);
- expect(isPoppedOutSurfaceTransitioning(snapshotWithPhase('live'))).toBe(false);
- expect(isPoppedOutSurfaceTransitioning(snapshotWithPhase('popped'))).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/useScreenShareWatchFailure.test.ts b/fluxer_app/src/features/voice/components/useScreenShareWatchFailure.test.ts
deleted file mode 100644
index 8b91777be..000000000
--- a/fluxer_app/src/features/voice/components/useScreenShareWatchFailure.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {screenShareWatchAttemptKey} from '@app/features/voice/components/useScreenShareWatchFailure';
-import {
- createVoiceMediaGraphSnapshot,
- selectVoiceMediaGraphAttempt,
- selectVoiceMediaGraphDeadline,
- transitionVoiceMediaGraph,
- type VoiceMediaGraphSnapshot,
- voiceMediaGraphAttemptKeyIsOperation,
- voiceMediaGraphWatchAttemptDeadlineKey,
- WATCH_ATTEMPT_TIMEOUT_MS,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {
- selectVoiceMediaGraphStreamTileState,
- type VoiceMediaGraphStreamTileState,
-} from '@app/features/voice/engine/VoiceMediaGraphTileState';
-import {VoiceTrackSource} from '@app/features/voice/engine/VoiceTrackSource';
-import {describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'dm:channel-a:connection-a';
-const PARTICIPANT_IDENTITY = 'user_2_connection-a';
-
-function watchAttemptKey(trackSid: string | null): string {
- return screenShareWatchAttemptKey({streamKey: STREAM_KEY, watchGeneration: 1, trackSid, operationKey: null});
-}
-
-describe('screenShareWatchAttemptKey', () => {
- it('gives a republished track its own attempt key', () => {
- expect(watchAttemptKey('TR_2')).not.toBe(watchAttemptKey('TR_1'));
- });
-
- it('puts the stream, the watch generation and the published track in the key', () => {
- expect(watchAttemptKey('TR_1')).toBe(`${STREAM_KEY}:1:TR_1:watch`);
- });
-
- it('separates a stream with no published track from one with a track', () => {
- expect(watchAttemptKey(null)).not.toBe(watchAttemptKey('TR_1'));
- });
-
- it('marks a republish buffering attempt as an operation attempt', () => {
- const buffering = screenShareWatchAttemptKey({
- streamKey: STREAM_KEY,
- watchGeneration: 1,
- trackSid: 'TR_1',
- operationKey: 'republish:3',
- });
-
- expect(voiceMediaGraphAttemptKeyIsOperation(buffering)).toBe(true);
- expect(voiceMediaGraphAttemptKeyIsOperation(watchAttemptKey('TR_1'))).toBe(false);
- });
-});
-
-function subscribedScreenShareGraph(): VoiceMediaGraphSnapshot {
- const graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'subscription.subscribe',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: null,
- context: 'focused',
- });
- return transitionVoiceMediaGraph(graph, {type: 'subscription.clearCommands'});
-}
-
-function screenShareTileState(graph: VoiceMediaGraphSnapshot): VoiceMediaGraphStreamTileState {
- return selectVoiceMediaGraphStreamTileState(graph, {
- streamKey: STREAM_KEY,
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- });
-}
-
-describe('screen share watch attempts across a republish', () => {
- it('arms a fresh first frame deadline when a new track replaces a rendered one', () => {
- const firstAttemptKey = watchAttemptKey('TR_1');
- let graph = transitionVoiceMediaGraph(subscribedScreenShareGraph(), {
- type: 'watch.started',
- streamKey: STREAM_KEY,
- at: 0,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.observed',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- trackSid: 'TR_1',
- at: 0,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_KEY,
- attemptKey: firstAttemptKey,
- startedAt: 0,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_KEY,
- attemptKey: firstAttemptKey,
- renderedAt: 500,
- });
- expect(screenShareTileState(graph)).toBe('rendering');
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.lost',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- at: 4000,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.observed',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- trackSid: 'TR_2',
- at: 4500,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_KEY,
- attemptKey: watchAttemptKey('TR_2'),
- startedAt: 4600,
- });
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_KEY)?.hasRenderedVideoFrame).toBe(false);
- expect(screenShareTileState(graph)).not.toBe('rendering');
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_KEY))?.dueAt).toBe(
- 4600 + WATCH_ATTEMPT_TIMEOUT_MS,
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/components/useScreenShareWatchFailureDeadline.test.tsx b/fluxer_app/src/features/voice/components/useScreenShareWatchFailureDeadline.test.tsx
deleted file mode 100644
index fd19a681a..000000000
--- a/fluxer_app/src/features/voice/components/useScreenShareWatchFailureDeadline.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {useScreenShareWatchFailure} from '@app/features/voice/components/useScreenShareWatchFailure';
-import {clearVideoFrameWatchersForTests} from '@app/features/voice/components/VideoElementFrameState';
-import {voiceMediaGraphStore} from '@app/features/voice/engine/VoiceMediaGraphStore';
-import {ScreenShareWatchFailures} from '@app/features/voice/state/ScreenShareWatchFailures';
-import type {RemoteTrackPublication} from 'livekit-client';
-import {act, useRef} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const STREAM_KEY = 'guild-a:channel-a:connection-watch';
-
-function WatchProbe({publication}: {publication: RemoteTrackPublication | null}) {
- const videoRef = useRef<HTMLVideoElement | null>(null);
- useScreenShareWatchFailure({
- enabled: true,
- streamKey: STREAM_KEY,
- participantIdentity: 'user_1_connection-watch',
- trackSid: 'TR_watch',
- hasPublication: publication != null,
- isPublicationDesired: publication != null,
- hasSubscribedVideo: publication != null,
- publication,
- videoRef,
- });
- return null;
-}
-
-function watchDeadlineFor(streamKey: string) {
- const snapshot = voiceMediaGraphStore.getGraphSnapshot();
- for (const deadline of snapshot.deadlinesByKey.values()) {
- if (deadline.kind === 'watchAttempt' && deadline.streamKey === streamKey) return deadline;
- }
- return null;
-}
-
-describe('useScreenShareWatchFailure', () => {
- let root: Root | null = null;
- let container: HTMLDivElement | null = null;
-
- beforeEach(() => {
- voiceMediaGraphStore.reset();
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
- });
-
- afterEach(() => {
- act(() => {
- root?.unmount();
- });
- root = null;
- container?.remove();
- container = null;
- clearVideoFrameWatchersForTests();
- });
-
- it('keeps the running watch deadline when the publication arrives after the watch started', () => {
- ScreenShareWatchFailures.markWatchStarted(STREAM_KEY);
- act(() => {
- root?.render(<WatchProbe publication={null} />);
- });
- const deadline = watchDeadlineFor(STREAM_KEY);
- expect(deadline).not.toBeNull();
-
- act(() => {
- root?.render(<WatchProbe publication={{trackSid: 'TR_watch'} as unknown as RemoteTrackPublication} />);
- });
-
- expect(watchDeadlineFor(STREAM_KEY)).toBe(deadline);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/useStreamTrackInfo.test.ts b/fluxer_app/src/features/voice/components/useStreamTrackInfo.test.ts
deleted file mode 100644
index ed4776489..000000000
--- a/fluxer_app/src/features/voice/components/useStreamTrackInfo.test.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- mergeStreamTrackInfo,
- resolveStreamTrackInfoSnapshot,
- resolveStreamTrackStatsInfo,
-} from '@app/features/voice/components/useStreamTrackInfo';
-import {createVoiceMediaGraphSnapshot, transitionVoiceMediaGraph} from '@app/features/voice/engine/VoiceMediaGraph';
-import {
- type VoiceMediaGraphStatsView,
- voiceMediaGraphStatsObservationsFromPerTrackStats,
-} from '@app/features/voice/engine/VoiceMediaGraphStats';
-import type {VoiceMediaGraphStatsTrackObservation} from '@app/features/voice/engine/VoiceMediaGraphStatsObservations';
-import {VoiceTrackSource} from '@app/features/voice/engine/VoiceTrackSource';
-import type {VoiceEngineV2PerTrackStats} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-function observation(overrides: Partial<VoiceMediaGraphStatsTrackObservation>): VoiceMediaGraphStatsTrackObservation {
- return {
- trackSid: null,
- trackIdentifier: null,
- mediaSourceId: null,
- mid: null,
- rid: null,
- ssrc: null,
- participantIdentity: null,
- participantSid: null,
- source: null,
- direction: 'recv',
- kind: 'video',
- fps: null,
- width: null,
- height: null,
- sourceFps: null,
- sourceWidth: null,
- sourceHeight: null,
- ...overrides,
- };
-}
-
-function graphViewWithObservations(
- tracks: ReadonlyArray<VoiceMediaGraphStatsTrackObservation>,
-): VoiceMediaGraphStatsView {
- return transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'conn-1',
- platform: 'web',
- tracks,
- });
-}
-
-function graphViewWithWebStats(tracks: ReadonlyArray<VoiceEngineV2PerTrackStats>): VoiceMediaGraphStatsView {
- return transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'conn-1',
- platform: 'web',
- tracks: voiceMediaGraphStatsObservationsFromPerTrackStats(tracks),
- });
-}
-
-describe('resolveStreamTrackInfoSnapshot', () => {
- it('prefers attached element dimensions and rounds track settings fps', () => {
- expect(
- resolveStreamTrackInfoSnapshot({
- attachedElements: [{videoWidth: 3840, videoHeight: 2160}],
- settings: {width: 1280, height: 720, frameRate: 29.7},
- }),
- ).toEqual({width: 3840, height: 2160, fps: 30});
- });
-});
-
-describe('mergeStreamTrackInfo', () => {
- it('fills missing rendered-track fps from matched stats without replacing rendered dimensions', () => {
- const renderedInfo = {width: 3840, height: 2160, fps: 0};
- const statsInfo = {width: 1920, height: 1080, fps: 24.7};
-
- expect(mergeStreamTrackInfo(renderedInfo, statsInfo)).toEqual({width: 3840, height: 2160, fps: 25});
- });
-});
-
-describe('resolveStreamTrackStatsInfo', () => {
- it('resolves screen-share info from the graph by trackSid', () => {
- const view = graphViewWithObservations([
- observation({
- trackSid: 'TR_screen',
- source: 'screen_share',
- direction: 'send',
- width: 2560,
- height: 1440,
- fps: 59.6,
- }),
- ]);
-
- expect(
- resolveStreamTrackStatsInfo(view, {
- trackSid: 'TR_screen',
- source: VoiceTrackSource.ScreenShare,
- kind: 'video',
- }),
- ).toEqual({width: 2560, height: 1440, fps: 59.6});
- });
-
- it('resolves remote screen-share info via the participantIdentity fallback', () => {
- const view = graphViewWithObservations([
- observation({
- participantSid: 'PA_1',
- participantIdentity: 'user_2_connection_2',
- trackSid: 'TR_remote_screen',
- source: 'screen_share',
- width: 3840,
- height: 2160,
- fps: 24.7,
- }),
- ]);
-
- expect(
- resolveStreamTrackStatsInfo(view, {
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- kind: 'video',
- }),
- ).toEqual({width: 3840, height: 2160, fps: 24.7});
- });
-
- it('resolves web per-track stats dispatched into the graph by trackIdentifier', () => {
- const view = graphViewWithWebStats([
- {
- direction: 'recv',
- kind: 'video',
- trackIdentifier: 'camera-media-track',
- bitrateKbps: 800,
- framesPerSecond: 30,
- },
- {
- direction: 'recv',
- kind: 'video',
- trackIdentifier: 'screen-media-track',
- bitrateKbps: 4200,
- framesPerSecond: 24.7,
- frameWidth: 3840,
- frameHeight: 2160,
- },
- ]);
-
- expect(
- resolveStreamTrackStatsInfo(view, {
- trackIdentifier: 'screen-media-track',
- source: VoiceTrackSource.ScreenShare,
- kind: 'video',
- }),
- ).toEqual({width: 3840, height: 2160, fps: 24.7});
- });
-
- it('can return fps-only web stats so rendered dimensions still get the estimated frame rate', () => {
- const view = graphViewWithWebStats([
- {
- direction: 'recv',
- kind: 'video',
- trackIdentifier: 'screen-media-track',
- bitrateKbps: 4200,
- framesPerSecond: 25,
- },
- ]);
-
- expect(
- resolveStreamTrackStatsInfo(view, {
- trackIdentifier: 'screen-media-track',
- source: VoiceTrackSource.ScreenShare,
- kind: 'video',
- }),
- ).toEqual({fps: 25});
- });
-});
diff --git a/fluxer_app/src/features/voice/components/voice_connection_status/LocalParticipantControlsStateMachine.test.ts b/fluxer_app/src/features/voice/components/voice_connection_status/LocalParticipantControlsStateMachine.test.ts
deleted file mode 100644
index f82597a17..000000000
--- a/fluxer_app/src/features/voice/components/voice_connection_status/LocalParticipantControlsStateMachine.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type LocalParticipantControlSignals,
- selectLocalParticipantControlsViewState,
- selectLocalParticipantMediaControlState,
-} from '@app/features/voice/components/voice_connection_status/LocalParticipantControlsStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function signals(overrides: Partial<LocalParticipantControlSignals> = {}): LocalParticipantControlSignals {
- return {
- isConnected: true,
- canStream: true,
- isCameraEnabled: false,
- isCameraUserCapReached: false,
- isScreenShareEnabled: false,
- ...overrides,
- };
-}
-
-describe('LocalParticipantControlsStateMachine', () => {
- it('waits for the room connection before exposing media actions', () => {
- const state = selectLocalParticipantControlsViewState(
- signals({
- isConnected: false,
- isCameraEnabled: true,
- isScreenShareEnabled: true,
- }),
- );
- expect(state.camera).toMatchObject({
- value: 'waiting',
- labelKey: 'waitingForConnection',
- disabled: true,
- canOpenSettings: false,
- });
- expect(state.screenShare).toMatchObject({
- value: 'waiting',
- labelKey: 'waitingForConnection',
- disabled: true,
- clickAction: 'none',
- canOpenMenu: false,
- canPreloadPicker: false,
- });
- });
-
- it('blocks starting camera or screen share when stream permission is missing', () => {
- const state = selectLocalParticipantControlsViewState(signals({canStream: false}));
- expect(state.camera).toMatchObject({
- value: 'permissionBlocked',
- labelKey: 'noCameraPermission',
- disabled: true,
- });
- expect(state.screenShare).toMatchObject({
- value: 'permissionBlocked',
- labelKey: 'noScreenSharePermission',
- disabled: true,
- clickAction: 'none',
- });
- });
-
- it('keeps active media controllable even if stream permission is later missing', () => {
- const state = selectLocalParticipantControlsViewState(
- signals({
- canStream: false,
- isCameraEnabled: true,
- isScreenShareEnabled: true,
- }),
- );
- expect(state.camera).toMatchObject({
- value: 'active',
- labelKey: 'turnOffCamera',
- disabled: false,
- canOpenSettings: true,
- });
- expect(state.screenShare).toMatchObject({
- value: 'active',
- labelKey: 'configureOrEndScreenShare',
- disabled: false,
- clickAction: 'openMenu',
- canOpenMenu: true,
- canPreloadPicker: false,
- });
- });
-
- it('selects picker actions for ready connected controls', () => {
- const state = selectLocalParticipantControlsViewState(signals());
- expect(state.camera).toMatchObject({
- value: 'ready',
- labelKey: 'turnOnCamera',
- disabled: false,
- canOpenSettings: true,
- });
- expect(state.screenShare).toMatchObject({
- value: 'ready',
- labelKey: 'shareScreen',
- disabled: false,
- clickAction: 'openPicker',
- canOpenMenu: false,
- canPreloadPicker: true,
- });
- });
-
- it('evaluates camera and screen share independently', () => {
- const mixed = signals({
- isCameraEnabled: true,
- isScreenShareEnabled: false,
- });
- expect(selectLocalParticipantMediaControlState('camera', mixed)).toBe('active');
- expect(selectLocalParticipantMediaControlState('screenShare', mixed)).toBe('ready');
- });
-
- it('blocks turning the camera on at the camera user cap but leaves screen share alone', () => {
- const capped = signals({isCameraUserCapReached: true});
- const state = selectLocalParticipantControlsViewState(capped);
- expect(state.camera).toMatchObject({
- value: 'capBlocked',
- labelKey: 'cameraUserCapReached',
- disabled: true,
- canOpenSettings: false,
- });
- expect(state.screenShare).toMatchObject({value: 'ready', disabled: false});
- });
-
- it('never blocks turning the camera off at the camera user cap', () => {
- const capped = signals({isCameraUserCapReached: true, isCameraEnabled: true});
- expect(selectLocalParticipantMediaControlState('camera', capped)).toBe('active');
- expect(selectLocalParticipantControlsViewState(capped).camera.disabled).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/voice_participant_tile/ScreenShareVideoSubscriptionRecovery.test.ts b/fluxer_app/src/features/voice/components/voice_participant_tile/ScreenShareVideoSubscriptionRecovery.test.ts
deleted file mode 100644
index 4725f7078..000000000
--- a/fluxer_app/src/features/voice/components/voice_participant_tile/ScreenShareVideoSubscriptionRecovery.test.ts
+++ /dev/null
@@ -1,263 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- isScreenShareVideoSubscriptionRecoveryWanted,
- ScreenShareVideoSubscriptionRecoveryCoordinator,
- type ScreenShareVideoSubscriptionRecoveryGraph,
- type ScreenShareVideoSubscriptionRecoveryPublication,
- type ScreenShareVideoSubscriptionRecoveryScheduler,
-} from '@app/features/voice/components/voice_participant_tile/ScreenShareVideoSubscriptionRecovery';
-import {
- createVoiceMediaGraphSnapshot,
- transitionVoiceMediaGraph,
- VOICE_MEDIA_GRAPH_SCREEN_SHARE_SOURCE,
- type VoiceMediaGraphFailure,
- type VoiceMediaGraphSnapshot,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {ScreenShareWatchErrorCode} from '@app/features/voice/state/ScreenShareWatchFailures';
-import {describe, expect, it, vi} from 'vitest';
-
-const STREAM_KEY = 'dm:channel-a:connection-a';
-const PARTICIPANT_IDENTITY = 'user_1_connection-a';
-const TRACK_SID = 'TR_screen_share';
-
-const FIRST_FRAME_TIMEOUT_FAILURE: Partial<VoiceMediaGraphFailure> = {
- code: ScreenShareWatchErrorCode.FirstFrameTimeout,
- reason: 'first-frame-timeout',
-};
-
-const REMOTE_SUBSCRIPTION_FAILURE: Partial<VoiceMediaGraphFailure> = {
- code: ScreenShareWatchErrorCode.RemoteTrackSubscriptionFailed,
- reason: 'remote-track-subscription-failed',
-};
-
-function createScheduler() {
- let nextId = 1;
- const callbacks = new Map<number, () => void>();
- const scheduledDelays: Array<number> = [];
- const scheduler: ScreenShareVideoSubscriptionRecoveryScheduler = {
- setTimeout: (callback, delayMs) => {
- const timeoutId = nextId;
- nextId += 1;
- callbacks.set(timeoutId, callback);
- scheduledDelays.push(delayMs);
- return timeoutId;
- },
- clearTimeout: (timeoutId) => {
- callbacks.delete(timeoutId);
- },
- };
- return {
- scheduler,
- pendingCount: () => callbacks.size,
- scheduledDelays: () => [...scheduledDelays],
- fire: () => {
- const next = callbacks.entries().next();
- if (next.done) return;
- callbacks.delete(next.value[0]);
- next.value[1]();
- },
- };
-}
-
-function createWatchedSnapshot(failure: Partial<VoiceMediaGraphFailure> | null): VoiceMediaGraphSnapshot {
- let snapshot: VoiceMediaGraphSnapshot = createVoiceMediaGraphSnapshot();
- snapshot = transitionVoiceMediaGraph(snapshot, {type: 'watchIntent.add', key: STREAM_KEY});
- snapshot = transitionVoiceMediaGraph(snapshot, {type: 'watch.started', streamKey: STREAM_KEY});
- if (!failure) return snapshot;
- return transitionVoiceMediaGraph(snapshot, {
- type: 'failure.reported',
- failure: {
- code: -2202,
- reason: 'remote-track-subscription-failed',
- reportedAt: 1000,
- source: VOICE_MEDIA_GRAPH_SCREEN_SHARE_SOURCE,
- streamKey: STREAM_KEY,
- participantIdentity: PARTICIPANT_IDENTITY,
- ...failure,
- },
- });
-}
-
-function createGraphPort(getSnapshot: () => VoiceMediaGraphSnapshot): ScreenShareVideoSubscriptionRecoveryGraph {
- return {
- getGraphSnapshot: getSnapshot,
- nowMs: () => 1000,
- transition: () => undefined,
- };
-}
-
-function createReceivablePublication(): ScreenShareVideoSubscriptionRecoveryPublication {
- return {
- trackSid: TRACK_SID,
- isSubscribed: true,
- track: {mediaStreamTrack: {readyState: 'live', muted: false}},
- };
-}
-
-function createMutedPublication(): ScreenShareVideoSubscriptionRecoveryPublication {
- return {
- trackSid: TRACK_SID,
- isSubscribed: true,
- track: {mediaStreamTrack: {readyState: 'live', muted: true}},
- };
-}
-
-function createWatchingTile(
- failure: Partial<VoiceMediaGraphFailure> | null,
- publication: ScreenShareVideoSubscriptionRecoveryPublication = createReceivablePublication(),
-) {
- let snapshot = createWatchedSnapshot(failure);
- const {scheduler, fire, pendingCount, scheduledDelays} = createScheduler();
- const coordinator = new ScreenShareVideoSubscriptionRecoveryCoordinator(
- scheduler,
- createGraphPort(() => snapshot),
- );
- const recover = vi.fn();
- const acquire = () =>
- coordinator.acquire({
- key: TRACK_SID,
- publication,
- streamKey: STREAM_KEY,
- participantIdentity: PARTICIPANT_IDENTITY,
- isStillWanted: () => isScreenShareVideoSubscriptionRecoveryWanted(snapshot, STREAM_KEY),
- recover,
- });
- const restartWatch = (nextFailure: Partial<VoiceMediaGraphFailure> | null) => {
- snapshot = createWatchedSnapshot(nextFailure);
- };
- return {coordinator, fire, pendingCount, scheduledDelays, recover, acquire, restartWatch};
-}
-
-function acquireWatchingTile(
- failure: Partial<VoiceMediaGraphFailure> | null,
- publication?: ScreenShareVideoSubscriptionRecoveryPublication,
-) {
- const tile = createWatchingTile(failure, publication);
- tile.acquire();
- return tile;
-}
-
-describe('isScreenShareVideoSubscriptionRecoveryWanted', () => {
- it('keeps the lease armed after a first-frame timeout so recovery can still run', () => {
- expect(
- isScreenShareVideoSubscriptionRecoveryWanted(createWatchedSnapshot(FIRST_FRAME_TIMEOUT_FAILURE), STREAM_KEY),
- ).toBe(true);
- });
-
- it('drops the lease for failures other than a first-frame timeout', () => {
- expect(
- isScreenShareVideoSubscriptionRecoveryWanted(createWatchedSnapshot(REMOTE_SUBSCRIPTION_FAILURE), STREAM_KEY),
- ).toBe(false);
- });
-
- it('drops the lease once the stream is no longer watched', () => {
- expect(isScreenShareVideoSubscriptionRecoveryWanted(createVoiceMediaGraphSnapshot(), STREAM_KEY)).toBe(false);
- });
-});
-
-describe('ScreenShareVideoSubscriptionRecoveryCoordinator first-frame recovery', () => {
- it('keeps resubscribing while a first-frame timeout stands, up to the recovery limit', () => {
- const {coordinator, fire, pendingCount, recover} = acquireWatchingTile(FIRST_FRAME_TIMEOUT_FAILURE);
-
- fire();
-
- expect(recover).toHaveBeenCalledTimes(1);
- expect(recover).toHaveBeenCalledWith('resubscribe');
- expect(pendingCount()).toBe(1);
-
- fire();
- fire();
-
- expect(recover).toHaveBeenCalledTimes(3);
- expect(recover).toHaveBeenNthCalledWith(3, 'resubscribe');
- expect(pendingCount()).toBe(1);
-
- fire();
-
- expect(recover).toHaveBeenCalledTimes(3);
- expect(coordinator.getActiveSessionCount()).toBe(0);
- });
-
- it('gives every rebuilt subscription at least the first-frame budget before resubscribing again', () => {
- const {fire, scheduledDelays} = acquireWatchingTile(FIRST_FRAME_TIMEOUT_FAILURE);
-
- fire();
- fire();
-
- expect(scheduledDelays().slice(1)).toEqual([20_000, 20_000]);
- });
-
- it('keeps polling without recovering while a receivable track has no reported failure', () => {
- const {coordinator, fire, recover} = acquireWatchingTile(null);
-
- fire();
- fire();
- fire();
-
- expect(recover).not.toHaveBeenCalled();
- expect(coordinator.getActiveSessionCount()).toBe(1);
- });
-
- it('closes the session without recovering for a failure other than a first-frame timeout', () => {
- const {coordinator, fire, recover} = acquireWatchingTile(REMOTE_SUBSCRIPTION_FAILURE);
-
- fire();
-
- expect(recover).not.toHaveBeenCalled();
- expect(coordinator.getActiveSessionCount()).toBe(0);
- });
-
- it('keeps the recovery count when the lease is released and taken again', () => {
- const {coordinator, fire, recover, acquire} = createWatchingTile(FIRST_FRAME_TIMEOUT_FAILURE);
- const release = acquire();
-
- fire();
-
- expect(recover).toHaveBeenCalledTimes(1);
-
- release();
-
- expect(coordinator.getActiveSessionCount()).toBe(0);
-
- acquire();
- fire();
- fire();
-
- expect(recover).toHaveBeenCalledTimes(3);
-
- fire();
-
- expect(recover).toHaveBeenCalledTimes(3);
- expect(coordinator.getActiveSessionCount()).toBe(0);
- });
-
- it('hands the next watch of the same stream a fresh recovery budget', () => {
- const {fire, recover, acquire, restartWatch} = createWatchingTile(FIRST_FRAME_TIMEOUT_FAILURE);
- const release = acquire();
-
- fire();
- fire();
- fire();
-
- expect(recover).toHaveBeenCalledTimes(3);
-
- release();
- restartWatch(null);
- acquire();
- restartWatch(FIRST_FRAME_TIMEOUT_FAILURE);
- fire();
-
- expect(recover).toHaveBeenCalledTimes(4);
- });
-
- it('leaves a muted track alone until a failure is recorded', () => {
- const {coordinator, fire, recover} = acquireWatchingTile(null, createMutedPublication());
-
- fire();
- fire();
-
- expect(recover).not.toHaveBeenCalled();
- expect(coordinator.getActiveSessionCount()).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/voice/components/voice_participant_tile/StreamPreviewUploadPolicy.test.ts b/fluxer_app/src/features/voice/components/voice_participant_tile/StreamPreviewUploadPolicy.test.ts
deleted file mode 100644
index 8135a9ba4..000000000
--- a/fluxer_app/src/features/voice/components/voice_participant_tile/StreamPreviewUploadPolicy.test.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getUploadUrlExpiresAtMs,
- isUploadUrlFresh,
- STREAM_PREVIEW_UPLOAD_URL_REFRESH_SKEW_MS,
- StreamPreviewUploadScheduler,
-} from '@app/features/voice/components/voice_participant_tile/StreamPreviewUploadPolicy';
-import {
- STREAM_PREVIEW_INITIAL_UPLOAD_INTERVAL_MS,
- STREAM_PREVIEW_INITIAL_UPLOAD_MAX_ATTEMPTS,
- STREAM_PREVIEW_UPLOAD_INTERVAL_MS,
-} from '@fluxer/constants/src/StreamConstants';
-import {describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'guild-1:channel-1:connection-1';
-
-function makeScheduler(): StreamPreviewUploadScheduler {
- return new StreamPreviewUploadScheduler(() => 0.5);
-}
-
-describe('StreamPreviewUploadScheduler', () => {
- it('uploads at the fast bootstrap interval before the first upload completes', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: false,
- initialAttempts: 0,
- hasSpectatorDemand: false,
- previewsDisabled: false,
- });
- expect(decision).toEqual({action: 'upload', nextDelayMs: STREAM_PREVIEW_INITIAL_UPLOAD_INTERVAL_MS});
- });
-
- it('switches to the steady cadence once bootstrap has uploaded and demand exists', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: true,
- initialAttempts: 1,
- hasSpectatorDemand: true,
- previewsDisabled: false,
- });
- expect(decision).toEqual({action: 'upload', nextDelayMs: STREAM_PREVIEW_UPLOAD_INTERVAL_MS});
- });
-
- it('idles without uploading after bootstrap when there is no spectator demand', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: true,
- initialAttempts: 1,
- hasSpectatorDemand: false,
- previewsDisabled: false,
- });
- expect(decision.action).toBe('wait');
- expect(decision.nextDelayMs).toBeGreaterThan(0);
- });
-
- it('keeps the bootstrap uploads unconditional even without demand', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: false,
- initialAttempts: STREAM_PREVIEW_INITIAL_UPLOAD_MAX_ATTEMPTS - 1,
- hasSpectatorDemand: false,
- previewsDisabled: false,
- });
- expect(decision.action).toBe('upload');
- });
-
- it('stops treating the session as bootstrap after the attempt cap is reached', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: false,
- initialAttempts: STREAM_PREVIEW_INITIAL_UPLOAD_MAX_ATTEMPTS,
- hasSpectatorDemand: false,
- previewsDisabled: false,
- });
- expect(decision.action).toBe('wait');
- });
-
- it('waits while previews are disabled regardless of bootstrap or demand', () => {
- const scheduler = makeScheduler();
- const decision = scheduler.decide({
- now: 0,
- hasUploadedOnce: false,
- initialAttempts: 0,
- hasSpectatorDemand: true,
- previewsDisabled: true,
- });
- expect(decision.action).toBe('wait');
- });
-});
-
-describe('isUploadUrlFresh', () => {
- it('treats a ticket as fresh until the refresh skew window before expiry', () => {
- const now = 1_000_000;
- const entry = {streamKey: STREAM_KEY, expiresAtMs: now + STREAM_PREVIEW_UPLOAD_URL_REFRESH_SKEW_MS + 1};
- expect(isUploadUrlFresh(entry, STREAM_KEY, now)).toBe(true);
- });
-
- it('flips to stale exactly at the expiry minus skew boundary', () => {
- const now = 1_000_000;
- const entry = {streamKey: STREAM_KEY, expiresAtMs: now + STREAM_PREVIEW_UPLOAD_URL_REFRESH_SKEW_MS};
- expect(isUploadUrlFresh(entry, STREAM_KEY, now)).toBe(false);
- });
-
- it('rejects a ticket minted for a different stream key', () => {
- const now = 1_000_000;
- const entry = {streamKey: 'other', expiresAtMs: now + STREAM_PREVIEW_UPLOAD_URL_REFRESH_SKEW_MS + 10_000};
- expect(isUploadUrlFresh(entry, STREAM_KEY, now)).toBe(false);
- });
-
- it('rejects a null ticket', () => {
- expect(isUploadUrlFresh(null, STREAM_KEY, 0)).toBe(false);
- });
-});
-
-describe('getUploadUrlExpiresAtMs', () => {
- it('prefers the absolute expires_at timestamp when parseable', () => {
- const expiresAt = new Date('2026-01-01T00:10:00.000Z').toISOString();
- expect(getUploadUrlExpiresAtMs({expires_at: expiresAt, expires_in: 600}, 0)).toBe(Date.parse(expiresAt));
- });
-
- it('falls back to now plus expires_in when expires_at is unparseable', () => {
- const now = 5_000;
- expect(getUploadUrlExpiresAtMs({expires_at: 'not-a-date', expires_in: 600}, now)).toBe(now + 600_000);
- });
-});
diff --git a/fluxer_app/src/features/voice/diagnostics/VoiceDebugStatsHtml.test.tsx b/fluxer_app/src/features/voice/diagnostics/VoiceDebugStatsHtml.test.tsx
deleted file mode 100644
index a28a4d7b1..000000000
--- a/fluxer_app/src/features/voice/diagnostics/VoiceDebugStatsHtml.test.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {renderVoiceDebugStatsHtml} from '@app/features/voice/diagnostics/VoiceDebugStatsHtml';
-import type {StatsForNerdsData} from '@app/features/voice/utils/VoiceStatsForNerdsPresenter';
-import {describe, expect, it} from 'vitest';
-
-function createStatsData(): StatsForNerdsData {
- return {
- session: {
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- latencyMs: 24,
- avgLatencyMs: 31,
- durationSeconds: 90,
- participants: 3,
- },
- network: {
- audioSendBitrateKbps: 48,
- audioRecvBitrateKbps: 64,
- videoSendBitrateKbps: 1200,
- videoRecvBitrateKbps: 900,
- audioPacketLossPercent: 0.5,
- videoPacketLossPercent: 1.25,
- jitterMs: 6,
- rttMs: 24,
- publisherTransport: null,
- subscriberTransport: null,
- },
- localVideo: null,
- localVideoLayers: [],
- localAudio: null,
- localScreenShare: null,
- localScreenShareAudio: null,
- remoteVideo: null,
- remoteScreenShare: null,
- remoteAudio: null,
- remoteScreenShareAudio: null,
- connection: {
- voiceServerEndpoint: 'voice.example',
- reconnectionCount: 0,
- },
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true,
- deepFilterNoiseSuppression: false,
- deepFilterNoiseSuppressionLevel: 0,
- processingMode: 'default',
- },
- screenShareSettings: {
- resolution: '1080p',
- frameRate: 30,
- streamingMode: 'quality',
- preferredCodec: 'h264',
- selectedCodec: 'h264',
- codecPreferenceOrder: ['h264', 'vp8'],
- contentHint: 'detail',
- encoderMode: 'auto',
- softwareQuality: 'balanced',
- scalabilityMode: 'none',
- backupCodecMode: 'auto',
- maxBitrateMbps: 4.5,
- audioSourceMode: 'none',
- audioIncludeSources: [],
- audioExcludeSources: [],
- shareDesktopAudio: false,
- shareAppAudio: false,
- muteStreamAudio: true,
- openH264Enabled: true,
- },
- screenShareAudioCapture: {
- nativeCapture: {},
- publications: [],
- },
- appInfo: {
- appVersion: 'dev',
- electronVersion: '41.2.2',
- chromiumVersion: '140.0.0.0',
- hardwareAccelerationEnabled: true,
- chromiumRuntime: null,
- },
- gpu: null,
- appMetrics: null,
- system: {
- platform: 'MacIntel',
- userAgent: 'Chrome',
- hardwareConcurrency: 10,
- deviceMemoryGB: 8,
- jsHeapUsedMB: 42,
- jsHeapTotalMB: 80,
- jsHeapLimitMB: 4096,
- },
- heapHistory: [40, 42, 45],
- cpuHistory: [3, 8, 4],
- sparklines: {
- latency: [31, 24, 44],
- bitrate: [1000, 1400, 1300],
- packetLoss: [0, 1.25, 0.5],
- },
- };
-}
-
-function createNativeCaptureRecord(): Record<string, unknown> {
- return {
- armedCapture: null,
- activeBridge: {captureId: 'native-audio:live'},
- supersededBridge: null,
- lastStartedCapture: null,
- lastArmFailure: null,
- bridgeStats: {
- active: true,
- bridgeMode: 'generator',
- captureId: 'native-audio:live',
- startedAt: 1772000000000,
- lastFrameAt: 1772000011240,
- lastFrameTimestampUs: 11240000,
- framesReceived: 1124,
- framesDropped: 0,
- lateFrameCount: 0,
- rebufferCount: 0,
- maxFrameArrivalGapMs: 32,
- maxFrameTimestampGapMs: 10,
- maxPendingFrames: 3,
- maxBufferedDurationMs: 30,
- lastFramePeak: 0.42,
- lastFrameRms: 0.11,
- maxFramePeak: 0.71,
- maxFrameRms: 0.19,
- nonSilentFrameCount: 1118,
- prebufferTargetMs: 60,
- frameDurationMs: 10,
- endReason: null,
- endDetail: null,
- endedAt: null,
- },
- endedBridgeCaptures: [],
- lifecycleFaults: [],
- };
-}
-
-function screenShareAudioCaptureSection(html: string): string {
- const match = /<section[^>]*><h3[^>]*>screenShareAudioCapture \(native\)<\/h3>[\s\S]*?<\/section>/.exec(html);
- expect(match).not.toBeNull();
- return match?.[0] ?? '';
-}
-
-describe('renderVoiceDebugStatsHtml', () => {
- it('renders pure SVG sparklines for key popout metrics', () => {
- const html = renderVoiceDebugStatsHtml(createStatsData(), '2026-06-10T18:00:00.000Z');
-
- expect(html).toContain('keyMetricSparklines');
- expect(html).toContain('<svg');
- expect(html).toContain('<polyline');
- expect(html).toContain('latencyMs sparkline');
- expect(html).toContain('totalBitrateKbps sparkline');
- expect(html).toContain('packetLossPercent sparkline');
- expect(html).toContain('heapUsedMB sparkline');
- expect(html).toContain('mainProcessCpuPercent sparkline');
- });
-
- it('does not render a screen-share audio pump section while the native capture is live', () => {
- const data = createStatsData();
- data.screenShareAudioCapture = {nativeCapture: createNativeCaptureRecord(), publications: []};
-
- const html = renderVoiceDebugStatsHtml(data, '2026-06-10T18:00:00.000Z');
-
- expect(html).toContain('screenShareAudioCapture (native)');
- expect(html).toContain('framesReceived');
- expect(html).not.toContain('screenShareAudioCapture (pump)');
- expect(html).not.toContain('publishStrategy');
- expect(html).not.toContain('droppedPushFrames');
- expect(html).not.toContain('usesNativeSink');
- });
-
- it('renders the screen-share audio capture section identically for Chromium and Firefox dumps', () => {
- const chromium = createStatsData();
- chromium.screenShareAudioCapture = {nativeCapture: createNativeCaptureRecord(), publications: []};
- chromium.system.platform = 'Win32';
- chromium.system.userAgent =
- '(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
- const firefox = createStatsData();
- firefox.screenShareAudioCapture = {nativeCapture: createNativeCaptureRecord(), publications: []};
- firefox.system.platform = 'Win32';
- firefox.system.userAgent = '(Windows NT 10.0; Win64; x64; rv:155.0) Gecko/20100101 Firefox/155.0';
- firefox.appInfo.electronVersion = null;
- firefox.appInfo.chromiumVersion = null;
- firefox.appInfo.hardwareAccelerationEnabled = null;
-
- const chromiumHtml = renderVoiceDebugStatsHtml(chromium, '2026-06-10T18:00:00.000Z');
- const firefoxHtml = renderVoiceDebugStatsHtml(firefox, '2026-06-10T18:00:00.000Z');
-
- expect(screenShareAudioCaptureSection(chromiumHtml)).toBe(screenShareAudioCaptureSection(firefoxHtml));
- expect(chromiumHtml).not.toContain('screenShareAudioCapture (pump)');
- expect(firefoxHtml).not.toContain('screenShareAudioCapture (pump)');
- });
-
- it('renders every camera simulcast layer instead of only the projected localVideo row', () => {
- const data = createStatsData();
- data.localVideoLayers = [
- {direction: 'send', kind: 'video', ssrc: 1001, rid: 'q', active: false, bitrateKbps: 0, bitrateWindowMs: 2001},
- {direction: 'send', kind: 'video', ssrc: 1002, rid: 'h', active: false, bitrateKbps: 0, bitrateWindowMs: 2001},
- {direction: 'send', kind: 'video', ssrc: 1003, rid: 'f', active: true, bitrateKbps: 1133, bitrateWindowMs: 2001},
- ];
- data.localVideo = data.localVideoLayers[0];
-
- const html = renderVoiceDebugStatsHtml(data, '2026-06-10T18:00:00.000Z');
-
- expect(html).toContain('track:localVideoLayers[0]');
- expect(html).toContain('track:localVideoLayers[1]');
- expect(html).toContain('track:localVideoLayers[2]');
- expect(html).toContain('bitrateWindowMs');
- });
-});
diff --git a/fluxer_app/src/features/voice/diagnostics/VoiceSubscriptionDebugSummary.test.ts b/fluxer_app/src/features/voice/diagnostics/VoiceSubscriptionDebugSummary.test.ts
deleted file mode 100644
index a4e546a51..000000000
--- a/fluxer_app/src/features/voice/diagnostics/VoiceSubscriptionDebugSummary.test.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- summarizeVoiceSubscriptionDebug,
- type VoiceSubscriptionDebugParticipant,
- type VoiceSubscriptionDebugPublication,
- type VoiceSubscriptionDebugSubscription,
- type VoiceSubscriptionDebugTransceiver,
-} from '@app/features/voice/diagnostics/VoiceSubscriptionDebugSummary';
-import {describe, expect, it} from 'vitest';
-
-function transceiver(overrides: Partial<VoiceSubscriptionDebugTransceiver>): VoiceSubscriptionDebugTransceiver {
- return {
- mid: '0',
- direction: 'recvonly',
- currentDirection: 'recvonly',
- receiver: {id: 'receiver', kind: 'video', enabled: true, muted: false, readyState: 'live'},
- sender: null,
- ...overrides,
- };
-}
-
-function publication(overrides: Partial<VoiceSubscriptionDebugPublication>): VoiceSubscriptionDebugPublication {
- return {
- trackSid: 'TR_1',
- trackName: 'screen',
- kind: 'video',
- source: 'screen_share',
- mimeType: 'video/VP9',
- dimensions: {width: 1920, height: 1080},
- simulcasted: false,
- muted: false,
- enabled: true,
- subscribed: false,
- desired: true,
- subscriptionStatus: 'desired',
- permissionStatus: 'allowed',
- videoQuality: 2,
- track: null,
- ...overrides,
- };
-}
-
-function participant(publications: Array<VoiceSubscriptionDebugPublication>): VoiceSubscriptionDebugParticipant {
- return {identity: 'user_1_connection-a', sid: 'PA_1', publications};
-}
-
-function subscription(overrides: Partial<VoiceSubscriptionDebugSubscription>): VoiceSubscriptionDebugSubscription {
- return {
- key: 'user_1_connection-a:screen_share',
- participantIdentity: 'user_1_connection-a',
- source: 'screen_share',
- desired: {enabled: true, quality: 'high', context: 'focused', isIntersecting: true, hasObservedElement: false},
- actual: {subscribed: null, enabled: null, quality: null, lastCommandAt: null, lastError: null},
- publication: {available: true, trackSid: 'TR_1', observedAt: 1000},
- firstFrame: {renderedAt: null},
- subscribed: true,
- ...overrides,
- };
-}
-
-describe('summarizeVoiceSubscriptionDebug', () => {
- it('reports zero issued commands when the client never asked for the stream', () => {
- const summary = summarizeVoiceSubscriptionDebug([], [participant([publication({})])], [subscription({})], 0);
- expect(summary.remoteScreenSharePublications).toBe(1);
- expect(summary.screenShareSubscriptions).toBe(1);
- expect(summary.screenShareSubscriptionsWithCommandIssued).toBe(0);
- expect(summary.videoReceiveTransceivers).toBe(0);
- expect(summary.negotiatedVideoReceiveTransceivers).toBe(0);
- expect(summary.screenSharePublicationsWithTrack).toBe(0);
- });
-
- it('counts a negotiated receive transceiver once the answer applies it', () => {
- const summary = summarizeVoiceSubscriptionDebug(
- [transceiver({}), transceiver({mid: '1', currentDirection: null})],
- [participant([publication({subscribed: true, track: null})])],
- [subscription({actual: {subscribed: true, enabled: true, quality: 'high', lastCommandAt: 5, lastError: null}})],
- 2,
- );
- expect(summary.videoReceiveTransceivers).toBe(2);
- expect(summary.negotiatedVideoReceiveTransceivers).toBe(1);
- expect(summary.subscribedScreenSharePublications).toBe(1);
- expect(summary.screenShareSubscriptionsWithCommandIssued).toBe(1);
- expect(summary.pendingSubscriptionCommands).toBe(2);
- });
-
- it('ignores send-only video, audio receivers, and non-screen-share sources', () => {
- const summary = summarizeVoiceSubscriptionDebug(
- [
- transceiver({direction: 'sendonly', currentDirection: 'sendonly'}),
- transceiver({
- mid: '1',
- receiver: {id: 'audio', kind: 'audio', enabled: true, muted: false, readyState: 'live'},
- }),
- ],
- [
- participant([
- publication({source: 'camera'}),
- publication({trackSid: 'TR_2', kind: 'audio', source: 'screen_share_audio'}),
- ]),
- ],
- [subscription({source: 'camera'})],
- 0,
- );
- expect(summary.videoReceiveTransceivers).toBe(0);
- expect(summary.negotiatedVideoReceiveTransceivers).toBe(0);
- expect(summary.remoteScreenSharePublications).toBe(0);
- expect(summary.screenShareSubscriptions).toBe(0);
- });
-
- it('counts a rendered first frame separately from an attached track', () => {
- const summary = summarizeVoiceSubscriptionDebug(
- [transceiver({})],
- [
- participant([
- publication({
- subscribed: true,
- track: {id: 'track', kind: 'video', enabled: true, muted: false, readyState: 'live'},
- }),
- ]),
- ],
- [subscription({firstFrame: {renderedAt: 42}})],
- 0,
- );
- expect(summary.screenSharePublicationsWithTrack).toBe(1);
- expect(summary.screenShareSubscriptionsWithFirstFrame).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/MediaEngineFacadeStateMachine.test.ts b/fluxer_app/src/features/voice/engine/MediaEngineFacadeStateMachine.test.ts
deleted file mode 100644
index 073548513..000000000
--- a/fluxer_app/src/features/voice/engine/MediaEngineFacadeStateMachine.test.ts
+++ /dev/null
@@ -1,435 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createMediaEngineFacadeSnapshot,
- getMediaEngineFacadeStateValue,
- selectMediaEngineConnectPreflightDecision,
- selectMediaEngineConnectRequestDecision,
- selectMediaEngineGatewayErrorDecision,
- shouldCancelMediaEngineReconnectForServerVoiceStateRemoval,
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval,
- shouldRunMediaEngineDeferredDisconnect,
- transitionMediaEngineFacadeSnapshot,
-} from '@app/features/voice/engine/MediaEngineFacadeStateMachine';
-import {GatewayErrorCodes} from '@fluxer/constants/src/GatewayConstants';
-import {describe, expect, it} from 'vitest';
-
-function connected(guildId: string | null = 'guild-1', channelId = 'channel-1') {
- return transitionMediaEngineFacadeSnapshot(createMediaEngineFacadeSnapshot(), {
- type: 'connection.connected',
- guildId,
- channelId,
- });
-}
-
-describe('MediaEngineFacadeStateMachine', () => {
- it('noops connect requests for the current channel', () => {
- const snapshot = connected();
- const decision = selectMediaEngineConnectRequestDecision(snapshot, {
- guildId: 'guild-1',
- channelId: 'channel-1',
- connected: true,
- connecting: false,
- });
- expect(decision).toEqual({type: 'noop', reason: 'same-channel'});
- });
-
- it('tracks user channel moves through local cleanup and the next connection', () => {
- let snapshot = connected();
- const decision = selectMediaEngineConnectRequestDecision(snapshot, {
- guildId: 'guild-1',
- channelId: 'channel-2',
- connected: true,
- connecting: false,
- });
- expect(decision).toEqual({type: 'move-user', guildId: 'guild-1', channelId: 'channel-2'});
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'userMove.requested',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'channelMove.cleanupStarted', reason: 'user'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('channelMoving');
- expect(snapshot.context.pendingUserMove).toEqual({guildId: 'guild-1', channelId: 'channel-2'});
- expect(snapshot.context.activeConnection).toBeNull();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'cleanup.complete'});
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'connection.connected',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- expect(snapshot.context.pendingUserMove).toBeNull();
- expect(snapshot.context.activeConnection).toEqual({guildId: 'guild-1', channelId: 'channel-2'});
- });
-
- it('clears pending user moves during server channel move cleanup', () => {
- let snapshot = connected();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'userMove.requested',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'channelMove.cleanupStarted', reason: 'server'});
- expect(snapshot.context.pendingUserMove).toBeNull();
- expect(snapshot.context.activeConnection).toBeNull();
- expect(snapshot.context.localCleanupReason).toBe('channelMove');
- });
-
- it('cancels and expires pending server disconnects by connection id', () => {
- let snapshot = createMediaEngineFacadeSnapshot();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'serverDisconnect.schedule',
- connectionId: 'connection-1',
- });
- expect(
- shouldRunMediaEngineDeferredDisconnect(snapshot, {
- connectionId: 'connection-1',
- currentConnectionId: 'connection-1',
- connected: true,
- currentVoiceStateChannelId: null,
- }),
- ).toBe(true);
- expect(
- shouldRunMediaEngineDeferredDisconnect(snapshot, {
- connectionId: 'connection-1',
- currentConnectionId: 'connection-1',
- connected: true,
- currentVoiceStateChannelId: 'channel-1',
- }),
- ).toBe(false);
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'serverDisconnect.cancel'});
- expect(snapshot.context.pendingServerDisconnectConnectionId).toBeNull();
- expect(
- shouldRunMediaEngineDeferredDisconnect(snapshot, {
- connectionId: 'connection-1',
- currentConnectionId: 'connection-1',
- connected: true,
- currentVoiceStateChannelId: null,
- }),
- ).toBe(false);
-
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'serverDisconnect.schedule',
- connectionId: 'connection-2',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'serverDisconnect.timeoutElapsed',
- connectionId: 'connection-2',
- });
- expect(snapshot.context.pendingServerDisconnectConnectionId).toBeNull();
- });
-
- it('disconnects immediately when the server removes the current local voice state without a live transport', () => {
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: true,
- connecting: false,
- }),
- ).toBe(false);
-
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: false,
- connecting: true,
- }),
- ).toBe(true);
-
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: false,
- connecting: false,
- }),
- ).toBe(true);
-
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: 'channel-1',
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: true,
- connecting: false,
- }),
- ).toBe(false);
-
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-2',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: true,
- connecting: false,
- }),
- ).toBe(false);
- });
-
- it('keeps the transport during a server move until the replacement connection arrives', () => {
- let snapshot = createMediaEngineFacadeSnapshot();
- expect(
- shouldImmediatelyDisconnectMediaEngineForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: true,
- connecting: false,
- }),
- ).toBe(false);
- expect(
- shouldCancelMediaEngineReconnectForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: true,
- connecting: false,
- }),
- ).toBe(false);
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'serverDisconnect.schedule',
- connectionId: 'connection-1',
- });
- expect(
- shouldRunMediaEngineDeferredDisconnect(snapshot, {
- connectionId: 'connection-1',
- currentConnectionId: 'connection-2',
- connected: true,
- currentVoiceStateChannelId: null,
- }),
- ).toBe(false);
- expect(
- shouldRunMediaEngineDeferredDisconnect(snapshot, {
- connectionId: 'connection-1',
- currentConnectionId: 'connection-1',
- connected: true,
- currentVoiceStateChannelId: null,
- }),
- ).toBe(true);
- });
-
- it('cancels reconnect when local voice-state removal arrives after transport disconnect', () => {
- expect(
- shouldCancelMediaEngineReconnectForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: null,
- connected: false,
- connecting: false,
- }),
- ).toBe(true);
- expect(
- shouldCancelMediaEngineReconnectForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-1',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: 'channel-1',
- connected: false,
- connecting: false,
- }),
- ).toBe(false);
- expect(
- shouldCancelMediaEngineReconnectForServerVoiceStateRemoval({
- voiceStateConnectionId: 'connection-2',
- voiceStateChannelId: null,
- currentConnectionId: 'connection-1',
- currentChannelId: null,
- connected: false,
- connecting: false,
- }),
- ).toBe(false);
- });
-
- it('selects gateway error abort decisions while connecting', () => {
- let snapshot = createMediaEngineFacadeSnapshot();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'sessionRestore.prepare',
- guildId: 'guild-1',
- channelId: 'channel-1',
- restoreVideo: true,
- restoreStream: true,
- });
- const decision = selectMediaEngineGatewayErrorDecision(snapshot, {
- code: GatewayErrorCodes.VOICE_CONNECTION_NOT_FOUND,
- connecting: true,
- connected: false,
- channelId: 'channel-1',
- });
- expect(decision).toMatchObject({
- type: 'handle',
- clearPendingSessionRestore: true,
- clearViewerStreamKeys: true,
- abortConnection: true,
- disconnectReason: null,
- });
- });
-
- it('selects unavailable target cleanup and aborts unavailable connecting targets', () => {
- let snapshot = createMediaEngineFacadeSnapshot();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'sessionRestore.prepare',
- guildId: 'guild-1',
- channelId: 'missing-channel',
- restoreVideo: false,
- restoreStream: false,
- });
- const decision = selectMediaEngineGatewayErrorDecision(snapshot, {
- code: GatewayErrorCodes.VOICE_CHANNEL_NOT_FOUND,
- connecting: true,
- connected: false,
- channelId: null,
- });
- expect(decision).toMatchObject({
- type: 'handle',
- unavailableChannelId: 'missing-channel',
- showUnavailableToast: true,
- clearViewerStreamKeys: true,
- abortConnection: true,
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'unavailableTarget.clear',
- channelId: 'missing-channel',
- });
- expect(snapshot.context.pendingSessionRestore).toBeNull();
- });
-
- it('preserves or clears pending session restore only for matching targets', () => {
- let snapshot = createMediaEngineFacadeSnapshot();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'sessionRestore.prepare',
- guildId: null,
- channelId: 'dm-1',
- restoreVideo: true,
- restoreStream: false,
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'sessionRestore.clearTarget',
- guildId: null,
- channelId: 'dm-2',
- });
- expect(snapshot.context.pendingSessionRestore?.channelId).toBe('dm-1');
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'sessionRestore.clearTarget',
- guildId: null,
- channelId: 'dm-1',
- });
- expect(snapshot.context.pendingSessionRestore).toBeNull();
- });
-
- it('stores, clears, and consumes pending screen share reconnect snapshots', () => {
- const reconnectSnapshot = {sourceId: 'screen-1'};
- let snapshot = createMediaEngineFacadeSnapshot();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'screenShareReconnect.prepare',
- snapshot: reconnectSnapshot,
- });
- expect(snapshot.context.pendingScreenShareReconnect).toBe(reconnectSnapshot);
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'screenShareReconnect.consume'});
- expect(snapshot.context.pendingScreenShareReconnect).toBeNull();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'screenShareReconnect.prepare',
- snapshot: reconnectSnapshot,
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'screenShareReconnect.clear'});
- expect(snapshot.context.pendingScreenShareReconnect).toBeNull();
- });
-
- it('resets all orchestration state on logout, cleanup, and reset', () => {
- let snapshot = connected();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'userMove.requested',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'serverDisconnect.schedule',
- connectionId: 'connection-1',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'cleanup.logoutStarted'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('loggingOut');
- expect(snapshot.context.activeConnection).toBeNull();
- expect(snapshot.context.pendingUserMove).toBeNull();
- expect(snapshot.context.pendingServerDisconnectConnectionId).toBeNull();
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'cleanup.complete'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('idle');
-
- snapshot = transitionMediaEngineFacadeSnapshot(connected(), {type: 'cleanup.cleanupStarted'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('cleaningUp');
- snapshot = transitionMediaEngineFacadeSnapshot(connected(), {type: 'cleanup.reset'});
- expect(snapshot.context).toMatchObject({
- activeConnection: null,
- pendingUserMove: null,
- pendingSessionRestore: null,
- pendingServerDisconnectConnectionId: null,
- });
- });
-
- it('handles repeated connect and disconnect cleanup sequences', () => {
- let snapshot = connected('guild-1', 'channel-1');
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'disconnect.cleanupStarted', reason: 'user'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('disconnecting');
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'cleanup.complete'});
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {
- type: 'connection.connected',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'disconnect.cleanupStarted', reason: 'server'});
- snapshot = transitionMediaEngineFacadeSnapshot(snapshot, {type: 'cleanup.complete'});
- expect(getMediaEngineFacadeStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.activeConnection).toBeNull();
- expect(snapshot.context.pendingSessionRestore).toBeNull();
- });
-
- it('keeps connect preflight outcomes pure', () => {
- expect(
- selectMediaEngineConnectPreflightDecision({
- targetAvailable: false,
- isTimedOut: false,
- isUnclaimed: false,
- isGuildOwner: true,
- isDirectMessage: false,
- hasGatewaySocket: true,
- blockedByMatureGate: false,
- channelLimitAllowed: true,
- }),
- ).toEqual({type: 'cleanup-unavailable-target', showToast: true});
- expect(
- selectMediaEngineConnectPreflightDecision({
- targetAvailable: true,
- isTimedOut: false,
- isUnclaimed: true,
- isGuildOwner: true,
- isDirectMessage: true,
- hasGatewaySocket: true,
- blockedByMatureGate: false,
- channelLimitAllowed: true,
- }),
- ).toEqual({type: 'toast', reason: 'claim-account-direct'});
- expect(
- selectMediaEngineConnectPreflightDecision({
- targetAvailable: true,
- isTimedOut: false,
- isUnclaimed: false,
- isGuildOwner: true,
- isDirectMessage: false,
- hasGatewaySocket: true,
- blockedByMatureGate: true,
- channelLimitAllowed: true,
- }),
- ).toEqual({type: 'navigate-channel-gate'});
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/ScreenShareCodecNegotiation.test.ts b/fluxer_app/src/features/voice/engine/ScreenShareCodecNegotiation.test.ts
deleted file mode 100644
index 070036f0b..000000000
--- a/fluxer_app/src/features/voice/engine/ScreenShareCodecNegotiation.test.ts
+++ /dev/null
@@ -1,436 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- FluxerCodecAdvertisement,
- FluxerSelectProtocolMessage,
-} from '@app/features/voice/engine/ScreenShareCodecNegotiation';
-import type {HardwareEncodeReport} from '@app/features/voice/utils/GpuEncoderCapabilities';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-let av1OptIn = false;
-let hevcOptIn = false;
-let preferredScreenShareCodec = 'auto';
-let gpuReport: HardwareEncodeReport | null = null;
-let firefoxBrowser = false;
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- getScreenShareAv1OptIn: () => av1OptIn,
- getScreenShareHevcOptIn: () => hevcOptIn,
- getPreferredScreenShareCodec: () => preferredScreenShareCodec,
- getScreenShareEncoderMode: () => 'auto',
- },
-}));
-
-vi.mock('@app/features/devtools/utils/DesktopTroubleshootingUtils', () => ({
- getCachedDesktopTroubleshootingSettings: () => null,
-}));
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- guessPlatform: () => 'windows',
- isChromiumBrowser: () => true,
- isDesktop: () => true,
- isFirefoxBrowser: () => firefoxBrowser,
-}));
-
-vi.mock('@app/features/voice/utils/GpuEncoderCapabilities', () => ({
- getGpuEncoderReportSync: () => gpuReport,
- loadGpuEncoderReport: async () => gpuReport,
-}));
-
-vi.mock('@app/features/voice/utils/NativeHardwareEncoderCapabilities', () => ({
- getNativeHardwareEncoderCapabilitiesSync: () => null,
- hasNativeHardwareEncoder: () => false,
- resetNativeHardwareEncoderCapabilities: () => undefined,
- loadNativeHardwareEncoderCapabilities: async () => null,
-}));
-
-vi.mock('@app/features/voice/utils/OpenH264Status', () => ({
- getOpenH264StatusSync: () => null,
- resetOpenH264Status: () => undefined,
- loadOpenH264Status: async () => null,
-}));
-
-vi.mock('@app/features/voice/utils/VideoDecoderCapabilities', () => ({
- clearScreenShareDecodeFailures: () => undefined,
- getScreenShareDecodeFailures: () => new Set(),
- getVideoDecoderExclusionsSync: () => [],
- loadVideoDecoderExclusions: async () => [],
-}));
-
-const VIDEO_CAPABILITIES = {
- codecs: [
- {mimeType: 'video/VP8'},
- {mimeType: 'video/VP9'},
- {mimeType: 'video/H264'},
- {mimeType: 'video/H265'},
- {mimeType: 'video/AV1'},
- ],
-};
-
-Object.defineProperty(globalThis, 'RTCRtpSender', {
- configurable: true,
- writable: true,
- value: {getCapabilities: () => VIDEO_CAPABILITIES},
-});
-
-Object.defineProperty(globalThis, 'RTCRtpReceiver', {
- configurable: true,
- writable: true,
- value: {getCapabilities: () => VIDEO_CAPABILITIES},
-});
-
-const {
- default: ScreenShareCodecNegotiation,
- buildLocalCodecAdvertisements,
- computeNegotiatedVideoCodec,
- getScreenShareCodecPreferenceOrder,
- SCREEN_SHARE_CODEC_NEGOTIATION_TOPIC,
-} = await import('@app/features/voice/engine/ScreenShareCodecNegotiation');
-const {resetCachedCodecCapabilities} = await import('@app/features/voice/utils/CodecCapabilityDetector');
-const {RoomEvent} = await import('livekit-client');
-
-class FakeRoom {
- private handlers = new Map<string, Set<(...args: Array<unknown>) => void>>();
- localParticipant = {identity: 'local', publishData: vi.fn(async () => undefined)};
- remoteParticipants = new Map<string, {identity: string}>();
-
- on(event: string, handler: (...args: Array<unknown>) => void): this {
- if (!this.handlers.has(event)) this.handlers.set(event, new Set());
- this.handlers.get(event)?.add(handler);
- return this;
- }
-
- off(event: string, handler: (...args: Array<unknown>) => void): this {
- this.handlers.get(event)?.delete(handler);
- return this;
- }
-
- emit(event: string, ...args: Array<unknown>): void {
- for (const handler of this.handlers.get(event) ?? []) handler(...args);
- }
-}
-
-function sessionUpdatePayload(codecs: Array<FluxerCodecAdvertisement>): Uint8Array {
- return new TextEncoder().encode(
- JSON.stringify({
- op: 14,
- d: {video_codec: 'H264', media_session_id: 'peer-session', reason: 'connected', codecs},
- }),
- );
-}
-
-function videoAdvertisement(name: 'AV1' | 'VP9' | 'H265', encode: boolean, decode: boolean): FluxerCodecAdvertisement {
- const payloadType = name === 'AV1' ? 101 : name === 'H265' ? 105 : 109;
- return {name, type: 'video', payload_type: payloadType, priority: 1, encode, decode};
-}
-
-describe('screen-share codec negotiation with the AV1 opt-in off', () => {
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- preferredScreenShareCodec = 'auto';
- gpuReport = {av1: 'hardware', h265: 'software', h264: 'hardware', vp9: 'software', vp8: 'software'};
- resetCachedCodecCapabilities();
- });
-
- it('keeps AV1 out of the negotiated preference order the hardware tail would refill', () => {
- expect(getScreenShareCodecPreferenceOrder()).not.toContain('av1');
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(getScreenShareCodecPreferenceOrder()).toContain('av1');
- });
-
- it('drops an explicitly requested AV1 preference from the order', () => {
- expect(getScreenShareCodecPreferenceOrder('av1')).not.toContain('av1');
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(getScreenShareCodecPreferenceOrder('av1')[0]).toBe('av1');
- });
-
- it('stops advertising AV1 encode while still advertising AV1 decode', () => {
- const av1 = buildLocalCodecAdvertisements().find((codec) => codec.name === 'AV1');
- expect(av1).toMatchObject({encode: false, decode: true});
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(buildLocalCodecAdvertisements().find((codec) => codec.name === 'AV1')).toMatchObject({
- encode: true,
- decode: true,
- });
- });
-
- it('negotiates away from AV1 even when both ends can encode and decode it', () => {
- const local = [videoAdvertisement('AV1', true, true), videoAdvertisement('VP9', true, true)];
- const remote = [[videoAdvertisement('AV1', true, true), videoAdvertisement('VP9', true, true)]];
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('vp9');
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('av1');
- });
-
- it('avoids exotic codecs while any participant codec set is still unknown', () => {
- av1OptIn = true;
- resetCachedCodecCapabilities();
- const local = [videoAdvertisement('AV1', true, true), videoAdvertisement('VP9', true, true)];
- const remote = [[videoAdvertisement('AV1', true, true), videoAdvertisement('VP9', true, true)]];
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('av1');
- expect(computeNegotiatedVideoCodec(local, remote, 1, getScreenShareCodecPreferenceOrder()).codec).toBe('vp9');
- });
-});
-
-describe('screen-share codec negotiation with the HEVC opt-in off', () => {
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- preferredScreenShareCodec = 'auto';
- gpuReport = {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'};
- resetCachedCodecCapabilities();
- });
-
- it('keeps HEVC out of the negotiated preference order the hardware tail would refill', () => {
- expect(getScreenShareCodecPreferenceOrder()).not.toContain('h265');
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(getScreenShareCodecPreferenceOrder()).toContain('h265');
- });
-
- it('drops an explicitly requested HEVC preference from the order', () => {
- expect(getScreenShareCodecPreferenceOrder('h265')).not.toContain('h265');
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(getScreenShareCodecPreferenceOrder('h265')[0]).toBe('h265');
- });
-
- it('stops advertising HEVC encode while still advertising HEVC decode', () => {
- const h265 = buildLocalCodecAdvertisements().find((codec) => codec.name === 'H265');
- expect(h265).toMatchObject({encode: false, decode: true});
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(buildLocalCodecAdvertisements().find((codec) => codec.name === 'H265')).toMatchObject({
- encode: true,
- decode: true,
- });
- });
-
- it('negotiates away from HEVC even when both ends can encode and decode it', () => {
- const local = [videoAdvertisement('H265', true, true), videoAdvertisement('VP9', true, true)];
- const remote = [[videoAdvertisement('H265', true, true), videoAdvertisement('VP9', true, true)]];
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('vp9');
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('h265');
- });
-});
-
-describe('screen-share codec negotiation on Gecko', () => {
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- preferredScreenShareCodec = 'auto';
- gpuReport = null;
- firefoxBrowser = true;
- resetCachedCodecCapabilities();
- });
-
- afterEach(() => {
- firefoxBrowser = false;
- resetCachedCodecCapabilities();
- });
-
- it('ranks VP8 ahead of H.264 because Gecko always software-encodes H.264', () => {
- expect(getScreenShareCodecPreferenceOrder()).toEqual(['vp8', 'h264']);
- });
-
- it('negotiates VP8 when both ends can encode and decode VP8 and H.264', () => {
- const local = buildLocalCodecAdvertisements();
- const remote = [buildLocalCodecAdvertisements()];
- expect(computeNegotiatedVideoCodec(local, remote, 0, getScreenShareCodecPreferenceOrder()).codec).toBe('vp8');
- });
-
- it('still lets an explicit H.264 pin win over the Gecko order', () => {
- expect(getScreenShareCodecPreferenceOrder('h264')[0]).toBe('h264');
- });
-});
-
-describe('advertising local capabilities over the negotiation topic', () => {
- let room: FakeRoom;
-
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- preferredScreenShareCodec = 'auto';
- gpuReport = {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'};
- resetCachedCodecCapabilities();
- room = new FakeRoom();
- ScreenShareCodecNegotiation.setSelectionChangeListener(null);
- });
-
- async function publishAndCaptureSelectProtocol(): Promise<{
- payload: Uint8Array;
- message: FluxerSelectProtocolMessage;
- }> {
- Object.defineProperty(globalThis, 'window', {configurable: true, writable: true, value: {}});
- try {
- ScreenShareCodecNegotiation.bind(room as never);
- await ScreenShareCodecNegotiation.publishLocalCapabilities(room as never, 'manual');
- } finally {
- Reflect.deleteProperty(globalThis, 'window');
- }
- const payloads = (room.localParticipant.publishData.mock.calls as Array<Array<unknown>>).map(
- (call) => call[0] as Uint8Array,
- );
- const payload = payloads.findLast(
- (candidate) => (JSON.parse(new TextDecoder().decode(candidate)) as {op: number}).op === 1,
- );
- if (!payload) throw new Error('no select-protocol message was published');
- return {payload, message: JSON.parse(new TextDecoder().decode(payload)) as FluxerSelectProtocolMessage};
- }
-
- it('advertises no experiments because nothing on either side reads them', async () => {
- const {message} = await publishAndCaptureSelectProtocol();
- expect(message.op).toBe(1);
- expect(message.d.experiments).toEqual([]);
- ScreenShareCodecNegotiation.dispose();
- });
-
- it('keeps the empty experiments list acceptable to the receive-side validator', async () => {
- const {payload} = await publishAndCaptureSelectProtocol();
- ScreenShareCodecNegotiation.dispose();
- const peerRoom = new FakeRoom();
- peerRoom.remoteParticipants.set('peer', {identity: 'peer'});
- ScreenShareCodecNegotiation.bind(peerRoom as never);
- const listener = vi.fn();
- ScreenShareCodecNegotiation.setSelectionChangeListener(listener);
- peerRoom.emit(RoomEvent.DataReceived, payload, {identity: 'peer'}, undefined, SCREEN_SHARE_CODEC_NEGOTIATION_TOPIC);
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(listener).toHaveBeenCalled();
- ScreenShareCodecNegotiation.dispose();
- });
-});
-
-describe('reacting to a mid-session codec selection change', () => {
- let room: FakeRoom;
-
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = true;
- preferredScreenShareCodec = 'auto';
- gpuReport = {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'};
- resetCachedCodecCapabilities();
- room = new FakeRoom();
- ScreenShareCodecNegotiation.setSelectionChangeListener(null);
- });
-
- function flush(): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, 0));
- }
-
- async function establishBaseline(): Promise<void> {
- ScreenShareCodecNegotiation.bind(room as never);
- room.emit(RoomEvent.ParticipantDisconnected, {identity: 'nobody-was-connected'});
- await flush();
- }
-
- it('picks the locally preferred codec while no remote participant is known', async () => {
- await establishBaseline();
- expect(ScreenShareCodecNegotiation.getSelectedCodec()).toBe('h265');
- ScreenShareCodecNegotiation.dispose();
- });
-
- it('notifies the selection-change listener once a peer without HEVC decode is discovered', async () => {
- await establishBaseline();
- expect(ScreenShareCodecNegotiation.getSelectedCodec()).toBe('h265');
- const listener = vi.fn();
- ScreenShareCodecNegotiation.setSelectionChangeListener(listener);
- room.remoteParticipants.set('peer-without-hevc', {identity: 'peer-without-hevc'});
- const payload = sessionUpdatePayload([videoAdvertisement('VP9', true, true)]);
- room.emit(
- RoomEvent.DataReceived,
- payload,
- {identity: 'peer-without-hevc'},
- undefined,
- SCREEN_SHARE_CODEC_NEGOTIATION_TOPIC,
- );
- await flush();
- const negotiated = ScreenShareCodecNegotiation.getSelectedCodec();
- expect(negotiated).not.toBe('h265');
- expect(listener).toHaveBeenCalledTimes(1);
- expect(listener).toHaveBeenCalledWith(room, negotiated, 'data');
- ScreenShareCodecNegotiation.dispose();
- });
-
- async function withWindowDefined(run: () => Promise<void>): Promise<void> {
- Object.defineProperty(globalThis, 'window', {configurable: true, writable: true, value: {}});
- try {
- await run();
- } finally {
- Reflect.deleteProperty(globalThis, 'window');
- }
- }
-
- it('stops reusing a live AV1 selection once the AV1 opt-in is turned off mid-share', async () => {
- av1OptIn = true;
- resetCachedCodecCapabilities();
- await establishBaseline();
- expect(ScreenShareCodecNegotiation.getSelectedCodec()).toBe('av1');
- av1OptIn = false;
- resetCachedCodecCapabilities();
- expect(ScreenShareCodecNegotiation.selectScreenShareCodec('auto')).not.toBe('av1');
- expect(ScreenShareCodecNegotiation.selectNativeScreenShareCodec('auto')).not.toBe('av1');
- expect(getScreenShareCodecPreferenceOrder()).toContain(ScreenShareCodecNegotiation.selectScreenShareCodec('auto'));
- ScreenShareCodecNegotiation.dispose();
- });
-
- it('renegotiates the live share off AV1 when the opt-in toggle refreshes the local capabilities', async () => {
- av1OptIn = true;
- resetCachedCodecCapabilities();
- await establishBaseline();
- expect(ScreenShareCodecNegotiation.getSelectedCodec()).toBe('av1');
- const listener = vi.fn();
- ScreenShareCodecNegotiation.setSelectionChangeListener(listener);
- av1OptIn = false;
- resetCachedCodecCapabilities();
- await withWindowDefined(async () => {
- await ScreenShareCodecNegotiation.publishLocalCapabilities(room as never, 'manual');
- });
- const negotiated = ScreenShareCodecNegotiation.getSelectedCodec();
- expect(negotiated).not.toBe('av1');
- expect(listener).toHaveBeenCalledTimes(1);
- expect(listener).toHaveBeenCalledWith(room, negotiated, 'manual');
- ScreenShareCodecNegotiation.dispose();
- });
-
- it('does not notify the listener when the recomputed selection is unchanged', async () => {
- await establishBaseline();
- room.remoteParticipants.set('peer-with-hevc', {identity: 'peer-with-hevc'});
- const firstPayload = sessionUpdatePayload([
- videoAdvertisement('H265', true, true),
- videoAdvertisement('VP9', true, true),
- ]);
- room.emit(
- RoomEvent.DataReceived,
- firstPayload,
- {identity: 'peer-with-hevc'},
- undefined,
- SCREEN_SHARE_CODEC_NEGOTIATION_TOPIC,
- );
- await flush();
- expect(ScreenShareCodecNegotiation.getSelectedCodec()).toBe('h265');
- const listener = vi.fn();
- ScreenShareCodecNegotiation.setSelectionChangeListener(listener);
- const secondPayload = sessionUpdatePayload([
- videoAdvertisement('H265', true, true),
- videoAdvertisement('VP9', true, true),
- ]);
- room.emit(
- RoomEvent.DataReceived,
- secondPayload,
- {identity: 'peer-with-hevc'},
- undefined,
- SCREEN_SHARE_CODEC_NEGOTIATION_TOPIC,
- );
- await flush();
- expect(listener).not.toHaveBeenCalled();
- ScreenShareCodecNegotiation.dispose();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/ScreenShareDecodeStallRenegotiation.test.ts b/fluxer_app/src/features/voice/engine/ScreenShareDecodeStallRenegotiation.test.ts
deleted file mode 100644
index 3e1b2abff..000000000
--- a/fluxer_app/src/features/voice/engine/ScreenShareDecodeStallRenegotiation.test.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {FluxerCodecAdvertisement} from '@app/features/voice/engine/ScreenShareCodecNegotiation';
-import type {HardwareEncodeReport} from '@app/features/voice/utils/GpuEncoderCapabilities';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const gpuReport: HardwareEncodeReport = {
- av1: 'hardware',
- h265: 'hardware',
- h264: 'hardware',
- vp9: 'software',
- vp8: 'software',
-};
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- getScreenShareAv1OptIn: () => false,
- getScreenShareHevcOptIn: () => false,
- getPreferredScreenShareCodec: () => 'auto',
- getScreenShareEncoderMode: () => 'auto',
- },
-}));
-
-vi.mock('@app/features/devtools/utils/DesktopTroubleshootingUtils', () => ({
- getCachedDesktopTroubleshootingSettings: () => null,
-}));
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- guessPlatform: () => 'windows',
- isChromiumBrowser: () => true,
- isDesktop: () => true,
- isFirefoxBrowser: () => false,
-}));
-
-vi.mock('@app/features/voice/utils/GpuEncoderCapabilities', () => ({
- getGpuEncoderReportSync: () => gpuReport,
- loadGpuEncoderReport: async () => gpuReport,
-}));
-
-vi.mock('@app/features/voice/utils/NativeHardwareEncoderCapabilities', () => ({
- getNativeHardwareEncoderCapabilitiesSync: () => null,
- hasNativeHardwareEncoder: () => false,
- resetNativeHardwareEncoderCapabilities: () => undefined,
- loadNativeHardwareEncoderCapabilities: async () => null,
-}));
-
-vi.mock('@app/features/voice/utils/OpenH264Status', () => ({
- getOpenH264StatusSync: () => null,
- resetOpenH264Status: () => undefined,
- loadOpenH264Status: async () => null,
-}));
-
-const VIDEO_CAPABILITIES = {
- codecs: [
- {mimeType: 'video/VP8'},
- {mimeType: 'video/VP9'},
- {mimeType: 'video/H264'},
- {mimeType: 'video/H265'},
- {mimeType: 'video/AV1'},
- ],
-};
-
-Object.defineProperty(globalThis, 'RTCRtpSender', {
- configurable: true,
- writable: true,
- value: {getCapabilities: () => VIDEO_CAPABILITIES},
-});
-
-Object.defineProperty(globalThis, 'RTCRtpReceiver', {
- configurable: true,
- writable: true,
- value: {getCapabilities: () => VIDEO_CAPABILITIES},
-});
-
-const {
- default: ScreenShareCodecNegotiation,
- buildLocalCodecAdvertisements,
- computeNegotiatedVideoCodec,
-} = await import('@app/features/voice/engine/ScreenShareCodecNegotiation');
-const {findStalledVideoDecoder, scheduleScreenShareDecoderVerification} = await import(
- '@app/features/voice/utils/ScreenShareCodecDiagnostics'
-);
-const {getVideoDecoderExclusionsSync, markScreenShareDecodeFailure, resetVideoDecoderExclusions} = await import(
- '@app/features/voice/utils/VideoDecoderCapabilities'
-);
-const {resetCachedCodecCapabilities} = await import('@app/features/voice/utils/CodecCapabilityDetector');
-
-function screenShareStats(mimeType: string, frames: {framesReceived: number; framesDecoded: number}): RTCStatsReport {
- const entries: Array<Record<string, unknown>> = [
- {id: 'codec-1', type: 'codec', mimeType},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 4200,
- bytesReceived: 3_500_000,
- decoderImplementation: 'D3D11VideoDecoder',
- powerEfficientDecoder: true,
- ...frames,
- },
- ];
- return new Map(entries.map((entry) => [entry.id as string, entry])) as unknown as RTCStatsReport;
-}
-
-function stalledScreenShareStats(mimeType: string): RTCStatsReport {
- return screenShareStats(mimeType, {framesReceived: 180, framesDecoded: 0});
-}
-
-function statsSequence(...reports: Array<RTCStatsReport>): () => Promise<RTCStatsReport | undefined> {
- const queue = [...reports];
- return () => Promise.resolve(queue.shift());
-}
-
-function decodeAdvertisedFor(name: 'H264' | 'VP8' | 'VP9'): boolean | undefined {
- return buildLocalCodecAdvertisements().find((codec) => codec.name === name)?.decode;
-}
-
-function publisherThatEncodes(): Array<FluxerCodecAdvertisement> {
- return [
- {name: 'H264', type: 'video', payload_type: 102, priority: 1, encode: true, decode: true},
- {name: 'VP9', type: 'video', payload_type: 109, priority: 2, encode: true, decode: true},
- ];
-}
-
-describe('a stalled H.264 screen share decode', () => {
- beforeEach(() => {
- resetVideoDecoderExclusions();
- resetCachedCodecCapabilities();
- ScreenShareCodecNegotiation.dispose();
- });
-
- it('is reported as an h264 decode stall by the stats diagnostic', () => {
- expect(findStalledVideoDecoder(stalledScreenShareStats('video/H264'))?.codec).toBe('h264');
- });
-
- it('withdraws the local H.264 decode advertisement so the publisher renegotiates away from it', () => {
- const stall = findStalledVideoDecoder(stalledScreenShareStats('video/H264'));
- if (!stall) throw new Error('expected the stats diagnostic to report a stalled decoder');
- expect(stall.codec).toBe('h264');
- expect(decodeAdvertisedFor('H264')).toBe(true);
- expect(
- computeNegotiatedVideoCodec(publisherThatEncodes(), [buildLocalCodecAdvertisements()], 0, ['h264', 'vp9']).codec,
- ).toBe('h264');
-
- expect(markScreenShareDecodeFailure(stall.codec, 'screen-share-decode-stalled')).toBe(true);
-
- expect(decodeAdvertisedFor('H264')).toBe(false);
- expect(
- computeNegotiatedVideoCodec(publisherThatEncodes(), [buildLocalCodecAdvertisements()], 0, ['h264', 'vp9']).codec,
- ).toBe('vp9');
- });
-
- it('never removes h264 or vp8 from the SDP-level subscriber exclusions', () => {
- markScreenShareDecodeFailure('h264', 'screen-share-decode-stalled');
- expect(getVideoDecoderExclusionsSync() ?? []).not.toContain('h264');
- expect(getVideoDecoderExclusionsSync() ?? []).not.toContain('vp8');
- });
-
- it('keeps a non-baseline runtime stall out of the SDP-level subscriber exclusions too', () => {
- expect(markScreenShareDecodeFailure('av1', 'screen-share-decode-stalled')).toBe(true);
- expect(getVideoDecoderExclusionsSync() ?? []).not.toContain('av1');
- });
-
- it('restores the H.264 decode advertisement when the room is torn down', () => {
- expect(markScreenShareDecodeFailure('h264', 'screen-share-decode-stalled')).toBe(true);
- expect(decodeAdvertisedFor('H264')).toBe(false);
- ScreenShareCodecNegotiation.dispose();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-
- it('stops after one codec change instead of cycling through the remaining codecs', () => {
- expect(markScreenShareDecodeFailure('h264', 'screen-share-decode-stalled')).toBe(true);
- expect(markScreenShareDecodeFailure('h264', 'screen-share-decode-stalled')).toBe(false);
- expect(markScreenShareDecodeFailure('vp8', 'screen-share-decode-stalled')).toBe(false);
- expect(decodeAdvertisedFor('VP8')).toBe(true);
- });
-});
-
-describe('confirming a screen share decode stall before a codec is withdrawn', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- resetVideoDecoderExclusions();
- resetCachedCodecCapabilities();
- ScreenShareCodecNegotiation.dispose();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('withdraws nothing from a single stalled sample', async () => {
- const onDecodeFailure = vi.fn();
- scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 240, framesDecoded: 0}),
- ),
- undefined,
- onDecodeFailure,
- );
- await vi.advanceTimersByTimeAsync(5000);
- expect(onDecodeFailure).not.toHaveBeenCalled();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-
- it('withdraws nothing when packets arrive but no whole frames do', async () => {
- const onDecodeFailure = vi.fn();
- scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 0, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 0, framesDecoded: 0}),
- ),
- undefined,
- onDecodeFailure,
- );
- await vi.advanceTimersByTimeAsync(5000);
- expect(vi.getTimerCount()).toBe(0);
- await vi.advanceTimersByTimeAsync(5000);
- expect(onDecodeFailure).not.toHaveBeenCalled();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-
- it('withdraws the codec exactly once when a second sample confirms the stall', async () => {
- const withdrawn: Array<string> = [];
- scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 240, framesDecoded: 0}),
- ),
- undefined,
- (failure) => {
- if (markScreenShareDecodeFailure(failure.codec, 'screen-share-decode-stalled')) {
- withdrawn.push(failure.codec);
- }
- },
- );
- await vi.advanceTimersByTimeAsync(5000);
- expect(withdrawn).toEqual([]);
- expect(decodeAdvertisedFor('H264')).toBe(true);
- await vi.advanceTimersByTimeAsync(5000);
- expect(withdrawn).toEqual(['h264']);
- expect(decodeAdvertisedFor('H264')).toBe(false);
- });
-
- it('withdraws nothing when the second sample decoded a frame', async () => {
- const onDecodeFailure = vi.fn();
- scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 240, framesDecoded: 12}),
- ),
- undefined,
- onDecodeFailure,
- );
- await vi.advanceTimersByTimeAsync(10000);
- expect(onDecodeFailure).not.toHaveBeenCalled();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-
- it('withdraws nothing when no new frames arrived between the samples', async () => {
- const onDecodeFailure = vi.fn();
- scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- ),
- undefined,
- onDecodeFailure,
- );
- await vi.advanceTimersByTimeAsync(10000);
- expect(onDecodeFailure).not.toHaveBeenCalled();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-
- it('withdraws nothing when the track goes away between the samples', async () => {
- const onDecodeFailure = vi.fn();
- const cancel = scheduleScreenShareDecoderVerification(
- statsSequence(
- screenShareStats('video/H264', {framesReceived: 180, framesDecoded: 0}),
- screenShareStats('video/H264', {framesReceived: 240, framesDecoded: 0}),
- ),
- undefined,
- onDecodeFailure,
- );
- await vi.advanceTimersByTimeAsync(5000);
- expect(vi.getTimerCount()).toBe(1);
- cancel();
- expect(vi.getTimerCount()).toBe(0);
- await vi.advanceTimersByTimeAsync(5000);
- expect(onDecodeFailure).not.toHaveBeenCalled();
- expect(decodeAdvertisedFor('H264')).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/ScreenSharePublicationMigrationStateMachine.test.ts b/fluxer_app/src/features/voice/engine/ScreenSharePublicationMigrationStateMachine.test.ts
deleted file mode 100644
index e59d78a24..000000000
--- a/fluxer_app/src/features/voice/engine/ScreenSharePublicationMigrationStateMachine.test.ts
+++ /dev/null
@@ -1,287 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ScreenShareRemoteMigrationState,
- transitionRemoteScreenShareMigrationState,
-} from '@app/features/voice/engine/ScreenSharePublicationMigrationStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function candidate(overrides: Partial<ScreenShareRemoteMigrationState> = {}): ScreenShareRemoteMigrationState {
- return {
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'new-track',
- committedTrackSid: 'old-track',
- codec: 'av1',
- phase: 'candidate',
- readySent: false,
- ...overrides,
- };
-}
-
-describe('ScreenSharePublicationMigrationStateMachine remote migration', () => {
- it('enters breaking state before a replacement publication exists', () => {
- const breaking = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.break',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- codec: 'av1',
- });
-
- expect(breaking).toEqual({
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: null,
- committedTrackSid: 'old-track',
- codec: 'av1',
- phase: 'breaking',
- readySent: true,
- });
- });
-
- it('keeps buffering when the previous publication disappears during break-before-make', () => {
- const breaking = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.break',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- codec: 'av1',
- });
-
- const stillBreaking = transitionRemoteScreenShareMigrationState(breaking, {
- type: 'migration.committedUnpublished',
- trackSid: 'old-track',
- });
-
- expect(stillBreaking).toMatchObject({
- migrationId: 'migration-a',
- phase: 'breaking',
- previousTrackSid: null,
- candidateTrackSid: null,
- committedTrackSid: null,
- });
- });
-
- it('commits a replacement after break-before-make', () => {
- const breaking = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.break',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- codec: 'av1',
- });
-
- const committed = transitionRemoteScreenShareMigrationState(breaking, {
- type: 'migration.commit',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'new-track',
- });
-
- expect(committed).toMatchObject({
- migrationId: 'migration-a',
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'new-track',
- readySent: true,
- });
- });
-
- it('rolls back or clears breaking state on abort without a candidate SID', () => {
- const breaking = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.break',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- codec: 'av1',
- });
-
- expect(
- transitionRemoteScreenShareMigrationState(breaking, {
- type: 'migration.abort',
- migrationId: 'migration-a',
- candidateTrackSid: null,
- }),
- ).toMatchObject({
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'old-track',
- readySent: true,
- });
-
- const oldTrackGone = transitionRemoteScreenShareMigrationState(breaking, {
- type: 'migration.committedUnpublished',
- trackSid: 'old-track',
- });
- expect(
- transitionRemoteScreenShareMigrationState(oldTrackGone, {
- type: 'migration.abort',
- migrationId: 'migration-a',
- candidateTrackSid: null,
- }),
- ).toBeNull();
- });
-
- it('moves from candidate to committed without selecting the candidate early', () => {
- const pending = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.candidate',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'new-track',
- codec: 'av1',
- });
-
- expect(pending).toEqual(candidate());
-
- const committed = transitionRemoteScreenShareMigrationState(pending, {
- type: 'migration.commit',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'new-track',
- });
-
- expect(committed).toMatchObject({
- migrationId: 'migration-a',
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'new-track',
- readySent: true,
- });
- });
-
- it('ignores stale candidates and stale mismatched commits', () => {
- const committed = candidate({
- migrationId: 'migration-b',
- generation: 2,
- candidateTrackSid: null,
- committedTrackSid: 'newer-track',
- phase: 'committed',
- readySent: true,
- });
-
- expect(
- transitionRemoteScreenShareMigrationState(committed, {
- type: 'migration.candidate',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'stale-candidate',
- codec: 'h264',
- }),
- ).toBe(committed);
- expect(
- transitionRemoteScreenShareMigrationState(committed, {
- type: 'migration.commit',
- migrationId: 'migration-c',
- generation: 2,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'wrong-track',
- }),
- ).toBe(committed);
- });
-
- it('allows a newer generation to supersede an existing committed publication', () => {
- const committed = candidate({
- migrationId: 'migration-a',
- generation: 1,
- candidateTrackSid: null,
- committedTrackSid: 'new-track',
- phase: 'committed',
- readySent: true,
- });
-
- const next = transitionRemoteScreenShareMigrationState(committed, {
- type: 'migration.candidate',
- migrationId: 'migration-b',
- generation: 2,
- previousTrackSid: 'new-track',
- candidateTrackSid: 'newer-track',
- codec: 'h264',
- });
-
- expect(next).toMatchObject({
- migrationId: 'migration-b',
- generation: 2,
- previousTrackSid: 'new-track',
- candidateTrackSid: 'newer-track',
- committedTrackSid: 'new-track',
- phase: 'candidate',
- readySent: false,
- });
- });
-
- it('accepts an out-of-order commit without first seeing the candidate announcement', () => {
- const committed = transitionRemoteScreenShareMigrationState(null, {
- type: 'migration.commit',
- migrationId: 'migration-a',
- generation: 1,
- previousTrackSid: 'old-track',
- candidateTrackSid: 'new-track',
- });
-
- expect(committed).toMatchObject({
- migrationId: 'migration-a',
- generation: 1,
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'new-track',
- readySent: true,
- });
- });
-
- it('rolls back to the previous publication on matching abort', () => {
- const pending = candidate();
- const rolledBack = transitionRemoteScreenShareMigrationState(pending, {
- type: 'migration.abort',
- migrationId: 'migration-a',
- candidateTrackSid: 'new-track',
- });
-
- expect(rolledBack).toMatchObject({
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'old-track',
- readySent: true,
- });
- expect(
- transitionRemoteScreenShareMigrationState(pending, {
- type: 'migration.abort',
- migrationId: 'migration-a',
- candidateTrackSid: 'different-track',
- }),
- ).toBe(pending);
- });
-
- it('clears candidate or committed state when the corresponding publication disappears', () => {
- expect(
- transitionRemoteScreenShareMigrationState(candidate(), {
- type: 'migration.candidateUnpublished',
- trackSid: 'new-track',
- }),
- ).toMatchObject({
- phase: 'committed',
- candidateTrackSid: null,
- committedTrackSid: 'old-track',
- });
- expect(
- transitionRemoteScreenShareMigrationState(candidate({phase: 'committed', committedTrackSid: 'old-track'}), {
- type: 'migration.committedUnpublished',
- trackSid: 'old-track',
- }),
- ).toBeNull();
- });
-
- it('marks candidate readiness idempotently', () => {
- const pending = candidate();
- const ready = transitionRemoteScreenShareMigrationState(pending, {type: 'migration.readySent'});
-
- expect(ready).toMatchObject({readySent: true});
- expect(transitionRemoteScreenShareMigrationState(ready, {type: 'migration.readySent'})).toBe(ready);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/Store.test.ts b/fluxer_app/src/features/voice/engine/Store.test.ts
deleted file mode 100644
index 303e2b199..000000000
--- a/fluxer_app/src/features/voice/engine/Store.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Store} from '@app/features/voice/engine/Store';
-import {autorun} from 'mobx';
-import {describe, expect, it} from 'vitest';
-
-class TestStore extends Store {
- bump(): void {
- this.update(() => {});
- }
-}
-
-describe('Store', () => {
- it('exposes updates through MobX observation for observer components', () => {
- const store = new TestStore();
- const snapshots: Array<number> = [];
- const dispose = autorun(() => {
- snapshots.push(store.getMobxSnapshot());
- });
-
- store.bump();
-
- dispose();
- expect(snapshots).toEqual([0, 1]);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceAfkTracking.test.ts b/fluxer_app/src/features/voice/engine/VoiceAfkTracking.test.ts
deleted file mode 100644
index 04ffcc70a..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceAfkTracking.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {shouldMoveToAfkOnTick, shouldMoveToGuildAfkChannel} from '@app/features/voice/engine/VoiceAfkTracking';
-import {describe, expect, it} from 'vitest';
-
-describe('voice AFK channel tracking', () => {
- it('moves when inactivity reaches the guild AFK timeout', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(true);
- });
- it('stays in the current voice channel before the guild AFK timeout', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 59_999,
- }),
- ).toBe(false);
- });
- it('does not move when already in the AFK channel or AFK is disabled', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'afk-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: null,
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 0,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- });
- it('treats a null or undefined afk timeout as disabled', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: null,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: undefined,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- });
- it('does not move when the afk channel is undefined', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: undefined,
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- });
- it('ignores a negative timeout the same as a disabled one', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: -5,
- inactiveDurationMs: 60_000,
- }),
- ).toBe(false);
- });
- it('respects fractional-second timeouts at the exact boundary', () => {
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 1.5,
- inactiveDurationMs: 1_500,
- }),
- ).toBe(true);
- expect(
- shouldMoveToGuildAfkChannel({
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 1.5,
- inactiveDurationMs: 1_499,
- }),
- ).toBe(false);
- });
-});
-
-describe('voice AFK per-tick decision', () => {
- const idleState = {
- channelId: 'voice-1',
- afkChannelId: 'afk-1',
- afkTimeoutSeconds: 60,
- inactiveDurationMs: 60_000,
- } as const;
-
- it('moves when idle past the timeout and no recent voice activity', () => {
- expect(shouldMoveToAfkOnTick({...idleState, hasRecentVoiceActivity: false})).toBe(true);
- });
- it('never moves while there is recent local voice activity, even past the timeout', () => {
- expect(shouldMoveToAfkOnTick({...idleState, hasRecentVoiceActivity: true})).toBe(false);
- });
- it('does not move before the timeout regardless of voice activity', () => {
- expect(shouldMoveToAfkOnTick({...idleState, inactiveDurationMs: 59_999, hasRecentVoiceActivity: false})).toBe(
- false,
- );
- });
- it('does not move when already in the afk channel', () => {
- expect(shouldMoveToAfkOnTick({...idleState, channelId: 'afk-1', hasRecentVoiceActivity: false})).toBe(false);
- });
- it('does not move when afk is disabled', () => {
- expect(shouldMoveToAfkOnTick({...idleState, afkChannelId: null, hasRecentVoiceActivity: false})).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceConnectionStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceConnectionStateMachine.test.ts
deleted file mode 100644
index 2bfa7b7fd..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceConnectionStateMachine.test.ts
+++ /dev/null
@@ -1,461 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- asVoiceEngineConnectionState,
- createVoiceConnectionSnapshot,
- getVoiceConnectionStateValue,
- isLatestVoiceConnectionAttempt,
- selectVoiceConnectionServerUpdateDecision,
- transitionVoiceConnectionSnapshot,
- type VoiceConnectionSnapshot,
- VoiceEngineConnectionState,
-} from '@app/features/voice/engine/VoiceConnectionStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const roomA = {id: 'room-a'};
-const roomB = {id: 'room-b'};
-
-function startAndAccept(): VoiceConnectionSnapshot {
- let snapshot = createVoiceConnectionSnapshot();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- return transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.accepted',
- guildId: 'guild-1',
- channelId: 'channel-1',
- endpoint: 'wss://voice-a.example',
- connectionId: 'connection-1',
- isChannelMove: false,
- });
-}
-
-describe('VoiceConnectionStateMachine', () => {
- it('normalizes external connection-state values into the Fluxer state contract', () => {
- expect(asVoiceEngineConnectionState('connecting')).toBe(VoiceEngineConnectionState.Connecting);
- expect(asVoiceEngineConnectionState('connected')).toBe(VoiceEngineConnectionState.Connected);
- expect(asVoiceEngineConnectionState('reconnecting')).toBe(VoiceEngineConnectionState.Reconnecting);
- expect(asVoiceEngineConnectionState('signalReconnecting')).toBe(VoiceEngineConnectionState.SignalReconnecting);
- expect(asVoiceEngineConnectionState('failed')).toBe(VoiceEngineConnectionState.Failed);
- expect(asVoiceEngineConnectionState('garbage')).toBe(VoiceEngineConnectionState.Disconnected);
- expect(asVoiceEngineConnectionState(undefined)).toBe(VoiceEngineConnectionState.Disconnected);
- });
-
- it('starts disconnected and tracks connection attempts', () => {
- let snapshot = createVoiceConnectionSnapshot();
- expect(getVoiceConnectionStateValue(snapshot)).toBe('disconnected');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connecting');
- expect(snapshot.context.connectionAttemptId).toBe(1);
- expect(snapshot.context.voiceServerTimeoutScheduled).toBe(true);
- expect(snapshot.context.connectionId).toBeNull();
- });
-
- it('marks recovered expectations without requiring an existing room', () => {
- let snapshot = createVoiceConnectionSnapshot();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.recoverExpectation',
- guildId: null,
- channelId: 'dm-1',
- });
- expect(snapshot.context.expectedRecovery).toBe(true);
- expect(snapshot.context.guildId).toBeNull();
- expect(snapshot.context.channelId).toBe('dm-1');
- expect(snapshot.context.connecting).toBe(true);
- });
-
- it('accepts VOICE_SERVER_UPDATE for the latest attempt and ignores stale attempts', () => {
- let snapshot = createVoiceConnectionSnapshot();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-2',
- });
- expect(isLatestVoiceConnectionAttempt(snapshot, 1)).toBe(false);
- const decision = selectVoiceConnectionServerUpdateDecision(
- snapshot,
- {
- guild_id: 'guild-1',
- channel_id: 'channel-2',
- connection_id: 'connection-1',
- endpoint: 'wss://voice.example',
- token: 'token',
- },
- 1,
- );
- expect(decision).toMatchObject({type: 'ignore', reason: 'stale-attempt'});
- });
-
- it('ignores channel-move VOICE_SERVER_UPDATE while not connected', () => {
- let snapshot = createVoiceConnectionSnapshot();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- const decision = selectVoiceConnectionServerUpdateDecision(snapshot, {
- guild_id: 'guild-1',
- channel_id: 'channel-2',
- connection_id: 'connection-2',
- endpoint: 'wss://voice.example',
- token: 'token',
- });
- expect(decision).toMatchObject({type: 'ignore', reason: 'stale-channel-update'});
- });
-
- it('preserves connection id while accepting a connected server channel move', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- const decision = selectVoiceConnectionServerUpdateDecision(snapshot, {
- guild_id: 'guild-1',
- channel_id: 'channel-2',
- connection_id: 'connection-2',
- endpoint: 'wss://voice-b.example',
- token: 'token-b',
- });
- expect(decision).toMatchObject({
- type: 'accept',
- isChannelMove: true,
- resolvedChannelId: 'channel-2',
- });
- if (decision.type !== 'accept') throw new Error('expected accepted decision');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.accepted',
- guildId: decision.guildId,
- channelId: decision.resolvedChannelId,
- endpoint: decision.endpoint,
- connectionId: decision.connectionId,
- isChannelMove: decision.isChannelMove,
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('channelMove');
- expect(snapshot.context.connectionId).toBe('connection-2');
- expect(snapshot.context.channelId).toBe('channel-2');
- });
-
- it('detects same-channel endpoint changes as hot-swap candidates', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- const decision = selectVoiceConnectionServerUpdateDecision(snapshot, {
- guild_id: 'guild-1',
- channel_id: 'channel-1',
- connection_id: 'connection-2',
- endpoint: 'wss://voice-b.example',
- token: 'token-b',
- });
- expect(decision).toMatchObject({type: 'accept', isRegionChange: true});
- });
-
- it('accepts roomReady after the connected event wins the LiveKit promise race', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connected');
- expect(snapshot.context.room).toBeNull();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connected');
- expect(snapshot.context.room).toBe(roomA);
- expect(snapshot.context.connected).toBe(true);
- expect(snapshot.context.connecting).toBe(false);
- });
-
- it('applies only the matching voice server timeout and routes to failed', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'other-channel',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connecting');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- expect(snapshot.context.guildId).toBeNull();
- expect(snapshot.context.channelId).toBeNull();
- expect(snapshot.context.localDisconnectReason).toBe('error');
- expect(snapshot.context.failureReason).toBe('connectTimeout');
- expect(snapshot.context.failedGuildId).toBe('guild-1');
- expect(snapshot.context.failedChannelId).toBe('channel-1');
- expect(snapshot.context.expectedRecovery).toBe(false);
- });
-
- it('routes an error disconnect while connecting to failed with a transport reason', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'error'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- expect(snapshot.context.failureReason).toBe('transport');
- expect(snapshot.context.failedChannelId).toBe('channel-1');
- expect(snapshot.context.connectionId).toBe('connection-1');
- });
-
- it('routes a connection.failed event while connecting to failed with a transport reason', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.failed', reason: 'error'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- expect(snapshot.context.failureReason).toBe('transport');
- });
-
- it('stays failed when a follow-up error disconnect arrives but exits to disconnected on a user disconnect', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.failed', reason: 'error'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'error'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- expect(snapshot.context.failureReason).toBe('transport');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'user'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('disconnected');
- expect(snapshot.context.failureReason).toBeNull();
- });
-
- it('retries from failed via connection.start and increments the attempt id', () => {
- let snapshot = startAndAccept();
- const attemptBeforeFailure = snapshot.context.connectionAttemptId;
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connecting');
- expect(snapshot.context.connectionAttemptId).toBe(attemptBeforeFailure + 1);
- expect(snapshot.context.failureReason).toBeNull();
- expect(snapshot.context.failedChannelId).toBeNull();
- });
-
- it('recovers from failed via connection.recover into connecting', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'connection.recover',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connecting');
- expect(snapshot.context.guildId).toBe('guild-1');
- expect(snapshot.context.channelId).toBe('channel-1');
- expect(snapshot.context.failureReason).toBeNull();
- });
-
- it('dismisses a failed connection via a user disconnect into disconnected', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'user'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('disconnected');
- expect(snapshot.context.failureReason).toBeNull();
- expect(snapshot.context.failedChannelId).toBeNull();
- });
-
- it('resets a failed connection into disconnected', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.timeout',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- expect(getVoiceConnectionStateValue(snapshot)).toBe('failed');
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.reset'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('disconnected');
- expect(snapshot.context.failureReason).toBeNull();
- });
-
- it('keeps server and error disconnect connection ids but clears user disconnect ids', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'server'});
- expect(snapshot.context.connectionId).toBe('connection-1');
- expect(snapshot.context.expectedRecovery).toBe(true);
- snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'error'});
- expect(snapshot.context.connectionId).toBe('connection-1');
- expect(snapshot.context.localDisconnectReason).toBe('error');
- snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnected', reason: 'user'});
- expect(snapshot.context.connectionId).toBeNull();
- expect(snapshot.context.expectedRecovery).toBe(false);
- });
-
- it('tracks reconnecting and reconnected state', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.reconnecting'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('reconnecting');
- expect(snapshot.context.reconnecting).toBe(true);
- expect(snapshot.context.expectedRecovery).toBe(true);
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.reconnected'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connected');
- expect(snapshot.context.expectedRecovery).toBe(false);
- });
-
- it('preserves connection id when disconnecting for a user-initiated channel move', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.disconnectForChannelMove'});
- expect(getVoiceConnectionStateValue(snapshot)).toBe('channelMove');
- expect(snapshot.context.connectionId).toBe('connection-1');
- expect(snapshot.context.localDisconnectReason).toBe('channelMove');
- });
-
- it('tracks hot-swap queue, completion, abort, and reset bookkeeping', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.start',
- pendingRoom: roomB,
- previousRoom: roomA,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.queueOperation'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.queueOperation'});
- expect(snapshot.context.hotSwap).toMatchObject({
- inProgress: true,
- pendingRoom: roomB,
- previousRoom: roomA,
- queuedOperationCount: 2,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.complete',
- room: roomB,
- endpoint: 'wss://voice-b.example',
- connectionId: 'connection-2',
- });
- expect(snapshot.context.room).toBe(roomB);
- expect(snapshot.context.hotSwap.inProgress).toBe(false);
- expect(snapshot.context.hotSwap.queuedOperationCount).toBe(2);
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.drainQueue'});
- expect(snapshot.context.hotSwap.queuedOperationCount).toBe(0);
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.start',
- pendingRoom: roomA,
- previousRoom: roomB,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.queueOperation'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.abort'});
- expect(snapshot.context.hotSwap).toMatchObject({
- inProgress: false,
- abortRequested: true,
- queuedOperationCount: 0,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.start',
- pendingRoom: roomA,
- previousRoom: roomB,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'hotSwap.reset'});
- expect(snapshot.context.hotSwap.abortRequested).toBe(false);
- });
-
- it('restores the connected state when a hot-swap completes while the old room was reconnecting', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.start',
- pendingRoom: roomB,
- previousRoom: roomA,
- });
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.reconnecting'});
- expect(snapshot.context.reconnecting).toBe(true);
- expect(snapshot.context.connected).toBe(false);
-
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.complete',
- room: roomB,
- endpoint: 'wss://voice-b.example',
- connectionId: 'connection-2',
- });
-
- expect(getVoiceConnectionStateValue(snapshot)).toBe('connected');
- expect(snapshot.context.connected).toBe(true);
- expect(snapshot.context.connecting).toBe(false);
- expect(snapshot.context.reconnecting).toBe(false);
- expect(snapshot.context.room).toBe(roomB);
- expect(snapshot.context.voiceServerEndpoint).toBe('wss://voice-b.example');
- expect(snapshot.context.hotSwap.inProgress).toBe(false);
- });
-
- it('ignores a hot-swap completion that arrives without an in-progress swap', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.reconnecting'});
-
- const completed = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'hotSwap.complete',
- room: roomB,
- endpoint: 'wss://voice-b.example',
- connectionId: 'connection-2',
- });
-
- expect(getVoiceConnectionStateValue(completed)).toBe('reconnecting');
- expect(completed.context.connected).toBe(false);
- expect(completed.context.reconnecting).toBe(true);
- expect(completed.context.room).toBe(roomA);
- });
-
- it('marks a connected voice-server replacement as replaced instead of a user disconnect', () => {
- let snapshot = startAndAccept();
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.roomReady', room: roomA, attemptId: 1});
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- expect(snapshot.context.localDisconnectReason).toBeNull();
-
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.accepted',
- guildId: 'guild-1',
- channelId: 'channel-1',
- endpoint: 'wss://voice-b.example',
- connectionId: 'connection-2',
- isChannelMove: false,
- });
-
- expect(snapshot.context.connected).toBe(false);
- expect(snapshot.context.localDisconnectReason).toBe('replaced');
-
- snapshot = transitionVoiceConnectionSnapshot(snapshot, {type: 'connection.connected'});
- expect(snapshot.context.localDisconnectReason).toBeNull();
- });
-
- it('keeps a null disconnect reason when a voice server is accepted while still connecting', () => {
- const snapshot = startAndAccept();
- expect(snapshot.context.connected).toBe(false);
- expect(snapshot.context.localDisconnectReason).toBeNull();
-
- const accepted = transitionVoiceConnectionSnapshot(snapshot, {
- type: 'voiceServer.accepted',
- guildId: 'guild-1',
- channelId: 'channel-1',
- endpoint: 'wss://voice-b.example',
- connectionId: 'connection-2',
- isChannelMove: false,
- });
-
- expect(accepted.context.localDisconnectReason).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.test.ts b/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.test.ts
deleted file mode 100644
index 6cd6ee4a0..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceLatencyTracker.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceLatencySnapshot,
- observeVoiceLatencyGap,
- recordVoiceLatencySample,
- startVoiceLatencyTracking,
- stopVoiceLatencyTracking,
-} from '@app/features/voice/engine/VoiceLatencyTracker';
-import {describe, expect, it} from 'vitest';
-
-describe('VoiceLatencyTracker', () => {
- it('records samples, caps history, and computes an average', () => {
- let latency = startVoiceLatencyTracking(createVoiceLatencySnapshot(), 1000);
- latency = recordVoiceLatencySample(latency, 1100, 12.4, {historyLimit: 2});
- latency = recordVoiceLatencySample(latency, 1200, 20.6, {historyLimit: 2});
- latency = recordVoiceLatencySample(latency, 1300, 31.2, {historyLimit: 2});
-
- expect(latency.status).toBe('fresh');
- expect(latency.currentLatency).toBe(31);
- expect(latency.averageLatency).toBe(26);
- expect(latency.latencyHistory).toEqual([
- {timestamp: 1200, latency: 21},
- {timestamp: 1300, latency: 31},
- ]);
- });
-
- it('treats missing samples as observation gaps instead of clearing the last measurement', () => {
- let latency = startVoiceLatencyTracking(createVoiceLatencySnapshot(), 1000);
- latency = recordVoiceLatencySample(latency, 1100, 24);
- latency = observeVoiceLatencyGap(latency, 1500);
-
- expect(latency.status).toBe('fresh');
- expect(latency.currentLatency).toBe(24);
- expect(latency.averageLatency).toBe(24);
- expect(latency.latencyHistory).toEqual([{timestamp: 1100, latency: 24}]);
- });
-
- it('marks old measurements stale without erasing their value', () => {
- let latency = startVoiceLatencyTracking(createVoiceLatencySnapshot(), 1000);
- latency = recordVoiceLatencySample(latency, 1100, 24, {staleAfterMs: 1000});
- latency = observeVoiceLatencyGap(latency, 2201, {staleAfterMs: 1000});
-
- expect(latency.status).toBe('stale');
- expect(latency.currentLatency).toBe(24);
- });
-
- it('keeps stopped tracking idle while retaining the last value until reset', () => {
- let latency = startVoiceLatencyTracking(createVoiceLatencySnapshot(), 1000);
- latency = recordVoiceLatencySample(latency, 1100, 24);
- latency = stopVoiceLatencyTracking(latency, 1200);
-
- expect(latency.status).toBe('idle');
- expect(latency.currentLatency).toBe(24);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceLocalAudioReconcilePolicy.test.ts b/fluxer_app/src/features/voice/engine/VoiceLocalAudioReconcilePolicy.test.ts
deleted file mode 100644
index 81ea0a74c..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceLocalAudioReconcilePolicy.test.ts
+++ /dev/null
@@ -1,407 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceLocalAudioReconcileCoalescerSnapshot,
- createVoiceMicrophoneFailureLatchSnapshot,
- isVoiceMicrophoneFailureLatchActive,
- selectVoiceLocalAudioEffectiveSelfMute,
- selectVoiceLocalAudioReconcileCoalescedCount,
- selectVoiceLocalAudioReconcileRunReasons,
- selectVoiceLocalAudioReconcileStartedRuns,
- selectVoiceMicrophoneFailureCount,
- shouldStartVoiceLocalAudioReconcileRun,
- shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns,
- transitionVoiceLocalAudioReconcileCoalescerSnapshot,
- transitionVoiceMicrophoneFailureLatchSnapshot,
- VOICE_LOCAL_AUDIO_RECONCILE_FOLLOW_UP_WARN_LIMIT,
- VOICE_LOCAL_AUDIO_RECONCILE_REASON_LIMIT,
- type VoiceLocalAudioReconcileCoalescerEvent,
- type VoiceLocalAudioReconcileCoalescerSnapshot,
- type VoiceMicrophoneFailureLatchEvent,
- type VoiceMicrophoneFailureLatchSnapshot,
-} from '@app/features/voice/engine/VoiceLocalAudioReconcilePolicy';
-import {describe, expect, it} from 'vitest';
-
-const RUNAWAY_RUN_LIMIT = 512;
-
-function sendCoalescer(
- snapshot: VoiceLocalAudioReconcileCoalescerSnapshot,
- event: VoiceLocalAudioReconcileCoalescerEvent,
-): VoiceLocalAudioReconcileCoalescerSnapshot {
- return transitionVoiceLocalAudioReconcileCoalescerSnapshot(snapshot, event);
-}
-
-function sendLatch(
- snapshot: VoiceMicrophoneFailureLatchSnapshot,
- event: VoiceMicrophoneFailureLatchEvent,
-): VoiceMicrophoneFailureLatchSnapshot {
- return transitionVoiceMicrophoneFailureLatchSnapshot(snapshot, event);
-}
-
-class ReconcileHarness {
- snapshot = createVoiceLocalAudioReconcileCoalescerSnapshot();
- startedRuns: Array<ReadonlyArray<string>> = [];
- private runningDepth = 0;
-
- constructor(private readonly body: (harness: ReconcileHarness) => void) {}
-
- request(reason: string): void {
- const previous = this.snapshot;
- this.snapshot = sendCoalescer(previous, {type: 'run.requested', reason});
- if (shouldStartVoiceLocalAudioReconcileRun(previous, this.snapshot)) {
- this.drain();
- }
- }
-
- private drain(): void {
- expect(this.runningDepth).toBe(0);
- this.runningDepth += 1;
- for (;;) {
- if (this.startedRuns.length >= RUNAWAY_RUN_LIMIT) {
- throw new Error('runaway local audio reconciliation');
- }
- this.startedRuns.push(selectVoiceLocalAudioReconcileRunReasons(this.snapshot));
- this.body(this);
- const previous = this.snapshot;
- this.snapshot = sendCoalescer(previous, {type: 'run.settled'});
- if (!shouldStartVoiceLocalAudioReconcileRun(previous, this.snapshot)) break;
- }
- this.runningDepth -= 1;
- }
-}
-
-describe('voice local audio reconcile coalescer', () => {
- it('starts a run when a request arrives while idle', () => {
- const initial = createVoiceLocalAudioReconcileCoalescerSnapshot();
- const next = sendCoalescer(initial, {type: 'run.requested', reason: 'voice room connected'});
- expect(shouldStartVoiceLocalAudioReconcileRun(initial, next)).toBe(true);
- expect(next.value).toBe('running');
- expect(selectVoiceLocalAudioReconcileStartedRuns(next)).toBe(1);
- expect(selectVoiceLocalAudioReconcileRunReasons(next)).toEqual(['voice room connected']);
- });
-
- it('absorbs a request that arrives while a run is in flight instead of starting a second run', () => {
- const running = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice room connected',
- });
- const dirty = sendCoalescer(running, {type: 'run.requested', reason: 'local audio state change'});
- expect(shouldStartVoiceLocalAudioReconcileRun(running, dirty)).toBe(false);
- expect(dirty.value).toBe('runningDirty');
- expect(selectVoiceLocalAudioReconcileStartedRuns(dirty)).toBe(1);
- expect(selectVoiceLocalAudioReconcileCoalescedCount(dirty)).toBe(1);
- });
-
- it('collapses K triggers arriving during one run into exactly one follow-up run', () => {
- const triggerCount = 10;
- let pendingTriggers = triggerCount;
- const harness = new ReconcileHarness((self) => {
- for (let index = 0; index < pendingTriggers; index++) {
- self.request(`trigger ${index}`);
- }
- pendingTriggers = 0;
- });
-
- harness.request('voice room connected');
-
- expect(harness.startedRuns).toHaveLength(2);
- expect(selectVoiceLocalAudioReconcileStartedRuns(harness.snapshot)).toBe(2);
- expect(harness.snapshot.value).toBe('idle');
- });
-
- it('records how many triggers were coalesced into the follow-up run', () => {
- let snapshot = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice room connected',
- });
- for (let index = 0; index < 10; index++) {
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: `trigger ${index}`});
- }
- expect(selectVoiceLocalAudioReconcileCoalescedCount(snapshot)).toBe(10);
- expect(selectVoiceLocalAudioReconcileStartedRuns(snapshot)).toBe(1);
-
- const followUp = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(followUp.value).toBe('running');
- expect(selectVoiceLocalAudioReconcileStartedRuns(followUp)).toBe(2);
- expect(selectVoiceLocalAudioReconcileCoalescedCount(followUp)).toBe(0);
- });
-
- it('returns to idle when a clean run settles and does not start another run', () => {
- const running = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice state update',
- });
- const settled = sendCoalescer(running, {type: 'run.settled'});
- expect(settled.value).toBe('idle');
- expect(shouldStartVoiceLocalAudioReconcileRun(running, settled)).toBe(false);
- expect(selectVoiceLocalAudioReconcileRunReasons(settled)).toEqual([]);
- });
-
- it('promotes the pending reasons into the follow-up run exactly once', () => {
- let snapshot = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice room connected',
- });
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'local audio state change'});
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'voice state update'});
- snapshot = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(selectVoiceLocalAudioReconcileRunReasons(snapshot)).toEqual([
- 'local audio state change',
- 'voice state update',
- ]);
- expect(selectVoiceLocalAudioReconcileStartedRuns(snapshot)).toBe(2);
- const idle = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(idle.value).toBe('idle');
- expect(selectVoiceLocalAudioReconcileStartedRuns(idle)).toBe(2);
- });
-
- it('ignores a settle that arrives while idle', () => {
- const initial = createVoiceLocalAudioReconcileCoalescerSnapshot();
- const settled = sendCoalescer(initial, {type: 'run.settled'});
- expect(settled.value).toBe('idle');
- expect(selectVoiceLocalAudioReconcileStartedRuns(settled)).toBe(0);
- });
-
- it('keeps the reconcile-storm ordering linear instead of doubling', () => {
- const failingRuns = 8;
- let remainingFailures = failingRuns;
- const harness = new ReconcileHarness((self) => {
- if (remainingFailures === 0) return;
- remainingFailures -= 1;
- self.request('local audio state change');
- self.request('voice state update');
- });
-
- harness.request('voice room connected');
-
- expect(harness.startedRuns).toHaveLength(failingRuns + 1);
- expect(harness.startedRuns.length).toBeLessThan(2 ** failingRuns);
- expect(harness.snapshot.value).toBe('idle');
- });
-
- it('settles after two runs once the failure latches self-mute and stops emitting triggers', () => {
- let latched = false;
- const harness = new ReconcileHarness((self) => {
- if (latched) return;
- latched = true;
- self.request('local audio state change');
- self.request('voice state update');
- });
-
- harness.request('voice room connected');
-
- expect(harness.startedRuns).toEqual([['voice room connected'], ['local audio state change', 'voice state update']]);
- expect(harness.snapshot.value).toBe('idle');
- });
-
- it('never drops a trigger: a run always starts after the last request in a burst', () => {
- const observedAtRunStart: Array<number> = [];
- let requestCounter = 0;
- let burst = 3;
- const harness = new ReconcileHarness((self) => {
- observedAtRunStart.push(requestCounter);
- for (let index = 0; index < burst; index++) {
- requestCounter += 1;
- self.request(`burst ${requestCounter}`);
- }
- burst = 0;
- });
-
- requestCounter += 1;
- harness.request(`burst ${requestCounter}`);
-
- expect(observedAtRunStart).toEqual([1, 4]);
- expect(observedAtRunStart[observedAtRunStart.length - 1]).toBe(requestCounter);
- });
-
- it('caps the reason list while still counting every coalesced trigger', () => {
- let snapshot = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice room connected',
- });
- const triggerCount = VOICE_LOCAL_AUDIO_RECONCILE_REASON_LIMIT + 5;
- for (let index = 0; index < triggerCount; index++) {
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: `trigger ${index}`});
- }
- expect(selectVoiceLocalAudioReconcileCoalescedCount(snapshot)).toBe(triggerCount);
- const followUp = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(selectVoiceLocalAudioReconcileRunReasons(followUp)).toHaveLength(VOICE_LOCAL_AUDIO_RECONCILE_REASON_LIMIT);
- });
-
- it('deduplicates repeated reasons so a storm stays readable', () => {
- let snapshot = sendCoalescer(createVoiceLocalAudioReconcileCoalescerSnapshot(), {
- type: 'run.requested',
- reason: 'voice room connected',
- });
- for (let index = 0; index < 50; index++) {
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'local audio state change'});
- }
- const followUp = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(selectVoiceLocalAudioReconcileRunReasons(followUp)).toEqual(['local audio state change']);
- expect(selectVoiceLocalAudioReconcileCoalescedCount(snapshot)).toBe(50);
- });
-
- it('flags a livelock once the follow-up runs never stop chaining', () => {
- let snapshot = createVoiceLocalAudioReconcileCoalescerSnapshot();
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'voice room connected'});
- for (let index = 0; index < VOICE_LOCAL_AUDIO_RECONCILE_FOLLOW_UP_WARN_LIMIT; index++) {
- expect(shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns(snapshot)).toBe(false);
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'local audio state change'});
- snapshot = sendCoalescer(snapshot, {type: 'run.settled'});
- }
- expect(shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns(snapshot)).toBe(true);
-
- const drained = sendCoalescer(snapshot, {type: 'run.settled'});
- expect(drained.value).toBe('idle');
- expect(shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns(drained)).toBe(false);
- });
-
- it('crosses the livelock threshold once so the drain can warn a single time', () => {
- let snapshot = createVoiceLocalAudioReconcileCoalescerSnapshot();
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'voice room connected'});
- let crossings = 0;
- for (let index = 0; index < VOICE_LOCAL_AUDIO_RECONCILE_FOLLOW_UP_WARN_LIMIT * 4; index++) {
- const before = snapshot;
- snapshot = sendCoalescer(snapshot, {type: 'run.requested', reason: 'local audio state change'});
- snapshot = sendCoalescer(snapshot, {type: 'run.settled'});
- if (
- shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns(snapshot) &&
- !shouldWarnAboutVoiceLocalAudioReconcileFollowUpRuns(before)
- ) {
- crossings += 1;
- }
- }
- expect(crossings).toBe(1);
- });
-
- it('is level-triggered: the reason never selects control flow', () => {
- const script: Array<VoiceLocalAudioReconcileCoalescerEvent> = [
- {type: 'run.requested', reason: 'first'},
- {type: 'run.requested', reason: 'second'},
- {type: 'run.settled'},
- {type: 'run.settled'},
- ];
- const replay = (reasonFor: (index: number) => string) => {
- let snapshot = createVoiceLocalAudioReconcileCoalescerSnapshot();
- const trace: Array<string> = [];
- script.forEach((event, index) => {
- snapshot = sendCoalescer(
- snapshot,
- event.type === 'run.requested' ? {type: 'run.requested', reason: reasonFor(index)} : event,
- );
- trace.push(`${String(snapshot.value)}:${selectVoiceLocalAudioReconcileStartedRuns(snapshot)}`);
- });
- return trace;
- };
- expect(replay((index) => `reason-${index}`)).toEqual(replay(() => 'voice state update'));
- });
-});
-
-describe('voice microphone failure latch', () => {
- const scope = {channelId: 'channel-1', inputDeviceId: 'mic-1'};
-
- function latchedSnapshot(): VoiceMicrophoneFailureLatchSnapshot {
- return sendLatch(createVoiceMicrophoneFailureLatchSnapshot(), {type: 'microphone.enableFailed', ...scope});
- }
-
- it('starts clear', () => {
- const initial = createVoiceMicrophoneFailureLatchSnapshot();
- expect(isVoiceMicrophoneFailureLatchActive(initial)).toBe(false);
- expect(selectVoiceMicrophoneFailureCount(initial)).toBe(0);
- });
-
- it('latches when enabling the microphone fails', () => {
- const latched = latchedSnapshot();
- expect(isVoiceMicrophoneFailureLatchActive(latched)).toBe(true);
- expect(selectVoiceMicrophoneFailureCount(latched)).toBe(1);
- });
-
- it('keeps forcing self-mute when the server echoes a stale self_mute:false', () => {
- const latched = latchedSnapshot();
- expect(selectVoiceLocalAudioEffectiveSelfMute({localSelfMute: true, microphoneFailureLatched: true})).toBe(true);
- const afterStaleEcho = sendLatch(latched, {type: 'scope.observed', ...scope});
- expect(isVoiceMicrophoneFailureLatchActive(afterStaleEcho)).toBe(true);
- expect(
- selectVoiceLocalAudioEffectiveSelfMute({
- localSelfMute: false,
- microphoneFailureLatched: isVoiceMicrophoneFailureLatchActive(afterStaleEcho),
- }),
- ).toBe(true);
- });
-
- it('survives repeated recomputes of the audio-controls snapshot', () => {
- let snapshot = latchedSnapshot();
- for (let index = 0; index < 20; index++) {
- snapshot = sendLatch(snapshot, {type: 'scope.observed', ...scope});
- expect(
- selectVoiceLocalAudioEffectiveSelfMute({
- localSelfMute: false,
- microphoneFailureLatched: isVoiceMicrophoneFailureLatchActive(snapshot),
- }),
- ).toBe(true);
- }
- expect(selectVoiceMicrophoneFailureCount(snapshot)).toBe(1);
- });
-
- it('clears when the microphone is enabled successfully', () => {
- const cleared = sendLatch(latchedSnapshot(), {type: 'microphone.enableSucceeded'});
- expect(isVoiceMicrophoneFailureLatchActive(cleared)).toBe(false);
- expect(selectVoiceMicrophoneFailureCount(cleared)).toBe(0);
- });
-
- it('clears when the user changes their own mute intent', () => {
- const cleared = sendLatch(latchedSnapshot(), {type: 'mute.userIntentChanged'});
- expect(isVoiceMicrophoneFailureLatchActive(cleared)).toBe(false);
- });
-
- it('clears when the voice connection is torn down or re-established', () => {
- const cleared = sendLatch(latchedSnapshot(), {type: 'latch.reset'});
- expect(isVoiceMicrophoneFailureLatchActive(cleared)).toBe(false);
- });
-
- it('clears when the active channel changes', () => {
- const cleared = sendLatch(latchedSnapshot(), {
- type: 'scope.observed',
- channelId: 'channel-2',
- inputDeviceId: scope.inputDeviceId,
- });
- expect(isVoiceMicrophoneFailureLatchActive(cleared)).toBe(false);
- });
-
- it('clears when the input device changes', () => {
- const cleared = sendLatch(latchedSnapshot(), {
- type: 'scope.observed',
- channelId: scope.channelId,
- inputDeviceId: 'mic-2',
- });
- expect(isVoiceMicrophoneFailureLatchActive(cleared)).toBe(false);
- });
-
- it('re-latches after a cleared latch fails again and counts the failures', () => {
- let snapshot = latchedSnapshot();
- snapshot = sendLatch(snapshot, {type: 'mute.userIntentChanged'});
- snapshot = sendLatch(snapshot, {type: 'microphone.enableFailed', ...scope});
- expect(isVoiceMicrophoneFailureLatchActive(snapshot)).toBe(true);
- expect(selectVoiceMicrophoneFailureCount(snapshot)).toBe(1);
- snapshot = sendLatch(snapshot, {type: 'microphone.enableFailed', ...scope});
- expect(selectVoiceMicrophoneFailureCount(snapshot)).toBe(2);
- });
-
- it('does not latch on recovery events observed while already clear', () => {
- let snapshot = createVoiceMicrophoneFailureLatchSnapshot();
- for (const event of [
- {type: 'microphone.enableSucceeded'},
- {type: 'mute.userIntentChanged'},
- {type: 'latch.reset'},
- {type: 'scope.observed', ...scope},
- ] as Array<VoiceMicrophoneFailureLatchEvent>) {
- snapshot = sendLatch(snapshot, event);
- expect(isVoiceMicrophoneFailureLatchActive(snapshot)).toBe(false);
- }
- });
-
- it('leaves self-mute untouched when nothing has failed', () => {
- expect(selectVoiceLocalAudioEffectiveSelfMute({localSelfMute: false, microphoneFailureLatched: false})).toBe(false);
- expect(selectVoiceLocalAudioEffectiveSelfMute({localSelfMute: true, microphoneFailureLatched: false})).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.ts b/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.ts
deleted file mode 100644
index daad25366..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type LocalSpeakingOverrideInput,
- resolveLocalSpeakingOverrideState,
- resolveVoiceActivityGateState,
- resolveVoiceActivityThresholdRms,
- updateVoiceActivityNoiseFloorRms,
- type VoiceActivityGateInput,
- type VoiceActivityGateState,
-} from '@app/features/voice/engine/VoiceLocalSpeakingGate';
-import {
- getLocalSpeakingThresholdRms,
- LOCAL_MAX_RMS,
- LOCAL_MIN_RMS,
- SPEAKING_LOCAL_RELEASE_MS,
-} from '@app/features/voice/engine/VoiceSpeakingThreshold';
-import {describe, expect, it} from 'vitest';
-
-const UNMUTED_OPEN_MIC: LocalSpeakingOverrideInput = {
- pushToTalkActive: false,
- pushToMuteActive: false,
- pushToMuteHeld: false,
- selfDeaf: false,
- effectiveSelfMute: false,
- hasMicrophonePublication: true,
- microphonePublicationMuted: false,
-};
-
-describe('resolveLocalSpeakingOverrideState', () => {
- it('lets VAD own normal open-mic speaking state', () => {
- expect(resolveLocalSpeakingOverrideState(UNMUTED_OPEN_MIC)).toBeNull();
- });
- it('forces local speaking off when open mic is effectively muted', () => {
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- effectiveSelfMute: true,
- microphonePublicationMuted: true,
- }),
- ).toBe(false);
- });
- it('uses the push-to-talk transmit gate instead of VAD', () => {
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- pushToTalkActive: true,
- }),
- ).toBe(true);
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- pushToTalkActive: true,
- effectiveSelfMute: true,
- microphonePublicationMuted: true,
- }),
- ).toBe(false);
- });
- it('does not mark push-to-talk speech active without a live mic publication', () => {
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- pushToTalkActive: true,
- hasMicrophonePublication: false,
- microphonePublicationMuted: true,
- }),
- ).toBe(false);
- });
- it('forces local speaking off while push-to-mute is held', () => {
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- pushToMuteActive: true,
- pushToMuteHeld: true,
- }),
- ).toBe(false);
- });
- it('forces local speaking off while deafened', () => {
- expect(
- resolveLocalSpeakingOverrideState({
- ...UNMUTED_OPEN_MIC,
- selfDeaf: true,
- }),
- ).toBe(false);
- });
-});
-
-const GATE_TICK_MS = 50;
-const KEYBOARD_NOISE_RMS = 0.012;
-const SPEECH_RMS = 0.06;
-
-function runGate(samples: ReadonlyArray<number>, thresholdRms: number): Array<boolean> {
- let open = false;
- let silenceStartedAtMs: number | null = null;
- return samples.map((rms, index) => {
- const input: VoiceActivityGateInput = {
- rms,
- thresholdRms,
- nowMs: index * GATE_TICK_MS,
- silenceStartedAtMs,
- gateOpen: open,
- releaseDelayMs: SPEAKING_LOCAL_RELEASE_MS,
- };
- const next = resolveVoiceActivityGateState(input);
- open = next.open;
- silenceStartedAtMs = next.silenceStartedAtMs;
- return open;
- });
-}
-
-describe('resolveVoiceActivityGateState', () => {
- it('keeps keyboard noise off the wire when the activity threshold is raised', () => {
- const opened = runGate(new Array(20).fill(KEYBOARD_NOISE_RMS), getLocalSpeakingThresholdRms(100));
- expect(opened.some((open) => open)).toBe(false);
- });
-
- it('still transmits the same noise when the activity threshold is lowered', () => {
- const opened = runGate(new Array(20).fill(KEYBOARD_NOISE_RMS), getLocalSpeakingThresholdRms(0));
- expect(opened.every((open) => open)).toBe(true);
- });
-
- it('opens on the first sample at or above the threshold and clears the silence clock', () => {
- const expected: VoiceActivityGateState = {open: true, silenceStartedAtMs: null};
- expect(
- resolveVoiceActivityGateState({
- rms: SPEECH_RMS,
- thresholdRms: getLocalSpeakingThresholdRms(100),
- nowMs: 1_000,
- silenceStartedAtMs: 800,
- gateOpen: false,
- releaseDelayMs: SPEAKING_LOCAL_RELEASE_MS,
- }),
- ).toEqual(expected);
- });
-
- it('holds the gate open for the release window before closing', () => {
- const threshold = getLocalSpeakingThresholdRms(100);
- expect(
- resolveVoiceActivityGateState({
- rms: KEYBOARD_NOISE_RMS,
- thresholdRms: threshold,
- nowMs: 1_000,
- silenceStartedAtMs: null,
- gateOpen: true,
- releaseDelayMs: SPEAKING_LOCAL_RELEASE_MS,
- }),
- ).toEqual({open: true, silenceStartedAtMs: 1_000});
- expect(
- resolveVoiceActivityGateState({
- rms: KEYBOARD_NOISE_RMS,
- thresholdRms: threshold,
- nowMs: 1_000 + SPEAKING_LOCAL_RELEASE_MS - 1,
- silenceStartedAtMs: 1_000,
- gateOpen: true,
- releaseDelayMs: SPEAKING_LOCAL_RELEASE_MS,
- }).open,
- ).toBe(true);
- expect(
- resolveVoiceActivityGateState({
- rms: KEYBOARD_NOISE_RMS,
- thresholdRms: threshold,
- nowMs: 1_000 + SPEAKING_LOCAL_RELEASE_MS,
- silenceStartedAtMs: 1_000,
- gateOpen: true,
- releaseDelayMs: SPEAKING_LOCAL_RELEASE_MS,
- }).open,
- ).toBe(false);
- });
-
- it('closes after speech stops and reopens when speech returns', () => {
- const threshold = getLocalSpeakingThresholdRms(100);
- const opened = runGate(
- [SPEECH_RMS, SPEECH_RMS, ...new Array(6).fill(KEYBOARD_NOISE_RMS), SPEECH_RMS, KEYBOARD_NOISE_RMS],
- threshold,
- );
- expect(opened).toEqual([true, true, true, true, true, true, false, false, true, true]);
- });
-});
-
-describe('resolveVoiceActivityThresholdRms', () => {
- it('follows the activity threshold slider when auto sensitivity is off', () => {
- expect(resolveVoiceActivityThresholdRms({autoSensitivity: false, vadThreshold: 100, noiseFloorRms: 0})).toBe(
- getLocalSpeakingThresholdRms(100),
- );
- expect(resolveVoiceActivityThresholdRms({autoSensitivity: false, vadThreshold: 0, noiseFloorRms: 0})).toBe(
- getLocalSpeakingThresholdRms(0),
- );
- });
-
- it('ignores the slider and tracks the measured noise floor when auto sensitivity is on', () => {
- expect(
- resolveVoiceActivityThresholdRms({autoSensitivity: true, vadThreshold: 0, noiseFloorRms: 0.005}),
- ).toBeCloseTo(0.015, 6);
- });
-
- it('clamps the auto threshold to the local speaking range', () => {
- expect(resolveVoiceActivityThresholdRms({autoSensitivity: true, vadThreshold: 50, noiseFloorRms: 0})).toBe(
- LOCAL_MIN_RMS,
- );
- expect(resolveVoiceActivityThresholdRms({autoSensitivity: true, vadThreshold: 50, noiseFloorRms: 1})).toBe(
- LOCAL_MAX_RMS,
- );
- });
-});
-
-describe('updateVoiceActivityNoiseFloorRms', () => {
- it('converges on the level measured while the gate is closed', () => {
- let noiseFloorRms = 0;
- for (let i = 0; i < 200; i++) {
- noiseFloorRms = updateVoiceActivityNoiseFloorRms(noiseFloorRms, KEYBOARD_NOISE_RMS);
- }
- expect(noiseFloorRms).toBeCloseTo(KEYBOARD_NOISE_RMS, 4);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraph.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraph.test.ts
deleted file mode 100644
index 9241ed635..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraph.test.ts
+++ /dev/null
@@ -1,1194 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildVoiceMediaGraphNativeCameraQualityCommand,
- buildVoiceMediaGraphNativeCameraSubscriptionCommand,
- buildVoiceMediaGraphNativeScreenShareQualityCommand,
- buildVoiceMediaGraphNativeScreenShareSubscriptionCommands,
- createVoiceMediaGraphSnapshot,
- getVoiceMediaGraphWatchIntentStateValue,
- mergeVoiceMediaGraphTrackInfo,
- normalizeVoiceMediaGraphViewerStreamKeys,
- PUBLICATION_MISSING_TIMEOUT_MS,
- PUBLISHER_REPUBLISH_GRACE_MS,
- selectVoiceMediaGraphAttempt,
- selectVoiceMediaGraphDeadline,
- selectVoiceMediaGraphDeferredStopKeys,
- selectVoiceMediaGraphFailure,
- selectVoiceMediaGraphHasFailureForStreamKey,
- selectVoiceMediaGraphStatsTrackInfo,
- selectVoiceMediaGraphSubscriptionCommands,
- selectVoiceMediaGraphSubscriptionEntry,
- selectVoiceMediaGraphViewerStreamKeys,
- selectVoiceMediaGraphWatchGeneration,
- selectVoiceMediaGraphWatchStopReason,
- transitionVoiceMediaGraph,
- transitionVoiceMediaGraphViewerStreamKeys,
- type VoiceMediaGraphDeadline,
- type VoiceMediaGraphFailure,
- type VoiceMediaGraphSnapshot,
- type VoiceMediaGraphStatsTrackObservation,
- voiceMediaGraphDeferredStopDeadlineKey,
- voiceMediaGraphPublicationMissingDeadlineKey,
- voiceMediaGraphWatchAttemptDeadlineKey,
- WATCH_ATTEMPT_TIMEOUT_MS,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {resolveVoiceMediaGraphPerTrackInfo} from '@app/features/voice/engine/VoiceMediaGraphStats';
-import {VoiceTrackSource} from '@app/features/voice/engine/VoiceTrackSource';
-import type {VoiceEngineV2PerTrackStats} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-function failure(overrides: Partial<VoiceMediaGraphFailure>): VoiceMediaGraphFailure {
- return {
- code: -2202,
- reason: 'remote-track-subscription-failed',
- reportedAt: 1000,
- source: 'screen_share',
- ...overrides,
- };
-}
-
-const STREAM_A = 'dm:channel-a:connection-a';
-const STREAM_B = 'dm:channel-a:connection-b';
-const STREAM_C = 'guild-a:channel-a:connection-c';
-
-describe('VoiceMediaGraph watch generations', () => {
- it('clears stale failures for the same rejoined connection when a watch starts', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({participantIdentity: 'user_2_connection_1'}),
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: 'dm:channel:connection_1'});
-
- expect(selectVoiceMediaGraphWatchGeneration(graph, 'dm:channel:connection_1')).toBe(1);
- expect(selectVoiceMediaGraphFailure(graph, {participantIdentity: 'user_2_connection_1'})).toBeNull();
- });
-
- it('scopes attempts to the current attempt key', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: 'dm:channel:connection_1',
- attemptKey: 'attempt-1',
- startedAt: 1000,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: 'dm:channel:connection_1',
- attemptKey: 'attempt-2',
- renderedAt: 1100,
- });
-
- expect(selectVoiceMediaGraphAttempt(graph, 'dm:channel:connection_1')).toEqual({
- attemptKey: 'attempt-1',
- startedAt: 1000,
- hasRenderedVideoFrame: false,
- generation: 0,
- holders: 1,
- });
- });
-
- it('stops watches by clearing generation, attempt, and stream failure state', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: 'dm:channel:connection_1'});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({streamKey: 'dm:channel:connection_1'}),
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: 'dm:channel:connection_1',
- attemptKey: 'attempt-1',
- startedAt: 1000,
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: 'dm:channel:connection_1'});
-
- expect(selectVoiceMediaGraphWatchGeneration(graph, 'dm:channel:connection_1')).toBe(0);
- expect(selectVoiceMediaGraphAttempt(graph, 'dm:channel:connection_1')).toBeNull();
- expect(selectVoiceMediaGraphHasFailureForStreamKey(graph, 'dm:channel:connection_1')).toBe(false);
- });
-});
-
-describe('VoiceMediaGraph watch intent', () => {
- it('normalizes viewer stream keys by dropping empty and duplicate keys', () => {
- expect(normalizeVoiceMediaGraphViewerStreamKeys([STREAM_A, '', STREAM_A, STREAM_B, STREAM_B])).toEqual([
- STREAM_A,
- STREAM_B,
- ]);
- });
-
- it('starts idle and moves to watching when a stream is added', () => {
- let graph = createVoiceMediaGraphSnapshot();
- expect(getVoiceMediaGraphWatchIntentStateValue(graph)).toBe('idle');
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_A});
- expect(getVoiceMediaGraphWatchIntentStateValue(graph)).toBe('watching');
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_A]);
- });
-
- it('keeps add idempotent for the same stream key', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_A});
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_A]);
- });
-
- it('replaces the watcher set with canonical order', () => {
- const keys = transitionVoiceMediaGraphViewerStreamKeys([STREAM_A], {
- type: 'watchIntent.replace',
- keys: [STREAM_B, STREAM_A, STREAM_B],
- });
- expect(keys).toEqual([STREAM_B, STREAM_A]);
- });
-
- it('removes a single stream and returns to idle after the last stream is removed', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'watchIntent.replace',
- keys: [STREAM_A, STREAM_B],
- });
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.remove', key: STREAM_A});
- expect(getVoiceMediaGraphWatchIntentStateValue(graph)).toBe('watching');
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_B]);
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.remove', key: STREAM_B});
- expect(getVoiceMediaGraphWatchIntentStateValue(graph)).toBe('idle');
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([]);
- });
-
- it('removes many inactive streams without disturbing unrelated keys', () => {
- const keys = transitionVoiceMediaGraphViewerStreamKeys([STREAM_A, STREAM_B, STREAM_C], {
- type: 'watchIntent.removeMany',
- keys: [STREAM_A, STREAM_C],
- });
- expect(keys).toEqual([STREAM_B]);
- });
-
- it('tracks deferred stops only for currently watched streams', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_B});
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).has(STREAM_B)).toBe(false);
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A});
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).has(STREAM_A)).toBe(true);
- });
-
- it('cancels deferred stops when a stream is republished', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.cancelDeferredRemove', key: STREAM_A});
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_A]);
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).size).toBe(0);
- });
-
- it('drops deferred stops when the stream is removed or replaced away', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'watchIntent.replace',
- keys: [STREAM_A, STREAM_B],
- });
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.remove', key: STREAM_A});
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).has(STREAM_A)).toBe(false);
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_B});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.replace', keys: [STREAM_C]});
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_C]);
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).size).toBe(0);
- });
-
- it('handles stop, restart, stop cycles without multiplying keys', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- for (let index = 0; index < 50; index += 1) {
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.cancelDeferredRemove', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_A});
- }
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([STREAM_A]);
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).size).toBe(0);
- });
-
- it('reset clears watched and deferred streams', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.reset'});
- expect(getVoiceMediaGraphWatchIntentStateValue(graph)).toBe('idle');
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([]);
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).size).toBe(0);
- });
-});
-
-describe('VoiceMediaGraph subscription commands', () => {
- it('records source-scoped screen-share subscribe commands in the graph', () => {
- let graph = createVoiceMediaGraphSnapshot();
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: null,
- context: 'focused',
- });
-
- expect(
- selectVoiceMediaGraphSubscriptionEntry(graph, 'user_2_connection_2', VoiceTrackSource.ScreenShare),
- ).toMatchObject({
- subscribed: true,
- enabled: true,
- quality: 'high',
- context: 'focused',
- });
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {
- type: 'subscribePublication',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- enabled: true,
- quality: 'high',
- },
- ]);
- });
-
- it('emits disable and low-quality commands when a screen-share subscription becomes hidden', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: null,
- context: 'focused',
- });
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.clearCommands'});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.setContext',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- context: 'hidden',
- });
-
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {
- type: 'setPublicationEnabled',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- enabled: false,
- },
- {
- type: 'setPublicationQuality',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- quality: 'low',
- },
- ]);
- });
-
- it('emits a forced resubscribe command after screen-share republish', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: null,
- context: 'focused',
- });
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.clearCommands'});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.reattachAfterPublish',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- forceResubscribe: true,
- });
-
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {
- type: 'resubscribePublication',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- enabled: true,
- quality: 'high',
- },
- ]);
- });
-
- it('cleans up only the requested subscription source', () => {
- const element = {};
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: element,
- context: 'focused',
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.Camera,
- hasPublication: true,
- observedElement: null,
- quality: 'low',
- });
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.clearCommands'});
-
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.cleanup', source: VoiceTrackSource.ScreenShare});
-
- expect(
- selectVoiceMediaGraphSubscriptionEntry(graph, 'user_2_connection_2', VoiceTrackSource.ScreenShare),
- ).toBeNull();
- expect(selectVoiceMediaGraphSubscriptionEntry(graph, 'user_2_connection_2', VoiceTrackSource.Camera)).toMatchObject(
- {
- subscribed: true,
- quality: 'low',
- },
- );
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {
- type: 'disconnectObserver',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- },
- {
- type: 'unsubscribePublication',
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- },
- ]);
- });
-
- it('does not subscribe hidden native screen-share media', () => {
- expect(
- buildVoiceMediaGraphNativeScreenShareSubscriptionCommands({
- participantIdentity: 'user_2_connection_2',
- subscribed: false,
- enabled: false,
- quality: 'low',
- }),
- ).toEqual([
- {
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShare,
- subscribed: false,
- enabled: false,
- },
- {
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.ScreenShareAudio,
- subscribed: false,
- enabled: false,
- },
- ]);
- });
-
- it('only emits native screen-share quality commands while enabled', () => {
- expect(
- buildVoiceMediaGraphNativeScreenShareQualityCommand({
- participantIdentity: 'user_2_connection_2',
- enabled: false,
- quality: 'high',
- }),
- ).toBeNull();
- });
-
- it('builds native camera placeholder subscriptions by participant identity', () => {
- expect(
- buildVoiceMediaGraphNativeCameraSubscriptionCommand({
- participantIdentity: 'user_2_connection_2',
- subscribed: true,
- quality: 'low',
- }),
- ).toEqual({
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.Camera,
- subscribed: true,
- enabled: true,
- quality: 'low',
- });
- });
-
- it('builds native camera quality updates without toggling enabled state', () => {
- expect(
- buildVoiceMediaGraphNativeCameraQualityCommand({
- participantIdentity: 'user_2_connection_2',
- quality: 'high',
- }),
- ).toEqual({
- participantIdentity: 'user_2_connection_2',
- source: VoiceTrackSource.Camera,
- subscribed: true,
- quality: 'high',
- });
- });
-});
-
-function observation(overrides: Partial<VoiceMediaGraphStatsTrackObservation>): VoiceMediaGraphStatsTrackObservation {
- return {
- trackSid: null,
- trackIdentifier: null,
- mediaSourceId: null,
- mid: null,
- rid: null,
- ssrc: null,
- participantIdentity: null,
- participantSid: null,
- source: null,
- direction: 'recv',
- kind: 'video',
- fps: null,
- width: null,
- height: null,
- sourceFps: null,
- sourceWidth: null,
- sourceHeight: null,
- ...overrides,
- };
-}
-
-function subscribedScreenShareGraph(participantIdentity: string): VoiceMediaGraphSnapshot {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- hasPublication: true,
- observedElement: null,
- context: 'focused',
- });
- return transitionVoiceMediaGraph(graph, {type: 'subscription.clearCommands'});
-}
-
-describe('VoiceMediaGraph generation scoping', () => {
- it('drops attempt events that carry a stale generation', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: 'attempt-stale',
- startedAt: 1000,
- generation: 1,
- });
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)).toBeNull();
- });
-
- it('drops rendered-frame events that carry a stale generation', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_A,
- attemptKey: 'attempt-stale',
- renderedAt: 1100,
- generation: 1,
- });
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)).toBeNull();
- });
-
- it('drops failures reported for a stale generation and records the generation otherwise', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({streamKey: STREAM_A}),
- generation: 1,
- });
- expect(selectVoiceMediaGraphHasFailureForStreamKey(graph, STREAM_A)).toBe(false);
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({streamKey: STREAM_A}),
- generation: 2,
- });
- expect(selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A})?.generation).toBe(2);
- });
-
- it('stamps the current generation on failures without an explicit generation', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A});
-
- graph = transitionVoiceMediaGraph(graph, {type: 'failure.reported', failure: failure({streamKey: STREAM_A})});
-
- expect(selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A})?.generation).toBe(1);
- });
-});
-
-describe('VoiceMediaGraph deadlines', () => {
- it('creates a watch attempt deadline when a watch starts with a timestamp', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 2000});
-
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toEqual({
- kind: 'watchAttempt',
- streamKey: STREAM_A,
- subscriptionKey: null,
- generation: 1,
- attemptKey: null,
- dueAt: 2000 + WATCH_ATTEMPT_TIMEOUT_MS,
- });
- });
-
- it('removes the watch attempt deadline when the watch stops', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 2000});
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: STREAM_A});
-
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('removes the watch attempt deadline when a frame renders', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 2000});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_A,
- attemptKey: 'attempt-1',
- renderedAt: 2500,
- });
-
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('reports a timeout failure when a watch attempt deadline fires', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 0});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: 'attempt-1',
- startedAt: 0,
- });
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A),
- at: WATCH_ATTEMPT_TIMEOUT_MS,
- });
-
- const recorded = selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A});
- expect(recorded?.code).toBe(-2302);
- expect(recorded?.reason).toBe('subscription-attach-timeout');
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('reports subscription attach timeout when a publication exists but no track attached', () => {
- const participantIdentity = 'user_2_connection-a';
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 0});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: 'attempt-1',
- startedAt: 0,
- });
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A),
- at: WATCH_ATTEMPT_TIMEOUT_MS,
- });
-
- const recorded = selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A});
- expect(recorded?.code).toBe(-2302);
- expect(recorded?.reason).toBe('subscription-attach-timeout');
- });
-
- it('reports republish timeout when an operation watch attempt deadline fires', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 0});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: `${STREAM_A}:operation:7`,
- startedAt: 0,
- });
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A),
- at: WATCH_ATTEMPT_TIMEOUT_MS,
- });
-
- const recorded = selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A});
- expect(recorded?.code).toBe(-2304);
- expect(recorded?.reason).toBe('republish-timeout');
- });
-
- it('reports a first-frame timeout when the subscription attached without rendering', () => {
- const participantIdentity = 'user_2_connection-a';
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 0});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: 'attempt-1',
- startedAt: 0,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- subscribed: true,
- enabled: true,
- quality: 'high',
- });
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A),
- at: WATCH_ATTEMPT_TIMEOUT_MS,
- });
-
- expect(selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A})?.reason).toBe('first-frame-timeout');
- });
-
- it('treats a stale deadline fire as a no-op aside from cleanup', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 0});
- const deadlineKey = voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A);
- const staleDeadline: VoiceMediaGraphDeadline = {
- kind: 'watchAttempt',
- streamKey: STREAM_A,
- subscriptionKey: null,
- generation: 0,
- attemptKey: null,
- dueAt: WATCH_ATTEMPT_TIMEOUT_MS,
- };
- graph = {...graph, deadlinesByKey: new Map([[deadlineKey, staleDeadline]])};
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: deadlineKey,
- at: WATCH_ATTEMPT_TIMEOUT_MS,
- });
-
- expect(selectVoiceMediaGraphHasFailureForStreamKey(graph, STREAM_A)).toBe(false);
- expect(selectVoiceMediaGraphDeadline(graph, deadlineKey)).toBeNull();
- });
-
- it('ignores fires for deadlines that no longer exist', () => {
- const graph = createVoiceMediaGraphSnapshot();
- const next = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A),
- at: 1,
- });
- expect(next).toBe(graph);
- });
-
- it('finalizes a deferred stop when its grace deadline fires', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A, at: 1000});
-
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphDeferredStopDeadlineKey(STREAM_A))?.dueAt).toBe(
- 1000 + PUBLISHER_REPUBLISH_GRACE_MS,
- );
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphDeferredStopDeadlineKey(STREAM_A),
- at: 1000 + PUBLISHER_REPUBLISH_GRACE_MS,
- });
-
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([]);
- expect(selectVoiceMediaGraphDeferredStopKeys(graph).size).toBe(0);
- });
-
- it('drops the grace deadline when the deferred stop is cancelled', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A, at: 1000});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.cancelDeferredRemove', key: STREAM_A});
-
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphDeferredStopDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('tracks publication loss with a deadline while watch intent exists', () => {
- const participantIdentity = 'user_2_connection-a';
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.lost',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 1000,
- });
-
- const deadlineKey = voiceMediaGraphPublicationMissingDeadlineKey(`${participantIdentity}:screen_share`);
- expect(selectVoiceMediaGraphDeadline(graph, deadlineKey)?.dueAt).toBe(1000 + PUBLICATION_MISSING_TIMEOUT_MS);
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.observed',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- trackSid: 'TR_1',
- at: 1500,
- });
-
- expect(selectVoiceMediaGraphDeadline(graph, deadlineKey)).toBeNull();
- expect(
- selectVoiceMediaGraphSubscriptionEntry(graph, participantIdentity, VoiceTrackSource.ScreenShare)?.publication,
- ).toEqual({available: true, trackSid: 'TR_1', observedAt: 1500});
- });
-
- it('reports a publication-missing failure when the loss deadline fires', () => {
- const participantIdentity = 'user_2_connection-a';
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'publication.lost',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 1000,
- });
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphPublicationMissingDeadlineKey(`${participantIdentity}:screen_share`),
- at: 1000 + PUBLICATION_MISSING_TIMEOUT_MS,
- });
-
- const recorded = selectVoiceMediaGraphFailure(graph, {streamKey: STREAM_A});
- expect(recorded?.code).toBe(-2301);
- expect(recorded?.reason).toBe('publication-missing-timeout');
- });
-
- it('records the expired republish grace as the stop reason for the dropped stream', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A, at: 1000});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphDeferredStopDeadlineKey(STREAM_A),
- at: 1000 + PUBLISHER_REPUBLISH_GRACE_MS,
- });
-
- expect(selectVoiceMediaGraphViewerStreamKeys(graph)).toEqual([]);
- expect(selectVoiceMediaGraphWatchStopReason(graph, STREAM_A)).toBe('republish-grace-expired');
- });
-
- it('forgets the recorded stop reason once the stream is watched again', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A, at: 1000});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphDeferredStopDeadlineKey(STREAM_A),
- at: 1000 + PUBLISHER_REPUBLISH_GRACE_MS,
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_A, at: 6000});
-
- expect(selectVoiceMediaGraphWatchStopReason(graph, STREAM_A)).toBeNull();
- });
-
- it('keeps the recorded stop reason through the watch stop that follows the grace expiry', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {type: 'watchIntent.add', key: STREAM_A});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_A, at: 1000});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'time.deadlineFired',
- key: voiceMediaGraphDeferredStopDeadlineKey(STREAM_A),
- at: 1000 + PUBLISHER_REPUBLISH_GRACE_MS,
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: STREAM_A});
-
- expect(selectVoiceMediaGraphWatchStopReason(graph, STREAM_A)).toBe('republish-grace-expired');
- });
-});
-
-describe('VoiceMediaGraph watch attempt holders', () => {
- const ATTEMPT_KEY = 'attempt-1';
-
- function ensureAttempt(graph: VoiceMediaGraphSnapshot, startedAt: number): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptEnsured',
- streamKey: STREAM_A,
- attemptKey: ATTEMPT_KEY,
- startedAt,
- });
- }
-
- function releaseAttempt(graph: VoiceMediaGraphSnapshot): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(graph, {
- type: 'watch.attemptReleased',
- streamKey: STREAM_A,
- attemptKey: ATTEMPT_KEY,
- });
- }
-
- function watchedStream(at: number): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'watch.started',
- streamKey: STREAM_A,
- at,
- });
- }
-
- it('keeps the attempt deadline while a second tile still holds the attempt', () => {
- let graph = ensureAttempt(watchedStream(1000), 1000);
- graph = ensureAttempt(graph, 1200);
-
- graph = releaseAttempt(graph);
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)?.holders).toBe(1);
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))?.dueAt).toBe(
- 1000 + WATCH_ATTEMPT_TIMEOUT_MS,
- );
- });
-
- it('drops the attempt deadline once the last tile releases the attempt', () => {
- let graph = ensureAttempt(watchedStream(1000), 1000);
- graph = ensureAttempt(graph, 1200);
-
- graph = releaseAttempt(releaseAttempt(graph));
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)?.holders).toBe(0);
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('rearms a released attempt from the time the attempt started', () => {
- let graph = ensureAttempt(watchedStream(1000), 1000);
- graph = releaseAttempt(graph);
-
- graph = ensureAttempt(graph, 9000);
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)?.startedAt).toBe(1000);
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))?.dueAt).toBe(
- 1000 + WATCH_ATTEMPT_TIMEOUT_MS,
- );
- });
-
- it('counts one holder per tile when every mount runs its effect twice', () => {
- let graph = ensureAttempt(watchedStream(1000), 1000);
- graph = ensureAttempt(releaseAttempt(graph), 1400);
- graph = ensureAttempt(graph, 1500);
- graph = ensureAttempt(releaseAttempt(graph), 1600);
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)?.holders).toBe(2);
-
- graph = releaseAttempt(releaseAttempt(graph));
-
- expect(selectVoiceMediaGraphAttempt(graph, STREAM_A)?.holders).toBe(0);
- expect(selectVoiceMediaGraphDeadline(graph, voiceMediaGraphWatchAttemptDeadlineKey(STREAM_A))).toBeNull();
- });
-
- it('ignores a release for an attempt the graph no longer tracks', () => {
- const graph = watchedStream(1000);
-
- expect(releaseAttempt(graph)).toBe(graph);
- });
-});
-
-describe('VoiceMediaGraph desired and actual subscription state', () => {
- const participantIdentity = 'user_2_connection-a';
-
- it('splits subscribe intent into desired, actual, publication, and first frame state', () => {
- const graph = subscribedScreenShareGraph(participantIdentity);
- const entry = selectVoiceMediaGraphSubscriptionEntry(graph, participantIdentity, VoiceTrackSource.ScreenShare);
-
- expect(entry?.desired).toEqual({
- enabled: true,
- quality: 'high',
- context: 'focused',
- isIntersecting: false,
- observedElement: null,
- });
- expect(entry?.actual).toEqual({
- subscribed: null,
- enabled: null,
- quality: null,
- lastCommandAt: null,
- lastError: null,
- });
- expect(entry?.publication).toEqual({available: true, trackSid: null, observedAt: null});
- expect(entry?.firstFrame).toEqual({renderedAt: null});
- expect(entry?.subscribed).toBe(true);
- expect(entry?.publicationAvailable).toBe(true);
- expect(entry?.enabled).toBe(true);
- expect(entry?.quality).toBe('high');
- expect(entry?.context).toBe('focused');
- });
-
- it('applies actual changes and clears the last error', () => {
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.commandFailed',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- code: -2102,
- reason: 'subscription-set-enabled-failed',
- });
-
- let entry = selectVoiceMediaGraphSubscriptionEntry(graph, participantIdentity, VoiceTrackSource.ScreenShare);
- expect(entry?.actual.lastError).toEqual({code: -2102, reason: 'subscription-set-enabled-failed', at: 100});
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 200,
- subscribed: true,
- enabled: true,
- quality: 'high',
- });
-
- entry = selectVoiceMediaGraphSubscriptionEntry(graph, participantIdentity, VoiceTrackSource.ScreenShare);
- expect(entry?.actual).toEqual({
- subscribed: true,
- enabled: true,
- quality: 'high',
- lastCommandAt: 200,
- lastError: null,
- });
- });
-
- it('ignores actual changes for unknown subscriptions', () => {
- const graph = createVoiceMediaGraphSnapshot();
- const next = transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- subscribed: true,
- });
- expect(next).toBe(graph);
- });
-
- it('reconciles desired against actual idempotently', () => {
- let graph = subscribedScreenShareGraph(participantIdentity);
-
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.reconcile'});
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {
- type: 'subscribePublication',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- enabled: true,
- quality: 'high',
- },
- ]);
-
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.reconcile'});
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toHaveLength(1);
- });
-
- it('emits no reconcile commands once desired and actual converge', () => {
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- subscribed: true,
- enabled: true,
- quality: 'high',
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.reconcile'});
-
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([]);
- });
-
- it('reconciles drifted enabled and quality through targeted commands', () => {
- let graph = subscribedScreenShareGraph(participantIdentity);
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- subscribed: true,
- enabled: false,
- quality: 'low',
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'subscription.reconcile'});
-
- expect(selectVoiceMediaGraphSubscriptionCommands(graph)).toEqual([
- {type: 'setPublicationEnabled', participantIdentity, source: VoiceTrackSource.ScreenShare, enabled: true},
- {type: 'setPublicationQuality', participantIdentity, source: VoiceTrackSource.ScreenShare, quality: 'high'},
- ]);
- });
-});
-
-describe('VoiceMediaGraph sticky failure clearing', () => {
- it('clears identity-keyed failures for the stream when the watch stops', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({participantIdentity: 'user_2_connection_1'}),
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: 'dm:channel:connection_1'});
-
- expect(selectVoiceMediaGraphFailure(graph, {participantIdentity: 'user_2_connection_1'})).toBeNull();
- });
-
- it('clears stream-keyed failures whose connection matches the stopped stream', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({streamKey: 'guild-1:channel:connection_1'}),
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: 'dm:channel:connection_1'});
-
- expect(selectVoiceMediaGraphFailure(graph, {streamKey: 'guild-1:channel:connection_1'})).toBeNull();
- });
-
- it('keeps failures for unrelated connections when a watch stops', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: failure({participantIdentity: 'user_2_connection_2'}),
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.stopped', streamKey: 'dm:channel:connection_1'});
-
- expect(selectVoiceMediaGraphFailure(graph, {participantIdentity: 'user_2_connection_2'})).not.toBeNull();
- });
-});
-
-describe('VoiceMediaGraph stats observations', () => {
- it('stores observations and serves track info through one selector', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'native',
- tracks: [
- observation({
- trackSid: 'TR_screen',
- participantIdentity: 'user_2_connection-a',
- source: 'screen_share',
- fps: 24.7,
- width: 1920,
- height: 1080,
- }),
- ],
- });
-
- expect(selectVoiceMediaGraphStatsTrackInfo(graph, {trackSid: 'TR_screen'})).toEqual({
- width: 1920,
- height: 1080,
- fps: 24.7,
- });
- expect(
- selectVoiceMediaGraphStatsTrackInfo(graph, {participantIdentity: 'user_2_connection-a', source: 'screen_share'}),
- ).toEqual({width: 1920, height: 1080, fps: 24.7});
- });
-
- it('falls back to source dimensions when encoded ones are missing', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-1', sourceFps: 30, sourceWidth: 3840, sourceHeight: 2160})],
- });
-
- expect(selectVoiceMediaGraphStatsTrackInfo(graph, {trackIdentifier: 'media-1'})).toEqual({
- width: 3840,
- height: 2160,
- fps: 30,
- });
- });
-
- it('drops observations for a stale connection id', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-1', fps: 30})],
- });
-
- const next = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 2000,
- connectionId: 'connection-b',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-2', fps: 60})],
- });
-
- expect(next).toBe(graph);
- });
-
- it('wipes stored observations when the connection changes', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-1', fps: 30})],
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'stats.connectionChanged', connectionId: 'connection-b'});
-
- expect(selectVoiceMediaGraphStatsTrackInfo(graph, {trackIdentifier: 'media-1'})).toBeNull();
- expect(graph.statsConnectionId).toBe('connection-b');
-
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 3000,
- connectionId: 'connection-b',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-2', fps: 60})],
- });
-
- expect(selectVoiceMediaGraphStatsTrackInfo(graph, {trackIdentifier: 'media-2'})).toEqual({fps: 60});
- });
-
- it('clears stats on clear.all', () => {
- let graph = createVoiceMediaGraphSnapshot();
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [observation({trackIdentifier: 'media-1', fps: 30})],
- });
-
- graph = transitionVoiceMediaGraph(graph, {type: 'clear.all'});
-
- expect(graph.statsConnectionId).toBeNull();
- expect(graph.statsByTrackKey.size).toBe(0);
- });
-});
-
-describe('VoiceMediaGraph stats selectors', () => {
- it('matches web stats by media track id and can return fps-only observations', () => {
- const tracks: Array<VoiceEngineV2PerTrackStats> = [
- {
- direction: 'recv',
- kind: 'video',
- trackIdentifier: 'screen-media-track',
- bitrateKbps: 4200,
- framesPerSecond: 25,
- },
- ];
-
- expect(resolveVoiceMediaGraphPerTrackInfo(tracks, {mediaTrackId: 'screen-media-track'})).toEqual({fps: 25});
- });
-
- it('fills missing rendered-track fps from matched stats without replacing rendered dimensions', () => {
- const renderedInfo = {width: 3840, height: 2160, fps: 0};
- const statsInfo = {width: 1920, height: 1080, fps: 24.7};
-
- expect(mergeVoiceMediaGraphTrackInfo(renderedInfo, statsInfo)).toEqual({width: 3840, height: 2160, fps: 25});
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraphInvariants.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraphInvariants.test.ts
deleted file mode 100644
index 108ffd0f4..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraphInvariants.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildVoiceMediaGraphSubscriptionEntry,
- createVoiceMediaGraphSnapshot,
- createVoiceMediaGraphSubscriptionActualState,
- createVoiceMediaGraphSubscriptionPublicationState,
- transitionVoiceMediaGraph,
- type VoiceMediaGraphDeadline,
- type VoiceMediaGraphSnapshot,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {checkVoiceMediaGraphInvariants} from '@app/features/voice/engine/VoiceMediaGraphInvariants';
-import {VoiceTrackSource} from '@app/features/voice/engine/VoiceTrackSource';
-import {describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'dm:channel-a:connection-a';
-
-function entryWithActualSubscribed(subscribed: boolean) {
- return buildVoiceMediaGraphSubscriptionEntry(
- {participantIdentity: 'user_2_connection-a', source: VoiceTrackSource.ScreenShare},
- {
- desired: {enabled: true, quality: 'high', context: 'focused', isIntersecting: false, observedElement: null},
- actual: {...createVoiceMediaGraphSubscriptionActualState(), subscribed: true},
- publication: createVoiceMediaGraphSubscriptionPublicationState(true),
- firstFrame: {renderedAt: null},
- subscribed,
- },
- );
-}
-
-describe('checkVoiceMediaGraphInvariants', () => {
- it('accepts a fresh snapshot and ordinary transitions', () => {
- let graph = createVoiceMediaGraphSnapshot();
- expect(checkVoiceMediaGraphInvariants(graph)).toEqual([]);
-
- graph = transitionVoiceMediaGraph(graph, {type: 'watch.started', streamKey: STREAM_KEY, at: 0});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.add', key: STREAM_KEY});
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.deferRemove', key: STREAM_KEY, at: 100});
- graph = transitionVoiceMediaGraph(graph, {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [],
- });
-
- expect(checkVoiceMediaGraphInvariants(graph)).toEqual([]);
- });
-
- it('flags actual subscriptions without a desired entry', () => {
- const entry = entryWithActualSubscribed(false);
- const graph: VoiceMediaGraphSnapshot = {
- ...createVoiceMediaGraphSnapshot(),
- subscriptionsByKey: new Map([['user_2_connection-a:screen_share', entry]]),
- };
-
- const violations = checkVoiceMediaGraphInvariants(graph);
- expect(violations).toHaveLength(1);
- expect(violations[0]).toContain('actually subscribed without a desired entry');
- });
-
- it('flags failures recorded for a generation newer than current', () => {
- const graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'failure.reported',
- failure: {
- code: -2302,
- reason: 'subscription-attach-timeout',
- reportedAt: 1000,
- streamKey: STREAM_KEY,
- generation: 5,
- },
- });
-
- const violations = checkVoiceMediaGraphInvariants(graph);
- expect(violations).toHaveLength(1);
- expect(violations[0]).toContain('newer than current');
- });
-
- it('flags deadlines referencing a missing attempt', () => {
- const deadline: VoiceMediaGraphDeadline = {
- kind: 'watchAttempt',
- streamKey: STREAM_KEY,
- subscriptionKey: null,
- generation: 0,
- attemptKey: 'attempt-gone',
- dueAt: 15000,
- };
- const graph: VoiceMediaGraphSnapshot = {
- ...createVoiceMediaGraphSnapshot(),
- deadlinesByKey: new Map([[`watchAttempt:${STREAM_KEY}`, deadline]]),
- };
-
- const violations = checkVoiceMediaGraphInvariants(graph);
- expect(violations).toHaveLength(1);
- expect(violations[0]).toContain('missing attempt');
- });
-
- it('flags stats entries for an unknown connection id', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'stats.observed',
- at: 1000,
- connectionId: 'connection-a',
- platform: 'web',
- tracks: [
- {
- trackSid: 'TR_1',
- trackIdentifier: null,
- mediaSourceId: null,
- mid: null,
- rid: null,
- ssrc: null,
- participantIdentity: null,
- participantSid: null,
- source: null,
- direction: 'recv',
- kind: 'video',
- fps: 30,
- width: null,
- height: null,
- sourceFps: null,
- sourceWidth: null,
- sourceHeight: null,
- },
- ],
- });
- graph = {...graph, statsConnectionId: 'connection-b'};
-
- const violations = checkVoiceMediaGraphInvariants(graph);
- expect(violations).toHaveLength(1);
- expect(violations[0]).toContain('unknown connection');
- });
-
- it('flags deferred stop keys that are not viewer stream keys', () => {
- const graph: VoiceMediaGraphSnapshot = {
- ...createVoiceMediaGraphSnapshot(),
- watchIntent: {viewerStreamKeys: [], deferredStopKeys: new Set([STREAM_KEY])},
- };
-
- const violations = checkVoiceMediaGraphInvariants(graph);
- expect(violations).toHaveLength(1);
- expect(violations[0]).toContain('not a viewer stream key');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraphStats.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraphStats.test.ts
deleted file mode 100644
index 907ad3a3b..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraphStats.test.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceMediaGraphSnapshot,
- transitionVoiceMediaGraph,
- type VoiceMediaGraphSnapshot,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {
- buildVoiceMediaGraphStatsView,
- selectVoiceMediaGraphStreamTrackInfo,
- voiceMediaGraphStatsObservationsFromPerTrackStats,
-} from '@app/features/voice/engine/VoiceMediaGraphStats';
-import type {VoiceMediaGraphStatsTrackObservation} from '@app/features/voice/engine/VoiceMediaGraphStatsObservations';
-import type {VoiceEngineV2PerTrackStats} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-function observation(overrides: Partial<VoiceMediaGraphStatsTrackObservation>): VoiceMediaGraphStatsTrackObservation {
- return {
- trackSid: null,
- trackIdentifier: null,
- mediaSourceId: null,
- mid: null,
- rid: null,
- ssrc: null,
- participantIdentity: null,
- participantSid: null,
- source: null,
- direction: 'recv',
- kind: 'video',
- fps: null,
- width: null,
- height: null,
- sourceFps: null,
- sourceWidth: null,
- sourceHeight: null,
- ...overrides,
- };
-}
-
-function snapshotWithObservations(
- connectionId: string,
- platform: 'native' | 'web',
- tracks: ReadonlyArray<VoiceMediaGraphStatsTrackObservation>,
-): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'stats.observed',
- at: 1000,
- connectionId,
- platform,
- tracks,
- });
-}
-
-describe('voiceMediaGraphStatsObservationsFromPerTrackStats', () => {
- it('normalizes web per-track stats and skips unknown kinds', () => {
- const tracks: Array<VoiceEngineV2PerTrackStats> = [
- {
- direction: 'recv',
- kind: 'video',
- trackIdentifier: 'screen-media-track',
- mediaSourceId: 'media-source-1',
- mid: '4',
- rid: 'f',
- ssrc: 1234,
- bitrateKbps: 4200,
- framesPerSecond: 24.7,
- frameWidth: 3840,
- frameHeight: 2160,
- sourceFramesPerSecond: 60,
- },
- {direction: 'recv', kind: 'unknown', bitrateKbps: 0},
- ];
-
- expect(voiceMediaGraphStatsObservationsFromPerTrackStats(tracks)).toEqual([
- observation({
- trackIdentifier: 'screen-media-track',
- mediaSourceId: 'media-source-1',
- mid: '4',
- rid: 'f',
- ssrc: 1234,
- fps: 24.7,
- width: 3840,
- height: 2160,
- sourceFps: 60,
- }),
- ]);
- });
-});
-
-describe('selectVoiceMediaGraphStreamTrackInfo', () => {
- it('matches on trackSid before any other key', () => {
- const snapshot = snapshotWithObservations('conn-1', 'native', [
- observation({trackSid: 'TR_a', rid: 'f', width: 1280, height: 720, fps: 15}),
- observation({trackSid: 'TR_b', width: 1920, height: 1080, fps: 30}),
- ]);
-
- expect(selectVoiceMediaGraphStreamTrackInfo(snapshot, {trackSid: 'TR_b', rid: 'f', kind: 'video'})).toEqual({
- width: 1920,
- height: 1080,
- fps: 30,
- });
- });
-
- it('falls back to rid when no track identifier matches', () => {
- const snapshot = snapshotWithObservations('conn-1', 'web', [
- observation({rid: 'h', width: 1280, height: 720, fps: 20}),
- observation({rid: 'f', width: 1920, height: 1080, fps: 30}),
- ]);
-
- expect(selectVoiceMediaGraphStreamTrackInfo(snapshot, {trackSid: 'TR_missing', rid: 'f', kind: 'video'})).toEqual({
- width: 1920,
- height: 1080,
- fps: 30,
- });
- });
-
- it('falls back to participantIdentity with strict source matching', () => {
- const snapshot = snapshotWithObservations('conn-1', 'native', [
- observation({
- trackSid: 'TR_camera',
- participantIdentity: 'user_2_conn_2',
- source: 'camera',
- width: 640,
- height: 480,
- fps: 24,
- }),
- observation({
- trackSid: 'TR_screen',
- participantIdentity: 'user_2_conn_2',
- source: 'screen_share',
- width: 3840,
- height: 2160,
- fps: 25,
- }),
- ]);
-
- expect(
- selectVoiceMediaGraphStreamTrackInfo(snapshot, {
- trackSid: 'TR_missing',
- participantIdentity: 'user_2_conn_2',
- source: 'screen_share',
- kind: 'video',
- }),
- ).toEqual({width: 3840, height: 2160, fps: 25});
- });
-
- it('does not match sourceless observations through the participantIdentity fallback', () => {
- const snapshot = snapshotWithObservations('conn-1', 'web', [observation({width: 640, height: 480, fps: 24})]);
-
- expect(
- selectVoiceMediaGraphStreamTrackInfo(snapshot, {
- participantIdentity: 'user_2_conn_2',
- source: 'screen_share',
- kind: 'video',
- }),
- ).toBeNull();
- });
-
- it('uses source dimensions and fps when encoded values are absent', () => {
- const snapshot = snapshotWithObservations('conn-1', 'web', [
- observation({trackIdentifier: 'screen-media-track', sourceWidth: 2560, sourceHeight: 1440, sourceFps: 60}),
- ]);
-
- expect(
- selectVoiceMediaGraphStreamTrackInfo(snapshot, {trackIdentifier: 'screen-media-track', kind: 'video'}),
- ).toEqual({width: 2560, height: 1440, fps: 60});
- });
-
- it('drops observations for a stale connectionId', () => {
- const snapshot = snapshotWithObservations('conn-1', 'native', [
- observation({trackSid: 'TR_a', width: 1920, height: 1080, fps: 30}),
- ]);
- const next = transitionVoiceMediaGraph(snapshot, {
- type: 'stats.observed',
- at: 2000,
- connectionId: 'conn-2',
- platform: 'native',
- tracks: [observation({trackSid: 'TR_b', width: 1280, height: 720, fps: 15})],
- });
-
- expect(next).toBe(snapshot);
- expect(selectVoiceMediaGraphStreamTrackInfo(next, {trackSid: 'TR_b', kind: 'video'})).toBeNull();
- });
-
- it('wipes stale entries when the stats connection changes', () => {
- const snapshot = snapshotWithObservations('conn-1', 'native', [
- observation({trackSid: 'TR_a', width: 1920, height: 1080, fps: 30}),
- ]);
- const next = transitionVoiceMediaGraph(snapshot, {type: 'stats.connectionChanged', connectionId: 'conn-2'});
-
- expect(next.statsConnectionId).toBe('conn-2');
- expect(selectVoiceMediaGraphStreamTrackInfo(next, {trackSid: 'TR_a', kind: 'video'})).toBeNull();
- });
-
- it('resolves from an ad-hoc stats view built from observations', () => {
- const view = buildVoiceMediaGraphStatsView(
- [observation({trackIdentifier: 'screen-media-track', width: 1920, height: 1080, fps: 30})],
- 'web',
- 0,
- 'fallback',
- );
-
- expect(selectVoiceMediaGraphStreamTrackInfo(view, {trackIdentifier: 'screen-media-track', kind: 'video'})).toEqual({
- width: 1920,
- height: 1080,
- fps: 30,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraphTileState.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraphTileState.test.ts
deleted file mode 100644
index 778d26a88..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraphTileState.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceMediaGraphSnapshot,
- transitionVoiceMediaGraph,
- type VoiceMediaGraphSnapshot,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {
- selectVoiceMediaGraphStreamTileState,
- VOICE_MEDIA_GRAPH_FIRST_FRAME_RECOVERY_VISIBLE_MS,
-} from '@app/features/voice/engine/VoiceMediaGraphTileState';
-import {VoiceTrackSource} from '@app/features/voice/engine/VoiceTrackSource';
-import {describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'dm:channel-a:connection-a';
-const PARTICIPANT_IDENTITY = 'user_2_connection-a';
-const FAILURE_REPORTED_AT = 300;
-
-const target = {
- streamKey: STREAM_KEY,
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
-};
-
-function subscribe(graph: VoiceMediaGraphSnapshot, hasPublication: boolean): VoiceMediaGraphSnapshot {
- const next = transitionVoiceMediaGraph(graph, {
- type: 'subscription.subscribe',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- hasPublication,
- observedElement: null,
- context: 'focused',
- });
- return transitionVoiceMediaGraph(next, {type: 'subscription.clearCommands'});
-}
-
-function attach(graph: VoiceMediaGraphSnapshot): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(graph, {
- type: 'subscription.actualChanged',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- subscribed: true,
- enabled: true,
- quality: 'high',
- });
-}
-
-function reportFailure(graph: VoiceMediaGraphSnapshot, code: number, reason: string): VoiceMediaGraphSnapshot {
- return transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: {
- code,
- reason,
- reportedAt: FAILURE_REPORTED_AT,
- streamKey: STREAM_KEY,
- participantIdentity: PARTICIPANT_IDENTITY,
- source: 'screen_share',
- },
- });
-}
-
-function watchedWithFailure(code: number, reason: string): VoiceMediaGraphSnapshot {
- return reportFailure(attach(subscribe(createVoiceMediaGraphSnapshot(), true)), code, reason);
-}
-
-describe('selectVoiceMediaGraphStreamTileState', () => {
- it('returns idle when the graph has no state for the tile', () => {
- expect(selectVoiceMediaGraphStreamTileState(createVoiceMediaGraphSnapshot(), target)).toBe('idle');
- });
-
- it('returns watchDesired when only watch intent exists', () => {
- const graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'watchIntent.add',
- key: STREAM_KEY,
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('watchDesired');
- });
-
- it('returns publicationMissing when a desired subscription has no publication', () => {
- const graph = subscribe(createVoiceMediaGraphSnapshot(), false);
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('publicationMissing');
- });
-
- it('returns attaching when the publication exists but actual is not yet subscribed', () => {
- const graph = subscribe(createVoiceMediaGraphSnapshot(), true);
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('attaching');
- });
-
- it('returns subscribedAwaitingFrame once actual reports a subscription', () => {
- const graph = attach(subscribe(createVoiceMediaGraphSnapshot(), true));
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('subscribedAwaitingFrame');
- });
-
- it('returns rendering once a frame is recorded for the attempt', () => {
- let graph = attach(subscribe(createVoiceMediaGraphSnapshot(), true));
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_KEY,
- attemptKey: 'attempt-1',
- renderedAt: 200,
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('rendering');
- });
-
- it('returns rendering from entry first frame state without an attempt', () => {
- let graph = attach(subscribe(createVoiceMediaGraphSnapshot(), true));
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_KEY,
- attemptKey: 'attempt-1',
- renderedAt: 200,
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, {...target, streamKey: null})).toBe('rendering');
- });
-
- it('returns failed when a failure is recorded, beating rendering', () => {
- let graph = attach(subscribe(createVoiceMediaGraphSnapshot(), true));
- graph = transitionVoiceMediaGraph(graph, {
- type: 'watch.renderedFrame',
- streamKey: STREAM_KEY,
- attemptKey: 'attempt-1',
- renderedAt: 200,
- });
- graph = transitionVoiceMediaGraph(graph, {
- type: 'failure.reported',
- failure: {
- code: -2202,
- reason: 'remote-track-subscription-failed',
- reportedAt: 300,
- participantIdentity: PARTICIPANT_IDENTITY,
- source: 'screen_share',
- },
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('failed');
- });
-
- it('returns failed when the last subscription command failed', () => {
- let graph = subscribe(createVoiceMediaGraphSnapshot(), true);
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.commandFailed',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- code: -2101,
- reason: 'subscription-set-subscribed-failed',
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('failed');
- });
-
- it('recovers from failed to subscribedAwaitingFrame after a successful actual change', () => {
- let graph = subscribe(createVoiceMediaGraphSnapshot(), true);
- graph = transitionVoiceMediaGraph(graph, {
- type: 'subscription.commandFailed',
- participantIdentity: PARTICIPANT_IDENTITY,
- source: VoiceTrackSource.ScreenShare,
- at: 100,
- code: -2101,
- reason: 'subscription-set-subscribed-failed',
- });
- graph = attach(graph);
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('subscribedAwaitingFrame');
- });
-
- it('returns recovering while a first-frame timeout still has recovery attempts left', () => {
- const graph = watchedWithFailure(-2303, 'first-frame-timeout');
- expect(
- selectVoiceMediaGraphStreamTileState(graph, target, {
- hasRecoveryBudget: true,
- nowMs: FAILURE_REPORTED_AT + 1000,
- }),
- ).toBe('recovering');
- });
-
- it('returns failed once the first-frame recovery budget is spent', () => {
- const graph = watchedWithFailure(-2303, 'first-frame-timeout');
- expect(
- selectVoiceMediaGraphStreamTileState(graph, target, {
- hasRecoveryBudget: false,
- nowMs: FAILURE_REPORTED_AT + 1000,
- }),
- ).toBe('failed');
- });
-
- it('returns failed once a first-frame timeout has been on screen for the visible cap', () => {
- const graph = watchedWithFailure(-2303, 'first-frame-timeout');
- expect(
- selectVoiceMediaGraphStreamTileState(graph, target, {
- hasRecoveryBudget: true,
- nowMs: FAILURE_REPORTED_AT + VOICE_MEDIA_GRAPH_FIRST_FRAME_RECOVERY_VISIBLE_MS,
- }),
- ).toBe('failed');
- });
-
- it('returns failed for a first-frame timeout when the caller tracks no recovery', () => {
- const graph = watchedWithFailure(-2303, 'first-frame-timeout');
- expect(selectVoiceMediaGraphStreamTileState(graph, target)).toBe('failed');
- });
-
- it('keeps every other failure code failed while recovery attempts remain', () => {
- const graph = watchedWithFailure(-2202, 'remote-track-subscription-failed');
- expect(
- selectVoiceMediaGraphStreamTileState(graph, target, {
- hasRecoveryBudget: true,
- nowMs: FAILURE_REPORTED_AT + 1000,
- }),
- ).toBe('failed');
- });
-
- it('returns watchDesired for entry-less streams and idle after the watch ends', () => {
- let graph = transitionVoiceMediaGraph(createVoiceMediaGraphSnapshot(), {
- type: 'watchIntent.add',
- key: STREAM_KEY,
- });
- expect(selectVoiceMediaGraphStreamTileState(graph, {...target, participantIdentity: null})).toBe('watchDesired');
- graph = transitionVoiceMediaGraph(graph, {type: 'watchIntent.remove', key: STREAM_KEY});
- expect(selectVoiceMediaGraphStreamTileState(graph, {...target, participantIdentity: null})).toBe('idle');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraphTimerScheduler.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraphTimerScheduler.test.ts
deleted file mode 100644
index d2fc81bfd..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraphTimerScheduler.test.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {screenShareWatchAttemptKey} from '@app/features/voice/components/useScreenShareWatchFailure';
-import {
- selectVoiceMediaGraphFailure,
- selectVoiceMediaGraphViewerStreamKeys,
- voiceMediaGraphWatchAttemptDeadlineKey,
- WATCH_ATTEMPT_TIMEOUT_MS,
-} from '@app/features/voice/engine/VoiceMediaGraph';
-import {VoiceMediaGraphStore} from '@app/features/voice/engine/VoiceMediaGraphStore';
-import {
- startVoiceMediaGraphTimerScheduler,
- stopVoiceMediaGraphTimerScheduler,
- VoiceMediaGraphTimerScheduler,
- type VoiceMediaGraphTimerSchedulerPlatform,
-} from '@app/features/voice/engine/VoiceMediaGraphTimerScheduler';
-import {afterEach, describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'dm:channel-a:connection-a';
-
-interface FakeTimer {
- id: number;
- callback: () => void;
- delayMs: number;
- cancelled: boolean;
- fired: boolean;
-}
-
-class FakePlatform implements VoiceMediaGraphTimerSchedulerPlatform {
- timers: Array<FakeTimer> = [];
- private nextId = 1;
-
- setTimeout(callback: () => void, delayMs: number): unknown {
- const timer: FakeTimer = {id: this.nextId, callback, delayMs, cancelled: false, fired: false};
- this.nextId += 1;
- this.timers.push(timer);
- return timer.id;
- }
-
- clearTimeout(handle: unknown): void {
- const timer = this.timers.find((candidate) => candidate.id === handle);
- if (timer) timer.cancelled = true;
- }
-
- fire(timer: FakeTimer): void {
- timer.fired = true;
- timer.callback();
- }
-
- get active(): Array<FakeTimer> {
- return this.timers.filter((timer) => !timer.cancelled && !timer.fired);
- }
-}
-
-function createHarness(startMs = 0) {
- let now = startMs;
- const store = new VoiceMediaGraphStore({now: () => now});
- const platform = new FakePlatform();
- const scheduler = new VoiceMediaGraphTimerScheduler(store, platform);
- return {
- store,
- platform,
- scheduler,
- advance(toMs: number) {
- now = toMs;
- },
- };
-}
-
-describe('VoiceMediaGraphTimerScheduler', () => {
- it('schedules exactly one timer per deadline', () => {
- const {store, platform, scheduler} = createHarness();
- scheduler.start();
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: store.nowMs()});
- expect(platform.active).toHaveLength(1);
- expect(platform.active[0].delayMs).toBe(WATCH_ATTEMPT_TIMEOUT_MS);
-
- store.transition({type: 'watchIntent.add', key: STREAM_KEY});
- expect(platform.active).toHaveLength(1);
-
- scheduler.stop();
- });
-
- it('cancels timers when their deadline is removed', () => {
- const {store, platform, scheduler} = createHarness();
- scheduler.start();
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: store.nowMs()});
- store.transition({type: 'watch.stopped', streamKey: STREAM_KEY});
-
- expect(platform.active).toHaveLength(0);
- scheduler.stop();
- });
-
- it('dispatches time.deadlineFired with the clock time when a timer fires', () => {
- const harness = createHarness();
- const {store, platform, scheduler} = harness;
- scheduler.start();
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: store.nowMs()});
- store.transition({
- type: 'watch.attemptEnsured',
- streamKey: STREAM_KEY,
- attemptKey: screenShareWatchAttemptKey({streamKey: STREAM_KEY, watchGeneration: 1}),
- startedAt: store.nowMs(),
- });
- harness.advance(WATCH_ATTEMPT_TIMEOUT_MS);
- platform.fire(platform.active[0]);
-
- const recorded = selectVoiceMediaGraphFailure(store.getGraphSnapshot(), {streamKey: STREAM_KEY});
- expect(recorded?.reportedAt).toBe(WATCH_ATTEMPT_TIMEOUT_MS);
- expect(recorded?.reason).toBe('subscription-attach-timeout');
- expect(store.getGraphSnapshot().deadlinesByKey.size).toBe(0);
- expect(platform.active).toHaveLength(0);
-
- scheduler.stop();
- });
-
- it('reschedules when a deadline is replaced with a new due time', () => {
- const harness = createHarness();
- const {store, platform, scheduler} = harness;
- scheduler.start();
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: 0});
- harness.advance(1000);
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: 1000});
-
- expect(platform.active).toHaveLength(1);
- expect(platform.active[0].delayMs).toBe(WATCH_ATTEMPT_TIMEOUT_MS);
- expect(platform.timers).toHaveLength(2);
-
- scheduler.stop();
- });
-
- it('drives the deferred stop grace deadline end to end', () => {
- const harness = createHarness();
- const {store, platform, scheduler} = harness;
- scheduler.start();
-
- store.transition({type: 'watchIntent.add', key: STREAM_KEY});
- store.transition({type: 'watchIntent.deferRemove', key: STREAM_KEY, at: store.nowMs()});
- expect(platform.active).toHaveLength(1);
-
- harness.advance(platform.active[0].delayMs);
- platform.fire(platform.active[0]);
-
- expect(selectVoiceMediaGraphViewerStreamKeys(store.getGraphSnapshot())).toEqual([]);
- expect(platform.active).toHaveLength(0);
-
- scheduler.stop();
- });
-
- it('ignores stale fires after the deadline was already removed', () => {
- const {store, platform, scheduler} = createHarness();
- scheduler.start();
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: 0});
- const timer = platform.active[0];
- store.transition({type: 'watch.stopped', streamKey: STREAM_KEY});
-
- platform.fire(timer);
-
- expect(selectVoiceMediaGraphFailure(store.getGraphSnapshot(), {streamKey: STREAM_KEY})).toBeNull();
- scheduler.stop();
- });
-
- it('cancels all timers on stop', () => {
- const {store, platform, scheduler} = createHarness();
- scheduler.start();
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: 0});
-
- scheduler.stop();
-
- expect(platform.active).toHaveLength(0);
- expect(
- store.getGraphSnapshot().deadlinesByKey.get(voiceMediaGraphWatchAttemptDeadlineKey(STREAM_KEY)),
- ).toBeDefined();
- });
-});
-
-describe('startVoiceMediaGraphTimerScheduler', () => {
- afterEach(() => {
- stopVoiceMediaGraphTimerScheduler();
- });
-
- it('keeps a single active scheduler across repeated starts', () => {
- const {store, platform} = createHarness();
- const first = startVoiceMediaGraphTimerScheduler(store, platform);
- const second = startVoiceMediaGraphTimerScheduler(store, platform);
- expect(second).toBe(first);
-
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: store.nowMs()});
- expect(platform.active).toHaveLength(1);
- });
-
- it('cancels timers on stop and allows a fresh scheduler afterwards', () => {
- const {store, platform} = createHarness();
- const first = startVoiceMediaGraphTimerScheduler(store, platform);
- store.transition({type: 'watch.started', streamKey: STREAM_KEY, at: store.nowMs()});
- expect(platform.active).toHaveLength(1);
-
- stopVoiceMediaGraphTimerScheduler();
- expect(platform.active).toHaveLength(0);
-
- const next = startVoiceMediaGraphTimerScheduler(store, platform);
- expect(next).not.toBe(first);
- expect(platform.active).toHaveLength(1);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaStateMachine.test.ts
deleted file mode 100644
index 3c6547a81..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceMediaStateMachine.test.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- computeVoiceMediaEffectiveAudioState,
- createVoiceMediaSnapshot,
- transitionVoiceMediaSnapshot,
- type VoiceMediaAudioControls,
- type VoiceMediaSnapshot,
-} from '@app/features/voice/engine/VoiceMediaStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const releasedPtt: VoiceMediaAudioControls = {
- pushToTalkActive: true,
- pushToTalkHeld: false,
- pushToMuteActive: false,
- pushToMuteHeld: false,
-};
-
-const heldPtt: VoiceMediaAudioControls = {
- pushToTalkActive: true,
- pushToTalkHeld: true,
- pushToMuteActive: false,
- pushToMuteHeld: false,
-};
-
-const heldPtm: VoiceMediaAudioControls = {
- pushToTalkActive: false,
- pushToTalkHeld: false,
- pushToMuteActive: true,
- pushToMuteHeld: true,
-};
-
-const noControls: VoiceMediaAudioControls = {
- pushToTalkActive: false,
- pushToTalkHeld: false,
- pushToMuteActive: false,
- pushToMuteHeld: false,
-};
-
-function clearCommands(snapshot: VoiceMediaSnapshot): VoiceMediaSnapshot {
- return transitionVoiceMediaSnapshot(snapshot, {type: 'commands.clear'});
-}
-
-describe('VoiceMediaStateMachine', () => {
- it('tracks microphone permission warmup grant and denial fallback states', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'permission.warmup.start'});
- expect(snapshot.context.permissionWarmup).toBe('checking');
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'permission.warmup.granted'});
- expect(snapshot.context.permissionWarmup).toBe('granted');
-
- snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'permission.warmup.denied'});
- expect(snapshot.context.permissionWarmup).toBe('denied');
- expect(snapshot.context.microphone.state).toBe('permissionDenied');
- expect(snapshot.context.commands).toEqual([
- {type: 'microphone.permissionDeniedFallbackSelfMute'},
- {type: 'voiceState.syncSelfMute', selfMute: true},
- ]);
- });
-
- it('does not publish the microphone twice for repeated enable requests while enabling', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'microphone.enable.request',
- hasPublication: false,
- hasLivePublication: false,
- });
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'microphone.enable.request',
- hasPublication: false,
- hasLivePublication: false,
- });
- expect(snapshot.context.microphone.state).toBe('enabling');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.enable'}]);
- });
-
- it('skips duplicate publication when an existing microphone track is live', () => {
- const snapshot = transitionVoiceMediaSnapshot(createVoiceMediaSnapshot(), {
- type: 'microphone.enable.request',
- hasPublication: true,
- hasLivePublication: true,
- });
- expect(snapshot.context.microphone.state).toBe('enabled');
- expect(snapshot.context.commands).toEqual([]);
- });
-
- it('recovers an ended microphone publication by requesting republish', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.enable.success'});
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.publication.ended'});
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'microphone.enable.request',
- hasPublication: true,
- hasLivePublication: false,
- });
- expect(snapshot.context.microphone.state).toBe('republishing');
- expect(snapshot.context.microphone.hasLivePublication).toBe(false);
- expect(snapshot.context.commands).toEqual([{type: 'microphone.republish'}]);
- });
-
- it('falls back to republish when microphone capture restart fails', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.enable.success'});
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'refresh.request', hasPublication: true});
- expect(snapshot.context.refresh.state).toBe('restarting');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.restart'}]);
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'refresh.restart.failure'});
- expect(snapshot.context.refresh.state).toBe('republishing');
- expect(snapshot.context.refresh.lastFailure).toBe('restart');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.republish'}]);
- });
-
- it('queues capture refresh requests while a refresh is already in flight', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.enable.success'});
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'refresh.request', hasPublication: true});
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'refresh.request',
- hasPublication: true,
- forceRepublish: true,
- });
- expect(snapshot.context.refresh.state).toBe('restarting');
- expect(snapshot.context.refresh.queued).toBe(true);
- expect(snapshot.context.refresh.forceRepublishQueued).toBe(true);
- expect(snapshot.context.commands).toEqual([]);
-
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'refresh.restart.success'});
- expect(snapshot.context.refresh.state).toBe('republishing');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.republish'}]);
- });
-
- it('models mute, deaf, push-to-talk, and push-to-mute effective audio transitions', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: true, selfDeaf: false}, noControls),
- controls: noControls,
- permissionMuted: false,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('muted');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.mutePublications', reason: 'voice state update'}]);
-
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: true}, noControls),
- controls: noControls,
- permissionMuted: false,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('muted');
- expect(snapshot.context.effectiveAudioState?.effectiveDeaf).toBe(true);
-
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: false}, releasedPtt),
- controls: releasedPtt,
- permissionMuted: false,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('muted');
-
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: false}, heldPtm),
- controls: heldPtm,
- permissionMuted: false,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('muted');
-
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: false}, heldPtt),
- controls: heldPtt,
- permissionMuted: false,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('unmuted');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.unmutePublications', reason: 'voice state update'}]);
- });
-
- it('requests microphone enable during unmuted reconcile when no live publication exists', () => {
- const snapshot = transitionVoiceMediaSnapshot(createVoiceMediaSnapshot(), {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: false}, noControls),
- controls: noControls,
- permissionMuted: false,
- hasLiveMicrophonePublication: false,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('unmuted');
- expect(snapshot.context.commands).toEqual([{type: 'microphone.enable'}]);
- });
-
- it('falls back to self mute when speak permission mutes local capture', () => {
- const snapshot = transitionVoiceMediaSnapshot(createVoiceMediaSnapshot(), {
- type: 'audio.reconcile',
- audioState: computeVoiceMediaEffectiveAudioState({selfMute: false, selfDeaf: false}, noControls),
- controls: noControls,
- permissionMuted: true,
- hasLiveMicrophonePublication: true,
- });
- expect(snapshot.context.effectiveAudioMode).toBe('muted');
- expect(snapshot.context.commands).toEqual([
- {type: 'microphone.disable'},
- {type: 'voiceState.syncSelfMute', selfMute: true},
- ]);
- });
-
- it('tracks speaking detector attachment and cleanup/reset', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.enable.success'});
- expect(snapshot.context.speakingDetector).toBe('attached');
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.disable.request', hasPublication: true});
- expect(snapshot.context.speakingDetector).toBe('detached');
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'microphone.disable.success'});
- expect(snapshot.context.microphone.state).toBe('disabled');
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'media.reset'});
- expect(snapshot.context.permissionWarmup).toBe('unknown');
- expect(snapshot.context.microphone.hasPublication).toBe(false);
- expect(snapshot.context.commands).toEqual([]);
- });
-
- it('models camera enable, update, disable, and permission denied behavior', () => {
- let snapshot = createVoiceMediaSnapshot();
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'camera.setEnabled.request',
- enabled: true,
- currentlyEnabled: false,
- });
- expect(snapshot.context.camera).toBe('enabling');
- expect(snapshot.context.commands).toEqual([{type: 'camera.enable'}]);
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {type: 'camera.success', enabled: true});
- expect(snapshot.context.camera).toBe('enabled');
-
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'camera.setEnabled.request',
- enabled: true,
- currentlyEnabled: true,
- });
- expect(snapshot.context.camera).toBe('updating');
- expect(snapshot.context.commands).toEqual([{type: 'camera.update'}]);
- snapshot = clearCommands(snapshot);
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'camera.setEnabled.request',
- enabled: false,
- currentlyEnabled: true,
- });
- expect(snapshot.context.camera).toBe('disabling');
- expect(snapshot.context.commands).toEqual([{type: 'camera.disable'}]);
-
- snapshot = transitionVoiceMediaSnapshot(snapshot, {
- type: 'camera.failure',
- actualEnabled: false,
- permissionDenied: true,
- });
- expect(snapshot.context.camera).toBe('permissionDenied');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceParticipantStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceParticipantStateMachine.test.ts
deleted file mode 100644
index fdfd4e1f3..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceParticipantStateMachine.test.ts
+++ /dev/null
@@ -1,496 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- __TEST__,
- createLivekitParticipantSnapshot,
- createLivekitParticipantSnapshotsFromRoom,
- createVoiceParticipantSnapshot,
- createVoiceRemoteSpeakingSnapshot,
- findParticipantSnapshotByUserIdAndConnectionId,
- transitionVoiceParticipantSnapshot,
- transitionVoiceRemoteSpeakingSnapshot,
- type VoiceRemoteSpeakingCommand,
- type VoiceRemoteSpeakingSnapshot,
-} from '@app/features/voice/engine/VoiceParticipantStateMachine';
-import {SPEAKING_REMOTE_ATTACK_MS, SPEAKING_REMOTE_RELEASE_MS} from '@app/features/voice/engine/VoiceSpeakingThreshold';
-import {
- VoiceConnectionQuality,
- type VoiceConnectionQuality as VoiceConnectionQualityType,
-} from '@app/features/voice/engine/VoiceTrackSource';
-import type {Participant, Room} from 'livekit-client';
-import {describe, expect, it} from 'vitest';
-
-const connectionQuality = VoiceConnectionQuality.Good;
-
-function participant(
- identity: string,
- overrides: Omit<Partial<Participant>, 'connectionQuality'> & {
- connectionQuality?: VoiceConnectionQualityType;
- audioTrackSids?: ReadonlyArray<string>;
- videoTrackSids?: ReadonlyArray<string>;
- } = {},
-): Participant {
- return {
- identity,
- sid: overrides.sid ?? `sid-${identity}`,
- isLocal: overrides.isLocal ?? false,
- isSpeaking: overrides.isSpeaking ?? false,
- connectionQuality: overrides.connectionQuality ?? connectionQuality,
- metadata: overrides.metadata,
- attributes: overrides.attributes ?? {},
- audioTrackPublications:
- overrides.audioTrackPublications ?? new Map((overrides.audioTrackSids ?? []).map((sid) => [sid, {}])),
- videoTrackPublications: new Map((overrides.videoTrackSids ?? []).map((sid) => [sid, {}])),
- isMicrophoneEnabled: overrides.isMicrophoneEnabled ?? false,
- isCameraEnabled: overrides.isCameraEnabled ?? false,
- isScreenShareEnabled: overrides.isScreenShareEnabled ?? false,
- joinedAt: overrides.joinedAt ?? null,
- lastSpokeAt: overrides.lastSpokeAt ?? null,
- } as Participant;
-}
-
-function room(localParticipant: Participant | null, remoteParticipants: ReadonlyArray<Participant>): Room {
- return {
- localParticipant,
- remoteParticipants: new Map(remoteParticipants.map((p) => [p.identity, p])),
- } as Room;
-}
-
-function commandsOf(snapshot: VoiceRemoteSpeakingSnapshot): ReadonlyArray<VoiceRemoteSpeakingCommand> {
- return snapshot.context.commands;
-}
-
-const LEVELLER_IDENTITY = 'user_1_a';
-const LEVELLER_TICK_MS = 50;
-
-function attachedRemoteSnapshot(): VoiceRemoteSpeakingSnapshot {
- const attached = transitionVoiceRemoteSpeakingSnapshot(createVoiceRemoteSpeakingSnapshot(), {
- type: 'remote.attach',
- identity: LEVELLER_IDENTITY,
- track: {},
- });
- return transitionVoiceRemoteSpeakingSnapshot(attached, {type: 'remote.clearCommands'});
-}
-
-function runRemoteTicks(
- snapshot: VoiceRemoteSpeakingSnapshot,
- options: {rms: number; threshold: number; ticks: number; startMs: number},
-): {snapshot: VoiceRemoteSpeakingSnapshot; commands: Array<VoiceRemoteSpeakingCommand>; endMs: number} {
- let next = snapshot;
- let nowMs = options.startMs;
- const commands: Array<VoiceRemoteSpeakingCommand> = [];
- for (let i = 0; i < options.ticks; i++) {
- next = transitionVoiceRemoteSpeakingSnapshot(next, {
- type: 'remote.tick',
- identity: LEVELLER_IDENTITY,
- rms: options.rms,
- threshold: options.threshold,
- nowMs,
- });
- commands.push(...commandsOf(next));
- next = transitionVoiceRemoteSpeakingSnapshot(next, {type: 'remote.clearCommands'});
- nowMs += LEVELLER_TICK_MS;
- }
- return {snapshot: next, commands, endMs: nowMs};
-}
-
-function playbackBoostOf(snapshot: VoiceRemoteSpeakingSnapshot): number {
- return snapshot.context.analysers.get(LEVELLER_IDENTITY)?.playbackBoost ?? Number.NaN;
-}
-
-function appliedBoostOf(snapshot: VoiceRemoteSpeakingSnapshot): number {
- return snapshot.context.analysers.get(LEVELLER_IDENTITY)?.appliedBoost ?? Number.NaN;
-}
-
-describe('VoiceParticipantStateMachine participants', () => {
- it('keeps participant snapshot references stable when an upsert is equal', () => {
- const p = participant('user_42_conn-a', {
- audioTrackSids: ['audio-b', 'audio-a'],
- videoTrackSids: ['video-a'],
- attributes: {role: 'speaker'},
- joinedAt: new Date(100),
- });
- let snapshot = createVoiceParticipantSnapshot();
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(p),
- });
- const participantsRef = snapshot.context.participants;
- const participantRef = snapshot.context.participants[p.identity];
-
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(
- participant('user_42_conn-a', {
- audioTrackSids: ['audio-b', 'audio-a'],
- videoTrackSids: ['video-a'],
- attributes: {role: 'speaker'},
- joinedAt: new Date(100),
- }),
- ),
- });
-
- expect(snapshot.context.participants).toBe(participantsRef);
- expect(snapshot.context.participants[p.identity]).toBe(participantRef);
- expect(participantRef?.audioTrackSids).toEqual(['audio-a', 'audio-b']);
- });
-
- it('derives screen-share audio state from audio publications', () => {
- const p = participant('user_42_conn-a', {
- audioTrackPublications: new Map([
- [
- 'screen-audio',
- {
- source: 'screen_share_audio',
- isMuted: false,
- },
- ],
- ]) as Participant['audioTrackPublications'],
- });
-
- expect(createLivekitParticipantSnapshot(p).isScreenShareAudioEnabled).toBe(true);
- });
-
- it('hydrates from the room and removes stale participants', () => {
- let snapshot = createVoiceParticipantSnapshot();
- const alice = participant('user_1_a');
- const bob = participant('user_2_b');
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.hydrate',
- snapshots: [createLivekitParticipantSnapshot(alice), createLivekitParticipantSnapshot(bob)],
- });
-
- const hydrated = createLivekitParticipantSnapshotsFromRoom(room(alice, []), snapshot.context.participants);
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {type: 'participant.hydrate', snapshots: hydrated});
-
- expect(Object.keys(snapshot.context.participants)).toEqual(['user_1_a']);
- expect(snapshot.context.participants['user_1_a']).toBeDefined();
- expect(snapshot.context.participants['user_2_b']).toBeUndefined();
- });
-
- it('parses multiple connections for the same user identity independently', () => {
- let snapshot = createVoiceParticipantSnapshot();
- for (const p of [participant('user_99_desktop'), participant('user_99_mobile')]) {
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(p),
- });
- }
-
- expect(
- findParticipantSnapshotByUserIdAndConnectionId(snapshot.context.participants, '99', 'desktop')?.identity,
- ).toBe('user_99_desktop');
- expect(
- findParticipantSnapshotByUserIdAndConnectionId(snapshot.context.participants, '99', 'mobile')?.identity,
- ).toBe('user_99_mobile');
- expect(findParticipantSnapshotByUserIdAndConnectionId(snapshot.context.participants, '99', null)).toBeUndefined();
- });
-
- it('diffs active speaker updates without creating missing participants', () => {
- let snapshot = createVoiceParticipantSnapshot();
- for (const p of [participant('user_1_a'), participant('user_2_b')]) {
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(p),
- });
- }
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.activeSpeakers',
- identities: ['user_1_a', 'user_3_c'],
- });
-
- expect(snapshot.context.participants['user_1_a']?.isSpeaking).toBe(true);
- expect(snapshot.context.participants['user_2_b']?.isSpeaking).toBe(false);
- expect(snapshot.context.participants['user_3_c']).toBeUndefined();
-
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.activeSpeakers',
- identities: ['user_2_b'],
- });
- expect(snapshot.context.participants['user_1_a']?.isSpeaking).toBe(false);
- expect(snapshot.context.participants['user_2_b']?.isSpeaking).toBe(true);
- });
-
- it('records lastSpokeAt from audio-level speaking updates', () => {
- let snapshot = createVoiceParticipantSnapshot();
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(participant('user_1_a')),
- });
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.setAudioLevelSpeaking',
- identity: 'user_1_a',
- speaking: true,
- nowMs: 1234,
- });
- expect(snapshot.context.participants['user_1_a']?.isAudioLevelSpeaking).toBe(true);
- expect(snapshot.context.participants['user_1_a']?.lastSpokeAt).toBe(1234);
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.upsert',
- snapshot: createLivekitParticipantSnapshot(
- participant('user_1_a', {lastSpokeAt: new Date(9999)}),
- snapshot.context.participants['user_1_a'],
- ),
- });
- expect(snapshot.context.participants['user_1_a']?.lastSpokeAt).toBe(1234);
- snapshot = transitionVoiceParticipantSnapshot(snapshot, {
- type: 'participant.setAudioLevelSpeaking',
- identity: 'user_1_a',
- speaking: false,
- nowMs: 2000,
- });
- expect(snapshot.context.participants['user_1_a']?.isAudioLevelSpeaking).toBe(false);
- expect(snapshot.context.participants['user_1_a']?.lastSpokeAt).toBe(1234);
- });
-});
-
-describe('VoiceParticipantStateMachine remote speaking', () => {
- it('applies attack and release timing for audio-level speaking', () => {
- const track = {};
- const threshold = 0.015;
- let snapshot = createVoiceRemoteSpeakingSnapshot();
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.attach', identity: 'user_1_a', track});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0.02,
- threshold,
- nowMs: 0,
- });
- expect(commandsOf(snapshot).some((command) => command.type === 'setAudioLevelSpeaking')).toBe(false);
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0.02,
- threshold,
- nowMs: SPEAKING_REMOTE_ATTACK_MS + 1,
- });
- expect(commandsOf(snapshot)).toContainEqual({type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: true});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0,
- threshold,
- nowMs: 100,
- });
- expect(commandsOf(snapshot).some((command) => command.type === 'setAudioLevelSpeaking')).toBe(false);
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0,
- threshold,
- nowMs: 100 + SPEAKING_REMOTE_RELEASE_MS + 1,
- });
- expect(commandsOf(snapshot)).toContainEqual({type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: false});
- });
-
- it('detaches and clears remote state when a track ends', () => {
- let snapshot = createVoiceRemoteSpeakingSnapshot();
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_1_a',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0,
- threshold: 0,
- nowMs: 10,
- trackEnded: true,
- });
-
- expect(snapshot.context.analysers.has('user_1_a')).toBe(false);
- expect(commandsOf(snapshot)).toEqual([
- {type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: false},
- {type: 'clearPlaybackBoost', identity: 'user_1_a'},
- ]);
- });
-
- it('suspends on visibility hide and requests rehydrate on show', () => {
- let snapshot = createVoiceRemoteSpeakingSnapshot();
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_1_a',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_2_b',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.visibilityHidden'});
- expect(snapshot.context.analyserSuspendedByVisibility).toBe(true);
- expect(snapshot.context.analysers.size).toBe(0);
- expect(commandsOf(snapshot)).toEqual([
- {type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: false},
- {type: 'clearPlaybackBoost', identity: 'user_1_a'},
- {type: 'setAudioLevelSpeaking', identity: 'user_2_b', speaking: false},
- {type: 'clearPlaybackBoost', identity: 'user_2_b'},
- ]);
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.visibilityVisible'});
- expect(snapshot.context.analyserSuspendedByVisibility).toBe(false);
- expect(commandsOf(snapshot)).toEqual([{type: 'rehydrateRemoteAnalysers'}]);
- });
-
- it('holds the playback boost through silence and releases it back to unity', () => {
- let snapshot = transitionVoiceRemoteSpeakingSnapshot(createVoiceRemoteSpeakingSnapshot(), {
- type: 'remote.attach',
- identity: LEVELLER_IDENTITY,
- track: {},
- });
- expect(commandsOf(snapshot)).toEqual([{type: 'setPlaybackBoost', identity: LEVELLER_IDENTITY, boost: 1}]);
- expect(playbackBoostOf(snapshot)).toBe(1);
- expect(appliedBoostOf(snapshot)).toBe(1);
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
-
- const settled = runRemoteTicks(snapshot, {rms: 0.03, threshold: 0.006, ticks: 60, startMs: 0});
- expect(playbackBoostOf(settled.snapshot)).toBeGreaterThan(2.5);
- expect(settled.commands.some((command) => command.type === 'setPlaybackBoost')).toBe(true);
-
- const settledBoost = playbackBoostOf(settled.snapshot);
- const held = runRemoteTicks(settled.snapshot, {rms: 0, threshold: 0.006, ticks: 60, startMs: settled.endMs});
- expect(held.endMs - settled.endMs).toBe(__TEST__.REMOTE_PLAYBACK_SILENCE_HOLD_MS);
- expect(playbackBoostOf(held.snapshot)).toBe(settledBoost);
- expect(held.commands.some((command) => command.type === 'clearPlaybackBoost')).toBe(false);
-
- const released = runRemoteTicks(held.snapshot, {rms: 0, threshold: 0.006, ticks: 700, startMs: held.endMs});
- expect(released.commands.filter((command) => command.type === 'clearPlaybackBoost')).toHaveLength(1);
- expect(playbackBoostOf(released.snapshot)).toBe(1);
- expect(appliedBoostOf(released.snapshot)).toBe(1);
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(released.snapshot, {
- type: 'remote.detach',
- identity: LEVELLER_IDENTITY,
- });
- expect(commandsOf(snapshot)).toEqual([
- {type: 'setAudioLevelSpeaking', identity: LEVELLER_IDENTITY, speaking: false},
- {type: 'clearPlaybackBoost', identity: LEVELLER_IDENTITY},
- ]);
- });
-
- it('holds the boost through an inter-syllabic pause instead of pumping', () => {
- const settled = runRemoteTicks(attachedRemoteSnapshot(), {rms: 0.02, threshold: 0.006, ticks: 120, startMs: 0});
- expect(playbackBoostOf(settled.snapshot)).toBeCloseTo(__TEST__.REMOTE_PLAYBACK_MAX_BOOST, 2);
-
- const settledBoost = playbackBoostOf(settled.snapshot);
- const paused = runRemoteTicks(settled.snapshot, {rms: 0.002, threshold: 0.006, ticks: 4, startMs: settled.endMs});
- expect(Math.abs(playbackBoostOf(paused.snapshot) - settledBoost)).toBeLessThan(settledBoost * 0.01);
- expect(paused.commands).toHaveLength(0);
- });
-
- it('integrates steps the emit guard suppresses', () => {
- const settled = runRemoteTicks(attachedRemoteSnapshot(), {rms: 0.086, threshold: 0.006, ticks: 200, startMs: 0});
- expect(playbackBoostOf(settled.snapshot)).toBeCloseTo(1.0465, 4);
- expect(appliedBoostOf(settled.snapshot)).toBeLessThan(playbackBoostOf(settled.snapshot));
- });
-
- it('targets roughly -21 dBFS of playback level', () => {
- const settled = runRemoteTicks(attachedRemoteSnapshot(), {rms: 0.045, threshold: 0.006, ticks: 200, startMs: 0});
- expect(playbackBoostOf(settled.snapshot)).toBeCloseTo(2, 4);
- expect(playbackBoostOf(settled.snapshot) * 0.045).toBeCloseTo(__TEST__.REMOTE_PLAYBACK_TARGET_RMS, 4);
- });
-
- it('never integrates on a zero threshold', () => {
- const settled = runRemoteTicks(attachedRemoteSnapshot(), {rms: 0, threshold: 0, ticks: 10, startMs: 0});
- expect(playbackBoostOf(settled.snapshot)).toBe(1);
- expect(settled.commands.some((command) => command.type === 'setPlaybackBoost')).toBe(false);
- });
-
- it('clears a stale boost when reattaching a different track', () => {
- const settled = runRemoteTicks(attachedRemoteSnapshot(), {rms: 0.02, threshold: 0.006, ticks: 60, startMs: 0});
- expect(appliedBoostOf(settled.snapshot)).toBeGreaterThan(1);
-
- const reattached = transitionVoiceRemoteSpeakingSnapshot(settled.snapshot, {
- type: 'remote.attach',
- identity: LEVELLER_IDENTITY,
- track: {},
- });
- expect(commandsOf(reattached)).toEqual([
- {type: 'setAudioLevelSpeaking', identity: LEVELLER_IDENTITY, speaking: false},
- {type: 'clearPlaybackBoost', identity: LEVELLER_IDENTITY},
- {type: 'setPlaybackBoost', identity: LEVELLER_IDENTITY, boost: 1},
- ]);
- expect(playbackBoostOf(reattached)).toBe(1);
- expect(appliedBoostOf(reattached)).toBe(1);
- });
-
- it('clears stale speaking flags after detach and clear', () => {
- let snapshot = createVoiceRemoteSpeakingSnapshot();
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_1_a',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0.02,
- threshold: 0.015,
- nowMs: 0,
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity: 'user_1_a',
- rms: 0.02,
- threshold: 0.015,
- nowMs: SPEAKING_REMOTE_ATTACK_MS + 1,
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.detach', identity: 'user_1_a'});
- expect(commandsOf(snapshot)).toContainEqual({type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: false});
-
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_1_a',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.attach',
- identity: 'user_2_b',
- track: {},
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- for (const identity of ['user_1_a', 'user_2_b']) {
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity,
- rms: 0.02,
- threshold: 0.015,
- nowMs: 0,
- });
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {
- type: 'remote.tick',
- identity,
- rms: 0.02,
- threshold: 0.015,
- nowMs: SPEAKING_REMOTE_ATTACK_MS + 1,
- });
- }
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clearCommands'});
- snapshot = transitionVoiceRemoteSpeakingSnapshot(snapshot, {type: 'remote.clear'});
- expect(commandsOf(snapshot)).toEqual([
- {type: 'setAudioLevelSpeaking', identity: 'user_1_a', speaking: false},
- {type: 'clearPlaybackBoost', identity: 'user_1_a'},
- {type: 'setAudioLevelSpeaking', identity: 'user_2_b', speaking: false},
- {type: 'clearPlaybackBoost', identity: 'user_2_b'},
- ]);
- expect(snapshot.context.analysers.size).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.test.ts
deleted file mode 100644
index 4fd6ac97b..000000000
--- a/fluxer_app/src/features/voice/engine/VoicePermissionStateMachine.test.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoicePermissionSnapshot,
- getVoicePermissionWatchStateValue,
- transitionVoicePermissionSnapshot,
- type VoicePermissionCommand,
- type VoicePermissionEvent,
- type VoicePermissionSnapshot,
-} from '@app/features/voice/engine/VoicePermissionStateMachine';
-import type {VoiceChannelPermissions} from '@app/features/voice/utils/VoicePermissionUtils';
-import {describe, expect, it} from 'vitest';
-
-const DEFAULT_PERMISSIONS: VoiceChannelPermissions = {
- canSpeak: true,
- canStream: true,
- canUseVideo: true,
- canConnect: true,
- canPrioritySpeaker: false,
- canUseVad: true,
-};
-
-function permissions(overrides: Partial<VoiceChannelPermissions> = {}): VoiceChannelPermissions {
- return {...DEFAULT_PERMISSIONS, ...overrides};
-}
-
-function transition(snapshot: VoicePermissionSnapshot, event: VoicePermissionEvent): VoicePermissionSnapshot {
- return transitionVoicePermissionSnapshot(snapshot, event);
-}
-
-function clearCommands(snapshot: VoicePermissionSnapshot): VoicePermissionSnapshot {
- return transition(snapshot, {type: 'permission.clearCommands'});
-}
-
-function commands(snapshot: VoicePermissionSnapshot): ReadonlyArray<VoicePermissionCommand> {
- return snapshot.context.commands;
-}
-
-describe('VoicePermissionStateMachine', () => {
- it('keeps unchanged permissions as a no-op', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {type: 'permission.update', permissions: permissions(), roomPresent: true});
-
- expect(snapshot.context.permissions).toEqual(permissions());
- expect(snapshot.context.roomPresent).toBe(true);
- expect(commands(snapshot)).toEqual([]);
- });
-
- it('emits mute sync and local audio revoke decisions when speak is revoked', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.update',
- permissions: permissions({canSpeak: false}),
- roomPresent: true,
- });
-
- expect(commands(snapshot)).toEqual([
- {type: 'syncSpeakPermission', canSpeak: false, selfMute: true},
- {type: 'revokeLocalAudio'},
- ]);
- expect(snapshot.context.permissions.canSpeak).toBe(false);
- });
-
- it('emits a screen-share stop decision when stream permission is revoked', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.update',
- permissions: permissions({canStream: false}),
- roomPresent: true,
- });
-
- expect(commands(snapshot)).toEqual([{type: 'stopScreenShare'}]);
- expect(snapshot.context.permissions.canStream).toBe(false);
- });
-
- it('emits a camera-off decision when video permission is revoked', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.update',
- permissions: permissions({canUseVideo: false}),
- roomPresent: true,
- });
-
- expect(commands(snapshot)).toEqual([{type: 'disableCamera'}]);
- expect(snapshot.context.permissions.canUseVideo).toBe(false);
- });
-
- it('turns remote microphone subscriptions off and back on for deafen toggles', () => {
- let snapshot = createVoicePermissionSnapshot();
- const microphonePublications = [
- {publicationId: 'mic-a', isDesired: true},
- {publicationId: 'mic-b', isDesired: false},
- ];
-
- snapshot = transition(snapshot, {
- type: 'deafen.apply',
- deafened: true,
- microphonePublications,
- });
- expect(snapshot.context.deafened).toBe(true);
- expect(commands(snapshot)).toEqual([
- {type: 'setRemoteMicrophoneEnabled', publicationId: 'mic-a', enabled: false},
- {type: 'setRemoteMicrophoneSubscribed', publicationId: 'mic-a', subscribed: false},
- {type: 'setRemoteMicrophoneSubscribed', publicationId: 'mic-b', subscribed: false},
- ]);
-
- snapshot = clearCommands(snapshot);
- snapshot = transition(snapshot, {
- type: 'deafen.apply',
- deafened: false,
- microphonePublications,
- });
- expect(snapshot.context.deafened).toBe(false);
- expect(commands(snapshot)).toEqual([
- {type: 'setRemoteMicrophoneSubscribed', publicationId: 'mic-a', subscribed: true},
- {type: 'setRemoteMicrophoneEnabled', publicationId: 'mic-a', enabled: true},
- {type: 'setRemoteMicrophoneSubscribed', publicationId: 'mic-b', subscribed: true},
- {type: 'setRemoteMicrophoneEnabled', publicationId: 'mic-b', enabled: true},
- ]);
- });
-
- it('initializes remote subscription policy from the current deafened state', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'deafen.apply',
- deafened: true,
- microphonePublications: [],
- });
- snapshot = clearCommands(snapshot);
- snapshot = transition(snapshot, {
- type: 'subscription.initialize',
- microphonePublications: [{publicationId: 'mic-a', isDesired: true}],
- videoPublicationIds: ['video-a'],
- });
-
- expect(commands(snapshot)).toEqual([
- {type: 'setRemoteMicrophoneSubscribed', publicationId: 'mic-a', subscribed: false},
- {type: 'setRemoteVideoSubscribed', publicationId: 'video-a', subscribed: false},
- ]);
- });
-
- it('updates permissions without room-bound revoke decisions when no room is present', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.update',
- permissions: permissions({canSpeak: false, canStream: false, canUseVideo: false}),
- roomPresent: false,
- });
-
- expect(snapshot.context.permissions).toEqual(permissions({canSpeak: false, canStream: false, canUseVideo: false}));
- expect(snapshot.context.roomPresent).toBe(false);
- expect(commands(snapshot)).toEqual([{type: 'syncSpeakPermission', canSpeak: false, selfMute: true}]);
- });
-
- it('tracks watcher activation and emits cleanup on reset', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.watch.start',
- guildId: 'guild-a',
- channelId: 'channel-a',
- roomPresent: true,
- });
- expect(getVoicePermissionWatchStateValue(snapshot)).toBe('watching');
- expect(snapshot.context).toMatchObject({
- guildId: 'guild-a',
- channelId: 'channel-a',
- roomPresent: true,
- watcherActive: true,
- });
-
- snapshot = transition(snapshot, {type: 'permission.reset'});
- expect(getVoicePermissionWatchStateValue(snapshot)).toBe('inactive');
- expect(snapshot.context.permissions).toEqual(DEFAULT_PERMISSIONS);
- expect(snapshot.context.deafened).toBe(false);
- expect(snapshot.context.roomPresent).toBe(false);
- expect(commands(snapshot)).toEqual([{type: 'stopPermissionWatch'}]);
- });
-
- it('handles repeated grant and revoke cycles idempotently', () => {
- let snapshot = createVoicePermissionSnapshot();
- snapshot = transition(snapshot, {
- type: 'permission.change',
- permission: 'speak',
- allowed: false,
- roomPresent: true,
- });
- expect(commands(snapshot)).toEqual([
- {type: 'syncSpeakPermission', canSpeak: false, selfMute: true},
- {type: 'revokeLocalAudio'},
- ]);
-
- snapshot = clearCommands(snapshot);
- snapshot = transition(snapshot, {
- type: 'permission.change',
- permission: 'speak',
- allowed: true,
- roomPresent: true,
- });
- expect(commands(snapshot)).toEqual([{type: 'syncSpeakPermission', canSpeak: true, selfMute: false}]);
-
- snapshot = clearCommands(snapshot);
- snapshot = transition(snapshot, {
- type: 'permission.change',
- permission: 'speak',
- allowed: false,
- roomPresent: true,
- });
- expect(commands(snapshot)).toEqual([
- {type: 'syncSpeakPermission', canSpeak: false, selfMute: true},
- {type: 'revokeLocalAudio'},
- ]);
-
- snapshot = clearCommands(snapshot);
- snapshot = transition(snapshot, {
- type: 'permission.change',
- permission: 'speak',
- allowed: false,
- roomPresent: true,
- });
- expect(commands(snapshot)).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceRoomEventBinder.test.ts b/fluxer_app/src/features/voice/engine/VoiceRoomEventBinder.test.ts
deleted file mode 100644
index 8ca544404..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceRoomEventBinder.test.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {RoomEventCallbacks, RoomEventDependencies} from '@app/features/voice/engine/VoiceRoomEventBinder';
-import {ConnectionState, type Room, RoomEvent} from 'livekit-client';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- bindCodecNegotiation: vi.fn(() => vi.fn()),
- disposeCodecNegotiation: vi.fn(),
- bindScreenShareMigration: vi.fn(() => vi.fn()),
- disposeScreenShareMigration: vi.fn(),
-}));
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-
-vi.mock('@app/features/voice/engine/ScreenShareCodecNegotiation', () => ({
- default: {
- bind: mocks.bindCodecNegotiation,
- dispose: mocks.disposeCodecNegotiation,
- getSelectedCodec: vi.fn(() => null),
- publishLocalCapabilities: vi.fn(async () => null),
- selectNativeScreenShareCodec: vi.fn(() => null),
- selectScreenShareCodec: vi.fn(() => null),
- setSelectionChangeListener: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/voice/engine/ScreenSharePublicationMigration', () => ({
- default: {
- bind: mocks.bindScreenShareMigration,
- dispose: mocks.disposeScreenShareMigration,
- getManagedScreenSharePublications: vi.fn(() => []),
- getScreenSharePublicationsToDisable: vi.fn(() => []),
- isScreenShareBuffering: vi.fn(() => false),
- selectScreenSharePublication: vi.fn(() => null),
- subscribe: vi.fn(() => vi.fn()),
- version: 0,
- },
-}));
-
-installVoiceMenuTestBootstrap();
-
-const {bindRoomEvents} = await import('@app/features/voice/engine/VoiceRoomEventBinder');
-
-class FakeRoom {
- private handlers = new Map<string, Set<(...args: Array<unknown>) => unknown>>();
- localParticipant = {identity: 'local', on: vi.fn(), off: vi.fn()};
- remoteParticipants = new Map<string, {identity: string}>();
-
- constructor(public state: ConnectionState) {}
-
- on(event: string, handler: (...args: Array<unknown>) => unknown): this {
- if (!this.handlers.has(event)) this.handlers.set(event, new Set());
- this.handlers.get(event)?.add(handler);
- return this;
- }
-
- off(event: string, handler: (...args: Array<unknown>) => unknown): this {
- this.handlers.get(event)?.delete(handler);
- return this;
- }
-
- async emit(event: string, ...args: Array<unknown>): Promise<void> {
- for (const handler of this.handlers.get(event) ?? []) {
- await handler(...args);
- }
- }
-}
-
-function createCallbacks(): RoomEventCallbacks {
- return {
- onConnected: vi.fn(async () => undefined),
- onDisconnected: vi.fn(),
- onReconnecting: vi.fn(),
- onReconnected: vi.fn(),
- };
-}
-
-function createDependencies(options: {attemptIsStale?: boolean} = {}): RoomEventDependencies {
- return {
- connection: {
- createGuardedHandler: (_attemptId, handler) => {
- return (...args) => {
- if (options.attemptIsStale) return;
- void handler(...args);
- };
- },
- isDisconnecting: () => false,
- isUserMovePending: () => true,
- markConnected: vi.fn(),
- markDisconnected: vi.fn(),
- markReconnecting: vi.fn(),
- markReconnected: vi.fn(),
- },
- media: {
- applyAllLocalAudioPreferences: vi.fn(),
- ensureMicrophone: vi.fn(async () => undefined),
- playEntranceSound: vi.fn(async () => undefined),
- resetStreamTracking: vi.fn(),
- },
- mediaState: {
- handleLocalTrackStateChange: vi.fn(() => false),
- resetLocalMediaState: vi.fn(),
- },
- participants: {
- clear: vi.fn(),
- hydrateFromRoom: vi.fn(),
- removeParticipant: vi.fn(),
- updateActiveSpeakers: vi.fn(),
- upsertParticipant: vi.fn(),
- },
- permissions: {
- applyDeafen: vi.fn(),
- syncWithPermissionState: vi.fn(),
- },
- remoteSpeaking: {
- attachIfApplicable: vi.fn(),
- clear: vi.fn(),
- detachByIdentity: vi.fn(),
- detachIfTrackMatches: vi.fn(),
- hydrateFromRoom: vi.fn(),
- },
- screenShare: {
- cleanupLingeringScreenShareTracks: vi.fn(async () => undefined),
- handleLocalScreenShareTrackUnpublished: vi.fn(),
- isScreenSharePublicationReplaceInFlight: () => false,
- },
- subscriptions: {
- isScreenShareSubscribed: () => false,
- reattachScreenShareAfterPublish: vi.fn(),
- reconcileSubscriptions: vi.fn(),
- },
- };
-}
-
-function bindFakeRoom(room: FakeRoom, options: {attemptIsStale?: boolean} = {}): void {
- bindRoomEvents(room as unknown as Room, 1, 'guild-1', 'channel-1', createCallbacks(), createDependencies(options));
-}
-
-describe('binding room events for screen share negotiation', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('binds codec negotiation and publication migration to a room that is already connected', () => {
- bindFakeRoom(new FakeRoom(ConnectionState.Connected));
- expect(mocks.bindCodecNegotiation).toHaveBeenCalledTimes(1);
- expect(mocks.bindScreenShareMigration).toHaveBeenCalledTimes(1);
- });
-
- it('binds neither until a room that is not connected yet reports it has connected', async () => {
- const room = new FakeRoom(ConnectionState.Disconnected);
- bindFakeRoom(room);
- expect(mocks.bindCodecNegotiation).not.toHaveBeenCalled();
- expect(mocks.bindScreenShareMigration).not.toHaveBeenCalled();
- room.state = ConnectionState.Connected;
- await room.emit(RoomEvent.Connected);
- expect(mocks.bindCodecNegotiation).toHaveBeenCalledTimes(1);
- expect(mocks.bindScreenShareMigration).toHaveBeenCalledTimes(1);
- });
-
- it('binds once however often an already connected room reports it has connected', async () => {
- const room = new FakeRoom(ConnectionState.Connected);
- bindFakeRoom(room);
- await room.emit(RoomEvent.Connected);
- await room.emit(RoomEvent.Connected);
- expect(mocks.bindCodecNegotiation).toHaveBeenCalledTimes(1);
- expect(mocks.bindScreenShareMigration).toHaveBeenCalledTimes(1);
- });
-
- it('binds again after an already connected room disconnects and connects once more', async () => {
- const room = new FakeRoom(ConnectionState.Connected);
- bindFakeRoom(room);
- await room.emit(RoomEvent.Disconnected);
- expect(mocks.disposeCodecNegotiation).toHaveBeenCalledTimes(1);
- expect(mocks.disposeScreenShareMigration).toHaveBeenCalledTimes(1);
- await room.emit(RoomEvent.Connected);
- expect(mocks.bindCodecNegotiation).toHaveBeenCalledTimes(2);
- expect(mocks.bindScreenShareMigration).toHaveBeenCalledTimes(2);
- });
-
- it('binds nothing to an already connected room whose connection attempt is stale', () => {
- bindFakeRoom(new FakeRoom(ConnectionState.Connected), {attemptIsStale: true});
- expect(mocks.bindCodecNegotiation).not.toHaveBeenCalled();
- expect(mocks.bindScreenShareMigration).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.test.ts
deleted file mode 100644
index 74509fec9..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceScreenShareStateMachine.test.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceScreenShareSnapshot,
- getVoiceScreenShareStateValue,
- transitionVoiceScreenShareSnapshot,
- type VoiceScreenShareSnapshot,
-} from '@app/features/voice/engine/VoiceScreenShareStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const STREAM_KEY = 'guild-a:channel-a:connection-a';
-
-function resolveActive(
- snapshot: VoiceScreenShareSnapshot,
- sourceType: 'display' | 'native-display' | 'device' = 'display',
-) {
- return transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.resolve',
- active: true,
- sourceType,
- encoderVerificationScheduled: true,
- streamingPriorityHeld: true,
- });
-}
-
-describe('VoiceScreenShareStateMachine', () => {
- it('tracks repeated start and stop without leaving duplicate pending state', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('pending');
- expect(snapshot.context.pendingOperation).toBe('starting');
- snapshot = resolveActive(snapshot);
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('active');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.stop',
- request: {sendUpdate: true, playSound: true},
- });
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.stop',
- request: {sendUpdate: false, playSound: false},
- });
- expect(snapshot.context.pendingOperation).toBe('stopping');
- expect(snapshot.context.queuedStopRequest).toEqual({sendUpdate: false, playSound: false});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.resolve',
- active: false,
- sourceType: null,
- encoderVerificationScheduled: false,
- streamingPriorityHeld: false,
- });
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('inactive');
- expect(snapshot.context.sourceType).toBeNull();
- expect(snapshot.context.streamingPriorityHeld).toBe(false);
- expect(snapshot.context.encoderVerificationScheduled).toBe(false);
- });
-
- it('returns to inactive after start cancellation or denial', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.cancel', active: false, sourceType: null});
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('inactive');
- expect(snapshot.context.pendingOperation).toBeNull();
- expect(snapshot.context.publicationReplaceInFlight).toBe(false);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'device'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.reject', active: false, sourceType: null});
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('inactive');
- });
-
- it('queues stop while start is pending and preserves the requested stop options', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'native-display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.stop',
- request: {sendUpdate: false, playSound: true},
- });
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('pending');
- expect(snapshot.context.pendingOperation).toBe('starting');
- expect(snapshot.context.queuedStopRequest).toEqual({sendUpdate: false, playSound: true});
- snapshot = resolveActive(snapshot, 'native-display');
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('active');
- expect(snapshot.context.queuedStopRequest).toEqual({sendUpdate: false, playSound: true});
- });
-
- it('tracks source replacement success and failure without losing the active source on failure', () => {
- let snapshot = resolveActive(
- transitionVoiceScreenShareSnapshot(createVoiceScreenShareSnapshot(), {
- type: 'share.start',
- sourceType: 'display',
- }),
- );
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.replace', sourceType: 'device'});
- expect(snapshot.context.pendingOperation).toBe('replacing');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.reject',
- active: true,
- sourceType: 'display',
- });
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('active');
- expect(snapshot.context.sourceType).toBe('display');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.replace', sourceType: 'device'});
- snapshot = resolveActive(snapshot, 'device');
- expect(snapshot.context.sourceType).toBe('device');
- });
-
- it('holds the replace lock only while a replacing publication is pending', () => {
- let snapshot = resolveActive(
- transitionVoiceScreenShareSnapshot(createVoiceScreenShareSnapshot(), {
- type: 'share.start',
- sourceType: 'display',
- }),
- );
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.replace',
- sourceType: 'display',
- publicationReplaceInFlight: true,
- });
- expect(snapshot.context.publicationReplaceInFlight).toBe(true);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.cancel',
- active: true,
- sourceType: 'display',
- });
- expect(snapshot.context.publicationReplaceInFlight).toBe(false);
- });
-
- it('lets a pending start or restore raise and drop the replace lock around a codec correction', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.publicationReplace.set', inFlight: true});
- expect(snapshot.context.publicationReplaceInFlight).toBe(false);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.publicationReplace.set', inFlight: true});
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('pending');
- expect(snapshot.context.pendingOperation).toBe('starting');
- expect(snapshot.context.publicationReplaceInFlight).toBe(true);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.publicationReplace.set', inFlight: false});
- expect(snapshot.context.publicationReplaceInFlight).toBe(false);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.publicationReplace.set', inFlight: true});
- snapshot = resolveActive(snapshot);
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('active');
- expect(snapshot.context.publicationReplaceInFlight).toBe(false);
- });
-
- it('tracks codec readiness through the xstate context while starting', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- expect(snapshot.context.codecReadiness).toBe('idle');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.loading'});
- expect(snapshot.context.codecReadiness).toBe('loading');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.ready'});
- expect(snapshot.context.codecReadiness).toBe('ready');
- snapshot = resolveActive(snapshot);
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('active');
- expect(snapshot.context.codecReadiness).toBe('ready');
- });
-
- it('records codec readiness timeout and resets it for the next operation', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'display'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.loading'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.timeout'});
- expect(snapshot.context.codecReadiness).toBe('timeout');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.cancel', active: false, sourceType: null});
- expect(snapshot.context.codecReadiness).toBe('idle');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.start', sourceType: 'native-display'});
- expect(snapshot.context.codecReadiness).toBe('idle');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.loading'});
- expect(snapshot.context.codecReadiness).toBe('loading');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.codecReadiness.reset'});
- expect(snapshot.context.codecReadiness).toBe('idle');
- });
-
- it('tracks active track ended cleanup independently from stop resolution', () => {
- let snapshot = resolveActive(
- transitionVoiceScreenShareSnapshot(createVoiceScreenShareSnapshot(), {
- type: 'share.start',
- sourceType: 'display',
- }),
- );
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.endedStop.start'});
- expect(snapshot.context.endedTrackStopInFlight).toBe(true);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.stop',
- request: {sendUpdate: true, playSound: true},
- });
- expect(snapshot.context.pendingOperation).toBe('stopping');
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.resolve',
- active: false,
- sourceType: null,
- encoderVerificationScheduled: false,
- streamingPriorityHeld: false,
- });
- expect(snapshot.context.endedTrackStopInFlight).toBe(true);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.endedStop.finish'});
- expect(snapshot.context.endedTrackStopInFlight).toBe(false);
- expect(getVoiceScreenShareStateValue(snapshot)).toBe('inactive');
- });
-
- it('emits local watcher add and remove decisions only when a change is needed', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: true,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys: [],
- });
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: true,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys: [STREAM_KEY],
- });
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: false,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys: [STREAM_KEY],
- });
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: false,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys: [],
- });
- expect(snapshot.context.watchCommands).toEqual([
- {type: 'watch.add', key: STREAM_KEY},
- {type: 'watch.remove', key: STREAM_KEY},
- ]);
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.clearWatchCommands'});
- expect(snapshot.context.watchCommands).toEqual([]);
- });
-
- it('does not accumulate duplicate watcher commands after repeated restarts when current state is synced', () => {
- let snapshot = createVoiceScreenShareSnapshot();
- let currentViewerStreamKeys: Array<string> = [];
- for (let i = 0; i < 10; i++) {
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: true,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys,
- });
- for (const command of snapshot.context.watchCommands) {
- if (command.type === 'watch.add' && !currentViewerStreamKeys.includes(command.key)) {
- currentViewerStreamKeys = [...currentViewerStreamKeys, command.key];
- }
- }
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.clearWatchCommands'});
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {
- type: 'share.localWatcher.sync',
- enabled: false,
- streamKey: STREAM_KEY,
- currentViewerStreamKeys,
- });
- for (const command of snapshot.context.watchCommands) {
- if (command.type === 'watch.remove') {
- currentViewerStreamKeys = currentViewerStreamKeys.filter((key) => key !== command.key);
- }
- }
- snapshot = transitionVoiceScreenShareSnapshot(snapshot, {type: 'share.clearWatchCommands'});
- }
- expect(currentViewerStreamKeys).toEqual([]);
- expect(snapshot.context.watchCommands).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceSelfJoinChime.test.ts b/fluxer_app/src/features/voice/engine/VoiceSelfJoinChime.test.ts
deleted file mode 100644
index 78bab6076..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceSelfJoinChime.test.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- discardVoiceJoinChimeSequence,
- resetSelfJoinChimesForTests,
- SELF_JOIN_CHIME_DEDUPE_WINDOW_MS,
- SELF_JOIN_CHIME_START_DEADLINE_MS,
- startVoiceJoinChimeSequence,
- VOICE_JOIN_CHIME_SEQUENCE_MAX_ENTRIES,
- VOICE_JOIN_CHIME_SEQUENCE_RETENTION_MS,
- type VoiceJoinChimeSequenceResult,
- waitForVoiceJoinChimeSequence,
-} from '@app/features/voice/engine/VoiceSelfJoinChime';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/ui/commands/SoundCommands', () => ({
- playOneShotSoundImmediatelyBypassingSelfDeafened: vi.fn(() => Promise.resolve(true)),
-}));
-
-vi.mock('@app/features/voice/state/VoiceRegionTeleport', () => ({
- default: {shouldSuppressRejoinSounds: () => false},
-}));
-
-const identity = {userId: 'user-1', channelId: 'channel-1'};
-
-function neverSettles(): Promise<boolean> {
- return new Promise<boolean>(() => {});
-}
-
-function track(promise: Promise<VoiceJoinChimeSequenceResult>): {value: VoiceJoinChimeSequenceResult | null} {
- const state: {value: VoiceJoinChimeSequenceResult | null} = {value: null};
- void promise.then((result) => {
- state.value = result;
- });
- return state;
-}
-
-describe('voice join chime sequence', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- resetSelfJoinChimesForTests();
- });
-
- afterEach(() => {
- resetSelfJoinChimesForTests();
- vi.useRealTimers();
- });
-
- it('dedupes two starts sharing the same join token', async () => {
- const start = vi.fn(() => Promise.resolve(true));
- const first = startVoiceJoinChimeSequence(identity, 'connection-1', start);
- const second = startVoiceJoinChimeSequence(identity, 'connection-1', start);
- expect(second).toBe(first);
- await vi.advanceTimersByTimeAsync(0);
- expect(start).toHaveBeenCalledTimes(1);
- await expect(first).resolves.toBe('started');
- await expect(second).resolves.toBe('started');
- });
-
- it('does not swallow a genuinely new connection token', async () => {
- const signals: Array<AbortSignal> = [];
- const start = vi.fn((signal: AbortSignal) => {
- signals.push(signal);
- return neverSettles();
- });
- const first = startVoiceJoinChimeSequence(identity, 'connection-1', start);
- await vi.advanceTimersByTimeAsync(0);
- const second = startVoiceJoinChimeSequence(identity, 'connection-2', start);
- await vi.advanceTimersByTimeAsync(0);
- expect(start).toHaveBeenCalledTimes(2);
- expect(signals[0]?.aborted).toBe(true);
- expect(signals[1]?.aborted).toBe(false);
- expect(second).not.toBe(first);
- await expect(first).resolves.toBe('unavailable');
- });
-
- it('adopts an existing entry when the join token is null', async () => {
- const firstStart = vi.fn(() => Promise.resolve(true));
- const secondStart = vi.fn(() => Promise.resolve(true));
- const first = startVoiceJoinChimeSequence(identity, 'connection-1', firstStart);
- const second = startVoiceJoinChimeSequence(identity, null, secondStart);
- expect(second).toBe(first);
- await vi.advanceTimersByTimeAsync(0);
- expect(firstStart).toHaveBeenCalledTimes(1);
- expect(secondStart).not.toHaveBeenCalled();
- });
-
- it('maps the start outcome onto the sequence result', async () => {
- const started = startVoiceJoinChimeSequence({userId: 'a', channelId: 'c'}, 'connection-a', () =>
- Promise.resolve(true),
- );
- const unavailable = startVoiceJoinChimeSequence({userId: 'b', channelId: 'c'}, 'connection-b', () =>
- Promise.resolve(false),
- );
- const threw = startVoiceJoinChimeSequence({userId: 'c', channelId: 'c'}, 'connection-c', () =>
- Promise.reject(new Error('no audio device')),
- );
- await vi.advanceTimersByTimeAsync(0);
- await expect(started).resolves.toBe('started');
- await expect(unavailable).resolves.toBe('unavailable');
- await expect(threw).resolves.toBe('unavailable');
- });
-
- it('expires a wait that no start ever adopts, and not one tick early', async () => {
- const waiting = track(waitForVoiceJoinChimeSequence(identity));
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_START_DEADLINE_MS - 1);
- expect(waiting.value).toBeNull();
- await vi.advanceTimersByTimeAsync(1);
- expect(waiting.value).toBe('expired-before-start');
- });
-
- it('lets a later start adopt the entry a wait created', async () => {
- const waiting = waitForVoiceJoinChimeSequence(identity);
- await vi.advanceTimersByTimeAsync(100);
- const start = vi.fn(() => Promise.resolve(true));
- const started = startVoiceJoinChimeSequence(identity, 'connection-1', start);
- await vi.advanceTimersByTimeAsync(0);
- expect(start).toHaveBeenCalledTimes(1);
- await expect(waiting).resolves.toBe('started');
- await expect(started).resolves.toBe('started');
- });
-
- it('bounds a start that never settles and aborts its signal', async () => {
- let captured: AbortSignal | null = null;
- const started = startVoiceJoinChimeSequence(identity, 'connection-1', (signal) => {
- captured = signal;
- return neverSettles();
- });
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_START_DEADLINE_MS);
- await expect(started).resolves.toBe('unavailable');
- expect(captured).not.toBeNull();
- expect((captured as unknown as AbortSignal).aborted).toBe(true);
- });
-
- it('keeps a settled started result across a discard and issues a fresh entry afterwards', async () => {
- const started = startVoiceJoinChimeSequence(identity, 'connection-1', () => Promise.resolve(true));
- await vi.advanceTimersByTimeAsync(0);
- await expect(started).resolves.toBe('started');
- discardVoiceJoinChimeSequence(identity);
- await expect(started).resolves.toBe('started');
- const waiting = track(waitForVoiceJoinChimeSequence(identity));
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_START_DEADLINE_MS);
- expect(waiting.value).toBe('expired-before-start');
- });
-
- it('expires an unsettled entry on discard and aborts its signal', async () => {
- let captured: AbortSignal | null = null;
- const started = startVoiceJoinChimeSequence(identity, 'connection-1', (signal) => {
- captured = signal;
- return neverSettles();
- });
- await vi.advanceTimersByTimeAsync(0);
- discardVoiceJoinChimeSequence(identity);
- await expect(started).resolves.toBe('expired-before-start');
- expect((captured as unknown as AbortSignal).aborted).toBe(true);
- });
-
- it('evicts the oldest entry rather than leaving its promise hanging', async () => {
- const evicted = track(waitForVoiceJoinChimeSequence({userId: 'user-0', channelId: 'channel-1'}));
- for (let index = 1; index <= VOICE_JOIN_CHIME_SEQUENCE_MAX_ENTRIES; index++) {
- waitForVoiceJoinChimeSequence({userId: `user-${index}`, channelId: 'channel-1'});
- }
- await vi.advanceTimersByTimeAsync(0);
- expect(evicted.value).toBe('expired-before-start');
- });
-
- it('keeps a settled outcome claimable by a late entrance event past the dedupe window', async () => {
- const startedIdentity = {userId: 'user-started', channelId: 'channel-1'};
- const unavailableIdentity = {userId: 'user-unavailable', channelId: 'channel-1'};
- const started = startVoiceJoinChimeSequence(startedIdentity, 'connection-started', () => Promise.resolve(true));
- const unavailable = startVoiceJoinChimeSequence(unavailableIdentity, 'connection-unavailable', () =>
- Promise.resolve(false),
- );
- await vi.advanceTimersByTimeAsync(0);
- await expect(started).resolves.toBe('started');
- await expect(unavailable).resolves.toBe('unavailable');
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_DEDUPE_WINDOW_MS + 1);
- const lateStarted = track(waitForVoiceJoinChimeSequence(startedIdentity));
- const lateUnavailable = track(waitForVoiceJoinChimeSequence(unavailableIdentity));
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_START_DEADLINE_MS);
- expect(lateStarted.value).toBe('started');
- expect(lateUnavailable.value).toBe('unavailable');
- });
-
- it('removes a settled entry after the retention window and leaves no timers behind', async () => {
- const started = startVoiceJoinChimeSequence(identity, 'connection-1', () => Promise.resolve(true));
- await vi.advanceTimersByTimeAsync(0);
- await expect(started).resolves.toBe('started');
- expect(vi.getTimerCount()).toBe(1);
- await vi.advanceTimersByTimeAsync(VOICE_JOIN_CHIME_SEQUENCE_RETENTION_MS);
- expect(vi.getTimerCount()).toBe(0);
- const late = track(waitForVoiceJoinChimeSequence(identity));
- await vi.advanceTimersByTimeAsync(SELF_JOIN_CHIME_START_DEADLINE_MS);
- expect(late.value).toBe('expired-before-start');
- });
-
- it('plays the chime once across the gateway and livekit-room sources for the same join', async () => {
- const gatewayStart = vi.fn(() => Promise.resolve(true));
- const livekitRoomStart = vi.fn(() => Promise.resolve(true));
- const fromGateway = startVoiceJoinChimeSequence(identity, 'connection-1', gatewayStart);
- const fromLivekitRoom = startVoiceJoinChimeSequence(identity, 'connection-1', livekitRoomStart);
- expect(fromLivekitRoom).toBe(fromGateway);
- await vi.advanceTimersByTimeAsync(0);
- expect(gatewayStart).toHaveBeenCalledTimes(1);
- expect(livekitRoomStart).not.toHaveBeenCalled();
- await expect(fromGateway).resolves.toBe('started');
- await expect(fromLivekitRoom).resolves.toBe('started');
- });
-
- it('discards the previous channel sequence on a quick channel hop and starts a fresh one', async () => {
- const firstChannel = {userId: 'user-1', channelId: 'channel-1'};
- const secondChannel = {userId: 'user-1', channelId: 'channel-2'};
- let firstSignal: AbortSignal | null = null;
- const firstStart = vi.fn((signal: AbortSignal) => {
- firstSignal = signal;
- return neverSettles();
- });
- const first = startVoiceJoinChimeSequence(firstChannel, 'connection-1', firstStart);
- const firstEntrance = track(waitForVoiceJoinChimeSequence(firstChannel));
- await vi.advanceTimersByTimeAsync(0);
- discardVoiceJoinChimeSequence(firstChannel);
- await expect(first).resolves.toBe('expired-before-start');
- expect((firstSignal as unknown as AbortSignal).aborted).toBe(true);
- expect(firstEntrance.value).toBe('expired-before-start');
- const secondStart = vi.fn(() => Promise.resolve(true));
- const second = startVoiceJoinChimeSequence(secondChannel, 'connection-2', secondStart);
- await vi.advanceTimersByTimeAsync(0);
- expect(secondStart).toHaveBeenCalledTimes(1);
- await expect(second).resolves.toBe('started');
- await expect(waitForVoiceJoinChimeSequence(secondChannel)).resolves.toBe('started');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceSharedAudioContext.test.ts b/fluxer_app/src/features/voice/engine/VoiceSharedAudioContext.test.ts
deleted file mode 100644
index f631d695d..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceSharedAudioContext.test.ts
+++ /dev/null
@@ -1,450 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {VOICE_TRACK_MAX_TOTAL_GAIN} from '@app/features/voice/utils/VoiceVolumeUtils';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-interface FakeAudioContext {
- state: AudioContextState;
- sampleRate: number;
- resumeCount: number;
-}
-
-interface FakeAudioNode {
- kind: string;
- connections: Array<FakeAudioNode>;
- connect: (target: FakeAudioNode) => FakeAudioNode;
-}
-
-interface FakeGainNode extends FakeAudioNode {
- gain: {value: number};
-}
-
-interface FakeWaveShaperNode extends FakeAudioNode {
- curve: Float32Array | null;
- oversample: OverSampleType;
-}
-
-interface FakeGraphContext {
- state: AudioContextState;
- sampleRate: number;
- hardwareDestination: FakeAudioNode;
- readonly destination: FakeAudioNode;
-}
-
-interface FakeGraphHarness {
- contexts: Array<FakeGraphContext>;
- gains: Array<FakeGainNode>;
- waveShapers: Array<FakeWaveShaperNode>;
-}
-
-interface FakeWindowHarness {
- requestedOptions: Array<AudioContextOptions | undefined>;
- contexts: Array<FakeAudioContext>;
- constructionErrors: Array<DOMException>;
- bodyListeners: Array<string>;
-}
-
-const HARDWARE_SAMPLE_RATE = 44100;
-
-function installFakeWindow(
- config: {
- throwOn?: (options: AudioContextOptions | undefined) => boolean;
- initialState?: AudioContextState;
- honourSampleRate?: boolean;
- } = {},
-): FakeWindowHarness {
- const harness: FakeWindowHarness = {requestedOptions: [], contexts: [], constructionErrors: [], bodyListeners: []};
- const throwOn = config.throwOn ?? ((): boolean => false);
- const honourSampleRate = config.honourSampleRate ?? true;
-
- class FakeAudioContextImpl {
- state: AudioContextState = config.initialState ?? 'running';
- sampleRate: number;
- resumeCount = 0;
-
- constructor(options?: AudioContextOptions) {
- harness.requestedOptions.push(options);
- if (throwOn(options)) {
- const error = new DOMException('sample rate not supported', 'NotSupportedError');
- harness.constructionErrors.push(error);
- throw error;
- }
- this.sampleRate = (honourSampleRate ? options?.sampleRate : undefined) ?? HARDWARE_SAMPLE_RATE;
- harness.contexts.push(this as unknown as FakeAudioContext);
- }
-
- async resume(): Promise<void> {
- this.resumeCount += 1;
- this.state = 'running';
- }
-
- addEventListener(): void {}
- removeEventListener(): void {}
- }
-
- vi.stubGlobal('window', {
- AudioContext: FakeAudioContextImpl,
- document: {
- body: {
- addEventListener: (type: string): void => {
- harness.bodyListeners.push(type);
- },
- removeEventListener: (): void => {},
- },
- },
- });
- return harness;
-}
-
-function createFakeAudioNode(kind: string): FakeAudioNode {
- const node: FakeAudioNode = {
- kind,
- connections: [],
- connect: (target: FakeAudioNode): FakeAudioNode => {
- node.connections.push(target);
- return target;
- },
- };
- return node;
-}
-
-function installFakeGraphWindow(config: {withWaveShaper?: boolean} = {}): FakeGraphHarness {
- const harness: FakeGraphHarness = {contexts: [], gains: [], waveShapers: []};
- const withWaveShaper = config.withWaveShaper ?? true;
-
- class FakeGraphAudioContextImpl {
- state: AudioContextState = 'running';
- sampleRate = HARDWARE_SAMPLE_RATE;
- hardwareDestination: FakeAudioNode;
-
- constructor() {
- this.hardwareDestination = createFakeAudioNode('destination');
- harness.contexts.push(this as unknown as FakeGraphContext);
- }
-
- get destination(): FakeAudioNode {
- return this.hardwareDestination;
- }
-
- createGain(): FakeGainNode {
- const node = createFakeAudioNode('gain') as FakeGainNode;
- node.gain = {value: 1};
- harness.gains.push(node);
- return node;
- }
-
- async resume(): Promise<void> {
- this.state = 'running';
- }
-
- addEventListener(): void {}
- removeEventListener(): void {}
- }
-
- class FakeGraphAudioContextWithWaveShaperImpl extends FakeGraphAudioContextImpl {
- createWaveShaper(): FakeWaveShaperNode {
- const node = createFakeAudioNode('waveShaper') as FakeWaveShaperNode;
- node.curve = null;
- node.oversample = '4x';
- harness.waveShapers.push(node);
- return node;
- }
- }
-
- vi.stubGlobal('window', {
- AudioContext: withWaveShaper ? FakeGraphAudioContextWithWaveShaperImpl : FakeGraphAudioContextImpl,
- document: {
- body: {
- addEventListener: (): void => {},
- removeEventListener: (): void => {},
- },
- },
- });
- return harness;
-}
-
-function evaluateSoftClipCurve(curve: Float32Array, input: number): number {
- const scaled = ((curve.length - 1) / 2) * (input + 1);
- if (scaled <= 0) return curve[0]!;
- if (scaled >= curve.length - 1) return curve[curve.length - 1]!;
- const index = Math.floor(scaled);
- const fraction = scaled - index;
- return (1 - fraction) * curve[index]! + fraction * curve[index + 1]!;
-}
-
-function expectCurveIsMonotoneOddAndBounded(curve: Float32Array): void {
- let maxAbsolute = 0;
- let maxOddError = 0;
- let maxBackwardsStep = 0;
- for (let i = 0; i < curve.length; i++) {
- maxAbsolute = Math.max(maxAbsolute, Math.abs(curve[i]!));
- maxOddError = Math.max(maxOddError, Math.abs(curve[i]! + curve[curve.length - 1 - i]!));
- if (i < curve.length - 1) {
- maxBackwardsStep = Math.max(maxBackwardsStep, curve[i]! - curve[i + 1]!);
- }
- }
- expect(maxBackwardsStep).toBe(0);
- expect(maxOddError).toBeLessThanOrEqual(1e-6);
- expect(maxAbsolute).toBeLessThanOrEqual(1);
-}
-
-function measureWorstTransparencyError(curve: Float32Array, maxAmplitude: number): number {
- let worst = 0;
- for (let step = -2000; step <= 2000; step++) {
- const amplitude = (step / 2000) * maxAmplitude;
- const shaped = evaluateSoftClipCurve(curve, amplitude / VOICE_TRACK_MAX_TOTAL_GAIN);
- worst = Math.max(worst, Math.abs(shaped - amplitude));
- }
- return worst;
-}
-
-async function loadModule() {
- vi.resetModules();
- return await import('@app/features/voice/engine/VoiceSharedAudioContext');
-}
-
-describe('VoiceSharedAudioContext', () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it('leaves the shared context on the hardware rate so it shares a graph with capture and playback', async () => {
- const harness = installFakeWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const context = getSharedVoiceAudioContext();
-
- expect(harness.requestedOptions).toEqual([{latencyHint: 'interactive'}]);
- expect(context).toBe(harness.contexts[0] as unknown as AudioContext);
- expect(context?.sampleRate).toBe(HARDWARE_SAMPLE_RATE);
- });
-
- it('returns null without throwing when the construction fails', async () => {
- const harness = installFakeWindow({throwOn: () => true});
- const {getSharedVoiceAudioContext} = await loadModule();
- const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
- try {
- let context: AudioContext | null | undefined;
- expect(() => {
- context = getSharedVoiceAudioContext();
- }).not.toThrow();
-
- expect(context).toBeNull();
- expect(harness.contexts).toHaveLength(0);
- expect(harness.requestedOptions).toEqual([{latencyHint: 'interactive'}]);
- expect(harness.constructionErrors).toHaveLength(1);
- expect(warning).toHaveBeenCalledTimes(1);
- expect(warning).toHaveBeenCalledWith(
- expect.stringMatching(/^%c\[\d{2}:\d{2}:\d{2}\] \[VoiceSharedAudioContext\] \[Warn\]$/),
- 'color:#ffc107;font-weight:normal',
- 'Failed to construct voice AudioContext',
- {
- options: {latencyHint: 'interactive'},
- error: harness.constructionErrors[0],
- },
- );
- } finally {
- warning.mockRestore();
- }
- });
-
- it('caches the context across calls and rebuilds it once it has closed', async () => {
- const harness = installFakeWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const first = getSharedVoiceAudioContext();
- expect(getSharedVoiceAudioContext()).toBe(first);
- expect(harness.requestedOptions).toHaveLength(1);
-
- harness.contexts[0].state = 'closed';
- const second = getSharedVoiceAudioContext();
-
- expect(second).not.toBe(first);
- expect(harness.contexts).toHaveLength(2);
- expect(harness.requestedOptions).toEqual([{latencyHint: 'interactive'}, {latencyHint: 'interactive'}]);
- });
-
- it('resumes a suspended context and arms the user-gesture resume listener', async () => {
- const harness = installFakeWindow({initialState: 'suspended'});
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const context = getSharedVoiceAudioContext();
-
- expect(context).not.toBeNull();
- expect(harness.contexts[0].resumeCount).toBe(1);
- expect(harness.bodyListeners).toEqual(['click']);
- });
-
- it('createVoiceAudioContext reports the rate the browser actually resolved, not the requested one', async () => {
- installFakeWindow({honourSampleRate: false});
- const {createVoiceAudioContext} = await loadModule();
-
- const context = createVoiceAudioContext({latencyHint: 'interactive', sampleRate: 48000});
-
- expect(context?.sampleRate).toBe(HARDWARE_SAMPLE_RATE);
- });
-
- it('createVoiceAudioContext returns null instead of throwing when the rate is rejected', async () => {
- const harness = installFakeWindow({throwOn: (options) => options?.sampleRate !== undefined});
- const {createVoiceAudioContext} = await loadModule();
- const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
- try {
- expect(createVoiceAudioContext({latencyHint: 'interactive', sampleRate: 48000})).toBeNull();
- expect(harness.constructionErrors).toHaveLength(1);
- expect(warning).toHaveBeenCalledTimes(1);
- expect(warning).toHaveBeenCalledWith(
- expect.stringMatching(/^%c\[\d{2}:\d{2}:\d{2}\] \[VoiceSharedAudioContext\] \[Warn\]$/),
- 'color:#ffc107;font-weight:normal',
- 'Failed to construct voice AudioContext',
- {
- options: {latencyHint: 'interactive', sampleRate: 48000},
- error: harness.constructionErrors[0],
- },
- );
- } finally {
- warning.mockRestore();
- }
- });
-
- it('leaves the context untouched when the browser has no WaveShaper', async () => {
- installFakeWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const context = getSharedVoiceAudioContext();
-
- expect(context).not.toBeNull();
- expect(Object.getOwnPropertyDescriptor(context as object, 'destination')).toBeUndefined();
- });
-
- it('leaves the hardware destination in place when the context cannot build a WaveShaper', async () => {
- const harness = installFakeGraphWindow({withWaveShaper: false});
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const context = getSharedVoiceAudioContext() as unknown as FakeGraphContext;
-
- expect(Object.getOwnPropertyDescriptor(context as object, 'destination')).toBeUndefined();
- expect(context.destination).toBe(harness.contexts[0]!.hardwareDestination);
- expect(harness.gains).toHaveLength(0);
- });
-});
-
-describe('VoiceSharedAudioContext master soft clip', () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it('routes LiveKit track gain through the master soft clipper', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const context = getSharedVoiceAudioContext() as unknown as FakeGraphContext;
- const masterInput = harness.gains[0]!;
- const waveShaper = harness.waveShapers[0]!;
-
- expect(context.destination).toBe(masterInput);
- expect(context.destination).not.toBe(context.hardwareDestination);
- expect(masterInput.connections).toEqual([waveShaper]);
- expect(waveShaper.connections).toEqual([context.hardwareDestination]);
- });
-
- it('pre-gain opens a 12x window', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- getSharedVoiceAudioContext();
-
- expect(harness.gains).toHaveLength(1);
- expect(harness.gains[0]!.gain.value).toBe(1 / VOICE_TRACK_MAX_TOTAL_GAIN);
- });
-
- it('oversample stays none so the limiter adds zero latency', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- getSharedVoiceAudioContext();
-
- expect(harness.waveShapers[0]!.oversample).toBe('none');
- });
-
- it('installs the shared curve, which is monotone, odd and never exceeds full scale', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext, createVoiceSoftClipCurve} = await loadModule();
-
- getSharedVoiceAudioContext();
- const curve = harness.waveShapers[0]!.curve;
-
- expect(curve).toEqual(createVoiceSoftClipCurve());
- expectCurveIsMonotoneOddAndBounded(curve as Float32Array);
- });
-
- it('is transparent below the knee so normal playback is unchanged', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- getSharedVoiceAudioContext();
- const curve = harness.waveShapers[0]!.curve as Float32Array;
-
- for (const amplitude of [0, 0.4, 0.79]) {
- expect(evaluateSoftClipCurve(curve, amplitude / VOICE_TRACK_MAX_TOTAL_GAIN)).toBeCloseTo(amplitude, 6);
- }
- expect(measureWorstTransparencyError(curve, 0.8)).toBeLessThan(1e-6);
- });
-
- it('reuses the shared context without stacking a second limiter', async () => {
- const harness = installFakeGraphWindow();
- const {getSharedVoiceAudioContext} = await loadModule();
-
- const first = getSharedVoiceAudioContext();
-
- expect(getSharedVoiceAudioContext()).toBe(first);
- expect(harness.gains).toHaveLength(1);
- expect(harness.waveShapers).toHaveLength(1);
- });
-});
-
-describe('createVoiceSoftClipCurve', () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it('spans the full 12x window and lands exactly on full scale at the edges', async () => {
- installFakeWindow();
- const {createVoiceSoftClipCurve} = await loadModule();
-
- const curve = createVoiceSoftClipCurve();
-
- expect(curve).toHaveLength(8192);
- expect(curve[0]).toBe(-1);
- expect(curve[curve.length - 1]).toBe(1);
- });
-
- it('is monotone, odd-symmetric and bounded by full scale', async () => {
- installFakeWindow();
- const {createVoiceSoftClipCurve} = await loadModule();
-
- expectCurveIsMonotoneOddAndBounded(createVoiceSoftClipCurve());
- });
-
- it('passes everything below the knee through untouched', async () => {
- installFakeWindow();
- const {createVoiceSoftClipCurve} = await loadModule();
-
- const curve = createVoiceSoftClipCurve();
-
- expect(measureWorstTransparencyError(curve, 0.8)).toBeLessThan(1e-6);
- });
-
- it('shaves full scale by 0.42 dB and hard limits far above it', async () => {
- installFakeWindow();
- const {createVoiceSoftClipCurve} = await loadModule();
-
- const curve = createVoiceSoftClipCurve();
- const atFullScale = evaluateSoftClipCurve(curve, 1 / VOICE_TRACK_MAX_TOTAL_GAIN);
-
- expect(atFullScale).toBeCloseTo(0.95232, 5);
- expect(20 * Math.log10(atFullScale)).toBeCloseTo(-0.42, 2);
- expect(evaluateSoftClipCurve(curve, 3 / VOICE_TRACK_MAX_TOTAL_GAIN)).toBeCloseTo(1, 6);
- expect(evaluateSoftClipCurve(curve, 5)).toBe(1);
- expect(evaluateSoftClipCurve(curve, -5)).toBe(-1);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.test.ts
deleted file mode 100644
index 2814e8d77..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceStatsStateMachine.test.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createInitialVoiceStats,
- createVoiceStatsSnapshot,
- getVoiceStatsStateValue,
- MAX_LATENCY_HISTORY,
- MAX_TIME_SERIES_SAMPLES,
- selectVoiceStatsCollectionDecision,
- transitionVoiceStatsSnapshot,
- type VoiceStatsSnapshot,
-} from '@app/features/voice/engine/VoiceStatsStateMachine';
-import type {VoiceEngineV2PerTrackStats, VoiceEngineV2TransportInfo} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-const roomA = {id: 'room-a'};
-const roomB = {id: 'room-b'};
-
-const publisherTransport: VoiceEngineV2TransportInfo = {
- candidatePairState: 'succeeded',
- currentRoundTripTimeMs: 42,
-};
-
-const sampleTracks: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'send', kind: 'audio', bitrateKbps: 16},
- {direction: 'recv', kind: 'audio', bitrateKbps: 32, packetsLossPercent: 1.2, jitterMs: 4.8},
- {direction: 'send', kind: 'video', bitrateKbps: 512},
- {direction: 'recv', kind: 'video', bitrateKbps: 256, packetsLossPercent: 2.4},
-];
-
-function startStats(snapshot: VoiceStatsSnapshot, roomIdentity: unknown = roomA): VoiceStatsSnapshot {
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'room.set', roomIdentity, now: 1000});
- return transitionVoiceStatsSnapshot(snapshot, {type: 'stats.start'});
-}
-
-function applyStatsCollection(
- snapshot: VoiceStatsSnapshot,
- options: {
- timestamp?: number;
- tracks?: Array<VoiceEngineV2PerTrackStats>;
- activeCounterIds?: Set<string>;
- rtpCounters?: Map<string, {timestamp: number; bytes?: number}>;
- } = {},
-): VoiceStatsSnapshot {
- const decision = selectVoiceStatsCollectionDecision(snapshot);
- if (decision.type !== 'collect') throw new Error(`expected collect decision, got ${decision.reason}`);
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionStarted',
- generation: decision.generation,
- roomIdentity: decision.roomIdentity,
- });
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionSucceeded',
- generation: decision.generation,
- roomIdentity: decision.roomIdentity,
- timestamp: options.timestamp ?? 3000,
- participantCount: 3,
- rtt: 37.6,
- tracks: options.tracks ?? sampleTracks,
- publisherTransport,
- subscriberTransport: null,
- rtpCounters: options.rtpCounters ?? new Map([['publisher:outbound-rtp:audio-a', {timestamp: 3000, bytes: 100}]]),
- activeCounterIds: options.activeCounterIds ?? new Set(['publisher:outbound-rtp:audio-a']),
- });
- return transitionVoiceStatsSnapshot(snapshot, {type: 'stats.collectionFinished', generation: decision.generation});
-}
-
-describe('VoiceStatsStateMachine', () => {
- it('keeps start and stop idempotent', () => {
- let snapshot = createVoiceStatsSnapshot();
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.start'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.start'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('trackingLatency');
- expect(snapshot.context.latencyIntervalActive).toBe(true);
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.start'});
- const generationAfterStart = snapshot.context.statsGeneration;
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.start'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('trackingBoth');
- expect(snapshot.context.statsGeneration).toBe(generationAfterStart);
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.stop'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.stop'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('trackingStats');
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.stop'});
- const generationAfterStop = snapshot.context.statsGeneration;
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.stop'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.statsGeneration).toBe(generationAfterStop);
- });
-
- it('clears RTP counters when the room identity changes', () => {
- let snapshot = startStats(createVoiceStatsSnapshot());
- snapshot = applyStatsCollection(snapshot, {
- rtpCounters: new Map([
- ['counter-a', {timestamp: 2000, bytes: 100}],
- ['counter-b', {timestamp: 2000, bytes: 200}],
- ]),
- activeCounterIds: new Set(['counter-a']),
- });
- expect([...snapshot.context.rtpCounters.keys()]).toEqual(['counter-a']);
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'room.set', roomIdentity: roomB, now: 4000});
- expect(snapshot.context.roomIdentity).toBe(roomB);
- expect(snapshot.context.rtpCounters.size).toBe(0);
- });
-
- it('discards stale async stats samples by generation', () => {
- let snapshot = startStats(createVoiceStatsSnapshot());
- const decision = selectVoiceStatsCollectionDecision(snapshot);
- if (decision.type !== 'collect') throw new Error('expected collect decision');
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionStarted',
- generation: decision.generation,
- roomIdentity: decision.roomIdentity,
- });
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.stop'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionSucceeded',
- generation: decision.generation,
- roomIdentity: decision.roomIdentity,
- timestamp: 3000,
- participantCount: 2,
- rtt: 99,
- tracks: sampleTracks,
- publisherTransport,
- subscriberTransport: null,
- rtpCounters: new Map([['stale-counter', {timestamp: 3000, bytes: 1}]]),
- activeCounterIds: new Set(['stale-counter']),
- });
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionFinished',
- generation: decision.generation,
- });
-
- expect(snapshot.context.voiceStats).toEqual(createInitialVoiceStats());
- expect(snapshot.context.statsTimeSeries).toEqual([]);
- expect(snapshot.context.rtpCounters.size).toBe(0);
- });
-
- it('guards collection while another stats collection is in flight', () => {
- let snapshot = startStats(createVoiceStatsSnapshot());
- const decision = selectVoiceStatsCollectionDecision(snapshot);
- if (decision.type !== 'collect') throw new Error('expected collect decision');
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionStarted',
- generation: decision.generation,
- roomIdentity: decision.roomIdentity,
- });
-
- expect(selectVoiceStatsCollectionDecision(snapshot)).toEqual({type: 'skip', reason: 'in-flight'});
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'stats.collectionFinished',
- generation: decision.generation,
- });
- expect(snapshot.context.statsCollectionInFlight).toBe(false);
- });
-
- it('caps latency history and recomputes current and average latency', () => {
- let snapshot = transitionVoiceStatsSnapshot(createVoiceStatsSnapshot(), {type: 'latency.start'});
- for (let i = 0; i < MAX_LATENCY_HISTORY + 5; i++) {
- snapshot = transitionVoiceStatsSnapshot(snapshot, {
- type: 'latency.sample',
- timestamp: i,
- latency: 10 + i,
- });
- }
-
- expect(snapshot.context.latencyHistory).toHaveLength(MAX_LATENCY_HISTORY);
- expect(snapshot.context.latencyHistory[0]).toEqual({timestamp: 5, latency: 15});
- expect(snapshot.context.currentLatency).toBe(74);
- expect(snapshot.context.averageLatency).toBe(45);
- });
-
- it('preserves the last measured latency across missing latency samples', () => {
- let snapshot = transitionVoiceStatsSnapshot(createVoiceStatsSnapshot(), {type: 'latency.start'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.sample', timestamp: 1000, latency: 42});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.gap', timestamp: 1500});
-
- expect(snapshot.context.currentLatency).toBe(42);
- expect(snapshot.context.averageLatency).toBe(42);
- expect(snapshot.context.latency.status).toBe('fresh');
- expect(snapshot.context.latencyHistory).toEqual([{timestamp: 1000, latency: 42}]);
- });
-
- it('marks old latency samples stale without clearing their displayed value', () => {
- let snapshot = transitionVoiceStatsSnapshot(createVoiceStatsSnapshot(), {type: 'latency.start'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.sample', timestamp: 1000, latency: 42});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.gap', timestamp: 12_001});
-
- expect(snapshot.context.currentLatency).toBe(42);
- expect(snapshot.context.latency.status).toBe('stale');
- });
-
- it('caps stats time-series samples', () => {
- let snapshot = startStats(createVoiceStatsSnapshot());
- for (let i = 0; i < MAX_TIME_SERIES_SAMPLES + 7; i++) {
- snapshot = applyStatsCollection(snapshot, {timestamp: 2000 + i});
- }
-
- expect(snapshot.context.statsTimeSeries).toHaveLength(MAX_TIME_SERIES_SAMPLES);
- expect(snapshot.context.statsTimeSeries[0]?.timestamp).toBe(2007);
- expect(snapshot.context.statsTimeSeries.at(-1)?.timestamp).toBe(2066);
- });
-
- it('ticks call duration without requiring a stats collection result', () => {
- let snapshot = startStats(createVoiceStatsSnapshot());
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.tick', timestamp: 3500});
-
- expect(snapshot.context.voiceStats.duration).toBe(2);
- expect(snapshot.context.statsTimeSeries).toEqual([]);
-
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.stop'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.tick', timestamp: 4500});
-
- expect(snapshot.context.voiceStats.duration).toBe(2);
- });
-
- it('cleanup and reset clear all derived state', () => {
- for (const eventType of ['stats.cleanup', 'stats.reset'] as const) {
- let snapshot = startStats(createVoiceStatsSnapshot());
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.start'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.sample', timestamp: 1200, latency: 42});
- snapshot = applyStatsCollection(snapshot);
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'reconnection.increment'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: eventType});
-
- expect(getVoiceStatsStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.currentLatency).toBeNull();
- expect(snapshot.context.averageLatency).toBeNull();
- expect(snapshot.context.latencyHistory).toEqual([]);
- expect(snapshot.context.voiceStats).toEqual(createInitialVoiceStats());
- expect(snapshot.context.perTrackStats).toEqual([]);
- expect(snapshot.context.statsTimeSeries).toEqual([]);
- expect(snapshot.context.publisherTransport).toBeNull();
- expect(snapshot.context.subscriberTransport).toBeNull();
- expect(snapshot.context.rtpCounters.size).toBe(0);
- expect(snapshot.context.connectionStartTime).toBeNull();
- expect(snapshot.context.reconnectionCount).toBe(0);
- expect(snapshot.context.statsCollectionInFlight).toBe(false);
- }
- });
-
- it('tracks reconnect count independently of stats samples', () => {
- let snapshot = createVoiceStatsSnapshot();
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'reconnection.increment'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'reconnection.increment'});
- expect(snapshot.context.reconnectionCount).toBe(2);
- });
-
- it('handles repeated start and stop cycles without leaking active state', () => {
- let snapshot = createVoiceStatsSnapshot();
- for (let i = 0; i < 50; i++) {
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.start'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.start'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('trackingBoth');
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'latency.stop'});
- snapshot = transitionVoiceStatsSnapshot(snapshot, {type: 'stats.stop'});
- expect(getVoiceStatsStateValue(snapshot)).toBe('idle');
- expect(snapshot.context.statsCollectionInFlight).toBe(false);
- }
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/VoiceTrackSource.test.ts b/fluxer_app/src/features/voice/engine/VoiceTrackSource.test.ts
deleted file mode 100644
index 8f1487088..000000000
--- a/fluxer_app/src/features/voice/engine/VoiceTrackSource.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- asVoiceTrackSource,
- isScreenShareAudioPublicationLike,
- VoiceTrackSource,
-} from '@app/features/voice/engine/VoiceTrackSource';
-import {describe, expect, it} from 'vitest';
-
-describe('VoiceTrackSource', () => {
- it('normalizes native screen-share audio source aliases', () => {
- expect(asVoiceTrackSource('screenshareAudio')).toBe(VoiceTrackSource.ScreenShareAudio);
- expect(asVoiceTrackSource('screenshare_audio')).toBe(VoiceTrackSource.ScreenShareAudio);
- expect(asVoiceTrackSource('screen_audio')).toBe(VoiceTrackSource.ScreenShareAudio);
- expect(asVoiceTrackSource('system_audio')).toBe(VoiceTrackSource.ScreenShareAudio);
- });
-
- it('recognizes native screen-share audio publications by track name', () => {
- expect(isScreenShareAudioPublicationLike({source: VoiceTrackSource.Microphone, trackName: 'screen-audio'})).toBe(
- true,
- );
- expect(
- isScreenShareAudioPublicationLike({
- source: VoiceTrackSource.Microphone,
- audioTrack: {mediaStreamTrack: {label: 'screenshareAudio'}},
- }),
- ).toBe(true);
- expect(isScreenShareAudioPublicationLike({source: VoiceTrackSource.Microphone, trackName: 'regular-mic'})).toBe(
- false,
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAdapterAssertions.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAdapterAssertions.test.ts
deleted file mode 100644
index 2bb1afe98..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAdapterAssertions.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- assertBoolean,
- assertDisconnectReason,
- assertNonEmptyString,
- assertNonNegativeFinite,
- assertNullableObjectLike,
- assertObjectLike,
- assertOptionalNonEmptyString,
- assertPositiveFinite,
- assertVoiceServerUpdateShape,
- hasAnyTerminalTransport,
- isMutedOrDeafened,
- isPermissionDeniedError,
- isReadyToRepublishTrack,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppAdapterAssertions';
-import {describe, expect, it} from 'vitest';
-
-describe('VoiceEngineV2AppAdapterAssertions', () => {
- describe('assertNonEmptyString', () => {
- it('accepts a non-empty string', () => {
- expect(() => assertNonEmptyString('hello', 'field')).not.toThrow();
- });
-
- it('rejects empty strings', () => {
- expect(() => assertNonEmptyString('', 'field')).toThrow();
- });
-
- it('rejects non-string values', () => {
- expect(() => assertNonEmptyString(null, 'field')).toThrow();
- expect(() => assertNonEmptyString(undefined, 'field')).toThrow();
- expect(() => assertNonEmptyString(42, 'field')).toThrow();
- });
- });
-
- describe('assertOptionalNonEmptyString', () => {
- it('accepts null and undefined', () => {
- expect(() => assertOptionalNonEmptyString(null, 'field')).not.toThrow();
- expect(() => assertOptionalNonEmptyString(undefined, 'field')).not.toThrow();
- });
-
- it('accepts non-empty strings', () => {
- expect(() => assertOptionalNonEmptyString('hello', 'field')).not.toThrow();
- });
-
- it('rejects empty strings', () => {
- expect(() => assertOptionalNonEmptyString('', 'field')).toThrow();
- });
-
- it('rejects non-string values', () => {
- expect(() => assertOptionalNonEmptyString(42, 'field')).toThrow();
- });
- });
-
- describe('assertPositiveFinite', () => {
- it('accepts positive finite numbers', () => {
- expect(() => assertPositiveFinite(1, 'field')).not.toThrow();
- expect(() => assertPositiveFinite(0.1, 'field')).not.toThrow();
- });
-
- it('rejects zero, negatives, and non-finite values', () => {
- expect(() => assertPositiveFinite(0, 'field')).toThrow();
- expect(() => assertPositiveFinite(-1, 'field')).toThrow();
- expect(() => assertPositiveFinite(Number.POSITIVE_INFINITY, 'field')).toThrow();
- expect(() => assertPositiveFinite(Number.NaN, 'field')).toThrow();
- expect(() => assertPositiveFinite('1', 'field')).toThrow();
- });
- });
-
- describe('assertNonNegativeFinite', () => {
- it('accepts zero and positives', () => {
- expect(() => assertNonNegativeFinite(0, 'field')).not.toThrow();
- expect(() => assertNonNegativeFinite(1, 'field')).not.toThrow();
- });
-
- it('rejects negatives and non-finite', () => {
- expect(() => assertNonNegativeFinite(-1, 'field')).toThrow();
- expect(() => assertNonNegativeFinite(Number.NaN, 'field')).toThrow();
- });
- });
-
- describe('assertBoolean', () => {
- it('accepts true and false', () => {
- expect(() => assertBoolean(true, 'field')).not.toThrow();
- expect(() => assertBoolean(false, 'field')).not.toThrow();
- });
-
- it('rejects truthy/falsy non-booleans', () => {
- expect(() => assertBoolean(1, 'field')).toThrow();
- expect(() => assertBoolean(0, 'field')).toThrow();
- expect(() => assertBoolean(null, 'field')).toThrow();
- });
- });
-
- describe('assertObjectLike', () => {
- it('accepts non-null objects', () => {
- expect(() => assertObjectLike({}, 'field')).not.toThrow();
- expect(() => assertObjectLike({a: 1}, 'field')).not.toThrow();
- });
-
- it('rejects null and non-objects', () => {
- expect(() => assertObjectLike(null, 'field')).toThrow();
- expect(() => assertObjectLike(undefined, 'field')).toThrow();
- expect(() => assertObjectLike(42, 'field')).toThrow();
- });
- });
-
- describe('assertNullableObjectLike', () => {
- it('accepts null and objects', () => {
- expect(() => assertNullableObjectLike(null, 'field')).not.toThrow();
- expect(() => assertNullableObjectLike({}, 'field')).not.toThrow();
- });
-
- it('rejects non-object non-null values', () => {
- expect(() => assertNullableObjectLike(42, 'field')).toThrow();
- expect(() => assertNullableObjectLike('str', 'field')).toThrow();
- });
- });
-
- describe('isMutedOrDeafened', () => {
- it('returns true if any flag set', () => {
- expect(isMutedOrDeafened({serverMute: true, serverDeaf: false, selfDeaf: false})).toBe(true);
- expect(isMutedOrDeafened({serverMute: false, serverDeaf: true, selfDeaf: false})).toBe(true);
- expect(isMutedOrDeafened({serverMute: false, serverDeaf: false, selfDeaf: true})).toBe(true);
- });
-
- it('returns false when all flags are false', () => {
- expect(isMutedOrDeafened({serverMute: false, serverDeaf: false, selfDeaf: false})).toBe(false);
- });
- });
-
- describe('isPermissionDeniedError', () => {
- it('matches NotAllowedError and PermissionDeniedError', () => {
- const a = new Error('x');
- a.name = 'NotAllowedError';
- expect(isPermissionDeniedError(a)).toBe(true);
- const b = new Error('x');
- b.name = 'PermissionDeniedError';
- expect(isPermissionDeniedError(b)).toBe(true);
- });
-
- it('returns false for non-Error and other names', () => {
- expect(isPermissionDeniedError(null)).toBe(false);
- expect(isPermissionDeniedError('NotAllowedError')).toBe(false);
- const c = new Error('x');
- c.name = 'TypeError';
- expect(isPermissionDeniedError(c)).toBe(false);
- });
- });
-
- describe('assertVoiceServerUpdateShape', () => {
- it('accepts well-shaped voice server update', () => {
- expect(() =>
- assertVoiceServerUpdateShape(
- {
- token: 'tok',
- endpoint: 'endpoint',
- connection_id: 'cid',
- guild_id: 'gid',
- channel_id: 'chid',
- },
- 'raw',
- ),
- ).not.toThrow();
- });
-
- it('rejects missing required fields', () => {
- expect(() => assertVoiceServerUpdateShape({token: 'tok', endpoint: 'ep'}, 'raw')).toThrow();
- });
-
- it('rejects wrong types', () => {
- expect(() => assertVoiceServerUpdateShape({token: 5, endpoint: 'ep', connection_id: 'cid'}, 'raw')).toThrow();
- });
- });
-
- describe('assertDisconnectReason', () => {
- it('accepts known reasons', () => {
- expect(() => assertDisconnectReason('user', 'r')).not.toThrow();
- expect(() => assertDisconnectReason('error', 'r')).not.toThrow();
- expect(() => assertDisconnectReason('server', 'r')).not.toThrow();
- });
-
- it('rejects unknown reasons', () => {
- expect(() => assertDisconnectReason('unknown', 'r')).toThrow();
- expect(() => assertDisconnectReason(null, 'r')).toThrow();
- });
- });
-
- describe('hasAnyTerminalTransport', () => {
- it('returns true when any slot is set', () => {
- const sentinel = {};
- expect(hasAnyTerminalTransport({current: {room: sentinel}, hotSwap: {}})).toBe(true);
- expect(hasAnyTerminalTransport({current: {}, hotSwap: {pendingRoom: sentinel}})).toBe(true);
- expect(hasAnyTerminalTransport({current: {}, hotSwap: {previousRoom: sentinel}})).toBe(true);
- });
-
- it('returns false when no transports are present', () => {
- expect(hasAnyTerminalTransport({current: {}, hotSwap: {}})).toBe(false);
- });
- });
-
- describe('isReadyToRepublishTrack', () => {
- it('returns true when track has a live media stream', () => {
- expect(isReadyToRepublishTrack({mediaStreamTrack: {readyState: 'live'}})).toBe(true);
- });
-
- it('returns false when track is null or undefined', () => {
- expect(isReadyToRepublishTrack(null)).toBe(false);
- expect(isReadyToRepublishTrack(undefined)).toBe(false);
- });
-
- it('returns false when media stream is missing or ended', () => {
- expect(isReadyToRepublishTrack({mediaStreamTrack: null})).toBe(false);
- expect(isReadyToRepublishTrack({mediaStreamTrack: {readyState: 'ended'}})).toBe(false);
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppCameraResolutionPresets.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppCameraResolutionPresets.test.ts
deleted file mode 100644
index 777bcfd42..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppCameraResolutionPresets.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getCameraCaptureDimensions,
- pickCameraSubscriptionQuality,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppCameraResolutionPresets';
-import type {CameraResolution} from '@app/features/voice/state/VoiceSettings';
-import {VideoPresets} from 'livekit-client';
-import {describe, expect, it} from 'vitest';
-
-const EXPECTED_PRESET_TABLE = [
- {resolution: 'high', width: 1920, height: 1080, frameRate: 30, videoPreset: VideoPresets.h1080},
- {resolution: 'medium', width: 1280, height: 720, frameRate: 30, videoPreset: VideoPresets.h720},
- {resolution: 'low', width: 640, height: 360, frameRate: 20, videoPreset: VideoPresets.h360},
-] as const;
-
-describe('getCameraCaptureDimensions', () => {
- for (const row of EXPECTED_PRESET_TABLE) {
- it(`maps ${row.resolution} to ${row.width}x${row.height}@${row.frameRate}`, () => {
- expect(getCameraCaptureDimensions(row.resolution)).toEqual({
- width: row.width,
- height: row.height,
- frameRate: row.frameRate,
- });
- });
- }
-
- it('falls back to the low entry for an unknown resolution key', () => {
- const dimensions = getCameraCaptureDimensions('ultra' as CameraResolution);
- expect(dimensions).toEqual({width: 640, height: 360, frameRate: 20});
- });
-});
-
-describe('camera preset table consistency', () => {
- for (const row of EXPECTED_PRESET_TABLE) {
- it(`keeps capture dimensions and the LiveKit encode preset in agreement for ${row.resolution}`, () => {
- const capture = getCameraCaptureDimensions(row.resolution);
- expect(row.videoPreset.width).toBe(capture.width);
- expect(row.videoPreset.height).toBe(capture.height);
- expect(row.videoPreset.encoding.maxFramerate).toBe(capture.frameRate);
- });
- }
-
- it('orders the table strictly by descending pixel area', () => {
- const areas = EXPECTED_PRESET_TABLE.map((row) => row.width * row.height);
- const sorted = [...areas].sort((first, second) => second - first);
- expect(areas).toEqual(sorted);
- expect(new Set(areas).size).toBe(areas.length);
- });
-});
-
-describe('camera capture constraint shape', () => {
- for (const row of EXPECTED_PRESET_TABLE) {
- it(`hands getUserMedia a plain video resolution for ${row.resolution}`, () => {
- const capture = getCameraCaptureDimensions(row.resolution);
- expect(Object.keys(capture).sort()).toEqual(['frameRate', 'height', 'width']);
- expect(capture.frameRate).toBeGreaterThan(0);
- });
- }
-});
-
-describe('pickCameraSubscriptionQuality', () => {
- it('requests the lowest layer for a hidden or zero-sized tile', () => {
- expect(pickCameraSubscriptionQuality(0, 0)).toBe('low');
- });
-
- it('requests the lowest layer when the display fits within the base layer', () => {
- expect(pickCameraSubscriptionQuality(VideoPresets.h180.width, VideoPresets.h180.height)).toBe('low');
- expect(pickCameraSubscriptionQuality(300, 160)).toBe('low');
- });
-
- it('requests the middle layer when the display exceeds the base layer', () => {
- expect(pickCameraSubscriptionQuality(VideoPresets.h180.width + 1, VideoPresets.h180.height + 1)).toBe('medium');
- expect(pickCameraSubscriptionQuality(VideoPresets.h360.width, VideoPresets.h360.height)).toBe('medium');
- });
-
- it('requests the top layer when the display exceeds the middle layer', () => {
- expect(pickCameraSubscriptionQuality(VideoPresets.h360.width + 1, VideoPresets.h360.height + 1)).toBe('high');
- expect(pickCameraSubscriptionQuality(VideoPresets.h720.width, VideoPresets.h720.height)).toBe('high');
- });
-
- it('caps at the top layer for displays larger than the top reference layer', () => {
- expect(pickCameraSubscriptionQuality(3840, 2160)).toBe('high');
- });
-
- it('escalates quality as either dimension grows', () => {
- const widthEscalation = [
- pickCameraSubscriptionQuality(200, 120),
- pickCameraSubscriptionQuality(500, 280),
- pickCameraSubscriptionQuality(1000, 560),
- ];
- expect(widthEscalation).toEqual(['low', 'medium', 'high']);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppConnectionHostAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppConnectionHostAdapter.test.ts
deleted file mode 100644
index f9166d3d9..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppConnectionHostAdapter.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceConnectionSnapshot,
- transitionVoiceConnectionSnapshot,
- type VoiceConnectionSnapshot,
-} from '@app/features/voice/engine/VoiceConnectionStateMachine';
-import {
- getRoomFromMediaEngine,
- getVoiceConnectionContextFromMediaEngine,
-} from '@app/features/voice/engine/VoiceMediaEngineBridge';
-import {afterEach, describe, expect, it} from 'vitest';
-
-type MediaEngineWindow = typeof globalThis & {_mediaEngine?: unknown};
-
-function connectedWithoutRoomSnapshot(): VoiceConnectionSnapshot {
- const started = transitionVoiceConnectionSnapshot(createVoiceConnectionSnapshot(), {
- type: 'connection.start',
- guildId: 'guild-1',
- channelId: 'channel-1',
- });
- return transitionVoiceConnectionSnapshot(started, {type: 'connection.connected'});
-}
-
-function seedMediaEngineFromSnapshot(snapshot: VoiceConnectionSnapshot, overrides: Record<string, unknown> = {}): void {
- const {context} = snapshot;
- (window as MediaEngineWindow)._mediaEngine = {
- guildId: context.guildId,
- channelId: context.channelId,
- connectionId: context.connectionId,
- connected: context.connected,
- connecting: context.connecting,
- reconnecting: context.reconnecting,
- room: context.room ?? undefined,
- ...overrides,
- };
-}
-
-describe('voice connection projection while connected without a room', () => {
- afterEach(() => {
- delete (window as MediaEngineWindow)._mediaEngine;
- });
-
- it('models a connected connection whose LiveKit room is still null', () => {
- const {context} = connectedWithoutRoomSnapshot();
-
- expect(context.connected).toBe(true);
- expect(context.room).toBeNull();
- });
-
- it('projects the LiveKit room when the store reports connected without a room', () => {
- seedMediaEngineFromSnapshot(connectedWithoutRoomSnapshot());
-
- expect(getVoiceConnectionContextFromMediaEngine()?.connected).toBe(true);
- expect(getRoomFromMediaEngine()).toBeNull();
- });
-
- it('projects the LiveKit room when only the v2 model reports connected without a room', () => {
- seedMediaEngineFromSnapshot(connectedWithoutRoomSnapshot(), {
- connected: undefined,
- connecting: undefined,
- reconnecting: undefined,
- room: undefined,
- voiceEngineV2Model: {
- connection: {
- connected: true,
- connecting: false,
- reconnecting: false,
- status: 'connected',
- gateway: {selfVoiceState: {guildId: 'guild-1', channelId: 'channel-1'}},
- },
- },
- });
-
- expect(getVoiceConnectionContextFromMediaEngine()?.connected).toBe(true);
- expect(getRoomFromMediaEngine()).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils.ts
deleted file mode 100644
index 0045b1735..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceEngineV2AppControllerHost,
- type VoiceEngineV2AppControllerHost,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHost';
-import {
- createVoiceEngineV2MemoryEventLogSpillSink,
- type VoiceEngineV2HostPorts,
- type VoiceEngineV2RuntimeClock,
-} from '@fluxer/voice_engine_v2';
-
-export interface VoiceEngineV2AppTestControllerHostOptions {
- ports: VoiceEngineV2HostPorts;
- clock?: VoiceEngineV2RuntimeClock;
-}
-
-export function createVoiceEngineV2AppTestControllerHost(
- options: VoiceEngineV2AppTestControllerHostOptions,
-): VoiceEngineV2AppControllerHost {
- return createVoiceEngineV2AppControllerHost({
- ...options,
- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),
- });
-}
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.test.ts
deleted file mode 100644
index fe30d388c..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceEngineV2AppDiagnosticsAdapter,
- VOICE_ENGINE_V2_DIAGNOSTICS_CODE_MAX_LENGTH,
- VOICE_ENGINE_V2_DIAGNOSTICS_MESSAGE_MAX_LENGTH,
- type VoiceEngineV2AppDiagnosticsLogger,
- type VoiceEngineV2DiagnosticsLevel,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter';
-import {describe, expect, it} from 'vitest';
-
-interface FakeLoggerCall {
- level: VoiceEngineV2DiagnosticsLevel;
- payload: Record<string, unknown>;
-}
-
-interface FakeLogger extends VoiceEngineV2AppDiagnosticsLogger {
- readonly calls: ReadonlyArray<FakeLoggerCall>;
-}
-
-function createFakeLogger(throwOn?: VoiceEngineV2DiagnosticsLevel, error?: unknown): FakeLogger {
- const calls: Array<FakeLoggerCall> = [];
- const make = (level: VoiceEngineV2DiagnosticsLevel) => (payload: Record<string, unknown>) => {
- calls.push({level, payload: {...payload}});
- if (throwOn === level) throw error ?? new Error('logger failure');
- };
- return {
- get calls() {
- return calls;
- },
- trace: make('trace'),
- debug: make('debug'),
- info: make('info'),
- warn: make('warn'),
- error: make('error'),
- };
-}
-
-describe('VoiceEngineV2AppDiagnosticsAdapter', () => {
- it('routes each known level to the matching logger method with code/message/detail payload', async () => {
- const logger = createFakeLogger();
- const adapter = createVoiceEngineV2AppDiagnosticsAdapter({logger});
-
- await adapter.log('trace', 'voice.trace', 'tick');
- await adapter.log('debug', 'voice.debug', 'detail', {a: 1});
- await adapter.log('info', 'voice.info', 'state changed');
- await adapter.log('warn', 'voice.warn', 'glitch');
- await adapter.log('error', 'voice.error', 'failure', {error: 'boom'});
-
- expect(logger.calls).toEqual([
- {level: 'trace', payload: {code: 'voice.trace', message: 'tick'}},
- {level: 'debug', payload: {code: 'voice.debug', message: 'detail', detail: {a: 1}}},
- {level: 'info', payload: {code: 'voice.info', message: 'state changed'}},
- {level: 'warn', payload: {code: 'voice.warn', message: 'glitch'}},
- {level: 'error', payload: {code: 'voice.error', message: 'failure', detail: {error: 'boom'}}},
- ]);
- });
-
- it('normalises mixed-case level strings and falls back to the configured fallbackLevel for unknown levels', async () => {
- const logger = createFakeLogger();
- const adapter = createVoiceEngineV2AppDiagnosticsAdapter({logger, fallbackLevel: 'warn'});
-
- await adapter.log('INFO', 'voice.upper', 'message');
- await adapter.log('Fatal', 'voice.unknown', 'fell through');
-
- expect(logger.calls).toEqual([
- {level: 'info', payload: {code: 'voice.upper', message: 'message'}},
- {level: 'warn', payload: {code: 'voice.unknown', message: 'fell through'}},
- ]);
- });
-
- it('rejects empty/oversized codes and oversized messages before the logger is touched', async () => {
- const logger = createFakeLogger();
- const adapter = createVoiceEngineV2AppDiagnosticsAdapter({logger});
- const oversizedCode = 'c'.repeat(VOICE_ENGINE_V2_DIAGNOSTICS_CODE_MAX_LENGTH + 1);
- const oversizedMessage = 'm'.repeat(VOICE_ENGINE_V2_DIAGNOSTICS_MESSAGE_MAX_LENGTH + 1);
-
- await expect(adapter.log('info', '', 'message')).rejects.toThrow(/must not be empty/);
- await expect(adapter.log('info', oversizedCode, 'message')).rejects.toThrow(/maximum length/);
- await expect(adapter.log('info', 'ok', oversizedMessage)).rejects.toThrow(/maximum length/);
- expect(logger.calls).toEqual([]);
- });
-
- it('swallows logger exceptions and reports them through onError without rejecting', async () => {
- const error = new Error('logger offline');
- const logger = createFakeLogger('warn', error);
- const errorEvents: Array<{code: string; error: unknown}> = [];
- const adapter = createVoiceEngineV2AppDiagnosticsAdapter({
- logger,
- onError: (code, e) => {
- errorEvents.push({code, error: e});
- },
- });
-
- await adapter.log('warn', 'voice.warn', 'glitch');
-
- expect(errorEvents).toEqual([{code: 'voice.warn', error}]);
- });
-
- it('emits the detail field only when the caller provides it (positive and negative space)', async () => {
- const logger = createFakeLogger();
- const adapter = createVoiceEngineV2AppDiagnosticsAdapter({logger});
-
- await adapter.log('info', 'voice.without_detail', 'no payload');
- await adapter.log('info', 'voice.with_detail', 'has payload', {ms: 12});
-
- expect(logger.calls[0]).toEqual({
- level: 'info',
- payload: {code: 'voice.without_detail', message: 'no payload'},
- });
- expect(logger.calls[1]).toEqual({
- level: 'info',
- payload: {code: 'voice.with_detail', message: 'has payload', detail: {ms: 12}},
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.test.ts
deleted file mode 100644
index d7d5f8f6c..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceEngineV2AppEventLogSpillLoggerSink,
- type VoiceEngineV2AppEventLogSpillLogger,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppEventLogSpillLoggerSink';
-import type {VoiceEngineV2EventLogEntry} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-function makeEntry(sequence: number, atMs: number = sequence * 10): VoiceEngineV2EventLogEntry {
- return {
- sequence,
- atMs,
- event: {
- type: 'inboundVideo.frameReceived',
- frame: {
- participantSid: 'p',
- trackSid: 't',
- width: 16,
- height: 16,
- timestampUs: sequence,
- },
- },
- commands: [],
- };
-}
-
-describe('VoiceEngineV2AppEventLogSpillLoggerSink', () => {
- it('logs the first evicted entry under the eventLogEvicted code', async () => {
- const warnings: Array<Record<string, unknown>> = [];
- const logger: VoiceEngineV2AppEventLogSpillLogger = {
- warn(payload) {
- warnings.push(payload);
- },
- };
- const sink = createVoiceEngineV2AppEventLogSpillLoggerSink({logger});
-
- const entry = makeEntry(7);
- await sink.write(entry);
-
- expect(warnings).toHaveLength(1);
- expect(warnings[0]).toEqual({
- code: 'eventLogEvicted',
- entry,
- evictedEntryCount: 1,
- suppressedEvictedEntryCount: 0,
- });
- expect(sink.swallowedErrorCount).toBe(0);
- });
-
- it('summarizes repeated evictions instead of warning for every frame', async () => {
- let nowMs = 1_000;
- const warnings: Array<Record<string, unknown>> = [];
- const logger: VoiceEngineV2AppEventLogSpillLogger = {
- warn(payload) {
- warnings.push(payload);
- },
- };
- const sink = createVoiceEngineV2AppEventLogSpillLoggerSink({
- logger,
- warnIntervalMs: 100,
- nowMs: () => nowMs,
- });
-
- const first = makeEntry(1);
- const second = makeEntry(2);
- const third = makeEntry(3);
- const fourth = makeEntry(4);
-
- await sink.write(first);
- nowMs = 1_050;
- await sink.write(second);
- nowMs = 1_099;
- await sink.write(third);
- nowMs = 1_100;
- await sink.write(fourth);
-
- expect(warnings).toHaveLength(2);
- expect(warnings[0]).toEqual({
- code: 'eventLogEvicted',
- entry: first,
- evictedEntryCount: 1,
- suppressedEvictedEntryCount: 0,
- });
- expect(warnings[1]).toEqual({
- code: 'eventLogEvicted',
- entry: fourth,
- evictedEntryCount: 4,
- suppressedEvictedEntryCount: 2,
- });
- expect(sink.swallowedErrorCount).toBe(0);
- });
-
- it('swallows logger errors and reports them through onLoggerError without rejecting the promise', async () => {
- const failures: Array<unknown> = [];
- const loggerError = new Error('logger offline');
- let nowMs = 1_000;
- const logger: VoiceEngineV2AppEventLogSpillLogger = {
- warn() {
- throw loggerError;
- },
- };
- const sink = createVoiceEngineV2AppEventLogSpillLoggerSink({
- logger,
- warnIntervalMs: 100,
- nowMs: () => nowMs,
- onLoggerError: (error) => failures.push(error),
- });
-
- await expect(sink.write(makeEntry(1))).resolves.toBeUndefined();
- nowMs = 1_100;
- await expect(sink.write(makeEntry(2))).resolves.toBeUndefined();
-
- expect(sink.swallowedErrorCount).toBe(2);
- expect(failures).toEqual([loggerError, loggerError]);
- });
-
- it('rejects malformed entries before reaching the logger', () => {
- const warnings: Array<Record<string, unknown>> = [];
- const logger: VoiceEngineV2AppEventLogSpillLogger = {
- warn(payload) {
- warnings.push(payload);
- },
- };
- const sink = createVoiceEngineV2AppEventLogSpillLoggerSink({logger});
-
- expect(() => sink.write({...makeEntry(0)})).toThrow(/sequence must be >= 1/);
- expect(warnings).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppHostPorts.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppHostPorts.test.ts
deleted file mode 100644
index d58a3b1cb..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppHostPorts.test.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createVoiceEngineV2AppTestControllerHost} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils';
-import {
- createVoiceEngineV2AppHostPorts,
- createVoiceEngineV2AppIngestionPort,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppHostPorts';
-import type {VoiceEngineV2Event, VoiceEngineV2Stats} from '@fluxer/voice_engine_v2';
-import {waitForRuntime} from '@fluxer/voice_engine_v2/testing';
-import {describe, expect, it} from 'vitest';
-
-type AppHostPortCall =
- | {type: 'gateway.writeVoiceState'}
- | {type: 'gateway.clearVoiceState'}
- | {type: 'media.prewarm'}
- | {type: 'media.connect'}
- | {type: 'media.publishMicrophone'}
- | {type: 'media.publishScreen'}
- | {type: 'subscription.setParticipantVolume'}
- | {type: 'subscription.setRemoteTrackSubscription'}
- | {type: 'stats.collect'};
-
-function createFakeStats(): VoiceEngineV2Stats {
- return {
- rttMs: 42,
- outbound: [],
- inbound: [],
- };
-}
-
-describe('VoiceEngineV2AppHostPorts', () => {
- it('executes v2 commands through named app ports without the legacy liveKit umbrella port', async () => {
- const calls: Array<AppHostPortCall> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppHostPorts({
- gateway: {
- async writeVoiceState(): Promise<void> {
- calls.push({type: 'gateway.writeVoiceState'});
- },
- async clearVoiceState(): Promise<void> {
- calls.push({type: 'gateway.clearVoiceState'});
- },
- },
- media: {
- async prewarm(): Promise<void> {
- calls.push({type: 'media.prewarm'});
- },
- async connect(): Promise<void> {
- calls.push({type: 'media.connect'});
- },
- async disconnect(): Promise<void> {},
- async publishMicrophone(): Promise<void> {
- calls.push({type: 'media.publishMicrophone'});
- },
- async unpublishMicrophone(): Promise<void> {},
- async setMicrophoneEnabled(): Promise<void> {},
- async publishCamera(): Promise<void> {},
- async updateCameraEncoding(): Promise<void> {},
- async unpublishCamera(): Promise<void> {},
- async publishScreen(): Promise<void> {
- calls.push({type: 'media.publishScreen'});
- },
- async updateScreenEncoding(): Promise<void> {},
- async unpublishScreen(): Promise<void> {},
- async publishScreenAudio(): Promise<void> {},
- async unpublishScreenAudio(): Promise<void> {},
- async setOutputDevice(): Promise<void> {},
- async publishData(): Promise<void> {},
- },
- subscriptions: {
- async setParticipantVolume(): Promise<void> {
- calls.push({type: 'subscription.setParticipantVolume'});
- },
- async setRemoteTrackSubscription(): Promise<void> {
- calls.push({type: 'subscription.setRemoteTrackSubscription'});
- },
- },
- stats: {
- async collectStats(): Promise<VoiceEngineV2Stats> {
- calls.push({type: 'stats.collect'});
- return createFakeStats();
- },
- },
- }),
- });
-
- host.controller.prewarm();
- await waitForRuntime();
- host.controller.writeGatewayVoiceState({
- guildId: 'guild-1',
- channelId: 'channel-1',
- selfMute: false,
- selfDeaf: false,
- });
- await waitForRuntime();
- host.controller.connect({url: 'wss://voice.example.test', token: 'token'});
- await waitForRuntime();
- host.controller.publishMicrophone({deviceId: 'mic-1'});
- await waitForRuntime();
- host.controller.publishScreen({
- captureId: 'screen:1',
- width: 1920,
- height: 1080,
- zeroCopyRequired: false,
- });
- await waitForRuntime();
- host.controller.setParticipantVolume({participantIdentity: 'user-2', volume: 0.5});
- await waitForRuntime();
- host.controller.setRemoteTrackSubscription({
- participantIdentity: 'user-2',
- source: 'camera',
- subscribed: true,
- quality: 'high',
- });
- await waitForRuntime();
- host.controller.collectStats();
- await waitForRuntime();
- host.controller.clearGatewayVoiceState('guild-1');
- await waitForRuntime();
-
- expect(calls).toEqual([
- {type: 'media.prewarm'},
- {type: 'gateway.writeVoiceState'},
- {type: 'media.connect'},
- {type: 'media.publishMicrophone'},
- {type: 'media.publishScreen'},
- {type: 'subscription.setParticipantVolume'},
- {type: 'subscription.setRemoteTrackSubscription'},
- {type: 'stats.collect'},
- {type: 'gateway.clearVoiceState'},
- ]);
- expect(host.model.stats).toEqual(createFakeStats());
-
- host.dispose();
- });
-
- it('ingests voice-state and participant projection events through app event-source ports', () => {
- const voiceState = createVoiceEngineV2AppIngestionPort();
- const participantProjection = createVoiceEngineV2AppIngestionPort();
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppHostPorts({
- voiceState,
- participantProjection,
- }),
- });
-
- voiceState.ingest({
- type: 'gateway.voiceStateUpdated',
- voiceState: {
- guildId: 'guild-1',
- channelId: 'channel-1',
- userId: 'user-1',
- sessionId: 'session-1',
- selfMute: false,
- selfDeaf: false,
- selfVideo: false,
- selfStream: false,
- suppress: false,
- requestToSpeakTimestamp: null,
- },
- });
- const participantEvent: VoiceEngineV2Event = {
- type: 'room.participantJoined',
- participant: {
- sid: 'participant-1',
- identity: 'user-1',
- name: 'Ada',
- },
- };
- participantProjection.ingest(participantEvent);
-
- expect(host.model.connection.gateway.selfVoiceState?.channelId).toBe('channel-1');
- expect(host.model.participants).toEqual([
- {
- sid: 'participant-1',
- identity: 'user-1',
- name: 'Ada',
- },
- ]);
-
- host.dispose();
- });
-
- it('detaches app ingestion event sources when the host is disposed', () => {
- const voiceState = createVoiceEngineV2AppIngestionPort();
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppHostPorts({voiceState}),
- });
-
- voiceState.ingest({
- type: 'gateway.voiceStateUpdated',
- voiceState: {
- guildId: 'guild-1',
- channelId: 'channel-1',
- userId: 'user-1',
- sessionId: 'session-1',
- selfMute: false,
- selfDeaf: false,
- selfVideo: false,
- selfStream: false,
- suppress: false,
- requestToSpeakTimestamp: null,
- },
- });
-
- expect(host.model.connection.gateway.selfVoiceState?.channelId).toBe('channel-1');
-
- host.dispose();
- voiceState.ingest({
- type: 'gateway.voiceStateUpdated',
- voiceState: {
- guildId: 'guild-1',
- channelId: 'channel-2',
- userId: 'user-1',
- sessionId: 'session-2',
- selfMute: true,
- selfDeaf: false,
- selfVideo: false,
- selfStream: false,
- suppress: false,
- requestToSpeakTimestamp: null,
- },
- });
-
- expect(host.model.connection.gateway.selfVoiceState?.channelId).toBe('channel-1');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.test.ts
deleted file mode 100644
index 953073335..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter.test.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceEngineV2AppDiagnosticsLogger} from '@app/features/voice/engine/v2/VoiceEngineV2AppDiagnosticsAdapter';
-import {
- createVoiceEngineV2AppLifecycleAdapter,
- LIFECYCLE_OPERATION_CAP,
- TEARDOWN_PER_DISPOSABLE_TIMEOUT_MS,
- type VoiceEngineV2AppLifecycleAdapter,
- type VoiceEngineV2AppLifecycleDisposable,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter';
-import {createVoiceEngineV2DeterministicClockPort} from '@fluxer/voice_engine_v2/runtime';
-import {describe, expect, it} from 'vitest';
-
-interface LoggerCall {
- readonly level: 'trace' | 'debug' | 'info' | 'warn' | 'error';
- readonly payload: Record<string, unknown>;
-}
-
-interface FakeLogger extends VoiceEngineV2AppDiagnosticsLogger {
- readonly calls: ReadonlyArray<LoggerCall>;
-}
-
-function createFakeLogger(): FakeLogger {
- const calls: Array<LoggerCall> = [];
- const make = (level: LoggerCall['level']) => (payload: Record<string, unknown>) => {
- calls.push({level, payload: {...payload}});
- };
- return {
- get calls() {
- return calls;
- },
- trace: make('trace'),
- debug: make('debug'),
- info: make('info'),
- warn: make('warn'),
- error: make('error'),
- };
-}
-
-interface CallTracker {
- readonly events: ReadonlyArray<string>;
- push(event: string): void;
-}
-
-function createCallTracker(): CallTracker {
- const events: Array<string> = [];
- return {
- get events() {
- return events;
- },
- push(event: string): void {
- events.push(event);
- },
- };
-}
-
-function disposable(name: string, tracker: CallTracker): VoiceEngineV2AppLifecycleDisposable {
- return {
- name,
- async dispose(): Promise<void> {
- tracker.push(`dispose:${name}`);
- },
- };
-}
-
-function hangingDisposable(name: string, tracker: CallTracker): VoiceEngineV2AppLifecycleDisposable {
- return {
- name,
- dispose(): Promise<void> {
- tracker.push(`enter:${name}`);
- return new Promise<void>(() => {});
- },
- };
-}
-
-function throwingDisposable(name: string, tracker: CallTracker, error: unknown): VoiceEngineV2AppLifecycleDisposable {
- return {
- name,
- async dispose(): Promise<void> {
- tracker.push(`throw:${name}`);
- throw error;
- },
- };
-}
-
-function buildAdapter(
- disposables: ReadonlyArray<VoiceEngineV2AppLifecycleDisposable>,
- logger: FakeLogger,
- teardownPerDisposableTimeoutMs?: number,
-): VoiceEngineV2AppLifecycleAdapter {
- return createVoiceEngineV2AppLifecycleAdapter({
- disposables,
- logger,
- clock: createVoiceEngineV2DeterministicClockPort(0, 1),
- ...(teardownPerDisposableTimeoutMs === undefined ? {} : {teardownPerDisposableTimeoutMs}),
- });
-}
-
-describe('VoiceEngineV2AppLifecycleAdapter', () => {
- it('cancelOperation aborts the registered controller and logs lifecycle.cancelled', async () => {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
- const controller = new AbortController();
- const seen: Array<string | null> = [];
- controller.signal.addEventListener('abort', () => {
- seen.push(typeof controller.signal.reason === 'string' ? controller.signal.reason : null);
- });
-
- adapter.register(7, controller, 'mediaAdapter');
- expect(adapter.registrySize).toBe(1);
-
- await adapter.cancelOperation(7, 'cancel-requested');
-
- expect(controller.signal.aborted).toBe(true);
- expect(seen).toEqual(['cancel-requested']);
- expect(adapter.registrySize).toBe(0);
- expect(logger.calls.some((entry) => entry.payload.code === 'lifecycle.cancelled')).toBe(true);
- });
-
- it('cancelOperation with an unknown id is a no-op and emits a debug log', async () => {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
-
- await adapter.cancelOperation(99, 'no-such-operation');
-
- expect(adapter.registrySize).toBe(0);
- const debug = logger.calls.find((entry) => entry.payload.code === 'lifecycle.cancel.unknown');
- expect(debug).toBeDefined();
- expect(debug?.level).toBe('debug');
- });
-
- it('register throws lifecycleRegistryFull when the cap is exhausted', () => {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
- for (let index = 1; index <= LIFECYCLE_OPERATION_CAP; index += 1) {
- adapter.register(index, new AbortController(), 'fillerAdapter');
- }
- expect(adapter.registrySize).toBe(LIFECYCLE_OPERATION_CAP);
- let captured: Error | undefined;
- try {
- adapter.register(LIFECYCLE_OPERATION_CAP + 1, new AbortController(), 'overflowAdapter');
- } catch (error) {
- captured = error as Error;
- }
- expect(captured).toBeDefined();
- expect((captured as Error & {code?: string}).code).toBe('lifecycleRegistryFull');
- expect(adapter.registrySize).toBe(LIFECYCLE_OPERATION_CAP);
- });
-
- it('teardown disposes in reverse creation order', async () => {
- const tracker = createCallTracker();
- const logger = createFakeLogger();
- const adapter = buildAdapter(
- [disposable('first', tracker), disposable('second', tracker), disposable('third', tracker)],
- logger,
- );
-
- await adapter.teardown();
-
- expect(tracker.events).toEqual(['dispose:third', 'dispose:second', 'dispose:first']);
- expect(adapter.isTornDown).toBe(true);
- });
-
- it('teardown is a no-op on subsequent calls', async () => {
- const tracker = createCallTracker();
- const logger = createFakeLogger();
- const adapter = buildAdapter([disposable('only', tracker)], logger);
-
- await adapter.teardown();
- await adapter.teardown();
- await adapter.teardown();
-
- expect(tracker.events).toEqual(['dispose:only']);
- const repeated = logger.calls.filter((entry) => entry.payload.code === 'lifecycle.teardown.repeated');
- expect(repeated.length).toBe(2);
- });
-
- it('teardown continues past a hanging disposable once the per-disposable timeout fires', async () => {
- const tracker = createCallTracker();
- const logger = createFakeLogger();
- const adapter = buildAdapter(
- [disposable('first', tracker), hangingDisposable('hang', tracker), disposable('last', tracker)],
- logger,
- 5,
- );
-
- await adapter.teardown();
-
- expect(tracker.events).toEqual(['dispose:last', 'enter:hang', 'dispose:first']);
- const timeout = logger.calls.find((entry) => entry.payload.code === 'lifecycle.teardown.timeout');
- expect(timeout).toBeDefined();
- expect(timeout?.level).toBe('error');
- expect((timeout?.payload.detail as {name?: string}).name).toBe('hang');
- });
-
- it('teardown continues past a throwing disposable and logs lifecycle.teardown.error', async () => {
- const tracker = createCallTracker();
- const logger = createFakeLogger();
- const error = new Error('boom');
- const adapter = buildAdapter(
- [disposable('first', tracker), throwingDisposable('explode', tracker, error), disposable('last', tracker)],
- logger,
- );
-
- await adapter.teardown();
-
- expect(tracker.events).toEqual(['dispose:last', 'throw:explode', 'dispose:first']);
- const errorEntry = logger.calls.find((entry) => entry.payload.code === 'lifecycle.teardown.error');
- expect(errorEntry).toBeDefined();
- expect(errorEntry?.level).toBe('error');
- expect((errorEntry?.payload.detail as {name?: string}).name).toBe('explode');
- });
-
- it('cancelOperation after teardown is harmless and does not re-trigger disposal', async () => {
- const tracker = createCallTracker();
- const logger = createFakeLogger();
- const adapter = buildAdapter([disposable('only', tracker)], logger);
-
- await adapter.teardown();
- const eventsAfterTeardown = [...tracker.events];
-
- await adapter.cancelOperation(1, 'after-teardown');
- await adapter.cancelOperation(2, 'still-after-teardown');
-
- expect(tracker.events).toEqual(eventsAfterTeardown);
- expect(adapter.registrySize).toBe(0);
- });
-
- it('produces the same registry transitions across runs for the same input sequence', async () => {
- const sequence: Array<{op: 'register' | 'unregister' | 'cancel'; id: number}> = [
- {op: 'register', id: 1},
- {op: 'register', id: 2},
- {op: 'register', id: 3},
- {op: 'cancel', id: 2},
- {op: 'unregister', id: 1},
- {op: 'register', id: 4},
- ];
-
- async function run(): Promise<Array<number>> {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
- const sizes: Array<number> = [];
- for (const step of sequence) {
- if (step.op === 'register') {
- adapter.register(step.id, new AbortController(), 'detAdapter');
- } else if (step.op === 'unregister') {
- adapter.unregister(step.id);
- } else {
- await adapter.cancelOperation(step.id, 'deterministic');
- }
- sizes.push(adapter.registrySize);
- }
- return sizes;
- }
-
- const first = await run();
- const second = await run();
- const third = await run();
- expect(first).toEqual(second);
- expect(second).toEqual(third);
- expect(first).toEqual([1, 2, 3, 2, 1, 2]);
- });
-
- it('register rejects duplicate operationIds with lifecycleOperationAlreadyRegistered', () => {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
- adapter.register(11, new AbortController(), 'dupAdapter');
- let captured: Error | undefined;
- try {
- adapter.register(11, new AbortController(), 'dupAdapter');
- } catch (error) {
- captured = error as Error;
- }
- expect(captured).toBeDefined();
- expect((captured as Error & {code?: string}).code).toBe('lifecycleOperationAlreadyRegistered');
- expect(adapter.registrySize).toBe(1);
- });
-
- it('exposes the documented constants for upstream wiring', () => {
- expect(LIFECYCLE_OPERATION_CAP).toBe(4096);
- expect(TEARDOWN_PER_DISPOSABLE_TIMEOUT_MS).toBe(5000);
- });
-
- it('unregister returns true when the operationId was tracked, false otherwise', () => {
- const logger = createFakeLogger();
- const adapter = buildAdapter([], logger);
- adapter.register(5, new AbortController(), 'unregAdapter');
- expect(adapter.unregister(5)).toBe(true);
- expect(adapter.unregister(5)).toBe(false);
- expect(adapter.registrySize).toBe(0);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneEnableCoalescing.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneEnableCoalescing.test.ts
deleted file mode 100644
index 8ebd2e998..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneEnableCoalescing.test.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installVoiceMenuTestBootstrap} from '@app/features/ui/action_menu/items/__fixtures__/VoiceMenuTestBootstrap';
-import type {Room} from 'livekit-client';
-import {expect, test, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-vi.mock('@lingui/react/macro', () => ({
- Trans: () => null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),
-}));
-
-installVoiceMenuTestBootstrap();
-
-await import('@app/features/voice/engine/MediaEngineFacade');
-const {VoiceEngineV2AppMediaExecutionAdapter} = await import(
- '@app/features/voice/engine/v2/VoiceEngineV2AppMediaExecutionAdapter'
-);
-
-interface FakeRoom {
- audioTrackPublications: Map<string, unknown>;
- localParticipant: {audioTrackPublications: Map<string, unknown>};
-}
-
-function createFakeRoom(): FakeRoom {
- const audioTrackPublications = new Map<string, unknown>();
- return {audioTrackPublications, localParticipant: {audioTrackPublications}};
-}
-
-function publishMicrophone(room: FakeRoom): void {
- room.audioTrackPublications.set('mic', {
- source: 'microphone',
- track: {mediaStreamTrack: {readyState: 'live'}},
- });
-}
-
-function unpublishMicrophone(room: FakeRoom): void {
- room.audioTrackPublications.delete('mic');
-}
-
-function asRoom(room: FakeRoom): Room {
- return room as unknown as Room;
-}
-
-function createDeferred(): {promise: Promise<void>; resolve: () => void} {
- let resolve = (): void => undefined;
- const promise = new Promise<void>((res) => {
- resolve = () => res();
- });
- return {promise, resolve};
-}
-
-function createAdapter(onEnable: (room: FakeRoom, channelId: string | null) => Promise<void>): {
- adapter: InstanceType<typeof VoiceEngineV2AppMediaExecutionAdapter>;
- calls: Array<{room: FakeRoom; channelId: string | null}>;
-} {
- const adapter = new VoiceEngineV2AppMediaExecutionAdapter();
- const calls: Array<{room: FakeRoom; channelId: string | null}> = [];
- (
- adapter as unknown as {enableMicrophoneNow: (room: Room, channelId: string | null) => Promise<void>}
- ).enableMicrophoneNow = async (room: Room, channelId: string | null): Promise<void> => {
- const fakeRoom = room as unknown as FakeRoom;
- calls.push({room: fakeRoom, channelId});
- await onEnable(fakeRoom, channelId);
- };
- return {adapter, calls};
-}
-
-test('an enable for a second room is not satisfied by an enable in flight for the first room', async () => {
- const roomA = createFakeRoom();
- const roomB = createFakeRoom();
- const gate = createDeferred();
- const {adapter, calls} = createAdapter(async (room) => {
- await gate.promise;
- publishMicrophone(room);
- });
-
- const first = adapter.enableMicrophone(asRoom(roomA), 'channel-a');
- await Promise.resolve();
- const second = adapter.enableMicrophone(asRoom(roomB), 'channel-b');
- gate.resolve();
- await Promise.all([first, second]);
-
- expect(calls.map((call) => call.channelId)).toEqual(['channel-a', 'channel-b']);
- expect(roomA.audioTrackPublications.size).toBe(1);
- expect(roomB.audioTrackPublications.size).toBe(1);
-});
-
-test('an enable is not satisfied by an in-flight enable whose publication was already unpublished', async () => {
- const room = createFakeRoom();
- const gate = createDeferred();
- const {adapter, calls} = createAdapter(async (target) => {
- publishMicrophone(target);
- await gate.promise;
- });
-
- const first = adapter.enableMicrophone(asRoom(room), 'channel-a');
- await Promise.resolve();
- unpublishMicrophone(room);
- const second = adapter.enableMicrophone(asRoom(room), 'channel-a');
- gate.resolve();
- await Promise.all([first, second]);
-
- expect(calls).toHaveLength(2);
- expect(room.audioTrackPublications.size).toBe(1);
-});
-
-test('a coalesced enable that already has a live publication does not enable again', async () => {
- const room = createFakeRoom();
- const gate = createDeferred();
- const {adapter, calls} = createAdapter(async (target) => {
- publishMicrophone(target);
- await gate.promise;
- });
-
- const first = adapter.enableMicrophone(asRoom(room), 'channel-a');
- await Promise.resolve();
- const second = adapter.enableMicrophone(asRoom(room), 'channel-a');
- gate.resolve();
- await Promise.all([first, second]);
-
- expect(calls).toHaveLength(1);
- expect(room.audioTrackPublications.size).toBe(1);
-});
-
-test('a rejection from the in-flight enable still propagates to the coalesced caller', async () => {
- const room = createFakeRoom();
- const gate = createDeferred();
- const {adapter, calls} = createAdapter(async () => {
- await gate.promise;
- throw new Error('enable failed');
- });
-
- const first = adapter.enableMicrophone(asRoom(room), 'channel-a');
- await Promise.resolve();
- const second = adapter.enableMicrophone(asRoom(room), 'channel-a');
- gate.resolve();
-
- await expect(first).rejects.toThrow('enable failed');
- await expect(second).rejects.toThrow('enable failed');
- expect(calls).toHaveLength(1);
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneTransaction.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneTransaction.test.ts
deleted file mode 100644
index db6a2e845..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppMicrophoneTransaction.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- chooseMicrophoneRefreshStrategy,
- computeSpeakingDetectorRms,
- createInitialMicrophoneEnableState,
- createInitialMicrophoneRefreshState,
- readSpeakingDetectorThresholdRms,
- shouldReleaseSpeakingHold,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppMicrophoneTransaction';
-import {describe, expect, it} from 'vitest';
-
-describe('VoiceEngineV2AppMicrophoneTransaction', () => {
- describe('createInitialMicrophoneEnableState', () => {
- it('returns a fresh state with no committed mutations', () => {
- const state = createInitialMicrophoneEnableState();
- expect(state.microphoneWasPublished).toBe(false);
- expect(state.audioTrack).toBeNull();
- expect(state.primaryMicPublication).toBeNull();
- expect(state.shouldUnmuteAfter).toBe(false);
- });
-
- it('returns independent state objects on each call so rollback cannot reach across transactions', () => {
- const a = createInitialMicrophoneEnableState();
- const b = createInitialMicrophoneEnableState();
- a.microphoneWasPublished = true;
- expect(b.microphoneWasPublished).toBe(false);
- });
- });
-
- describe('createInitialMicrophoneRefreshState', () => {
- it('returns a fresh state with restartSucceeded false so the parent can detect uncommitted restarts', () => {
- const state = createInitialMicrophoneRefreshState();
- expect(state.restartSucceeded).toBe(false);
- expect(state.primaryMicPublication).toBeNull();
- expect(state.shouldUnmuteAfter).toBe(false);
- });
- });
-
- describe('chooseMicrophoneRefreshStrategy', () => {
- it('returns restart-in-place when forceRepublish is not set so the refresh reuses the active track', () => {
- expect(chooseMicrophoneRefreshStrategy({})).toBe('restart-in-place');
- });
-
- it('returns restart-in-place when forceRepublish is explicitly false', () => {
- expect(chooseMicrophoneRefreshStrategy({forceRepublish: false})).toBe('restart-in-place');
- });
-
- it('returns force-republish when forceRepublish is true so the refresh tears down and re-publishes', () => {
- expect(chooseMicrophoneRefreshStrategy({forceRepublish: true})).toBe('force-republish');
- });
-
- it('asserts on null input to surface programmer error', () => {
- expect(() => chooseMicrophoneRefreshStrategy(null as unknown as {forceRepublish?: boolean})).toThrow();
- });
- });
-
- describe('computeSpeakingDetectorRms', () => {
- it('returns zero for a silent (all 128) buffer', () => {
- const samples = new Uint8Array(256).fill(128);
- expect(computeSpeakingDetectorRms(samples)).toBe(0);
- });
-
- it('returns 1 for a maximally loud buffer (alternating 0/255)', () => {
- const samples = new Uint8Array(8);
- for (let i = 0; i < samples.length; i++) {
- samples[i] = i % 2 === 0 ? 0 : 255;
- }
- const rms = computeSpeakingDetectorRms(samples);
- expect(rms).toBeGreaterThan(0.99);
- expect(rms).toBeLessThanOrEqual(1.001);
- });
-
- it('returns a value strictly between 0 and 1 for a mid-amplitude buffer', () => {
- const samples = new Uint8Array(4);
- samples[0] = 192;
- samples[1] = 64;
- samples[2] = 192;
- samples[3] = 64;
- const rms = computeSpeakingDetectorRms(samples);
- expect(rms).toBeGreaterThan(0);
- expect(rms).toBeLessThan(1);
- });
-
- it('asserts on empty buffer to prevent divide-by-zero downstream', () => {
- expect(() => computeSpeakingDetectorRms(new Uint8Array(0))).toThrow();
- });
-
- it('reads threshold from the live provider so VAD changes apply without detector restart', () => {
- let threshold = 0.01;
- expect(readSpeakingDetectorThresholdRms(() => threshold)).toBe(0.01);
- threshold = 0.04;
- expect(readSpeakingDetectorThresholdRms(() => threshold)).toBe(0.04);
- });
-
- it('asserts invalid live threshold values before a speaking tick can use them', () => {
- expect(() => readSpeakingDetectorThresholdRms(() => Number.NaN)).toThrow();
- expect(() => readSpeakingDetectorThresholdRms(() => -1)).toThrow();
- });
- });
-
- describe('shouldReleaseSpeakingHold', () => {
- it('does not release while still speaking from silence the same tick', () => {
- expect(
- shouldReleaseSpeakingHold({
- silenceStartedAt: 1000,
- now: 1000,
- releaseDelayMs: 200,
- currentlySpeaking: true,
- }),
- ).toBe(false);
- });
-
- it('releases once the silence window has elapsed', () => {
- expect(
- shouldReleaseSpeakingHold({
- silenceStartedAt: 1000,
- now: 1300,
- releaseDelayMs: 200,
- currentlySpeaking: true,
- }),
- ).toBe(true);
- });
-
- it('never releases when not currently speaking so the detector teardown is idempotent', () => {
- expect(
- shouldReleaseSpeakingHold({
- silenceStartedAt: 1000,
- now: 5000,
- releaseDelayMs: 200,
- currentlySpeaking: false,
- }),
- ).toBe(false);
- });
-
- it('does not release when silence has not yet started', () => {
- expect(
- shouldReleaseSpeakingHold({
- silenceStartedAt: null,
- now: 5000,
- releaseDelayMs: 200,
- currentlySpeaking: true,
- }),
- ).toBe(false);
- });
-
- it('asserts on negative releaseDelayMs to surface programmer error', () => {
- expect(() =>
- shouldReleaseSpeakingHold({
- silenceStartedAt: 0,
- now: 0,
- releaseDelayMs: -1,
- currentlySpeaking: true,
- }),
- ).toThrow();
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppProductionHostPorts.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppProductionHostPorts.test.ts
deleted file mode 100644
index bd9efbd71..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppProductionHostPorts.test.ts
+++ /dev/null
@@ -1,458 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createVoiceEngineV2AppTestControllerHost} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils';
-import {createVoiceEngineV2AppIngestionPort} from '@app/features/voice/engine/v2/VoiceEngineV2AppHostPorts';
-import {createVoiceEngineV2AppLifecycleAdapter} from '@app/features/voice/engine/v2/VoiceEngineV2AppLifecycleAdapter';
-import {createVoiceEngineV2AppProductionHostPorts} from '@app/features/voice/engine/v2/VoiceEngineV2AppProductionHostPorts';
-import type {VoiceEngineV2AppTimerScheduler} from '@app/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter';
-import {
- createVoiceEngineV2ShadowHostPorts,
- type VoiceEngineV2ShadowHostPortCall,
-} from '@app/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts';
-import {
- availableVoiceEngineV2Capabilities,
- type NativeMediaPort,
- type StatsPort,
- type SubscriptionPort,
- type VoiceEngineV2CameraOptions,
- type VoiceEngineV2Event,
- type VoiceEngineV2MicrophoneOptions,
- type VoiceEngineV2Stats,
-} from '@fluxer/voice_engine_v2';
-import {createVoiceEngineV2DeterministicClockPort} from '@fluxer/voice_engine_v2/runtime';
-import {waitForRuntime} from '@fluxer/voice_engine_v2/testing';
-import type {Room} from 'livekit-client';
-import {describe, expect, it} from 'vitest';
-
-type ProductionCall =
- | {type: 'connect'; guildId: string | null; channelId: string}
- | {type: 'enableMicrophone'; channelId: string | null; options?: VoiceEngineV2MicrophoneOptions}
- | {type: 'setCameraEnabled'; enabled: boolean; options?: VoiceEngineV2CameraOptions}
- | {type: 'setOutputDevice'; deviceId: string};
-type NativeMediaCall =
- | {type: 'startCapture'; captureId: string; zeroCopyRequired: boolean}
- | {type: 'attachFrameSink'; captureId: string; sinkId: string; zeroCopyRequired: boolean};
-
-function createStatsPort(): StatsPort {
- return {
- async collectStats(): Promise<VoiceEngineV2Stats> {
- return {rttMs: null, outbound: [], inbound: []};
- },
- };
-}
-
-function createSubscriptionPort(): SubscriptionPort {
- return {
- async setParticipantVolume(): Promise<void> {},
- async setRemoteTrackSubscription(): Promise<void> {},
- };
-}
-
-function createNativeMediaPort(calls: Array<NativeMediaCall>): NativeMediaPort {
- return {
- async startCapture(options): Promise<void> {
- calls.push({
- type: 'startCapture',
- captureId: options.captureId,
- zeroCopyRequired: options.zeroCopyRequired,
- });
- },
- async updateCapture(): Promise<void> {},
- async stopCapture(): Promise<void> {},
- async startAudioTap(): Promise<void> {},
- async stopAudioTap(): Promise<void> {},
- async attachFrameSink(options): Promise<void> {
- calls.push({
- type: 'attachFrameSink',
- captureId: options.captureId,
- sinkId: options.sinkId,
- zeroCopyRequired: options.zeroCopyRequired,
- });
- },
- async detachFrameSink(): Promise<void> {},
- };
-}
-
-function createLogger() {
- return {
- trace(): void {},
- debug(): void {},
- info(): void {},
- warn(): void {},
- error(): void {},
- };
-}
-
-function createBaseProductionOptions() {
- return {
- gateway: {
- async writeVoiceState(): Promise<void> {},
- async clearVoiceState(): Promise<void> {},
- },
- connection: {
- startConnection(): boolean {
- return true;
- },
- },
- media: {
- async enableMicrophone(): Promise<void> {},
- async disableMicrophone(): Promise<void> {},
- async setMicrophoneEnabled(): Promise<void> {},
- async setCameraEnabled(): Promise<'applied'> {
- return 'applied';
- },
- async updateCameraEncoding(): Promise<void> {},
- },
- screenShare: {
- async publishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async unpublishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async updateActiveScreenShareSettings(): Promise<boolean> {
- return true;
- },
- setScreenShareAudioMuted(): void {},
- },
- getRoom: () => ({}) as Room,
- getActiveGuildId: () => 'guild-1',
- getActiveChannelId: () => 'channel-1',
- stats: createStatsPort(),
- subscriptions: createSubscriptionPort(),
- audioOutputStore: {
- async setOutputDevice(): Promise<void> {},
- },
- logger: createLogger(),
- };
-}
-
-describe('VoiceEngineV2AppProductionHostPorts', () => {
- it('routes media commands through real production delegates instead of shadow ports', async () => {
- const productionCalls: Array<ProductionCall> = [];
- const shadowCalls: Array<VoiceEngineV2ShadowHostPortCall> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- gateway: {
- async writeVoiceState(): Promise<void> {},
- async clearVoiceState(): Promise<void> {},
- },
- connection: {
- startConnection(guildId, channelId): boolean {
- productionCalls.push({type: 'connect', guildId, channelId});
- return true;
- },
- },
- media: {
- async enableMicrophone(_room, channelId, options): Promise<void> {
- productionCalls.push({type: 'enableMicrophone', channelId, options});
- },
- async disableMicrophone(): Promise<void> {},
- async setMicrophoneEnabled(): Promise<void> {},
- async setCameraEnabled(enabled, options): Promise<'applied'> {
- productionCalls.push({type: 'setCameraEnabled', enabled, options});
- return 'applied';
- },
- async updateCameraEncoding(): Promise<void> {},
- },
- screenShare: {
- async publishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async unpublishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async updateActiveScreenShareSettings(): Promise<boolean> {
- return true;
- },
- setScreenShareAudioMuted(): void {},
- },
- getRoom: () => ({}) as Room,
- getActiveGuildId: () => 'guild-1',
- getActiveChannelId: () => 'channel-1',
- stats: createStatsPort(),
- subscriptions: createSubscriptionPort(),
- audioOutputStore: {
- async setOutputDevice(deviceId): Promise<void> {
- productionCalls.push({type: 'setOutputDevice', deviceId});
- },
- },
- logger: createLogger(),
- passthrough: createVoiceEngineV2ShadowHostPorts({
- record(call): void {
- shadowCalls.push(call);
- },
- }),
- }),
- });
-
- host.controller.connect({url: 'wss://voice.example.test', token: 'token'});
- await waitForRuntime();
- host.controller.publishMicrophone({
- deviceId: 'mic-1',
- echoCancellation: false,
- noiseSuppression: true,
- autoGainControl: false,
- });
- await waitForRuntime();
- host.controller.setOutputDevice({deviceId: 'speaker-1'});
- await waitForRuntime();
- host.controller.publishCamera({deviceId: 'cam-1'});
- await waitForRuntime();
- host.controller.unpublishCamera();
- await waitForRuntime();
-
- expect(productionCalls).toEqual([
- {type: 'connect', guildId: 'guild-1', channelId: 'channel-1'},
- {
- type: 'enableMicrophone',
- channelId: 'channel-1',
- options: {
- deviceId: 'mic-1',
- echoCancellation: false,
- noiseSuppression: true,
- autoGainControl: false,
- },
- },
- {type: 'setOutputDevice', deviceId: 'speaker-1'},
- {type: 'setCameraEnabled', enabled: true, options: {deviceId: 'cam-1'}},
- {type: 'setCameraEnabled', enabled: false, options: undefined},
- ]);
- expect(shadowCalls).toEqual([]);
- host.dispose();
- });
-
- it('routes native capture and frame sinks through production native-media port', async () => {
- const nativeMediaCalls: Array<NativeMediaCall> = [];
- const shadowCalls: Array<VoiceEngineV2ShadowHostPortCall> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- gateway: {
- async writeVoiceState(): Promise<void> {},
- async clearVoiceState(): Promise<void> {},
- },
- connection: {
- startConnection(): boolean {
- return true;
- },
- },
- media: {
- async enableMicrophone(): Promise<void> {},
- async disableMicrophone(): Promise<void> {},
- async setMicrophoneEnabled(): Promise<void> {},
- async setCameraEnabled(): Promise<'applied'> {
- return 'applied';
- },
- async updateCameraEncoding(): Promise<void> {},
- },
- screenShare: {
- async publishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async unpublishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async updateActiveScreenShareSettings(): Promise<boolean> {
- return true;
- },
- setScreenShareAudioMuted(): void {},
- },
- getRoom: () => ({}) as Room,
- getActiveGuildId: () => 'guild-1',
- getActiveChannelId: () => 'channel-1',
- stats: createStatsPort(),
- subscriptions: createSubscriptionPort(),
- audioOutputStore: {
- async setOutputDevice(): Promise<void> {},
- },
- nativeMedia: createNativeMediaPort(nativeMediaCalls),
- logger: createLogger(),
- passthrough: createVoiceEngineV2ShadowHostPorts({
- record(call): void {
- shadowCalls.push(call);
- },
- }),
- }),
- });
-
- host.dispatch({type: 'capabilities.changed', capabilities: availableVoiceEngineV2Capabilities()});
- host.controller.startNativeCapture({
- captureId: 'screen-1',
- source: {kind: 'screen', id: 'display-1', title: 'Display 1'},
- width: 1920,
- height: 1080,
- frameRate: 60,
- includeCursor: true,
- includeAudio: true,
- zeroCopyRequired: true,
- });
- host.controller.attachNativeFrameSink({
- captureId: 'screen-1',
- sinkId: 'sink-1',
- trackSid: 'TR_screen',
- zeroCopyRequired: true,
- });
- await waitForRuntime();
-
- expect(nativeMediaCalls).toEqual([
- {type: 'startCapture', captureId: 'screen-1', zeroCopyRequired: true},
- {type: 'attachFrameSink', captureId: 'screen-1', sinkId: 'sink-1', zeroCopyRequired: true},
- ]);
- expect(shadowCalls).toEqual([]);
- host.dispose();
- });
-
- it('fails missing production native-media ports instead of falling through to shadow', async () => {
- const shadowCalls: Array<VoiceEngineV2ShadowHostPortCall> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- gateway: {
- async writeVoiceState(): Promise<void> {},
- async clearVoiceState(): Promise<void> {},
- },
- connection: {
- startConnection(): boolean {
- return true;
- },
- },
- media: {
- async enableMicrophone(): Promise<void> {},
- async disableMicrophone(): Promise<void> {},
- async setMicrophoneEnabled(): Promise<void> {},
- async setCameraEnabled(): Promise<'applied'> {
- return 'applied';
- },
- async updateCameraEncoding(): Promise<void> {},
- },
- screenShare: {
- async publishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async unpublishControllerScreenViaLiveKitFlows(): Promise<void> {},
- async updateActiveScreenShareSettings(): Promise<boolean> {
- return true;
- },
- setScreenShareAudioMuted(): void {},
- },
- getRoom: () => ({}) as Room,
- getActiveGuildId: () => 'guild-1',
- getActiveChannelId: () => 'channel-1',
- stats: createStatsPort(),
- subscriptions: createSubscriptionPort(),
- audioOutputStore: {
- async setOutputDevice(): Promise<void> {},
- },
- logger: createLogger(),
- }),
- });
-
- host.dispatch({type: 'capabilities.changed', capabilities: availableVoiceEngineV2Capabilities()});
- host.controller.startNativeCapture({
- captureId: 'screen-1',
- source: {kind: 'screen', id: 'display-1', title: 'Display 1'},
- width: 1920,
- height: 1080,
- frameRate: 60,
- includeCursor: true,
- includeAudio: true,
- zeroCopyRequired: true,
- });
- await waitForRuntime();
-
- expect(host.snapshot.nativeCapture.failure).toMatchObject({
- code: 'unsupportedCapability',
- capability: 'nativeMedia',
- });
- expect(shadowCalls).toEqual([]);
- host.dispose();
- });
-
- it('dispatches timer.fired into the runtime when a scheduled timer fires', async () => {
- const firePending: Array<() => void> = [];
- const scheduler: VoiceEngineV2AppTimerScheduler = {
- setTimeout(callback): unknown {
- firePending.push(callback);
- return firePending.length;
- },
- clearTimeout(): void {},
- };
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- ...createBaseProductionOptions(),
- timerScheduler: scheduler,
- }),
- });
- const seenEvents: Array<VoiceEngineV2Event> = [];
- const unsubscribe = host.subscribe(({event}) => {
- seenEvents.push(event);
- });
-
- host.dispatch({type: 'timer.scheduleRequested', options: {timerId: 'reconnect-backoff', delayMs: 250}});
- await waitForRuntime();
- expect(firePending).toHaveLength(1);
-
- firePending[0]?.();
- await waitForRuntime();
-
- expect(seenEvents).toContainEqual({type: 'timer.fired', timerId: 'reconnect-backoff', operationId: null});
- unsubscribe();
- host.dispose();
- });
-
- it('wires the production participant projection ingestion source into the runtime', () => {
- const ingestion = createVoiceEngineV2AppIngestionPort();
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- ...createBaseProductionOptions(),
- ingestion,
- }),
- });
-
- ingestion.ingest({
- type: 'room.participantJoined',
- participant: {sid: 'participant-1', identity: 'user-1', name: 'Ada'},
- });
-
- expect(host.model.participants).toEqual([{sid: 'participant-1', identity: 'user-1', name: 'Ada'}]);
- host.dispose();
- });
-
- it('tears down production lifecycle disposables when lifecycle teardown is requested', async () => {
- const disposed: Array<string> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- ...createBaseProductionOptions(),
- lifecycleDisposables: [
- {
- name: 'native-bridge',
- async dispose(): Promise<void> {
- disposed.push('native-bridge');
- },
- },
- ],
- }),
- });
-
- host.dispatch({type: 'lifecycle.teardownRequested', reason: 'appShutdown'});
- await waitForRuntime();
-
- expect(disposed).toEqual(['native-bridge']);
- expect(host.snapshot.lifecycle.tearingDown).toBe(false);
- expect(host.snapshot.lifecycle.failure).toBeNull();
- host.dispose();
- });
-
- it('cancels registered operations through an injected production lifecycle adapter', async () => {
- const lifecycle = createVoiceEngineV2AppLifecycleAdapter({
- disposables: [],
- logger: createLogger(),
- clock: createVoiceEngineV2DeterministicClockPort(),
- });
- const controller = new AbortController();
- lifecycle.register(7, controller, 'test-adapter');
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2AppProductionHostPorts({
- ...createBaseProductionOptions(),
- lifecycle,
- }),
- });
-
- host.dispatch({
- type: 'operation.cancelRequested',
- operationId: 7,
- resourceKey: 'connection',
- reason: 'user-cancelled',
- });
- await waitForRuntime();
-
- expect(controller.signal.aborted).toBe(true);
- expect(lifecycle.registrySize).toBe(0);
- host.dispose();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareControllerRouting.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareControllerRouting.test.ts
deleted file mode 100644
index bf73d88c2..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareControllerRouting.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type VoiceEngineV2AppScreenShareControllerGateway,
- VoiceEngineV2AppScreenShareControllerRouting,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareControllerRouting';
-import type {VoiceEngineV2AppScreenShareExecutionAdapter} from '@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter';
-import {
- getRecentScreenShares,
- recordScreenShareStarted,
- resetRecentScreenSharesForTests,
-} from '@app/features/voice/utils/ScreenShareLifecycleLog';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/voice/engine/voice_screen_share_manager/shared', () => ({
- logger: {debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined},
-}));
-
-vi.mock('@app/features/voice/state/LocalVoiceState', () => ({
- default: {getSelfStream: () => true},
-}));
-
-const setEnabled = vi.fn(async () => undefined);
-
-function createAdapter(): VoiceEngineV2AppScreenShareExecutionAdapter {
- return {liveKitFlows: {setEnabled}} as unknown as VoiceEngineV2AppScreenShareExecutionAdapter;
-}
-
-function createGateway(
- overrides: Partial<VoiceEngineV2AppScreenShareControllerGateway> = {},
-): VoiceEngineV2AppScreenShareControllerGateway {
- return {
- isScreenCommandRoutable: () => true,
- hasScreenPublication: () => true,
- hasScreenDesired: () => false,
- clearScreenDesired: () => undefined,
- executingScreenOperationId: () => null,
- isScreenOperationPending: () => true,
- publishScreen: async () => undefined,
- unpublishScreen: async () => undefined,
- ...overrides,
- };
-}
-
-describe('routed screen share stop attribution', () => {
- beforeEach(() => {
- resetRecentScreenSharesForTests();
- setEnabled.mockClear();
- });
-
- it('keeps a stop the user asked for as a user stop when the controller carries it out', async () => {
- const routing = new VoiceEngineV2AppScreenShareControllerRouting(createAdapter());
- let executingOperationId: number | null = null;
- routing.setGateway(
- createGateway({
- executingScreenOperationId: () => executingOperationId,
- unpublishScreen: async (onPlanned) => {
- onPlanned([7]);
- executingOperationId = 7;
- await routing.unpublishViaLiveKitFlows(null);
- },
- }),
- );
- recordScreenShareStarted();
-
- await routing.setEnabled(null, false, {sendUpdate: true, playSound: true});
-
- expect(setEnabled).toHaveBeenCalledTimes(1);
- expect(getRecentScreenShares()[0].stopTrigger).toBe('user');
- });
-
- it('records an unpublish the app never asked for as a gateway echo', async () => {
- const routing = new VoiceEngineV2AppScreenShareControllerRouting(createAdapter());
- routing.setGateway(createGateway());
- recordScreenShareStarted();
-
- await routing.unpublishViaLiveKitFlows(null);
-
- expect(getRecentScreenShares()[0].stopTrigger).toBe('gateway-echo');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.ts
deleted file mode 100644
index 9a52a1b1b..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.ts
+++ /dev/null
@@ -1,490 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- isVoiceEngineV2AppParticipantSpeaking,
- selectVoiceEngineV2AppConnection,
- selectVoiceEngineV2AppConnectionWithFallback,
- selectVoiceEngineV2AppDevices,
- selectVoiceEngineV2AppE2ee,
- selectVoiceEngineV2AppEffectiveSelfMuteForVoiceStatePayload,
- selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls,
- selectVoiceEngineV2AppInboundVideoTrack,
- selectVoiceEngineV2AppIntentSelfMuteForVoiceStatePayload,
- selectVoiceEngineV2AppIntentSelfMuteFromAudioControls,
- selectVoiceEngineV2AppLocalMedia,
- selectVoiceEngineV2AppMuteReason,
- selectVoiceEngineV2AppParticipant,
- selectVoiceEngineV2AppParticipants,
- selectVoiceEngineV2AppStats,
- selectVoiceEngineV2AppTrackForSource,
- selectVoiceEngineV2AppTracks,
- selectVoiceEngineV2AppTracksForParticipant,
- selectVoiceEngineV2AppView,
- selectVoiceEngineV2AppWatchedStream,
- selectVoiceEngineV2AppWatchedStreams,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppSelectors';
-import {
- availableVoiceEngineV2Capabilities,
- createVoiceEngineV2InitialSnapshot,
- transitionVoiceEngineV2,
- type VoiceEngineV2Event,
- type VoiceEngineV2Snapshot,
-} from '@fluxer/voice_engine_v2';
-import appVoiceSessionFixtureJson from '@fluxer/voice_engine_v2/fixtures/event_logs/app_voice_session.json';
-import {replayVoiceEngineV2EventLogFixture, type VoiceEngineV2EventLogFixture} from '@fluxer/voice_engine_v2/testing';
-import {describe, expect, it} from 'vitest';
-
-function replayEvents(events: Array<VoiceEngineV2Event>): VoiceEngineV2Snapshot {
- let snapshot = createVoiceEngineV2InitialSnapshot(availableVoiceEngineV2Capabilities());
- for (const event of events) {
- snapshot = transitionVoiceEngineV2(snapshot, event).snapshot;
- }
- return snapshot;
-}
-
-describe('VoiceEngineV2AppSelectors', () => {
- it('projects the canonical app voice-session fixture from snapshots and models', () => {
- const replay = replayVoiceEngineV2EventLogFixture(appVoiceSessionFixtureJson as VoiceEngineV2EventLogFixture);
- const snapshotView = selectVoiceEngineV2AppView(replay.finalSnapshot);
- const modelView = selectVoiceEngineV2AppView(replay.finalModel);
-
- expect(snapshotView).toEqual(modelView);
- expect(snapshotView.connection).toMatchObject({
- status: 'connected',
- connected: true,
- canPublishMedia: true,
- guildId: 'guild-1',
- channelId: 'channel-1',
- userId: 'user-1',
- sessionId: 'session-1',
- roomSid: 'room-1',
- roomName: 'guild-1/channel-1',
- serverRegion: 'us-east',
- });
- expect(snapshotView.localMedia).toMatchObject({
- microphone: 'published',
- camera: 'published',
- screen: 'published',
- screenAudio: 'published',
- audioMode: 'pushToTalk',
- hasActiveLocalMedia: true,
- effectiveMicrophoneEnabled: true,
- localSpeakingOverride: true,
- pushToTalkActive: true,
- screenCaptureId: 'screen-1',
- });
- expect(snapshotView.participants.participantIdentities).toEqual(['user-2']);
- expect(snapshotView.tracks.microphoneTracks.map((track) => track.trackSid)).toEqual(['track-remote-mic-1']);
- expect(snapshotView.tracks.screenTracks.map((track) => track.trackSid)).toEqual(['track-remote-screen-1']);
- expect(snapshotView.devices.selectedAudioInput?.label).toBe('Studio Mic');
- expect(snapshotView.devices.selectedAudioOutput?.label).toBe('Desk Speakers');
- expect(snapshotView.devices.selectedCamera?.label).toBe('Face Camera');
- expect(snapshotView.stats).toMatchObject({
- hasStats: true,
- rttMs: 42,
- outboundTrackCount: 2,
- inboundTrackCount: 1,
- droppedNativeVideoFrames: 0,
- failureCode: null,
- });
- expect(snapshotView.stats.summary?.network).toMatchObject({
- audioSendBitrateKbps: 48,
- audioRecvBitrateKbps: 40,
- videoSendBitrateKbps: 2500,
- rttMs: 42,
- });
- expect(snapshotView.e2ee).toMatchObject({status: 'disabled', enabled: false, pending: false, failed: false});
- });
-
- it('selects participants, tracks, watched streams, and inbound video from v2 events', () => {
- const snapshot = replayEvents([
- {type: 'connection.connectRequested', options: {url: 'wss://voice.example.test', token: 'token-1'}},
- {type: 'connection.connectSucceeded', operationId: 1},
- {
- type: 'watchedStream.watchRequested',
- stream: {
- participantIdentity: 'alice',
- source: 'screen',
- trackSid: null,
- quality: 'high',
- enabled: true,
- },
- },
- {type: 'room.participantJoined', participant: {sid: 'PA_alice', identity: 'alice', name: 'Alice'}},
- {
- type: 'room.trackPublished',
- track: {
- participantIdentity: 'alice',
- participantSid: 'PA_alice',
- trackSid: 'TR_screen',
- trackName: 'screen',
- kind: 'video',
- source: 'screen',
- muted: false,
- },
- },
- {
- type: 'room.trackPublished',
- track: {
- participantIdentity: 'alice',
- participantSid: 'PA_alice',
- trackSid: 'TR_microphone',
- trackName: 'microphone',
- kind: 'audio',
- source: 'microphone',
- muted: false,
- },
- },
- {
- type: 'inboundVideo.trackSubscribed',
- track: {
- participantSid: 'PA_alice',
- participantIdentity: 'alice',
- trackSid: 'TR_screen',
- source: 'screen',
- },
- },
- {
- type: 'inboundVideo.frameReceived',
- frame: {
- participantSid: 'PA_alice',
- participantIdentity: 'alice',
- trackSid: 'TR_screen',
- width: 1280,
- height: 720,
- timestampUs: 2000,
- byteLength: 1_382_400,
- },
- },
- ]);
-
- expect(selectVoiceEngineV2AppConnection(snapshot).canPublishMedia).toBe(true);
- expect(selectVoiceEngineV2AppParticipants(snapshot).participantIdentities).toEqual(['alice']);
- expect(selectVoiceEngineV2AppParticipant(snapshot, 'alice')?.name).toBe('Alice');
- expect(selectVoiceEngineV2AppTracks(snapshot)).toMatchObject({
- audioTracks: [{trackSid: 'TR_microphone'}],
- videoTracks: [{trackSid: 'TR_screen'}],
- screenTracks: [{trackSid: 'TR_screen'}],
- });
- expect(selectVoiceEngineV2AppTracksForParticipant(snapshot, 'alice').map((track) => track.trackSid)).toEqual([
- 'TR_microphone',
- 'TR_screen',
- ]);
- expect(selectVoiceEngineV2AppTrackForSource(snapshot, 'alice', 'screen')?.trackSid).toBe('TR_screen');
- expect(selectVoiceEngineV2AppWatchedStreams(snapshot).enabledStreams).toEqual([
- {
- participantIdentity: 'alice',
- source: 'screen',
- trackSid: 'TR_screen',
- quality: 'high',
- enabled: true,
- },
- ]);
- expect(selectVoiceEngineV2AppWatchedStream(snapshot, 'alice', 'screen')?.trackSid).toBe('TR_screen');
- expect(selectVoiceEngineV2AppInboundVideoTrack(snapshot, 'TR_screen')).toMatchObject({
- participantIdentity: 'alice',
- width: 1280,
- height: 720,
- frameCount: 1,
- lastFrameByteLength: 1_382_400,
- });
- });
-
- it('projects selected devices, permissions, stats failures, and E2EE without exposing reducer bookkeeping', () => {
- const snapshot = replayEvents([
- {type: 'connection.connectRequested', options: {url: 'wss://voice.example.test', token: 'token-1'}},
- {type: 'connection.connectSucceeded', operationId: 1},
- {
- type: 'devices.changed',
- operationId: null,
- reason: 'initial',
- devices: {
- audioInputs: [{deviceId: 'mic-1', label: 'Studio Mic', isDefault: true, role: 'communications'}],
- audioOutputs: [{deviceId: 'speaker-1', label: 'Desk Speakers', isDefault: true}],
- cameras: [{deviceId: 'camera-1', label: 'Face Camera'}],
- selectedAudioInputId: 'mic-1',
- selectedAudioOutputId: 'speaker-1',
- selectedCameraId: 'camera-1',
- },
- },
- {
- type: 'permissions.result',
- operationId: null,
- result: {name: 'microphone', status: 'denied', canPrompt: true},
- },
- {type: 'stats.collectRequested'},
- {
- type: 'stats.collectFailed',
- operationId: 2,
- error: {code: 'implementationError', message: 'stats failed'},
- },
- {type: 'e2ee.setEnabledRequested', enabled: true, keyId: 'key-a'},
- {type: 'e2ee.enabled', operationId: 3, keyId: 'key-a'},
- {
- type: 'e2ee.failed',
- operationId: null,
- error: {code: 'implementationError', message: 'key rotation failed', capability: 'e2ee'},
- },
- ]);
- const devices = selectVoiceEngineV2AppDevices(snapshot);
- const stats = selectVoiceEngineV2AppStats(snapshot);
- const e2ee = selectVoiceEngineV2AppE2ee(snapshot);
-
- expect(devices).toMatchObject({
- hasAudioInput: true,
- hasAudioOutput: true,
- hasCamera: true,
- selectedAudioInput: {deviceId: 'mic-1', label: 'Studio Mic', role: 'communications'},
- selectedAudioOutput: {deviceId: 'speaker-1', label: 'Desk Speakers'},
- selectedCamera: {deviceId: 'camera-1', label: 'Face Camera'},
- microphonePermission: {name: 'microphone', status: 'denied', canPrompt: true},
- });
- expect(stats).toMatchObject({
- hasStats: false,
- summary: null,
- rttMs: null,
- outboundTrackCount: 0,
- inboundTrackCount: 0,
- failureCode: 'implementationError',
- });
- expect(e2ee).toMatchObject({
- status: 'failed',
- keyId: 'key-a',
- enabled: false,
- pending: false,
- failed: true,
- failure: {code: 'implementationError', capability: 'e2ee'},
- });
- expect('operationId' in e2ee).toBe(false);
- });
-
- it('keeps model-only selectors usable when no snapshot failure state is available', () => {
- const replay = replayVoiceEngineV2EventLogFixture(appVoiceSessionFixtureJson as VoiceEngineV2EventLogFixture);
- const localMedia = selectVoiceEngineV2AppLocalMedia(replay.finalModel);
- const stats = selectVoiceEngineV2AppStats(replay.finalModel);
-
- expect(localMedia.screenCaptureId).toBe('screen-1');
- expect(stats.failureCode).toBeNull();
- expect(stats.summary?.localScreenShare?.trackIdentifier).toBe('local-screen');
- });
-
- it('uses app-shell connection fallback only while v2 has no active connection projection', () => {
- const initialSnapshot = createVoiceEngineV2InitialSnapshot(availableVoiceEngineV2Capabilities());
- expect(
- selectVoiceEngineV2AppConnectionWithFallback(initialSnapshot, {
- connected: true,
- connecting: false,
- guildId: 'guild-fallback',
- channelId: 'channel-fallback',
- sessionId: 'connection-fallback',
- }),
- ).toMatchObject({
- status: 'connected',
- connected: true,
- connecting: false,
- guildId: 'guild-fallback',
- channelId: 'channel-fallback',
- sessionId: 'connection-fallback',
- });
-
- const connectedSnapshot = replayEvents([
- {type: 'connection.connectRequested', options: {url: 'wss://voice.example.test', token: 'token-1'}},
- {type: 'connection.connectSucceeded', operationId: 1},
- {
- type: 'gateway.voiceStateUpdated',
- voiceState: {
- guildId: 'guild-v2',
- channelId: 'channel-v2',
- userId: 'user-v2',
- sessionId: 'session-v2',
- selfMute: false,
- selfDeaf: false,
- selfVideo: false,
- selfStream: false,
- suppress: false,
- requestToSpeakTimestamp: null,
- },
- },
- ]);
- expect(
- selectVoiceEngineV2AppConnectionWithFallback(connectedSnapshot, {
- connected: true,
- channelId: 'channel-fallback',
- }),
- ).toMatchObject({
- status: 'connected',
- connected: true,
- channelId: 'channel-v2',
- sessionId: 'session-v2',
- });
- });
-
- it('checks participant speaking from the v2 app selector helper', () => {
- expect(isVoiceEngineV2AppParticipantSpeaking(null)).toBe(false);
- expect(isVoiceEngineV2AppParticipantSpeaking({isSpeaking: false, isAudioLevelSpeaking: false})).toBe(false);
- expect(isVoiceEngineV2AppParticipantSpeaking({isSpeaking: true, isAudioLevelSpeaking: false})).toBe(true);
- expect(isVoiceEngineV2AppParticipantSpeaking({isSpeaking: false, isAudioLevelSpeaking: true})).toBe(true);
- });
-
- it('projects the effective self-mute payload from v2 audio controls', () => {
- const pushToTalkMutedSnapshot = replayEvents([
- {
- type: 'audioControls.changed',
- controls: {
- mode: 'pushToTalk',
- locallyMuted: false,
- pushToTalkActive: false,
- },
- },
- ]);
- const pushToMuteMutedSnapshot = replayEvents([
- {
- type: 'audioControls.changed',
- controls: {
- mode: 'pushToMute',
- locallyMuted: false,
- pushToMuteActive: true,
- },
- },
- ]);
- const voiceActivityUnmutedSnapshot = replayEvents([
- {
- type: 'audioControls.changed',
- controls: {
- mode: 'voiceActivity',
- locallyMuted: false,
- pushToTalkActive: false,
- pushToMuteActive: false,
- },
- },
- ]);
-
- expect(selectVoiceEngineV2AppEffectiveSelfMuteForVoiceStatePayload(pushToTalkMutedSnapshot)).toBe(true);
- expect(selectVoiceEngineV2AppEffectiveSelfMuteForVoiceStatePayload(pushToMuteMutedSnapshot)).toBe(true);
- expect(selectVoiceEngineV2AppEffectiveSelfMuteForVoiceStatePayload(voiceActivityUnmutedSnapshot)).toBe(false);
- expect(
- selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls({
- mode: 'pushToTalk',
- locallyMuted: false,
- preferredLocallyMuted: false,
- locallyDeafened: false,
- mutedByPermission: false,
- hasUserSetMute: false,
- hasUserSetDeaf: false,
- shouldUnmuteOnUndeafen: false,
- pushToTalkActive: false,
- pushToMuteActive: false,
- inputVolume: 1,
- outputVolume: 1,
- }),
- ).toBe(true);
- });
-
- it('projects the gateway self-mute payload from intent, not push-to-talk silence (canonical bug)', () => {
- const pushToTalkUnmutedIdle = replayEvents([
- {
- type: 'audioControls.changed',
- controls: {
- mode: 'pushToTalk',
- locallyMuted: false,
- pushToTalkActive: false,
- pushToMuteActive: false,
- },
- },
- ]);
- const pushToTalkMutedIdle = replayEvents([
- {
- type: 'localAudio.muteRequested',
- muted: true,
- },
- {
- type: 'audioControls.changed',
- controls: {
- mode: 'pushToTalk',
- pushToTalkActive: false,
- },
- },
- ]);
-
- expect(selectVoiceEngineV2AppEffectiveSelfMuteForVoiceStatePayload(pushToTalkUnmutedIdle)).toBe(true);
- expect(selectVoiceEngineV2AppIntentSelfMuteForVoiceStatePayload(pushToTalkUnmutedIdle)).toBe(false);
- expect(selectVoiceEngineV2AppIntentSelfMuteForVoiceStatePayload(pushToTalkMutedIdle)).toBe(true);
- expect(
- selectVoiceEngineV2AppIntentSelfMuteFromAudioControls({
- mode: 'pushToTalk',
- locallyMuted: false,
- preferredLocallyMuted: false,
- locallyDeafened: false,
- mutedByPermission: true,
- hasUserSetMute: false,
- hasUserSetDeaf: false,
- shouldUnmuteOnUndeafen: false,
- pushToTalkActive: false,
- pushToMuteActive: false,
- inputVolume: 1,
- outputVolume: 1,
- }),
- ).toBe(true);
- });
-
- it('selects app mute reasons from v2 audio controls and server permission state', () => {
- const audio = {
- mode: 'voiceActivity' as const,
- locallyMuted: false,
- preferredLocallyMuted: false,
- locallyDeafened: false,
- mutedByPermission: false,
- hasUserSetMute: false,
- hasUserSetDeaf: false,
- shouldUnmuteOnUndeafen: false,
- pushToTalkActive: false,
- pushToMuteActive: false,
- inputVolume: 1,
- outputVolume: 1,
- };
-
- expect(selectVoiceEngineV2AppMuteReason({voiceState: {mute: true}, permissionMuted: false, audio})).toBe('guild');
- expect(selectVoiceEngineV2AppMuteReason({voiceState: {mute: false}, permissionMuted: true, audio})).toBe(
- 'permission',
- );
- expect(
- selectVoiceEngineV2AppMuteReason({
- voiceState: {mute: false},
- permissionMuted: false,
- audio: {...audio, locallyMuted: true},
- }),
- ).toBe('self');
- expect(
- selectVoiceEngineV2AppMuteReason({
- voiceState: {mute: false},
- permissionMuted: false,
- audio: {...audio, mode: 'pushToTalk', pushToTalkActive: false},
- }),
- ).toBe('voice_push_to_talk');
- expect(selectVoiceEngineV2AppMuteReason({voiceState: {mute: false}, permissionMuted: false, audio})).toBeNull();
- });
-
- it('asserts non-null source for projection selectors (negative space)', () => {
- expect(() => selectVoiceEngineV2AppConnection(null as never)).toThrow();
- expect(() => selectVoiceEngineV2AppView(undefined as never)).toThrow();
- expect(() => selectVoiceEngineV2AppParticipant(null as never, 'identity')).toThrow();
- });
-
- it('treats push-to-mute active as effective self mute via split predicate', () => {
- const audio = {
- mode: 'pushToMute' as const,
- locallyMuted: false,
- preferredLocallyMuted: false,
- locallyDeafened: false,
- mutedByPermission: false,
- hasUserSetMute: false,
- hasUserSetDeaf: false,
- shouldUnmuteOnUndeafen: false,
- pushToTalkActive: false,
- pushToMuteActive: true,
- inputVolume: 1,
- outputVolume: 1,
- };
- expect(selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls(audio)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.test.ts
deleted file mode 100644
index 72c20e1e6..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge.test.ts
+++ /dev/null
@@ -1,647 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceEngineV2AppControllerHost} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHost';
-import {createVoiceEngineV2AppTestControllerHost} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils';
-import {
- VoiceEngineV2AppSourceLifecycleBridge,
- type VoiceEngineV2AppSourceLifecycleClosedCleanInfo,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge';
-import {createVoiceEngineV2ShadowHostPorts} from '@app/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts';
-import type {NativeScreenCaptureLifecycleMessage} from '@app/types/electron.d';
-import type {VoiceEngineV2Event} from '@fluxer/voice_engine_v2';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-interface MockNativeBinding {
- dispatch(message: NativeScreenCaptureLifecycleMessage): void;
- subscribe(callback: (message: NativeScreenCaptureLifecycleMessage) => void): () => void;
- listenerCount(): number;
-}
-
-function createMockNativeBinding(): MockNativeBinding {
- const listeners = new Set<(message: NativeScreenCaptureLifecycleMessage) => void>();
- return {
- dispatch(message): void {
- for (const listener of listeners) {
- listener(message);
- }
- },
- subscribe(callback): () => void {
- listeners.add(callback);
- return () => {
- listeners.delete(callback);
- };
- },
- listenerCount(): number {
- return listeners.size;
- },
- };
-}
-
-function createFixedNow(): {next: () => number; advance: (ms: number) => void} {
- let value = 1000;
- return {
- next: () => value,
- advance: (ms) => {
- value += ms;
- },
- };
-}
-
-interface FakeRemoteTrack {
- on(event: 'ended', listener: () => void): void;
- off(event: 'ended', listener: () => void): void;
- emit(event: 'ended'): void;
- listenerCount(event: 'ended'): number;
-}
-
-function createFakeRemoteTrack(): FakeRemoteTrack {
- const listeners = new Set<() => void>();
- return {
- on(_event, listener): void {
- listeners.add(listener);
- },
- off(_event, listener): void {
- listeners.delete(listener);
- },
- emit(_event): void {
- for (const listener of Array.from(listeners)) {
- listener();
- }
- },
- listenerCount(_event): number {
- return listeners.size;
- },
- };
-}
-
-let host: VoiceEngineV2AppControllerHost;
-
-beforeEach(() => {
- host = createVoiceEngineV2AppTestControllerHost({ports: createVoiceEngineV2ShadowHostPorts()});
-});
-
-describe('VoiceEngineV2AppSourceLifecycleBridge', () => {
- it('bind dispatches an active sourceLifecycle.transitioned event into the v2 host', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- now: () => 1234,
- });
-
- const ok = bridge.bind({captureId: 'capture-1', sourceId: 'source-1'});
- expect(ok).toBe(true);
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].sourceId).toBe('source-1');
- expect(dispatched[0].kind).toBe('active');
- expect(dispatched[0].attempts).toBe(0);
- expect(dispatched[0].fault).toBeNull();
- }
- bridge.dispose();
- });
-
- it('an "error" native lifecycle event dispatches sourceLifecycle.transitioned with reconnecting + captureDeviceLost', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'capture-2', sourceId: 'source-2'});
- dispatched.length = 0;
-
- binding.dispatch({captureId: 'capture-2', kind: 'error', message: 'stream lost'});
-
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].kind).toBe('reconnecting');
- expect(dispatched[0].sourceId).toBe('source-2');
- expect(dispatched[0].attempts).toBe(1);
- expect(dispatched[0].fault).toBe('captureDeviceLost');
- }
- bridge.dispose();
- });
-
- it('lifecycle events from the mock native binding flow into the v2 reducer snapshot', () => {
- const binding = createMockNativeBinding();
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => host.dispatch(event),
- subscribe: binding.subscribe,
- });
-
- expect(bridge.bind({captureId: 'capture-3', sourceId: 'source-3'})).toBe(true);
- expect(host.snapshot.sourceLifecycles['source-3']?.kind).toBe('active');
-
- binding.dispatch({captureId: 'capture-3', kind: 'error', message: 'connection died'});
-
- const reconnecting = host.snapshot.sourceLifecycles['source-3'];
- expect(reconnecting?.kind).toBe('reconnecting');
- if (reconnecting?.kind === 'reconnecting') {
- expect(reconnecting.attempts).toBe(1);
- expect(reconnecting.lastFault).toBe('captureDeviceLost');
- }
- bridge.dispose();
- });
-
- it('ignores lifecycle events for unknown captureIds', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'capture-known', sourceId: 'source-known'});
- dispatched.length = 0;
-
- binding.dispatch({captureId: 'capture-unknown', kind: 'error', message: 'lost'});
-
- expect(dispatched).toHaveLength(0);
- bridge.dispose();
- });
-
- it('translates "stalled" to networkError and routes diagnostic messages to diagnostics', async () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const diagnosticsCalls: Array<{
- level: string;
- code: string;
- message: string;
- detail: unknown;
- }> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- diagnostics: {
- async log(level, code, message, detail): Promise<void> {
- diagnosticsCalls.push({level, code, message, detail});
- },
- },
- });
-
- bridge.bind({captureId: 'cap-stall', sourceId: 'src-stall'});
- dispatched.length = 0;
-
- binding.dispatch({captureId: 'cap-stall', kind: 'stalled', message: 'frames slow'});
- binding.dispatch({captureId: 'cap-stall', kind: 'diagnostic', message: 'gpu temp ok'});
-
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].fault).toBe('networkError');
- expect(dispatched[0].kind).toBe('reconnecting');
- }
- await Promise.resolve();
- expect(diagnosticsCalls).toEqual([
- {
- level: 'info',
- code: 'nativeCaptureDiagnostic',
- message: 'gpu temp ok',
- detail: {captureId: 'cap-stall', sourceId: 'src-stall', source: 'unknown'},
- },
- ]);
- bridge.dispose();
- });
-
- it('unbind removes the binding and stops forwarding events for that captureId', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-x', sourceId: 'src-x'});
- bridge.unbind('cap-x');
- dispatched.length = 0;
-
- binding.dispatch({captureId: 'cap-x', kind: 'error', message: 'too late'});
-
- expect(dispatched).toHaveLength(0);
- bridge.dispose();
- });
-
- it('unbind dispatches sourceLifecycle.removed so the reducer drops the snapshot slot', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-removed', sourceId: 'src-removed'});
- dispatched.length = 0;
-
- expect(bridge.unbind('cap-removed')).toBe(true);
-
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.removed');
- if (dispatched[0]?.type === 'sourceLifecycle.removed') {
- expect(dispatched[0].sourceId).toBe('src-removed');
- }
- expect(bridge.unbind('cap-removed')).toBe(false);
- bridge.dispose();
- });
-
- it('dispose dispatches sourceLifecycle.removed for every remaining binding', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-1', sourceId: 'src-1'});
- bridge.bind({captureId: 'cap-2', sourceId: 'src-2'});
- dispatched.length = 0;
-
- bridge.dispose();
-
- expect(dispatched.map((event) => event.type)).toEqual(['sourceLifecycle.removed', 'sourceLifecycle.removed']);
- expect(dispatched.flatMap((event) => (event.type === 'sourceLifecycle.removed' ? [event.sourceId] : []))).toEqual([
- 'src-1',
- 'src-2',
- ]);
- });
-
- it('dispose is re-entrant safe and does not re-dispatch removals', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- let reentrant: VoiceEngineV2AppSourceLifecycleBridge | null = null;
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => {
- dispatched.push(event);
- if (event.type === 'sourceLifecycle.removed') reentrant?.dispose();
- },
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-reentrant', sourceId: 'src-reentrant'});
- dispatched.length = 0;
- reentrant = bridge;
-
- bridge.dispose();
-
- expect(dispatched.map((event) => event.type)).toEqual(['sourceLifecycle.removed']);
- expect(binding.listenerCount()).toBe(0);
- });
-
- it('dispose unsubscribes from the native binding', () => {
- const binding = createMockNativeBinding();
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: () => {},
- subscribe: binding.subscribe,
- });
-
- expect(binding.listenerCount()).toBe(1);
- bridge.dispose();
- expect(binding.listenerCount()).toBe(0);
- });
-
- it('rejects malformed native lifecycle payloads', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-bad', sourceId: 'src-bad'});
- dispatched.length = 0;
-
- const badPayloads = [
- null,
- {captureId: '', kind: 'error', message: 'x'},
- {captureId: 'cap-bad', kind: 'bogus', message: 'x'},
- {captureId: 'cap-bad', kind: 42, message: 'x'},
- ] as unknown as Array<NativeScreenCaptureLifecycleMessage>;
- for (const payload of badPayloads) {
- binding.dispatch(payload);
- }
-
- expect(dispatched).toHaveLength(0);
- bridge.dispose();
- });
-
- it('bind dispatches an active lifecycle event for a microphone source', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- now: () => 5000,
- });
-
- const ok = bridge.bind({captureId: 'mic-capture-1', sourceId: 'mic-source-1'});
- expect(ok).toBe(true);
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].sourceId).toBe('mic-source-1');
- expect(dispatched[0].kind).toBe('active');
- expect(dispatched[0].fault).toBeNull();
- }
- bridge.dispose();
- });
-
- it('bind dispatches an active lifecycle event for a camera source', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- now: () => 5000,
- });
-
- const ok = bridge.bind({captureId: 'cam-capture-1', sourceId: 'cam-source-1'});
- expect(ok).toBe(true);
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].sourceId).toBe('cam-source-1');
- expect(dispatched[0].kind).toBe('active');
- expect(dispatched[0].fault).toBeNull();
- }
- bridge.dispose();
- });
-
- it('clean closed reason does not trigger reconnect FSM', () => {
- const binding = createMockNativeBinding();
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => host.dispatch(event),
- subscribe: binding.subscribe,
- });
-
- expect(bridge.bind({captureId: 'cap-clean', sourceId: 'src-clean'})).toBe(true);
- expect(host.snapshot.sourceLifecycles['src-clean']?.kind).toBe('active');
-
- binding.dispatch({captureId: 'cap-clean', kind: 'closed-clean', message: 'user stopped'});
-
- const stateAfterClean = host.snapshot.sourceLifecycles['src-clean'];
- expect(stateAfterClean?.kind).toBe('active');
- bridge.dispose();
- });
-
- it('error closed reason triggers reconnect FSM with captureDeviceLost', () => {
- const binding = createMockNativeBinding();
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => host.dispatch(event),
- subscribe: binding.subscribe,
- });
-
- expect(bridge.bind({captureId: 'cap-err', sourceId: 'src-err'})).toBe(true);
- binding.dispatch({captureId: 'cap-err', kind: 'closed', message: 'device unplugged'});
-
- const reconnecting = host.snapshot.sourceLifecycles['src-err'];
- expect(reconnecting?.kind).toBe('reconnecting');
- if (reconnecting?.kind === 'reconnecting') {
- expect(reconnecting.lastFault).toBe('captureDeviceLost');
- expect(reconnecting.attempts).toBe(1);
- }
- bridge.dispose();
- });
-
- it('reportLifecycle routes non-IPC fault into the FSM', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- bridge.bind({captureId: 'cap-report', sourceId: 'src-report'});
- dispatched.length = 0;
- bridge.reportLifecycle({captureId: 'cap-report', kind: 'error', message: 'track ended'});
-
- expect(dispatched).toHaveLength(1);
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].kind).toBe('reconnecting');
- expect(dispatched[0].fault).toBe('captureDeviceLost');
- }
- bridge.dispose();
- });
-
- it('bindRemoteTrackLifecycle dispatches active state for a remote screen-share', () => {
- const binding = createMockNativeBinding();
- const track = createFakeRemoteTrack();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- now: () => 7777,
- });
-
- const unbind = bridge.bindRemoteTrackLifecycle(track, {
- captureId: 'watch:remote-screen-share:user_1_aaa:SCR1',
- sourceId: 'watch:remote-screen-share:user_1_aaa:SCR1',
- });
-
- expect(typeof unbind).toBe('function');
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].sourceId).toBe('watch:remote-screen-share:user_1_aaa:SCR1');
- expect(dispatched[0].kind).toBe('active');
- expect(dispatched[0].fault).toBeNull();
- }
- unbind();
- bridge.dispose();
- });
-
- it('track ended on a remote screen-share dispatches networkError lifecycle event', () => {
- const binding = createMockNativeBinding();
- const track = createFakeRemoteTrack();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- const unbind = bridge.bindRemoteTrackLifecycle(track, {
- captureId: 'watch:remote-screen-share:user_1_bbb:SCR2',
- sourceId: 'watch:remote-screen-share:user_1_bbb:SCR2',
- });
- dispatched.length = 0;
-
- track.emit('ended');
-
- expect(dispatched).toHaveLength(1);
- expect(dispatched[0]?.type).toBe('sourceLifecycle.transitioned');
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].kind).toBe('reconnecting');
- expect(dispatched[0].fault).toBe('networkError');
- expect(dispatched[0].attempts).toBe(1);
- expect(dispatched[0].sourceId).toBe('watch:remote-screen-share:user_1_bbb:SCR2');
- }
- unbind();
- bridge.dispose();
- });
-
- it('bindRemoteTrackLifecycle unbind removes the binding and stops forwarding', () => {
- const binding = createMockNativeBinding();
- const track = createFakeRemoteTrack();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- const unbind = bridge.bindRemoteTrackLifecycle(track, {
- captureId: 'watch:remote-camera:user_1_ccc:CAM3',
- sourceId: 'watch:remote-camera:user_1_ccc:CAM3',
- });
- unbind();
- dispatched.length = 0;
-
- track.emit('ended');
-
- expect(dispatched).toHaveLength(0);
- expect(track.listenerCount('ended')).toBe(0);
- bridge.dispose();
- });
-
- it('multiple watched remote tracks dispatch independently per captureId', () => {
- const binding = createMockNativeBinding();
- const trackA = createFakeRemoteTrack();
- const trackB = createFakeRemoteTrack();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- });
-
- const unbindA = bridge.bindRemoteTrackLifecycle(trackA, {
- captureId: 'watch:remote-screen-share:user_1_aaa:SCRA',
- sourceId: 'watch:remote-screen-share:user_1_aaa:SCRA',
- });
- const unbindB = bridge.bindRemoteTrackLifecycle(trackB, {
- captureId: 'watch:remote-screen-share:user_1_bbb:SCRB',
- sourceId: 'watch:remote-screen-share:user_1_bbb:SCRB',
- });
- dispatched.length = 0;
-
- trackA.emit('ended');
-
- expect(dispatched).toHaveLength(1);
- if (dispatched[0]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[0].sourceId).toBe('watch:remote-screen-share:user_1_aaa:SCRA');
- expect(dispatched[0].fault).toBe('networkError');
- }
-
- trackB.emit('ended');
-
- expect(dispatched).toHaveLength(2);
- if (dispatched[1]?.type === 'sourceLifecycle.transitioned') {
- expect(dispatched[1].sourceId).toBe('watch:remote-screen-share:user_1_bbb:SCRB');
- expect(dispatched[1].fault).toBe('networkError');
- }
-
- unbindA();
- unbindB();
- bridge.dispose();
- });
-
- it('atMs is sourced from the injected now function', () => {
- const binding = createMockNativeBinding();
- const now = createFixedNow();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- now: now.next,
- });
-
- bridge.bind({captureId: 'cap-t', sourceId: 'src-t'});
- now.advance(500);
- binding.dispatch({captureId: 'cap-t', kind: 'error', message: ''});
-
- expect(dispatched).toHaveLength(2);
- const first = dispatched[0];
- const second = dispatched[1];
- if (first?.type !== 'sourceLifecycle.transitioned') throw new Error('expected sourceLifecycle.transitioned');
- if (second?.type !== 'sourceLifecycle.transitioned') throw new Error('expected sourceLifecycle.transitioned');
- expect(first.atMs).toBe(1000);
- expect(second.atMs).toBe(1500);
- bridge.dispose();
- });
-
- it('programmatic stop synthesizes closed-clean event for screen-share source', () => {
- const binding = createMockNativeBinding();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const closedCleans: Array<VoiceEngineV2AppSourceLifecycleClosedCleanInfo> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- onClosedClean: (info) => closedCleans.push(info),
- now: () => 9_000,
- });
-
- bridge.bind({captureId: 'cap-screen', sourceId: 'src-screen'});
- dispatched.length = 0;
-
- binding.dispatch({
- captureId: 'cap-screen',
- kind: 'closed-clean',
- message: 'programmatic-stop',
- source: 'programmatic',
- });
-
- expect(closedCleans).toHaveLength(1);
- expect(closedCleans[0]?.captureId).toBe('cap-screen');
- expect(closedCleans[0]?.sourceId).toBe('src-screen');
- expect(closedCleans[0]?.source).toBe('programmatic');
- expect(closedCleans[0]?.atMs).toBe(9_000);
- expect(dispatched).toHaveLength(0);
- bridge.dispose();
- });
-
- it('delegate-fired and programmatic-synthesized events are deduped within a window', () => {
- const binding = createMockNativeBinding();
- const now = createFixedNow();
- const dispatched: Array<VoiceEngineV2Event> = [];
- const closedCleans: Array<VoiceEngineV2AppSourceLifecycleClosedCleanInfo> = [];
- const bridge = new VoiceEngineV2AppSourceLifecycleBridge({
- dispatch: (event) => dispatched.push(event),
- subscribe: binding.subscribe,
- onClosedClean: (info) => closedCleans.push(info),
- now: now.next,
- });
-
- bridge.bind({captureId: 'cap-dup', sourceId: 'src-dup'});
- dispatched.length = 0;
-
- binding.dispatch({
- captureId: 'cap-dup',
- kind: 'closed-clean',
- message: 'user stopped',
- source: 'delegate',
- });
- now.advance(100);
- binding.dispatch({
- captureId: 'cap-dup',
- kind: 'closed-clean',
- message: 'programmatic-stop',
- source: 'programmatic',
- });
-
- expect(closedCleans).toHaveLength(1);
- expect(closedCleans[0]?.source).toBe('delegate');
- expect(dispatched).toHaveLength(0);
-
- now.advance(500);
- binding.dispatch({
- captureId: 'cap-dup',
- kind: 'closed-clean',
- message: 'second-cycle stop',
- source: 'programmatic',
- });
- expect(closedCleans).toHaveLength(2);
- expect(closedCleans[1]?.source).toBe('programmatic');
- bridge.dispose();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.test.ts
deleted file mode 100644
index e5e7b64bb..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter.test.ts
+++ /dev/null
@@ -1,459 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type PerTrackStats,
- type TransportInfo,
- VoiceEngineV2AppStatsHostAdapter,
- type VoiceEngineV2AppStatsHostAdapterScheduler,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppStatsHostAdapter';
-import {classifyVoiceEngineV2TrackStats} from '@fluxer/voice_engine_v2';
-import type {Room} from 'livekit-client';
-import {describe, expect, it} from 'vitest';
-
-interface FakeScheduler extends VoiceEngineV2AppStatsHostAdapterScheduler {
- runStatsTick(): void;
-}
-
-function createScheduler(): FakeScheduler {
- const handlers = new Map<number, () => void>();
- return {
- setInterval(handler, intervalMs) {
- handlers.set(intervalMs, handler);
- return intervalMs;
- },
- clearInterval(handle) {
- handlers.delete(handle as number);
- },
- runStatsTick() {
- handlers.get(2000)?.();
- },
- };
-}
-
-function chromiumCameraSimulcastReports(bytesSentByRid: Record<string, number>): Map<string, unknown> {
- return new Map<string, unknown>([
- [
- 'SV1',
- {
- type: 'media-source',
- id: 'SV1',
- kind: 'video',
- trackIdentifier: 'cam-track',
- width: 1280,
- height: 720,
- framesPerSecond: 30,
- frames: 1801,
- },
- ],
- ['C1', {type: 'codec', id: 'C1', mimeType: 'video/H264', payloadType: 108}],
- [
- 'OT01V1',
- {
- type: 'outbound-rtp',
- id: 'OT01V1',
- kind: 'video',
- ssrc: 1001,
- rid: 'q',
- mid: '2',
- active: false,
- mediaSourceId: 'SV1',
- codecId: 'C1',
- bytesSent: bytesSentByRid.q,
- framesEncoded: 1,
- targetBitrate: 0,
- qualityLimitationReason: 'none',
- },
- ],
- [
- 'OT01V2',
- {
- type: 'outbound-rtp',
- id: 'OT01V2',
- kind: 'video',
- ssrc: 1002,
- rid: 'h',
- mid: '2',
- active: false,
- mediaSourceId: 'SV1',
- codecId: 'C1',
- bytesSent: bytesSentByRid.h,
- framesEncoded: 1,
- targetBitrate: 0,
- qualityLimitationReason: 'none',
- },
- ],
- [
- 'OT01V3',
- {
- type: 'outbound-rtp',
- id: 'OT01V3',
- kind: 'video',
- ssrc: 1003,
- rid: 'f',
- mid: '2',
- active: true,
- mediaSourceId: 'SV1',
- codecId: 'C1',
- bytesSent: bytesSentByRid.f,
- framesEncoded: 1,
- frameWidth: 1280,
- frameHeight: 720,
- targetBitrate: 1133000,
- qualityLimitationReason: 'none',
- },
- ],
- ]);
-}
-
-async function collectChromiumCameraRows(
- samples: ReadonlyArray<{now: number; bytesSentByRid: Record<string, number>}>,
-): Promise<Array<PerTrackStats>> {
- const scheduler = createScheduler();
- let sampleIndex = 0;
- let now = samples[0].now;
- const publisher = {
- getStats() {
- return Promise.resolve(chromiumCameraSimulcastReports(samples[sampleIndex].bytesSentByRid));
- },
- };
- const adapter = new VoiceEngineV2AppStatsHostAdapter({now: () => now, scheduler});
- adapter.setRoom({engine: {pcManager: {publisher}}, numParticipants: 2} as unknown as Room);
- adapter.startStatsTracking();
- for (sampleIndex = 0; sampleIndex < samples.length; sampleIndex += 1) {
- now = samples[sampleIndex].now;
- scheduler.runStatsTick();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- }
- const rows = adapter.perTrackStats;
- adapter.cleanup();
- return rows;
-}
-
-describe('VoiceEngineV2AppStatsHostAdapter chromium outbound rows', () => {
- it('collects the outbound-rtp active flag for every simulcast layer', async () => {
- const rows = await collectChromiumCameraRows([{now: 1000, bytesSentByRid: {q: 0, h: 0, f: 5_000_000}}]);
-
- expect(rows.map((row) => row.rid)).toEqual(['q', 'h', 'f']);
- expect(rows.map((row) => row.active)).toEqual([false, false, true]);
- });
-
- it('omits the bitrate window on a first observation so a zero bitrate is not read as measured', async () => {
- const rows = await collectChromiumCameraRows([{now: 1000, bytesSentByRid: {q: 0, h: 0, f: 5_000_000}}]);
-
- expect(rows.map((row) => row.bitrateKbps)).toEqual([0, 0, 0]);
- expect(rows.map((row) => row.bitrateWindowMs)).toEqual([undefined, undefined, undefined]);
- });
-
- it('reports the bitrate window once a delta was measured so a zero bitrate is falsifiable', async () => {
- const rows = await collectChromiumCameraRows([
- {now: 1000, bytesSentByRid: {q: 0, h: 0, f: 5_000_000}},
- {now: 3001, bytesSentByRid: {q: 0, h: 0, f: 5_000_000}},
- ]);
-
- expect(rows.map((row) => row.bitrateKbps)).toEqual([0, 0, 0]);
- expect(rows.map((row) => row.bitrateWindowMs)).toEqual([2001, 2001, 2001]);
- });
-
- it('keeps every pre-existing chromium row field byte-identical', async () => {
- const rows = await collectChromiumCameraRows([
- {now: 1000, bytesSentByRid: {q: 0, h: 0, f: 5_000_000}},
- {now: 3000, bytesSentByRid: {q: 0, h: 0, f: 5_500_000}},
- ]);
- const {active, bitrateWindowMs, ...legacy} = rows[2];
-
- expect(legacy).toEqual({
- direction: 'send',
- kind: 'video',
- ssrc: 1003,
- rid: 'f',
- mid: '2',
- trackIdentifier: 'cam-track',
- mediaSourceId: 'SV1',
- codec: 'video/H264',
- payloadType: 108,
- bitrateKbps: 2000,
- framesEncoded: 1,
- frameWidth: 1280,
- frameHeight: 720,
- sourceFrameWidth: 1280,
- sourceFrameHeight: 720,
- sourceFramesPerSecond: 30,
- sourceFrames: 1801,
- targetBitrateKbps: 1133,
- qualityLimitationReason: 'none',
- encoderAcceleration: 'unknown',
- });
- });
-});
-
-function firefoxCameraAndScreenShareReports(): Map<string, unknown> {
- return new Map<string, unknown>([
- ['C1', {type: 'codec', id: 'C1', mimeType: 'video/H264', payloadType: 108}],
- ['C2', {type: 'codec', id: 'C2', mimeType: 'audio/opus', payloadType: 109}],
- [
- 'outbound_rtp_audio_1',
- {
- type: 'outbound-rtp',
- id: 'outbound_rtp_audio_1',
- kind: 'audio',
- ssrc: 724915693,
- mid: '1',
- codecId: 'C2',
- bytesSent: 100_000,
- },
- ],
- [
- 'outbound_rtp_video_3',
- {
- type: 'outbound-rtp',
- id: 'outbound_rtp_video_3',
- kind: 'video',
- ssrc: 4089824766,
- mid: '3',
- codecId: 'C1',
- bytesSent: 5_000_000,
- framesEncoded: 900,
- },
- ],
- [
- 'outbound_rtp_video_4',
- {
- type: 'outbound-rtp',
- id: 'outbound_rtp_video_4',
- kind: 'video',
- ssrc: 1477030229,
- mid: '4',
- codecId: 'C1',
- bytesSent: 2_000_000,
- framesEncoded: 600,
- },
- ],
- [
- 'inbound_rtp_audio_2',
- {
- type: 'inbound-rtp',
- id: 'inbound_rtp_audio_2',
- kind: 'audio',
- ssrc: 1661789229,
- mid: '2',
- codecId: 'C2',
- trackIdentifier: '{8a106956-d202-4916-8e19-0a1672c64b73}',
- bytesReceived: 50_000,
- },
- ],
- ]);
-}
-
-async function collectFirefoxRows(
- transceivers: ReadonlyArray<{mid: string | null; sender?: {track?: {id: string} | null} | null}> | null,
-): Promise<Array<PerTrackStats>> {
- const scheduler = createScheduler();
- const publisher = {
- getStats() {
- return Promise.resolve(firefoxCameraAndScreenShareReports());
- },
- ...(transceivers === null ? {} : {getTransceivers: () => transceivers}),
- };
- const adapter = new VoiceEngineV2AppStatsHostAdapter({now: () => 1000, scheduler});
- adapter.setRoom({engine: {pcManager: {publisher}}, numParticipants: 2} as unknown as Room);
- adapter.startStatsTracking();
- scheduler.runStatsTick();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- const rows = adapter.perTrackStats;
- adapter.cleanup();
- return rows;
-}
-
-describe('VoiceEngineV2AppStatsHostAdapter firefox outbound rows', () => {
- it('backfills the outbound trackIdentifier from the transceiver mid when the report carries neither identity member', async () => {
- const rows = await collectFirefoxRows([
- {mid: '1', sender: {track: {id: '{mic-track}'}}},
- {mid: '2', sender: {track: null}},
- {mid: '3', sender: {track: {id: '{camera-track}'}}},
- {mid: '4', sender: {track: {id: '{screen-track}'}}},
- ]);
-
- expect(rows.map((row) => [row.direction, row.kind, row.mid, row.trackIdentifier])).toEqual([
- ['send', 'audio', '1', '{mic-track}'],
- ['send', 'video', '3', '{camera-track}'],
- ['send', 'video', '4', '{screen-track}'],
- ['recv', 'audio', '2', '{8a106956-d202-4916-8e19-0a1672c64b73}'],
- ]);
- });
-
- it('leaves an outbound row unidentified when no transceiver carries its mid', async () => {
- const rows = await collectFirefoxRows([{mid: '3', sender: {track: {id: '{camera-track}'}}}]);
-
- expect(rows.map((row) => row.trackIdentifier)).toEqual([
- undefined,
- '{camera-track}',
- undefined,
- '{8a106956-d202-4916-8e19-0a1672c64b73}',
- ]);
- });
-
- it('keeps the inbound trackIdentifier when the source exposes no transceivers at all', async () => {
- const rows = await collectFirefoxRows(null);
-
- expect(rows.map((row) => row.trackIdentifier)).toEqual([
- undefined,
- undefined,
- undefined,
- '{8a106956-d202-4916-8e19-0a1672c64b73}',
- ]);
- });
-
- it('lets the classifier tell a firefox camera apart from a simultaneous screen share', async () => {
- const rows = await collectFirefoxRows([
- {mid: '1', sender: {track: {id: '{mic-track}'}}},
- {mid: '3', sender: {track: {id: '{camera-track}'}}},
- {mid: '4', sender: {track: {id: '{screen-track}'}}},
- ]);
- const classification = classifyVoiceEngineV2TrackStats({
- tracks: rows.map((row) => ({
- direction: row.direction,
- kind: row.kind,
- rid: row.rid,
- trackIdentifier: row.trackIdentifier,
- bitrateKbps: row.bitrateKbps,
- })),
- publications: {
- localCameraTrackId: '{camera-track}',
- localMicrophoneTrackId: '{mic-track}',
- localScreenShareTrackId: '{screen-track}',
- localScreenShareAudioTrackId: null,
- remoteMicrophoneTrackIds: [],
- remoteScreenShareTrackIds: [],
- remoteScreenShareAudioTrackIds: [],
- },
- });
-
- expect(rows[classification.localVideoTrackIndex!].mid).toBe('3');
- expect(rows[classification.localScreenShareTrackIndex!].mid).toBe('4');
- });
-});
-
-function chromiumWatchedScreenShareReports(): Map<string, unknown> {
- return new Map<string, unknown>([
- [
- 'C1',
- {
- type: 'codec',
- id: 'C1',
- mimeType: 'video/H264',
- payloadType: 108,
- sdpFmtpLine: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
- },
- ],
- [
- 'IT01V',
- {
- type: 'inbound-rtp',
- id: 'IT01V',
- kind: 'video',
- ssrc: 2001,
- mid: '5',
- codecId: 'C1',
- trackIdentifier: 'screen-share-track',
- bytesReceived: 3_500_000,
- packetsReceived: 4210,
- framesReceived: 0,
- framesDecoded: 0,
- keyFramesDecoded: 0,
- pliCount: 7,
- frameWidth: 1920,
- frameHeight: 1080,
- },
- ],
- [
- 'CP1',
- {
- type: 'candidate-pair',
- id: 'CP1',
- state: 'succeeded',
- nominated: true,
- selected: true,
- localCandidateId: 'LC1',
- remoteCandidateId: 'RC1',
- currentRoundTripTime: 0.023,
- },
- ],
- [
- 'LC1',
- {
- type: 'local-candidate',
- id: 'LC1',
- candidateType: 'relay',
- protocol: 'udp',
- relayProtocol: 'tls',
- url: 'turn:turn.fluxer.example:443?transport=tcp',
- networkType: 'wifi',
- },
- ],
- ['RC1', {type: 'remote-candidate', id: 'RC1', candidateType: 'host', protocol: 'udp'}],
- [
- 'T1',
- {type: 'transport', id: 'T1', dtlsState: 'connected', iceState: 'connected', selectedCandidatePairId: 'CP1'},
- ],
- ]);
-}
-
-async function collectWatchedScreenShareStats(): Promise<{
- rows: Array<PerTrackStats>;
- transport: TransportInfo | null;
-}> {
- const scheduler = createScheduler();
- const subscriber = {
- getStats() {
- return Promise.resolve(chromiumWatchedScreenShareReports());
- },
- };
- const adapter = new VoiceEngineV2AppStatsHostAdapter({now: () => 1000, scheduler});
- adapter.setRoom({
- engine: {pcManager: {subscriber, mode: 'subscriber-primary'}},
- numParticipants: 2,
- } as unknown as Room);
- adapter.startStatsTracking();
- scheduler.runStatsTick();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- const rows = adapter.perTrackStats;
- const transport = adapter.subscriberTransport;
- adapter.cleanup();
- return {rows, transport};
-}
-
-describe('VoiceEngineV2AppStatsHostAdapter watched screen share rows', () => {
- it('collects the inbound packet, byte and frame counters that tell a stalled decode apart from a dead feed', async () => {
- const {rows} = await collectWatchedScreenShareStats();
-
- expect(rows.map((row) => [row.packetsReceived, row.bytesReceived, row.framesReceived, row.framesDecoded])).toEqual([
- [4210, 3_500_000, 0, 0],
- ]);
- });
-
- it('collects the codec sdp fmtp line of the receive row', async () => {
- const {rows} = await collectWatchedScreenShareStats();
-
- expect(rows[0].codecSdpFmtpLine).toBe('level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f');
- });
-
- it('collects the relay protocol of the selected local candidate, which the local protocol never shows', async () => {
- const {transport} = await collectWatchedScreenShareStats();
-
- expect(transport?.localProtocol).toBe('udp');
- expect(transport?.localRelayProtocol).toBe('tls');
- expect(transport?.localCandidateUrlHost).toBe('turn.fluxer.example');
- });
-
- it('collects the peer connection mode alongside the transport block', async () => {
- const {transport} = await collectWatchedScreenShareStats();
-
- expect(transport?.peerConnectionMode).toBe('subscriber-primary');
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.test.ts
deleted file mode 100644
index d4d7edb4d..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter.test.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createVoiceEngineV2AppTimerAdapter,
- VOICE_ENGINE_V2_TIMER_REGISTRY_CAP,
- type VoiceEngineV2AppTimerFireEvent,
- type VoiceEngineV2AppTimerHandle,
- VoiceEngineV2AppTimerRegistryFullError,
- type VoiceEngineV2AppTimerScheduler,
-} from '@app/features/voice/engine/v2/VoiceEngineV2AppTimerAdapter';
-import {createVoiceEngineV2DeterministicClockPort} from '@fluxer/voice_engine_v2/runtime';
-import {describe, expect, it} from 'vitest';
-
-interface FakeTimer {
- id: number;
- callback: () => void;
- ms: number;
- cleared: boolean;
-}
-
-interface FakeScheduler extends VoiceEngineV2AppTimerScheduler {
- readonly timers: ReadonlyArray<FakeTimer>;
- fireById(id: number): void;
- pendingCount(): number;
-}
-
-function createFakeScheduler(): FakeScheduler {
- const timers: Array<FakeTimer> = [];
- let nextId = 1;
- return {
- get timers() {
- return timers;
- },
- setTimeout(callback, ms): VoiceEngineV2AppTimerHandle {
- const timer: FakeTimer = {id: nextId++, callback, ms, cleared: false};
- timers.push(timer);
- return timer;
- },
- clearTimeout(handle): void {
- const timer = handle as FakeTimer;
- timer.cleared = true;
- },
- fireById(id): void {
- const timer = timers.find((t) => t.id === id);
- if (timer === undefined) throw new Error(`no fake timer with id=${id}`);
- if (timer.cleared) throw new Error(`fake timer id=${id} was cleared; refuse to fire`);
- timer.callback();
- },
- pendingCount(): number {
- return timers.filter((t) => !t.cleared).length;
- },
- };
-}
-
-describe('VoiceEngineV2AppTimerAdapter', () => {
- it('schedule registers a setTimeout and removes the entry on fire', async () => {
- const scheduler = createFakeScheduler();
- const fires: Array<VoiceEngineV2AppTimerFireEvent> = [];
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(100, 1),
- scheduler,
- onFire: (event) => fires.push(event),
- });
-
- await adapter.schedule({timerId: 't1', delayMs: 250});
- expect(scheduler.timers).toEqual([{id: 1, callback: expect.any(Function), ms: 250, cleared: false}]);
-
- scheduler.fireById(1);
-
- expect(fires).toEqual([{timerId: 't1', scheduledAtMs: 100, firedAtMs: 101}]);
- await adapter.cancel('t1');
- expect(scheduler.timers[0].cleared).toBe(false);
- });
-
- it('cancel before fire clears the underlying timeout and forgets the entry', async () => {
- const scheduler = createFakeScheduler();
- const fires: Array<VoiceEngineV2AppTimerFireEvent> = [];
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- onFire: (event) => fires.push(event),
- });
-
- await adapter.schedule({timerId: 't1', delayMs: 500});
- await adapter.cancel('t1');
-
- expect(scheduler.timers[0].cleared).toBe(true);
- expect(fires).toEqual([]);
- });
-
- it('cancel after fire is an idempotent no-op (no extra clearTimeout, no exception)', async () => {
- const scheduler = createFakeScheduler();
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- });
-
- await adapter.schedule({timerId: 't1', delayMs: 100});
- scheduler.fireById(1);
- await adapter.cancel('t1');
- await adapter.cancel('t1');
- await adapter.cancel('never-existed');
-
- expect(scheduler.timers[0].cleared).toBe(false);
- });
-
- it('rejects schedule with the structured timerRegistryFull error when the cap is exceeded', async () => {
- const scheduler = createFakeScheduler();
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- registryCap: 2,
- });
-
- await adapter.schedule({timerId: 'a', delayMs: 100});
- await adapter.schedule({timerId: 'b', delayMs: 100});
-
- await expect(adapter.schedule({timerId: 'c', delayMs: 100})).rejects.toMatchObject({
- code: 'timerRegistryFull',
- capability: 'timer',
- timerId: 'c',
- cap: 2,
- });
- await expect(adapter.schedule({timerId: 'c', delayMs: 100})).rejects.toBeInstanceOf(
- VoiceEngineV2AppTimerRegistryFullError,
- );
- expect(scheduler.pendingCount()).toBe(2);
- });
-
- it('tracks multiple concurrent timers independently and fires them in scheduler order', async () => {
- const scheduler = createFakeScheduler();
- const fires: Array<VoiceEngineV2AppTimerFireEvent> = [];
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(1_000, 5),
- scheduler,
- onFire: (event) => fires.push(event),
- });
-
- await adapter.schedule({timerId: 'first', delayMs: 100});
- await adapter.schedule({timerId: 'second', delayMs: 200});
- await adapter.schedule({timerId: 'third', delayMs: 300});
-
- scheduler.fireById(2);
- scheduler.fireById(1);
- scheduler.fireById(3);
-
- expect(fires.map((f) => f.timerId)).toEqual(['second', 'first', 'third']);
- expect(fires[0].scheduledAtMs).toBe(1_005);
- expect(fires[1].scheduledAtMs).toBe(1_000);
- expect(fires[2].scheduledAtMs).toBe(1_010);
- });
-
- it('produces a deterministic registry state for identical schedule sequences', async () => {
- function runOnce(): ReadonlyArray<{timerId: string; scheduledAtMs: number; firedAtMs: number}> {
- const scheduler = createFakeScheduler();
- const fires: Array<VoiceEngineV2AppTimerFireEvent> = [];
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 2),
- scheduler,
- onFire: (event) => fires.push(event),
- });
- void adapter.schedule({timerId: 'a', delayMs: 10});
- void adapter.schedule({timerId: 'b', delayMs: 20});
- scheduler.fireById(1);
- scheduler.fireById(2);
- return fires.slice();
- }
- expect(runOnce()).toEqual(runOnce());
- });
-
- it('removes the entry from the registry as part of the setTimeout callback', async () => {
- const scheduler = createFakeScheduler();
- let observedDuringFire: number | null = null;
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- onFire: () => {
- observedDuringFire = scheduler.pendingCount();
- },
- });
-
- await adapter.schedule({timerId: 't1', delayMs: 100});
- scheduler.fireById(1);
-
- await adapter.schedule({timerId: 't2', delayMs: 100});
- expect(scheduler.timers).toHaveLength(2);
- expect(observedDuringFire).toBe(1);
- });
-
- it('rejects invalid timer options (empty id, zero delay, non-finite delay, oversized id)', async () => {
- const scheduler = createFakeScheduler();
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- });
-
- await expect(adapter.schedule({timerId: '', delayMs: 100})).rejects.toThrow(/must not be empty/);
- await expect(adapter.schedule({timerId: 't1', delayMs: 0})).rejects.toThrow(/positive/);
- await expect(adapter.schedule({timerId: 't1', delayMs: Number.NaN})).rejects.toThrow(/finite/);
- await expect(adapter.schedule({timerId: 't1', delayMs: 100, repeat: true})).rejects.toThrow(/repeat=true/);
- expect(scheduler.timers).toEqual([]);
- });
-
- it('exposes the documented registry cap default and enforces it as the upper bound', async () => {
- expect(VOICE_ENGINE_V2_TIMER_REGISTRY_CAP).toBe(256);
- const scheduler = createFakeScheduler();
- const adapter = createVoiceEngineV2AppTimerAdapter({
- clock: createVoiceEngineV2DeterministicClockPort(0, 0),
- scheduler,
- });
-
- for (let i = 0; i < VOICE_ENGINE_V2_TIMER_REGISTRY_CAP; i++) {
- await adapter.schedule({timerId: `t${i}`, delayMs: 1});
- }
- await expect(adapter.schedule({timerId: 'overflow', delayMs: 1})).rejects.toBeInstanceOf(
- VoiceEngineV2AppTimerRegistryFullError,
- );
- expect(scheduler.pendingCount()).toBe(VOICE_ENGINE_V2_TIMER_REGISTRY_CAP);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppVoiceStateAdapter.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppVoiceStateAdapter.test.ts
deleted file mode 100644
index 609863af3..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppVoiceStateAdapter.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {GuildReadyData} from '@app/features/gateway/types/GatewayGuildTypes';
-import type {VoiceState} from '@app/features/gateway/types/GatewayVoiceTypes';
-import {Logger} from '@app/features/platform/utils/AppLogger';
-import {VoiceEngineV2AppVoiceStateAdapter} from '@app/features/voice/engine/v2/VoiceEngineV2AppVoiceStateAdapter';
-import {autorun} from 'mobx';
-import {describe, expect, it, vi} from 'vitest';
-
-function voiceState(overrides: Partial<VoiceState> = {}): VoiceState {
- return {
- guild_id: 'guild-1',
- channel_id: 'channel-1',
- user_id: 'user-1',
- connection_id: 'connection-1',
- mute: false,
- deaf: false,
- self_mute: false,
- self_deaf: false,
- self_video: false,
- self_stream: false,
- viewer_stream_keys: [],
- ...overrides,
- };
-}
-
-function guild(id: string, voiceStates: ReadonlyArray<VoiceState> = []): GuildReadyData {
- return {
- id,
- properties: {} as GuildReadyData['properties'],
- channels: [],
- emojis: [],
- members: [],
- member_count: 0,
- voice_states: voiceStates,
- roles: [],
- joined_at: '2026-01-01T00:00:00.000Z',
- };
-}
-
-describe('VoiceEngineV2AppVoiceStateAdapter', () => {
- it('keeps gateway voice-state indexes as immutable replacement projections', () => {
- const adapter = new VoiceEngineV2AppVoiceStateAdapter();
- adapter.handleGatewayReady([
- guild('guild-1', [voiceState({connection_id: 'connection-1', channel_id: 'channel-1'})]),
- ]);
- const before = adapter.getConnectionVoiceStates();
- const beforeConnection = before['connection-1'];
-
- adapter.handleGatewayVoiceStateUpdate(
- 'guild-1',
- voiceState({connection_id: 'connection-1', channel_id: 'channel-2'}),
- );
-
- const after = adapter.getConnectionVoiceStates();
- expect(after).not.toBe(before);
- expect(after['connection-1']).not.toBe(beforeConnection);
- expect(adapter.getAllVoiceStatesInChannel('guild-1', 'channel-1')['connection-1']).toBeUndefined();
- expect(adapter.getAllVoiceStatesInChannel('guild-1', 'channel-2')['connection-1']).toBe(after['connection-1']);
- });
-
- it('does not reinsert locally removed stale connections', () => {
- const debug = vi.spyOn(Logger.prototype, 'debug').mockImplementation(() => undefined);
- try {
- const adapter = new VoiceEngineV2AppVoiceStateAdapter();
- adapter.handleGatewayVoiceStateUpdate('guild-1', voiceState({connection_id: 'stale-connection'}));
- expect(adapter.getVoiceStateByConnectionId('stale-connection')).toBeDefined();
-
- adapter.removeVoiceStateConnection('stale-connection');
- adapter.handleGatewayVoiceStateUpdate('guild-1', voiceState({connection_id: 'stale-connection'}));
-
- expect(adapter.isConnectionIgnored('stale-connection')).toBe(true);
- expect(adapter.getVoiceStateByConnectionId('stale-connection')).toBeNull();
- expect(adapter.getAllVoiceStatesInChannel('guild-1', 'channel-1')['stale-connection']).toBeUndefined();
- expect(debug).toHaveBeenCalledExactlyOnceWith('Ignored voice state update for locally removed connection', {
- guildId: 'guild-1',
- channelId: 'channel-1',
- userId: 'user-1',
- connectionId: 'stale-connection',
- });
- } finally {
- debug.mockRestore();
- }
- });
-
- it('publishes self-video true-to-false changes through MobX observation', () => {
- const adapter = new VoiceEngineV2AppVoiceStateAdapter();
- const observed: Array<boolean | undefined> = [];
- const dispose = autorun(() => {
- observed.push(adapter.getAllVoiceStatesInChannel('guild-1', 'channel-1')['connection-1']?.self_video);
- });
-
- adapter.handleGatewayVoiceStateUpdate('guild-1', voiceState({self_video: true}));
- adapter.handleGatewayVoiceStateUpdate('guild-1', voiceState({self_video: false}));
-
- dispose();
- expect(observed).toEqual([undefined, true, false]);
- expect(adapter.getAllVoiceStatesInChannel('guild-1', 'channel-1')['connection-1']?.self_video).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts.test.ts
deleted file mode 100644
index 8eb18ce2f..000000000
--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createVoiceEngineV2AppTestControllerHost} from '@app/features/voice/engine/v2/VoiceEngineV2AppControllerHostTestUtils';
-import {
- createVoiceEngineV2ShadowHostPorts,
- type VoiceEngineV2ShadowHostPortCall,
-} from '@app/features/voice/engine/v2/VoiceEngineV2ShadowHostPorts';
-import {waitForRuntime} from '@fluxer/voice_engine_v2/testing';
-import {describe, expect, it} from 'vitest';
-
-describe('VoiceEngineV2ShadowHostPorts', () => {
- it('records v2 command intent while returning deterministic host results', async () => {
- const calls: Array<VoiceEngineV2ShadowHostPortCall> = [];
- const host = createVoiceEngineV2AppTestControllerHost({
- ports: createVoiceEngineV2ShadowHostPorts({
- record(call) {
- calls.push(call);
- },
- }),
- });
-
- host.controller.connect({url: 'wss://voice.example.test', token: 'token'});
- await waitForRuntime();
- host.controller.checkPermission('microphone');
- await waitForRuntime();
- host.controller.enumerateDevices();
- await waitForRuntime();
- host.controller.queryHardwareEncoderCapabilities();
- await waitForRuntime();
- host.controller.collectStats();
- await waitForRuntime();
-
- expect(calls.map((call) => call.type)).toEqual([
- 'liveKit.connect',
- 'permissions.check',
- 'devices.enumerate',
- 'capabilities.getHardwareEncoderCapabilities',
- 'liveKit.collectStats',
- ]);
- expect(host.model.connection.connected).toBe(true);
- expect(host.model.permissions.microphone).toEqual({
- name: 'microphone',
- status: 'unknown',
- canPrompt: true,
- });
- expect(host.model.devices).toEqual({
- audioInputs: [],
- audioOutputs: [],
- cameras: [],
- selectedAudioInputId: null,
- selectedAudioOutputId: null,
- selectedCameraId: null,
- });
- expect(host.model.stats).toEqual({rttMs: null, outbound: [], inbound: []});
- expect(host.snapshot.hardwareEncoder.capabilities).toMatchObject({
- available: false,
- backend: 'none',
- reason: 'shadow-host',
- });
-
- host.dispose();
- });
-});
diff --git a/fluxer_app/src/features/voice/engine/voice_screen_share_manager/shared.test.ts b/fluxer_app/src/features/voice/engine/voice_screen_share_manager/shared.test.ts
deleted file mode 100644
index e174dc9f7..000000000
--- a/fluxer_app/src/features/voice/engine/voice_screen_share_manager/shared.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- findStalledVideoEncoder,
- scheduleScreenShareEncoderVerification,
- shouldTriggerSoftwareEncoderWarning,
-} from '@app/features/voice/engine/voice_screen_share_manager/shared';
-import SoftwareEncoderWarning from '@app/features/voice/state/SoftwareEncoderWarning';
-import VoiceSettings from '@app/features/voice/state/VoiceSettings';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/features/voice/utils/VideoQualityEntitlement', () => ({hasHigherVideoQuality: () => false}));
-
-let h264Acceleration = 'hardware';
-const markSoftwareEncodeObserved = vi.fn();
-
-vi.mock('@app/features/voice/utils/CodecCapabilityDetector', () => ({
- adjustScreenShareEncodingForCodec: (encoding: unknown) => encoding,
- getCodecCapabilityReport: () => ({
- vp8: {hardwareAccelerated: 'software'},
- vp9: {hardwareAccelerated: 'software'},
- h264: {hardwareAccelerated: h264Acceleration},
- h265: {hardwareAccelerated: 'software'},
- av1: {hardwareAccelerated: 'software'},
- }),
- markScreenShareCodecSoftwareEncodeObserved: (codec: string) => markSoftwareEncodeObserved(codec),
- resolveVideoPublishCodecPolicy: (requested: string) => ({
- allowed: [requested],
- requested,
- primary: requested,
- backupCodec: false,
- }),
-}));
-
-function makeStats(entries: ReadonlyArray<Record<string, unknown>>): RTCStatsReport {
- return new Map(entries.map((entry) => [entry.id as string, entry])) as unknown as RTCStatsReport;
-}
-
-const CODEC_REPORT = {type: 'codec', id: 'codec-h264', mimeType: 'video/H264'};
-const SOURCE_REPORT = {type: 'media-source', id: 'source-1', kind: 'video', frames: 240, framesPerSecond: 30};
-
-function outboundReport(overrides: Record<string, unknown>): Record<string, unknown> {
- return {
- type: 'outbound-rtp',
- id: 'outbound-1',
- kind: 'video',
- codecId: 'codec-h264',
- mediaSourceId: 'source-1',
- framesEncoded: 0,
- framesSent: 0,
- ...overrides,
- };
-}
-
-describe('findStalledVideoEncoder', () => {
- test('reports a stall when the encoding is active and the source is producing frames', () => {
- const stats = makeStats([CODEC_REPORT, SOURCE_REPORT, outboundReport({active: true})]);
- expect(findStalledVideoEncoder(stats, 'h264')).toEqual({
- codec: 'h264',
- framesEncoded: 0,
- framesSent: 0,
- sourceFrames: 240,
- sourceFramesPerSecond: 30,
- });
- });
-
- test('ignores an encoding the SFU deactivated even though the source is producing frames', () => {
- const stats = makeStats([CODEC_REPORT, SOURCE_REPORT, outboundReport({active: false})]);
- expect(findStalledVideoEncoder(stats, 'h264')).toBeNull();
- });
-
- test('still reports a stall when active is absent, as on Firefox', () => {
- const stats = makeStats([CODEC_REPORT, SOURCE_REPORT, outboundReport({})]);
- expect(findStalledVideoEncoder(stats, 'h264')?.codec).toBe('h264');
- });
-
- test('skips a deactivated layer and reports the still-active sibling instead', () => {
- const stats = makeStats([
- CODEC_REPORT,
- SOURCE_REPORT,
- {type: 'media-source', id: 'source-low', kind: 'video', frames: 90, framesPerSecond: 15},
- outboundReport({id: 'outbound-low', mediaSourceId: 'source-low', active: false}),
- outboundReport({id: 'outbound-high', active: true}),
- ]);
- expect(findStalledVideoEncoder(stats, 'h264')?.sourceFrames).toBe(240);
- });
-});
-
-describe('the screen share encoder verification', () => {
- function openH264Stats(): RTCStatsReport {
- return makeStats([
- CODEC_REPORT,
- SOURCE_REPORT,
- outboundReport({
- active: true,
- framesEncoded: 120,
- framesSent: 120,
- encoderImplementation: 'OpenH264',
- powerEfficientEncoder: false,
- }),
- ]);
- }
-
- async function verifyOpenH264Share(): Promise<void> {
- scheduleScreenShareEncoderVerification(async () => openH264Stats(), 'h264');
- await vi.advanceTimersByTimeAsync(2500);
- }
-
- beforeEach(() => {
- vi.useFakeTimers();
- h264Acceleration = 'hardware';
- markSoftwareEncodeObserved.mockClear();
- SoftwareEncoderWarning.reset();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- vi.restoreAllMocks();
- SoftwareEncoderWarning.reset();
- });
-
- test('records a software session verdict when the encoder turns out to be OpenH264', async () => {
- await verifyOpenH264Share();
- expect(markSoftwareEncodeObserved).toHaveBeenCalledWith('h264');
- });
-
- test('warns about the software encoder while the capability layer still claims hardware', async () => {
- await verifyOpenH264Share();
- expect(SoftwareEncoderWarning.showWarning).toBe(true);
- });
-
- test('does not warn once the session verdict says the codec encodes in software', async () => {
- h264Acceleration = 'software';
- await verifyOpenH264Share();
- expect(SoftwareEncoderWarning.showWarning).toBe(false);
- expect(markSoftwareEncodeObserved).toHaveBeenCalledWith('h264');
- });
-
- test('records no verdict when the user asked for the software encoder', async () => {
- vi.spyOn(VoiceSettings, 'getScreenShareEncoderMode').mockReturnValue('software');
- await verifyOpenH264Share();
- expect(markSoftwareEncodeObserved).not.toHaveBeenCalled();
- });
-});
-
-describe('the software encoder warning gate', () => {
- test('stays quiet once the session verdict says the codec encodes in software', () => {
- h264Acceleration = 'software';
- expect(shouldTriggerSoftwareEncoderWarning('h264')).toBe(false);
- });
-
- test('still speaks up while the capability layer claims hardware', () => {
- h264Acceleration = 'hardware';
- expect(shouldTriggerSoftwareEncoderWarning('h264')).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/events/EntranceSoundPlay.test.ts b/fluxer_app/src/features/voice/events/EntranceSoundPlay.test.ts
deleted file mode 100644
index 911706305..000000000
--- a/fluxer_app/src/features/voice/events/EntranceSoundPlay.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {GatewayHandlerContext} from '@app/features/gateway/events/EventRouter';
-import EntranceSoundPlaybackEngine from '@app/features/voice/engine/EntranceSoundPlaybackEngine';
-import MediaEngine from '@app/features/voice/engine/MediaEngineFacade';
-import {waitForVoiceJoinChimeSequence} from '@app/features/voice/engine/VoiceSelfJoinChime';
-import {handleEntranceSoundPlay} from '@app/features/voice/events/EntranceSoundPlay';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/voice/engine/EntranceSoundPlaybackEngine', () => ({
- default: {play: vi.fn(() => Promise.resolve())},
-}));
-
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: {connected: true, channelId: 'channel-1'},
-}));
-
-vi.mock('@app/features/voice/engine/VoiceSelfJoinChime', () => ({
- waitForVoiceJoinChimeSequence: vi.fn(),
-}));
-
-const payload = {
- user_id: 'user-1',
- channel_id: 'channel-1',
- guild_id: 'guild-1',
- sound_id: 'sound-1',
- hash: 'hash-1',
- url: 'https://example.invalid/entrance.mp3',
- duration_ms: 1200,
- content_type: 'audio/mpeg',
-};
-
-const context = {} as GatewayHandlerContext;
-
-describe('handleEntranceSoundPlay', () => {
- beforeEach(() => {
- vi.mocked(EntranceSoundPlaybackEngine.play).mockClear();
- vi.mocked(waitForVoiceJoinChimeSequence).mockReset();
- });
-
- it('plays the entrance sound after the join chime started', async () => {
- vi.mocked(waitForVoiceJoinChimeSequence).mockResolvedValue('started');
- handleEntranceSoundPlay(payload, context);
- await vi.waitFor(() => expect(EntranceSoundPlaybackEngine.play).toHaveBeenCalledTimes(1));
- expect(waitForVoiceJoinChimeSequence).toHaveBeenCalledWith({userId: 'user-1', channelId: 'channel-1'});
- });
-
- it('plays the entrance sound when the join chime was unavailable', async () => {
- vi.mocked(waitForVoiceJoinChimeSequence).mockResolvedValue('unavailable');
- handleEntranceSoundPlay(payload, context);
- await vi.waitFor(() => expect(EntranceSoundPlaybackEngine.play).toHaveBeenCalledTimes(1));
- });
-
- it('drops the entrance sound when the join chime expired before starting', async () => {
- vi.mocked(waitForVoiceJoinChimeSequence).mockResolvedValue('expired-before-start');
- handleEntranceSoundPlay(payload, context);
- await Promise.resolve();
- await Promise.resolve();
- expect(EntranceSoundPlaybackEngine.play).not.toHaveBeenCalled();
- });
-
- it('drops the entrance sound when the channel changed while waiting', async () => {
- vi.mocked(waitForVoiceJoinChimeSequence).mockImplementation(() =>
- Promise.resolve().then(() => {
- vi.mocked(MediaEngine).channelId = 'channel-2';
- return 'started' as const;
- }),
- );
- handleEntranceSoundPlay(payload, context);
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- expect(EntranceSoundPlaybackEngine.play).not.toHaveBeenCalled();
- vi.mocked(MediaEngine).channelId = 'channel-1';
- });
-});
diff --git a/fluxer_app/src/features/voice/state/ActiveScreenShareSource.test.ts b/fluxer_app/src/features/voice/state/ActiveScreenShareSource.test.ts
deleted file mode 100644
index 8a67fb3c2..000000000
--- a/fluxer_app/src/features/voice/state/ActiveScreenShareSource.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import ActiveScreenShareSource from '@app/features/voice/state/ActiveScreenShareSource';
-import {afterEach, describe, expect, it} from 'vitest';
-
-describe('ActiveScreenShareSource', () => {
- afterEach(() => {
- ActiveScreenShareSource.clear();
- });
-
- it('tracks and clears whether the selected source is a Fluxer-owned window', () => {
- ActiveScreenShareSource.setPublishedSource('app', 'window:42:0', {isOwnWindow: true});
- expect(ActiveScreenShareSource.getSourceId()).toBe('window:42:0');
- expect(ActiveScreenShareSource.isOwnWindow()).toBe(true);
- expect(ActiveScreenShareSource.getShareContext()).toBe('app');
-
- ActiveScreenShareSource.setPublishedSource('display', 'screen:1:0');
- expect(ActiveScreenShareSource.getSourceId()).toBe('screen:1:0');
- expect(ActiveScreenShareSource.isOwnWindow()).toBe(false);
- expect(ActiveScreenShareSource.getShareContext()).toBe('display');
-
- ActiveScreenShareSource.clear();
- expect(ActiveScreenShareSource.getSourceId()).toBeNull();
- expect(ActiveScreenShareSource.isOwnWindow()).toBe(false);
- expect(ActiveScreenShareSource.getShareContext()).toBeNull();
- });
-
- it('keeps a scope picked before the share starts out of the running share until it is committed', () => {
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('window');
-
- ActiveScreenShareSource.setPendingWindowAudioScope('system');
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('system');
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('window');
-
- ActiveScreenShareSource.clearPendingWindowAudioScope();
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('window');
- });
-
- it('offers the running share own scope to the next picker until the user picks another one', () => {
- ActiveScreenShareSource.setPublishedSource('app', 'window:42:0');
- ActiveScreenShareSource.setWindowAudioScope('system');
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('system');
-
- ActiveScreenShareSource.setPendingWindowAudioScope('window');
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('window');
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('system');
-
- ActiveScreenShareSource.clearPendingWindowAudioScope();
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('system');
- });
-
- it('keeps the window audio scope for the running share and drops it when the share ends', () => {
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('window');
-
- ActiveScreenShareSource.setWindowAudioScope('system');
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('system');
-
- ActiveScreenShareSource.setPublishedSource('app', 'window:42:0');
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('system');
-
- ActiveScreenShareSource.setPendingWindowAudioScope('system');
- ActiveScreenShareSource.clear();
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('window');
- expect(ActiveScreenShareSource.getPendingWindowAudioScope()).toBe('window');
- });
-});
diff --git a/fluxer_app/src/features/voice/state/LocalVoiceStateMachine.test.ts b/fluxer_app/src/features/voice/state/LocalVoiceStateMachine.test.ts
deleted file mode 100644
index 682ff511c..000000000
--- a/fluxer_app/src/features/voice/state/LocalVoiceStateMachine.test.ts
+++ /dev/null
@@ -1,359 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createLocalVoiceStateSnapshot,
- getActiveLocalVoiceState,
- hasLocalVoiceConnectionState,
- type LocalVoiceStateEvent,
- type LocalVoiceStateSnapshot,
- transitionLocalVoiceStateSnapshot,
-} from '@app/features/voice/state/LocalVoiceStateMachine';
-import {describe, expect, it} from 'vitest';
-
-const CONNECTION_A = 'connection-a';
-const CONNECTION_B = 'connection-b';
-const STREAM_A = 'guild-a:channel-a:connection-a';
-const STREAM_B = 'guild-a:channel-a:connection-b';
-const STREAM_C = 'guild-a:channel-a:connection-c';
-
-function send(snapshot: LocalVoiceStateSnapshot, event: LocalVoiceStateEvent): LocalVoiceStateSnapshot {
- return transitionLocalVoiceStateSnapshot(snapshot, event);
-}
-
-function active(snapshot: LocalVoiceStateSnapshot, connectionId: string | null = null) {
- return getActiveLocalVoiceState(snapshot, connectionId);
-}
-
-describe('LocalVoiceStateMachine', () => {
- it('initializes fallback state from persisted defaults and canonicalizes viewer keys', () => {
- const snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- persistedDefaults: {
- selfMute: true,
- selfDeaf: true,
- hasUserSetMute: true,
- hasUserSetDeaf: true,
- },
- fallback: {
- selfVideo: true,
- selfStream: true,
- viewerStreamKeys: [STREAM_A, '', STREAM_A, STREAM_B],
- },
- });
- expect(active(snapshot)).toMatchObject({
- selfMute: true,
- selfDeaf: true,
- selfVideo: true,
- selfStream: true,
- viewerStreamKeys: [STREAM_A, STREAM_B],
- hasUserSetMute: true,
- hasUserSetDeaf: true,
- });
- });
-
- it('applies persisted defaults to fallback only when no connection is active', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- persistedDefaults: {selfMute: false},
- });
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {selfMute: true, selfDeaf: true},
- });
- snapshot = send(snapshot, {
- type: 'defaults.apply',
- activeConnectionId: CONNECTION_A,
- persistedDefaults: {selfMute: false, selfDeaf: false},
- });
- expect(active(snapshot, CONNECTION_A)).toMatchObject({selfMute: true, selfDeaf: true});
- snapshot = send(snapshot, {
- type: 'defaults.apply',
- activeConnectionId: null,
- persistedDefaults: {selfMute: false, selfDeaf: false},
- });
- expect(active(snapshot)).toMatchObject({selfMute: false, selfDeaf: false});
- });
-
- it('defaults to unmuted on initial permission grant when the user never set mute', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- persistedDefaults: {selfMute: true, hasUserSetMute: false},
- });
- snapshot = send(snapshot, {
- type: 'permission.sync',
- activeConnectionId: null,
- microphoneGranted: true,
- defaultMuteInitialized: false,
- });
- expect(active(snapshot)).toMatchObject({selfMute: false, mutedByPermission: false, hasUserSetMute: false});
- expect(snapshot.context.persistedDefaults.selfMute).toBe(false);
- });
-
- it('permission denial mutes transiently and grant restores persisted mute preference', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- persistedDefaults: {selfMute: false, hasUserSetMute: true},
- });
- snapshot = send(snapshot, {type: 'permission.deny', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: true, mutedByPermission: true});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: false, hasUserSetMute: true});
- snapshot = send(snapshot, {type: 'permission.grant', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: false, mutedByPermission: false, hasUserSetMute: true});
- });
-
- it('unmutes on first permission grant when the user never set mute', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: false,
- persistedDefaults: {selfMute: true, hasUserSetMute: false},
- fallback: {selfMute: true, mutedByPermission: true},
- });
- snapshot = send(snapshot, {type: 'permission.grant', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: false, mutedByPermission: false, hasUserSetMute: false});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: false, hasUserSetMute: false});
- });
-
- it('keeps user-requested unmute muted while permission is denied', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: false,
- persistedDefaults: {selfMute: false},
- fallback: {selfMute: true, mutedByPermission: true},
- });
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: true, mutedByPermission: true, hasUserSetMute: true});
- snapshot = send(snapshot, {type: 'mute.update', activeConnectionId: null, muted: false});
- expect(active(snapshot)).toMatchObject({selfMute: true, mutedByPermission: true});
- });
-
- it('unmuting while deafened also undeafens, but denied permission keeps mute enabled', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- fallback: {selfMute: true, selfDeaf: true, shouldUnmuteOnUndeafen: true},
- });
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({
- selfMute: false,
- selfDeaf: false,
- hasUserSetMute: true,
- hasUserSetDeaf: true,
- shouldUnmuteOnUndeafen: false,
- });
-
- snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: false,
- fallback: {selfMute: true, selfDeaf: true, mutedByPermission: true, shouldUnmuteOnUndeafen: true},
- });
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({
- selfMute: true,
- selfDeaf: false,
- mutedByPermission: true,
- hasUserSetMute: true,
- hasUserSetDeaf: true,
- });
- });
-
- it('tracks shouldUnmuteOnUndeafen only when deafening from an unmuted state', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({
- selfMute: true,
- selfDeaf: true,
- hasUserSetDeaf: true,
- shouldUnmuteOnUndeafen: true,
- });
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: false, selfDeaf: false, shouldUnmuteOnUndeafen: false});
-
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: true, selfDeaf: true, shouldUnmuteOnUndeafen: false});
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfMute: true, selfDeaf: false, shouldUnmuteOnUndeafen: false});
- });
-
- it('keeps mute and deaf persisted defaults synchronized with audio changes', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: true, hasUserSetMute: true});
- snapshot = send(snapshot, {type: 'mute.clearUserSet', activeConnectionId: null});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: true, hasUserSetMute: false});
- snapshot = send(snapshot, {type: 'deaf.update', activeConnectionId: null, deafened: true});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: true, selfDeaf: true});
- });
-
- it('toggles and updates local video and screen share state', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {type: 'video.toggle', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'stream.toggle', activeConnectionId: null});
- expect(active(snapshot)).toMatchObject({selfVideo: true, selfStream: true});
- snapshot = send(snapshot, {type: 'video.update', activeConnectionId: null, video: false});
- snapshot = send(snapshot, {type: 'stream.update', activeConnectionId: null, streaming: false});
- expect(active(snapshot)).toMatchObject({selfVideo: false, selfStream: false});
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: false, selfDeaf: false});
- });
-
- it('canonicalizes viewer stream keys for replace, seed, and server sync', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {
- type: 'viewer.replace',
- activeConnectionId: null,
- keys: [STREAM_A, '', STREAM_A, STREAM_B, STREAM_B, STREAM_C],
- });
- expect(active(snapshot).viewerStreamKeys).toEqual([STREAM_A, STREAM_B, STREAM_C]);
-
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {viewerStreamKeys: [STREAM_C, STREAM_C, STREAM_A]},
- });
- expect(active(snapshot, CONNECTION_A).viewerStreamKeys).toEqual([STREAM_C, STREAM_A]);
-
- snapshot = send(snapshot, {
- type: 'connection.sync',
- connectionId: CONNECTION_A,
- seed: {viewerStreamKeys: [STREAM_B, '', STREAM_B, STREAM_A]},
- });
- expect(active(snapshot, CONNECTION_A).viewerStreamKeys).toEqual([STREAM_B, STREAM_A]);
- });
-
- it('isolates video, stream, and viewer state per connection while persisting audio defaults', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {
- selfMute: true,
- selfDeaf: true,
- selfVideo: true,
- selfStream: true,
- viewerStreamKeys: [STREAM_A],
- },
- });
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_B,
- seed: {
- selfVideo: false,
- selfStream: false,
- viewerStreamKeys: [STREAM_B],
- },
- });
- expect(active(snapshot, CONNECTION_A)).toMatchObject({
- selfMute: true,
- selfDeaf: true,
- selfVideo: true,
- selfStream: true,
- viewerStreamKeys: [STREAM_A],
- });
- expect(active(snapshot, CONNECTION_B)).toMatchObject({
- selfMute: true,
- selfDeaf: true,
- selfVideo: false,
- selfStream: false,
- viewerStreamKeys: [STREAM_B],
- });
- expect(snapshot.context.persistedDefaults).toMatchObject({selfMute: true, selfDeaf: true});
- });
-
- it('does not overwrite an existing connection on seed, but server sync applies partial updates', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {selfMute: true, selfVideo: true, viewerStreamKeys: [STREAM_A]},
- });
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {selfMute: false, selfVideo: false, viewerStreamKeys: [STREAM_B]},
- });
- expect(active(snapshot, CONNECTION_A)).toMatchObject({
- selfMute: true,
- selfVideo: true,
- viewerStreamKeys: [STREAM_A],
- });
-
- snapshot = send(snapshot, {
- type: 'connection.sync',
- connectionId: CONNECTION_A,
- seed: {
- selfMute: false,
- hasUserSetMute: false,
- mutedByPermission: true,
- shouldUnmuteOnUndeafen: true,
- },
- });
- expect(active(snapshot, CONNECTION_A)).toMatchObject({
- selfMute: false,
- selfVideo: true,
- hasUserSetMute: false,
- mutedByPermission: true,
- shouldUnmuteOnUndeafen: true,
- });
- });
-
- it('clears a connection and resets fallback media watcher state', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: true,
- fallback: {selfVideo: true, selfStream: true, viewerStreamKeys: [STREAM_A]},
- });
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {selfVideo: true, selfStream: true, viewerStreamKeys: [STREAM_B]},
- });
- expect(hasLocalVoiceConnectionState(snapshot, CONNECTION_A)).toBe(true);
- snapshot = send(snapshot, {type: 'connection.clear', connectionId: CONNECTION_A});
- expect(hasLocalVoiceConnectionState(snapshot, CONNECTION_A)).toBe(false);
- expect(active(snapshot)).toMatchObject({selfVideo: false, selfStream: false, viewerStreamKeys: []});
- });
-
- it('resets preferences, clears connections, and keeps permission mute when permission is denied', () => {
- let snapshot = createLocalVoiceStateSnapshot({
- microphonePermissionGranted: false,
- persistedDefaults: {selfMute: true, selfDeaf: true, hasUserSetMute: true, hasUserSetDeaf: true},
- fallback: {selfVideo: true, selfStream: true, viewerStreamKeys: [STREAM_A], mutedByPermission: true},
- });
- snapshot = send(snapshot, {
- type: 'connection.seed',
- connectionId: CONNECTION_A,
- seed: {selfVideo: true, viewerStreamKeys: [STREAM_B]},
- });
- snapshot = send(snapshot, {type: 'preferences.reset'});
- expect(snapshot.context.persistedDefaults).toEqual({
- selfMute: false,
- selfDeaf: false,
- hasUserSetMute: false,
- hasUserSetDeaf: false,
- });
- expect(active(snapshot)).toMatchObject({
- selfMute: true,
- selfDeaf: false,
- selfVideo: false,
- selfStream: false,
- viewerStreamKeys: [],
- mutedByPermission: true,
- });
- expect(hasLocalVoiceConnectionState(snapshot, CONNECTION_A)).toBe(false);
- });
-
- it('survives repeated toggles and permission denied/granted cycles without losing canonical state', () => {
- let snapshot = createLocalVoiceStateSnapshot({microphonePermissionGranted: true});
- for (let i = 0; i < 25; i++) {
- snapshot = send(snapshot, {type: 'mute.toggle', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'deaf.toggle', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'viewer.replace', activeConnectionId: null, keys: [STREAM_A, STREAM_A]});
- snapshot = send(snapshot, {type: 'permission.deny', activeConnectionId: null});
- snapshot = send(snapshot, {type: 'mute.update', activeConnectionId: null, muted: false});
- snapshot = send(snapshot, {type: 'permission.grant', activeConnectionId: null});
- }
- expect(active(snapshot).viewerStreamKeys).toEqual([STREAM_A]);
- expect(active(snapshot)).toMatchObject({
- selfDeaf: false,
- mutedByPermission: false,
- shouldUnmuteOnUndeafen: false,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/state/PopoutWindowManager.test.ts b/fluxer_app/src/features/voice/state/PopoutWindowManager.test.ts
deleted file mode 100644
index fdf968b26..000000000
--- a/fluxer_app/src/features/voice/state/PopoutWindowManager.test.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import PopoutWindowManager, {
- getVoiceCallPopoutKey,
- getVoiceTilePopoutKey,
- type VoiceTilePopoutSource,
-} from '@app/features/voice/state/PopoutWindowManager';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-interface PendingAlwaysOnTopCall {
- key: string;
- flag: boolean;
- resolve: () => void;
- reject: (error: Error) => void;
-}
-
-let pendingAlwaysOnTopCalls: Array<PendingAlwaysOnTopCall> = [];
-
-function installElectronApi(): void {
- pendingAlwaysOnTopCalls = [];
- (window as unknown as {electron: unknown}).electron = {
- popoutFocus: () => Promise.resolve(true),
- popoutSetAlwaysOnTop: (key: string, flag: boolean) =>
- new Promise<boolean>((resolve, reject) => {
- pendingAlwaysOnTopCalls.push({key, flag, resolve: () => resolve(true), reject});
- }),
- };
-}
-
-function openCallPopout(channelId: string): string {
- expect(PopoutWindowManager.openCallPopout({channelId, guildId: null, title: channelId})).toBe(true);
- return getVoiceCallPopoutKey(channelId);
-}
-
-function openTilePopout(participantIdentity: string, source: VoiceTilePopoutSource): string {
- expect(
- PopoutWindowManager.openTilePopout({
- participantIdentity,
- source,
- userId: 'user-1',
- connectionId: 'connection-1',
- channelId: 'channel-1',
- guildId: null,
- title: participantIdentity,
- }),
- ).toBe(true);
- return getVoiceTilePopoutKey(participantIdentity, source);
-}
-
-function generationOf(key: string): number {
- const descriptor = PopoutWindowManager.popouts[key];
- if (!descriptor) throw new Error(`Expected popout ${key} to be open`);
- return descriptor.generation;
-}
-
-beforeEach(() => {
- installElectronApi();
- PopoutWindowManager.closeAll();
-});
-
-afterEach(() => {
- PopoutWindowManager.closeAll();
- delete (window as unknown as {electron?: unknown}).electron;
-});
-
-describe('popout generations', () => {
- test('allocates a fresh generation every time a key is reopened', () => {
- const key = openCallPopout('channel-a');
- const firstGeneration = generationOf(key);
- PopoutWindowManager.close(key, firstGeneration);
- openCallPopout('channel-a');
- expect(generationOf(key)).not.toBe(firstGeneration);
- });
-
- test('ignores handleWindowClosed from a superseded window', () => {
- const key = openCallPopout('channel-a');
- const firstGeneration = generationOf(key);
- PopoutWindowManager.close(key, firstGeneration);
- openCallPopout('channel-a');
- const secondGeneration = generationOf(key);
- PopoutWindowManager.handleWindowClosed(key, firstGeneration);
- expect(PopoutWindowManager.isOpen(key)).toBe(true);
- PopoutWindowManager.handleWindowClosed(key, secondGeneration);
- expect(PopoutWindowManager.isOpen(key)).toBe(false);
- });
-
- test('ignores close from a superseded window', () => {
- const key = openCallPopout('channel-a');
- const firstGeneration = generationOf(key);
- PopoutWindowManager.close(key, firstGeneration);
- openCallPopout('channel-a');
- PopoutWindowManager.close(key, firstGeneration);
- expect(PopoutWindowManager.isOpen(key)).toBe(true);
- });
-
- test('ignores attachWindow from a superseded window', () => {
- const key = openCallPopout('channel-a');
- const staleGeneration = generationOf(key);
- PopoutWindowManager.close(key, staleGeneration);
- openCallPopout('channel-a');
- const staleChildWindow = {closed: false, focus: vi.fn(), close: vi.fn()};
- PopoutWindowManager.attachWindow(key, staleGeneration, staleChildWindow);
- PopoutWindowManager.close(key);
- expect(staleChildWindow.close).not.toHaveBeenCalled();
- });
-
- test('closes the child window attached for the current generation', () => {
- const key = openCallPopout('channel-a');
- const childWindow = {closed: false, focus: vi.fn(), close: vi.fn()};
- PopoutWindowManager.attachWindow(key, generationOf(key), childWindow);
- PopoutWindowManager.close(key);
- expect(childWindow.close).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('always on top', () => {
- test('commits the pinned state only after the desktop call resolves', async () => {
- const key = openCallPopout('channel-a');
- PopoutWindowManager.setAlwaysOnTop(key, true);
- expect(pendingAlwaysOnTopCalls).toHaveLength(1);
- expect(PopoutWindowManager.isAlwaysOnTop(key)).toBe(false);
- pendingAlwaysOnTopCalls[0]?.resolve();
- await vi.waitFor(() => expect(PopoutWindowManager.isAlwaysOnTop(key)).toBe(true));
- });
-
- test('leaves the pinned state untouched when the desktop call rejects', async () => {
- const key = openCallPopout('channel-a');
- PopoutWindowManager.setAlwaysOnTop(key, true);
- pendingAlwaysOnTopCalls[0]?.reject(new Error('popout pin failed'));
- await vi.waitFor(() => expect(pendingAlwaysOnTopCalls).toHaveLength(1));
- expect(PopoutWindowManager.isAlwaysOnTop(key)).toBe(false);
- });
-
- test('serializes concurrent toggles and applies the last requested value', async () => {
- const key = openCallPopout('channel-a');
- PopoutWindowManager.setAlwaysOnTop(key, true);
- PopoutWindowManager.setAlwaysOnTop(key, false);
- expect(pendingAlwaysOnTopCalls).toHaveLength(1);
- expect(pendingAlwaysOnTopCalls[0]?.flag).toBe(true);
- pendingAlwaysOnTopCalls[0]?.resolve();
- await vi.waitFor(() => expect(pendingAlwaysOnTopCalls).toHaveLength(2));
- expect(pendingAlwaysOnTopCalls[1]?.flag).toBe(false);
- pendingAlwaysOnTopCalls[1]?.resolve();
- await vi.waitFor(() => expect(PopoutWindowManager.isAlwaysOnTop(key)).toBe(false));
- });
-
- test('toggles against the pending desired value rather than the committed one', () => {
- const key = openCallPopout('channel-a');
- PopoutWindowManager.toggleAlwaysOnTop(key);
- expect(pendingAlwaysOnTopCalls[0]?.flag).toBe(true);
- PopoutWindowManager.toggleAlwaysOnTop(key);
- expect(pendingAlwaysOnTopCalls).toHaveLength(1);
- PopoutWindowManager.toggleAlwaysOnTop(key);
- expect(pendingAlwaysOnTopCalls).toHaveLength(1);
- });
-
- test('drops in-flight operations when the popout is removed', async () => {
- const key = openCallPopout('channel-a');
- PopoutWindowManager.setAlwaysOnTop(key, true);
- PopoutWindowManager.close(key);
- pendingAlwaysOnTopCalls[0]?.resolve();
- await vi.waitFor(() => expect(pendingAlwaysOnTopCalls).toHaveLength(1));
- expect(PopoutWindowManager.isAlwaysOnTop(key)).toBe(false);
- });
-});
-
-describe('closeConnectionBoundPopouts', () => {
- test('keeps standalone user popouts and closes track-bound ones', () => {
- const callKey = openCallPopout('channel-a');
- const cameraKey = openTilePopout('participant-1', 'camera');
- const screenShareKey = openTilePopout('participant-1', 'screen_share');
- const userKey = openTilePopout('participant-2', 'user');
- PopoutWindowManager.closeConnectionBoundPopouts();
- expect(PopoutWindowManager.isOpen(callKey)).toBe(false);
- expect(PopoutWindowManager.isOpen(cameraKey)).toBe(false);
- expect(PopoutWindowManager.isOpen(screenShareKey)).toBe(false);
- expect(PopoutWindowManager.isOpen(userKey)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/state/RemoteVoicePlaybackBoost.test.ts b/fluxer_app/src/features/voice/state/RemoteVoicePlaybackBoost.test.ts
deleted file mode 100644
index e3c119e72..000000000
--- a/fluxer_app/src/features/voice/state/RemoteVoicePlaybackBoost.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- clearRemoteVoicePlaybackBoost,
- getRemoteVoicePlaybackBoost,
- setRemoteVoicePlaybackBoost,
-} from '@app/features/voice/state/RemoteVoicePlaybackBoost';
-import {afterEach, describe, expect, test} from 'vitest';
-
-describe('RemoteVoicePlaybackBoost', () => {
- afterEach(() => {
- clearRemoteVoicePlaybackBoost('user-1');
- });
-
- test('defaults to unity gain', () => {
- expect(getRemoteVoicePlaybackBoost('user-1')).toBe(1);
- });
-
- test('stores boosts above unity and clears non-positive values', () => {
- setRemoteVoicePlaybackBoost('user-1', 1.75);
- expect(getRemoteVoicePlaybackBoost('user-1')).toBe(1.75);
-
- setRemoteVoicePlaybackBoost('user-1', 1);
- expect(getRemoteVoicePlaybackBoost('user-1')).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/voice/state/ScreenSharePiPController.test.ts b/fluxer_app/src/features/voice/state/ScreenSharePiPController.test.ts
deleted file mode 100644
index 30d6db6a2..000000000
--- a/fluxer_app/src/features/voice/state/ScreenSharePiPController.test.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {PiPContent} from '@app/features/ui/state/PiP';
-import type {VoiceMediaGraphSnapshot} from '@app/features/voice/engine/VoiceMediaGraph';
-import {type Room, Track} from 'livekit-client';
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-const viewerStreamKeys = {current: [] as Array<string>};
-const pipContent = {current: null as PiPContent | null};
-const selfStream = {current: false};
-
-const mediaEngine = {
- room: null as Room | null,
- participants: {} as Record<string, {identity: string; isScreenShareEnabled: boolean}>,
- connectionVoiceStates: {} as Record<string, {channel_id: string}>,
- channelId: null as string | null,
- guildId: null as string | null,
- connectionId: null as string | null,
- subscribe: vi.fn(),
-};
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug = vi.fn();
- info = vi.fn();
- warn = vi.fn();
- error = vi.fn();
- },
-}));
-
-vi.mock('@app/features/platform/utils/DeferUntilModulesLoaded', () => ({
- deferUntilModulesLoaded: vi.fn(),
-}));
-
-vi.mock('@app/features/navigation/state/SelectedChannel', () => ({
- default: {currentChannelId: null},
-}));
-
-vi.mock('@app/features/ui/commands/PiPCommands', () => ({
- openPiP: vi.fn(),
- closePiP: vi.fn(),
-}));
-
-vi.mock('@app/features/ui/state/MobileLayout', () => ({
- default: {isMobileLayout: () => false},
-}));
-
-vi.mock('@app/features/ui/state/PiP', () => ({
- default: {
- getContent: () => pipContent.current,
- getSessionDisable: () => false,
- },
-}));
-
-vi.mock('@app/features/user/state/Users', () => ({
- default: {currentUser: {id: '1'}},
-}));
-
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: mediaEngine,
-}));
-
-vi.mock('@app/features/voice/engine/VoiceMediaGraphStore', () => ({
- voiceMediaGraphStore: {
- getGraphSnapshot: () =>
- ({watchIntent: {viewerStreamKeys: viewerStreamKeys.current}}) as unknown as VoiceMediaGraphSnapshot,
- subscribe: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/voice/state/LocalVoiceState', () => ({
- default: {
- getSelfStream: () => selfStream.current,
- subscribe: vi.fn(),
- },
-}));
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {disablePictureInPicturePopoutScreenShare: false},
-}));
-
-const {detectScreenSharePiPContent} = await import('@app/features/voice/state/ScreenSharePiPController');
-
-function makeParticipant(identity: string, sharing: boolean) {
- const publications = new Map<string, {source: Track.Source; isMuted: boolean; trackSid: string}>();
- publications.set('camera', {source: Track.Source.Camera, isMuted: false, trackSid: `${identity}-camera`});
- if (sharing) {
- publications.set('screen', {source: Track.Source.ScreenShare, isMuted: false, trackSid: `${identity}-screen`});
- }
- return {identity, trackPublications: publications};
-}
-
-function setRoom(remoteIdentities: Array<string>) {
- mediaEngine.room = {
- localParticipant: makeParticipant('user_1_connection-self', false),
- remoteParticipants: new Map(remoteIdentities.map((identity) => [identity, makeParticipant(identity, true)])),
- } as unknown as Room;
-}
-
-beforeEach(() => {
- viewerStreamKeys.current = [];
- pipContent.current = null;
- selfStream.current = false;
- mediaEngine.room = null;
- mediaEngine.participants = {};
- mediaEngine.connectionVoiceStates = {};
- mediaEngine.channelId = 'channel-1';
- mediaEngine.guildId = 'guild-1';
- mediaEngine.connectionId = 'connection-self';
-});
-
-describe('detectScreenSharePiPContent', () => {
- test('ignores a remote screen share the user is not watching', () => {
- setRoom(['user_2_connection-2']);
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toBeNull();
- });
-
- test('returns a remote screen share the user is watching', () => {
- setRoom(['user_2_connection-2']);
- viewerStreamKeys.current = ['guild-1:channel-1:connection-2'];
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toEqual({
- participantIdentity: 'user_2_connection-2',
- userId: '2',
- connectionId: 'connection-2',
- source: 'livekit',
- });
- });
-
- test('returns the watched share when several participants are sharing', () => {
- setRoom(['user_2_connection-2', 'user_3_connection-3']);
- viewerStreamKeys.current = ['guild-1:channel-1:connection-3'];
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toEqual({
- participantIdentity: 'user_3_connection-3',
- userId: '3',
- connectionId: 'connection-3',
- source: 'livekit',
- });
- });
-
- test('ignores an unwatched participant snapshot screen share', () => {
- mediaEngine.participants = {
- 'user_2_connection-2': {identity: 'user_2_connection-2', isScreenShareEnabled: true},
- };
- mediaEngine.connectionVoiceStates = {'connection-2': {channel_id: 'channel-1'}};
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toBeNull();
- });
-
- test('returns a watched participant snapshot screen share', () => {
- mediaEngine.participants = {
- 'user_2_connection-2': {identity: 'user_2_connection-2', isScreenShareEnabled: true},
- };
- mediaEngine.connectionVoiceStates = {'connection-2': {channel_id: 'channel-1'}};
- viewerStreamKeys.current = ['guild-1:channel-1:connection-2'];
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toEqual({
- participantIdentity: 'user_2_connection-2',
- userId: '2',
- connectionId: 'connection-2',
- source: 'participant-snapshot',
- });
- });
-
- test('ignores an unwatched remote screen share in a DM call', () => {
- setRoom(['user_2_connection-2']);
- mediaEngine.guildId = null;
- expect(detectScreenSharePiPContent('channel-1', null)).toBeNull();
- });
-
- test('returns a watched remote screen share in a DM call', () => {
- setRoom(['user_2_connection-2']);
- mediaEngine.guildId = null;
- viewerStreamKeys.current = ['dm:channel-1:connection-2'];
- expect(detectScreenSharePiPContent('channel-1', null)).toEqual({
- participantIdentity: 'user_2_connection-2',
- userId: '2',
- connectionId: 'connection-2',
- source: 'livekit',
- });
- });
-
- test('keeps returning the local share while watch intent is empty', () => {
- selfStream.current = true;
- setRoom([]);
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toEqual({
- participantIdentity: 'user_1_connection-self',
- userId: '1',
- connectionId: 'connection-self',
- source: 'local-self-state',
- });
- });
-
- test('keeps an open PiP alive for a watched stream that stopped publishing', () => {
- pipContent.current = {
- type: 'stream',
- participantIdentity: 'user_2_connection-2',
- channelId: 'channel-1',
- guildId: 'guild-1',
- connectionId: 'connection-2',
- userId: '2',
- };
- viewerStreamKeys.current = ['guild-1:channel-1:connection-2'];
- expect(detectScreenSharePiPContent('channel-1', 'guild-1')).toEqual({
- participantIdentity: 'user_2_connection-2',
- userId: '2',
- connectionId: 'connection-2',
- source: 'watched-stream',
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/state/ScreenSharePiPStateMachine.test.ts b/fluxer_app/src/features/voice/state/ScreenSharePiPStateMachine.test.ts
deleted file mode 100644
index 896329ed5..000000000
--- a/fluxer_app/src/features/voice/state/ScreenSharePiPStateMachine.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createScreenSharePiPSnapshot,
- type ScreenSharePiPConditions,
- type ScreenSharePiPScreenShare,
- type ScreenSharePiPSnapshot,
- selectScreenSharePiPCommands,
- selectScreenSharePiPMode,
- transitionScreenSharePiPSnapshot,
-} from '@app/features/voice/state/ScreenSharePiPStateMachine';
-import {describe, expect, it} from 'vitest';
-
-function makeShare(overrides: Partial<ScreenSharePiPScreenShare> = {}): ScreenSharePiPScreenShare {
- return {
- participantIdentity: 'user_123_connection-1',
- userId: '123',
- connectionId: 'connection-1',
- ...overrides,
- };
-}
-
-function makeConditions(overrides: Partial<ScreenSharePiPConditions> = {}): ScreenSharePiPConditions {
- return {
- connectedChannelId: null,
- connectedGuildId: null,
- screenShare: null,
- selectedChannelId: null,
- isMobile: false,
- disabledBySetting: false,
- disabledBySession: false,
- ...overrides,
- };
-}
-
-function feed(snapshot: ScreenSharePiPSnapshot, overrides: Partial<ScreenSharePiPConditions>): ScreenSharePiPSnapshot {
- return transitionScreenSharePiPSnapshot(snapshot, {
- type: 'conditions.changed',
- conditions: makeConditions(overrides),
- });
-}
-
-describe('screenSharePiPStateMachine', () => {
- it('starts closed with no commands', () => {
- const snapshot = createScreenSharePiPSnapshot();
- expect(selectScreenSharePiPMode(snapshot).kind).toBe('closed');
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([]);
- });
-
- it('emits open when a screen share appears in a voice channel the user is not viewing', () => {
- const snapshot = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- connectedGuildId: 'guild-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPMode(snapshot).kind).toBe('open');
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([
- {
- type: 'open',
- content: {
- type: 'stream',
- participantIdentity: 'user_123_connection-1',
- channelId: 'channel-1',
- guildId: 'guild-1',
- connectionId: 'connection-1',
- userId: '123',
- },
- },
- ]);
- });
-
- it('keeps PiP closed while the user is viewing the originating channel', () => {
- const snapshot = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- connectedGuildId: 'guild-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-1',
- });
- expect(selectScreenSharePiPMode(snapshot).kind).toBe('closed');
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([]);
- });
-
- it('opens PiP when the user navigates away from the originating channel', () => {
- const viewing = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-1',
- });
- const navigated = feed(viewing, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPMode(navigated).kind).toBe('open');
- expect(selectScreenSharePiPCommands(navigated)).toEqual([
- {type: 'open', content: expect.objectContaining({channelId: 'channel-1'})},
- ]);
- });
-
- it('closes PiP when the user navigates back to the originating channel', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const back = feed(open, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-1',
- });
- expect(selectScreenSharePiPMode(back).kind).toBe('closed');
- expect(selectScreenSharePiPCommands(back)).toEqual([{type: 'close'}]);
- });
-
- it('does not emit redundant commands when conditions repeat', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const again = feed(open, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPCommands(again)).toEqual([]);
- });
-
- it('reopens with new content when the sharing participant changes', () => {
- const first = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare({participantIdentity: 'user_1_connection-a', userId: '1', connectionId: 'connection-a'}),
- selectedChannelId: 'channel-2',
- });
- const second = feed(first, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare({participantIdentity: 'user_2_connection-b', userId: '2', connectionId: 'connection-b'}),
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPCommands(second)).toEqual([
- {type: 'close'},
- {
- type: 'open',
- content: expect.objectContaining({
- participantIdentity: 'user_2_connection-b',
- userId: '2',
- connectionId: 'connection-b',
- }),
- },
- ]);
- });
-
- it('closes PiP when the screen share ends', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const ended = feed(open, {
- connectedChannelId: 'channel-1',
- screenShare: null,
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPCommands(ended)).toEqual([{type: 'close'}]);
- });
-
- it('keeps PiP open when an ended share is still represented as a watched stream', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const watchedPlaceholder = feed(open, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare({source: 'watched-stream'}),
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPMode(watchedPlaceholder)).toEqual(
- expect.objectContaining({
- kind: 'open',
- content: expect.objectContaining({
- participantIdentity: 'user_123_connection-1',
- connectionId: 'connection-1',
- }),
- }),
- );
- expect(selectScreenSharePiPCommands(watchedPlaceholder)).toEqual([]);
- });
-
- it('closes PiP when the user disconnects from voice', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const disconnected = feed(open, {
- connectedChannelId: null,
- screenShare: null,
- selectedChannelId: 'channel-2',
- });
- expect(selectScreenSharePiPCommands(disconnected)).toEqual([{type: 'close'}]);
- });
-
- it('suppresses PiP on mobile', () => {
- const snapshot = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- isMobile: true,
- });
- expect(selectScreenSharePiPMode(snapshot).kind).toBe('closed');
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([]);
- });
-
- it('suppresses PiP when disabled by setting', () => {
- const snapshot = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- disabledBySetting: true,
- });
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([]);
- });
-
- it('suppresses PiP when disabled for the session', () => {
- const snapshot = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- disabledBySession: true,
- });
- expect(selectScreenSharePiPCommands(snapshot)).toEqual([]);
- });
-
- it('closes the open PiP when the setting is enabled mid-session', () => {
- const open = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- });
- const disabled = feed(open, {
- connectedChannelId: 'channel-1',
- screenShare: makeShare(),
- selectedChannelId: 'channel-2',
- disabledBySetting: true,
- });
- expect(selectScreenSharePiPCommands(disabled)).toEqual([{type: 'close'}]);
- });
-
- it('opens PiP for the new channel when the user joins a different voice channel mid-share', () => {
- const first = feed(createScreenSharePiPSnapshot(), {
- connectedChannelId: 'channel-1',
- screenShare: makeShare({participantIdentity: 'user_1_connection-a', userId: '1', connectionId: 'connection-a'}),
- selectedChannelId: 'channel-3',
- });
- const switched = feed(first, {
- connectedChannelId: 'channel-2',
- screenShare: makeShare({participantIdentity: 'user_9_connection-z', userId: '9', connectionId: 'connection-z'}),
- selectedChannelId: 'channel-3',
- });
- expect(selectScreenSharePiPCommands(switched)).toEqual([
- {type: 'close'},
- {
- type: 'open',
- content: expect.objectContaining({channelId: 'channel-2', participantIdentity: 'user_9_connection-z'}),
- },
- ]);
- });
-});
diff --git a/fluxer_app/src/features/voice/state/ScreenShareWatchFailures.test.ts b/fluxer_app/src/features/voice/state/ScreenShareWatchFailures.test.ts
deleted file mode 100644
index 2afefc5be..000000000
--- a/fluxer_app/src/features/voice/state/ScreenShareWatchFailures.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {screenShareWatchAttemptKey} from '@app/features/voice/components/useScreenShareWatchFailure';
-import {voiceMediaGraphStore} from '@app/features/voice/engine/VoiceMediaGraphStore';
-import {ScreenShareWatchErrorCode, ScreenShareWatchFailures} from '@app/features/voice/state/ScreenShareWatchFailures';
-import type {RemoteTrackPublication} from 'livekit-client';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-function inboundStatsReport(): RTCStatsReport {
- return new Map<string, unknown>([
- [
- 'IT01V',
- {
- type: 'inbound-rtp',
- id: 'IT01V',
- kind: 'video',
- codecId: 'C1',
- packetsReceived: 4210,
- bytesReceived: 3_500_000,
- framesReceived: 0,
- framesDecoded: 0,
- keyFramesDecoded: 0,
- framesDropped: 0,
- pliCount: 7,
- firCount: 0,
- nackCount: 2,
- freezeCount: 0,
- decoderImplementation: 'ExternalDecoder (D3D11VideoDecoder)',
- powerEfficientDecoder: true,
- frameWidth: 1920,
- frameHeight: 1080,
- },
- ],
- [
- 'C1',
- {
- type: 'codec',
- id: 'C1',
- mimeType: 'video/H264',
- sdpFmtpLine: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
- },
- ],
- ]) as unknown as RTCStatsReport;
-}
-
-function publicationWithStats(report: RTCStatsReport): RemoteTrackPublication {
- return {
- videoTrack: {
- getRTCStatsReport: () => Promise.resolve(report),
- },
- } as unknown as RemoteTrackPublication;
-}
-
-async function settleStatsSnapshot(): Promise<void> {
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
-}
-
-function fireWatchDeadlines(streamKey: string): void {
- const snapshot = voiceMediaGraphStore.getGraphSnapshot();
- const dueAt = voiceMediaGraphStore.nowMs() + 60_000;
- for (const [key, deadline] of snapshot.deadlinesByKey) {
- if (deadline.streamKey !== streamKey) continue;
- voiceMediaGraphStore.transition({type: 'time.deadlineFired', key, at: dueAt});
- }
-}
-
-function historyFor(streamKey: string) {
- return ScreenShareWatchFailures.getFailureHistory().filter((record) => record.streamKey === streamKey);
-}
-
-function watchDeadlineFor(streamKey: string) {
- const snapshot = voiceMediaGraphStore.getGraphSnapshot();
- for (const deadline of snapshot.deadlinesByKey.values()) {
- if (deadline.kind === 'watchAttempt' && deadline.streamKey === streamKey) return deadline;
- }
- return null;
-}
-
-describe('ScreenShareWatchFailures failure history', () => {
- beforeEach(() => {
- voiceMediaGraphStore.reset();
- });
-
- it('keeps a reported failure after the viewer stops watching', () => {
- const streamKey = 'guild-a:channel-a:connection-stop';
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- ScreenShareWatchFailures.reportFailure({
- streamKey,
- participantIdentity: 'user_1_connection-stop',
- trackSid: 'TR_stop',
- code: ScreenShareWatchErrorCode.RemoteTrackSubscriptionFailed,
- reason: 'remote-track-subscription-failed',
- });
- expect(ScreenShareWatchFailures.getFailure({streamKey})).not.toBeNull();
-
- ScreenShareWatchFailures.markWatchStopped(streamKey);
-
- expect(ScreenShareWatchFailures.getFailure({streamKey})).toBeNull();
- expect(historyFor(streamKey).map((record) => [record.code, record.trackSid, record.participantIdentity])).toEqual([
- [ScreenShareWatchErrorCode.RemoteTrackSubscriptionFailed, 'TR_stop', 'user_1_connection-stop'],
- ]);
- });
-
- it('keeps a failure raised by a watch deadline after the viewer stops watching', () => {
- const streamKey = 'guild-a:channel-a:connection-deadline';
- const attemptKey = screenShareWatchAttemptKey({streamKey, watchGeneration: 1});
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- ScreenShareWatchFailures.ensureAttempt({streamKey}, attemptKey);
- ScreenShareWatchFailures.setWatchTarget(streamKey, {videoRef: {current: null}});
-
- fireWatchDeadlines(streamKey);
-
- const graphFailure = ScreenShareWatchFailures.getFailure({streamKey});
- expect(graphFailure).not.toBeNull();
-
- ScreenShareWatchFailures.markWatchStopped(streamKey);
-
- expect(ScreenShareWatchFailures.getFailure({streamKey})).toBeNull();
- expect(historyFor(streamKey).map((record) => record.code)).toEqual([graphFailure!.code]);
- });
-
- it('records the inbound counters of the watched publication alongside the failure', async () => {
- const streamKey = 'guild-a:channel-a:connection-counters';
- const attemptKey = screenShareWatchAttemptKey({streamKey, watchGeneration: 1});
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- ScreenShareWatchFailures.ensureAttempt({streamKey}, attemptKey);
- ScreenShareWatchFailures.setWatchTarget(streamKey, {
- videoRef: {current: null},
- publication: publicationWithStats(inboundStatsReport()),
- });
-
- ScreenShareWatchFailures.reportFailure({
- streamKey,
- trackSid: 'TR_counters',
- code: ScreenShareWatchErrorCode.FirstFrameTimeout,
- reason: 'first-frame-timeout',
- });
- await settleStatsSnapshot();
-
- expect(historyFor(streamKey)[0].inbound).toEqual({
- packetsReceived: 4210,
- bytesReceived: 3_500_000,
- framesReceived: 0,
- framesDecoded: 0,
- keyFramesDecoded: 0,
- framesDropped: 0,
- pliCount: 7,
- firCount: 0,
- nackCount: 2,
- freezeCount: 0,
- decoderImplementation: 'ExternalDecoder (D3D11VideoDecoder)',
- powerEfficientDecoder: true,
- mimeType: 'video/H264',
- sdpFmtpLine: 'level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
- frameWidth: 1920,
- frameHeight: 1080,
- });
- });
-
- it('records the size and readiness of the attached video element', () => {
- const streamKey = 'guild-a:channel-a:connection-tile';
- const attemptKey = screenShareWatchAttemptKey({streamKey, watchGeneration: 1});
- const video = {readyState: 0, videoWidth: 0, videoHeight: 0, clientWidth: 960, clientHeight: 540};
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- ScreenShareWatchFailures.ensureAttempt({streamKey}, attemptKey);
- ScreenShareWatchFailures.setWatchTarget(streamKey, {
- videoRef: {current: video as unknown as HTMLVideoElement},
- });
-
- ScreenShareWatchFailures.reportFailure({
- streamKey,
- code: ScreenShareWatchErrorCode.FirstFrameTimeout,
- reason: 'first-frame-timeout',
- });
-
- expect(historyFor(streamKey)[0].tile).toMatchObject({
- hasVideoElement: true,
- readyState: 0,
- videoWidth: 0,
- videoHeight: 0,
- clientWidth: 960,
- clientHeight: 540,
- });
- });
-
- it('leaves the running watch deadline alone when the watch target is registered', () => {
- const streamKey = 'guild-a:channel-a:connection-target';
- const attemptKey = screenShareWatchAttemptKey({streamKey, watchGeneration: 1});
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- ScreenShareWatchFailures.ensureAttempt({streamKey}, attemptKey);
- const deadline = watchDeadlineFor(streamKey);
- expect(deadline).not.toBeNull();
-
- ScreenShareWatchFailures.setWatchTarget(streamKey, {videoRef: {current: null}});
- ScreenShareWatchFailures.setWatchTarget(streamKey, {
- videoRef: {current: null},
- publication: publicationWithStats(inboundStatsReport()),
- });
-
- expect(watchDeadlineFor(streamKey)).toBe(deadline);
- });
-
- it('keeps only the most recent failures once the ring is full', () => {
- const streamKey = 'guild-a:channel-a:connection-ring';
- ScreenShareWatchFailures.markWatchStarted(streamKey);
- for (let index = 0; index < 20; index += 1) {
- ScreenShareWatchFailures.reportFailure({
- streamKey,
- trackSid: `TR_ring_${index}`,
- code: ScreenShareWatchErrorCode.FirstFrameTimeout,
- reason: 'first-frame-timeout',
- });
- }
-
- const history = historyFor(streamKey);
- expect(history.length).toBe(16);
- expect([history[0].trackSid, history[history.length - 1].trackSid]).toEqual(['TR_ring_4', 'TR_ring_19']);
- });
-});
diff --git a/fluxer_app/src/features/voice/state/VoiceNoiseSuppressionRollout.test.ts b/fluxer_app/src/features/voice/state/VoiceNoiseSuppressionRollout.test.ts
deleted file mode 100644
index 34b4be181..000000000
--- a/fluxer_app/src/features/voice/state/VoiceNoiseSuppressionRollout.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,
- type VoiceNoiseSuppressionAssignmentResponse,
-} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';
-import {
- type ExperimentAssignmentsResponse,
- INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE,
-} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
-import {runInAction} from 'mobx';
-import {afterEach, 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/platform/transport/RestTransport', () => ({
- http: {get: vi.fn(), post: vi.fn()},
-}));
-
-const {ExperimentAssignments} = await import('@app/features/experiment/state/ExperimentAssignments');
-const {VoiceNoiseSuppressionRollout} = await import('@app/features/voice/state/VoiceNoiseSuppressionRollout');
-
-const GUILD_ID = '1485064866382176262';
-const OTHER_GUILD_ID = '1485064866382176263';
-
-const CANARY_ASSIGNMENT: VoiceNoiseSuppressionAssignmentResponse = {
- enabled: true,
- config_version: 7,
- user_targeted: true,
- backend: 'rnnoise',
- source: 'canary',
- guild_overrides: [{guild_id: GUILD_ID, backend: 'speex'}],
- enabled_backends: ['none', 'speex', 'rnnoise', 'gtcrn'],
- allow_user_override: true,
- stereo_enabled: false,
- suppression_strength: 80,
-};
-
-function publish(assignment: VoiceNoiseSuppressionAssignmentResponse): void {
- const response: ExperimentAssignmentsResponse = {
- poll_interval_seconds: 300,
- poll_jitter_percent: 15,
- assignments: {voice_noise_suppression: assignment},
- };
- runInAction(() => {
- ExperimentAssignments.response = response;
- });
-}
-
-afterEach(() => {
- runInAction(() => {
- ExperimentAssignments.response = INERT_EXPERIMENT_ASSIGNMENTS_RESPONSE;
- });
-});
-
-describe('VoiceNoiseSuppressionRollout assignment', () => {
- it('reads the inert assignment out of the inert envelope', () => {
- expect(VoiceNoiseSuppressionRollout.assignment).toBe(INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT);
- });
-
- it('reads the assignment out of a populated envelope', () => {
- publish(CANARY_ASSIGNMENT);
- expect(VoiceNoiseSuppressionRollout.assignment).toEqual(CANARY_ASSIGNMENT);
- });
-
- it('follows the envelope back to inert when the store is reset', () => {
- publish(CANARY_ASSIGNMENT);
- ExperimentAssignments.reset();
- expect(VoiceNoiseSuppressionRollout.assignment).toBe(INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT);
- });
-});
-
-describe('VoiceNoiseSuppressionRollout resolveForCall', () => {
- it('returns null while the inert envelope is in place', () => {
- expect(VoiceNoiseSuppressionRollout.resolveForCall(null, null)).toBeNull();
- expect(VoiceNoiseSuppressionRollout.resolveForCall(GUILD_ID, 'gtcrn')).toBeNull();
- });
-
- it('delegates to the shared resolver for the canary, guild and override cases', () => {
- publish(CANARY_ASSIGNMENT);
- expect(VoiceNoiseSuppressionRollout.resolveForCall(null, null)).toEqual({
- backend: 'rnnoise',
- source: 'canary',
- stereoEnabled: false,
- suppressionStrength: 80,
- configVersion: 7,
- });
- expect(VoiceNoiseSuppressionRollout.resolveForCall(OTHER_GUILD_ID, null)?.source).toBe('canary');
- expect(VoiceNoiseSuppressionRollout.resolveForCall(GUILD_ID, null)).toEqual({
- backend: 'speex',
- source: 'guild_rule',
- stereoEnabled: false,
- suppressionStrength: 80,
- configVersion: 7,
- });
- expect(VoiceNoiseSuppressionRollout.resolveForCall(GUILD_ID, 'gtcrn')).toEqual({
- backend: 'gtcrn',
- source: 'user_override',
- stereoEnabled: false,
- suppressionStrength: 80,
- configVersion: 7,
- });
- expect(VoiceNoiseSuppressionRollout.resolveForCall(null, 'deep_filter')?.source).toBe('canary');
- });
-
- it('lets a user rule win over a guild override', () => {
- publish({...CANARY_ASSIGNMENT, backend: 'gtcrn', source: 'user_rule', allow_user_override: false});
- expect(VoiceNoiseSuppressionRollout.resolveForCall(GUILD_ID, 'speex')).toEqual({
- backend: 'gtcrn',
- source: 'user_rule',
- stereoEnabled: false,
- suppressionStrength: 80,
- configVersion: 7,
- });
- });
-
- it('returns null for a user the rollout does not target', () => {
- publish({...CANARY_ASSIGNMENT, user_targeted: false, backend: null, source: null, guild_overrides: []});
- expect(VoiceNoiseSuppressionRollout.resolveForCall(null, 'rnnoise')).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/voice/state/VoiceSettingsCodecOptIn.test.ts b/fluxer_app/src/features/voice/state/VoiceSettingsCodecOptIn.test.ts
deleted file mode 100644
index d6144292d..000000000
--- a/fluxer_app/src/features/voice/state/VoiceSettingsCodecOptIn.test.ts
+++ /dev/null
@@ -1,301 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {runInAction} from 'mobx';
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@app/features/voice/utils/VoiceBackgroundAvailability', () => ({
- areVoiceBackgroundsAvailable: () => true,
-}));
-
-vi.mock('@app/features/app/utils/LimitResolverAdapter', () => ({
- LimitResolver: {resolve: () => 0},
-}));
-
-vi.mock('@app/features/app/utils/LimitUtils', () => ({
- isLimitToggleEnabled: () => false,
-}));
-
-const AppStorage = (await import('@app/features/platform/state/PersistentStorage')).default;
-
-AppStorage.setItem(
- 'VoiceSettings',
- JSON.stringify({
- preferredScreenShareCodec: 'av1',
- screenShareContentHintPrefV2: 'auto',
- screenshareResolution: 'low_240p',
- inputDeviceId: 'headset-1',
- screenShareAudioSourceMode: 'specific',
- screenShareAudioIncludeSources: [{'application.name': 'mpv'}],
- screenShareAudioExcludeSources: [{'application.name': 'Fluxer'}],
- screenShareManualAudioSourcesOptIn: true,
- manualScreenShareAudioSourcesOptInMigratedV1: true,
- __mps__: {version: 1},
- }),
-);
-
-const storageWrites: Array<string> = [];
-AppStorage.subscribe(
- (event) => {
- if (event.newValue != null) storageWrites.push(event.newValue);
- },
- {key: 'VoiceSettings'},
-);
-
-async function loadVoiceSettings() {
- const [{Logger}, persistenceModule] = await Promise.all([
- import('@app/features/platform/utils/AppLogger'),
- import('@app/features/platform/utils/MobXPersistence'),
- ]);
- const debug = vi.spyOn(Logger.prototype, 'debug').mockImplementation(() => undefined);
- try {
- const [{default: VoiceSettings}, {default: MediaPermission}] = await Promise.all([
- import('@app/features/voice/state/VoiceSettings'),
- import('@app/features/permissions/system/state/MediaPermission'),
- ]);
- await Promise.all([
- persistenceModule.awaitHydration('MacPermissions'),
- persistenceModule.awaitHydration('VoiceSettings'),
- vi.waitFor(() => expect(MediaPermission.isInitialized()).toBe(true)),
- ]);
- expect(debug).toHaveBeenCalledTimes(3);
- expect(debug).toHaveBeenCalledWith('Store MacPermissions hydrated from AppStorage and is now persisting.');
- expect(debug).toHaveBeenCalledWith('Initial permission state', {
- microphone: 'granted',
- camera: 'granted',
- micDenied: false,
- cameraDenied: false,
- });
- expect(debug).toHaveBeenCalledWith('Store VoiceSettings hydrated from AppStorage and is now persisting.');
- return VoiceSettings;
- } finally {
- debug.mockRestore();
- }
-}
-
-const VoiceSettings = await loadVoiceSettings();
-const {applyManualAudioSourcesOptOutResetMigrationV1} = await import('@app/features/voice/state/VoiceSettings');
-
-describe('AV1/HEVC screen-share opt-in', () => {
- it('rewrites a stored AV1 screen-share preference back to automatic on first launch', () => {
- const migrated = JSON.parse(storageWrites[0]);
- expect(migrated.preferredScreenShareCodec).toBe('auto');
- expect(migrated.screenShareAv1OptOutMigratedV1).toBe(true);
- expect(migrated.screenShareHevcOptOutMigratedV1).toBe(true);
- expect(VoiceSettings.screenShareAv1OptOutMigratedV1).toBe(true);
- expect(VoiceSettings.screenShareHevcOptOutMigratedV1).toBe(true);
- expect(VoiceSettings.screenShareAv1OptIn).toBe(false);
- expect(VoiceSettings.screenShareHevcOptIn).toBe(false);
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('auto');
- });
-
- it('hands out automatic while a hydrated AV1 or HEVC preference is not opted in', () => {
- VoiceSettings.updateSettings({screenShareAv1OptIn: false, screenShareHevcOptIn: false});
- runInAction(() => {
- VoiceSettings.preferredScreenShareCodec = 'av1';
- });
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('auto');
- runInAction(() => {
- VoiceSettings.preferredScreenShareCodec = 'h265';
- });
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('auto');
- });
-
- it('refuses to store an AV1 or HEVC preference while the opt-in is off', () => {
- VoiceSettings.updateSettings({
- screenShareAv1OptIn: false,
- screenShareHevcOptIn: false,
- preferredScreenShareCodec: 'auto',
- });
- VoiceSettings.updateSettings({preferredScreenShareCodec: 'av1'});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('auto');
- VoiceSettings.updateSettings({preferredScreenShareCodec: 'h265'});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('auto');
- });
-
- it('accepts an AV1 preference together with its opt-in in one patch', () => {
- VoiceSettings.updateSettings({screenShareAv1OptIn: false, preferredScreenShareCodec: 'auto'});
- VoiceSettings.updateSettings({screenShareAv1OptIn: true, preferredScreenShareCodec: 'av1'});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('av1');
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('av1');
- });
-
- it('accepts an HEVC preference together with its opt-in in one patch', () => {
- VoiceSettings.updateSettings({screenShareHevcOptIn: false, preferredScreenShareCodec: 'auto'});
- VoiceSettings.updateSettings({screenShareHevcOptIn: true, preferredScreenShareCodec: 'h265'});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('h265');
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('h265');
- });
-
- it('drops the AV1 preference again when the opt-in is turned back off', () => {
- VoiceSettings.updateSettings({screenShareAv1OptIn: true, preferredScreenShareCodec: 'av1'});
- VoiceSettings.updateSettings({screenShareAv1OptIn: false});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('auto');
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('auto');
- });
-
- it('drops the HEVC preference again when the opt-in is turned back off', () => {
- VoiceSettings.updateSettings({screenShareHevcOptIn: true, preferredScreenShareCodec: 'h265'});
- VoiceSettings.updateSettings({screenShareHevcOptIn: false});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('auto');
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('auto');
- });
-
- it('leaves an always-available codec preference alone', () => {
- VoiceSettings.updateSettings({preferredScreenShareCodec: 'vp9'});
- expect(VoiceSettings.preferredScreenShareCodec).toBe('vp9');
- expect(VoiceSettings.getPreferredScreenShareCodec()).toBe('vp9');
- });
-});
-
-describe('manual screen-share audio sources', () => {
- it('hydrates a profile that still stores the removed opt-in keys without losing anything else', () => {
- const stored = JSON.parse(storageWrites[0]);
- expect(stored.screenShareManualAudioSourcesOptIn).toBe(true);
- expect(stored.manualScreenShareAudioSourcesOptInMigratedV1).toBe(true);
- expect(stored.manualAudioSourcesOptOutResetMigratedV1).toBe(true);
- expect(VoiceSettings.inputDeviceId).toBe('headset-1');
- expect(VoiceSettings.getScreenShareAudioIncludeSources()).toEqual([{'application.name': 'mpv'}]);
- expect(VoiceSettings.getScreenShareAudioExcludeSources()).toEqual([{'application.name': 'Fluxer'}]);
- });
-
- it('keeps the reset migration out of the way of a profile that had the opt-in on', () => {
- expect(VoiceSettings.manualAudioSourcesOptOutResetMigratedV1).toBe(true);
- expect(VoiceSettings.getScreenShareAudioSourceMode()).toBe('specific');
- });
-
- it('returns a profile that switched the opt-in off to the defaults it was already getting', () => {
- const stored: Record<string, unknown> = {
- screenShareManualAudioSourcesOptIn: false,
- screenShareAudioSourceMode: 'none',
- screenShareAudioIncludeSources: [{'application.name': 'mpv'}],
- screenShareAudioExcludeSources: [{'application.name': 'Fluxer'}],
- inputDeviceId: 'headset-1',
- };
-
- expect(applyManualAudioSourcesOptOutResetMigrationV1(stored)).toBe(true);
-
- expect(stored.screenShareAudioSourceMode).toBe('system');
- expect(stored.screenShareAudioIncludeSources).toEqual([]);
- expect(stored.screenShareAudioExcludeSources).toEqual([]);
- expect(stored.inputDeviceId).toBe('headset-1');
- expect(stored.manualAudioSourcesOptOutResetMigratedV1).toBe(true);
- });
-
- it('leaves every other profile untouched and never runs twice', () => {
- const optedIn: Record<string, unknown> = {
- screenShareManualAudioSourcesOptIn: true,
- screenShareAudioSourceMode: 'specific',
- screenShareAudioIncludeSources: [{'application.name': 'mpv'}],
- };
- expect(applyManualAudioSourcesOptOutResetMigrationV1(optedIn)).toBe(true);
- expect(optedIn.screenShareAudioSourceMode).toBe('specific');
- expect(optedIn.screenShareAudioIncludeSources).toEqual([{'application.name': 'mpv'}]);
-
- const fresh: Record<string, unknown> = {};
- expect(applyManualAudioSourcesOptOutResetMigrationV1(fresh)).toBe(true);
- expect(fresh).toEqual({manualAudioSourcesOptOutResetMigratedV1: true});
-
- const alreadyMigrated: Record<string, unknown> = {
- manualAudioSourcesOptOutResetMigratedV1: true,
- screenShareManualAudioSourcesOptIn: false,
- screenShareAudioSourceMode: 'none',
- };
- expect(applyManualAudioSourcesOptOutResetMigrationV1(alreadyMigrated)).toBe(false);
- expect(alreadyMigrated.screenShareAudioSourceMode).toBe('none');
- });
-
- it('hands every Linux user the stored selection with no opt-in left to satisfy', () => {
- VoiceSettings.updateSettings({
- screenShareAudioSourceMode: 'specific',
- screenShareAudioIncludeSources: [{'application.name': 'mpv'}],
- screenShareAudioExcludeSources: [{'application.name': 'Fluxer'}],
- });
- expect(VoiceSettings.getScreenShareAudioSourceMode()).toBe('specific');
- expect(VoiceSettings.getEffectiveScreenShareAudioSourceMode()).toBe('specific');
- expect(VoiceSettings.getEffectiveScreenShareAudioIncludeSources()).toEqual([{'application.name': 'mpv'}]);
- expect(VoiceSettings.getEffectiveScreenShareAudioExcludeSources()).toEqual([{'application.name': 'Fluxer'}]);
-
- VoiceSettings.updateSettings({screenShareAudioSourceMode: 'none'});
- expect(VoiceSettings.getEffectiveScreenShareAudioSourceMode()).toBe('none');
-
- VoiceSettings.updateSettings({
- screenShareAudioSourceMode: 'system',
- screenShareAudioIncludeSources: [],
- screenShareAudioExcludeSources: [],
- });
- expect(VoiceSettings.getEffectiveScreenShareAudioSourceMode()).toBe('system');
- expect(VoiceSettings.getEffectiveScreenShareAudioIncludeSources()).toEqual([]);
- expect(VoiceSettings.getEffectiveScreenShareAudioExcludeSources()).toEqual([]);
- });
-
- it('drops the removed opt-in keys from storage on the next write and keeps the selection', async () => {
- VoiceSettings.updateSettings({
- screenShareAudioSourceMode: 'specific',
- screenShareAudioIncludeSources: [{'application.name': 'mpv'}],
- });
- await vi.waitFor(() => {
- const latest = JSON.parse(storageWrites[storageWrites.length - 1]);
- expect(latest.screenShareManualAudioSourcesOptIn).toBeUndefined();
- expect(latest.manualScreenShareAudioSourcesOptInMigratedV1).toBeUndefined();
- expect(latest.manualAudioSourcesOptOutResetMigratedV1).toBe(true);
- expect(latest.screenShareAudioSourceMode).toBe('specific');
- expect(latest.inputDeviceId).toBe('headset-1');
- });
- });
-});
-
-describe('screen share content hint default', () => {
- it('moves a stored automatic content hint to text on first launch', () => {
- const migrated = JSON.parse(storageWrites[0]);
- expect(migrated.screenShareContentHintPrefV2).toBe('text');
- expect(migrated.screenShareContentHintDefaultMigratedV1).toBe(true);
- expect(VoiceSettings.getScreenShareContentHint()).toBe('text');
- expect(VoiceSettings.getScreenShareContentHintOverride()).toBe('text');
- });
-
- it('keeps an automatic content hint chosen after the migration', () => {
- VoiceSettings.updateSettings({screenShareContentHint: 'auto'});
- expect(VoiceSettings.getScreenShareContentHint()).toBe('auto');
- expect(VoiceSettings.getScreenShareContentHintOverride()).toBeUndefined();
- });
-});
-
-describe('stored video quality preferences', () => {
- it('retires a stored 240p screen share preference to 480p on first launch', () => {
- const migrated = JSON.parse(storageWrites[0]);
- expect(migrated.screenshareResolution).toBe('low_480p');
- expect(VoiceSettings.screenshareResolution).toBe('low_480p');
- });
-
- it('upgrades a retired 240p patch to 480p', () => {
- VoiceSettings.updateSettings({screenshareResolution: 'low_240p'});
- expect(VoiceSettings.screenshareResolution).toBe('low_480p');
- });
-
- it('keeps premium video quality choices stored while the entitlement is missing', () => {
- VoiceSettings.updateSettings({screenshareResolution: 'ultra', cameraResolution: 'high', videoFrameRate: 60});
- VoiceSettings.updateSettings({outputDeviceId: 'default'});
- expect(VoiceSettings.screenshareResolution).toBe('ultra');
- expect(VoiceSettings.cameraResolution).toBe('high');
- expect(VoiceSettings.videoFrameRate).toBe(60);
- });
-
- it('still hands out free-tier video quality while the entitlement is missing', () => {
- VoiceSettings.updateSettings({screenshareResolution: 'ultra', cameraResolution: 'high', videoFrameRate: 60});
- expect(VoiceSettings.getScreenshareResolution()).toBe('medium');
- expect(VoiceSettings.getCameraResolution()).toBe('medium');
- expect(VoiceSettings.getVideoFrameRate()).toBe(30);
- });
-
- it('keeps every stored background image while the entitlement is missing', () => {
- const images = [1, 2, 3, 4, 5].map((index) => ({id: `background-${index}`, createdAt: index}));
- runInAction(() => {
- VoiceSettings.backgroundImages = images;
- });
- VoiceSettings.updateSettings({outputDeviceId: 'default'});
- expect(VoiceSettings.backgroundImages).toHaveLength(5);
- VoiceSettings.updateSettings({backgroundImages: images.slice(0, 4)});
- expect(VoiceSettings.backgroundImages).toHaveLength(4);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/AudioPublishOptions.test.ts b/fluxer_app/src/features/voice/utils/AudioPublishOptions.test.ts
deleted file mode 100644
index cfe81ae48..000000000
--- a/fluxer_app/src/features/voice/utils/AudioPublishOptions.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildMicrophonePublishOptions,
- normaliseAudioBitrateBps,
- OPUS_MAX_AUDIO_BITRATE_BPS,
- SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS,
-} from '@app/features/voice/utils/AudioPublishOptions';
-import {resolveVoiceChannelBitrate} from '@fluxer/constants/src/GuildConstants';
-import {describe, expect, it} from 'vitest';
-
-describe('normaliseAudioBitrateBps', () => {
- it('keeps stored channel bitrates in bits per second', () => {
- expect(normaliseAudioBitrateBps(64000)).toBe(64000);
- expect(normaliseAudioBitrateBps(320000)).toBe(320000);
- expect(normaliseAudioBitrateBps(384000)).toBe(384000);
- });
- it('accepts legacy kilobit-style values defensively', () => {
- expect(normaliseAudioBitrateBps(64)).toBe(64000);
- expect(normaliseAudioBitrateBps(384)).toBe(384000);
- });
- it('bounds audio bitrates to the supported Opus range used by WebRTC', () => {
- expect(normaliseAudioBitrateBps(1)).toBe(8000);
- expect(normaliseAudioBitrateBps(999999)).toBe(OPUS_MAX_AUDIO_BITRATE_BPS);
- });
- it('ignores missing or invalid values', () => {
- expect(normaliseAudioBitrateBps(null)).toBeUndefined();
- expect(normaliseAudioBitrateBps(undefined)).toBeUndefined();
- expect(normaliseAudioBitrateBps(0)).toBeUndefined();
- expect(normaliseAudioBitrateBps(Number.NaN)).toBeUndefined();
- });
-});
-
-describe('buildMicrophonePublishOptions', () => {
- it('leaves stereo to the track when the rollout requests it and the bitrate allows', () => {
- expect(buildMicrophonePublishOptions(256000, 'voice', true)).toEqual({
- audioPreset: {maxBitrate: 256000, priority: 'high'},
- red: true,
- });
- });
-
- it('forces mono when the rollout requests stereo but the bitrate is too low', () => {
- expect(buildMicrophonePublishOptions(96000, 'voice', true)).toEqual({
- audioPreset: {maxBitrate: 96000, priority: 'high'},
- red: true,
- forceStereo: false,
- });
- });
-
- it('is unchanged when the rollout does not request stereo', () => {
- expect(buildMicrophonePublishOptions(96000, 'voice', false)).toEqual(buildMicrophonePublishOptions(96000, 'voice'));
- expect(buildMicrophonePublishOptions(320000, 'studio', false)).toEqual(
- buildMicrophonePublishOptions(320000, 'studio'),
- );
- });
-
- it('uses the channel bitrate for normal voice tracks', () => {
- expect(buildMicrophonePublishOptions(96000, 'voice')).toEqual({
- audioPreset: {
- maxBitrate: 96000,
- priority: 'high',
- },
- red: true,
- });
- });
- it('keeps studio microphone tracks high fidelity when the channel can carry stereo', () => {
- expect(buildMicrophonePublishOptions(320000, 'studio')).toEqual({
- audioPreset: {
- maxBitrate: 320000,
- priority: 'high',
- },
- dtx: false,
- forceStereo: true,
- red: true,
- });
- });
- it('pins a call outside a guild to 64 kbps', () => {
- expect(buildMicrophonePublishOptions(resolveVoiceChannelBitrate(null, null), 'voice')).toEqual({
- audioPreset: {
- maxBitrate: 64000,
- priority: 'high',
- },
- red: true,
- });
- });
- it('does not force stereo below the stereo voice threshold', () => {
- expect(buildMicrophonePublishOptions(96000, 'studio')).toEqual({
- audioPreset: {
- maxBitrate: 96000,
- priority: 'high',
- },
- dtx: false,
- forceStereo: false,
- red: true,
- });
- });
-});
-
-describe('SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS', () => {
- it('uses maximum stereo Opus settings for screen-share audio', () => {
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.audioPreset?.maxBitrate).toBe(OPUS_MAX_AUDIO_BITRATE_BPS);
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.audioPreset?.priority).toBe('high');
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.dtx).toBe(false);
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.forceStereo).toBe(true);
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.red).toBe(true);
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.source).toBe('screen_share_audio');
- expect(SCREEN_SHARE_AUDIO_PUBLISH_OPTIONS.stream).toBe('screen_share');
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/CodecCapabilityDetector.test.ts b/fluxer_app/src/features/voice/utils/CodecCapabilityDetector.test.ts
deleted file mode 100644
index df9a81110..000000000
--- a/fluxer_app/src/features/voice/utils/CodecCapabilityDetector.test.ts
+++ /dev/null
@@ -1,356 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {Logger} from '@app/features/platform/utils/AppLogger';
-import type {HardwareEncodeReport} from '@app/features/voice/utils/GpuEncoderCapabilities';
-import {afterEach, beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';
-
-let av1OptIn = false;
-let hevcOptIn = false;
-let desktop = true;
-let platform = 'windows';
-let gpuReport: HardwareEncodeReport | null = null;
-let nativeHardwareEncoder: {backend: string; codecs: ReadonlyArray<string>} | null = null;
-let cameraPreference = 'auto';
-let openH264Status: {enabled: boolean; downloaded: boolean} | null = null;
-let codecCapabilityInfo: MockInstance<(...args: Array<unknown>) => void>;
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- getScreenShareAv1OptIn: () => av1OptIn,
- getScreenShareHevcOptIn: () => hevcOptIn,
- getPreferredVideoCodec: () => cameraPreference,
- },
-}));
-
-vi.mock('@app/features/devtools/utils/DesktopTroubleshootingUtils', () => ({
- getCachedDesktopTroubleshootingSettings: () => null,
-}));
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- guessPlatform: () => platform,
- isChromiumBrowser: () => true,
- isDesktop: () => desktop,
- isFirefoxBrowser: () => false,
-}));
-
-vi.mock('@app/features/voice/utils/GpuEncoderCapabilities', () => ({
- getGpuEncoderReportSync: () => gpuReport,
-}));
-
-vi.mock('@app/features/voice/utils/NativeHardwareEncoderCapabilities', () => ({
- getNativeHardwareEncoderCapabilitiesSync: () => nativeHardwareEncoder,
- hasNativeHardwareEncoder: (codec: string) => nativeHardwareEncoder?.codecs.includes(codec) === true,
- resetNativeHardwareEncoderCapabilities: () => undefined,
-}));
-
-vi.mock('@app/features/voice/utils/OpenH264Status', () => ({
- getOpenH264StatusSync: () => openH264Status,
- resetOpenH264Status: () => undefined,
-}));
-
-const ALL_SENDER_CODECS = ['video/VP8', 'video/VP9', 'video/H264', 'video/H265', 'video/AV1'];
-let senderCodecs = ALL_SENDER_CODECS;
-
-Object.defineProperty(globalThis, 'RTCRtpSender', {
- configurable: true,
- writable: true,
- value: {
- getCapabilities: () => ({codecs: senderCodecs.map((mimeType) => ({mimeType}))}),
- },
-});
-
-const {
- buildCameraPublishOptions,
- findVideoPublishCodecPolicyViolation,
- getAllowedVideoPublishCodecs,
- getCodecCapabilityReport,
- getRoomVideoPublishDefaults,
- isVideoCodecAllowedForPublish,
- markScreenShareCodecEncodeRuntimeFailure,
- markScreenShareCodecSoftwareEncodeObserved,
- resetCachedCodecCapabilities,
- resolveScreenShareEncoderVerificationAction,
- resolveVideoPublishCodecPolicy,
- selectAutomaticScreenShareCodec,
-} = await import('@app/features/voice/utils/CodecCapabilityDetector');
-
-const ALL_SOFTWARE: HardwareEncodeReport = {
- av1: 'software',
- h265: 'software',
- h264: 'software',
- vp9: 'software',
- vp8: 'software',
-};
-
-describe('screen-share AV1/HEVC opt-in gate', () => {
- afterEach(() => {
- try {
- expect(codecCapabilityInfo.mock.calls.length).toBeGreaterThan(0);
- for (const call of codecCapabilityInfo.mock.calls) {
- expect(call).toEqual([
- 'Codec capabilities probed',
- {capabilities: {vp8: true, vp9: true, h264: true, h265: true, av1: true}},
- ]);
- }
- } finally {
- codecCapabilityInfo.mockRestore();
- }
- });
-
- beforeEach(() => {
- codecCapabilityInfo = vi.spyOn(Logger.prototype, 'info').mockImplementation(() => undefined);
- av1OptIn = false;
- hevcOptIn = false;
- desktop = true;
- gpuReport = null;
- resetCachedCodecCapabilities();
- });
-
- it('reports AV1 as unsupported until the user opts in, even when the encoder is there', () => {
- expect(getCodecCapabilityReport().av1).toMatchObject({supported: false, reason: 'opt-in-required'});
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(getCodecCapabilityReport().av1).toMatchObject({supported: true, reason: 'supported'});
- });
-
- it('reports HEVC as unsupported until the user opts in, even when the encoder is there', () => {
- expect(getCodecCapabilityReport().h265).toMatchObject({supported: false, reason: 'opt-in-required'});
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(getCodecCapabilityReport().h265).toMatchObject({supported: true, reason: 'supported'});
- });
-
- it('leaves the always-available codecs alone while AV1 and HEVC are gated', () => {
- const report = getCodecCapabilityReport();
- expect(report.vp9.supported).toBe(true);
- expect(report.h264.supported).toBe(true);
- expect(report.vp8.supported).toBe(true);
- expect(report.av1.supported).toBe(false);
- expect(report.h265.supported).toBe(false);
- });
-
- it('never selects AV1 for the forced-software path while the opt-in is off', () => {
- expect(selectAutomaticScreenShareCodec('software')).toEqual({codec: 'vp9', reason: 'software-vp9'});
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(selectAutomaticScreenShareCodec('software')).toEqual({codec: 'av1', reason: 'software-av1'});
- });
-
- it('never selects AV1 for the desktop hardware path while the opt-in is off', () => {
- gpuReport = {...ALL_SOFTWARE, av1: 'hardware'};
- expect(selectAutomaticScreenShareCodec('auto').codec).not.toBe('av1');
- av1OptIn = true;
- resetCachedCodecCapabilities();
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'av1', reason: 'hardware-av1'});
- });
-
- it('never selects HEVC for the desktop hardware path while the opt-in is off', () => {
- gpuReport = {...ALL_SOFTWARE, h265: 'hardware'};
- expect(selectAutomaticScreenShareCodec('auto').codec).not.toBe('h265');
- hevcOptIn = true;
- resetCachedCodecCapabilities();
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'h265', reason: 'hardware-h265'});
- });
-
- it('never selects AV1 or HEVC for the software fallback path while the opt-ins are off', () => {
- desktop = false;
- gpuReport = ALL_SOFTWARE;
- const selection = selectAutomaticScreenShareCodec('auto').codec;
- expect(selection).not.toBe('av1');
- expect(selection).not.toBe('h265');
- });
-
- it('rebuilds the memoised report when either opt-in is flipped at runtime', () => {
- expect(getCodecCapabilityReport().av1.supported).toBe(false);
- expect(getCodecCapabilityReport().h265.supported).toBe(false);
- av1OptIn = true;
- expect(getCodecCapabilityReport().av1.supported).toBe(true);
- hevcOptIn = true;
- expect(getCodecCapabilityReport().h265.supported).toBe(true);
- });
-});
-
-describe('video publish codec policy', () => {
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- desktop = true;
- gpuReport = null;
- cameraPreference = 'auto';
- openH264Status = null;
- senderCodecs = ALL_SENDER_CODECS;
- resetCachedCodecCapabilities();
- });
-
- it('keeps AV1 and HEVC out of the allowed set while the opt-ins are off', () => {
- expect(getAllowedVideoPublishCodecs()).toEqual(['vp8', 'h264', 'vp9']);
- expect(isVideoCodecAllowedForPublish('av1')).toBe(false);
- expect(isVideoCodecAllowedForPublish('h265')).toBe(false);
- });
-
- it('admits AV1 and HEVC only once their opt-ins are on', () => {
- av1OptIn = true;
- expect(getAllowedVideoPublishCodecs()).toEqual(['vp8', 'h264', 'vp9', 'av1']);
- hevcOptIn = true;
- expect(getAllowedVideoPublishCodecs()).toEqual(['vp8', 'h264', 'vp9', 'av1', 'h265']);
- expect(resolveVideoPublishCodecPolicy('av1').primary).toBe('av1');
- expect(resolveVideoPublishCodecPolicy('h265').primary).toBe('h265');
- });
-
- it('substitutes an opted-out request with the first compatible codec and never AV1 or HEVC', () => {
- expect(resolveVideoPublishCodecPolicy('av1')).toMatchObject({primary: 'h264', backupCodec: false});
- expect(resolveVideoPublishCodecPolicy('h265')).toMatchObject({primary: 'h264', backupCodec: false});
- expect(resolveVideoPublishCodecPolicy('vp9')).toMatchObject({primary: 'vp9', backupCodec: {codec: 'h264'}});
- expect(resolveVideoPublishCodecPolicy('h264')).toMatchObject({primary: 'h264', backupCodec: false});
- });
-
- it('drops H.264 from the allowed set when the sender cannot encode it even though OpenH264 claims it is ready', () => {
- senderCodecs = ALL_SENDER_CODECS.filter((mimeType) => mimeType !== 'video/H264');
- openH264Status = {enabled: true, downloaded: true};
- expect(getCodecCapabilityReport().h264.supported).toBe(true);
- expect(isVideoCodecAllowedForPublish('h264')).toBe(false);
- expect(resolveVideoPublishCodecPolicy('h264')).toMatchObject({primary: 'vp9', backupCodec: false});
- expect(getRoomVideoPublishDefaults()).toEqual({videoCodec: 'vp9', backupCodec: false});
- });
-
- it('drops a codec from the allowed set once it failed to encode at runtime', () => {
- expect(markScreenShareCodecEncodeRuntimeFailure('vp9', 'test')).toBe(true);
- expect(getAllowedVideoPublishCodecs()).toEqual(['vp8', 'h264']);
- expect(resolveVideoPublishCodecPolicy('vp9').primary).toBe('h264');
- });
-
- it('hands the camera an explicit allowed codec for every preference while the opt-ins are off', () => {
- expect(buildCameraPublishOptions()).toEqual({
- videoCodec: 'vp9',
- backupCodec: {codec: 'h264'},
- backupCodecPolicy: 1,
- });
- for (const preference of ['auto', 'vp8', 'vp9', 'h264', 'av1', 'h265']) {
- cameraPreference = preference;
- const options = buildCameraPublishOptions();
- expect(options.videoCodec).toBeDefined();
- expect(getAllowedVideoPublishCodecs()).toContain(options.videoCodec);
- expect(options.videoCodec).not.toBe('av1');
- expect(options.videoCodec).not.toBe('h265');
- }
- cameraPreference = 'av1';
- expect(buildCameraPublishOptions().videoCodec).toBe('h264');
- av1OptIn = true;
- expect(buildCameraPublishOptions().videoCodec).toBe('av1');
- });
-
- it('derives the room publish defaults from the same policy', () => {
- expect(getRoomVideoPublishDefaults()).toEqual({videoCodec: 'vp9', backupCodec: {codec: 'h264'}});
- cameraPreference = 'av1';
- expect(getRoomVideoPublishDefaults().videoCodec).toBe('h264');
- });
-
- it('flags a negotiated codec outside the policy with a bounded alternative', () => {
- expect(findVideoPublishCodecPolicyViolation('h264', 'av1')).toEqual({
- requested: 'h264',
- negotiated: 'av1',
- alternative: 'vp9',
- });
- expect(findVideoPublishCodecPolicyViolation('h264', 'h264')).toBeNull();
- expect(findVideoPublishCodecPolicyViolation('h264', 'vp9')).toBeNull();
- expect(findVideoPublishCodecPolicyViolation('h264', undefined)).toBeNull();
- });
-
- it('no longer blacklists the requested codec when the publisher negotiated a different one', () => {
- expect(
- resolveScreenShareEncoderVerificationAction({reason: 'codec-mismatch', codec: 'h264', activeCodecs: ['av1']}),
- ).toEqual({kind: 'correct-negotiated', requested: 'h264', negotiated: ['av1'], alternative: 'vp9'});
- expect(isVideoCodecAllowedForPublish('h264')).toBe(true);
- expect(getCodecCapabilityReport().h264.supported).toBe(true);
- expect(
- resolveScreenShareEncoderVerificationAction({reason: 'codec-mismatch', codec: 'h264', activeCodecs: ['vp9']}),
- ).toEqual({kind: 'accept-negotiated', requested: 'h264', negotiated: ['vp9']});
- expect(isVideoCodecAllowedForPublish('h264')).toBe(true);
- });
-
- it('still blacklists a codec whose encoder stalled, and only warns about it once', () => {
- expect(resolveScreenShareEncoderVerificationAction({reason: 'stalled', codec: 'h264'})).toEqual({
- kind: 'recover-stalled',
- codec: 'h264',
- });
- expect(isVideoCodecAllowedForPublish('h264')).toBe(false);
- expect(getCodecCapabilityReport().h264).toMatchObject({supported: false, reason: 'runtime-failed'});
- expect(resolveScreenShareEncoderVerificationAction({reason: 'stalled', codec: 'h264'})).toEqual({
- kind: 'ignore-repeated-stall',
- codec: 'h264',
- });
- });
-
- it('keeps recovering from a vp8 stall because vp8 is never blacklisted', () => {
- for (let attempt = 0; attempt < 2; attempt++) {
- expect(resolveScreenShareEncoderVerificationAction({reason: 'stalled', codec: 'vp8'})).toEqual({
- kind: 'recover-stalled',
- codec: 'vp8',
- });
- expect(isVideoCodecAllowedForPublish('vp8')).toBe(true);
- }
- });
-});
-
-describe('H.264 hardware verdict', () => {
- beforeEach(() => {
- av1OptIn = false;
- hevcOptIn = false;
- desktop = true;
- platform = 'windows';
- gpuReport = null;
- nativeHardwareEncoder = null;
- cameraPreference = 'auto';
- openH264Status = null;
- senderCodecs = ALL_SENDER_CODECS;
- resetCachedCodecCapabilities();
- });
-
- afterEach(() => {
- platform = 'windows';
- nativeHardwareEncoder = null;
- resetCachedCodecCapabilities();
- });
-
- it('treats H.264 as software until the GPU probe has resolved', () => {
- expect(getCodecCapabilityReport().h264.hardwareAccelerated).toBe('software');
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'vp9', reason: 'software-vp9'});
- });
-
- it('does not pick hardware H.264 on a Windows AMD machine whose probe came back software', () => {
- gpuReport = {...ALL_SOFTWARE, gpuFamily: 'amd-rdna3-plus'};
- expect(getCodecCapabilityReport().h264.hardwareAccelerated).toBe('software');
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'vp9', reason: 'software-vp9'});
- });
-
- it('keeps hardware H.264 on Linux when the probe reported a power efficient encoder', () => {
- platform = 'linux';
- gpuReport = {...ALL_SOFTWARE, h264: 'hardware'};
- expect(getCodecCapabilityReport().h264.hardwareAccelerated).toBe('hardware');
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'h264', reason: 'hardware-h264'});
- });
-
- it('does not let a macOS native VideoToolbox encoder stand in for hardware H.264', () => {
- platform = 'macos';
- nativeHardwareEncoder = {backend: 'videotoolbox', codecs: ['h264']};
- const report = getCodecCapabilityReport();
- expect(report.h264.supported).toBe(true);
- expect(report.h264.hardwareAccelerated).toBe('software');
- expect(selectAutomaticScreenShareCodec('auto').reason).not.toBe('hardware-h264');
- });
-
- it('still counts a native NVENC encoder as hardware H.264', () => {
- platform = 'linux';
- nativeHardwareEncoder = {backend: 'nvenc', codecs: ['h264']};
- expect(getCodecCapabilityReport().h264.hardwareAccelerated).toBe('hardware');
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'h264', reason: 'hardware-h264'});
- });
-
- it('stops selecting hardware H.264 once the session verdict says it encoded in software', () => {
- gpuReport = {...ALL_SOFTWARE, h264: 'hardware'};
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'h264', reason: 'hardware-h264'});
- expect(markScreenShareCodecSoftwareEncodeObserved('h264')).toBe(true);
- expect(getCodecCapabilityReport().h264.hardwareAccelerated).toBe('software');
- expect(selectAutomaticScreenShareCodec('auto')).toEqual({codec: 'vp9', reason: 'software-vp9'});
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.ts b/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.ts
deleted file mode 100644
index 2f132f876..000000000
--- a/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {HardwareEncodeReport} from '@app/features/voice/utils/GpuEncoderCapabilities';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-let streamingMode = 'custom';
-let screenshareResolution = 'high';
-let videoFrameRate = 60;
-let higherVideoQuality = true;
-let shareSettingsUnavailable = false;
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- getStreamingMode: () => {
- if (shareSettingsUnavailable) throw new ReferenceError('Cannot access VoiceSettings before initialization');
- return streamingMode;
- },
- getScreenshareResolution: () => screenshareResolution,
- getVideoFrameRate: () => videoFrameRate,
- },
-}));
-
-vi.mock('@app/features/voice/utils/VideoQualityEntitlement', () => ({
- hasHigherVideoQuality: () => higherVideoQuality,
-}));
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- getElectronAPI: () => null,
- getNativePlatformSync: () => 'windows',
- isDesktop: () => false,
-}));
-
-interface EncodingInfoConfig {
- type: string;
- video: {contentType: string; width: number; height: number; bitrate: number; framerate: number};
-}
-
-const encodingInfoConfigs: Array<EncodingInfoConfig> = [];
-let encodingInfoAnswer: () => {supported?: boolean; powerEfficient?: boolean} = () => ({
- supported: true,
- powerEfficient: false,
-});
-
-Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- writable: true,
- value: {
- mediaCapabilities: {
- encodingInfo: async (config: EncodingInfoConfig) => {
- encodingInfoConfigs.push(config);
- return encodingInfoAnswer();
- },
- },
- },
-});
-
-const {
- AMD_RDNA3_PLUS,
- NEGOTIABLE_H264_PROBE_CONTENT_TYPE,
- NVIDIA_PRE_ADA,
- PCI_VENDOR_AMD,
- PCI_VENDOR_APPLE,
- PCI_VENDOR_NVIDIA,
- probeWebRtcEncodeEfficiency,
- reconcileHardwareEncodeReport,
-} = await import('@app/features/voice/utils/GpuEncoderCapabilities');
-
-const AMD_RDNA3_REPORT: HardwareEncodeReport = {...AMD_RDNA3_PLUS.caps, gpuFamily: AMD_RDNA3_PLUS.family};
-const NVIDIA_REPORT: HardwareEncodeReport = {...NVIDIA_PRE_ADA.caps, gpuFamily: NVIDIA_PRE_ADA.family};
-const PROBE_SAYS_SOFTWARE = {
- av1: 'software',
- h265: 'software',
- h264: 'software',
- vp9: 'software',
- vp8: 'software',
-} as const;
-
-function h264Probes(): Array<EncodingInfoConfig> {
- return encodingInfoConfigs.filter((config) => config.video.contentType.startsWith('video/H264'));
-}
-
-describe('the WebRTC encode probe', () => {
- beforeEach(() => {
- encodingInfoConfigs.length = 0;
- streamingMode = 'custom';
- screenshareResolution = 'high';
- videoFrameRate = 60;
- higherVideoQuality = true;
- shareSettingsUnavailable = false;
- encodingInfoAnswer = () => ({supported: true, powerEfficient: false});
- });
-
- it('asks about the single H.264 format the SFU can negotiate', async () => {
- await probeWebRtcEncodeEfficiency();
- expect(h264Probes().map((config) => config.video.contentType)).toEqual([
- 'video/H264;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
- ]);
- expect(NEGOTIABLE_H264_PROBE_CONTENT_TYPE).toBe(
- 'video/H264;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f',
- );
- });
-
- it('probes at the configured share size and frame rate', async () => {
- await probeWebRtcEncodeEfficiency();
- expect(h264Probes()[0]?.video).toMatchObject({width: 1920, height: 1080, framerate: 60, bitrate: 6_000_000});
- });
-
- it('follows the share settings down when the user picks a smaller share', async () => {
- screenshareResolution = 'medium';
- videoFrameRate = 30;
- await probeWebRtcEncodeEfficiency();
- expect(h264Probes()[0]?.video).toMatchObject({width: 1280, height: 720, framerate: 30, bitrate: 3_000_000});
- });
-
- it('answers software for H.264 when the negotiated format is not power efficient', async () => {
- await expect(probeWebRtcEncodeEfficiency()).resolves.toMatchObject({h264: 'software'});
- });
-
- it('answers hardware for H.264 when the negotiated format is power efficient', async () => {
- encodingInfoAnswer = () => ({supported: true, powerEfficient: true});
- await expect(probeWebRtcEncodeEfficiency()).resolves.toMatchObject({h264: 'hardware'});
- });
-
- it('still answers at the largest share size when the share settings cannot be read', async () => {
- shareSettingsUnavailable = true;
- await expect(probeWebRtcEncodeEfficiency()).resolves.toMatchObject({h264: 'software'});
- expect(h264Probes()[0]?.video).toMatchObject({width: 1920, height: 1080, framerate: 60, bitrate: 6_000_000});
- });
-});
-
-describe('reconciling the GPU table against the probe', () => {
- it('demotes H.264 to software on Windows when the negotiated format is not power efficient', () => {
- const report = reconcileHardwareEncodeReport(AMD_RDNA3_REPORT, PROBE_SAYS_SOFTWARE, 'windows', PCI_VENDOR_AMD);
- expect(report.h264).toBe('software');
- });
-
- it('demotes H.264 to software on macOS when the negotiated format is not power efficient', () => {
- const report = reconcileHardwareEncodeReport(AMD_RDNA3_REPORT, PROBE_SAYS_SOFTWARE, 'macos', PCI_VENDOR_APPLE);
- expect(report.h264).toBe('software');
- });
-
- it('demotes H.264 to software when the probe could not answer at all', () => {
- expect(reconcileHardwareEncodeReport(AMD_RDNA3_REPORT, null, 'windows', PCI_VENDOR_AMD).h264).toBe('software');
- });
-
- it('keeps hardware H.264 on Windows when the probe reports a power efficient encoder', () => {
- const report = reconcileHardwareEncodeReport(
- AMD_RDNA3_REPORT,
- {...PROBE_SAYS_SOFTWARE, h264: 'hardware'},
- 'windows',
- PCI_VENDOR_AMD,
- );
- expect(report.h264).toBe('hardware');
- });
-
- it('keeps hardware H.264 on Linux when the probe reports a power efficient encoder', () => {
- const report = reconcileHardwareEncodeReport(
- NVIDIA_REPORT,
- {...PROBE_SAYS_SOFTWARE, h264: 'hardware'},
- 'linux',
- PCI_VENDOR_NVIDIA,
- );
- expect(report.h264).toBe('hardware');
- });
-
- it('leaves the other codecs on the table verdict outside Linux NVIDIA', () => {
- const report = reconcileHardwareEncodeReport(AMD_RDNA3_REPORT, PROBE_SAYS_SOFTWARE, 'windows', PCI_VENDOR_AMD);
- expect(report.av1).toBe('hardware');
- expect(report.h265).toBe('hardware');
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.test.ts b/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.test.ts
deleted file mode 100644
index 09c9801b7..000000000
--- a/fluxer_app/src/features/voice/utils/LinuxAudioSourceRules.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- filterRoutableLinuxAudioSources,
- getLinuxAudioSourceDisplayName,
- LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY,
- LINUX_AUDIO_PRESERVE_VOLATILE_IDENTITY_PATTERN_KEY,
- LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY,
- linuxAudioSourceItemKey,
- mapLinuxAudioNodeToItems,
- toNativeLinuxAudioPattern,
- toNativeLinuxAudioPatterns,
- uniqueLinuxAudioSourceItems,
-} from '@app/features/voice/utils/LinuxAudioSourceRules';
-import type {VirtmicNode} from '@app/types/electron.d';
-import {describe, expect, it} from 'vitest';
-
-function node(overrides: VirtmicNode): VirtmicNode {
- return overrides;
-}
-
-describe('LinuxAudioSourceRules', () => {
- it('hides playback devices unless device selection is enabled', () => {
- const sink = node({
- 'media.class': 'Audio/Sink',
- 'application.name': 'WirePlumber',
- 'node.name': 'alsa_output.pci-0000_00_1f.3.analog-stereo',
- 'node.description': 'Built-in audio analog stereo',
- 'object.serial': '42',
- });
- expect(mapLinuxAudioNodeToItems(sink, {granular: false, deviceSelect: false, ignoreVirtual: false})).toEqual([]);
- expect(mapLinuxAudioNodeToItems(sink, {granular: false, deviceSelect: true, ignoreVirtual: false})).toEqual([
- {
- name: 'Built-in audio analog stereo',
- value: {
- [LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Built-in audio analog stereo',
- [LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: '42\nalsa_output.pci-0000_00_1f.3.analog-stereo',
- },
- },
- ]);
- });
- it('maps app playback streams to app and granular selectors', () => {
- const stream = node({
- 'media.class': 'Stream/Output/Audio',
- 'application.name': 'Firefox',
- 'application.process.id': '1234',
- 'media.name': 'Web audio',
- });
- expect(mapLinuxAudioNodeToItems(stream, {granular: true, deviceSelect: false, ignoreVirtual: false})).toEqual([
- {name: 'Firefox', value: {'application.name': 'Firefox'}},
- {
- name: 'Firefox (1234)',
- value: {
- 'application.name': 'Firefox',
- 'application.process.id': '1234',
- [LINUX_AUDIO_PRESERVE_VOLATILE_IDENTITY_PATTERN_KEY]: 'true',
- },
- },
- {
- name: 'Firefox [Web audio]',
- value: {'application.name': 'Firefox', 'media.name': 'Web audio'},
- },
- {
- name: 'Firefox [Stream/Output/Audio]',
- value: {'application.name': 'Firefox', 'media.class': 'Stream/Output/Audio'},
- },
- ]);
- });
- it('falls back to stable PipeWire stream identity when app pid is unavailable', () => {
- const stream = node({
- 'media.class': 'Stream/Output/Audio',
- 'application.name': 'Chromium',
- 'client.id': '77',
- 'object.serial': '88',
- });
- expect(mapLinuxAudioNodeToItems(stream, {granular: false, deviceSelect: false, ignoreVirtual: false})).toEqual([
- {name: 'Chromium', value: {'application.name': 'Chromium'}},
- ]);
- });
- it('filters virtual, input, video, and midi nodes out of picker entries', () => {
- const options = {granular: true, deviceSelect: true, ignoreVirtual: true};
- expect(
- mapLinuxAudioNodeToItems(node({'media.class': 'Stream/Output/Audio', 'node.virtual': 'true'}), options),
- ).toEqual([]);
- expect(
- mapLinuxAudioNodeToItems(node({'media.class': 'Stream/Input/Audio', 'application.name': 'Recorder'}), options),
- ).toEqual([]);
- expect(
- mapLinuxAudioNodeToItems(node({'media.class': 'Video/Source', 'application.name': 'Camera'}), options),
- ).toEqual([]);
- expect(
- mapLinuxAudioNodeToItems(node({'media.class': 'Midi/Bridge', 'application.name': 'Synth'}), options),
- ).toEqual([]);
- });
- it('strips display-only metadata before sending rules to native routing', () => {
- const pattern = {
- [LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Built-in speakers',
- [LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: '42\nalsa_output.foo',
- };
- expect(toNativeLinuxAudioPattern(pattern)).toEqual({
- [LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: '42\nalsa_output.foo',
- });
- expect(toNativeLinuxAudioPattern({[LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Built-in speakers'})).toBeNull();
- expect(toNativeLinuxAudioPatterns([pattern, {[LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Display only'}])).toEqual([
- {[LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: '42\nalsa_output.foo'},
- ]);
- });
- it('normalizes legacy app selectors by stripping volatile PipeWire identity before native routing', () => {
- expect(
- toNativeLinuxAudioPattern({
- 'application.name': 'Chromium',
- 'application.process.id': '1935',
- 'client.id': '77',
- 'object.serial': '88',
- }),
- ).toEqual({'application.name': 'Chromium'});
- expect(
- toNativeLinuxAudioPattern({
- 'application.name': 'Firefox',
- 'application.process.id': '1234',
- 'media.name': 'Web audio',
- }),
- ).toEqual({'application.name': 'Firefox', 'media.name': 'Web audio'});
- expect(
- toNativeLinuxAudioPattern({
- 'application.name': 'Firefox',
- 'application.process.id': '1234',
- [LINUX_AUDIO_PRESERVE_VOLATILE_IDENTITY_PATTERN_KEY]: 'true',
- }),
- ).toEqual({'application.name': 'Firefox', 'application.process.id': '1234'});
- });
- it('summarizes selected synthetic device patterns by display name', () => {
- expect(
- getLinuxAudioSourceDisplayName({
- [LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Built-in speakers',
- [LINUX_AUDIO_TARGET_OBJECTS_PATTERN_KEY]: '42',
- }),
- ).toBe('Built-in speakers');
- });
- it('keeps only the selections the capture layer can still match on', () => {
- const routable = {'application.name': 'Firefox'};
- const displayOnly = {[LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Firefox'};
- const volatileOnly = {'application.process.id': '1234'};
- expect(filterRoutableLinuxAudioSources([routable, displayOnly, volatileOnly])).toEqual([routable, volatileOnly]);
- expect(filterRoutableLinuxAudioSources([{...routable, [LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Firefox'}])).toEqual(
- [{...routable, [LINUX_AUDIO_DISPLAY_NAME_PATTERN_KEY]: 'Firefox'}],
- );
- expect(filterRoutableLinuxAudioSources([])).toEqual([]);
- });
- it('deduplicates identical item values without hiding same-named different selectors', () => {
- const duplicate = {name: 'Firefox', value: {'application.name': 'Firefox'}};
- const pidSpecific = {name: 'Firefox', value: {'application.name': 'Firefox', 'application.process.id': '1234'}};
- expect(uniqueLinuxAudioSourceItems([duplicate, {...duplicate}, pidSpecific]).map(linuxAudioSourceItemKey)).toEqual([
- linuxAudioSourceItemKey(duplicate),
- linuxAudioSourceItemKey(pidSpecific),
- ]);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/MediaDeviceRefresh.test.ts b/fluxer_app/src/features/voice/utils/MediaDeviceRefresh.test.ts
deleted file mode 100644
index 2860d994d..000000000
--- a/fluxer_app/src/features/voice/utils/MediaDeviceRefresh.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-const ensureDevices = vi.fn(async () => ({}));
-const invalidate = vi.fn();
-
-vi.mock('@app/features/voice/engine/VoiceDevicePermissionState', () => ({
- default: {ensureDevices},
-}));
-
-vi.mock('@app/features/voice/devices/MediaDeviceCache', () => ({
- mediaDeviceCache: {invalidate},
-}));
-
-const {refreshMediaDeviceLists, MediaDeviceRefreshType} = await import('@app/features/voice/utils/MediaDeviceRefresh');
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('refreshMediaDeviceLists', () => {
- test('an audio refresh only requests audio permission, never video', async () => {
- await refreshMediaDeviceLists({type: MediaDeviceRefreshType.audio});
- expect(invalidate).toHaveBeenCalledWith(MediaDeviceRefreshType.audio);
- expect(ensureDevices).toHaveBeenCalledTimes(1);
- expect(ensureDevices).toHaveBeenCalledWith({requestPermissionTypes: ['audio'], forceRefresh: true});
- });
-
- test('a video refresh only requests video permission, never audio', async () => {
- await refreshMediaDeviceLists({type: MediaDeviceRefreshType.video});
- expect(invalidate).toHaveBeenCalledWith(MediaDeviceRefreshType.video);
- expect(ensureDevices).toHaveBeenCalledTimes(1);
- expect(ensureDevices).toHaveBeenCalledWith({requestPermissionTypes: ['video'], forceRefresh: true});
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/MediaDeviceStartupPreload.test.ts b/fluxer_app/src/features/voice/utils/MediaDeviceStartupPreload.test.ts
deleted file mode 100644
index 3da25537c..000000000
--- a/fluxer_app/src/features/voice/utils/MediaDeviceStartupPreload.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const mediaPermission = vi.hoisted(() => ({
- isInitialized: () => true,
- isMicrophoneGranted: () => true,
- isCameraGranted: () => true,
- getMicrophonePermissionState: (): PermissionState => 'granted',
- getCameraPermissionState: (): PermissionState => 'granted',
- addChangeListener: (listener: () => void): (() => void) => {
- listener();
- return () => {};
- },
-}));
-
-vi.mock('@app/features/permissions/system/state/MediaPermission', () => ({default: mediaPermission}));
-
-const makeDevice = (kind: MediaDeviceKind, deviceId: string, label: string): MediaDeviceInfo =>
- ({
- deviceId,
- groupId: `${deviceId}-group`,
- kind,
- label,
- toJSON: () => ({deviceId, kind, label}),
- }) as MediaDeviceInfo;
-
-const getUserMediaCalls: Array<MediaStreamConstraints> = [];
-let browserExposesLabels = false;
-
-const fakeMediaDevices = {
- enumerateDevices: async (): Promise<Array<MediaDeviceInfo>> => [
- makeDevice('audioinput', 'mic-1', browserExposesLabels ? 'Studio Mic' : ''),
- makeDevice('videoinput', 'cam-1', browserExposesLabels ? 'Studio Camera' : ''),
- ],
- getUserMedia: async (constraints: MediaStreamConstraints): Promise<MediaStream> => {
- getUserMediaCalls.push(constraints);
- return {getTracks: () => []} as unknown as MediaStream;
- },
- addEventListener: () => {},
- removeEventListener: () => {},
-};
-
-let originalNavigator: PropertyDescriptor | undefined;
-let originalWindow: PropertyDescriptor | undefined;
-
-beforeEach(() => {
- getUserMediaCalls.length = 0;
- browserExposesLabels = false;
- originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
- originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {userAgent: 'node', mediaDevices: fakeMediaDevices},
- });
- Object.defineProperty(globalThis, 'window', {
- configurable: true,
- value: {matchMedia: () => ({matches: false})},
- });
- vi.resetModules();
-});
-
-afterEach(() => {
- if (originalNavigator) {
- Object.defineProperty(globalThis, 'navigator', originalNavigator);
- } else {
- Reflect.deleteProperty(globalThis, 'navigator');
- }
- if (originalWindow) {
- Object.defineProperty(globalThis, 'window', originalWindow);
- } else {
- Reflect.deleteProperty(globalThis, 'window');
- }
-});
-
-const runStartupPreload = async () => {
- const {startMediaDeviceStartupPreload} = await import('@app/features/voice/utils/MediaDeviceStartupPreload');
- const {default: VoiceDevicePermissionState} = await import('@app/features/voice/engine/VoiceDevicePermissionState');
- const stopPreload = startMediaDeviceStartupPreload();
- const state = await VoiceDevicePermissionState.ensureDevices();
- stopPreload();
- return state;
-};
-
-describe('startMediaDeviceStartupPreload', () => {
- test('never opens capture for a granted microphone and camera when the browser hides device labels', async () => {
- const state = await runStartupPreload();
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus).toEqual({audio: 'idle', video: 'idle'});
- });
-
- test('confirms a granted microphone and camera from exposed device labels without opening capture', async () => {
- browserExposesLabels = true;
- const state = await runStartupPreload();
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus).toEqual({audio: 'granted', video: 'granted'});
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/NativeAudioCaptureBridge.test.ts b/fluxer_app/src/features/voice/utils/NativeAudioCaptureBridge.test.ts
deleted file mode 100644
index e53da140e..000000000
--- a/fluxer_app/src/features/voice/utils/NativeAudioCaptureBridge.test.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {VoiceEngineV2AppSourceLifecycleBridge} from '@app/features/voice/engine/v2/VoiceEngineV2AppSourceLifecycleBridge';
-import {
- armNativeSystemAudioForNextCapture,
- captureNativeAudioTrackForLinuxRouting,
- getNativeAudioCaptureDiagnosticState,
- resetNativeAudioCaptureBridgeForTests,
- setNativeAudioCaptureBridgeLifecycleBridge,
-} from '@app/features/voice/utils/NativeAudioCaptureBridge';
-import {recordBridgeFrame, startBridgeStats} from '@app/features/voice/utils/native_audio_capture_bridge/bridgeStats';
-import type {
- NativeAudioBridgeEndedCapture,
- NativeAudioBridgeStats,
-} from '@app/features/voice/utils/native_audio_capture_bridge/shared';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const electronApi = {current: null as Record<string, unknown> | null};
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- getElectronAPI: () => electronApi.current,
-}));
-
-vi.mock('@app/features/voice/utils/SelfWindowScreenShareAudioMix', () => ({
- mixTrackWithSelfWindowScreenShareAudio: async (primaryTrack: MediaStreamTrack) => ({
- track: primaryTrack,
- cleanup: async () => undefined,
- }),
-}));
-
-const CAPTURE_ID = 'native-audio:stop-cause';
-
-class FakeMediaStreamTrack extends EventTarget {
- readyState: 'live' | 'ended' = 'live';
-
- constructor(readonly kind: 'audio' | 'video') {
- super();
- }
-
- stop(): void {
- this.readyState = 'ended';
- }
-}
-
-class FakeGeneratorTrack extends FakeMediaStreamTrack {
- readonly writable = new WritableStream();
-
- constructor(_options: {kind: 'audio'}) {
- super('audio');
- }
-}
-
-class FakeMediaStream {
- private readonly tracks: Array<FakeMediaStreamTrack>;
-
- constructor(tracks: Array<FakeMediaStreamTrack> = []) {
- this.tracks = [...tracks];
- }
-
- getTracks(): Array<FakeMediaStreamTrack> {
- return [...this.tracks];
- }
-
- getVideoTracks(): Array<FakeMediaStreamTrack> {
- return this.tracks.filter((track) => track.kind === 'video');
- }
-
- getAudioTracks(): Array<FakeMediaStreamTrack> {
- return this.tracks.filter((track) => track.kind === 'audio');
- }
-
- addTrack(track: FakeMediaStreamTrack): void {
- this.tracks.push(track);
- }
-
- removeTrack(track: FakeMediaStreamTrack): void {
- const index = this.tracks.indexOf(track);
- if (index >= 0) this.tracks.splice(index, 1);
- }
-}
-
-const stopNativeCapture = vi.fn(async () => undefined);
-const reportLifecycle = vi.fn(() => true);
-
-function createNativeAudioApi() {
- return {
- getAvailability: async () => ({
- available: true,
- backend: 'windows-wasapi-loopback',
- capabilities: {process: true, system: true, systemExcludesSelf: true},
- }),
- start: async () => ({captureId: CAPTURE_ID, sampleRate: 48000, channels: 2}),
- stop: stopNativeCapture,
- onFrame: () => () => undefined,
- onEnd: () => () => undefined,
- };
-}
-
-function installLifecycleBridge(): void {
- setNativeAudioCaptureBridgeLifecycleBridge({
- bind: () => true,
- unbind: () => undefined,
- reportLifecycle,
- } as unknown as VoiceEngineV2AppSourceLifecycleBridge);
-}
-
-async function flushCleanup(): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, 0));
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-async function startDisplayShareWithNativeAudio(): Promise<{
- videoTrack: FakeMediaStreamTrack;
- audioTrack: FakeMediaStreamTrack;
-}> {
- const videoTrack = new FakeMediaStreamTrack('video');
- const capturedStream = new FakeMediaStream([videoTrack]);
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {mediaDevices: {getDisplayMedia: async () => capturedStream}},
- });
- expect(await armNativeSystemAudioForNextCapture()).toBe(true);
- const stream = (await navigator.mediaDevices.getDisplayMedia({video: true})) as unknown as FakeMediaStream;
- const audioTrack = stream.getAudioTracks()[0];
- expect(audioTrack).toBeInstanceOf(FakeGeneratorTrack);
- return {videoTrack, audioTrack};
-}
-
-function currentBridgeStats(): NativeAudioBridgeStats {
- return getNativeAudioCaptureDiagnosticState().bridgeStats as NativeAudioBridgeStats;
-}
-
-function currentLifecycleFaults(): Array<{message: string}> {
- return getNativeAudioCaptureDiagnosticState().lifecycleFaults as Array<{message: string}>;
-}
-
-describe('getNativeAudioCaptureDiagnosticState', () => {
- it('keeps the six fields real dumps already carry and appends the retained histories', () => {
- expect(Object.keys(getNativeAudioCaptureDiagnosticState())).toEqual([
- 'armedCapture',
- 'activeBridge',
- 'supersededBridge',
- 'lastStartedCapture',
- 'lastArmFailure',
- 'bridgeStats',
- 'endedBridgeCaptures',
- 'lifecycleFaults',
- ]);
- });
-
- it('emits the superseded capture next to the live one instead of only the replacement', () => {
- startBridgeStats('generator', 'native-audio:diag-failed', {prebufferTargetUs: 60_000, frameDurationUs: 10_000});
- recordBridgeFrame('native-audio:diag-failed', {timestampUs: 0, durationUs: 10_000, peak: 0.31, rms: 0.08});
- startBridgeStats('generator', 'native-audio:diag-live', {prebufferTargetUs: 60_000, frameDurationUs: 10_000});
-
- const state = getNativeAudioCaptureDiagnosticState();
-
- expect((state.bridgeStats as NativeAudioBridgeStats).captureId).toBe('native-audio:diag-live');
- const ended = state.endedBridgeCaptures as Array<NativeAudioBridgeEndedCapture>;
- const retained = ended.find((capture) => capture.captureId === 'native-audio:diag-failed');
- expect(retained?.framesReceived).toBe(1);
- expect(retained?.nonSilentFrameCount).toBe(1);
- expect(retained?.endReason).toBe('superseded');
- });
-
- it('exposes a native-audio fault history that outlives the lifecycle unbind', () => {
- expect(Array.isArray(getNativeAudioCaptureDiagnosticState().lifecycleFaults)).toBe(true);
- });
-});
-
-describe('native audio capture teardown cause', () => {
- beforeEach(() => {
- resetNativeAudioCaptureBridgeForTests();
- Object.defineProperty(globalThis, 'window', {
- configurable: true,
- value: {MediaStreamTrackGenerator: FakeGeneratorTrack, AudioData: class {}},
- });
- Object.defineProperty(globalThis, 'MediaStream', {configurable: true, value: FakeMediaStream});
- electronApi.current = {platform: 'win32', nativeAudio: createNativeAudioApi()};
- stopNativeCapture.mockClear();
- reportLifecycle.mockClear();
- installLifecycleBridge();
- });
-
- it('records caller-stopped with no fault when the share is stopped by hand', async () => {
- const {audioTrack} = await startDisplayShareWithNativeAudio();
-
- audioTrack.stop();
- await flushCleanup();
-
- expect(currentLifecycleFaults()).toEqual([]);
- expect(reportLifecycle).not.toHaveBeenCalled();
- expect(currentBridgeStats().endDetail).toBe('caller-stopped');
- expect(stopNativeCapture).toHaveBeenCalledTimes(1);
- });
-
- it('names the audio track when the capture track ends on its own', async () => {
- const {audioTrack} = await startDisplayShareWithNativeAudio();
-
- audioTrack.dispatchEvent(new Event('ended'));
- await flushCleanup();
-
- expect(currentLifecycleFaults().map((fault) => fault.message)).toEqual(['native-audio-tap-audio-track-ended']);
- expect(reportLifecycle).toHaveBeenCalledWith({
- captureId: CAPTURE_ID,
- kind: 'error',
- message: 'native-audio-tap-audio-track-ended',
- });
- expect(currentBridgeStats().endDetail).toBe('audio-track-ended');
- });
-
- it('names the video track when the shared screen stops sending frames', async () => {
- const {videoTrack} = await startDisplayShareWithNativeAudio();
-
- videoTrack.dispatchEvent(new Event('ended'));
- await flushCleanup();
-
- expect(currentLifecycleFaults().map((fault) => fault.message)).toEqual(['native-audio-tap-video-track-ended']);
- expect(currentBridgeStats().endDetail).toBe('video-track-ended');
- });
-
- it('tears down once and keeps the track-ended cause when a stop follows it', async () => {
- const {audioTrack} = await startDisplayShareWithNativeAudio();
-
- audioTrack.dispatchEvent(new Event('ended'));
- audioTrack.stop();
- await flushCleanup();
-
- expect(currentLifecycleFaults()).toHaveLength(1);
- expect(currentBridgeStats().endDetail).toBe('audio-track-ended');
- expect(stopNativeCapture).toHaveBeenCalledTimes(1);
- });
-
- it('names the audio track when a capture mixed with self-window audio ends on its own', async () => {
- electronApi.current = {platform: 'linux', nativeAudio: createNativeAudioApi()};
- const track = (await captureNativeAudioTrackForLinuxRouting(
- {include: []},
- {includeSelfWindowAudio: true},
- )) as unknown as FakeMediaStreamTrack | null;
- expect(track).toBeInstanceOf(FakeGeneratorTrack);
-
- track?.dispatchEvent(new Event('ended'));
- await flushCleanup();
-
- expect(currentBridgeStats().endDetail).toBe('audio-track-ended');
- });
-
- it('tears down once and keeps caller-stopped when the track ends after the stop', async () => {
- const {audioTrack} = await startDisplayShareWithNativeAudio();
-
- audioTrack.stop();
- audioTrack.dispatchEvent(new Event('ended'));
- await flushCleanup();
-
- expect(currentLifecycleFaults()).toEqual([]);
- expect(currentBridgeStats().endDetail).toBe('caller-stopped');
- expect(stopNativeCapture).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/NativeAudioFailureUtils.test.ts b/fluxer_app/src/features/voice/utils/NativeAudioFailureUtils.test.ts
deleted file mode 100644
index aca0126d8..000000000
--- a/fluxer_app/src/features/voice/utils/NativeAudioFailureUtils.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {getNativeAudioErrorDetail} from '@app/features/voice/utils/NativeAudioFailureUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('NativeAudioFailureUtils', () => {
- it('preserves native audio error details for diagnostics', () => {
- expect(getNativeAudioErrorDetail(new Error('Native audio addon unavailable'))).toBe(
- 'Native audio addon unavailable',
- );
- expect(getNativeAudioErrorDetail('failed to start PipeWire direct audio capture')).toBe(
- 'failed to start PipeWire direct audio capture',
- );
- });
- it('does not turn silence at startup into a user-facing failure classification', () => {
- expect(getNativeAudioErrorDetail('selected source was silent during startup')).toBe(
- 'selected source was silent during startup',
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/ScreenShareAudioSummary.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareAudioSummary.test.ts
deleted file mode 100644
index 20ae4a6f4..000000000
--- a/fluxer_app/src/features/voice/utils/ScreenShareAudioSummary.test.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {describe, expect, it, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => {
- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);
- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};
-});
-
-const {
- APP_COUNT_DESCRIPTOR,
- CUSTOM_SOURCES_DESCRIPTOR,
- ENTIRE_SYSTEM_DESCRIPTOR,
- MICROPHONE_DESCRIPTOR,
- MICROPHONE_WITH_DEVICE_DESCRIPTOR,
- NO_AUDIO_DESCRIPTOR,
- resolveScreenShareAudioSummary,
- SHARED_WINDOW_DESCRIPTOR,
-} = await import('@app/features/voice/utils/ScreenShareAudioSummary');
-type ScreenShareAudioSummaryInput = Parameters<typeof resolveScreenShareAudioSummary>[0];
-
-function summary(overrides: Partial<ScreenShareAudioSummaryInput> = {}) {
- return resolveScreenShareAudioSummary({
- sourceMode: 'system',
- includeSources: [],
- shareContext: 'display',
- displayShareEnvironment: 'desktop-custom',
- ...overrides,
- });
-}
-
-describe('resolveScreenShareAudioSummary', () => {
- it('says no audio on a display share once the sources are switched off', () => {
- expect(summary({shareContext: 'display', sourceMode: 'none'})).toEqual({
- kind: 'message',
- descriptor: NO_AUDIO_DESCRIPTOR,
- });
- expect(summary({shareContext: 'app', windowAudioScope: 'system', sourceMode: 'none'})).toEqual({
- kind: 'message',
- descriptor: NO_AUDIO_DESCRIPTOR,
- });
- });
-
- it('never says no audio on a device share, whose microphone the source mode cannot switch off', () => {
- expect(summary({shareContext: 'device', sourceMode: 'none', microphoneLabel: 'Yeti'})).toEqual({
- kind: 'message',
- descriptor: MICROPHONE_WITH_DEVICE_DESCRIPTOR,
- values: {deviceLabel: 'Yeti'},
- });
- });
-
- it('never says no audio on a window share it still captures the window of', () => {
- expect(summary({shareContext: 'app', sourceMode: 'none', windowAudioScope: 'window'})).toEqual({
- kind: 'message',
- descriptor: SHARED_WINDOW_DESCRIPTOR,
- });
- });
-
- it('names the single picked application in every share context, capture cards included', () => {
- for (const shareContext of ['device', 'display'] as const) {
- expect(
- summary({
- shareContext,
- sourceMode: 'specific',
- includeSources: [{'application.name': 'mpv'}],
- microphoneLabel: 'Yeti',
- }),
- ).toEqual({kind: 'sourceName', name: 'mpv'});
- }
- expect(
- summary({
- shareContext: 'app',
- windowAudioScope: 'system',
- sourceMode: 'specific',
- includeSources: [{'application.name': 'mpv'}],
- }),
- ).toEqual({kind: 'sourceName', name: 'mpv'});
- });
-
- it('reads a selection the capture layer cannot express as the scope actually armed', () => {
- expect(summary({sourceMode: 'specific', includeSources: [{'fluxer.display.name': 'mpv'}]})).toEqual({
- kind: 'message',
- descriptor: ENTIRE_SYSTEM_DESCRIPTOR,
- });
- expect(
- summary({
- shareContext: 'app',
- windowAudioScope: 'system',
- sourceMode: 'specific',
- includeSources: [{'fluxer.display.name': 'mpv'}],
- }),
- ).toEqual({kind: 'message', descriptor: ENTIRE_SYSTEM_DESCRIPTOR});
- expect(
- summary({
- shareContext: 'device',
- microphoneLabel: 'Yeti',
- sourceMode: 'specific',
- includeSources: [{'fluxer.display.name': 'mpv'}],
- }),
- ).toEqual({kind: 'message', descriptor: MICROPHONE_WITH_DEVICE_DESCRIPTOR, values: {deviceLabel: 'Yeti'}});
- });
-
- it('counts the picked applications past the first one', () => {
- expect(
- summary({
- sourceMode: 'specific',
- includeSources: [{'application.name': 'mpv'}, {'application.name': 'Firefox'}],
- }),
- ).toEqual({kind: 'message', descriptor: APP_COUNT_DESCRIPTOR, values: {length: 2}});
- });
-
- it('falls back to a custom label for a picked source with no readable name', () => {
- expect(summary({sourceMode: 'specific', includeSources: [{'object.serial': '41'}]})).toEqual({
- kind: 'message',
- descriptor: CUSTOM_SOURCES_DESCRIPTOR,
- });
- });
-
- it('reads an empty specific selection as the wide scope it actually routes', () => {
- expect(summary({sourceMode: 'specific', includeSources: []})).toEqual({
- kind: 'message',
- descriptor: ENTIRE_SYSTEM_DESCRIPTOR,
- });
- expect(summary({shareContext: 'app', sourceMode: 'specific', includeSources: []})).toEqual({
- kind: 'message',
- descriptor: SHARED_WINDOW_DESCRIPTOR,
- });
- expect(
- summary({shareContext: 'app', windowAudioScope: 'system', sourceMode: 'specific', includeSources: []}),
- ).toEqual({kind: 'message', descriptor: ENTIRE_SYSTEM_DESCRIPTOR});
- });
-
- it('names the microphone on a device share and its device when one is resolved', () => {
- expect(summary({shareContext: 'device', microphoneLabel: 'Yeti'})).toEqual({
- kind: 'message',
- descriptor: MICROPHONE_WITH_DEVICE_DESCRIPTOR,
- values: {deviceLabel: 'Yeti'},
- });
- expect(summary({shareContext: 'device'})).toEqual({kind: 'message', descriptor: MICROPHONE_DESCRIPTOR});
- expect(summary({shareContext: 'device', microphoneLabel: ''})).toEqual({
- kind: 'message',
- descriptor: MICROPHONE_DESCRIPTOR,
- });
- });
-
- it('names the microphone on a device share that picked it over the stored application selection', () => {
- expect(
- summary({
- shareContext: 'device',
- microphoneLabel: 'Elgato 4K X Analog Stereo',
- sourceMode: 'specific',
- includeSources: [{'application.name': 'mpv'}],
- usesDeviceMicrophone: true,
- }),
- ).toEqual({
- kind: 'message',
- descriptor: MICROPHONE_WITH_DEVICE_DESCRIPTOR,
- values: {deviceLabel: 'Elgato 4K X Analog Stereo'},
- });
- expect(
- summary({
- shareContext: 'display',
- sourceMode: 'specific',
- includeSources: [{'application.name': 'mpv'}],
- usesDeviceMicrophone: true,
- }),
- ).toEqual({kind: 'sourceName', name: 'mpv'});
- });
-
- it('keeps a window share on the shared window whatever the stored display selection says', () => {
- for (const sourceMode of ['none', 'system', 'specific'] as const) {
- expect(summary({shareContext: 'app', sourceMode, includeSources: [{'application.name': 'mpv'}]})).toEqual({
- kind: 'message',
- descriptor: SHARED_WINDOW_DESCRIPTOR,
- });
- }
- });
-
- it('says the shared window on a window share and the entire system once it is widened', () => {
- expect(summary({shareContext: 'app'})).toEqual({kind: 'message', descriptor: SHARED_WINDOW_DESCRIPTOR});
- expect(summary({shareContext: 'app', windowAudioScope: 'window'})).toEqual({
- kind: 'message',
- descriptor: SHARED_WINDOW_DESCRIPTOR,
- });
- expect(summary({shareContext: 'app', windowAudioScope: 'system'})).toEqual({
- kind: 'message',
- descriptor: ENTIRE_SYSTEM_DESCRIPTOR,
- });
- });
-
- it('never promises a Wayland window share its own window audio', () => {
- expect(
- summary({shareContext: 'app', displayShareEnvironment: 'desktop-wayland', windowAudioScope: 'window'}),
- ).toEqual({kind: 'message', descriptor: ENTIRE_SYSTEM_DESCRIPTOR});
- });
-
- it('says the entire system on a display share whatever the window scope holds', () => {
- for (const windowAudioScope of ['window', 'system'] as const) {
- expect(summary({shareContext: 'display', windowAudioScope})).toEqual({
- kind: 'message',
- descriptor: ENTIRE_SYSTEM_DESCRIPTOR,
- });
- }
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.ts
deleted file mode 100644
index 631761e53..000000000
--- a/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- confirmDecodeStall,
- findSoftwareVideoDecoder,
- findStalledVideoDecoder,
- isSoftwareVideoImplementation,
- type StalledVideoDecoderInfo,
-} from '@app/features/voice/utils/ScreenShareCodecDiagnostics';
-import {describe, expect, it} from 'vitest';
-
-function createStatsReport(entries: Array<Record<string, unknown>>): RTCStatsReport {
- return new Map(entries.map((entry) => [entry.id as string, entry])) as unknown as RTCStatsReport;
-}
-
-function createStallInfo(overrides: Partial<StalledVideoDecoderInfo> = {}): StalledVideoDecoderInfo {
- return {
- codec: 'h264',
- mimeType: 'video/H264',
- packetsReceived: 400,
- bytesReceived: 250_000,
- framesDecoded: 0,
- framesReceived: 20,
- ...overrides,
- };
-}
-
-describe('isSoftwareVideoImplementation', () => {
- it('detects common software encoder and decoder implementations', () => {
- expect(isSoftwareVideoImplementation('libvpx')).toBe(true);
- expect(isSoftwareVideoImplementation('FFmpegVideoDecoder')).toBe(true);
- expect(isSoftwareVideoImplementation('Dav1dVideoDecoder')).toBe(true);
- expect(isSoftwareVideoImplementation('D3D11VideoDecoder')).toBe(false);
- });
-});
-
-describe('findSoftwareVideoDecoder', () => {
- it('finds a software decoder from the decoder implementation', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/AV1'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- decoderImplementation: 'Dav1dVideoDecoder',
- powerEfficientDecoder: false,
- },
- ]);
- expect(findSoftwareVideoDecoder(stats)).toEqual({
- codec: 'AV1',
- implementation: 'Dav1dVideoDecoder',
- powerEfficientDecoder: false,
- });
- });
- it('finds a software decoder from power efficiency when implementation is hidden', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- codecId: 'codec-1',
- powerEfficientDecoder: false,
- },
- ]);
- expect(findSoftwareVideoDecoder(stats)).toEqual({
- codec: 'H264',
- implementation: 'software decoder',
- powerEfficientDecoder: false,
- });
- });
- it('does not flag a named hardware decoder only because power efficiency is false', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- decoderImplementation: 'VideoToolboxVideoDecoder',
- powerEfficientDecoder: false,
- },
- ]);
- expect(findSoftwareVideoDecoder(stats)).toBeNull();
- });
- it('ignores hardware and non-video inbound stats', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {id: 'codec-2', type: 'codec', mimeType: 'audio/opus'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- decoderImplementation: 'D3D11VideoDecoder',
- powerEfficientDecoder: true,
- },
- {
- id: 'inbound-2',
- type: 'inbound-rtp',
- kind: 'audio',
- codecId: 'codec-2',
- decoderImplementation: 'FFmpegAudioDecoder',
- powerEfficientDecoder: false,
- },
- ]);
- expect(findSoftwareVideoDecoder(stats)).toBeNull();
- });
-});
-
-describe('findStalledVideoDecoder', () => {
- it('detects received video packets that never decode into frames', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/VP9'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 42,
- bytesReceived: 32000,
- framesDecoded: 0,
- framesReceived: 8,
- },
- ]);
- expect(findStalledVideoDecoder(stats)).toMatchObject({
- codec: 'vp9',
- mimeType: 'video/VP9',
- packetsReceived: 42,
- bytesReceived: 32000,
- framesDecoded: 0,
- framesReceived: 8,
- });
- });
- it('does not treat an idle track as a decoder stall', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/AV1'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 0,
- bytesReceived: 0,
- framesDecoded: 0,
- },
- ]);
- expect(findStalledVideoDecoder(stats)).toBeNull();
- });
- it('does not treat a first keyframe that is still arriving as a decoder stall', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 40,
- bytesReceived: 60_000,
- framesReceived: 0,
- framesDecoded: 0,
- },
- ]);
- expect(findStalledVideoDecoder(stats)).toBeNull();
- });
- it('does not treat packets that carry no video frames as a decoder stall', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 50,
- bytesReceived: 0,
- framesReceived: 0,
- framesDecoded: 0,
- },
- ]);
- expect(findStalledVideoDecoder(stats)).toBeNull();
- });
- it('treats whole frames that never decode as a decoder stall', () => {
- const stats = createStatsReport([
- {id: 'codec-1', type: 'codec', mimeType: 'video/H264'},
- {
- id: 'inbound-1',
- type: 'inbound-rtp',
- kind: 'video',
- codecId: 'codec-1',
- packetsReceived: 40,
- bytesReceived: 60_000,
- framesReceived: 40,
- framesDecoded: 0,
- },
- ]);
- expect(findStalledVideoDecoder(stats)).toMatchObject({codec: 'h264', framesReceived: 40, framesDecoded: 0});
- });
-});
-
-describe('confirmDecodeStall', () => {
- it('confirms a stall when more frames arrived and none of them decoded', () => {
- const second = createStallInfo({framesReceived: 45});
- expect(confirmDecodeStall(createStallInfo({framesReceived: 20}), second)).toBe(second);
- });
- it('does not confirm a stall when the second sample decoded a frame', () => {
- expect(confirmDecodeStall(createStallInfo(), createStallInfo({framesReceived: 45, framesDecoded: 3}))).toBeNull();
- });
- it('does not confirm a stall when the second sample is missing', () => {
- expect(confirmDecodeStall(createStallInfo(), null)).toBeNull();
- });
- it('does not confirm a stall when no new frames arrived between the samples', () => {
- expect(confirmDecodeStall(createStallInfo({framesReceived: 20}), createStallInfo({framesReceived: 20}))).toBeNull();
- });
- it('does not confirm a stall across two different codecs', () => {
- expect(
- confirmDecodeStall(
- createStallInfo({framesReceived: 20}),
- createStallInfo({codec: 'vp9', mimeType: 'video/VP9', framesReceived: 45}),
- ),
- ).toBeNull();
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/ScreenShareLifecycleLog.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareLifecycleLog.test.ts
deleted file mode 100644
index 86234064d..000000000
--- a/fluxer_app/src/features/voice/utils/ScreenShareLifecycleLog.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import ActiveScreenShareSource from '@app/features/voice/state/ActiveScreenShareSource';
-import {
- getRecentScreenShares,
- recordScreenShareEncoderVerification,
- recordScreenShareEndedModal,
- recordScreenShareRequestedCodec,
- recordScreenShareStartError,
- recordScreenShareStarted,
- recordScreenShareStopped,
- resetRecentScreenSharesForTests,
-} from '@app/features/voice/utils/ScreenShareLifecycleLog';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-describe('ScreenShareLifecycleLog', () => {
- beforeEach(() => {
- resetRecentScreenSharesForTests();
- ActiveScreenShareSource.clear();
- });
-
- it('keeps the first trigger that stopped a share instead of the later unpublish', () => {
- recordScreenShareStarted();
- recordScreenShareStopped('media-track-ended');
- recordScreenShareStopped('server-unpublish');
-
- const [entry] = getRecentScreenShares();
- expect(entry.stopTrigger).toBe('media-track-ended');
- expect(entry.stoppedAt).not.toBeNull();
- });
-
- it('tells a user stop apart from a share that stopped on its own', () => {
- recordScreenShareStarted();
- recordScreenShareStopped('user');
- recordScreenShareStarted();
- recordScreenShareStopped('gateway-echo');
-
- expect(getRecentScreenShares().map((entry) => entry.stopTrigger)).toEqual(['user', 'gateway-echo']);
- });
-
- it('records the codec verification and the modal a stopped share showed', () => {
- recordScreenShareStarted();
- recordScreenShareRequestedCodec('h264');
- recordScreenShareEncoderVerification('correct-negotiated', ['vp9']);
- recordScreenShareEndedModal('codec-policy-failed');
- recordScreenShareStopped('codec-republish-failed');
-
- const [entry] = getRecentScreenShares();
- expect(entry.requestedCodec).toBe('h264');
- expect(entry.negotiatedCodecs).toEqual(['vp9']);
- expect(entry.encoderVerification).toBe('correct-negotiated');
- expect(entry.modalShown).toBe('codec-policy-failed');
- expect(entry.stopTrigger).toBe('codec-republish-failed');
- });
-
- it('freezes the published source when the share stops', () => {
- ActiveScreenShareSource.setPublishedSource('app', 'window:7');
- recordScreenShareStarted();
- recordScreenShareStopped('user');
- ActiveScreenShareSource.clear();
-
- expect(getRecentScreenShares()[0].sourceKind).toBe('app');
- });
-
- it('reports the live published source while a share is still running', () => {
- recordScreenShareStarted();
- ActiveScreenShareSource.setPublishedSource('display', 'screen:1');
-
- expect(getRecentScreenShares()[0].sourceKind).toBe('display');
- });
-
- it('records a start failure without marking it as a stop', () => {
- recordScreenShareStarted();
- recordScreenShareStartError(new Error('portal refused'));
-
- const [entry] = getRecentScreenShares();
- expect(entry.startError).toBe('Error: portal refused');
- expect(entry.stopTrigger).toBeNull();
- expect(entry.stoppedAt).toBeNull();
- });
-
- it('leaves a closed share untouched when a later trigger arrives', () => {
- recordScreenShareStarted();
- recordScreenShareStartError(new Error('portal refused'));
- recordScreenShareStopped('user');
-
- expect(getRecentScreenShares()[0].stopTrigger).toBeNull();
- });
-
- it('keeps only the eight most recent shares', () => {
- for (let index = 0; index < 11; index += 1) {
- recordScreenShareStarted();
- recordScreenShareStopped('user');
- }
-
- expect(getRecentScreenShares()).toHaveLength(8);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.ts
deleted file mode 100644
index 6ca7e0160..000000000
--- a/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.ts
+++ /dev/null
@@ -1,312 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildScreenShareOptions,
- capScreenShareEncodingToDimensions,
- getScreenShareBitrateBps,
- getScreenShareEncoding,
- resolveStreamingModeSettings,
- SCREEN_SHARE_MAX_VIDEO_BITRATE_BPS,
- STREAMING_MODE_PRESETS,
- SUPPORTED_SCREEN_SHARE_FRAME_RATES,
- type SupportedScreenShareFrameRate,
-} from '@app/features/voice/utils/ScreenShareOptions';
-import {describe, expect, it} from 'vitest';
-
-const RESOLUTIONS = ['low_240p', 'low_480p', 'medium', 'high', 'ultra', 'source'] as const;
-
-describe('buildScreenShareOptions', () => {
- it('asks display capture to omit the cursor for app windows', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- preferredDisplaySurface: 'window',
- });
- expect(captureOptions.video).toMatchObject({cursor: 'never'});
- });
- it('asks display capture to include the cursor for full displays', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- preferredDisplaySurface: 'monitor',
- });
- expect(captureOptions.video).toMatchObject({
- cursor: 'always',
- displaySurface: 'monitor',
- });
- });
- it('preserves the preferred app display surface while omitting the cursor', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: true,
- preferredDisplaySurface: 'window',
- });
- expect(captureOptions.video).toMatchObject({
- cursor: 'never',
- displaySurface: 'window',
- });
- });
- it('requests own-audio restriction without offering monitor system audio for app window shares', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: true,
- preferredDisplaySurface: 'window',
- });
- expect(captureOptions).toMatchObject({
- audio: true,
- restrictOwnAudio: true,
- systemAudio: 'exclude',
- windowAudio: 'window',
- monitorTypeSurfaces: 'exclude',
- });
- });
- it('does not offer system audio for full display shares', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: true,
- preferredDisplaySurface: 'monitor',
- });
- expect(captureOptions).toMatchObject({
- audio: true,
- restrictOwnAudio: true,
- systemAudio: 'exclude',
- windowAudio: 'window',
- monitorTypeSurfaces: 'include',
- });
- });
- it('excludes window and system audio hints when audio is disabled', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- });
- expect(captureOptions).toMatchObject({
- audio: false,
- systemAudio: 'exclude',
- windowAudio: 'exclude',
- });
- });
- it('prefers resolution for detail-oriented shares', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: true,
- });
- expect(publishOptions.degradationPreference).toBe('maintain-resolution');
- });
- it('keeps resolution for gaming-style high-framerate shares', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'ultra',
- frameRate: 60,
- includeAudio: true,
- });
- expect(publishOptions.degradationPreference).toBe('maintain-resolution');
- });
- it('passes the selected content hint through capture options', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- contentHint: 'motion',
- });
- expect(captureOptions.contentHint).toBe('motion');
- });
- it('leaves screen share content hint unset by default', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- });
- expect(captureOptions.contentHint).toBeUndefined();
- });
- it('publishes the ceiling bitrate for the largest preset', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'source',
- frameRate: 60,
- includeAudio: false,
- });
- expect(publishOptions.screenShareEncoding?.maxBitrate).toBe(SCREEN_SHARE_MAX_VIDEO_BITRATE_BPS);
- });
- it('publishes a lower bitrate for a smaller preset', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- });
- expect(publishOptions.screenShareEncoding?.maxBitrate).toBe(3_000_000);
- });
- it('bills the source preset at the rung the capture geometry actually fills', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'source',
- frameRate: 15,
- includeAudio: false,
- sourceDimensions: {width: 1920, height: 1080},
- });
- expect(publishOptions.screenShareEncoding?.maxBitrate).toBe(3_000_000);
- });
- it('bills a shared window at the rung its pixel count reaches', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'source',
- frameRate: 30,
- includeAudio: false,
- sourceDimensions: {width: 1080, height: 1920},
- });
- expect(publishOptions.screenShareEncoding?.maxBitrate).toBe(4_500_000);
- });
- it('keeps the source preset on its own rung when the capture fills it', () => {
- const {publishOptions} = buildScreenShareOptions({
- resolution: 'source',
- frameRate: 15,
- includeAudio: false,
- sourceDimensions: {width: 3840, height: 2160},
- });
- expect(publishOptions.screenShareEncoding?.maxBitrate).toBe(4_500_000);
- });
- it('defaults the high-tier gaming preset to 60 fps', () => {
- expect(resolveStreamingModeSettings('gaming', 'medium', 30, true)).toEqual({
- resolution: 'ultra',
- frameRate: 60,
- });
- });
- it('keeps free-tier gaming capped at 30 fps', () => {
- expect(resolveStreamingModeSettings('gaming', 'medium', 30, false)).toEqual({
- resolution: 'medium',
- frameRate: 30,
- });
- });
- it('starts the free-tier screenshare preset at 720p 30 fps', () => {
- expect(resolveStreamingModeSettings('screenshare', 'medium', 15, false)).toEqual({
- resolution: 'medium',
- frameRate: 30,
- });
- });
- it('lifts a retired free-tier 240p custom choice back to 720p', () => {
- expect(resolveStreamingModeSettings('custom', 'low_240p', 30, false)).toEqual({
- resolution: 'medium',
- frameRate: 30,
- });
- });
- it('keeps 480p as the lowest free-tier rung', () => {
- expect(resolveStreamingModeSettings('custom', 'low_480p', 30, false)).toEqual({
- resolution: 'low_480p',
- frameRate: 30,
- });
- });
- it('offers the browser picker system audio for every surface when audio is requested', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: true,
- useBrowserAudioPicker: true,
- });
- expect(captureOptions).toMatchObject({
- audio: true,
- systemAudio: 'include',
- windowAudio: 'system',
- });
- });
- it('keeps the browser picker audio hints excluded when audio is not requested', () => {
- const {captureOptions} = buildScreenShareOptions({
- resolution: 'medium',
- frameRate: 30,
- includeAudio: false,
- useBrowserAudioPicker: true,
- });
- expect(captureOptions).toMatchObject({
- audio: false,
- systemAudio: 'exclude',
- windowAudio: 'exclude',
- });
- });
-});
-
-describe('screen share bitrate ladder', () => {
- it('publishes the Twitch anchor bitrates', () => {
- expect(getScreenShareBitrateBps('high', 60)).toBe(6_000_000);
- expect(getScreenShareBitrateBps('high', 30)).toBe(4_500_000);
- expect(getScreenShareBitrateBps('medium', 60)).toBe(4_500_000);
- expect(getScreenShareBitrateBps('medium', 30)).toBe(3_000_000);
- });
-
- it('never exceeds the published ceiling', () => {
- for (const resolution of RESOLUTIONS) {
- for (const frameRate of SUPPORTED_SCREEN_SHARE_FRAME_RATES) {
- expect(getScreenShareBitrateBps(resolution, frameRate)).toBeLessThanOrEqual(SCREEN_SHARE_MAX_VIDEO_BITRATE_BPS);
- }
- }
- });
-
- it('rises with frame rate at every resolution', () => {
- for (const resolution of RESOLUTIONS) {
- let previous = 0;
- for (const frameRate of SUPPORTED_SCREEN_SHARE_FRAME_RATES) {
- const bitrate = getScreenShareBitrateBps(resolution, frameRate);
- expect(bitrate).toBeGreaterThanOrEqual(previous);
- previous = bitrate;
- }
- }
- });
-
- it('rises with resolution at every frame rate', () => {
- for (const frameRate of SUPPORTED_SCREEN_SHARE_FRAME_RATES) {
- let previous = 0;
- for (const resolution of RESOLUTIONS) {
- const bitrate = getScreenShareBitrateBps(resolution, frameRate);
- expect(bitrate).toBeGreaterThanOrEqual(previous);
- previous = bitrate;
- }
- }
- });
-
- it('reuses the 60 fps cell above 60 fps', () => {
- const highFrameRates: Array<SupportedScreenShareFrameRate> = [90, 120];
- for (const resolution of RESOLUTIONS) {
- for (const frameRate of highFrameRates) {
- expect(getScreenShareBitrateBps(resolution, frameRate)).toBe(getScreenShareBitrateBps(resolution, 60));
- }
- }
- });
-
- it('scales the screenshare preset to its own rung', () => {
- const {resolution, frameRate} = STREAMING_MODE_PRESETS.screenshare;
- expect(getScreenShareEncoding(resolution, frameRate).maxBitrate).toBe(4_500_000);
- });
-
- it('scales the gaming preset to its own rung', () => {
- const {resolution, frameRate} = STREAMING_MODE_PRESETS.gaming;
- expect(getScreenShareEncoding(resolution, frameRate).maxBitrate).toBe(6_000_000);
- });
-
- it('varies with frame rate', () => {
- expect(getScreenShareEncoding('medium', 15).maxBitrate).toBe(2_000_000);
- expect(getScreenShareEncoding('medium', 60).maxBitrate).toBe(4_500_000);
- });
-
- it('rounds an unsupported frame rate down to a supported rung', () => {
- expect(getScreenShareEncoding('medium', 45).maxBitrate).toBe(getScreenShareEncoding('medium', 30).maxBitrate);
- expect(getScreenShareEncoding('medium', 45).maxFramerate).toBe(30);
- });
-
- it('caps a selected rung at the rung the captured picture actually fills', () => {
- const encoding = getScreenShareEncoding('source', 30);
- expect(capScreenShareEncodingToDimensions(encoding, {width: 800, height: 600}).maxBitrate).toBe(2_000_000);
- expect(capScreenShareEncodingToDimensions(encoding, {width: 1920, height: 1080}).maxBitrate).toBe(4_500_000);
- });
-
- it('never raises a selected rung to match a larger capture', () => {
- const encoding = getScreenShareEncoding('low_480p', 30);
- expect(capScreenShareEncodingToDimensions(encoding, {width: 3840, height: 2160})).toEqual(encoding);
- });
-
- it('leaves the selected rung alone without usable capture dimensions', () => {
- const encoding = getScreenShareEncoding('high', 60);
- expect(capScreenShareEncodingToDimensions(encoding, undefined)).toEqual(encoding);
- expect(capScreenShareEncodingToDimensions(encoding, {width: 0, height: 1080})).toEqual(encoding);
- expect(capScreenShareEncodingToDimensions(encoding, {width: 1920})).toEqual(encoding);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/ScreenShareStartFlow.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareStartFlow.test.ts
deleted file mode 100644
index b3d7d3fd0..000000000
--- a/fluxer_app/src/features/voice/utils/ScreenShareStartFlow.test.ts
+++ /dev/null
@@ -1,736 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-const platform = {current: 'darwin' as NodeJS.Platform | string};
-
-const voiceSettings = {
- audioSourceMode: 'system' as 'none' | 'system' | 'specific',
- includeSources: [] as Array<Record<string, string>>,
- excludeSources: [] as Array<Record<string, string>>,
- audioDeviceId: 'default',
- deviceUsesMicrophone: false,
-};
-
-const activeShareContext = {current: null as 'app' | 'device' | 'display' | null};
-const activeShareSourceId = {current: null as string | null};
-const activeShareOwnWindow = {current: false};
-const activeWindowAudioScope = {current: 'window' as 'window' | 'system'};
-const pendingWindowAudioScope = {current: null as 'window' | 'system' | null};
-const activeShareVideoDeviceId = {current: ''};
-
-const nativeAudioAvailability = {
- current: {
- available: true,
- backend: 'linux-pipewire',
- capabilities: {process: true, system: true, systemExcludesSelf: true},
- } as {available: boolean; backend?: string; capabilities?: {process: boolean; system: boolean}},
-};
-
-const setScreenShareEnabled = vi.fn(async () => {});
-const replaceActiveDisplayScreenShare = vi.fn(async () => true);
-const startDeviceScreenShare = vi.fn(async () => {});
-const replaceActiveDeviceScreenShare = vi.fn(async () => true);
-const disarmNativeAudio = vi.fn();
-const ensureLinuxScreenShareAudioPublication = vi.fn(async (_rule: Record<string, unknown>) => true);
-const ensureDeviceScreenShareMicPublication = vi.fn(async () => true);
-const ensureWindowScreenShareAudioPublication = vi.fn(async (_sourceId: string) => true);
-const armNativeAudioForNextCapture = vi.fn(async () => true);
-const armNativeSystemAudioForNextCapture = vi.fn(async () => true);
-const armNativeAudioForLinuxRouting = vi.fn(async (_rule: Record<string, unknown>) => true);
-
-const enumerateDevices = vi.fn(async (): Promise<Array<Record<string, string>>> => []);
-Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {mediaDevices: {enumerateDevices}},
-});
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- getElectronAPI: () => ({platform: platform.current}),
- supportsDesktopScreenShareAudioCapture: () => true,
-}));
-
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: {
- room: {localParticipant: {isScreenShareEnabled: true}},
- setScreenShareEnabled,
- replaceActiveDisplayScreenShare,
- startDeviceScreenShare,
- replaceActiveDeviceScreenShare,
- ensureLinuxScreenShareAudioPublication,
- ensureDeviceScreenShareMicPublication,
- ensureWindowScreenShareAudioPublication,
- getActiveScreenShareVideoDeviceId: () => activeShareVideoDeviceId.current,
- },
-}));
-
-vi.mock('@app/features/voice/utils/ScreenShareEnvironment', () => ({
- getDisplayShareEnvironment: async () => 'desktop-custom',
- usesNativeDisplayShareAudioSelection: (environment: string) => environment !== 'desktop-custom',
-}));
-
-vi.mock('@app/features/voice/utils/NativeAudioCaptureBridge', () => ({
- armNativeAudioForLinuxRouting,
- armNativeAudioForNextCapture,
- armNativeSystemAudioForNextCapture,
- disarmNativeAudio,
- disarmPendingNativeAudio: vi.fn(),
- getLastNativeAudioArmFailure: () => null,
- getNativeAudioAvailabilityCached: async () => nativeAudioAvailability.current,
-}));
-
-vi.mock('@app/features/voice/utils/LinuxScreenShareAudio', () => ({
- disarmVirtmic: vi.fn(),
-}));
-
-vi.mock('@app/features/voice/state/ActiveScreenShareSource', () => ({
- default: {
- setPublishedSource: vi.fn(),
- clear: vi.fn(),
- getSourceId: () => activeShareSourceId.current,
- getShareContext: () => activeShareContext.current,
- isOwnWindow: () => activeShareOwnWindow.current,
- getWindowAudioScope: () => activeWindowAudioScope.current,
- setWindowAudioScope: vi.fn((scope: 'window' | 'system') => {
- activeWindowAudioScope.current = scope;
- }),
- getPendingWindowAudioScope: () => pendingWindowAudioScope.current ?? activeWindowAudioScope.current,
- },
-}));
-
-vi.mock('@app/features/voice/state/DesktopSourceIntent', () => ({
- setDesktopSourceIntent: vi.fn(),
- clearDesktopSourceIntent: vi.fn(),
-}));
-
-vi.mock('@app/features/voice/state/LocalVoiceState', () => ({
- default: {getSelfStream: () => null},
-}));
-
-vi.mock('@app/features/voice/utils/ScreenShareUtils', () => ({
- executeScreenShareOperation: async (operation: () => Promise<void>) => {
- await operation();
- },
-}));
-
-vi.mock('@app/features/voice/engine/ScreenShareCodecNegotiation', () => ({
- default: {selectScreenShareCodec: () => 'vp8'},
-}));
-
-vi.mock('@app/features/voice/utils/CodecCapabilityDetector', () => ({
- resolveScreenShareContentHintForContext: () => 'motion',
-}));
-
-vi.mock('@app/features/app/utils/LimitResolverAdapter', () => ({
- LimitResolver: {resolve: () => 0},
-}));
-
-vi.mock('@app/features/app/utils/LimitUtils', () => ({
- isLimitToggleEnabled: () => false,
-}));
-
-vi.mock('@app/features/voice/commands/VoiceSettingsCommands', () => ({
- update: vi.fn(),
-}));
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: {
- getShareAppAudio: () => true,
- getShareDesktopAudio: () => true,
- getShareDeviceAudio: () => true,
- getScreenshareResolution: () => 'medium',
- getStreamingMode: () => 'screenshare',
- getVideoFrameRate: () => 30,
- getPreferredScreenShareCodec: () => 'auto',
- getScreenShareContentHintOverride: () => 'auto',
- getScreenShareMaxBitrateBpsOverride: () => null,
- getScreenShareAudioDeviceId: () => voiceSettings.audioDeviceId,
- getEffectiveScreenShareAudioDeviceId: () =>
- voiceSettings.audioDeviceId === 'default' ? 'mic-1' : voiceSettings.audioDeviceId,
- getScreenShareAudioSourceMode: () => voiceSettings.audioSourceMode,
- getScreenShareAudioIncludeSources: () => voiceSettings.includeSources,
- getScreenShareAudioExcludeSources: () => voiceSettings.excludeSources,
- getScreenShareDeviceAudioUsesMicrophone: () => voiceSettings.deviceUsesMicrophone,
- getEffectiveScreenShareAudioSourceMode: () => voiceSettings.audioSourceMode,
- getEffectiveScreenShareAudioIncludeSources: () => voiceSettings.includeSources,
- getEffectiveScreenShareAudioExcludeSources: () => voiceSettings.excludeSources,
- getLinuxAudioCaptureIgnoreInputMedia: () => true,
- getLinuxAudioCaptureIgnoreVirtual: () => false,
- getLinuxAudioCaptureIgnoreDevices: () => true,
- getLinuxAudioCaptureOnlySpeakers: () => true,
- getLinuxAudioCaptureOnlyDefaultSpeakers: () => true,
- },
-}));
-
-const {
- applyLiveScreenShareAudioSourceChange,
- reconfigureActiveDeviceShareAudio,
- reconfigureActiveLinuxAppShareAudio,
- startConfiguredDeviceScreenShare,
- startConfiguredDisplayScreenShare,
- switchConfiguredDeviceScreenShare,
- switchConfiguredDisplayScreenShare,
-} = await import('@app/features/voice/utils/ScreenShareStartFlow');
-const {isScreenShareAudioCaptureError} = await import('@app/features/voice/utils/ScreenShareAudioCaptureError');
-const ActiveScreenShareSource = (await import('@app/features/voice/state/ActiveScreenShareSource')).default;
-
-beforeEach(() => {
- platform.current = 'darwin';
- voiceSettings.audioSourceMode = 'system';
- voiceSettings.includeSources = [];
- voiceSettings.excludeSources = [];
- voiceSettings.audioDeviceId = 'default';
- voiceSettings.deviceUsesMicrophone = false;
- activeShareContext.current = null;
- activeShareSourceId.current = null;
- activeShareOwnWindow.current = false;
- activeWindowAudioScope.current = 'window';
- pendingWindowAudioScope.current = null;
- activeShareVideoDeviceId.current = '';
- nativeAudioAvailability.current = {
- available: true,
- backend: 'linux-pipewire',
- capabilities: {process: true, system: true},
- };
- vi.clearAllMocks();
- setScreenShareEnabled.mockResolvedValue(undefined);
- armNativeAudioForNextCapture.mockResolvedValue(true);
- replaceActiveDeviceScreenShare.mockResolvedValue(true);
- ensureLinuxScreenShareAudioPublication.mockResolvedValue(true);
- ensureDeviceScreenShareMicPublication.mockResolvedValue(true);
- ensureWindowScreenShareAudioPublication.mockResolvedValue(true);
- enumerateDevices.mockResolvedValue([]);
-});
-
-function deviceShareAudioDeviceId(call: unknown): string | undefined {
- return (call as [{audioDeviceId?: string}, unknown])[0].audioDeviceId;
-}
-
-describe('sharing a video device', () => {
- test('takes its audio from the configured input device on every desktop platform', async () => {
- for (const current of ['linux', 'win32', 'darwin']) {
- vi.clearAllMocks();
- platform.current = current;
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- }
- });
-
- test('opens no microphone and links the selected applications', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBeUndefined();
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(1);
- });
-
- test('keeps the microphone while no application is selected', async () => {
- platform.current = 'linux';
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('keeps the microphone on a device share whose stored source mode says none', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'none';
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
-
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
- expect(ensureDeviceScreenShareMicPublication).toHaveBeenCalledWith('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('keeps the microphone when the picked applications cannot be routed', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'fluxer.display.name': 'mpv'}];
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('never routes application audio into a device share off Linux', async () => {
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('never routes application audio when the capture layer cannot express a selection', async () => {
- platform.current = 'linux';
- nativeAudioAvailability.current = {available: false, backend: 'linux-pipewire'};
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('prefers the shared capture card own audio input while no device was ever chosen', async () => {
- platform.current = 'linux';
- enumerateDevices.mockResolvedValue([
- {kind: 'videoinput', deviceId: 'camera-1', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'default', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'elgato-line-in', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'headset', groupId: 'usb-headset'},
- ]);
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('elgato-line-in');
- });
-
- test('keeps a chosen audio device instead of pairing one with the video device', async () => {
- platform.current = 'linux';
- voiceSettings.audioDeviceId = 'headset';
- enumerateDevices.mockResolvedValue([
- {kind: 'videoinput', deviceId: 'camera-1', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'elgato-line-in', groupId: 'elgato'},
- ]);
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('headset');
- });
-
- test('falls back to the voice input device when the capture card exposes no audio input', async () => {
- platform.current = 'linux';
- enumerateDevices.mockResolvedValue([
- {kind: 'videoinput', deviceId: 'camera-1', groupId: 'webcam'},
- {kind: 'audioinput', deviceId: 'headset', groupId: 'usb-headset'},
- ]);
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- });
-
- test('relinks the selected applications after switching the capture device', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await switchConfiguredDeviceScreenShare('camera-2')).toBe(true);
-
- expect(deviceShareAudioDeviceId(replaceActiveDeviceScreenShare.mock.calls[0])).toBeUndefined();
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(1);
- });
-
- test('does not relink application audio when the device switch fails', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
- replaceActiveDeviceScreenShare.mockResolvedValue(false);
-
- expect(await switchConfiguredDeviceScreenShare('camera-2')).toBe(false);
-
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('swaps a live device share between the microphone and the selected applications', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(1);
- expect(ensureDeviceScreenShareMicPublication).not.toHaveBeenCalled();
-
- voiceSettings.includeSources = [];
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(1);
- expect(ensureDeviceScreenShareMicPublication).toHaveBeenCalledWith('mic-1');
-
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(2);
- expect(ensureDeviceScreenShareMicPublication).toHaveBeenCalledTimes(1);
- });
-
- test('keeps the microphone the device picker chose while the shared application selection stands', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
- voiceSettings.deviceUsesMicrophone = true;
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBe('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
-
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
- expect(ensureDeviceScreenShareMicPublication).toHaveBeenCalledWith('mic-1');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
-
- expect(voiceSettings.audioSourceMode).toBe('specific');
- expect(voiceSettings.includeSources).toEqual([{'application.name': 'mpv'}]);
- });
-
- test('routes the selected applications again once the device picker leaves the microphone', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
- voiceSettings.deviceUsesMicrophone = false;
-
- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);
-
- expect(deviceShareAudioDeviceId(startDeviceScreenShare.mock.calls[0])).toBeUndefined();
- expect(ensureLinuxScreenShareAudioPublication).toHaveBeenCalledTimes(1);
- });
-
- test('keeps the paired capture card input when the live share rebinds its microphone', async () => {
- platform.current = 'linux';
- activeShareVideoDeviceId.current = 'camera-1';
- enumerateDevices.mockResolvedValue([
- {kind: 'videoinput', deviceId: 'camera-1', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'elgato-line-in', groupId: 'elgato'},
- {kind: 'audioinput', deviceId: 'mic-1', groupId: 'usb-headset'},
- ]);
-
- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);
-
- expect(ensureDeviceScreenShareMicPublication).toHaveBeenCalledWith('elgato-line-in');
- });
-});
-
-describe('sharing a whole display', () => {
- test('captures the desktop mix without Fluxer on Linux when nothing is selected', async () => {
- platform.current = 'linux';
- voiceSettings.excludeSources = [{'application.name': 'Discord'}];
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(armNativeAudioForLinuxRouting).toHaveBeenCalledTimes(1);
- expect(armNativeAudioForLinuxRouting.mock.calls[0][0]).toMatchObject({
- include: [],
- exclude: [{'application.name': 'Discord'}],
- ignoreInputMedia: true,
- onlySpeakers: true,
- onlyDefaultSpeakers: true,
- });
- });
-
- test('publishes no audio at all when the stored selection asks for none', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'none';
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- const call = setScreenShareEnabled.mock.calls[0] as unknown as [boolean, {audio: boolean}, unknown];
- expect(call[1].audio).toBe(false);
- });
-
- test('honours the stored include list', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(armNativeAudioForLinuxRouting.mock.calls[0][0]).toMatchObject({
- include: [{'application.name': 'mpv'}],
- ignoreInputMedia: true,
- });
- });
-
- test('keeps the stored include list while a device share of its own is on the microphone', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
- voiceSettings.deviceUsesMicrophone = true;
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(armNativeAudioForLinuxRouting.mock.calls[0][0]).toMatchObject({
- include: [{'application.name': 'mpv'}],
- ignoreInputMedia: true,
- });
- });
-
- test('arms native system audio on Windows and macOS', async () => {
- for (const current of ['win32', 'darwin']) {
- vi.clearAllMocks();
- platform.current = current;
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(armNativeSystemAudioForNextCapture).toHaveBeenCalledTimes(1);
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- }
- });
-});
-
-describe('sharing a Fluxer-owned window while app audio is enabled', () => {
- test('starts the share video-only instead of failing', async () => {
- const started = await startConfiguredDisplayScreenShare('window:99:0', {
- isOwnWindow: true,
- preferredDisplaySurface: 'window',
- });
-
- expect(started).toBe(true);
- expect(setScreenShareEnabled).toHaveBeenCalledTimes(1);
- const call = setScreenShareEnabled.mock.calls[0] as unknown as [
- boolean,
- {audio: boolean; systemAudio: string; windowAudio: string},
- unknown,
- ];
- expect(call[0]).toBe(true);
- expect(call[1].audio).toBe(false);
- expect(call[1].systemAudio).toBe('exclude');
- expect(call[1].windowAudio).toBe('exclude');
- expect(armNativeAudioForNextCapture).not.toHaveBeenCalled();
- });
-});
-
-describe('sharing another application window while app audio is enabled', () => {
- test('arms native per-window audio and hard-fails when it cannot be armed', async () => {
- armNativeAudioForNextCapture.mockResolvedValue(false);
-
- await expect(
- startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'}),
- ).rejects.toSatisfy(isScreenShareAudioCaptureError);
- expect(armNativeAudioForNextCapture).toHaveBeenCalledWith('window:42:0');
- expect(setScreenShareEnabled).not.toHaveBeenCalled();
- });
-
- test('takes the shared window own audio by default on Linux, never the whole system mix', async () => {
- platform.current = 'linux';
- voiceSettings.excludeSources = [{'application.name': 'Discord'}];
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).toHaveBeenCalledWith('window:42:0');
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- });
-
- test('widens a Linux window share to the system mix minus the stored exclusions on request', async () => {
- platform.current = 'linux';
- pendingWindowAudioScope.current = 'system';
- voiceSettings.excludeSources = [{'application.name': 'Discord'}];
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).not.toHaveBeenCalled();
- expect(armNativeAudioForLinuxRouting).toHaveBeenCalledTimes(1);
- expect(armNativeAudioForLinuxRouting.mock.calls[0][0]).toMatchObject({
- include: [],
- exclude: [{'application.name': 'Discord'}],
- onlySpeakers: true,
- onlyDefaultSpeakers: true,
- });
- });
-
- test('ignores a stored display-share selection until the window scope is widened', async () => {
- for (const audioSourceMode of ['none', 'specific'] as const) {
- vi.clearAllMocks();
- platform.current = 'linux';
- voiceSettings.audioSourceMode = audioSourceMode;
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).toHaveBeenCalledWith('window:42:0');
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- }
- });
-
- test('routes the picked applications once the window share was widened to the system', async () => {
- platform.current = 'linux';
- pendingWindowAudioScope.current = 'system';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).not.toHaveBeenCalled();
- expect(armNativeAudioForLinuxRouting.mock.calls[0][0]).toMatchObject({
- include: [{'application.name': 'mpv'}],
- });
- });
-
- test('captures the shared window rather than the whole desktop when the picked apps cannot be routed', async () => {
- platform.current = 'linux';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'fluxer.display.name': 'mpv'}];
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).toHaveBeenCalledWith('window:42:0');
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- });
-
- test('publishes no audio at all on a widened Linux window share asked for none', async () => {
- platform.current = 'linux';
- pendingWindowAudioScope.current = 'system';
- voiceSettings.audioSourceMode = 'none';
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(armNativeAudioForNextCapture).not.toHaveBeenCalled();
- expect(armNativeAudioForLinuxRouting).not.toHaveBeenCalled();
- const call = setScreenShareEnabled.mock.calls[0] as unknown as [boolean, {audio: boolean}, unknown];
- expect(call[1].audio).toBe(false);
- });
-
- test('commits the scope it armed to the running share', async () => {
- platform.current = 'linux';
- pendingWindowAudioScope.current = 'system';
-
- expect(await startConfiguredDisplayScreenShare('window:42:0', {preferredDisplaySurface: 'window'})).toBe(true);
-
- expect(ActiveScreenShareSource.setWindowAudioScope).toHaveBeenCalledWith('system');
- });
-
- test('never carries a window scope over into a display share', async () => {
- platform.current = 'linux';
- pendingWindowAudioScope.current = 'system';
-
- expect(await startConfiguredDisplayScreenShare('screen:1')).toBe(true);
-
- expect(ActiveScreenShareSource.setWindowAudioScope).toHaveBeenCalledWith('window');
- });
-});
-
-describe('changing the audio sources of a live window share', () => {
- test('re-publishes the shared window own audio while the scope is the window', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
-
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(true);
-
- expect(ensureWindowScreenShareAudioPublication).toHaveBeenCalledWith('window:42:0');
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('relinks a widened window share through the manual rule instead', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
- activeWindowAudioScope.current = 'system';
- voiceSettings.excludeSources = [{'application.name': 'Discord'}];
-
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(true);
-
- expect(ensureWindowScreenShareAudioPublication).not.toHaveBeenCalled();
- expect(ensureLinuxScreenShareAudioPublication.mock.calls[0][0]).toMatchObject({
- include: [],
- exclude: [{'application.name': 'Discord'}],
- });
- });
-
- test('relinks the picked applications on a live window share that was widened', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
- activeWindowAudioScope.current = 'system';
- voiceSettings.audioSourceMode = 'specific';
- voiceSettings.includeSources = [{'application.name': 'mpv'}];
-
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(true);
-
- expect(ensureWindowScreenShareAudioPublication).not.toHaveBeenCalled();
- expect(ensureLinuxScreenShareAudioPublication.mock.calls[0][0]).toMatchObject({
- include: [{'application.name': 'mpv'}],
- });
- });
-
- test('leaves a window share alone off Linux, and drops its audio when no window source is published', async () => {
- platform.current = 'darwin';
- activeShareSourceId.current = 'window:42:0';
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(false);
- expect(disarmNativeAudio).not.toHaveBeenCalled();
-
- platform.current = 'linux';
- activeShareSourceId.current = null;
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(false);
- expect(disarmNativeAudio).toHaveBeenCalledTimes(1);
-
- expect(ensureWindowScreenShareAudioPublication).not.toHaveBeenCalled();
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-
- test('drops the audio rather than keeping the system mix live when narrowing back to the window fails', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
- activeWindowAudioScope.current = 'system';
- ensureWindowScreenShareAudioPublication.mockResolvedValue(false);
-
- expect(await applyLiveScreenShareAudioSourceChange('app', 'window')).toBe(false);
-
- expect(ensureWindowScreenShareAudioPublication).toHaveBeenCalledWith('window:42:0');
- expect(disarmNativeAudio).toHaveBeenCalledTimes(1);
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('system');
- });
-
- test('drops the audio rather than keeping the system mix live when the window publication throws', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
- activeWindowAudioScope.current = 'system';
- ensureWindowScreenShareAudioPublication.mockRejectedValue(new Error('window vanished'));
-
- expect(await applyLiveScreenShareAudioSourceChange('app', 'window')).toBe(false);
-
- expect(disarmNativeAudio).toHaveBeenCalledTimes(1);
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('system');
- });
-
- test('commits the narrowed scope only once the window audio is actually publishing', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:42:0';
- activeWindowAudioScope.current = 'system';
-
- expect(await applyLiveScreenShareAudioSourceChange('app', 'window')).toBe(true);
-
- expect(ActiveScreenShareSource.getWindowAudioScope()).toBe('window');
- });
-
- test('never routes audio into a Fluxer-owned window share', async () => {
- platform.current = 'linux';
- activeShareSourceId.current = 'window:99:0';
- activeShareOwnWindow.current = true;
-
- expect(await reconfigureActiveLinuxAppShareAudio()).toBe(false);
-
- expect(ensureWindowScreenShareAudioPublication).not.toHaveBeenCalled();
- expect(ensureLinuxScreenShareAudioPublication).not.toHaveBeenCalled();
- });
-});
-
-describe('switching the display source', () => {
- test('preserves the running share state when the switch fails', async () => {
- replaceActiveDisplayScreenShare.mockResolvedValue(false);
-
- const switched = await switchConfiguredDisplayScreenShare('window:7:0', {preferredDisplaySurface: 'window'});
-
- expect(switched).toBe(false);
- expect(ActiveScreenShareSource.clear).not.toHaveBeenCalled();
- expect(ActiveScreenShareSource.setPublishedSource).not.toHaveBeenCalled();
- });
-
- test('records the new published source when the switch succeeds', async () => {
- replaceActiveDisplayScreenShare.mockResolvedValue(true);
-
- const switched = await switchConfiguredDisplayScreenShare('window:7:0', {preferredDisplaySurface: 'window'});
-
- expect(switched).toBe(true);
- expect(ActiveScreenShareSource.setPublishedSource).toHaveBeenCalledWith('app', 'window:7:0', {isOwnWindow: false});
- expect(ActiveScreenShareSource.clear).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/StatsForNerdsCopy.test.ts b/fluxer_app/src/features/voice/utils/StatsForNerdsCopy.test.ts
deleted file mode 100644
index efd9f6c4d..000000000
--- a/fluxer_app/src/features/voice/utils/StatsForNerdsCopy.test.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {StatsForNerdsData} from '@app/features/voice/utils/VoiceStatsForNerdsPresenter';
-import {describe, expect, it, vi} from 'vitest';
-
-const failureRecord = {
- code: -2303,
- reason: 'first-frame-timeout',
- reportedAt: 1000,
- streamKey: 'guild-a:channel-a:connection-a',
- trackSid: 'TR_screen_share',
- participantIdentity: 'user_1_connection-a',
- inbound: {
- packetsReceived: 4210,
- bytesReceived: 3_500_000,
- framesReceived: 0,
- framesDecoded: 0,
- keyFramesDecoded: 0,
- framesDropped: 0,
- pliCount: 7,
- firCount: 0,
- nackCount: 2,
- freezeCount: 0,
- decoderImplementation: 'ExternalDecoder (D3D11VideoDecoder)',
- powerEfficientDecoder: true,
- mimeType: 'video/H264',
- sdpFmtpLine: 'profile-level-id=42e01f',
- frameWidth: 1920,
- frameHeight: 1080,
- },
- tile: {
- hasVideoElement: true,
- readyState: 0,
- videoWidth: 0,
- videoHeight: 0,
- clientWidth: 960,
- clientHeight: 540,
- visibilityState: 'visible',
- },
-};
-
-const localCodecs = [{name: 'h264', type: 'video', payload_type: 108, priority: 900, encode: true, decode: true}];
-
-const subscriptionDebugReport = {capturedAt: '2026-09-11T00:00:00.000Z', failures: []};
-
-vi.mock('@app/features/app/config/Config', () => ({default: {PUBLIC_BUILD_VERSION: 'test'}}));
-
-vi.mock('@app/features/devtools/utils/DesktopTroubleshootingUtils', () => ({
- getCachedDesktopTroubleshootingSettings: () => null,
- getDesktopTroubleshootingSettings: async () => ({}),
-}));
-
-vi.mock('@app/features/ui/utils/NativeUtils', () => ({
- getElectronAPI: () => null,
- getNativePlatform: async () => 'web',
- isDesktop: () => false,
- supportsDesktopScreenShareAudioCapture: () => false,
-}));
-
-vi.mock('@app/features/voice/diagnostics/VoiceSubscriptionDebugReport', () => ({
- collectVoiceSubscriptionDebugReport: () => subscriptionDebugReport,
-}));
-
-vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({
- default: {
- room: null,
- connected: false,
- connecting: false,
- guildId: null,
- channelId: null,
- connectionId: null,
- voiceServerEndpoint: null,
- voiceStats: null,
- perTrackStats: [],
- statsTimeSeries: [],
- publisherTransport: null,
- subscriberTransport: null,
- },
-}));
-
-vi.mock('@app/features/voice/engine/ScreenShareCodecNegotiation', () => ({
- default: {
- getSelectedCodec: () => 'h264',
- getLocalCodecAdvertisements: () => localCodecs,
- getRemoteDecodeCodecsByIdentity: () => ({'user_1_connection-a': ['h264', 'vp8']}),
- },
- getScreenShareCodecPreferenceOrder: () => ['h264', 'vp8'],
-}));
-
-vi.mock('@app/features/voice/engine/voice_screen_share_manager/NativeEngineAudioTrackPump', () => ({
- getNativeEngineAudioTrackPumpStats: () => null,
-}));
-
-vi.mock('@app/features/voice/engine/voice_screen_share_manager/shared', () => ({
- getPublishedScreenShareMaxBitrateBps: () => null,
-}));
-
-vi.mock('@app/features/voice/state/ScreenShareWatchFailures', () => ({
- ScreenShareWatchFailures: {getFailureHistory: () => [failureRecord]},
-}));
-
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({
- default: new Proxy({}, {get: () => () => null}),
-}));
-
-vi.mock('@app/features/voice/utils/CodecCapabilityDetector', () => ({
- getCameraPublishCodecPolicy: () => ({primary: 'h264'}),
- getCodecCapabilityReport: () => ({}),
- getLiveKitSupportedCodecs: () => ['h264', 'vp8'],
- selectOptimalScreenShareCodec: () => 'h264',
-}));
-
-vi.mock('@app/features/voice/utils/GpuEncoderCapabilities', () => ({loadGpuEncoderReport: async () => null}));
-
-vi.mock('@app/features/voice/utils/NativeAudioCaptureBridge', () => ({
- getNativeAudioBridgeStats: () => null,
- getNativeAudioCaptureDiagnosticState: () => null,
-}));
-
-vi.mock('@app/features/voice/utils/ScreenShareEnvironment', () => ({getDisplayShareEnvironment: async () => ({})}));
-
-vi.mock('@app/features/voice/utils/ScreenShareOptions', () => ({
- getScreenShareBitrateBps: () => 2_500_000,
- resolveStreamingModeSettings: () => ({resolution: 1080, frameRate: 60}),
-}));
-
-vi.mock('@app/features/voice/utils/VideoDecoderCapabilities', () => ({
- getScreenShareDecodeFailures: () => new Set(['vp9']),
-}));
-
-vi.mock('@app/features/voice/utils/VideoQualityEntitlement', () => ({hasHigherVideoQuality: () => false}));
-
-vi.mock('@app/features/voice/utils/VoiceStatsForNerdsPresenter', () => ({
- buildVoiceStatsForNerdsPresentation: () => ({}),
- collectScreenShareAudioPublicationDiagnostics: () => [],
-}));
-
-const {buildStatsForNerdsCopyPayload} = await import('@app/features/voice/utils/StatsForNerdsCopy');
-
-describe('buildStatsForNerdsCopyPayload watch failure diagnostics', () => {
- it('copies the screen share failure ring with its codes, track sids and inbound counters', async () => {
- const payload = await buildStatsForNerdsCopyPayload({} as StatsForNerdsData);
-
- expect(payload.screenShareWatchFailures).toEqual([failureRecord]);
- });
-
- it('copies the screen share negotiation block with the selected codec and decode sets', async () => {
- const payload = await buildStatsForNerdsCopyPayload({} as StatsForNerdsData);
-
- expect(payload.screenShareNegotiation).toEqual({
- selectedCodec: 'h264',
- localCodecs,
- remoteDecodeCodecsByIdentity: {'user_1_connection-a': ['h264', 'vp8']},
- decodeFailures: ['vp9'],
- });
- });
-
- it('copies the voice subscription debug report that was only reachable from the debug console', async () => {
- const payload = await buildStatsForNerdsCopyPayload({} as StatsForNerdsData);
-
- expect(payload.voiceSubscriptionDebug).toEqual(subscriptionDebugReport);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.ts b/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.ts
deleted file mode 100644
index 3f3a36275..000000000
--- a/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- canSelectManualAudioSources,
- isLinuxDesktopAudioShare,
- manualAudioSourcesGovernShare,
- resolveWindowShareAudioScope,
- routesManualAudioSources,
- selectAppShareAudioRoute,
- shouldReconfigureAudioForActiveStreamSettings,
- supportsWindowShareAudioScope,
-} from '@app/features/voice/utils/StreamSettingsUpdatePolicy';
-import type {NativeAudioAvailability} from '@app/types/electron.d';
-import {describe, expect, it} from 'vitest';
-
-const LINUX_PIPEWIRE: NativeAudioAvailability = {
- available: true,
- backend: 'linux-pipewire',
- capabilities: {process: true, system: true, systemExcludesSelf: true},
-};
-const WINDOWS_WASAPI: NativeAudioAvailability = {
- available: true,
- backend: 'windows-wasapi-loopback',
- capabilities: {
- process: true,
- system: true,
- systemExcludesSelf: true,
- processInclude: true,
- processExclude: true,
- sessionMixer: true,
- systemLoopbackMode: 'process-exclude',
- },
-};
-const MACOS_SCK: NativeAudioAvailability = {
- available: true,
- backend: 'macos-sck',
- capabilities: {process: true, system: true, systemExcludesSelf: true},
-};
-
-describe('StreamSettingsUpdatePolicy', () => {
- it('reconfigures Linux audio only for live desktop audio shares with changed audio settings', () => {
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform: 'linux',
- shareContext: 'display',
- audioSettingsChanged: true,
- }),
- ).toBe(true);
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform: 'linux',
- shareContext: 'app',
- audioSettingsChanged: true,
- }),
- ).toBe(true);
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform: 'linux',
- shareContext: 'display',
- audioSettingsChanged: false,
- }),
- ).toBe(false);
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform: 'win32',
- shareContext: 'display',
- audioSettingsChanged: true,
- }),
- ).toBe(false);
- expect(isLinuxDesktopAudioShare({platform: 'linux', shareContext: 'device'})).toBe(false);
- });
-
- it('reconfigures a device share on any platform whenever its audio settings change', () => {
- for (const platform of ['linux', 'win32', 'darwin']) {
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform,
- shareContext: 'device',
- audioSettingsChanged: true,
- }),
- ).toBe(true);
- expect(
- shouldReconfigureAudioForActiveStreamSettings({
- platform,
- shareContext: 'device',
- audioSettingsChanged: false,
- }),
- ).toBe(false);
- }
- });
-
- it('offers manual audio source selection only where the capture layer can express it', () => {
- expect(canSelectManualAudioSources({platform: 'linux', nativeAudioAvailability: LINUX_PIPEWIRE})).toBe(true);
- expect(canSelectManualAudioSources({platform: 'win32', nativeAudioAvailability: WINDOWS_WASAPI})).toBe(false);
- expect(canSelectManualAudioSources({platform: 'darwin', nativeAudioAvailability: MACOS_SCK})).toBe(false);
- expect(canSelectManualAudioSources({platform: 'linux', nativeAudioAvailability: null})).toBe(false);
- expect(
- canSelectManualAudioSources({
- platform: 'linux',
- nativeAudioAvailability: {available: false, backend: 'linux-pipewire', reason: 'no-pipewire'},
- }),
- ).toBe(false);
- expect(
- canSelectManualAudioSources({
- platform: 'linux',
- nativeAudioAvailability: {available: true, capabilities: {process: false, system: true}},
- }),
- ).toBe(false);
- });
-
- it('offers manual audio source selection on every desktop share type, with no opt-in left to satisfy', () => {
- expect(
- canSelectManualAudioSources({
- platform: 'linux',
- nativeAudioAvailability: LINUX_PIPEWIRE,
- }),
- ).toBe(true);
- for (const displayShareEnvironment of ['desktop-custom', 'desktop-wayland'] as const) {
- expect(manualAudioSourcesGovernShare({platform: 'linux', displayShareEnvironment})).toBe(true);
- }
- });
-
- it('leaves the audio source decision to the platform wherever the stored mode cannot reach the capture', () => {
- expect(manualAudioSourcesGovernShare({platform: 'linux', displayShareEnvironment: 'web'})).toBe(false);
- for (const platform of ['win32', 'darwin', null, undefined]) {
- expect(manualAudioSourcesGovernShare({platform, displayShareEnvironment: 'desktop-custom'})).toBe(false);
- }
- });
-
- it('offers the window audio scope only to a window share whose window the capture layer can name', () => {
- expect(supportsWindowShareAudioScope({shareContext: 'app', displayShareEnvironment: 'desktop-custom'})).toBe(true);
- expect(supportsWindowShareAudioScope({shareContext: 'app', displayShareEnvironment: 'desktop-wayland'})).toBe(
- false,
- );
- expect(supportsWindowShareAudioScope({shareContext: 'app', displayShareEnvironment: 'web'})).toBe(false);
- expect(supportsWindowShareAudioScope({shareContext: 'app'})).toBe(false);
- for (const shareContext of ['device', 'display'] as const) {
- expect(supportsWindowShareAudioScope({shareContext, displayShareEnvironment: 'desktop-custom'})).toBe(false);
- }
- });
-
- it('defaults a window share to its own window and widens only where the user asked for it', () => {
- expect(resolveWindowShareAudioScope({shareContext: 'app', displayShareEnvironment: 'desktop-custom'})).toBe(
- 'window',
- );
- expect(
- resolveWindowShareAudioScope({
- shareContext: 'app',
- displayShareEnvironment: 'desktop-custom',
- windowAudioScope: 'window',
- }),
- ).toBe('window');
- expect(
- resolveWindowShareAudioScope({
- shareContext: 'app',
- displayShareEnvironment: 'desktop-custom',
- windowAudioScope: 'system',
- }),
- ).toBe('system');
- expect(
- resolveWindowShareAudioScope({
- shareContext: 'app',
- displayShareEnvironment: 'desktop-wayland',
- windowAudioScope: 'window',
- }),
- ).toBe('system');
- for (const shareContext of ['device', 'display'] as const) {
- expect(
- resolveWindowShareAudioScope({
- shareContext,
- displayShareEnvironment: 'desktop-custom',
- windowAudioScope: 'window',
- }),
- ).toBe('system');
- }
- });
-
- it('keeps a window share on its own window until the user widens the scope', () => {
- for (const audioSourceMode of ['none', 'system', 'specific'] as const) {
- for (const selectedSourceCount of [0, 2]) {
- expect(selectAppShareAudioRoute({audioSourceMode, selectedSourceCount, windowAudioScope: 'window'})).toBe(
- 'window',
- );
- }
- }
- expect(selectAppShareAudioRoute({windowAudioScope: 'window'})).toBe('window');
- });
-
- it('lets the stored selection govern a window share only once it is widened to the system', () => {
- expect(selectAppShareAudioRoute({audioSourceMode: 'system', windowAudioScope: 'system'})).toBe('system');
- expect(selectAppShareAudioRoute({windowAudioScope: 'system'})).toBe('system');
- expect(selectAppShareAudioRoute({audioSourceMode: 'none', windowAudioScope: 'system'})).toBe('none');
- expect(
- selectAppShareAudioRoute({audioSourceMode: 'specific', selectedSourceCount: 2, windowAudioScope: 'system'}),
- ).toBe('apps');
- expect(
- selectAppShareAudioRoute({audioSourceMode: 'specific', selectedSourceCount: 0, windowAudioScope: 'system'}),
- ).toBe('system');
- });
-
- it('routes manual audio sources only once specific sources are selected', () => {
- const base = {
- platform: 'linux',
- shareContext: 'device',
- nativeAudioAvailability: LINUX_PIPEWIRE,
- } as const;
- expect(routesManualAudioSources({...base, audioSourceMode: 'specific', selectedSourceCount: 1})).toBe(true);
- expect(routesManualAudioSources({...base, audioSourceMode: 'specific', selectedSourceCount: 0})).toBe(false);
- expect(routesManualAudioSources({...base, audioSourceMode: 'system', selectedSourceCount: 2})).toBe(false);
- expect(routesManualAudioSources({...base, audioSourceMode: 'none', selectedSourceCount: 2})).toBe(false);
- expect(
- routesManualAudioSources({
- ...base,
- platform: 'win32',
- nativeAudioAvailability: WINDOWS_WASAPI,
- audioSourceMode: 'specific',
- selectedSourceCount: 2,
- }),
- ).toBe(false);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VideoAccelerationClassification.test.ts b/fluxer_app/src/features/voice/utils/VideoAccelerationClassification.test.ts
deleted file mode 100644
index cfd8d17c7..000000000
--- a/fluxer_app/src/features/voice/utils/VideoAccelerationClassification.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- classifyVideoDecoderAcceleration,
- classifyVideoEncoderAcceleration,
- isHardwareVideoImplementation,
- isSoftwareVideoImplementation,
-} from '@app/features/voice/utils/VideoAccelerationClassification';
-import {describe, expect, it} from 'vitest';
-
-describe('video acceleration implementation classification', () => {
- it('detects common software implementations', () => {
- expect(isSoftwareVideoImplementation('FFmpegVideoDecoder')).toBe(true);
- expect(isSoftwareVideoImplementation('Dav1dVideoDecoder')).toBe(true);
- expect(isSoftwareVideoImplementation('libvpx')).toBe(true);
- expect(isSoftwareVideoImplementation('OpenH264')).toBe(true);
- });
-
- it('detects common hardware implementations', () => {
- expect(isHardwareVideoImplementation('D3D11VideoDecoder')).toBe(true);
- expect(isHardwareVideoImplementation('VideoToolboxVideoDecoder')).toBe(true);
- expect(isHardwareVideoImplementation('VaapiVideoDecoder')).toBe(true);
- expect(isHardwareVideoImplementation('NVENCVideoEncoder')).toBe(true);
- expect(isHardwareVideoImplementation('h264_qsv')).toBe(true);
- });
-});
-
-describe('video acceleration status classification', () => {
- it('prefers a known software implementation over power efficiency', () => {
- expect(classifyVideoDecoderAcceleration('FFmpegVideoDecoder', true)).toBe('software');
- expect(classifyVideoEncoderAcceleration('libaom', true)).toBe('software');
- });
-
- it('prefers a known hardware implementation over power efficiency', () => {
- expect(classifyVideoDecoderAcceleration('D3D11VideoDecoder', false)).toBe('hardware');
- expect(classifyVideoEncoderAcceleration('VideoToolboxVideoEncoder', false)).toBe('hardware');
- });
-
- it('falls back to WebRTC power efficiency flags when implementation is hidden', () => {
- expect(classifyVideoDecoderAcceleration(undefined, true)).toBe('hardware');
- expect(classifyVideoDecoderAcceleration(undefined, false)).toBe('software');
- expect(classifyVideoEncoderAcceleration(undefined, true)).toBe('hardware');
- expect(classifyVideoEncoderAcceleration(undefined, false)).toBe('software');
- });
-
- it('returns unknown when no useful signal is exposed', () => {
- expect(classifyVideoDecoderAcceleration(undefined, undefined)).toBe('unknown');
- expect(classifyVideoEncoderAcceleration('MysteryVideoEncoder', undefined)).toBe('unknown');
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.test.ts b/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.test.ts
deleted file mode 100644
index dd1bf6ca4..000000000
--- a/fluxer_app/src/features/voice/utils/VoiceCameraCapacity.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- countDistinctCameraUsers,
- isCameraUserCapBlocked,
- type VoiceCameraCapacityVoiceState,
-} from '@app/features/voice/utils/VoiceCameraCapacity';
-import {VOICE_CHANNEL_CAMERA_USER_LIMIT} from '@fluxer/constants/src/LimitConstants';
-import {describe, expect, it} from 'vitest';
-
-function buildVoiceStates(
- cameraUserCount: number,
- options: {extraConnectionsForUser?: string; nonCameraUserCount?: number} = {},
-): Record<string, VoiceCameraCapacityVoiceState> {
- const voiceStates: Record<string, VoiceCameraCapacityVoiceState> = {};
- for (let i = 0; i < cameraUserCount; i++) {
- voiceStates[`conn-camera-${i}`] = {user_id: `user-${i}`, self_video: true};
- }
- for (let i = 0; i < (options.nonCameraUserCount ?? 0); i++) {
- voiceStates[`conn-idle-${i}`] = {user_id: `idle-user-${i}`, self_video: false};
- }
- if (options.extraConnectionsForUser) {
- voiceStates['conn-extra-1'] = {user_id: options.extraConnectionsForUser, self_video: true};
- voiceStates['conn-extra-2'] = {user_id: options.extraConnectionsForUser, self_video: true};
- }
- return voiceStates;
-}
-
-describe('countDistinctCameraUsers', () => {
- it('counts only users with self_video enabled', () => {
- expect(countDistinctCameraUsers(buildVoiceStates(3, {nonCameraUserCount: 5}))).toBe(3);
- });
-
- it('counts a user with multiple camera connections once', () => {
- expect(countDistinctCameraUsers(buildVoiceStates(2, {extraConnectionsForUser: 'multi-user'}))).toBe(3);
- });
-
- it('ignores voice states without a self_video flag', () => {
- expect(countDistinctCameraUsers({'conn-1': {user_id: 'user-1'}})).toBe(0);
- });
-
- it('returns zero for an empty channel', () => {
- expect(countDistinctCameraUsers({})).toBe(0);
- });
-});
-
-describe('isCameraUserCapBlocked', () => {
- it('does not block below the limit', () => {
- expect(
- isCameraUserCapBlocked({
- voiceStates: buildVoiceStates(VOICE_CHANNEL_CAMERA_USER_LIMIT - 1),
- currentUserId: 'someone-else',
- isOwnCameraEnabled: false,
- }),
- ).toBe(false);
- });
-
- it('blocks exactly at the limit', () => {
- expect(
- isCameraUserCapBlocked({
- voiceStates: buildVoiceStates(VOICE_CHANNEL_CAMERA_USER_LIMIT),
- currentUserId: 'someone-else',
- isOwnCameraEnabled: false,
- }),
- ).toBe(true);
- });
-
- it('never blocks turning the camera off', () => {
- expect(
- isCameraUserCapBlocked({
- voiceStates: buildVoiceStates(VOICE_CHANNEL_CAMERA_USER_LIMIT),
- currentUserId: 'someone-else',
- isOwnCameraEnabled: true,
- }),
- ).toBe(false);
- });
-
- it('exempts the current user when their own camera is already counted in voice states', () => {
- const voiceStates = buildVoiceStates(VOICE_CHANNEL_CAMERA_USER_LIMIT);
- expect(
- isCameraUserCapBlocked({
- voiceStates,
- currentUserId: 'user-0',
- isOwnCameraEnabled: false,
- }),
- ).toBe(false);
- });
-
- it('counts a multi-connection user once when evaluating the cap', () => {
- const voiceStates = buildVoiceStates(VOICE_CHANNEL_CAMERA_USER_LIMIT - 2, {
- extraConnectionsForUser: 'multi-user',
- });
- expect(
- isCameraUserCapBlocked({
- voiceStates,
- currentUserId: 'someone-else',
- isOwnCameraEnabled: false,
- }),
- ).toBe(false);
- });
-
- it('supports an explicit limit override', () => {
- expect(
- isCameraUserCapBlocked({
- voiceStates: buildVoiceStates(2),
- currentUserId: 'someone-else',
- isOwnCameraEnabled: false,
- limit: 2,
- }),
- ).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VoiceDevicePermissionTypes.test.ts b/fluxer_app/src/features/voice/utils/VoiceDevicePermissionTypes.test.ts
deleted file mode 100644
index 79903932e..000000000
--- a/fluxer_app/src/features/voice/utils/VoiceDevicePermissionTypes.test.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-interface FakeMediaDevices {
- enumerateDevices: () => Promise<Array<MediaDeviceInfo>>;
- getUserMedia: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
- addEventListener: () => void;
- removeEventListener: () => void;
-}
-
-const makeDevice = (kind: MediaDeviceKind, deviceId: string, label: string): MediaDeviceInfo =>
- ({
- deviceId,
- groupId: `${deviceId}-group`,
- kind,
- label,
- toJSON: () => ({deviceId, kind, label}),
- }) as MediaDeviceInfo;
-
-const makeStream = (kinds: Array<'audio' | 'video'>): MediaStream => {
- const tracks = kinds.map((kind) => ({kind, label: `${kind}-track`, stop: vi.fn()}));
- return {getTracks: () => tracks} as unknown as MediaStream;
-};
-
-const getUserMediaCalls: Array<MediaStreamConstraints> = [];
-const enumerationHooks: Array<() => void> = [];
-let labelledDevices = false;
-
-const fakeMediaDevices: FakeMediaDevices = {
- enumerateDevices: async () => {
- await Promise.resolve();
- enumerationHooks.shift()?.();
- return labelledDevices
- ? [makeDevice('audioinput', 'mic-1', 'Studio Mic'), makeDevice('videoinput', 'cam-1', 'Studio Camera')]
- : [makeDevice('audioinput', 'mic-1', ''), makeDevice('videoinput', 'cam-1', '')];
- },
- getUserMedia: async (constraints) => {
- getUserMediaCalls.push(constraints);
- labelledDevices = true;
- const kinds: Array<'audio' | 'video'> = [];
- if (constraints.audio) kinds.push('audio');
- if (constraints.video) kinds.push('video');
- return makeStream(kinds);
- },
- addEventListener: () => {},
- removeEventListener: () => {},
-};
-
-const fakeElectron = {
- platform: 'darwin',
- checkMediaAccess: vi.fn(async () => 'granted'),
- requestMediaAccess: vi.fn(async () => true),
-};
-
-let originalNavigator: PropertyDescriptor | undefined;
-let originalWindow: PropertyDescriptor | undefined;
-
-beforeEach(() => {
- getUserMediaCalls.length = 0;
- enumerationHooks.length = 0;
- labelledDevices = false;
- fakeElectron.checkMediaAccess.mockClear();
- fakeElectron.requestMediaAccess.mockClear();
- originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
- originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {userAgent: 'node', mediaDevices: fakeMediaDevices},
- });
- Object.defineProperty(globalThis, 'window', {
- configurable: true,
- value: {matchMedia: () => ({matches: false})},
- });
- vi.resetModules();
-});
-
-afterEach(() => {
- if (originalNavigator) {
- Object.defineProperty(globalThis, 'navigator', originalNavigator);
- } else {
- Reflect.deleteProperty(globalThis, 'navigator');
- }
- if (originalWindow) {
- Object.defineProperty(globalThis, 'window', originalWindow);
- } else {
- Reflect.deleteProperty(globalThis, 'window');
- }
-});
-
-const loadManager = async () => {
- const module = await import('@app/features/voice/utils/VoiceDeviceManager');
- return module.voiceDeviceManager;
-};
-
-const runAsDesktop = () => {
- Object.defineProperty(globalThis, 'window', {
- configurable: true,
- value: {matchMedia: () => ({matches: false}), electron: fakeElectron},
- });
-};
-
-describe('voiceDeviceManager permission types', () => {
- test('an audio-only request never asks the browser for video', async () => {
- const manager = await loadManager();
- const state = await manager.ensureDevices({requestPermissionTypes: ['audio'], forceRefresh: true});
- expect(getUserMediaCalls).toEqual([{audio: true, video: false}]);
- expect(state.permissionStatus.audio).toBe('granted');
- expect(state.permissionStatus.video).toBe('idle');
- });
-
- test('a video-only request never asks the browser for audio', async () => {
- const manager = await loadManager();
- const state = await manager.ensureDevices({requestPermissionTypes: ['video'], forceRefresh: true});
- expect(getUserMediaCalls).toEqual([{audio: false, video: true}]);
- expect(state.permissionStatus.video).toBe('granted');
- expect(state.permissionStatus.audio).toBe('idle');
- });
-
- test('the legacy requestPermissions boolean still asks for both types', async () => {
- const manager = await loadManager();
- const state = await manager.ensureDevices({requestPermissions: true, forceRefresh: true});
- expect(getUserMediaCalls).toEqual([{audio: true, video: true}]);
- expect(state.permissionStatus).toEqual({audio: 'granted', video: 'granted'});
- });
-
- test('a passive enumeration never prompts', async () => {
- const manager = await loadManager();
- const state = await manager.ensureDevices({requestPermissions: false, forceRefresh: true});
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus).toEqual({audio: 'idle', video: 'idle'});
- expect(state.inputDevices.length).toBeGreaterThan(0);
- });
-
- test('a confirmation never asks the browser for access when device labels are hidden', async () => {
- const manager = await loadManager();
- const state = await manager.ensureDevices({confirmPermissionTypes: ['audio', 'video'], forceRefresh: true});
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus).toEqual({audio: 'idle', video: 'idle'});
- });
-
- test('a confirmation marks only the confirmed type granted from exposed device labels', async () => {
- labelledDevices = true;
- const manager = await loadManager();
- const state = await manager.ensureDevices({confirmPermissionTypes: ['audio'], forceRefresh: true});
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus).toEqual({audio: 'granted', video: 'idle'});
- });
-
- test('a request that joins an in-flight confirmation of the same type still asks the browser', async () => {
- const manager = await loadManager();
- const confirmation = manager.ensureDevices({confirmPermissionTypes: ['audio'], forceRefresh: true});
- const request = manager.ensureDevices({requestPermissionTypes: ['audio']});
- const [, state] = await Promise.all([confirmation, request]);
- expect(getUserMediaCalls).toEqual([{audio: true, video: false}]);
- expect(state.permissionStatus.audio).toBe('granted');
- });
-
- test('confirmations escalated into requests for every type finish within the enumeration pass bound', async () => {
- const manager = await loadManager();
- const joins: Array<Promise<unknown>> = [];
- enumerationHooks.push(
- () => joins.push(manager.ensureDevices({confirmPermissionTypes: ['audio']})),
- () => joins.push(manager.ensureDevices({requestPermissionTypes: ['audio']})),
- () => joins.push(manager.ensureDevices({confirmPermissionTypes: ['video']})),
- () => {},
- () => joins.push(manager.ensureDevices({requestPermissionTypes: ['video']})),
- );
- const state = await manager.ensureDevices({forceRefresh: true});
- await Promise.all(joins);
- expect(getUserMediaCalls).toEqual([{audio: true, video: false}]);
- expect(state.permissionStatus).toEqual({audio: 'granted', video: 'granted'});
- });
-
- test('a confirmation never runs the native permission flow on desktop', async () => {
- runAsDesktop();
- const manager = await loadManager();
- const state = await manager.ensureDevices({confirmPermissionTypes: ['audio'], forceRefresh: true});
- expect(fakeElectron.checkMediaAccess).not.toHaveBeenCalled();
- expect(fakeElectron.requestMediaAccess).not.toHaveBeenCalled();
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus.audio).toBe('idle');
- });
-
- test('a request runs the native permission flow on desktop', async () => {
- runAsDesktop();
- const manager = await loadManager();
- const state = await manager.ensureDevices({requestPermissionTypes: ['audio'], forceRefresh: true});
- expect(fakeElectron.checkMediaAccess).toHaveBeenCalledWith('microphone');
- expect(getUserMediaCalls).toEqual([]);
- expect(state.permissionStatus.audio).toBe('granted');
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VoiceLatencySignal.test.ts b/fluxer_app/src/features/voice/utils/VoiceLatencySignal.test.ts
deleted file mode 100644
index aaa02f6b3..000000000
--- a/fluxer_app/src/features/voice/utils/VoiceLatencySignal.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- getLatencySignalBaseline,
- getLatencySignalState,
- type LatencySignalSample,
-} from '@app/features/voice/utils/VoiceLatencySignal';
-import {describe, expect, it} from 'vitest';
-
-function samples(...latencies: Array<number>): Array<LatencySignalSample> {
- return latencies.map((latency) => ({latency}));
-}
-
-describe('VoiceLatencySignal', () => {
- it('keeps a stable high cross-region latency green', () => {
- expect(getLatencySignalState(170, samples(168, 170, 171, 169, 170))).toMatchObject({
- kind: 'value',
- baselineLatency: 170,
- excessLatency: 0,
- filledCount: 4,
- tone: 'green',
- });
- });
- it('uses the recent median as the baseline', () => {
- expect(getLatencySignalBaseline(samples(168, 171, 500, 170, 169))).toBe(170);
- });
- it('degrades from the baseline only when latency rises meaningfully', () => {
- const baseline = samples(48, 50, 51, 49, 50, 50);
- expect(getLatencySignalState(115, baseline)).toMatchObject({filledCount: 4, tone: 'green'});
- expect(getLatencySignalState(140, baseline)).toMatchObject({filledCount: 3, tone: 'yellow'});
- expect(getLatencySignalState(250, baseline)).toMatchObject({filledCount: 2, tone: 'orange'});
- expect(getLatencySignalState(390, baseline)).toMatchObject({filledCount: 1, tone: 'red'});
- });
- it('does not punish the first measured sample before a baseline exists', () => {
- expect(getLatencySignalState(270)).toMatchObject({
- kind: 'value',
- baselineLatency: 270,
- excessLatency: 0,
- filledCount: 4,
- tone: 'green',
- });
- });
- it('returns loading while latency is unavailable', () => {
- expect(getLatencySignalState(null, samples(50, 51, 49))).toEqual({kind: 'loading'});
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VoiceStatsForNerdsPresenter.test.ts b/fluxer_app/src/features/voice/utils/VoiceStatsForNerdsPresenter.test.ts
deleted file mode 100644
index da97e430e..000000000
--- a/fluxer_app/src/features/voice/utils/VoiceStatsForNerdsPresenter.test.ts
+++ /dev/null
@@ -1,651 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- buildVoiceStatsForNerdsPresentation,
- collectScreenShareAudioPublicationDiagnostics,
- type ParticipantPublicationLookup,
-} from '@app/features/voice/utils/VoiceStatsForNerdsPresenter';
-import type {
- VoiceEngineV2PerTrackStats,
- VoiceEngineV2Stats,
- VoiceEngineV2StatsSample,
- VoiceEngineV2VoiceStats,
-} from '@fluxer/voice_engine_v2';
-import {describe, expect, it} from 'vitest';
-
-function participant(publications: Record<string, string>): ParticipantPublicationLookup {
- return {
- getTrackPublication(source) {
- const trackId = publications[String(source)];
- if (!trackId) return undefined;
- const mediaStreamTrack = {id: trackId} as MediaStreamTrack;
- if (String(source) === 'camera' || String(source) === 'screen_share') {
- return {videoTrack: {mediaStreamTrack}};
- }
- if (String(source) === 'microphone' || String(source) === 'screen_share_audio') {
- return {audioTrack: {mediaStreamTrack}};
- }
- return {track: {mediaStreamTrack}};
- },
- };
-}
-
-function participantWithAudioPublications(
- publications: Record<string, string>,
- audioPublications: Array<{
- source: string;
- trackName?: string;
- trackId: string;
- }>,
-): ParticipantPublicationLookup {
- const baseParticipant = participant(publications);
- return {
- getTrackPublication: baseParticipant.getTrackPublication,
- audioTrackPublications: new Map(
- audioPublications.map((publication) => [
- publication.trackId,
- {
- source: publication.source,
- trackName: publication.trackName,
- audioTrack: {
- mediaStreamTrack: {id: publication.trackId} as MediaStreamTrack,
- },
- },
- ]),
- ),
- };
-}
-
-const voiceStats: VoiceEngineV2VoiceStats = {
- audioSendBitrate: 48,
- audioRecvBitrate: 64,
- videoSendBitrate: 1200,
- videoRecvBitrate: 900,
- audioPacketLoss: 1.5,
- videoPacketLoss: 2.5,
- rtt: 37,
- jitter: 8,
- participantCount: 3,
- duration: 12,
-};
-
-const timeSeries: Array<VoiceEngineV2StatsSample> = [
- {
- timestamp: 1000,
- rtt: 31,
- jitter: 6,
- audioPacketLoss: 1,
- videoPacketLoss: 2,
- audioSendBitrate: 40,
- audioRecvBitrate: 50,
- videoSendBitrate: 600,
- videoRecvBitrate: 700,
- },
-];
-
-function nativeStats(overrides: Partial<VoiceEngineV2Stats>): VoiceEngineV2Stats {
- return {rttMs: null, outbound: [], inbound: [], ...overrides};
-}
-
-function chromiumCameraSimulcastTracks(): Array<VoiceEngineV2PerTrackStats> {
- return [
- {
- direction: 'send',
- kind: 'video',
- ssrc: 1001,
- rid: 'q',
- active: false,
- mid: '2',
- trackIdentifier: 'cam-track',
- mediaSourceId: 'SV1',
- bitrateKbps: 0,
- bitrateWindowMs: 2001,
- framesEncoded: 1,
- targetBitrateKbps: 0,
- },
- {
- direction: 'send',
- kind: 'video',
- ssrc: 1002,
- rid: 'h',
- active: false,
- mid: '2',
- trackIdentifier: 'cam-track',
- mediaSourceId: 'SV1',
- bitrateKbps: 0,
- bitrateWindowMs: 2001,
- framesEncoded: 1,
- targetBitrateKbps: 0,
- },
- {
- direction: 'send',
- kind: 'video',
- ssrc: 1003,
- rid: 'f',
- active: true,
- mid: '2',
- trackIdentifier: 'cam-track',
- mediaSourceId: 'SV1',
- bitrateKbps: 0,
- bitrateWindowMs: 2001,
- framesEncoded: 1,
- frameWidth: 1280,
- frameHeight: 720,
- targetBitrateKbps: 1133,
- },
- {
- direction: 'send',
- kind: 'video',
- ssrc: 2001,
- mid: '3',
- trackIdentifier: 'screen-track',
- mediaSourceId: 'SV2',
- bitrateKbps: 3500,
- },
- ];
-}
-
-describe('buildVoiceStatsForNerdsPresentation', () => {
- it('classifies browser per-track stats once for overlay and copy consumers', () => {
- const localParticipant = participant({
- camera: 'local-camera',
- microphone: 'local-mic',
- screen_share: 'local-screen',
- screen_share_audio: 'local-screen-audio',
- });
- const remoteParticipant = participant({
- microphone: 'remote-mic',
- screen_share: 'remote-screen',
- screen_share_audio: 'remote-screen-audio',
- });
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'send', kind: 'video', trackIdentifier: 'local-camera', bitrateKbps: 500},
- {direction: 'send', kind: 'audio', trackIdentifier: 'local-mic', bitrateKbps: 48},
- {direction: 'send', kind: 'video', trackIdentifier: 'local-screen', bitrateKbps: 1200},
- {direction: 'send', kind: 'audio', trackIdentifier: 'local-screen-audio', bitrateKbps: 96},
- {direction: 'recv', kind: 'audio', trackIdentifier: 'remote-mic', bitrateKbps: 64},
- {direction: 'recv', kind: 'video', trackIdentifier: 'remote-camera', bitrateKbps: 900},
- {direction: 'recv', kind: 'video', trackIdentifier: 'remote-screen', bitrateKbps: 1800},
- {direction: 'recv', kind: 'audio', trackIdentifier: 'remote-screen-audio', bitrateKbps: 128},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: [remoteParticipant],
- });
-
- expect(presentation.session).toMatchObject({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- latencyMs: 37,
- avgLatencyMs: 41,
- durationSeconds: 12,
- participants: 3,
- });
- expect(presentation.localVideo?.trackIdentifier).toBe('local-camera');
- expect(presentation.localAudio?.trackIdentifier).toBe('local-mic');
- expect(presentation.localScreenShare?.trackIdentifier).toBe('local-screen');
- expect(presentation.localScreenShareAudio?.trackIdentifier).toBe('local-screen-audio');
- expect(presentation.remoteVideo?.trackIdentifier).toBe('remote-camera');
- expect(presentation.remoteAudio?.trackIdentifier).toBe('remote-mic');
- expect(presentation.remoteScreenShare?.trackIdentifier).toBe('remote-screen');
- expect(presentation.remoteScreenShareAudio?.trackIdentifier).toBe('remote-screen-audio');
- expect(presentation.network.audioSendBitrateKbps).toBe(48);
- expect(presentation.sparklines).toEqual({
- latency: [31],
- bitrate: [1390],
- packetLoss: [2],
- });
- });
-
- it('classifies native named screen-share audio publications when source lookup misses', () => {
- const remoteParticipant = participantWithAudioPublications(
- {
- screen_share: 'remote-screen',
- },
- [{source: 'microphone', trackName: 'screen-audio', trackId: 'remote-screen-audio'}],
- );
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'recv', kind: 'audio', trackIdentifier: 'remote-screen-audio', bitrateKbps: 4},
- {direction: 'recv', kind: 'video', trackIdentifier: 'remote-screen', bitrateKbps: 1800},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant: null,
- remoteParticipants: [remoteParticipant],
- });
-
- expect(presentation.remoteScreenShareAudio?.trackIdentifier).toBe('remote-screen-audio');
- expect(presentation.remoteAudio).toBeNull();
- });
-
- it('classifies a firefox screen share whose outbound stats omit the track identifier', () => {
- const localParticipant = participant({
- microphone: 'b0d2f1a7-6c3e-4f8a-9b21-5d7c4e0a1f36',
- screen_share: '2f4c8de1-9a07-4b53-8c6d-1e5b7a02d94f',
- });
- const remoteParticipant = participant({microphone: '8a106956-d202-4916-8e19-0a1672c64b73'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {
- direction: 'recv',
- kind: 'audio',
- mid: '2',
- trackIdentifier: '{8a106956-d202-4916-8e19-0a1672c64b73}',
- bitrateKbps: 46,
- },
- {direction: 'send', kind: 'audio', mid: '1', bitrateKbps: 30},
- {direction: 'send', kind: 'video', mid: '3', bitrateKbps: 47, framesPerSecond: 58, frameWidth: 1920},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: [remoteParticipant],
- });
-
- expect(presentation.localScreenShare?.mid).toBe('3');
- expect(presentation.localVideo).toBeNull();
- });
-
- it('classifies a firefox inbound screen share reported with a braced track identifier', () => {
- const remoteParticipant = participant({screen_share: '34171e0d-174d-4d56-bb71-76b4fba330c3'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {
- direction: 'recv',
- kind: 'video',
- mid: '3',
- trackIdentifier: '{34171e0d-174d-4d56-bb71-76b4fba330c3}',
- bitrateKbps: 3585,
- },
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant: null,
- remoteParticipants: [remoteParticipant],
- });
-
- expect(presentation.remoteScreenShare?.mid).toBe('3');
- expect(presentation.remoteVideo).toBeNull();
- });
-
- it('exposes every camera simulcast layer next to the projected localVideo row', () => {
- const localParticipant = participant({camera: 'cam-track', screen_share: 'screen-track'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = chromiumCameraSimulcastTracks();
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: null,
- });
-
- expect(presentation.localVideo?.rid).toBe('q');
- expect(presentation.localVideoLayers).toHaveLength(3);
- expect(presentation.localVideoLayers.map((layer) => layer.rid)).toEqual(['q', 'h', 'f']);
- expect(presentation.localVideoLayers.map((layer) => layer.active)).toEqual([false, false, true]);
- expect(presentation.localVideoLayers.map((layer) => layer.bitrateWindowMs)).toEqual([2001, 2001, 2001]);
- });
-
- it('keeps the screen-share publication out of the camera layer view', () => {
- const localParticipant = participant({camera: 'cam-track', screen_share: 'screen-track'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = chromiumCameraSimulcastTracks();
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: null,
- });
-
- expect(presentation.localScreenShare?.trackIdentifier).toBe('screen-track');
- expect(presentation.localVideoLayers).not.toContain(perTrackStats[3]);
- });
-
- it('reports a single camera layer when firefox omits rid and media source ids', () => {
- const localParticipant = participant({camera: 'cam-track'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'send', kind: 'audio', mid: '1', bitrateKbps: 30},
- {direction: 'send', kind: 'video', mid: '3', bitrateKbps: 47, framesPerSecond: 58, frameWidth: 1920},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: null,
- });
-
- expect(presentation.localVideo?.mid).toBe('3');
- expect(presentation.localVideoLayers).toEqual([perTrackStats[1]]);
- });
-
- it('reports no camera layers rather than a false single layer when firefox simulcast is unidentifiable', () => {
- const localParticipant = participant({camera: 'cam-track'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'send', kind: 'audio', mid: '1', bitrateKbps: 30},
- {direction: 'send', kind: 'video', mid: '3', rid: 'q', bitrateKbps: 0},
- {direction: 'send', kind: 'video', mid: '3', rid: 'h', bitrateKbps: 0},
- {direction: 'send', kind: 'video', mid: '3', rid: 'f', bitrateKbps: 1133},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: null,
- });
-
- expect(presentation.localVideo).toBeNull();
- expect(presentation.localVideoLayers).toEqual([]);
- });
-
- it('keeps the chromium simulcast projection byte-identical', () => {
- const localParticipant = participant({camera: 'cam-track', screen_share: 'screen-track'});
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = chromiumCameraSimulcastTracks();
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: voiceStats,
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: null,
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant,
- remoteParticipants: null,
- });
-
- expect(presentation.localVideo).toBe(perTrackStats[0]);
- expect(presentation.localScreenShare).toBe(perTrackStats[3]);
- expect(presentation.localAudio).toBeNull();
- expect(presentation.remoteVideo).toBeNull();
- expect(presentation.network.videoSendBitrateKbps).toBe(1200);
- });
-
- it('uses the canonical v2 native stats projection when native stats are available', () => {
- const perTrackStats: Array<VoiceEngineV2PerTrackStats> = [
- {direction: 'send', kind: 'video', trackIdentifier: 'browser-camera', bitrateKbps: 500},
- {direction: 'send', kind: 'audio', trackIdentifier: 'browser-mic', bitrateKbps: 48},
- ];
-
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: {
- ...voiceStats,
- audioSendBitrate: 1,
- videoSendBitrate: 2,
- rtt: 999,
- },
- perTrackStats,
- statsTimeSeries: timeSeries,
- nativeStats: nativeStats({
- rttMs: 25,
- droppedNativeVideoFrames: 7,
- outbound: [
- {
- trackSid: 'native-camera',
- source: 'camera',
- kind: 'video',
- bitrateKbps: 700,
- packetsLost: 0,
- fps: 30,
- },
- {
- trackSid: 'native-screen-audio',
- source: 'screen_share_audio',
- kind: 'audio',
- bitrateKbps: 96,
- packetsLost: 1,
- packetsSent: 100,
- },
- ],
- inbound: [
- {
- participantSid: 'remote-a',
- trackSid: 'native-remote-audio',
- kind: 'audio',
- bitrateKbps: 64,
- packetsLost: 3,
- packetsReceived: 97,
- jitterMs: 9,
- },
- ],
- }),
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant: null,
- remoteParticipants: null,
- });
-
- expect(presentation.network).toMatchObject({
- audioSendBitrateKbps: 96,
- audioRecvBitrateKbps: 64,
- videoSendBitrateKbps: 700,
- audioPacketLossPercent: 3,
- jitterMs: 9,
- rttMs: 25,
- droppedVideoFrameCallbacks: 7,
- });
- expect(presentation.localVideo?.trackIdentifier).toBe('native-camera');
- expect(presentation.localAudio).toBeNull();
- expect(presentation.localScreenShareAudio?.trackIdentifier).toBe('native-screen-audio');
- expect(presentation.remoteAudio?.trackIdentifier).toBe('native-remote-audio');
- });
-
- it('uses the tracked latency for native RTT when a sparse native stats sample omits RTT', () => {
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: 37,
- averageLatency: 41,
- stats: {
- ...voiceStats,
- rtt: 999,
- },
- perTrackStats: [],
- statsTimeSeries: timeSeries,
- nativeStats: nativeStats({
- rttMs: null,
- outbound: [
- {
- trackSid: 'native-mic',
- source: 'microphone',
- kind: 'audio',
- bitrateKbps: 48,
- packetsLost: 0,
- },
- ],
- inbound: [],
- }),
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant: null,
- remoteParticipants: null,
- });
-
- expect(presentation.network.rttMs).toBe(37);
- });
-
- it('keeps native RTT unknown before the first tracked latency sample', () => {
- const presentation = buildVoiceStatsForNerdsPresentation({
- connectionId: 'connection-a',
- connectionQuality: 'excellent',
- currentLatency: null,
- averageLatency: null,
- stats: {
- ...voiceStats,
- rtt: 999,
- },
- perTrackStats: [],
- statsTimeSeries: timeSeries,
- nativeStats: nativeStats({rttMs: null}),
- publisherTransport: null,
- subscriberTransport: null,
- localParticipant: null,
- remoteParticipants: null,
- });
-
- expect(presentation.network.rttMs).toBeNull();
- });
-});
-
-describe('collectScreenShareAudioPublicationDiagnostics', () => {
- it('reports the mute and upstream state of every local screen-share audio publication', () => {
- const displayPublication = {
- trackSid: 'TR_display',
- source: 'screen_share_audio',
- isMuted: false,
- audioTrack: {
- isUpstreamPaused: true,
- mediaStreamTrack: {
- id: 'display-audio',
- readyState: 'live',
- muted: true,
- enabled: true,
- } as MediaStreamTrack,
- },
- };
- const devicePublication = {
- trackSid: 'TR_device',
- source: 'screen_share_audio',
- isMuted: false,
- audioTrack: {
- isUpstreamPaused: false,
- mediaStreamTrack: {
- id: 'device-audio',
- readyState: 'live',
- muted: false,
- enabled: true,
- } as MediaStreamTrack,
- },
- };
- const micPublication = {
- trackSid: 'TR_mic',
- source: 'microphone',
- isMuted: false,
- audioTrack: {
- isUpstreamPaused: false,
- mediaStreamTrack: {
- id: 'mic-audio',
- readyState: 'live',
- muted: false,
- enabled: true,
- } as MediaStreamTrack,
- },
- };
- const localParticipant: ParticipantPublicationLookup = {
- getTrackPublication: (source) => (String(source) === 'screen_share_audio' ? displayPublication : undefined),
- audioTrackPublications: new Map([
- ['TR_display', displayPublication],
- ['TR_device', devicePublication],
- ['TR_mic', micPublication],
- ]),
- };
-
- const diagnostics = collectScreenShareAudioPublicationDiagnostics(localParticipant);
-
- expect(diagnostics).toEqual([
- {
- trackSid: 'TR_display',
- source: 'screen_share_audio',
- isMuted: false,
- isUpstreamPaused: true,
- mediaStreamTrackId: 'display-audio',
- mediaStreamTrackReadyState: 'live',
- mediaStreamTrackMuted: true,
- mediaStreamTrackEnabled: true,
- },
- {
- trackSid: 'TR_device',
- source: 'screen_share_audio',
- isMuted: false,
- isUpstreamPaused: false,
- mediaStreamTrackId: 'device-audio',
- mediaStreamTrackReadyState: 'live',
- mediaStreamTrackMuted: false,
- mediaStreamTrackEnabled: true,
- },
- ]);
- });
-
- it('reports nothing when there is no local participant', () => {
- expect(collectScreenShareAudioPublicationDiagnostics(null)).toEqual([]);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/VoiceVolumeUtils.test.ts b/fluxer_app/src/features/voice/utils/VoiceVolumeUtils.test.ts
deleted file mode 100644
index 9012233ba..000000000
--- a/fluxer_app/src/features/voice/utils/VoiceVolumeUtils.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- boostedVoiceVolumePercentToTrackVolume,
- clampVoiceTrackTotalGain,
- composeVoiceVolumeGain,
- recalibrateStoredVoiceVolumePercent,
- recalibrateStoredVoiceVolumes,
- VOICE_TRACK_MAX_TOTAL_GAIN,
- VOICE_VOLUME_MAX_GAIN,
- VOICE_VOLUME_MAX_PERCENT,
- VOICE_VOLUME_MAX_SLIDER_VOLUME,
-} from '@app/features/voice/utils/VoiceVolumeUtils';
-import {describe, expect, it} from 'vitest';
-
-describe('boostedVoiceVolumePercentToTrackVolume', () => {
- it('leaves every setting at or below unity untouched', () => {
- const cases: Array<[number, number]> = [
- [0, 0],
- [1, 10 ** -1.188],
- [10, 10 ** -1.08],
- [25, 10 ** -0.9],
- [50, 10 ** -0.6],
- [75, 10 ** -0.3],
- [99, 10 ** -0.012],
- [100, 1],
- ];
- for (const [percent, expected] of cases) {
- expect(boostedVoiceVolumePercentToTrackVolume(percent)).toBeCloseTo(expected, 15);
- }
- expect(boostedVoiceVolumePercentToTrackVolume(0)).toBe(0);
- expect(boostedVoiceVolumePercentToTrackVolume(100)).toBe(1);
- });
-
- it('widens the boost leg to +12.04 dB at 200%', () => {
- expect(boostedVoiceVolumePercentToTrackVolume(200)).toBeCloseTo(4, 12);
- expect(boostedVoiceVolumePercentToTrackVolume(150)).toBe(2);
- expect(boostedVoiceVolumePercentToTrackVolume(125)).toBe(Math.SQRT2);
- expect(boostedVoiceVolumePercentToTrackVolume(100)).toBe(1);
- });
-});
-
-describe('voice volume ceilings', () => {
- it('keeps the slider ceiling and the gain ceiling as separate quantities', () => {
- expect(VOICE_VOLUME_MAX_SLIDER_VOLUME).toBe(2);
- expect(VOICE_VOLUME_MAX_SLIDER_VOLUME).toBe(VOICE_VOLUME_MAX_PERCENT / 100);
- expect(VOICE_VOLUME_MAX_GAIN).toBe(4);
- expect(boostedVoiceVolumePercentToTrackVolume(VOICE_VOLUME_MAX_PERCENT)).toBeCloseTo(VOICE_VOLUME_MAX_GAIN, 12);
- expect(VOICE_TRACK_MAX_TOTAL_GAIN).toBe(12);
- });
-});
-
-describe('composeVoiceVolumeGain', () => {
- it('composes faders in linear gain instead of collapsing them', () => {
- expect(composeVoiceVolumeGain(200, 100, 200)).toBeCloseTo(16, 12);
- expect(composeVoiceVolumeGain(200, 100, 200)).toBeGreaterThan(composeVoiceVolumeGain(200, 100, 100));
- expect(composeVoiceVolumeGain(50, 100, 100)).toBe(10 ** -0.6);
- expect(composeVoiceVolumeGain()).toBe(1);
- });
-
- it('clamps each part, not the product', () => {
- expect(composeVoiceVolumeGain(400)).toBe(composeVoiceVolumeGain(200));
- expect(composeVoiceVolumeGain(-50)).toBe(0);
- });
-});
-
-describe('clampVoiceTrackTotalGain', () => {
- it('fails to unity, not silence', () => {
- expect(clampVoiceTrackTotalGain(Number.NaN)).toBe(1);
- expect(clampVoiceTrackTotalGain(Number.POSITIVE_INFINITY)).toBe(1);
- expect(clampVoiceTrackTotalGain(48)).toBe(12);
- expect(clampVoiceTrackTotalGain(-1)).toBe(0);
- });
-});
-
-describe('recalibrateStoredVoiceVolumePercent', () => {
- it('pulls every boosted stored value back to unity', () => {
- expect(recalibrateStoredVoiceVolumePercent(200)).toBe(100);
- expect(recalibrateStoredVoiceVolumePercent(150)).toBe(100);
- expect(recalibrateStoredVoiceVolumePercent(101)).toBe(100);
- });
-
- it('leaves unity and quieter values untouched', () => {
- expect(recalibrateStoredVoiceVolumePercent(100)).toBe(100);
- expect(recalibrateStoredVoiceVolumePercent(40)).toBe(40);
- expect(recalibrateStoredVoiceVolumePercent(0)).toBe(0);
- });
-
- it('keeps the same object when nothing needs recalibrating', () => {
- const volumes = {alice: 100, bob: 40};
- expect(recalibrateStoredVoiceVolumes(volumes)).toBe(volumes);
- });
-
- it('caps only the boosted entries in a stored map', () => {
- expect(recalibrateStoredVoiceVolumes({alice: 200, bob: 60, carol: 150})).toEqual({
- alice: 100,
- bob: 60,
- carol: 100,
- });
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/RoutingRuleEquality.test.ts b/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/RoutingRuleEquality.test.ts
deleted file mode 100644
index cf9e6e7f1..000000000
--- a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/RoutingRuleEquality.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type NativeAudioRoutingRule,
- nativeAudioRoutingRulesEqual,
-} from '@app/features/voice/utils/native_audio_capture_bridge/shared';
-import {describe, expect, it} from 'vitest';
-
-const base: NativeAudioRoutingRule = {
- include: [{'application.name': 'Firefox'}],
- exclude: [{'node.name': 'fluxer'}],
- ignoreDevices: true,
-};
-
-describe('nativeAudioRoutingRulesEqual', () => {
- it('treats a rule as equal to itself and to a structural copy', () => {
- expect(nativeAudioRoutingRulesEqual(base, base)).toBe(true);
- expect(nativeAudioRoutingRulesEqual(base, {...base, include: [{'application.name': 'Firefox'}]})).toBe(true);
- });
-
- it('ignores the order of include and exclude patterns', () => {
- const a: NativeAudioRoutingRule = {include: [{'application.name': 'A'}, {'application.name': 'B'}]};
- const b: NativeAudioRoutingRule = {include: [{'application.name': 'B'}, {'application.name': 'A'}]};
- expect(nativeAudioRoutingRulesEqual(a, b)).toBe(true);
- });
-
- it('separates a missing list from an empty one only when the contents differ', () => {
- expect(nativeAudioRoutingRulesEqual({include: []}, {})).toBe(true);
- expect(nativeAudioRoutingRulesEqual({include: [{'application.name': 'A'}]}, {})).toBe(false);
- });
-
- it('detects a changed selection, which is the case that must restart routing', () => {
- expect(nativeAudioRoutingRulesEqual(base, {...base, include: [{'application.name': 'Chromium'}]})).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, {...base, include: []})).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, {...base, exclude: []})).toBe(false);
- });
-
- it('detects a changed tuning flag', () => {
- expect(nativeAudioRoutingRulesEqual(base, {...base, ignoreDevices: false})).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, {...base, onlySpeakers: true})).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, {...base, onlyDefaultSpeakers: true})).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, {...base, ignoreInputMedia: true})).toBe(false);
- });
-
- it('treats an undefined flag as false rather than as a difference', () => {
- expect(nativeAudioRoutingRulesEqual({include: []}, {include: [], onlySpeakers: false})).toBe(true);
- });
-
- it('never reports equality when a rule is missing', () => {
- expect(nativeAudioRoutingRulesEqual(undefined, base)).toBe(false);
- expect(nativeAudioRoutingRulesEqual(base, undefined)).toBe(false);
- expect(nativeAudioRoutingRulesEqual(undefined, undefined)).toBe(true);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/bridgeStats.test.ts b/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/bridgeStats.test.ts
deleted file mode 100644
index 5cdc353e0..000000000
--- a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/bridgeStats.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- endBridgeStats,
- getBridgeStats,
- getEndedBridgeCaptures,
- recordBridgeFrame,
- startBridgeStats,
-} from '@app/features/voice/utils/native_audio_capture_bridge/bridgeStats';
-import {describe, expect, it, vi} from 'vitest';
-
-function recordFrames(captureId: string, count: number, peak: number, rms: number): void {
- for (let index = 0; index < count; index++) {
- recordBridgeFrame(captureId, {timestampUs: index * 10_000, durationUs: 10_000, peak, rms});
- }
-}
-
-function findEndedCapture(captureId: string) {
- return getEndedBridgeCaptures().find((capture) => capture.captureId === captureId);
-}
-
-describe('bridgeStats', () => {
- it('retains the counters of a capture that a mid-share restart supersedes', () => {
- startBridgeStats('generator', 'native-audio:failed', {prebufferTargetUs: 60_000, frameDurationUs: 10_000});
- recordFrames('native-audio:failed', 1124, 0.42, 0.11);
-
- startBridgeStats('generator', 'native-audio:replacement', {prebufferTargetUs: 60_000, frameDurationUs: 10_000});
-
- expect(getBridgeStats().captureId).toBe('native-audio:replacement');
- expect(getBridgeStats().framesReceived).toBe(0);
- const retained = findEndedCapture('native-audio:failed');
- expect(retained?.bridgeMode).toBe('generator');
- expect(retained?.framesReceived).toBe(1124);
- expect(retained?.nonSilentFrameCount).toBe(1124);
- expect(retained?.lastFramePeak).toBe(0.42);
- expect(retained?.endReason).toBe('superseded');
- });
-
- it('records the end reason of a capture the newer capture already superseded', () => {
- startBridgeStats('generator', 'native-audio:ends-late');
- recordFrames('native-audio:ends-late', 3, 0.2, 0.05);
- startBridgeStats('generator', 'native-audio:ends-late-replacement');
-
- endBridgeStats('native-audio:ends-late', 'ended', 'source-disappeared');
-
- const retained = findEndedCapture('native-audio:ends-late');
- expect(retained?.endReason).toBe('ended');
- expect(retained?.endDetail).toBe('source-disappeared');
- expect(retained?.endedAt).not.toBeNull();
- expect(getBridgeStats().captureId).toBe('native-audio:ends-late-replacement');
- expect(getBridgeStats().active).toBe(true);
- });
-
- it('still ends the active capture in place', () => {
- startBridgeStats('script-processor', 'native-audio:active-end');
-
- endBridgeStats('native-audio:active-end', 'cleanup', 'caller-stopped');
-
- const stats = getBridgeStats();
- expect(stats.active).toBe(false);
- expect(stats.endReason).toBe('cleanup');
- expect(stats.endDetail).toBe('caller-stopped');
- expect(stats.endedAt).not.toBeNull();
- });
-
- it('keeps the first end reason of the active capture', () => {
- startBridgeStats('generator', 'native-audio:double-end');
- endBridgeStats('native-audio:double-end', 'ended', 'source-disappeared');
-
- endBridgeStats('native-audio:double-end', 'cleanup', 'caller-stopped');
-
- expect(getBridgeStats().endReason).toBe('ended');
- expect(getBridgeStats().endDetail).toBe('source-disappeared');
- });
-
- it('flags a capture whose frames keep arriving while every one of them is silence', () => {
- const startMs = Date.UTC(2026, 8, 8, 12, 0, 0);
- vi.useFakeTimers();
- try {
- vi.setSystemTime(startMs);
- startBridgeStats('generator', 'native-audio:all-silent', {frameDurationUs: 10_000});
- for (let index = 0; index < 400; index++) {
- vi.setSystemTime(startMs + index * 100);
- recordBridgeFrame('native-audio:all-silent', {
- timestampUs: index * 10_000,
- durationUs: 10_000,
- peak: 0,
- rms: 0,
- });
- }
-
- const stats = getBridgeStats();
- expect(stats.framesReceived).toBe(400);
- expect(stats.nonSilentFrameCount).toBe(0);
- expect(stats.lastNonSilentFrameAt).toBeNull();
- expect(stats.silentFrameStreak).toBe(400);
- expect(stats.maxSilentRunMs).toBe(39_900);
- expect(stats.sustainedSilenceWarned).toBe(true);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('does not flag a capture that keeps producing audible frames', () => {
- const startMs = Date.UTC(2026, 8, 8, 13, 0, 0);
- vi.useFakeTimers();
- try {
- vi.setSystemTime(startMs);
- startBridgeStats('generator', 'native-audio:audible', {frameDurationUs: 10_000});
- for (let index = 0; index < 400; index++) {
- vi.setSystemTime(startMs + index * 100);
- const audible = index % 4 === 0;
- recordBridgeFrame('native-audio:audible', {
- timestampUs: index * 10_000,
- durationUs: 10_000,
- peak: audible ? 0.3 : 0,
- rms: audible ? 0.1 : 0,
- });
- }
-
- const stats = getBridgeStats();
- expect(stats.nonSilentFrameCount).toBe(100);
- expect(stats.lastNonSilentFrameAt).toBe(startMs + 396 * 100);
- expect(stats.silentFrameStreak).toBe(3);
- expect(stats.maxSilentRunMs).toBe(300);
- expect(stats.sustainedSilenceWarned).toBe(false);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('bounds the retained capture history', () => {
- for (let index = 0; index < 12; index++) {
- startBridgeStats('generator', `native-audio:bounded-${index}`);
- }
-
- expect(getEndedBridgeCaptures().length).toBeLessThanOrEqual(8);
- expect(findEndedCapture('native-audio:bounded-11')).toBeUndefined();
- expect(findEndedCapture('native-audio:bounded-10')).toBeDefined();
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/shared.test.ts b/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/shared.test.ts
deleted file mode 100644
index f02702555..000000000
--- a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/shared.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- GENERATOR_AUDIO_CHUNK_DURATION_US,
- mixToStereoInterleaved,
- NativeAudioFrameChunker,
- resampleInterleavedStereo,
- shouldMixSelfWindowAudioIntoSystemCapture,
-} from '@app/features/voice/utils/native_audio_capture_bridge/shared';
-import {describe, expect, it} from 'vitest';
-
-function expectSamples(actual: Float32Array, expected: ReadonlyArray<number>): void {
- expect(Array.from(actual)).toEqual(expected);
-}
-
-function audioMessage(samples: Float32Array, timestampUs: number, sampleRate = 48000, channels = 2) {
- return {
- sampleRate,
- channels,
- timestampUs,
- samples: samples.buffer.slice(samples.byteOffset, samples.byteOffset + samples.byteLength) as ArrayBuffer,
- };
-}
-
-describe('shouldMixSelfWindowAudioIntoSystemCapture', () => {
- it('keeps system capture independent of the Fluxer renderer audio tap', () => {
- expect(
- shouldMixSelfWindowAudioIntoSystemCapture({
- available: true,
- backend: 'windows-wasapi-loopback',
- capabilities: {
- process: true,
- system: true,
- systemExcludesSelf: true,
- },
- }),
- ).toBe(false);
- });
-});
-
-describe('NativeAudioFrameChunker', () => {
- it('accumulates short native packets into stable 20 ms chunks', () => {
- const chunker = new NativeAudioFrameChunker(GENERATOR_AUDIO_CHUNK_DURATION_US);
- const firstHalf = new Float32Array(480 * 2).fill(0.25);
- const secondHalf = new Float32Array(480 * 2).fill(0.5);
- expect(chunker.push(audioMessage(firstHalf, 1234))).toEqual([]);
- const chunks = chunker.push(audioMessage(secondHalf, 11_234));
- expect(chunks).toHaveLength(1);
- expect(chunks[0].sampleRate).toBe(48000);
- expect(chunks[0].channels).toBe(2);
- expect(chunks[0].numberOfFrames).toBe(960);
- expect(chunks[0].durationUs).toBe(20_000);
- expect(chunks[0].timestampUs).toBe(1234);
- expect(chunks[0].samples[0]).toBe(0.25);
- expect(chunks[0].samples[960]).toBe(0.5);
- });
-
- it('splits large native packets and advances timestamps continuously', () => {
- const chunker = new NativeAudioFrameChunker(GENERATOR_AUDIO_CHUNK_DURATION_US);
- const samples = new Float32Array(1920 * 2).fill(1);
- const chunks = chunker.push(audioMessage(samples, 50_000));
- expect(chunks).toHaveLength(2);
- expect(chunks.map((chunk) => chunk.numberOfFrames)).toEqual([960, 960]);
- expect(chunks.map((chunk) => chunk.timestampUs)).toEqual([50_000, 70_000]);
- });
-
- it('resets partial buffered audio when the native format changes', () => {
- const chunker = new NativeAudioFrameChunker(GENERATOR_AUDIO_CHUNK_DURATION_US);
- expect(chunker.push(audioMessage(new Float32Array(480 * 2), 100_000))).toEqual([]);
- const chunks = chunker.push(audioMessage(new Float32Array(882 * 2).fill(0.75), 200_000, 44100, 2));
- expect(chunks).toHaveLength(1);
- expect(chunks[0].sampleRate).toBe(44100);
- expect(chunks[0].numberOfFrames).toBe(882);
- expect(chunks[0].timestampUs).toBe(200_000);
- });
-});
-
-describe('mixToStereoInterleaved', () => {
- it('duplicates mono samples into interleaved stereo frames', () => {
- expectSamples(mixToStereoInterleaved(new Float32Array([0.25, -0.5]), 1), [0.25, 0.25, -0.5, -0.5]);
- });
- it('keeps stereo samples as interleaved stereo frames', () => {
- expectSamples(mixToStereoInterleaved(new Float32Array([0.25, -0.5, 0.75, -1]), 2), [0.25, -0.5, 0.75, -1]);
- });
- it('downmixes channels after stereo into the matching side at half amplitude', () => {
- expectSamples(mixToStereoInterleaved(new Float32Array([0.25, 0.5, 0.25, 0.5]), 4), [0.375, 0.75]);
- });
- it('clamps output to [-1, 1] when surround channels push past full scale', () => {
- expectSamples(mixToStereoInterleaved(new Float32Array([1, 2, 0.5, 0.25, -1, -2, 4, -6]), 4), [1, 1, 1, -1]);
- });
-});
-
-describe('resampleInterleavedStereo', () => {
- it('returns the original samples when rates match', () => {
- const samples = new Float32Array([0.25, -0.5, 0.75, -1]);
- expect(resampleInterleavedStereo(samples, 48000, 48000)).toBe(samples);
- });
- it('linearly interpolates during downsampling', () => {
- expectSamples(resampleInterleavedStereo(new Float32Array([0, 10, 3, 13, 9, 19]), 48000, 32000), [0, 10, 6, 16]);
- });
- it('linearly interpolates during upsampling and clamps the final frame', () => {
- expectSamples(
- resampleInterleavedStereo(new Float32Array([0, 10, 8, 18]), 24000, 48000),
- [0, 10, 4, 14, 8, 18, 8, 18],
- );
- });
- it('returns empty output when resampling zero frames', () => {
- expectSamples(resampleInterleavedStereo(new Float32Array(0), 48000, 32000), []);
- });
- it('returns empty output for invalid rates', () => {
- expectSamples(resampleInterleavedStereo(new Float32Array([1, 2, 3, 4]), 0, 48000), []);
- expectSamples(resampleInterleavedStereo(new Float32Array([1, 2, 3, 4]), 48000, 0), []);
- expectSamples(resampleInterleavedStereo(new Float32Array([1, 2, 3, 4]), -1, 48000), []);
- });
- it('returns empty output for a single sample (less than one stereo frame)', () => {
- expectSamples(resampleInterleavedStereo(new Float32Array([1]), 48000, 44100), []);
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionBackends.test.ts b/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionBackends.test.ts
deleted file mode 100644
index 76555b6ea..000000000
--- a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionBackends.test.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createRequire} from 'node:module';
-import {
- detectWasmSimdSupport,
- getNoiseSuppressionBackendDescriptor,
- getNoiseSuppressionUnsupportedReason,
- isNoiseSuppressionBackendSupported,
- isVoiceNoiseSuppressionBackend,
- type NoiseSuppressionRuntimeCapabilities,
- resetWasmSimdSupportCacheForTests,
- resolveNoiseSuppressionContextSampleRate,
- selectUsableNoiseSuppressionBackend,
- VOICE_NOISE_SUPPRESSION_BACKENDS,
-} from '@app/features/voice/utils/noise_suppression/NoiseSuppressionBackends';
-import {
- NOISE_GATE_OPEN_THRESHOLD_DB_AT_MAX_STRENGTH,
- NOISE_GATE_OPEN_THRESHOLD_DB_AT_MIN_STRENGTH,
- resolveNoiseGateTuning,
-} from '@app/features/voice/utils/noise_suppression/NoiseSuppressionGateTuning';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-const CAPABLE: NoiseSuppressionRuntimeCapabilities = {sampleRate: 48000, wasmSimd: true, audioWorklet: true};
-
-describe('noise suppression backend descriptors', () => {
- it('describes every backend in the shared contract', () => {
- for (const backend of VOICE_NOISE_SUPPRESSION_BACKENDS) {
- expect(getNoiseSuppressionBackendDescriptor(backend).id).toBe(backend);
- }
- });
-
- it('only lets none and standard carry the input channel layout through', () => {
- const preserving = VOICE_NOISE_SUPPRESSION_BACKENDS.filter(
- (backend) => getNoiseSuppressionBackendDescriptor(backend).preservesInputChannels,
- );
- expect(preserving).toEqual(['none', 'standard']);
- });
-
- it('only asks the browser for its own suppression on standard', () => {
- const browserBacked = VOICE_NOISE_SUPPRESSION_BACKENDS.filter(
- (backend) => getNoiseSuppressionBackendDescriptor(backend).browserNoiseSuppression,
- );
- expect(browserBacked).toEqual(['standard']);
- });
-
- it('recognises only contract backends', () => {
- expect(isVoiceNoiseSuppressionBackend('rnnoise')).toBe(true);
- expect(isVoiceNoiseSuppressionBackend('krisp')).toBe(false);
- expect(isVoiceNoiseSuppressionBackend(null)).toBe(false);
- expect(isVoiceNoiseSuppressionBackend(undefined)).toBe(false);
- expect(isVoiceNoiseSuppressionBackend(3)).toBe(false);
- });
-});
-
-describe('runtime support', () => {
- it('never blocks the two zero-dependency backends', () => {
- const hostile: NoiseSuppressionRuntimeCapabilities = {sampleRate: 44100, wasmSimd: false, audioWorklet: false};
- expect(isNoiseSuppressionBackendSupported('none', hostile)).toBe(true);
- expect(isNoiseSuppressionBackendSupported('standard', hostile)).toBe(true);
- });
-
- it('blocks every worklet backend without AudioWorklet', () => {
- const noWorklet: NoiseSuppressionRuntimeCapabilities = {...CAPABLE, audioWorklet: false};
- for (const backend of ['gate', 'speex', 'rnnoise', 'gtcrn', 'deep_filter'] as const) {
- expect(getNoiseSuppressionUnsupportedReason(backend, noWorklet)).toBe('audio_worklet');
- }
- });
-
- it('blocks gtcrn without wasm simd and nothing else', () => {
- const noSimd: NoiseSuppressionRuntimeCapabilities = {...CAPABLE, wasmSimd: false};
- expect(getNoiseSuppressionUnsupportedReason('gtcrn', noSimd)).toBe('wasm_simd');
- expect(getNoiseSuppressionUnsupportedReason('rnnoise', noSimd)).toBeNull();
- expect(getNoiseSuppressionUnsupportedReason('speex', noSimd)).toBeNull();
- expect(getNoiseSuppressionUnsupportedReason('gate', noSimd)).toBeNull();
- expect(getNoiseSuppressionUnsupportedReason('deep_filter', noSimd)).toBeNull();
- });
-
- it('blocks fixed-rate backends at an unsupported context rate', () => {
- const at44k: NoiseSuppressionRuntimeCapabilities = {...CAPABLE, sampleRate: 44100};
- expect(getNoiseSuppressionUnsupportedReason('rnnoise', at44k)).toBe('sample_rate');
- expect(getNoiseSuppressionUnsupportedReason('gtcrn', at44k)).toBe('sample_rate');
- expect(getNoiseSuppressionUnsupportedReason('deep_filter', at44k)).toBe('sample_rate');
- expect(getNoiseSuppressionUnsupportedReason('speex', at44k)).toBeNull();
- expect(getNoiseSuppressionUnsupportedReason('gate', at44k)).toBeNull();
- });
-
- it('accepts gtcrn at both of its native rates', () => {
- expect(isNoiseSuppressionBackendSupported('gtcrn', {...CAPABLE, sampleRate: 16000})).toBe(true);
- expect(isNoiseSuppressionBackendSupported('gtcrn', {...CAPABLE, sampleRate: 48000})).toBe(true);
- expect(isNoiseSuppressionBackendSupported('gtcrn', {...CAPABLE, sampleRate: 32000})).toBe(false);
- });
-});
-
-describe('fallback selection', () => {
- it('keeps the requested backend when it is usable', () => {
- expect(selectUsableNoiseSuppressionBackend('gtcrn', CAPABLE)).toBe('gtcrn');
- });
-
- it('falls back to standard when the request cannot run', () => {
- expect(selectUsableNoiseSuppressionBackend('gtcrn', {...CAPABLE, wasmSimd: false})).toBe('standard');
- });
-
- it('falls all the way to none when nothing in the fallback order fits', () => {
- const at44k: NoiseSuppressionRuntimeCapabilities = {...CAPABLE, sampleRate: 44100};
- expect(selectUsableNoiseSuppressionBackend('rnnoise', at44k, ['gtcrn', 'speex'])).toBe('speex');
- expect(selectUsableNoiseSuppressionBackend('rnnoise', at44k, ['gtcrn'])).toBe('none');
- });
-
- it('never returns the failing request itself', () => {
- expect(selectUsableNoiseSuppressionBackend('gtcrn', {...CAPABLE, wasmSimd: false}, ['gtcrn', 'none'])).toBe('none');
- });
-});
-
-describe('context sample rate resolution', () => {
- it('leaves rate-agnostic backends on the capture rate', () => {
- expect(resolveNoiseSuppressionContextSampleRate('speex', 44100)).toBe(44100);
- expect(resolveNoiseSuppressionContextSampleRate('gate', 44100)).toBe(44100);
- expect(resolveNoiseSuppressionContextSampleRate('none', 44100)).toBe(44100);
- });
-
- it('pulls fixed-rate backends onto 48k when the capture rate does not fit', () => {
- expect(resolveNoiseSuppressionContextSampleRate('rnnoise', 44100)).toBe(48000);
- expect(resolveNoiseSuppressionContextSampleRate('gtcrn', 44100)).toBe(48000);
- expect(resolveNoiseSuppressionContextSampleRate('deep_filter', 44100)).toBe(48000);
- });
-
- it('leaves a fixed-rate backend alone when the capture rate already fits', () => {
- expect(resolveNoiseSuppressionContextSampleRate('gtcrn', 16000)).toBe(16000);
- expect(resolveNoiseSuppressionContextSampleRate('rnnoise', 48000)).toBe(48000);
- });
-});
-
-describe('wasm simd probe', () => {
- beforeEach(() => {
- resetWasmSimdSupportCacheForTests();
- });
-
- it('detects simd support on a runtime that has it', () => {
- expect(detectWasmSimdSupport()).toBe(true);
- });
-
- it('caches the probe result', () => {
- const first = detectWasmSimdSupport();
- expect(detectWasmSimdSupport()).toBe(first);
- });
-});
-
-describe('noise gate tuning', () => {
- it('maps strength onto the documented threshold range', () => {
- expect(resolveNoiseGateTuning(0).openThreshold).toBeCloseTo(NOISE_GATE_OPEN_THRESHOLD_DB_AT_MIN_STRENGTH, 6);
- expect(resolveNoiseGateTuning(100).openThreshold).toBeCloseTo(NOISE_GATE_OPEN_THRESHOLD_DB_AT_MAX_STRENGTH, 6);
- });
-
- it('is monotonically more aggressive as strength rises', () => {
- let previous = Number.NEGATIVE_INFINITY;
- for (let strength = 0; strength <= 100; strength += 5) {
- const {openThreshold} = resolveNoiseGateTuning(strength);
- expect(openThreshold).toBeGreaterThanOrEqual(previous);
- previous = openThreshold;
- }
- });
-
- it('always keeps the close threshold below the open threshold', () => {
- for (const strength of [0, 25, 50, 80, 100]) {
- const tuning = resolveNoiseGateTuning(strength);
- expect(tuning.closeThreshold).toBeLessThan(tuning.openThreshold);
- }
- });
-
- it('clamps out-of-range and non-finite strengths', () => {
- expect(resolveNoiseGateTuning(-40).openThreshold).toBe(resolveNoiseGateTuning(0).openThreshold);
- expect(resolveNoiseGateTuning(4000).openThreshold).toBe(resolveNoiseGateTuning(100).openThreshold);
- expect(resolveNoiseGateTuning(Number.NaN).openThreshold).toBe(resolveNoiseGateTuning(80).openThreshold);
- });
-});
-
-describe('worklet build-time codemod', () => {
- const require = createRequire(import.meta.url);
- const loader = require('../../../../../scripts/build/rspack/noise-suppressor-worklet-loader.cjs') as (
- this: {resourcePath: string},
- source: string,
- ) => string;
- const readWorklet = (specifier: string) => {
- const resourcePath = require.resolve(specifier);
- const source = require('node:fs').readFileSync(resourcePath, 'utf8') as string;
- return {resourcePath, source};
- };
-
- it('teaches every wasm worklet to pass audio through, signal ready, and start its port', () => {
- for (const specifier of [
- '@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js',
- '@sapphi-red/web-noise-suppressor/gtcrnWorklet.js',
- '@sapphi-red/web-noise-suppressor/speexWorklet.js',
- ]) {
- const {resourcePath, source} = readWorklet(specifier);
- const output = loader.call({resourcePath}, source);
- expect(output).toContain('type:"ready"');
- expect(output).toContain('type:"error"');
- expect(output).toContain('this.port.start()');
- expect(output).toContain('__out[__ch].set(__src)');
- expect(output).not.toContain('!this.processor||this.processor.process(e[0],t[0])');
- }
- });
-
- it('signals ready from the synchronous gate worklet', () => {
- const {resourcePath, source} = readWorklet('@sapphi-red/web-noise-suppressor/noiseGateWorklet.js');
- const output = loader.call({resourcePath}, source);
- expect(output).toContain('type:"ready"');
- });
-
- it('fails loudly when the upstream bundle no longer matches', () => {
- expect(() => loader.call({resourcePath: '/tmp/rnnoise/workletProcessor.js'}, 'not the upstream bundle')).toThrow(
- /update this loader/u,
- );
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionLifecycle.test.ts b/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionLifecycle.test.ts
deleted file mode 100644
index f4e752f3e..000000000
--- a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionLifecycle.test.ts
+++ /dev/null
@@ -1,491 +0,0 @@
-import {
- buildNoiseSuppressionWorkletChain,
- NOISE_SUPPRESSION_STARTUP_TIMEOUT_MS,
-} from '@app/features/voice/utils/noise_suppression/NoiseSuppressionChain';
-import {removeVoiceInputProcessor, syncVoiceInputProcessor} from '@app/features/voice/utils/VoiceInputProcessor';
-import type {LocalAudioTrack, Track, TrackProcessor} from 'livekit-client';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const settings = vi.hoisted(() => ({configVersion: 0, inputVolume: 150, warn: vi.fn()}));
-
-vi.mock('@app/features/platform/utils/AppLogger', () => ({
- Logger: class {
- debug() {}
- info() {}
- warn = settings.warn;
- },
-}));
-vi.mock('@app/features/input/state/InputKeybind', () => ({default: {transmitMode: 'push_to_talk'}}));
-vi.mock('@app/features/voice/state/VoiceSettings', () => ({default: {getInputVolume: () => settings.inputVolume}}));
-vi.mock('@app/features/voice/utils/VoiceProcessingProfile', () => ({
- getActiveInputDeviceLabel: () => 'microphone',
- resolveVoiceProcessingFromStateForDeviceLabel: () => ({
- mode: 'custom',
- echoCancellation: false,
- browserNoiseSuppression: false,
- autoGainControl: false,
- deepFilter: false,
- deepFilterNoiseReductionLevel: 0,
- contentHint: '',
- noiseSuppressionBackend: 'none',
- stereoCapture: false,
- }),
-}));
-vi.mock('@app/features/voice/utils/noise_suppression/NoiseSuppressionRuntime', () => ({
- readEffectiveNoiseSuppression: () => ({
- rolloutApplied: true,
- backend: 'gate',
- requestedBackend: 'gate',
- source: 'global',
- suppressionStrength: 80,
- stereoEnabled: false,
- configVersion: settings.configVersion,
- }),
-}));
-vi.mock('@app/features/voice/engine/v2/VoiceEngineV2AppMicrophoneTransaction', () => ({
- computeSpeakingDetectorRms: () => 0,
-}));
-vi.mock('@app/features/voice/utils/DeepFilterNoiseProcessor', () => ({
- buildDeepFilterAudioChain: () => {
- throw new Error('DeepFilter is outside this worklet lifecycle test');
- },
-}));
-vi.mock('@app/features/voice/utils/noise_suppression/NoiseSuppressionWorkletAssets', () => ({
- NOISE_SUPPRESSION_WORKLET_MODULE_URLS: {
- gate: '/gate.js',
- speex: '/speex.js',
- rnnoise: '/rnnoise.js',
- gtcrn: '/gtcrn.js',
- },
- NOISE_SUPPRESSION_WASM_URLS: {
- speex: '/speex.wasm',
- rnnoise: '/rnnoise.wasm',
- rnnoiseSimd: '/rnnoise_simd.wasm',
- gtcrn: '/gtcrn.wasm',
- },
-}));
-
-interface Deferred<T> {
- promise: Promise<T>;
- resolve: (value: T) => void;
- reject: (error: unknown) => void;
-}
-
-function deferred<T>(): Deferred<T> {
- let resolve!: (value: T) => void;
- let reject!: (error: unknown) => void;
- const promise = new Promise<T>((onResolve, onReject) => {
- resolve = onResolve;
- reject = onReject;
- });
- return {promise, resolve, reject};
-}
-
-class FakeTrack {
- readyState: MediaStreamTrackState = 'live';
- enabled = true;
- stop = vi.fn(() => {
- this.readyState = 'ended';
- });
-}
-
-class FakeStream {
- constructor(private readonly tracks: Array<FakeTrack>) {}
- getAudioTracks(): Array<FakeTrack> {
- return this.tracks;
- }
-}
-
-class FakeNode {
- channelCount = 2;
- channelCountMode = 'max';
- channelInterpretation = 'speakers';
- gain = {value: 1};
- connect = vi.fn();
- disconnect = vi.fn();
-}
-
-class FakeDestination extends FakeNode {
- readonly track = new FakeTrack();
- readonly stream = new FakeStream([this.track]);
-}
-
-let moduleRequested: Deferred<void>;
-let moduleResult: Promise<void>;
-let nodeCreated: Deferred<FakeWorklet>;
-let failOutputConnection: boolean;
-const contexts: Array<FakeContext> = [];
-const worklets: Array<FakeWorklet> = [];
-
-class FakeContext {
- readonly sampleRate = 48000;
- readonly destinations: Array<FakeDestination> = [];
- readonly sources: Array<FakeNode> = [];
- readonly close = vi.fn(async () => {});
- readonly audioWorklet = {
- addModule: vi.fn(() => {
- moduleRequested.resolve(undefined);
- return moduleResult;
- }),
- };
- constructor() {
- contexts.push(this);
- }
- createMediaStreamDestination(): FakeDestination {
- const destination = new FakeDestination();
- this.destinations.push(destination);
- return destination;
- }
- createMediaStreamSource(): FakeNode {
- const source = new FakeNode();
- this.sources.push(source);
- return source;
- }
- createGain(): FakeNode {
- return new FakeNode();
- }
-}
-
-class FakeWorklet extends FakeNode {
- onprocessorerror: (() => void) | null = null;
- readonly port = {
- onmessage: null as ((event: {data: unknown}) => void) | null,
- start: vi.fn(),
- postMessage: vi.fn(),
- close: vi.fn(),
- };
- constructor() {
- super();
- if (failOutputConnection) {
- this.connect.mockImplementation(() => {
- throw new Error('Output connection failed');
- });
- }
- worklets.push(this);
- nodeCreated.resolve(this);
- }
- signal(data: unknown): void {
- this.port.onmessage?.({data});
- }
-}
-
-class FakeLocalTrack {
- readonly rawTrack = new FakeTrack();
- readonly context = new FakeContext();
- processor?: TrackProcessor<Track.Kind.Audio>;
- installCount = 0;
- initializationBarrier?: Promise<void>;
- readonly initializationStarted = deferred<void>();
- private operation: Promise<void> = Promise.resolve();
-
- private exclusive<T>(operation: () => Promise<T>): Promise<T> {
- const result = this.operation.then(operation);
- this.operation = result.then(
- () => {},
- () => {},
- );
- return result;
- }
-
- setProcessor(processor: TrackProcessor<Track.Kind.Audio>): Promise<void> {
- return this.exclusive(async () => {
- this.installCount++;
- this.initializationStarted.resolve(undefined);
- if (this.initializationBarrier) await this.initializationBarrier;
- await processor.init({
- kind: 'audio' as Track.Kind.Audio,
- track: this.rawTrack as unknown as MediaStreamTrack,
- audioContext: this.context as unknown as AudioContext,
- });
- this.processor = processor;
- });
- }
-
- stopProcessorIfCurrent(processor: TrackProcessor<Track.Kind.Audio>): Promise<boolean> {
- return this.exclusive(async () => {
- if (this.processor !== processor) return false;
- this.processor = undefined;
- await processor.destroy();
- return true;
- });
- }
-
- asLocalAudioTrack(): LocalAudioTrack {
- return this as unknown as LocalAudioTrack;
- }
-}
-
-function captureContext(): AudioContext {
- return new FakeContext() as unknown as AudioContext;
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- settings.configVersion++;
- settings.warn.mockClear();
- contexts.length = 0;
- worklets.length = 0;
- moduleRequested = deferred<void>();
- moduleResult = Promise.resolve();
- nodeCreated = deferred<FakeWorklet>();
- failOutputConnection = false;
- vi.stubGlobal('window', {AudioContext: FakeContext, setTimeout, clearTimeout, setInterval, clearInterval});
- vi.stubGlobal('AudioWorkletNode', FakeWorklet);
- vi.stubGlobal('MediaStream', FakeStream);
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => Promise.reject(new Error('Unexpected asset request'))),
- );
-});
-
-afterEach(async () => {
- await removeVoiceInputProcessor();
- expect(vi.getTimerCount()).toBe(0);
- vi.unstubAllGlobals();
- vi.useRealTimers();
-});
-
-describe('worklet startup ownership', () => {
- it('does not allocate resources for an already-cancelled startup', async () => {
- const audioContext = captureContext();
- const controller = new AbortController();
- controller.abort(new Error('Cancelled before setup'));
- await expect(
- buildNoiseSuppressionWorkletChain({
- audioContext,
- backend: 'gate',
- suppressionStrength: 80,
- signal: controller.signal,
- }),
- ).rejects.toThrow('Cancelled before setup');
- expect(contexts).toHaveLength(1);
- expect(contexts[0].destinations).toHaveLength(0);
- });
-
- it('bounds module loading and ignores its late completion after timeout', async () => {
- const loading = deferred<void>();
- moduleResult = loading.promise;
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'gate',
- suppressionStrength: 80,
- });
- const failure = expect(build).rejects.toThrow('startup timed out');
- await moduleRequested.promise;
- await vi.advanceTimersByTimeAsync(NOISE_SUPPRESSION_STARTUP_TIMEOUT_MS);
- await failure;
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- expect(contexts[0].destinations[0].track.readyState).toBe('ended');
- loading.resolve(undefined);
- await loading.promise;
- expect(worklets).toHaveLength(0);
- });
-
- it('releases a timed-out startup without waiting for audio-context closure', async () => {
- moduleResult = deferred<void>().promise;
- const closing = deferred<void>();
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'gate',
- suppressionStrength: 80,
- });
- const failure = expect(build).rejects.toThrow('startup timed out');
- await moduleRequested.promise;
- contexts[1].close.mockImplementation(() => closing.promise);
- await vi.advanceTimersByTimeAsync(NOISE_SUPPRESSION_STARTUP_TIMEOUT_MS);
- await failure;
- expect(contexts[0].destinations[0].track.readyState).toBe('ended');
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- closing.resolve(undefined);
- await closing.promise;
- });
-
- it('aborts a stalled WASM download and does not cache its late response', async () => {
- const download = deferred<Response>();
- const requested = deferred<AbortSignal>();
- vi.mocked(fetch).mockImplementation((_url, options) => {
- requested.resolve(options!.signal as AbortSignal);
- return download.promise;
- });
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'rnnoise',
- suppressionStrength: 80,
- });
- const failure = expect(build).rejects.toThrow('startup timed out');
- const signal = await requested.promise;
- await vi.advanceTimersByTimeAsync(NOISE_SUPPRESSION_STARTUP_TIMEOUT_MS);
- await failure;
- expect(signal.aborted).toBe(true);
- download.resolve(new Response(new Uint8Array([1])));
- await download.promise;
- await vi.advanceTimersByTimeAsync(0);
- expect(worklets).toHaveLength(0);
- vi.mocked(fetch).mockResolvedValueOnce(new Response(new Uint8Array([2])));
- const retry = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'rnnoise',
- suppressionStrength: 80,
- });
- (await nodeCreated.promise).signal({type: 'ready'});
- const chain = await retry;
- expect(fetch).toHaveBeenCalledTimes(2);
- await chain.dispose();
- });
-
- it.each([
- 'abort',
- 'processor-error',
- ] as const)('releases startup resources on %s before readiness', async (failureKind) => {
- const controller = new AbortController();
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'gate',
- suppressionStrength: 80,
- signal: controller.signal,
- });
- const failure = expect(build).rejects.toThrow(failureKind === 'abort' ? 'Cancelled' : 'processor error');
- const node = await nodeCreated.promise;
- if (failureKind === 'abort') controller.abort(new Error('Cancelled'));
- else node.onprocessorerror?.();
- await failure;
- expect(node.port.onmessage).toBeNull();
- expect(node.onprocessorerror).toBeNull();
- expect(node.port.close).toHaveBeenCalledTimes(1);
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- expect(contexts[0].destinations[0].track.readyState).toBe('ended');
- });
-
- it('stops an output track when connecting the completed graph fails', async () => {
- failOutputConnection = true;
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'gate',
- suppressionStrength: 80,
- });
- const failure = expect(build).rejects.toThrow('Output connection failed');
- (await nodeCreated.promise).signal({type: 'ready'});
- await failure;
- expect(contexts[1].destinations[0].track.readyState).toBe('ended');
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- });
-
- it('reports a runtime failure once and shares one disposal operation', async () => {
- const onRuntimeFailure = vi.fn();
- const build = buildNoiseSuppressionWorkletChain({
- audioContext: captureContext(),
- backend: 'gate',
- suppressionStrength: 80,
- onRuntimeFailure,
- });
- const node = await nodeCreated.promise;
- node.signal({type: 'ready'});
- const chain = await build;
- const oldMessageHandler = node.port.onmessage!;
- node.signal({type: 'error', message: 'Failed during processing'});
- node.onprocessorerror?.();
- expect(onRuntimeFailure).toHaveBeenCalledTimes(1);
- const disposal = chain.dispose();
- expect(chain.dispose()).toBe(disposal);
- await disposal;
- oldMessageHandler({data: {type: 'error', message: 'Late error'}});
- expect(onRuntimeFailure).toHaveBeenCalledTimes(1);
- expect(chain.processedTrack.readyState).toBe('ended');
- expect(contexts[0].close).not.toHaveBeenCalled();
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('voice input processor lifecycle', () => {
- it('cancels an installing processor before the track has published it', async () => {
- const loading = deferred<void>();
- moduleResult = loading.promise;
- const track = new FakeLocalTrack();
- const install = syncVoiceInputProcessor(track.asLocalAudioTrack());
- await moduleRequested.promise;
- await Promise.all([removeVoiceInputProcessor(track.asLocalAudioTrack()), install]);
- expect(track.processor).toBeUndefined();
- expect(contexts[1].close).toHaveBeenCalledTimes(1);
- loading.resolve(undefined);
- await loading.promise;
- expect(worklets).toHaveLength(0);
- expect(settings.warn).not.toHaveBeenCalled();
- });
-
- it('replaces a pending track without letting its late failure blacklist the backend', async () => {
- const loading = deferred<void>();
- moduleResult = loading.promise;
- const first = new FakeLocalTrack();
- const installFirst = syncVoiceInputProcessor(first.asLocalAudioTrack());
- await moduleRequested.promise;
- moduleResult = Promise.resolve();
- const second = new FakeLocalTrack();
- const installSecond = syncVoiceInputProcessor(second.asLocalAudioTrack());
- loading.reject(new Error('Obsolete asset failure'));
- (await nodeCreated.promise).signal({type: 'ready'});
- await Promise.all([installFirst, installSecond]);
- expect(first.processor).toBeUndefined();
- expect(second.processor?.processedTrack?.readyState).toBe('live');
- await removeVoiceInputProcessor(first.asLocalAudioTrack());
- expect(second.processor).toBeDefined();
- expect(settings.warn).not.toHaveBeenCalled();
- });
-
- it('coalesces overlapping requests before creating the processor', async () => {
- const track = new FakeLocalTrack();
- const first = syncVoiceInputProcessor(track.asLocalAudioTrack());
- const second = syncVoiceInputProcessor(track.asLocalAudioTrack());
- (await nodeCreated.promise).signal({type: 'ready'});
- await Promise.all([first, second]);
- expect(track.installCount).toBe(1);
- expect(worklets).toHaveLength(1);
- });
-
- it('cancels a candidate while it is waiting to enter initialization', async () => {
- const track = new FakeLocalTrack();
- const waiting = deferred<void>();
- track.initializationBarrier = waiting.promise;
- const install = syncVoiceInputProcessor(track.asLocalAudioTrack());
- await track.initializationStarted.promise;
- const removal = removeVoiceInputProcessor(track.asLocalAudioTrack());
- waiting.resolve(undefined);
- await Promise.all([install, removal]);
- expect(track.processor).toBeUndefined();
- expect(contexts).toHaveLength(1);
- expect(worklets).toHaveLength(0);
- expect(settings.warn).not.toHaveBeenCalled();
- });
-
- it('retains the capture context for LiveKit restarts that omit it', async () => {
- const track = new FakeLocalTrack();
- const install = syncVoiceInputProcessor(track.asLocalAudioTrack());
- (await nodeCreated.promise).signal({type: 'ready'});
- await install;
- const previousOutput = track.processor!.processedTrack!;
- nodeCreated = deferred<FakeWorklet>();
- const restart = track.processor!.restart({
- kind: 'audio' as Track.Kind.Audio,
- track: track.rawTrack as unknown as MediaStreamTrack,
- });
- (await nodeCreated.promise).signal({type: 'ready'});
- await restart;
- expect(previousOutput.readyState).toBe('ended');
- expect(track.processor!.processedTrack!.readyState).toBe('live');
- expect(contexts[0].close).not.toHaveBeenCalled();
- });
-
- it('does not reinstall an old track when a runtime failure overlaps a track change', async () => {
- const first = new FakeLocalTrack();
- const installFirst = syncVoiceInputProcessor(first.asLocalAudioTrack());
- const failedNode = await nodeCreated.promise;
- failedNode.signal({type: 'ready'});
- await installFirst;
- failedNode.signal({type: 'error', message: 'Processing failed'});
- const second = new FakeLocalTrack();
- await syncVoiceInputProcessor(second.asLocalAudioTrack());
- expect(first.processor).toBeUndefined();
- expect(first.installCount).toBe(1);
- expect(second.installCount).toBe(1);
- expect(second.processor!.processedTrack!.readyState).toBe('live');
- });
-});
diff --git a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionSelection.test.ts b/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionSelection.test.ts
deleted file mode 100644
index df5b87495..000000000
--- a/fluxer_app/src/features/voice/utils/noise_suppression/NoiseSuppressionSelection.test.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {NoiseSuppressionRuntimeCapabilities} from '@app/features/voice/utils/noise_suppression/NoiseSuppressionBackends';
-import {
- applyNoiseSuppressionOverride,
- INERT_EFFECTIVE_NOISE_SUPPRESSION,
- resolveEffectiveNoiseSuppression,
-} from '@app/features/voice/utils/noise_suppression/NoiseSuppressionSelection';
-import type {ResolvedVoiceProcessing} from '@app/features/voice/utils/VoiceProcessingProfile';
-import type {
- VoiceNoiseSuppressionAssignmentResponse,
- VoiceNoiseSuppressionBackend,
-} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';
-import {INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT} from '@fluxer/schema/src/domains/admin/VoiceNoiseSuppressionSchemas';
-import {describe, expect, it} from 'vitest';
-
-const CAPABLE: NoiseSuppressionRuntimeCapabilities = {sampleRate: 48000, wasmSimd: true, audioWorklet: true};
-
-function assignment(
- overrides: Partial<VoiceNoiseSuppressionAssignmentResponse> = {},
-): VoiceNoiseSuppressionAssignmentResponse {
- return {
- ...INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT,
- enabled: true,
- user_targeted: true,
- backend: 'rnnoise',
- source: 'canary',
- enabled_backends: ['none', 'standard', 'gate', 'speex', 'rnnoise', 'gtcrn', 'deep_filter'],
- allow_user_override: true,
- stereo_enabled: true,
- suppression_strength: 65,
- config_version: 7,
- ...overrides,
- };
-}
-
-function voiceProfile(overrides: Partial<ResolvedVoiceProcessing> = {}): ResolvedVoiceProcessing {
- return {
- mode: 'voice',
- echoCancellation: true,
- browserNoiseSuppression: true,
- autoGainControl: true,
- deepFilter: false,
- deepFilterNoiseReductionLevel: 0,
- contentHint: 'speech',
- noiseSuppressionBackend: 'standard',
- stereoCapture: false,
- ...overrides,
- };
-}
-
-describe('resolveEffectiveNoiseSuppression', () => {
- it('is inert for the default assignment', () => {
- const effective = resolveEffectiveNoiseSuppression(INERT_VOICE_NOISE_SUPPRESSION_ASSIGNMENT, null, null, CAPABLE);
- expect(effective).toEqual(INERT_EFFECTIVE_NOISE_SUPPRESSION);
- expect(effective.rolloutApplied).toBe(false);
- });
-
- it('is inert for an untargeted user even while the rollout is enabled', () => {
- const effective = resolveEffectiveNoiseSuppression(
- assignment({user_targeted: false, backend: null, source: null}),
- null,
- null,
- CAPABLE,
- );
- expect(effective.rolloutApplied).toBe(false);
- });
-
- it('carries the targeted backend and knobs through', () => {
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, null, CAPABLE);
- expect(effective.rolloutApplied).toBe(true);
- expect(effective.backend).toBe('rnnoise');
- expect(effective.requestedBackend).toBe('rnnoise');
- expect(effective.source).toBe('canary');
- expect(effective.suppressionStrength).toBe(65);
- expect(effective.configVersion).toBe(7);
- });
-
- it('honours a guild override', () => {
- const effective = resolveEffectiveNoiseSuppression(
- assignment({
- user_targeted: false,
- backend: null,
- source: null,
- guild_overrides: [{guild_id: '42', backend: 'speex'}],
- }),
- '42',
- null,
- CAPABLE,
- );
- expect(effective.backend).toBe('speex');
- expect(effective.source).toBe('guild_rule');
- });
-
- it('ignores a guild override for a different call', () => {
- const effective = resolveEffectiveNoiseSuppression(
- assignment({
- user_targeted: false,
- backend: null,
- source: null,
- guild_overrides: [{guild_id: '42', backend: 'speex'}],
- }),
- '43',
- null,
- CAPABLE,
- );
- expect(effective.rolloutApplied).toBe(false);
- });
-
- it('honours an allowed user preference', () => {
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, 'gtcrn', CAPABLE);
- expect(effective.backend).toBe('gtcrn');
- expect(effective.source).toBe('user_override');
- });
-
- it('ignores a preference that is not a known backend', () => {
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, 'krisp', CAPABLE);
- expect(effective.backend).toBe('rnnoise');
- });
-
- it('ignores a preference the config does not enable', () => {
- const effective = resolveEffectiveNoiseSuppression(
- assignment({enabled_backends: ['standard', 'rnnoise']}),
- null,
- 'gtcrn',
- CAPABLE,
- );
- expect(effective.backend).toBe('rnnoise');
- });
-
- it('ignores a preference when overrides are disallowed', () => {
- const effective = resolveEffectiveNoiseSuppression(
- assignment({allow_user_override: false}),
- null,
- 'gtcrn',
- CAPABLE,
- );
- expect(effective.backend).toBe('rnnoise');
- });
-
- it('falls back to a usable backend when the target cannot run here', () => {
- const at44k: NoiseSuppressionRuntimeCapabilities = {...CAPABLE, sampleRate: 44100};
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, null, at44k);
- expect(effective.requestedBackend).toBe('rnnoise');
- expect(effective.backend).toBe('standard');
- });
-
- it('falls back when gtcrn is targeted without wasm simd', () => {
- const effective = resolveEffectiveNoiseSuppression(assignment({backend: 'gtcrn'}), null, null, {
- ...CAPABLE,
- wasmSimd: false,
- });
- expect(effective.backend).toBe('standard');
- });
-
- it('only reports stereo for a backend that keeps the channel layout', () => {
- expect(resolveEffectiveNoiseSuppression(assignment({backend: 'standard'}), null, null, CAPABLE).stereoEnabled).toBe(
- true,
- );
- expect(resolveEffectiveNoiseSuppression(assignment({backend: 'none'}), null, null, CAPABLE).stereoEnabled).toBe(
- true,
- );
- for (const backend of ['gate', 'speex', 'rnnoise', 'gtcrn', 'deep_filter'] as const) {
- expect(resolveEffectiveNoiseSuppression(assignment({backend}), null, null, CAPABLE).stereoEnabled).toBe(false);
- }
- });
-
- it('lets the user turn stereo off without turning it on when the rollout has not', () => {
- expect(
- resolveEffectiveNoiseSuppression(assignment({backend: 'standard'}), null, null, CAPABLE, false).stereoEnabled,
- ).toBe(false);
- expect(
- resolveEffectiveNoiseSuppression(
- assignment({backend: 'standard', stereo_enabled: false}),
- null,
- null,
- CAPABLE,
- true,
- ).stereoEnabled,
- ).toBe(false);
- });
-});
-
-describe('applyNoiseSuppressionOverride', () => {
- it('leaves the profile untouched when the rollout is inert', () => {
- const profile = voiceProfile();
- expect(applyNoiseSuppressionOverride(profile, INERT_EFFECTIVE_NOISE_SUPPRESSION)).toBe(profile);
- });
-
- it('never overrides studio mode', () => {
- const profile = voiceProfile({mode: 'studio', browserNoiseSuppression: false, contentHint: 'music'});
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, null, CAPABLE);
- expect(applyNoiseSuppressionOverride(profile, effective)).toBe(profile);
- });
-
- it('turns the browser filter off for every worklet backend', () => {
- for (const backend of ['gate', 'speex', 'rnnoise', 'gtcrn', 'deep_filter', 'none'] as const) {
- const effective = resolveEffectiveNoiseSuppression(assignment({backend}), null, null, CAPABLE);
- const applied = applyNoiseSuppressionOverride(voiceProfile(), effective);
- expect(applied.browserNoiseSuppression).toBe(false);
- expect(applied.noiseSuppressionBackend).toBe(backend);
- }
- });
-
- it('turns the browser filter on for standard', () => {
- const effective = resolveEffectiveNoiseSuppression(assignment({backend: 'standard'}), null, null, CAPABLE);
- const applied = applyNoiseSuppressionOverride(voiceProfile({browserNoiseSuppression: false}), effective);
- expect(applied.browserNoiseSuppression).toBe(true);
- expect(applied.deepFilter).toBe(false);
- });
-
- it('routes the strength into the deep filter level only for deep_filter', () => {
- const deep = resolveEffectiveNoiseSuppression(assignment({backend: 'deep_filter'}), null, null, CAPABLE);
- const appliedDeep = applyNoiseSuppressionOverride(voiceProfile(), deep);
- expect(appliedDeep.deepFilter).toBe(true);
- expect(appliedDeep.deepFilterNoiseReductionLevel).toBe(65);
-
- const rnnoise = resolveEffectiveNoiseSuppression(assignment({backend: 'rnnoise'}), null, null, CAPABLE);
- const appliedRnnoise = applyNoiseSuppressionOverride(voiceProfile(), rnnoise);
- expect(appliedRnnoise.deepFilter).toBe(false);
- expect(appliedRnnoise.deepFilterNoiseReductionLevel).toBe(0);
- });
-
- it('preserves every field it does not own', () => {
- const profile = voiceProfile({echoCancellation: false, autoGainControl: false, contentHint: 'speech'});
- const effective = resolveEffectiveNoiseSuppression(assignment(), null, null, CAPABLE);
- const applied = applyNoiseSuppressionOverride(profile, effective);
- expect(applied.mode).toBe(profile.mode);
- expect(applied.echoCancellation).toBe(false);
- expect(applied.autoGainControl).toBe(false);
- expect(applied.contentHint).toBe('speech');
- });
-
- it('sets stereo capture only when the effective resolution says so', () => {
- const stereo = resolveEffectiveNoiseSuppression(assignment({backend: 'standard'}), null, null, CAPABLE);
- expect(applyNoiseSuppressionOverride(voiceProfile(), stereo).stereoCapture).toBe(true);
- const mono = resolveEffectiveNoiseSuppression(assignment({backend: 'rnnoise'}), null, null, CAPABLE);
- expect(applyNoiseSuppressionOverride(voiceProfile(), mono).stereoCapture).toBe(false);
- });
-});
-
-describe('backend coverage', () => {
- it('resolves every contract backend to something runnable', () => {
- const backends: ReadonlyArray<VoiceNoiseSuppressionBackend> = [
- 'none',
- 'standard',
- 'gate',
- 'speex',
- 'rnnoise',
- 'gtcrn',
- 'deep_filter',
- ];
- for (const backend of backends) {
- const effective = resolveEffectiveNoiseSuppression(assignment({backend}), null, null, CAPABLE);
- expect(effective.backend).toBe(backend);
- }
- });
-});
diff --git a/fluxer_app/src/lib/forms/RemoteFormReset.test.ts b/fluxer_app/src/lib/forms/RemoteFormReset.test.ts
deleted file mode 100644
index cee358d1d..000000000
--- a/fluxer_app/src/lib/forms/RemoteFormReset.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- createRemoteFormResetMachineSnapshot,
- getRemoteFormResetDecision,
- getRemoteFormResetMachineStateValue,
- type RemoteFormResetMachineEvent,
- type RemoteFormResetMachineSnapshot,
- transitionRemoteFormResetSnapshot,
-} from '@app/lib/forms/RemoteFormReset';
-import {describe, expect, it} from 'vitest';
-
-function transition(
- snapshot: RemoteFormResetMachineSnapshot,
- event: RemoteFormResetMachineEvent,
-): RemoteFormResetMachineSnapshot {
- return transitionRemoteFormResetSnapshot(snapshot, event);
-}
-
-describe('remoteFormResetStateMachine', () => {
- it('starts unhydrated and applies the first remote values regardless of dirty state', () => {
- let snapshot = createRemoteFormResetMachineSnapshot();
- expect(getRemoteFormResetMachineStateValue(snapshot)).toBe('unhydrated');
- snapshot = transition(snapshot, {
- type: 'remote.inspect',
- identityChanged: false,
- remoteValuesChanged: false,
- isDirty: true,
- });
- expect(getRemoteFormResetMachineStateValue(snapshot)).toBe('hydrated');
- expect(snapshot.context.decision).toEqual({shouldReset: true, reason: 'initial'});
- });
-
- it('keeps dirty same-identity remote refreshes from resetting the form', () => {
- let snapshot = createRemoteFormResetMachineSnapshot();
- snapshot = transition(snapshot, {type: 'remote.commit'});
- snapshot = transition(snapshot, {
- type: 'remote.inspect',
- identityChanged: false,
- remoteValuesChanged: true,
- isDirty: true,
- });
- expect(snapshot.context.decision).toEqual({shouldReset: false});
- });
-
- it('allows identity changes, clean remote refreshes, explicit resets, and commits', () => {
- let snapshot = createRemoteFormResetMachineSnapshot();
- snapshot = transition(snapshot, {type: 'remote.commit'});
- snapshot = transition(snapshot, {
- type: 'remote.inspect',
- identityChanged: true,
- remoteValuesChanged: true,
- isDirty: true,
- });
- expect(snapshot.context.decision).toEqual({shouldReset: true, reason: 'identity-change'});
- snapshot = transition(snapshot, {
- type: 'remote.inspect',
- identityChanged: false,
- remoteValuesChanged: true,
- isDirty: false,
- });
- expect(snapshot.context.decision).toEqual({shouldReset: true, reason: 'remote-clean'});
- snapshot = transition(snapshot, {type: 'remote.explicitReset'});
- expect(snapshot.context.decision).toEqual({shouldReset: true, reason: 'explicit-reset'});
- snapshot = transition(snapshot, {type: 'remote.commit'});
- expect(snapshot.context.decision).toEqual({shouldReset: true, reason: 'commit'});
- });
-});
-
-describe('getRemoteFormResetDecision', () => {
- it('hydrates before any remote values have been applied', () => {
- expect(
- getRemoteFormResetDecision({
- hasAppliedRemoteValues: false,
- identityChanged: false,
- remoteValuesChanged: false,
- isDirty: true,
- }),
- ).toEqual({shouldReset: true, reason: 'initial'});
- });
-
- it('resets on identity changes even when the previous entity is dirty', () => {
- expect(
- getRemoteFormResetDecision({
- hasAppliedRemoteValues: true,
- identityChanged: true,
- remoteValuesChanged: true,
- isDirty: true,
- }),
- ).toEqual({shouldReset: true, reason: 'identity-change'});
- });
-
- it('accepts remote refreshes while the form is clean', () => {
- expect(
- getRemoteFormResetDecision({
- hasAppliedRemoteValues: true,
- identityChanged: false,
- remoteValuesChanged: true,
- isDirty: false,
- }),
- ).toEqual({shouldReset: true, reason: 'remote-clean'});
- });
-
- it('does not overwrite dirty local edits for the same identity', () => {
- expect(
- getRemoteFormResetDecision({
- hasAppliedRemoteValues: true,
- identityChanged: false,
- remoteValuesChanged: true,
- isDirty: true,
- }),
- ).toEqual({shouldReset: false});
- });
-
- it('does nothing when the same remote values are seen again', () => {
- expect(
- getRemoteFormResetDecision({
- hasAppliedRemoteValues: true,
- identityChanged: false,
- remoteValuesChanged: false,
- isDirty: false,
- }),
- ).toEqual({shouldReset: false});
- });
-});
diff --git a/fluxer_app/src/lib/forms/TransientUploadFields.test.ts b/fluxer_app/src/lib/forms/TransientUploadFields.test.ts
deleted file mode 100644
index 9751b6a68..000000000
--- a/fluxer_app/src/lib/forms/TransientUploadFields.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- assignTransientUploadFieldMutation,
- getTransientUploadFieldMutation,
- omitTransientUploadFields,
-} from '@app/lib/forms/TransientUploadFields';
-import {describe, expect, it} from 'vitest';
-
-describe('getTransientUploadFieldMutation', () => {
- it('preserves the existing remote asset when there is no explicit upload or clear', () => {
- expect(getTransientUploadFieldMutation({value: null})).toBeUndefined();
- expect(getTransientUploadFieldMutation({value: 'stale-form-value'})).toBeUndefined();
- });
-
- it('returns null only for explicit clears', () => {
- expect(
- getTransientUploadFieldMutation({value: 'new-upload', previewUrl: 'new-upload', hasCleared: true}),
- ).toBeNull();
- });
-
- it('returns the pending upload when a preview exists', () => {
- expect(getTransientUploadFieldMutation({value: 'new-upload', previewUrl: 'new-upload'})).toBe('new-upload');
- expect(getTransientUploadFieldMutation({value: undefined, previewUrl: 'preview-upload'})).toBe('preview-upload');
- });
-});
-
-describe('assignTransientUploadFieldMutation', () => {
- it('omits unchanged upload fields from API payloads', () => {
- const payload: {name: string; avatar?: string | null} = {name: 'Doc'};
- assignTransientUploadFieldMutation(payload, 'avatar', {value: null});
- expect(payload).toEqual({name: 'Doc'});
- });
-
- it('assigns explicit uploads and clears', () => {
- const uploadPayload: {avatar?: string | null} = {};
- assignTransientUploadFieldMutation(uploadPayload, 'avatar', {value: 'base64', previewUrl: 'base64'});
- expect(uploadPayload).toEqual({avatar: 'base64'});
-
- const clearPayload: {avatar?: string | null} = {};
- assignTransientUploadFieldMutation(clearPayload, 'avatar', {value: null, hasCleared: true});
- expect(clearPayload).toEqual({avatar: null});
- });
-});
-
-describe('omitTransientUploadFields', () => {
- it('removes one-shot upload fields from committed remote form values', () => {
- expect(
- omitTransientUploadFields({name: 'Doc', avatar: null, banner: 'base64'}, ['avatar', 'banner'] as const),
- ).toEqual({name: 'Doc'});
- });
-});