Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions apps/desktop/src/__tests__/stores/voiceStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ vi.mock('../../stores/settingsStore', async () => {

import { useVoiceStore, isMicProducer, registerShareMaskHooks } from '../../stores/voiceStore';
import { useSettingsStore } from '../../stores/settingsStore';
import { toast } from '../../stores/toastStore';
import i18n from '../../i18n';
import { getSocket, onSocketReconnect } from '../../services/socket';
import type { VoiceUser } from '@voxium/shared';

Expand Down Expand Up @@ -1239,6 +1241,142 @@ describe('voiceStore', () => {
expect(useVoiceStore.getState().dmCallUsers).toHaveLength(1); // no duplicate entry
});

describe('a direct call whose peer connection fails', () => {
const toldCount = () => toastError.mock.calls.length;
const failPeer = async (opts: { connectedFirst?: boolean } = {}) => {
useVoiceStore.getState().createDMPeer('peer-x', true);
await flushAsync();
const pc = FakeRTCPeerConnection.instances[FakeRTCPeerConnection.instances.length - 1];
const handler = pc.onconnectionstatechange;
if (opts.connectedFirst) {
pc.connectionState = 'connected';
handler?.();
}
pc.connectionState = 'failed';
handler?.();
return { pc, handler };
};
const toldKeys = () => toastError.mock.calls.map((c: unknown[]) => c[0] as string);
const FAILED = () => i18n.t('e2e.callConnectFailed');
const LOST = () => i18n.t('e2e.callConnectionLost');
let toastError: ReturnType<typeof vi.spyOn>;
let consoleError: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
useVoiceStore.getState().setLocalUserId('me');
useVoiceStore.setState({ dmCallConversationId: 'conv-1', dmCallPeerDevice: PEER });
toastError = vi.spyOn(toast, 'error').mockImplementation(() => undefined as never);
consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
});
afterEach(() => {
toastError.mockRestore();
consoleError.mockRestore();
});

it('says once that the call could not connect, and still destroys the peer and logs', async () => {
const { pc } = await failPeer();

expect(toldKeys()).toEqual([FAILED()]);
expect(FAILED()).not.toBe('e2e.callConnectFailed'); // a real sentence, not the raw key
expect(LOST()).not.toBe('e2e.callConnectionLost');
expect(FAILED()).not.toBe(LOST());
expect(pc.close).toHaveBeenCalled();
expect(useVoiceStore.getState().peers.size).toBe(0);
expect(consoleError.mock.calls.flat().map(String).join('\n')).toMatch(
/\[DMVoice\] Connection failed permanently with peer-x/
);
});

it('says nothing more when the peer is made again and fails again in the same call', async () => {
await failPeer();
await failPeer();

expect(toldCount()).toBe(1);
expect(useVoiceStore.getState().peers.size).toBe(0); // the second one was destroyed too
});

it('says it again for a new call', async () => {
await failPeer();
useVoiceStore.getState().leaveDMCall();
useVoiceStore.setState({ dmCallConversationId: 'conv-1', dmCallPeerDevice: PEER });
await failPeer();

expect(toldCount()).toBe(2);
});

it('says the connection was lost, not that it could not connect, for a peer that had connected', async () => {
await failPeer({ connectedFirst: true });

expect(toldKeys()).toEqual([LOST()]);
expect(useVoiceStore.getState().peers.size).toBe(0);
});

it('says each sentence at most once in a call', async () => {
await failPeer({ connectedFirst: true });
await failPeer({ connectedFirst: true });
await failPeer();
await failPeer();

expect(toldKeys()).toEqual([LOST(), FAILED()]);
});

it('says one of each when the first peer never connected and the peer made again connects and drops', async () => {
await failPeer();
await failPeer({ connectedFirst: true });

expect(toldKeys()).toEqual([FAILED(), LOST()]);
});

it('starts fresh in a new call, for both sentences', async () => {
await failPeer();
await failPeer({ connectedFirst: true });
useVoiceStore.getState().leaveDMCall();
useVoiceStore.setState({ dmCallConversationId: 'conv-1', dmCallPeerDevice: PEER });
await failPeer({ connectedFirst: true });
await failPeer();

expect(toldKeys()).toEqual([FAILED(), LOST(), LOST(), FAILED()]);
});

it('says nothing for a call that is ending', async () => {
useVoiceStore.getState().createDMPeer('peer-x', true);
await flushAsync();
const pc = FakeRTCPeerConnection.instances[FakeRTCPeerConnection.instances.length - 1];
const handler = pc.onconnectionstatechange;
useVoiceStore.getState().leaveDMCall();
pc.connectionState = 'failed';
handler?.(); // a late event of a connection the end already closed

expect(toldCount()).toBe(0);
});

it('says nothing when no direct call is up (a space voice session)', async () => {
useVoiceStore.getState().createDMPeer('peer-x', true);
await flushAsync();
const pc = FakeRTCPeerConnection.instances[FakeRTCPeerConnection.instances.length - 1];
useVoiceStore.setState({ dmCallConversationId: null, activeChannelId: 'ch-ok' });
pc.connectionState = 'failed';
pc.onconnectionstatechange?.();

expect(toldCount()).toBe(0);
expect(useVoiceStore.getState().peers.size).toBe(0); // the teardown is unchanged
});

it('says nothing for a peer that was already replaced', async () => {
useVoiceStore.getState().createDMPeer('peer-x', true);
await flushAsync();
const old = FakeRTCPeerConnection.instances[FakeRTCPeerConnection.instances.length - 1];
const staleHandler = old.onconnectionstatechange;
useVoiceStore.setState({
peers: new Map([['peer-x', { pc: { close: vi.fn() } as unknown as RTCPeerConnection, makingOffer: false, pendingCandidates: [] }]]),
});
old.connectionState = 'failed';
staleHandler?.();

expect(toldCount()).toBe(0);
});
});

it('drops signals from anyone who is not the pinned call peer', async () => {
useVoiceStore.getState().setLocalUserId('me');
useVoiceStore.setState({ dmCallConversationId: 'conv-1', dmCallPeerDevice: PEER });
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -1858,7 +1858,9 @@
"callAbortPeerMustUpdate": "انتهت المكالمة: تطبيق {{name}} لا يدعم المكالمات الآمنة. اطلب منه تحديث Voxium.",
"callAbortPeerNotE2E": "انتهت المكالمة: لم يقم {{name}} بإعداد التشفير بعد، لذا يتعذّر إجراء مكالمة آمنة.",
"callAbortSignalingFailed": "انتهت المكالمة: فشل إنشاء المكالمة الآمنة. حاول مجددًا.",
"callNotReady": "يتعذّر بدء مكالمة آمنة بعد — لا يزال التشفير قيد الإعداد على هذا الجهاز. حاول مجددًا بعد قليل."
"callNotReady": "يتعذّر بدء مكالمة آمنة بعد — لا يزال التشفير قيد الإعداد على هذا الجهاز. حاول مجددًا بعد قليل.",
"callConnectFailed": "تعذّر إتمام المكالمة: لم يتمكن الجهازان من إنشاء اتصال مباشر.",
"callConnectionLost": "انقطع اتصال المكالمة. أنهِ المكالمة وابدأها من جديد."
},
"people": {
"title": "الأعضاء",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -1846,7 +1846,9 @@
"callAbortPeerMustUpdate": "Anruf beendet: Die App von {{name}} unterstützt keine sicheren Anrufe. Bitte um ein Update von Voxium.",
"callAbortPeerNotE2E": "Anruf beendet: {{name}} hat die Verschlüsselung noch nicht eingerichtet, daher kann kein sicherer Anruf aufgebaut werden.",
"callAbortSignalingFailed": "Anruf beendet: Der sichere Verbindungsaufbau ist fehlgeschlagen. Versuche es erneut.",
"callNotReady": "Ein sicherer Anruf ist noch nicht möglich — die Verschlüsselung wird auf diesem Gerät noch eingerichtet. Versuche es gleich erneut."
"callNotReady": "Ein sicherer Anruf ist noch nicht möglich — die Verschlüsselung wird auf diesem Gerät noch eingerichtet. Versuche es gleich erneut.",
"callConnectFailed": "Der Anruf konnte nicht verbunden werden: Die beiden Geräte konnten keine direkte Verbindung aufbauen.",
"callConnectionLost": "Die Verbindung des Anrufs ist abgebrochen. Beende den Anruf und starte ihn erneut."
},
"people": {
"title": "Personen",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1799,7 +1799,9 @@
"callAbortPeerMustUpdate": "Call ended: {{name}}'s app can't make secure calls. Ask them to update Voxium.",
"callAbortPeerNotE2E": "Call ended: {{name}} hasn't set up encryption yet, so a secure call can't be established.",
"callAbortSignalingFailed": "Call ended: secure call setup failed. Try again.",
"callNotReady": "Can't start a secure call yet — encryption is still setting up on this device. Try again in a moment."
"callNotReady": "Can't start a secure call yet — encryption is still setting up on this device. Try again in a moment.",
"callConnectFailed": "The call could not connect: the two devices could not set up a direct connection.",
"callConnectionLost": "The call lost its connection. End the call and start it again."
},
"people": {
"title": "People",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1846,7 +1846,9 @@
"callAbortPeerMustUpdate": "Llamada finalizada: la aplicación de {{name}} no puede hacer llamadas seguras. Pídele que actualice Voxium.",
"callAbortPeerNotE2E": "Llamada finalizada: {{name}} aún no ha configurado el cifrado, así que no se puede establecer una llamada segura.",
"callAbortSignalingFailed": "Llamada finalizada: falló el establecimiento de la llamada segura. Inténtalo de nuevo.",
"callNotReady": "Aún no se puede iniciar una llamada segura: el cifrado todavía se está configurando en este dispositivo. Inténtalo de nuevo en un momento."
"callNotReady": "Aún no se puede iniciar una llamada segura: el cifrado todavía se está configurando en este dispositivo. Inténtalo de nuevo en un momento.",
"callConnectFailed": "No se pudo establecer la llamada: los dos dispositivos no pudieron establecer una conexión directa.",
"callConnectionLost": "La llamada perdió la conexión. Finaliza la llamada y vuelve a iniciarla."
},
"people": {
"title": "Personas",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1846,7 +1846,9 @@
"callAbortPeerMustUpdate": "Appel terminé : l’application de {{name}} ne peut pas passer d’appels sécurisés. Demandez-lui de mettre à jour Voxium.",
"callAbortPeerNotE2E": "Appel terminé : {{name}} n’a pas encore configuré le chiffrement, impossible d’établir un appel sécurisé.",
"callAbortSignalingFailed": "Appel terminé : l’établissement de l’appel sécurisé a échoué. Réessayez.",
"callNotReady": "Impossible de passer un appel sécurisé pour l’instant — le chiffrement est encore en cours de configuration sur cet appareil. Réessayez dans un instant."
"callNotReady": "Impossible de passer un appel sécurisé pour l’instant — le chiffrement est encore en cours de configuration sur cet appareil. Réessayez dans un instant.",
"callConnectFailed": "L’appel n’a pas pu aboutir : les deux appareils n’ont pas pu établir de connexion directe.",
"callConnectionLost": "L’appel a perdu sa connexion. Terminez l’appel et lancez-le de nouveau."
},
"people": {
"title": "Membres",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,9 @@
"callAbortPeerMustUpdate": "通話終了:{{name}}のアプリは安全な通話に対応していません。Voxiumの更新を依頼してください。",
"callAbortPeerNotE2E": "通話終了:{{name}}はまだ暗号化を設定していないため、安全な通話を確立できません。",
"callAbortSignalingFailed": "通話終了:安全な通話の確立に失敗しました。もう一度お試しください。",
"callNotReady": "安全な通話をまだ開始できません — このデバイスで暗号化の設定が進行中です。しばらくしてからもう一度お試しください。"
"callNotReady": "安全な通話をまだ開始できません — このデバイスで暗号化の設定が進行中です。しばらくしてからもう一度お試しください。",
"callConnectFailed": "通話を接続できませんでした。2台のデバイス間で直接接続を確立できませんでした。",
"callConnectionLost": "通話の接続が切れました。通話を終了して、もう一度開始してください。"
},
"people": {
"title": "メンバー",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,9 @@
"callAbortPeerMustUpdate": "통화 종료: {{name}}님의 앱이 보안 통화를 지원하지 않습니다. Voxium 업데이트를 요청하세요.",
"callAbortPeerNotE2E": "통화 종료: {{name}}님이 아직 암호화를 설정하지 않아 보안 통화를 연결할 수 없습니다.",
"callAbortSignalingFailed": "통화 종료: 보안 통화 연결에 실패했습니다. 다시 시도하세요.",
"callNotReady": "아직 보안 통화를 시작할 수 없습니다. 이 기기에서 암호화를 설정하는 중입니다. 잠시 후 다시 시도하세요."
"callNotReady": "아직 보안 통화를 시작할 수 없습니다. 이 기기에서 암호화를 설정하는 중입니다. 잠시 후 다시 시도하세요.",
"callConnectFailed": "통화를 연결할 수 없습니다. 두 기기가 직접 연결을 설정하지 못했습니다.",
"callConnectionLost": "통화 연결이 끊어졌습니다. 통화를 종료한 후 다시 시작하세요."
},
"people": {
"title": "사람",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -1846,7 +1846,9 @@
"callAbortPeerMustUpdate": "Chamada encerrada: o aplicativo de {{name}} não consegue fazer chamadas seguras. Peça para atualizar o Voxium.",
"callAbortPeerNotE2E": "Chamada encerrada: {{name}} ainda não configurou a criptografia, então não é possível estabelecer uma chamada segura.",
"callAbortSignalingFailed": "Chamada encerrada: falha ao estabelecer a chamada segura. Tente novamente.",
"callNotReady": "Ainda não é possível iniciar uma chamada segura — a criptografia ainda está sendo configurada neste dispositivo. Tente novamente em instantes."
"callNotReady": "Ainda não é possível iniciar uma chamada segura — a criptografia ainda está sendo configurada neste dispositivo. Tente novamente em instantes.",
"callConnectFailed": "Não foi possível estabelecer a chamada: os dois dispositivos não conseguiram estabelecer uma conexão direta.",
"callConnectionLost": "A chamada perdeu a conexão. Encerre a chamada e inicie-a novamente."
},
"people": {
"title": "Pessoas",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -1852,7 +1852,9 @@
"callAbortPeerMustUpdate": "Звонок завершён: приложение {{name}} не поддерживает защищённые звонки. Попросите обновить Voxium.",
"callAbortPeerNotE2E": "Звонок завершён: {{name}} ещё не настроил(а) шифрование, поэтому защищённый звонок невозможен.",
"callAbortSignalingFailed": "Звонок завершён: не удалось установить защищённое соединение. Попробуйте ещё раз.",
"callNotReady": "Пока нельзя начать защищённый звонок — шифрование ещё настраивается на этом устройстве. Повторите попытку через мгновение."
"callNotReady": "Пока нельзя начать защищённый звонок — шифрование ещё настраивается на этом устройстве. Повторите попытку через мгновение.",
"callConnectFailed": "Не удалось установить звонок: два устройства не смогли установить прямое соединение.",
"callConnectionLost": "Соединение звонка потеряно. Завершите звонок и начните его заново."
},
"people": {
"title": "Участники",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/uk.json
Original file line number Diff line number Diff line change
Expand Up @@ -1852,7 +1852,9 @@
"callAbortPeerMustUpdate": "Дзвінок завершено: застосунок {{name}} не підтримує захищені дзвінки. Попросіть оновити Voxium.",
"callAbortPeerNotE2E": "Дзвінок завершено: {{name}} ще не налаштував(-ла) шифрування, тому захищений дзвінок неможливий.",
"callAbortSignalingFailed": "Дзвінок завершено: не вдалося встановити захищене з'єднання. Спробуйте ще раз.",
"callNotReady": "Поки що неможливо розпочати захищений дзвінок — шифрування ще налаштовується на цьому пристрої. Спробуйте ще раз за мить."
"callNotReady": "Поки що неможливо розпочати захищений дзвінок — шифрування ще налаштовується на цьому пристрої. Спробуйте ще раз за мить.",
"callConnectFailed": "Не вдалося встановити дзвінок: два пристрої не змогли встановити пряме з'єднання.",
"callConnectionLost": "З'єднання дзвінка втрачено. Завершіть дзвінок і почніть його знову."
},
"people": {
"title": "Учасники",
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,9 @@
"callAbortPeerMustUpdate": "通话已结束:{{name}}的应用无法进行安全通话。请对方更新 Voxium。",
"callAbortPeerNotE2E": "通话已结束:{{name}}尚未设置加密,无法建立安全通话。",
"callAbortSignalingFailed": "通话已结束:安全通话建立失败。请重试。",
"callNotReady": "暂时无法发起安全通话——此设备仍在设置加密。请稍后重试。"
"callNotReady": "暂时无法发起安全通话——此设备仍在设置加密。请稍后重试。",
"callConnectFailed": "无法接通通话:两台设备无法建立直接连接。",
"callConnectionLost": "通话已断开连接。请结束通话并重新发起。"
},
"people": {
"title": "成员",
Expand Down
Loading
Loading