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(audio-translation): live audio translation prosody support (#17537)

bgrozev7f0e07b85d4b
diff --git a/resources/prosody-plugins/mod_audio_translation_component.lua b/resources/prosody-plugins/mod_audio_translation_component.lua
new file mode 100644
index 0000000000..33aecc8a50
--- /dev/null
+++ b/resources/prosody-plugins/mod_audio_translation_component.lua
@@ -0,0 +1,475 @@
+-- mod_audio_translation_component.lua
+--
+-- Prosody component that collects per-receiver live-translation subscriptions
+-- and exposes the aggregated <senderId, set<language>> map to jicofo (and only
+-- jicofo) through RoomMetadata.
+--
+-- ── Subscription updates (client → component) ────────────────────────────────
+-- A receiver sends a <message> to this component containing an <audio-translation
+-- xmlns='http://jitsi.org/jitmeet'> child whose text is a JSON object that maps a
+-- sender's endpoint id to a target language:
+--
+-- { "a1b2c3d4": "en", "b2c3d4e5": "" }
+--
+-- The payload is a DELTA merged into the receiver's existing subscription map:
+-- · "<lang>" adds/replaces the subscription for that sender (one language per
+-- sender — a new language replaces the previous one).
+-- · "" removes the subscription for that sender (no-op if absent).
+-- Senders/languages not mentioned in the delta are left untouched.
+--
+-- The whole stanza is applied atomically: if any entry fails validation the
+-- entire delta is rejected with an error reply and no state changes.
+--
+-- Processing (on_message):
+-- 1. The sender must be an occupant of the room identified by the session's
+-- jitsi_web_query_room field (set from the WebSocket ?room= URL param).
+-- 2. If the feature is disabled in RoomMetadata (audioTranslation.enabled ==
+-- false) the message is a silent no-op. A missing flag means enabled.
+-- 3. The receiver must have the 'live-translation-subscribe' permission, which
+-- everybody has unless the token explicitly sets it to "false".
+-- 4. Each entry is validated: senderId is 8 hex digits and a current occupant,
+-- language is alphabetical and at most 20 characters (or "" to remove).
+-- 5. A receiver may hold at most audio_translation_max_subscriptions distinct
+-- subscriptions (unlimited by default; set the option to enforce a cap).
+--
+-- ── Aggregate map (component → jicofo) ───────────────────────────────────────
+-- Whenever the set of subscriptions changes, a debounced task recomputes the
+-- aggregate { [senderId] = { lang, ... } } (the union of all receivers' requests)
+-- and stores it on room._data.audioTranslationRequests, then fires
+-- 'room-metadata-changed' so mod_room_metadata_component broadcasts it. That
+-- module injects audioTranslationRequests into the metadata only for admin
+-- (jicofo) occupants, so regular clients never see it.
+--
+-- ── Enable-flag write gating ─────────────────────────────────────────────────
+-- The audioTranslation metadata key (which carries the room-level enable flag)
+-- is written through mod_room_metadata_component. This module hooks
+-- 'jitsi-metadata-allow-moderation' to gate that write behind the
+-- 'live-translation' permission (moderators by default) and to sanitise the
+-- stored value to { enabled = <bool> }.
+--
+-- Component "audiotranslation.jitmeet.example.com" "audio_translation_component"
+-- muc_component = "conference.jitmeet.example.com"
+local json = require 'util.json';
+local st = require 'util.stanza';
+local jid_resource = require 'util.jid'.resource;
+local timer = require 'util.timer';
+
+local util = module:require 'util';
+local is_healthcheck_room = util.is_healthcheck_room;
+local is_feature_allowed = util.is_feature_allowed;
+local get_room_by_name_and_subdomain = util.get_room_by_name_and_subdomain;
+local get_occupant_by_real_jid = util.get_occupant_by_real_jid;
+local process_host_module = util.process_host_module;
+
+local AUDIO_TRANSLATION_NS = 'http://jitsi.org/jitmeet';
+local ELEMENT_NAME = 'audio-translation';
+
+-- RoomMetadata key carrying the room-level enable flag ({ enabled = bool }).
+-- Client/preset writable through mod_room_metadata_component; read-only here.
+local ENABLED_METADATA_KEY = 'audioTranslation';
+-- Aggregate map exposed to jicofo only. Stored on room._data (never in
+-- jitsiMetadata) so it is never broadcast to regular clients.
+local REQUESTS_METADATA_KEY = 'audioTranslationRequests';
+
+local ENABLE_PERMISSION = 'live-translation';
+local SUBSCRIBE_PERMISSION = 'live-translation-subscribe';
+
+local LANG_MAX_LENGTH = 20;
+
+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
+
+local main_virtual_host = module:get_option_string('muc_mapper_domain_base');
+if not main_virtual_host then
+ module:log('warn', 'No muc_mapper_domain_base option set.');
+ return;
+end
+
+-- Maximum distinct subscriptions a single receiver may hold. Unlimited unless the option is set.
+local max_subscriptions = module:get_option_number('audio_translation_max_subscriptions');
+-- Coalesce bursts of subscription changes into a single metadata update.
+local debounce_interval = module:get_option_number('audio_translation_debounce_interval', 0.5);
+
+module:log('info', 'Starting audio_translation for %s (max_subscriptions=%s, debounce=%ss)',
+ muc_component_host, max_subscriptions and tostring(max_subscriptions) or 'unlimited', tostring(debounce_interval));
+
+local main_muc_module;
+
+-- Returns (creating if needed) the per-room translation state:
+-- { receivers = { [receiverId] = { [senderId] = lang } }, last_published = <json|nil> }
+local function get_state(room)
+ if not room._audio_translation then
+ room._audio_translation = { receivers = {} };
+ end
+
+ return room._audio_translation;
+end
+
+-- The endpoint id of an occupant is the resource part of its in-room nick.
+local function endpoint_id(occupant)
+ return jid_resource(occupant.nick);
+end
+
+-- True unless the feature is explicitly disabled (audioTranslation.enabled == false).
+-- A missing audioTranslation key, or a key without an explicit enabled=false,
+-- means enabled.
+local function is_enabled(room)
+ local at = room.jitsiMetadata and room.jitsiMetadata[ENABLED_METADATA_KEY];
+
+ if type(at) == 'table' and at.enabled == false then
+ return false;
+ end
+
+ return true;
+end
+
+-- Everyone may subscribe unless the token explicitly sets the permission to false.
+local function subscribe_allowed(session)
+ local features = session and session.jitsi_meet_context_features;
+
+ if features then
+ local v = features[SUBSCRIBE_PERMISSION];
+
+ if v == false or v == 'false' then
+ return false;
+ end
+ end
+
+ return true;
+end
+
+local function is_valid_sender_id(id)
+ return type(id) == 'string' and id:match('^%x%x%x%x%x%x%x%x$') ~= nil;
+end
+
+local function is_valid_language(lang)
+ return type(lang) == 'string' and #lang <= LANG_MAX_LENGTH and lang:match('^%a+$') ~= nil;
+end
+
+-- Applies a delta to the receiver's subscription map atomically.
+-- Returns true on success, or false plus an (error-type, condition) pair.
+local function apply_delta(room, receiver_id, delta)
+ local state = get_state(room);
+ local current = state.receivers[receiver_id] or {};
+
+ -- Work on a copy so a mid-delta failure leaves the stored map untouched.
+ local next_map = {};
+
+ for sender_id, lang in pairs(current) do
+ next_map[sender_id] = lang;
+ end
+
+ for sender_id, lang in pairs(delta) do
+ if not is_valid_sender_id(sender_id) then
+ return false, 'modify', 'bad-request';
+ end
+
+ if type(lang) ~= 'string' then
+ return false, 'modify', 'bad-request';
+ end
+
+ if lang == '' then
+ -- Removal; benign no-op when the sender is not currently subscribed.
+ next_map[sender_id] = nil;
+ else
+ if not is_valid_language(lang) then
+ return false, 'modify', 'bad-request';
+ end
+
+ if not room:get_occupant_by_nick(room.jid..'/'..sender_id) then
+ return false, 'cancel', 'item-not-found';
+ end
+
+ next_map[sender_id] = lang;
+ end
+ end
+
+ local count = 0;
+
+ for _ in pairs(next_map) do
+ count = count + 1;
+ end
+
+ if max_subscriptions and count > max_subscriptions then
+ return false, 'cancel', 'policy-violation';
+ end
+
+ state.receivers[receiver_id] = next_map;
+
+ return true;
+end
+
+-- Builds the aggregate { [senderId] = { lang, ... } } (union over all receivers),
+-- or nil when there are no subscriptions.
+local function compute_aggregate(room)
+ local sets = {};
+ local any = false;
+
+ for _, subs in pairs(get_state(room).receivers) do
+ for sender_id, lang in pairs(subs) do
+ local set = sets[sender_id];
+
+ if not set then
+ set = {};
+ sets[sender_id] = set;
+ end
+ set[lang] = true;
+ any = true;
+ end
+ end
+
+ if not any then
+ return nil;
+ end
+
+ local out = {};
+
+ for sender_id, set in pairs(sets) do
+ local langs = {};
+
+ for lang in pairs(set) do
+ langs[#langs + 1] = lang;
+ end
+ table.sort(langs);
+ out[sender_id] = langs;
+ end
+
+ return out;
+end
+
+-- Recomputes the aggregate and, when it changed, publishes it to jicofo via
+-- RoomMetadata. Stored on room._data so mod_room_metadata_component only forwards
+-- it to admin (jicofo) occupants.
+-- While the feature is disabled for the room the published map is cleared (nil) so
+-- jicofo stops translation; the receivers' subscriptions are kept in memory and
+-- republished if the room is re-enabled.
+local function publish(room)
+ if not room._audio_translation or not main_muc_module then
+ return;
+ end
+
+ -- Neutral, default-open extension point: an external module may veto publishing
+ -- the translation request map by returning false from this event. No handler, or
+ -- any non-false return, means allowed. This keeps any gating/entitlement logic out
+ -- of this module (open by default). Follows the same false=deny / nil=no-opinion
+ -- convention as 'jitsi-metadata-allow-moderation'.
+ local allow_publish = main_muc_module:fire_event('jitsi-audio-translation-allow-publish', { room = room; }) ~= false;
+
+ -- The request set the receivers have asked for, independent of gating. Computed
+ -- unconditionally so we can tell "nothing requested" apart from "requests suppressed".
+ local requested = compute_aggregate(room);
+ local aggregate = (allow_publish and is_enabled(room)) and requested or nil;
+ local encoded = aggregate and json.encode(aggregate) or nil;
+
+ if encoded == room._audio_translation.last_published then
+ return;
+ end
+ room._audio_translation.last_published = encoded;
+
+ -- Log when we transition to suppressing a non-empty request set (feature disabled for
+ -- the room, or an external handler vetoed publishing). Deduped by last_published above,
+ -- so this fires on the transition, not on every update. Normally the client hides the
+ -- control, so a suppressed request set is worth being able to discover.
+ if aggregate == nil and requested ~= nil then
+ module:log('warn', 'Not publishing audio-translation requests in room %s: %s', room.jid,
+ allow_publish and 'disabled for the room' or 'publishing vetoed by a handler');
+ end
+
+ room._data.audioTranslationRequests = aggregate;
+
+ main_muc_module:fire_event('room-metadata-changed', { room = room; });
+end
+
+-- Schedules a debounced publish so a burst of updates produces a single metadata
+-- broadcast.
+local function schedule_publish(room)
+ local state = get_state(room);
+
+ if state.publish_scheduled then
+ return;
+ end
+ state.publish_scheduled = true;
+
+ timer.add_task(debounce_interval, function()
+ if room._audio_translation then
+ room._audio_translation.publish_scheduled = nil;
+ end
+ publish(room);
+ end);
+end
+
+function on_message(event)
+ local origin, stanza = event.origin, event.stanza;
+
+ if stanza.attr.type == 'error' then
+ return; -- Do not reply to error stanzas (avoids loops).
+ end
+
+ if not origin or not origin.jitsi_web_query_room then
+ return false;
+ end
+
+ local at = stanza:get_child(ELEMENT_NAME, AUDIO_TRANSLATION_NS);
+
+ if not at then
+ return true; -- Not for us.
+ end
+
+ local body = at:get_text();
+
+ if not body or body == '' then
+ return true;
+ end
+
+ local room = get_room_by_name_and_subdomain(
+ origin.jitsi_web_query_room, origin.jitsi_web_query_prefix or '');
+
+ if not room then
+ module:log('warn', 'No room found for %s/%s',
+ origin.jitsi_web_query_prefix, origin.jitsi_web_query_room);
+ origin.send(st.error_reply(stanza, 'cancel', 'item-not-found'));
+
+ return true;
+ end
+
+ local from = stanza.attr.from;
+ local occupant = get_occupant_by_real_jid(room, from);
+
+ if not occupant then
+ module:log('warn', '%s is not an occupant of %s', from, room.jid);
+ origin.send(st.error_reply(stanza, 'auth', 'forbidden'));
+
+ return true;
+ end
+
+ -- Disabled for the room → no-op. Log it: the client normally hides the control when
+ -- translation is disabled, so a subscription arriving here is unexpected and worth
+ -- being able to discover.
+ if not is_enabled(room) then
+ module:log('warn', 'Ignoring audio-translation subscription from %s: disabled for room %s', from, room.jid);
+ return true;
+ end
+
+ if not subscribe_allowed(origin) then
+ module:log('warn', '%s is not allowed to subscribe to translations in %s', from, room.jid);
+ origin.send(st.error_reply(stanza, 'auth', 'forbidden'));
+
+ return true;
+ end
+
+ local delta = json.decode(body);
+
+ if type(delta) ~= 'table' then
+ module:log('warn', 'Invalid audio_translation payload from %s: %s', from, body);
+ origin.send(st.error_reply(stanza, 'modify', 'bad-request'));
+
+ return true;
+ end
+
+ local ok, err_type, err_condition = apply_delta(room, endpoint_id(occupant), delta);
+
+ if not ok then
+ origin.send(st.error_reply(stanza, err_type, err_condition));
+
+ return true;
+ end
+
+ schedule_publish(room);
+
+ return true;
+end
+
+module:hook('message/host', on_message);
+
+function process_main_muc_loaded(main_muc, host_module)
+ main_muc_module = host_module;
+
+ module:log('info', 'Hooked audio_translation to muc events on %s', muc_component_host);
+
+ -- Prune subscriptions when an occupant leaves: drop the leaver's own
+ -- subscriptions (receiver) and remove it as a sender from everyone else.
+ host_module:hook('muc-occupant-left', function(event)
+ local room, occupant = event.room, event.occupant;
+
+ if not room._audio_translation or is_healthcheck_room(room.jid) then
+ return;
+ end
+
+ local id = endpoint_id(occupant);
+ local changed = false;
+
+ if room._audio_translation.receivers[id] then
+ room._audio_translation.receivers[id] = nil;
+ changed = true;
+ end
+
+ for _, subs in pairs(room._audio_translation.receivers) do
+ if subs[id] then
+ subs[id] = nil;
+ changed = true;
+ end
+ end
+
+ if changed then
+ schedule_publish(room);
+ end
+ end);
+
+ -- React when the room-level enable flag is toggled: republish so the aggregate
+ -- map is cleared when disabled (translation stops) or restored when re-enabled.
+ host_module:hook('jitsi-metadata-updated', function(event)
+ local room = event.room;
+
+ if event.key == ENABLED_METADATA_KEY and room._audio_translation
+ and not is_healthcheck_room(room.jid) then
+ schedule_publish(room);
+ end
+ end);
+end
+
+process_host_module(muc_component_host, function(host_module, host)
+ local muc_module = prosody.hosts[host].modules.muc;
+
+ if muc_module then
+ process_main_muc_loaded(muc_module, host_module);
+ else
+ module:log('debug', 'Will wait for muc to be available');
+ prosody.hosts[host].events.add_handler('module-loaded', function(event)
+ if event.module == 'muc' then
+ process_main_muc_loaded(prosody.hosts[host].modules.muc, host_module);
+ end
+ end);
+ end
+end);
+
+-- Advertise the component as a disco identity on the main virtual host so
+-- clients can discover it (handled by mod_features_identity), and gate writes to
+-- the audioTranslation enable flag behind the 'live-translation' permission
+-- (moderators by default) while sanitising the stored value.
+process_host_module(main_virtual_host, function(host_module)
+ module:context(host_module.host):fire_event('jitsi-add-identity', {
+ name = ELEMENT_NAME; host = module.host;
+ });
+
+ host_module:hook('jitsi-metadata-allow-moderation', function(event)
+ if event.key ~= ENABLED_METADATA_KEY then
+ return; -- No opinion on other keys.
+ end
+
+ local session = event.session;
+ local is_moderator = event.actor and event.actor.role == 'moderator';
+ local features = session and session.jitsi_meet_context_features;
+
+ if not is_feature_allowed(ENABLE_PERMISSION, features, is_moderator) then
+ return false;
+ end
+
+ local data = event.data;
+ local enabled = type(data) == 'table' and (data.enabled == true or data.enabled == 'true');
+
+ return { enabled = enabled };
+ end);
+end);
diff --git a/resources/prosody-plugins/mod_jitsi_permissions.lua b/resources/prosody-plugins/mod_jitsi_permissions.lua
index 20992589dd..dffd0df516 100644
--- a/resources/prosody-plugins/mod_jitsi_permissions.lua
+++ b/resources/prosody-plugins/mod_jitsi_permissions.lua
@@ -59,6 +59,8 @@ local function load_config()
['create-polls'] = true;
['send-groupchat'] = true;
flip = true;
+ ['live-translation'] = true;
+ ['live-translation-subscribe'] = true;
});
end
load_config();
diff --git a/resources/prosody-plugins/mod_room_metadata_component.lua b/resources/prosody-plugins/mod_room_metadata_component.lua
index b06ad97d3d..66446fa00a 100644
--- a/resources/prosody-plugins/mod_room_metadata_component.lua
+++ b/resources/prosody-plugins/mod_room_metadata_component.lua
@@ -107,6 +107,7 @@ local blocked_metadata_keys = module:get_option_set('room_metadata_blocked_keys'
'allownersEnabled',
'asyncTranscription',
'audioTranslationAvailable',
+ 'audioTranslationRequests',
'conferencePresetsServiceEnabled',
'dialinEnabled',
'moderators',
@@ -193,6 +194,25 @@ function send_metadata(occupant, room, json_msg, include_services)
metadata_to_send.participants = participants;
metadata_to_send.moderators = moderators;
+ -- The aggregated live-translation request map is for jicofo only.
+ -- It is kept on room._data (never in jitsiMetadata) so it is never
+ -- broadcast to regular clients.
+ metadata_to_send.audioTranslationRequests = room._data.audioTranslationRequests;
+
+ -- Neutral, default-open extension point: an external module may contribute
+ -- additional jicofo-only metadata fields by returning a table from this
+ -- event -- for instance per-room translator connect headers. Fired inside
+ -- the admin branch, so injected fields reach only jicofo and are never
+ -- broadcast to client occupants. No handler means nothing is added; this
+ -- module holds no token/entitlement logic of its own.
+ local admin_extra = main_muc_module and main_muc_module:fire_event(
+ 'jitsi-room-metadata-admin-extra', { room = room; });
+ if type(admin_extra) == 'table' then
+ for k, v in pairs(admin_extra) do
+ metadata_to_send[k] = v;
+ end
+ end
+
module:log('info', 'Sending metadata to jicofo room=%s,meeting_id=%s', room.jid, room._data.meetingId);
else
-- regular occupants get a sanitized copy (jicofo-only fields removed)
diff --git a/resources/prosody-plugins/mod_test_observer_http.lua b/resources/prosody-plugins/mod_test_observer_http.lua
index 1f19507902..f648607036 100644
--- a/resources/prosody-plugins/mod_test_observer_http.lua
+++ b/resources/prosody-plugins/mod_test_observer_http.lua
@@ -526,6 +526,35 @@ module:provides("http", {
};
end;
+ -- GET /test-observer/rooms/[email protected]
+ -- Returns: { jid, audioTranslationRequests } where the value is the
+ -- aggregated map stored on room._data by mod_audio_translation_component
+ -- (omitted when there are no subscriptions).
+ ["GET /rooms/audio-translation-requests"] = function(event)
+ local params = parse_query(event.request.url.query);
+ local room_jid = params["jid"];
+ if not room_jid then
+ return { status_code = 400; body = '{"error":"missing jid param"}' };
+ end
+ local rooms = shared.rooms or {};
+ local room = rooms[room_jid];
+ if not room then
+ return { status_code = 404; body = '{"error":"room not found"}' };
+ end
+ local encoded, err = json.encode({
+ jid = room.jid;
+ audioTranslationRequests = room._data.audioTranslationRequests;
+ });
+ if not encoded then
+ return { status_code = 500; body = json.encode({ error = 'encode failed: ' .. tostring(err) }) };
+ end
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = encoded;
+ };
+ end;
+
-- GET /test-observer/[email protected]
-- Returns: { jid, hidden, occupant_count }
["GET /rooms"] = function(event)
diff --git a/tests/prosody/docker/prosody.cfg.lua b/tests/prosody/docker/prosody.cfg.lua
index 7df3fe387e..315cbd715b 100644
--- a/tests/prosody/docker/prosody.cfg.lua
+++ b/tests/prosody/docker/prosody.cfg.lua
@@ -72,6 +72,9 @@ VirtualHost "localhost"
"muc_census";
-- Module order below follows prod (conference.8x8.vc VirtualHost) so that
-- same-priority hook execution order matches production.
+ -- Handles 'jitsi-add-identity' so components (room_metadata,
+ -- audio_translation, ...) can advertise a disco identity on this host.
+ "features_identity";
"conference_duration";
"filter_iq_rayo"; -- priority 1 on pre-iq/full; listed before filter_iq_jibri (matches prod)
"filter_iq_jibri";
@@ -290,6 +293,19 @@ Component "filesharing.localhost" "filesharing_component"
muc_mapper_domain_base = "localhost"
muc_mapper_domain_prefix = "conference"
+-- Component for mod_audio_translation_component tests. Receivers send
+-- <audio-translation> messages here; the component aggregates per-receiver
+-- subscriptions and exposes the map to jicofo via room._data.audioTranslationRequests
+-- (forwarded by mod_room_metadata_component on the metadata.localhost component).
+Component "audiotranslation.localhost" "audio_translation_component"
+ muc_component = "conference.localhost"
+ muc_mapper_domain_base = "localhost"
+ muc_mapper_domain_prefix = "conference"
+ -- Short debounce so tests don't wait long for the aggregate broadcast.
+ audio_translation_debounce_interval = 0.1
+ -- Low limit so the per-receiver cap is exercised without many subscriptions.
+ audio_translation_max_subscriptions = 3
+
-- Component for mod_polls_component tests. The module hooks message/host for
-- new-poll / answer-poll json-messages, keeps per-room poll state (installed on
-- conference.localhost via process_host_module) and re-broadcasts poll updates
diff --git a/tests/prosody/helpers/test_observer.js b/tests/prosody/helpers/test_observer.js
index 5d04d56dfa..4456a90677 100644
--- a/tests/prosody/helpers/test_observer.js
+++ b/tests/prosody/helpers/test_observer.js
@@ -284,6 +284,32 @@ export async function getRoomMetadata(roomJid) {
return res.json();
}
+/**
+ * Returns the aggregated live-translation request map stored on room._data by
+ * mod_audio_translation_component. Reads server state directly, so it is robust
+ * against broadcast de-duplication (no broadcast fires when the aggregate is
+ * unchanged).
+ *
+ * Returns null if the room does not exist; the map is undefined when there are
+ * no subscriptions.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @returns {Promise<{jid: string, audioTranslationRequests?: object}|null>}
+ */
+export async function getAudioTranslationRequests(roomJid) {
+ const res = await fetch(
+ `${BASE}/rooms/audio-translation-requests?jid=${encodeURIComponent(roomJid)}`);
+
+ if (res.status === 404) {
+ return null;
+ }
+ if (!res.ok) {
+ throw new Error(`GET /rooms/audio-translation-requests failed: ${res.status} ${await res.text()}`);
+ }
+
+ return res.json();
+}
+
/**
* Returns room state from Prosody's internal MUC state.
* @param {string} roomJid e.g. '[email protected]'
diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.js
index 5aac6f58e7..982fb1fff8 100644
--- a/tests/prosody/helpers/xmpp_client.js
+++ b/tests/prosody/helpers/xmpp_client.js
@@ -454,6 +454,37 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
data }));
},
+ /**
+ * Sends a raw <audio-translation> message to an audio-translation component.
+ * Use this to test malformed payloads; prefer sendAudioTranslation for
+ * well-formed deltas.
+ *
+ * The session must have jitsi_web_query_room set (connect with
+ * params: { room: '<roomname>' }) — the component resolves the room from
+ * the session, not from a stanza attribute.
+ *
+ * @param {string} componentJid e.g. 'audiotranslation.localhost'
+ * @param {string} rawPayload raw text for the <audio-translation> body
+ */
+ sendAudioTranslationRaw(componentJid, rawPayload) {
+ return xmpp.send(
+ xml('message', { to: componentJid,
+ id: `at-${++_counter}` },
+ xml('audio-translation', { xmlns: 'http://jitsi.org/jitmeet' }, rawPayload)
+ )
+ );
+ },
+
+ /**
+ * Sends a well-formed audio-translation subscription delta.
+ *
+ * @param {string} componentJid e.g. 'audiotranslation.localhost'
+ * @param {object} delta { senderId: language, ... }; "" removes
+ */
+ sendAudioTranslation(componentJid, delta) {
+ return this.sendAudioTranslationRaw(componentJid, JSON.stringify(delta));
+ },
+
/**
* Sends a plain <message> stanza to the given JID with no special children.
* Useful for testing that the end_conference component ignores messages
diff --git a/tests/prosody/mod_audio_translation_component_spec.js b/tests/prosody/mod_audio_translation_component_spec.js
new file mode 100644
index 0000000000..1b2ae38950
--- /dev/null
+++ b/tests/prosody/mod_audio_translation_component_spec.js
@@ -0,0 +1,988 @@
+import assert from 'assert';
+
+import { mintAsapToken } from './helpers/jwt.js';
+import { getAudioTranslationRequests, setRoomMaxOccupants } from './helpers/test_observer.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const AT_COMPONENT = 'audiotranslation.localhost';
+const METADATA_COMPONENT = 'metadata.localhost';
+const JITMEET_NS = 'http://jitsi.org/jitmeet';
+
+// Matches audio_translation_max_subscriptions in docker/prosody.cfg.lua.
+const MAX_SUBSCRIPTIONS = 3;
+
+let _counter = 0;
+const nextRoom = () => `at-${++_counter}@${CONFERENCE}`;
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+/**
+ * Connects a client on the main VirtualHost, passing ?room=<roomName> so that
+ * mod_jitsi_session sets jitsi_web_query_room (required by the component).
+ *
+ * @param {string} roomJid full room JID
+ * @param {object} [opts]
+ * @param {object} [opts.user] JWT context.user claims
+ * @param {object} [opts.features] JWT context.features map
+ */
+function connect(roomJid, { user, features } = {}) {
+ const roomName = roomJid.split('@')[0];
+ const params = { room: roomName };
+
+ if (user !== undefined || features !== undefined) {
+ const context = {};
+
+ if (user !== undefined) {
+ context.user = user;
+ }
+ if (features !== undefined) {
+ context.features = features;
+ }
+ params.token = mintAsapToken({ room: roomName,
+ context });
+ }
+
+ return createXmppClient({ params });
+}
+
+/**
+ * Joins the focus (creating the room) and raises the per-room occupant limit so
+ * tests can add more than the global muc_max_occupants (2) regular occupants.
+ */
+async function startRoom(roomJid) {
+ const foc = await joinWithFocus(roomJid);
+
+ await setRoomMaxOccupants(roomJid, 50);
+
+ return foc;
+}
+
+/** Connects a client and joins the room as an occupant. */
+async function joinOccupant(roomJid, opts) {
+ const c = await connect(roomJid, opts);
+
+ await c.joinRoom(roomJid);
+
+ return c;
+}
+
+/** True if the stanza is a metadata broadcast (a json-message message). */
+function isMetadataBroadcast(msg) {
+ return msg.name === 'message'
+ && msg.getChild('json-message', JITMEET_NS) !== undefined;
+}
+
+/** Parses a metadata broadcast stanza into its JSON payload (or null). */
+function parseBroadcast(msg) {
+ const text = msg.getChild('json-message', JITMEET_NS)?.getText();
+
+ return text ? JSON.parse(text) : null;
+}
+
+/** Waits for the next metadata broadcast delivered to a client. */
+function waitForMetadata(client, timeout = 3000) {
+ return client.waitForMessage(isMetadataBroadcast, timeout);
+}
+
+/**
+ * Drains the initial metadata push delivered to an occupant on join, so a later
+ * waitForMetadata sees the next real broadcast rather than this one.
+ *
+ * Only call this for regular occupants — they receive the push immediately (it
+ * is queued during the join), so the timeout is never actually hit. The focus is
+ * the room creator: its self-presence is emitted while the room is still locked,
+ * before mod_room_metadata_component's muc-room-created hook initialises
+ * room.sent_initial_metadata, so the initial-metadata filter skips it and focus
+ * never gets a push to drain.
+ */
+async function drainInitialMetadata(client) {
+ try {
+ await waitForMetadata(client, 500);
+ } catch { /* no initial metadata is fine */ }
+}
+
+/** Asserts that no metadata broadcast arrives within the timeout. */
+async function assertNoMetadata(client, timeout = 350) {
+ try {
+ await client.waitForMessage(isMetadataBroadcast, timeout);
+ throw new Error('received unexpected metadata broadcast');
+ } catch (err) {
+ if (err.message.includes('Timeout')) {
+ return;
+ }
+ throw err;
+ }
+}
+
+/** Asserts that no error stanza arrives within the timeout. */
+async function assertNoErrorStanza(client, timeout = 300) {
+ try {
+ await client.waitForMessage(s => s.attrs.type === 'error', timeout);
+ throw new Error('received unexpected error stanza — module may have crashed');
+ } catch (err) {
+ if (err.message.includes('Timeout')) {
+ return;
+ }
+ throw err;
+ }
+}
+
+/** Waits for an error reply to a subscription request. */
+function waitForError(client, timeout = 2000) {
+ return client.waitForMessage(s => s.attrs.type === 'error', timeout);
+}
+
+/** Waits long enough for a delta to be processed and the debounced publish to run. */
+function settle(ms = 300) {
+ return new Promise(res => setTimeout(res, ms));
+}
+
+/** Sends a delta and returns the aggregate map as seen by jicofo (the focus). */
+async function pushAndGetRequests(rx, focus, delta) {
+ rx.sendAudioTranslation(AT_COMPONENT, delta);
+ const broadcast = await waitForMetadata(focus);
+
+ return parseBroadcast(broadcast).metadata.audioTranslationRequests;
+}
+
+/**
+ * Waits for a metadata broadcast whose audioTranslationRequests satisfies `predicate`, returning that value.
+ * Toggling the enable flag produces an immediate flag-change broadcast and a later debounced aggregate update,
+ * so callers use the predicate to skip to the broadcast they care about.
+ */
+async function waitForRequests(focus, predicate) {
+ for (let i = 0; i < 5; i++) {
+ const broadcast = await waitForMetadata(focus); // eslint-disable-line no-await-in-loop
+ const requests = parseBroadcast(broadcast).metadata.audioTranslationRequests;
+
+ if (predicate(requests)) {
+ return requests;
+ }
+ }
+ throw new Error('audioTranslationRequests did not reach the expected state');
+}
+
+// ─── Tests ────────────────────────────────────────────────────────────────────
+
+describe('mod_audio_translation_component', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // ── Disco identity ────────────────────────────────────────────────────────
+ describe('disco identity', () => {
+
+ it('advertises an audio-translation component identity on the main host', async () => {
+ const c = await connect(nextRoom());
+
+ clients.push(c);
+
+ const res = await c.sendDiscoInfo('localhost');
+ const identities = res.getChild('query', 'http://jabber.org/protocol/disco#info')
+ ?.getChildren('identity') ?? [];
+ const at = identities.find(i =>
+ i.attrs.category === 'component' && i.attrs.type === 'audio-translation');
+
+ assert.ok(at, 'main host disco#info must advertise an audio-translation component identity');
+ assert.strictEqual(at.attrs.name, AT_COMPONENT);
+ });
+ });
+
+ // ── Routing / parsing ───────────────────────────────────────────────────
+ describe('routing and parsing', () => {
+
+ it('ignores a message with no <audio-translation> child', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ rx.sendPlainMessage(AT_COMPONENT);
+
+ await assertNoErrorStanza(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('ignores an empty <audio-translation> body', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslationRaw(AT_COMPONENT, '');
+
+ await assertNoErrorStanza(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects invalid JSON', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslationRaw(AT_COMPONENT, '{not valid json{{');
+
+ const err = await waitForError(rx);
+
+ assert.equal(err.attrs.type, 'error');
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects a JSON payload that is not an object', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslationRaw(AT_COMPONENT, '"a string"');
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('ignores a message from a session without a room context', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+
+ // Connect WITHOUT ?room= so jitsi_web_query_room is unset.
+ const rx = await createXmppClient();
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { a1b2c3d4: 'en' });
+
+ await assertNoMetadata(foc);
+ });
+ });
+
+ // ── Room / occupant ─────────────────────────────────────────────────────
+ describe('room and occupant resolution', () => {
+
+ it('rejects a sender that is not an occupant of the room', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+
+ // Connected with a room context but never joined the MUC.
+ const rx = await connect(r);
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { a1b2c3d4: 'en' });
+
+ const err = await waitForError(rx);
+
+ assert.equal(err.attrs.type, 'error');
+ await assertNoMetadata(foc);
+ });
+ });
+
+ // ── Enabled flag ────────────────────────────────────────────────────────
+ describe('enabled flag', () => {
+
+ it('silently ignores requests when audioTranslation.enabled is false', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const mod = await joinOccupant(r, { user: { moderator: true } });
+
+ clients.push(foc, mod);
+ await drainInitialMetadata(mod);
+
+ // Disable the feature.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: false });
+ await waitForMetadata(foc);
+
+ const sender = await joinOccupant(r);
+
+ clients.push(sender);
+
+ mod.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+
+ await assertNoErrorStanza(mod);
+ await assertNoMetadata(foc);
+ });
+
+ it('processes requests when audioTranslation is absent (enabled by default)', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+
+ assert.deepEqual(requests[sender.nick], [ 'en' ]);
+ });
+
+ it('clears the map (stops translation) when disabled, and restores it when re-enabled', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const mod = await joinOccupant(r, { user: { moderator: true } });
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, mod, sender);
+ await drainInitialMetadata(mod);
+
+ // Subscribe — the aggregate map reaches jicofo.
+ const requests = await pushAndGetRequests(mod, foc, { [sender.nick]: 'en' });
+
+ assert.deepEqual(requests[sender.nick], [ 'en' ]);
+
+ // Disable — the map is cleared so jicofo stops translation.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: false });
+ const cleared = await waitForRequests(foc, v => v === undefined);
+
+ assert.equal(cleared, undefined);
+
+ // Re-enable — the retained subscription is republished.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: true });
+ const restored = await waitForRequests(foc, v => v !== undefined);
+
+ assert.deepEqual(restored[sender.nick], [ 'en' ]);
+ });
+ });
+
+ // ── Subscribe authorization ──────────────────────────────────────────────
+ describe('subscribe authorization (live-translation-subscribe)', () => {
+
+ it('denies a receiver whose token sets live-translation-subscribe to false', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r, { features: { 'live-translation-subscribe': 'false' } });
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+
+ const err = await waitForError(rx);
+
+ assert.equal(err.attrs.type, 'error');
+ await assertNoMetadata(foc);
+ });
+
+ it('allows a receiver with no token features', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+
+ assert.deepEqual(requests[sender.nick], [ 'en' ]);
+ });
+
+ it('allows a receiver whose token sets the feature to true', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r, { features: { 'live-translation-subscribe': 'true' } });
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+
+ assert.deepEqual(requests[sender.nick], [ 'en' ]);
+ });
+ });
+
+ // ── Validation (atomic) ──────────────────────────────────────────────────
+ describe('validation (whole-stanza atomicity)', () => {
+
+ it('rejects a senderId that is not 8 hex digits', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { nothex: 'en' });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects a non-alphabetical language', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en1' });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects a language longer than 20 characters', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'a'.repeat(21) });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects a request whose target sender is not a current occupant', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+
+ // Syntactically valid 8-hex id that belongs to nobody in the room.
+ rx.sendAudioTranslation(AT_COMPONENT, { deadbeef: 'en' });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('rejects the whole stanza when one of several entries is invalid', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ // First entry valid, second invalid → nothing must be applied.
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en',
+ badid: 'fr' });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+
+ // A subsequent valid request proves the first entry was NOT applied:
+ // only the new sender appears.
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'de' });
+
+ assert.deepEqual(requests, { [sender.nick]: [ 'de' ] });
+ });
+ });
+
+ // ── Delta semantics ───────────────────────────────────────────────────────
+ describe('delta semantics', () => {
+
+ it('merges added entries and leaves earlier ones untouched', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const s1 = await joinOccupant(r);
+ const s2 = await joinOccupant(r);
+
+ clients.push(foc, rx, s1, s2);
+
+ await pushAndGetRequests(rx, foc, { [s1.nick]: 'en' });
+ const requests = await pushAndGetRequests(rx, foc, { [s2.nick]: 'fr' });
+
+ assert.deepEqual(requests[s1.nick], [ 'en' ]);
+ assert.deepEqual(requests[s2.nick], [ 'fr' ]);
+ });
+
+ it('removes an entry with an empty-string language', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const s1 = await joinOccupant(r);
+ const s2 = await joinOccupant(r);
+
+ clients.push(foc, rx, s1, s2);
+
+ await pushAndGetRequests(rx, foc, { [s1.nick]: 'en',
+ [s2.nick]: 'fr' });
+ const requests = await pushAndGetRequests(rx, foc, { [s1.nick]: '' });
+
+ assert.equal(requests[s1.nick], undefined);
+ assert.deepEqual(requests[s2.nick], [ 'fr' ]);
+ });
+
+ it('treats removal of an absent entry as a benign no-op', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const s1 = await joinOccupant(r);
+ const s2 = await joinOccupant(r);
+
+ clients.push(foc, rx, s1, s2);
+
+ // s2 is not subscribed; removing it must not reject and the add applies.
+ const requests = await pushAndGetRequests(rx, foc, { [s1.nick]: 'en',
+ [s2.nick]: '' });
+
+ assert.deepEqual(requests[s1.nick], [ 'en' ]);
+ assert.equal(requests[s2.nick], undefined);
+ });
+
+ it('replaces the language when switching the same sender', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'es' });
+
+ assert.deepEqual(requests[sender.nick], [ 'es' ]);
+ });
+
+ it('does not broadcast when the resulting aggregate is unchanged', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+
+ // Identical request — aggregate does not change → no broadcast.
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+ await assertNoMetadata(foc);
+ });
+ });
+
+ // ── Per-receiver limit ─────────────────────────────────────────────────────
+ describe(`per-receiver limit (${MAX_SUBSCRIPTIONS})`, () => {
+
+ /** Joins n sender occupants and returns them. */
+ async function joinSenders(r, n) {
+ const senders = [];
+
+ for (let i = 0; i < n; i++) {
+ const s = await joinOccupant(r); // eslint-disable-line no-await-in-loop
+
+ senders.push(s);
+ clients.push(s);
+ }
+
+ return senders;
+ }
+
+ it('accepts subscriptions up to the limit', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+ const senders = await joinSenders(r, MAX_SUBSCRIPTIONS);
+
+
+ const delta = {};
+
+ for (const s of senders) {
+ delta[s.nick] = 'en';
+ }
+
+ const requests = await pushAndGetRequests(rx, foc, delta);
+
+ assert.equal(Object.keys(requests).length, MAX_SUBSCRIPTIONS);
+ });
+
+ it('rejects a new subscription that would exceed the limit', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+ const senders = await joinSenders(r, MAX_SUBSCRIPTIONS + 1);
+
+
+ const delta = {};
+
+ for (let i = 0; i < MAX_SUBSCRIPTIONS; i++) {
+ delta[senders[i].nick] = 'en';
+ }
+ await pushAndGetRequests(rx, foc, delta);
+
+ // One more distinct sender → over the limit → reject whole stanza.
+ rx.sendAudioTranslation(AT_COMPONENT, { [senders[MAX_SUBSCRIPTIONS].nick]: 'en' });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('allows a language switch at the limit (count unchanged)', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+ const senders = await joinSenders(r, MAX_SUBSCRIPTIONS);
+
+
+ const delta = {};
+
+ for (const s of senders) {
+ delta[s.nick] = 'en';
+ }
+ await pushAndGetRequests(rx, foc, delta);
+
+ const requests = await pushAndGetRequests(rx, foc, { [senders[0].nick]: 'es' });
+
+ assert.deepEqual(requests[senders[0].nick], [ 'es' ]);
+ });
+
+ it('rejects a delta whose net result exceeds the limit', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+
+ clients.push(foc, rx);
+ const senders = await joinSenders(r, MAX_SUBSCRIPTIONS + 2);
+
+
+ const delta = {};
+
+ for (let i = 0; i < MAX_SUBSCRIPTIONS; i++) {
+ delta[senders[i].nick] = 'en';
+ }
+ await pushAndGetRequests(rx, foc, delta);
+
+ // Remove 1, add 2 → net MAX+1 → reject whole stanza.
+ rx.sendAudioTranslation(AT_COMPONENT, {
+ [senders[0].nick]: '',
+ [senders[MAX_SUBSCRIPTIONS].nick]: 'en',
+ [senders[MAX_SUBSCRIPTIONS + 1].nick]: 'en'
+ });
+
+ await waitForError(rx);
+ await assertNoMetadata(foc);
+ });
+
+ it('tracks the limit independently per receiver', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+
+ clients.push(foc, rx1, rx2);
+ const senders = await joinSenders(r, MAX_SUBSCRIPTIONS);
+
+
+ const delta = {};
+
+ for (const s of senders) {
+ delta[s.nick] = 'en';
+ }
+
+ // rx1 fills its quota.
+ await pushAndGetRequests(rx1, foc, delta);
+
+ // rx2 may still subscribe to the same senders.
+ const requests = await pushAndGetRequests(rx2, foc, { [senders[0].nick]: 'fr' });
+
+ assert.deepEqual(requests[senders[0].nick].sort(), [ 'en', 'fr' ]);
+ });
+ });
+
+ // ── Aggregation across receivers ───────────────────────────────────────────
+ describe('aggregation across receivers', () => {
+
+ it('unions different languages requested for the same sender', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx1, rx2, sender);
+
+ await pushAndGetRequests(rx1, foc, { [sender.nick]: 'en' });
+ const requests = await pushAndGetRequests(rx2, foc, { [sender.nick]: 'fr' });
+
+ assert.deepEqual(requests[sender.nick].sort(), [ 'en', 'fr' ]);
+ });
+
+ it('deduplicates the same language requested by two receivers', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx1, rx2, sender);
+
+ await pushAndGetRequests(rx1, foc, { [sender.nick]: 'en' });
+
+ // rx2 wants the same language: the aggregate is unchanged so no
+ // broadcast fires. Read server state directly instead.
+ rx2.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+ await settle();
+
+ const { audioTranslationRequests } = await getAudioTranslationRequests(r);
+
+ assert.deepEqual(audioTranslationRequests[sender.nick], [ 'en' ]);
+ });
+
+ it('keeps a language referenced by another receiver after a switch', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx1, rx2, sender);
+
+ await pushAndGetRequests(rx1, foc, { [sender.nick]: 'en' });
+
+ // rx2 also wants en — aggregate unchanged, so no broadcast fires.
+ rx2.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+ await settle();
+
+ // rx1 switches to es; rx2 still references en → { sender: [en, es] }.
+ const requests = await pushAndGetRequests(rx1, foc, { [sender.nick]: 'es' });
+
+ assert.deepEqual(requests[sender.nick].sort(), [ 'en', 'es' ]);
+ });
+
+ it('drops a language when its sole referencer switches away', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+
+ await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+ const requests = await pushAndGetRequests(rx, foc, { [sender.nick]: 'es' });
+
+ assert.deepEqual(requests[sender.nick], [ 'es' ]);
+ });
+
+ it('keeps a language when one of two referencers removes it', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx1, rx2, sender);
+
+ await pushAndGetRequests(rx1, foc, { [sender.nick]: 'en' });
+
+ // rx2 requests the same language (no broadcast — aggregate unchanged).
+ rx2.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+ await settle();
+
+ // rx1 removes its request; rx2 still references 'en' so the aggregate
+ // is still { sender: [en] } — again no broadcast. Read server state.
+ rx1.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: '' });
+ await settle();
+
+ const { audioTranslationRequests } = await getAudioTranslationRequests(r);
+
+ assert.deepEqual(audioTranslationRequests[sender.nick], [ 'en' ]);
+ });
+
+ it('exposes the request map to jicofo but not to regular clients', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx, sender);
+ await drainInitialMetadata(rx);
+
+ rx.sendAudioTranslation(AT_COMPONENT, { [sender.nick]: 'en' });
+
+ const [ focBroadcast, rxBroadcast ] = await Promise.all([
+ waitForMetadata(foc),
+ waitForMetadata(rx)
+ ]);
+
+ assert.deepEqual(
+ parseBroadcast(focBroadcast).metadata.audioTranslationRequests[sender.nick],
+ [ 'en' ]);
+ assert.equal(
+ parseBroadcast(rxBroadcast).metadata.audioTranslationRequests,
+ undefined,
+ 'regular clients must never receive the request map');
+ });
+
+ it('blocks a client from setting audioTranslationRequests via metadata', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const mod = await joinOccupant(r, { user: { moderator: true } });
+
+ clients.push(foc, mod);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslationRequests', { evil: [ 'xx' ] });
+ await assertNoMetadata(mod);
+ });
+ });
+
+ // ── Enable-flag write gating (live-translation) ────────────────────────────
+ describe('enable-flag write gating (live-translation)', () => {
+
+ it('lets a moderator enable the feature', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const mod = await joinOccupant(r, { user: { moderator: true } });
+
+ clients.push(foc, mod);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: true });
+ const broadcast = await waitForMetadata(mod);
+
+ assert.deepEqual(parseBroadcast(broadcast).metadata.audioTranslation, { enabled: true });
+ });
+
+ it('denies a non-moderator without the live-translation feature', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const member = await joinOccupant(r, { user: { id: 'member1' } });
+
+ clients.push(foc, member);
+ await drainInitialMetadata(member);
+
+ member.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: true });
+ await assertNoMetadata(member);
+ });
+
+ it('allows a non-moderator whose token grants live-translation', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const member = await joinOccupant(r, { features: { 'live-translation': 'true' } });
+
+ clients.push(foc, member);
+ await drainInitialMetadata(member);
+
+ member.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation', { enabled: true });
+ const broadcast = await waitForMetadata(member);
+
+ assert.deepEqual(parseBroadcast(broadcast).metadata.audioTranslation, { enabled: true });
+ });
+
+ it('sanitizes the stored value to only the enabled flag', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const mod = await joinOccupant(r, { user: { moderator: true } });
+
+ clients.push(foc, mod);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'audioTranslation',
+ { enabled: true,
+ requests: { evil: [ 'xx' ] } });
+ const broadcast = await waitForMetadata(mod);
+
+ assert.deepEqual(parseBroadcast(broadcast).metadata.audioTranslation, { enabled: true });
+ });
+ });
+
+ // ── MUC-leave pruning ──────────────────────────────────────────────────────
+ describe('MUC-leave pruning', () => {
+
+ it('drops a receiver\'s subscriptions when it leaves', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx1 = await joinOccupant(r);
+ const rx2 = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, rx2, sender);
+
+ await pushAndGetRequests(rx1, foc, { [sender.nick]: 'en' });
+ await pushAndGetRequests(rx2, foc, { [sender.nick]: 'fr' });
+
+ await rx1.disconnect();
+
+ const broadcast = await waitForMetadata(foc);
+
+ assert.deepEqual(
+ parseBroadcast(broadcast).metadata.audioTranslationRequests[sender.nick],
+ [ 'fr' ]);
+ });
+
+ it('prunes a departed sender from every receiver', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const s1 = await joinOccupant(r);
+ const s2 = await joinOccupant(r);
+
+ clients.push(foc, rx, s2);
+
+ await pushAndGetRequests(rx, foc, { [s1.nick]: 'en',
+ [s2.nick]: 'fr' });
+
+ await s1.disconnect();
+
+ const broadcast = await waitForMetadata(foc);
+ const requests = parseBroadcast(broadcast).metadata.audioTranslationRequests;
+
+ assert.equal(requests[s1.nick], undefined);
+ assert.deepEqual(requests[s2.nick], [ 'fr' ]);
+ });
+
+ it('removes the request map entirely once the last subscription is gone', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const sender = await joinOccupant(r);
+
+ clients.push(foc, sender);
+
+ await pushAndGetRequests(rx, foc, { [sender.nick]: 'en' });
+
+ await rx.disconnect();
+
+ const broadcast = await waitForMetadata(foc);
+
+ assert.equal(parseBroadcast(broadcast).metadata.audioTranslationRequests, undefined);
+ });
+ });
+
+ // ── Debounce ────────────────────────────────────────────────────────────────
+ describe('debounce', () => {
+
+ it('coalesces a burst of deltas into a single broadcast', async () => {
+ const r = nextRoom();
+ const foc = await startRoom(r);
+ const rx = await joinOccupant(r);
+ const s1 = await joinOccupant(r);
+ const s2 = await joinOccupant(r);
+ const s3 = await joinOccupant(r);
+
+ clients.push(foc, rx, s1, s2, s3);
+
+ // Three rapid deltas within the debounce window.
+ rx.sendAudioTranslation(AT_COMPONENT, { [s1.nick]: 'en' });
+ rx.sendAudioTranslation(AT_COMPONENT, { [s2.nick]: 'fr' });
+ rx.sendAudioTranslation(AT_COMPONENT, { [s3.nick]: 'de' });
+
+ const broadcast = await waitForMetadata(foc);
+ const requests = parseBroadcast(broadcast).metadata.audioTranslationRequests;
+
+ assert.deepEqual(requests[s1.nick], [ 'en' ]);
+ assert.deepEqual(requests[s2.nick], [ 'fr' ]);
+ assert.deepEqual(requests[s3.nick], [ 'de' ]);
+
+ // Only one broadcast for the whole burst.
+ await assertNoMetadata(foc);
+ });
+ });
+});