diff --git a/apps/desktop/src/__tests__/stores/voiceStore.test.ts b/apps/desktop/src/__tests__/stores/voiceStore.test.ts index 56bd2ce2..0420114d 100644 --- a/apps/desktop/src/__tests__/stores/voiceStore.test.ts +++ b/apps/desktop/src/__tests__/stores/voiceStore.test.ts @@ -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'; @@ -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; + let consoleError: ReturnType; + + 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 }); diff --git a/apps/desktop/src/i18n/locales/ar.json b/apps/desktop/src/i18n/locales/ar.json index 6ad2cced..be2dd5a1 100644 --- a/apps/desktop/src/i18n/locales/ar.json +++ b/apps/desktop/src/i18n/locales/ar.json @@ -1858,7 +1858,9 @@ "callAbortPeerMustUpdate": "انتهت المكالمة: تطبيق {{name}} لا يدعم المكالمات الآمنة. اطلب منه تحديث Voxium.", "callAbortPeerNotE2E": "انتهت المكالمة: لم يقم {{name}} بإعداد التشفير بعد، لذا يتعذّر إجراء مكالمة آمنة.", "callAbortSignalingFailed": "انتهت المكالمة: فشل إنشاء المكالمة الآمنة. حاول مجددًا.", - "callNotReady": "يتعذّر بدء مكالمة آمنة بعد — لا يزال التشفير قيد الإعداد على هذا الجهاز. حاول مجددًا بعد قليل." + "callNotReady": "يتعذّر بدء مكالمة آمنة بعد — لا يزال التشفير قيد الإعداد على هذا الجهاز. حاول مجددًا بعد قليل.", + "callConnectFailed": "تعذّر إتمام المكالمة: لم يتمكن الجهازان من إنشاء اتصال مباشر.", + "callConnectionLost": "انقطع اتصال المكالمة. أنهِ المكالمة وابدأها من جديد." }, "people": { "title": "الأعضاء", diff --git a/apps/desktop/src/i18n/locales/de.json b/apps/desktop/src/i18n/locales/de.json index 676e1b04..b46ba344 100644 --- a/apps/desktop/src/i18n/locales/de.json +++ b/apps/desktop/src/i18n/locales/de.json @@ -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", diff --git a/apps/desktop/src/i18n/locales/en.json b/apps/desktop/src/i18n/locales/en.json index 8f7c29c1..19104dc8 100644 --- a/apps/desktop/src/i18n/locales/en.json +++ b/apps/desktop/src/i18n/locales/en.json @@ -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", diff --git a/apps/desktop/src/i18n/locales/es.json b/apps/desktop/src/i18n/locales/es.json index fa1f8a5f..ca90032c 100644 --- a/apps/desktop/src/i18n/locales/es.json +++ b/apps/desktop/src/i18n/locales/es.json @@ -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", diff --git a/apps/desktop/src/i18n/locales/fr.json b/apps/desktop/src/i18n/locales/fr.json index 585ea04f..5c562473 100644 --- a/apps/desktop/src/i18n/locales/fr.json +++ b/apps/desktop/src/i18n/locales/fr.json @@ -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", diff --git a/apps/desktop/src/i18n/locales/ja.json b/apps/desktop/src/i18n/locales/ja.json index 6bcb9e52..faa956b6 100644 --- a/apps/desktop/src/i18n/locales/ja.json +++ b/apps/desktop/src/i18n/locales/ja.json @@ -1843,7 +1843,9 @@ "callAbortPeerMustUpdate": "通話終了:{{name}}のアプリは安全な通話に対応していません。Voxiumの更新を依頼してください。", "callAbortPeerNotE2E": "通話終了:{{name}}はまだ暗号化を設定していないため、安全な通話を確立できません。", "callAbortSignalingFailed": "通話終了:安全な通話の確立に失敗しました。もう一度お試しください。", - "callNotReady": "安全な通話をまだ開始できません — このデバイスで暗号化の設定が進行中です。しばらくしてからもう一度お試しください。" + "callNotReady": "安全な通話をまだ開始できません — このデバイスで暗号化の設定が進行中です。しばらくしてからもう一度お試しください。", + "callConnectFailed": "通話を接続できませんでした。2台のデバイス間で直接接続を確立できませんでした。", + "callConnectionLost": "通話の接続が切れました。通話を終了して、もう一度開始してください。" }, "people": { "title": "メンバー", diff --git a/apps/desktop/src/i18n/locales/ko.json b/apps/desktop/src/i18n/locales/ko.json index f5a0ce91..a7fad307 100644 --- a/apps/desktop/src/i18n/locales/ko.json +++ b/apps/desktop/src/i18n/locales/ko.json @@ -1843,7 +1843,9 @@ "callAbortPeerMustUpdate": "통화 종료: {{name}}님의 앱이 보안 통화를 지원하지 않습니다. Voxium 업데이트를 요청하세요.", "callAbortPeerNotE2E": "통화 종료: {{name}}님이 아직 암호화를 설정하지 않아 보안 통화를 연결할 수 없습니다.", "callAbortSignalingFailed": "통화 종료: 보안 통화 연결에 실패했습니다. 다시 시도하세요.", - "callNotReady": "아직 보안 통화를 시작할 수 없습니다. 이 기기에서 암호화를 설정하는 중입니다. 잠시 후 다시 시도하세요." + "callNotReady": "아직 보안 통화를 시작할 수 없습니다. 이 기기에서 암호화를 설정하는 중입니다. 잠시 후 다시 시도하세요.", + "callConnectFailed": "통화를 연결할 수 없습니다. 두 기기가 직접 연결을 설정하지 못했습니다.", + "callConnectionLost": "통화 연결이 끊어졌습니다. 통화를 종료한 후 다시 시작하세요." }, "people": { "title": "사람", diff --git a/apps/desktop/src/i18n/locales/pt.json b/apps/desktop/src/i18n/locales/pt.json index b0fc7d90..646b4f5c 100644 --- a/apps/desktop/src/i18n/locales/pt.json +++ b/apps/desktop/src/i18n/locales/pt.json @@ -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", diff --git a/apps/desktop/src/i18n/locales/ru.json b/apps/desktop/src/i18n/locales/ru.json index 976f9cda..a2a43990 100644 --- a/apps/desktop/src/i18n/locales/ru.json +++ b/apps/desktop/src/i18n/locales/ru.json @@ -1852,7 +1852,9 @@ "callAbortPeerMustUpdate": "Звонок завершён: приложение {{name}} не поддерживает защищённые звонки. Попросите обновить Voxium.", "callAbortPeerNotE2E": "Звонок завершён: {{name}} ещё не настроил(а) шифрование, поэтому защищённый звонок невозможен.", "callAbortSignalingFailed": "Звонок завершён: не удалось установить защищённое соединение. Попробуйте ещё раз.", - "callNotReady": "Пока нельзя начать защищённый звонок — шифрование ещё настраивается на этом устройстве. Повторите попытку через мгновение." + "callNotReady": "Пока нельзя начать защищённый звонок — шифрование ещё настраивается на этом устройстве. Повторите попытку через мгновение.", + "callConnectFailed": "Не удалось установить звонок: два устройства не смогли установить прямое соединение.", + "callConnectionLost": "Соединение звонка потеряно. Завершите звонок и начните его заново." }, "people": { "title": "Участники", diff --git a/apps/desktop/src/i18n/locales/uk.json b/apps/desktop/src/i18n/locales/uk.json index 7d2c6fb9..1f48f857 100644 --- a/apps/desktop/src/i18n/locales/uk.json +++ b/apps/desktop/src/i18n/locales/uk.json @@ -1852,7 +1852,9 @@ "callAbortPeerMustUpdate": "Дзвінок завершено: застосунок {{name}} не підтримує захищені дзвінки. Попросіть оновити Voxium.", "callAbortPeerNotE2E": "Дзвінок завершено: {{name}} ще не налаштував(-ла) шифрування, тому захищений дзвінок неможливий.", "callAbortSignalingFailed": "Дзвінок завершено: не вдалося встановити захищене з'єднання. Спробуйте ще раз.", - "callNotReady": "Поки що неможливо розпочати захищений дзвінок — шифрування ще налаштовується на цьому пристрої. Спробуйте ще раз за мить." + "callNotReady": "Поки що неможливо розпочати захищений дзвінок — шифрування ще налаштовується на цьому пристрої. Спробуйте ще раз за мить.", + "callConnectFailed": "Не вдалося встановити дзвінок: два пристрої не змогли встановити пряме з'єднання.", + "callConnectionLost": "З'єднання дзвінка втрачено. Завершіть дзвінок і почніть його знову." }, "people": { "title": "Учасники", diff --git a/apps/desktop/src/i18n/locales/zh.json b/apps/desktop/src/i18n/locales/zh.json index 1e43e148..bec9652e 100644 --- a/apps/desktop/src/i18n/locales/zh.json +++ b/apps/desktop/src/i18n/locales/zh.json @@ -1843,7 +1843,9 @@ "callAbortPeerMustUpdate": "通话已结束:{{name}}的应用无法进行安全通话。请对方更新 Voxium。", "callAbortPeerNotE2E": "通话已结束:{{name}}尚未设置加密,无法建立安全通话。", "callAbortSignalingFailed": "通话已结束:安全通话建立失败。请重试。", - "callNotReady": "暂时无法发起安全通话——此设备仍在设置加密。请稍后重试。" + "callNotReady": "暂时无法发起安全通话——此设备仍在设置加密。请稍后重试。", + "callConnectFailed": "无法接通通话:两台设备无法建立直接连接。", + "callConnectionLost": "通话已断开连接。请结束通话并重新发起。" }, "people": { "title": "成员", diff --git a/apps/desktop/src/stores/voiceStore.ts b/apps/desktop/src/stores/voiceStore.ts index 3094086d..2fb618fd 100644 --- a/apps/desktop/src/stores/voiceStore.ts +++ b/apps/desktop/src/stores/voiceStore.ts @@ -401,6 +401,31 @@ let dmRejoinSentUnder: number | null = null; // Track ICE restart timers per DM peer const iceRestartTimers = new Map>(); +/** The two sentences of a direct call whose peer connection was given up. */ +type DMConnectNotice = 'e2e.callConnectFailed' | 'e2e.callConnectionLost'; + +/** Per sentence, the voice session generation of the direct call that was + * already told it (null: none). Every join and every end of a call moves the + * generation, so a new call is told again and the same sentence is never + * shown twice within one call. */ +const dmConnectNoticeToldUnder: Record = { + 'e2e.callConnectFailed': null, + 'e2e.callConnectionLost': null, +}; + +/** The peer connections that reached `connected` (gone with the connection). */ +const connectedDMPeers = new WeakSet(); + +/** The notice of a direct call whose peer connection was given up: one + * sentence for a connection that never connected, another for one that + * connected and was lost. */ +function tellDMCallConnectionGivenUp(pc: RTCPeerConnection) { + const key: DMConnectNotice = connectedDMPeers.has(pc) ? 'e2e.callConnectionLost' : 'e2e.callConnectFailed'; + if (dmConnectNoticeToldUnder[key] === voiceSessionGeneration) return; + dmConnectNoticeToldUnder[key] = voiceSessionGeneration; + toast.error(i18n.t(key)); +} + // ─── Audio element helpers ────────────────────────────────────────────────── function getAudioContainer(): HTMLElement { @@ -1220,9 +1245,14 @@ function createPeerInternal( pc.onconnectionstatechange = () => { debugLog(`${logPrefix} Connection state with ${targetUserId}: ${pc.connectionState}`); + if (pc.connectionState === 'connected') connectedDMPeers.add(pc); if (pc.connectionState === 'failed') { console.error(`${logPrefix} Connection failed permanently with ${targetUserId}`); + // Only the peer this call holds now, in a call still up: a peer already + // replaced, or a call being torn down, says nothing + const ofLiveCall = getState().peers.get(targetUserId)?.pc === pc && getState().dmCallConversationId !== null; getState().destroyPeer(targetUserId); + if (ofLiveCall) tellDMCallConnectionGivenUp(pc); } };