Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(voice-agents): voice agents in meetings, provisioned through prosody (#17869)

Jaya Allamsettyd613213aab32
diff --git a/config.js b/config.js
index d12ea77358..acd42a9cd8 100644
--- a/config.js
+++ b/config.js
@@ -453,6 +453,15 @@ var config = {
// // consentLearnMoreLink: 'https://jitsi.org/meet/consent',
// },
+ // Voice agents: server-side AI participants provisioned through the voice-agent API.
+ // voiceAgents: {
+ // // Ask each participant before an agent may hear them (they are muted until they decide, and only
+ // // participants who allow the agent hear it). By default agents are let in without asking.
+ // // requireConsent: false,
+ // // Link for the consent dialog's "Learn more" link.
+ // // consentLearnMoreLink: 'https://jitsi.org/meet/consent',
+ // },
+
// recordingService: {
// // When integrations like dropbox are enabled only that will be shown,
// // by enabling fileRecordingsServiceEnabled, we show both the integrations
diff --git a/lang/main.json b/lang/main.json
index 42619a1045..65e370d506 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -391,6 +391,7 @@
"displayNameRequired": "Hi! What's your name?",
"done": "Done",
"e2eeDescription": "End-to-End Encryption is currently EXPERIMENTAL. Please keep in mind that turning on end-to-end encryption will effectively disable server-side provided services such as: phone participation. Also keep in mind that the meeting will only work for people joining from browsers with support for insertable streams.",
+ "e2eeDisabledDueToAgentDescription": "End-to-End Encryption can't be turned on while an AI agent is in the meeting.",
"e2eeDisabledDueToMaxModeDescription": "Cannot enable End-to-End Encryption due to large number of participants in the conference.",
"e2eeDisabledDueToTranscriptionDescription": "End-to-End Encryption can't be turned on while the meeting is being transcribed.",
"e2eeDisabledDueToTranslationDescription": "End-to-End Encryption can't be turned on while live translation is in use.",
@@ -1796,6 +1797,20 @@
},
"waitingMessage": "You'll join the meeting as soon as it is live!"
},
+ "voiceAgents": {
+ "allow": "Allow",
+ "consentDescription": "The agent only hears participants who allow it. If you allow, it will hear you and you will hear its replies.",
+ "consentDescriptionMuted": "The agent only hears participants who allow it. If you allow, it will hear you and you will hear its replies. You are muted until you decide.",
+ "consentTitle": "{{name}} joined as an AI agent",
+ "e2eeUnsupportedDescription": "AI agents cannot take part in end-to-end encrypted meetings. Turn off end-to-end encryption to let the agent hear and be heard.",
+ "e2eeUnsupportedTitle": "{{name}} is unavailable",
+ "labelTooltip": "AI agent in the meeting: {{names}}",
+ "labelTooltipAllow": "AI agent in the meeting: {{names}}. Click to let it hear you.",
+ "labelTooltipE2EE": "AI agent in the meeting: {{names}}. Unavailable while the meeting is end-to-end encrypted.",
+ "nativeTitle": "AI agent in the meeting",
+ "notNow": "Not now",
+ "thumbnailTooltip": "AI agent"
+ },
"volumeSlider": "Volume slider",
"welcomepage": {
"accessibilityLabel": {
diff --git a/modules/API/API.js b/modules/API/API.js
index a035868ef2..4c9b225170 100755
--- a/modules/API/API.js
+++ b/modules/API/API.js
@@ -146,6 +146,7 @@ import { muteAllParticipants, muteRemote } from '../../react/features/video-menu
import { setVideoQuality } from '../../react/features/video-quality/actions';
import { toggleBackgroundEffect, toggleBlurredBackgroundEffect } from '../../react/features/virtual-background/actions';
import { VIRTUAL_BACKGROUND_TYPE } from '../../react/features/virtual-background/constants';
+import { allowVoiceAgent, declineVoiceAgent } from '../../react/features/voice-agents/actions';
import { toggleWhiteboard } from '../../react/features/whiteboard/actions.web';
import { getJitsiMeetTransport } from '../transport';
@@ -234,6 +235,17 @@ function initCommands() {
unmute ? APP.store.dispatch(grantRecordingConsentAndUnmute())
: APP.store.dispatch(grantRecordingConsent());
},
+ 'grant-voice-agent-consent': (id, allow = true) => {
+ const { agents, consent } = APP.store.getState()['features/voice-agents'];
+
+ // An id that is not a present agent decides nothing (and must not touch an open dialog).
+ if (id && !Object.hasOwn(agents, id)) {
+ return;
+ }
+ const ids = id ? [ id ] : Object.keys(agents).filter(agentId => consent[agentId] !== true);
+
+ ids.forEach(agentId => APP.store.dispatch(allow ? allowVoiceAgent(agentId) : declineVoiceAgent(agentId)));
+ },
'display-name': displayName => {
sendAnalytics(createApiEvent('display.name.changed'));
APP.store.dispatch(updateSettings({ displayName: getNormalizedDisplayName(displayName) }));
@@ -2156,6 +2168,21 @@ class API {
});
}
+ /**
+ * Notify external application that the voice-agent consent dialog was opened or closed.
+ *
+ * @param {boolean} open - Whether the dialog is open.
+ * @param {string} id - The agent the dialog is about.
+ * @returns {void}
+ */
+ notifyVoiceAgentConsentDialogOpen(open, id) {
+ this._sendEvent({
+ name: 'voice-agent-consent-dialog-open',
+ id,
+ open
+ });
+ }
+
/**
* Notify external application of the current meeting requiring a password
* to join.
diff --git a/modules/API/external/external_api.js b/modules/API/external/external_api.js
index 60b247006e..518db3aca2 100644
--- a/modules/API/external/external_api.js
+++ b/modules/API/external/external_api.js
@@ -41,6 +41,7 @@ const commands = {
email: 'email',
grantModerator: 'grant-moderator',
grantRecordingConsent: 'grant-recording-consent',
+ grantVoiceAgentConsent: 'grant-voice-agent-consent',
hangup: 'video-hangup',
hideNotification: 'hide-notification',
initiatePrivateChat: 'initiate-private-chat',
@@ -173,6 +174,7 @@ const events = {
'raise-hand-updated': 'raiseHandUpdated',
'ready': 'ready',
'recording-consent-dialog-open': 'recordingConsentDialogOpen',
+ 'voice-agent-consent-dialog-open': 'voiceAgentConsentDialogOpen',
'recording-link-available': 'recordingLinkAvailable',
'recording-status-changed': 'recordingStatusChanged',
'participant-menu-button-clicked': 'participantMenuButtonClick',
diff --git a/package-lock.json b/package-lock.json
index 4150d906ed..17221f7643 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -70,7 +70,7 @@
"js-md5": "0.6.1",
"js-sha512": "0.8.0",
"jwt-decode": "2.2.0",
- "lib-jitsi-meet": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2231.0.0+f88763ea/lib-jitsi-meet.tgz",
+ "lib-jitsi-meet": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2233.0.0+7634be62/lib-jitsi-meet.tgz",
"lodash-es": "4.18.1",
"null-loader": "4.0.1",
"optional-require": "1.0.3",
@@ -14424,8 +14424,8 @@
},
"node_modules/lib-jitsi-meet": {
"version": "0.0.0",
- "resolved": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2231.0.0+f88763ea/lib-jitsi-meet.tgz",
- "integrity": "sha512-ExX5xzKfK3T7Q9BtK0WZdohcouXu6wRuX0k1qPveObm7viL/pLe8R6znxJGLfXVP1PhBxaq8SGvyIsQNeMjGoA==",
+ "resolved": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2233.0.0+7634be62/lib-jitsi-meet.tgz",
+ "integrity": "sha512-DNk4Ylo4T69N9d9jRv8u94T88nzZgvHVVFd1W254EYrjYEqzVUcmqVQAgdzhqcTH3RLO3OQ8NvgnVYfBLKNuvQ==",
"dependencies": {
"@jitsi/js-utils": "12.0.7",
"@jitsi/logger": "2.1.1",
@@ -31748,8 +31748,8 @@
}
},
"lib-jitsi-meet": {
- "version": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2231.0.0+f88763ea/lib-jitsi-meet.tgz",
- "integrity": "sha512-ExX5xzKfK3T7Q9BtK0WZdohcouXu6wRuX0k1qPveObm7viL/pLe8R6znxJGLfXVP1PhBxaq8SGvyIsQNeMjGoA==",
+ "version": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2233.0.0+7634be62/lib-jitsi-meet.tgz",
+ "integrity": "sha512-DNk4Ylo4T69N9d9jRv8u94T88nzZgvHVVFd1W254EYrjYEqzVUcmqVQAgdzhqcTH3RLO3OQ8NvgnVYfBLKNuvQ==",
"requires": {
"@jitsi/js-utils": "12.0.7",
"@jitsi/logger": "2.1.1",
diff --git a/package.json b/package.json
index 1e1cf7e437..1dac33f9f4 100644
--- a/package.json
+++ b/package.json
@@ -76,7 +76,7 @@
"js-md5": "0.6.1",
"js-sha512": "0.8.0",
"jwt-decode": "2.2.0",
- "lib-jitsi-meet": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2231.0.0+f88763ea/lib-jitsi-meet.tgz",
+ "lib-jitsi-meet": "https://github.com/jitsi/lib-jitsi-meet/releases/download/v2233.0.0+7634be62/lib-jitsi-meet.tgz",
"lodash-es": "4.18.1",
"null-loader": "4.0.1",
"optional-require": "1.0.3",
diff --git a/react/features/app/middlewares.any.ts b/react/features/app/middlewares.any.ts
index f09fca773b..e54587044e 100644
--- a/react/features/app/middlewares.any.ts
+++ b/react/features/app/middlewares.any.ts
@@ -55,6 +55,7 @@ import '../video-layout/middleware';
import '../video-quality/middleware';
import '../videosipgw/middleware';
import '../visitors/middleware';
+import '../voice-agents/middleware';
import '../whiteboard/middleware.any';
import './middleware';
diff --git a/react/features/app/reducers.any.ts b/react/features/app/reducers.any.ts
index ea3efbf1ab..ee60368f79 100644
--- a/react/features/app/reducers.any.ts
+++ b/react/features/app/reducers.any.ts
@@ -57,4 +57,5 @@ import '../video-layout/reducer';
import '../video-quality/reducer';
import '../videosipgw/reducer';
import '../visitors/reducer';
+import '../voice-agents/reducer';
import '../whiteboard/reducer';
diff --git a/react/features/app/types.ts b/react/features/app/types.ts
index d89bf38636..e95ffaf3a2 100644
--- a/react/features/app/types.ts
+++ b/react/features/app/types.ts
@@ -84,6 +84,7 @@ import { IVideoQualityPersistedState, IVideoQualityState } from '../video-qualit
import { IVideoSipGW } from '../videosipgw/reducer';
import { IVirtualBackground } from '../virtual-background/reducer';
import { IVisitorsState } from '../visitors/reducer';
+import { IVoiceAgentsState } from '../voice-agents/reducer';
import { IWebHid } from '../web-hid/reducer';
import { IWhiteboardState } from '../whiteboard/reducer';
@@ -180,6 +181,7 @@ export interface IReduxState {
'features/videosipgw': IVideoSipGW;
'features/virtual-background': IVirtualBackground;
'features/visitors': IVisitorsState;
+ 'features/voice-agents': IVoiceAgentsState;
'features/web-hid': IWebHid;
'features/whiteboard': IWhiteboardState;
}
diff --git a/react/features/audio-translation/middleware.any.ts b/react/features/audio-translation/middleware.any.ts
index fa2e6256ef..98d7cb54cd 100644
--- a/react/features/audio-translation/middleware.any.ts
+++ b/react/features/audio-translation/middleware.any.ts
@@ -140,8 +140,15 @@ StateListenerRegistry.register(
return;
}
- conference.on(JitsiConferenceEvents.TRANSLATED_SOURCE_SENDING_CHANGED,
- ({ sending, sourceName, timestamp }: { sending: boolean; sourceName: string; timestamp: number; }) => {
+ conference.on(JitsiConferenceEvents.SYNTHETIC_SOURCE_SENDING_CHANGED,
+ ({ kind, sending, sourceName, timestamp }: {
+ kind?: string; sending: boolean; sourceName: string; timestamp: number; }) => {
+ // The event covers every synthetic source; the bridge says which kind, and only
+ // translations belong here.
+ if (kind && kind !== 'translation') {
+ return;
+ }
+
dispatch(updateTranslatedSourceSending(sourceName, sending, timestamp));
});
diff --git a/react/features/base/conference/reducer.ts b/react/features/base/conference/reducer.ts
index ab484807af..1fec03e678 100644
--- a/react/features/base/conference/reducer.ts
+++ b/react/features/base/conference/reducer.ts
@@ -55,6 +55,20 @@ const DEFAULT_STATE = {
export interface IConferenceMetadata {
+ /**
+ * The voice agents (bot participants) provisioned for the room, keyed by agent id. Written by the
+ * voice-agent prosody module; read-only for clients. An agent becomes audible only after the local
+ * participant subscribes to its source (consent-gated, see features/voice-agents).
+ */
+ agents?: {
+ [agentId: string]: {
+ displayName?: string;
+ kind?: string;
+ sourceName?: string;
+ state?: string;
+ };
+ };
+
/**
* Server-controlled flag: the deployment transcribes on the backend, started through
* {@code recording.isTranscribingEnabled}, instead of dialing a transcriber.
@@ -204,6 +218,7 @@ export interface IJitsiConference {
sendTextMessage: Function;
sendTones: Function;
sessionId: string;
+ setAgentAudioSubscription?: (sourceNames: string[]) => void;
setAssumedBandwidthBps: (value: number) => void;
setDesktopSharingFrameRate: Function;
setDisplayName: Function;
diff --git a/react/features/base/config/configType.ts b/react/features/base/config/configType.ts
index 3f1aa01805..374b8c0256 100644
--- a/react/features/base/config/configType.ts
+++ b/react/features/base/config/configType.ts
@@ -831,6 +831,14 @@ export interface IConfig {
queueService: string;
showJoinMeetingDialog?: boolean;
};
+ /**
+ * Voice agents (bot participants). Every participant is subscribed to an agent's audio automatically;
+ * set requireConsent to true to prompt each participant before the agent may hear them or be heard.
+ */
+ voiceAgents?: {
+ consentLearnMoreLink?: string;
+ requireConsent?: boolean;
+ };
watchRTCConfigParams?: IWatchRTCConfiguration;
webhookProxyUrl?: string;
webrtcIceTcpDisable?: boolean;
diff --git a/react/features/base/config/configWhitelist.ts b/react/features/base/config/configWhitelist.ts
index 25a351db92..ef489b0b1a 100644
--- a/react/features/base/config/configWhitelist.ts
+++ b/react/features/base/config/configWhitelist.ts
@@ -211,6 +211,7 @@ export default [
'prejoinConfig.showHangUp',
'raisedHands',
'recordingService',
+ 'voiceAgents',
'requireDisplayName',
'remoteVideoMenu',
'roomPasswordNumberOfDigits',
diff --git a/react/features/base/participants/constants.ts b/react/features/base/participants/constants.ts
index d2518eda9a..99215958f7 100644
--- a/react/features/base/participants/constants.ts
+++ b/react/features/base/participants/constants.ts
@@ -1,4 +1,4 @@
-import { IconPhoneRinging, IconWhiteboard } from '../icons/svg';
+import { IconAI, IconPhoneRinging, IconWhiteboard } from '../icons/svg';
/**
* The relative path to the default/stock avatar (image) file used on both
@@ -81,6 +81,11 @@ export const LOWER_HAND_AUDIO_LEVEL = 0.2;
*/
export const WHITEBOARD_PARTICIPANT_ICON = IconWhiteboard;
+/**
+ * The icon shown for a voice agent (fake participant) as its avatar.
+ */
+export const VOICE_AGENT_PARTICIPANT_ICON = IconAI;
+
/**
* The ID used for non-participant (system) messages coming from a transcriber.
*/
diff --git a/react/features/base/participants/functions.ts b/react/features/base/participants/functions.ts
index 33f29ff0d8..0d86a2c64a 100644
--- a/react/features/base/participants/functions.ts
+++ b/react/features/base/participants/functions.ts
@@ -22,6 +22,7 @@ import {
JIGASI_PARTICIPANT_ICON,
MAX_DISPLAY_NAME_LENGTH,
PARTICIPANT_ROLE,
+ VOICE_AGENT_PARTICIPANT_ICON,
WHITEBOARD_PARTICIPANT_ICON
} from './constants';
import { preloadImage } from './preloadImage';
@@ -41,6 +42,9 @@ const AVATAR_CHECKER_FUNCTIONS = [
(participant: IParticipant) => {
return isWhiteboardParticipant(participant) ? WHITEBOARD_PARTICIPANT_ICON : null;
},
+ (participant: IParticipant) => {
+ return isVoiceAgentParticipant(participant) ? VOICE_AGENT_PARTICIPANT_ICON : null;
+ },
(participant: IParticipant) => {
return participant?.avatarURL ? participant.avatarURL : null;
},
@@ -288,6 +292,16 @@ export function isWhiteboardParticipant(participant?: IParticipant): boolean {
return participant?.fakeParticipant === FakeParticipant.Whiteboard;
}
+/**
+ * Returns whether the fake participant is a voice agent.
+ *
+ * @param {IParticipant|undefined} participant - The participant entity.
+ * @returns {boolean} - True if it's a voice agent participant.
+ */
+export function isVoiceAgentParticipant(participant?: IParticipant): boolean {
+ return participant?.fakeParticipant === FakeParticipant.Agent;
+}
+
/**
* Returns a count of the known remote participants in the passed in redux state.
*
diff --git a/react/features/base/participants/middleware.ts b/react/features/base/participants/middleware.ts
index 0f8a5010f8..dbdf47cc65 100644
--- a/react/features/base/participants/middleware.ts
+++ b/react/features/base/participants/middleware.ts
@@ -90,6 +90,7 @@ import {
hasRaisedHand,
isLocalParticipantModerator,
isScreenShareParticipant,
+ isVoiceAgentParticipant,
isWhiteboardParticipant
} from './functions';
import logger from './logger';
@@ -304,18 +305,21 @@ MiddlewareRegistry.register(store => next => action => {
}
case PARTICIPANT_JOINED: {
- // Do not play sounds when a screenshare or whiteboard participant tile is created for screenshare.
+ // Do not play sounds when a screenshare or whiteboard participant tile is created for screenshare, nor for
+ // agent tiles, which voice-agents announces itself.
(!isScreenShareParticipant(action.participant)
&& !isWhiteboardParticipant(action.participant)
+ && !isVoiceAgentParticipant(action.participant)
) && _maybePlaySounds(store, action);
return _participantJoinedOrUpdated(store, next, action);
}
case PARTICIPANT_LEFT: {
- // Do not play sounds when a tile for screenshare or whiteboard is removed.
+ // Do not play sounds when a tile for screenshare, whiteboard or an agent is removed.
(!isScreenShareParticipant(action.participant)
&& !isWhiteboardParticipant(action.participant)
+ && !isVoiceAgentParticipant(action.participant)
) && _maybePlaySounds(store, action);
break;
diff --git a/react/features/base/participants/reducer.ts b/react/features/base/participants/reducer.ts
index 01d4260999..3529f7b41c 100644
--- a/react/features/base/participants/reducer.ts
+++ b/react/features/base/participants/reducer.ts
@@ -218,6 +218,11 @@ ReducerRegistry.register<IParticipantsState>('features/base/participants',
if (state.remote.has(id)) {
newParticipant = _participant(oldParticipant, action);
state.remote.set(id, newParticipant);
+
+ // Keep the fake-participant index on the same object as the roster (e.g. a renamed voice agent).
+ if (newParticipant.fakeParticipant && state.fakeParticipants.has(id)) {
+ state.fakeParticipants.set(id, newParticipant);
+ }
} else if (id === state.local?.id) {
newParticipant = state.local = _participant(state.local, action);
}
diff --git a/react/features/base/participants/types.ts b/react/features/base/participants/types.ts
index a57646cc59..d0c6e411c9 100644
--- a/react/features/base/participants/types.ts
+++ b/react/features/base/participants/types.ts
@@ -1,6 +1,7 @@
import { IJitsiConference } from '../conference/reducer';
export enum FakeParticipant {
+ Agent = 'Agent',
LocalScreenShare = 'LocalScreenShare',
RemoteScreenShare = 'RemoteScreenShare',
SharedVideo = 'SharedVideo',
diff --git a/react/features/base/tracks/functions.any.ts b/react/features/base/tracks/functions.any.ts
index 1f5dbb25e2..76937c65b0 100644
--- a/react/features/base/tracks/functions.any.ts
+++ b/react/features/base/tracks/functions.any.ts
@@ -8,7 +8,8 @@ import { IGUMPendingState } from '../media/types';
import {
getMutedStateByParticipantAndMediaType,
getVirtualScreenshareParticipantOwnerId,
- isScreenShareParticipant
+ isScreenShareParticipant,
+ isVoiceAgentParticipant
} from '../participants/functions';
import { IParticipant } from '../participants/types';
@@ -37,6 +38,11 @@ export function isParticipantMediaMuted(participant: IParticipant | undefined,
return false;
}
+ // An agent has no presence to report its mute state: its track is the source of truth.
+ if (isVoiceAgentParticipant(participant)) {
+ return isRemoteTrackMuted(getTrackState(state), mediaType, participant.id);
+ }
+
if (getSsrcRewritingFeatureFlag(state)) {
return getMutedStateByParticipantAndMediaType(state, participant, mediaType);
}
diff --git a/react/features/conference/components/web/ConferenceInfo.tsx b/react/features/conference/components/web/ConferenceInfo.tsx
index e25e3760a2..0aff021130 100644
--- a/react/features/conference/components/web/ConferenceInfo.tsx
+++ b/react/features/conference/components/web/ConferenceInfo.tsx
@@ -15,6 +15,7 @@ import { showToolbox } from '../../../toolbox/actions.web';
import { isToolboxVisible } from '../../../toolbox/functions.web';
import VideoQualityLabel from '../../../video-quality/components/VideoQualityLabel.web';
import VisitorsCountLabel from '../../../visitors/components/web/VisitorsCountLabel';
+import VoiceAgentLabel from '../../../voice-agents/components/web/VoiceAgentLabel';
import ConferenceTimer from '../ConferenceTimer';
import { getConferenceInfo } from '../functions.web';
@@ -107,6 +108,7 @@ const COMPONENTS: Array<{
<RecordingLabel mode = { JitsiRecordingConstants.mode.STREAM } />
<TranscribingLabel />
<TranslationLabel />
+ <VoiceAgentLabel />
</>
),
id: 'recording'
diff --git a/react/features/e2ee/components/E2EESection.tsx b/react/features/e2ee/components/E2EESection.tsx
index c62179f2af..162672e1dd 100644
--- a/react/features/e2ee/components/E2EESection.tsx
+++ b/react/features/e2ee/components/E2EESection.tsx
@@ -151,6 +151,7 @@ const E2EESection = ({
* Why each server-side service keeps E2EE from being turned on.
*/
const E2EE_BLOCKED_REASONS: Record<E2EEBlockingService, string> = {
+ agent: 'dialog.e2eeDisabledDueToAgentDescription',
transcription: 'dialog.e2eeDisabledDueToTranscriptionDescription',
translation: 'dialog.e2eeDisabledDueToTranslationDescription'
};
diff --git a/react/features/e2ee/functions.ts b/react/features/e2ee/functions.ts
index 98bf85a9c1..063b4972bc 100644
--- a/react/features/e2ee/functions.ts
+++ b/react/features/e2ee/functions.ts
@@ -143,7 +143,7 @@ export function isE2EEOnInMeeting(stateful: IStateful) {
/**
* A server-side service that needs the media in the clear, so it and end-to-end encryption exclude each other.
*/
-export type E2EEBlockingService = 'transcription' | 'translation';
+export type E2EEBlockingService = 'agent' | 'transcription' | 'translation';
/**
* Returns the server-side service that keeps end-to-end encryption from being turned on, if any.
@@ -152,6 +152,13 @@ export type E2EEBlockingService = 'transcription' | 'translation';
* @returns {E2EEBlockingService|undefined}
*/
export function getE2EEBlockingService(state: IReduxState): E2EEBlockingService | undefined {
+ // An agent being provisioned, connecting or active; read from metadata so voice-agents can depend on this module.
+ const agents = state['features/base/conference'].metadata?.agents ?? {};
+
+ if (Object.values(agents).some(agent => agent?.state !== 'failed')) {
+ return 'agent';
+ }
+
// A transcriber in the room (Jigasi) or the deployment's backend transcription.
if (isTranscribing(state) || isAsyncTranscriptionActive(state)) {
return 'transcription';
diff --git a/react/features/filmstrip/components/web/StatusIndicators.tsx b/react/features/filmstrip/components/web/StatusIndicators.tsx
index f16cfb5f04..277f3137a6 100644
--- a/react/features/filmstrip/components/web/StatusIndicators.tsx
+++ b/react/features/filmstrip/components/web/StatusIndicators.tsx
@@ -4,7 +4,11 @@ import { connect } from 'react-redux';
import { IReduxState } from '../../../app/types';
import { MEDIA_TYPE } from '../../../base/media/constants';
import { PARTICIPANT_ROLE } from '../../../base/participants/constants';
-import { getParticipantByIdOrUndefined, isScreenShareParticipantById } from '../../../base/participants/functions';
+import {
+ getParticipantByIdOrUndefined,
+ isScreenShareParticipantById,
+ isVoiceAgentParticipant
+} from '../../../base/participants/functions';
import {
getVideoTrackByParticipant,
isLocalTrackMuted,
@@ -102,8 +106,10 @@ function _mapStateToProps(state: IReduxState, ownProps: any) {
if (participant?.local) {
isAudioMuted = isLocalTrackMuted(tracks, MEDIA_TYPE.AUDIO);
- } else if (!participant?.fakeParticipant || isScreenShareParticipantById(state, participantID)) {
- // remote participants excluding shared video
+ } else if (!participant?.fakeParticipant
+ || isScreenShareParticipantById(state, participantID)
+ || isVoiceAgentParticipant(participant)) {
+ // remote participants excluding shared video (an agent has an audio track like anyone else)
const track = getVideoTrackByParticipant(state, participant);
isScreenSharing = track?.videoType === 'desktop';
diff --git a/react/features/filmstrip/components/web/Thumbnail.tsx b/react/features/filmstrip/components/web/Thumbnail.tsx
index 58493c0aba..ecd5113819 100644
--- a/react/features/filmstrip/components/web/Thumbnail.tsx
+++ b/react/features/filmstrip/components/web/Thumbnail.tsx
@@ -22,6 +22,7 @@ import {
hasRaisedHand,
isLocalScreenshareParticipant,
isScreenShareParticipant,
+ isVoiceAgentParticipant,
isWhiteboardParticipant
} from '../../../base/participants/functions';
import { IParticipant } from '../../../base/participants/types';
@@ -64,6 +65,7 @@ import ThumbnailAudioIndicator from './ThumbnailAudioIndicator';
import ThumbnailBottomIndicators from './ThumbnailBottomIndicators';
import ThumbnailTopIndicators from './ThumbnailTopIndicators';
import VirtualScreenshareParticipant from './VirtualScreenshareParticipant';
+import VoiceAgentIndicator from './VoiceAgentIndicator';
/**
* Module-scoped so the second-screen trigger's click handler stays stable
@@ -1024,7 +1026,8 @@ class Thumbnail extends Component<IProps, IState> {
const video = _videoTrack && <VideoTrack
className = { local ? videoTrackClassName : '' }
eventHandlers = { videoEventListeners }
- id = { local ? 'localVideo_container' : `remoteVideo_${videoTrackId || ''}` }
+ id = { local ? 'localVideo_container'
+ : isVoiceAgentParticipant(_participant) ? `participant_${id}` : `remoteVideo_${videoTrackId || ''}` }
muted = { local ? undefined : true }
style = { styles.video }
videoTrack = { _videoTrack } />;
@@ -1088,7 +1091,8 @@ class Thumbnail extends Component<IProps, IState> {
_thumbnailType === THUMBNAIL_TYPE.TILE && 'tile-view-mode'
) }>
<ThumbnailTopIndicators
- disableConnectionIndicator = { isWhiteboardParticipant(_participant) }
+ disableConnectionIndicator = { isWhiteboardParticipant(_participant)
+ || isVoiceAgentParticipant(_participant) }
hidePopover = { this._hidePopover }
indicatorsClassName = { classes.indicatorsBackground }
isHovered = { isHovered }
@@ -1099,6 +1103,7 @@ class Thumbnail extends Component<IProps, IState> {
thumbnailType = { _thumbnailType } />
</div>
{_shouldDisplayTintBackground && <div className = { classes.tintBackground } />}
+ {isVoiceAgentParticipant(_participant) && <VoiceAgentIndicator />}
{!_gifSrc && this._renderAvatar(styles.avatar) }
{ !local && (
<div className = 'presence-label-container'>
@@ -1150,8 +1155,11 @@ class Thumbnail extends Component<IProps, IState> {
return this._renderParticipant(true);
}
+ // A voice agent is a participant without a transport (a video source may follow later), so it takes the
+ // regular tile like the whiteboard does; the fake-participant tile is shared video's.
if (fakeParticipant
&& !isWhiteboardParticipant(_participant)
+ && !isVoiceAgentParticipant(_participant)
&& !_isVirtualScreenshareParticipant
) {
return this._renderFakeParticipant();
diff --git a/react/features/filmstrip/components/web/VoiceAgentIndicator.tsx b/react/features/filmstrip/components/web/VoiceAgentIndicator.tsx
new file mode 100644
index 0000000000..36bf92d396
--- /dev/null
+++ b/react/features/filmstrip/components/web/VoiceAgentIndicator.tsx
@@ -0,0 +1,43 @@
+import React from 'react';
+import { makeStyles } from 'tss-react/mui';
+
+import { IconAI } from '../../../base/icons/svg';
+import BaseIndicator from '../../../base/react/components/web/BaseIndicator';
+
+const useStyles = makeStyles()(theme => {
+ return {
+ indicator: {
+ backgroundColor: theme.palette.action01,
+ borderRadius: '4px',
+ boxSizing: 'border-box',
+ display: 'inline-block',
+ left: theme.spacing(1),
+ padding: '4px',
+ position: 'absolute',
+ top: theme.spacing(1),
+ zIndex: 10
+ }
+ };
+});
+
+/**
+ * Thumbnail badge marking a voice agent's tile as an AI agent.
+ *
+ * @returns {ReactElement}
+ */
+const VoiceAgentIndicator = () => {
+ const { classes, theme } = useStyles();
+
+ return (
+ <div className = { classes.indicator }>
+ <BaseIndicator
+ icon = { IconAI }
+ iconColor = { theme.palette.icon01 }
+ iconSize = { 16 }
+ tooltipKey = 'voiceAgents.thumbnailTooltip'
+ tooltipPosition = 'top' />
+ </div>
+ );
+};
+
+export default VoiceAgentIndicator;
diff --git a/react/features/notifications/middleware.ts b/react/features/notifications/middleware.ts
index 195b132ed5..4c694080cd 100644
--- a/react/features/notifications/middleware.ts
+++ b/react/features/notifications/middleware.ts
@@ -11,6 +11,7 @@ import {
getParticipantById,
getParticipantDisplayName,
isScreenShareParticipant,
+ isVoiceAgentParticipant,
isWhiteboardParticipant
} from '../base/participants/functions';
import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
@@ -125,11 +126,13 @@ MiddlewareRegistry.register(store => next => action => {
const { participant: p } = action;
const { conference } = state['features/base/conference'];
- // Do not display notifications for the virtual screenshare and whiteboard tiles.
+ // Do not display notifications for the virtual screenshare and whiteboard tiles, nor for agent tiles,
+ // which voice-agents announces itself.
if (conference
&& !p.local
&& !isScreenShareParticipant(p)
&& !isWhiteboardParticipant(p)
+ && !isVoiceAgentParticipant(p)
&& !joinLeaveNotificationsDisabled()
&& !p.isReplacing) {
dispatch(showParticipantJoinedNotification(
@@ -146,11 +149,12 @@ MiddlewareRegistry.register(store => next => action => {
action.participant.id
);
- // Do not display notifications for the virtual screenshare tiles.
+ // Do not display notifications for the virtual screenshare tiles, nor for agent tiles (see above).
if (participant
&& !participant.local
&& !isScreenShareParticipant(participant)
&& !isWhiteboardParticipant(participant)
+ && !isVoiceAgentParticipant(participant)
&& !action.participant.isReplaced) {
dispatch(showParticipantLeftNotification(
getParticipantDisplayName(state, participant.id)
diff --git a/react/features/participants-pane/components/web/MeetingParticipantContextMenu.tsx b/react/features/participants-pane/components/web/MeetingParticipantContextMenu.tsx
index fc1becd1e7..ea4ff2f596 100644
--- a/react/features/participants-pane/components/web/MeetingParticipantContextMenu.tsx
+++ b/react/features/participants-pane/components/web/MeetingParticipantContextMenu.tsx
@@ -5,11 +5,13 @@ import { IReduxState, IStore } from '../../../app/types';
import { translate } from '../../../base/i18n/functions';
import {
getLocalParticipant,
- getParticipantByIdOrUndefined
+ getParticipantByIdOrUndefined,
+ isVoiceAgentParticipant
} from '../../../base/participants/functions';
import { IParticipant } from '../../../base/participants/types';
import FakeParticipantContextMenu from '../../../video-menu/components/web/FakeParticipantContextMenu';
import ParticipantContextMenu from '../../../video-menu/components/web/ParticipantContextMenu';
+import VoiceAgentContextMenu from '../../../video-menu/components/web/VoiceAgentContextMenu';
interface IProps {
@@ -106,6 +108,10 @@ class MeetingParticipantContextMenu extends Component<IProps> {
thumbnailMenu: false
};
+ if (isVoiceAgentParticipant(_participant)) {
+ return <VoiceAgentContextMenu { ...props } />;
+ }
+
if (_participant?.fakeParticipant) {
return (
<FakeParticipantContextMenu
diff --git a/react/features/participants-pane/components/web/MeetingParticipantItem.tsx b/react/features/participants-pane/components/web/MeetingParticipantItem.tsx
index cd97eb2aef..089f41bd77 100644
--- a/react/features/participants-pane/components/web/MeetingParticipantItem.tsx
+++ b/react/features/participants-pane/components/web/MeetingParticipantItem.tsx
@@ -9,7 +9,8 @@ import {
getParticipantByIdOrUndefined,
getParticipantDisplayName,
hasRaisedHand,
- isParticipantModerator
+ isParticipantModerator,
+ isVoiceAgentParticipant
} from '../../../base/participants/functions';
import { IParticipant } from '../../../base/participants/types';
import {
@@ -19,6 +20,7 @@ import {
isParticipantVideoMuted
} from '../../../base/tracks/functions.web';
import { ITrack } from '../../../base/tracks/types';
+import { hasVoiceAgentMenuItems } from '../../../video-menu/functions.web';
import { ACTION_TRIGGER, MEDIA_STATE, type MediaState } from '../../constants';
import {
getParticipantAudioMediaState,
@@ -53,6 +55,11 @@ interface IProps {
*/
_displayName: string;
+ /**
+ * Whether a voice agent's context menu would have anything in it here.
+ */
+ _hasAgentMenu: boolean;
+
/**
* Whether or not moderation is supported.
*/
@@ -173,6 +180,7 @@ function MeetingParticipantItem({
_audioTrack,
_disableModeratorIndicator,
_displayName,
+ _hasAgentMenu,
_local,
_localVideoOwner,
_matchesSearch,
@@ -231,7 +239,9 @@ function MeetingParticipantItem({
<ParticipantItem
actionsTrigger = { ACTION_TRIGGER.HOVER }
{
- ...(_participant?.fakeParticipant ? {} : {
+ // An agent is a participant without a transport: its mic (and later video) state shows like
+ // anyone's, unlike shared video's.
+ ...(_participant?.fakeParticipant && !isVoiceAgentParticipant(_participant) ? {} : {
audioMediaState,
videoMediaState: _videoMediaState
})
@@ -242,7 +252,8 @@ function MeetingParticipantItem({
isModerator = { isParticipantModerator(_participant) }
local = { _local }
onLeave = { onLeave }
- openDrawerForParticipant = { openDrawerForParticipant }
+ openDrawerForParticipant = {
+ isVoiceAgentParticipant(_participant) && !_hasAgentMenu ? undefined : openDrawerForParticipant }
overflowDrawer = { overflowDrawer }
participantID = { _participantID }
raisedHand = { _raisedHand }
@@ -263,7 +274,8 @@ function MeetingParticipantItem({
</>
}
- {!overflowDrawer && (_localVideoOwner && _participant?.fakeParticipant) && (
+ {!overflowDrawer && _participant?.fakeParticipant
+ && (isVoiceAgentParticipant(_participant) ? _hasAgentMenu : _localVideoOwner) && (
<ParticipantActionEllipsis
accessibilityLabel = { participantActionEllipsisLabel }
onClick = { onContextMenu } />
@@ -304,6 +316,7 @@ function _mapStateToProps(state: IReduxState, ownProps: any) {
_audioTrack,
_disableModeratorIndicator: Boolean(disableModeratorIndicator),
_displayName,
+ _hasAgentMenu: hasVoiceAgentMenuItems(state, false),
_local: Boolean(participant?.local),
_localVideoOwner: Boolean(ownerId === localParticipantId),
_matchesSearch,
diff --git a/react/features/video-menu/components/web/RemoteVideoMenuTriggerButton.tsx b/react/features/video-menu/components/web/RemoteVideoMenuTriggerButton.tsx
index c721935b57..3401df6a91 100644
--- a/react/features/video-menu/components/web/RemoteVideoMenuTriggerButton.tsx
+++ b/react/features/video-menu/components/web/RemoteVideoMenuTriggerButton.tsx
@@ -6,7 +6,11 @@ import { makeStyles } from 'tss-react/mui';
import { IReduxState, IStore } from '../../../app/types';
import { isMobileBrowser } from '../../../base/environment/utils';
import { IconDotsHorizontal } from '../../../base/icons/svg';
-import { getLocalParticipant, getParticipantById } from '../../../base/participants/functions';
+import {
+ getLocalParticipant,
+ getParticipantById,
+ isVoiceAgentParticipant
+} from '../../../base/participants/functions';
import { IParticipant } from '../../../base/participants/types';
import Popover from '../../../base/popover/components/Popover.web';
import { setParticipantContextMenuOpen } from '../../../base/responsive-ui/actions';
@@ -15,10 +19,12 @@ import ConnectionIndicatorContent from
'../../../connection-indicator/components/web/ConnectionIndicatorContent';
import { THUMBNAIL_TYPE } from '../../../filmstrip/constants';
import { renderConnectionStatus } from '../../actions.web';
+import { hasVoiceAgentMenuItems } from '../../functions.web';
import FakeParticipantContextMenu from './FakeParticipantContextMenu';
import ParticipantContextMenu from './ParticipantContextMenu';
import { REMOTE_CONTROL_MENU_STATES } from './RemoteControlButton';
+import VoiceAgentContextMenu from './VoiceAgentContextMenu';
/**
* The type of the React {@code Component} props of
@@ -31,6 +37,11 @@ interface IProps {
*/
_disabled: Boolean;
+ /**
+ * Whether a voice agent's context menu would have anything in it on the thumbnail.
+ */
+ _hasAgentMenu: boolean;
+
/**
* Shared video local participant owner.
*/
@@ -122,6 +133,7 @@ const useStyles = makeStyles()(() => {
const RemoteVideoMenuTriggerButton = ({
_disabled,
+ _hasAgentMenu,
_localVideoOwner,
_menuPosition,
_participant,
@@ -160,6 +172,10 @@ const RemoteVideoMenuTriggerButton = ({
thumbnailMenu: true
};
+ if (isVoiceAgentParticipant(_participant)) {
+ return <VoiceAgentContextMenu { ...props } />;
+ }
+
if (_participant?.fakeParticipant) {
return (
<FakeParticipantContextMenu
@@ -179,7 +195,7 @@ const RemoteVideoMenuTriggerButton = ({
if (_showConnectionInfo) {
content = <ConnectionIndicatorContent participantId = { participantID } />;
- } else if (!_disabled) {
+ } else if (!_disabled && (_hasAgentMenu || !isVoiceAgentParticipant(_participant))) {
content = _renderRemoteVideoMenu();
}
@@ -261,6 +277,7 @@ function _mapStateToProps(state: IReduxState, ownProps: Partial<IProps>) {
return {
_disabled: Boolean(remoteVideoMenu?.disabled),
+ _hasAgentMenu: hasVoiceAgentMenuItems(state, true),
_localVideoOwner: Boolean(ownerId === localParticipantId),
_menuPosition,
_participant: participant ?? { id: '' },
diff --git a/react/features/video-menu/components/web/VoiceAgentContextMenu.tsx b/react/features/video-menu/components/web/VoiceAgentContextMenu.tsx
new file mode 100644
index 0000000000..377d07980c
--- /dev/null
+++ b/react/features/video-menu/components/web/VoiceAgentContextMenu.tsx
@@ -0,0 +1,135 @@
+import React, { useCallback } from 'react';
+import { useDispatch, useSelector } from 'react-redux';
+
+import { IReduxState } from '../../../app/types';
+import Avatar from '../../../base/avatar/components/Avatar';
+import { IParticipant } from '../../../base/participants/types';
+import ContextMenu from '../../../base/ui/components/web/ContextMenu';
+import ContextMenuItemGroup from '../../../base/ui/components/web/ContextMenuItemGroup';
+import { setVolume } from '../../../filmstrip/actions.web';
+import { showOverflowDrawer } from '../../../toolbox/functions.web';
+import { hasVoiceAgentMenuItems } from '../../functions.web';
+
+import VolumeSlider from './VolumeSlider';
+
+interface IProps {
+
+ /**
+ * Class name for the context menu.
+ */
+ className?: string;
+
+ /**
+ * Closes a drawer if open.
+ */
+ closeDrawer?: () => void;
+
+ /**
+ * The participant for which the drawer is open.
+ * It contains the displayName & participantID.
+ */
+ drawerParticipant?: {
+ displayName: string;
+ participantID: string;
+ };
+
+ /**
+ * Target elements against which positioning calculations are made.
+ */
+ offsetTarget?: HTMLElement;
+
+ /**
+ * Callback for the mouse entering the component.
+ */
+ onEnter?: (e?: React.MouseEvent) => void;
+
+ /**
+ * Callback for the mouse leaving the component.
+ */
+ onLeave?: (e?: React.MouseEvent) => void;
+
+ /**
+ * Callback for making a selection in the menu.
+ */
+ onSelect: (value?: boolean | React.MouseEvent) => void;
+
+ /**
+ * The agent.
+ */
+ participant: IParticipant;
+
+ /**
+ * Whether or not the menu is displayed in the thumbnail remote video menu.
+ */
+ thumbnailMenu?: boolean;
+}
+
+/**
+ * The context menu of a voice agent. An agent is a participant without a transport of its own, so neither the
+ * moderation and messaging actions of a participant nor the actions of the other fake participants (shared video,
+ * whiteboard) apply to it. What does apply is what this participant can do for themselves, starting with the
+ * volume; a video source later changes nothing here.
+ *
+ * @param {IProps} props - The props of the component.
+ * @returns {JSX.Element}
+ */
+const VoiceAgentContextMenu = ({
+ className,
+ closeDrawer,
+ drawerParticipant,
+ offsetTarget,
+ onEnter,
+ onLeave,
+ onSelect,
+ participant,
+ thumbnailMenu
+}: IProps) => {
+ const dispatch = useDispatch();
+ const _overflowDrawer: boolean = useSelector(showOverflowDrawer);
+ const { participantsVolume } = useSelector((state: IReduxState) => state['features/filmstrip']);
+ const _volume = participantsVolume[participant.id] ?? 1;
+
+ const clickHandler = useCallback(() => onSelect(true), [ onSelect ]);
+
+ const _onVolumeChange = useCallback((value: number) => {
+ dispatch(setVolume(participant.id, value));
+ }, [ participant.id, dispatch ]);
+
+ const hasItems = useSelector((state: IReduxState) => hasVoiceAgentMenuItems(state, Boolean(thumbnailMenu)));
+ const showVolumeSlider = hasItems && typeof _volume === 'number' && !isNaN(_volume);
+
+ return (
+ <ContextMenu
+ activateFocusTrap = { !thumbnailMenu }
+ className = { className }
+ entity = { participant }
+ hidden = { thumbnailMenu ? false : undefined }
+ inDrawer = { thumbnailMenu && _overflowDrawer }
+ isDrawerOpen = { Boolean(drawerParticipant) }
+ offsetTarget = { offsetTarget }
+ onClick = { onSelect }
+ onClickOutside = { thumbnailMenu ? undefined : clickHandler }
+ onDrawerClose = { thumbnailMenu ? onSelect : closeDrawer }
+ onMouseEnter = { onEnter }
+ onMouseLeave = { onLeave }>
+ {!thumbnailMenu && _overflowDrawer && drawerParticipant && <ContextMenuItemGroup
+ actions = { [ {
+ accessibilityLabel: drawerParticipant.displayName,
+ customIcon: <Avatar
+ participantId = { drawerParticipant.participantID }
+ size = { 20 } />,
+ text: drawerParticipant.displayName
+ } ] } />}
+ {showVolumeSlider && (
+ <ContextMenuItemGroup>
+ <VolumeSlider
+ initialValue = { _volume }
+ key = 'volume-slider'
+ onChange = { _onVolumeChange } />
+ </ContextMenuItemGroup>
+ )}
+ </ContextMenu>
+ );
+};
+
+export default VoiceAgentContextMenu;
diff --git a/react/features/video-menu/functions.web.ts b/react/features/video-menu/functions.web.ts
new file mode 100644
index 0000000000..6dd8f60eed
--- /dev/null
+++ b/react/features/video-menu/functions.web.ts
@@ -0,0 +1,18 @@
+import { IReduxState } from '../app/types';
+import { isIosMobileBrowser } from '../base/environment/utils';
+import { showOverflowDrawer } from '../toolbox/functions.web';
+
+/**
+ * Whether a voice agent's context menu has anything in it. Its only item is the volume slider, offered where a
+ * participant's is: on the thumbnail and in the overflow drawer, not in the desktop participants pane, and never with
+ * startSilent or on iOS, which has no volume control.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @param {boolean} thumbnailMenu - Whether the menu opens from the thumbnail.
+ * @returns {boolean}
+ */
+export function hasVoiceAgentMenuItems(state: IReduxState, thumbnailMenu: boolean): boolean {
+ return !state['features/base/config'].startSilent
+ && !isIosMobileBrowser()
+ && (showOverflowDrawer(state) || thumbnailMenu);
+}
diff --git a/react/features/voice-agents/actionTypes.ts b/react/features/voice-agents/actionTypes.ts
new file mode 100644
index 0000000000..9c3f1ae4eb
--- /dev/null
+++ b/react/features/voice-agents/actionTypes.ts
@@ -0,0 +1,9 @@
+/** Updates the known set of voice agents (mirrored from room metadata). */
+export const SET_VOICE_AGENTS = 'SET_VOICE_AGENTS';
+
+/** Records the local participant's consent decision for receiving a voice agent's media. */
+export const SET_VOICE_AGENT_CONSENT = 'SET_VOICE_AGENT_CONSENT';
+
+/** Saves (or forgets) the mute state from before a consent request muted the local participant. */
+export const SET_VOICE_AGENT_CONSENT_MUTE = 'SET_VOICE_AGENT_CONSENT_MUTE';
+
diff --git a/react/features/voice-agents/actions.ts b/react/features/voice-agents/actions.ts
new file mode 100644
index 0000000000..702449c614
--- /dev/null
+++ b/react/features/voice-agents/actions.ts
@@ -0,0 +1,203 @@
+import { batch } from 'react-redux';
+
+import { IStore } from '../app/types';
+import { hideDialog, openDialog } from '../base/dialog/actions';
+import { isDialogOpen } from '../base/dialog/functions';
+import { setAudioMuted, setAudioUnmutePermissions } from '../base/media/actions';
+
+import { SET_VOICE_AGENTS, SET_VOICE_AGENT_CONSENT, SET_VOICE_AGENT_CONSENT_MUTE } from './actionTypes';
+import VoiceAgentConsentDialog from './components/VoiceAgentConsentDialog';
+import { IVoiceAgentConsentMute, IVoiceAgents } from './types';
+
+const DIALOG_NAME = 'VoiceAgentConsentDialog';
+
+/**
+ * The props of the consent dialog.
+ */
+export interface IConsentDialogProps {
+ agentId?: string;
+ forcedMute?: boolean;
+}
+
+/**
+ * Saves, or forgets, the local participant's state from before a consent request muted them.
+ *
+ * @param {IVoiceAgentConsentMute} [consentMute] - The saved state; omitted to forget it.
+ * @returns {Object}
+ */
+function _setConsentMute(consentMute?: IVoiceAgentConsentMute) {
+ return {
+ type: SET_VOICE_AGENT_CONSENT_MUTE,
+ consentMute
+ };
+}
+
+/**
+ * Undoes a consent request's mute: releases the unmute block if the request took it, restores the mute state from
+ * before the request when asked to, and forgets the saved state.
+ *
+ * @param {Function} dispatch - The redux dispatch function.
+ * @param {IVoiceAgentConsentMute} consentMute - The saved state.
+ * @param {boolean} restoreMute - Whether to restore the mute state from before the request.
+ * @returns {void}
+ */
+function _releaseConsentMute(dispatch: IStore['dispatch'], consentMute: IVoiceAgentConsentMute, restoreMute: boolean) {
+ consentMute.tookBlock && dispatch(setAudioUnmutePermissions(false, true));
+ restoreMute && dispatch(setAudioMuted(consentMute.audioWasMuted, false));
+ dispatch(_setConsentMute());
+}
+
+/**
+ * Asks the local participant whether a newly active voice agent may hear them. Mirrors recording consent:
+ * the participant is muted, with unmuting blocked, until they decide. The block is released on the decision
+ * only if this request took it.
+ *
+ * @param {string} agentId - The agent asking for consent.
+ * @returns {Function}
+ */
+export function requestVoiceAgentConsent(agentId: string) {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const state = getState();
+ const { muted, unmuteBlocked } = state['features/base/media'].audio;
+
+ // Asked again after another dialog replaced this one: the state saved before the first mute is still the
+ // participant's own.
+ const saved = state['features/voice-agents'].consentMute;
+
+ batch(() => {
+ if (!unmuteBlocked) {
+ dispatch(setAudioUnmutePermissions(true, true));
+ }
+ dispatch(setAudioMuted(true));
+ dispatch(_setConsentMute({
+ agentId,
+ audioWasMuted: saved ? saved.audioWasMuted : muted,
+ tookBlock: Boolean(saved?.tookBlock) || !unmuteBlocked
+ }));
+ dispatch(openDialog(DIALOG_NAME, VoiceAgentConsentDialog, {
+ agentId,
+ forcedMute: true
+ }));
+ });
+ };
+}
+
+/**
+ * Re-opens the consent dialog for an agent the participant has not allowed yet (e.g. from the meeting
+ * label). The mute state is left as it is.
+ *
+ * @param {string} agentId - The agent to decide about.
+ * @returns {Function}
+ */
+export function showVoiceAgentConsentDialog(agentId: string) {
+ return (dispatch: IStore['dispatch']) => {
+ dispatch(openDialog(DIALOG_NAME, VoiceAgentConsentDialog, {
+ agentId,
+ forcedMute: false
+ }));
+ };
+}
+
+/**
+ * Lets the agent hear the local participant (and the participant hear the agent), restoring the mute state
+ * from before the consent request. A decision about another agent (e.g. from the external API while a forced
+ * request is up) leaves that request's mute alone.
+ *
+ * @param {string} agentId - The agent that was allowed.
+ * @returns {Function}
+ */
+export function allowVoiceAgent(agentId: string) {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const { consentMute } = getState()['features/voice-agents'];
+
+ batch(() => {
+ dispatch(setVoiceAgentConsent(agentId, true));
+ consentMute?.agentId === agentId && _releaseConsentMute(dispatch, consentMute, true);
+ dispatch(hideDialog(DIALOG_NAME, VoiceAgentConsentDialog));
+ });
+ };
+}
+
+/**
+ * Declines for now: the participant stays muted but may unmute for the other participants; the agent
+ * neither hears them nor is shown to them until they allow it later.
+ *
+ * @param {string} agentId - The agent that was declined.
+ * @returns {Function}
+ */
+export function declineVoiceAgent(agentId: string) {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const { consentMute } = getState()['features/voice-agents'];
+
+ batch(() => {
+ dispatch(setVoiceAgentConsent(agentId, false));
+ consentMute?.agentId === agentId && _releaseConsentMute(dispatch, consentMute, false);
+ dispatch(hideDialog(DIALOG_NAME, VoiceAgentConsentDialog));
+ });
+ };
+}
+
+/**
+ * The agent left before the participant decided: restores the mute state from before its request, whether or not
+ * its dialog is still up (another dialog may have replaced it), and closes the dialog if it is asking about it.
+ *
+ * @param {string} agentId - The agent that left.
+ * @returns {Function}
+ */
+export function dismissVoiceAgentConsentDialog(agentId: string) {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const state = getState();
+ const { consentMute } = state['features/voice-agents'];
+ const props = state['features/base/dialog'].componentProps as IConsentDialogProps | undefined;
+ const open = isDialogOpen(state, VoiceAgentConsentDialog) && props?.agentId === agentId;
+
+ batch(() => {
+ consentMute?.agentId === agentId && _releaseConsentMute(dispatch, consentMute, true);
+ open && dispatch(hideDialog(DIALOG_NAME, VoiceAgentConsentDialog));
+ });
+ };
+}
+
+/**
+ * Releases the unmute block of a consent request still undecided when the room changes: its dialog is gone, and the
+ * block would keep the participant from unmuting in the next room.
+ *
+ * @returns {Function}
+ */
+export function releaseVoiceAgentConsentMute() {
+ return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {
+ const { consentMute } = getState()['features/voice-agents'];
+
+ consentMute && _releaseConsentMute(dispatch, consentMute, false);
+ };
+}
+
+/**
+ * Updates the known set of voice agents (mirrored from room metadata).
+ *
+ * @param {IVoiceAgents} agents - The agents, keyed by agent id.
+ * @returns {Object}
+ */
+export function setVoiceAgents(agents: IVoiceAgents) {
+ return {
+ type: SET_VOICE_AGENTS,
+ agents
+ };
+}
+
+/**
+ * Records the local participant's consent decision for receiving a voice agent's media. Allowing
+ * subscribes to the agent's audio source (making it audible); disallowing unsubscribes.
+ *
+ * @param {string} agentId - The agent the decision applies to.
+ * @param {boolean} allowed - Whether receiving the agent's media is allowed.
+ * @returns {Object}
+ */
+export function setVoiceAgentConsent(agentId: string, allowed: boolean) {
+ return {
+ type: SET_VOICE_AGENT_CONSENT,
+ agentId,
+ allowed
+ };
+}
+
diff --git a/react/features/voice-agents/components/VoiceAgentConsentDialog.native.tsx b/react/features/voice-agents/components/VoiceAgentConsentDialog.native.tsx
new file mode 100644
index 0000000000..14c25205be
--- /dev/null
+++ b/react/features/voice-agents/components/VoiceAgentConsentDialog.native.tsx
@@ -0,0 +1,70 @@
+import React, { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import Dialog from 'react-native-dialog';
+import { useDispatch, useSelector } from 'react-redux';
+
+import { IReduxState } from '../../app/types';
+import ConfirmDialog from '../../base/dialog/components/native/ConfirmDialog';
+import Link from '../../base/react/components/native/Link';
+import { allowVoiceAgent, declineVoiceAgent } from '../actions';
+
+interface IProps {
+
+ /**
+ * The agent asking for consent.
+ */
+ agentId: string;
+
+ /**
+ * Whether the participant was muted for the decision (initial request) or opened the dialog themselves.
+ */
+ forcedMute?: boolean;
+}
+
+/**
+ * Asks whether a voice agent may hear the local participant (which also makes the agent audible and
+ * visible to them).
+ *
+ * @param {IProps} props - The props.
+ * @returns {JSX.Element}
+ */
+export default function VoiceAgentConsentDialog({ agentId, forcedMute }: IProps) {
+ const dispatch = useDispatch();
+ const { t } = useTranslation();
+ const agent = useSelector((state: IReduxState) => state['features/voice-agents'].agents[agentId]);
+ const consentLearnMoreLink = useSelector(
+ (state: IReduxState) => state['features/base/config'].voiceAgents?.consentLearnMoreLink);
+ const name = agent?.displayName ?? agentId;
+
+ const allow = useCallback(() => {
+ dispatch(allowVoiceAgent(agentId));
+
+ return true;
+ }, [ agentId ]);
+
+ const decline = useCallback(() => {
+ dispatch(declineVoiceAgent(agentId));
+
+ return true;
+ }, [ agentId ]);
+
+ return (
+ <ConfirmDialog
+ cancelLabel = { 'voiceAgents.notNow' }
+ confirmLabel = { 'voiceAgents.allow' }
+ onCancel = { decline }
+ onSubmit = { allow }
+ title = { 'voiceAgents.nativeTitle' }
+ verticalButtons = { true }>
+ <Dialog.Description>
+ { `${t('voiceAgents.consentTitle', { name })}. ` }
+ { t(forcedMute ? 'voiceAgents.consentDescriptionMuted' : 'voiceAgents.consentDescription') }
+ { consentLearnMoreLink && (
+ <Link url = { consentLearnMoreLink }>
+ { ` (${t('dialog.learnMore')})` }
+ </Link>
+ ) }
+ </Dialog.Description>
+ </ConfirmDialog>
+ );
+}
diff --git a/react/features/voice-agents/components/VoiceAgentConsentDialog.web.tsx b/react/features/voice-agents/components/VoiceAgentConsentDialog.web.tsx
new file mode 100644
index 0000000000..1e98111ac4
--- /dev/null
+++ b/react/features/voice-agents/components/VoiceAgentConsentDialog.web.tsx
@@ -0,0 +1,78 @@
+import React, { useCallback, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useDispatch, useSelector } from 'react-redux';
+
+import { IReduxState } from '../../app/types';
+import Dialog from '../../base/ui/components/web/Dialog';
+import { allowVoiceAgent, declineVoiceAgent } from '../actions';
+
+interface IProps {
+
+ /**
+ * The agent asking for consent.
+ */
+ agentId: string;
+
+ /**
+ * Whether the participant was muted for the decision (initial request) or opened the dialog themselves.
+ */
+ forcedMute?: boolean;
+}
+
+/**
+ * Asks whether a voice agent may hear the local participant (which also makes the agent audible and
+ * visible to them). Cannot be dismissed without a decision, like the recording consent dialog.
+ *
+ * @param {IProps} props - The props.
+ * @returns {JSX.Element}
+ */
+export default function VoiceAgentConsentDialog({ agentId, forcedMute }: IProps) {
+ const { t } = useTranslation();
+ const dispatch = useDispatch();
+ const agent = useSelector((state: IReduxState) => state['features/voice-agents'].agents[agentId]);
+ const consentLearnMoreLink = useSelector(
+ (state: IReduxState) => state['features/base/config'].voiceAgents?.consentLearnMoreLink);
+ const name = agent?.displayName ?? agentId;
+
+ useEffect(() => {
+ APP.API.notifyVoiceAgentConsentDialogOpen(true, agentId);
+
+ return () => {
+ APP.API.notifyVoiceAgentConsentDialogOpen(false, agentId);
+ };
+ }, [ agentId ]);
+
+ const allow = useCallback(() => {
+ dispatch(allowVoiceAgent(agentId));
+ }, [ agentId ]);
+
+ const decline = useCallback(() => {
+ dispatch(declineVoiceAgent(agentId));
+ }, [ agentId ]);
+
+ return (
+ <Dialog
+ cancel = {{ translationKey: 'voiceAgents.notNow' }}
+ disableBackdropClose = { true }
+ disableEscape = { true }
+ hideCloseButton = { true }
+ ok = {{ translationKey: 'voiceAgents.allow' }}
+ onCancel = { decline }
+ onSubmit = { allow }
+ title = { t('voiceAgents.consentTitle', { name }) }>
+ { t(forcedMute ? 'voiceAgents.consentDescriptionMuted' : 'voiceAgents.consentDescription') }
+ { consentLearnMoreLink && (
+ <>
+ {' '}
+ <a
+ href = { consentLearnMoreLink }
+ rel = 'noopener noreferrer'
+ target = '_blank'>
+ { t('dialog.learnMore') }
+ </a>
+ {'.'}
+ </>
+ ) }
+ </Dialog>
+ );
+}
diff --git a/react/features/voice-agents/components/web/VoiceAgentLabel.tsx b/react/features/voice-agents/components/web/VoiceAgentLabel.tsx
new file mode 100644
index 0000000000..eed4ea0884
--- /dev/null
+++ b/react/features/voice-agents/components/web/VoiceAgentLabel.tsx
@@ -0,0 +1,68 @@
+import React, { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useDispatch, useSelector } from 'react-redux';
+import { makeStyles } from 'tss-react/mui';
+
+import { IReduxState } from '../../../app/types';
+import { IconAI } from '../../../base/icons/svg';
+import Label from '../../../base/label/components/web/Label';
+import Tooltip from '../../../base/tooltip/components/Tooltip';
+import { showVoiceAgentConsentDialog } from '../../actions';
+import { getVoiceAgentAwaitingConsent, isVoiceAgentBlockedByE2EE } from '../../functions';
+
+const useStyles = makeStyles()(theme => {
+ return {
+ agent: {
+ background: theme.palette.action01
+ }
+ };
+});
+
+/**
+ * Conference-header label shown to everyone while a voice agent is in the meeting. Clicking it reopens the
+ * consent dialog for an agent the local participant has not allowed yet.
+ *
+ * @returns {ReactElement|null}
+ */
+const VoiceAgentLabel = () => {
+ const { classes: styles } = useStyles();
+ const { t } = useTranslation();
+ const dispatch = useDispatch();
+ const agents = useSelector((state: IReduxState) => state['features/voice-agents'].agents);
+ const awaiting = useSelector(getVoiceAgentAwaitingConsent);
+ const blocked = useSelector(isVoiceAgentBlockedByE2EE);
+
+ const onClick = useCallback(() => {
+ if (awaiting) {
+ dispatch(showVoiceAgentConsentDialog(awaiting));
+ }
+ }, [ awaiting ]);
+
+ const names = Object.values(agents).map(agent => agent.displayName).filter(Boolean)
+ .join(', ');
+
+ if (!names) {
+ return null;
+ }
+
+ let tooltipKey = awaiting ? 'voiceAgents.labelTooltipAllow' : 'voiceAgents.labelTooltip';
+
+ if (blocked) {
+ tooltipKey = 'voiceAgents.labelTooltipE2EE';
+ }
+ const content = t(tooltipKey, { names });
+
+ return (
+ <Tooltip
+ content = { content }
+ position = { 'bottom' }>
+ <Label
+ accessibilityText = { content }
+ className = { styles.agent }
+ icon = { IconAI }
+ onClick = { awaiting ? onClick : undefined } />
+ </Tooltip>
+ );
+};
+
+export default VoiceAgentLabel;
diff --git a/react/features/voice-agents/functions.ts b/react/features/voice-agents/functions.ts
new file mode 100644
index 0000000000..e64df179a4
--- /dev/null
+++ b/react/features/voice-agents/functions.ts
@@ -0,0 +1,178 @@
+import { IReduxState } from '../app/types';
+import { getCurrentConference } from '../base/conference/functions';
+import { isAnyDialogOpen } from '../base/dialog/functions';
+import { isE2EEOnInMeeting } from '../e2ee/functions';
+import { iAmVisitor } from '../visitors/functions';
+
+import { IVoiceAgent, IVoiceAgents } from './types';
+
+/**
+ * Keys that must never be used as object keys, since assigning them can pollute the prototype chain.
+ * Agent ids come from room metadata (server-controlled, but treated as untrusted at this boundary).
+ */
+const UNSAFE_KEYS = new Set([ '__proto__', 'constructor', 'prototype' ]);
+
+/** Reserved id namespace for agents; requiring it stops a metadata id shadowing a real participant. */
+const AGENT_ID_PREFIX = 'agent-';
+
+/**
+ * Whether an agent id is safe to mirror: it must be in the reserved `agent-` namespace and not a
+ * prototype-pollution key.
+ *
+ * @param {string} agentId - The agent id.
+ * @returns {boolean}
+ */
+export function isSafeAgentId(agentId: string): boolean {
+ return agentId.startsWith(AGENT_ID_PREFIX) && !UNSAFE_KEYS.has(agentId);
+}
+
+/**
+ * Drops any prototype-pollution-prone keys from an agents map before it is stored or acted on.
+ *
+ * @param {IVoiceAgents} agents - The agents map from metadata.
+ * @returns {IVoiceAgents}
+ */
+export function sanitizeAgents(agents: IVoiceAgents): IVoiceAgents {
+ const safe: IVoiceAgents = {};
+
+ for (const [ agentId, agent ] of Object.entries(agents)) {
+ if (isSafeAgentId(agentId)) {
+ safe[agentId] = agent;
+ }
+ }
+
+ return safe;
+}
+
+/**
+ * Whether a voice agent is present in the room: its media leg is up (state `active`). While it is being
+ * provisioned it is not shown, so an agent whose allocation fails never joins the roster or fires the join and
+ * leave notifications. A missing state (older deployments) counts as present.
+ *
+ * @param {IVoiceAgent} agent - The agent.
+ * @returns {boolean}
+ */
+export function isVoiceAgentPresent(agent: IVoiceAgent): boolean {
+ return agent.state === undefined || agent.state === 'active';
+}
+
+/**
+ * Keeps only the agents that are present in the room (see {@link isVoiceAgentPresent}).
+ *
+ * @param {IVoiceAgents} agents - The agents map from metadata.
+ * @returns {IVoiceAgents}
+ */
+export function pickPresentAgents(agents: IVoiceAgents): IVoiceAgents {
+ const present: IVoiceAgents = {};
+
+ for (const [ agentId, agent ] of Object.entries(agents)) {
+ if (isVoiceAgentPresent(agent)) {
+ present[agentId] = agent;
+ }
+ }
+
+ return present;
+}
+
+/**
+ * Whether receiving a voice agent's media requires an explicit user consent. Defaults to false, so every
+ * participant is subscribed automatically; a deployment can ask first with `config.voiceAgents.requireConsent: true`.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean}
+ */
+export function isVoiceAgentConsentRequired(state: IReduxState): boolean {
+ return state['features/base/config'].voiceAgents?.requireConsent === true;
+}
+
+/**
+ * Whether anyone in the meeting has end-to-end encryption on. Agents cannot take part then: the bridge would hand
+ * them ciphertext, and the audio they inject is not encrypted with the meeting's keys.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean}
+ */
+export function isVoiceAgentBlockedByE2EE(state: IReduxState): boolean {
+ return isE2EEOnInMeeting(state);
+}
+
+/**
+ * Whether the local participant must be asked before an agent may hear them. Recorders and visitors are
+ * never exported and simply receive the agent, so they are not asked.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean}
+ */
+export function shouldAskForVoiceAgentConsent(state: IReduxState): boolean {
+ return isVoiceAgentConsentRequired(state)
+ && !state['features/base/config'].iAmRecorder
+ && !iAmVisitor(state);
+}
+
+/**
+ * The ids of the present agents the local participant has allowed to hear them.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {Array<string>}
+ */
+export function getAllowedAgentIds(state: IReduxState): string[] {
+ const { agents, consent } = state['features/voice-agents'];
+
+ return Object.keys(agents).filter(agentId => consent[agentId] === true);
+}
+
+/**
+ * A present agent the local participant has not allowed yet, if any (the one the meeting label offers to
+ * decide about).
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {string|undefined}
+ */
+export function getVoiceAgentAwaitingConsent(state: IReduxState): string | undefined {
+ if (isVoiceAgentBlockedByE2EE(state)) {
+ return undefined;
+ }
+ const { agents, consent } = state['features/voice-agents'];
+
+ return Object.keys(agents).find(agentId => consent[agentId] !== true);
+}
+
+/**
+ * The agent to ask for consent now, if any: one agent at a time, and only while no other dialog is open, because
+ * opening over one (e.g. recording consent) would replace it and this decision would then release its mute.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {string|undefined}
+ */
+export function getNextVoiceAgentConsentRequest(state: IReduxState): string | undefined {
+ if (!getCurrentConference(state)
+ || !shouldAskForVoiceAgentConsent(state)
+ || isVoiceAgentBlockedByE2EE(state)
+ || isAnyDialogOpen(state)) {
+ return undefined;
+ }
+ const { agents, consent } = state['features/voice-agents'];
+
+ return Object.keys(agents).find(agentId => consent[agentId] === undefined);
+}
+
+
+/**
+ * The source names of the voice agents the local participant currently receives: agents still present
+ * in the room whose consent decision is 'allowed'.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {Array<string>}
+ */
+export function getConsentedAgentSourceNames(state: IReduxState): string[] {
+ const { agents, consent } = state['features/voice-agents'];
+ const sourceNames: string[] = [];
+
+ for (const [ agentId, agent ] of Object.entries(agents)) {
+ if (consent[agentId] && agent.sourceName) {
+ sourceNames.push(agent.sourceName);
+ }
+ }
+
+ return sourceNames;
+}
diff --git a/react/features/voice-agents/logger.ts b/react/features/voice-agents/logger.ts
new file mode 100644
index 0000000000..993c00492d
--- /dev/null
+++ b/react/features/voice-agents/logger.ts
@@ -0,0 +1,3 @@
+import { getLogger } from '../base/logging/functions';
+
+export default getLogger('features/voice-agents');
diff --git a/react/features/voice-agents/middleware.ts b/react/features/voice-agents/middleware.ts
new file mode 100644
index 0000000000..4c61e3ee80
--- /dev/null
+++ b/react/features/voice-agents/middleware.ts
@@ -0,0 +1,375 @@
+import { IStore } from '../app/types';
+import { CONFERENCE_JOINED, SET_ROOM, UPDATE_CONFERENCE_METADATA } from '../base/conference/actionTypes';
+import { getCurrentConference } from '../base/conference/functions';
+import { IJitsiConference } from '../base/conference/reducer';
+import { participantJoined, participantLeft, participantUpdated } from '../base/participants/actions';
+import { PARTICIPANT_JOINED_SOUND_ID, PARTICIPANT_LEFT_SOUND_ID } from '../base/participants/constants';
+import { getParticipantById } from '../base/participants/functions';
+import { FakeParticipant } from '../base/participants/types';
+import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
+import StateListenerRegistry from '../base/redux/StateListenerRegistry';
+import { playSound } from '../base/sounds/actions';
+import {
+ showNotification,
+ showParticipantJoinedNotification,
+ showParticipantLeftNotification
+} from '../notifications/actions';
+import { NOTIFICATION_TIMEOUT_TYPE } from '../notifications/constants';
+import { joinLeaveNotificationsDisabled } from '../notifications/functions';
+
+import { SET_VOICE_AGENT_CONSENT } from './actionTypes';
+import {
+ dismissVoiceAgentConsentDialog,
+ releaseVoiceAgentConsentMute,
+ requestVoiceAgentConsent,
+ setVoiceAgentConsent,
+ setVoiceAgents
+} from './actions';
+import {
+ getAllowedAgentIds,
+ getConsentedAgentSourceNames,
+ getNextVoiceAgentConsentRequest,
+ isVoiceAgentBlockedByE2EE,
+ pickPresentAgents,
+ sanitizeAgents,
+ shouldAskForVoiceAgentConsent
+} from './functions';
+import logger from './logger';
+import { IVoiceAgents } from './types';
+
+/**
+ * The local-participant presence property carrying the ids of the agents allowed to hear this participant.
+ * Jicofo derives each agent's export list from it, so nothing is exported to an agent without it.
+ */
+export const CONSENT_PRESENCE_PROPERTY = 'voiceAgentConsent';
+
+/** Conferences already warned about for lacking the agent audio subscription API. */
+const warnedNoSubscriptionApi = new WeakSet<object>();
+
+/**
+ * Middleware that mirrors the `agents` room metadata into the conference. An active agent first asks the
+ * local participant for consent; once allowed it is shown as a fake participant (the roster entry), the
+ * agent is told it may hear the participant (presence property read by jicofo), and the participant
+ * subscribes to the agent's synthetic audio source (voice-agents synthetic-audio service in lib-jitsi-meet,
+ * which co-exists with audio translation). An agent that is still provisioning, whose provisioning failed,
+ * or that the participant has not allowed is not shown.
+ */
+MiddlewareRegistry.register(store => next => action => {
+ const result = next(action);
+
+ switch (action.type) {
+ case UPDATE_CONFERENCE_METADATA: {
+ // Cleared (null) on every conference change, a reconnect included: that removes no agent. The agents and
+ // this participant's decisions are kept, so a rejoin neither asks again nor re-announces anyone; the tiles
+ // go with the conference and CONFERENCE_JOINED puts them back.
+ if (action.metadata === null) {
+ break;
+ }
+
+ // Metadata is server-written but treated as untrusted here: drop prototype-pollution-prone ids
+ // before they are used as object keys / participant ids. Only active agents count as present.
+ const agents: IVoiceAgents = pickPresentAgents(sanitizeAgents(action.metadata?.agents ?? {}));
+
+ _agentsChanged(store, agents);
+ break;
+ }
+ case SET_ROOM:
+ // Another room: nothing known or decided about the previous one's agents carries over.
+ store.dispatch(releaseVoiceAgentConsentMute());
+ store.dispatch(setVoiceAgents({}));
+ break;
+ case SET_VOICE_AGENT_CONSENT:
+ _consentChanged(store, action.agentId, action.allowed);
+ break;
+ case CONFERENCE_JOINED:
+ _syncParticipants(store);
+
+ // A decision taken before the join completed may predate the presence; advertise it again.
+ _syncConsent(store);
+ break;
+ }
+
+ return result;
+});
+
+/**
+ * Encryption came on or went off in the meeting: the local toggle, or a participant this client doesn't follow.
+ */
+StateListenerRegistry.register(
+ state => isVoiceAgentBlockedByE2EE(state),
+ (blocked, store) => _e2eeChanged(store, blocked));
+
+/**
+ * Asks about agents awaiting consent, one at a time, whenever no other dialog is open.
+ */
+StateListenerRegistry.register(
+ state => getNextVoiceAgentConsentRequest(state),
+ (agentId, { dispatch }) => {
+ agentId && dispatch(requestVoiceAgentConsent(agentId));
+ });
+
+/**
+ * Diffs the advertised agents against the known set: asks for consent for new agents, and removes the
+ * roster entry, any pending consent dialog and the subscription of agents that left.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {IVoiceAgents} agents - The active agents from the updated room metadata.
+ * @returns {void}
+ */
+function _agentsChanged(store: IStore, agents: IVoiceAgents) {
+ const { dispatch, getState } = store;
+ const state = getState();
+ const previous = state['features/voice-agents']?.agents ?? {};
+ const conference = getCurrentConference(state);
+ const added = Object.keys(agents).filter(id => !(id in previous));
+ const removed = Object.keys(previous).filter(id => !(id in agents));
+ const changed = Object.keys(agents).filter(id => id in previous
+ && (previous[id].displayName !== agents[id].displayName || previous[id].sourceName !== agents[id].sourceName));
+
+ if (added.length === 0 && removed.length === 0 && changed.length === 0) {
+ return;
+ }
+
+ dispatch(setVoiceAgents(agents));
+
+ for (const agentId of changed) {
+ if (conference && previous[agentId].displayName !== agents[agentId].displayName
+ && getParticipantById(state, agentId)) {
+ dispatch(participantUpdated({ conference, id: agentId, name: agents[agentId].displayName }));
+ }
+ }
+
+ for (const agentId of removed) {
+ logger.info(`Voice agent left: ${agentId}`);
+ _announcePresence(store, previous[agentId]?.displayName ?? agentId, false);
+ dispatch(dismissVoiceAgentConsentDialog(agentId));
+
+ // Metadata is cleared (null) when the conference is left, at which point base/participants purges
+ // the fake participants on its own.
+ if (conference && getParticipantById(state, agentId)) {
+ dispatch(participantLeft(agentId, conference, { fakeParticipant: FakeParticipant.Agent }));
+ }
+ }
+
+ if (!conference) {
+ return;
+ }
+
+ for (const agentId of added) {
+ logger.info(`Voice agent active: ${agentId} (${agents[agentId].displayName})`);
+
+ // Under E2EE the participant is told the agent is unavailable instead.
+ if (!isVoiceAgentBlockedByE2EE(state)) {
+ _announcePresence(store, agents[agentId].displayName ?? agentId, true);
+ }
+ _admitAgent(store, agentId);
+ }
+
+ // Consent entries of removed agents were pruned by setVoiceAgents, and a renamed source needs a new
+ // subscription; re-advertise what is left.
+ if (removed.length > 0 || changed.some(id => previous[id].sourceName !== agents[id].sourceName)) {
+ _syncConsent(store);
+ }
+}
+
+/**
+ * Puts the agents' roster entries back after a (re)join: the tiles go with the conference, the agents and the
+ * decisions about them do not. Agents not decided about yet are let in as when they first appeared.
+ *
+ * @param {IStore} store - The redux store.
+ * @returns {void}
+ */
+function _syncParticipants(store: IStore) {
+ const state = store.getState();
+ const conference = getCurrentConference(state);
+
+ if (!conference) {
+ return;
+ }
+ const { agents, consent } = state['features/voice-agents'];
+ const blocked = isVoiceAgentBlockedByE2EE(state);
+
+ for (const [ agentId, agent ] of Object.entries(agents)) {
+ if (consent[agentId] === undefined) {
+ _admitAgent(store, agentId);
+ } else if (consent[agentId] === true && !blocked) {
+ _addAgentParticipant(store, conference, agentId, agent.displayName);
+ }
+ }
+}
+
+/**
+ * Puts an agent on the roster, unless it is already there.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {IJitsiConference} conference - The conference the agent is in.
+ * @param {string} agentId - The agent.
+ * @param {string} [name] - The agent's display name.
+ * @returns {void}
+ */
+function _addAgentParticipant({ dispatch, getState }: IStore, conference: IJitsiConference, agentId: string,
+ name?: string) {
+ if (!getParticipantById(getState(), agentId)) {
+ dispatch(participantJoined({ conference, fakeParticipant: FakeParticipant.Agent, id: agentId, name }));
+ }
+}
+
+/**
+ * Applies a consent decision: an allowed agent joins the roster for this participant, a declined one is
+ * hidden, and both directions of audio follow the decision.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} agentId - The agent the decision applies to.
+ * @param {boolean} allowed - Whether the agent may hear the participant.
+ * @returns {void}
+ */
+function _consentChanged(store: IStore, agentId: string, allowed: boolean) {
+ const { dispatch, getState } = store;
+ const state = getState();
+ const conference = getCurrentConference(state);
+ const agent = state['features/voice-agents'].agents[agentId];
+
+ if (!conference || !agent) {
+ return;
+ }
+
+ const participant = getParticipantById(state, agentId);
+
+ // A decision taken in a dialog opened before encryption came on must not bring the agent back.
+ if (allowed && isVoiceAgentBlockedByE2EE(state)) {
+ _syncConsent(store);
+
+ return;
+ }
+
+ if (allowed) {
+ _addAgentParticipant(store, conference, agentId, agent.displayName);
+ } else if (participant) {
+ dispatch(participantLeft(agentId, conference, { fakeParticipant: FakeParticipant.Agent }));
+ }
+
+ _syncConsent(store);
+}
+
+/**
+ * Lets a newly present agent in: allows it unless the deployment requires consent, which the consent listener
+ * then asks for. In an end-to-end encrypted meeting the agent cannot take part, so the participant is told instead.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} agentId - The agent.
+ * @returns {void}
+ */
+function _admitAgent({ dispatch, getState }: IStore, agentId: string) {
+ const state = getState();
+
+ if (isVoiceAgentBlockedByE2EE(state)) {
+ _notifyE2EEUnsupported(dispatch, state['features/voice-agents'].agents[agentId]?.displayName, agentId);
+ } else if (!shouldAskForVoiceAgentConsent(state)) {
+ dispatch(setVoiceAgentConsent(agentId, true));
+ }
+}
+
+/**
+ * Announces an agent joining or leaving the meeting like a participant, with the same notification and sound. Its
+ * tile can't drive this, since it also comes and goes with this participant's consent and E2EE.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {string} name - The agent's display name.
+ * @param {boolean} joined - Whether the agent joined (or left).
+ * @returns {void}
+ */
+function _announcePresence({ dispatch, getState }: IStore, name: string, joined: boolean) {
+ const state = getState();
+ const { soundsParticipantJoined, soundsParticipantLeft } = state['features/base/settings'];
+
+ // Like participants', not for those already in the meeting when it is joined, nor on leaving it.
+ if (!state['features/base/conference'].conference) {
+ return;
+ }
+ if (!joinLeaveNotificationsDisabled()) {
+ dispatch(joined ? showParticipantJoinedNotification(name) : showParticipantLeftNotification(name));
+ }
+ if (joined ? soundsParticipantJoined : soundsParticipantLeft) {
+ dispatch(playSound(joined ? PARTICIPANT_JOINED_SOUND_ID : PARTICIPANT_LEFT_SOUND_ID));
+ }
+}
+
+/**
+ * End-to-end encryption was turned on or off. On: agents stop hearing and being heard by this participant and
+ * their tiles go. Off: present agents are let in again as if they had just joined, or shown again if allowed.
+ *
+ * @param {IStore} store - The redux store.
+ * @param {boolean} enabled - Whether encryption is now on.
+ * @returns {void}
+ */
+function _e2eeChanged(store: IStore, enabled: boolean) {
+ const { dispatch, getState } = store;
+ const state = getState();
+ const conference = getCurrentConference(state);
+ const { agents, consent } = state['features/voice-agents'];
+
+ if (!conference) {
+ return;
+ }
+
+ for (const [ agentId, agent ] of Object.entries(agents)) {
+ if (enabled) {
+ dispatch(dismissVoiceAgentConsentDialog(agentId));
+ if (getParticipantById(state, agentId)) {
+ dispatch(participantLeft(agentId, conference, { fakeParticipant: FakeParticipant.Agent }));
+ }
+ _notifyE2EEUnsupported(dispatch, agent.displayName, agentId);
+ } else if (consent[agentId] === true) {
+ _addAgentParticipant(store, conference, agentId, agent.displayName);
+ } else if (consent[agentId] === undefined) {
+ _admitAgent(store, agentId);
+ }
+ }
+
+ _syncConsent(store);
+}
+
+/**
+ * Tells the participant an agent cannot take part while the meeting is end-to-end encrypted.
+ *
+ * @param {Function} dispatch - The redux dispatch function.
+ * @param {string|undefined} name - The agent's display name.
+ * @param {string} agentId - The agent, which keys the notification so it is shown once.
+ * @returns {void}
+ */
+function _notifyE2EEUnsupported(dispatch: IStore['dispatch'], name: string | undefined, agentId: string) {
+ dispatch(showNotification({
+ descriptionKey: 'voiceAgents.e2eeUnsupportedDescription',
+ titleArguments: { name: name ?? '' },
+ titleKey: 'voiceAgents.e2eeUnsupportedTitle',
+ uid: `voice-agent-e2ee-${agentId}`
+ }, NOTIFICATION_TIMEOUT_TYPE.LONG));
+}
+
+/**
+ * Advertises the allowed agents in presence (for jicofo to build the agents' export lists) and subscribes
+ * to their audio sources through the conference's voice-agents synthetic-audio subscription. Nothing is
+ * advertised or subscribed while the meeting is end-to-end encrypted.
+ *
+ * @param {IStore} store - The redux store.
+ * @returns {void}
+ */
+function _syncConsent({ getState }: IStore) {
+ const state = getState();
+ const conference: IJitsiConference | undefined = getCurrentConference(state);
+
+ if (!conference) {
+ return;
+ }
+ const blocked = isVoiceAgentBlockedByE2EE(state);
+
+ conference.setLocalParticipantProperty(CONSENT_PRESENCE_PROPERTY,
+ JSON.stringify(blocked ? [] : getAllowedAgentIds(state)));
+
+ if (typeof conference.setAgentAudioSubscription === 'function') {
+ conference.setAgentAudioSubscription(blocked ? [] : getConsentedAgentSourceNames(state));
+ } else if (!warnedNoSubscriptionApi.has(conference)) {
+ warnedNoSubscriptionApi.add(conference);
+ logger.warn('This lib-jitsi-meet has no setAgentAudioSubscription: voice agents will not be audible.');
+ }
+}
diff --git a/react/features/voice-agents/reducer.ts b/react/features/voice-agents/reducer.ts
new file mode 100644
index 0000000000..d9f23bf034
--- /dev/null
+++ b/react/features/voice-agents/reducer.ts
@@ -0,0 +1,89 @@
+import ReducerRegistry from '../base/redux/ReducerRegistry';
+
+import { SET_VOICE_AGENTS, SET_VOICE_AGENT_CONSENT, SET_VOICE_AGENT_CONSENT_MUTE } from './actionTypes';
+import { isSafeAgentId, sanitizeAgents } from './functions';
+import { IVoiceAgentConsentMute, IVoiceAgents } from './types';
+
+type AgentFlags = { [agentId: string]: boolean; };
+
+export interface IVoiceAgentsState {
+
+ /**
+ * The known voice agents, mirrored from room metadata.
+ */
+ agents: IVoiceAgents;
+
+ /**
+ * The local participant's consent decisions, by agent id. Absent = not yet decided (a pending
+ * consent notification, or consent not required). Entries for agents that left are pruned so a
+ * re-provisioned agent with the same id asks again.
+ */
+ consent: AgentFlags;
+
+ /**
+ * The local participant's state from before a consent request muted them. Kept until that agent is decided about
+ * or leaves, not with the dialog: another dialog can replace this one, and the request asked again must still
+ * restore the participant's own state, not the forced one.
+ */
+ consentMute?: IVoiceAgentConsentMute;
+}
+
+const DEFAULT_STATE: IVoiceAgentsState = {
+ agents: {},
+ consent: {}
+};
+
+/**
+ * Drops entries for agents no longer present (stale consent once an agent leaves).
+ *
+ * @param {AgentFlags} map - The per-agent flags to prune.
+ * @param {IVoiceAgents} agents - The currently known agents.
+ * @returns {AgentFlags}
+ */
+function pruneToAgents(map: AgentFlags, agents: IVoiceAgents): AgentFlags {
+ const pruned: AgentFlags = {};
+
+ for (const [ agentId, value ] of Object.entries(map)) {
+ if (agentId in agents) {
+ pruned[agentId] = value;
+ }
+ }
+
+ return pruned;
+}
+
+/**
+ * Whether a per-agent flag may be recorded for this id: it must be safe (`in` reports __proto__ as present)
+ * and currently known.
+ *
+ * @param {IVoiceAgentsState} state - The feature state.
+ * @param {string} agentId - The agent id.
+ * @returns {boolean}
+ */
+function isKnownAgent(state: IVoiceAgentsState, agentId: string): boolean {
+ return isSafeAgentId(agentId) && agentId in state.agents;
+}
+
+ReducerRegistry.register<IVoiceAgentsState>(
+ 'features/voice-agents',
+ (state = DEFAULT_STATE, action): IVoiceAgentsState => {
+ switch (action.type) {
+ case SET_VOICE_AGENTS: {
+ const agents = sanitizeAgents(action.agents ?? {});
+
+ return {
+ ...state,
+ agents,
+ consent: pruneToAgents(state.consent, agents)
+ };
+ }
+ case SET_VOICE_AGENT_CONSENT:
+ return isKnownAgent(state, action.agentId)
+ ? { ...state, consent: { ...state.consent, [action.agentId]: action.allowed } }
+ : state;
+ case SET_VOICE_AGENT_CONSENT_MUTE:
+ return { ...state, consentMute: action.consentMute };
+ }
+
+ return state;
+ });
diff --git a/react/features/voice-agents/types.ts b/react/features/voice-agents/types.ts
new file mode 100644
index 0000000000..be03f05171
--- /dev/null
+++ b/react/features/voice-agents/types.ts
@@ -0,0 +1,41 @@
+/**
+ * The provisioning lifecycle of a voice agent, as reported by the prosody module. Only an `active` agent is
+ * mirrored into the room; the rest have no media leg yet, or never will.
+ */
+export type VoiceAgentState = 'provisioning' | 'connecting' | 'active' | 'failed' | 'ended';
+
+/**
+ * A voice agent (bot participant) as advertised through room metadata by the voice-agent prosody module.
+ */
+export interface IVoiceAgent {
+ displayName?: string;
+
+ /**
+ * The agent's synthetic audio source name (by convention `<agentId>-a0`). Subscribing to it is what
+ * makes the agent audible.
+ */
+ sourceName?: string;
+
+ /** The agent's lifecycle state. Absent on older deployments, which is treated as present. */
+ state?: VoiceAgentState;
+}
+
+/**
+ * The local participant's state from before a consent request muted them, and the agent it was for.
+ */
+export interface IVoiceAgentConsentMute {
+ agentId: string;
+
+ /** Whether the participant was muted before the request. */
+ audioWasMuted: boolean;
+
+ /** Whether the request blocked unmuting itself, and so must release the block. */
+ tookBlock: boolean;
+}
+
+/**
+ * The known voice agents, keyed by agent id.
+ */
+export interface IVoiceAgents {
+ [agentId: string]: IVoiceAgent;
+}
diff --git a/resources/prosody-plugins/mod_room_metadata_component.lua b/resources/prosody-plugins/mod_room_metadata_component.lua
index 2cfe9cd834..9e3444d22f 100644
--- a/resources/prosody-plugins/mod_room_metadata_component.lua
+++ b/resources/prosody-plugins/mod_room_metadata_component.lua
@@ -104,6 +104,7 @@ local extdisco_occpuant_check = module:get_option_boolean('extdisco_occpuant_che
-- metadata message API. These are either server-controlled fields or keys whose
-- values are assembled and injected by the server at broadcast time.
local blocked_metadata_keys = module:get_option_set('room_metadata_blocked_keys', {
+ 'agents',
'allownersEnabled',
'asyncTranscription',
'audioTranslationAvailable',
diff --git a/resources/prosody-plugins/mod_voice_agent_component.lua b/resources/prosody-plugins/mod_voice_agent_component.lua
new file mode 100644
index 0000000000..eb91219bb4
--- /dev/null
+++ b/resources/prosody-plugins/mod_voice_agent_component.lua
@@ -0,0 +1,1257 @@
+-- mod_voice_agent_component.lua
+--
+-- HTTP module that provisions voice agents (bot participants) for a room.
+-- Intended for internal system use (the JaaS provisioning API), not for
+-- end-user clients — the same trust model as mod_muc_jigasi_invite.
+--
+-- A voice agent is not a MUC occupant: its presence is advertised to clients
+-- through room metadata (the 'agents' key), and its media runs bridge-side (a
+-- synthetic colibri2 endpoint jicofo allocates when it sees the agent in the
+-- admin-only metadata). Clients render the roster entry from the metadata and,
+-- after user consent, subscribe to the agent's audio source by name.
+--
+-- ── State ─────────────────────────────────────────────────────────────────────
+-- Client-facing (broadcast to all occupants via mod_room_metadata_component):
+-- room.jitsiMetadata.agents[agentId] = {
+-- kind = 'agent', displayName = <string>, sourceName = '<agentId>-a0',
+-- state = provisioning|connecting|active|failed
+-- }
+-- Prosody-only (never broadcast):
+-- room._data.voice_agents[agentId] = { endpoint = { url, authorization }, customParameters, callbackUrl,
+-- mediaFormat = { encoding }, fanIn }
+-- The dial config stays here: jicofo's connect carries only the conference and
+-- agent id, and the media relay fetches the endpoint by id (GET /voice-agent/dial)
+-- when the bridge connects, so no customer secret travels through room metadata,
+-- jicofo or the bridge. callbackUrl never leaves prosody.
+--
+-- ── Endpoints (contract frozen at v1.0 — see AGENT_REST_API.md) ───────────────
+-- Authentication: Authorization: Bearer <system ASAP token>, verified against
+-- prosody_password_public_key_repo_url (NOT login tokens), exactly like
+-- mod_muc_jigasi_invite.
+--
+-- `conference` names the room as customers know it, '<tenant>/<room>' or '<room>' (plain or percent-encoded, any
+-- case), or by its JID (what jicofo and the media relay send, and the only way to name a breakout room). Every
+-- response, webhook and the dial config name it the public way, as the meeting URL spells it; never by JID.
+--
+-- POST /voice-agent/invite { conference, displayName, agentId?, endpoint{url,authorization?},
+-- customParameters?, callbackUrl?, mediaFormat?{encoding}, fanIn? }
+-- mediaFormat.encoding: 'audio/l16' (PCM16 24 kHz, the default) or 'audio/opus' (relayed undecoded)
+-- fanIn: 'per-source' (every participant's audio as its own stream, the default) or 'dominant'
+-- (only the dominant speaker's, as the bridge ranks them)
+-- → 200 { agentId, sourceName } — idempotent on agentId: an identical re-invite
+-- returns the existing agent, a different one is 409; 409 too while anyone has E2EE on
+-- POST /voice-agent/dismiss { conference, agentId } → 200 { agentId }
+-- GET /voice-agent/list?conference=<room> → 200 { agents = { <agentId>: <client fields> } }
+-- GET /voice-agent/get?conference=<room>&agentId=<id> → 200 <agent> | 404
+-- POST /voice-agent/status { conference, agentId, state, reason? }
+-- internal: jicofo and the media relay advance the lifecycle (connecting|active|failed|ended);
+-- active → agent.connected, failed → agent.failed, ended → teardown (agent.ended unless the agent had
+-- already failed: one terminal webhook per agent); forward-only, so a stale or duplicate report is
+-- acknowledged and ignored; 404 once the agent is gone
+-- auth: ASAP, or the voice_agent_status_secret (jicofo) / voice_agent_dial_secret (relay) shared secrets
+-- GET /voice-agent/dial?conference=<jid>&agentId=<id>
+-- internal: the media relay fetches { agentId, conference, endpoint, customParameters, mediaFormat, fanIn }
+-- when dialing;
+-- auth: ASAP or voice_agent_dial_secret (falls back to voice_agent_status_secret when no dial secret is
+-- set, which lets whoever holds jicofo's secret read customer credentials; set both in production)
+-- GET /voice-agent/events[?conference=<room>]
+-- a text/event-stream of the lifecycle events below, for a backend that holds one outbound connection instead
+-- of exposing a webhook: `id: <id>` / `event: agent.connected|agent.failed|agent.ended` / `data: <payload>`.
+-- A new stream first gets `snapshot` ({ conference?, agents: [ { agentId, conference, displayName, sourceName,
+-- state } ] }), unless its Last-Event-ID is still in the replay buffer, in which case it gets the events it
+-- missed instead. A keepalive comment every 15 s; closed after voice_agent_event_stream_max_age seconds
+-- (the client reconnects with Last-Event-ID); at most voice_agent_max_event_streams open at once (503)
+-- auth: ASAP, like the provisioning routes
+--
+-- Provisioning auth needs prosody_password_public_key_repo_url: without it the module refuses to load (a meeting
+-- token would otherwise pass), unless voice_agent_insecure_skip_auth is set for a dev rig. Lifecycle webhooks need
+-- voice_agent_webhook_secret: without it an invite with a callbackUrl is refused rather than delivered unsigned.
+-- voice_agent_callback_allowed_hosts (exact host or .suffix) limits where callbacks may go; empty allows any host,
+-- so an OSS deployment that accepts invites from several customers should set it (prosody POSTs there).
+--
+-- Webhooks: when an agent has a callbackUrl, lifecycle events are POSTed to it as
+-- { event, agentId, conference, sourceName, state, timestamp, reason? }, signed
+-- X-Agent-Signature: sha256=<hmac> with voice_agent_webhook_secret, retried with
+-- backoff up to voice_agent_webhook_retries times (at-least-once).
+-- Every lifecycle event is also written to the open event streams (GET /voice-agent/events) and fires the module
+-- event 'voice-agent-lifecycle' on this host, with { room, agent_id, payload } and the same payload, whether or
+-- not the agent has a callbackUrl, so a co-located module can deliver it another way (a hosted deployment's
+-- webhook platform).
+--
+-- Copyright (C) 2026-present 8x8, Inc.
+
+local async = require 'util.async';
+local hashes = require 'util.hashes';
+local random = require 'util.random';
+local json = require 'cjson.safe';
+local http_util = require 'util.http';
+local http = require 'net.http';
+
+local util = module:require 'util';
+local async_handler_wrapper = util.async_handler_wrapper;
+local extract_subdomain = util.extract_subdomain;
+local get_room_by_name_and_subdomain = util.get_room_by_name_and_subdomain;
+local get_room_from_jid = util.get_room_from_jid;
+local is_healthcheck_room = util.is_healthcheck_room;
+local process_host_module = util.process_host_module;
+local room_jid_match_rewrite = util.room_jid_match_rewrite;
+local starts_with = util.starts_with;
+local table_shallow_copy = util.table_shallow_copy;
+
+local muc_component_host = module:get_option_string('muc_component');
+if muc_component_host == nil then
+ module:log('error', 'No muc_component specified. No muc to operate on!');
+ return;
+end
+-- Optional: breakout rooms can be addressed by JID too, and host agents like the main room.
+local breakout_rooms_component_host = module:get_option_string('breakout_rooms_component');
+
+-- Where lifecycle webhooks may be delivered (exact host or '.suffix'); empty allows any host.
+local CALLBACK_ALLOWED_HOSTS = module:get_option_array('voice_agent_callback_allowed_hosts', {});
+
+local JSON_CONTENT_TYPE = 'application/json';
+
+-- Caps keeping a single provisioning request from bloating room state and the
+-- metadata broadcastable payload.
+local MAX_AGENTS_PER_ROOM = module:get_option_number('voice_agent_max_agents', 5);
+-- Event streams (GET /voice-agent/events): how many may be open at once (503 beyond), and the age at which one is
+-- closed so its client reconnects with Last-Event-ID, which also bounds how long an expired token keeps one open.
+local MAX_EVENT_STREAMS = module:get_option_number('voice_agent_max_event_streams', 64);
+local EVENT_STREAM_MAX_AGE = module:get_option_number('voice_agent_event_stream_max_age', 3600);
+local MAX_PARAM_ENTRIES = 16;
+local MAX_PARAM_KEY_LENGTH = 128;
+local MAX_PARAM_VALUE_LENGTH = 2048;
+local MAX_DISPLAY_NAME_LENGTH = 256;
+local MAX_CALLBACK_URL_LENGTH = 2048;
+
+-- Reserved namespace for agent ids, so an agent id can never equal a real participant's endpoint id.
+local AGENT_ID_PREFIX = 'agent-';
+
+-- Lifecycle states; 'ended' is terminal and removes the agent.
+local STATE_PROVISIONING = 'provisioning';
+local STATE_CONNECTING = 'connecting';
+local STATE_ACTIVE = 'active';
+local STATE_FAILED = 'failed';
+local STATE_ENDED = 'ended';
+-- Forward-only lifecycle: a report only ever moves the state forward, so a duplicate or a stale retry
+-- (a delayed 'connecting' landing after 'active') is acknowledged and ignored. 'ended' outranks 'failed' so a
+-- failed agent is still removed (and stops counting toward the room cap); it gets no second terminal webhook.
+local STATE_RANK = {
+ [STATE_PROVISIONING] = 0; [STATE_CONNECTING] = 1; [STATE_ACTIVE] = 2; [STATE_FAILED] = 3; [STATE_ENDED] = 4;
+};
+local STATUS_TRANSITIONS = {
+ [STATE_CONNECTING] = true; [STATE_ACTIVE] = true; [STATE_FAILED] = true; [STATE_ENDED] = true;
+};
+
+local invite_count = module:measure('voice_agent_invite_rate', 'rate');
+local invite_success_count = module:measure('voice_agent_invite_success', 'rate');
+local dismiss_count = module:measure('voice_agent_dismiss_rate', 'rate');
+
+-- DEV ONLY: skip provisioning-token auth (no ASAP keyserver). Default false; never enable where
+-- untrusted callers can reach it.
+local INSECURE_SKIP_AUTH = module:get_option_boolean('voice_agent_insecure_skip_auth', false);
+
+-- DEV ONLY: allow a ws:// (cleartext) endpoint.url for local test rigs; prod always requires wss://.
+local INSECURE_ALLOW_WS_ENDPOINT = module:get_option_boolean('voice_agent_insecure_allow_ws_endpoint', false);
+
+-- DEV ONLY: allow an http:// callbackUrl for local rigs; prod always requires https://.
+local INSECURE_ALLOW_HTTP_CALLBACK = module:get_option_boolean('voice_agent_insecure_allow_http_callback', false);
+
+local WEBHOOK_SECRET = module:get_option_string('voice_agent_webhook_secret', '');
+local WEBHOOK_RETRIES = module:get_option_number('voice_agent_webhook_retries', 3);
+if WEBHOOK_SECRET == '' then
+ module:log('warn', 'voice_agent_webhook_secret is not set: invites with a callbackUrl will be refused, since '
+ .. 'the webhook contract promises signed deliveries');
+end
+
+-- Shared secret jicofo presents on /voice-agent/status (it cannot mint ASAP tokens); ASAP is still accepted.
+local STATUS_SECRET = module:get_option_string('voice_agent_status_secret', '');
+-- Shared secret the media relay presents on /voice-agent/dial (and /status); separate from jicofo's so that
+-- holding jicofo's secret does not read customer credentials. Falls back to the status secret when unset.
+local DIAL_SECRET = module:get_option_string('voice_agent_dial_secret', '');
+if DIAL_SECRET == '' and STATUS_SECRET ~= '' then
+ module:log('warn', 'voice_agent_dial_secret is not set: the status secret also reads dial configs (customer '
+ .. 'endpoint credentials); set both to keep jicofo and the media relay apart');
+end
+
+local ASAP_KEY_SERVER = module:get_option_string('prosody_password_public_key_repo_url', '');
+local token_util;
+if INSECURE_SKIP_AUTH then
+ module:log('warn', 'voice_agent_insecure_skip_auth is ON — /voice-agent endpoints are UNAUTHENTICATED');
+else
+ -- Empty string is truthy in Lua, so compare explicitly.
+ if ASAP_KEY_SERVER == '' then
+ -- token/util would fall back to the host's meeting-token settings, and a meeting token must not invite
+ -- or dismiss agents, nor read dial configs. Same stance as mod_muc_jigasi_invite.
+ module:log('error', 'No prosody_password_public_key_repo_url set: provisioning tokens cannot be verified. '
+ .. 'Disabling /voice-agent (set voice_agent_insecure_skip_auth only on a dev rig).');
+ return;
+ end
+ token_util = module:require 'token/util'.new(module);
+ token_util:set_asap_key_server(ASAP_KEY_SERVER);
+end
+
+local main_muc_module;
+
+process_host_module(muc_component_host, function(host_module)
+ main_muc_module = host_module;
+end);
+
+local function is_token_valid(token)
+ if token == nil then
+ module:log('warn', 'no token provided');
+ return false;
+ end
+
+ local session = {};
+ session.auth_token = token;
+ local verified, reason, msg = token_util:process_and_verify_token(session);
+ if not verified then
+ module:log('warn', 'not a valid token %s %s', tostring(reason), tostring(msg));
+ return false;
+ end
+ return true;
+end
+
+-- Verifies the Authorization header; returns nil when authorized, or the error response.
+local function check_authorization(request)
+ if INSECURE_SKIP_AUTH then
+ return nil;
+ end
+ local token = request.headers['authorization'];
+ if not token then
+ module:log('warn', 'Authorization header was not provided');
+ return { status_code = 401 };
+ end
+ if starts_with(token, 'Bearer ') then
+ token = token:sub(8, #token);
+ else
+ module:log('warn', 'Authorization header is invalid');
+ return { status_code = 401 };
+ end
+ if not is_token_valid(token) then
+ return { status_code = 401 };
+ end
+ return nil;
+end
+
+-- Constant-time secret comparison: HMACs under a per-load random key have a fixed length and leak nothing about
+-- where a mismatch occurs, unlike a plain string compare.
+local COMPARE_KEY = random.bytes(16);
+local function secrets_equal(a, b)
+ return hashes.hmac_sha256(COMPARE_KEY, a, true) == hashes.hmac_sha256(COMPARE_KEY, b, true);
+end
+
+-- Whether the request carries one of the given shared secrets as a bearer.
+local function bearer_matches(request, ...)
+ local token = request.headers['authorization'];
+ if type(token) ~= 'string' or not starts_with(token, 'Bearer ') then
+ return false;
+ end
+ for _, secret in ipairs({ ... }) do
+ if secret ~= '' and secrets_equal(token:sub(8), secret) then
+ return true;
+ end
+ end
+ return false;
+end
+
+-- The status route is called by jicofo and the media relay, neither of which mints ASAP tokens: accept either
+-- shared secret as a bearer there, in addition to a regular ASAP token. Never used for the provisioning routes.
+local function check_status_authorization(request)
+ if bearer_matches(request, STATUS_SECRET, DIAL_SECRET) then
+ return nil;
+ end
+ return check_authorization(request);
+end
+
+-- The dial route hands out customer credentials: only the media relay's secret (or the status secret while no
+-- dial secret is configured) and ASAP are accepted; jicofo's secret alone does not read them once both are set.
+local function check_dial_authorization(request)
+ if bearer_matches(request, DIAL_SECRET ~= '' and DIAL_SECRET or STATUS_SECRET) then
+ return nil;
+ end
+ return check_authorization(request);
+end
+
+local function error_response(status_code, message)
+ return { status_code = status_code, body = json.encode({ error = message }) };
+end
+
+-- Reads a JSON request body; returns the payload, or nil plus the error response.
+local function parse_json_request(request)
+ if request.headers.content_type ~= JSON_CONTENT_TYPE or (not request.body or #request.body == 0) then
+ module:log('warn', 'Wrong content type: %s or missing payload', request.headers.content_type);
+ return nil, { status_code = 400 };
+ end
+ local payload, decode_error = json.decode(request.body);
+ if not payload then
+ module:log('warn', 'Cannot decode json error:%s', decode_error);
+ return nil, { status_code = 400 };
+ end
+ return payload;
+end
+
+-- Validates a string->string map (customParameters); returns a bounded
+-- copy, or nil plus an error message.
+local function validate_string_map(value, name)
+ if value == nil then
+ return nil;
+ end
+ if type(value) ~= 'table' then
+ return nil, name .. ' must be an object';
+ end
+ local copy = {};
+ local entries = 0;
+ for k, v in pairs(value) do
+ if type(k) ~= 'string' or type(v) ~= 'string' then
+ return nil, name .. ' must map strings to strings';
+ end
+ if #k > MAX_PARAM_KEY_LENGTH then
+ return nil, name .. ' key too long';
+ end
+ if #v > MAX_PARAM_VALUE_LENGTH then
+ return nil, name .. ' value too long';
+ end
+ -- Reject control chars (CR/LF) so a value can never split or inject a header or a log line.
+ if k:find('[%c]') or v:find('[%c]') then
+ return nil, name .. ' must not contain control characters';
+ end
+ entries = entries + 1;
+ if entries > MAX_PARAM_ENTRIES then
+ return nil, name .. ' has too many entries';
+ end
+ copy[k] = v;
+ end
+ return copy;
+end
+
+-- Broadcast to every client, so no control characters either.
+local function is_valid_display_name(name)
+ return type(name) == 'string' and name ~= '' and #name <= MAX_DISPLAY_NAME_LENGTH and not name:find('[%c]');
+end
+
+-- The host of an http(s) URL, lower-cased, or nil.
+local function url_host(url)
+ local host = url:match('^https?://([^/?#]+)');
+ if not host then
+ return nil;
+ end
+ -- Drop credentials and the port.
+ host = host:gsub('^.*@', ''):gsub(':%d+$', '');
+ return host:lower();
+end
+
+-- Whether callbacks may be delivered to this host: any host when no allowlist is configured, else an exact
+-- entry or a subdomain of a '.suffix' entry.
+local function callback_host_allowed(host)
+ if #CALLBACK_ALLOWED_HOSTS == 0 then
+ return true;
+ end
+ for _, entry in ipairs(CALLBACK_ALLOWED_HOSTS) do
+ local bare = entry:lower():gsub('^%.', '');
+ if host == bare or host:sub(-#bare - 1) == '.' .. bare then
+ return true;
+ end
+ end
+ return false;
+end
+
+-- Validates callbackUrl: https:// (http:// only with the dev flag), bounded, no control chars, a host the
+-- deployment allows, and only while deliveries can be signed.
+local function validate_callback_url(url)
+ if url == nil then
+ return nil;
+ end
+ if type(url) ~= 'string' or url == '' or #url > MAX_CALLBACK_URL_LENGTH or url:find('[%c]') then
+ return nil, 'Invalid callbackUrl';
+ end
+ if not (starts_with(url, 'https://') or (INSECURE_ALLOW_HTTP_CALLBACK and starts_with(url, 'http://'))) then
+ return nil, 'callbackUrl must be an https:// URL';
+ end
+ local host = url_host(url);
+ if not host or not callback_host_allowed(host) then
+ return nil, 'callbackUrl host is not allowed';
+ end
+ if WEBHOOK_SECRET == '' then
+ return nil, 'callbackUrl requires voice_agent_webhook_secret to be configured';
+ end
+ return url;
+end
+
+-- Validates the required endpoint.{url,authorization}; returns a bounded copy, or nil plus an error.
+-- Enforces the wss:// scheme only; host-level SSRF filtering is done by the media relay's endpoint
+-- guard at dial time.
+local function validate_endpoint(endpoint)
+ if type(endpoint) ~= 'table' or type(endpoint.url) ~= 'string' or #endpoint.url > MAX_PARAM_VALUE_LENGTH
+ or endpoint.url:find('[%c]')
+ or not (starts_with(endpoint.url, 'wss://')
+ or (INSECURE_ALLOW_WS_ENDPOINT and starts_with(endpoint.url, 'ws://'))) then
+ return nil, 'endpoint.url is required and must be a wss:// URL';
+ end
+ local authorization = endpoint.authorization;
+ if authorization ~= nil and (type(authorization) ~= 'string' or #authorization > MAX_PARAM_VALUE_LENGTH
+ or authorization:find('[%c]')) then
+ return nil, 'Invalid endpoint.authorization';
+ end
+ return { url = endpoint.url; authorization = authorization };
+end
+
+-- Presence property a participant's client sets while it has end-to-end encryption on.
+local E2EE_PRESENCE_PROPERTY = 'jitsi_participant_e2ee.enabled';
+
+-- Whether anyone in the room has end-to-end encryption on: the agent's media goes through the bridge, which cannot
+-- decrypt it.
+local function is_e2ee_enabled(room)
+ for _, occupant in room:each_occupant() do
+ local presence = occupant:get_presence();
+ if presence and presence:get_child_text(E2EE_PRESENCE_PROPERTY) == 'true' then
+ return true;
+ end
+ end
+ return false;
+end
+
+-- Audio encodings the media relay speaks on the agent leg.
+local DEFAULT_MEDIA_ENCODING = 'audio/l16';
+local MEDIA_ENCODINGS = { ['audio/l16'] = true; ['audio/opus'] = true };
+
+-- Validates the optional mediaFormat; returns { encoding } (the default when absent), or nil plus an error.
+local function validate_media_format(media_format)
+ if media_format == nil then
+ return { encoding = DEFAULT_MEDIA_ENCODING };
+ end
+ if type(media_format) ~= 'table' or not MEDIA_ENCODINGS[media_format.encoding] then
+ return nil, 'mediaFormat.encoding must be audio/l16 or audio/opus';
+ end
+ for key in pairs(media_format) do
+ if key ~= 'encoding' then
+ return nil, 'mediaFormat supports only encoding';
+ end
+ end
+ return { encoding = media_format.encoding };
+end
+
+-- How the media relay fans several participants' audio in to the agent.
+local DEFAULT_FAN_IN = 'per-source';
+local FAN_INS = { ['per-source'] = true; ['dominant'] = true };
+
+-- Validates the optional fanIn; returns the policy (the default when absent), or nil plus an error.
+local function validate_fan_in(fan_in)
+ if fan_in == nil then
+ return DEFAULT_FAN_IN;
+ end
+ if not FAN_INS[fan_in] then
+ return nil, 'fanIn must be per-source or dominant';
+ end
+ return fan_in;
+end
+
+-- Shallow equality for string maps; nil and {} compare equal.
+local function maps_equal(a, b)
+ a = a or {};
+ b = b or {};
+ for k, v in pairs(a) do
+ if b[k] ~= v then
+ return false;
+ end
+ end
+ for k in pairs(b) do
+ if a[k] == nil then
+ return false;
+ end
+ end
+ return true;
+end
+
+local MAX_CONFERENCE_LENGTH = 512;
+
+local function url_decode(s)
+ return (s:gsub('%%(%x%x)', function(hex) return string.char(tonumber(hex, 16)); end));
+end
+
+-- One segment of a room name as the client stores it (getBackendSafeRoomName): lower-cased, then percent-encoded
+-- like encodeURIComponent with lower-case hex. Decoding first lets the plain and the encoded spelling meet.
+local function backend_safe(segment)
+ return (url_decode(segment):lower():gsub("[^%w%-_%.!~%*'%(%)]", function(c)
+ return string.format('%%%02x', c:byte());
+ end));
+end
+
+-- A room by the name customers know it by: '<tenant>/<room>' or '<room>', plain or percent-encoded, any case.
+local function find_room_by_name(conference)
+ local tenant, name = conference:match('^([^/]+)/([^/]+)$');
+ if not tenant then
+ if conference:find('/', 1, true) then
+ return nil;
+ end
+ name = conference;
+ end
+ return get_room_by_name_and_subdomain(backend_safe(name), tenant and backend_safe(tenant));
+end
+
+-- A room by its JID: what jicofo and the media relay send, and the only way to name a breakout room. Conference and
+-- breakout rooms only; a lobby room never hosts an agent, and its public name would be the main room's.
+local function find_room_by_jid(conference)
+ local room_jid = room_jid_match_rewrite(conference);
+ local host = room_jid:match('@([^/]+)');
+ if host == nil or (host ~= muc_component_host and host ~= breakout_rooms_component_host) then
+ return nil;
+ end
+ return get_room_from_jid(room_jid);
+end
+
+-- Resolves the room from a request's conference: its public name or its JID.
+local function find_room(conference)
+ if type(conference) ~= 'string' or conference == '' or #conference > MAX_CONFERENCE_LENGTH then
+ return nil;
+ end
+ local room;
+ if conference:find('@', 1, true) then
+ room = find_room_by_jid(conference);
+ else
+ room = find_room_by_name(conference);
+ end
+ if room and is_healthcheck_room(room.jid) then
+ return nil;
+ end
+ return room;
+end
+
+local MAX_REASON_LENGTH = 200;
+
+-- A status reason as customers (agent.failed webhook) may see it: bounded, and with any internal address, such as a
+-- bridge JID inside a jicofo allocation error, masked.
+local function public_reason(reason)
+ return (reason:sub(1, MAX_REASON_LENGTH):gsub('[%c]', ' '):gsub('%S*@%S*', '<internal>'));
+end
+
+-- The name customers know a room by: '<tenant>/<room>', or '<room>' outside a tenant. Never the MUC JID.
+local function public_room_name(room)
+ local tenant, name = extract_subdomain(room.jid:match('^([^@]+)@') or room.jid);
+ return tenant and (tenant .. '/' .. name) or name;
+end
+
+-- Returns the client-facing entry and the jicofo-only entry for an agent, or nil when unknown.
+-- The id as stored: invite accepts it with or without the reserved prefix, so the other routes do too.
+local function normalize_agent_id(agent_id)
+ if type(agent_id) ~= 'string' then
+ return nil;
+ end
+ return starts_with(agent_id, AGENT_ID_PREFIX) and agent_id or (AGENT_ID_PREFIX .. agent_id);
+end
+
+-- The client-facing entry and the prosody-only record of an agent, plus its normalized id; nil when unknown.
+local function get_agent(room, agent_id)
+ agent_id = normalize_agent_id(agent_id);
+ local agents = room.jitsiMetadata and room.jitsiMetadata.agents;
+ if agent_id == nil or not agents or agents[agent_id] == nil then
+ return nil;
+ end
+ local voice_agents = room._data.voice_agents or {};
+ return agents[agent_id], voice_agents[agent_id] or {}, agent_id;
+end
+
+local function agent_response(agent_id, entry)
+ return {
+ agentId = agent_id;
+ displayName = entry.displayName;
+ sourceName = entry.sourceName;
+ state = entry.state;
+ };
+end
+
+-- Fires the metadata rebroadcast after agent state changed.
+local function notify_metadata_changed(room)
+ if main_muc_module then
+ main_muc_module:fire_event('room-metadata-changed', { room = room; });
+ end
+end
+
+-- ── Event stream ──────────────────────────────────────────────────────────────
+
+-- Stream state is shared across every host this module is loaded on (module:shared): a room's destroy hook runs in
+-- whichever instance hooked the MUC host first, while the streams were opened over HTTP on another host's
+-- instance, so a per-instance table would leave those streams without the room-destroyed events.
+local shared = module:shared('/*/voice_agent_component/event_stream');
+-- Rooms that currently have agents, for a stream's snapshot. Weak keys: a destroyed room is forgotten.
+shared.rooms = shared.rooms or setmetatable({}, { __mode = 'k' });
+-- Open streams: { response, conference = <public name, or nil for every room>, opened } → true.
+shared.streams = shared.streams or {};
+shared.count = shared.count or 0;
+-- Event ids are '<epoch>-<n>'. The epoch changes with every restart, so an id from before never replays another
+-- process's events; clients treat the id as opaque.
+shared.epoch = shared.epoch or (random.bytes(4):gsub('.', function(c) return string.format('%02x', c:byte()); end));
+shared.seq = shared.seq or 0;
+-- The last EVENT_BUFFER_SIZE events as { seq, conference, frame }, replayed to a reconnecting stream.
+shared.buffer = shared.buffer or {};
+local rooms_with_agents = shared.rooms;
+local streams = shared.streams;
+local event_buffer = shared.buffer;
+local EVENT_BUFFER_SIZE = 256;
+local EVENT_STREAM_KEEPALIVE = 15;
+-- Whether this instance owns the one keepalive timer (released on unload, see module.unload).
+local keepalive_here = false;
+
+local function event_id(seq)
+ return shared.epoch .. '-' .. seq;
+end
+
+local function sse_frame(id, event_name, data)
+ return 'id: ' .. id .. '\nevent: ' .. event_name .. '\ndata: ' .. data .. '\n\n';
+end
+
+-- One chunk of a chunked response; a stream never has a Content-Length.
+local function chunked(data)
+ return string.format('%x\r\n%s\r\n', #data, data);
+end
+
+local function close_stream(stream, why)
+ if stream.closed then
+ return;
+ end
+ stream.closed = true;
+ streams[stream] = nil;
+ shared.count = shared.count - 1;
+ local response = stream.response;
+ response.on_destroy = nil;
+ if not response.finished then
+ pcall(function()
+ response.conn:write('0\r\n\r\n');
+ response:done();
+ end);
+ end
+ module:log('debug', 'Event stream closed (%s), %d open', why, shared.count);
+end
+
+local function stream_write(stream, data)
+ if stream.closed then
+ return;
+ end
+ local ok, err = pcall(function() stream.response.conn:write(chunked(data)); end);
+ if not ok then
+ module:log('debug', 'Event stream write failed: %s', tostring(err));
+ close_stream(stream, 'write failed');
+ end
+end
+
+local function in_scope(stream, conference)
+ return stream.conference == nil or stream.conference == conference;
+end
+
+-- Records a lifecycle event (body: its encoded payload) and writes it to every stream in scope.
+local function broadcast_lifecycle(event_name, conference, body)
+ shared.seq = shared.seq + 1;
+ local seq = shared.seq;
+ local frame = sse_frame(event_id(seq), event_name, body);
+ table.insert(event_buffer, { seq = seq; conference = conference; frame = frame; });
+ if #event_buffer > EVENT_BUFFER_SIZE then
+ table.remove(event_buffer, 1);
+ end
+ for stream in pairs(streams) do
+ if in_scope(stream, conference) then
+ stream_write(stream, frame);
+ end
+ end
+end
+
+-- The frames a stream missed since its Last-Event-ID, or nil when they cannot be known (another epoch, an id
+-- older than the buffer), in which case the stream gets a snapshot instead.
+local function missed_frames(last_event_id, conference)
+ local epoch, seq = tostring(last_event_id or ''):match('^(%x+)%-(%d+)$');
+ seq = tonumber(seq);
+ if epoch ~= shared.epoch or not seq or seq > shared.seq then
+ return nil;
+ end
+ local oldest = event_buffer[1] and event_buffer[1].seq or (shared.seq + 1);
+ if seq < oldest - 1 then
+ return nil;
+ end
+ local frames = {};
+ for _, entry in ipairs(event_buffer) do
+ if entry.seq > seq and (conference == nil or entry.conference == conference) then
+ table.insert(frames, entry.frame);
+ end
+ end
+ return frames;
+end
+
+-- Every agent in scope with its state, for a stream's first event; sorted so the output is stable.
+local function snapshot_agents(conference)
+ local agents = {};
+ for room in pairs(rooms_with_agents) do
+ local name = public_room_name(room);
+ if conference == nil or conference == name then
+ for agent_id, entry in pairs((room.jitsiMetadata and room.jitsiMetadata.agents) or {}) do
+ local agent = agent_response(agent_id, entry);
+ agent.conference = name;
+ table.insert(agents, agent);
+ end
+ end
+ end
+ table.sort(agents, function(a, b)
+ if a.conference ~= b.conference then
+ return a.conference < b.conference;
+ end
+ return a.agentId < b.agentId;
+ end);
+ return agents;
+end
+
+-- The snapshot body, assembled by hand: cjson encodes an empty Lua table as {}, and the contract says `agents` is
+-- an array even when nobody is in scope.
+local function encode_snapshot(conference, agents)
+ local parts = {};
+ for _, agent in ipairs(agents) do
+ table.insert(parts, json.encode(agent));
+ end
+ return '{' .. (conference and ('"conference":' .. json.encode(conference) .. ',') or '')
+ .. '"agents":[' .. table.concat(parts, ',') .. ']}';
+end
+
+-- A comment line keeps proxies from closing an idle stream; the same tick retires streams past their max age.
+local function arm_keepalive()
+ if shared.keepalive_armed then
+ return;
+ end
+ shared.keepalive_armed = true;
+ keepalive_here = true;
+ module:add_timer(EVENT_STREAM_KEEPALIVE, function()
+ if next(streams) == nil then
+ shared.keepalive_armed = false;
+ keepalive_here = false;
+ return;
+ end
+ local now = os.time();
+ for stream in pairs(streams) do
+ if now - stream.opened >= EVENT_STREAM_MAX_AGE then
+ close_stream(stream, 'max age');
+ else
+ stream_write(stream, ': keepalive\n\n');
+ end
+ end
+ return EVENT_STREAM_KEEPALIVE;
+ end);
+end
+
+-- ── Webhooks ──────────────────────────────────────────────────────────────────
+
+local deliver_webhook;
+deliver_webhook = function(url, body, signature, attempt)
+ local headers = { ['Content-Type'] = JSON_CONTENT_TYPE };
+ if signature then
+ headers['X-Agent-Signature'] = signature;
+ end
+ local ok, err = pcall(http.request, url, { method = 'POST'; headers = headers; body = body; },
+ function(_, code)
+ if type(code) == 'number' and code >= 200 and code < 300 then
+ return;
+ end
+ if attempt < WEBHOOK_RETRIES then
+ module:add_timer(2 ^ attempt, function()
+ deliver_webhook(url, body, signature, attempt + 1);
+ end);
+ else
+ -- The host only: the URL's query string may carry the customer's token.
+ module:log('warn', 'Webhook to %s failed after %d attempts (last status %s)',
+ tostring(url_host(url)), attempt, tostring(code));
+ end
+ end);
+ if not ok then
+ module:log('warn', 'Webhook request to %s errored: %s', tostring(url_host(url)), tostring(err));
+ end
+end
+
+local function send_webhook(callback_url, body)
+ if not callback_url then
+ return;
+ end
+ local signature;
+ if WEBHOOK_SECRET ~= '' then
+ signature = 'sha256=' .. hashes.hmac_sha256(WEBHOOK_SECRET, body, true);
+ end
+ deliver_webhook(callback_url, body, signature, 1);
+end
+
+local LIFECYCLE_EVENT = 'voice-agent-lifecycle';
+
+-- One lifecycle event, three consumers: the agent's callbackUrl when it has one, the open event streams, and a
+-- module event any co-located module may hook to deliver it another way. The body is encoded before the hooks
+-- run, so they cannot alter it, and a failing hook cannot break the transition.
+local function notify_lifecycle(room, agent_id, entry, callback_url, event_name, extra)
+ local payload = {
+ event = event_name;
+ agentId = agent_id;
+ conference = public_room_name(room);
+ sourceName = entry.sourceName;
+ state = entry.state;
+ timestamp = os.date('!%Y-%m-%dT%H:%M:%SZ');
+ };
+ for k, v in pairs(extra or {}) do
+ payload[k] = v;
+ end
+ local body = json.encode(payload);
+ send_webhook(callback_url, body);
+ broadcast_lifecycle(event_name, payload.conference, body);
+ local ok, err = pcall(module.fire_event, module, LIFECYCLE_EVENT,
+ { room = room; agent_id = agent_id; payload = payload; });
+ if not ok then
+ module:log('warn', 'A %s hook failed: %s', LIFECYCLE_EVENT, tostring(err));
+ end
+end
+
+-- Tears an agent down: terminal state, agent.ended webhook (unless agent.failed already was its terminal
+-- webhook), removal from both maps.
+local function remove_agent(room, agent_id, reason)
+ local entry, jicofo_entry, id = get_agent(room, agent_id);
+ if not entry then
+ return false;
+ end
+ agent_id = id;
+ local already_terminal = entry.state == STATE_FAILED;
+ entry.state = STATE_ENDED;
+ if not already_terminal then
+ notify_lifecycle(room, agent_id, entry, jicofo_entry.callbackUrl, 'agent.ended', { reason = reason });
+ end
+ room.jitsiMetadata.agents[agent_id] = nil;
+ if room._data.voice_agents then
+ room._data.voice_agents[agent_id] = nil;
+ end
+ if next(room.jitsiMetadata.agents) == nil then
+ rooms_with_agents[room] = nil;
+ end
+ notify_metadata_changed(room);
+ return true;
+end
+
+-- ── Handlers ──────────────────────────────────────────────────────────────────
+
+local function handle_invite(event)
+ invite_count();
+ local request = event.request;
+
+ local auth_error = check_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+ local payload, parse_error = parse_json_request(request);
+ if not payload then
+ return parse_error;
+ end
+
+ local room = find_room(payload.conference);
+ if not room then
+ module:log('warn', 'No room found for %s', tostring(payload.conference));
+ return error_response(404, 'Room not found');
+ end
+
+ if not is_valid_display_name(payload.displayName) then
+ return error_response(400, 'Missing or invalid displayName');
+ end
+
+ -- Agent ids live in a reserved "agent-" namespace so they can NEVER equal a real participant's
+ -- endpoint id (8 hex chars) -- otherwise a caller could shadow a real participant's roster entry and
+ -- source. The prefix is enforced/normalized here (the authoritative id space), which makes the
+ -- collision impossible by construction rather than via a racy occupant check. The suffix after the
+ -- prefix is validated to a safe charset and to exclude prototype-pollution keys (defense in depth for
+ -- the client, which keys plain objects by agent id).
+ local agent_id;
+ local requested = payload.agentId;
+ if requested ~= nil then
+ if type(requested) ~= 'string' then
+ return error_response(400, 'Invalid agentId');
+ end
+ -- Accept with or without the reserved prefix; normalize to exactly one.
+ local suffix = starts_with(requested, AGENT_ID_PREFIX)
+ and requested:sub(#AGENT_ID_PREFIX + 1) or requested;
+ if not suffix:match('^[%w_-]+$') or #suffix > 48
+ or suffix == '__proto__' or suffix == 'constructor' or suffix == 'prototype' then
+ return error_response(400, 'Invalid agentId');
+ end
+ agent_id = AGENT_ID_PREFIX .. suffix;
+ else
+ agent_id = AGENT_ID_PREFIX .. hashes.sha256(random.bytes(8), true):sub(1, 8);
+ end
+
+ local endpoint, endpoint_error = validate_endpoint(payload.endpoint);
+ if endpoint_error then
+ return error_response(400, endpoint_error);
+ end
+ local custom_params, custom_error = validate_string_map(payload.customParameters, 'customParameters');
+ if custom_error then
+ return error_response(400, custom_error);
+ end
+ local callback_url, callback_error = validate_callback_url(payload.callbackUrl);
+ if callback_error then
+ return error_response(400, callback_error);
+ end
+ local media_format, media_format_error = validate_media_format(payload.mediaFormat);
+ if media_format_error then
+ return error_response(400, media_format_error);
+ end
+ local fan_in, fan_in_error = validate_fan_in(payload.fanIn);
+ if fan_in_error then
+ return error_response(400, fan_in_error);
+ end
+ room.jitsiMetadata = room.jitsiMetadata or {};
+ local agents = room.jitsiMetadata.agents or {};
+ local voice_agents = room._data.voice_agents or {};
+ local source_name = agent_id .. '-a0';
+
+ local existing = agents[agent_id];
+ -- Idempotent on agentId: an identical re-invite returns the existing agent, even under E2EE (a retry after a
+ -- timeout must not see a failure for a live agent); a different one conflicts. A failed agent is replaced below.
+ if existing and existing.state ~= STATE_FAILED then
+ local jicofo_entry = voice_agents[agent_id] or {};
+ if existing.displayName == payload.displayName
+ and maps_equal(jicofo_entry.endpoint, endpoint)
+ and maps_equal(jicofo_entry.customParameters, custom_params)
+ and (jicofo_entry.mediaFormat or { encoding = DEFAULT_MEDIA_ENCODING }).encoding == media_format.encoding
+ and (jicofo_entry.fanIn or DEFAULT_FAN_IN) == fan_in
+ and jicofo_entry.callbackUrl == callback_url then
+ return { status_code = 200, body = json.encode({ agentId = agent_id, sourceName = source_name }) };
+ end
+ return error_response(409, 'agentId already exists with different parameters');
+ end
+
+ -- Before the failed record is replaced, so a refused invite leaves it as it was.
+ if is_e2ee_enabled(room) then
+ return error_response(409, 'End-to-end encryption is on in this meeting');
+ end
+
+ if existing then
+ -- A failed allocation is terminal for jicofo: re-inviting replaces the record, and the removal
+ -- broadcast clears jicofo's failure before the fresh entry is announced.
+ module:log('info', 'Replacing failed voice agent %s in room %s', agent_id, room.jid);
+ agents[agent_id] = nil;
+ voice_agents[agent_id] = nil;
+ notify_metadata_changed(room);
+ end
+
+ local count = 0;
+ for _ in pairs(agents) do
+ count = count + 1;
+ end
+ if count >= MAX_AGENTS_PER_ROOM then
+ return error_response(409, 'Too many agents in the room');
+ end
+
+ -- Client-facing entry (broadcast to every occupant).
+ agents[agent_id] = {
+ kind = 'agent';
+ displayName = payload.displayName;
+ sourceName = source_name;
+ state = STATE_PROVISIONING;
+ };
+ -- Dial config, fetched by the media relay by id; never broadcast.
+ voice_agents[agent_id] = {
+ endpoint = endpoint;
+ customParameters = custom_params;
+ callbackUrl = callback_url;
+ mediaFormat = media_format;
+ fanIn = fan_in;
+ };
+
+ room.jitsiMetadata.agents = agents;
+ room._data.voice_agents = voice_agents;
+ rooms_with_agents[room] = true;
+
+ module:log('info', 'Voice agent %s invited to room %s,meeting_id:%s',
+ agent_id, room.jid, room._data.meetingId);
+ notify_metadata_changed(room);
+ invite_success_count();
+
+ return { status_code = 200, body = json.encode({ agentId = agent_id, sourceName = source_name }) };
+end
+
+local function handle_dismiss(event)
+ dismiss_count();
+ local request = event.request;
+
+ local auth_error = check_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+ local payload, parse_error = parse_json_request(request);
+ if not payload then
+ return parse_error;
+ end
+
+ local room = find_room(payload.conference);
+ if not room then
+ return error_response(404, 'Room not found');
+ end
+
+ local agent_id = normalize_agent_id(payload.agentId);
+ if not agent_id or not remove_agent(room, agent_id, 'dismissed') then
+ return error_response(404, 'Agent not found');
+ end
+
+ module:log('info', 'Voice agent %s dismissed from room %s,meeting_id:%s',
+ agent_id, room.jid, room._data.meetingId);
+
+ return { status_code = 200, body = json.encode({ agentId = agent_id }) };
+end
+
+local function query_params(request)
+ local query = request.url and request.url.query;
+ return query and http_util.formdecode(query) or {};
+end
+
+local function handle_list(event)
+ local request = event.request;
+
+ local auth_error = check_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+
+ local room = find_room(query_params(request).conference);
+ if not room then
+ return error_response(404, 'Room not found');
+ end
+
+ local agents = (room.jitsiMetadata and room.jitsiMetadata.agents) or {};
+ return { status_code = 200, body = json.encode({ agents = agents }) };
+end
+
+local function handle_get(event)
+ local request = event.request;
+
+ local auth_error = check_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+
+ local params = query_params(request);
+ local room = find_room(params.conference);
+ if not room then
+ return error_response(404, 'Room not found');
+ end
+ local entry, _, agent_id = get_agent(room, params.agentId);
+ if not entry then
+ return error_response(404, 'Agent not found');
+ end
+ return { status_code = 200, body = json.encode(agent_response(agent_id, entry)) };
+end
+
+
+-- The public name a stream filters on. The room may not exist yet (a stream is often opened before the meeting
+-- starts), so a name that resolves to no room is normalised the way public_room_name() will spell it. A JID must
+-- resolve: one for a room that does not exist names nothing a customer could be told about.
+local function stream_conference(conference)
+ if type(conference) ~= 'string' or conference == '' or #conference > MAX_CONFERENCE_LENGTH then
+ return nil;
+ end
+ local room = find_room(conference);
+ if room then
+ return public_room_name(room);
+ end
+ if conference:find('@', 1, true) then
+ return nil;
+ end
+ local tenant, name = conference:match('^([^/]+)/([^/]+)$');
+ if tenant then
+ return backend_safe(tenant) .. '/' .. backend_safe(name);
+ end
+ if conference:find('/', 1, true) then
+ return nil;
+ end
+ return backend_safe(conference);
+end
+
+-- Opens a lifecycle event stream on the response once the request is authorized; returns an error response instead
+-- when it cannot be opened.
+local function open_event_stream(request, response)
+ local params = query_params(request);
+ local conference;
+ if params.conference ~= nil then
+ conference = stream_conference(params.conference);
+ if not conference then
+ return error_response(404, 'Room not found');
+ end
+ end
+ if shared.count >= MAX_EVENT_STREAMS then
+ return error_response(503, 'Too many event streams');
+ end
+
+ response.status_code = 200;
+ response.headers.content_type = 'text/event-stream';
+ response.headers.cache_control = 'no-cache';
+ response.headers.transfer_encoding = 'chunked';
+ -- nginx would otherwise hold the chunks back.
+ response.headers.x_accel_buffering = 'no';
+ response:write_headers();
+
+ local stream = { response = response; conference = conference; opened = os.time(); };
+ streams[stream] = true;
+ shared.count = shared.count + 1;
+ response.on_destroy = function()
+ close_stream(stream, 'disconnected');
+ end;
+
+ local missed = missed_frames(request.headers['last_event_id'], conference);
+ if missed then
+ for _, frame in ipairs(missed) do
+ stream_write(stream, frame);
+ end
+ else
+ stream_write(stream, sse_frame(event_id(shared.seq), 'snapshot',
+ encode_snapshot(conference, snapshot_agents(conference))));
+ end
+ arm_keepalive();
+ module:log('debug', 'Event stream opened for %s, %d open', conference or 'every room', shared.count);
+ return nil;
+end
+
+-- GET /voice-agent/events: a text/event-stream of the lifecycle events, held open until the client leaves or the
+-- stream reaches its max age. Not wrapped by async_handler_wrapper, which would end the response: the token check
+-- may fetch an ASAP key, which has to wait, so it runs in its own runner, and the stream then takes the response over.
+local function handle_events(event)
+ -- The runner only calls its function for input it is given, so the event goes in run().
+ async.runner(function(e)
+ local refused = check_authorization(e.request) or open_event_stream(e.request, e.response);
+ if refused then
+ e.response.status_code = refused.status_code;
+ e.response:send(refused.body);
+ end
+ end):run(event);
+ return true;
+end
+
+-- Internal lifecycle reporting for jicofo/JVB; drives the client-facing state and the webhooks.
+local function handle_status(event)
+ local request = event.request;
+
+ local auth_error = check_status_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+ local payload, parse_error = parse_json_request(request);
+ if not payload then
+ return parse_error;
+ end
+
+ local room = find_room(payload.conference);
+ if not room then
+ return error_response(404, 'Room not found');
+ end
+ if not STATUS_TRANSITIONS[payload.state] then
+ return error_response(400, 'Invalid state');
+ end
+ local reason = type(payload.reason) == 'string' and public_reason(payload.reason) or nil;
+
+ local entry, jicofo_entry, agent_id = get_agent(room, payload.agentId);
+ if not entry then
+ -- Also a repeated 'ended': the agent is gone, which reporters take as done.
+ return error_response(404, 'Agent not found');
+ end
+ if STATE_RANK[payload.state] <= (STATE_RANK[entry.state] or 0) then
+ module:log('debug', 'Ignoring stale status %s for agent %s in state %s',
+ payload.state, agent_id, entry.state);
+ return { status_code = 200, body = json.encode(agent_response(agent_id, entry)) };
+ end
+ if payload.state == STATE_ENDED then
+ remove_agent(room, agent_id, reason or 'ended');
+ return { status_code = 200, body = json.encode({ agentId = agent_id }) };
+ end
+ entry.state = payload.state;
+ if payload.state == STATE_ACTIVE then
+ notify_lifecycle(room, agent_id, entry, jicofo_entry.callbackUrl, 'agent.connected');
+ elseif payload.state == STATE_FAILED then
+ notify_lifecycle(room, agent_id, entry, jicofo_entry.callbackUrl, 'agent.failed', { reason = reason });
+ end
+ notify_metadata_changed(room);
+ return { status_code = 200, body = json.encode(agent_response(agent_id, entry)) };
+end
+
+-- Internal: the media relay fetches the dial config by id when the bridge connects, so the customer
+-- endpoint and its secret leave prosody only for the dial itself.
+local function handle_dial(event)
+ local request = event.request;
+
+ local auth_error = check_dial_authorization(request);
+ if auth_error then
+ return auth_error;
+ end
+
+ local params = query_params(request);
+ local room = find_room(params.conference);
+ if not room then
+ return error_response(404, 'Room not found');
+ end
+ local entry, jicofo_entry, agent_id = get_agent(room, params.agentId);
+ if not entry or not jicofo_entry.endpoint then
+ return error_response(404, 'Agent not found');
+ end
+ return { status_code = 200, body = json.encode({
+ agentId = agent_id;
+ conference = public_room_name(room);
+ endpoint = jicofo_entry.endpoint;
+ customParameters = jicofo_entry.customParameters;
+ mediaFormat = jicofo_entry.mediaFormat;
+ fanIn = jicofo_entry.fanIn;
+ }) };
+end
+
+module:log('info', 'Adding http handlers for /voice-agent on %s', module.host);
+module:depends('http');
+module:provides('http', {
+ default_path = '/';
+ route = {
+ ['POST voice-agent/invite'] = function(event)
+ return async_handler_wrapper(event, handle_invite);
+ end;
+ ['POST voice-agent/dismiss'] = function(event)
+ return async_handler_wrapper(event, handle_dismiss);
+ end;
+ ['GET voice-agent/list'] = function(event)
+ return async_handler_wrapper(event, handle_list);
+ end;
+ ['GET voice-agent/get'] = function(event)
+ return async_handler_wrapper(event, handle_get);
+ end;
+ ['POST voice-agent/status'] = function(event)
+ return async_handler_wrapper(event, handle_status);
+ end;
+ ['GET voice-agent/dial'] = function(event)
+ return async_handler_wrapper(event, handle_dial);
+ end;
+ ['GET voice-agent/events'] = handle_events;
+ };
+});
+
+-- The conference (or breakout room) ending takes every agent with it; make that observable to the customer.
+local function hook_room_destroyed(host_module)
+ host_module:hook('muc-room-destroyed', function(event)
+ local room = event.room;
+ local agents = room.jitsiMetadata and room.jitsiMetadata.agents;
+ if not agents then
+ return;
+ end
+ local voice_agents = room._data.voice_agents or {};
+ for agent_id, entry in pairs(agents) do
+ -- The module may be loaded on several hosts (e.g. via global modules_enabled), each hooking
+ -- the same room: the first run marks the agent ended so later runs stay silent. A failed agent
+ -- already had its terminal webhook.
+ if entry.state ~= STATE_ENDED and entry.state ~= STATE_FAILED then
+ entry.state = STATE_ENDED;
+ notify_lifecycle(room, agent_id, entry, (voice_agents[agent_id] or {}).callbackUrl,
+ 'agent.ended', { reason = 'room-destroyed' });
+ end
+ end
+ rooms_with_agents[room] = nil;
+ end);
+end
+
+process_host_module(muc_component_host, hook_room_destroyed);
+if breakout_rooms_component_host then
+ process_host_module(breakout_rooms_component_host, hook_room_destroyed);
+end
+
+-- Prosody cancels this instance's timers on unload; the shared flag must not keep claiming a keepalive that is gone.
+function module.unload()
+ if keepalive_here then
+ shared.keepalive_armed = false;
+ end
+end
diff --git a/tests/prosody/lua/mod_voice_agent_component_spec.lua b/tests/prosody/lua/mod_voice_agent_component_spec.lua
new file mode 100644
index 0000000000..88b5e94e82
--- /dev/null
+++ b/tests/prosody/lua/mod_voice_agent_component_spec.lua
@@ -0,0 +1,1403 @@
+-- Unit tests for mod_voice_agent_component.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted ../../tests/prosody/lua/
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed. These focus on the
+-- security-relevant validation at the provisioning boundary: ASAP auth, agentId namespacing (the
+-- reserved "agent-" prefix that makes an agent id un-collidable with a real 8-hex endpoint id),
+-- prototype-pollution key rejection, string-map bounds, prosody-only dial-config segregation — and the
+-- v1 contract additions: idempotent invite, get, the state lifecycle, and signed webhooks.
+-- End-to-end behaviour against a real Prosody is covered by the integration specs.
+
+-- ---------------------------------------------------------------------------
+-- Stubs for top-level `require`d Prosody libs (no Prosody install under busted)
+-- ---------------------------------------------------------------------------
+
+package.preload['util.hashes'] = function()
+ return {
+ sha256 = function() return 'deadbeefcafef00d' end,
+ hmac_sha256 = function(_key, data, _hex) return 'h:' .. data end
+ };
+end
+package.preload['util.random'] = function()
+ return { bytes = function() return 'xxxxxxxx' end };
+end
+package.preload['util.http'] = function()
+ return {
+ formdecode = function(query)
+ local params = {};
+ for k, v in (query or ''):gmatch('([^&=]+)=([^&]*)') do params[k] = v; end
+ return params;
+ end
+ };
+end
+
+-- net.http: captures outbound webhook requests; `http_next_code` is the status the stub reports back.
+local http_requests = {};
+local metadata_events = 0;
+local http_next_code = 200;
+package.preload['net.http'] = function()
+ return {
+ request = function(url, ex, callback)
+ table.insert(http_requests, { url = url, ex = ex });
+ if callback then callback('', http_next_code, {}); end
+ return true;
+ end
+ };
+end
+
+-- cjson.safe: decode returns the per-test `next_decoded` table; encode records every table it is
+-- given so tests can inspect response and webhook payloads without a real JSON parser.
+local next_decoded;
+local encoded = {};
+package.preload['cjson.safe'] = function()
+ return {
+ decode = function(s)
+ if s == nil or s == '' then
+ return nil, 'empty';
+ end
+ return next_decoded;
+ end,
+ encode = function(t)
+ if type(t) == 'string' then return '"' .. t .. '"'; end
+ table.insert(encoded, t);
+ return '{}';
+ end
+ };
+end
+
+-- ---------------------------------------------------------------------------
+-- Controllable stub state
+-- ---------------------------------------------------------------------------
+
+local token_valid = true;
+local mock_room;
+local timers = {};
+local host_hooks = {};
+-- The same hooks keyed by the host they were installed on (the module hooks the main and breakout MUC hosts).
+local host_hooks_by_host = {};
+-- module:log calls, as { level, text }.
+local logs = {};
+-- Module events the module fires (module:fire_event); `fire_event_error` makes the next hook fail.
+local module_events = {};
+local fire_event_error = false;
+-- module:shared() tables by path, kept across loads of the file so two loads act as two host instances.
+local shared_store = {};
+
+-- Public room-name lookups ({ name, subdomain }) seen by the util stub.
+local name_lookups = {};
+
+local util_stub = {
+ async_handler_wrapper = function(event, handler) return handler(event); end,
+ extract_subdomain = function(node)
+ local subdomain, room = node:match('^%[([^%]]+)%](.+)$');
+ return subdomain, room or node;
+ end,
+ get_room_by_name_and_subdomain = function(name, subdomain)
+ table.insert(name_lookups, { name = name, subdomain = subdomain });
+ if name == 'missing' then return nil; end
+ return mock_room;
+ end,
+ get_room_from_jid = function(jid)
+ if jid == 'missing' then return nil; end
+ return mock_room;
+ end,
+ is_healthcheck_room = function(_) return false; end,
+ process_host_module = function(host, cb)
+ host_hooks_by_host[host] = host_hooks_by_host[host] or {};
+ cb({ hook = function(_, name, fn)
+ host_hooks[name] = fn;
+ host_hooks_by_host[host][name] = fn;
+ end; fire_event = function(_, name)
+ if name == 'room-metadata-changed' then metadata_events = metadata_events + 1; end
+ end });
+ end,
+ room_jid_match_rewrite = function(jid) return jid; end,
+ starts_with = function(s, prefix) return type(s) == 'string' and s:sub(1, #prefix) == prefix; end,
+ table_shallow_copy = function(t)
+ local c = {};
+ for k, v in pairs(t or {}) do c[k] = v; end
+ return c;
+ end
+};
+
+-- util.async: a runner that, like Prosody's, calls its function only for input given to run(), and a waiter that,
+-- like Prosody's, fails outside a runner.
+local in_runner = false;
+package.preload['util.async'] = function()
+ return {
+ runner = function(fn)
+ return {
+ run = function(_, input)
+ if input == nil then
+ return;
+ end
+ in_runner = true;
+ local ok, err = pcall(fn, input);
+ in_runner = false;
+ if not ok then error(err, 0); end
+ end
+ };
+ end,
+ waiter = function()
+ if not in_runner then
+ error('Not running in an async context');
+ end
+ return function() end, function() end;
+ end
+ };
+end
+
+-- Whether the token's signing key is in the key cache; when not, verifying it fetches the key, which waits.
+local key_cached = true;
+
+local token_util_stub = {
+ new = function()
+ return {
+ set_asap_key_server = function() end,
+ process_and_verify_token = function()
+ if not key_cached then
+ require('util.async').waiter();
+ end
+ return token_valid, 'reason', 'msg';
+ end
+ };
+ end
+};
+
+-- Captured HTTP route handlers, filled by the module:provides stub below.
+local routes = {};
+
+-- Option values the module is loaded with; a test may reload it with overrides (see "alternate configurations").
+local option_overrides = {};
+local function option(key, default)
+ if option_overrides[key] ~= nil then return option_overrides[key]; end
+ if key == 'muc_component' then return 'conference.localhost'; end
+ if key == 'breakout_rooms_component' then return 'breakout.localhost'; end
+ if key == 'voice_agent_webhook_secret' then return 'shh'; end
+ if key == 'voice_agent_status_secret' then return 'jicofo-secret'; end
+ if key == 'voice_agent_dial_secret' then return 'relay-secret'; end
+ if key == 'prosody_password_public_key_repo_url' then return 'https://keys.example.com/'; end
+ if key == 'voice_agent_callback_allowed_hosts' then return { 'app.example.com' }; end
+ return default;
+end
+
+_G.module = {
+ host = 'voiceagent.localhost',
+ fire_event = function(_, name, event)
+ table.insert(module_events, { name = name, event = event });
+ if fire_event_error then error('hook failed'); end
+ end,
+ shared = function(_, path)
+ shared_store[path] = shared_store[path] or {};
+ return shared_store[path];
+ end,
+ log = function(_, level, fmt, ...)
+ local ok, text = pcall(string.format, fmt, ...);
+ table.insert(logs, { level = level, text = ok and text or fmt });
+ end,
+ get_option_string = function(_, key, default) return option(key, default); end,
+ get_option_number = function(_, key, default) return option(key, default); end,
+ get_option_boolean = function(_, key, default) return option(key, default); end,
+ get_option_array = function(_, key, default) return option(key, default or {}); end,
+ measure = function() return function() end; end,
+ depends = function() end,
+ add_timer = function(_, delay, fn) table.insert(timers, { delay = delay, fn = fn }); end,
+ require = function(_, name)
+ if name == 'util' then return util_stub; end
+ if name == 'token/util' then return token_util_stub; end
+ return {};
+ end,
+ provides = function(_, _kind, def)
+ for name, handler in pairs(def.route) do routes[name] = handler; end
+ end
+};
+
+-- ---------------------------------------------------------------------------
+-- Load the module under test
+-- ---------------------------------------------------------------------------
+
+local ok, load_err = pcall(dofile, 'mod_voice_agent_component.lua');
+if not ok then
+ describe('mod_voice_agent_component', function()
+ it('skipped — failed to load module', function()
+ pending(tostring(load_err):match('([^\n]+)') or tostring(load_err));
+ end)
+ end)
+ return;
+end
+
+for _, route in ipairs({ 'POST voice-agent/invite', 'POST voice-agent/dismiss', 'GET voice-agent/list',
+ 'GET voice-agent/get', 'POST voice-agent/status', 'GET voice-agent/dial',
+ 'GET voice-agent/events' }) do
+ assert(routes[route], route .. ' route not registered');
+end
+
+-- ---------------------------------------------------------------------------
+-- Test helpers
+-- ---------------------------------------------------------------------------
+
+local function fresh_room()
+ return {
+ jitsiMetadata = {};
+ _data = {};
+ occupants = {};
+ each_occupant = function(self)
+ local i = 0;
+ return function()
+ i = i + 1;
+ local occupant = self.occupants[i];
+ if occupant then
+ return occupant.nick, occupant;
+ end
+ end;
+ end;
+ };
+end
+
+-- An occupant whose presence carries the given jitsi_participant_* properties.
+local function occupant(props)
+ return {
+ nick = '[email protected]/p' .. tostring(math.random(1e6));
+ get_presence = function()
+ return { get_child_text = function(_, name) return props[name]; end };
+ end;
+ };
+end
+
+local function post(route, payload, opts)
+ opts = opts or {};
+ next_decoded = payload;
+ local headers = { content_type = 'application/json' };
+ if not opts.omitAuth then
+ headers.authorization = opts.token or 'Bearer sometoken';
+ end
+ return routes[route]({ request = { headers = headers; body = 'x' } });
+end
+
+local DEFAULT_ENDPOINT = { url = 'wss://agents.example.com/s' };
+
+-- Every invite needs an endpoint; tests that do not care get the default one.
+local function invite(payload, opts)
+ opts = opts or {};
+ if payload.endpoint == nil and not opts.noEndpoint then
+ payload.endpoint = DEFAULT_ENDPOINT;
+ end
+ return post('POST voice-agent/invite', payload, opts);
+end
+local function dismiss(payload) return post('POST voice-agent/dismiss', payload); end
+local function status(payload, opts) return post('POST voice-agent/status', payload, opts); end
+
+local function get(query)
+ return routes['GET voice-agent/get']({
+ request = { headers = { authorization = 'Bearer t' }; url = { query = query } } });
+end
+
+local function dial(query, opts)
+ opts = opts or {};
+ local headers = {};
+ if not opts.omitAuth then
+ headers.authorization = opts.token or 'Bearer t';
+ end
+ return routes['GET voice-agent/dial']({ request = { headers = headers; url = { query = query } } });
+end
+
+local function agent_ids(room)
+ local ids = {};
+ for id in pairs(room.jitsiMetadata.agents or {}) do table.insert(ids, id); end
+ return ids;
+end
+
+-- Every recorded webhook payload of the given event type, in emission order.
+local function webhook_payloads(event_name)
+ local out = {};
+ for _, t in ipairs(encoded) do
+ if type(t) == 'table' and t.event == event_name then table.insert(out, t); end
+ end
+ return out;
+end
+
+local CALLBACK = 'https://app.example.com/agent-events';
+
+-- A Prosody-shaped response object for the event stream: records every write and behaves like
+-- net.http.server on done()/on_destroy().
+local function sse_response()
+ local response = { status_code = 200; headers = {}; finished = false; writes = {} };
+ response.conn = { write = function(_, data) table.insert(response.writes, data); end };
+ response.write_headers = function(self) self.headers_written = true; end;
+ response.done = function(self)
+ self.finished = true;
+ if self.on_destroy then self:on_destroy(); self.on_destroy = nil; end
+ end;
+ -- A plain response, as a refused request gets.
+ response.send = function(self, body)
+ self.sent = body or '';
+ self.finished = true;
+ end;
+ -- What net.http.server does when the client goes away.
+ response.disconnect = function(self)
+ self.finished = true;
+ if self.on_destroy then self:on_destroy(); end
+ end;
+ return response;
+end
+
+-- Streams opened by the current test, disconnected before the next one so module state does not leak.
+local open_streams = {};
+
+-- Opens an event stream; returns the handler's result and the response it wrote to.
+local function events(query, opts)
+ opts = opts or {};
+ local headers = {};
+ if not opts.omitAuth then headers.authorization = opts.token or 'Bearer t'; end
+ if opts.lastEventId then headers.last_event_id = opts.lastEventId; end
+ local response = sse_response();
+ table.insert(open_streams, response);
+ local result = routes['GET voice-agent/events']({
+ request = { headers = headers; url = { query = query } }; response = response });
+ -- The route takes every request over; a refusal is sent on the response.
+ if response.sent ~= nil then
+ return { status_code = response.status_code; body = response.sent }, response;
+ end
+ return result, response;
+end
+
+-- The SSE events a stream received, in order, as { id, event }; keepalive comments as { comment = true }.
+local function stream_events(response)
+ local out = {};
+ for _, w in ipairs(response.writes) do
+ local text = w:match('^%x+\r\n(.*)\r\n$');
+ if text and text:sub(1, 1) == ':' then
+ table.insert(out, { comment = true });
+ elseif text then
+ table.insert(out, { id = text:match('id: ([^\n]+)'); event = text:match('event: ([^\n]+)') });
+ end
+ end
+ return out;
+end
+
+-- The data line of the last snapshot frame a stream received (every table in it encodes as {} under the stub).
+local function snapshot_data(response)
+ local data;
+ for _, w in ipairs(response.writes) do
+ local text = w:match('^%x+\r\n(.*)\r\n$');
+ if text and text:find('event: snapshot', 1, true) then
+ data = text:match('data: ([^\n]*)');
+ end
+ end
+ return data;
+end
+
+-- The agents the module encoded for snapshots (client fields plus `conference`), in order.
+local function snapshot_agents()
+ local out = {};
+ for _, t in ipairs(encoded) do
+ if type(t) == 'table' and t.agentId and t.conference and t.displayName and not t.event then
+ table.insert(out, t);
+ end
+ end
+ return out;
+end
+
+-- ---------------------------------------------------------------------------
+-- Tests
+-- ---------------------------------------------------------------------------
+
+describe('mod_voice_agent_component', function()
+ before_each(function()
+ for _, response in ipairs(open_streams) do response:disconnect(); end
+ open_streams = {};
+ -- With every stream gone, a pending keepalive tick disarms itself, so the next test gets a fresh timer.
+ for _, timer in ipairs(timers) do
+ if timer.delay == 15 then pcall(timer.fn); end
+ end
+ token_valid = true;
+ mock_room = fresh_room();
+ http_requests = {};
+ metadata_events = 0;
+ http_next_code = 200;
+ timers = {};
+ name_lookups = {};
+ logs = {};
+ module_events = {};
+ fire_event_error = false;
+ key_cached = true;
+ in_runner = false;
+ for i = #encoded, 1, -1 do encoded[i] = nil; end
+ -- The module remembers rooms with agents by weak key: collect the previous test's room.
+ collectgarbage('collect');
+ end)
+
+ describe('public room names (no MUC JIDs for customers)', function()
+ it('resolves <tenant>/<room>, lower-cased, through the tenant', function()
+ assert.are.equal(200, invite({ conference = 'Acme/Support-Room'; displayName = 'Bot' }).status_code);
+ assert.are.same({ name = 'support-room', subdomain = 'acme' }, name_lookups[1]);
+ end)
+
+ it('resolves a bare <room> outside any tenant', function()
+ assert.are.equal(200, invite({ conference = 'lobby'; displayName = 'Bot' }).status_code);
+ assert.are.same({ name = 'lobby' }, name_lookups[1]);
+ end)
+
+ it('also takes a room JID, without a name lookup', function()
+ assert.are.equal(200, invite({ conference = '[email protected]'; displayName = 'Bot';
+ agentId = 'support' }).status_code);
+ assert.are.equal(200, dismiss({ conference = '[email protected]'; agentId = 'agent-support' }).status_code);
+ assert.are.equal(0, #name_lookups);
+ end)
+
+ it('takes conference and breakout room JIDs, not a lobby room\'s', function()
+ assert.are.equal(200, invite({ conference = '[email protected]'; displayName = 'Bot';
+ agentId = 'support' }).status_code);
+ assert.are.equal(200, dial('[email protected]&agentId=agent-support').status_code);
+ assert.are.equal(404, invite({ conference = '[email protected]'; displayName = 'Bot' }).status_code);
+ assert.are.equal(404, dial('[email protected]&agentId=agent-support').status_code);
+ end)
+
+ it('spells names as the client stores them, from the plain or the encoded form', function()
+ local cases = {
+ { 'Sales Standup', 'sales%20standup' },
+ { 'sales%20STANDUP', 'sales%20standup' },
+ { 'Caf\195\169', 'caf%c3%a9' },
+ { 'caf%C3%A9', 'caf%c3%a9' },
+ { 'a+b', 'a%2bb' },
+ { '100%', '100%25' },
+ { '[t]room', '%5bt%5droom' },
+ };
+ for i, case in ipairs(cases) do
+ invite({ conference = case[1]; displayName = 'Bot' });
+ assert.are.equal(case[2], name_lookups[i].name, case[1]);
+ end
+ end)
+
+ it('rejects names with more than one tenant segment or an empty one', function()
+ for _, bad in ipairs({ 'a/b/c', '/room', 'tenant/' }) do
+ assert.are.equal(404, invite({ conference = bad; displayName = 'Bot' }).status_code, bad);
+ end
+ end)
+
+ it('masks internal addresses in a failure reason before it reaches the webhook', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed';
+ reason = 'bridge allocation failed: Session no longer active ([email protected]/jvb-1)' },
+ { token = 'Bearer jicofo-secret' });
+ assert.are.equal('bridge allocation failed: Session no longer active <internal>',
+ webhook_payloads('agent.failed')[1].reason);
+ end)
+
+ it('names the room <tenant>/<room> in webhooks and the dial response, never by JID', function()
+ mock_room.jid = '[acme][email protected]';
+ invite({ conference = 'acme/support'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ status({ conference = '[acme][email protected]'; agentId = 'agent-support'; state = 'active' },
+ { token = 'Bearer jicofo-secret' });
+ assert.are.equal('acme/support', webhook_payloads('agent.connected')[1].conference);
+ dial('conference=[acme][email protected]&agentId=agent-support');
+ assert.are.equal('acme/support', encoded[#encoded].conference);
+ end)
+
+ it('names a room outside any tenant by its bare name', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ assert.are.equal('room1', webhook_payloads('agent.ended')[1].conference);
+ end)
+ end)
+
+ describe('authentication', function()
+ it('returns 401 when the Authorization header is absent', function()
+ local res = invite({ conference = 'r'; displayName = 'Bot' }, { omitAuth = true });
+ assert.are.equal(401, res.status_code);
+ end)
+
+ it('returns 401 when the token does not verify', function()
+ token_valid = false;
+ local res = invite({ conference = 'r'; displayName = 'Bot' });
+ assert.are.equal(401, res.status_code);
+ end)
+ end)
+
+ describe('agentId namespacing (collision prevention)', function()
+ it('generates an agent- prefixed id when none is provided', function()
+ local res = invite({ conference = 'r'; displayName = 'Bot' });
+ assert.are.equal(200, res.status_code);
+ local ids = agent_ids(mock_room);
+ assert.are.equal(1, #ids);
+ assert.is_truthy(ids[1]:match('^agent%-'), 'generated id must be agent- prefixed: ' .. ids[1]);
+ end)
+
+ it('normalizes a bare (endpoint-id-shaped) agentId into the agent- namespace', function()
+ -- '1a2b3c4d' is exactly the shape of a real participant endpoint id.
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = '1a2b3c4d' });
+ assert.is_truthy(mock_room.jitsiMetadata.agents['agent-1a2b3c4d'],
+ 'a bare id must be namespaced so it cannot collide with a real endpoint id');
+ assert.is_nil(mock_room.jitsiMetadata.agents['1a2b3c4d']);
+ end)
+
+ it('is idempotent when the agentId already carries the prefix', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'agent-support' });
+ assert.is_truthy(mock_room.jitsiMetadata.agents['agent-support']);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-agent-support']);
+ end)
+
+ it('derives the source name from the namespaced id', function()
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal('agent-support-a0', mock_room.jitsiMetadata.agents['agent-support'].sourceName);
+ -- The 200 body echoes the same source name (encode is stubbed, so just assert success).
+ assert.are.equal(200, res.status_code);
+ end)
+ end)
+
+ describe('prototype-pollution key rejection', function()
+ for _, bad in ipairs({ '__proto__', 'constructor', 'prototype' }) do
+ it('rejects agentId "' .. bad .. '"', function()
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = bad });
+ assert.are.equal(400, res.status_code);
+ assert.are.equal(0, #agent_ids(mock_room));
+ end)
+ end
+ end)
+
+ describe('agentId charset and length', function()
+ it('rejects an agentId with disallowed characters', function()
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'B'; agentId = 'a b/c' }).status_code);
+ end)
+
+ it('rejects an over-long agentId suffix', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; agentId = string.rep('a', 49) }).status_code);
+ end)
+ end)
+
+ describe('required fields and limits', function()
+ it('returns 400 when displayName is missing', function()
+ assert.are.equal(400, invite({ conference = 'r' }).status_code);
+ end)
+
+ it('returns 404 when the room does not exist', function()
+ assert.are.equal(404, invite({ conference = 'missing'; displayName = 'B' }).status_code);
+ end)
+
+ it('enforces the per-room agent cap', function()
+ for i = 1, 5 do
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'B'; agentId = 'a' .. i }).status_code);
+ end
+ assert.are.equal(409, invite({ conference = 'r'; displayName = 'B'; agentId = 'a6' }).status_code);
+ end)
+ end)
+
+ describe('customParameters validation', function()
+ it('rejects a non-string map value', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; customParameters = { k = 5 } }).status_code);
+ end)
+
+ it('rejects too many entries', function()
+ local big = {};
+ for i = 1, 17 do big['k' .. i] = 'v'; end
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; customParameters = big }).status_code);
+ end)
+
+ it('rejects a value with control characters', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B';
+ customParameters = { X = 'a\r\nX-Injected: 1' } }).status_code);
+ end)
+
+ it('rejects an over-long key', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B';
+ customParameters = { [string.rep('k', 129)] = 'v' } }).status_code);
+ end)
+ end)
+
+ describe('endpoint', function()
+ it('is required', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B' }, { noEndpoint = true }).status_code);
+ end)
+
+ it('rejects a non-wss endpoint.url', function()
+ assert.are.equal(400, invite({
+ conference = 'r'; displayName = 'B'; endpoint = { url = 'http://evil/s' }
+ }).status_code);
+ end)
+
+ it('rejects an endpoint.authorization with control characters', function()
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'B';
+ endpoint = { url = 'wss://agents.example.com/s'; authorization = 'Bearer k\r\nX: 1' } }).status_code);
+ end)
+
+ it('keeps the endpoint and its secret out of the client-facing entry', function()
+ invite({
+ conference = 'r';
+ displayName = 'Bot';
+ agentId = 'support';
+ endpoint = { url = 'wss://agents.example.com/s'; authorization = 'Bearer k' }
+ });
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support'].endpoint);
+ local stored = mock_room._data.voice_agents['agent-support'].endpoint;
+ assert.are.equal('wss://agents.example.com/s', stored.url);
+ assert.are.equal('Bearer k', stored.authorization);
+ end)
+ end)
+
+ describe('end-to-end encryption', function()
+ it('rejects an invite while anyone has end-to-end encryption on', function()
+ mock_room.occupants = { occupant({}), occupant({ ['jitsi_participant_e2ee.enabled'] = 'true' }) };
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(409, res.status_code);
+ assert.are.equal('End-to-end encryption is on in this meeting', encoded[#encoded].error);
+ assert.are.equal(0, #agent_ids(mock_room));
+ end)
+
+ it('accepts the invite once encryption is off again', function()
+ mock_room.occupants = { occupant({ ['jitsi_participant_e2ee.enabled'] = 'false' }) };
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' }).status_code);
+ end)
+
+ it('still answers an identical re-invite of a present agent with 200', function()
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' }).status_code);
+ mock_room.occupants = { occupant({ ['jitsi_participant_e2ee.enabled'] = 'true' }) };
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(200, res.status_code);
+ end)
+
+ it('reports a different re-invite as a conflict, not as encryption', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ mock_room.occupants = { occupant({ ['jitsi_participant_e2ee.enabled'] = 'true' }) };
+ local res = invite({ conference = 'r'; displayName = 'Other'; agentId = 'support' });
+ assert.are.equal(409, res.status_code);
+ assert.are.equal('agentId already exists with different parameters', encoded[#encoded].error);
+ end)
+
+ it('refuses to replace a failed agent, and keeps its record', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'no bridge' });
+ mock_room.occupants = { occupant({ ['jitsi_participant_e2ee.enabled'] = 'true' }) };
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(409, res.status_code);
+ assert.are.equal('End-to-end encryption is on in this meeting', encoded[#encoded].error);
+ assert.are.equal('failed', mock_room.jitsiMetadata.agents['agent-support'].state);
+ end)
+ end)
+
+ describe('mediaFormat', function()
+ local function dial_body()
+ assert.are.equal(200, dial('conference=r&agentId=agent-support').status_code);
+ return encoded[#encoded];
+ end
+
+ it('defaults to PCM16 in the dial response', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal('audio/l16', dial_body().mediaFormat.encoding);
+ end)
+
+ it('carries Opus to the dial response and keeps it out of the client-facing entry', function()
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ mediaFormat = { encoding = 'audio/opus' } }).status_code);
+ assert.are.equal('audio/opus', dial_body().mediaFormat.encoding);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support'].mediaFormat);
+ end)
+
+ it('rejects an unknown encoding, a non-object and unsupported fields', function()
+ for _, bad in ipairs({ { encoding = 'audio/pcmu' }, 'audio/opus', {},
+ { encoding = 'audio/l16'; sampleRate = 16000 } }) do
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'Bot'; mediaFormat = bad }).status_code);
+ end
+ assert.are.equal(0, #agent_ids(mock_room));
+ end)
+
+ it('is part of the idempotency check, the default matching an explicit audio/l16', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ mediaFormat = { encoding = 'audio/l16' } }).status_code);
+ -- A record from before mediaFormat existed counts as the default.
+ mock_room._data.voice_agents['agent-support'].mediaFormat = nil;
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' }).status_code);
+ assert.are.equal(409, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ mediaFormat = { encoding = 'audio/opus' } }).status_code);
+ end)
+ end)
+
+ describe('fanIn', function()
+ local function dial_body()
+ assert.are.equal(200, dial('conference=r&agentId=agent-support').status_code);
+ return encoded[#encoded];
+ end
+
+ it('defaults to per-source in the dial response', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal('per-source', dial_body().fanIn);
+ end)
+
+ it('carries dominant to the dial response and keeps it out of the client-facing entry', function()
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ fanIn = 'dominant' }).status_code);
+ assert.are.equal('dominant', dial_body().fanIn);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support'].fanIn);
+ end)
+
+ it('rejects an unknown policy and a non-string', function()
+ for _, bad in ipairs({ 'loudest', 'Dominant', 42, { 'dominant' } }) do
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'Bot'; fanIn = bad }).status_code);
+ end
+ assert.are.equal(0, #agent_ids(mock_room));
+ end)
+
+ it('is part of the idempotency check, the default matching an explicit per-source', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ fanIn = 'per-source' }).status_code);
+ -- A record from before fanIn existed counts as the default.
+ mock_room._data.voice_agents['agent-support'].fanIn = nil;
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' }).status_code);
+ assert.are.equal(409, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ fanIn = 'dominant' }).status_code);
+ end)
+ end)
+
+ describe('dial (internal, fetched by the media relay)', function()
+ local function invite_support()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ endpoint = { url = 'wss://agents.example.com/s'; authorization = 'Bearer k' };
+ customParameters = { campaign = '42' } });
+ end
+
+ it('returns the endpoint and custom parameters for the dial secret bearer', function()
+ invite_support();
+ local res = dial('conference=r&agentId=agent-support', { token = 'Bearer relay-secret' });
+ assert.are.equal(200, res.status_code);
+ local body = encoded[#encoded];
+ assert.are.equal('agent-support', body.agentId);
+ assert.are.equal('wss://agents.example.com/s', body.endpoint.url);
+ assert.are.equal('Bearer k', body.endpoint.authorization);
+ assert.are.equal('42', body.customParameters.campaign);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support'].customParameters);
+ end)
+
+ it('accepts an ASAP token too', function()
+ invite_support();
+ assert.are.equal(200, dial('conference=r&agentId=agent-support').status_code);
+ end)
+
+ it('refuses jicofo\'s status secret once a dial secret is configured, while status takes either', function()
+ invite_support();
+ token_valid = false;
+ assert.are.equal(401, dial('conference=r&agentId=agent-support', { token = 'Bearer jicofo-secret' }).status_code);
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'connecting' },
+ { token = 'Bearer relay-secret' }).status_code);
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'active' },
+ { token = 'Bearer jicofo-secret' }).status_code);
+ end)
+
+ it('rejects a missing or invalid token', function()
+ invite_support();
+ assert.are.equal(401, dial('conference=r&agentId=agent-support', { omitAuth = true }).status_code);
+ token_valid = false;
+ assert.are.equal(401, dial('conference=r&agentId=agent-support', { token = 'Bearer wrong' }).status_code);
+ end)
+
+ it('returns 404 for an unknown agent and for a missing room', function()
+ assert.are.equal(404, dial('conference=r&agentId=agent-nope').status_code);
+ assert.are.equal(404, dial('conference=missing&agentId=agent-support').status_code);
+ end)
+ end)
+
+ describe('idempotent invite', function()
+ it('returns the existing agent for an identical re-invite without duplicating it', function()
+ local first = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ customParameters = { a = '1' } });
+ local second = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ customParameters = { a = '1' } });
+ assert.are.equal(200, first.status_code);
+ assert.are.equal(200, second.status_code);
+ assert.are.equal(1, #agent_ids(mock_room));
+ end)
+
+ it('conflicts (409) when the same agentId is re-invited with different parameters', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(409, invite({ conference = 'r'; displayName = 'Other'; agentId = 'support' }).status_code);
+ assert.are.equal(409, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ customParameters = { a = '2' } }).status_code);
+ assert.are.equal('Bot', mock_room.jitsiMetadata.agents['agent-support'].displayName);
+ end)
+ end)
+
+ describe('state lifecycle', function()
+ it('starts an invited agent in the provisioning state', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal('provisioning', mock_room.jitsiMetadata.agents['agent-support'].state);
+ end)
+
+ it('advances to connecting without a webhook', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'connecting' }).status_code);
+ assert.are.equal('connecting', mock_room.jitsiMetadata.agents['agent-support'].state);
+ assert.are.equal(0, #http_requests);
+ end)
+
+ it('advances to active and fires agent.connected', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal('active', mock_room.jitsiMetadata.agents['agent-support'].state);
+ local connected = webhook_payloads('agent.connected');
+ assert.are.equal(1, #connected);
+ assert.are.equal('agent-support', connected[1].agentId);
+ assert.are.equal('active', connected[1].state);
+ end)
+
+ it('marks failed with a reason and fires agent.failed', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'dial refused' });
+ assert.are.equal('failed', mock_room.jitsiMetadata.agents['agent-support'].state);
+ local failed = webhook_payloads('agent.failed');
+ assert.are.equal(1, #failed);
+ assert.are.equal('dial refused', failed[1].reason);
+ end)
+
+ it('tears the agent down on ended and fires agent.ended', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'ended' }).status_code);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support']);
+ assert.is_nil(mock_room._data.voice_agents['agent-support']);
+ assert.are.equal(1, #webhook_payloads('agent.ended'));
+ end)
+
+ it('rejects an unknown state', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ assert.are.equal(400, status({ conference = 'r'; agentId = 'agent-support'; state = 'dancing' }).status_code);
+ end)
+
+ it('returns 404 for an unknown agent', function()
+ assert.are.equal(404, status({ conference = 'r'; agentId = 'agent-nope'; state = 'active' }).status_code);
+ end)
+ end)
+
+ describe('get', function()
+ it('returns the client-facing agent', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local res = get('conference=r&agentId=agent-support');
+ assert.are.equal(200, res.status_code);
+ local body = encoded[#encoded];
+ assert.are.equal('agent-support', body.agentId);
+ assert.are.equal('agent-support-a0', body.sourceName);
+ assert.are.equal('provisioning', body.state);
+ end)
+
+ it('returns 404 for an unknown agent and for a missing room', function()
+ assert.are.equal(404, get('conference=r&agentId=agent-nope').status_code);
+ assert.are.equal(404, get('conference=missing&agentId=agent-support').status_code);
+ end)
+ end)
+
+ describe('callbackUrl and webhooks', function()
+ it('rejects a non-https callbackUrl', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; callbackUrl = 'http://app.example.com/hook' }).status_code);
+ end)
+
+ it('stores callbackUrl jicofo-only, never in the client-facing entry', function()
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support'; callbackUrl = CALLBACK });
+ assert.are.equal(CALLBACK, mock_room._data.voice_agents['agent-support'].callbackUrl);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support'].callbackUrl);
+ end)
+
+ it('sends no webhook when the agent has no callbackUrl', function()
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ assert.are.equal(0, #http_requests);
+ end)
+
+ it('POSTs a signed agent.ended webhook on dismiss', function()
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support'; callbackUrl = CALLBACK });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ assert.are.equal(1, #http_requests);
+ local req = http_requests[1];
+ assert.are.equal(CALLBACK, req.url);
+ assert.are.equal('POST', req.ex.method);
+ assert.are.equal('application/json', req.ex.headers['Content-Type']);
+ assert.are.equal('sha256=h:{}', req.ex.headers['X-Agent-Signature']);
+ local ended = webhook_payloads('agent.ended');
+ assert.are.equal(1, #ended);
+ assert.are.equal('agent-support', ended[1].agentId);
+ assert.are.equal('ended', ended[1].state);
+ assert.are.equal('dismissed', ended[1].reason);
+ assert.is_truthy(ended[1].timestamp);
+ end)
+
+ it('retries a failed delivery with backoff', function()
+ http_next_code = 500;
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support'; callbackUrl = CALLBACK });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ assert.are.equal(1, #http_requests);
+ assert.are.equal(1, #timers, 'first failure must schedule a retry');
+ timers[1].fn();
+ assert.are.equal(2, #http_requests);
+ assert.is_true(timers[2].delay > timers[1].delay, 'backoff must grow');
+ end)
+
+ it('fires agent.ended for every agent when the room is destroyed', function()
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'one'; callbackUrl = CALLBACK });
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'two'; callbackUrl = CALLBACK });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ local ended = webhook_payloads('agent.ended');
+ assert.are.equal(2, #ended);
+ assert.are.equal('room-destroyed', ended[1].reason);
+ end)
+
+ it('sends agent.ended once per agent even when the destroy hook runs twice', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ assert.are.equal(1, #webhook_payloads('agent.ended'));
+ end)
+ end)
+
+ describe('voice-agent-lifecycle module event', function()
+ local function lifecycle_events()
+ local out = {};
+ for _, e in ipairs(module_events) do
+ if e.name == 'voice-agent-lifecycle' then table.insert(out, e.event); end
+ end
+ return out;
+ end
+
+ it('fires for connected and ended with the webhook payload, without a callbackUrl', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ local events = lifecycle_events();
+ assert.are.equal(2, #events);
+ assert.are.equal(mock_room, events[1].room);
+ assert.are.equal('agent-support', events[1].agent_id);
+ assert.are.equal('agent.connected', events[1].payload.event);
+ assert.are.equal('active', events[1].payload.state);
+ assert.are.equal('agent-support-a0', events[1].payload.sourceName);
+ assert.is_truthy(events[1].payload.timestamp);
+ assert.are.equal('agent.ended', events[2].payload.event);
+ assert.are.equal('dismissed', events[2].payload.reason);
+ assert.are.equal(0, #http_requests, 'no callbackUrl, no webhook');
+ end)
+
+ it('fires one terminal event: a failed agent gets no ended event on dismiss', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'no bridge available' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ local events = lifecycle_events();
+ assert.are.equal(1, #events);
+ assert.are.equal('agent.failed', events[1].payload.event);
+ assert.are.equal('no bridge available', events[1].payload.reason);
+ end)
+
+ it('fires on room destroy with the same payload as the webhook', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ local events = lifecycle_events();
+ assert.are.equal(1, #events);
+ assert.are.equal('room-destroyed', events[1].payload.reason);
+ assert.are.equal(events[1].payload, webhook_payloads('agent.ended')[1]);
+ end)
+
+ it('survives a failing hook: the transition and the webhook still happen', function()
+ fire_event_error = true;
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ local res = status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal(200, res.status_code);
+ assert.are.equal('active', mock_room.jitsiMetadata.agents['agent-support'].state);
+ assert.are.equal(1, #http_requests);
+ local warned = false;
+ for _, entry in ipairs(logs) do
+ if entry.level == 'warn' and entry.text:find('voice-agent-lifecycle', 1, true) then warned = true; end
+ end
+ assert.is_true(warned, 'a failing hook must be logged');
+ end)
+ end)
+
+ describe('event stream (GET /voice-agent/events)', function()
+ it('verifies the token in an async runner, so a key that is not cached yet does not fail the stream', function()
+ key_cached = false;
+ local result, response = events('conference=r');
+ assert.is_true(result);
+ assert.are.equal('text/event-stream', response.headers.content_type);
+ assert.are.equal('snapshot', stream_events(response)[1].event);
+ end)
+
+ it('requires authorization', function()
+ local result, response = events('conference=r', { omitAuth = true });
+ assert.are.equal(401, result.status_code);
+ assert.are.equal(0, #response.writes);
+ end)
+
+ it('opens a chunked text/event-stream and starts with a snapshot of the agents in scope', function()
+ invite({ conference = 'r'; displayName = 'A'; agentId = 'one' });
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'two' });
+ status({ conference = 'r'; agentId = 'agent-two'; state = 'active' });
+ local result, response = events('conference=r');
+ assert.is_true(result);
+ assert.is_true(response.headers_written);
+ assert.are.equal('text/event-stream', response.headers.content_type);
+ assert.are.equal('chunked', response.headers.transfer_encoding);
+ assert.are.equal('no', response.headers.x_accel_buffering);
+ local received = stream_events(response);
+ assert.are.equal(1, #received);
+ assert.are.equal('snapshot', received[1].event);
+ assert.are.equal('{"conference":"room1","agents":[{},{}]}', snapshot_data(response));
+ local agents = snapshot_agents();
+ assert.are.equal(2, #agents);
+ assert.are.equal('agent-one', agents[1].agentId);
+ assert.are.equal('provisioning', agents[1].state);
+ assert.are.equal('agent-two', agents[2].agentId);
+ assert.are.equal('active', agents[2].state);
+ assert.are.equal('room1', agents[2].conference);
+ assert.is_nil(agents[2].endpoint, 'a snapshot carries client fields only');
+ end)
+
+ it('writes each lifecycle event to the stream, with an opaque id', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local _, response = events('conference=r');
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ local received = stream_events(response);
+ assert.are.equal(3, #received);
+ assert.are.equal('agent.connected', received[2].event);
+ assert.are.equal('agent.ended', received[3].event);
+ assert.is_truthy(received[2].id:match('^%x+%-%d+$'));
+ assert.are_not.equal(received[2].id, received[3].id);
+ end)
+
+ it('a stream for a room that does not exist yet gets an empty snapshot and no other room\'s events', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local result, response = events('conference=missing');
+ assert.is_true(result);
+ assert.are.equal('{"conference":"missing","agents":[]}', snapshot_data(response), 'an empty snapshot is still an array');
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal(1, #stream_events(response), 'room1 events stay out of a stream for another room');
+ end)
+
+ it('a stream without a conference covers every room', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local _, response = events(nil);
+ assert.are.equal('{"agents":[{}]}', snapshot_data(response));
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal('agent.connected', stream_events(response)[2].event);
+ end)
+
+ it('rejects a JID outside the conference hosts', function()
+ assert.are.equal(404, events('[email protected]').status_code);
+ end)
+
+ it('replays the events missed since a known Last-Event-ID instead of a snapshot', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local _, first = events('conference=r');
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ local connected_id = stream_events(first)[2].id;
+ first:disconnect();
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ local _, second = events('conference=r', { lastEventId = connected_id });
+ local received = stream_events(second);
+ assert.are.equal(1, #received);
+ assert.are.equal('agent.ended', received[1].event);
+ end)
+
+ it('sends a snapshot when the Last-Event-ID is from another epoch', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local _, response = events('conference=r', { lastEventId = 'deadbeef-7' });
+ assert.are.equal('snapshot', stream_events(response)[1].event);
+ end)
+
+ it('forgets a stream whose client went away', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local _, response = events('conference=r');
+ response:disconnect();
+ local before = #response.writes;
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal(before, #response.writes);
+ end)
+
+ it('drops a room from the snapshot once its last agent is gone', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ local _, response = events('conference=r');
+ assert.are.equal('{"conference":"room1","agents":[]}', snapshot_data(response));
+ end)
+
+ it('drops a destroyed room from the snapshot', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ local _, response = events(nil);
+ assert.are.equal('{"agents":[]}', snapshot_data(response));
+ end)
+
+ it('keeps the stream alive with a comment on each timer tick', function()
+ local _, response = events('conference=r');
+ assert.are.equal(15, timers[#timers].delay);
+ local again = timers[#timers].fn();
+ assert.are.equal(15, again, 'the keepalive re-arms itself while streams are open');
+ local received = stream_events(response);
+ assert.is_true(received[#received].comment);
+ end)
+ end)
+
+ describe('status route auth (jicofo shared secret)', function()
+ it('accepts the configured shared secret without an ASAP token', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ token_valid = false;
+ local res = status({ conference = 'r'; agentId = 'agent-support'; state = 'active' },
+ { token = 'Bearer jicofo-secret' });
+ assert.are.equal(200, res.status_code);
+ assert.are.equal('active', mock_room.jitsiMetadata.agents['agent-support'].state);
+ end)
+
+ it('rejects a wrong shared secret', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ token_valid = false;
+ assert.are.equal(401, status({ conference = 'r'; agentId = 'agent-support'; state = 'active' },
+ { token = 'Bearer nope' }).status_code);
+ end)
+
+ it('never lets the shared secret provision agents', function()
+ token_valid = false;
+ assert.are.equal(401, invite({ conference = 'r'; displayName = 'Bot' },
+ { token = 'Bearer jicofo-secret' }).status_code);
+ end)
+ end)
+
+ describe('status lifecycle is forward-only', function()
+ before_each(function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ callbackUrl = 'https://app.example.com/hook' });
+ end)
+
+ it('ignores a stale connecting after active and a duplicate active, sending one webhook', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'connecting' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'connecting' }).status_code);
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'active' }).status_code);
+ assert.are.equal('active', mock_room.jitsiMetadata.agents['agent-support'].state);
+ assert.are.equal(1, #webhook_payloads('agent.connected'));
+ end)
+
+ it('still accepts failed after active', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'media leg lost' });
+ assert.are.equal('failed', mock_room.jitsiMetadata.agents['agent-support'].state);
+ assert.are.equal(1, #webhook_payloads('agent.failed'));
+ end)
+
+ it('removes a failed agent on ended, with agent.failed as its only terminal webhook', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'dial refused' });
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'ended' }).status_code);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support']);
+ assert.is_nil(mock_room._data.voice_agents['agent-support']);
+ assert.are.equal(1, #webhook_payloads('agent.failed'));
+ assert.are.equal(0, #webhook_payloads('agent.ended'));
+ end)
+
+ it('lets a failed agent stop counting toward the room cap once ended', function()
+ for i = 1, 4 do
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'extra' .. i });
+ status({ conference = 'r'; agentId = 'agent-extra' .. i; state = 'failed'; reason = 'x' });
+ status({ conference = 'r'; agentId = 'agent-extra' .. i; state = 'ended' });
+ end
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot'; agentId = 'fits' }).status_code);
+ end)
+
+ it('answers a repeated ended with 404, sending agent.ended once', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'active' });
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'agent-support'; state = 'ended' }).status_code);
+ assert.are.equal(404, status({ conference = 'r'; agentId = 'agent-support'; state = 'ended' }).status_code);
+ assert.are.equal(1, #webhook_payloads('agent.ended'));
+ end)
+
+ it('sends no agent.ended for a failed agent when the room is destroyed', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'dial refused' });
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ assert.are.equal(0, #webhook_payloads('agent.ended'));
+ end)
+
+ it('sends no second terminal webhook when a failed agent is dismissed', function()
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'dial refused' });
+ assert.are.equal(200, dismiss({ conference = 'r'; agentId = 'agent-support' }).status_code);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support']);
+ assert.are.equal(1, #webhook_payloads('agent.failed'));
+ assert.are.equal(0, #webhook_payloads('agent.ended'));
+ end)
+ end)
+
+ describe('re-invite after failure', function()
+ it('replaces a failed agent instead of treating it as a duplicate', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ callbackUrl = 'https://app.example.com/hook' });
+ status({ conference = 'r'; agentId = 'agent-support'; state = 'failed'; reason = 'no bridge' });
+ metadata_events = 0;
+ local res = invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support';
+ callbackUrl = 'https://app.example.com/hook' });
+ assert.are.equal(200, res.status_code);
+ assert.are.equal('provisioning', mock_room.jitsiMetadata.agents['agent-support'].state);
+ assert.are.equal(2, metadata_events, 'removal broadcast, then the fresh entry');
+ assert.are.equal(0, #webhook_payloads('agent.ended'));
+ end)
+ end)
+
+ describe('dismiss', function()
+ it('removes an existing agent from both the client and jicofo maps', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ local res = dismiss({ conference = 'r'; agentId = 'agent-support' });
+ assert.are.equal(200, res.status_code);
+ assert.is_nil(mock_room.jitsiMetadata.agents['agent-support']);
+ assert.is_nil(mock_room._data.voice_agents['agent-support']);
+ assert.are.equal('agent-support', encoded[#encoded].agentId, '200 body echoes the agentId');
+ end)
+
+ it('returns 404 for an unknown agent', function()
+ assert.are.equal(404, dismiss({ conference = 'r'; agentId = 'agent-nope' }).status_code);
+ end)
+ end)
+ describe('callbackUrl host allowlist and signing', function()
+ it('refuses a host outside voice_agent_callback_allowed_hosts', function()
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; callbackUrl = 'https://evil.example.net/hook' }).status_code);
+ assert.are.equal(400,
+ invite({ conference = 'r'; displayName = 'B'; callbackUrl = 'https://app.example.com.evil.net/hook' }).status_code);
+ end)
+
+ it('accepts the listed host and its subdomains', function()
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'B'; agentId = 'one';
+ callbackUrl = 'https://app.example.com/hook' }).status_code);
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'B'; agentId = 'two';
+ callbackUrl = 'https://eu.app.example.com:8443/hook' }).status_code);
+ end)
+
+ it('logs only the host when a delivery gives up, never the URL\'s query string', function()
+ http_next_code = 500;
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support'; callbackUrl = CALLBACK .. '?token=sekrit' });
+ dismiss({ conference = 'r'; agentId = 'agent-support' });
+ while #timers > 0 do
+ local t = table.remove(timers, 1);
+ t.fn();
+ end
+ local gave_up = false;
+ for _, entry in ipairs(logs) do
+ assert.is_nil(entry.text:find('sekrit', 1, true), 'token leaked into a log line: ' .. entry.text);
+ if entry.text:find('app.example.com', 1, true) and entry.text:find('failed after', 1, true) then
+ gave_up = true;
+ end
+ end
+ assert.is_true(gave_up, 'expected a give-up warning naming the host');
+ end)
+ end)
+
+ describe('displayName', function()
+ it('rejects control characters, since it is broadcast to every client', function()
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'Bot\r\nX' }).status_code);
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'Bot\0' }).status_code);
+ end)
+ end)
+
+ describe('agentId normalization on every route', function()
+ it('accepts a bare id on get, status, dial and dismiss, answering with the stored id', function()
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support'; callbackUrl = CALLBACK });
+ assert.are.equal(200, get('conference=r&agentId=support').status_code);
+ assert.are.equal('agent-support', encoded[#encoded].agentId);
+ assert.are.equal(200, status({ conference = 'r'; agentId = 'support'; state = 'active' }).status_code);
+ assert.are.equal('agent-support', encoded[#encoded].agentId);
+ assert.are.equal(200, dial('conference=r&agentId=support', { token = 'Bearer relay-secret' }).status_code);
+ assert.are.equal('agent-support', encoded[#encoded].agentId);
+ assert.are.equal(200, dismiss({ conference = 'r'; agentId = 'support' }).status_code);
+ assert.are.equal('agent-support', encoded[#encoded].agentId);
+ assert.are.equal(0, #agent_ids(mock_room));
+ end)
+ end)
+
+ describe('breakout rooms', function()
+ it('fires agent.ended when a breakout room is destroyed', function()
+ invite({ conference = 'r'; displayName = 'B'; agentId = 'support'; callbackUrl = CALLBACK });
+ local hook = host_hooks_by_host['breakout.localhost']['muc-room-destroyed'];
+ assert.is_function(hook, 'the destroy hook must be installed on the breakout host too');
+ hook({ room = mock_room });
+ assert.are.equal(1, #webhook_payloads('agent.ended'));
+ end)
+ end)
+
+ describe('alternate configurations (module reloaded)', function()
+ -- Reloads the module with option overrides into the same `routes` table, so the request helpers above
+ -- drive the reloaded module; the defaults are restored afterwards.
+ local function reload_with(overrides)
+ option_overrides = overrides;
+ for k in pairs(routes) do routes[k] = nil; end
+ for k in pairs(shared_store) do shared_store[k] = nil; end
+ logs = {};
+ assert(pcall(dofile, 'mod_voice_agent_component.lua'));
+ end
+ after_each(function()
+ reload_with({});
+ end)
+
+ it('shares streams across the hosts the module is loaded on: a destroy seen by another instance reaches them', function()
+ reload_with({});
+ local first = {};
+ for k, v in pairs(routes) do first[k] = v; end
+ -- A second instance (the module loaded on another host) shares the store and now owns host_hooks.
+ assert(pcall(dofile, 'mod_voice_agent_component.lua'));
+ local response = sse_response();
+ table.insert(open_streams, response);
+ assert.is_true(first['GET voice-agent/events']({
+ request = { headers = { authorization = 'Bearer t' }; url = { query = 'conference=r' } }; response = response }));
+ next_decoded = { conference = 'r'; displayName = 'Bot'; agentId = 'support'; endpoint = DEFAULT_ENDPOINT };
+ assert.are.equal(200, first['POST voice-agent/invite']({
+ request = { headers = { content_type = 'application/json'; authorization = 'Bearer t' }; body = 'x' } }).status_code);
+ host_hooks['muc-room-destroyed']({ room = mock_room });
+ local received = stream_events(response);
+ assert.are.equal('agent.ended', received[#received].event);
+ local ended = webhook_payloads('agent.ended');
+ assert.are.equal(1, #ended, 'the destroy ends the agent once across instances');
+ assert.are.equal('room-destroyed', ended[1].reason);
+ end)
+
+ it('refuses event streams beyond voice_agent_max_event_streams with 503', function()
+ reload_with({ voice_agent_max_event_streams = 1 });
+ assert.is_true((events('conference=r')));
+ assert.are.equal(503, events('conference=r').status_code);
+ end)
+
+ it('closes a stream past voice_agent_event_stream_max_age on the keepalive tick', function()
+ reload_with({ voice_agent_event_stream_max_age = 0 });
+ local _, response = events('conference=r');
+ timers[#timers].fn();
+ assert.is_true(response.finished);
+ assert.are.equal('0\r\n\r\n', response.writes[#response.writes]);
+ end)
+
+ it('refuses to load without an ASAP key repository, so a meeting token can never provision agents', function()
+ reload_with({ prosody_password_public_key_repo_url = '' });
+ assert.is_nil(next(routes), 'no route may be registered');
+ local said_why = false;
+ for _, entry in ipairs(logs) do
+ if entry.level == 'error' and entry.text:find('prosody_password_public_key_repo_url', 1, true) then
+ said_why = true;
+ end
+ end
+ assert.is_true(said_why);
+ end)
+
+ it('loads without a key repository only under the insecure dev flag', function()
+ reload_with({ prosody_password_public_key_repo_url = ''; voice_agent_insecure_skip_auth = true });
+ assert.is_function(routes['POST voice-agent/invite']);
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'Bot' }, { omitAuth = true }).status_code);
+ end)
+
+ it('refuses a callbackUrl while webhooks cannot be signed', function()
+ reload_with({ voice_agent_webhook_secret = '' });
+ assert.are.equal(400, invite({ conference = 'r'; displayName = 'B'; callbackUrl = CALLBACK }).status_code);
+ assert.are.equal(200, invite({ conference = 'r'; displayName = 'B' }).status_code);
+ end)
+
+ it('lets the status secret read dial configs only while no dial secret is set', function()
+ reload_with({ voice_agent_dial_secret = '' });
+ invite({ conference = 'r'; displayName = 'Bot'; agentId = 'support' });
+ token_valid = false;
+ assert.are.equal(200, dial('conference=r&agentId=agent-support', { token = 'Bearer jicofo-secret' }).status_code);
+ end)
+ end)
+end)
diff --git a/webpack.config.js b/webpack.config.js
index 930238082c..569d78040b 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -390,7 +390,7 @@ module.exports = (_env, argv) => {
})
],
- performance: getPerformanceHints(perfHintOptions, 3.5 * 1024 * 1024) },
+ performance: getPerformanceHints(perfHintOptions, 3.6 * 1024 * 1024) },
{ ...config,
entry: {
'alwaysontop': './react/features/always-on-top/index.tsx'
@@ -443,7 +443,7 @@ module.exports = (_env, argv) => {
...config.plugins,
...getBundleAnalyzerPlugin(analyzeBundle, 'external_api')
],
- performance: getPerformanceHints(perfHintOptions, 100 * 1024) },
+ performance: getPerformanceHints(perfHintOptions, 110 * 1024) },
{ ...config,
entry: {
'preload': './react/features/preload/preload.web.ts'