A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(app): remove voice engine and helper unit tests
Hampus0a88dfe434fe
diff --git a/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.ts b/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.tsdeleted file mode 100644index 0c9d12118..000000000--- a/fluxer_app/src/features/voice/components/VoiceControlBarStateMachine.test.ts+++ /dev/null@@ -1,69 +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,- isSelfMuted: false,- effectiveMuted: false,- canStream: true,- isCameraEnabled: false,- isCameraLimitReached: false,- isCameraUserCapReached: false,- isScreenShareEnabled: false,- screenShareDisabled: false,- ...overrides,- };-}--describe('voice control bar mute button in push to talk', () => {- it('enables the toggle and shows the idle gate as unmuted with the hold hint', () => {- expect(transitionVoiceControlBarState(signals({isPushToTalkEffective: true, effectiveMuted: true})).mute).toEqual({- disabled: false,- pressed: false,- label: 'pushToTalkHoldHint',- });- });-- it('offers unmute when self-muted', () => {- expect(- transitionVoiceControlBarState(signals({isPushToTalkEffective: true, isSelfMuted: true, effectiveMuted: true}))- .mute,- ).toEqual({disabled: false, pressed: true, label: 'unmute'});- });-- it('keeps server and permission mutes locked', () => {- expect(- transitionVoiceControlBarState(signals({isPushToTalkEffective: true, isGuildMuted: true, effectiveMuted: true}))- .mute,- ).toEqual({disabled: true, pressed: true, label: 'moderatorMuted'});- expect(- transitionVoiceControlBarState(- signals({isPushToTalkEffective: true, isPermissionMuted: true, effectiveMuted: true}),- ).mute,- ).toEqual({disabled: true, pressed: true, label: 'permissionMuted'});- expect(- transitionVoiceControlBarState(- signals({isPushToTalkEffective: true, isGuildDeafened: true, effectiveMuted: true}),- ).mute,- ).toEqual({disabled: true, pressed: true, label: 'moderatorDeafened'});- });-- it('keeps voice activity labels unchanged', () => {- expect(transitionVoiceControlBarState(signals({})).mute).toEqual({disabled: false, pressed: false, label: 'mute'});- expect(transitionVoiceControlBarState(signals({isSelfMuted: true, effectiveMuted: true})).mute).toEqual({- disabled: false,- pressed: true,- label: 'unmute',- });- });-});diff --git a/fluxer_app/src/features/voice/engine/VoiceChannelConnector.test.ts b/fluxer_app/src/features/voice/engine/VoiceChannelConnector.test.tsdeleted file mode 100644index 8c7f699f7..000000000--- a/fluxer_app/src/features/voice/engine/VoiceChannelConnector.test.ts+++ /dev/null@@ -1,90 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {transitionVoiceEngineV2} from '@fluxer/voice_engine_v2/src/core/reducer';-import {- availableVoiceEngineV2Capabilities,- createVoiceEngineV2InitialSnapshot,- type VoiceEngineV2Snapshot,-} from '@fluxer/voice_engine_v2/src/core/state';-import type {VoiceEngineV2AudioControlsPatch} from '@fluxer/voice_engine_v2/src/protocol/types';-import {beforeEach, describe, expect, it, vi} from 'vitest';--const updateVoiceStateExplicit = vi.fn();-const engine: {snapshot: VoiceEngineV2Snapshot | null} = {snapshot: 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 ?? ''}}),-}));--vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({- default: {foregroundConnection: {socket: {updateVoiceStateExplicit}}},-}));--vi.mock('@app/features/voice/engine/VoiceMediaEngineBridge', () => ({- getAllVoiceStatesInChannelFromMediaEngine: () => ({}),- getVoiceConnectionContextFromMediaEngine: () => ({connectionId: 'local'}),- getVoiceEngineV2SnapshotFromMediaEngine: () => engine.snapshot,-}));--vi.mock('@app/features/voice/utils/VoicePermissionUtils', () => ({- applyVoiceSpeakPermissionToSelfMute: (_guildId: string | null, _channelId: string, selfMute: boolean) => selfMute,-}));--vi.mock('@app/features/voice/components/alerts/VoiceChannelFullModal', () => ({VoiceChannelFullModal: () => null}));-vi.mock('@app/features/voice/components/alerts/VoiceConnectionConfirmModal', () => ({- VoiceConnectionConfirmModal: () => null,-}));-vi.mock('@app/features/voice/components/alerts/VoiceP2pConsentModal', () => ({VoiceP2pConsentModal: () => null}));--const {syncVoiceStateToServer} = await import('@app/features/voice/engine/VoiceChannelConnector');--function snapshotWith(controls: VoiceEngineV2AudioControlsPatch): VoiceEngineV2Snapshot {- return transitionVoiceEngineV2(createVoiceEngineV2InitialSnapshot(availableVoiceEngineV2Capabilities()), {- type: 'audioControls.changed',- controls,- }).snapshot;-}--function lastSelfMute(): boolean {- const [payload] = updateVoiceStateExplicit.mock.lastCall as [{self_mute: boolean}];- return payload.self_mute;-}--describe('direct gateway voice state sync with push to talk', () => {- beforeEach(() => {- updateVoiceStateExplicit.mockClear();- });-- it('reports self_mute while the push to talk key is up on a viewer stream key sync', () => {- engine.snapshot = snapshotWith({mode: 'pushToTalk', pushToTalkActive: false, locallyMuted: false});- syncVoiceStateToServer('1', '2', 'local', {viewer_stream_keys: []});- expect(lastSelfMute()).toBe(true);- });-- it('reports unmuted while the push to talk key is held', () => {- engine.snapshot = snapshotWith({mode: 'pushToTalk', pushToTalkActive: true, locallyMuted: false});- syncVoiceStateToServer('1', '2', 'local', {viewer_stream_keys: []});- expect(lastSelfMute()).toBe(false);- });-- it('reports self-mute over a held push to talk key', () => {- engine.snapshot = snapshotWith({mode: 'pushToTalk', pushToTalkActive: true, locallyMuted: true});- syncVoiceStateToServer('1', '2', 'local', {viewer_stream_keys: []});- expect(lastSelfMute()).toBe(true);- });-- it('keeps voice activity unmuted and prefers an explicit self_mute', () => {- engine.snapshot = snapshotWith({mode: 'voiceActivity', locallyMuted: false});- syncVoiceStateToServer('1', '2', 'local', {viewer_stream_keys: []});- expect(lastSelfMute()).toBe(false);- syncVoiceStateToServer('1', '2', 'local', {self_mute: true});- expect(lastSelfMute()).toBe(true);- });-});diff --git a/fluxer_app/src/features/voice/engine/VoiceGatewayStateMachine.test.ts b/fluxer_app/src/features/voice/engine/VoiceGatewayStateMachine.test.tsdeleted file mode 100644index 68c0e04d3..000000000--- a/fluxer_app/src/features/voice/engine/VoiceGatewayStateMachine.test.ts+++ /dev/null@@ -1,503 +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 {- createVoiceGatewayStateSnapshot,- transitionVoiceGatewayStateSnapshot,- type VoiceGatewayStateContext,- type VoiceGatewayStateEvent,- type VoiceGatewayStateSnapshot,-} from '@app/features/voice/engine/VoiceGatewayStateMachine';-import {describe, expect, it} 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',- };-}--function transition(snapshot: VoiceGatewayStateSnapshot, event: VoiceGatewayStateEvent): VoiceGatewayStateSnapshot {- return transitionVoiceGatewayStateSnapshot(snapshot, event);-}--function expectConnection(- context: VoiceGatewayStateContext,- connectionId: string,- expected: Pick<VoiceState, 'guild_id' | 'channel_id' | 'user_id'>,-): void {- const byConnection = context.connectionVoiceStates[connectionId];- expect(byConnection).toMatchObject(expected);- expect(context.voiceStates[expected.guild_id]?.[expected.channel_id ?? '']?.[connectionId]).toBe(byConnection);- expect(context.userVoiceStates[expected.user_id]?.[expected.guild_id]?.[connectionId]).toBe(byConnection);-}--function expectNoGuild(context: VoiceGatewayStateContext, guildId: string): void {- expect(context.voiceStates[guildId]).toBeUndefined();- for (const userStates of Object.values(context.userVoiceStates)) {- expect(userStates[guildId]).toBeUndefined();- }- for (const voiceStateValue of Object.values(context.connectionVoiceStates)) {- expect(voiceStateValue.guild_id).not.toBe(guildId);- }-}--function expectProjectionConsistent(context: VoiceGatewayStateContext): void {- const seenConnectionIds = new Set<string>();- for (const [guildId, guildStates] of Object.entries(context.voiceStates)) {- for (const [channelId, channelStates] of Object.entries(guildStates)) {- for (const [connectionId, state] of Object.entries(channelStates)) {- expect(seenConnectionIds.has(connectionId)).toBe(false);- seenConnectionIds.add(connectionId);- expect(state.guild_id).toBe(guildId);- expect(state.channel_id).toBe(channelId);- expect(state.connection_id).toBe(connectionId);- expect(context.connectionVoiceStates[connectionId]).toBe(state);- expect(context.userVoiceStates[state.user_id]?.[guildId]?.[connectionId]).toBe(state);- }- }- }-- for (const [connectionId, state] of Object.entries(context.connectionVoiceStates)) {- expect(state.connection_id).toBe(connectionId);- expect(state.channel_id).toBeTruthy();- expect(context.voiceStates[state.guild_id]?.[state.channel_id ?? '']?.[connectionId]).toBe(state);- expect(context.userVoiceStates[state.user_id]?.[state.guild_id]?.[connectionId]).toBe(state);- }-- for (const [userId, userStates] of Object.entries(context.userVoiceStates)) {- for (const [guildId, guildStates] of Object.entries(userStates)) {- expect(Object.keys(guildStates).length).toBeGreaterThan(0);- for (const [connectionId, state] of Object.entries(guildStates)) {- expect(state.user_id).toBe(userId);- expect(state.guild_id).toBe(guildId);- expect(state.connection_id).toBe(connectionId);- expect(context.connectionVoiceStates[connectionId]).toBe(state);- expect(context.voiceStates[guildId]?.[state.channel_id ?? '']?.[connectionId]).toBe(state);- }- }- }-}--function createRandom(seed: number): () => number {- let state = seed;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x100000000;- };-}--describe('VoiceGatewayStateMachine', () => {- it('moves a connection across channels and guilds without leaving stale indexes', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({guild_id: 'ignored', channel_id: 'channel-1', connection_id: 'connection-1'}),- });- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({channel_id: 'channel-2', connection_id: 'connection-1'}),- });- expect(snapshot.context.voiceStates['guild-1']?.['channel-1']).toBeUndefined();- expectConnection(snapshot.context, 'connection-1', {- guild_id: 'guild-1',- channel_id: 'channel-2',- user_id: 'user-1',- });-- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-2',- voiceState: voiceState({channel_id: 'channel-3', connection_id: 'connection-1'}),- });- expectNoGuild(snapshot.context, 'guild-1');- expectConnection(snapshot.context, 'connection-1', {- guild_id: 'guild-2',- channel_id: 'channel-3',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('tracks multiple connections for one user and removes only the leaving connection', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-1', channel_id: 'channel-1'}),- });- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-2', channel_id: 'channel-2'}),- });-- expect(Object.keys(snapshot.context.userVoiceStates['user-1']?.['guild-1'] ?? {})).toEqual([- 'connection-1',- 'connection-2',- ]);-- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-1', channel_id: null}),- });- expect(snapshot.context.connectionVoiceStates['connection-1']).toBeUndefined();- expectConnection(snapshot.context, 'connection-2', {- guild_id: 'guild-1',- channel_id: 'channel-2',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('replaces stale same-session connections for one user without removing other sessions', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-old', session_id: 'session-a', channel_id: 'channel-1'}),- });- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-other', session_id: 'session-b', channel_id: 'channel-1'}),- });- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-new', session_id: 'session-a', channel_id: 'channel-1'}),- });-- expect(snapshot.context.connectionVoiceStates['connection-old']).toBeUndefined();- expectConnection(snapshot.context, 'connection-new', {- guild_id: 'guild-1',- channel_id: 'channel-1',- user_id: 'user-1',- });- expectConnection(snapshot.context, 'connection-other', {- guild_id: 'guild-1',- channel_id: 'channel-1',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('keeps same-session connections in different channels', () => {- const snapshot = transition(createVoiceGatewayStateSnapshot(), {- type: 'guild.create',- guild: guild('guild-1', [- voiceState({connection_id: 'connection-a', session_id: 'session-a', channel_id: 'channel-1'}),- voiceState({connection_id: 'connection-b', session_id: 'session-a', channel_id: 'channel-2'}),- ]),- });-- expectConnection(snapshot.context, 'connection-a', {- guild_id: 'guild-1',- channel_id: 'channel-1',- user_id: 'user-1',- });- expectConnection(snapshot.context, 'connection-b', {- guild_id: 'guild-1',- channel_id: 'channel-2',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('deletes all user connections in a guild', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [- guild('guild-1', [- voiceState({connection_id: 'connection-1', user_id: 'user-1', channel_id: 'channel-1'}),- voiceState({connection_id: 'connection-2', user_id: 'user-1', channel_id: 'channel-2'}),- voiceState({connection_id: 'connection-3', user_id: 'user-2', channel_id: 'channel-2'}),- ]),- ],- });- snapshot = transition(snapshot, {type: 'voiceState.delete', guildId: 'guild-1', userId: 'user-1'});- expect(snapshot.context.connectionVoiceStates['connection-1']).toBeUndefined();- expect(snapshot.context.connectionVoiceStates['connection-2']).toBeUndefined();- expectConnection(snapshot.context, 'connection-3', {- guild_id: 'guild-1',- channel_id: 'channel-2',- user_id: 'user-2',- });- expectProjectionConsistent(snapshot.context);- });-- it('ignores updates and snapshots with missing connection IDs', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: {...voiceState(), connection_id: undefined} as unknown as VoiceState,- });- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [guild('guild-1', [{...voiceState(), connection_id: ''}])],- });- expect(snapshot.context).toEqual({- voiceStates: {},- userVoiceStates: {},- connectionVoiceStates: {},- });- });-- it('normalizes missing viewer stream keys on stored voice states', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({- connection_id: 'connection-1',- viewer_stream_keys: undefined,- }),- });- expect(snapshot.context.connectionVoiceStates['connection-1']?.viewer_stream_keys).toEqual([]);-- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({- connection_id: 'connection-1',- viewer_stream_keys: ['stream-a', '', 'stream-a', 'stream-b'],- }),- });- expect(snapshot.context.connectionVoiceStates['connection-1']?.viewer_stream_keys).toEqual([- 'stream-a',- 'stream-b',- ]);- expect(snapshot.context.voiceStates['guild-1']?.['channel-1']?.['connection-1']?.viewer_stream_keys).toEqual([- 'stream-a',- 'stream-b',- ]);- expectProjectionConsistent(snapshot.context);- });-- it('replaces stale guild-create state and removes duplicate connections from old guilds', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [- guild('guild-1', [voiceState({connection_id: 'old-connection', channel_id: 'old-channel'})]),- guild('guild-2', [voiceState({connection_id: 'shared-connection', channel_id: 'other-channel'})]),- ],- });-- snapshot = transition(snapshot, {- type: 'guild.create',- guild: guild('guild-1', [- voiceState({connection_id: 'new-connection', channel_id: 'new-channel'}),- voiceState({connection_id: 'shared-connection', channel_id: 'new-channel'}),- ]),- });-- expect(snapshot.context.connectionVoiceStates['old-connection']).toBeUndefined();- expect(snapshot.context.voiceStates['guild-1']?.['old-channel']).toBeUndefined();- expect(snapshot.context.voiceStates['guild-2']?.['other-channel']?.['shared-connection']).toBeUndefined();- expectConnection(snapshot.context, 'new-connection', {- guild_id: 'guild-1',- channel_id: 'new-channel',- user_id: 'user-1',- });- expectConnection(snapshot.context, 'shared-connection', {- guild_id: 'guild-1',- channel_id: 'new-channel',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('purges all indexes for guild delete', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [- guild('guild-1', [voiceState({connection_id: 'connection-1', channel_id: 'channel-1'})]),- guild('guild-2', [- voiceState({connection_id: 'connection-2', user_id: 'user-1', channel_id: 'channel-1'}),- voiceState({connection_id: 'connection-3', user_id: 'user-2', channel_id: 'channel-2'}),- ]),- ],- });- snapshot = transition(snapshot, {type: 'guild.delete', guildId: 'guild-2'});- expectNoGuild(snapshot.context, 'guild-2');- expectConnection(snapshot.context, 'connection-1', {- guild_id: 'guild-1',- channel_id: 'channel-1',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('applies duplicate updates idempotently', () => {- let snapshot = createVoiceGatewayStateSnapshot();- const update: VoiceGatewayStateEvent = {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'connection-1', channel_id: 'channel-1'}),- };- snapshot = transition(snapshot, update);- const once = snapshot.context;- snapshot = transition(snapshot, update);- expect(snapshot.context).toEqual(once);- expectProjectionConsistent(snapshot.context);- });-- it('removes one connection from all indexes without waiting for a full gateway refresh', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [- guild('guild-1', [- voiceState({connection_id: 'stale-connection', channel_id: 'channel-1'}),- voiceState({connection_id: 'active-connection', channel_id: 'channel-1'}),- ]),- ],- });- snapshot = transition(snapshot, {type: 'voiceState.removeConnection', connectionId: 'stale-connection'});-- expect(snapshot.context.connectionVoiceStates['stale-connection']).toBeUndefined();- expect(snapshot.context.voiceStates['guild-1']?.['channel-1']?.['stale-connection']).toBeUndefined();- expect(snapshot.context.userVoiceStates['user-1']?.['guild-1']?.['stale-connection']).toBeUndefined();- expectConnection(snapshot.context, 'active-connection', {- guild_id: 'guild-1',- channel_id: 'channel-1',- user_id: 'user-1',- });- expectProjectionConsistent(snapshot.context);- });-- it('connection-open snapshots replace all prior state', () => {- let snapshot = createVoiceGatewayStateSnapshot();- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: 'guild-1',- voiceState: voiceState({connection_id: 'stale-connection'}),- });- snapshot = transition(snapshot, {- type: 'connection.open',- guilds: [- guild('guild-2', [- voiceState({guild_id: 'ignored', user_id: 'user-2', connection_id: 'connection-2', channel_id: 'channel-2'}),- voiceState({user_id: 'user-3', connection_id: 'connection-3', channel_id: null}),- ]),- ],- });- expect(snapshot.context.connectionVoiceStates['stale-connection']).toBeUndefined();- expect(snapshot.context.connectionVoiceStates['connection-3']).toBeUndefined();- expectConnection(snapshot.context, 'connection-2', {- guild_id: 'guild-2',- channel_id: 'channel-2',- user_id: 'user-2',- });- expectProjectionConsistent(snapshot.context);- });-- it('keeps projection indexes consistent after long randomized sequences', () => {- let snapshot = createVoiceGatewayStateSnapshot();- const random = createRandom(0x5eed);- const guildIds = ['guild-1', 'guild-2', 'guild-3'];- const channelIds = ['channel-1', 'channel-2', 'channel-3', 'channel-4'];- const userIds = ['user-1', 'user-2', 'user-3', 'user-4'];- const connectionIds = ['connection-1', 'connection-2', 'connection-3', 'connection-4', 'connection-5'];- const pick = <T>(values: Array<T>): T => values[Math.floor(random() * values.length)];-- for (let i = 0; i < 500; i += 1) {- const op = Math.floor(random() * 6);- if (op === 0) {- const guildId = pick(guildIds);- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId,- voiceState: voiceState({- guild_id: 'payload-guild',- user_id: pick(userIds),- connection_id: pick(connectionIds),- channel_id: pick(channelIds),- self_mute: random() > 0.5,- self_deaf: random() > 0.5,- }),- });- } else if (op === 1) {- snapshot = transition(snapshot, {- type: 'voiceState.update',- guildId: pick(guildIds),- voiceState: voiceState({- user_id: pick(userIds),- connection_id: pick(connectionIds),- channel_id: null,- }),- });- } else if (op === 2) {- snapshot = transition(snapshot, {- type: 'voiceState.delete',- guildId: pick(guildIds),- userId: pick(userIds),- });- } else if (op === 3) {- snapshot = transition(snapshot, {type: 'guild.delete', guildId: pick(guildIds)});- } else if (op === 4) {- const guildId = pick(guildIds);- const count = Math.floor(random() * 4);- const voiceStates = Array.from({length: count}, () =>- voiceState({- guild_id: 'payload-guild',- user_id: pick(userIds),- connection_id: pick(connectionIds),- channel_id: random() > 0.2 ? pick(channelIds) : null,- }),- );- snapshot = transition(snapshot, {type: 'guild.create', guild: guild(guildId, voiceStates)});- } else {- const readyGuilds = guildIds.map((guildId) => {- const count = Math.floor(random() * 3);- return guild(- guildId,- Array.from({length: count}, () =>- voiceState({- guild_id: 'payload-guild',- user_id: pick(userIds),- connection_id: pick(connectionIds),- channel_id: random() > 0.2 ? pick(channelIds) : null,- }),- ),- );- });- snapshot = transition(snapshot, {type: 'connection.open', guilds: readyGuilds});- }-- expectProjectionConsistent(snapshot.context);- }- });-});diff --git a/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.ts b/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.tsdeleted file mode 100644index 31a20d609..000000000--- a/fluxer_app/src/features/voice/engine/VoiceLocalSpeakingGate.test.ts+++ /dev/null@@ -1,30 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- isLocalSpeakingSuppressed,- type LocalSpeakingSuppressionInput,-} from '@app/features/voice/engine/VoiceLocalSpeakingGate';-import {describe, expect, it} from 'vitest';--function input(overrides: Partial<LocalSpeakingSuppressionInput>): LocalSpeakingSuppressionInput {- return {- selfDeaf: false,- effectiveSelfMute: false,- hasMicrophonePublication: true,- microphonePublicationMuted: false,- ...overrides,- };-}--describe('isLocalSpeakingSuppressed', () => {- it('lets the measured outgoing audio decide for a live, unmuted microphone', () => {- expect(isLocalSpeakingSuppressed(input({}))).toBe(false);- });-- it('suppresses the indicator whenever nothing is sent', () => {- expect(isLocalSpeakingSuppressed(input({effectiveSelfMute: true}))).toBe(true);- expect(isLocalSpeakingSuppressed(input({selfDeaf: true}))).toBe(true);- expect(isLocalSpeakingSuppressed(input({hasMicrophonePublication: false}))).toBe(true);- expect(isLocalSpeakingSuppressed(input({microphonePublicationMuted: true}))).toBe(true);- });-});diff --git a/fluxer_app/src/features/voice/engine/VoiceMediaGraphSimulation.test.ts b/fluxer_app/src/features/voice/engine/VoiceMediaGraphSimulation.test.tsdeleted file mode 100644index bef574726..000000000--- a/fluxer_app/src/features/voice/engine/VoiceMediaGraphSimulation.test.ts+++ /dev/null@@ -1,659 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- createVoiceMediaGraphSnapshot,- selectVoiceMediaGraphSubscriptionEntry,- transitionVoiceMediaGraph,- type VoiceMediaGraphEvent,- type VoiceMediaGraphSnapshot,- type VoiceMediaGraphStatsTrackObservation,- type VoiceMediaGraphSubscriptionObservedElement,- type VoiceMediaGraphSubscriptionTarget,- voiceMediaGraphPublicationMissingDeadlineKey,- voiceMediaGraphWatchAttemptDeadlineKey,-} from '@app/features/voice/engine/VoiceMediaGraph';-import {checkVoiceMediaGraphInvariants} from '@app/features/voice/engine/VoiceMediaGraphInvariants';-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 SIMULATION_SEEDS: ReadonlyArray<number> = Array.from({length: 20}, (_, index) => 1 + index * 7919);-const SIMULATION_STEP_COUNT = 1000;-const SIMULATION_EPOCH_MS = 1_750_000_000_000;-const SIMULATION_STEP_ADVANCE_MS_MAX = 500;-const SIMULATION_COMMAND_DRAIN_THRESHOLD = 256;-const SIMULATION_GATE_RETRY_LIMIT = 8;-const SIMULATION_QUALITIES = ['low', 'medium', 'high'] as const;-const SIMULATION_CONTEXTS = ['focused', 'carousel', 'hidden'] as const;-const SIMULATION_STATS_CONNECTION_IDS = ['stats-conn-0', 'stats-conn-1', 'stats-conn-2'] as const;-const SIMULATION_OBSERVED_ELEMENTS: ReadonlyArray<VoiceMediaGraphSubscriptionObservedElement> = [- null,- {simulationElementId: 0},- {simulationElementId: 1},-];-const SIMULATION_SOURCES = [VoiceTrackSource.ScreenShare, VoiceTrackSource.Camera] as const;--interface SimulationParticipant {- connectionId: string;- participantIdentity: string;- streamKey: string;-}--const SIMULATION_PARTICIPANTS: ReadonlyArray<SimulationParticipant> = [0, 1, 2].map((index) => ({- connectionId: `conn-${index}`,- participantIdentity: `user_${index}_conn-${index}`,- streamKey: `dm:channel-sim:conn-${index}`,-}));--interface SimulationRng {- int(maxExclusive: number): number;- pick<T>(items: ReadonlyArray<T>): T;- bool(): boolean;-}--function createSimulationRng(seed: number): SimulationRng {- let state = seed >>> 0;- if (state === 0) state = 0x9e3779b9;- const nextU32 = (): number => {- state = (Math.imul(state, 1664525) + 1013904223) >>> 0;- return state;- };- const int = (maxExclusive: number): number => Math.floor((nextU32() / 0x1_0000_0000) * maxExclusive);- return {- int,- pick: <T>(items: ReadonlyArray<T>): T => items[int(items.length)] as T,- bool: (): boolean => nextU32() >= 0x8000_0000,- };-}--type SimulationEventBuilder = (- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-) => VoiceMediaGraphEvent | null;--function simulationEventGeneration(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- streamKey: string,-): number | undefined {- const current = snapshot.watchGenerationByStreamKey.get(streamKey) ?? 0;- switch (rng.int(4)) {- case 0:- return undefined;- case 1:- return current > 0 ? current - 1 : current;- default:- return current;- }-}--function simulationTriState(rng: SimulationRng): boolean | undefined {- switch (rng.int(3)) {- case 0:- return true;- case 1:- return false;- default:- return undefined;- }-}--function isSimulationRendering(snapshot: VoiceMediaGraphSnapshot, participant: SimulationParticipant): boolean {- const attempt = snapshot.attemptsByStreamKey.get(participant.streamKey);- if (!attempt) return false;- if (!attempt.hasRenderedVideoFrame) return false;- const generation = snapshot.watchGenerationByStreamKey.get(participant.streamKey) ?? 0;- if (attempt.generation !== generation) return false;- const entry = selectVoiceMediaGraphSubscriptionEntry(- snapshot,- participant.participantIdentity,- VoiceTrackSource.ScreenShare,- );- if (!entry) return false;- return entry.firstFrame.renderedAt !== null;-}--function canSimulationRenderFrame(snapshot: VoiceMediaGraphSnapshot, participant: SimulationParticipant): boolean {- const tileState = selectVoiceMediaGraphStreamTileState(snapshot, {- streamKey: participant.streamKey,- participantIdentity: participant.participantIdentity,- source: VoiceTrackSource.ScreenShare,- });- if (tileState === 'failed') return false;- const entry = selectVoiceMediaGraphSubscriptionEntry(- snapshot,- participant.participantIdentity,- VoiceTrackSource.ScreenShare,- );- if (!entry) return true;- if (!entry.publication.available) return false;- return entry.actual.lastError === null;-}--function buildSimulationWatchEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const streamKey = participant.streamKey;- switch (rng.int(4)) {- case 0:- return rng.bool() ? {type: 'watch.started', streamKey, at: nowMs} : {type: 'watch.started', streamKey};- case 1:- return {type: 'watch.stopped', streamKey};- case 2: {- const generation = simulationEventGeneration(rng, snapshot, streamKey);- return {- type: 'watch.attemptEnsured',- streamKey,- attemptKey: `attempt-${rng.int(6)}`,- startedAt: nowMs,- ...(generation === undefined ? {} : {generation}),- };- }- default: {- if (!canSimulationRenderFrame(snapshot, participant)) return null;- const attempt = snapshot.attemptsByStreamKey.get(streamKey);- const generation = simulationEventGeneration(rng, snapshot, streamKey);- return {- type: 'watch.renderedFrame',- streamKey,- attemptKey: attempt?.attemptKey ?? `attempt-${rng.int(6)}`,- renderedAt: nowMs,- ...(generation === undefined ? {} : {generation}),- };- }- }-}--function buildSimulationIntentEvent(- rng: SimulationRng,- _snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const key = participant.streamKey;- switch (rng.int(7)) {- case 0: {- const count = rng.int(SIMULATION_PARTICIPANTS.length + 1);- return {- type: 'watchIntent.replace',- keys: SIMULATION_PARTICIPANTS.slice(0, count).map((candidate) => candidate.streamKey),- };- }- case 1:- return {type: 'watchIntent.add', key};- case 2:- return {type: 'watchIntent.remove', key};- case 3:- return {type: 'watchIntent.removeMany', keys: [key, rng.pick(SIMULATION_PARTICIPANTS).streamKey]};- case 4:- return rng.bool() ? {type: 'watchIntent.deferRemove', key, at: nowMs} : {type: 'watchIntent.deferRemove', key};- case 5:- return {type: 'watchIntent.cancelDeferredRemove', key};- default:- return {type: 'watchIntent.reset'};- }-}--function buildSimulationFailureEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- switch (rng.int(4)) {- case 0: {- if (isSimulationRendering(snapshot, participant)) return null;- const generation = simulationEventGeneration(rng, snapshot, participant.streamKey);- return {- type: 'failure.reported',- failure: {- code: -2202,- reason: 'screen-share-watch-failed',- reportedAt: nowMs,- streamKey: participant.streamKey,- participantIdentity: participant.participantIdentity,- source: VoiceTrackSource.ScreenShare,- },- ...(generation === undefined ? {} : {generation}),- };- }- case 1:- return {- type: 'failure.reported',- failure: {- code: -2210,- reason: 'camera-subscribe-failed',- reportedAt: nowMs,- participantIdentity: participant.participantIdentity,- source: VoiceTrackSource.Camera,- },- };- case 2:- return {- type: 'failure.cleared',- target: rng.bool()- ? {streamKey: participant.streamKey}- : {participantIdentity: participant.participantIdentity, source: rng.pick(SIMULATION_SOURCES)},- };- default:- return {type: 'failureWatch.clearAll'};- }-}--function buildSimulationSubscriptionShapeEvent(- rng: SimulationRng,- target: VoiceMediaGraphSubscriptionTarget,- hasPublication: boolean,-): VoiceMediaGraphEvent {- switch (rng.int(4)) {- case 0: {- const context = rng.bool() ? rng.pick(SIMULATION_CONTEXTS) : undefined;- const quality = rng.bool() ? rng.pick(SIMULATION_QUALITIES) : undefined;- return {- type: 'subscription.subscribe',- ...target,- hasPublication,- observedElement: rng.pick(SIMULATION_OBSERVED_ELEMENTS),- ...(context === undefined ? {} : {context}),- ...(quality === undefined ? {} : {quality}),- };- }- case 1:- return {type: 'subscription.unsubscribe', ...target};- case 2:- return {- type: 'subscription.replaceObserver',- ...target,- hasPublication,- observedElement: rng.pick(SIMULATION_OBSERVED_ELEMENTS),- };- default:- return {type: 'subscription.intersection', ...target, hasPublication, isIntersecting: rng.bool()};- }-}--function buildSimulationSubscriptionTuningEvent(- rng: SimulationRng,- target: VoiceMediaGraphSubscriptionTarget,- hasPublication: boolean,-): VoiceMediaGraphEvent {- switch (rng.int(8)) {- case 0:- return {type: 'subscription.setEnabled', ...target, hasPublication, enabled: rng.bool()};- case 1:- return {type: 'subscription.setQuality', ...target, hasPublication, quality: rng.pick(SIMULATION_QUALITIES)};- case 2:- return {type: 'subscription.setContext', ...target, hasPublication, context: rng.pick(SIMULATION_CONTEXTS)};- case 3:- return {- type: 'subscription.reattachAfterPublish',- ...target,- hasPublication,- forceResubscribe: rng.bool(),- };- case 4:- return {type: 'subscription.publicationMissing', ...target};- case 5:- return rng.bool() ? {type: 'subscription.cleanup'} : {type: 'subscription.cleanup', source: target.source};- case 6:- return {type: 'subscription.reconcile'};- default:- return {type: 'subscription.clearCommands'};- }-}--function buildSimulationSubscriptionEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- _nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const source = rng.pick(SIMULATION_SOURCES);- const entry = selectVoiceMediaGraphSubscriptionEntry(snapshot, participant.participantIdentity, source);- const hasPublication = entry?.publication.available ?? false;- const target: VoiceMediaGraphSubscriptionTarget = {participantIdentity: participant.participantIdentity, source};- if (rng.bool()) return buildSimulationSubscriptionShapeEvent(rng, target, hasPublication);- return buildSimulationSubscriptionTuningEvent(rng, target, hasPublication);-}--function buildSimulationFeedbackEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const source = rng.pick(SIMULATION_SOURCES);- const entry = selectVoiceMediaGraphSubscriptionEntry(snapshot, participant.participantIdentity, source);- if (!entry) return null;- const generation = simulationEventGeneration(rng, snapshot, participant.streamKey);- if (rng.int(3) === 0) {- if (source === VoiceTrackSource.ScreenShare && isSimulationRendering(snapshot, participant)) return null;- return {- type: 'subscription.commandFailed',- participantIdentity: participant.participantIdentity,- source,- at: nowMs,- code: -2302,- reason: 'simulated-command-failure',- ...(source === VoiceTrackSource.ScreenShare ? {streamKey: participant.streamKey} : {}),- ...(generation === undefined ? {} : {generation}),- };- }- const subscribed = simulationTriState(rng);- const enabled = simulationTriState(rng);- const quality = rng.bool() ? rng.pick(SIMULATION_QUALITIES) : undefined;- return {- type: 'subscription.actualChanged',- participantIdentity: participant.participantIdentity,- source,- at: nowMs,- ...(subscribed === undefined ? {} : {subscribed}),- ...(enabled === undefined ? {} : {enabled}),- ...(quality === undefined ? {} : {quality}),- ...(entry.publication.available && rng.bool() ? {trackSid: `TS_${rng.int(8)}`} : {}),- ...(rng.bool() ? {streamKey: participant.streamKey} : {}),- ...(generation === undefined ? {} : {generation}),- };-}--function buildSimulationPublicationEvent(- rng: SimulationRng,- _snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const source = rng.pick(SIMULATION_SOURCES);- if (rng.bool()) {- return {- type: 'publication.observed',- participantIdentity: participant.participantIdentity,- source,- trackSid: rng.bool() ? `TS_${rng.int(8)}` : null,- at: nowMs,- };- }- return {type: 'publication.lost', participantIdentity: participant.participantIdentity, source, at: nowMs};-}--function buildSimulationDeadlineEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const keys = [...snapshot.deadlinesByKey.keys()];- if (rng.bool() && keys.length > 0) {- return {type: 'time.deadlineFired', key: rng.pick(keys), at: nowMs};- }- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const key = rng.bool()- ? voiceMediaGraphWatchAttemptDeadlineKey(participant.streamKey)- : voiceMediaGraphPublicationMissingDeadlineKey(`${participant.participantIdentity}:screen_share`);- return {type: 'time.deadlineFired', key, at: nowMs};-}--function buildSimulationStatsObservation(rng: SimulationRng): VoiceMediaGraphStatsTrackObservation {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const variant = rng.int(3);- const dimension = rng.pick([null, 640, 1280, 1920]);- return {- trackSid: variant === 0 ? `TR_${rng.int(24)}` : null,- trackIdentifier: variant === 1 ? `TI_${rng.int(24)}` : null,- mediaSourceId: null,- mid: rng.bool() ? `${rng.int(8)}` : null,- rid: null,- ssrc: rng.bool() ? 1000 + rng.int(50) : null,- participantIdentity: variant === 2 ? participant.participantIdentity : null,- participantSid: null,- source: variant === 2 ? VoiceTrackSource.ScreenShare : null,- direction: rng.bool() ? 'send' : 'recv',- kind: rng.bool() ? 'audio' : 'video',- fps: rng.pick([null, 0, 30, 60]),- width: dimension,- height: dimension === null ? null : Math.floor((dimension * 9) / 16),- sourceFps: rng.pick([null, 30, 60]),- sourceWidth: rng.pick([null, 1920]),- sourceHeight: rng.pick([null, 1080]),- };-}--function buildSimulationStatsEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent {- if (rng.int(4) === 0) {- return {- type: 'stats.connectionChanged',- connectionId: rng.bool() ? rng.pick(SIMULATION_STATS_CONNECTION_IDS) : null,- };- }- const connectionId = rng.bool()- ? (snapshot.statsConnectionId ?? rng.pick(SIMULATION_STATS_CONNECTION_IDS))- : rng.pick(SIMULATION_STATS_CONNECTION_IDS);- const trackCount = 1 + rng.int(3);- const tracks = Array.from({length: trackCount}, () => buildSimulationStatsObservation(rng));- return {- type: 'stats.observed',- at: nowMs,- connectionId,- platform: rng.bool() ? 'native' : 'web',- tracks,- };-}--function buildSimulationResetEvent(rng: SimulationRng): VoiceMediaGraphEvent | null {- if (rng.int(8) !== 0) return null;- return {type: 'clear.all'};-}--function buildSimulationScenarioEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- nowMs: number,-): VoiceMediaGraphEvent | null {- const participant = rng.pick(SIMULATION_PARTICIPANTS);- const participantIdentity = participant.participantIdentity;- const streamKey = participant.streamKey;- const source = VoiceTrackSource.ScreenShare;- const entry = selectVoiceMediaGraphSubscriptionEntry(snapshot, participantIdentity, source);- if (!entry) {- return {- type: 'subscription.subscribe',- participantIdentity,- source,- hasPublication: false,- observedElement: rng.pick(SIMULATION_OBSERVED_ELEMENTS),- context: 'focused',- };- }- if (!entry.publication.available) {- return {type: 'publication.observed', participantIdentity, source, trackSid: `TS_${rng.int(8)}`, at: nowMs};- }- if ((snapshot.watchGenerationByStreamKey.get(streamKey) ?? 0) === 0) {- return {type: 'watch.started', streamKey, at: nowMs};- }- const attempt = snapshot.attemptsByStreamKey.get(streamKey);- if (!attempt) {- return {type: 'watch.attemptEnsured', streamKey, attemptKey: `attempt-${rng.int(6)}`, startedAt: nowMs};- }- if (entry.actual.subscribed !== true) {- return {- type: 'subscription.actualChanged',- participantIdentity,- source,- at: nowMs,- subscribed: true,- enabled: true,- };- }- if (attempt.hasRenderedVideoFrame && entry.firstFrame.renderedAt !== null) return null;- if (!canSimulationRenderFrame(snapshot, participant)) return null;- return {type: 'watch.renderedFrame', streamKey, attemptKey: attempt.attemptKey, renderedAt: nowMs};-}--const SIMULATION_WEIGHTED_BUILDERS: ReadonlyArray<SimulationEventBuilder> = [- buildSimulationWatchEvent,- buildSimulationIntentEvent,- buildSimulationFailureEvent,- buildSimulationSubscriptionEvent,- buildSimulationFeedbackEvent,- buildSimulationPublicationEvent,- buildSimulationDeadlineEvent,- buildSimulationStatsEvent,- buildSimulationScenarioEvent,-];--function buildSimulationBuilderPool(rng: SimulationRng): Array<SimulationEventBuilder> {- const pool: Array<SimulationEventBuilder> = [];- for (const builder of SIMULATION_WEIGHTED_BUILDERS) {- const weight = 1 + rng.int(4);- for (let copy = 0; copy < weight; copy += 1) pool.push(builder);- }- pool.push(buildSimulationResetEvent);- return pool;-}--function nextSimulationEvent(- rng: SimulationRng,- snapshot: VoiceMediaGraphSnapshot,- pool: ReadonlyArray<SimulationEventBuilder>,- nowMs: number,-): VoiceMediaGraphEvent {- for (let attempt = 0; attempt < SIMULATION_GATE_RETRY_LIMIT; attempt += 1) {- const event = rng.pick(pool)(rng, snapshot, nowMs);- if (event) return event;- }- return buildSimulationStatsEvent(rng, snapshot, nowMs);-}--interface SimulationStepContext {- seed: number;- step: number;- eventType: string;-}--function simulationStepMessage(context: SimulationStepContext): string {- return `seed=${context.seed} step=${context.step} event=${context.eventType}`;-}--function assertSimulationActualSubscribed(snapshot: VoiceMediaGraphSnapshot, message: string): void {- for (const [key, entry] of snapshot.subscriptionsByKey) {- if (entry.actual.subscribed !== true) continue;- expect(entry.subscribed, `${message}: ${key} actually subscribed without desired entry`).toBe(true);- }-}--function assertSimulationDeferredSubset(snapshot: VoiceMediaGraphSnapshot, message: string): void {- for (const key of snapshot.watchIntent.deferredStopKeys) {- expect(- snapshot.watchIntent.viewerStreamKeys.includes(key),- `${message}: deferred stop key ${key} is not a viewer stream key`,- ).toBe(true);- }-}--function assertSimulationFailureRenderOrdering(snapshot: VoiceMediaGraphSnapshot, message: string): void {- for (const failure of snapshot.failuresByKey.values()) {- if (!failure.streamKey) continue;- const participant = SIMULATION_PARTICIPANTS.find((candidate) => candidate.streamKey === failure.streamKey);- if (!participant) continue;- const currentGeneration = snapshot.watchGenerationByStreamKey.get(failure.streamKey) ?? 0;- if ((failure.generation ?? currentGeneration) !== currentGeneration) continue;- const entry = selectVoiceMediaGraphSubscriptionEntry(- snapshot,- participant.participantIdentity,- VoiceTrackSource.ScreenShare,- );- if (!entry) continue;- if (entry.firstFrame.renderedAt === null) continue;- expect(- entry.firstFrame.renderedAt <= failure.reportedAt,- `${message}: stream ${failure.streamKey} rendered a frame after its current-generation failure`,- ).toBe(true);- }-}--function selectSimulationTileState(- snapshot: VoiceMediaGraphSnapshot,- participant: SimulationParticipant,- source: VoiceTrackSource,- message: string,-): VoiceMediaGraphStreamTileState {- try {- return selectVoiceMediaGraphStreamTileState(snapshot, {- streamKey: source === VoiceTrackSource.ScreenShare ? participant.streamKey : null,- participantIdentity: participant.participantIdentity,- source,- });- } catch (error) {- throw new Error(`${message}: tile selector threw for ${participant.participantIdentity}:${source}: ${error}`);- }-}--function assertSimulationTileStates(snapshot: VoiceMediaGraphSnapshot, message: string): void {- for (const participant of SIMULATION_PARTICIPANTS) {- for (const source of SIMULATION_SOURCES) {- const state = selectSimulationTileState(snapshot, participant, source, message);- if (source !== VoiceTrackSource.ScreenShare) continue;- if (!isSimulationRendering(snapshot, participant)) continue;- expect(- state,- `${message}: tile for ${participant.streamKey} must render while current generation has a frame`,- ).toBe('rendering');- }- }-}--function assertSimulationStats(snapshot: VoiceMediaGraphSnapshot, message: string): void {- if (snapshot.statsConnectionId === null) {- expect(snapshot.statsByTrackKey.size, `${message}: stats entries without a connection`).toBe(0);- return;- }- for (const [key, entry] of snapshot.statsByTrackKey) {- expect(entry.connectionId, `${message}: stats entry ${key} for cleared connection`).toBe(- snapshot.statsConnectionId,- );- }-}--function assertSimulationStep(snapshot: VoiceMediaGraphSnapshot, context: SimulationStepContext): void {- const message = simulationStepMessage(context);- expect(checkVoiceMediaGraphInvariants(snapshot), `${message}: invariant violations`).toEqual([]);- assertSimulationActualSubscribed(snapshot, message);- assertSimulationDeferredSubset(snapshot, message);- assertSimulationFailureRenderOrdering(snapshot, message);- assertSimulationTileStates(snapshot, message);- assertSimulationStats(snapshot, message);-}--function runSimulation(seed: number): VoiceMediaGraphSnapshot {- const rng = createSimulationRng(seed);- const pool = buildSimulationBuilderPool(rng);- let snapshot = createVoiceMediaGraphSnapshot();- let nowMs = SIMULATION_EPOCH_MS;- for (let step = 0; step < SIMULATION_STEP_COUNT; step += 1) {- nowMs += 1 + rng.int(SIMULATION_STEP_ADVANCE_MS_MAX);- const event = nextSimulationEvent(rng, snapshot, pool, nowMs);- snapshot = transitionVoiceMediaGraph(snapshot, event);- if (snapshot.subscriptionCommands.length > SIMULATION_COMMAND_DRAIN_THRESHOLD) {- snapshot = transitionVoiceMediaGraph(snapshot, {type: 'subscription.clearCommands'});- }- assertSimulationStep(snapshot, {seed, step, eventType: event.type});- }- return snapshot;-}--describe('VoiceMediaGraphSimulation', () => {- for (const seed of SIMULATION_SEEDS) {- it(`maintains every invariant across ${SIMULATION_STEP_COUNT} random steps for seed ${seed}`, () => {- runSimulation(seed);- });- }-});diff --git a/fluxer_app/src/features/voice/engine/VoiceSpeakingDetection.test.ts b/fluxer_app/src/features/voice/engine/VoiceSpeakingDetection.test.tsdeleted file mode 100644index 5ff601ca5..000000000--- a/fluxer_app/src/features/voice/engine/VoiceSpeakingDetection.test.ts+++ /dev/null@@ -1,257 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import vm from 'node:vm';-import gateWorkletSource from '@app/features/voice/utils/voiceGateProcessor.worklet.js?raw';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--const SAMPLE_RATE = 48000;-const QUANTUM = 128;-const TICK_SAMPLES = SAMPLE_RATE / 20;-const ANALYSER_WINDOW = 512;--const audio = vi.hoisted(() => ({window: new Float32Array(512), state: 'running'}));--vi.mock('@app/features/voice/state/VoiceSettings', () => ({default: {getVadThreshold: () => 50}}));--vi.mock('@app/features/voice/engine/VoiceSharedAudioContext', () => ({- getSharedVoiceAudioContext: () => ({- get state() {- return audio.state;- },- createMediaStreamSource: () => ({connect: () => undefined, disconnect: () => undefined}),- createAnalyser: () => ({- fftSize: 0,- smoothingTimeConstant: 0,- disconnect: () => undefined,- getFloatTimeDomainData: (target: Float32Array) => target.set(audio.window),- }),- }),-}));--const {LOCAL_AUTO_MIN_RMS, LOCAL_MAX_RMS, SPEAKING_LOCAL_RELEASE_MS, getLocalSpeakingThresholdRms} = await import(- '@app/features/voice/engine/VoiceSpeakingThreshold'-);-const {computeTimeDomainRms, readSpeakingThresholdRms, VoiceSpeakingMeter} = await import(- '@app/features/voice/engine/VoiceSpeakingDetection'-);-const {createVoiceRemoteSpeakingSnapshot, transitionVoiceRemoteSpeakingSnapshot, clearVoiceRemoteSpeakingCommands} =- await import('@app/features/voice/engine/VoiceParticipantStateMachine');--interface GateProcessor {- speaking: boolean;- process(inputs: Array<Array<Float32Array>>, outputs: Array<Array<Float32Array>>): boolean;-}--type GateConstructor = new (options: {processorOptions: Record<string, unknown>}) => GateProcessor;--interface GateMode {- apply: boolean;- auto: boolean;- slider?: number;-}--function loadGate(mode: GateMode): GateProcessor {- let Processor: GateConstructor | null = null;- const sandbox = vm.createContext({- sampleRate: SAMPLE_RATE,- currentTime: 0,- AudioWorkletProcessor: class {- port = {postMessage: () => undefined, onmessage: null};- },- registerProcessor: (_name: string, processor: GateConstructor) => {- Processor = processor;- },- });- vm.runInContext(gateWorkletSource, sandbox);- if (!Processor) throw new Error('voice gate worklet did not register');- return new (Processor as GateConstructor)({- processorOptions: {- apply: mode.apply,- auto: mode.auto,- manualThresholdRms: getLocalSpeakingThresholdRms(mode.slider ?? 50),- channelCount: 1,- minRms: LOCAL_AUTO_MIN_RMS,- maxRms: LOCAL_MAX_RMS,- releaseMs: SPEAKING_LOCAL_RELEASE_MS,- },- });-}--function createRandom(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state + 0x6d2b79f5) >>> 0;- let value = state;- value = Math.imul(value ^ (value >>> 15), value | 1);- value ^= value + Math.imul(value ^ (value >>> 7), value | 61);- return ((value ^ (value >>> 14)) >>> 0) / 4294967296;- };-}--const UNIFORM_RMS_TO_PEAK = Math.sqrt(3);--function noise(random: () => number, rms: number): number {- return (random() * 2 - 1) * rms * UNIFORM_RMS_TO_PEAK;-}--function syllable(index: number, periodSamples: number, onSamples: number): boolean {- return index % periodSamples < onSamples;-}--function tone(index: number, rms: number): number {- return Math.sin((2 * Math.PI * 180 * index) / SAMPLE_RATE) * rms * Math.SQRT2;-}--interface Timeline {- gateSpeaking: boolean;- localSpeaking: Array<boolean>;- remoteSpeaking: Array<boolean>;-}--function runPipeline(mode: GateMode, seconds: number, signal: (index: number) => number, transmit = true): Timeline {- const gate = loadGate(mode);- const track = {readyState: 'live'} as MediaStreamTrack;- const meter = new VoiceSpeakingMeter(- () => track,- () => undefined,- );- let remote = transitionVoiceRemoteSpeakingSnapshot(createVoiceRemoteSpeakingSnapshot(), {- type: 'remote.attach',- identity: 'peer',- track: 'track',- });- const history = new Float32Array(ANALYSER_WINDOW);- const timeline: Timeline = {gateSpeaking: false, localSpeaking: [], remoteSpeaking: []};- const seedEnd = 0.3 * SAMPLE_RATE;- const total = Math.floor(seconds * SAMPLE_RATE);- let nextTick = TICK_SAMPLES;- for (let start = 0; start < total; start += QUANTUM) {- const input = new Float32Array(QUANTUM);- for (let offset = 0; offset < QUANTUM; offset++) input[offset] = signal(start + offset);- const output = new Float32Array(QUANTUM);- gate.process([[input]], [[output]]);- if (start >= seedEnd && gate.speaking) timeline.gateSpeaking = true;- history.copyWithin(0, QUANTUM);- history.set(transmit ? output : new Float32Array(QUANTUM), ANALYSER_WINDOW - QUANTUM);- const end = start + QUANTUM;- if (end < nextTick) continue;- nextTick += TICK_SAMPLES;- const nowMs = (end / SAMPLE_RATE) * 1000;- audio.window.set(history);- meter.tick(nowMs);- remote = transitionVoiceRemoteSpeakingSnapshot(remote, {- type: 'remote.tick',- identity: 'peer',- rms: computeTimeDomainRms(history),- threshold: readSpeakingThresholdRms(),- nowMs,- });- remote = clearVoiceRemoteSpeakingCommands(remote);- timeline.localSpeaking.push(meter.speaking);- timeline.remoteSpeaking.push(remote.context.analysers.get('peer')?.speaking ?? false);- }- meter.dispose();- return timeline;-}--const VAD_AUTO: GateMode = {apply: true, auto: true};-const VAD_MANUAL: GateMode = {apply: true, auto: false, slider: 50};-const VAD_MANUAL_SENSITIVE: GateMode = {apply: true, auto: false, slider: 10};-const PUSH_TO_TALK: GateMode = {apply: false, auto: true};-const MODES: Array<[string, GateMode]> = [- ['voice activity with auto sensitivity', VAD_AUTO],- ['voice activity with a manual threshold', VAD_MANUAL],- ['voice activity with a sensitive manual threshold', VAD_MANUAL_SENSITIVE],- ['push to talk', PUSH_TO_TALK],-];--function suppressionResidue(seed: number): (index: number) => number {- const random = createRandom(seed);- return (index) => {- const click = syllable(index, 0.3 * SAMPLE_RATE, 0.02 * SAMPLE_RATE);- return noise(random, click ? 0.001 : 0.00003);- };-}--function hardwareMutedWhilePeersTalk(seed: number): (index: number) => number {- const random = createRandom(seed);- return (index) => {- if (index < SAMPLE_RATE) return 0;- const peerTalking = syllable(index, 0.25 * SAMPLE_RATE, 0.15 * SAMPLE_RATE);- return peerTalking ? tone(index, 0.00004) + noise(random, 0.00001) : 0;- };-}--function speechInRoomNoise(seed: number): (index: number) => number {- const random = createRandom(seed);- return (index) => {- const room = noise(random, 0.0003);- if (index < SAMPLE_RATE) return room;- return syllable(index, 0.2 * SAMPLE_RATE, 0.15 * SAMPLE_RATE) ? room + tone(index, 0.05) : room;- };-}--describe('local speaking indicator', () => {- beforeEach(() => {- vi.stubGlobal('MediaStream', class {});- audio.window.fill(0);- audio.state = 'running';- });-- afterEach(() => {- vi.unstubAllGlobals();- });-- it.each(MODES)('stays dark on noise left behind by noise suppression in %s', (_name, mode) => {- const timeline = runPipeline(mode, 3, suppressionResidue(1));- expect(timeline.localSpeaking).not.toContain(true);- expect(timeline.remoteSpeaking).not.toContain(true);- });-- it.each(MODES)('stays dark when a hardware-muted mic only carries peer bleed in %s', (_name, mode) => {- const timeline = runPipeline(mode, 4, hardwareMutedWhilePeersTalk(2));- expect(timeline.localSpeaking).not.toContain(true);- expect(timeline.remoteSpeaking).not.toContain(true);- });-- it.each(MODES)('lights for real speech in %s', (_name, mode) => {- const timeline = runPipeline(mode, 3, speechInRoomNoise(3));- expect(timeline.localSpeaking).toContain(true);- expect(timeline.localSpeaking.slice(0, 18)).not.toContain(true);- });-- it.each(MODES)('agrees tick for tick with how peers judge the same audio in %s', (_name, mode) => {- for (const signal of [suppressionResidue(4), hardwareMutedWhilePeersTalk(5), speechInRoomNoise(6)]) {- const timeline = runPipeline(mode, 3, signal);- expect(timeline.localSpeaking).toEqual(timeline.remoteSpeaking);- }- });-- it('never lights while the outgoing track is muted, even for loud speech', () => {- for (const [, mode] of MODES) {- const timeline = runPipeline(mode, 3, speechInRoomNoise(7), false);- expect(timeline.localSpeaking).not.toContain(true);- }- });-- it('keeps the transmit gate opening on those inaudible inputs, so the gate cannot drive the indicator', () => {- expect(runPipeline(VAD_AUTO, 3, suppressionResidue(1)).gateSpeaking).toBe(true);- expect(runPipeline(VAD_AUTO, 4, hardwareMutedWhilePeersTalk(2)).gateSpeaking).toBe(true);- });-- it('does not hold a stale reading while the analysing context is not running', () => {- const track = {readyState: 'live'} as MediaStreamTrack;- const meter = new VoiceSpeakingMeter(- () => track,- () => undefined,- );- audio.window.fill(0.1);- meter.tick(0);- meter.tick(50);- expect(meter.speaking).toBe(true);- audio.state = 'suspended';- for (let nowMs = 100; nowMs <= 400; nowMs += 50) meter.tick(nowMs);- expect(meter.speaking).toBe(false);- meter.dispose();- });-});diff --git a/fluxer_app/src/features/voice/engine/VoiceTrackPublicationUtils.test.ts b/fluxer_app/src/features/voice/engine/VoiceTrackPublicationUtils.test.tsdeleted file mode 100644index 00c7e3305..000000000--- a/fluxer_app/src/features/voice/engine/VoiceTrackPublicationUtils.test.ts+++ /dev/null@@ -1,72 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {EventEmitter} from 'node:events';-import {releaseCaptureWithRepublishedTrack} from '@app/features/voice/engine/VoiceTrackPublicationUtils';-import {type LocalParticipant, type LocalTrack, type LocalTrackPublication, ParticipantEvent} from 'livekit-client';-import {describe, expect, it, vi} from 'vitest';--function fakeMediaStreamTrack(): MediaStreamTrack {- return {readyState: 'live'} as MediaStreamTrack;-}--function fakeLocalTrack(mediaStreamTrack: MediaStreamTrack): LocalTrack {- return {mediaStreamTrack, stop: vi.fn()} as unknown as LocalTrack;-}--function fakeRoom(): {participant: LocalParticipant; unpublish(publication: LocalTrackPublication): void} {- const emitter = new EventEmitter();- return {- participant: emitter as unknown as LocalParticipant,- unpublish: (publication) => emitter.emit(ParticipantEvent.LocalTrackUnpublished, publication),- };-}--function republish(room: ReturnType<typeof fakeRoom>, sourceTrack: LocalTrack): LocalTrackPublication {- const publication = {track: fakeLocalTrack(sourceTrack.mediaStreamTrack)} as LocalTrackPublication;- releaseCaptureWithRepublishedTrack(room.participant, publication, sourceTrack);- return publication;-}--function stopTrack(track: MediaStreamTrack): void {- Object.assign(track, {readyState: 'ended'});-}--describe('releaseCaptureWithRepublishedTrack', () => {- it('stops the processed microphone capture when its hot-swapped publication is stopped on leave', () => {- const processedTrack = fakeMediaStreamTrack();- const microphone = fakeLocalTrack(processedTrack);- const newRoom = fakeRoom();- const publication = republish(newRoom, microphone);-- stopTrack(processedTrack);- newRoom.unpublish(publication);-- expect(microphone.stop).toHaveBeenCalledTimes(1);- });-- it('keeps the capture running when the publication is handed to another room without stopping', () => {- const processedTrack = fakeMediaStreamTrack();- const microphone = fakeLocalTrack(processedTrack);- const newRoom = fakeRoom();- const publication = republish(newRoom, microphone);-- newRoom.unpublish(publication);-- expect(microphone.stop).not.toHaveBeenCalled();- });-- it('stops the original capture after a second hot-swap republishes the wrapper track', () => {- const processedTrack = fakeMediaStreamTrack();- const microphone = fakeLocalTrack(processedTrack);- const secondRoom = fakeRoom();- const secondPublication = republish(secondRoom, microphone);- const thirdRoom = fakeRoom();- const thirdPublication = republish(thirdRoom, secondPublication.track!);-- secondRoom.unpublish(secondPublication);- stopTrack(processedTrack);- thirdRoom.unpublish(thirdPublication);-- expect(microphone.stop).toHaveBeenCalledTimes(1);- });-});diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAudioPreferencesSyncBinding.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAudioPreferencesSyncBinding.test.tsdeleted file mode 100644index eca5b1f7a..000000000--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppAudioPreferencesSyncBinding.test.ts+++ /dev/null@@ -1,63 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {Room} from 'livekit-client';-import {afterEach, 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: () => null,- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}),-}));--vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({default: {}}));--const {default: Keybind} = await import('@app/features/input/state/InputKeybind');-const {isVoiceActivityGateEnabled} = await import('@app/features/voice/utils/VoiceInputProcessor');-const {bindVoiceEngineV2AppAudioPreferencesSync} = await import(- '@app/features/voice/engine/v2/VoiceEngineV2AppAudioPreferencesSyncBinding'-);--function createAdapter() {- return {- requestMicrophoneRefresh: vi.fn(async () => {}),- configureVoiceInput: vi.fn(),- handleInputKeybindChange: vi.fn(),- applyAllLocalAudioPreferences: vi.fn(),- };-}--describe('voice engine v2 audio preferences sync binding', () => {- let dispose: (() => void) | null = null;-- afterEach(() => {- dispose?.();- dispose = null;- Keybind.setTransmitMode('voice_activity');- });-- it('reconfigures voice input when transmit mode flips without a push-to-mute keybind', () => {- Keybind.setTransmitMode('voice_activity');- expect(Keybind.isPushToMuteEffective()).toBe(false);- const gateBefore = isVoiceActivityGateEnabled();- const adapter = createAdapter();- dispose = bindVoiceEngineV2AppAudioPreferencesSync({} as Room, adapter, {warn: vi.fn()});-- Keybind.setTransmitMode('voice_push_to_talk');-- expect(isVoiceActivityGateEnabled()).toBe(false);- expect(gateBefore).not.toBe(isVoiceActivityGateEnabled());- expect(adapter.configureVoiceInput).toHaveBeenCalledTimes(1);- expect(adapter.handleInputKeybindChange).not.toHaveBeenCalled();-- Keybind.setTransmitMode('voice_activity');-- expect(isVoiceActivityGateEnabled()).toBe(gateBefore);- expect(adapter.configureVoiceInput).toHaveBeenCalledTimes(2);- expect(adapter.handleInputKeybindChange).not.toHaveBeenCalled();- });-});diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppPushToTalkSelfMute.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppPushToTalkSelfMute.test.tsdeleted file mode 100644index a0790814e..000000000--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppPushToTalkSelfMute.test.ts+++ /dev/null@@ -1,321 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {Room} from 'livekit-client';-import {Track} from 'livekit-client';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--const syncLocalVoiceStateWithServer = vi.fn();-const setVoiceEngineV2ParticipantAudioLevelSpeaking = vi.fn(() => true);-const outgoingAudio = vi.hoisted(() => ({rms: 0}));--const keybind = {- pushToTalkEnabled: true,- pushToTalkHeld: false,- pushToMuteHeld: false,- isPushToTalkEffective: () => keybind.pushToTalkEnabled,- isPushToMuteEffective: () => false,- setPushToTalkHeld: (held: boolean) => {- keybind.pushToTalkHeld = held;- },- setPushToMuteHeld: (held: boolean) => {- keybind.pushToMuteHeld = held;- },- resetPushToTalkState: () => {- keybind.pushToTalkHeld = false;- },- resetPushToMuteState: () => {- keybind.pushToMuteHeld = false;- },-};--const localVoiceState = {- selfMute: false,- selfDeaf: false,- shouldUnmuteOnUndeafen: false,- getSelfMute: () => localVoiceState.selfMute,- getSelfDeaf: () => localVoiceState.selfDeaf,- getMutedByPermission: () => false,- getHasUserSetMute: () => true,- getHasUserSetDeaf: () => false,- updateSelfMute: (muted: boolean) => {- localVoiceState.selfMute = muted;- },- updateSelfDeaf: (deafened: boolean) => {- localVoiceState.selfDeaf = deafened;- },-};--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 ?? ''}}),-}));--vi.mock('@app/app/I18n', () => ({default: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}));--vi.mock('@app/features/input/state/InputKeybind', () => ({default: keybind}));--vi.mock('@app/features/voice/state/LocalVoiceState', () => ({default: localVoiceState}));--vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({default: {}, useMediaEngineVersion: () => 0}));--vi.mock('@app/features/voice/engine/VoiceSharedAudioContext', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/features/voice/engine/VoiceSharedAudioContext')>()),- getSharedVoiceAudioContext: () => ({- state: 'running',- createMediaStreamSource: () => ({connect: () => undefined, disconnect: () => undefined}),- createAnalyser: () => ({- disconnect: () => undefined,- getFloatTimeDomainData: (target: Float32Array) => target.fill(outgoingAudio.rms),- }),- }),-}));--vi.mock('@app/features/voice/engine/VoiceMediaEngineBridge', () => ({- getRoomFromMediaEngine: () => null,- getVoiceConnectionContextFromMediaEngine: () => null,- getVoiceEngineV2SnapshotFromMediaEngine: () => null,- getVoiceStateByConnectionIdFromMediaEngine: () => null,- setVoiceEngineV2ParticipantAudioLevelSpeaking: (...args: Array<unknown>) =>- setVoiceEngineV2ParticipantAudioLevelSpeaking(...(args as [])),- syncLocalVoiceStateWithServer: (...args: Array<unknown>) => syncLocalVoiceStateWithServer(...args),- updateLocalParticipantFromRoom: () => undefined,-}));--const {installRuntimeBootstrap} = await import('@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture');-installRuntimeBootstrap('https://primary.test/api');--const {default: adapter} = await import('@app/features/voice/engine/v2/VoiceEngineV2AppMediaExecutionAdapter');--interface FakeMicrophonePublication {- source: Track.Source;- isMuted: boolean;- track: {- mediaStreamTrack: {readyState: string; getSettings(): MediaTrackSettings; getConstraints(): MediaTrackConstraints};- getProcessor(): undefined;- on(): void;- off(): void;- };- mute: ReturnType<typeof vi.fn>;- unmute: ReturnType<typeof vi.fn>;-}--function createMicrophonePublication(): FakeMicrophonePublication {- const publication: FakeMicrophonePublication = {- source: Track.Source.Microphone,- isMuted: true,- track: {- mediaStreamTrack: {readyState: 'live', getSettings: () => ({}), getConstraints: () => ({})},- getProcessor: () => undefined,- on: () => undefined,- off: () => undefined,- },- mute: vi.fn(async () => {- publication.isMuted = true;- }),- unmute: vi.fn(async () => {- publication.isMuted = false;- }),- };- return publication;-}--function createRoom(): {room: Room; publications: Map<string, FakeMicrophonePublication>} {- const publications = new Map<string, FakeMicrophonePublication>();- const room = {- localParticipant: {- identity: 'user_1_connection',- audioTrackPublications: publications,- trackPublications: publications,- },- remoteParticipants: new Map(),- } as unknown as Room;- return {room, publications};-}--function lastSyncedSelfMute(): unknown {- const call = syncLocalVoiceStateWithServer.mock.calls.at(-1);- return (call?.[0] as {self_mute?: boolean} | undefined)?.self_mute;-}--function lastSpeaking(): unknown {- return setVoiceEngineV2ParticipantAudioLevelSpeaking.mock.calls.at(-1)?.[1 as never];-}--const noServerVoiceState = () => null;--describe('push to talk with self-mute', () => {- beforeEach(() => {- keybind.pushToTalkEnabled = true;- keybind.pushToTalkHeld = false;- localVoiceState.selfMute = false;- localVoiceState.selfDeaf = false;- syncLocalVoiceStateWithServer.mockClear();- setVoiceEngineV2ParticipantAudioLevelSpeaking.mockClear();- });-- it('keeps the microphone muted and reports self_mute while the key is held and the user is self-muted', () => {- const {room, publications} = createRoom();- const publication = createMicrophonePublication();- publications.set('mic', publication);- localVoiceState.selfMute = true;- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(keybind.pushToTalkHeld).toBe(true);- expect(publication.unmute).not.toHaveBeenCalled();- expect(publication.mute).toHaveBeenCalled();- expect(publication.isMuted).toBe(true);- expect(lastSyncedSelfMute()).toBe(true);- expect(lastSpeaking()).toBe(false);- adapter.applyPushToTalkHold(false, room, noServerVoiceState);- expect(publication.unmute).not.toHaveBeenCalled();- expect(lastSyncedSelfMute()).toBe(true);- });-- it('gates the microphone on the key again once the user unmutes', () => {- const {room, publications} = createRoom();- const publication = createMicrophonePublication();- publications.set('mic', publication);- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(publication.unmute).toHaveBeenCalledTimes(1);- expect(lastSyncedSelfMute()).toBe(false);- expect(lastSpeaking()).toBe(false);- adapter.applyPushToTalkHold(false, room, noServerVoiceState);- expect(publication.isMuted).toBe(true);- expect(lastSyncedSelfMute()).toBe(true);- expect(lastSpeaking()).toBe(false);- });-- it('transmits when the user unmutes while the key is still held', () => {- const {room, publications} = createRoom();- const publication = createMicrophonePublication();- publications.set('mic', publication);- localVoiceState.selfMute = true;- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(publication.isMuted).toBe(true);- localVoiceState.selfMute = false;- adapter.handlePushToTalkModeChange(room, noServerVoiceState);- expect(keybind.pushToTalkHeld).toBe(false);- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(publication.isMuted).toBe(false);- expect(lastSyncedSelfMute()).toBe(false);- });-- it('keeps self-mute when switching into and out of push to talk', () => {- const {room, publications} = createRoom();- const publication = createMicrophonePublication();- publications.set('mic', publication);- localVoiceState.selfMute = true;- keybind.pushToTalkEnabled = false;- adapter.handlePushToTalkModeChange(room, noServerVoiceState);- expect(lastSyncedSelfMute()).toBe(true);- keybind.pushToTalkEnabled = true;- adapter.handlePushToTalkModeChange(room, noServerVoiceState);- expect(localVoiceState.selfMute).toBe(true);- expect(publication.unmute).not.toHaveBeenCalled();- expect(lastSyncedSelfMute()).toBe(true);- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(publication.unmute).not.toHaveBeenCalled();- expect(lastSyncedSelfMute()).toBe(true);- keybind.pushToTalkEnabled = false;- adapter.handlePushToTalkModeChange(room, noServerVoiceState);- expect(localVoiceState.selfMute).toBe(true);- expect(publication.unmute).not.toHaveBeenCalled();- expect(lastSyncedSelfMute()).toBe(true);- });-- it('publishes a muted microphone when a self-muted push to talk user unmutes without holding the key', async () => {- const {room, publications} = createRoom();- const enableMicrophone = vi.spyOn(adapter, 'enableMicrophone').mockImplementation(async () => {- publications.set('mic', createMicrophonePublication());- });- localVoiceState.selfMute = true;- await adapter.reconcileEffectiveAudioState(room, {channelId: '1', serverMute: false, serverDeaf: false});- expect(enableMicrophone).not.toHaveBeenCalled();- expect(publications.size).toBe(0);- localVoiceState.selfMute = false;- await adapter.reconcileEffectiveAudioState(room, {channelId: '1', serverMute: false, serverDeaf: false});- expect(enableMicrophone).toHaveBeenCalledTimes(1);- const publication = publications.get('mic');- expect(publication).toBeDefined();- expect(publication?.isMuted).toBe(true);- expect(publication?.unmute).not.toHaveBeenCalled();- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- expect(publication?.unmute).toHaveBeenCalledTimes(1);- expect(publication?.isMuted).toBe(false);- expect(lastSyncedSelfMute()).toBe(false);- enableMicrophone.mockRestore();- });-});--interface LocalSpeakingMeterProbe {- startLocalSpeakingDetector(room: Room): void;- stopLocalSpeakingDetector(room?: Room | null): void;- localSpeakingMeter: {tick(nowMs: number): void} | null;-}--describe('local speaking indicator in push to talk', () => {- const probe = adapter as unknown as LocalSpeakingMeterProbe;- let nowMs = 0;-- function tick(rms: number, ticks = 1): void {- outgoingAudio.rms = rms;- for (let index = 0; index < ticks; index++) {- nowMs += 50;- probe.localSpeakingMeter?.tick(nowMs);- }- }-- beforeEach(() => {- vi.stubGlobal('MediaStream', class {});- keybind.pushToTalkEnabled = true;- keybind.pushToTalkHeld = false;- localVoiceState.selfMute = false;- localVoiceState.selfDeaf = false;- outgoingAudio.rms = 0;- setVoiceEngineV2ParticipantAudioLevelSpeaking.mockClear();- });-- afterEach(() => {- probe.stopLocalSpeakingDetector();- vi.unstubAllGlobals();- });-- function startWithMicrophone(): {room: Room; publication: FakeMicrophonePublication} {- const {room, publications} = createRoom();- const publication = createMicrophonePublication();- publications.set('mic', publication);- probe.startLocalSpeakingDetector(room);- return {room, publication};- }-- it('stays dark while the key is held and nothing audible is sent', () => {- const {room} = startWithMicrophone();- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- tick(0.001, 10);- expect(setVoiceEngineV2ParticipantAudioLevelSpeaking).not.toHaveBeenCalledWith(expect.anything(), true);- });-- it('lights for speech sent while the key is held and goes dark the moment it is released', () => {- const {room} = startWithMicrophone();- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- tick(0.05, 2);- expect(lastSpeaking()).toBe(true);- adapter.applyPushToTalkHold(false, room, noServerVoiceState);- expect(lastSpeaking()).toBe(false);- tick(0.05, 4);- expect(setVoiceEngineV2ParticipantAudioLevelSpeaking).toHaveBeenLastCalledWith(expect.anything(), false);- });-- it('never lights for a self-muted user, however loud the microphone is', () => {- const {room} = startWithMicrophone();- localVoiceState.selfMute = true;- adapter.applyPushToTalkHold(true, room, noServerVoiceState);- tick(0.2, 10);- expect(setVoiceEngineV2ParticipantAudioLevelSpeaking).not.toHaveBeenCalledWith(expect.anything(), true);- });-});diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareWiring.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareWiring.test.tsdeleted file mode 100644index 084614e21..000000000--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppScreenShareWiring.test.ts+++ /dev/null@@ -1,1025 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {EventEmitter} from 'node:events';-import type {ScreenShareEncoderVerificationAction} from '@app/features/voice/utils/CodecCapabilityDetector';-import {BackupCodecPolicy, ParticipantEvent, type Room, Track, type VideoCodec} from 'livekit-client';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--const pushWithKey = vi.fn();-const publishLocalCapabilities = vi.fn(async () => null);-const refreshSelection = vi.fn(async () => null);-const selectScreenShareCodec = vi.fn((): VideoCodec => 'vp8');-const markRuntimeFailure = vi.fn();-let selfStream = true;-let codecDenial: string | null = null;-let vp8Available = false;-let av1Available = false;-let knownDecode: Array<Set<VideoCodec>> = [];-let unknownParticipants = 0;-let preferenceOrder: Array<VideoCodec> = ['h264'];-let selectedCodec: VideoCodec | null = 'vp9';-let stallAction: ScreenShareEncoderVerificationAction = {kind: 'recover-stalled', codec: 'h264'};-const gpuReport: {gpuLabel: string} | null = null;-const gpuReportLoad: Promise<unknown> = Promise.resolve(null);-let h264HardwareProfiles: {profiles: Set<string>} | null = null;-let softwareVideoEncodeExpected = false;-let displayShareEnvironment: 'web' | 'desktop-custom' | 'desktop-wayland' = 'web';-const voiceConnectionContext: {guildId: string | null; channelId: string | null; connectionId: string | null} | null =- null;-const voiceStates: Record<string, Record<string, Record<string, unknown>>> = {};--vi.mock('@app/features/voice/utils/GpuEncoderCapabilities', () => ({- getGpuEncoderReportSync: () => gpuReport,- getH264HardwareProfilesSync: () => h264HardwareProfiles,- isSoftwareVideoEncodeExpectedSync: () => softwareVideoEncodeExpected,- loadGpuEncoderReport: () => gpuReportLoad,-}));--vi.mock('@app/features/voice/utils/ScreenShareEnvironment', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/features/voice/utils/ScreenShareEnvironment')>()),- getDisplayShareEnvironment: async () => displayShareEnvironment,-}));--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: {- locale: 'en-GB',- _: (descriptor: {message?: string}, values?: Record<string, unknown>) =>- (descriptor.message ?? '').replace(/{(\w+)}/g, (token, key: string) =>- values && key in values ? String(values[key]) : token,- ),- number: (value: number) => String(value),- },- }),-}));--vi.mock('@app/app/I18n', () => ({default: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}));--vi.mock('@app/features/app/components/alerts/GenericErrorModal', () => ({GenericErrorModal: () => null}));--vi.mock('@app/features/voice/components/StreamKeys', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/features/voice/components/StreamKeys')>()),- getStreamKey: () => 'stream',-}));--vi.mock('@app/features/voice/engine/VoiceMediaGraphStore', () => ({- voiceMediaGraphStore: {getGraphSnapshot: () => null},-}));--vi.mock('@app/features/voice/engine/VoiceMediaGraph', () => ({- normalizeVoiceMediaGraphViewerStreamKeys: () => [],- selectVoiceMediaGraphViewerStreamKeys: () => [],-}));--vi.mock('@app/features/voice/engine/VoiceStreamWatchState', () => ({- addWatchedStreamKey: () => undefined,- stopWatchingStreamKey: () => undefined,-}));--vi.mock('@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareStateSync', () => ({- applyVoiceEngineV2AppScreenShareState: () => undefined,-}));--vi.mock('@app/features/voice/engine/voice_screen_share_manager/NativePermissionGate', () => ({- ensureNativeCameraPermissionForDeviceShare: async () => undefined,- ensureNativeMicrophonePermissionForDeviceShare: async () => undefined,-}));--vi.mock('@app/features/voice/state/LocalVoiceState', () => ({- default: {- getSelfStream: () => selfStream,- updateSelfStreamAudio: () => undefined,- getViewerStreamKeys: () => [],- },-}));--vi.mock('@app/features/voice/utils/NativeAudioCaptureBridge', () => ({- armNativeAudioForLinuxRouting: async () => false,- armNativeAudioForNextCapture: async () => false,- armNativeSystemAudioForNextCapture: async () => false,- captureNativeAudioTrackForLinuxRouting: async () => null,- captureNativeAudioTrackForWindowPid: async () => null,- commitNativeAudioBridgeReplacement: () => undefined,- disarmNativeAudio: () => undefined,- disarmPendingNativeAudio: () => undefined,- getLastNativeAudioArmFailure: () => null,- getNativeAudioAvailabilityCached: async () => null,- getNativeAudioAvailabilitySnapshot: () => null,- reconfigureLinuxNativeAudioRouting: async () => 'unsupported',-}));--vi.mock('@app/features/voice/utils/ScreenShareUtils', () => ({- executeScreenShareOperation: async (operation: () => Promise<void>) => {- await operation();- },- handleScreenShareError: () => undefined,-}));--vi.mock('@app/features/voice/engine/MediaEngineFacade', () => ({default: {}, useMediaEngineVersion: () => 0}));--vi.mock('@app/features/voice/engine/VoiceMediaEngineBridge', () => ({- getAllVoiceStatesFromMediaEngine: () => voiceStates,- getVoiceConnectionContextFromMediaEngine: () => voiceConnectionContext,- updateLocalParticipantFromRoom: () => undefined,-}));--vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: 'publisher'}}));--vi.mock('@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareLiveKitFlows', () => ({- VoiceEngineV2AppScreenShareLiveKitFlows: class {- async republishActiveShareWithCodec(): Promise<boolean> {- return true;- }- },-}));--vi.mock('@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareControllerRouting', () => ({- selectVoiceEngineV2AppScreenShareSetEnabledOptions: () => ({}),- VoiceEngineV2AppScreenShareControllerRouting: class {},-}));--vi.mock('@app/features/ui/commands/ModalCommands', () => ({- modal: (render: unknown) => render,- pushWithKey: (...args: Array<unknown>) => pushWithKey(...args),-}));--vi.mock('@app/features/ui/commands/SoundCommands', () => ({playSound: () => undefined}));--vi.mock('@app/features/ui/commands/ToastCommands', () => ({createToast: () => undefined}));--vi.mock('@app/features/premium/commands/PremiumModalCommands', () => ({open: () => undefined}));--vi.mock('@app/features/voice/utils/VideoQualityEntitlement', () => ({- hasHigherVideoQuality: () => true,- getScreenShareBitrateCeilingBps: () => 9_000_000,-}));--vi.mock('@app/features/voice/engine/ScreenShareCodecNegotiation', () => ({- default: {- getRemoteDecodeInputs: () => ({knownDecode, unknownParticipants}),- getSelectedCodec: () => selectedCodec,- publishLocalCapabilities: () => publishLocalCapabilities(),- refreshSelection: () => refreshSelection(),- selectScreenShareCodec: () => selectScreenShareCodec(),- },- getScreenShareCodecPreferenceOrder: () => preferenceOrder,-}));--vi.mock('@app/features/voice/utils/CodecCapabilityDetector', () => {- const unavailable = {allowed: false, supported: false, hardware: false};- return {- LIVEKIT_SUPPORTED_CODECS: ['vp8', 'h264', 'vp9', 'av1', 'h265'],- buildScreenShareCodecProfile: () => ({- browser: 'chromium',- desktop: true,- codecs: {- av1: {allowed: av1Available, supported: av1Available, hardware: false},- h265: unavailable,- h264: {allowed: true, supported: true, hardware: true},- vp9: unavailable,- vp8: {allowed: vp8Available, supported: vp8Available, hardware: false},- },- }),- findVideoPublishCodecPolicyViolation: () => null,- getCodecCapabilityReport: () => ({h264: {hardwareAccelerated: 'hardware'}}),- getVideoPublishCodecDenial: () => codecDenial,- markScreenShareCodecEncodeRuntimeFailure: (...args: Array<unknown>) => markRuntimeFailure(...args),- markScreenShareCodecSoftwareEncodeObserved: () => undefined,- resolveScreenShareEncoderVerificationAction: () => stallAction,- resolveVideoPublishCodecPolicy: (requested: string) => ({- allowed: [requested, 'h264'],- requested,- primary: requested,- backupCodec: requested === 'h264' || requested === 'vp8' ? false : {codec: 'h264'},- }),- };-});--const BOOTSTRAP_ENDPOINT = 'https://primary.test/api';--const {installRuntimeBootstrap} = await import('@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture');-installRuntimeBootstrap(BOOTSTRAP_ENDPOINT);--const {VoiceEngineV2AppScreenShareExecutionAdapter, shouldRestoreScreenShareAfterReconnect} = await import(- '@app/features/voice/engine/v2/VoiceEngineV2AppScreenShareExecutionAdapter'-);-const {default: ActiveScreenShareSource} = await import('@app/features/voice/state/ActiveScreenShareSource');-const {default: VoiceSettings} = await import('@app/features/voice/state/VoiceSettings');-const {default: SoftwareEncoderWarning} = await import('@app/features/voice/state/SoftwareEncoderWarning');-const {recordScreenShareStarted, resetRecentScreenSharesForTests} = await import(- '@app/features/voice/utils/ScreenShareLifecycleLog'-);-const {ensureCommittedScreenShareTarget, getEffectivePublishOptions, resolveConfiguredScreenShareTarget} = await import(- '@app/features/voice/engine/voice_screen_share_manager/shared'-);-const {resolveScreenShareDegradationPreference} = await import('@app/features/voice/utils/ScreenShareOptions');-const {rankScreenShareCodecs} = await import('@app/features/voice/utils/ScreenShareCodecSelection');--const FIRST_TICK_MS = 2500;-const TICK_MS = 2000;--interface StatsFeed {- encodedFps: number;- sourceFps: number;- targetBitrate: number;- active: boolean;- sentWidth: number;- sentHeight: number;-}--interface FakeSender {- sender: RTCRtpSender;- setParameters: ReturnType<typeof vi.fn>;- getStats: ReturnType<typeof vi.fn>;- getParameters: ReturnType<typeof vi.fn>;- current: () => RTCRtpSendParameters;-}--function createStatsReader(feed: StatsFeed): () => RTCStatsReport {- let last = Date.now();- let framesEncoded = 0;- let sourceFrames = 0;- let bytesSent = 0;- return () => {- const now = Date.now();- const seconds = (now - last) / 1000;- last = now;- framesEncoded += Math.round(feed.encodedFps * seconds);- sourceFrames += Math.round(feed.sourceFps * seconds);- bytesSent += Math.round((feed.targetBitrate * seconds) / 8);- const entries: Array<Record<string, unknown>> = [- {type: 'codec', id: 'codec', mimeType: 'video/H264'},- {- type: 'media-source',- id: 'source',- kind: 'video',- frames: sourceFrames,- framesPerSecond: feed.sourceFps,- width: 3840,- height: 2160,- },- {- type: 'outbound-rtp',- id: 'outbound',- kind: 'video',- codecId: 'codec',- mediaSourceId: 'source',- active: feed.active,- framesEncoded,- framesSent: framesEncoded,- bytesSent,- headerBytesSent: 0,- frameWidth: feed.sentWidth,- frameHeight: feed.sentHeight,- targetBitrate: feed.targetBitrate,- qualityLimitationReason: 'none',- encoderImplementation: 'NVENC',- timestamp: now,- },- ];- return new Map(entries.map((entry) => [entry.id as string, entry])) as unknown as RTCStatsReport;- };-}--function createSender(- feed: StatsFeed,- options: {mimeType?: string; encodings?: Array<RTCRtpEncodingParameters>} = {},-): FakeSender {- let params = {- codecs: [{mimeType: options.mimeType ?? 'video/H264'}],- encodings: options.encodings ?? [{scalabilityMode: 'L1T3'}],- } as unknown as RTCRtpSendParameters;- const getParameters = vi.fn(() => structuredClone(params));- const readStats = createStatsReader(feed);- const setParameters = vi.fn(async (next: RTCRtpSendParameters) => {- params = next;- });- const getStats = vi.fn(async () => readStats());- const sender = {- track: {getSettings: () => ({width: 3840, height: 2160}), contentHint: ''},- getParameters,- setParameters,- getStats,- } as unknown as RTCRtpSender;- return {sender, setParameters, getStats, getParameters, current: () => params};-}--function createShare(sender: RTCRtpSender) {- const applyConstraints = vi.fn(async () => undefined);- const track = Object.assign(new EventEmitter(), {- sender,- mediaStreamTrack: Object.assign(new EventTarget(), {- contentHint: '',- readyState: 'live',- getConstraints: () => ({}),- applyConstraints,- }),- simulcastCodecs: new Map<string, {sender: RTCRtpSender}>(),- attach: () => undefined,- detach: () => undefined,- setDegradationPreference: async () => undefined,- getProcessor: () => null,- });- const publication = {source: Track.Source.ScreenShare, videoTrack: track, track, options: {videoCodec: 'h264'}};- const participant = Object.assign(new EventEmitter(), {- isScreenShareEnabled: true,- trackPublications: new Map([['screen', publication]]),- getTrackPublication: (source: Track.Source) => (source === Track.Source.ScreenShare ? publication : undefined),- publishTrack: vi.fn(async () => publication),- unpublishTrack: vi.fn(async () => undefined),- setScreenShareEnabled: vi.fn(async () => undefined),- });- const room = {localParticipant: participant, on: () => undefined, off: () => undefined} as unknown as Room;- return {track, publication, participant, room, applyConstraints};-}--function createAdapter() {- const adapter = new VoiceEngineV2AppScreenShareExecutionAdapter();- const republish = vi.spyOn(adapter.liveKitFlows, 'republishActiveShareWithCodec').mockResolvedValue(true);- const setEnabled = vi.spyOn(adapter, 'setScreenShareEnabled').mockResolvedValue(undefined);- return {adapter, republish, setEnabled};-}--function sentFrameRate(fake: FakeSender): number | undefined {- return fake.current().encodings[0].maxFramerate;-}--describe('the screen share wiring', () => {- let feed: StatsFeed;-- beforeEach(() => {- vi.useFakeTimers();- feed = {- encodedFps: 30,- sourceFps: 30,- targetBitrate: 4_500_000,- active: true,- sentWidth: 1920,- sentHeight: 1080,- };- codecDenial = null;- vp8Available = false;- av1Available = false;- knownDecode = [];- unknownParticipants = 0;- preferenceOrder = ['h264'];- selectedCodec = 'vp9';- stallAction = {kind: 'recover-stalled', codec: 'h264'};- pushWithKey.mockClear();- publishLocalCapabilities.mockReset();- publishLocalCapabilities.mockImplementation(async () => null);- selectScreenShareCodec.mockReset();- selectScreenShareCodec.mockImplementation(() => 'vp8');- markRuntimeFailure.mockReset();- vi.spyOn(VoiceSettings, 'getStreamingMode').mockReturnValue('custom');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('high');- vi.spyOn(VoiceSettings, 'getVideoFrameRate').mockReturnValue(30);- vi.spyOn(VoiceSettings, 'getScreenShareContentHint').mockReturnValue('text');- vi.spyOn(VoiceSettings, 'getPreferredScreenShareCodec').mockReturnValue('auto');- resetRecentScreenSharesForTests();- recordScreenShareStarted();- ActiveScreenShareSource.setPublishedSource('display', 'screen:1');- ActiveScreenShareSource.setSourceDimensions({width: 3840, height: 2160});- ensureCommittedScreenShareTarget();- });-- afterEach(() => {- vi.useRealTimers();- vi.restoreAllMocks();- ActiveScreenShareSource.clear();- });-- it('keeps the committed target across a reconnect restore', () => {- const primary = createSender(feed);- const {room} = createShare(primary.sender);- const {adapter} = createAdapter();- const committed = ActiveScreenShareSource.getTarget();- const snapshot = adapter.prepareScreenShareReconnect(room);- expect(snapshot).not.toBeNull();- expect(shouldRestoreScreenShareAfterReconnect(false, snapshot)).toBe(true);- expect(ActiveScreenShareSource.getTarget()).toEqual(committed);- });-- it('recovers a stalled encoder once and stops the share when it stalls again', async () => {- const primary = createSender(feed);- const {room, participant, track} = createShare(primary.sender);- const {adapter, republish, setEnabled} = createAdapter();- feed.encodedFps = 0;- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(publishLocalCapabilities).toHaveBeenCalledTimes(1);- expect(setEnabled).not.toHaveBeenCalled();- expect(pushWithKey).not.toHaveBeenCalled();- republish.mockClear();- stallAction = {kind: 'stop-stalled', codec: 'h264'};- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(setEnabled).toHaveBeenCalledWith(room, false, {sendUpdate: true, playSound: true});- expect(pushWithKey).toHaveBeenCalledTimes(1);- adapter.cancelEncoderVerificationInternal();- });-- it('keeps verifying until a sample shows frames, and reports encoding only while they keep coming', async () => {- const primary = createSender(feed);- const {room, participant, track} = createShare(primary.sender);- const {adapter} = createAdapter();- feed.encodedFps = 0;- feed.sourceFps = 0;- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(ActiveScreenShareSource.encoding).toBe(false);- expect(publishLocalCapabilities).not.toHaveBeenCalled();- feed.sourceFps = 30;- await vi.advanceTimersByTimeAsync(TICK_MS);- expect(publishLocalCapabilities).toHaveBeenCalledTimes(1);- expect(ActiveScreenShareSource.encoding).toBe(false);- adapter.cancelEncoderVerificationInternal();- });-- it('reports the share as encoding only once frames arrive and stops when they stop', async () => {- const primary = createSender(feed);- const {room, participant, track} = createShare(primary.sender);- const {adapter} = createAdapter();- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(ActiveScreenShareSource.encoding).toBe(false);- await vi.advanceTimersByTimeAsync(TICK_MS);- expect(ActiveScreenShareSource.encoding).toBe(true);- feed.encodedFps = 0;- await vi.advanceTimersByTimeAsync(TICK_MS);- expect(ActiveScreenShareSource.encoding).toBe(false);- adapter.cancelEncoderVerificationInternal();- });-- it('re-enforces the sender parameters on every tick', async () => {- const first = createSender(feed);- const second = createSender(feed);- const {room, participant, track} = createShare(first.sender);- const {adapter} = createAdapter();- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(first.current().degradationPreference).toBe('maintain-resolution');- expect(first.current().encodings).toEqual([- {maxBitrate: 4_500_000, maxFramerate: 30, scaleResolutionDownBy: 2, priority: 'high', networkPriority: 'high'},- ]);- track.sender = second.sender;- await vi.advanceTimersByTimeAsync(TICK_MS);- expect(second.current().degradationPreference).toBe('maintain-resolution');- expect(sentFrameRate(second)).toBe(30);- adapter.cancelEncoderVerificationInternal();- });-- it('enforces a backup sender created later and on every tick after it', async () => {- const primary = createSender(feed);- const later = createSender(feed, {mimeType: 'video/VP9'});- const {room, participant, track} = createShare(primary.sender);- const {adapter} = createAdapter();- await adapter.enforceScreenShareSenderParametersInternal(participant as never, {videoCodec: 'h264'});- participant.emit(ParticipantEvent.LocalSenderCreated, later.sender, track, 'h264');- await vi.advanceTimersByTimeAsync(0);- expect(later.current().degradationPreference).toBe('maintain-resolution');- expect(later.current().encodings).toEqual([- {maxBitrate: 4_500_000, maxFramerate: 30, scaleResolutionDownBy: 2, priority: 'high', networkPriority: 'high'},- ]);- track.simulcastCodecs.set('h264', {sender: later.sender});- adapter.startEncoderVerificationInternal(room, participant as never, 'h264', track as never);- later.current().encodings[0].maxFramerate = 60;- await vi.advanceTimersByTimeAsync(FIRST_TICK_MS);- expect(sentFrameRate(later)).toBe(30);- adapter.cancelEncoderVerificationInternal();- });-- it('leaves an encoding that is not active alone', async () => {- const primary = createSender(feed, {- encodings: [{rid: 'q', active: false, scaleResolutionDownBy: 4}, {rid: 'f'}],- });- const {participant} = createShare(primary.sender);- const {adapter} = createAdapter();- await adapter.enforceScreenShareSenderParametersInternal(participant as never, {videoCodec: 'h264'});- expect(primary.current().encodings[0]).toEqual({rid: 'q', active: false, scaleResolutionDownBy: 4});- expect(primary.current().encodings[1]).toMatchObject({rid: 'f', maxFramerate: 30, priority: 'high'});- });-- it('never lets a screen share trade resolution for frame rate', () => {- expect(resolveScreenShareDegradationPreference(resolveConfiguredScreenShareTarget('display', null))).toBe(- 'maintain-resolution',- );- expect(resolveScreenShareDegradationPreference(resolveConfiguredScreenShareTarget('app', null))).toBe(- 'maintain-resolution',- );- expect(resolveScreenShareDegradationPreference(resolveConfiguredScreenShareTarget('device', null))).toBe(- 'balanced',- );- });-- it('drops a codec the sender cannot encode instead of flooring the order to it', () => {- const entry = (supported: boolean) => ({allowed: supported, supported, hardware: false});- const {order} = rankScreenShareCodecs({- profile: {- browser: 'chromium',- desktop: true,- codecs: {vp8: entry(true), vp9: entry(true), h264: entry(false), h265: entry(false), av1: entry(true)},- },- encoderModeSetting: 'auto',- pin: 'auto',- });- expect(order).toEqual(['av1', 'vp9', 'vp8']);- });-- it('ranks hardware encoders ahead of software ones unless software encoding is forced', () => {- const entry = (hardware: boolean) => ({allowed: true, supported: true, hardware});- const profile = {- browser: 'chromium' as const,- desktop: true,- codecs: {vp8: entry(false), vp9: entry(false), h264: entry(true), h265: entry(true), av1: entry(false)},- };- expect(rankScreenShareCodecs({profile, encoderModeSetting: 'auto', pin: 'auto'}).order).toEqual([- 'h265',- 'h264',- 'av1',- 'vp9',- 'vp8',- ]);- expect(rankScreenShareCodecs({profile, encoderModeSetting: 'software', pin: 'auto'}).order).toEqual([- 'av1',- 'h264',- 'vp9',- 'vp8',- ]);- });-- it('refuses to publish h264 when the sender cannot encode it', async () => {- const detector = await vi.importActual<typeof import('@app/features/voice/utils/CodecCapabilityDetector')>(- '@app/features/voice/utils/CodecCapabilityDetector',- );- const capabilities = {codecs: [{mimeType: 'video/vp8'}, {mimeType: 'video/vp9'}]};- const host = globalThis as Record<string, unknown>;- host.RTCRtpSender = {getCapabilities: () => capabilities};- host.RTCRtpReceiver = {getCapabilities: () => capabilities};- try {- detector.resetCachedCodecCapabilities();- expect(detector.getVideoPublishCodecDenial('h264')).toBe('sender-cannot-encode');- expect(detector.getAllowedVideoPublishCodecs()).not.toContain('h264');- expect(detector.resolveVideoPublishCodecPolicy('h264').primary).toBe('vp9');- expect(detector.resolveVideoPublishCodecPolicy('vp9').backupCodec).toBe(false);- } finally {- detector.resetCachedCodecCapabilities();- Reflect.deleteProperty(host, 'RTCRtpSender');- Reflect.deleteProperty(host, 'RTCRtpReceiver');- }- });-- it('refuses to publish a codec the decode probe excluded, and keeps publishing one a runtime stall hit', async () => {- const decoder = await vi.importActual<typeof import('@app/features/voice/utils/VideoDecoderCapabilities')>(- '@app/features/voice/utils/VideoDecoderCapabilities',- );- const detector = await vi.importActual<typeof import('@app/features/voice/utils/CodecCapabilityDetector')>(- '@app/features/voice/utils/CodecCapabilityDetector',- );- const capabilities = {codecs: [{mimeType: 'video/h265'}, {mimeType: 'video/h264'}]};- const host = globalThis as Record<string, unknown>;- host.RTCRtpSender = {getCapabilities: () => capabilities};- host.RTCRtpReceiver = {getCapabilities: () => capabilities};- host.VideoDecoder = {isConfigSupported: async () => ({supported: false})};- vi.spyOn(VoiceSettings, 'getScreenShareHevcOptIn').mockReturnValue(true);- try {- decoder.resetVideoDecoderExclusions();- detector.resetCachedCodecCapabilities();- expect(detector.isVideoCodecAllowedForPublish('h265')).toBe(true);-- expect(decoder.markScreenShareDecodeFailure('h265', 'decode stall')).toBe(true);- detector.resetCachedCodecCapabilities();- expect(detector.getVideoPublishCodecDenial('h265')).toBeNull();- expect(detector.isVideoCodecAllowedForPublish('h265')).toBe(true);-- await decoder.loadVideoDecoderExclusions();- detector.resetCachedCodecCapabilities();- expect(detector.getVideoPublishCodecDenial('h265')).toBe('decoder-excluded');- expect(detector.isVideoCodecAllowedForPublish('h265')).toBe(false);- expect(detector.isVideoCodecAllowedForPublish('h264')).toBe(true);- expect(detector.getAllowedVideoPublishCodecs()).toContain('h264');- expect(detector.resolveVideoPublishCodecPolicy('h265').primary).not.toBe('h265');- } finally {- decoder.resetVideoDecoderExclusions();- detector.resetCachedCodecCapabilities();- Reflect.deleteProperty(host, 'RTCRtpSender');- Reflect.deleteProperty(host, 'RTCRtpReceiver');- Reflect.deleteProperty(host, 'VideoDecoder');- }- });-});--describe('the retired H.264 backup stream mode', () => {- it('still publishes the automatic H.264 backup simulcast for an SVC primary', async () => {- const svc = await getEffectivePublishOptions(true, {videoCodec: 'av1'});- expect(svc?.backupCodec).toEqual({codec: 'h264'});- expect(svc?.backupCodecPolicy).toBe(BackupCodecPolicy.SIMULCAST);-- const h264 = await getEffectivePublishOptions(true, {videoCodec: 'h264'});- expect(h264?.backupCodec).toBe(false);- expect(h264?.backupCodecPolicy).toBeUndefined();- });-});--describe('the software H.264 clamp warning', () => {- beforeEach(() => {- h264HardwareProfiles = {profiles: new Set()};- selectScreenShareCodec.mockImplementation(() => 'h264');- ActiveScreenShareSource.clear();- SoftwareEncoderWarning.reset();- });-- afterEach(() => {- h264HardwareProfiles = null;- softwareVideoEncodeExpected = false;- selectScreenShareCodec.mockImplementation(() => 'vp8');- ActiveScreenShareSource.clear();- SoftwareEncoderWarning.reset();- });-- it('warns when a clamped share runs on a system that should have a hardware encoder', async () => {- await getEffectivePublishOptions(true, {videoCodec: 'h264'});- expect(SoftwareEncoderWarning.showWarning).toBe(true);- });-- it('stays quiet when the system has no hardware encoder to fall back from', async () => {- softwareVideoEncodeExpected = true;- await getEffectivePublishOptions(true, {videoCodec: 'h264'});- expect(SoftwareEncoderWarning.showWarning).toBe(false);- });-});--const {resolveUserVideoTabScreenShareState} = await import(- '@app/features/user/components/modals/tabs/UserVideoTabState'-);-const {resolveScreenShareQualityPick} = await import('@app/features/voice/utils/ScreenShareOptions');--describe('the video settings tab', () => {- const FREE_RESOLUTION_OPTIONS = [- {value: 'low_480p', isDisabled: false},- {value: 'medium', isDisabled: false},- {value: 'high', isDisabled: true},- {value: 'ultra', isDisabled: true},- {value: 'source', isDisabled: true},- ];- const stateOf = (quality: Parameters<typeof resolveScreenShareQualityPick>[0], selfHosted = false) =>- resolveUserVideoTabScreenShareState({- quality,- hintSetting: 'auto',- bitrate: {ceilingBps: 9_000_000, chosenBps: null},- selfHosted,- });-- it('shows a free account the clamped values, the saved ones and no preset note', () => {- const quality = {- mode: 'custom',- storedResolution: 'source',- storedFrameRate: 30,- entitled: false,- context: 'display',- } as const;- expect(stateOf(quality)).toEqual({- resolution: 'medium',- frameRate: 30,- resolutionOptions: FREE_RESOLUTION_OPTIONS,- frameRateOptions: [15, 30],- bitrate: null,- bitrateOptions: [2_000_000, 4_000_000, 6_000_000, 8_000_000, 9_000_000],- preset: null,- presetOverriddenByContext: false,- saved: {resolution: 'source', frameRate: 30},- });- });-});--const {default: MediaEngine} = await import('@app/features/voice/engine/MediaEngineFacade');-const {- buildConfiguredScreenShareOptions,- startConfiguredDeviceScreenShare,- startConfiguredDisplayScreenShare,- switchConfiguredDeviceScreenShare,- switchConfiguredDisplayScreenShare,-} = await import('@app/features/voice/utils/ScreenShareStartFlow');--describe('the configured screen share start flow', () => {- const engine = MediaEngine as unknown as {- startDeviceScreenShare: ReturnType<typeof vi.fn>;- replaceActiveDeviceScreenShare: ReturnType<typeof vi.fn>;- };- let storedResolution: 'high' | 'medium' | 'source' = 'high';- let started: Array<{resolution: unknown; publishOptions: unknown}> = [];-- beforeEach(() => {- selfStream = true;- storedResolution = 'high';- started = [];- ActiveScreenShareSource.clear();- vi.spyOn(VoiceSettings, 'getStreamingMode').mockReturnValue('custom');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockImplementation(() => storedResolution);- vi.spyOn(VoiceSettings, 'getVideoFrameRate').mockReturnValue(30);- vi.spyOn(VoiceSettings, 'getScreenShareContentHint').mockReturnValue('text');- vi.spyOn(VoiceSettings, 'getPreferredScreenShareCodec').mockReturnValue('auto');- vi.spyOn(VoiceSettings, 'getShareDeviceAudio').mockReturnValue(false);- refreshSelection.mockReset();- refreshSelection.mockResolvedValue(null);- selectScreenShareCodec.mockReset();- selectScreenShareCodec.mockReturnValue('h264');- engine.startDeviceScreenShare = vi.fn(async (options: {resolution: unknown}, publishOptions: unknown) => {- started.push({resolution: options.resolution, publishOptions});- });- engine.replaceActiveDeviceScreenShare = vi.fn(async () => true);- });-- afterEach(() => {- vi.restoreAllMocks();- ActiveScreenShareSource.clear();- selfStream = true;- });-- it('publishes the target the settings push builds', async () => {- expect(await startConfiguredDeviceScreenShare('camera-1')).toBe(true);- const target = resolveConfiguredScreenShareTarget('device', null);- const expected = buildConfiguredScreenShareOptions({- target,- sourceDimensions: null,- includeAudio: false,- videoCodec: 'h264',- });- expect(started).toEqual([- {resolution: expected.captureOptions.resolution, publishOptions: expected.publishOptions},- ]);- expect(expected.publishOptions.videoCodec).toBe('h264');- expect(expected.publishOptions.degradationPreference).toBe('balanced');- expect(ActiveScreenShareSource.getTarget()).toEqual(target);- });-- it('clears the recorded source dimensions for a capture device', async () => {- ActiveScreenShareSource.setPublishedSource('display', 'screen:1');- ActiveScreenShareSource.setSourceDimensions({width: 3840, height: 2160});- await startConfiguredDeviceScreenShare('camera-1');- expect(ActiveScreenShareSource.getPublishedSource()).toBe('device');- expect(ActiveScreenShareSource.getSourceDimensions()).toBeNull();- });-- it('retargets the committed target on a source switch', async () => {- await startConfiguredDeviceScreenShare('camera-1');- const startedTarget = ActiveScreenShareSource.getTarget();- storedResolution = 'medium';- expect(await switchConfiguredDeviceScreenShare('camera-2')).toBe(true);- const switched = resolveConfiguredScreenShareTarget('device', null);- expect(switched).not.toEqual(startedTarget);- expect(ActiveScreenShareSource.getTarget()).toEqual(switched);- });-- it('puts the committed target back when a switch does not take', async () => {- await startConfiguredDeviceScreenShare('camera-1');- const before = ActiveScreenShareSource.getTarget();- engine.replaceActiveDeviceScreenShare = vi.fn(async () => false);- storedResolution = 'medium';- expect(await switchConfiguredDeviceScreenShare('camera-2')).toBe(false);- expect(ActiveScreenShareSource.getTarget()).toEqual(before);- });-});--describe('the configured display screen share start flow', () => {- const engine = MediaEngine as unknown as {- setScreenShareEnabled: ReturnType<typeof vi.fn>;- replaceActiveDisplayScreenShare: ReturnType<typeof vi.fn>;- };- const electronHost = window as unknown as {electron?: {platform: string}};-- beforeEach(() => {- selfStream = true;- displayShareEnvironment = 'desktop-custom';- electronHost.electron = {platform: 'win32'};- ActiveScreenShareSource.clear();- vi.spyOn(VoiceSettings, 'getStreamingMode').mockReturnValue('custom');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('source');- vi.spyOn(VoiceSettings, 'getVideoFrameRate').mockReturnValue(30);- vi.spyOn(VoiceSettings, 'getScreenShareContentHint').mockReturnValue('text');- vi.spyOn(VoiceSettings, 'getPreferredScreenShareCodec').mockReturnValue('auto');- vi.spyOn(VoiceSettings, 'getShareDesktopAudio').mockReturnValue(false);- vi.spyOn(VoiceSettings, 'getShareAppAudio').mockReturnValue(false);- refreshSelection.mockReset();- refreshSelection.mockResolvedValue(null);- selectScreenShareCodec.mockReset();- selectScreenShareCodec.mockReturnValue('h264');- engine.setScreenShareEnabled = vi.fn(async () => undefined);- engine.replaceActiveDisplayScreenShare = vi.fn(async () => true);- });-- afterEach(() => {- vi.restoreAllMocks();- ActiveScreenShareSource.clear();- displayShareEnvironment = 'web';- Reflect.deleteProperty(electronHost, 'electron');- });-- it('commits the target of the picked source rather than the one still recorded', async () => {- ActiveScreenShareSource.setPublishedSource('display', 'screen:0');- ActiveScreenShareSource.setSourceDimensions({width: 3840, height: 2160});- const picked = {width: 1280, height: 720};- const pickedTarget = resolveConfiguredScreenShareTarget('display', picked);- expect(pickedTarget).not.toEqual(resolveConfiguredScreenShareTarget('display', {width: 3840, height: 2160}));- expect(await startConfiguredDisplayScreenShare('screen:1', {sourceDimensions: picked})).toBe(true);- expect(ActiveScreenShareSource.getTarget()).toEqual(pickedTarget);- });-- it('rebuilds the target from the newly picked source on a switch', async () => {- const first = {width: 1280, height: 720};- const second = {width: 3840, height: 2160};- expect(await startConfiguredDisplayScreenShare('screen:1', {sourceDimensions: first})).toBe(true);- ActiveScreenShareSource.setSourceDimensions(first);- const secondTarget = resolveConfiguredScreenShareTarget('display', second);- expect(secondTarget).not.toEqual(resolveConfiguredScreenShareTarget('display', first));- expect(await switchConfiguredDisplayScreenShare('screen:2', {sourceDimensions: second})).toBe(true);- expect(ActiveScreenShareSource.getTarget()).toEqual(secondTarget);- expect(ActiveScreenShareSource.getSourceDimensions()).toEqual(second);- });-- it('asks for the tracking to be held when it stops the share a Wayland source switch restarts', async () => {- displayShareEnvironment = 'desktop-wayland';- electronHost.electron = {platform: 'linux'};- const stops: Array<unknown> = [];- engine.setScreenShareEnabled = vi.fn(async (enabled: boolean, options: unknown) => {- if (!enabled) stops.push(options);- });- expect(await startConfiguredDisplayScreenShare(null, {preferredDisplaySurface: 'monitor'})).toBe(true);- expect(await switchConfiguredDisplayScreenShare(null, {preferredDisplaySurface: 'monitor'})).toBe(true);- expect(stops).toEqual([- {sendUpdate: false, playSound: false, preserveStreamAudioPreferences: true, keepShareTracking: true},- ]);- });-});--const {pushActiveStreamSettings} = await import('@app/features/voice/components/StreamSettingsMenuContent');--describe('a live settings push', () => {- const engine = MediaEngine as unknown as {- startDeviceScreenShare: ReturnType<typeof vi.fn>;- updateActiveScreenShareSettings: ReturnType<typeof vi.fn>;- };-- beforeEach(() => {- selfStream = true;- ActiveScreenShareSource.clear();- vi.spyOn(VoiceSettings, 'getStreamingMode').mockReturnValue('custom');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('high');- vi.spyOn(VoiceSettings, 'getVideoFrameRate').mockReturnValue(30);- vi.spyOn(VoiceSettings, 'getScreenShareContentHint').mockReturnValue('text');- vi.spyOn(VoiceSettings, 'getPreferredScreenShareCodec').mockReturnValue('auto');- vi.spyOn(VoiceSettings, 'getShareDeviceAudio').mockReturnValue(false);- refreshSelection.mockReset();- refreshSelection.mockResolvedValue(null);- selectScreenShareCodec.mockReset();- selectScreenShareCodec.mockReturnValue('h264');- });-- afterEach(() => {- vi.restoreAllMocks();- ActiveScreenShareSource.clear();- });-- it('puts the committed target back when the live share refuses the push', async () => {- engine.startDeviceScreenShare = vi.fn(async () => undefined);- engine.updateActiveScreenShareSettings = vi.fn(async () => false);- await startConfiguredDeviceScreenShare('camera-1');- const before = ActiveScreenShareSource.getTarget();- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('low_480p');- expect(resolveConfiguredScreenShareTarget('device', null)).not.toEqual(before);- await pushActiveStreamSettings('device', 'desktop-custom');- expect(engine.updateActiveScreenShareSettings).toHaveBeenCalledTimes(1);- expect(ActiveScreenShareSource.getTarget()).toEqual(before);- });-- it('keeps the retargeted target when the live share takes the push', async () => {- engine.startDeviceScreenShare = vi.fn(async () => undefined);- engine.updateActiveScreenShareSettings = vi.fn(async () => true);- await startConfiguredDeviceScreenShare('camera-1');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('low_480p');- const retargeted = resolveConfiguredScreenShareTarget('device', null);- await pushActiveStreamSettings('device', 'desktop-custom');- expect(ActiveScreenShareSource.getTarget()).toEqual(retargeted);- });-- it('sends the live share what the start flow published', async () => {- const published: Array<{resolution: unknown; publishOptions: unknown}> = [];- engine.startDeviceScreenShare = vi.fn(async (options: {resolution: unknown}, publishOptions: unknown) => {- published.push({resolution: options.resolution, publishOptions});- });- engine.updateActiveScreenShareSettings = vi.fn(- async (captureOptions: {resolution: unknown}, publishOptions: unknown) => {- published.push({resolution: captureOptions.resolution, publishOptions});- },- );- await startConfiguredDeviceScreenShare('camera-1');- await pushActiveStreamSettings('device', 'desktop-custom');- expect(published).toHaveLength(2);- expect(published[1]).toEqual(published[0]);- });-});--const {reconfigureActiveDeviceShareAudio} = await import('@app/features/voice/utils/ScreenShareStartFlow');--describe('the device share audio input', () => {- const engine = MediaEngine as unknown as {- startDeviceScreenShare: ReturnType<typeof vi.fn>;- ensureDeviceScreenShareMicPublication: ReturnType<typeof vi.fn>;- getActiveScreenShareVideoDeviceId: ReturnType<typeof vi.fn>;- setScreenShareAudioMuted: ReturnType<typeof vi.fn>;- };- const CARD = {deviceId: 'card-video', groupId: 'card', kind: 'videoinput', label: 'Capture card'} as MediaDeviceInfo;- const CARD_AUDIO = {- deviceId: 'card-audio',- groupId: 'card',- kind: 'audioinput',- label: 'Capture card audio',- } as MediaDeviceInfo;- const HEADSET = {- deviceId: 'microphone-1',- groupId: 'headset',- kind: 'audioinput',- label: 'Headset',- } as MediaDeviceInfo;- let devices: Array<MediaDeviceInfo> = [];- let published: Array<string | undefined> = [];- let chosenAudioDeviceId = 'default';- let usesMicrophone = false;-- beforeEach(() => {- selfStream = true;- devices = [CARD, HEADSET];- published = [];- chosenAudioDeviceId = 'default';- usesMicrophone = false;- ActiveScreenShareSource.clear();- Object.defineProperty(navigator, 'mediaDevices', {- configurable: true,- value: {enumerateDevices: async () => devices},- });- vi.spyOn(VoiceSettings, 'getStreamingMode').mockReturnValue('custom');- vi.spyOn(VoiceSettings, 'getScreenshareResolution').mockReturnValue('high');- vi.spyOn(VoiceSettings, 'getVideoFrameRate').mockReturnValue(30);- vi.spyOn(VoiceSettings, 'getScreenShareContentHint').mockReturnValue('text');- vi.spyOn(VoiceSettings, 'getPreferredScreenShareCodec').mockReturnValue('auto');- vi.spyOn(VoiceSettings, 'getShareDeviceAudio').mockReturnValue(true);- vi.spyOn(VoiceSettings, 'getInputDeviceId').mockReturnValue('microphone-1');- vi.spyOn(VoiceSettings, 'getScreenShareAudioDeviceId').mockImplementation(() => chosenAudioDeviceId);- vi.spyOn(VoiceSettings, 'getScreenShareDeviceAudioUsesMicrophone').mockImplementation(() => usesMicrophone);- refreshSelection.mockReset();- refreshSelection.mockResolvedValue(null);- selectScreenShareCodec.mockReset();- selectScreenShareCodec.mockReturnValue('h264');- engine.startDeviceScreenShare = vi.fn(async (options: {audioDeviceId?: string}) => {- published.push(options.audioDeviceId);- });- engine.ensureDeviceScreenShareMicPublication = vi.fn(async (audioDeviceId: string) => {- published.push(audioDeviceId);- return true;- });- engine.getActiveScreenShareVideoDeviceId = vi.fn(() => 'card-video');- engine.setScreenShareAudioMuted = vi.fn();- });-- afterEach(() => {- vi.restoreAllMocks();- ActiveScreenShareSource.clear();- selfStream = true;- });-- it('never publishes the voice input for a capture device that has no audio of its own', async () => {- expect(await startConfiguredDeviceScreenShare('card-video')).toBe(true);- expect(published).toEqual([undefined]);- });-- it('publishes the capture device own audio input when it has one', async () => {- devices = [CARD, CARD_AUDIO, HEADSET];- expect(await startConfiguredDeviceScreenShare('card-video')).toBe(true);- expect(published).toEqual(['card-audio']);- });-- it('publishes the input the user picked in the audio device menu', async () => {- chosenAudioDeviceId = 'microphone-1';- expect(await startConfiguredDeviceScreenShare('card-video')).toBe(true);- expect(published).toEqual(['microphone-1']);- });-- it('publishes the voice input when the audio source picker asked for the microphone', async () => {- usesMicrophone = true;- expect(await startConfiguredDeviceScreenShare('card-video')).toBe(true);- expect(published).toEqual(['microphone-1']);- });-- it('silences a live device share rather than leaving an earlier input publishing', async () => {- expect(await reconfigureActiveDeviceShareAudio()).toBe(true);- expect(engine.setScreenShareAudioMuted).toHaveBeenCalledWith(true);- expect(engine.ensureDeviceScreenShareMicPublication).not.toHaveBeenCalled();- });-});diff --git a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.ts b/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.tsdeleted file mode 100644index 28c8aa715..000000000--- a/fluxer_app/src/features/voice/engine/v2/VoiceEngineV2AppSelectors.test.ts+++ /dev/null@@ -1,93 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls,- selectVoiceEngineV2AppMuteReason,- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload,-} from '@app/features/voice/engine/v2/VoiceEngineV2AppSelectors';-import {transitionVoiceEngineV2} from '@fluxer/voice_engine_v2/src/core/reducer';-import {- availableVoiceEngineV2Capabilities,- createVoiceEngineV2InitialSnapshot,- type VoiceEngineV2Snapshot,-} from '@fluxer/voice_engine_v2/src/core/state';-import type {- VoiceEngineV2AudioControls,- VoiceEngineV2AudioControlsPatch,-} from '@fluxer/voice_engine_v2/src/protocol/types';-import {describe, expect, it} from 'vitest';--function audio(overrides: Partial<VoiceEngineV2AudioControls>): VoiceEngineV2AudioControls {- return {- mode: 'pushToTalk',- locallyMuted: false,- preferredLocallyMuted: false,- locallyDeafened: false,- mutedByPermission: false,- hasUserSetMute: false,- hasUserSetDeaf: false,- shouldUnmuteOnUndeafen: false,- pushToTalkActive: false,- pushToMuteActive: false,- inputVolume: 100,- outputVolume: 100,- ...overrides,- };-}--function snapshotWith(controls: VoiceEngineV2AudioControlsPatch): VoiceEngineV2Snapshot {- return transitionVoiceEngineV2(createVoiceEngineV2InitialSnapshot(availableVoiceEngineV2Capabilities()), {- type: 'audioControls.changed',- controls,- }).snapshot;-}--describe('push to talk self-mute selectors', () => {- it('reports self-mute over a held push to talk key', () => {- const controls = audio({locallyMuted: true, pushToTalkActive: true});- expect(selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls(controls)).toBe(true);- expect(selectVoiceEngineV2AppMuteReason({voiceState: null, permissionMuted: false, audio: controls})).toBe('self');- });-- it('reports the push to talk gate when not self-muted', () => {- const idle = audio({});- expect(selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls(idle)).toBe(true);- expect(selectVoiceEngineV2AppMuteReason({voiceState: null, permissionMuted: false, audio: idle})).toBe(- 'voice_push_to_talk',- );- const held = audio({pushToTalkActive: true});- expect(selectVoiceEngineV2AppEffectiveSelfMuteFromAudioControls(held)).toBe(false);- expect(selectVoiceEngineV2AppMuteReason({voiceState: null, permissionMuted: false, audio: held})).toBeNull();- });-- it('syncs self_mute from self-mute and the push to talk gate', () => {- expect(selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(snapshotWith({mode: 'pushToTalk'}))).toBe(true);- expect(- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(- snapshotWith({mode: 'pushToTalk', pushToTalkActive: true}),- ),- ).toBe(false);- expect(- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(- snapshotWith({mode: 'pushToTalk', pushToTalkActive: true, locallyMuted: true}),- ),- ).toBe(true);- });-- it('keeps voice activity and permission mutes in the synced self_mute', () => {- expect(selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(snapshotWith({mode: 'voiceActivity'}))).toBe(false);- expect(- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(snapshotWith({mode: 'voiceActivity', locallyMuted: true})),- ).toBe(true);- expect(- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(- snapshotWith({mode: 'voiceActivity', mutedByPermission: true}),- ),- ).toBe(true);- expect(- selectVoiceEngineV2AppSyncSelfMuteForVoiceStatePayload(- snapshotWith({mode: 'pushToMute', pushToMuteActive: true}),- ),- ).toBe(true);- });-});diff --git a/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.ts b/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.tsdeleted file mode 100644index 61358d94c..000000000--- a/fluxer_app/src/features/voice/utils/GpuEncoderCapabilities.test.ts+++ /dev/null@@ -1,110 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- describeHardwareVideoEncodeProfiles,- type HardwareVideoEncodeProfile,- isSoftwareVideoEncodeExpected,- probeHardwareVideoEncodeProfiles,- type VideoEncoderLike,-} from '@app/features/voice/utils/GpuEncoderCapabilities';-import {describe, expect, it} from 'vitest';--const H264_HIGH: HardwareVideoEncodeProfile = {- codec: 'h264',- profile: 'high',- maxWidth: 3840,- maxHeight: 2160,- maxFrameRate: 30,-};--interface ProbeConfig {- codec: string;- width: number;- height: number;- framerate?: number;- hardwareAcceleration: string;-}--function fakeEncoder(supports: (config: ProbeConfig) => boolean): VideoEncoderLike {- return {- isConfigSupported: async (config) => ({supported: supports(config as ProbeConfig)}),- };-}--describe('expected software video encoding', () => {- it('is expected on Linux when the system has no hardware encoder at all', () => {- expect(- isSoftwareVideoEncodeExpected({platform: 'linux', h264HardwareProfileCount: 0, hardwareEncodeProfiles: []}),- ).toBe(true);- expect(- isSoftwareVideoEncodeExpected({platform: 'linux', h264HardwareProfileCount: null, hardwareEncodeProfiles: []}),- ).toBe(true);- expect(- isSoftwareVideoEncodeExpected({platform: 'linux', h264HardwareProfileCount: 0, hardwareEncodeProfiles: null}),- ).toBe(true);- });-- it('is not expected on Linux when a hardware encoder exists', () => {- expect(- isSoftwareVideoEncodeExpected({- platform: 'linux',- h264HardwareProfileCount: 0,- hardwareEncodeProfiles: [H264_HIGH],- }),- ).toBe(false);- expect(- isSoftwareVideoEncodeExpected({platform: 'linux', h264HardwareProfileCount: 2, hardwareEncodeProfiles: []}),- ).toBe(false);- });-- it('is not expected on Linux before anything has been probed', () => {- expect(- isSoftwareVideoEncodeExpected({platform: 'linux', h264HardwareProfileCount: null, hardwareEncodeProfiles: null}),- ).toBe(false);- });-- it('is never expected on other platforms', () => {- for (const platform of ['windows', 'macos', 'unknown'] as const) {- expect(isSoftwareVideoEncodeExpected({platform, h264HardwareProfileCount: 0, hardwareEncodeProfiles: []})).toBe(- false,- );- }- });-});--describe('hardware video encode profiles', () => {- it('reports nothing when WebCodecs is unavailable', async () => {- await expect(probeHardwareVideoEncodeProfiles(null)).resolves.toBeNull();- expect(describeHardwareVideoEncodeProfiles(null)).toMatch(/^unknown/);- });-- it('reports an empty list when every hardware probe fails', async () => {- const profiles = await probeHardwareVideoEncodeProfiles(fakeEncoder(() => false));- expect(profiles).toEqual([]);- expect(describeHardwareVideoEncodeProfiles(profiles)).toMatch(/^none/);- });-- it('only asks for hardware encoders', async () => {- const asked = new Set<string>();- await probeHardwareVideoEncodeProfiles(- fakeEncoder((config) => {- asked.add(config.hardwareAcceleration);- return false;- }),- );- expect([...asked]).toEqual(['prefer-hardware']);- });-- it('bounds each profile by the largest size and frame rate the encoder accepts', async () => {- const bounded = await probeHardwareVideoEncodeProfiles(- fakeEncoder(- (config) =>- config.codec === 'avc1.640033' &&- config.width <= 2560 &&- (config.framerate === undefined || config.framerate <= 60),- ),- );- expect(bounded).toEqual([{codec: 'h264', profile: 'high', maxWidth: 2560, maxHeight: 1440, maxFrameRate: 60}]);- expect(describeHardwareVideoEncodeProfiles(bounded)).toEqual(['h264 high up to 2560x1440 at 60 fps']);- });-});diff --git a/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.tsdeleted file mode 100644index 5d0ef8b98..000000000--- a/fluxer_app/src/features/voice/utils/ScreenShareCodecDiagnostics.test.ts+++ /dev/null@@ -1,60 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- findInboundVideoDecodeSample,- findStalledVideoDecoder,-} from '@app/features/voice/utils/ScreenShareCodecDiagnostics';-import {- markScreenShareDecodeFailure,- resetVideoDecoderExclusions,-} from '@app/features/voice/utils/VideoDecoderCapabilities';-import {afterEach, describe, expect, it} from 'vitest';--function buildStats(inbound: Record<string, unknown>): RTCStatsReport {- return new Map<string, unknown>([- ['codec-1', {type: 'codec', id: 'codec-1', mimeType: 'video/H264'}],- ['inbound-1', {type: 'inbound-rtp', id: 'inbound-1', kind: 'video', codecId: 'codec-1', ...inbound}],- ]) as unknown as RTCStatsReport;-}--function buildSample(inbound: Record<string, unknown>) {- const sample = findInboundVideoDecodeSample(buildStats(inbound));- if (!sample) throw new Error('expected an inbound video sample');- return sample;-}--describe('the screen share decode stall detector', () => {- it('calls a stream that never decoded a keyframe a stall', () => {- const stall = findStalledVideoDecoder(- buildSample({framesDecoded: 0, keyFramesDecoded: 0, framesReceived: 6, framesDropped: 6}),- );- expect(stall?.codec).toBe('h264');- });-- it('refuses to call a stream that decoded and then froze a stall', () => {- expect(- findStalledVideoDecoder(- buildSample({framesDecoded: 240, keyFramesDecoded: 2, framesReceived: 260, framesDropped: 20}),- ),- ).toBeNull();- });-- it('refuses to call anything a stall when the stats report no keyframe counter', () => {- expect(findStalledVideoDecoder(buildSample({framesDecoded: 0, framesReceived: 6, framesDropped: 6}))).toBeNull();- });-});--describe('the baseline decode floor', () => {- afterEach(() => {- resetVideoDecoderExclusions();- });-- it('never withdraws a codec every WebRTC endpoint is required to decode', () => {- expect(markScreenShareDecodeFailure('h264', 'test')).toBe(false);- expect(markScreenShareDecodeFailure('vp8', 'test')).toBe(false);- });-- it('still withdraws an optional codec', () => {- expect(markScreenShareDecodeFailure('av1', 'test')).toBe(true);- });-});diff --git a/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.ts b/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.tsdeleted file mode 100644index 19b350441..000000000--- a/fluxer_app/src/features/voice/utils/ScreenShareOptions.test.ts+++ /dev/null@@ -1,119 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- buildScreenShareOptions,- resolveScreenShareDegradationPreference,- resolveScreenShareLayering,- resolveScreenShareTarget,-} from '@app/features/voice/utils/ScreenShareOptions';-import {describe, expect, it, vi} from 'vitest';--vi.mock('@app/features/voice/utils/NativeAudioCaptureBridge', () => ({- rememberCapturedDisplayAudioTrack: () => undefined,-}));-vi.mock('@app/features/voice/engine/voice_screen_share_manager/shared', () => ({- stopMediaTrack: () => undefined,- stopUnselectedStreamTracks: () => undefined,-}));--const {getDisplayMediaOptions} = await import(- '@app/features/voice/engine/voice_screen_share_manager/DisplayMediaCapture'-);--function collectKeys(value: unknown, keys: Set<string>): Set<string> {- if (typeof value !== 'object' || value === null) return keys;- for (const [key, entry] of Object.entries(value)) {- keys.add(key);- collectKeys(entry, keys);- }- return keys;-}--function targetOf(overrides: {mode?: 'gaming' | 'screenshare' | 'custom'; softwareEncoderClamp?: boolean} = {}) {- return resolveScreenShareTarget({- mode: overrides.mode ?? 'screenshare',- storedResolution: 'medium',- storedFrameRate: 30,- entitled: true,- context: 'display',- sourceDimensions: null,- hintSetting: 'auto',- bitrate: {ceilingBps: 9_000_000, chosenBps: null},- ...(overrides.softwareEncoderClamp === undefined ? {} : {softwareEncoderClamp: overrides.softwareEncoderClamp}),- });-}--describe('screen share layering', () => {- it('never asks for temporal layers on the codecs livekit forwards without a dependency descriptor', () => {- for (const codec of ['h264', 'vp8'] as const) {- expect(resolveScreenShareLayering({codec, svcSetting: 'auto'}).scalabilityMode).toBeUndefined();- expect(resolveScreenShareLayering({codec, svcSetting: 'temporal'}).scalabilityMode).toBeUndefined();- }- });-- it('keeps temporal layers for the SVC codecs that have one', () => {- for (const codec of ['av1', 'vp9'] as const) {- expect(resolveScreenShareLayering({codec, svcSetting: 'auto'}).scalabilityMode).toBe('L1T3');- }- });-});--describe('display capture constraints', () => {- it('asks for no min and no exact, which getDisplayMedia rejects before the picker runs', () => {- const {captureOptions} = buildScreenShareOptions({- resolution: 'high',- frameRate: 60,- maxBitrate: 6_000_000,- context: 'display',- includeAudio: true,- contentHint: 'text',- sourceDimensions: {width: 3840, height: 2160},- preferredDisplaySurface: 'monitor',- });- const keys = collectKeys(getDisplayMediaOptions(captureOptions).video, new Set<string>());- expect(keys.has('min')).toBe(false);- expect(keys.has('exact')).toBe(false);- });-});--describe('screen share quality', () => {- it('applies the software H.264 clamp', () => {- expect(targetOf({mode: 'gaming', softwareEncoderClamp: true})).toMatchObject({- resolution: 'medium',- frameRate: 30,- softwareEncoderClamped: true,- });- });-});--describe('screen share degradation preference', () => {- it('keeps device shares balanced', () => {- expect(- resolveScreenShareDegradationPreference({- context: 'device',- rung: 'medium',- contentHint: undefined,- maxBitrate: 3_000_000,- }),- ).toBe('balanced');- });-- it('refuses maintain-framerate below the initial frame dropper cliff', () => {- expect(- resolveScreenShareDegradationPreference({- context: 'display',- rung: 'low_240p',- contentHint: undefined,- maxBitrate: 300_000,- }),- ).toBe('maintain-resolution');- expect(- resolveScreenShareDegradationPreference({- context: 'display',- rung: 'medium',- contentHint: undefined,- maxBitrate: 3_000_000,- }),- ).toBe('maintain-framerate');- });-});diff --git a/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.ts b/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.tsdeleted file mode 100644index 0009faa0a..000000000--- a/fluxer_app/src/features/voice/utils/StreamSettingsUpdatePolicy.test.ts+++ /dev/null@@ -1,55 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {canSelectWindowsDesktopAudioSource} from '@app/features/voice/utils/StreamSettingsUpdatePolicy';-import type {NativeAudioAvailability} from '@app/types/electron.d';-import {describe, expect, it} from 'vitest';--const withEndpointSelect: NativeAudioAvailability = {- available: true,- backend: 'windows-wasapi-loopback',- capabilities: {process: true, system: true, systemExcludesSelf: true, sessionMixer: true, endpointSelect: true},-};-const withoutEndpointSelect: NativeAudioAvailability = {- available: true,- backend: 'windows-wasapi-loopback',- capabilities: {process: true, system: true, systemExcludesSelf: true},-};--describe('canSelectWindowsDesktopAudioSource', () => {- it('offers device selection for Windows entire-screen shares', () => {- expect(- canSelectWindowsDesktopAudioSource({- platform: 'win32',- shareContext: 'display',- nativeAudioAvailability: withEndpointSelect,- }),- ).toBe(true);- });-- it('hides device selection elsewhere', () => {- expect(- canSelectWindowsDesktopAudioSource({- platform: 'darwin',- shareContext: 'display',- nativeAudioAvailability: withEndpointSelect,- }),- ).toBe(false);- expect(- canSelectWindowsDesktopAudioSource({- platform: 'win32',- shareContext: 'app',- nativeAudioAvailability: withEndpointSelect,- }),- ).toBe(false);- expect(- canSelectWindowsDesktopAudioSource({- platform: 'win32',- shareContext: 'display',- nativeAudioAvailability: withoutEndpointSelect,- }),- ).toBe(false);- expect(- canSelectWindowsDesktopAudioSource({platform: 'win32', shareContext: 'display', nativeAudioAvailability: null}),- ).toBe(false);- });-});diff --git a/fluxer_app/src/features/voice/utils/VoiceMessageDescriptors.test.ts b/fluxer_app/src/features/voice/utils/VoiceMessageDescriptors.test.tsdeleted file mode 100644index e25a4384a..000000000--- a/fluxer_app/src/features/voice/utils/VoiceMessageDescriptors.test.ts+++ /dev/null@@ -1,147 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {GpuInfo} from '@app/types/electron.d';-import type {MessageDescriptor} from '@lingui/core';-import type {VideoCodec} from 'livekit-client';-import {afterEach, describe, expect, it, vi} from 'vitest';--vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));--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 {- ENCODE_PROBE_VIDEO_CONFIG,- H264_ENCODE_PROBE_CONTENT_TYPES,- probeWebRtcEncodeEfficiency,- reconcileHardwareEncodeReport,- reportFromGpuInfo,-} = await import('@app/features/voice/utils/GpuEncoderCapabilities');--const RTX_5090_GPU_INFO: GpuInfo = {- devices: [{active: true, vendorId: 0x10de, deviceId: 0x2b85, vendorName: 'NVIDIA', deviceString: 'RTX 5090'}],- glRenderer: 'ANGLE (NVIDIA, NVIDIA GeForce RTX 5090 Direct3D11 vs_5_0 ps_5_0, D3D11)',-};--const CHROMIUM_HARDWARE_H264_PROFILES: ReadonlySet<string> = new Set(['6400', '4d00', '4200']);--const h264ProfileLevelId = (contentType: string): string =>- /profile-level-id=([0-9a-f]{6})/.exec(contentType)?.[1] ?? '';--function stubChromiumEncodingInfo(hardwareCodecs: ReadonlySet<string>): Array<string> {- const asked: Array<string> = [];- vi.stubGlobal('navigator', {- mediaCapabilities: {- encodingInfo: async ({video}: {video: {contentType: string}}) => {- asked.push(video.contentType);- if (video.contentType.startsWith('video/H264')) {- const profile = h264ProfileLevelId(video.contentType).slice(0, 4);- return {- supported: true,- powerEfficient: hardwareCodecs.has('h264') && CHROMIUM_HARDWARE_H264_PROFILES.has(profile),- };- }- const codec = video.contentType.slice('video/'.length).toLowerCase();- if (codec === 'h265' && !hardwareCodecs.has('h265')) return {supported: false, powerEfficient: false};- return {supported: true, powerEfficient: hardwareCodecs.has(codec)};- },- },- });- return asked;-}--afterEach(() => {- vi.unstubAllGlobals();-});--describe('WebRTC hardware encode probe', () => {- it('keeps every probed H.264 level high enough for the resolution the probe asks about', () => {- const macroblocks =- Math.ceil(ENCODE_PROBE_VIDEO_CONFIG.width / 16) * Math.ceil(ENCODE_PROBE_VIDEO_CONFIG.height / 16);- expect(macroblocks).toBeLessThanOrEqual(8192);- expect(macroblocks * ENCODE_PROBE_VIDEO_CONFIG.framerate).toBeLessThanOrEqual(245_760);- for (const contentType of H264_ENCODE_PROBE_CONTENT_TYPES) {- expect(Number.parseInt(h264ProfileLevelId(contentType).slice(4), 16)).toBeGreaterThanOrEqual(0x28);- }- });-- it('reads H.264 as hardware on a Chromium that only accelerates the unconstrained profiles', async () => {- const asked = stubChromiumEncodingInfo(new Set<string>(['h264', 'h265']));- await expect(probeWebRtcEncodeEfficiency()).resolves.toEqual({- av1: 'software',- h265: 'hardware',- h264: 'hardware',- vp9: 'software',- vp8: 'software',- });- expect(asked).toContain(H264_ENCODE_PROBE_CONTENT_TYPES[0]);- expect(asked).not.toContain('video/H264;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f');- });-- it('reads a codec Chromium cannot encode at all as unknown, not as software', async () => {- stubChromiumEncodingInfo(new Set<string>(['h264']));- await expect(probeWebRtcEncodeEfficiency()).resolves.toMatchObject({h265: 'unknown'});- });-- it('returns nothing when the browser has no encodingInfo to ask', async () => {- vi.stubGlobal('navigator', {});- await expect(probeWebRtcEncodeEfficiency()).resolves.toBeNull();- });-});--describe('reconcileHardwareEncodeReport', () => {- const table = (): ReturnType<typeof reportFromGpuInfo> => reportFromGpuInfo(RTX_5090_GPU_INFO);- const probe = (overrides: Partial<Record<VideoCodec, 'hardware' | 'software' | 'unknown'>>) => ({- av1: 'unknown' as const,- h265: 'unknown' as const,- h264: 'unknown' as const,- vp9: 'unknown' as const,- vp8: 'unknown' as const,- ...overrides,- });-- it('classifies an RTX 5090 from its PCI id before any probe runs', () => {- expect(table().gpuFamily).toBe('nvidia-ada-or-blackwell');- expect(table().h264).toBe('hardware');- });-- it('takes the probe answer over the GPU table for every codec', () => {- expect(- reconcileHardwareEncodeReport(- table(),- probe({av1: 'software', h265: 'software', h264: 'hardware', vp9: 'hardware'}),- ),- ).toMatchObject({av1: 'software', h265: 'software', h264: 'hardware', vp9: 'hardware'});- });-- it('keeps the GPU table answer where the probe says unknown', () => {- expect(reconcileHardwareEncodeReport(table(), probe({}))).toMatchObject({- av1: 'hardware',- h265: 'hardware',- h264: 'hardware',- vp9: 'software',- vp8: 'software',- });- });-- it('keeps the GPU table when the probe could not run', () => {- expect(reconcileHardwareEncodeReport(table(), null)).toEqual(table());- });-- it('answers hardware H.264 end to end for an RTX 5090 behind a Chromium that refuses constrained baseline', async () => {- stubChromiumEncodingInfo(new Set<string>(['h264', 'h265', 'av1']));- const efficiency = await probeWebRtcEncodeEfficiency();- expect(reconcileHardwareEncodeReport(table(), efficiency)).toMatchObject({- av1: 'hardware',- h265: 'hardware',- h264: 'hardware',- });- });-});diff --git a/fluxer_app/src/features/voice/utils/VoiceTtsUtils.test.ts b/fluxer_app/src/features/voice/utils/VoiceTtsUtils.test.tsdeleted file mode 100644index 370bd0c8c..000000000--- a/fluxer_app/src/features/voice/utils/VoiceTtsUtils.test.ts+++ /dev/null@@ -1,217 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later-// @vitest-environment happy-dom--import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';-import type {Message} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';--const ME = '100';-const OTHER = '200';-const SELECTED_CHANNEL = '1000';-const THREAD_CHANNEL = '2000';-const OTHER_CHANNEL = '3000';--const state = {- enableTTSCommand: true,- selfDeaf: false,- navigationChannelId: null as string | null,- selectedChannelId: SELECTED_CHANNEL as string | null,- threadId: null as string | null,- mutedChannelIds: new Set<string>(),-};--const speak = vi.fn();--vi.mock('@lingui/core/macro', () => ({- msg: (descriptor: unknown) => descriptor,- t: (descriptor: unknown) => descriptor,-}));--vi.mock('@lingui/react/macro', () => ({- Trans: () => null,- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}),-}));--vi.mock('@app/features/voice/utils/TtsSpeechUtils', () => ({- nativeApiPresent: () => true,- nativeHasVoices: () => true,- resumeNative: vi.fn(),- cancel: vi.fn(),- speak: (utterance: {text: string}) => speak(utterance.text),- createUtterances: (text: string) => [{text}],- getVoices: () => [],- selectPreferredVoice: () => null,-}));--vi.mock('@app/features/ui/utils/NativeUtils', async (importOriginal) => ({- ...(await importOriginal<typeof import('@app/features/ui/utils/NativeUtils')>()),- getNativePlatformSync: () => 'web',-}));--vi.mock('@app/features/navigation/state/Navigation', () => ({- default: {- get channelId() {- return state.navigationChannelId;- },- get threadId() {- return state.threadId;- },- },-}));--vi.mock('@app/features/accessibility/state/Accessibility', () => ({- default: {- get enableTTSCommand() {- return state.enableTTSCommand;- },- ttsRate: 1,- },-}));--vi.mock('@app/features/auth/state/Authentication', () => ({default: {currentUserId: ME}}));--vi.mock('@app/features/navigation/state/SelectedChannel', () => ({- default: {- get currentChannelId() {- return state.selectedChannelId;- },- },-}));--vi.mock('@app/features/relationship/state/Relationships', () => ({default: {isBlocked: () => false}}));--vi.mock('@app/features/channel/state/Channels', () => ({- default: {getChannel: (id: string) => ({id, guildId: '1'})},-}));--vi.mock('@app/features/user/state/UserGuildSettings', () => ({- default: {- isGuildOrChannelMuted: (_guildId: string | null, channelId: string) => state.mutedChannelIds.has(channelId),- isParentCategoryMuted: () => false,- },-}));--vi.mock('@app/features/user/state/UserSettings', () => ({default: {locale: 'en-US'}}));-vi.mock('@app/features/user/state/Users', () => ({default: {getUser: (id: string) => ({id})}}));-vi.mock('@app/features/user/utils/NicknameUtils', () => ({getNickname: (user: {id: string}) => user.id}));-vi.mock('@app/features/voice/utils/TtsTextFormatter', () => ({formatMessageForTts: (content: string) => content}));-vi.mock('@app/features/messaging/state/MessageReferences', () => ({- default: {getMessageReference: () => ({state: 0})},- MessageReferenceState: {LOADED: 1},-}));-vi.mock('@app/features/messaging/utils/SystemMessageUtils', () => ({- SystemMessageUtils: {stringify: () => 'system'},-}));--Object.defineProperty(window, 'speechSynthesis', {- configurable: true,- value: {addEventListener: vi.fn(), removeEventListener: vi.fn()},-});--const {default: LocalVoiceState} = await import('@app/features/voice/state/LocalVoiceState');-vi.spyOn(LocalVoiceState, 'getSelfDeaf').mockImplementation(() => state.selfDeaf);-const {default: Notification, TTSNotificationMode} = await import('@app/features/ui/state/Notification');-const {default: TtsUtils} = await import('@app/features/voice/utils/VoiceTtsUtils');--let nextId = 1;--function message(overrides: {channelId?: string; authorId?: string; tts?: boolean; type?: number}): Message {- return {- id: String(nextId++),- channel_id: overrides.channelId ?? SELECTED_CHANNEL,- author: {id: overrides.authorId ?? OTHER},- type: overrides.type ?? MessageTypes.DEFAULT,- tts: overrides.tts ?? false,- content: 'hello',- } as unknown as Message;-}--function spoken(input: Parameters<typeof message>[0]): boolean {- speak.mockClear();- TtsUtils.handleIncomingTtsMessage(message(input));- return speak.mock.calls.length > 0;-}--describe('incoming message text-to-speech gate', () => {- beforeEach(() => {- Notification.setTTSNotificationMode(TTSNotificationMode.NEVER);- state.navigationChannelId = null;- state.enableTTSCommand = true;- state.selfDeaf = false;- state.selectedChannelId = SELECTED_CHANNEL;- state.threadId = null;- state.mutedChannelIds = new Set();- });-- afterEach(() => {- TtsUtils.dispose();- });-- it('keeps /tts from a channel you are not viewing silent when narration is off', () => {- expect(spoken({channelId: OTHER_CHANNEL, tts: true})).toBe(false);- });-- it('speaks /tts in the selected channel when narration is off', () => {- expect(spoken({tts: true})).toBe(true);- });-- it('speaks /tts in the thread open in the side panel when narration is off', () => {- state.threadId = THREAD_CHANNEL;- expect(spoken({channelId: THREAD_CHANNEL, tts: true})).toBe(true);- });-- it('follows the routed channel over a stale selected channel', () => {- state.navigationChannelId = OTHER_CHANNEL;- expect(spoken({channelId: OTHER_CHANNEL, tts: true})).toBe(true);- expect(spoken({tts: true})).toBe(false);- });-- it('speaks your own /tts in the selected channel', () => {- expect(spoken({authorId: ME, tts: true})).toBe(true);- });-- it('keeps /tts silent when /tts playback is disabled', () => {- state.enableTTSCommand = false;- expect(spoken({tts: true})).toBe(false);- });-- it('does not narrate your own plain messages', () => {- Notification.setTTSNotificationMode(TTSNotificationMode.FOR_ALL_CHANNELS);- expect(spoken({authorId: ME})).toBe(false);- });-- it('does not narrate your own system messages', () => {- Notification.setTTSNotificationMode(TTSNotificationMode.FOR_ALL_CHANNELS);- expect(spoken({authorId: ME, type: MessageTypes.CHANNEL_PINNED_MESSAGE})).toBe(false);- });-- it('narrates other channels only in every-channel mode', () => {- Notification.setTTSNotificationMode(TTSNotificationMode.FOR_ALL_CHANNELS);- expect(spoken({channelId: OTHER_CHANNEL})).toBe(true);- Notification.setTTSNotificationMode(TTSNotificationMode.FOR_CURRENT_CHANNEL);- expect(spoken({channelId: OTHER_CHANNEL})).toBe(false);- });-- it('narrates the side-panel thread in current-channel mode', () => {- Notification.setTTSNotificationMode(TTSNotificationMode.FOR_CURRENT_CHANNEL);- state.threadId = THREAD_CHANNEL;- expect(spoken({channelId: THREAD_CHANNEL})).toBe(true);- });-- it('stays silent in every mode while self-deafened', () => {- state.selfDeaf = true;- for (const mode of [- TTSNotificationMode.NEVER,- TTSNotificationMode.FOR_CURRENT_CHANNEL,- TTSNotificationMode.FOR_ALL_CHANNELS,- ]) {- Notification.setTTSNotificationMode(mode);- expect(spoken({tts: true})).toBe(false);- }- });-- it('stays silent in a muted channel', () => {- state.mutedChannelIds.add(SELECTED_CHANNEL);- expect(spoken({tts: true})).toBe(false);- });-});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.tsdeleted file mode 100644index db5298d9e..000000000--- a/fluxer_app/src/features/voice/utils/native_audio_capture_bridge/shared.test.ts+++ /dev/null@@ -1,56 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- selectWindowsDesktopAudioStart,- windowsEndpointsEqual,-} from '@app/features/voice/utils/native_audio_capture_bridge/shared';-import type {NativeAudioAvailability} from '@app/types/electron.d';-import {describe, expect, it} from 'vitest';--const withEndpointSelect: NativeAudioAvailability = {- available: true,- backend: 'windows-wasapi-loopback',- capabilities: {process: true, system: true, systemExcludesSelf: true, sessionMixer: true, endpointSelect: true},-};-const withoutEndpointSelect: NativeAudioAvailability = {- available: true,- backend: 'windows-wasapi-loopback',- capabilities: {process: true, system: true, systemExcludesSelf: true},-};--describe('selectWindowsDesktopAudioStart', () => {- it('keeps entire system audio when the shell cannot pick devices', () => {- expect(selectWindowsDesktopAudioStart({all: false, devices: ['default']}, withoutEndpointSelect)).toEqual({- winCaptureScope: 'system',- });- expect(selectWindowsDesktopAudioStart({all: false, devices: ['default']}, null)).toEqual({- winCaptureScope: 'system',- });- });-- it('keeps entire system audio when the user asked for it', () => {- expect(selectWindowsDesktopAudioStart({all: true, devices: ['default']}, withEndpointSelect)).toEqual({- winCaptureScope: 'system',- });- });-- it('limits capture to the chosen playback devices', () => {- expect(- selectWindowsDesktopAudioStart({all: false, devices: ['default', '{speakers}']}, withEndpointSelect),- ).toEqual({- winCaptureScope: 'session-mixer',- winEndpoints: ['default', '{speakers}'],- });- });-});--describe('windowsEndpointsEqual', () => {- it('ignores order', () => {- expect(windowsEndpointsEqual(['default', '{a}'], ['{a}', 'default'])).toBe(true);- });-- it('compares contents and length', () => {- expect(windowsEndpointsEqual(['default'], ['default', '{a}'])).toBe(false);- expect(windowsEndpointsEqual(['default', '{a}'], ['default', '{b}'])).toBe(false);- });-});