Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add voice as a core plugin (#43044)

Rafael dos Santos Silva89bcc0f498cf
diff --git a/.gitignore b/.gitignore
index fed34449ded..eb6116be9e0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,6 +76,9 @@
!/plugins/discourse-cakeday
!/plugins/discourse-rewind
!/plugins/discourse-workflows
+!/plugins/voice
+/plugins/voice/gems
+/plugins/voice/public/javascripts
/plugins/*/auto_generated
/spec/fixtures/plugins/my_plugin/auto_generated
diff --git a/Gemfile b/Gemfile
index 0cb16063f2c..86a9655684d 100644
--- a/Gemfile
+++ b/Gemfile
@@ -308,6 +308,9 @@ gem "tiktoken_ruby", require: false
gem "smarter_json", require: false
gem "json_completer", require: false
gem "discourse_ai-tokenizers", require: false
+
+# for the voice plugin
+gem "discourse_voice_assets", require: false
gem "ed25519" # TODO: remove this as existing ssl gem should handle this
gem "Ascii85", require: false
gem "ruby-rc4", require: false
diff --git a/Gemfile.lock b/Gemfile.lock
index 79371856ee5..e86a0fca170 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -213,6 +213,7 @@ GEM
faker (~> 3.5.1)
literate_randomizer
discourse_math_bundle (1.0.1)
+ discourse_voice_assets (0.1.0)
docile (1.4.1)
drb (2.2.3)
dry-initializer (3.2.0)
@@ -854,6 +855,7 @@ DEPENDENCIES
discourse_ai-tokenizers
discourse_dev_assets
discourse_math_bundle
+ discourse_voice_assets
dry-initializer (~> 3.1)
ed25519
email_reply_trimmer
@@ -1047,6 +1049,7 @@ CHECKSUMS
discourse_ai-tokenizers (0.4.2) sha256=61c2f254582a3ae69255115b2b072904361003612b5b0f52aa64773817aae413
discourse_dev_assets (0.0.6) sha256=4dfe7946927aa3d61a4ba89b5aef39d6daaeb70e35d7125dc481806a5c0aea4e
discourse_math_bundle (1.0.1) sha256=c7d82fa65c9680cab2f77daeba32c1b89e500faccd2269e050ab27d5e1bc8337
+ discourse_voice_assets (0.1.0) sha256=67bfbc3e9eaa1805e71ac3c5e2172d8beefdecbfa7b956ed5426e7e057c10cc2
docile (1.4.1) sha256=96159be799bfa73cdb721b840e9802126e4e03dfc26863db73647204c727f21e
drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373
dry-initializer (3.2.0) sha256=37d59798f912dc0a1efe14a4db4a9306989007b302dcd5f25d0a2a20c166c4e3
diff --git a/app/models/notification.rb b/app/models/notification.rb
index e9784b2e3ab..e21b8828866 100644
--- a/app/models/notification.rb
+++ b/app/models/notification.rb
@@ -175,7 +175,7 @@ class Notification < ActiveRecord::Base
following_created_topic: 801, # Used by https://github.com/discourse/discourse-follow
following_replied: 802, # Used by https://github.com/discourse/discourse-follow
circles_activity: 900, # Used by https://github.com/discourse/discourse-circles
- resenha_invitation: 1000, # Used by https://github.com/discourse/resenha
+ voice_invitation: 1000, # Used by the voice plugin
)
end
diff --git a/db/structure.sql b/db/structure.sql
index eae1af0412c..db4ef82a16e 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -12405,6 +12405,230 @@ CREATE SEQUENCE public.users_id_seq
ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
+--
+-- Name: voice_co_presences; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_co_presences (
+ id bigint NOT NULL,
+ user_id_1 integer NOT NULL,
+ user_id_2 integer NOT NULL,
+ date date NOT NULL,
+ total_seconds integer DEFAULT 0 NOT NULL,
+ session_count integer DEFAULT 0 NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL,
+ CONSTRAINT chk_voice_co_presences_user_order CHECK ((user_id_1 < user_id_2))
+);
+
+
+--
+-- Name: voice_co_presences_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_co_presences_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_co_presences_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_co_presences_id_seq OWNED BY public.voice_co_presences.id;
+
+
+--
+-- Name: voice_invites; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_invites (
+ id bigint NOT NULL,
+ room_id bigint NOT NULL,
+ user_id bigint NOT NULL,
+ invited_by_id bigint NOT NULL,
+ source integer DEFAULT 0 NOT NULL,
+ redeemed_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: voice_invites_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_invites_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_invites_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_invites_id_seq OWNED BY public.voice_invites.id;
+
+
+--
+-- Name: voice_recordings; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_recordings (
+ id bigint NOT NULL,
+ room_id bigint NOT NULL,
+ started_by_id bigint NOT NULL,
+ egress_id character varying NOT NULL,
+ status integer DEFAULT 0 NOT NULL,
+ filepath character varying NOT NULL,
+ filename character varying,
+ location character varying,
+ duration_ms bigint,
+ size_bytes bigint,
+ started_at timestamp(6) without time zone NOT NULL,
+ ended_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: voice_recordings_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_recordings_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_recordings_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_recordings_id_seq OWNED BY public.voice_recordings.id;
+
+
+--
+-- Name: voice_room_memberships; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_room_memberships (
+ id bigint NOT NULL,
+ room_id bigint NOT NULL,
+ user_id bigint NOT NULL,
+ role integer DEFAULT 0 NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: voice_room_memberships_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_room_memberships_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_room_memberships_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_room_memberships_id_seq OWNED BY public.voice_room_memberships.id;
+
+
+--
+-- Name: voice_rooms; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_rooms (
+ id bigint NOT NULL,
+ name character varying NOT NULL,
+ slug character varying NOT NULL,
+ description text,
+ public boolean DEFAULT false NOT NULL,
+ max_participants integer,
+ creator_id bigint NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL,
+ cooked_description text,
+ room_type integer DEFAULT 0 NOT NULL,
+ video_enabled boolean DEFAULT true NOT NULL,
+ chat_channel_id bigint,
+ chat_idle_minutes integer DEFAULT 15 NOT NULL,
+ livekit_enabled boolean DEFAULT false NOT NULL,
+ max_quality_profile integer,
+ ephemeral boolean DEFAULT false NOT NULL,
+ last_occupied_at timestamp(6) without time zone
+);
+
+
+--
+-- Name: voice_rooms_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_rooms_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_rooms_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_rooms_id_seq OWNED BY public.voice_rooms.id;
+
+
+--
+-- Name: voice_sessions; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.voice_sessions (
+ id bigint NOT NULL,
+ user_id bigint NOT NULL,
+ room_id bigint NOT NULL,
+ joined_at timestamp(6) without time zone NOT NULL,
+ left_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: voice_sessions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.voice_sessions_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: voice_sessions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.voice_sessions_id_seq OWNED BY public.voice_sessions.id;
+
+
--
-- Name: watched_word_groups; Type: TABLE; Schema: public; Owner: -
--
@@ -14882,6 +15106,48 @@ ALTER TABLE ONLY public.user_warnings ALTER COLUMN id SET DEFAULT nextval('publi
ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
+--
+-- Name: voice_co_presences id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_co_presences ALTER COLUMN id SET DEFAULT nextval('public.voice_co_presences_id_seq'::regclass);
+
+
+--
+-- Name: voice_invites id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_invites ALTER COLUMN id SET DEFAULT nextval('public.voice_invites_id_seq'::regclass);
+
+
+--
+-- Name: voice_recordings id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_recordings ALTER COLUMN id SET DEFAULT nextval('public.voice_recordings_id_seq'::regclass);
+
+
+--
+-- Name: voice_room_memberships id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_room_memberships ALTER COLUMN id SET DEFAULT nextval('public.voice_room_memberships_id_seq'::regclass);
+
+
+--
+-- Name: voice_rooms id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_rooms ALTER COLUMN id SET DEFAULT nextval('public.voice_rooms_id_seq'::regclass);
+
+
+--
+-- Name: voice_sessions id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_sessions ALTER COLUMN id SET DEFAULT nextval('public.voice_sessions_id_seq'::regclass);
+
+
--
-- Name: watched_word_groups id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -17555,6 +17821,54 @@ ALTER TABLE ONLY public.user_search_data
ADD CONSTRAINT users_search_pkey PRIMARY KEY (user_id);
+--
+-- Name: voice_co_presences voice_co_presences_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_co_presences
+ ADD CONSTRAINT voice_co_presences_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: voice_invites voice_invites_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_invites
+ ADD CONSTRAINT voice_invites_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: voice_recordings voice_recordings_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_recordings
+ ADD CONSTRAINT voice_recordings_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: voice_room_memberships voice_room_memberships_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_room_memberships
+ ADD CONSTRAINT voice_room_memberships_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: voice_rooms voice_rooms_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_rooms
+ ADD CONSTRAINT voice_rooms_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: voice_sessions voice_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_sessions
+ ADD CONSTRAINT voice_sessions_pkey PRIMARY KEY (id);
+
+
--
-- Name: watched_word_groups watched_word_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -18591,6 +18905,34 @@ CREATE INDEX idx_users_ip_address ON public.users USING btree (ip_address);
CREATE INDEX idx_users_moderator ON public.users USING btree (id) WHERE moderator;
+--
+-- Name: idx_voice_co_presences_unique; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_voice_co_presences_unique ON public.voice_co_presences USING btree (user_id_1, user_id_2, date);
+
+
+--
+-- Name: idx_voice_invites_redeemed; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_voice_invites_redeemed ON public.voice_invites USING btree (invited_by_id, user_id) WHERE (redeemed_at IS NOT NULL);
+
+
+--
+-- Name: idx_voice_room_memberships_on_room_and_user; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_voice_room_memberships_on_room_and_user ON public.voice_room_memberships USING btree (room_id, user_id);
+
+
+--
+-- Name: idx_voice_sessions_orphaned; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_voice_sessions_orphaned ON public.voice_sessions USING btree (left_at) WHERE (left_at IS NULL);
+
+
--
-- Name: idx_web_hook_event_types_hooks_on_ids; Type: INDEX; Schema: public; Owner: -
--
@@ -22959,6 +23301,125 @@ CREATE UNIQUE INDEX index_users_on_username ON public.users USING btree (usernam
CREATE UNIQUE INDEX index_users_on_username_lower ON public.users USING btree (username_lower);
+--
+-- Name: index_voice_co_presences_on_user_id_1_and_date; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_co_presences_on_user_id_1_and_date ON public.voice_co_presences USING btree (user_id_1, date);
+
+
+--
+-- Name: index_voice_co_presences_on_user_id_2_and_date; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_co_presences_on_user_id_2_and_date ON public.voice_co_presences USING btree (user_id_2, date);
+
+
+--
+-- Name: index_voice_invites_on_room_id_and_user_id_and_invited_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_voice_invites_on_room_id_and_user_id_and_invited_by_id ON public.voice_invites USING btree (room_id, user_id, invited_by_id);
+
+
+--
+-- Name: index_voice_invites_on_user_id_and_room_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_invites_on_user_id_and_room_id ON public.voice_invites USING btree (user_id, room_id);
+
+
+--
+-- Name: index_voice_recordings_on_egress_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_voice_recordings_on_egress_id ON public.voice_recordings USING btree (egress_id);
+
+
+--
+-- Name: index_voice_recordings_on_room_id_and_started_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_recordings_on_room_id_and_started_at ON public.voice_recordings USING btree (room_id, started_at);
+
+
+--
+-- Name: index_voice_room_memberships_on_room_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_room_memberships_on_room_id ON public.voice_room_memberships USING btree (room_id);
+
+
+--
+-- Name: index_voice_room_memberships_on_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_room_memberships_on_user_id ON public.voice_room_memberships USING btree (user_id);
+
+
+--
+-- Name: index_voice_rooms_on_chat_channel_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_rooms_on_chat_channel_id ON public.voice_rooms USING btree (chat_channel_id);
+
+
+--
+-- Name: index_voice_rooms_on_creator_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_rooms_on_creator_id ON public.voice_rooms USING btree (creator_id);
+
+
+--
+-- Name: index_voice_rooms_on_ephemeral; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_rooms_on_ephemeral ON public.voice_rooms USING btree (id) WHERE ephemeral;
+
+
+--
+-- Name: index_voice_rooms_on_slug; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_voice_rooms_on_slug ON public.voice_rooms USING btree (slug);
+
+
+--
+-- Name: index_voice_sessions_on_room_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_sessions_on_room_id ON public.voice_sessions USING btree (room_id);
+
+
+--
+-- Name: index_voice_sessions_on_room_id_and_joined_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_sessions_on_room_id_and_joined_at ON public.voice_sessions USING btree (room_id, joined_at);
+
+
+--
+-- Name: index_voice_sessions_on_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_sessions_on_user_id ON public.voice_sessions USING btree (user_id);
+
+
+--
+-- Name: index_voice_sessions_on_user_id_and_joined_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_sessions_on_user_id_and_joined_at ON public.voice_sessions USING btree (user_id, joined_at);
+
+
+--
+-- Name: index_voice_sessions_on_user_id_and_room_id_and_joined_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_voice_sessions_on_user_id_and_room_id_and_joined_at ON public.voice_sessions USING btree (user_id, room_id, joined_at);
+
+
--
-- Name: index_watched_words_on_action_and_word; Type: INDEX; Schema: public; Owner: -
--
@@ -23320,6 +23781,14 @@ ALTER TABLE ONLY public.reviewable_notes
ADD CONSTRAINT fk_rails_9ea278a8aa FOREIGN KEY (user_id) REFERENCES public.users(id);
+--
+-- Name: voice_room_memberships fk_rails_a55e8c404b; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.voice_room_memberships
+ ADD CONSTRAINT fk_rails_a55e8c404b FOREIGN KEY (room_id) REFERENCES public.voice_rooms(id);
+
+
--
-- Name: poll_votes fk_rails_a6e6974b7e; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23423,10 +23892,13 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260831162602'),
('20260828145150'),
('20260827064809'),
('20260826124054'),
('20260826090055'),
+('20260824214608'),
+('20260824214603'),
('20260824091843'),
('20260824072257'),
('20260824051214'),
@@ -23450,6 +23922,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260814060100'),
('20260814060000'),
('20260813202233'),
+('20260813160047'),
('20260813071230'),
('20260813071223'),
('20260812094609'),
@@ -23459,10 +23932,14 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260807182856'),
('20260806074210'),
('20260806074204'),
+('20260803163818'),
+('20260803163214'),
+('20260803144425'),
('20260803015314'),
('20260731055703'),
('20260730183114'),
('20260729153343'),
+('20260728201053'),
('20260728162521'),
('20260728162516'),
('20260728150000'),
@@ -23485,6 +23962,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260721080420'),
('20260721043536'),
('20260721043534'),
+('20260717172530'),
('20260715202231'),
('20260715183411'),
('20260715134306'),
@@ -23494,6 +23972,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260715064155'),
('20260714152340'),
('20260713180615'),
+('20260709165411'),
('20260708095336'),
('20260708080308'),
('20260708051450'),
@@ -23504,10 +23983,12 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260706050124'),
('20260703164430'),
('20260703163425'),
+('20260703134812'),
('20260702102111'),
('20260701073045'),
('20260701013609'),
('20260701013606'),
+('20260630183841'),
('20260630034050'),
('20260629233141'),
('20260629210246'),
@@ -23528,6 +24009,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260616114637'),
('20260615084100'),
('20260615082047'),
+('20260612135211'),
('20260612092612'),
('20260612064730'),
('20260611102547'),
@@ -23626,8 +24108,12 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260306183220'),
('20260306000002'),
('20260306000001'),
+('20260305165401'),
+('20260305165400'),
+('20260305162426'),
('20260304063335'),
('20260223032030'),
+('20260220154336'),
('20260218104617'),
('20260218000000'),
('20260217064339'),
@@ -23945,6 +24431,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20241111022618'),
('20241110120303'),
('20241108154026'),
+('20241107000000'),
('20241105211601'),
('20241104132424'),
('20241104053309'),
diff --git a/plugins/voice/README.md b/plugins/voice/README.md
new file mode 100644
index 00000000000..4083ba195bd
--- /dev/null
+++ b/plugins/voice/README.md
@@ -0,0 +1,141 @@
+# Voice
+
+Voice is a Discourse plugin that adds Discord-style voice rooms powered by WebRTC. Rooms appear in the sidebar; users join or leave with a single click and talk peer-to-peer — no media goes through the Discourse server. Sites that need bigger calls can optionally route rooms through a self-hosted [LiveKit](https://livekit.io) media server.
+
+> **Status:** early alpha — test with small groups before opening to a full community.
+
+## Features
+
+- **Sidebar-first UX** — click a room to join/leave, see live participant avatars with speaking indicators, all without a route change.
+- **Mute, deafen, and per-user volume** — right-click any participant (or use the kebab menu) for audio controls. Room managers can kick participants.
+- **Voice settings with mic test** — input/output device pickers, a live input level meter, and an input sensitivity gate that stops transmitting below a chosen level. Preferences persist per device via `localStorage`.
+- **User room creation** — users in the allowed group see a "+" button to create rooms directly from the sidebar; room creators and managers can edit rooms in-app.
+- **Direct calls** — allowed users can call someone from their user card or profile.
+- **Themed audio cues** — synthesized tones for calls, connect/disconnect, user join/leave, and mute/deafen toggles follow each listener's existing **Chat notifications** sound choice. **None**, missing, or legacy choices use **Classic and clean**.
+- **Noise suppression** — optional DTLN-based background noise filtering via WebAssembly. See [Noise Suppression](#noise-suppression).
+- **Live subtitles** — optional viewer-side captions powered by NVIDIA Parakeet speech recognition running locally via WebGPU. See [Live Subtitles](#live-subtitles).
+- **Video and screen sharing** — optional, off by default. Each room gets a full page at `/voice/r/<slug>` with a tile grid; camera and screen share toggle without renegotiation, and senders only encode toward peers who are actually watching the page. Rooms can opt out individually. See [Video](#video).
+- **Video settings with background blur** — a per-room video settings modal with a live preview, camera device picker, and MediaPipe-powered background blur with an adjustable strength slider. See [Background Blur](#background-blur).
+- **Pure browser WebRTC** — signaling through Discourse + MessageBus; media stays peer-to-peer, no SFU/MCU required.
+- **Optional LiveKit SFU** — point the plugin at a self-hosted LiveKit server and route all rooms (or individually opted-in rooms) through it for enterprise-scale calls; everything else keeps working identically. See [LiveKit](#livekit-media-server-sfu).
+
+## Installation
+
+Voice is a core plugin bundled with Discourse — no installation needed. Enable it via **Admin > Settings > Plugins > voice enabled**.
+
+The plugin seeds a default "Watercooler" room on first enable.
+
+## Configuration
+
+| Setting | Description |
+| ------------------------------------ | ------------------------------------------------------------------------------------ |
+| `voice_enabled` | Master switch. |
+| `voice_allowed_groups` | Groups that can access voice rooms (default: everyone). |
+| `voice_create_room_allowed_groups` | Groups that can create new rooms (default: admins, moderators, TL2). |
+| `voice_max_rooms_per_user` | Max rooms per creator (default 5). |
+| `voice_participant_ttl_seconds` | Redis presence TTL in seconds (default 30). Client heartbeat refreshes every 10s. |
+| `voice_video_enabled` | Allow camera video and screen sharing (default off). Rooms can opt out individually. |
+| `voice_video_max_publishers` | Max simultaneous video/screen publishers per room (default 8). |
+| `voice_video_background_blur_enabled` | Allow users to blur their camera background (default on; requires video). |
+| `voice_stun_servers` | STUN server addresses (pipe-separated). |
+| `voice_turn_servers` | TURN server addresses for NAT traversal. |
+| `voice_livekit_url` | WebSocket URL of a self-hosted LiveKit server (empty = mesh only). |
+| `voice_livekit_api_key` / `_api_secret` | LiveKit API credentials used to sign short-lived room tokens. |
+| `voice_livekit_room_policy` | Which rooms use LiveKit: `disabled` (default), `per_room`, or `all_rooms`. |
+
+## Video
+
+When `voice_video_enabled` is on (and the room's own video toggle is too), the room view at `/voice/r/<slug>` shows a video grid alongside the usual controls. Audio joins stay sidebar-first and unchanged; video lives on the page.
+
+- Still pure mesh: a video m-line is pre-negotiated on every peer connection, so toggling the camera or a screen share is a `replaceTrack` with no renegotiation.
+- Senders attach video only toward participants currently on the room page (`watching_video` presence flag) — every skipped peer saves a full encoder session.
+- Encoding quality scales down with watcher count (720p ≤3 watchers, 480p ≤6, 360p beyond) and is capped by `voice_video_max_publishers`.
+- Camera and screen share are mutually exclusive per user. Stage rooms do not support video yet.
+- On LiveKit-routed rooms the mesh details above are handled by the SFU instead: each track is published once with simulcast, and per-watcher gating happens on the subscriber side. The UI, the `watching_video` flag, and the publisher cap behave identically.
+
+See `docs/roadmap/video-screenshare.md` for the full design.
+
+### Screen sharing troubleshooting
+
+Screen sharing has more environmental dependencies than the camera, and failures surface as a generic `NotAllowedError` in the browser console:
+
+- **Linux on Wayland**: capture goes through `xdg-desktop-portal` + PipeWire. If the picker never appears and the error is instant, check `systemctl --user is-active graphical-session.target xdg-desktop-portal` — a compositor session that isn't wired into systemd (common on minimal window manager setups) leaves the portal unable to start. The camera is unaffected, which makes this easy to misread as an application bug.
+- **macOS Firefox**: needs Screen Recording permission in System Settings, and only picks it up after a full browser restart.
+- **Insecure dev origins**: `getDisplayMedia` hard-requires a secure context. Firefox's `about:config` overrides that unlock `getUserMedia` on plain-http dev hosts do **not** extend to screen capture — use `https://` or a `localhost` origin.
+
+## Background Blur
+
+Camera publishers can blur their background from the video settings modal (cog menu on the room page). Person segmentation runs entirely on the publisher's device using [MediaPipe](https://github.com/google-ai-edge/mediapipe) selfie segmentation (Apache-2.0), compiled to WebAssembly — no media leaves the browser unprocessed, and viewers pay no extra cost.
+
+```
+Camera → hidden <video> → MediaPipe ImageSegmenter (person mask)
+ → canvas composite (blurred frame + sharp person cutout)
+ → canvas.captureStream() → WebRTC peers
+```
+
+The blur strength slider adjusts the composite live; the toggle swaps tracks on all peers via `replaceTrack` without renegotiation. Preferences persist per device via `localStorage`.
+
+The MediaPipe runtime, wasm binaries, and the `selfie_segmenter.tflite` model (all Apache-2.0, © Google) are vendored in the [discourse_voice_assets](https://github.com/discourse/discourse_voice_assets) gem (served here from `public/javascripts/<gem version>/mediapipe/`). Its `scripts/fetch-mediapipe-assets.sh` pins the `@mediapipe/tasks-vision` npm version and the model version, and verifies the model's SHA-256 checksum.
+
+## LiveKit media server (SFU)
+
+By default media is pure peer-to-peer, which is ideal for small rooms but scales upstream bandwidth with room size. Deploy your own [LiveKit](https://livekit.io) server and set `voice_livekit_url`, `voice_livekit_api_key`, `voice_livekit_api_secret`, and `voice_livekit_room_policy` to route rooms through it — each participant then publishes every track exactly once, whatever the room size.
+
+- The server picks each call's transport when its first participant joins and pins it for the whole call; a room is never split across transports, and setting changes only affect the next call.
+- Presence, sessions, stats, mute/deafen/PTT, noise suppression, and background blur are transport-independent — they behave identically on both paths.
+- The pinned `livekit-client` SDK is vendored in the discourse_voice_assets gem (served from `public/javascripts/<gem version>/livekit/`; rebuild with the gem's `scripts/build-livekit-bundle.sh`) and is only ever loaded in the browser for LiveKit-routed rooms — mesh installs ship zero LiveKit bytes.
+
+See [docs/livekit.md](docs/livekit.md) for the full deployment runbook (provisioning, firewall/CSP notes, verification, emergency levers) and the manual browser checklist.
+
+## Noise Suppression
+
+Selectable AI noise-suppression engines running as WebAssembly AudioWorklets. Users pick a mode (None / Standard / an AI engine) from the voice settings modal or the mic button's dropdown; a badge on the mic button shows while an AI engine is confirmed active. The preference persists per device via `localStorage`. In AI modes the browser's native `noiseSuppression` constraint is turned off so filters never stack.
+
+| Engine | Source | Assets | Profile |
+|---|---|---|---|
+| RNNoise | [xiph/rnnoise](https://github.com/xiph/rnnoise) @ v0.1.1 (classic model) | ~130KB wasm | lightweight, lowest CPU |
+| DTLN | [dtln-rs](https://github.com/DataDog/dtln-rs) | ~6MB wasm | balanced |
+| DeepFilterNet3 | [DeepFilterNet](https://github.com/Rikorose/DeepFilterNet) via tract | ~9.5MB wasm + 8MB model | best quality, highest CPU |
+
+```
+Microphone → AudioContext → AudioWorkletNode (engine) → MediaStreamDestination → WebRTC peers
+```
+
+All engines share one worklet runtime (`src/ns-worklet/runtime.js` in the discourse_voice_assets gem) and protocol: the main thread fetches the engine's assets and posts the bytes to the worklet, which instantiates them and answers a `ready` handshake once a warm-up denoise succeeds — only then is the suppressed track published, so an enabled mode always means the filter is really running.
+
+Pre-built assets ship in the [discourse_voice_assets](https://github.com/discourse/discourse_voice_assets) gem under stable filenames, served from a gem-version-stamped path (`public/javascripts/<gem version>/<engine>/`) that the client learns from the site serializer — the versioned URL busts the immutable `/plugins/` caches, so a gem bump needs no plugin change. The gem's build scripts clone each upstream at a pinned commit (applying patches where needed); `spec/integrity/voice_assets_spec.rb` pins the filenames the loaders reference against the gem's vendor tree.
+
+## Live Subtitles
+
+Opt-in, viewer-side captions: the user who enables subtitles transcribes the remote audio they already receive with [parakeet.js](https://github.com/ysdede/parakeet.js) (NVIDIA Parakeet TDT 0.6b v3, multilingual) — no audio leaves the browser and nothing is required from the other participants, on either transport.
+
+```
+remote stream → Silero VAD (per participant) → utterance PCM → Worker (Parakeet, WebGPU) → caption overlay
+```
+
+Each remote mic stream gets a [Silero VAD](https://github.com/ricky0123/vad) finding utterance boundaries; while a speaker keeps talking, the utterance-so-far is re-transcribed every ~1.5s as a provisional line that updates in place, and the speech-end pass finalizes it. Utterances are transcribed by one shared model in a Web Worker (fp32 encoder on WebGPU, int8 decoder on single-threaded WASM — fp16 encoders silently produce empty transcriptions on some GPU stacks, and multithreaded WASM would require COOP/COEP headers). Requires WebGPU; gated by the `voice_subtitles_enabled` site setting.
+
+The runtime bundles (worker, VAD, onnxruntime, ~41 MB) are pinned and shipped in the discourse_voice_assets gem (served here from `public/javascripts/<gem version>/stt/`, built by the gem's `scripts/build-stt-assets.sh`). The ~2.5 GB model weights are **not** committed: they download on first use from Discourse's HuggingFace repository (kept in a durable Cache API store), or from a self-hosted mirror configured via `voice_stt_model_base_url` — see [docs/subtitles-model-mirror.md](docs/subtitles-model-mirror.md) for what to mirror and how.
+
+An end-to-end smoke check (`scripts/smoke-stt-worker.mjs`, real model on WebGPU in headless Chromium) lives in the gem alongside the build script.
+
+## Development
+
+```bash
+bin/rspec plugins/voice/spec # Ruby specs
+bin/lint plugins/voice # JS/SCSS/Ruby lint
+```
+
+Key entry points:
+
+- `app/controllers/voice/rooms_controller.rb` — room CRUD, signaling relay, participant state (mute/deafen/video/watching)
+- `app/controllers/voice/page_controller.rb` — serves the full-page room view at `/voice/r/:slug`
+- `lib/voice/guardian_extension.rb` — authorization (group-based access and room creation permissions)
+- `assets/javascripts/discourse/app/services/voice-webrtc.js` — WebRTC orchestration, audio controls, video/screen-share publishing, sound effects
+- `assets/javascripts/discourse/initializers/voice-sidebar.js` — sidebar section, click/context-menu handlers
+- `assets/javascripts/discourse/components/voice/room-page.gjs` — room page: tile grid, call controls, watching lifecycle
+
+## Known Limitations
+
+- The default peer-to-peer topology means large rooms may hit browser limits; rooms that outgrow it need a [LiveKit server](docs/livekit.md).
+- No call recording or moderation tools beyond kick and the admin "End call" action.
diff --git a/plugins/voice/admin/assets/javascripts/admin/adapters/voice-room.js b/plugins/voice/admin/assets/javascripts/admin/adapters/voice-room.js
new file mode 100644
index 00000000000..fc913df4379
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/adapters/voice-room.js
@@ -0,0 +1,19 @@
+import RestAdapter from "discourse/adapters/rest";
+
+export default class VoiceRoomAdapter extends RestAdapter {
+ jsonMode = true;
+
+ basePath() {
+ return "/admin/plugins/voice/";
+ }
+
+ pathFor(store, type, id) {
+ return id === undefined
+ ? "/admin/plugins/voice/rooms.json"
+ : `/admin/plugins/voice/rooms/${id}.json`;
+ }
+
+ apiNameFor() {
+ return "room";
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/admin/components/voice-dashboard.gjs b/plugins/voice/admin/assets/javascripts/admin/components/voice-dashboard.gjs
new file mode 100644
index 00000000000..eee1613f0fc
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/components/voice-dashboard.gjs
@@ -0,0 +1,154 @@
+import Component from "@glimmer/component";
+import DashboardPeriodSelector from "discourse/admin/components/dashboard-period-selector";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import { i18n } from "discourse-i18n";
+import VoiceLivekitStatus from "discourse/plugins/voice/admin/components/voice-livekit-status";
+
+function formatDuration(seconds) {
+ if (!seconds || seconds <= 0) {
+ return "0m";
+ }
+
+ const h = Math.floor(seconds / 3600);
+ const m = Math.floor((seconds % 3600) / 60);
+
+ if (h > 0) {
+ return `${h}h ${m}m`;
+ }
+ return `${m}m`;
+}
+
+export default class VoiceDashboard extends Component {
+ get overview() {
+ return this.args.model?.overview;
+ }
+
+ get rooms() {
+ return this.args.model?.rooms || [];
+ }
+
+ get users() {
+ return this.args.model?.users || [];
+ }
+
+ get hasData() {
+ return this.overview?.total_sessions > 0;
+ }
+
+ <template>
+ <section class="voice-dashboard">
+ <div class="voice-dashboard__header">
+ <h2>{{i18n "voice.admin.dashboard.overview"}}</h2>
+ <DashboardPeriodSelector
+ @period={{@controller.period}}
+ @setPeriod={{@controller.setPeriod}}
+ @startDate={{@controller.startDate}}
+ @endDate={{@controller.endDate}}
+ @setCustomDateRange={{@controller.setCustomDateRange}}
+ />
+ </div>
+
+ {{#if this.hasData}}
+ <div class="voice-dashboard__stats-cards">
+ <div class="voice-dashboard__card">
+ <span
+ class="voice-dashboard__card-value"
+ >{{this.overview.total_sessions}}</span>
+ <span class="voice-dashboard__card-label">{{i18n
+ "voice.admin.dashboard.total_sessions"
+ }}</span>
+ </div>
+ <div class="voice-dashboard__card">
+ <span
+ class="voice-dashboard__card-value"
+ >{{this.overview.unique_users}}</span>
+ <span class="voice-dashboard__card-label">{{i18n
+ "voice.admin.dashboard.unique_users"
+ }}</span>
+ </div>
+ <div class="voice-dashboard__card">
+ <span class="voice-dashboard__card-value">{{formatDuration
+ this.overview.avg_duration
+ }}</span>
+ <span class="voice-dashboard__card-label">{{i18n
+ "voice.admin.dashboard.avg_duration"
+ }}</span>
+ </div>
+ </div>
+
+ {{#if this.rooms.length}}
+ <h3>{{i18n "voice.admin.dashboard.top_rooms"}}</h3>
+ <table class="d-admin-table voice-dashboard__rooms-table">
+ <thead>
+ <tr>
+ <th>{{i18n "voice.admin.dashboard.room_name"}}</th>
+ <th>{{i18n "voice.admin.dashboard.unique_users"}}</th>
+ <th>{{i18n "voice.admin.dashboard.total_time"}}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.rooms as |room|}}
+ <tr class="d-admin-row__content">
+ <td class="d-admin-row__overview">
+ {{#if room.room_name}}
+ {{room.room_name}}
+ {{else}}
+ {{i18n "voice.admin.dashboard.deleted_room"}}
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail">{{room.unique_users}}</td>
+ <td class="d-admin-row__detail">{{formatDuration
+ room.total_seconds
+ }}</td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{/if}}
+
+ {{#if this.users.length}}
+ <h3>{{i18n "voice.admin.dashboard.top_users"}}</h3>
+ <table class="d-admin-table voice-dashboard__users-table">
+ <thead>
+ <tr>
+ <th>{{i18n "voice.admin.dashboard.user"}}</th>
+ <th>{{i18n "voice.admin.dashboard.sessions"}}</th>
+ <th>{{i18n "voice.admin.dashboard.total_time"}}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.users as |u|}}
+ <tr class="d-admin-row__content">
+ <td class="d-admin-row__overview">
+ {{#if u.username}}
+ <a
+ href="/admin/users/{{u.user_id}}/{{u.username}}"
+ data-user-card={{u.username}}
+ class="voice-dashboard__user-cell"
+ >
+ {{dAvatar u imageSize="small"}}
+ <span>{{u.username}}</span>
+ </a>
+ {{else}}
+ {{i18n "voice.admin.dashboard.deleted_user"}}
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail">{{u.session_count}}</td>
+ <td class="d-admin-row__detail">{{formatDuration
+ u.total_seconds
+ }}</td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{/if}}
+ {{else}}
+ <p class="voice-dashboard__empty">{{i18n
+ "voice.admin.dashboard.no_data"
+ }}</p>
+ {{/if}}
+
+ <VoiceLivekitStatus />
+ </section>
+ </template>
+}
diff --git a/plugins/voice/admin/assets/javascripts/admin/components/voice-livekit-status.gjs b/plugins/voice/admin/assets/javascripts/admin/components/voice-livekit-status.gjs
new file mode 100644
index 00000000000..da6ccb41cd6
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/components/voice-livekit-status.gjs
@@ -0,0 +1,336 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const STATE_ICONS = {
+ ok: "circle-check",
+ warning: "triangle-exclamation",
+ error: "circle-xmark",
+};
+
+const PREFIX = "voice.admin.dashboard.livekit";
+
+export default class VoiceLivekitStatus extends Component {
+ @tracked status;
+ @tracked loading = true;
+ @tracked loadFailed = false;
+
+ constructor() {
+ super(...arguments);
+ this.load();
+ }
+
+ @action
+ async load({ refreshProbe = false } = {}) {
+ this.loading = true;
+ this.loadFailed = false;
+
+ try {
+ this.status = await ajax(
+ `/admin/plugins/voice/livekit/${refreshProbe ? "probe" : "status"}.json`,
+ refreshProbe ? { type: "POST" } : {}
+ );
+ } catch {
+ this.loadFailed = true;
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async refresh() {
+ await this.load({ refreshProbe: true });
+ }
+
+ // Pure-mesh installs (no LiveKit setting touched) never see the card.
+ get visible() {
+ if (this.loading && !this.status) {
+ return false;
+ }
+ if (this.loadFailed) {
+ return true;
+ }
+
+ const settings = this.status?.settings;
+ if (!settings) {
+ return false;
+ }
+
+ return (
+ settings.url_present ||
+ settings.api_key_present ||
+ settings.api_secret_present ||
+ settings.policy !== "disabled"
+ );
+ }
+
+ get checks() {
+ const status = this.status;
+ if (!status) {
+ return [];
+ }
+
+ const checks = [];
+
+ if (status.configured) {
+ checks.push({
+ state: "ok",
+ label: i18n(`${PREFIX}.config_ok`, { policy: status.settings.policy }),
+ });
+ } else {
+ const missing = [];
+ if (!status.settings.url_present) {
+ missing.push("voice_livekit_url");
+ }
+ if (!status.settings.api_key_present) {
+ missing.push("voice_livekit_api_key");
+ }
+ if (!status.settings.api_secret_present) {
+ missing.push("voice_livekit_api_secret");
+ }
+ checks.push({
+ state: "error",
+ label: i18n(`${PREFIX}.config_missing`, {
+ settings: missing.join(", "),
+ }),
+ });
+ }
+
+ if (status.token_check) {
+ checks.push(
+ status.token_check.ok
+ ? { state: "ok", label: i18n(`${PREFIX}.token_ok`) }
+ : {
+ state: "error",
+ label: i18n(`${PREFIX}.token_error`, {
+ error: status.token_check.error,
+ }),
+ }
+ );
+ }
+
+ if (status.server_check) {
+ checks.push(
+ status.server_check.ok
+ ? {
+ state: "ok",
+ label: i18n(`${PREFIX}.server_ok`, {
+ latency: status.server_check.latency_ms,
+ count: status.server_check.room_count,
+ }),
+ }
+ : {
+ state: "error",
+ label: i18n(`${PREFIX}.server_error`, {
+ error: status.server_check.error,
+ }),
+ }
+ );
+ }
+
+ if (status.last_probe) {
+ checks.push({
+ state: status.last_probe.ok ? "ok" : "error",
+ label: i18n(
+ `${PREFIX}.${status.last_probe.ok ? "probe_ok" : "probe_failed"}`
+ ),
+ at: status.last_probe.checked_at,
+ });
+ } else if (status.configured) {
+ checks.push({ state: "warning", label: i18n(`${PREFIX}.probe_never`) });
+ }
+
+ checks.push(
+ status.last_webhook_at
+ ? {
+ state: "ok",
+ label: i18n(`${PREFIX}.webhook_received`),
+ at: status.last_webhook_at,
+ }
+ : { state: "warning", label: i18n(`${PREFIX}.webhook_never`) }
+ );
+
+ return checks.map((check) => ({
+ ...check,
+ icon: STATE_ICONS[check.state],
+ }));
+ }
+
+ // Rendered only until the first webhook arrives. The api_key line is a
+ // placeholder on purpose: status payloads never echo setting values.
+ get showWebhookConfig() {
+ return this.status?.configured && !this.status?.last_webhook_at;
+ }
+
+ get webhookConfigSnippet() {
+ return [
+ "webhook:",
+ " urls:",
+ ` - ${this.status.webhook_url}`,
+ " api_key: your_api_key # the value of voice_livekit_api_key",
+ ].join("\n");
+ }
+
+ get roomRows() {
+ return (this.status?.rooms || []).map((room) => {
+ const probed = room.livekit_user_ids !== undefined || !!room.error;
+
+ return {
+ name: room.name,
+ presenceCount: room.presence_user_ids.length,
+ livekitCount: room.livekit_user_ids?.length,
+ probed,
+ error: room.error,
+ inSync:
+ probed &&
+ !room.error &&
+ !room.missing_on_livekit?.length &&
+ !room.missing_in_presence?.length,
+ missingOnLivekit: this.#usernames(room.missing_on_livekit),
+ missingInPresence: this.#usernames(room.missing_in_presence),
+ };
+ });
+ }
+
+ #usernames(userIds) {
+ if (!userIds?.length) {
+ return null;
+ }
+ return userIds
+ .map((id) => this.status.usernames?.[id] || `#${id}`)
+ .join(", ");
+ }
+
+ <template>
+ {{#if this.visible}}
+ <div class="voice-livekit-status">
+ <div class="voice-livekit-status__header">
+ <h3>{{i18n "voice.admin.dashboard.livekit.title"}}</h3>
+ <DButton
+ class="btn-default btn-small voice-livekit-status__refresh"
+ @icon="arrows-rotate"
+ @label="voice.admin.dashboard.livekit.refresh"
+ @action={{this.refresh}}
+ @disabled={{this.loading}}
+ />
+ </div>
+
+ <DConditionalLoadingSpinner @condition={{this.loading}}>
+ {{#if this.loadFailed}}
+ <p class="voice-livekit-status__load-failed">{{i18n
+ "voice.admin.dashboard.livekit.load_failed"
+ }}</p>
+ {{else}}
+ <ul class="voice-livekit-status__checks">
+ {{#each this.checks as |check|}}
+ <li class="voice-livekit-status__check --{{check.state}}">
+ {{dIcon check.icon}}
+ <span>
+ {{check.label}}
+ {{#if check.at}}{{dFormatDate
+ check.at
+ leaveAgo="true"
+ }}{{/if}}
+ </span>
+ </li>
+ {{/each}}
+ </ul>
+
+ {{#if this.showWebhookConfig}}
+ <div class="voice-livekit-status__webhook-config">
+ <p>{{i18n
+ "voice.admin.dashboard.livekit.webhook_config_hint"
+ }}</p>
+ <pre><code>{{this.webhookConfigSnippet}}</code></pre>
+ </div>
+ {{/if}}
+
+ {{#if this.status.configured}}
+ <h4>{{i18n "voice.admin.dashboard.livekit.rooms_title"}}</h4>
+ {{#if this.roomRows.length}}
+ <table class="d-admin-table voice-livekit-status__rooms">
+ <thead>
+ <tr>
+ <th>{{i18n "voice.admin.dashboard.livekit.room"}}</th>
+ <th>{{i18n
+ "voice.admin.dashboard.livekit.discourse_participants"
+ }}</th>
+ <th>{{i18n
+ "voice.admin.dashboard.livekit.livekit_participants"
+ }}</th>
+ <th>{{i18n
+ "voice.admin.dashboard.livekit.room_status"
+ }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.roomRows as |row|}}
+ <tr class="d-admin-row__content">
+ <td class="d-admin-row__overview">{{row.name}}</td>
+ <td class="d-admin-row__detail">
+ {{row.presenceCount}}
+ </td>
+ <td class="d-admin-row__detail">
+ {{if row.probed row.livekitCount "—"}}
+ </td>
+ <td
+ class="d-admin-row__detail voice-livekit-status__room-diff"
+ >
+ {{#if row.error}}
+ <span class="--error">
+ {{dIcon "circle-xmark"}}
+ {{i18n
+ "voice.admin.dashboard.livekit.room_error"
+ error=row.error
+ }}
+ </span>
+ {{else if row.inSync}}
+ <span class="--ok">
+ {{dIcon "circle-check"}}
+ {{i18n "voice.admin.dashboard.livekit.in_sync"}}
+ </span>
+ {{else if row.probed}}
+ {{#if row.missingOnLivekit}}
+ <div class="--warning">
+ {{dIcon "triangle-exclamation"}}
+ {{i18n
+ "voice.admin.dashboard.livekit.missing_on_livekit"
+ users=row.missingOnLivekit
+ }}
+ </div>
+ {{/if}}
+ {{#if row.missingInPresence}}
+ <div class="--warning">
+ {{dIcon "triangle-exclamation"}}
+ {{i18n
+ "voice.admin.dashboard.livekit.missing_in_presence"
+ users=row.missingInPresence
+ }}
+ </div>
+ {{/if}}
+ {{else}}
+ —
+ {{/if}}
+ </td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{else}}
+ <p class="voice-livekit-status__no-rooms">{{i18n
+ "voice.admin.dashboard.livekit.no_rooms"
+ }}</p>
+ {{/if}}
+ {{/if}}
+ {{/if}}
+ </DConditionalLoadingSpinner>
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/admin/assets/javascripts/admin/components/voice-recording-list.gjs b/plugins/voice/admin/assets/javascripts/admin/components/voice-recording-list.gjs
new file mode 100644
index 00000000000..f43d225ffe8
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/components/voice-recording-list.gjs
@@ -0,0 +1,164 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DPageSubheader from "discourse/ui-kit/d-page-subheader";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import { i18n } from "discourse-i18n";
+
+const PREFIX = "voice.admin.recordings";
+
+function formatDuration(durationMs) {
+ if (!durationMs) {
+ return "-";
+ }
+
+ const totalSeconds = Math.round(durationMs / 1000);
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ const pad = (value) => String(value).padStart(2, "0");
+
+ return hours > 0
+ ? `${hours}:${pad(minutes)}:${pad(seconds)}`
+ : `${minutes}:${pad(seconds)}`;
+}
+
+export default class VoiceRecordingList extends Component {
+ @tracked extraRecordings = [];
+ @tracked hasMoreOverride = null;
+ @tracked loadingMore = false;
+
+ statusLabel = (status) => i18n(`${PREFIX}.status_${status}`);
+
+ formatDuration = (durationMs) => formatDuration(durationMs);
+
+ isDownloadUrl = (location) => /^https?:\/\//.test(location);
+
+ filePath = (recording) =>
+ recording.location || recording.filename || recording.filepath;
+
+ get recordings() {
+ return [...this.args.model.recordings, ...this.extraRecordings];
+ }
+
+ get hasMore() {
+ return this.hasMoreOverride ?? this.args.model.has_more;
+ }
+
+ @action
+ async loadMore() {
+ this.loadingMore = true;
+ try {
+ const payload = await ajax(
+ `/admin/plugins/voice/recordings.json?offset=${this.recordings.length}`
+ );
+ this.extraRecordings = [...this.extraRecordings, ...payload.recordings];
+ this.hasMoreOverride = payload.has_more;
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ <template>
+ <section class="voice-recordings">
+ <DPageSubheader
+ @titleLabel={{i18n "voice.admin.recordings_title"}}
+ @descriptionLabel={{i18n "voice.admin.recordings.description"}}
+ />
+
+ {{#if this.recordings.length}}
+ <table class="d-admin-table voice-recordings__table">
+ <thead>
+ <tr>
+ <th>{{i18n "voice.admin.recordings.room"}}</th>
+ <th>{{i18n "voice.admin.recordings.requested_by"}}</th>
+ <th>{{i18n "voice.admin.recordings.status"}}</th>
+ <th>{{i18n "voice.admin.recordings.started_at"}}</th>
+ <th>{{i18n "voice.admin.recordings.duration"}}</th>
+ <th>{{i18n "voice.admin.recordings.file"}}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.recordings as |recording|}}
+ <tr class="d-admin-row__content">
+ <td class="d-admin-row__overview voice-recordings__room">
+ {{recording.room_name}}
+ </td>
+ <td class="d-admin-row__detail voice-recordings__requester">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.recordings.requested_by"}}
+ </div>
+ {{#if recording.started_by}}
+ {{dAvatar recording.started_by imageSize="tiny"}}
+ {{recording.started_by.username}}
+ {{else}}
+ -
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail voice-recordings__status">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.recordings.status"}}
+ </div>
+ <span
+ class="voice-recordings__status-badge --{{recording.status}}"
+ >
+ {{this.statusLabel recording.status}}
+ </span>
+ </td>
+ <td class="d-admin-row__detail voice-recordings__started-at">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.recordings.started_at"}}
+ </div>
+ {{dFormatDate recording.started_at leaveAgo="true"}}
+ </td>
+ <td class="d-admin-row__detail voice-recordings__duration">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.recordings.duration"}}
+ </div>
+ {{this.formatDuration recording.duration_ms}}
+ </td>
+ <td class="d-admin-row__detail voice-recordings__file">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.recordings.file"}}
+ </div>
+ {{#if (this.isDownloadUrl recording.location)}}
+ <a
+ href={{recording.location}}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ {{i18n "voice.admin.recordings.download"}}
+ </a>
+ {{else}}
+ <code>{{this.filePath recording}}</code>
+ {{/if}}
+ </td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+
+ <DConditionalLoadingSpinner @condition={{this.loadingMore}}>
+ {{#if this.hasMore}}
+ <DButton
+ @action={{this.loadMore}}
+ @label="voice.admin.recordings.load_more"
+ class="btn-default voice-recordings__load-more"
+ />
+ {{/if}}
+ </DConditionalLoadingSpinner>
+ {{else}}
+ <p class="voice-recordings__empty">
+ {{i18n "voice.admin.recordings.empty"}}
+ </p>
+ {{/if}}
+ </section>
+ </template>
+}
diff --git a/plugins/voice/admin/assets/javascripts/admin/components/voice-room-list.gjs b/plugins/voice/admin/assets/javascripts/admin/components/voice-room-list.gjs
new file mode 100644
index 00000000000..a38393b6867
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/components/voice-room-list.gjs
@@ -0,0 +1,177 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { escapeExpression } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+import DPageSubheader from "discourse/ui-kit/d-page-subheader";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceRoomList extends Component {
+ @service dialog;
+
+ @action
+ async endCall(room) {
+ await this.dialog.yesNoConfirm({
+ message: i18n("voice.admin.end_call.confirm", {
+ name: escapeExpression(room.name),
+ }),
+ didConfirm: async () => {
+ try {
+ await ajax(`/admin/plugins/voice/rooms/${room.id}/end_call`, {
+ type: "POST",
+ });
+ room.set("live_participant_count", 0);
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ @action
+ async destroyRoom(room) {
+ room.set("isDeleting", true);
+ try {
+ await this.dialog.deleteConfirm({
+ message: i18n("voice.admin.destroy_room.confirm", {
+ name: escapeExpression(room.name),
+ }),
+ didConfirm: async () => {
+ try {
+ await room.destroyRecord();
+ this.args.onDestroy?.(room);
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ } finally {
+ room?.set("isDeleting", false);
+ }
+ }
+
+ <template>
+ <section class="voice-rooms-table">
+ <DPageSubheader @titleLabel={{i18n "voice.admin.rooms_title"}}>
+ <:actions as |actions|>
+ <actions.Primary
+ @label="voice.admin.create_room"
+ @route="adminPlugins.show.voice-rooms.new"
+ @icon="plus"
+ class="voice-admin__create-btn"
+ />
+ </:actions>
+ </DPageSubheader>
+
+ {{#if @rooms.length}}
+ <table class="d-admin-table voice-rooms">
+ <thead>
+ <tr>
+ <th>{{i18n "voice.admin.room.name"}}</th>
+ <th>{{i18n "voice.admin.room.public"}}</th>
+ <th>{{i18n "voice.admin.room.max_participants"}}</th>
+ <th>{{i18n "voice.admin.room.member_count"}}</th>
+ <th>{{i18n "voice.admin.room.creator"}}</th>
+ <th>{{i18n "voice.admin.room.created_at"}}</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each @rooms as |room|}}
+ <tr class="d-admin-row__content">
+ <td class="d-admin-row__overview voice-rooms__name">
+ {{room.name}}
+ </td>
+ <td class="d-admin-row__detail voice-rooms__public">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.room.public"}}
+ </div>
+ {{#if room.public}}
+ {{i18n "yes_value"}}
+ {{else}}
+ {{i18n "no_value"}}
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail voice-rooms__max-participants">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.room.max_participants"}}
+ </div>
+ {{#if room.max_participants}}
+ {{room.max_participants}}
+ {{else}}
+ -
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail voice-rooms__member-count">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.room.member_count"}}
+ </div>
+ {{room.member_count}}
+ </td>
+ <td class="d-admin-row__detail voice-rooms__creator">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.room.creator"}}
+ </div>
+ {{#if room.creator}}
+ <a
+ href={{room.creator.userPath}}
+ data-user-card={{room.creator.username}}
+ >
+ {{dAvatar room.creator imageSize="small"}}
+ </a>
+ {{/if}}
+ </td>
+ <td class="d-admin-row__detail voice-rooms__created-at">
+ <div class="d-admin-row__mobile-label">
+ {{i18n "voice.admin.room.created_at"}}
+ </div>
+ {{dFormatDate room.created_at leaveAgo="true"}}
+ </td>
+ <td class="d-admin-row__controls voice-rooms__controls">
+ {{#if room.live_participant_count}}
+ <DButton
+ @icon="phone-slash"
+ @title="voice.admin.end_call.title"
+ {{on "click" (fn this.endCall room)}}
+ class="btn-small btn-danger voice-rooms__end-call"
+ />
+ {{/if}}
+
+ <LinkTo
+ @route="adminPlugins.show.voice-rooms.edit"
+ @model={{room.id}}
+ class="btn btn-default btn-text btn-small"
+ >
+ {{i18n "voice.admin.edit"}}
+ </LinkTo>
+
+ <DButton
+ @icon="trash-can"
+ @disabled={{room.isDeleting}}
+ {{on "click" (fn this.destroyRoom room)}}
+ class="btn-small btn-danger voice-rooms__delete"
+ />
+ </td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ {{else}}
+ <AdminConfigAreaEmptyList
+ @ctaLabel="voice.admin.create_room"
+ @ctaRoute="adminPlugins.show.voice-rooms.new"
+ @ctaClass="voice-admin__create-btn"
+ @emptyLabel="voice.admin.no_rooms_yet"
+ />
+ {{/if}}
+ </section>
+ </template>
+}
diff --git a/plugins/voice/admin/assets/javascripts/admin/models/voice-room.js b/plugins/voice/admin/assets/javascripts/admin/models/voice-room.js
new file mode 100644
index 00000000000..34840a36e3e
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/admin/models/voice-room.js
@@ -0,0 +1,37 @@
+import RestModel from "discourse/models/rest";
+
+const SAVED_PROPERTIES = [
+ "name",
+ "description",
+ "public",
+ "max_participants",
+ "video_enabled",
+ "livekit_enabled",
+ "chat_channel_id",
+ "chat_idle_minutes",
+];
+
+// A cleared FormKit <field.Control @type="select"> reports `undefined`
+// (its "None" option), and this model's adapter JSON-encodes properties for
+// the request body — JSON.stringify drops `undefined`-valued keys entirely,
+// so clearing a nullable field like chat_channel_id would silently never
+// reach the server. Send an explicit `null` instead.
+function withNullsForUndefined(properties) {
+ const normalized = { ...properties };
+ for (const key of Object.keys(normalized)) {
+ if (normalized[key] === undefined) {
+ normalized[key] = null;
+ }
+ }
+ return normalized;
+}
+
+export default class VoiceRoom extends RestModel {
+ createProperties() {
+ return withNullsForUndefined(this.getProperties(SAVED_PROPERTIES));
+ }
+
+ updateProperties() {
+ return withNullsForUndefined(this.getProperties(SAVED_PROPERTIES));
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-dashboard.js b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-dashboard.js
new file mode 100644
index 00000000000..26aa157f7c0
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-dashboard.js
@@ -0,0 +1,54 @@
+import { tracked } from "@glimmer/tracking";
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+
+export default class VoiceDashboardController extends Controller {
+ @tracked period = "weekly";
+ @tracked start_date = null;
+ @tracked end_date = null;
+
+ queryParams = ["period", "start_date", "end_date"];
+
+ get startDate() {
+ if (this.start_date) {
+ return moment.utc(this.start_date).locale("en").startOf("day");
+ }
+ return this.#calculateStartDate();
+ }
+
+ get endDate() {
+ if (this.end_date) {
+ return moment.utc(this.end_date).locale("en").endOf("day");
+ }
+ return moment().locale("en").utc().endOf("day");
+ }
+
+ #calculateStartDate() {
+ const fullDay = moment().locale("en").utc().endOf("day");
+
+ switch (this.period) {
+ case "daily":
+ return fullDay.startOf("day");
+ case "quarterly":
+ return fullDay.subtract(3, "month").startOf("day");
+ case "weekly":
+ return fullDay.subtract(6, "days").startOf("day");
+ default:
+ return fullDay.subtract(1, "month").startOf("day");
+ }
+ }
+
+ @action
+ setCustomDateRange(startDate, endDate) {
+ this.period = "custom";
+ this.start_date = moment(startDate).format("YYYY-MM-DD");
+ this.end_date = moment(endDate).format("YYYY-MM-DD");
+ }
+
+ @action
+ setPeriod(period) {
+ this.period = period;
+ this.start_date = null;
+ this.end_date = null;
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/edit.js b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/edit.js
new file mode 100644
index 00000000000..3dcd470616e
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/edit.js
@@ -0,0 +1,18 @@
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceRoomsEditController extends Controller {
+ @service router;
+ @service toasts;
+
+ @action
+ saveRoom() {
+ this.toasts.success({
+ data: { message: i18n("voice.admin.room_updated") },
+ duration: 2000,
+ });
+ this.router.transitionTo("adminPlugins.show.voice-rooms.index");
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/index.js b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/index.js
new file mode 100644
index 00000000000..293ccdf5fd5
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/index.js
@@ -0,0 +1,10 @@
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { removeValueFromArray } from "discourse/lib/array-tools";
+
+export default class VoiceRoomsIndexController extends Controller {
+ @action
+ destroyRoom(room) {
+ removeValueFromArray(this.model.content, room);
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/new.js b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/new.js
new file mode 100644
index 00000000000..ea5ac2bcff1
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/controllers/admin-plugins/show/voice-rooms/new.js
@@ -0,0 +1,18 @@
+import Controller from "@ember/controller";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceRoomsNewController extends Controller {
+ @service router;
+ @service toasts;
+
+ @action
+ saveRoom() {
+ this.toasts.success({
+ data: { message: i18n("voice.admin.room_created") },
+ duration: 2000,
+ });
+ this.router.transitionTo("adminPlugins.show.voice-rooms.index");
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-dashboard.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-dashboard.js
new file mode 100644
index 00000000000..2a4d167e807
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-dashboard.js
@@ -0,0 +1,37 @@
+import Route from "@ember/routing/route";
+import { ajax } from "discourse/lib/ajax";
+
+export default class VoiceDashboardRoute extends Route {
+ queryParams = {
+ period: { refreshModel: true },
+ start_date: { refreshModel: true },
+ end_date: { refreshModel: true },
+ };
+
+ async model() {
+ const controller = this.controllerFor("admin-plugins.show.voice-dashboard");
+ const queryString = this.#buildQuery(controller);
+
+ const [overview, rooms, users] = await Promise.all([
+ ajax(`/admin/plugins/voice/stats/overview.json?${queryString}`),
+ ajax(`/admin/plugins/voice/stats/rooms.json?${queryString}`),
+ ajax(`/admin/plugins/voice/stats/users.json?${queryString}`),
+ ]);
+
+ return { overview, rooms: rooms.rooms, users: users.users };
+ }
+
+ #buildQuery(controller) {
+ const params = new URLSearchParams();
+ params.set("period", controller.period || "weekly");
+
+ if (controller.start_date) {
+ params.set("start_date", controller.start_date);
+ }
+ if (controller.end_date) {
+ params.set("end_date", controller.end_date);
+ }
+
+ return params.toString();
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-recordings.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-recordings.js
new file mode 100644
index 00000000000..30609449121
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-recordings.js
@@ -0,0 +1,8 @@
+import Route from "@ember/routing/route";
+import { ajax } from "discourse/lib/ajax";
+
+export default class VoiceRecordingsRoute extends Route {
+ async model() {
+ return await ajax("/admin/plugins/voice/recordings.json");
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms.js
new file mode 100644
index 00000000000..2aec3771082
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms.js
@@ -0,0 +1,3 @@
+import Route from "@ember/routing/route";
+
+export default class VoiceRoomsRoute extends Route {}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/edit.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/edit.js
new file mode 100644
index 00000000000..563d4120a9f
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/edit.js
@@ -0,0 +1,10 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class VoiceRoomsEditRoute extends DiscourseRoute {
+ @service store;
+
+ model(params) {
+ return this.store.find("voice-room", params.id);
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/index.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/index.js
new file mode 100644
index 00000000000..775638174fe
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/index.js
@@ -0,0 +1,16 @@
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class VoiceRoomsIndexRoute extends DiscourseRoute {
+ @service store;
+
+ model() {
+ return this.store.findAll("voice-room");
+ }
+
+ @action
+ triggerRefresh() {
+ this.refresh();
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/new.js b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/new.js
new file mode 100644
index 00000000000..5081a672a90
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/routes/admin-plugins/show/voice-rooms/new.js
@@ -0,0 +1,10 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class VoiceRoomsNewRoute extends DiscourseRoute {
+ @service store;
+
+ model() {
+ return this.store.createRecord("voice-room");
+ }
+}
diff --git a/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-dashboard.gjs b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-dashboard.gjs
new file mode 100644
index 00000000000..6132cf831d2
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-dashboard.gjs
@@ -0,0 +1,5 @@
+import VoiceDashboard from "discourse/plugins/voice/admin/components/voice-dashboard";
+
+export default <template>
+ <VoiceDashboard @model={{@model}} @controller={{@controller}} />
+</template>
diff --git a/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-recordings.gjs b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-recordings.gjs
new file mode 100644
index 00000000000..9927dbd88cc
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-recordings.gjs
@@ -0,0 +1,3 @@
+import VoiceRecordingList from "discourse/plugins/voice/admin/components/voice-recording-list";
+
+export default <template><VoiceRecordingList @model={{@model}} /></template>
diff --git a/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/edit.gjs b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/edit.gjs
new file mode 100644
index 00000000000..f41520d5d39
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/edit.gjs
@@ -0,0 +1,5 @@
+import VoiceRoomForm from "discourse/plugins/voice/discourse/components/voice-room-form";
+
+export default <template>
+ <VoiceRoomForm @room={{@controller.model}} @onSave={{@controller.saveRoom}} />
+</template>
diff --git a/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/index.gjs b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/index.gjs
new file mode 100644
index 00000000000..d3d69d0715c
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/index.gjs
@@ -0,0 +1,8 @@
+import VoiceRoomList from "discourse/plugins/voice/admin/components/voice-room-list";
+
+export default <template>
+ <VoiceRoomList
+ @rooms={{@controller.model.content}}
+ @onDestroy={{@controller.destroyRoom}}
+ />
+</template>
diff --git a/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/new.gjs b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/new.gjs
new file mode 100644
index 00000000000..f41520d5d39
--- /dev/null
+++ b/plugins/voice/admin/assets/javascripts/discourse/templates/admin-plugins/show/voice-rooms/new.gjs
@@ -0,0 +1,5 @@
+import VoiceRoomForm from "discourse/plugins/voice/discourse/components/voice-room-form";
+
+export default <template>
+ <VoiceRoomForm @room={{@controller.model}} @onSave={{@controller.saveRoom}} />
+</template>
diff --git a/plugins/voice/app/controllers/voice/admin_controller.rb b/plugins/voice/app/controllers/voice/admin_controller.rb
new file mode 100644
index 00000000000..22902cd8dc4
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/admin_controller.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminController < ::Admin::AdminController
+ requires_plugin "voice"
+
+ def index
+ end
+
+ def new
+ end
+
+ def edit
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/admin_livekit_controller.rb b/plugins/voice/app/controllers/voice/admin_livekit_controller.rb
new file mode 100644
index 00000000000..0ed9087370d
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/admin_livekit_controller.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module Voice
+ # Status payloads report presence booleans, latencies and error strings —
+ # never setting values. A request spec pins that the API secret cannot
+ # appear here (or in any serializer) whatever state the probes are in.
+ class AdminLivekitController < ::Admin::AdminController
+ requires_plugin "voice"
+
+ def status
+ render json: status_payload
+ end
+
+ def probe
+ return render json: status_payload unless Livekit.configured?
+
+ result = Livekit::HealthCheck.connectivity_check
+ Livekit::HealthCheck.store_probe!(result)
+
+ render json:
+ status_payload(
+ probe_result: result,
+ token_check: result[:token],
+ server_check: result[:server],
+ )
+ end
+
+ private
+
+ def status_payload(probe_result: nil, token_check: nil, server_check: nil)
+ configured = Livekit.configured?
+
+ payload = {
+ configured:,
+ settings: Livekit::HealthCheck.settings_status,
+ last_webhook_at: Livekit.last_webhook_at&.iso8601,
+ # For the ready-to-paste server config snippet; derived from the
+ # site's own URL, not from any LiveKit setting.
+ webhook_url: "#{Discourse.base_url}/voice/livekit/webhook",
+ last_probe: probe_result || Livekit::HealthCheck.last_probe,
+ rooms: [],
+ }
+
+ if configured
+ payload[:token_check] = token_check || Livekit::HealthCheck.token_check
+ payload[:server_check] = server_check || Livekit::HealthCheck.server_check
+
+ # When the server is already known unreachable, per-room participant
+ # probes would only stack timeouts onto the response.
+ rooms =
+ Livekit::HealthCheck.pinned_rooms_status(probe_participants: payload[:server_check][:ok])
+ payload[:rooms] = rooms
+ payload[:usernames] = usernames_for(rooms)
+ end
+
+ payload
+ end
+
+ # Id → username for every id in the roster diffs, so the panel can show
+ # who is ghosting instead of bare ids.
+ def usernames_for(rooms)
+ user_ids =
+ rooms
+ .flat_map { |room| [room[:presence_user_ids], room[:livekit_user_ids]] }
+ .flatten
+ .compact
+ .uniq
+ return {} if user_ids.empty?
+
+ User.where(id: user_ids).pluck(:id, :username).to_h
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/admin_recordings_controller.rb b/plugins/voice/app/controllers/voice/admin_recordings_controller.rb
new file mode 100644
index 00000000000..07edceb6145
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/admin_recordings_controller.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminRecordingsController < ::Admin::AdminController
+ requires_plugin "voice"
+
+ PAGE_SIZE = 50
+
+ def index
+ recordings =
+ Voice::Recording
+ .includes(:room, :started_by)
+ .order(started_at: :desc)
+ .offset(params[:offset].to_i.clamp(0..))
+ .limit(PAGE_SIZE + 1)
+ .to_a
+
+ has_more = recordings.size > PAGE_SIZE
+ recordings = recordings.first(PAGE_SIZE)
+
+ render json: {
+ recordings: serialize_data(recordings, Voice::AdminRecordingSerializer, root: false),
+ has_more: has_more,
+ }
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/admin_rooms_controller.rb b/plugins/voice/app/controllers/voice/admin_rooms_controller.rb
new file mode 100644
index 00000000000..568ba0f7e87
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/admin_rooms_controller.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminRoomsController < ::Admin::AdminController
+ requires_plugin "voice"
+
+ def index
+ rooms = Voice::Room.includes(:creator, :room_memberships).order(:name).all
+
+ render_serialized rooms, AdminRoomSerializer, root: :rooms
+ end
+
+ def show
+ room = Voice::Room.includes(:creator, :room_memberships).find(params[:id])
+ render_serialized room, AdminRoomSerializer, root: :room
+ end
+
+ def create
+ room = Voice::Room.new(room_params)
+ room.creator = current_user
+
+ if room.save
+ render_serialized room, AdminRoomSerializer, root: :room, status: :created
+ else
+ render_json_error room
+ end
+ end
+
+ def update
+ room = Voice::Room.find(params[:id])
+
+ if room.update(room_params)
+ render_serialized room, AdminRoomSerializer, root: :room
+ else
+ render_json_error room
+ end
+ end
+
+ def destroy
+ room = Voice::Room.find(params[:id])
+ room.destroy!
+ Voice::Livekit::RoomServiceClient.delete_room(room)
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ head :no_content
+ end
+
+ # Emergency lever that force-ends a room's live call: evicts the media
+ # session from the SFU, unpins the transport so the next join re-resolves
+ # against current settings, and sends every participant the same per-user
+ # `kicked` message a room-level kick uses — the client handler already
+ # forces a clean leave, so no new client message types are needed.
+ def end_call
+ room = Voice::Room.find(params[:id])
+ participant_ids = Voice::ParticipantTracker.user_ids(room.id)
+
+ Voice::Livekit::RoomServiceClient.delete_room(room)
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ participant_ids.each { |user_id| Voice::RoomBroadcaster.publish_kick(room, user_id) }
+
+ head :no_content
+ end
+
+ private
+
+ def room_params
+ permitted =
+ params.require(:room).permit(
+ :name,
+ :slug,
+ :description,
+ :public,
+ :max_participants,
+ :room_type,
+ :video_enabled,
+ :livekit_enabled,
+ :chat_channel_id,
+ :chat_idle_minutes,
+ :max_quality_profile,
+ )
+ if permitted.key?(:room_type)
+ permitted[:room_type] = Voice::Room.room_type_from_name!(permitted[:room_type])
+ end
+ if permitted.key?(:max_quality_profile)
+ permitted[:max_quality_profile] = Voice::Room::QUALITY_PROFILES[
+ permitted[:max_quality_profile].to_s
+ ]
+ end
+ permitted
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/admin_stats_controller.rb b/plugins/voice/app/controllers/voice/admin_stats_controller.rb
new file mode 100644
index 00000000000..c84def3526f
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/admin_stats_controller.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminStatsController < ::Admin::AdminController
+ requires_plugin "voice"
+
+ PERIOD_DAYS = { "daily" => 1, "weekly" => 7, "monthly" => 30, "quarterly" => 90 }.freeze
+ DURATION_SQL = "EXTRACT(EPOCH FROM (COALESCE(left_at, NOW()) - joined_at))"
+
+ def overview
+ sessions = sessions_in_period
+
+ total_sessions = sessions.count
+ unique_users = sessions.distinct.count(:user_id)
+ avg_duration = sessions.average(Arel.sql(DURATION_SQL)).to_f.round
+
+ render json: { total_sessions:, unique_users:, avg_duration: }
+ end
+
+ def rooms
+ rows =
+ sessions_in_period
+ .joins("LEFT JOIN voice_rooms ON voice_rooms.id = voice_sessions.room_id")
+ .group(:room_id, "voice_rooms.name")
+ .select(
+ "voice_sessions.room_id",
+ # NULL when the room was deleted; the dashboard renders a fallback.
+ "voice_rooms.name AS room_name",
+ "COUNT(DISTINCT voice_sessions.user_id) AS unique_users",
+ "ROUND(SUM(#{DURATION_SQL})) AS total_seconds",
+ )
+ .order(Arel.sql("total_seconds DESC"))
+ .limit(50)
+
+ render json: {
+ rooms:
+ rows.map do |r|
+ {
+ room_id: r.room_id,
+ room_name: r.room_name,
+ unique_users: r.unique_users,
+ total_seconds: r.total_seconds.to_i,
+ }
+ end,
+ }
+ end
+
+ def users
+ rows =
+ sessions_in_period
+ .group(:user_id)
+ .select(
+ "voice_sessions.user_id",
+ "COUNT(*) AS session_count",
+ "ROUND(SUM(#{DURATION_SQL})) AS total_seconds",
+ )
+ .order(Arel.sql("total_seconds DESC"))
+ .limit(50)
+
+ user_ids = rows.map(&:user_id)
+ users_by_id = User.where(id: user_ids).index_by(&:id)
+
+ render json: {
+ users:
+ rows.map do |r|
+ user = users_by_id[r.user_id]
+ {
+ user_id: r.user_id,
+ username: user&.username,
+ name: user&.name,
+ avatar_template: user&.avatar_template,
+ session_count: r.session_count,
+ total_seconds: r.total_seconds.to_i,
+ }
+ end,
+ }
+ end
+
+ private
+
+ def sessions_in_period
+ if params[:period] == "custom" && params[:start_date].present? && params[:end_date].present?
+ start_date = Date.parse(params[:start_date])
+ end_date = Date.parse(params[:end_date])
+
+ Voice::Session.where(
+ "joined_at >= ? AND joined_at <= ?",
+ start_date.beginning_of_day,
+ end_date.end_of_day,
+ )
+ else
+ days = PERIOD_DAYS.fetch(params[:period].to_s, 7)
+ Voice::Session.where("joined_at > ?", days.days.ago)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/application_controller.rb b/plugins/voice/app/controllers/voice/application_controller.rb
new file mode 100644
index 00000000000..dc4a22bf65d
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/application_controller.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Voice
+ class ApplicationController < ::ApplicationController
+ requires_plugin ::Voice::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+ before_action :ensure_enabled!
+
+ private
+
+ def ensure_enabled!
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_enabled")) unless Voice.enabled?
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/calls_controller.rb b/plugins/voice/app/controllers/voice/calls_controller.rb
new file mode 100644
index 00000000000..dcd5c48e339
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/calls_controller.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module Voice
+ # Starts a direct call: an ephemeral room holding the caller and callee as
+ # peers, surfaced to the callee by the ring the inviter publishes. The room
+ # reaps itself through the ephemeral TTL if the call never connects.
+ class CallsController < ApplicationController
+ def create
+ unless guardian.can_start_voice_call?
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+
+ username = params.require(:username).to_s
+ callee = User.real.not_staged.find_by(username_lower: username.downcase)
+ raise Discourse::NotFound if callee.nil?
+
+ if callee.id == current_user.id || callee.bot? || !callee.guardian.can_access_voice?
+ raise Discourse::InvalidParameters.new(:username)
+ end
+
+ # One message for every preference-based refusal (mute, ignore, personal
+ # messages disabled or allowlisted), matching what personal messages and
+ # chat DMs reveal without saying which preference applied.
+ unless guardian.can_call_voice_user?(callee)
+ raise Discourse::InvalidAccess.new(
+ "cannot call user",
+ nil,
+ custom_message: "voice.errors.cannot_call_user",
+ )
+ end
+
+ RateLimiter.new(current_user, "voice-calls", 10, 1.minute).performed!
+
+ # The ring consumes the daily invite budget inside RoomInviter; checked
+ # here first so an exhausted budget rejects the call before an ephemeral
+ # room exists, instead of leaving one behind for cleanup.
+ invite_limiter =
+ RateLimiter.new(
+ current_user,
+ "voice-invites-daily",
+ SiteSetting.voice_max_invites_per_day,
+ 1.day,
+ )
+ unless invite_limiter.can_perform?
+ raise RateLimiter::LimitExceeded.new(invite_limiter.seconds_to_wait, "voice-invites-daily")
+ end
+
+ room =
+ Voice::EphemeralRoomManager.create!(
+ creator: current_user,
+ # Named for both parties so neither side reads it as someone else's
+ # room. Truncated because two maximum-length usernames can exceed
+ # the room name limit.
+ name:
+ I18n.t(
+ "voice.call.room_name",
+ caller: current_user.username,
+ callee: callee.username,
+ ).truncate(80),
+ # A call has no host: either side may pull someone else in.
+ moderators: [callee],
+ )
+
+ begin
+ Voice::RoomInviter.invite!(room: room, inviter: current_user, users: [callee])
+ rescue StandardError
+ # A call that could not ring must not leave an orphaned room behind.
+ Voice::EphemeralRoomManager.destroy!(room)
+ raise
+ end
+
+ render_serialized room, Voice::RoomSerializer, root: :room
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/chat_threads_controller.rb b/plugins/voice/app/controllers/voice/chat_threads_controller.rb
new file mode 100644
index 00000000000..41564a36e93
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/chat_threads_controller.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module Voice
+ class ChatThreadsController < ApplicationController
+ # Answers "which voice room did this chat thread come from?" for the
+ # back-to-room button chat renders in session thread headers. Every miss —
+ # unknown thread, not a session thread, invisible channel or room — is the
+ # same 404, so the endpoint reveals nothing about what exists.
+ def show
+ raise Discourse::NotFound unless Voice::ChatSession.chat_available?
+
+ thread = ::Chat::Thread.find_by(id: params[:id])
+ raise Discourse::NotFound if thread.blank?
+
+ # Mirror chat's own thread visibility (Chat::LookupThread): no room info
+ # about threads the user couldn't open — invisible channel, threading
+ # no longer available, or a deleted starter message (which hides the
+ # thread from everyone but channel moderators).
+ raise Discourse::NotFound unless guardian.can_preview_chat_channel?(thread.channel)
+ raise Discourse::NotFound unless thread.channel.threading_enabled || thread.force
+ raise Discourse::NotFound unless original_message_visible?(thread)
+
+ room = Voice::Room.find_by(id: thread.custom_fields[Voice::THREAD_ROOM_ID_FIELD].to_i)
+ raise Discourse::NotFound if room.blank?
+
+ # A marker pointing at a room that has since been linked to a different
+ # channel is stale — the thread is no longer one of the room's session
+ # threads.
+ raise Discourse::NotFound if room.chat_channel_id != thread.channel_id
+ raise Discourse::NotFound unless guardian.can_see_voice_room?(room)
+
+ render json: {
+ id: room.id,
+ slug: room.slug,
+ name: room.name,
+ # Whether this thread is still the room's live session — an
+ # ended session's thread links back to the room, but arriving
+ # there shouldn't open a chat panel for a conversation that has
+ # already rolled over.
+ chat_active: Voice::ChatSession.state(room)[:thread_id] == thread.id,
+ }
+ end
+
+ private
+
+ def original_message_visible?(thread)
+ return false if thread.original_message.blank?
+ thread.original_message.deleted_at.blank? ||
+ guardian.can_moderate_chat?(thread.channel.chatable)
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/contacts_controller.rb b/plugins/voice/app/controllers/voice/contacts_controller.rb
new file mode 100644
index 00000000000..57c0a106d95
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/contacts_controller.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module Voice
+ class ContactsController < ApplicationController
+ def index
+ raise Discourse::NotFound unless SiteSetting.voice_analytics_enabled
+
+ contacts = Voice::CoPresence.top_contacts_for(current_user.id, since: 30.days.ago, limit: 10)
+
+ users = User.where(id: contacts.map(&:contact_id)).index_by(&:id)
+
+ render json: {
+ contacts:
+ contacts.filter_map do |row|
+ user = users[row.contact_id]
+ next unless user
+
+ BasicUserSerializer
+ .new(user, scope: guardian, root: false)
+ .as_json
+ .merge(
+ total_seconds: row.total_seconds,
+ session_count: row.session_count,
+ last_co_present_on: row.last_co_present_on,
+ )
+ end,
+ }
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/invites_controller.rb b/plugins/voice/app/controllers/voice/invites_controller.rb
new file mode 100644
index 00000000000..c262d1b7594
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/invites_controller.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module Voice
+ class InvitesController < ApplicationController
+ MAX_USERS_PER_REQUEST = 10
+ SUGGESTION_LIMIT = 10
+
+ before_action :load_room
+
+ def create
+ guardian.ensure_can_invite_to_voice_room!(@room)
+ RateLimiter.new(current_user, "voice-invites", 10, 1.minute).performed!
+
+ # Bounded before any normalization or query construction: `limit` below
+ # caps the rows returned, not the size of the IN list an oversized
+ # parameter would otherwise be interpolated into.
+ usernames = Array.wrap(params.require(:usernames))
+ if usernames.blank? || usernames.size > MAX_USERS_PER_REQUEST
+ raise Discourse::InvalidParameters.new(:usernames)
+ end
+ usernames = usernames.map(&:to_s).uniq
+
+ users =
+ User
+ .real
+ .not_staged
+ .where(username_lower: usernames.map(&:downcase))
+ .limit(MAX_USERS_PER_REQUEST)
+
+ invited = Voice::RoomInviter.invite!(room: @room, inviter: current_user, users: users)
+ # Users the inviter named but the inviter service refused (no access to
+ # voice, can't join this room, …) — surfaced so the modal can explain
+ # instead of failing silently.
+ skipped = users.to_a - invited
+ render json: {
+ invited_usernames: invited.map(&:username),
+ skipped_usernames: skipped.map(&:username),
+ }
+ end
+
+ # People the current user has shared this room with recently, most time
+ # together first — the shortlist the invite modal opens with.
+ def suggestions
+ guardian.ensure_can_invite_to_voice_room!(@room)
+
+ rows =
+ if SiteSetting.voice_analytics_enabled
+ Voice::Session.top_room_companions_for(
+ current_user.id,
+ @room.id,
+ since: 30.days.ago,
+ # Overfetched so dropping whoever is already in the call cannot
+ # leave the list short.
+ limit: SUGGESTION_LIMIT * 2,
+ )
+ else
+ []
+ end
+
+ present_ids = Voice::ParticipantTracker.user_ids(@room.id)
+ rows = rows.reject { |row| present_ids.include?(row.companion_id) }
+
+ users = User.real.not_staged.where(id: rows.map(&:companion_id)).index_by(&:id)
+
+ suggestions =
+ rows
+ .filter_map do |row|
+ user = users[row.companion_id]
+ next unless user
+ # Session history outlives group membership: only people who can
+ # still use voice rooms are worth suggesting.
+ next unless user.guardian.can_access_voice?
+
+ BasicUserSerializer
+ .new(user, scope: guardian, root: false)
+ .as_json
+ .merge(total_seconds: row.total_seconds, last_together_at: row.last_together_at)
+ end
+ .first(SUGGESTION_LIMIT)
+
+ render json: { suggestions: suggestions }
+ end
+
+ private
+
+ def load_room
+ @room = Voice::Room.find(params[:room_id])
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb b/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb
new file mode 100644
index 00000000000..d4bd3c14e40
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb
@@ -0,0 +1,137 @@
+# frozen_string_literal: true
+
+module Voice
+ # Receives LiveKit server webhooks. Strictly a reconcile-only backstop:
+ # events may early-expire presence LiveKit knows is gone, or clear the
+ # transport pin of a finished room — but they never create presence and
+ # never touch Session rows. Heartbeats and CloseOrphanedSessions remain the
+ # source of truth on both transports, so undelivered webhooks cost nothing
+ # but reaction time.
+ class LivekitWebhooksController < ApplicationController
+ skip_before_action :ensure_logged_in,
+ :verify_authenticity_token,
+ :redirect_to_login_if_required,
+ :redirect_to_profile_if_required,
+ :check_xhr,
+ :preload_json
+
+ def create
+ body = request.body.read
+
+ begin
+ Livekit::WebhookVerifier.verify!(
+ authorization: request.headers["Authorization"],
+ body: body,
+ )
+ rescue Livekit::WebhookVerifier::VerificationError => e
+ Rails.logger.warn("[voice-livekit] rejected webhook: #{e.message}")
+ return head :forbidden
+ end
+
+ Livekit.touch_last_webhook!
+
+ event = parse_event(body)
+ return head :bad_request if event.nil?
+
+ case event["event"]
+ when "participant_joined"
+ record_participant_sid(event)
+ when "participant_left", "participant_connection_aborted"
+ expire_participant(event)
+ when "room_finished"
+ finish_room(event)
+ when "egress_ended"
+ egress_ended(event)
+ end
+
+ head :ok
+ end
+
+ private
+
+ def parse_event(body)
+ parsed = JSON.parse(body)
+ parsed.is_a?(Hash) ? parsed : nil
+ rescue JSON::ParserError
+ nil
+ end
+
+ # Not presence — only which media session (SID) is the user's current one,
+ # so a superseded session's late departure can be told apart from the live
+ # session's.
+ def record_participant_sid(event)
+ room = event_room(event)
+ return if room.nil?
+
+ user_id = event.dig("participant", "identity").to_i
+ return if user_id <= 0
+
+ Voice::ParticipantTracker.set_livekit_sid(room.id, user_id, event.dig("participant", "sid"))
+ end
+
+ def expire_participant(event)
+ room = event_room(event)
+ return if room.nil?
+
+ user_id = event.dig("participant", "identity").to_i
+ return if user_id <= 0
+
+ # A quick disconnect/rejoin can deliver the old session's departure
+ # after the new session is up; `gone_at` can't distinguish them (the
+ # rejoin predates the disconnect), but the SID can. Departures without
+ # SID context on either side keep expiring — reconcile-only backstop.
+ sid = event.dig("participant", "sid")
+ known_sid = Voice::ParticipantTracker.livekit_sid(room.id, user_id)
+ return if sid.present? && known_sid.present? && sid != known_sid
+
+ expired =
+ Voice::ParticipantTracker.expire_presence(
+ room.id,
+ user_id,
+ gone_at: event_created_at(event),
+ )
+ Voice::RoomBroadcaster.publish_participants_if_changed(room) if expired
+ end
+
+ def finish_room(event)
+ room = event_room(event)
+ return if room.nil?
+
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.clear_livekit_sids(room.id)
+ end
+
+ # Egress events name the room inside egressInfo, not in a room object,
+ # and are handled regardless of the transport pin: by the time the final
+ # egress of a finished room reports in, the pin may already be gone.
+ def egress_ended(event)
+ egress_info = event["egress_info"] || event["egressInfo"]
+ room_name = egress_info&.fetch("room_name", egress_info["roomName"])
+ room_id = Livekit.room_id_from_name(room_name)
+ return if room_id.nil?
+
+ room = Voice::Room.find_by(id: room_id)
+ return if room.nil?
+
+ Voice::RecordingManager.handle_egress_ended(room, egress_info)
+ end
+
+ # Resolves the event's LiveKit room name back to a room, ignoring events
+ # for other sites on a shared server (foreign prefix) and for rooms not
+ # currently pinned to livekit — a mesh call's presence is none of
+ # LiveKit's business, however stale the SFU's view of the room is.
+ def event_room(event)
+ room_id = Livekit.room_id_from_name(event.dig("room", "name"))
+ return if room_id.nil?
+ return if Voice::ParticipantTracker.pinned_transport(room_id) != "livekit"
+
+ Voice::Room.find_by(id: room_id)
+ end
+
+ # Proto3 JSON renders int64 as a string; tolerate a plain number too.
+ def event_created_at(event)
+ ts = event["createdAt"].to_i
+ ts.positive? ? Time.at(ts) : nil
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/page_controller.rb b/plugins/voice/app/controllers/voice/page_controller.rb
new file mode 100644
index 00000000000..4d3c880f204
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/page_controller.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module Voice
+ class PageController < ApplicationController
+ # Anonymous visitors may view public room pages when access is open to
+ # everyone, mirroring the rooms directory; the guardian gates the rest.
+ skip_before_action :ensure_logged_in
+
+ # Without this, HTML requests short-circuit into the app shell before the
+ # action runs, so unknown slugs and forbidden rooms would never 404/403.
+ skip_before_action :check_xhr, only: :show
+
+ def show
+ room = Voice::Room.find_by(slug: params[:slug])
+ raise Discourse::NotFound if room.blank?
+
+ guardian.ensure_can_see_voice_room!(room)
+
+ render "default/empty"
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/room_memberships_controller.rb b/plugins/voice/app/controllers/voice/room_memberships_controller.rb
new file mode 100644
index 00000000000..a38e6d03334
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/room_memberships_controller.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomMembershipsController < ApplicationController
+ before_action :load_room
+
+ def index
+ guardian.ensure_can_manage_voice_room!(@room)
+ render_serialized @room.room_memberships, Voice::RoomMembershipSerializer, root: :memberships
+ end
+
+ def create
+ guardian.ensure_can_manage_voice_room!(@room)
+ user = fetch_user
+ role = Voice::RoomMembership.role_value(params[:role])
+ membership = @room.room_memberships.find_or_initialize_by(user: user)
+ membership.role = role
+ membership.save!
+
+ if Voice::ParticipantTracker.user_ids(@room.id).include?(user.id)
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, user.id)
+ metadata[:role] = membership.role_name
+ metadata.delete(:hand_raised_at) if membership.can_speak?
+ Voice::ParticipantTracker.update_metadata(@room.id, user.id, metadata)
+ Voice::RoomBroadcaster.publish_role_change(@room, user.id, membership.role_name)
+ Voice::RoomBroadcaster.publish_participants(@room)
+ Voice::Livekit::RoomServiceClient.update_participant(@room, user)
+ end
+
+ render_serialized membership, Voice::RoomMembershipSerializer, root: :membership
+ end
+
+ def update
+ guardian.ensure_can_manage_voice_room!(@room)
+ membership = @room.room_memberships.find(params[:id])
+ new_role = params.require(:role)
+ membership.update!(role: Voice::RoomMembership.role_value(new_role))
+
+ if Voice::ParticipantTracker.user_ids(@room.id).include?(membership.user_id)
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, membership.user_id)
+ metadata[:role] = membership.role_name
+ metadata.delete(:hand_raised_at) if membership.can_speak?
+ Voice::ParticipantTracker.update_metadata(@room.id, membership.user_id, metadata)
+ Voice::RoomBroadcaster.publish_role_change(@room, membership.user_id, membership.role_name)
+ Voice::RoomBroadcaster.publish_participants(@room)
+ # Lets a promoted stage listener publish without reconnecting; on
+ # failure the client falls back to re-minting a token and reconnecting.
+ Voice::Livekit::RoomServiceClient.update_participant(@room, membership.user)
+ end
+
+ render_serialized membership, Voice::RoomMembershipSerializer, root: :membership
+ end
+
+ def destroy
+ guardian.ensure_can_manage_voice_room!(@room)
+ membership = @room.room_memberships.find(params[:id])
+ user_id = membership.user_id
+ membership.destroy!
+
+ if Voice::ParticipantTracker.user_ids(@room.id).include?(user_id)
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, user_id)
+ metadata[:role] = "participant"
+ Voice::ParticipantTracker.update_metadata(@room.id, user_id, metadata)
+ Voice::RoomBroadcaster.publish_role_change(@room, user_id, "participant")
+ Voice::RoomBroadcaster.publish_participants(@room)
+ if (user = User.find_by(id: user_id))
+ Voice::Livekit::RoomServiceClient.update_participant(@room, user)
+ end
+ end
+
+ head :no_content
+ end
+
+ private
+
+ def fetch_user
+ if params[:user_id]
+ User.find(params[:user_id])
+ elsif params[:username]
+ User.find_by_username_or_email(params[:username])
+ else
+ raise Discourse::InvalidParameters
+ end
+ end
+
+ def load_room
+ @room = Voice::Room.find(params[:room_id])
+ end
+ end
+end
diff --git a/plugins/voice/app/controllers/voice/rooms_controller.rb b/plugins/voice/app/controllers/voice/rooms_controller.rb
new file mode 100644
index 00000000000..89512ecfde3
--- /dev/null
+++ b/plugins/voice/app/controllers/voice/rooms_controller.rb
@@ -0,0 +1,811 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomsController < ApplicationController
+ # Signal budgets are accounted in relayed events (not HTTP requests), so a
+ # legitimate full-room Trickle ICE burst — one offer plus batched
+ # candidates to every peer, with headroom for an ICE restart — passes
+ # while sustained signaling beyond it is rejected before any MessageBus
+ # work happens.
+ SIGNAL_REQUESTS_PER_USER = 30 # per 10 seconds
+ SIGNAL_EVENTS_PER_USER_PER_MINUTE = 5_000
+ SIGNAL_EVENTS_PER_ROOM_PER_MINUTE = 100_000
+
+ STATE_FIELDS = %i[muted deafened video screen watching transcribing]
+
+ # Anonymous visitors may browse the directory; the guardian still limits the
+ # listing to public rooms, and only when access is open to everyone.
+ skip_before_action :ensure_logged_in, only: :index
+
+ before_action :load_room,
+ only: %i[
+ show
+ update
+ destroy
+ join
+ leave
+ participants
+ signal
+ chat_session
+ ensure_chat_session
+ chat_message
+ kick
+ flag
+ heartbeat
+ toggle_mute
+ state
+ livekit_token
+ start_recording
+ stop_recording
+ request_to_speak
+ withdraw_request_to_speak
+ ]
+
+ def index
+ Voice::DefaultRoomSeeder.ensure!
+
+ rooms =
+ Voice::Room
+ .persistent
+ .includes(:room_memberships)
+ .order(:created_at)
+ .select { |room| guardian.can_see_voice_room?(room) }
+
+ # Captured before serializing so clients subscribing from this position
+ # never miss a directory event published while the response was built.
+ index_message_bus_last_id = MessageBus.last_id(Voice.room_index_channel)
+
+ render json: {
+ rooms: serialize_data(rooms, Voice::RoomSerializer),
+ can_create_room: guardian.can_create_voice_room?,
+ index_message_bus_last_id: index_message_bus_last_id,
+ }
+ end
+
+ def show
+ guardian.ensure_can_see_voice_room!(@room)
+ render_serialized @room, Voice::RoomSerializer, root: :room, include_visit_count: true
+ end
+
+ def create
+ guardian.ensure_can_create_voice_room!
+
+ # Ephemeral rooms are created by features on the user's behalf (with
+ # their own TTL-based cap), not by the user — they don't count here.
+ if current_user.voice_rooms.persistent.count >= SiteSetting.voice_max_rooms_per_user
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.room_limit"))
+ end
+
+ room = Voice::Room.new(room_params)
+ room.creator = current_user
+
+ if room.save
+ Voice::DirectoryBroadcaster.broadcast(action: :created, room: room)
+ Voice::BadgeGranterHooks.on_room_create(current_user)
+ render_serialized room, Voice::RoomSerializer, root: :room
+ else
+ render_json_error room
+ end
+ end
+
+ def update
+ guardian.ensure_can_manage_voice_room!(@room)
+
+ name_changed = room_params[:name].present? && room_params[:name] != @room.name
+
+ if @room.update(room_params)
+ Voice::DirectoryBroadcaster.broadcast(action: :updated, room: @room)
+ refresh_participant_statuses(@room) if name_changed
+ render_serialized @room, Voice::RoomSerializer, root: :room
+ else
+ render_json_error @room
+ end
+ end
+
+ def destroy
+ guardian.ensure_can_manage_voice_room!(@room)
+ # Built before the destroy so the broadcast still targets the members
+ # whose memberships the destroy cascades away.
+ broadcaster = Voice::DirectoryBroadcaster.new(@room, :destroyed)
+ @room.destroy!
+ broadcaster.broadcast
+ Voice::Livekit::RoomServiceClient.delete_room(@room)
+ Voice::ParticipantTracker.clear_transport_pin(@room.id)
+ render json: success_json
+ end
+
+ def join
+ guardian.ensure_can_join_voice_room!(@room)
+ RateLimiter.new(current_user, "voice-joins", 30, 1.minute).performed!
+
+ # A repeated join carrying the live participant session (a UI retry, a
+ # duplicated request) refreshes the existing grant instead of re-running
+ # join side effects: no session rotation, no second analytics session,
+ # no badge/invite re-fires, no roster rebroadcast.
+ if repeat_join?
+ transport = Voice::ParticipantTracker.pinned_transport(@room.id) || "mesh"
+
+ livekit = nil
+ if transport == "livekit"
+ livekit = mint_livekit_payload
+ if livekit.nil?
+ return(render_json_error(I18n.t("voice.errors.livekit_unavailable"), status: 503))
+ end
+ end
+
+ Voice::ParticipantTracker.add(@room.id, current_user.id)
+ Voice::ParticipantTracker.refresh_participant_session(@room.id, current_user.id)
+ Voice::ParticipantTracker.refresh_transport_pin(@room.id)
+
+ payload = {
+ transport: transport,
+ participant_session_id: params[:participant_session_id],
+ ice: Voice::IceConfig.payload(current_user),
+ room:
+ Voice::RoomSerializer.new(
+ @room,
+ scope: guardian,
+ root: false,
+ include_visit_count: true,
+ ).as_json,
+ }
+ payload[:livekit] = livekit if livekit
+ return render json: payload
+ end
+
+ # Resolved before presence is added, so a LiveKit failure rejects the
+ # join without leaving the user in the roster.
+ transport = Voice::ParticipantTracker.pinned_transport(@room.id)
+ transport ||= Voice::Livekit.available_for?(@room) ? "livekit" : "mesh"
+
+ livekit = nil
+ if transport == "livekit"
+ livekit = mint_livekit_payload
+
+ if livekit.nil?
+ # Fall back to mesh only when explicitly enabled and the room is
+ # empty — an occupied LiveKit room must never be split, and silent
+ # degradation hides outages from ops.
+ if SiteSetting.voice_livekit_mesh_fallback &&
+ Voice::ParticipantTracker.user_ids(@room.id).empty?
+ Voice::ParticipantTracker.clear_transport_pin(@room.id)
+ transport = "mesh"
+ else
+ return(render_json_error(I18n.t("voice.errors.livekit_unavailable"), status: 503))
+ end
+ end
+ end
+
+ transport = Voice::ParticipantTracker.pin_transport!(@room.id, transport)
+
+ # A concurrent first join can win the pin race with a different
+ # transport (e.g. settings changed between the two resolutions) —
+ # the pin is authoritative.
+ if transport == "livekit" && livekit.nil?
+ livekit = mint_livekit_payload
+ if livekit.nil?
+ return(render_json_error(I18n.t("voice.errors.livekit_unavailable"), status: 503))
+ end
+ end
+ livekit = nil if transport == "mesh"
+
+ Voice::ParticipantTracker.clear_left(@room.id, current_user.id)
+
+ admission =
+ Voice::ParticipantTracker.add_within_capacity(
+ @room.id,
+ current_user.id,
+ @room.effective_max_participants,
+ )
+ return render_json_error(I18n.t("voice.errors.room_full"), status: 422) if admission == :full
+
+ # A joiner already in the roster but without the live session proof (a
+ # reloaded tab, a second device — or a client replaying this endpoint)
+ # takes over the existing grant rather than re-running first-join side
+ # effects: the session still rotates so the new tab gains signaling
+ # authority, but the open analytics row is reused and badge/invite
+ # hooks don't re-fire. Otherwise every replayed join is a free
+ # analytics insert and roster broadcast.
+ takeover = admission == :existing
+ previous_metadata =
+ (
+ if takeover
+ Voice::ParticipantTracker.get_metadata(@room.id, current_user.id)
+ else
+ {}
+ end
+ )
+
+ participant_session_id =
+ Voice::ParticipantTracker.create_participant_session!(@room.id, current_user.id)
+
+ membership = @room.room_memberships.find_by(user_id: current_user.id)
+ role = membership&.role_name || "participant"
+ metadata = { role: role, last_heartbeat_at: Time.now.to_f }
+
+ if SiteSetting.voice_analytics_enabled
+ session = nil
+ if previous_metadata[:session_id]
+ session =
+ Voice::Session.find_by(
+ id: previous_metadata[:session_id],
+ user_id: current_user.id,
+ room_id: @room.id,
+ left_at: nil,
+ )
+ end
+ session ||= Voice::Session.create!(user: current_user, room: @room, joined_at: Time.current)
+ metadata[:session_id] = session.id
+ end
+
+ metadata[:skip_status] = true if params[:skip_status].present?
+ Voice::ParticipantTracker.update_metadata(@room.id, current_user.id, metadata)
+
+ if takeover
+ Voice::RoomBroadcaster.publish_participants_if_changed(@room)
+ else
+ Voice::RoomBroadcaster.publish_participants(@room)
+
+ participants = Voice::ParticipantTracker.list(@room.id)
+ Voice::BadgeGranterHooks.on_join(current_user, @room, participants)
+
+ if params[:invited_by].present?
+ invite =
+ Voice::Invite.redeem!(
+ room: @room,
+ user: current_user,
+ inviter_username: params[:invited_by],
+ )
+ Voice::BadgeGranterHooks.on_invite_redeemed(invite) if invite
+ end
+ end
+
+ # A join settles this room's pending invitation/call notifications: the
+ # incoming-call modal, push notifications, and cached-room transitions
+ # never pass through the user-menu click marking, so without this the
+ # notification stays unread forever.
+ mark_invitation_notifications_read!
+
+ Voice::UserStatusManager.set_voice_status(current_user, @room) if params[:skip_status].blank?
+
+ payload = {
+ transport: transport,
+ participant_session_id: participant_session_id,
+ ice: Voice::IceConfig.payload(current_user),
+ room:
+ Voice::RoomSerializer.new(
+ @room,
+ scope: guardian,
+ root: false,
+ include_visit_count: true,
+ ).as_json,
+ }
+ payload[:livekit] = livekit if livekit
+ render json: payload
+ end
+
+ # Reissues a LiveKit access token for the reconnect ladder, which runs
+ # precisely when the presence TTL may have lapsed — so this endpoint
+ # re-adds presence itself (same authz as heartbeat) instead of requiring
+ # it. 410 tells the client the room instance ended: stop the ladder,
+ # tear down locally, and offer a rejoin.
+ def livekit_token
+ guardian.ensure_can_join_voice_room!(@room)
+ RateLimiter.new(current_user, "voice-livekit-token", 10, 1.minute).performed!
+
+ if Voice::ParticipantTracker.pinned_transport(@room.id) != "livekit"
+ return(render_json_error(I18n.t("voice.errors.livekit_room_instance_ended"), status: 410))
+ end
+
+ # The reconnect ladder only runs while the client considers itself in the
+ # call, so an explicit token request voids any leave/kick tombstone.
+ Voice::ParticipantTracker.clear_left(@room.id, current_user.id)
+ Voice::ParticipantTracker.add(@room.id, current_user.id)
+ # The session may have expired along with the lapsed presence — mint a
+ # fresh one so heartbeat/state keep working after the reconnect.
+ participant_session_id =
+ Voice::ParticipantTracker.create_participant_session!(@room.id, current_user.id)
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, current_user.id)
+ metadata[:last_heartbeat_at] = Time.now.to_f
+ Voice::ParticipantTracker.update_metadata(@room.id, current_user.id, metadata)
+ Voice::ParticipantTracker.refresh_transport_pin(@room.id)
+ Voice::RoomBroadcaster.publish_participants_if_changed(@room)
+
+ livekit = mint_livekit_payload
+ if livekit.nil?
+ return(render_json_error(I18n.t("voice.errors.livekit_unavailable"), status: 503))
+ end
+
+ render json: livekit.merge(participant_session_id: participant_session_id)
+ end
+
+ def start_recording
+ guardian.ensure_can_manage_voice_room!(@room)
+ render json: { recording: Voice::RecordingManager.start!(@room, current_user) }
+ rescue Voice::RecordingManager::Error => e
+ render_json_error(e.message, status: 422)
+ end
+
+ def stop_recording
+ guardian.ensure_can_manage_voice_room!(@room)
+ Voice::RecordingManager.stop!(@room)
+ head :no_content
+ rescue Voice::RecordingManager::Error => e
+ render_json_error(e.message, status: 422)
+ end
+
+ def leave
+ guardian.ensure_can_join_voice_room!(@room)
+
+ # A leave from a stale tab — carrying a participant session that a newer
+ # join has since superseded — must not tear down the presence and
+ # session the newer tab now owns.
+ if params[:participant_session_id].present? &&
+ !Voice::ParticipantTracker.valid_participant_session?(
+ @room.id,
+ current_user.id,
+ params[:participant_session_id],
+ )
+ return head :no_content
+ end
+
+ session = close_session_for(@room.id, current_user.id)
+ Voice::ParticipantTracker.mark_left(@room.id, current_user.id)
+ Voice::ParticipantTracker.remove(@room.id, current_user.id)
+ if Voice::ParticipantTracker.user_ids(@room.id).empty?
+ Voice::Livekit::RoomServiceClient.delete_room(@room)
+ Voice::ParticipantTracker.clear_transport_pin(@room.id)
+ end
+ Voice::UserStatusManager.clear_voice_status(current_user)
+ Voice::RoomBroadcaster.publish_participants(@room)
+ Voice::BadgeGranterHooks.on_leave(current_user, session, room: @room)
+ head :no_content
+ end
+
+ def heartbeat
+ guardian.ensure_can_join_voice_room!(@room)
+
+ # A beat already in flight when the user left (or was kicked) must not
+ # resurrect their presence; only join/livekit_token re-establish it.
+ return head :no_content if Voice::ParticipantTracker.recently_left?(@room.id, current_user.id)
+
+ ensure_participant_session!
+
+ Voice::ParticipantTracker.add(@room.id, current_user.id)
+ Voice::ParticipantTracker.refresh_participant_session(@room.id, current_user.id)
+
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, current_user.id)
+ metadata[:last_heartbeat_at] = Time.now.to_f
+
+ if params.key?(:idle_state)
+ idle_state = params[:idle_state].to_s
+ metadata[:idle_state] = idle_state if %w[active idle afk].include?(idle_state)
+ end
+
+ Voice::ParticipantTracker.update_metadata(@room.id, current_user.id, metadata)
+ Voice::ParticipantTracker.refresh_transport_pin(@room.id)
+
+ # Keep an in-progress chat session alive while someone is present, so it
+ # only rolls over to a new thread once the room is idle AND empty.
+ Voice::ChatSession.touch!(@room)
+
+ # Detect and broadcast any drift (idle change, or a participant whose TTL
+ # lapsed after an abrupt disconnect) now that metadata is persisted.
+ Voice::RoomBroadcaster.publish_participants_if_changed(@room)
+
+ if !metadata[:skip_status] && Voice::UserStatusManager.voice_status_active?(current_user)
+ if metadata[:idle_state] == "afk"
+ Voice::UserStatusManager.set_afk_status(current_user, @room)
+ else
+ Voice::UserStatusManager.set_voice_status(current_user, @room)
+ end
+ end
+
+ head :no_content
+ end
+
+ def participants
+ guardian.ensure_can_join_voice_room!(@room)
+ all_metadata = Voice::ParticipantTracker.get_all_metadata(@room.id)
+ render json: {
+ participants:
+ Voice::ParticipantTracker
+ .list(@room.id)
+ .map do |user|
+ BasicUserSerializer
+ .new(user, scope: guardian, root: false)
+ .as_json
+ .merge(all_metadata[user.id] || {})
+ end,
+ }
+ end
+
+ def state
+ guardian.ensure_can_join_voice_room!(@room)
+ ensure_participant_session!
+ RateLimiter.new(current_user, "voice-room-state", 40, 10.seconds).performed!
+
+ if STATE_FIELDS.none? { |field| params.key?(field) }
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.state_change_required"))
+ end
+
+ bool = ActiveModel::Type::Boolean.new
+ wants_unmute = params.key?(:muted) && !bool.cast(params[:muted])
+
+ if wants_unmute && @room.stage? && !guardian.can_speak_in_voice_room?(@room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.listeners_cannot_unmute"))
+ end
+
+ wants_camera = params.key?(:video) && bool.cast(params[:video])
+ wants_screen = params.key?(:screen) && bool.cast(params[:screen])
+
+ if wants_camera || wants_screen
+ unless @room.video_allowed? && guardian.can_speak_in_voice_room?(@room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.video_not_allowed"))
+ end
+
+ if video_publisher_count(@room, exclude_user_id: current_user.id) >=
+ SiteSetting.voice_video_max_publishers
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.video_publisher_limit"))
+ end
+ end
+
+ metadata = Voice::ParticipantTracker.get_metadata(@room.id, current_user.id)
+ previous_metadata = metadata.dup
+ metadata[:is_muted] = bool.cast(params[:muted]) if params.key?(:muted)
+ metadata[:is_deafened] = bool.cast(params[:deafened]) if params.key?(:deafened)
+ metadata[:is_video_on] = bool.cast(params[:video]) if params.key?(:video)
+ metadata[:is_screen_sharing] = bool.cast(params[:screen]) if params.key?(:screen)
+ metadata[:watching_video] = bool.cast(params[:watching]) if params.key?(:watching)
+ metadata[:is_transcribing] = bool.cast(params[:transcribing]) if params.key?(:transcribing)
+
+ # A request that changes nothing must not become a full-roster
+ # rebroadcast to every participant.
+ return head :no_content if metadata == previous_metadata
+
+ Voice::ParticipantTracker.update_metadata(@room.id, current_user.id, metadata)
+
+ Voice::RoomBroadcaster.publish_participants(@room)
+
+ head :no_content
+ end
+
+ alias toggle_mute state
+
+ def kick
+ guardian.ensure_can_manage_voice_room!(@room)
+
+ user_id = params.require(:user_id).to_i
+
+ if user_id == current_user.id
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.cannot_kick_self"))
+ end
+
+ if user_id == @room.creator_id
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.cannot_kick_creator"))
+ end
+
+ session = close_session_for(@room.id, user_id)
+ Voice::ParticipantTracker.mark_left(@room.id, user_id)
+ Voice::ParticipantTracker.remove(@room.id, user_id)
+
+ kicked_user = User.find_by(id: user_id)
+ Voice::UserStatusManager.clear_voice_status(kicked_user) if kicked_user
+
+ Voice::BadgeGranterHooks.on_leave(kicked_user, session, room: @room) if kicked_user
+ Voice::RoomBroadcaster.publish_kick(@room, user_id)
+ Voice::RoomBroadcaster.publish_participants(@room)
+
+ # The client-side kicked handler already forces a clean leave; this
+ # additionally evicts the media session from the SFU.
+ Voice::Livekit::RoomServiceClient.remove_participant(@room, user_id)
+
+ head :no_content
+ end
+
+ def flag
+ RateLimiter.new(current_user, "flag_voice_user", 4, 1.minute).performed!
+
+ permitted = params.permit(:user_id, :flag_type_id, :message)
+
+ target_user = User.find_by(id: permitted[:user_id].to_i)
+ raise Discourse::InvalidParameters.new(:user_id) if target_user.blank?
+
+ # A room participant carries no implied context the way a post or chat
+ # message does, so the free-form notify_moderators flag is the only one
+ # that can be raised here.
+ if permitted[:flag_type_id].to_i != ReviewableScore.types[:notify_moderators]
+ raise Discourse::InvalidParameters.new(:flag_type_id)
+ end
+
+ raise Discourse::InvalidParameters.new(:message) if permitted[:message].blank?
+
+ result =
+ Voice::ReviewQueue.new.flag_user(
+ @room,
+ target_user,
+ guardian,
+ permitted[:flag_type_id].to_i,
+ message: permitted[:message],
+ )
+
+ if result[:success]
+ render json: success_json
+ else
+ render_json_error(result[:errors])
+ end
+ end
+
+ def request_to_speak
+ guardian.ensure_can_request_to_speak_in_voice_room!(@room)
+ # The session (not the eventually-consistent roster) is what proves the
+ # user is actually in the call.
+ ensure_participant_session!
+
+ if Voice::ParticipantTracker.raise_hand(@room.id, current_user.id)
+ raised_at =
+ Voice::ParticipantTracker.get_metadata(@room.id, current_user.id)[:hand_raised_at]
+ Voice::RoomBroadcaster.publish_hand_raise(
+ @room,
+ current_user.id,
+ raised: true,
+ raised_at: raised_at,
+ reason: "raised",
+ )
+ Voice::RoomBroadcaster.publish_participants(@room)
+ end
+
+ head :no_content
+ end
+
+ def withdraw_request_to_speak
+ target_id = params[:user_id].present? ? params[:user_id].to_i : current_user.id
+
+ if target_id == current_user.id
+ guardian.ensure_can_join_voice_room!(@room)
+ ensure_participant_session!
+ else
+ # A moderator dismissing someone else's raised hand is a management
+ # action and must not require the moderator to be in the call.
+ guardian.ensure_can_manage_voice_room!(@room)
+ end
+
+ if Voice::ParticipantTracker.lower_hand(@room.id, target_id)
+ reason = target_id == current_user.id ? "withdrawn" : "dismissed"
+ Voice::RoomBroadcaster.publish_hand_raise(@room, target_id, raised: false, reason: reason)
+ Voice::RoomBroadcaster.publish_participants(@room)
+ end
+
+ head :no_content
+ end
+
+ def signal
+ guardian.ensure_can_join_voice_room!(@room)
+ # Room eligibility alone is not enough: signaling authority comes from
+ # the server-attested session minted by join, so an eligible user who
+ # never joined can't reach anyone's media stack.
+ ensure_participant_session!
+
+ RateLimiter.new(
+ current_user,
+ "voice-signals",
+ SIGNAL_REQUESTS_PER_USER,
+ 10.seconds,
+ ).performed!
+
+ # Defense in depth: LiveKit rooms never exchange WebRTC signals.
+ if Voice::ParticipantTracker.pinned_transport(@room.id) == "livekit"
+ return(render_json_error(I18n.t("voice.errors.livekit_no_signaling"), status: 422))
+ end
+
+ raw_payload = params[:payload]
+ raw_payload = raw_payload.to_unsafe_h if raw_payload.respond_to?(:to_unsafe_h)
+ if raw_payload.blank?
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.missing_payload"))
+ end
+
+ messages = Voice::SignalValidator.parse!(raw_payload, room: @room)
+ if messages.blank?
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.missing_payload"))
+ end
+
+ total_events = messages.sum { |message| message[:events].size }
+ Voice::ControlPlaneLimiter.perform!(
+ "signal-events:user:#{current_user.id}",
+ limit: SIGNAL_EVENTS_PER_USER_PER_MINUTE,
+ period: 1.minute,
+ weight: total_events,
+ )
+ Voice::ControlPlaneLimiter.perform!(
+ "signal-events:room:#{@room.id}",
+ limit: SIGNAL_EVENTS_PER_ROOM_PER_MINUTE,
+ period: 1.minute,
+ weight: total_events,
+ )
+
+ relay = Voice::SignalRelay.new(@room)
+ messages.each do |message|
+ relay.publish!(
+ from: current_user,
+ recipient_id: message[:recipient_id],
+ events: message[:events],
+ )
+ end
+
+ head :no_content
+ end
+
+ # Returns the room's current live chat session (linked channel and active
+ # thread) so the panel can render it. Does not create or change anything.
+ def chat_session
+ ensure_chat_available!
+ render json: Voice::ChatSession.state(@room)
+ end
+
+ # Prepares the room's chat session for the caller: rolls a stale session
+ # over and follows them on the linked channel so chat's own message
+ # endpoints accept their posts. Never creates a thread — that only happens
+ # with the session's first message (see #chat_message); every later message
+ # goes through chat's regular API, not through Voice.
+ def ensure_chat_session
+ ensure_chat_available!
+ render json: Voice::ChatSession.start!(@room, current_user)
+ end
+
+ # Posts the session's opening message, creating the thread it roots. Only
+ # called by a panel that sees no live thread; once one exists, messages go
+ # through chat's own API instead.
+ def chat_message
+ ensure_chat_available!
+
+ text = params.require(:message).to_s
+ # We post through Chat::CreateMessage directly, which bypasses the
+ # per-user flood limit + auto-silence that chat enforces in its own
+ # controller — apply it here so this endpoint isn't a way around it.
+ ::Chat::MessageRateLimiter.run!(current_user)
+ render json: Voice::ChatSession.post_message!(@room, current_user, text)
+ rescue Voice::ChatSession::Error => e
+ # The chat plugin rejected the message for a reason worth showing (a
+ # duplicate, a too-long message, threading disabled, …) — surface it
+ # instead of the generic 403 that an access error would produce.
+ render_json_error(e.message, status: 422)
+ end
+
+ private
+
+ def ensure_participant_session!
+ if Voice::ParticipantTracker.valid_participant_session?(
+ @room.id,
+ current_user.id,
+ params[:participant_session_id],
+ )
+ return
+ end
+
+ # Sustained probing with a missing or stale session is cut off before it
+ # can accumulate into free Redis/roster work.
+ RateLimiter.new(current_user, "voice-session-denied", 30, 1.minute).performed!
+
+ raise Discourse::InvalidAccess.new(
+ :voice_participant_session_required,
+ nil,
+ custom_message: "voice.errors.participant_session_required",
+ )
+ end
+
+ def repeat_join?
+ params[:participant_session_id].present? &&
+ Voice::ParticipantTracker.valid_participant_session?(
+ @room.id,
+ current_user.id,
+ params[:participant_session_id],
+ ) && Voice::ParticipantTracker.user_ids(@room.id).include?(current_user.id)
+ end
+
+ def mark_invitation_notifications_read!
+ notification_ids =
+ current_user
+ .notifications
+ .where(notification_type: Notification.types[:voice_invitation], read: false)
+ .select { |notification| notification.data_hash[:room_id] == @room.id }
+ .map(&:id)
+ return if notification_ids.empty?
+
+ Notification.read(current_user, notification_ids)
+ current_user.publish_notifications_state
+ end
+
+ # Broad rescue is deliberate: a LiveKit problem must surface as the 503
+ # handled by the callers, never as an opaque 500.
+ def mint_livekit_payload
+ token = Voice::Livekit.mint_token(user: current_user, room: @room, guardian: guardian)
+ { url: SiteSetting.voice_livekit_url, token: token }
+ rescue StandardError => e
+ Rails.logger.error(
+ "[voice-livekit] token mint failed for room #{@room.id}: #{e.class} #{e.message}",
+ )
+ nil
+ end
+
+ def ensure_chat_available!
+ guardian.ensure_can_join_voice_room!(@room)
+ unless Voice::ChatSession.available_for?(@room, guardian)
+ raise Discourse::InvalidAccess.new(
+ :voice_chat_unavailable,
+ nil,
+ custom_message: "voice.errors.chat_unavailable",
+ )
+ end
+ if Voice::ParticipantTracker.user_ids(@room.id).exclude?(current_user.id)
+ raise Discourse::InvalidAccess.new(
+ :voice_chat_requires_presence,
+ nil,
+ custom_message: "voice.errors.chat_requires_presence",
+ )
+ end
+ end
+
+ def refresh_participant_statuses(room)
+ Voice::ParticipantTracker
+ .user_ids(room.id)
+ .each do |uid|
+ user = User.find_by(id: uid)
+ next unless user
+ next unless Voice::UserStatusManager.voice_status_active?(user)
+ Voice::UserStatusManager.set_voice_status(user, room)
+ end
+ end
+
+ def close_session_for(room_id, user_id)
+ metadata = Voice::ParticipantTracker.get_metadata(room_id, user_id)
+ return unless metadata[:session_id]
+
+ session = Voice::Session.find_by(id: metadata[:session_id])
+ session&.close!
+ session
+ end
+
+ def video_publisher_count(room, exclude_user_id: nil)
+ active_ids = Voice::ParticipantTracker.user_ids(room.id)
+ all_metadata = Voice::ParticipantTracker.get_all_metadata(room.id)
+
+ active_ids.count do |user_id|
+ next false if user_id == exclude_user_id
+ metadata = all_metadata[user_id] || {}
+ metadata[:is_video_on] || metadata[:is_screen_sharing]
+ end
+ end
+
+ def room_params
+ permitted =
+ params.require(:room).permit(
+ :name,
+ :slug,
+ :description,
+ :public,
+ :max_participants,
+ :room_type,
+ :video_enabled,
+ :livekit_enabled,
+ :chat_channel_id,
+ :chat_idle_minutes,
+ :max_quality_profile,
+ )
+ if permitted.key?(:room_type)
+ permitted[:room_type] = Voice::Room.room_type_from_name!(permitted[:room_type])
+ end
+ if permitted.key?(:max_quality_profile)
+ permitted[:max_quality_profile] = Voice::Room::QUALITY_PROFILES[
+ permitted[:max_quality_profile].to_s
+ ]
+ end
+ permitted
+ end
+
+ def load_room
+ @room =
+ Voice::Room.find_by(id: params[:id]) ||
+ Voice::Room.find_by!(slug: params[:id] || params[:slug])
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/regular/voice_livekit_probe.rb b/plugins/voice/app/jobs/regular/voice_livekit_probe.rb
new file mode 100644
index 00000000000..eff3cdbbca8
--- /dev/null
+++ b/plugins/voice/app/jobs/regular/voice_livekit_probe.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Jobs
+ # One-shot connectivity probe enqueued whenever a LiveKit setting changes,
+ # so a bad URL or key pair surfaces on the admin status panel (and in the
+ # logs) within seconds of saving — not at the first user's failed join.
+ class VoiceLivekitProbe < ::Jobs::Base
+ sidekiq_options retry: false
+
+ def execute(args)
+ unless ::Voice::Livekit.configured?
+ # Deconfiguring is also a settings change: drop the stale result
+ # instead of reporting the health of a server we no longer use.
+ ::Voice::Livekit::HealthCheck.clear_probe!
+ return
+ end
+
+ result = ::Voice::Livekit::HealthCheck.connectivity_check
+ ::Voice::Livekit::HealthCheck.store_probe!(result)
+
+ if !result[:ok]
+ errors = [result.dig(:token, :error), result.dig(:server, :error)].compact.join("; ")
+ Rails.logger.warn("[voice-livekit] connectivity probe failed: #{errors}")
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/publish_room_participants.rb b/plugins/voice/app/jobs/scheduled/publish_room_participants.rb
new file mode 100644
index 00000000000..006a8210d4b
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/publish_room_participants.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module Jobs
+ class PublishRoomParticipants < ::Jobs::Scheduled
+ every 1.minute
+ sidekiq_options retry: false
+ cluster_concurrency 1
+
+ # Backstop that re-asserts full participant state so clients converge even
+ # after missing a broadcast (page-load races, sleep/resume, message-bus
+ # backlog gaps). It iterates rooms with recent membership activity rather
+ # than scanning for participants keys in Redis: an emptied room's key is
+ # gone, but its (empty) state still needs re-broadcasting for a while,
+ # otherwise a single missed leave message shows ghosts until reload.
+ def execute(args)
+ return unless ::Voice.enabled?
+
+ room_ids = ::Voice::ParticipantTracker.recently_active_room_ids
+
+ # Auto voice statuses have no ends_at, so a lapsed heartbeat must drop
+ # the status the same way it drops the roster entry. Live-anywhere is
+ # the keep criterion: a user mid-move between rooms is still live.
+ live_user_ids =
+ room_ids.flat_map { |room_id| ::Voice::ParticipantTracker.user_ids(room_id) }.uniq
+ ::Voice::UserStatusManager.clear_stale_statuses(live_user_ids)
+
+ return if room_ids.empty?
+
+ ::Voice::Room
+ .where(id: room_ids)
+ .find_each do |room|
+ # Backstop for the pin-clear on last leave: a room that emptied
+ # without one (crashed clients, missed leave) must not hold its
+ # transport for the next call.
+ if ::Voice::ParticipantTracker.user_ids(room.id).empty?
+ # No-op once the pin is gone, so an emptied room is deleted from
+ # the SFU at most once, on the sweep that clears its pin.
+ ::Voice::Livekit::RoomServiceClient.delete_room(room)
+ ::Voice::ParticipantTracker.clear_transport_pin(room.id)
+ end
+ ::Voice::RoomBroadcaster.publish_participants(room)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/voice/cleanup_ephemeral_rooms.rb b/plugins/voice/app/jobs/scheduled/voice/cleanup_ephemeral_rooms.rb
new file mode 100644
index 00000000000..4d881556270
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/voice/cleanup_ephemeral_rooms.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Voice
+ class CleanupEphemeralRooms < ::Jobs::Scheduled
+ every 5.minutes
+
+ def execute(_args)
+ return unless SiteSetting.voice_enabled
+
+ ::Voice::EphemeralRoomManager.cleanup!
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/voice/close_orphaned_sessions.rb b/plugins/voice/app/jobs/scheduled/voice/close_orphaned_sessions.rb
new file mode 100644
index 00000000000..848c297dfc0
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/voice/close_orphaned_sessions.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Voice
+ class CloseOrphanedSessions < ::Jobs::Scheduled
+ every 5.minutes
+
+ def execute(_args)
+ return unless SiteSetting.voice_enabled && SiteSetting.voice_analytics_enabled
+
+ participant_cache = {}
+
+ ::Voice::Session.orphaned.find_each do |session|
+ participant_ids =
+ participant_cache[session.room_id] ||= ::Voice::ParticipantTracker.user_ids(
+ session.room_id,
+ )
+ next if participant_ids.include?(session.user_id)
+
+ left_at =
+ ::Voice::ParticipantTracker.last_heartbeat_at(session.room_id, session.user_id) ||
+ Time.current
+
+ session.close!(at: left_at)
+ ::Voice::ParticipantTracker.remove(session.room_id, session.user_id)
+
+ user = User.find_by(id: session.user_id)
+ room = ::Voice::Room.find_by(id: session.room_id)
+ ::Voice::BadgeGranterHooks.on_leave(user, session, room: room) if user && room
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/voice/purge_old_sessions.rb b/plugins/voice/app/jobs/scheduled/voice/purge_old_sessions.rb
new file mode 100644
index 00000000000..dcc654ade84
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/voice/purge_old_sessions.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Voice
+ class PurgeOldSessions < ::Jobs::Scheduled
+ every 1.day
+
+ def execute(_args)
+ return unless SiteSetting.voice_enabled
+
+ days = SiteSetting.voice_session_retention_days
+ return if days <= 0
+
+ cutoff = days.days.ago
+ ::Voice::Session.where("created_at < ?", cutoff).in_batches(of: 1000).delete_all
+ ::Voice::CoPresence.where("date < ?", cutoff.to_date).in_batches(of: 1000).delete_all
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/voice/reconcile_recordings.rb b/plugins/voice/app/jobs/scheduled/voice/reconcile_recordings.rb
new file mode 100644
index 00000000000..a94c6a79ef4
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/voice/reconcile_recordings.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Voice
+ # Delivery backstop for call recordings: webhooks are the fast path, but
+ # they are optional server configuration — this sweep resolves any
+ # recording still marked live by polling the Egress service, so the
+ # requester's PM and the admin log never depend on webhooks being set up.
+ class ReconcileRecordings < ::Jobs::Scheduled
+ every 15.minutes
+ sidekiq_options retry: false
+ cluster_concurrency 1
+
+ def execute(_args)
+ return unless SiteSetting.voice_enabled
+ return unless SiteSetting.voice_livekit_recording_enabled
+ return unless ::Voice::Livekit.configured?
+ # The common case is no unresolved recordings — skip without HTTP.
+ return unless ::Voice::Recording.recording.exists?
+
+ ::Voice::RecordingManager.reconcile_pending!
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/jobs/scheduled/voice/update_co_presence.rb b/plugins/voice/app/jobs/scheduled/voice/update_co_presence.rb
new file mode 100644
index 00000000000..c7b9e64d86c
--- /dev/null
+++ b/plugins/voice/app/jobs/scheduled/voice/update_co_presence.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Voice
+ class UpdateCoPresence < ::Jobs::Scheduled
+ every 5.minutes
+
+ JOB_INTERVAL_SECONDS = 300
+ GAP_THRESHOLD = 10.minutes
+
+ def execute(_args)
+ return unless SiteSetting.voice_enabled && SiteSetting.voice_analytics_enabled
+
+ each_active_room do |room_id|
+ # Bounded by the site capacity ceiling even if Redis holds strays,
+ # since the pair count below grows quadratically.
+ user_ids =
+ ::Voice::ParticipantTracker
+ .user_ids(room_id)
+ .sort
+ .first(SiteSetting.voice_max_room_participants)
+ next if user_ids.size < 2
+
+ today = Date.today
+
+ # Block form: iterates the pairs without materializing them all.
+ user_ids.combination(2) { |user_a, user_b| upsert_co_presence(user_a, user_b, today) }
+ end
+ end
+
+ private
+
+ def each_active_room(&block)
+ pattern = "#{::Voice::ParticipantTracker::KEY_NAMESPACE}:*:participants"
+ Discourse
+ .redis
+ .scan_each(match: pattern) do |key|
+ yield Regexp.last_match(1).to_i if key =~ /voice:room:(\d+):participants/
+ end
+ end
+
+ def upsert_co_presence(user_a, user_b, date)
+ record =
+ ::Voice::CoPresence.find_or_initialize_by(
+ user_id_1: user_a,
+ user_id_2: user_b,
+ date: date,
+ )
+
+ gap = record.new_record? || record.updated_at < GAP_THRESHOLD.ago
+
+ record.total_seconds += JOB_INTERVAL_SECONDS
+ record.session_count += 1 if gap
+ record.save!
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/models/reviewable_voice_user.rb b/plugins/voice/app/models/reviewable_voice_user.rb
new file mode 100644
index 00000000000..945b6fcdbb9
--- /dev/null
+++ b/plugins/voice/app/models/reviewable_voice_user.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+class ReviewableVoiceUser < Reviewable
+ include ReviewableActionBuilder
+
+ def serializer
+ ReviewableVoiceUserSerializer
+ end
+
+ def self.action_aliases
+ { agree_and_suspend: :agree_and_keep, agree_and_silence: :agree_and_keep }
+ end
+
+ def session
+ @session ||= target || Voice::Session.find_by(id: target_id)
+ end
+
+ def flagged_by_user_ids
+ @flagged_by_user_ids ||= reviewable_scores.map(&:user_id)
+ end
+
+ # Core assumes flag reviewables hang off a post.
+ def post
+ nil
+ end
+
+ def build_combined_actions(actions, guardian, _args)
+ return unless pending?
+
+ agree =
+ actions.add_bundle("#{id}-agree", icon: "thumbs-up", label: "reviewables.actions.agree.title")
+ build_action(actions, :agree_and_keep, icon: "thumbs-up", bundle: agree)
+
+ if guardian.can_suspend?(target_created_by)
+ build_action(
+ actions,
+ :agree_and_suspend,
+ icon: "ban",
+ bundle: agree,
+ client_action: "suspend",
+ )
+ build_action(
+ actions,
+ :agree_and_silence,
+ icon: "microphone-slash",
+ bundle: agree,
+ client_action: "silence",
+ )
+ end
+
+ build_action(actions, :disagree, icon: "thumbs-down")
+ build_action(actions, :ignore, icon: "xmark")
+ end
+
+ def perform_agree_and_keep(_performed_by, _args)
+ create_result(:success, :approved) do |result|
+ result.update_flag_stats = { status: :agreed, user_ids: flagged_by_user_ids }
+ result.recalculate_score = true
+ end
+ end
+
+ def perform_disagree(_performed_by, _args)
+ create_result(:success, :rejected) do |result|
+ result.update_flag_stats = { status: :disagreed, user_ids: flagged_by_user_ids }
+ result.recalculate_score = true
+ end
+ end
+
+ def perform_ignore(_performed_by, _args)
+ create_result(:success, :ignored) do |result|
+ result.update_flag_stats = { status: :ignored, user_ids: flagged_by_user_ids }
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: reviewables
+#
+# id :bigint not null, primary key
+# force_review :boolean default(FALSE), not null
+# latest_score :datetime
+# payload :json
+# potential_spam :boolean default(FALSE), not null
+# potentially_illegal :boolean default(FALSE)
+# reject_reason :text
+# reviewable_by_moderator :boolean default(FALSE), not null
+# score :float default(0.0), not null
+# status :integer default("pending"), not null
+# target_type :string
+# type :string not null
+# type_source :string default("unknown"), not null
+# version :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# category_id :integer
+# created_by_id :integer not null
+# target_created_by_id :integer
+# target_id :integer
+# topic_id :integer
+#
+# Indexes
+#
+# idx_reviewables_score_desc_created_at_desc (score,created_at)
+# index_reviewables_on_reviewable_by_group_id (reviewable_by_group_id)
+# index_reviewables_on_status_and_created_at (status,created_at)
+# index_reviewables_on_status_and_score (status,score)
+# index_reviewables_on_status_and_type (status,type)
+# index_reviewables_on_target_created_by_id (target_created_by_id)
+# index_reviewables_on_target_id_where_post_type_eq_post (target_id) WHERE ((target_type)::text = 'Post'::text)
+# index_reviewables_on_topic_id_and_status_and_created_by_id (topic_id,status,created_by_id)
+# index_reviewables_on_type_and_target_id (type,target_id) UNIQUE
+#
diff --git a/plugins/voice/app/models/voice/co_presence.rb b/plugins/voice/app/models/voice/co_presence.rb
new file mode 100644
index 00000000000..e6456003201
--- /dev/null
+++ b/plugins/voice/app/models/voice/co_presence.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module Voice
+ class CoPresence < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}co_presences"
+
+ belongs_to :user_1, class_name: "User"
+ belongs_to :user_2, class_name: "User"
+
+ validates :user_id_1, comparison: { less_than: :user_id_2 }
+
+ def self.top_contacts_for(user_id, since:, limit: 10)
+ uid = user_id.to_i
+ where("(user_id_1 = :uid OR user_id_2 = :uid) AND date >= :since", uid: uid, since: since)
+ .select(
+ Arel.sql("CASE WHEN user_id_1 = #{uid} THEN user_id_2 ELSE user_id_1 END AS contact_id"),
+ Arel.sql("SUM(total_seconds) AS total_seconds"),
+ Arel.sql("SUM(session_count) AS session_count"),
+ Arel.sql("MAX(date) AS last_co_present_on"),
+ )
+ .group(Arel.sql("contact_id"))
+ .order(Arel.sql("total_seconds DESC"))
+ .limit(limit)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_co_presences
+#
+# id :bigint not null, primary key
+# date :date not null
+# session_count :integer default(0), not null
+# total_seconds :integer default(0), not null
+# user_id_1 :integer not null
+# user_id_2 :integer not null
+# created_at :datetime not null
+# updated_at :datetime not null
+#
+# Indexes
+#
+# idx_voice_co_presences_unique (user_id_1,user_id_2,date) UNIQUE
+# index_voice_co_presences_on_user_id_1_and_date (user_id_1,date)
+# index_voice_co_presences_on_user_id_2_and_date (user_id_2,date)
+#
diff --git a/plugins/voice/app/models/voice/invite.rb b/plugins/voice/app/models/voice/invite.rb
new file mode 100644
index 00000000000..d4f64586c6f
--- /dev/null
+++ b/plugins/voice/app/models/voice/invite.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module Voice
+ class Invite < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}invites"
+
+ SOURCES = { notification: 0, link: 1 }
+
+ # History rows, like sessions: they outlive their room and users.
+ belongs_to :room, optional: true
+ belongs_to :user, optional: true
+ belongs_to :invited_by, class_name: "User", optional: true
+
+ validates :user_id, comparison: { other_than: :invited_by_id }
+
+ scope :redeemed, -> { where.not(redeemed_at: nil) }
+
+ # A join that followed an invite — a notification and a shared link both
+ # carry the inviter's username. Returns the invite only on its first
+ # redemption, so the inviter is credited at most once per invitee per room.
+ def self.redeem!(room:, user:, inviter_username:)
+ inviter = User.find_by(username_lower: inviter_username.to_s.downcase)
+ return if inviter.nil? || inviter.id == user.id
+
+ invite =
+ create_or_find_by(room_id: room.id, user_id: user.id, invited_by_id: inviter.id) do |i|
+ i.source = SOURCES[:link]
+ end
+ return if invite.redeemed_at.present?
+
+ invite.update!(redeemed_at: Time.current)
+ invite
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_invites
+#
+# id :bigint not null, primary key
+# redeemed_at :datetime
+# source :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# invited_by_id :bigint not null
+# room_id :bigint not null
+# user_id :bigint not null
+#
+# Indexes
+#
+# idx_voice_invites_redeemed (invited_by_id,user_id) WHERE (redeemed_at IS NOT NULL)
+# index_voice_invites_on_room_id_and_user_id_and_invited_by_id (room_id,user_id,invited_by_id) UNIQUE
+# index_voice_invites_on_user_id_and_room_id (user_id,room_id)
+#
diff --git a/plugins/voice/app/models/voice/recording.rb b/plugins/voice/app/models/voice/recording.rb
new file mode 100644
index 00000000000..4f1ce027fcd
--- /dev/null
+++ b/plugins/voice/app/models/voice/recording.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module Voice
+ # Durable log of a call recording, one row per LiveKit egress. The Redis
+ # recording state dies with the room instance, but the egress_ended webhook
+ # — which carries the file's final location — usually arrives after that,
+ # so delivery (the requester's PM, the admin listing) needs this row.
+ class Recording < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}recordings"
+
+ enum :status, { recording: 0, completed: 1, failed: 2 }
+
+ belongs_to :room, class_name: "Voice::Room"
+ belongs_to :started_by, class_name: "User"
+
+ validates :egress_id, presence: true, uniqueness: true
+ validates :filepath, presence: true
+
+ # The URL when the egress uploaded to cloud storage, otherwise the path
+ # on the recording server's own storage.
+ def link_or_path
+ location.presence || filepath
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_recordings
+#
+# id :bigint not null, primary key
+# duration_ms :bigint
+# ended_at :datetime
+# filename :string
+# filepath :string not null
+# location :string
+# size_bytes :bigint
+# started_at :datetime not null
+# status :integer default("recording"), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# egress_id :string not null
+# room_id :bigint not null
+# started_by_id :bigint not null
+#
+# Indexes
+#
+# index_voice_recordings_on_egress_id (egress_id) UNIQUE
+# index_voice_recordings_on_room_id_and_started_at (room_id,started_at)
+#
diff --git a/plugins/voice/app/models/voice/room.rb b/plugins/voice/app/models/voice/room.rb
new file mode 100644
index 00000000000..a69f04e4907
--- /dev/null
+++ b/plugins/voice/app/models/voice/room.rb
@@ -0,0 +1,196 @@
+# frozen_string_literal: true
+
+module Voice
+ class Room < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}rooms"
+
+ # TODO(02-2027): Remove this line
+ self.ignored_columns += %i[chat_thread_title_template]
+
+ ROOM_TYPE_OPEN = 0
+ ROOM_TYPE_STAGE = 1
+ ROOM_TYPES = { "open" => ROOM_TYPE_OPEN, "stage" => ROOM_TYPE_STAGE }.freeze
+
+ # nil means "no room-level cap" — the site-setting caps still apply.
+ QUALITY_PROFILES = { "standard" => 0, "high" => 1, "maximum" => 2 }.freeze
+
+ belongs_to :creator, class_name: "User"
+ has_many :room_memberships, class_name: "Voice::RoomMembership", dependent: :destroy
+ has_many :members, through: :room_memberships, source: :user
+ has_many :recordings, class_name: "Voice::Recording", dependent: :delete_all
+
+ validates :name, presence: true, length: { maximum: 80 }
+ validates :slug, presence: true, uniqueness: true
+ validates :room_type, inclusion: { in: ROOM_TYPES.values }
+ validates :max_participants,
+ numericality: {
+ only_integer: true,
+ allow_nil: true,
+ greater_than_or_equal_to: 2,
+ less_than_or_equal_to: ->(r) { r.stage? ? 200 : 50 },
+ }
+ validates :max_quality_profile, inclusion: { in: QUALITY_PROFILES.values }, allow_nil: true
+ validates :chat_idle_minutes,
+ numericality: {
+ only_integer: true,
+ greater_than_or_equal_to: 2,
+ less_than_or_equal_to: 1440,
+ }
+ validate :chat_channel_must_support_threading, if: :chat_channel_id_changed?
+
+ before_validation :ensure_slug
+ before_save :cook_description
+ after_commit :ensure_creator_membership, on: :create
+
+ scope :public_rooms, -> { where(public: true) }
+ scope :persistent, -> { where(ephemeral: false) }
+ scope :ephemeral, -> { where(ephemeral: true) }
+
+ # Strict by design: the column is an integer, so letting an unknown name
+ # through means AR casts it with to_i and silently produces an open room.
+ def self.room_type_from_name!(name)
+ ROOM_TYPES.fetch(name.to_s) { raise Discourse::InvalidParameters.new(:room_type) }
+ end
+
+ def open?
+ room_type == ROOM_TYPE_OPEN
+ end
+
+ def stage?
+ room_type == ROOM_TYPE_STAGE
+ end
+
+ def room_type_name
+ ROOM_TYPES.key(room_type) || "open"
+ end
+
+ def max_quality_profile_name
+ QUALITY_PROFILES.key(max_quality_profile)
+ end
+
+ # The hard presence cap: a room-level limit can lower the site ceiling,
+ # never raise it. Enforced atomically when presence is established.
+ def effective_max_participants
+ [max_participants, SiteSetting.voice_max_room_participants].compact.min
+ end
+
+ # Room-level capability only; per-user publish rights are guardian-driven
+ # (stage listeners never publish even when this is true).
+ def video_allowed?
+ SiteSetting.voice_video_enabled && video_enabled
+ end
+
+ def moderator_ids
+ room_memberships.moderator.pluck(:user_id)
+ end
+
+ def member_ids
+ room_memberships.pluck(:user_id)
+ end
+
+ def message_bus_targets
+ public? ? Voice.public_room_message_bus_targets : { user_ids: member_ids }
+ end
+
+ def chat_linked?
+ chat_channel_id.present?
+ end
+
+ # Memoized (keyed on the current id, so an in-flight reassignment isn't
+ # served a stale channel): serialization consults the channel several
+ # times per room, which would otherwise be a query each.
+ def chat_channel
+ return nil unless chat_channel_id && defined?(::Chat)
+ if @chat_channel_for_id != chat_channel_id
+ @chat_channel_for_id = chat_channel_id
+ @chat_channel = ::Chat::Channel.find_by(id: chat_channel_id)
+ end
+ @chat_channel
+ end
+
+ def reload(...)
+ @chat_channel_for_id = @chat_channel = nil
+ super
+ end
+
+ def chat_idle_seconds
+ [chat_idle_minutes || 15, 2].max * 60
+ end
+
+ private
+
+ def ensure_slug
+ if slug.present?
+ # A user-provided slug is normalized rather than trusted verbatim;
+ # rejected here (instead of silently regenerating from the name) so
+ # the author learns their input was unusable.
+ self.slug = Slug.for(slug, "")
+ errors.add(:slug, :invalid) if slug.blank?
+ return
+ end
+
+ return if name.blank?
+
+ # Ephemeral rooms are created programmatically with generic names
+ # ("Call", an event title), so a bare Slug.for would collide with the
+ # persistent room that already owns that slug.
+ self.slug = ephemeral? ? "#{Slug.for(name)}-#{SecureRandom.hex(4)}" : Slug.for(name)
+ end
+
+ def cook_description
+ self.cooked_description = (PrettyText.cook(description) if description.present?)
+ end
+
+ def ensure_creator_membership
+ room_memberships.find_or_create_by!(user: creator) do |membership|
+ membership.role = Voice::RoomMembership::ROLE_MODERATOR
+ end
+ end
+
+ # Voice never edits chat channels itself (that would silently change a
+ # setting for everyone else using it, on behalf of a user who may not have
+ # permission to edit that channel at all) — a channel has to already have
+ # threading enabled before it can be linked.
+ def chat_channel_must_support_threading
+ return if chat_channel_id.blank? || !defined?(::Chat)
+
+ channel = chat_channel
+ if channel.nil?
+ errors.add(:chat_channel_id, "must reference an existing chat channel")
+ elsif !channel.threading_enabled?
+ errors.add(:chat_channel_id, "must have threading enabled")
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_rooms
+#
+# id :bigint not null, primary key
+# chat_idle_minutes :integer default(15), not null
+# cooked_description :text
+# description :text
+# ephemeral :boolean default(FALSE), not null
+# last_occupied_at :datetime
+# livekit_enabled :boolean default(FALSE), not null
+# max_participants :integer
+# max_quality_profile :integer
+# name :string not null
+# public :boolean default(FALSE), not null
+# room_type :integer default(0), not null
+# slug :string not null
+# video_enabled :boolean default(TRUE), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# chat_channel_id :bigint
+# creator_id :bigint not null
+#
+# Indexes
+#
+# index_voice_rooms_on_chat_channel_id (chat_channel_id)
+# index_voice_rooms_on_creator_id (creator_id)
+# index_voice_rooms_on_ephemeral (id) WHERE ephemeral
+# index_voice_rooms_on_slug (slug) UNIQUE
+#
diff --git a/plugins/voice/app/models/voice/room_membership.rb b/plugins/voice/app/models/voice/room_membership.rb
new file mode 100644
index 00000000000..70bef8ce334
--- /dev/null
+++ b/plugins/voice/app/models/voice/room_membership.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomMembership < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}room_memberships"
+
+ belongs_to :room, class_name: "Voice::Room"
+ belongs_to :user
+
+ ROLE_PARTICIPANT = 0
+ ROLE_MODERATOR = 1
+ ROLE_SPEAKER = 2
+ ROLES = {
+ "participant" => ROLE_PARTICIPANT,
+ "moderator" => ROLE_MODERATOR,
+ "speaker" => ROLE_SPEAKER,
+ }.freeze
+
+ scope :moderator, -> { where(role: ROLE_MODERATOR) }
+ scope :speaker, -> { where(role: ROLE_SPEAKER) }
+
+ def moderator?
+ role == ROLE_MODERATOR
+ end
+
+ def participant?
+ role == ROLE_PARTICIPANT
+ end
+
+ def speaker?
+ role == ROLE_SPEAKER
+ end
+
+ def can_speak?
+ moderator? || speaker?
+ end
+
+ def role_name
+ ROLES.key(role) || "participant"
+ end
+
+ def self.role_value(key)
+ return ROLE_PARTICIPANT if key.blank?
+
+ ROLES[key.to_s] || ROLE_PARTICIPANT
+ end
+
+ validates :room_id, presence: true
+ validates :user_id, presence: true, uniqueness: { scope: :room_id }
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_room_memberships
+#
+# id :bigint not null, primary key
+# role :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# room_id :bigint not null
+# user_id :bigint not null
+#
+# Indexes
+#
+# idx_voice_room_memberships_on_room_and_user (room_id,user_id) UNIQUE
+# index_voice_room_memberships_on_room_id (room_id)
+# index_voice_room_memberships_on_user_id (user_id)
+#
+# Foreign Keys
+#
+# fk_rails_... (room_id => voice_rooms.id)
+#
diff --git a/plugins/voice/app/models/voice/session.rb b/plugins/voice/app/models/voice/session.rb
new file mode 100644
index 00000000000..e2746767110
--- /dev/null
+++ b/plugins/voice/app/models/voice/session.rb
@@ -0,0 +1,95 @@
+# frozen_string_literal: true
+
+module Voice
+ class Session < ActiveRecord::Base
+ self.table_name = "#{Voice.table_name_prefix}sessions"
+
+ # optional: sessions are history and outlive both their room's and their
+ # user's deletion — close! must still work on a session whose room or
+ # user is gone.
+ belongs_to :user, optional: true
+ belongs_to :room, class_name: "Voice::Room", optional: true
+
+ scope :orphaned, -> { where(left_at: nil) }
+
+ def close!(at: Time.current)
+ update!(left_at: at)
+ end
+
+ # A session's recorded end can be far later than the user's actual leave —
+ # the orphan sweep stamps left_at when it finally runs, and until then an
+ # abandoned session is open-ended — so any single shared interval is
+ # capped at a plausible call length to keep phantom days out of the sums.
+ MAX_COMPANION_OVERLAP_SECONDS = 12.hours.to_i
+
+ # Matches the co-presence badge threshold: less than five minutes together
+ # is a brush, not a shared session worth suggesting.
+ MIN_COMPANION_OVERLAP_SECONDS = 5.minutes.to_i
+
+ # People who shared time in this room with the user, most time together
+ # first. Overlap is computed pairwise from session intervals; a session
+ # still in progress counts up to now.
+ def self.top_room_companions_for(user_id, room_id, since:, limit: 10)
+ overlap_seconds = <<~SQL
+ LEAST(
+ EXTRACT(
+ EPOCH FROM (
+ LEAST(COALESCE(mine.left_at, CURRENT_TIMESTAMP), COALESCE(theirs.left_at, CURRENT_TIMESTAMP)) -
+ GREATEST(mine.joined_at, theirs.joined_at)
+ )
+ ),
+ :max_overlap
+ )
+ SQL
+
+ DB.query(
+ <<~SQL,
+ SELECT theirs.user_id AS companion_id,
+ SUM(#{overlap_seconds})::bigint AS total_seconds,
+ MAX(GREATEST(mine.joined_at, theirs.joined_at)) AS last_together_at
+ FROM voice_sessions mine
+ JOIN voice_sessions theirs
+ ON theirs.room_id = mine.room_id
+ AND theirs.user_id <> mine.user_id
+ AND theirs.joined_at < COALESCE(mine.left_at, CURRENT_TIMESTAMP)
+ AND mine.joined_at < COALESCE(theirs.left_at, CURRENT_TIMESTAMP)
+ WHERE mine.user_id = :user_id
+ AND mine.room_id = :room_id
+ AND mine.joined_at >= :since
+ GROUP BY theirs.user_id
+ HAVING SUM(#{overlap_seconds}) >= :min_total
+ ORDER BY total_seconds DESC, last_together_at DESC
+ LIMIT :limit
+ SQL
+ user_id: user_id.to_i,
+ room_id: room_id.to_i,
+ since: since,
+ limit: limit,
+ max_overlap: MAX_COMPANION_OVERLAP_SECONDS,
+ min_total: MIN_COMPANION_OVERLAP_SECONDS,
+ )
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: voice_sessions
+#
+# id :bigint not null, primary key
+# joined_at :datetime not null
+# left_at :datetime
+# created_at :datetime not null
+# updated_at :datetime not null
+# room_id :bigint not null
+# user_id :bigint not null
+#
+# Indexes
+#
+# idx_voice_sessions_orphaned (left_at) WHERE (left_at IS NULL)
+# index_voice_sessions_on_room_id (room_id)
+# index_voice_sessions_on_room_id_and_joined_at (room_id,joined_at)
+# index_voice_sessions_on_user_id (user_id)
+# index_voice_sessions_on_user_id_and_joined_at (user_id,joined_at)
+# index_voice_sessions_on_user_id_and_room_id_and_joined_at (user_id,room_id,joined_at)
+#
diff --git a/plugins/voice/app/serializers/reviewable_voice_user_serializer.rb b/plugins/voice/app/serializers/reviewable_voice_user_serializer.rb
new file mode 100644
index 00000000000..469dd93e4e5
--- /dev/null
+++ b/plugins/voice/app/serializers/reviewable_voice_user_serializer.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+require_dependency "reviewable_serializer"
+
+class ReviewableVoiceUserSerializer < ReviewableSerializer
+ payload_attributes :message, :room_id, :room_name, :room_slug
+ attributes :room_url
+
+ def created_from_flag?
+ true
+ end
+
+ def room_url
+ "/voice/r/#{object.payload["room_slug"]}"
+ end
+end
diff --git a/plugins/voice/app/serializers/voice/admin_recording_serializer.rb b/plugins/voice/app/serializers/voice/admin_recording_serializer.rb
new file mode 100644
index 00000000000..38a6887ed6c
--- /dev/null
+++ b/plugins/voice/app/serializers/voice/admin_recording_serializer.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminRecordingSerializer < ApplicationSerializer
+ attributes :id,
+ :room_id,
+ :room_name,
+ :egress_id,
+ :status,
+ :filepath,
+ :filename,
+ :location,
+ :duration_ms,
+ :size_bytes,
+ :started_at,
+ :ended_at
+
+ has_one :started_by, serializer: BasicUserSerializer, embed: :objects
+
+ def room_name
+ object.room&.name
+ end
+ end
+end
diff --git a/plugins/voice/app/serializers/voice/admin_room_serializer.rb b/plugins/voice/app/serializers/voice/admin_room_serializer.rb
new file mode 100644
index 00000000000..47db9e14881
--- /dev/null
+++ b/plugins/voice/app/serializers/voice/admin_room_serializer.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module Voice
+ class AdminRoomSerializer < ApplicationSerializer
+ attributes :id,
+ :name,
+ :slug,
+ :description,
+ :public,
+ :max_participants,
+ :room_type,
+ :video_enabled,
+ :livekit_enabled,
+ :chat_channel_id,
+ :chat_idle_minutes,
+ :max_quality_profile,
+ :member_count,
+ :live_participant_count,
+ :created_at,
+ :updated_at
+
+ has_one :creator, serializer: BasicUserSerializer, embed: :objects
+
+ def room_type
+ object.room_type_name
+ end
+
+ def max_quality_profile
+ object.max_quality_profile_name
+ end
+
+ def member_count
+ object.room_memberships.size
+ end
+
+ def live_participant_count
+ Voice::ParticipantTracker.user_ids(object.id).size
+ end
+ end
+end
diff --git a/plugins/voice/app/serializers/voice/room_membership_serializer.rb b/plugins/voice/app/serializers/voice/room_membership_serializer.rb
new file mode 100644
index 00000000000..23ed13dde98
--- /dev/null
+++ b/plugins/voice/app/serializers/voice/room_membership_serializer.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomMembershipSerializer < ApplicationSerializer
+ attributes :id, :room_id, :user_id, :role, :role_name, :created_at, :updated_at
+
+ has_one :user, serializer: BasicUserSerializer, embed: :objects
+
+ def role_name
+ object.role_name
+ end
+ end
+end
diff --git a/plugins/voice/app/serializers/voice/room_serializer.rb b/plugins/voice/app/serializers/voice/room_serializer.rb
new file mode 100644
index 00000000000..7a7ee0fc210
--- /dev/null
+++ b/plugins/voice/app/serializers/voice/room_serializer.rb
@@ -0,0 +1,180 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomSerializer < ApplicationSerializer
+ attributes :id,
+ :name,
+ :slug,
+ :description,
+ :cooked_description,
+ :public,
+ :ephemeral,
+ :room_type,
+ :max_participants,
+ :created_at,
+ :updated_at,
+ :member_count,
+ :message_bus_last_id,
+ :active_participants,
+ :creator_id,
+ :can_manage,
+ :can_invite,
+ :description_excerpt,
+ :visit_count,
+ :video_enabled,
+ :video_allowed,
+ :chat_channel_id,
+ :chat_idle_minutes,
+ :chat_available,
+ :livekit_enabled,
+ :expected_transport,
+ :max_quality_profile,
+ :recording,
+ :ringing
+
+ has_one :membership, serializer: Voice::RoomMembershipSerializer, embed: :objects
+
+ def include_ringing?
+ object.ephemeral?
+ end
+
+ # People this call is still reaching out to: unredeemed invites, stamped
+ # with when they were last rung so clients can stop showing ones whose
+ # ring has run out. The client hides entries for users already present.
+ def ringing
+ invites = Voice::Invite.where(room_id: object.id, redeemed_at: nil)
+ users = User.real.not_staged.where(id: invites.map(&:user_id)).index_by(&:id)
+
+ invites.filter_map do |invite|
+ user = users[invite.user_id]
+ next unless user
+
+ {
+ user: BasicUserSerializer.new(user, scope: scope, root: false).as_json,
+ notified_at: invite.updated_at.to_i,
+ }
+ end
+ end
+
+ def membership
+ object.room_memberships.find { |membership| membership.user_id == scope.user&.id }
+ end
+
+ def member_count
+ object.room_memberships.size
+ end
+
+ # Read before active_participants (attributes serialize in declaration
+ # order) so clients subscribing from this position replay, at worst,
+ # broadcasts already reflected in the snapshot — never a gap.
+ def message_bus_last_id
+ MessageBus.last_id(Voice.room_channel(object.id))
+ end
+
+ def active_participants
+ tracked_participants.map do |user|
+ BasicUserSerializer
+ .new(user, scope: scope, root: false)
+ .as_json
+ .merge(participant_metadata[user.id] || {})
+ end
+ end
+
+ def room_type
+ object.room_type_name
+ end
+
+ def max_quality_profile
+ object.max_quality_profile_name
+ end
+
+ def can_manage
+ return @can_manage if defined?(@can_manage)
+ @can_manage = scope.can_manage_voice_room?(object)
+ end
+
+ def can_invite
+ scope.can_invite_to_voice_room?(object)
+ end
+
+ def description_excerpt
+ object.description&.lines&.first&.truncate(150)
+ end
+
+ def visit_count
+ Voice::Session.where(user_id: scope.user.id, room_id: object.id).count
+ end
+
+ def include_visit_count?
+ scope.user.present? && @options[:include_visit_count]
+ end
+
+ def video_allowed
+ object.video_allowed?
+ end
+
+ def chat_available
+ return @chat_available if defined?(@chat_available)
+ @chat_available = Voice::ChatSession.available_for?(object, scope)
+ end
+
+ # The room's chat wiring isn't for general consumption: whether chat is
+ # usable only matters to someone actually in the room (or managing it),
+ # and the channel link plus session settings are only edited by managers.
+ # Everyone else — including the anonymously-scoped directory broadcasts —
+ # gets a room without chat fields; the client preserves the ones it
+ # already knows across those broadcasts.
+ def include_chat_available?
+ can_manage || participating?
+ end
+
+ def include_chat_channel_id?
+ can_manage
+ end
+
+ def include_chat_idle_minutes?
+ can_manage
+ end
+
+ # Only the room form consumes this; the live call's transport is never
+ # serialized — clients learn it at join.
+ def include_livekit_enabled?
+ can_manage
+ end
+
+ # Best-effort prediction of the transport a join would resolve to right
+ # now, mirroring the join endpoint's resolution (pin, then availability).
+ # The pin set at join remains authoritative; this exists so clients can
+ # warn about mesh's IP exposure before joining, and a race that flips
+ # mesh → livekit only makes the warning over-cautious.
+ def expected_transport
+ Voice::ParticipantTracker.pinned_transport(object.id) ||
+ (Voice::Livekit.available_for?(object) ? "livekit" : "mesh")
+ end
+
+ # Not gated per user: an active recording is something everyone who can
+ # see the room is entitled to know about.
+ def recording
+ return @recording if defined?(@recording)
+ @recording = Voice::RecordingManager.status(object.id)
+ end
+
+ def include_recording?
+ recording.present?
+ end
+
+ private
+
+ def tracked_participants
+ @tracked_participants ||= Voice::ParticipantTracker.list(object.id)
+ end
+
+ def participant_metadata
+ @participant_metadata ||= Voice::ParticipantTracker.get_all_metadata(object.id)
+ end
+
+ def participating?
+ scope.user.present? && tracked_participants.any? { |user| user.id == scope.user.id }
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/badge_granter_hooks.rb b/plugins/voice/app/services/voice/badge_granter_hooks.rb
new file mode 100644
index 00000000000..616416eb1ce
--- /dev/null
+++ b/plugins/voice/app/services/voice/badge_granter_hooks.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+module Voice
+ class BadgeGranterHooks
+ def self.on_leave(user, session, room:)
+ return unless badges_enabled?
+ return if session&.left_at.blank?
+
+ grant("Mic Check", user) if mic_check?(session, room)
+ grant("Night Owl", user) if night_owl?(user, session)
+ grant("Early Bird", user) if early_bird?(user, session)
+ grant("Marathoner", user) if marathoner?(session)
+ end
+
+ def self.on_join(user, room, participants)
+ return unless badges_enabled?
+
+ grant("Packed House", user) if room_full?(room, participants)
+ grant("Icebreaker", user) if icebreaker?(user, participants)
+ end
+
+ def self.on_room_create(user)
+ return unless badges_enabled?
+ grant("Host", user)
+ end
+
+ def self.on_invite_redeemed(invite)
+ return unless badges_enabled?
+
+ inviter = invite.invited_by
+ grant("Plus One", inviter) if inviter
+ end
+
+ BADGE_GROUP_NAME = "Voice"
+
+ def self.enable_all!
+ grouping = BadgeGrouping.find_by(name: BADGE_GROUP_NAME)
+ Badge.where(badge_grouping_id: grouping.id).update_all(enabled: true) if grouping
+ end
+
+ def self.disable_all!
+ grouping = BadgeGrouping.find_by(name: BADGE_GROUP_NAME)
+ Badge.where(badge_grouping_id: grouping.id).update_all(enabled: false) if grouping
+ end
+
+ class << self
+ private
+
+ def grant(badge_name, user)
+ badge = Badge.find_by(name: badge_name)
+ BadgeGranter.grant(badge, user) if badge&.enabled?
+ end
+
+ def mic_check?(session, room)
+ duration = (session.left_at - session.joined_at).to_i
+ duration >= 30 && Voice::ParticipantTracker.user_ids(room.id).any?
+ end
+
+ def night_owl?(user, session)
+ hour = local_hour(user, session.joined_at)
+ hour >= 0 && hour < 5
+ end
+
+ def early_bird?(user, session)
+ hour = local_hour(user, session.joined_at)
+ hour >= 5 && hour < 9
+ end
+
+ def marathoner?(session)
+ duration = (session.left_at - session.joined_at).to_i
+ duration >= 4.hours.to_i
+ end
+
+ def room_full?(room, participants)
+ room.max_participants.present? && participants.count >= room.max_participants
+ end
+
+ def icebreaker?(user, participants)
+ other_ids = participants.map(&:id) - [user.id]
+ return false if other_ids.empty?
+
+ Voice::CoPresence
+ .where("(user_id_1 = :uid OR user_id_2 = :uid)", uid: user.id)
+ .where("(user_id_1 IN (:others) OR user_id_2 IN (:others))", others: other_ids)
+ .none?
+ end
+
+ def local_hour(user, time)
+ tz = user.user_option&.timezone.presence || "UTC"
+ time.in_time_zone(tz).hour
+ end
+
+ def badges_enabled?
+ SiteSetting.enable_badges && SiteSetting.voice_badges_enabled
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/chat_session.rb b/plugins/voice/app/services/voice/chat_session.rb
new file mode 100644
index 00000000000..7d9d3b530a8
--- /dev/null
+++ b/plugins/voice/app/services/voice/chat_session.rb
@@ -0,0 +1,323 @@
+# frozen_string_literal: true
+
+module Voice
+ # Bridges a voice room to the Discourse chat plugin.
+ #
+ # A room is linked to a chat channel; each "chat session" lives in a thread on
+ # that channel. A session's thread is only created when someone actually sends
+ # a message: that first message roots the thread, prefixed with the room's
+ # hashtag so the opener links back to the room, and the thread is titled
+ # after the room.
+ #
+ # From then on participants read and post through chat's own UI and API;
+ # Voice only tracks WHICH thread is the room's live session.
+ #
+ # The live thread id lives in Redis, keyed by room. Liveness is derived from
+ # two sources: the timestamp of the thread's most recent chat message
+ # (messages already carry their own +created_at+, so there's nothing extra to
+ # store) and a Redis "last seen" timestamp bumped on the room heartbeat while
+ # a participant is present. A session only rolls over to a fresh thread once
+ # both have been quiet longer than the room's configured timeout — i.e. it
+ # has been idle (no messages) AND empty (no one present).
+ class ChatSession
+ # Raised when an underlying chat operation is rejected for a reason worth
+ # showing the user (threading disabled on the channel, a duplicate or
+ # too-long message, etc.) rather than masking it behind a generic "not
+ # permitted" error. The controller renders it as a 422 carrying the real
+ # message.
+ class Error < StandardError
+ end
+
+ KEY_NAMESPACE = "voice:room"
+ SAFETY_TTL = 1.day.to_i
+
+ class << self
+ def chat_available?
+ defined?(::Chat) && SiteSetting.voice_chat_enabled && SiteSetting.chat_enabled
+ end
+
+ # Whether the current user can use chat in this room (chat installed +
+ # enabled, a channel is linked, and the user may post in that channel).
+ def available_for?(room, guardian)
+ return false unless chat_available?
+ channel = room.chat_channel
+ return false unless channel
+ guardian.can_chat? && guardian.can_join_chat_channel?(channel)
+ end
+
+ # A snapshot of the room's live chat session for the client: the linked
+ # channel and the active thread (if any). Never creates anything.
+ def state(room)
+ channel_id = room.chat_channel_id
+ thread_id = channel_id.present? && !stale?(room) ? live_thread_id(room) : nil
+ { channel_id: channel_id, thread_id: thread_id }
+ end
+
+ # Records that a participant is present (called on the room heartbeat) so a
+ # session with people in it but no recent messages doesn't roll over.
+ # Message recency is read straight from the messages themselves.
+ def touch!(room)
+ return if redis.get(thread_key(room.id)).blank?
+
+ # Never revive a session that already went idle AND empty — let the next
+ # panel open roll it over to a fresh thread instead.
+ return if stale?(room)
+
+ # Keep the identity key alive alongside presence, so a long, present but
+ # quiet session doesn't lose its thread pointer to TTL expiry.
+ redis.expire(thread_key(room.id), SAFETY_TTL)
+ redis.set(seen_key(room.id), Time.now.to_f, ex: SAFETY_TTL)
+ end
+
+ # Prepares the room's session for +user+ without creating anything: rolls
+ # a stale session over and follows the user on the channel so chat's own
+ # message endpoints accept their posts. The thread itself only comes into
+ # existence with the session's first message (see +post_message!+).
+ # Returns the session state.
+ def start!(room, user)
+ channel = ensure_channel!(room)
+ with_session_lock(room) do
+ roll_over_if_stale!(room)
+ ::Chat::ChannelMembershipManager.new(channel).follow(user)
+ end
+ state(room)
+ end
+
+ # Posts the session's opening message as +user+: the message is created on
+ # the channel and a thread is opened from it. Once a thread is live, messages flow through
+ # chat's own API instead — this is only called by a panel that believes no
+ # thread exists yet, so if one appeared in the meantime the message is
+ # delivered there rather than spawning a competing thread.
+ # Returns the session state.
+ def post_message!(room, user, message)
+ channel = ensure_channel!(room)
+ with_session_lock(room) do
+ roll_over_if_stale!(room)
+
+ if (thread_id = live_thread_id(room))
+ create_message!(
+ guardian: user.guardian,
+ channel_id: channel.id,
+ message: message,
+ thread_id: thread_id,
+ )
+ else
+ open_session_thread!(room, channel, user, message)
+ end
+ end
+ state(room)
+ end
+
+ def clear(room_id)
+ redis.del(thread_key(room_id))
+ redis.del(seen_key(room_id))
+ end
+
+ private
+
+ def ensure_channel!(room)
+ room.chat_channel ||
+ raise(
+ Discourse::InvalidAccess.new(
+ :voice_chat_unavailable,
+ nil,
+ custom_message: "voice.errors.chat_unavailable",
+ ),
+ )
+ end
+
+ def roll_over_if_stale!(room)
+ clear(room.id) if stale?(room)
+ end
+
+ # Serializes the read-modify-write of a room's session so two near
+ # simultaneous panel opens can't each start their own thread.
+ def with_session_lock(room, &blk)
+ DistributedMutex.synchronize("#{KEY_NAMESPACE}:#{room.id}:chat_lock", &blk)
+ end
+
+ # Opens the session's thread from its first message: +message+ itself
+ # roots the thread, prefixed with the room's hashtag so the opener links
+ # back to the room. The change is published so every open panel picks
+ # the new thread up.
+ def open_session_thread!(room, channel, user, message)
+ # Bail before posting: if the channel can't hold a thread, thread
+ # creation would be rejected and leave the message orphaned as a loose
+ # channel message (re-posted on every retry).
+ ensure_threading_enabled!(channel)
+
+ root =
+ create_message!(
+ guardian: user.guardian,
+ channel_id: channel.id,
+ message: opener_for(room, message),
+ )
+ thread = open_thread!(channel, root, title: title_for(room))
+ # Mark the thread as this room's before anything is published: a panel
+ # reacting to the publish looks the thread up by this field right away,
+ # and a miss would be cached as "not a session thread". Unlike the
+ # Redis pointer, the marker outlives the session, tracing any past
+ # session thread back to its room.
+ thread.upsert_custom_fields(Voice::THREAD_ROOM_ID_FIELD => room.id)
+ store_thread(room, thread.id)
+ publish_state(room)
+
+ thread
+ end
+
+ # --- chat plumbing -------------------------------------------------------
+
+ def open_thread!(channel, original_message, title:)
+ params = {
+ channel_id: channel.id,
+ original_message_id: original_message.id,
+ title: title.truncate(::Chat::Thread::MAX_TITLE_LENGTH),
+ }
+
+ result = ::Chat::CreateThread.call(guardian: Discourse.system_user.guardian, params: params)
+ raise_unless_chat_success(result)
+ result.thread
+ end
+
+ def create_message!(guardian:, channel_id:, message:, thread_id: nil)
+ result =
+ ::Chat::CreateMessage.call(
+ guardian: guardian,
+ params: { chat_channel_id: channel_id, thread_id: thread_id, message: message }.compact,
+ options: {
+ enforce_membership: true,
+ },
+ )
+ raise_unless_chat_success(result)
+ result.message_instance
+ end
+
+ def ensure_threading_enabled!(channel)
+ return if channel.threading_enabled?
+ raise Error, I18n.t("voice.errors.chat_threading_disabled")
+ end
+
+ def raise_unless_chat_success(result)
+ return if result.success?
+ Rails.logger.warn(
+ "[voice] chat operation failed: #{Service::StepsInspector.new(result).inspect}",
+ )
+ raise Error, chat_failure_message(result)
+ end
+
+ # Best-effort, user-facing reason a chat service failed — the validation
+ # error on the rejected message/thread, else the failing policy's reason,
+ # else a generic fallback. Used verbatim in the 422 the controller
+ # returns.
+ def chat_failure_message(result)
+ record = result.message_instance || result.thread
+ if record.respond_to?(:errors) && record.errors.present?
+ return record.errors.full_messages.to_sentence
+ end
+ Service::StepsInspector.new(result).error.presence ||
+ I18n.t("voice.errors.chat_unavailable")
+ end
+
+ # Publishes a content-free "something changed" signal, not the state
+ # itself: `room.message_bus_targets` is the room's audience, which can be
+ # broader than who is actually authorized to see the linked chat channel
+ # (e.g. a public room linked to a restricted channel). Clients react by
+ # re-fetching through the chat_session endpoint, which re-checks
+ # `available_for?` for the requesting user on every call.
+ def publish_state(room)
+ MessageBus.publish(
+ Voice.room_chat_channel(room.id),
+ { type: "updated" },
+ **message_bus_targets(room),
+ )
+ end
+
+ # Same audience the room broadcaster uses: the room's configured targets
+ # plus anyone currently present, so a participant who isn't a channel/room
+ # member still sees the panel follow along.
+ def message_bus_targets(room)
+ targets = room.message_bus_targets
+ participant_ids = Voice::ParticipantTracker.user_ids(room.id)
+ return targets if participant_ids.empty?
+ targets.merge(user_ids: Array(targets[:user_ids] || []) | participant_ids)
+ end
+
+ # --- redis state ---------------------------------------------------------
+
+ def live_thread_id(room)
+ id = redis.get(thread_key(room.id)).to_i
+ return nil if id <= 0
+ thread = ::Chat::Thread.find_by(id: id, channel_id: room.chat_channel_id)
+ return nil unless thread
+ # If the thread's original message has been deleted the thread can no
+ # longer be loaded by participants, so treat the session as gone and let
+ # the next panel open start a fresh one. (Chat::Message is soft-deleted,
+ # so this existence check excludes trashed rows.)
+ unless ::Chat::Message.exists?(
+ id: thread.original_message_id,
+ chat_channel_id: room.chat_channel_id,
+ )
+ return nil
+ end
+ id
+ end
+
+ def store_thread(room, thread_id)
+ redis.set(thread_key(room.id), thread_id, ex: SAFETY_TTL)
+ end
+
+ # A session is stale once it has been both idle (no messages) and empty (no
+ # one present, so no heartbeats) for longer than the room's timeout.
+ def stale?(room)
+ last = liveness_at(room)
+ return true if last.nil?
+ (Time.now.to_f - last) > room.chat_idle_seconds
+ end
+
+ # The most recent sign of life: the newest message in the session, or the
+ # last heartbeat while someone was present — whichever is later.
+ def liveness_at(room)
+ candidates = []
+ message_at = last_message_at(room)
+ candidates << message_at.to_f if message_at
+ seen_at = redis.get(seen_key(room.id))
+ candidates << seen_at.to_f if seen_at.present?
+ candidates.max
+ end
+
+ # Timestamp of the session's most recent (non-deleted) chat message, read
+ # straight from the thread's messages.
+ def last_message_at(room)
+ thread_id = redis.get(thread_key(room.id)).to_i
+ return nil if thread_id <= 0
+ ::Chat::Message.where(thread_id: thread_id).maximum(:created_at)
+ end
+
+ # I18n interpolation inserts the message verbatim (no re-interpolation),
+ # so user text containing tokens like %{room} or gsub escapes is safe.
+ def opener_for(room, message)
+ I18n.t(
+ "voice.chat.default_thread_opener",
+ room: "##{room.slug}::#{Voice::RoomHashtagDataSource.type}",
+ message: message,
+ )
+ end
+
+ def title_for(room)
+ I18n.t("voice.chat.default_thread_title", room: room.name.to_s).strip
+ end
+
+ def redis
+ Discourse.redis
+ end
+
+ def thread_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:chat_thread"
+ end
+
+ def seen_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:chat_seen_at"
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/control_plane_limiter.rb b/plugins/voice/app/services/voice/control_plane_limiter.rb
new file mode 100644
index 00000000000..3908d64ba5e
--- /dev/null
+++ b/plugins/voice/app/services/voice/control_plane_limiter.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Voice
+ # Fixed-window weighted rate limiter. Unlike core RateLimiter, one call can
+ # consume several units of budget — a signal request is accounted by the
+ # events it relays, not by being a single HTTP request — so burst-heavy but
+ # bounded traffic (a full-room Trickle ICE burst) passes while sustained
+ # abuse is cut off.
+ class ControlPlaneLimiter
+ def self.perform!(key, limit:, period:, weight: 1)
+ return if RateLimiter.disabled?
+
+ redis = Discourse.redis.without_namespace
+ redis_key = Discourse.redis.namespace_key("voice-budget:#{key}")
+
+ count = redis.incrby(redis_key, weight)
+ ttl = redis.ttl(redis_key)
+ if ttl < 0
+ redis.expire(redis_key, period)
+ ttl = period
+ end
+
+ raise RateLimiter::LimitExceeded.new(ttl, key) if count > limit
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/default_room_seeder.rb b/plugins/voice/app/services/voice/default_room_seeder.rb
new file mode 100644
index 00000000000..98b5408106e
--- /dev/null
+++ b/plugins/voice/app/services/voice/default_room_seeder.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Voice
+ class DefaultRoomSeeder
+ DEFAULT_NAME = "Watercooler"
+ MUTEX = "voice-default-room-seeder"
+
+ def self.ensure!
+ return unless SiteSetting.voice_enabled?
+ return unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ # Runs at plugin activation, which can precede pending migrations (dev
+ # DBs, rake db:migrate itself) — and Room queries the newest columns.
+ # DatabaseTasks.migrations_paths is the set that includes plugin paths;
+ # the connection pool's migration_context only knows core's.
+ if ActiveRecord::MigrationContext.new(
+ ActiveRecord::Tasks::DatabaseTasks.migrations_paths,
+ ).needs_migration?
+ return
+ end
+
+ DistributedMutex.synchronize(MUTEX) do
+ next if Voice::Room.persistent.exists?
+
+ room =
+ Voice::Room.create!(
+ name: DEFAULT_NAME,
+ description: I18n.t("voice.defaults.watercooler_description"),
+ public: true,
+ creator: Discourse.system_user,
+ )
+
+ Voice::DirectoryBroadcaster.broadcast(action: :created, room: room)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/directory_broadcaster.rb b/plugins/voice/app/services/voice/directory_broadcaster.rb
new file mode 100644
index 00000000000..a9bb15a1d6d
--- /dev/null
+++ b/plugins/voice/app/services/voice/directory_broadcaster.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module Voice
+ class DirectoryBroadcaster
+ def self.broadcast(action:, room:)
+ new(room, action).broadcast
+ end
+
+ # Targets are captured eagerly so a broadcaster built before a destructive
+ # action (see RoomsController#destroy) still knows who to notify once the
+ # room's memberships are gone.
+ def initialize(room, action)
+ @room = room
+ @action = action
+ @targets =
+ if room.public?
+ Voice.public_room_message_bus_targets
+ else
+ { user_ids: room.member_ids }
+ end
+ end
+
+ def broadcast
+ # Ephemeral rooms never appear in the directory, so clients must not
+ # receive index events that would splice them into it.
+ return if room.ephemeral?
+
+ # MessageBus rejects an empty user_ids target, and there is nobody to
+ # notify anyway.
+ return if targets[:user_ids] == []
+
+ MessageBus.publish(
+ Voice.room_index_channel,
+ {
+ type: action,
+ room: Voice::RoomSerializer.new(room, scope: Guardian.new(nil), root: false).as_json,
+ },
+ **targets,
+ )
+ end
+
+ private
+
+ attr_reader :room, :action, :targets
+ end
+end
diff --git a/plugins/voice/app/services/voice/ephemeral_room_manager.rb b/plugins/voice/app/services/voice/ephemeral_room_manager.rb
new file mode 100644
index 00000000000..9e3f9b1acf9
--- /dev/null
+++ b/plugins/voice/app/services/voice/ephemeral_room_manager.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+module Voice
+ # Backend API for ephemeral rooms: short-lived rooms created by other
+ # features (a direct call between two users, a scheduled event's stage)
+ # rather than by a user filling in the room form. They never appear in the
+ # directory or any other discovery surface — whoever creates one is
+ # responsible for surfacing it — and they are reaped automatically once
+ # they have sat empty past the configured TTL.
+ class EphemeralRoomManager
+ # Live (not yet reaped) ephemeral rooms one user can have outstanding at a
+ # time; caps how much room state repeated call attempts can accumulate
+ # before the TTL cleanup runs.
+ MAX_LIVE_ROOMS_PER_CREATOR = 10
+
+ # Inviting into a room is a moderator ability, so `moderators` is how a
+ # consumer makes the parties peers (a direct call, where either side may
+ # pull someone else in), while `members` fits an audience invited to a
+ # room someone else runs.
+ def self.create!(creator:, name:, members: [], moderators: [], **attrs)
+ room = nil
+
+ # The count and create must not be raceable, or concurrent call
+ # attempts could blow past the cap.
+ DistributedMutex.synchronize("voice-ephemeral-rooms-#{creator.id}") do
+ if Voice::Room.ephemeral.where(creator_id: creator.id).count >= MAX_LIVE_ROOMS_PER_CREATOR
+ raise Discourse::InvalidAccess.new(
+ :voice_ephemeral_room_limit,
+ nil,
+ custom_message: "voice.errors.ephemeral_room_limit",
+ )
+ end
+
+ room =
+ Voice::Room.create!(
+ ephemeral: true,
+ creator: creator,
+ name: name,
+ last_occupied_at: Time.current,
+ **attrs,
+ )
+ end
+
+ # The creator already holds a moderator membership from the model hook.
+ moderators.each do |user|
+ next if user.id == creator.id
+ room.room_memberships.create!(user: user, role: RoomMembership::ROLE_MODERATOR)
+ end
+
+ members.each do |user|
+ next if user.id == creator.id
+ room.room_memberships.find_or_create_by!(user: user)
+ end
+
+ room
+ end
+
+ # Occupied rooms get their clock reset; rooms empty past the TTL are
+ # destroyed. The TTL (rather than delete-on-empty) tolerates the gap
+ # between creation and the first join, and a call where everyone's
+ # presence briefly lapses at once.
+ def self.cleanup!
+ ttl = SiteSetting.voice_ephemeral_room_ttl_minutes.minutes
+
+ Voice::Room.ephemeral.find_each do |room|
+ if Voice::ParticipantTracker.user_ids(room.id).any?
+ room.update_column(:last_occupied_at, Time.current)
+ elsif (room.last_occupied_at || room.created_at) < ttl.ago
+ destroy!(room)
+ end
+ end
+ end
+
+ def self.destroy!(room)
+ # Guards consumers holding a stale reference: a persistent room must
+ # never be torn down through the ephemeral lifecycle.
+ raise Discourse::InvalidParameters.new(:room) unless room.ephemeral?
+
+ room.destroy!
+ Voice::Livekit::RoomServiceClient.delete_room(room)
+ Voice::ParticipantTracker.clear(room.id)
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/participant_tracker.rb b/plugins/voice/app/services/voice/participant_tracker.rb
new file mode 100644
index 00000000000..1f7a9c673d4
--- /dev/null
+++ b/plugins/voice/app/services/voice/participant_tracker.rb
@@ -0,0 +1,375 @@
+# frozen_string_literal: true
+
+module Voice
+ class ParticipantTracker
+ KEY_NAMESPACE = "voice:room"
+ RECENTLY_ACTIVE_ROOMS_KEY = "voice:recently_active_rooms"
+ SAFETY_TTL = 30.minutes.to_i
+ # Must outlive one client heartbeat interval (10s) plus request latency,
+ # so a beat already in flight when the user leaves can't resurrect them.
+ LEFT_TOMBSTONE_TTL = 15
+
+ # Purge-expired, existence check, capacity check, and add in one script:
+ # a separate ZCARD followed by ZADD would let concurrent joiners race the
+ # room past its cap. Members already present (even at capacity) refresh
+ # rather than count as a new admission.
+ ADD_WITHIN_CAPACITY = DiscourseRedis::EvalHelper.new <<~LUA
+ local now = ARGV[1]
+ local cutoff = ARGV[2]
+ local capacity = tonumber(ARGV[3])
+ local user_id = ARGV[4]
+ local ttl = tonumber(ARGV[5])
+
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', '(' .. cutoff)
+
+ if redis.call('ZSCORE', KEYS[1], user_id) then
+ redis.call('ZADD', KEYS[1], now, user_id)
+ redis.call('EXPIRE', KEYS[1], ttl)
+ return 1
+ end
+
+ if redis.call('ZCARD', KEYS[1]) >= capacity then
+ return -1
+ end
+
+ redis.call('ZADD', KEYS[1], now, user_id)
+ redis.call('EXPIRE', KEYS[1], ttl)
+ return 2
+ LUA
+
+ class << self
+ def add(room_id, user_id, migrated: false)
+ return if user_id.to_i <= 0
+
+ redis.zadd(key(room_id), Time.now.to_f, user_id)
+ redis.expire(key(room_id), SAFETY_TTL)
+ redis.expire(metadata_key(room_id), SAFETY_TTL)
+ touch_recently_active(room_id)
+ rescue Redis::CommandError => e
+ raise if e.message.exclude?("WRONGTYPE") || migrated
+ redis.del(key(room_id))
+ add(room_id, user_id, migrated: true)
+ end
+
+ # Capacity-enforced admission for join. Returns :existing when the user
+ # already holds a slot (refreshed, even in a full room), :added when a
+ # free slot was taken, and :full when the room is at capacity.
+ # Session-attested refreshes (heartbeat, reconnect token) use plain
+ # `add`: their slot was granted by an earlier admission.
+ def add_within_capacity(room_id, user_id, capacity, migrated: false)
+ return :full if user_id.to_i <= 0
+
+ now = Time.now.to_f
+ cutoff = now - SiteSetting.voice_participant_ttl_seconds
+ result =
+ ADD_WITHIN_CAPACITY.eval(
+ redis.without_namespace,
+ [redis.namespace_key(key(room_id))],
+ [now, cutoff, capacity.to_i, user_id, SAFETY_TTL],
+ )
+
+ return :full if result == -1
+
+ redis.expire(metadata_key(room_id), SAFETY_TTL)
+ touch_recently_active(room_id)
+ result == 1 ? :existing : :added
+ rescue Redis::CommandError => e
+ raise if e.message.exclude?("WRONGTYPE") || migrated
+ redis.del(key(room_id))
+ add_within_capacity(room_id, user_id, capacity, migrated: true)
+ end
+
+ def remove(room_id, user_id)
+ redis.zrem(key(room_id), user_id)
+ redis.hdel(metadata_key(room_id), user_id)
+ revoke_participant_session(room_id, user_id)
+ touch_recently_active(room_id)
+ end
+
+ # Server-attested participant session: minted synchronously by join (and
+ # rotated by livekit_token), so signaling authority never depends on the
+ # eventually-consistent roster broadcast. Rotating on every mint is what
+ # invalidates a pre-leave session after a rejoin.
+ def create_participant_session!(room_id, user_id)
+ session_id = SecureRandom.hex(16)
+ redis.setex(participant_session_key(room_id, user_id), participant_session_ttl, session_id)
+ session_id
+ end
+
+ def valid_participant_session?(room_id, user_id, session_id)
+ return false if session_id.blank?
+
+ stored = redis.get(participant_session_key(room_id, user_id))
+ return false if stored.blank?
+
+ ActiveSupport::SecurityUtils.secure_compare(stored, session_id.to_s)
+ end
+
+ def participant_session?(room_id, user_id)
+ redis.exists?(participant_session_key(room_id, user_id))
+ end
+
+ def refresh_participant_session(room_id, user_id)
+ redis.expire(participant_session_key(room_id, user_id), participant_session_ttl)
+ end
+
+ def revoke_participant_session(room_id, user_id)
+ redis.del(participant_session_key(room_id, user_id))
+ end
+
+ # 2x the presence TTL (like the transport pin) so a briefly-lapsed
+ # heartbeat can still self-heal presence before the session dies.
+ def participant_session_ttl
+ SiteSetting.voice_participant_ttl_seconds.to_i * 2
+ end
+
+ # Short-lived tombstone for a deliberate departure (leave/kick), letting
+ # presence-refreshing endpoints distinguish a racing in-flight heartbeat
+ # (dropped) from an intentional return (join clears it). Purely
+ # time-bounded — an expired tombstone costs nothing but exposure to the
+ # race it exists to close.
+ def mark_left(room_id, user_id)
+ redis.setex(left_key(room_id, user_id), LEFT_TOMBSTONE_TTL, "1")
+ end
+
+ def clear_left(room_id, user_id)
+ redis.del(left_key(room_id, user_id))
+ end
+
+ def recently_left?(room_id, user_id)
+ redis.exists?(left_key(room_id, user_id))
+ end
+
+ # The SID of the user's current LiveKit media session, recorded from
+ # participant_joined webhooks. On a quick disconnect/rejoin the old
+ # session's departure event can arrive after the new session is already
+ # up — `gone_at` can't catch that (the rejoin predates the disconnect),
+ # but a SID mismatch can.
+ def set_livekit_sid(room_id, user_id, sid)
+ return if sid.blank?
+ redis.hset(livekit_sid_key(room_id), user_id, sid)
+ redis.expire(livekit_sid_key(room_id), SAFETY_TTL)
+ end
+
+ def livekit_sid(room_id, user_id)
+ redis.hget(livekit_sid_key(room_id), user_id)
+ end
+
+ def clear_livekit_sids(room_id)
+ redis.del(livekit_sid_key(room_id))
+ end
+
+ # Reconcile-only early expiry (LiveKit webhooks): backdates the member's
+ # presence so it drops out of the roster through the exact same TTL
+ # filter a lapsed heartbeat uses. Metadata is kept — session bookkeeping
+ # stays with CloseOrphanedSessions. Never creates presence (ZADD XX) and
+ # skips members whose presence was refreshed after `gone_at` (a
+ # reconnect racing the event). Returns whether anything was expired.
+ def expire_presence(room_id, user_id, gone_at: nil)
+ # ZSCORE is not on DiscourseRedis's namespaced-command list, so it
+ # would silently read an un-namespaced key; ZRANGE is, and rooms are
+ # small (bounded by max_participants).
+ score = redis.zrange(key(room_id), 0, -1, withscores: true).to_h[user_id.to_s]
+ return false if score.nil?
+ return false if gone_at && score > gone_at.to_f
+
+ expired_score = Time.now.to_f - SiteSetting.voice_participant_ttl_seconds - 1
+ redis.zadd(key(room_id), [score, expired_score].min, user_id, xx: true)
+ touch_recently_active(room_id)
+ true
+ end
+
+ def list(room_id)
+ ids = user_ids(room_id)
+ User.where(id: ids)
+ end
+
+ def user_ids(room_id, migrated: false)
+ cutoff = Time.now.to_f - SiteSetting.voice_participant_ttl_seconds
+ redis.zrangebyscore(key(room_id), cutoff, "+inf").map(&:to_i).select(&:positive?)
+ rescue Redis::CommandError => e
+ raise if e.message.exclude?("WRONGTYPE") || migrated
+ redis.del(key(room_id))
+ user_ids(room_id, migrated: true)
+ end
+
+ def last_heartbeat_at(room_id, user_id)
+ metadata = get_metadata(room_id, user_id)
+ ts = metadata[:last_heartbeat_at]
+ ts ? Time.at(ts) : nil
+ end
+
+ def clear(room_id)
+ redis.del(key(room_id))
+ redis.del(metadata_key(room_id))
+ redis.del(fingerprint_key(room_id))
+ redis.del(transport_key(room_id))
+ redis.del(recording_key(room_id))
+ redis.del(livekit_sid_key(room_id))
+ end
+
+ # Never resets an existing timestamp — queue position is first-come.
+ # Returns false when already raised so callers can skip re-broadcasting.
+ def raise_hand(room_id, user_id)
+ metadata = get_metadata(room_id, user_id)
+ return false if metadata[:hand_raised_at]
+
+ metadata[:hand_raised_at] = Time.now.to_f
+ update_metadata(room_id, user_id, metadata)
+ true
+ end
+
+ def lower_hand(room_id, user_id)
+ metadata = get_metadata(room_id, user_id)
+ return false unless metadata.delete(:hand_raised_at)
+
+ update_metadata(room_id, user_id, metadata)
+ true
+ end
+
+ def update_metadata(room_id, user_id, metadata)
+ redis.hset(metadata_key(room_id), user_id, metadata.to_json)
+ redis.expire(metadata_key(room_id), SAFETY_TTL)
+ end
+
+ def get_metadata(room_id, user_id)
+ raw = redis.hget(metadata_key(room_id), user_id)
+ return {} if raw.nil?
+ JSON.parse(raw, symbolize_names: true)
+ end
+
+ def get_all_metadata(room_id)
+ raw = redis.hgetall(metadata_key(room_id))
+ raw
+ .transform_keys(&:to_i)
+ .transform_values { |value| JSON.parse(value, symbolize_names: true) }
+ end
+
+ # A stable hash of the live (TTL-filtered) membership plus the metadata
+ # that clients render. `last_heartbeat_at` is excluded so the fingerprint
+ # only changes when something a client would actually display changes —
+ # otherwise every 10s heartbeat would look like a change.
+ def participants_fingerprint(room_id)
+ metadata = get_all_metadata(room_id)
+ payload =
+ user_ids(room_id).sort.map do |id|
+ [id, (metadata[id] || {}).except(:last_heartbeat_at).sort.to_h]
+ end
+ Digest::MD5.hexdigest(payload.to_json)
+ end
+
+ # Atomically store the new fingerprint and return the previous one, so a
+ # single caller (whichever heartbeat observes the change first) can decide
+ # to broadcast while concurrent heartbeats see their own value and skip it.
+ def swap_fingerprint(room_id, fingerprint)
+ previous = redis.getset(fingerprint_key(room_id), fingerprint)
+ redis.expire(fingerprint_key(room_id), SAFETY_TTL)
+ previous
+ end
+
+ def update_fingerprint(room_id, fingerprint = nil)
+ fingerprint ||= participants_fingerprint(room_id)
+ redis.set(fingerprint_key(room_id), fingerprint, ex: SAFETY_TTL)
+ end
+
+ # The transport pin ("mesh" | "livekit") holds a room instance to one
+ # transport for its whole life: joiners after the first ignore current
+ # settings, so a call is never split across transports. `SET NX` makes
+ # the first join win under a race; the short TTL (refreshed by every
+ # join/heartbeat) lets a crashed room self-heal instead of holding a
+ # stale transport.
+ def pin_transport!(room_id, transport)
+ redis.set(transport_key(room_id), transport, nx: true, ex: transport_pin_ttl)
+ refresh_transport_pin(room_id)
+ pinned_transport(room_id) || transport
+ end
+
+ def pinned_transport(room_id)
+ redis.get(transport_key(room_id))
+ end
+
+ def refresh_transport_pin(room_id)
+ redis.expire(transport_key(room_id), transport_pin_ttl)
+ # An active recording rides the same heartbeat: its TTL is only a
+ # backstop for a room whose call died without a clean teardown.
+ redis.expire(recording_key(room_id), SAFETY_TTL)
+ end
+
+ def clear_transport_pin(room_id)
+ redis.del(transport_key(room_id))
+ # A recording is a property of the live room instance; when the
+ # instance ends, so does anything the SFU was capturing.
+ redis.del(recording_key(room_id))
+ end
+
+ def set_recording(room_id, info)
+ redis.set(recording_key(room_id), info.to_json, ex: SAFETY_TTL)
+ end
+
+ def recording(room_id)
+ raw = redis.get(recording_key(room_id))
+ raw.present? ? JSON.parse(raw, symbolize_names: true) : nil
+ end
+
+ def clear_recording(room_id)
+ redis.del(recording_key(room_id))
+ end
+
+ def transport_pin_ttl
+ SiteSetting.voice_participant_ttl_seconds.to_i * 2
+ end
+
+ def touch_recently_active(room_id)
+ redis.zadd(RECENTLY_ACTIVE_ROOMS_KEY, Time.now.to_f, room_id)
+ end
+
+ # Rooms whose membership changed within the safety window. This includes
+ # rooms that have since emptied — whose participants key no longer exists
+ # in Redis — so the republish backstop can keep re-asserting their empty
+ # state to clients that missed the final leave broadcast.
+ def recently_active_room_ids
+ cutoff = Time.now.to_f - SAFETY_TTL
+ redis.zremrangebyscore(RECENTLY_ACTIVE_ROOMS_KEY, "-inf", "(#{cutoff}")
+ redis.zrangebyscore(RECENTLY_ACTIVE_ROOMS_KEY, cutoff, "+inf").map(&:to_i)
+ end
+
+ private
+
+ def redis
+ @redis ||= Discourse.redis
+ end
+
+ def key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:participants"
+ end
+
+ def metadata_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:metadata"
+ end
+
+ def fingerprint_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:fingerprint"
+ end
+
+ def transport_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:transport"
+ end
+
+ def recording_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:recording"
+ end
+
+ def left_key(room_id, user_id)
+ "#{KEY_NAMESPACE}:#{room_id}:left:#{user_id}"
+ end
+
+ def participant_session_key(room_id, user_id)
+ "#{KEY_NAMESPACE}:#{room_id}:participant_session:#{user_id}"
+ end
+
+ def livekit_sid_key(room_id)
+ "#{KEY_NAMESPACE}:#{room_id}:livekit_sids"
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/recording_manager.rb b/plugins/voice/app/services/voice/recording_manager.rb
new file mode 100644
index 00000000000..9ed4967ee5c
--- /dev/null
+++ b/plugins/voice/app/services/voice/recording_manager.rb
@@ -0,0 +1,220 @@
+# frozen_string_literal: true
+
+module Voice
+ # Starts and stops server-side recordings of a room's live call and owns
+ # the room-wide "this call is being recorded" state. Recording is a LiveKit
+ # egress, so it only exists for calls pinned to that transport; the live
+ # state sits alongside the transport pin and dies with the room instance,
+ # while a Recording row persists each egress for delivery and the admin
+ # log.
+ #
+ # Every state change is broadcast to the room: participants must always
+ # know a recording is running, not just whoever pressed the button.
+ class RecordingManager
+ class Error < StandardError
+ end
+
+ # Terminal values of EgressInfo.status; anything else is still running
+ # (or about to run) and must not be finalized.
+ FINAL_EGRESS_STATUSES = %w[
+ EGRESS_COMPLETE
+ EGRESS_FAILED
+ EGRESS_ABORTED
+ EGRESS_LIMIT_REACHED
+ ].freeze
+
+ # An unresolved row whose egress the server no longer remembers (restart,
+ # retention) can never complete; past this age it is written off.
+ ABANDONED_AFTER = 24.hours
+
+ class << self
+ def available_for?(room)
+ SiteSetting.voice_livekit_recording_enabled &&
+ Voice::ParticipantTracker.pinned_transport(room.id) == "livekit"
+ end
+
+ # Public shape shared by the serializer, the broadcasts, and the
+ # start endpoint's response.
+ def status(room_id)
+ info = Voice::ParticipantTracker.recording(room_id)
+ return nil if info.nil?
+
+ {
+ started_at: info[:started_at],
+ started_by: {
+ id: info[:user_id],
+ username: info[:username],
+ },
+ }
+ end
+
+ def start!(room, user)
+ raise Error, I18n.t("voice.errors.recording_unavailable") unless available_for?(room)
+ if Voice::ParticipantTracker.recording(room.id)
+ raise Error, I18n.t("voice.errors.recording_already_active")
+ end
+
+ # The random suffix makes the storage path a capability: the final
+ # URL is only ever shared with the requester, so it must not be
+ # derivable from public facts like the room name and start time.
+ filepath = "#{SiteSetting.voice_livekit_recording_filepath}-#{SecureRandom.hex(8)}"
+
+ result = Voice::Livekit::EgressClient.start_room_composite(room, filepath: filepath)
+ raise Error, I18n.t("voice.errors.recording_failed") unless result[:ok]
+
+ egress_id = result[:data]["egress_id"] || result[:data]["egressId"]
+ started_at = Time.zone.now
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: egress_id,
+ filepath: filepath,
+ started_at: started_at,
+ )
+ Voice::ParticipantTracker.set_recording(
+ room.id,
+ egress_id: egress_id,
+ user_id: user.id,
+ username: user.username,
+ started_at: started_at.to_f,
+ )
+ broadcast(room)
+ status(room.id)
+ end
+
+ def stop!(room)
+ info = Voice::ParticipantTracker.recording(room.id)
+ raise Error, I18n.t("voice.errors.recording_not_active") if info.nil?
+
+ result = Voice::Livekit::EgressClient.stop(info[:egress_id])
+ # A failed stop keeps the state: the egress may well still be
+ # capturing, and claiming otherwise is worse than asking the
+ # moderator to retry. The egress_ended webhook and the state's TTL
+ # clean up an egress that already ended on its own.
+ raise Error, I18n.t("voice.errors.recording_stop_failed") unless result[:ok]
+
+ Voice::ParticipantTracker.clear_recording(room.id)
+ broadcast(room)
+ end
+
+ # The egress_ended webhook closes out every recording — whether stopped
+ # from here, ended with the room, or killed server-side. It finalizes
+ # the Recording row with the file's whereabouts and messages the
+ # requester, then clears any still-live room state.
+ def handle_egress_ended(room, egress_info)
+ egress_id = (egress_info["egress_id"] || egress_info["egressId"]).to_s
+ recording = Voice::Recording.find_by(egress_id: egress_id)
+
+ if recording&.recording?
+ finalize_recording(recording, egress_info)
+ deliver_recording(recording) if recording.completed?
+ end
+
+ info = Voice::ParticipantTracker.recording(room.id)
+ return if info.nil? || info[:egress_id] != egress_id
+
+ Voice::ParticipantTracker.clear_recording(room.id)
+ broadcast(room)
+ end
+
+ # Polling fallback for sites without webhooks (and backstop for missed
+ # deliveries): resolve every stuck row by asking the Egress service
+ # directly. ListEgress returns the same EgressInfo shape the webhook
+ # carries, so a finished egress goes through the exact same
+ # finalize-and-deliver path.
+ def reconcile_pending!
+ Voice::Recording
+ .recording
+ .includes(:room)
+ .find_each do |recording|
+ result = Voice::Livekit::EgressClient.list(egress_id: recording.egress_id)
+ next unless result[:ok]
+
+ info = Array(result[:data]["items"]).first
+
+ if info.nil?
+ if recording.started_at < ABANDONED_AFTER.ago
+ recording.update!(status: :failed, ended_at: Time.zone.now)
+ end
+ next
+ end
+
+ next if FINAL_EGRESS_STATUSES.exclude?(info["status"])
+
+ handle_egress_ended(recording.room, info)
+ end
+ end
+
+ private
+
+ def finalize_recording(recording, egress_info)
+ file = Array(egress_info["file_results"] || egress_info["fileResults"]).first || {}
+ failed = egress_info["error"].present? || file.blank?
+
+ recording.update!(
+ status: failed ? :failed : :completed,
+ filename: file["filename"].presence,
+ location: file["location"].presence,
+ # Proto3 JSON renders int64 as a string; duration is nanoseconds.
+ duration_ms: file["duration"].present? ? file["duration"].to_i / 1_000_000 : nil,
+ size_bytes: file["size"].presence&.to_i,
+ ended_at: Time.zone.now,
+ )
+ end
+
+ def deliver_recording(recording)
+ requester = recording.started_by
+ return if requester.nil? || !requester.human?
+
+ body_key =
+ if recording.location.present?
+ "voice.recording_ready_pm.body_with_link"
+ else
+ "voice.recording_ready_pm.body_with_path"
+ end
+
+ PostCreator.create!(
+ Discourse.system_user,
+ archetype: Archetype.private_message,
+ target_usernames: requester.username,
+ title: I18n.t("voice.recording_ready_pm.title", room_name: recording.room.name),
+ raw:
+ I18n.t(
+ body_key,
+ room_name: recording.room.name,
+ link: recording.location,
+ filepath: recording.filepath,
+ duration: format_duration(recording.duration_ms),
+ ),
+ skip_validations: true,
+ )
+ rescue StandardError => e
+ # Delivery is best-effort: the recording is safe and listed in the
+ # admin panel even when the PM cannot be created.
+ Rails.logger.warn(
+ "[voice-livekit] recording PM failed for recording #{recording.id}: " \
+ "#{e.class} #{e.message}",
+ )
+ end
+
+ def format_duration(duration_ms)
+ return I18n.t("voice.recording_ready_pm.unknown_duration") if duration_ms.blank?
+
+ total_seconds = duration_ms / 1000
+ minutes, seconds = total_seconds.divmod(60)
+ hours, minutes = minutes.divmod(60)
+ if hours.positive?
+ format("%d:%02d:%02d", hours, minutes, seconds)
+ else
+ format("%d:%02d", minutes, seconds)
+ end
+ end
+
+ def broadcast(room)
+ Voice::RoomBroadcaster.new(room).publish_room(
+ { type: "recording", recording: status(room.id) },
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/review_queue.rb b/plugins/voice/app/services/voice/review_queue.rb
new file mode 100644
index 00000000000..aa1a330e66a
--- /dev/null
+++ b/plugins/voice/app/services/voice/review_queue.rb
@@ -0,0 +1,95 @@
+# frozen_string_literal: true
+
+module Voice
+ # Mirrors Chat::ReviewQueue for flags raised against a room participant.
+ # Only the "something else" (notify_moderators) flag is supported: rooms
+ # have no post or message to attach a canned flag reason to, so every flag
+ # carries a custom message that is delivered to moderators as a companion
+ # PM, alongside the reviewable itself.
+ class ReviewQueue
+ def flag_user(room, target_user, guardian, flag_type_id, opts = {})
+ result = { success: false, errors: [] }
+
+ guardian.ensure_can_flag_voice_user!(room, target_user)
+
+ session = Voice::Session.where(room: room, user: target_user).order(joined_at: :desc).first
+
+ if session.blank?
+ result[:errors] << I18n.t("voice.errors.flag_target_never_joined")
+ return result
+ end
+
+ existing_reviewable = Reviewable.includes(:reviewable_scores).find_by(target: session)
+
+ if !can_flag_again?(existing_reviewable, guardian.user)
+ result[:errors] << I18n.t("voice.errors.flag_already_handled")
+ return result
+ end
+
+ pm_creator = companion_pm_creator(room, target_user, guardian.user, opts)
+ post = pm_creator.create
+
+ if pm_creator.errors.present?
+ pm_creator.errors.full_messages.each { |msg| result[:errors] << msg }
+ return result
+ end
+
+ reviewable =
+ ReviewableVoiceUser.needs_review!(
+ created_by: guardian.user,
+ target: session,
+ reviewable_by_moderator: true,
+ )
+ reviewable.update!(
+ target_created_by: target_user,
+ payload: {
+ message: opts[:message],
+ room_id: room.id,
+ room_name: room.name,
+ room_slug: room.slug,
+ },
+ )
+ reviewable.add_score(guardian.user, flag_type_id, meta_topic_id: post&.topic_id)
+
+ result[:success] = true
+ result[:reviewable] = reviewable
+ result
+ end
+
+ private
+
+ def can_flag_again?(reviewable, flagger)
+ return true if reviewable.blank?
+
+ reviewable.reviewable_scores.none? { |score| score.user_id == flagger.id && score.pending? }
+ end
+
+ def companion_pm_creator(room, target_user, flagger, opts)
+ title =
+ I18n.t(
+ "voice.reviewable_score_types.notify_moderators.pm_title",
+ username: target_user.username,
+ locale: SiteSetting.default_locale,
+ )
+
+ body =
+ I18n.t(
+ "voice.reviewable_score_types.notify_moderators.pm_body",
+ message: opts[:message],
+ username: target_user.username,
+ room_name: room.name,
+ link: "#{Discourse.base_url}/voice/r/#{room.slug}",
+ locale: SiteSetting.default_locale,
+ )
+
+ PostCreator.new(
+ flagger,
+ archetype: Archetype.private_message,
+ title: title.truncate(SiteSetting.max_topic_title_length, separator: /\s/),
+ raw: body,
+ subtype: TopicSubtype.notify_moderators,
+ target_group_names: [Group[:moderators].name],
+ )
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/room_broadcaster.rb b/plugins/voice/app/services/voice/room_broadcaster.rb
new file mode 100644
index 00000000000..3a1cc99e9da
--- /dev/null
+++ b/plugins/voice/app/services/voice/room_broadcaster.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomBroadcaster
+ def self.publish_participants(room)
+ new(room).publish_participants
+ end
+
+ def self.publish_participants_if_changed(room)
+ new(room).publish_participants_if_changed
+ end
+
+ def self.publish_kick(room, user_id)
+ new(room).publish_kick(user_id)
+ end
+
+ def self.publish_role_change(room, user_id, new_role)
+ new(room).publish_role_change(user_id, new_role)
+ end
+
+ def self.publish_hand_raise(room, user_id, raised:, raised_at: nil, reason: nil)
+ new(room).publish_hand_raise(user_id, raised: raised, raised_at: raised_at, reason: reason)
+ end
+
+ # Someone in the room started ringing `user` — lets open room pages show
+ # a pending tile for them without refetching the room.
+ def self.publish_ringing(room, user, notified_at:)
+ new(room).publish_room(
+ type: "ringing",
+ user: BasicUserSerializer.new(user, scope: Guardian.new(nil), root: false).as_json,
+ notified_at: notified_at,
+ )
+ end
+
+ def initialize(room)
+ @room = room
+ end
+
+ def publish_participants(fingerprint: nil)
+ guardian = Guardian.new(nil)
+ all_metadata = Voice::ParticipantTracker.get_all_metadata(room.id)
+ payload = {
+ type: "participants",
+ room_id: room.id,
+ participants:
+ Voice::ParticipantTracker
+ .list(room.id)
+ .map do |user|
+ BasicUserSerializer
+ .new(user, scope: guardian, root: false)
+ .as_json
+ .merge(all_metadata[user.id] || {})
+ end,
+ }
+
+ MessageBus.publish(Voice.room_channel(room.id), payload, **room_message_bus_targets)
+
+ # Keep the stored fingerprint in sync so the heartbeat backstop doesn't
+ # redundantly re-broadcast the state we just sent.
+ Voice::ParticipantTracker.update_fingerprint(room.id, fingerprint)
+ end
+
+ # Backstop for ghosts left by abrupt disconnects (refresh, tab close,
+ # crash) that never sent a clean leave. Called on every heartbeat: it
+ # compares the live membership/state against the last broadcast and emits a
+ # single participants broadcast when — and only when — something changed.
+ def publish_participants_if_changed
+ fingerprint = Voice::ParticipantTracker.participants_fingerprint(room.id)
+ previous = Voice::ParticipantTracker.swap_fingerprint(room.id, fingerprint)
+ return if previous == fingerprint
+
+ publish_participants(fingerprint: fingerprint)
+ end
+
+ def publish_room(payload)
+ MessageBus.publish(
+ Voice.room_channel(room.id),
+ payload.merge(room_id: room.id),
+ **room_message_bus_targets,
+ )
+ end
+
+ def publish_kick(user_id)
+ MessageBus.publish(
+ Voice.room_channel(room.id),
+ { type: "kicked", room_id: room.id },
+ user_ids: [user_id],
+ )
+ end
+
+ def publish_role_change(user_id, new_role)
+ participant_ids = Voice::ParticipantTracker.user_ids(room.id)
+ return if participant_ids.empty?
+
+ MessageBus.publish(
+ Voice.room_channel(room.id),
+ { type: "role_change", room_id: room.id, user_id: user_id, role: new_role },
+ user_ids: participant_ids,
+ )
+ end
+
+ # Lightweight event alongside the authoritative participants broadcast, so
+ # clients can toast on raises/dismissals without diffing rosters.
+ def publish_hand_raise(user_id, raised:, raised_at: nil, reason: nil)
+ participant_ids = Voice::ParticipantTracker.user_ids(room.id)
+ return if participant_ids.empty?
+
+ MessageBus.publish(
+ Voice.room_channel(room.id),
+ {
+ type: "hand_raise",
+ room_id: room.id,
+ user_id: user_id,
+ raised: raised,
+ raised_at: raised_at,
+ reason: reason,
+ },
+ user_ids: participant_ids,
+ )
+ end
+
+ private
+
+ attr_reader :room
+
+ def room_message_bus_targets
+ targets = room.message_bus_targets
+ # An untargeted publish already reaches everyone; merging user_ids into
+ # it would restrict delivery to just those users.
+ return targets if targets.blank?
+
+ participant_ids = Voice::ParticipantTracker.user_ids(room.id)
+ return targets if participant_ids.empty?
+
+ targets.merge(user_ids: Array(targets[:user_ids] || []) | participant_ids)
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/room_inviter.rb b/plugins/voice/app/services/voice/room_inviter.rb
new file mode 100644
index 00000000000..ca92141b2b4
--- /dev/null
+++ b/plugins/voice/app/services/voice/room_inviter.rb
@@ -0,0 +1,164 @@
+# frozen_string_literal: true
+
+module Voice
+ # Delivers room invites: records them (so redeemed ones can award badges),
+ # grants private-room invitees a membership, and notifies each invitee in
+ # Discourse and via web push.
+ class RoomInviter
+ # An unredeemed invite can be re-sent once it is this old; anything more
+ # frequent silently no-ops so repeat invites can't be used to spam
+ # notifications at someone.
+ RENOTIFY_AFTER = 1.day
+ # Ephemeral rooms are live calls: a ring that went unanswered may be
+ # retried once the previous ring has run out, but not while it is still
+ # sounding on the callee's devices.
+ RENOTIFY_EPHEMERAL_AFTER = 1.minute
+
+ # How long clients ring for. Also stamped on the ring payload so a tab
+ # waking up to a stale MessageBus backlog can discard expired rings.
+ RING_SECONDS = 60
+
+ def self.invite!(room:, inviter:, users:)
+ users.filter_map { |user| new(room: room, inviter: inviter, user: user).invite! }
+ end
+
+ def initialize(room:, inviter:, user:)
+ @room = room
+ @inviter = inviter
+ @user = user
+ end
+
+ def invite!
+ return if @user.id == @inviter.id || @user.bot?
+ return unless @user.guardian.can_access_voice?
+
+ ensure_membership! unless @room.public?
+ return unless @user.guardian.can_join_voice_room?(@room)
+
+ invite =
+ Voice::Invite.create_or_find_by(
+ room_id: @room.id,
+ user_id: @user.id,
+ invited_by_id: @inviter.id,
+ ) { |new_invite| new_invite.source = Voice::Invite::SOURCES[:notification] }
+
+ # Reported as invited either way: an inviter must not be able to tell
+ # they are muted, or probe how recently someone else already invited.
+ notify!(invite) if should_notify?(invite)
+ @user
+ end
+
+ private
+
+ def should_notify?(invite)
+ return false if notifications_blocked?
+ return true if invite.previously_new_record?
+
+ renotify_after = @room.ephemeral? ? RENOTIFY_EPHEMERAL_AFTER : RENOTIFY_AFTER
+ invite.redeemed_at.nil? && invite.updated_at < renotify_after.ago
+ end
+
+ # Anyone the invitee could not receive a personal message from — muted,
+ # ignored, or screened out by their personal message preferences — cannot
+ # ring or notify them either.
+ def notifications_blocked?
+ UserCommScreener.new(
+ acting_user: @inviter,
+ target_user_ids: [@user.id],
+ ).disallowing_pms_from_actor?(@user.id)
+ end
+
+ # The room page prompts for the invite to be redeemed on an actual join,
+ # so notification clicks and shared links land on the same URL.
+ def invite_path
+ "/voice/r/#{@room.slug}/invited-by/#{@inviter.username_lower}"
+ end
+
+ def ensure_membership!
+ @room
+ .room_memberships
+ .find_or_create_by!(user: @user) do |membership|
+ membership.role = Voice::RoomMembership::ROLE_PARTICIPANT
+ end
+ end
+
+ def notify!(invite)
+ RateLimiter.new(
+ @inviter,
+ "voice-invites-daily",
+ SiteSetting.voice_max_invites_per_day,
+ 1.day,
+ ).performed!
+
+ # Marks the re-notify window without disturbing redemption state.
+ invite.touch unless invite.previously_new_record?
+
+ # An invite into an ephemeral room is a call: the notification reads
+ # "is calling you" and the client rings instead of just chiming.
+ calling = @room.ephemeral?
+
+ @user.notifications.create!(
+ notification_type: Notification.types[:voice_invitation],
+ high_priority: true,
+ data: {
+ room_id: @room.id,
+ room_slug: @room.slug,
+ room_name: @room.name,
+ display_username: @inviter.username,
+ call: calling || nil,
+ }.compact.to_json,
+ )
+
+ i18n_scope = calling ? "voice.call_notification" : "voice.invite_notification"
+ payload = nil
+ I18n.with_locale(@user.effective_locale) do
+ payload = {
+ notification_type: Notification.types[:voice_invitation],
+ username: @inviter.username,
+ translated_title:
+ I18n.t("#{i18n_scope}.title", username: @inviter.username, room_name: @room.name),
+ excerpt: I18n.t("#{i18n_scope}.excerpt", room_name: @room.name),
+ post_url: invite_path,
+ tag: "#{Discourse.current_hostname}-voice-invite-#{@room.id}",
+ }
+ end
+
+ MessageBus.publish("/notification-alert/#{@user.id}", payload, user_ids: [@user.id])
+ PostAlerter.push_notification(@user, payload)
+
+ ring! if calling
+ end
+
+ # Real-time ring for open clients. `sent_at` lets a tab that receives the
+ # event late (MessageBus backlog after waking) drop rings that have
+ # already run out instead of replaying them.
+ def ring!
+ notified_at = Time.current.to_i
+
+ # A callee in do-not-disturb is not rung, but the caller still sees a
+ # normal outgoing ring: the call simply goes unanswered, without
+ # revealing the do-not-disturb status, and the missed-call notification
+ # is waiting once it ends.
+ ring_devices!(notified_at) unless @user.do_not_disturb?
+
+ Voice::RoomBroadcaster.publish_ringing(@room, @user, notified_at: notified_at)
+ end
+
+ def ring_devices!(notified_at)
+ MessageBus.publish(
+ "/voice/call-ring/#{@user.id}",
+ {
+ room_id: @room.id,
+ room_slug: @room.slug,
+ room_name: @room.name,
+ caller_username: @inviter.username,
+ caller_name: @inviter.name,
+ caller_avatar_template: @inviter.avatar_template,
+ sent_at: notified_at,
+ ring_seconds: RING_SECONDS,
+ },
+ user_ids: [@user.id],
+ )
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/signal_relay.rb b/plugins/voice/app/services/voice/signal_relay.rb
new file mode 100644
index 00000000000..3bb68e52f84
--- /dev/null
+++ b/plugins/voice/app/services/voice/signal_relay.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module Voice
+ class SignalRelay
+ def initialize(room)
+ @room = room
+ end
+
+ # Relays one envelope per recipient carrying that recipient's ordered
+ # event batch, and only to recipients holding a live participant session —
+ # a queued signal to someone who already left is discarded rather than
+ # delivered. The serialized sender rides along so the recipient can render
+ # a provisional participant before the roster broadcast catches up.
+ def publish!(from:, recipient_id:, events:)
+ if events.blank? || recipient_id.blank?
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.missing_payload"))
+ end
+
+ return false unless Voice::ParticipantTracker.participant_session?(room.id, recipient_id)
+
+ MessageBus.publish(
+ Voice.room_channel(room.id),
+ {
+ type: "signal",
+ room_id: room.id,
+ sender_id: from.id,
+ sender: sender_json(from),
+ events: events,
+ },
+ user_ids: Array(recipient_id),
+ )
+ true
+ end
+
+ private
+
+ attr_reader :room
+
+ def sender_json(from)
+ @sender_json ||= BasicUserSerializer.new(from, scope: Guardian.new(nil), root: false).as_json
+ end
+ end
+end
diff --git a/plugins/voice/app/services/voice/signal_validator.rb b/plugins/voice/app/services/voice/signal_validator.rb
new file mode 100644
index 00000000000..41bbe50f424
--- /dev/null
+++ b/plugins/voice/app/services/voice/signal_validator.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+module Voice
+ # Parses a signal request body into ordered per-recipient event batches,
+ # enforcing the signaling schema: only offer/answer/candidate events, exact
+ # per-type shapes, and hard size/count limits. Any unknown, malformed, or
+ # oversized element rejects the entire request before anything is relayed.
+ class SignalValidator
+ ALLOWED_TYPES = %w[offer answer candidate]
+ ALLOWED_CANDIDATE_KEYS = %i[candidate sdpMid sdpMLineIndex usernameFragment]
+ MAX_SDP_BYTES = 32_768
+ MAX_CANDIDATE_BYTES = 2_048
+ MAX_EVENTS_PER_RECIPIENT = 25
+ # One short of the largest room the model validates (a stage of 200): a
+ # peer never signals more people than can share a room with it. The
+ # room's effective capacity usually lowers this further.
+ MAX_RECIPIENTS = 199
+ MAX_TOTAL_BYTES = 1_048_576
+
+ def self.parse!(payload, room:)
+ new(payload, room: room).parse!
+ end
+
+ def initialize(payload, room:)
+ @payload = payload
+ @room = room
+ @total_bytes = 0
+ end
+
+ # Returns [{ recipient_id:, events: }, ...] with events for a repeated
+ # recipient merged in request order, so the relay publishes exactly one
+ # envelope per recipient.
+ def parse!
+ payload = normalize_hash(@payload)
+ reject! if payload.blank?
+
+ batches = {}
+
+ normalize_collection(payload[:messages]).each { |message| append!(batches, message) }
+
+ if payload.key?(:recipient_id)
+ append!(batches, payload.except(:messages))
+ elsif payload.key?(:messages)
+ # A messages envelope carrying stray top-level event fields is
+ # malformed rather than silently ignored.
+ reject! if payload.except(:messages).present?
+ end
+
+ reject! if batches.size > max_recipients
+ batches.each_value { |events| reject! if events.size > MAX_EVENTS_PER_RECIPIENT }
+
+ batches.map { |recipient_id, events| { recipient_id: recipient_id, events: events } }
+ end
+
+ private
+
+ def append!(batches, message)
+ message = normalize_hash(message)
+ reject! if message.blank?
+
+ recipient_id = validate_recipient_id!(message[:recipient_id])
+
+ events =
+ if message.key?(:events)
+ reject! if message.except(:recipient_id, :events).present?
+ collection = normalize_collection(message[:events])
+ reject! if collection.blank?
+ collection.map { |event| validate_event!(normalize_hash(event)) }
+ else
+ [validate_event!(message.except(:recipient_id))]
+ end
+
+ (batches[recipient_id] ||= []).concat(events)
+ end
+
+ def validate_recipient_id!(raw)
+ reject! unless raw.is_a?(Integer) || raw.to_s.match?(/\A\d+\z/)
+ recipient_id = raw.to_i
+ reject! unless recipient_id.positive?
+ recipient_id
+ end
+
+ def validate_event!(event)
+ reject! unless event.is_a?(Hash)
+
+ type = event[:type]
+ reject! if ALLOWED_TYPES.exclude?(type)
+
+ case type
+ when "offer", "answer"
+ reject! unless event.keys.sort == %i[sdp type]
+ sdp = event[:sdp]
+ reject! unless sdp.is_a?(String) && sdp.present?
+ track_bytes!(sdp.bytesize, MAX_SDP_BYTES)
+ { type: type, sdp: sdp }
+ when "candidate"
+ reject! unless event.keys.sort == %i[candidate type]
+ candidate = normalize_hash(event[:candidate])
+ reject! if candidate.blank?
+ reject! unless (candidate.keys - ALLOWED_CANDIDATE_KEYS).empty?
+ candidate.each_value { |value| reject! unless scalar?(value) }
+ track_bytes!(candidate.to_json.bytesize, MAX_CANDIDATE_BYTES)
+ { type: type, candidate: candidate }
+ end
+ end
+
+ def track_bytes!(bytes, limit)
+ reject! if bytes > limit
+ @total_bytes += bytes
+ reject! if @total_bytes > MAX_TOTAL_BYTES
+ end
+
+ def scalar?(value)
+ value.nil? || value.is_a?(String) || value.is_a?(Numeric) || value == true || value == false
+ end
+
+ def max_recipients
+ [@room.effective_max_participants - 1, MAX_RECIPIENTS].min
+ end
+
+ def normalize_hash(value)
+ return nil unless value.respond_to?(:to_h)
+
+ hash = value.to_h
+ hash.is_a?(Hash) ? hash.symbolize_keys : nil
+ rescue TypeError
+ nil
+ end
+
+ # Form-encoded arrays reach Rails as hashes keyed by numeric strings;
+ # numeric ordering (not lexicographic) keeps event order intact past ten
+ # elements.
+ def normalize_collection(raw)
+ return [] if raw.blank?
+ return raw if raw.is_a?(Array)
+
+ hash = normalize_hash(raw)
+ reject! if hash.nil?
+ reject! unless hash.keys.all? { |key| key.to_s.match?(/\A\d+\z/) }
+ hash.sort_by { |key, _| key.to_s.to_i }.map { |_, value| value }
+ end
+
+ def reject!
+ raise Discourse::InvalidParameters.new(I18n.t("voice.errors.invalid_signal"))
+ end
+ end
+end
diff --git a/plugins/voice/app/validators/voice_livekit_policy_validator.rb b/plugins/voice/app/validators/voice_livekit_policy_validator.rb
new file mode 100644
index 00000000000..d1cb1573930
--- /dev/null
+++ b/plugins/voice/app/validators/voice_livekit_policy_validator.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+# Refuses any LiveKit room policy other than "disabled" unless the server URL
+# (a valid wss:// origin — see VoiceLivekitUrlValidator), API key, and API
+# secret are all present, so admins get a config-time failure instead of a
+# first-join failure.
+class VoiceLivekitPolicyValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(value)
+ return true if value == "disabled"
+
+ @error_key =
+ if !VoiceLivekitUrlValidator.acceptable?(SiteSetting.voice_livekit_url)
+ "voice_livekit_policy_requires_url"
+ elsif SiteSetting.voice_livekit_api_key.blank?
+ "voice_livekit_policy_requires_api_key"
+ elsif SiteSetting.voice_livekit_api_secret.blank?
+ "voice_livekit_policy_requires_api_secret"
+ end
+
+ @error_key.nil?
+ end
+
+ def error_message
+ I18n.t("site_settings.errors.#{@error_key}") if @error_key
+ end
+end
diff --git a/plugins/voice/app/validators/voice_livekit_url_validator.rb b/plugins/voice/app/validators/voice_livekit_url_validator.rb
new file mode 100644
index 00000000000..765ee390de5
--- /dev/null
+++ b/plugins/voice/app/validators/voice_livekit_url_validator.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+# Config-time shape check for the LiveKit server URL. The URL is converted to
+# HTTP(S) for server-side Twirp requests, so it must be a bare ws(s):// origin
+# with a host and no credentials — and TLS is mandatory in production, both
+# for the signaling WebSocket and the derived HTTPS API calls. Address-level
+# SSRF protection happens at request time via FinalDestination.
+class VoiceLivekitUrlValidator
+ def self.acceptable?(value)
+ value.present? && VoiceLivekitUrlValidator.new.valid_value?(value)
+ end
+
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(value)
+ return true if value.blank?
+
+ uri = URI.parse(value.to_s)
+ @error_key =
+ if %w[ws wss].exclude?(uri.scheme.to_s) || uri.host.blank? || uri.userinfo.present?
+ "voice_livekit_url_invalid"
+ elsif uri.scheme == "ws" && Rails.env.production?
+ "voice_livekit_url_requires_wss"
+ end
+ @error_key.nil?
+ rescue URI::Error
+ @error_key = "voice_livekit_url_invalid"
+ false
+ end
+
+ def error_message
+ I18n.t("site_settings.errors.#{@error_key}") if @error_key
+ end
+end
diff --git a/plugins/voice/app/validators/voice_turn_secret_servers_validator.rb b/plugins/voice/app/validators/voice_turn_secret_servers_validator.rb
new file mode 100644
index 00000000000..4e36492e6f0
--- /dev/null
+++ b/plugins/voice/app/validators/voice_turn_secret_servers_validator.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+# Secret-authenticated TURN servers are unusable without the shared secret,
+# so admins get a config-time failure instead of dead ICE entries.
+class VoiceTurnSecretServersValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(value)
+ value.blank? || SiteSetting.voice_turn_secret.present?
+ end
+
+ def error_message
+ I18n.t("site_settings.errors.voice_turn_secret_servers_requires_secret")
+ end
+end
diff --git a/plugins/voice/assets/javascripts/admin-voice-route-map.js b/plugins/voice/assets/javascripts/admin-voice-route-map.js
new file mode 100644
index 00000000000..4af9631669e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/admin-voice-route-map.js
@@ -0,0 +1,18 @@
+export default {
+ resource: "admin.adminPlugins.show",
+
+ path: "/plugins",
+
+ map() {
+ this.route("voice-dashboard");
+ this.route("voice-recordings");
+ this.route(
+ "voice-rooms",
+
+ function () {
+ this.route("new");
+ this.route("edit", { path: "/:id" });
+ }
+ );
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/app/services/voice-calls.js b/plugins/voice/assets/javascripts/discourse/app/services/voice-calls.js
new file mode 100644
index 00000000000..4c64316a2c8
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/app/services/voice-calls.js
@@ -0,0 +1,145 @@
+import Service, { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { bind } from "discourse/lib/decorators";
+import { isPrimaryTab } from "discourse/lib/utilities";
+import VoiceIncomingCallModal from "../../components/modal/voice-incoming-call";
+import { claimCallAlert } from "../../lib/voice/call-alert-dedup";
+import { RING_SECONDS } from "../../lib/voice/call-constants";
+import { setPendingInviteRef } from "../../lib/voice/invite-ref";
+import { startRingtone, stopCallSounds } from "../../lib/voice/sound-effects";
+
+// Direct calls: starts them (user-card button) and answers them (the ring
+// event published when someone invites this user into an ephemeral room).
+export default class VoiceCallsService extends Service {
+ @service currentUser;
+ @service messageBus;
+ @service modal;
+ @service router;
+ @service("voice-rooms") voiceRooms;
+ @service("voice-webrtc") voiceWebrtc;
+
+ #subscribed = false;
+ #ringtoneRetry = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ if (this.#subscribed) {
+ this.messageBus.unsubscribe(this.#ringChannel, this.onRing);
+ }
+ this.#cancelRingtoneRetry();
+ stopCallSounds();
+ }
+
+ listen() {
+ if (this.#subscribed || !this.currentUser) {
+ return;
+ }
+ this.#subscribed = true;
+ this.messageBus.subscribe(this.#ringChannel, this.onRing);
+ }
+
+ // Creates the ephemeral call room, rings the callee, and lands the caller
+ // on the room page with an auto-join. The webrtc service loops the waiting
+ // tone once the caller is connected and alone, and silences it when the
+ // callee's peer arrives.
+ async callUser(username) {
+ const response = await ajax("/voice/calls", {
+ type: "POST",
+ data: { username },
+ });
+
+ const room = response.room;
+ this.voiceRooms.upsertRoom?.(room);
+ this.router.transitionTo("voice-room", room.slug, {
+ queryParams: { join: "true" },
+ });
+
+ return room;
+ }
+
+ @bind
+ async onRing(data) {
+ if (!data?.room_id) {
+ return;
+ }
+
+ // A tab waking up replays the channel backlog — only rings still within
+ // their window are real.
+ const ringMs = (data.ring_seconds ?? RING_SECONDS) * 1000;
+ const remainingMs = data.sent_at * 1000 + ringMs - Date.now();
+ if (remainingMs <= 0) {
+ return;
+ }
+
+ // Already in that call (answered from the push notification, or rung for
+ // a room this user is sitting in).
+ if (this.voiceWebrtc.activeRoomId === data.room_id) {
+ return;
+ }
+
+ // Same dedup as notification sounds: only the primary tab handles the
+ // ring, and the claim keeps a late backlog replay from ringing twice.
+ if (!(await isPrimaryTab())) {
+ return;
+ }
+ if (
+ !claimCallAlert(`${data.room_id}-${data.caller_username}-${data.sent_at}`)
+ ) {
+ return;
+ }
+
+ // Best effort: without a prior user gesture in this tab the browser
+ // keeps the AudioContext suspended. The answer modal still shows, and
+ // the first gesture while it's up starts the ringtone late.
+ startRingtone(this.currentUser.chat_sound).then((played) => {
+ if (!played && !this.isDestroying) {
+ this.#retryRingtoneOnGesture();
+ }
+ });
+ this.modal
+ .show(VoiceIncomingCallModal, {
+ model: { ring: data, remainingMs, calls: this },
+ })
+ .finally(() => {
+ this.#cancelRingtoneRetry();
+ stopCallSounds();
+ });
+ }
+
+ answer(ring) {
+ stopCallSounds();
+ // Joining through the invite ref credits the caller, the same as joining
+ // from the notification link.
+ setPendingInviteRef(ring.room_slug, ring.caller_username);
+ this.router.transitionTo("voice-room", ring.room_slug, {
+ queryParams: { join: "true" },
+ });
+ }
+
+ get #ringChannel() {
+ return `/voice/call-ring/${this.currentUser.id}`;
+ }
+
+ // If the retried start lands on a gesture that also ends the ring (e.g.
+ // clicking Answer), the modal's close bumps the sound generation and the
+ // late start is discarded — it can't outlive the ring.
+ #retryRingtoneOnGesture() {
+ this.#cancelRingtoneRetry();
+
+ const retry = () => {
+ this.#cancelRingtoneRetry();
+ startRingtone(this.currentUser.chat_sound);
+ };
+ this.#ringtoneRetry = retry;
+ document.addEventListener("pointerdown", retry, { once: true });
+ document.addEventListener("keydown", retry, { once: true });
+ }
+
+ #cancelRingtoneRetry() {
+ if (this.#ringtoneRetry) {
+ document.removeEventListener("pointerdown", this.#ringtoneRetry);
+ document.removeEventListener("keydown", this.#ringtoneRetry);
+ this.#ringtoneRetry = null;
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/app/services/voice-rooms.js b/plugins/voice/assets/javascripts/discourse/app/services/voice-rooms.js
new file mode 100644
index 00000000000..5702a6f4b5f
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/app/services/voice-rooms.js
@@ -0,0 +1,589 @@
+import { tracked } from "@glimmer/tracking";
+import Service, { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { bind } from "discourse/lib/decorators";
+
+// Directory broadcasts are serialized without a user, so fields the server
+// gates per user (chat availability, manager-only chat settings) are absent
+// from them. A broadcast replaces the whole room object; carry over what this
+// client already knows so a mid-call room update doesn't wipe its own state.
+const USER_GATED_ROOM_FIELDS = [
+ "chat_available",
+ "chat_channel_id",
+ "chat_idle_minutes",
+];
+
+// Participant broadcasts arrive in arbitrary database order, so every list
+// that reaches the UI is normalized to one canonical order — otherwise
+// sidebar rows and video tiles reshuffle on each broadcast.
+function sortParticipants(participants) {
+ return [...(participants || [])].sort((a, b) => {
+ const nameA = (a?.username || "").toLowerCase();
+ const nameB = (b?.username || "").toLowerCase();
+ if (nameA !== nameB) {
+ return nameA < nameB ? -1 : 1;
+ }
+ return Number(a?.id) - Number(b?.id);
+ });
+}
+
+// Speaking flips several times per utterance, so it lives outside the room
+// payloads: mutating one tracked flag re-renders only the bindings that read
+// it, instead of invalidating `rooms` and rebuilding every sidebar link and
+// tile on each flip.
+class ParticipantSpeakingState {
+ @tracked speaking = false;
+}
+
+export default class VoiceRoomsService extends Service {
+ @service currentUser;
+ @service messageBus;
+ @service siteSettings;
+ @service site;
+
+ @tracked rooms = [];
+ @tracked canCreateRoom = false;
+
+ #roomsById = new Map();
+ #roomsBySlug = new Map();
+ #roomSubscriptions = new Map();
+ #roomHandlers = new Map();
+ #speakingByKey = new Map();
+
+ constructor() {
+ super(...arguments);
+ if (!this.siteSettings.voice_enabled) {
+ return;
+ }
+
+ // Anonymous visitors only bootstrap when Voice is open to everyone; the
+ // server then returns just the public rooms.
+ if (!this.currentUser && !this.site.voice_public_access) {
+ return;
+ }
+
+ this.ready = this.#bootstrap();
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.messageBus.unsubscribe(
+ "/voice/rooms/index",
+ this.handleDirectoryEvent
+ );
+ this.#roomSubscriptions.forEach((callback, roomId) => {
+ this.messageBus.unsubscribe(`/voice/rooms/${roomId}`, callback);
+ });
+ this.#roomSubscriptions.clear();
+ this.#roomHandlers.clear();
+ }
+
+ roomById(id) {
+ return this.#roomsById.get(id);
+ }
+
+ roomBySlug(slug) {
+ return this.#roomsBySlug.get(slug);
+ }
+
+ async #bootstrap() {
+ const payload = await ajax("/voice/rooms.json");
+ this.canCreateRoom = payload.can_create_room ?? false;
+ this.#hydrateRooms(payload.rooms);
+
+ // Subscribing from the snapshot's message-bus position replays anything
+ // published while the payload was in flight; subscribing without one
+ // would silently drop those events.
+ this.messageBus.subscribe(
+ "/voice/rooms/index",
+ this.handleDirectoryEvent,
+ payload.index_message_bus_last_id ?? -1
+ );
+
+ return this.rooms;
+ }
+
+ #hydrateRooms(roomPayloads) {
+ this.rooms = roomPayloads;
+ this.#roomsById.clear();
+ this.#roomsBySlug.clear();
+
+ roomPayloads.forEach((room) => {
+ room.active_participants = sortParticipants(room.active_participants);
+ this.#roomsById.set(room.id, room);
+ this.#roomsBySlug.set(room.slug, room);
+ this.#ensureRoomSubscription(room.id, room.message_bus_last_id);
+ });
+ }
+
+ // Replaces (or adds) a room from a fresh payload — a directory broadcast or
+ // an endpoint response like join's, whose serialization is scoped to the
+ // current user and so carries the per-user chat fields.
+ upsertRoom(room) {
+ room.active_participants = sortParticipants(room.active_participants);
+
+ const previous = this.#roomsById.get(room.id);
+ if (previous) {
+ USER_GATED_ROOM_FIELDS.forEach((field) => {
+ if (room[field] === undefined) {
+ room[field] = previous[field];
+ }
+ });
+ }
+
+ this.#roomsById.set(room.id, room);
+ this.#roomsBySlug.set(room.slug, room);
+ this.#ensureRoomSubscription(room.id, room.message_bus_last_id);
+ this.rooms = Array.from(this.#roomsById.values());
+ }
+
+ @bind
+ handleDirectoryEvent(message) {
+ if (message.type === "destroyed") {
+ this.#roomsById.delete(message.room.id);
+ this.#roomsBySlug.delete(message.room.slug);
+ this.#teardownRoomSubscription(message.room.id);
+ } else {
+ this.upsertRoom(message.room);
+ }
+
+ this.rooms = Array.from(this.#roomsById.values());
+
+ if (message.type === "updated") {
+ this.#forwardToRoomHandlers(message.room.id, {
+ type: "room_updated",
+ room_id: message.room.id,
+ room: message.room,
+ });
+ }
+ }
+
+ registerRoomHandler(roomId, callback) {
+ let handlers = this.#roomHandlers.get(roomId);
+ if (!handlers) {
+ handlers = new Set();
+ this.#roomHandlers.set(roomId, handlers);
+ }
+ handlers.add(callback);
+ }
+
+ unregisterRoomHandler(roomId, callback) {
+ const handlers = this.#roomHandlers.get(roomId);
+ if (!handlers) {
+ return;
+ }
+ handlers.delete(callback);
+ if (handlers.size === 0) {
+ this.#roomHandlers.delete(roomId);
+ }
+ }
+
+ handleRoomBroadcast(payload) {
+ const room = this.#roomsById.get(payload.room_id);
+ if (!room) {
+ return;
+ }
+
+ if (payload.type === "participants") {
+ this.#setRoomParticipants(room.id, payload.participants || []);
+ } else if (payload.type === "role_change") {
+ this.setParticipantRole(payload.room_id, payload.user_id, payload.role);
+ } else if (payload.type === "hand_raise") {
+ this.setParticipantHandRaised(
+ payload.room_id,
+ payload.user_id,
+ payload.raised ? payload.raised_at : null
+ );
+ } else if (payload.type === "recording") {
+ this.setRoomRecording(payload.room_id, payload.recording);
+ } else if (payload.type === "ringing") {
+ this.#addRinging(payload.room_id, payload.user, payload.notified_at);
+ }
+
+ this.#forwardToRoomHandlers(payload.room_id, payload);
+ }
+
+ #ensureRoomSubscription(roomId, lastId) {
+ if (this.#roomSubscriptions.has(roomId)) {
+ return;
+ }
+
+ const channel = `/voice/rooms/${roomId}`;
+ const callback = (message) => this.handleRoomBroadcast(message);
+ this.messageBus.subscribe(channel, callback, lastId ?? -1);
+ this.#roomSubscriptions.set(roomId, callback);
+ }
+
+ #teardownRoomSubscription(roomId) {
+ const callback = this.#roomSubscriptions.get(roomId);
+ if (callback) {
+ const channel = `/voice/rooms/${roomId}`;
+ this.messageBus.unsubscribe(channel, callback);
+ this.#roomSubscriptions.delete(roomId);
+ }
+ this.#roomHandlers.delete(roomId);
+ }
+
+ #forwardToRoomHandlers(roomId, payload) {
+ const handlers = this.#roomHandlers.get(roomId);
+ if (!handlers) {
+ return;
+ }
+ handlers.forEach((callback) => callback(payload));
+ }
+
+ setRoomRecording(roomId, recording) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ room.recording = recording ?? null;
+ this.rooms = [...this.rooms];
+ }
+
+ // Someone in an ephemeral call room started ringing `user` — record it so
+ // the room page can show a pending tile. A repeat ring for the same user
+ // replaces their entry, restarting the ring window. Entries are never
+ // pruned here; the display filters out present users and expired rings.
+ #addRinging(roomId, user, notifiedAt) {
+ const room = this.#roomsById.get(roomId);
+ if (!room || !user?.id) {
+ return;
+ }
+
+ const others = (room.ringing || []).filter(
+ (entry) => Number(entry.user?.id) !== Number(user.id)
+ );
+ room.ringing = [...others, { user, notified_at: notifiedAt }];
+ this.rooms = [...this.rooms];
+ }
+
+ addParticipant(roomId, participant) {
+ if (!participant?.id) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ const existing = room.active_participants || [];
+ if (existing.some((p) => p?.id === participant.id)) {
+ return;
+ }
+
+ room.active_participants = sortParticipants([...existing, participant]);
+ this.rooms = [...this.rooms];
+ }
+
+ removeParticipant(roomId, userId) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ const filtered = room.active_participants.filter(
+ (participant) => Number(participant?.id) !== targetId
+ );
+
+ if (filtered.length === room.active_participants.length) {
+ return;
+ }
+
+ room.active_participants = filtered;
+ this.setParticipantSpeaking(roomId, targetId, false);
+ this.rooms = [...this.rooms];
+ }
+
+ isParticipantSpeaking(roomId, userId) {
+ return this.#speakingState(roomId, userId).speaking;
+ }
+
+ setParticipantSpeaking(roomId, userId, speaking) {
+ const state = this.#speakingState(roomId, userId);
+ if (state.speaking !== !!speaking) {
+ state.speaking = !!speaking;
+ }
+ }
+
+ #speakingState(roomId, userId) {
+ const key = `${roomId}:${Number(userId)}`;
+ let state = this.#speakingByKey.get(key);
+ if (!state) {
+ state = new ParticipantSpeakingState();
+ this.#speakingByKey.set(key, state);
+ }
+ return state;
+ }
+
+ setParticipantMuted(roomId, userId, muted) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ if (!!participant.is_muted === muted) {
+ return participant;
+ }
+
+ changed = true;
+ return {
+ ...participant,
+ is_muted: muted,
+ };
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ setParticipantIdleState(roomId, userId, idleState) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ if (participant.idle_state === idleState) {
+ return participant;
+ }
+
+ changed = true;
+ return {
+ ...participant,
+ idle_state: idleState,
+ };
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ setParticipantVideoState(roomId, userId, fields) {
+ const targetId = Number(userId);
+ if (!targetId || !fields) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ const unchanged = Object.entries(fields).every(
+ ([key, value]) => !!participant[key] === !!value
+ );
+ if (unchanged) {
+ return participant;
+ }
+
+ changed = true;
+ return {
+ ...participant,
+ ...fields,
+ };
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ setParticipantRole(roomId, userId, role) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ if (participant.role === role) {
+ return participant;
+ }
+
+ changed = true;
+ return {
+ ...participant,
+ role,
+ };
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ setParticipantHandRaised(roomId, userId, raisedAt) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ if ((participant.hand_raised_at ?? null) === (raisedAt ?? null)) {
+ return participant;
+ }
+
+ changed = true;
+ const updated = { ...participant };
+ if (raisedAt) {
+ updated.hand_raised_at = raisedAt;
+ } else {
+ delete updated.hand_raised_at;
+ }
+ return updated;
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ setParticipantDeafened(roomId, userId, deafened) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return;
+ }
+
+ const room = this.#roomsById.get(roomId);
+ if (!room || !Array.isArray(room.active_participants)) {
+ return;
+ }
+
+ let changed = false;
+ room.active_participants = room.active_participants.map((participant) => {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId !== targetId) {
+ return participant;
+ }
+
+ if (!!participant.is_deafened === deafened) {
+ return participant;
+ }
+
+ changed = true;
+ return {
+ ...participant,
+ is_deafened: deafened,
+ };
+ });
+
+ if (changed) {
+ this.rooms = [...this.rooms];
+ }
+ }
+
+ #setRoomParticipants(roomId, participants) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ const previous = room.active_participants || [];
+ const stateByUserId = new Map(
+ previous
+ .filter((participant) => Number(participant?.id))
+ .map((participant) => [
+ Number(participant.id),
+ {
+ is_muted: participant.is_muted === true,
+ is_deafened: participant.is_deafened === true,
+ is_video_on: participant.is_video_on === true,
+ is_screen_sharing: participant.is_screen_sharing === true,
+ watching_video: participant.watching_video === true,
+ idle_state: participant.idle_state,
+ },
+ ])
+ );
+
+ const merged = (participants || []).map((participant) => {
+ const participantId = Number(participant?.id);
+ const previousState = stateByUserId.get(participantId);
+ if (!participantId || !previousState) {
+ return participant;
+ }
+
+ return {
+ ...participant,
+ is_muted: participant.is_muted ?? previousState.is_muted,
+ is_deafened: participant.is_deafened ?? previousState.is_deafened,
+ is_video_on: participant.is_video_on ?? previousState.is_video_on,
+ is_screen_sharing:
+ participant.is_screen_sharing ?? previousState.is_screen_sharing,
+ watching_video:
+ participant.watching_video ?? previousState.watching_video,
+ idle_state: participant.idle_state ?? previousState.idle_state,
+ };
+ });
+ const mergedIds = new Set(merged.map((p) => Number(p?.id)));
+ previous.forEach((participant) => {
+ const participantId = Number(participant?.id);
+ if (participantId && !mergedIds.has(participantId)) {
+ this.setParticipantSpeaking(roomId, participantId, false);
+ }
+ });
+
+ room.active_participants = sortParticipants(merged);
+ this.rooms = [...this.rooms];
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js b/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js
new file mode 100644
index 00000000000..0dbfed1d26b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js
@@ -0,0 +1,1836 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import Service, { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import Draft from "discourse/models/draft";
+import { i18n } from "discourse-i18n";
+import { confirmMeshPrivacy } from "../../components/modal/voice-mesh-privacy-warning";
+import { reportMicAcquisitionFailure } from "../../components/modal/voice-mic-permission";
+import AudioMonitor from "../../lib/voice/audio-monitor";
+import { RING_SECONDS } from "../../lib/voice/call-constants";
+import HeartbeatManager from "../../lib/voice/heartbeat-manager";
+import IdleTracker, { idleThresholds } from "../../lib/voice/idle-tracker";
+import { consumePendingInviteRef } from "../../lib/voice/invite-ref";
+import LivekitCoordinator from "../../lib/voice/livekit-coordinator";
+import LocalAudioPipeline from "../../lib/voice/local-audio-pipeline";
+import LocalVideoManager from "../../lib/voice/local-video-manager";
+import {
+ applyOutputDevice,
+ preferredOutputDeviceId,
+ setPreferredOutputDeviceId,
+} from "../../lib/voice/media-devices";
+import MeshSignalHandler from "../../lib/voice/mesh-signal-handler";
+import ParticipantAudio from "../../lib/voice/participant-audio";
+import PeerManager from "../../lib/voice/peer-manager";
+import PresencePendingPeers from "../../lib/voice/presence-pending-peers";
+import PttManager from "../../lib/voice/ptt-manager";
+import {
+ allowedQualityTiers,
+ clampQuality,
+ preferredCameraQuality,
+ preferredScreenContent,
+ preferredScreenQuality,
+ preferredVoiceQuality,
+ QUALITY_STANDARD,
+ setPreferredCameraQuality,
+ setPreferredScreenContent,
+ setPreferredScreenQuality,
+ setPreferredVoiceQuality,
+} from "../../lib/voice/quality-preferences";
+import RemoteStreamRegistry from "../../lib/voice/remote-stream-registry";
+import { activeRingingEntries } from "../../lib/voice/ringing";
+import RoomMessageQueue from "../../lib/voice/room-message-queue";
+import RosterHandler from "../../lib/voice/roster-handler";
+import SignalingManager from "../../lib/voice/signaling";
+import {
+ playConnectedSound,
+ playDeafenSound,
+ playDisconnectedSound,
+ playMuteSound,
+ playUndeafenSound,
+ playUnmuteSound,
+ schedulePlaybackResume,
+ startWaitingSound,
+ stopCallSounds,
+} from "../../lib/voice/sound-effects";
+import {
+ participantCanSpeak,
+ remoteTrackAllowed,
+} from "../../lib/voice/stage-roles";
+import TranscriptionCoordinator from "../../lib/voice/transcription-coordinator";
+import { applyVoiceQuality } from "../../lib/voice/video-quality";
+
+export default class VoiceWebrtcService extends Service {
+ @service currentUser;
+ @service messageBus;
+ @service modal;
+ @service siteSettings;
+ @service("voice-rooms") voiceRooms;
+ @service toasts;
+
+ @tracked activeRoomId = null;
+ @tracked watchingRoomId = null;
+ @tracked audioEnabled = true;
+ @tracked deafened = false;
+ @tracked remoteStreamsRevision = 0;
+ @tracked connectionRevision = 0;
+ @tracked idleState = "active";
+ @tracked pttEnabled = false;
+ @tracked pttKey = "Space";
+ @tracked pttActive = false;
+ @tracked autoStatusEnabled = true;
+ @tracked callWidgetHidden = false;
+ @tracked outputDeviceId;
+ @tracked voiceQuality = preferredVoiceQuality();
+ @tracked cameraQuality = preferredCameraQuality();
+ @tracked screenQuality = preferredScreenQuality();
+ @tracked screenContent = preferredScreenContent();
+
+ #connectingRoomIds = new Set();
+ #activeRoomIds = new Set();
+ #joinRevision = 0;
+ #connectingParticipantSnapshots = new Map();
+ #connectingSignalQueue = new Map();
+ // Server-attested participant session per room, from the join response
+ // (rotated by livekit_token). Signal/heartbeat/state requests must carry it:
+ // the server binds signaling authority to this session instead of to roster
+ // presence, which propagates asynchronously.
+ #roomSessions = new Map();
+ // Per-room transport tag ("mesh" | "livekit"), read from the join response.
+ // Rooms without a tag (older servers, messages arriving before the join
+ // response, tests) default to mesh, so every guard below is a tautology on
+ // pure-P2P installs.
+ #roomTransports = new Map();
+ // ICE configuration from the most recent join response. Server-provided so
+ // TURN credentials can be minted per user and per session instead of being
+ // exposed as client site settings. Peers are only created for active rooms,
+ // and a room only becomes active after its join response arrives, so this
+ // is always populated before it is read.
+ #iceConfig = null;
+ #roomHandlerCallbacks = new Map();
+ #deferredTeardownTimers = new Set();
+ #pendingPlaybackElements = new WeakSet();
+
+ #signaling;
+ #peerManager;
+ #meshSignals;
+ #audioMonitor;
+ #idleTracker;
+ #localAudio;
+ #localVideo;
+ #pttManager;
+ #roomMessageQueue;
+ #remoteStreamRegistry;
+ #participantAudio;
+ #heartbeat;
+ #presencePending;
+ #livekit;
+ #roster;
+ #transcription;
+
+ constructor() {
+ super(...arguments);
+
+ this.#pttManager = new PttManager({
+ onPress: () => this.#handlePttPress(),
+ onReleaseImmediate: () => this.#handlePttRelease(),
+ onReleaseDebounced: () => this.#broadcastMuteState(),
+ isConnected: () => this.#activeRoomIds.size > 0,
+ });
+
+ this.pttEnabled = this.#pttManager.enabled;
+ this.pttKey = this.#pttManager.key;
+
+ this.#signaling = new SignalingManager({
+ isActiveRoom: (id) => this.#activeRoomIds.has(id),
+ hasPeer: (roomId, uid) => this.#peerManager.has(roomId, uid),
+ getParticipantSessionId: (roomId) => this.#roomSessions.get(roomId),
+ });
+
+ this.#peerManager = new PeerManager({
+ getIceServers: () => this.iceServers,
+ getIceTransportPolicy: () => this.iceTransportPolicy,
+ getLocalStream: () => this.localStream,
+ getLocalVideoTrack: (roomId, uid) =>
+ this.#localVideo.trackFor(roomId, uid),
+ getLocalScreenAudioTrack: (roomId, uid) =>
+ this.#localVideo.screenAudioTrackFor(roomId, uid),
+ sendSignal: (roomId, uid, payload) =>
+ this.#signaling.send(roomId, uid, payload),
+ flushQueuedSignals: (roomId, uid) =>
+ this.#signaling.flushQueued(roomId, uid),
+ canPublishMedia: (roomId) => this.#canPublishMediaIn(roomId),
+ onTrack: (roomId, uid, track, streams) =>
+ this.#registerRemoteTrack(roomId, uid, track, streams),
+ clearSignalQueue: (roomId, uid) =>
+ this.#signaling.clearForPeer(roomId, uid),
+ onPeerDestroyed: (roomId, uid) => this.#removeRemoteStream(roomId, uid),
+ onPeerConnected: (roomId, uid, pc) => {
+ const tier = this.effectiveVoiceQuality(roomId);
+ if (tier !== QUALITY_STANDARD) {
+ const sender = PeerManager.micSenderFor(pc);
+ if (sender?.track) {
+ applyVoiceQuality([sender], tier);
+ }
+ }
+ },
+ shouldRestartPeer: (roomId, uid) =>
+ this.#meshSignals.shouldMaintainPeerConnection(roomId, uid),
+ });
+
+ this.#audioMonitor = new AudioMonitor({
+ onSpeakingChange: (roomId, userId, speaking) =>
+ this.voiceRooms?.setParticipantSpeaking(roomId, userId, speaking),
+ onVoiceActivity: () => this.#idleTracker?.onVoiceActivity(),
+ });
+
+ this.#idleTracker = new IdleTracker({
+ onIdleStateChange: (state, wasAfk) =>
+ this.#handleIdleStateChange(state, wasAfk),
+ onAutoMute: () => this.#handleAutoMute(),
+ onDisconnect: () => this.#handleIdleDisconnect(),
+ getThresholds: () => idleThresholds(this.siteSettings),
+ });
+
+ this.#localAudio = new LocalAudioPipeline({
+ onStreamChanged: () => this.#syncLocalStreamState(),
+ onSuppressionFailed: () => {
+ this.toasts.error({
+ duration: 5000,
+ data: {
+ message: i18n("voice.voice_settings.noise_suppression_failed"),
+ },
+ });
+ },
+ replaceTrackOnPeers: () => this.#replaceTrackOnAllPeers(),
+ });
+
+ this.outputDeviceId = preferredOutputDeviceId();
+
+ this.#roomMessageQueue = new RoomMessageQueue();
+
+ this.#remoteStreamRegistry = new RemoteStreamRegistry({
+ onChange: () => this.remoteStreamsRevision++,
+ onMicTrack: (roomId, userId, stream) => {
+ this.#audioMonitor.ensure(roomId, userId, stream, false);
+ this.#transcription.attachRemote(roomId, userId, stream);
+ },
+ });
+
+ this.#transcription = new TranscriptionCoordinator({
+ siteSettings: this.siteSettings,
+ getParticipantSessionId: (roomId) => this.#roomSessions.get(roomId),
+ getCurrentUserId: () => this.currentUser?.id,
+ getRoom: (roomId) => this.voiceRooms?.roomById(roomId),
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ getActiveRoomIds: () => this.#activeRoomIds,
+ getRemoteUserIds: (roomId) =>
+ this.#remoteStreamRegistry.userIdsFor(roomId),
+ getRemoteStream: (roomId, userId) =>
+ this.#remoteStreamRegistry.streamFor(roomId, userId),
+ getLocalStream: () => this.localStream,
+ setParticipantTranscribing: (roomId, transcribing) =>
+ this.voiceRooms?.setParticipantVideoState(
+ roomId,
+ this.currentUser?.id,
+ { is_transcribing: transcribing }
+ ),
+ saveDraft: (key, sequence, data) =>
+ Draft.save(key, sequence, data, this.messageBus.clientId),
+ openComposer: (opts) =>
+ getOwner(this).lookup("service:composer").open(opts),
+ showError: (messageKey) =>
+ this.toasts.error({
+ duration: 5000,
+ data: { message: i18n(messageKey) },
+ }),
+ });
+
+ this.#participantAudio = new ParticipantAudio({
+ isDeafened: () => this.deafened,
+ });
+
+ this.#heartbeat = new HeartbeatManager({
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ buildPayload: (roomId) => this.#heartbeatPayload(roomId),
+ onExpelled: (roomId) => this.leave({ id: roomId }),
+ });
+
+ this.#presencePending = new PresencePendingPeers({
+ onExpired: (roomId, userId) => {
+ if (!this.#meshSignals.shouldMaintainPeerConnection(roomId, userId)) {
+ this.#peerManager.destroy(roomId, userId);
+ }
+ },
+ });
+
+ this.#localVideo = new LocalVideoManager({
+ peerManager: this.#peerManager,
+ getParticipantSessionId: (roomId) => this.#roomSessions.get(roomId),
+ getLivekitSession: (roomId) => this.#livekit.sessionFor(roomId),
+ isMeshRoom: (roomId) => this.#isMeshRoom(roomId),
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ isConnectingRoom: (roomId) => this.#connectingRoomIds.has(roomId),
+ getFirstActiveRoomId: () => this.#firstActiveRoomId(),
+ getActiveRoomId: () => this.activeRoomId,
+ getRoom: (roomId) => this.voiceRooms?.roomById(roomId),
+ canPublishVideo: (roomId) => this.canPublishVideo(roomId),
+ getCameraQuality: (roomId) => this.effectiveCameraQuality(roomId),
+ getScreenQuality: (roomId) => this.effectiveScreenQuality(roomId),
+ getScreenContent: () => this.screenContent,
+ isBlurAllowed: () => this.videoBlurAvailable,
+ setParticipantVideoState: (roomId, state) =>
+ this.voiceRooms?.setParticipantVideoState(
+ roomId,
+ this.currentUser?.id,
+ state
+ ),
+ showError: (messageKey) =>
+ this.toasts.error({
+ duration: 5000,
+ data: { message: i18n(messageKey) },
+ }),
+ });
+
+ this.#meshSignals = new MeshSignalHandler({
+ peerManager: this.#peerManager,
+ signaling: this.#signaling,
+ presencePending: this.#presencePending,
+ getCurrentUserId: () => this.currentUser?.id,
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ getRoom: (roomId) => this.voiceRooms?.roomById(roomId),
+ isRoleChangeInProgress: (roomId) =>
+ this.#roster.isRoleChangeInProgress(roomId),
+ addProvisionalParticipant: (roomId, participant) =>
+ this.voiceRooms?.addParticipant(roomId, participant),
+ onOfferHandled: async (roomId) => {
+ if (this.localVideoKind) {
+ await this.#localVideo.syncSenders(roomId);
+ }
+ },
+ });
+
+ this.#livekit = new LivekitCoordinator({
+ getCurrentUserId: () => this.currentUser?.id,
+ getParticipantSessionId: (roomId) => this.#roomSessions.get(roomId),
+ onParticipantSessionRenewed: (roomId, sessionId) => {
+ if (sessionId) {
+ this.#roomSessions.set(roomId, sessionId);
+ }
+ },
+ getLocalStream: () => this.localStream,
+ getLocalVideoTrack: () => this.localVideoTrack,
+ getLocalScreenAudioTrack: () => this.localScreenAudioTrack,
+ getLocalVideoKind: () => this.localVideoKind,
+ getVideoPublisherCount: (roomId) => this.videoPublisherCount(roomId),
+ getQualityTiers: (roomId) => ({
+ voice: this.effectiveVoiceQuality(roomId),
+ camera: this.effectiveCameraQuality(roomId),
+ screen: this.effectiveScreenQuality(roomId),
+ }),
+ onTrack: (roomId, userId, track, streams) =>
+ this.#remoteStreamRegistry.register(roomId, userId, track, streams),
+ removeRemoteStream: (roomId, userId) =>
+ this.#removeRemoteStream(roomId, userId),
+ getRemoteUserIds: (roomId) =>
+ this.#remoteStreamRegistry.userIdsFor(roomId),
+ bumpConnectionRevision: () => this.#bumpConnectionRevision(),
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ isConnectingRoom: (roomId) => this.#connectingRoomIds.has(roomId),
+ isJoinCurrent: (revision) => this.#joinRevision === revision,
+ leave: (roomId, options) => this.leave({ id: roomId }, options),
+ unwindFailedJoin: (roomId) => {
+ this.#handleJoinFailure(roomId);
+ // The failure landed after the active-mark, which #handleJoinFailure
+ // (built for pre-mark failures) doesn't unwind.
+ this.#clearActiveRoomId(roomId);
+ },
+ showError: (messageKey) =>
+ this.toasts.error({
+ duration: 8000,
+ data: { message: i18n(messageKey) },
+ }),
+ showNotice: (messageKey) =>
+ this.toasts.default({
+ duration: 8000,
+ data: { message: i18n(messageKey) },
+ }),
+ });
+
+ this.#roster = new RosterHandler({
+ peerManager: this.#peerManager,
+ signaling: this.#signaling,
+ presencePending: this.#presencePending,
+ livekit: this.#livekit,
+ toasts: this.toasts,
+ getCurrentUserId: () => this.currentUser?.id,
+ getChatSound: () => this.currentUser?.chat_sound,
+ getRoom: (roomId) => this.voiceRooms?.roomById(roomId),
+ isActiveRoom: (roomId) => this.#activeRoomIds.has(roomId),
+ isConnectingRoom: (roomId) => this.#connectingRoomIds.has(roomId),
+ isMeshRoom: (roomId) => this.#isMeshRoom(roomId),
+ registerTrack: (roomId, userId, track) =>
+ this.#registerRemoteTrack(roomId, userId, track),
+ getRemoteUserIds: (roomId) =>
+ this.#remoteStreamRegistry.userIdsFor(roomId),
+ removeRemoteStream: (roomId, userId) =>
+ this.#removeRemoteStream(roomId, userId),
+ removeAllRemoteStreams: (roomId) => this.#removeAllRemoteStreams(roomId),
+ getLocalVideoKind: () => this.localVideoKind,
+ syncVideoSenders: (roomId) => this.#localVideo.syncSenders(roomId),
+ stopLocalVideo: () => this.#localVideo.stop(),
+ getLocalStream: () => this.localStream,
+ acquireMicrophone: () => this.#acquireMicrophoneWithFeedback(),
+ setMicEnabled: (enabled) => this.#setMicEnabled(enabled),
+ stopLocalAudio: () => this.#localAudio.stop(),
+ ensureLocalAudioMonitor: (roomId) =>
+ this.#audioMonitor.ensure(
+ roomId,
+ this.currentUser?.id,
+ this.localStream,
+ true
+ ),
+ });
+
+ try {
+ const stored = localStorage.getItem("voice_auto_status_enabled");
+ this.autoStatusEnabled = stored !== "false";
+ } catch {
+ this.autoStatusEnabled = true;
+ }
+
+ try {
+ this.callWidgetHidden =
+ localStorage.getItem("voice_call_widget_hidden") === "true";
+ } catch {
+ this.callWidgetHidden = false;
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+
+ this.#joinRevision++;
+ this.#pttManager.destroy();
+ this.#idleTracker.stop();
+ this.#audioMonitor.destroyAll();
+ this.#peerManager.destroyAll();
+ this.#livekit.destroy();
+ this.#signaling.destroy();
+
+ this.#localVideo.destroy();
+ this.#localAudio.stop();
+ this.#transcription.destroy();
+
+ this.#roomHandlerCallbacks.forEach((callback, roomId) => {
+ this.voiceRooms?.unregisterRoomHandler(roomId, callback);
+ });
+ this.#roomHandlerCallbacks.clear();
+ this.#heartbeat.stopAll();
+ this.#deferredTeardownTimers.forEach((timer) => clearTimeout(timer));
+ this.#deferredTeardownTimers.clear();
+ this.#connectingRoomIds.clear();
+ this.#connectingParticipantSnapshots.clear();
+ this.#connectingSignalQueue.clear();
+ this.#roomTransports.clear();
+ this.#roomSessions.clear();
+ this.#presencePending.clearAll();
+ this.#roomMessageQueue.clearAll();
+ }
+
+ get iceServers() {
+ return this.#iceConfig?.servers ?? [];
+ }
+
+ get iceTransportPolicy() {
+ return this.#iceConfig?.transport_policy ?? "all";
+ }
+
+ // --- Local audio pipeline delegates ---
+
+ get localStream() {
+ return this.#localAudio.stream;
+ }
+
+ get noiseSuppressionEnabled() {
+ return this.#localAudio.noiseSuppressionEnabled;
+ }
+
+ get noiseSuppressionState() {
+ return this.#localAudio.noiseSuppressionState;
+ }
+
+ get noiseSuppressionMode() {
+ return this.#localAudio.noiseSuppressionMode;
+ }
+
+ get echoCancellation() {
+ return this.#localAudio.echoCancellation;
+ }
+
+ get autoGainControl() {
+ return this.#localAudio.autoGainControl;
+ }
+
+ setNoiseSuppressionMode(mode) {
+ return this.#localAudio.setNoiseSuppressionMode(mode);
+ }
+
+ setEchoCancellation(enabled) {
+ return this.#localAudio.setEchoCancellation(enabled);
+ }
+
+ setAutoGainControl(enabled) {
+ return this.#localAudio.setAutoGainControl(enabled);
+ }
+
+ get gateThreshold() {
+ return this.#localAudio.gateThreshold;
+ }
+
+ get inputDeviceId() {
+ return this.#localAudio.inputDeviceId;
+ }
+
+ setInputDevice(deviceId) {
+ return this.#localAudio.setInputDevice(deviceId);
+ }
+
+ setGateThreshold(value) {
+ return this.#localAudio.setGateThreshold(value);
+ }
+
+ // --- Subtitles & transcript delegates ---
+
+ get subtitlesAvailable() {
+ return this.#transcription.available;
+ }
+
+ get subtitlesEnabled() {
+ return this.#transcription.enabled;
+ }
+
+ get subtitlesLoading() {
+ return this.#transcription.loading;
+ }
+
+ get subtitlesProgress() {
+ return this.#transcription.progress;
+ }
+
+ get captions() {
+ return this.#transcription.captions;
+ }
+
+ toggleSubtitles() {
+ this.#transcription.toggle();
+ }
+
+ get transcriptRecording() {
+ return this.#transcription.recording;
+ }
+
+ get transcriptRoomId() {
+ return this.#transcription.roomId;
+ }
+
+ get transcriptEntries() {
+ return this.#transcription.entries;
+ }
+
+ get transcriptEntriesRoomId() {
+ return this.#transcription.entriesRoomId;
+ }
+
+ get transcriptStartedAt() {
+ return this.#transcription.startedAt;
+ }
+
+ isTranscribingRoom(roomId) {
+ return this.#transcription.isTranscribingRoom(roomId);
+ }
+
+ toggleTranscriptRecording(roomId) {
+ this.#transcription.toggleRecording(roomId);
+ }
+
+ openTranscriptDraft() {
+ return this.#transcription.openDraft();
+ }
+
+ captionsFor(roomId) {
+ return this.#transcription.captionsFor(roomId);
+ }
+
+ get remoteStreams() {
+ this.remoteStreamsRevision;
+ return this.#remoteStreamRegistry.allStreams();
+ }
+
+ get remoteScreenAudioStreams() {
+ this.remoteStreamsRevision;
+ return this.#remoteStreamRegistry.allScreenAudioStreams();
+ }
+
+ remoteStreamsFor(roomId) {
+ this.remoteStreamsRevision;
+ return this.#remoteStreamRegistry.streamsFor(roomId);
+ }
+
+ // The server-attested session participant actions (hand raising, state
+ // changes) must carry to be accepted.
+ participantSessionIdFor(roomId) {
+ return this.#roomSessions.get(roomId);
+ }
+
+ remoteStreamFor(roomId, userId) {
+ this.remoteStreamsRevision;
+ return this.#remoteStreamRegistry.streamFor(roomId, userId);
+ }
+
+ connectionStateFor(roomId) {
+ this.connectionRevision;
+ if (this.#connectingRoomIds.has(roomId)) {
+ return "connecting";
+ }
+ if (this.#activeRoomIds.has(roomId)) {
+ return "connected";
+ }
+ return "idle";
+ }
+
+ get hasActiveRoom() {
+ return !!this.activeRoomId;
+ }
+
+ get activeRoom() {
+ return this.activeRoomId
+ ? this.voiceRooms?.roomById(this.activeRoomId)
+ : null;
+ }
+
+ isActiveRoom(roomId) {
+ return Number(this.activeRoomId) === Number(roomId);
+ }
+
+ #setActiveRoomId(roomId) {
+ this.activeRoomId = roomId ?? null;
+ }
+
+ #clearActiveRoomId(roomId) {
+ if (Number(this.activeRoomId) !== Number(roomId)) {
+ return;
+ }
+
+ this.activeRoomId = this.#activeRoomIds.values().next().value ?? null;
+ }
+
+ #canSpeakInRoom(room) {
+ return participantCanSpeak(room, this.currentUser?.id);
+ }
+
+ #isMeshRoom(roomId) {
+ return (this.#roomTransports.get(roomId) ?? "mesh") === "mesh";
+ }
+
+ isLivekitRoom(roomId) {
+ return this.#roomTransports.get(roomId) === "livekit";
+ }
+
+ async #acquireMicrophoneWithFeedback() {
+ const acquired = await this.#localAudio.acquireMicrophone();
+ if (!acquired) {
+ reportMicAcquisitionFailure(this.#localAudio.lastAcquisitionError, {
+ modal: this.modal,
+ toasts: this.toasts,
+ });
+ }
+ return acquired;
+ }
+
+ async join(room) {
+ if (!room?.id) {
+ return;
+ }
+
+ // Several call controls can request a join. Once this room already owns
+ // a media session, a second request would connect another LiveKit client
+ // with the same user identity and evict the first one.
+ if (
+ this.#activeRoomIds.has(room.id) ||
+ this.#connectingRoomIds.has(room.id)
+ ) {
+ return;
+ }
+
+ // Confirmed before any join state is touched, so cancelling leaves
+ // nothing to unwind.
+ const meshPrivacyConfirmed = await confirmMeshPrivacy(room, {
+ currentUser: this.currentUser,
+ modal: this.modal,
+ siteSettings: this.siteSettings,
+ });
+ if (!meshPrivacyConfirmed) {
+ return;
+ }
+
+ // Whatever call loop was sounding (ringtone on an answered call, waiting
+ // tone when hopping rooms) is over once a join starts.
+ stopCallSounds();
+
+ // Bump the join revision so any in-flight join for a different room
+ // will detect it has been superseded and abort.
+ const revision = ++this.#joinRevision;
+
+ this.#connectingRoomIds.add(room.id);
+ this.#bumpConnectionRevision();
+
+ // Leave rooms that are already active.
+ for (const activeRoomId of this.#activeRoomIds) {
+ if (activeRoomId !== room.id) {
+ this.leave({ id: activeRoomId }, { keepLocalStream: true });
+ }
+ }
+
+ // Abort any other in-progress joins (still in connecting state).
+ for (const connectingId of this.#connectingRoomIds) {
+ if (connectingId !== room.id) {
+ this.#connectingRoomIds.delete(connectingId);
+ this.#teardownRoom(connectingId);
+ }
+ }
+
+ // eslint-disable-next-line no-console
+ console.log(`[voice] joining room ${room.id}`);
+
+ this.#registerRoomHandler(room.id);
+
+ let response;
+
+ try {
+ const joinData = {};
+ if (
+ !this.autoStatusEnabled ||
+ !this.siteSettings.voice_auto_status_enabled
+ ) {
+ joinData.skip_status = true;
+ }
+ const invitedBy = consumePendingInviteRef(room);
+ if (invitedBy) {
+ joinData.invited_by = invitedBy;
+ }
+ // Carrying the live session makes a duplicated join idempotent on the
+ // server: it refreshes the existing grant instead of rotating it.
+ const existingSessionId = this.#roomSessions.get(room.id);
+ if (existingSessionId) {
+ joinData.participant_session_id = existingSessionId;
+ }
+ response = await ajax(`/voice/rooms/${room.id}/join`, {
+ type: "POST",
+ data: joinData,
+ });
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to join room", error);
+ this.#handleJoinFailure(room.id);
+ return;
+ }
+
+ if (this.#joinRevision !== revision) {
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: { participant_session_id: response?.participant_session_id },
+ });
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] join response, active_participants:`,
+ response?.room?.active_participants
+ );
+
+ this.#roomTransports.set(room.id, response?.transport ?? "mesh");
+ if (response?.participant_session_id) {
+ this.#roomSessions.set(room.id, response.participant_session_id);
+ }
+ this.#iceConfig = response?.ice ?? this.#iceConfig;
+
+ const joinedRoom = response?.room;
+ if (joinedRoom) {
+ // The join response is serialized as the (now participating) user, so
+ // it carries the per-user chat fields the directory payloads gate off —
+ // fold it in so the room page sees them.
+ this.voiceRooms?.upsertRoom?.(joinedRoom);
+ }
+ const isStageListener =
+ joinedRoom?.room_type === "stage" && !this.#canSpeakInRoom(joinedRoom);
+
+ if (!isStageListener && !this.localStream) {
+ const acquired = await this.#acquireMicrophoneWithFeedback();
+ if (!acquired) {
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: { participant_session_id: this.#roomSessions.get(room.id) },
+ });
+ this.#handleJoinFailure(room.id);
+ return;
+ }
+ }
+
+ if (this.#joinRevision !== revision) {
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: { participant_session_id: this.#roomSessions.get(room.id) },
+ });
+ return;
+ }
+
+ if (this.localStream) {
+ this.#setMicEnabled(!this.pttEnabled);
+ }
+
+ // Only mark the room as active after the microphone is ready.
+ // This prevents incoming MessageBus signals from creating peer
+ // connections before localStream is available (race condition that
+ // caused voice to fail on first join).
+ this.#activeRoomIds.add(room.id);
+ this.#setActiveRoomId(room.id);
+
+ if (!this.#isMeshRoom(room.id)) {
+ const connected = await this.#livekit.connect(
+ room,
+ response?.livekit,
+ revision
+ );
+ if (!connected) {
+ return;
+ }
+ }
+
+ this.#addLocalParticipant(room.id);
+
+ if (this.localStream) {
+ this.#audioMonitor.ensure(
+ room.id,
+ this.currentUser?.id,
+ this.localStream,
+ true
+ );
+ }
+
+ this.#heartbeat.start(room.id);
+ this.#idleTracker.start();
+
+ const latestParticipants =
+ this.#connectingParticipantSnapshots.get(room.id) ??
+ response?.room?.active_participants;
+ this.#connectingParticipantSnapshots.delete(room.id);
+
+ if (latestParticipants) {
+ await this.#roster.handleParticipants(room.id, {
+ participants: latestParticipants,
+ });
+ }
+
+ const queuedSignals = this.#connectingSignalQueue.get(room.id) || [];
+ this.#connectingSignalQueue.delete(room.id);
+
+ if (this.#isMeshRoom(room.id)) {
+ for (const payload of queuedSignals) {
+ await this.#meshSignals.handle(room.id, payload);
+ }
+ }
+
+ this.#connectingRoomIds.delete(room.id);
+ this.#bumpConnectionRevision();
+
+ if (this.pttEnabled && this.localStream) {
+ this.#pttManager.startListening();
+ }
+
+ if (this.watchingRoomId === room.id) {
+ this.setWatching(room.id, true);
+ }
+
+ playConnectedSound(this.currentUser?.chat_sound);
+
+ // Joining an ephemeral call room alone while someone is still being rung
+ // means the other side hasn't picked up yet: loop the waiting tone until
+ // a peer arrives or the last ring runs out. Merely being alone isn't
+ // enough — rejoining a call everyone has left must stay silent.
+ const others = (latestParticipants || []).filter(
+ (participant) => Number(participant?.id) !== this.currentUser?.id
+ );
+ const now = Date.now();
+ const ringing = activeRingingEntries(joinedRoom, now);
+ if (joinedRoom?.ephemeral && others.length === 0 && ringing.length > 0) {
+ const lastRingEndsAt =
+ Math.max(...ringing.map((entry) => entry.notified_at * 1000)) +
+ RING_SECONDS * 1000;
+ startWaitingSound(lastRingEndsAt - now, this.currentUser?.chat_sound);
+ }
+ }
+
+ leave(room, options = {}) {
+ if (!room?.id) {
+ return;
+ }
+
+ const keepLocalStream = options.keepLocalStream === true;
+ // Local-only teardown: everything below runs except DELETE /leave. Used
+ // when the server must not close the presence/session that now belongs
+ // to someone else (e.g. a newer tab after DUPLICATE_IDENTITY).
+ const skipServer = options.skipServer === true;
+ const wasConnecting = this.#connectingRoomIds.has(room.id);
+ const wasConnected = this.#activeRoomIds.has(room.id);
+
+ if (this.localVideoKind && (wasConnected || wasConnecting)) {
+ this.#localVideo.stop({ broadcast: false }).catch(() => {});
+ }
+
+ if (wasConnecting) {
+ this.#joinRevision++;
+ }
+
+ // Hanging up while still ringing (caller waiting alone) ends the ring.
+ stopCallSounds();
+ this.#connectingParticipantSnapshots.delete(room.id);
+ this.#connectingSignalQueue.delete(room.id);
+ this.#pttManager.resetActive();
+ this.pttActive = false;
+ if (!skipServer) {
+ // The session id lets the server drop a leave from a stale tab whose
+ // session a newer join has already superseded.
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: { participant_session_id: this.#roomSessions.get(room.id) },
+ });
+ }
+ this.#connectingRoomIds.delete(room.id);
+ this.#activeRoomIds.delete(room.id);
+ this.#clearActiveRoomId(room.id);
+ this.#bumpConnectionRevision();
+
+ if (wasConnected && !keepLocalStream) {
+ playDisconnectedSound(this.currentUser?.chat_sound);
+ }
+ this.#removeLocalParticipant(room.id);
+ this.#heartbeat.stop(room.id);
+
+ if (this.#activeRoomIds.size === 0) {
+ this.#idleTracker.stop();
+ this.#pttManager.stopListening();
+ }
+
+ const teardown = () => {
+ this.#audioMonitor.teardown(room.id, this.currentUser?.id);
+ this.#teardownRoom(room.id);
+
+ if (!keepLocalStream && this.#activeRoomIds.size === 0) {
+ this.#localAudio.stop();
+ }
+ };
+
+ if (wasConnected && !keepLocalStream) {
+ const timer = setTimeout(() => {
+ this.#deferredTeardownTimers.delete(timer);
+ teardown();
+ }, 500);
+ this.#deferredTeardownTimers.add(timer);
+ } else {
+ teardown();
+ }
+ }
+
+ @action
+ attachStream(stream, element) {
+ if (!element || !stream) {
+ return;
+ }
+
+ if (element.srcObject === stream) {
+ return;
+ }
+
+ element.srcObject = stream;
+ element.autoplay = true;
+ element.playsInline = true;
+
+ const isLocal = stream === this.localStream;
+ if (isLocal) {
+ element.muted = true;
+ element.volume = 0;
+ } else {
+ const participant = this.#remoteStreamRegistry.participantFor(stream);
+ if (participant) {
+ const { roomId, userId, screenAudio } = participant;
+ this.#participantAudio.trackElement(
+ roomId,
+ userId,
+ element,
+ screenAudio ? "screen" : "voice"
+ );
+ this.#participantAudio.apply(roomId, userId);
+ }
+ applyOutputDevice(element, this.outputDeviceId);
+ }
+
+ if (typeof element.play === "function") {
+ try {
+ const playPromise = element.play();
+ playPromise?.catch?.((error) => {
+ if (error?.name === "NotAllowedError") {
+ schedulePlaybackResume(element, this.#pendingPlaybackElements);
+ } else {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] audio element failed to play", error);
+ }
+ });
+ } catch (error) {
+ if (error?.name === "NotAllowedError") {
+ schedulePlaybackResume(element, this.#pendingPlaybackElements);
+ } else {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] audio element failed to play", error);
+ }
+ }
+ }
+ }
+
+ setParticipantVolume(roomId, userId, volume) {
+ this.#participantAudio.setVolume(roomId, userId, volume);
+ }
+
+ getParticipantVolume(roomId, userId) {
+ return this.#participantAudio.volumeFor(roomId, userId);
+ }
+
+ toggleParticipantMute(roomId, userId) {
+ const newMutedState = this.#participantAudio.toggleMuted(roomId, userId);
+ this.voiceRooms?.setParticipantMuted(roomId, userId, newMutedState);
+ return newMutedState;
+ }
+
+ isParticipantMuted(roomId, userId) {
+ return this.#participantAudio.isMuted(roomId, userId);
+ }
+
+ #setMicEnabled(enabled) {
+ this.audioEnabled = enabled;
+ for (const track of this.localStream?.getAudioTracks() || []) {
+ track.enabled = enabled;
+ }
+ }
+
+ toggleMute() {
+ if (this.pttEnabled) {
+ return;
+ }
+
+ this.#setMicEnabled(!this.audioEnabled);
+
+ if (this.audioEnabled) {
+ playUnmuteSound(this.currentUser?.chat_sound);
+ this.#idleTracker.wasAutoMuted = false;
+ this.#idleTracker.resetActivity();
+ } else {
+ playMuteSound(this.currentUser?.chat_sound);
+ }
+
+ if (this.audioEnabled && this.deafened) {
+ this.deafened = false;
+ }
+
+ this.#broadcastMuteState();
+ }
+
+ toggleDeafen() {
+ this.deafened = !this.deafened;
+
+ if (this.deafened) {
+ playDeafenSound(this.currentUser?.chat_sound);
+ } else {
+ playUndeafenSound(this.currentUser?.chat_sound);
+ }
+
+ if (this.deafened) {
+ this.#setMicEnabled(false);
+ } else {
+ this.#setMicEnabled(!this.pttEnabled);
+ }
+
+ this.#participantAudio.applyAll();
+
+ this.#broadcastMuteState();
+ }
+
+ // --- Quality tiers ---
+
+ // Effective tier: the user's stored preference clamped by the room's
+ // optional cap and the site setting cap. Passing no roomId (settings modal
+ // opened outside a call) clamps against the site cap only.
+ effectiveVoiceQuality(roomId = this.activeRoomId) {
+ return clampQuality(
+ this.voiceQuality,
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_voice_quality
+ );
+ }
+
+ effectiveCameraQuality(roomId = this.activeRoomId) {
+ return clampQuality(
+ this.cameraQuality,
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_camera_quality
+ );
+ }
+
+ effectiveScreenQuality(roomId = this.activeRoomId) {
+ return clampQuality(
+ this.screenQuality,
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_screen_share_quality
+ );
+ }
+
+ #roomQualityCap(roomId) {
+ return this.voiceRooms?.roomById(roomId)?.max_quality_profile;
+ }
+
+ allowedVoiceQualityTiers(roomId = this.activeRoomId) {
+ return allowedQualityTiers(
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_voice_quality
+ );
+ }
+
+ allowedCameraQualityTiers(roomId = this.activeRoomId) {
+ return allowedQualityTiers(
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_camera_quality
+ );
+ }
+
+ allowedScreenQualityTiers(roomId = this.activeRoomId) {
+ return allowedQualityTiers(
+ this.#roomQualityCap(roomId),
+ this.siteSettings.voice_max_screen_share_quality
+ );
+ }
+
+ @action
+ setVoiceQuality(tier) {
+ this.voiceQuality = tier;
+ setPreferredVoiceQuality(tier);
+ this.#applyVoiceQualityToPeers();
+ }
+
+ @action
+ setCameraQuality(tier) {
+ this.cameraQuality = tier;
+ setPreferredCameraQuality(tier);
+ this.#localVideo.refreshQuality();
+ }
+
+ @action
+ setScreenQuality(tier) {
+ this.screenQuality = tier;
+ setPreferredScreenQuality(tier);
+ this.#localVideo.refreshQuality();
+ }
+
+ @action
+ setScreenContent(content) {
+ this.screenContent = content;
+ setPreferredScreenContent(content);
+ this.#localVideo.refreshQuality({ contentHintChanged: true });
+ }
+
+ async #applyVoiceQualityToPeers() {
+ for (const [roomId] of this.#peerManager.allPeerConnections()) {
+ await applyVoiceQuality(
+ this.#peerManager.micSendersFor(roomId),
+ this.effectiveVoiceQuality(roomId)
+ );
+ }
+ }
+
+ // --- Device selection & input sensitivity ---
+
+ setOutputDevice(deviceId) {
+ this.outputDeviceId = deviceId;
+ setPreferredOutputDeviceId(deviceId);
+ this.#participantAudio.setOutputDevice(deviceId);
+ }
+
+ // --- Video & screen sharing ---
+
+ get screenShareSupported() {
+ return !!navigator.mediaDevices?.getDisplayMedia;
+ }
+
+ videoAllowedIn(room) {
+ return !!(
+ this.siteSettings.voice_video_enabled &&
+ room?.video_enabled &&
+ (room?.room_type !== "stage" || this.#canSpeakInRoom(room))
+ );
+ }
+
+ videoPublisherCount(roomId) {
+ const room = this.voiceRooms?.roomById(roomId);
+ return (room?.active_participants || []).filter(
+ (participant) =>
+ participant?.is_video_on || participant?.is_screen_sharing
+ ).length;
+ }
+
+ canPublishVideo(roomId) {
+ const room = this.voiceRooms?.roomById(roomId);
+ if (!room || !this.videoAllowedIn(room)) {
+ return false;
+ }
+ if (!this.#activeRoomIds.has(roomId)) {
+ return false;
+ }
+ if (this.localVideoKind) {
+ return true;
+ }
+ return (
+ this.videoPublisherCount(roomId) <
+ this.siteSettings.voice_video_max_publishers
+ );
+ }
+
+ get localVideoStream() {
+ return this.#localVideo.stream;
+ }
+
+ get localVideoKind() {
+ return this.#localVideo.kind;
+ }
+
+ get videoBlurEnabled() {
+ return this.#localVideo.blurEnabled;
+ }
+
+ get videoBlurAmount() {
+ return this.#localVideo.blurAmount;
+ }
+
+ get videoInputDeviceId() {
+ return this.#localVideo.inputDeviceId;
+ }
+
+ toggleCamera() {
+ return this.#localVideo.toggleCamera();
+ }
+
+ toggleScreenShare() {
+ return this.#localVideo.toggleScreenShare();
+ }
+
+ toggleVideoBlur() {
+ return this.#localVideo.toggleBlur();
+ }
+
+ setVideoBlurAmount(value) {
+ this.#localVideo.setBlurAmount(value);
+ }
+
+ setVideoInputDevice(deviceId) {
+ return this.#localVideo.setInputDevice(deviceId);
+ }
+
+ // Whether the site allows background blur; distinct from browser support
+ // so the UI can tell "turned off by admin" apart from "can't run here".
+ get videoBlurAvailable() {
+ return !!this.siteSettings.voice_video_background_blur_enabled;
+ }
+
+ get videoBlurSupported() {
+ return this.#localVideo.blurSupported;
+ }
+
+ setWatching(roomId, watching, options = {}) {
+ if (watching) {
+ this.watchingRoomId = roomId;
+ } else if (this.watchingRoomId === roomId) {
+ this.watchingRoomId = null;
+ }
+
+ if (!this.#activeRoomIds.has(roomId)) {
+ return;
+ }
+
+ // The room page used to hold the only controls that stop a camera or
+ // screen share, so leaving it stopped publishing. A persistent call widget
+ // is also a visible control surface; when it is present, route changes can
+ // keep video alive without leaving capture running invisibly.
+ const keepVideo = options.keepVideo === true;
+ const stoppingVideo = !watching && !keepVideo && !!this.localVideoKind;
+ if (stoppingVideo) {
+ this.#localVideo.stop({ broadcast: false }).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to stop video on page leave", error);
+ });
+ }
+
+ const localState = { watching_video: watching };
+ const data = { watching };
+ if (stoppingVideo) {
+ localState.is_video_on = false;
+ localState.is_screen_sharing = false;
+ data.video = false;
+ data.screen = false;
+ }
+
+ this.voiceRooms?.setParticipantVideoState(
+ roomId,
+ this.currentUser?.id,
+ localState
+ );
+
+ data.participant_session_id = this.#roomSessions.get(roomId);
+ ajax(`/voice/rooms/${roomId}/state`, {
+ type: "POST",
+ data,
+ }).catch(() => {});
+
+ // The roster flag above drives tiles on both transports; on the SFU the
+ // watching state additionally gates the actual video subscriptions.
+ if (!this.#isMeshRoom(roomId)) {
+ this.#livekit.sessionFor(roomId)?.setVideoSubscriptionsEnabled(watching);
+ }
+ }
+
+ @action
+ attachVideoStream(stream, element) {
+ if (!element || !stream) {
+ return;
+ }
+
+ if (element.srcObject !== stream) {
+ element.srcObject = stream;
+ }
+
+ // Remote audio plays through the voice canvas sinks; video elements stay
+ // muted so the same stream never produces doubled audio.
+ element.muted = true;
+ element.autoplay = true;
+ element.playsInline = true;
+
+ try {
+ element.play?.()?.catch?.(() => {});
+ } catch {
+ // ignore playback errors; the element retries on user interaction
+ }
+ }
+
+ #firstActiveRoomId() {
+ for (const roomId of this.#activeRoomIds) {
+ return roomId;
+ }
+ return null;
+ }
+
+ get localVideoTrack() {
+ return this.#localVideo.track;
+ }
+
+ get localScreenAudioTrack() {
+ return this.#localVideo.screenAudioTrack;
+ }
+
+ // Room state updates in voiceRooms; this only surfaces the change to
+ // people in the call. The moderator who pressed the button gets no toast —
+ // their button state already changed under their pointer.
+ #handleRecordingChanged(payload) {
+ const startedBySelf =
+ payload.recording?.started_by?.id === this.currentUser?.id;
+
+ if (payload.recording) {
+ if (!startedBySelf) {
+ this.toasts.default({
+ duration: 8000,
+ data: {
+ icon: "record-vinyl",
+ message: i18n("voice.room.recording_started_toast"),
+ },
+ });
+ }
+ } else {
+ this.toasts.default({
+ duration: 5000,
+ data: { message: i18n("voice.room.recording_stopped_toast") },
+ });
+ }
+ }
+
+ #handleRoomUpdated(roomId) {
+ if (!this.localVideoKind) {
+ return;
+ }
+
+ const room = this.voiceRooms?.roomById(roomId);
+ if (room && !this.videoAllowedIn(room)) {
+ this.#localVideo.stop().catch(() => {});
+ this.toasts.default({
+ duration: 5000,
+ data: { message: i18n("voice.video.room_disabled") },
+ });
+ }
+ }
+
+ enablePtt() {
+ this.#pttManager.enable();
+ this.pttEnabled = true;
+ this.pttActive = false;
+
+ this.#setMicEnabled(false);
+ this.#broadcastMuteState();
+
+ if (this.#activeRoomIds.size > 0) {
+ this.#pttManager.startListening();
+ }
+ }
+
+ disablePtt() {
+ this.#pttManager.disable();
+ this.pttEnabled = false;
+ this.pttActive = false;
+
+ this.#setMicEnabled(true);
+ this.#broadcastMuteState();
+ }
+
+ setPttKey(keyCode) {
+ if (!this.#pttManager.setKey(keyCode)) {
+ return false;
+ }
+ this.pttKey = keyCode;
+ return true;
+ }
+
+ toggleAutoStatus() {
+ this.autoStatusEnabled = !this.autoStatusEnabled;
+ try {
+ localStorage.setItem(
+ "voice_auto_status_enabled",
+ this.autoStatusEnabled ? "true" : "false"
+ );
+ } catch {
+ // ignore storage errors
+ }
+
+ if (!this.autoStatusEnabled && this.#activeRoomIds.size > 0) {
+ ajax("/user-status.json", { type: "DELETE" }).catch(() => {});
+ }
+ }
+
+ toggleCallWidgetHidden() {
+ this.setCallWidgetHidden(!this.callWidgetHidden);
+ }
+
+ setCallWidgetHidden(hidden) {
+ this.callWidgetHidden = hidden;
+ try {
+ localStorage.setItem(
+ "voice_call_widget_hidden",
+ hidden ? "true" : "false"
+ );
+ } catch {
+ // ignore storage errors
+ }
+ }
+
+ // --- Private orchestration ---
+
+ #broadcastMuteState() {
+ for (const roomId of this.#activeRoomIds) {
+ this.voiceRooms?.setParticipantMuted(
+ roomId,
+ this.currentUser?.id,
+ !this.audioEnabled
+ );
+ this.voiceRooms?.setParticipantDeafened(
+ roomId,
+ this.currentUser?.id,
+ this.deafened
+ );
+
+ ajax(`/voice/rooms/${roomId}/toggle_mute`, {
+ type: "POST",
+ data: {
+ muted: !this.audioEnabled,
+ deafened: this.deafened,
+ participant_session_id: this.#roomSessions.get(roomId),
+ },
+ });
+ }
+ }
+
+ #registerRoomHandler(roomId) {
+ if (this.#roomHandlerCallbacks.has(roomId)) {
+ return;
+ }
+
+ const callback = (payload) => this.#handleRoomMessage(roomId, payload);
+ this.voiceRooms.registerRoomHandler(roomId, callback);
+ this.#roomHandlerCallbacks.set(roomId, callback);
+ }
+
+ #teardownRoom(roomId) {
+ this.#connectingParticipantSnapshots.delete(roomId);
+ this.#connectingSignalQueue.delete(roomId);
+ this.#roomTransports.delete(roomId);
+ this.#roomSessions.delete(roomId);
+ this.#presencePending.clearAll(roomId);
+ this.#livekit.disconnectRoom(roomId);
+
+ const callback = this.#roomHandlerCallbacks.get(roomId);
+ if (callback) {
+ this.voiceRooms?.unregisterRoomHandler(roomId, callback);
+ this.#roomHandlerCallbacks.delete(roomId);
+ }
+
+ this.#peerManager.destroyRoom(roomId);
+ this.#removeAllRemoteStreams(roomId);
+ this.#audioMonitor.teardownRoom(roomId);
+ this.#signaling.clearForRoom(roomId);
+ this.#signaling.clearHttpQueue(roomId);
+ this.#roomMessageQueue.clear(roomId);
+ this.#transcription.stopIfTranscribing(roomId);
+ }
+
+ #handleRoomMessage(roomId, payload) {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ // Serialize all message processing per room to prevent async
+ // handlers from interleaving (e.g. concurrent participant broadcasts,
+ // signals arriving mid-peer-setup, role changes overlapping signals).
+ this.#roomMessageQueue
+ .enqueue(roomId, () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ return this.#processRoomMessage(roomId, payload);
+ })
+ .catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to process room message", error);
+ });
+ }
+
+ async #processRoomMessage(roomId, payload) {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] 📨 MessageBus message: room=${roomId}, type=${payload.type}, active=${this.#activeRoomIds.has(roomId)}`
+ );
+
+ if (!this.#activeRoomIds.has(roomId)) {
+ if (
+ payload.type === "participants" &&
+ this.#connectingRoomIds.has(roomId)
+ ) {
+ this.#connectingParticipantSnapshots.set(
+ roomId,
+ payload.participants || []
+ );
+ } else if (
+ payload.type === "signal" &&
+ this.#connectingRoomIds.has(roomId)
+ ) {
+ const queue = this.#connectingSignalQueue.get(roomId) || [];
+ queue.push(payload);
+ this.#connectingSignalQueue.set(roomId, queue);
+ } else if (
+ payload.type === "kicked" &&
+ this.#connectingRoomIds.has(roomId)
+ ) {
+ this.#handleKicked(roomId);
+ }
+ return;
+ }
+
+ if (payload.type === "signal") {
+ // Mesh-only: non-mesh transports never exchange WebRTC signals.
+ if (this.#isMeshRoom(roomId)) {
+ await this.#meshSignals.handle(roomId, payload);
+ }
+ } else if (payload.type === "participants") {
+ await this.#roster.handleParticipants(roomId, payload);
+ } else if (payload.type === "role_change") {
+ await this.#roster.handleRoleChange(roomId, payload);
+ } else if (payload.type === "hand_raise") {
+ this.#roster.handleHandRaise(roomId, payload);
+ } else if (payload.type === "kicked") {
+ this.#handleKicked(roomId);
+ } else if (payload.type === "room_updated") {
+ this.#handleRoomUpdated(roomId);
+ } else if (payload.type === "recording") {
+ this.#handleRecordingChanged(payload);
+ }
+ }
+
+ #handleKicked(roomId) {
+ // eslint-disable-next-line no-console
+ console.log(`[voice] kicked from room ${roomId}`);
+ this.leave({ id: roomId });
+ }
+
+ #currentUserParticipant() {
+ if (!this.currentUser) {
+ return null;
+ }
+
+ return {
+ id: this.currentUser.id,
+ username: this.currentUser.username,
+ name: this.currentUser.name,
+ avatar_template: this.currentUser.avatar_template,
+ };
+ }
+
+ #addLocalParticipant(roomId) {
+ const participant = this.#currentUserParticipant();
+ if (!participant) {
+ return;
+ }
+
+ participant.is_muted = !this.audioEnabled;
+ participant.is_deafened = this.deafened;
+ participant.is_video_on = this.localVideoKind === "camera";
+ participant.is_screen_sharing = this.localVideoKind === "screen";
+ participant.watching_video = this.watchingRoomId === roomId;
+
+ const room = this.voiceRooms?.roomById(roomId);
+ if (room?.membership?.role_name) {
+ participant.role = room.membership.role_name;
+ }
+
+ this.voiceRooms?.addParticipant(roomId, participant);
+ }
+
+ #removeLocalParticipant(roomId) {
+ if (!this.currentUser) {
+ return;
+ }
+
+ this.voiceRooms?.removeParticipant(roomId, this.currentUser.id);
+ }
+
+ // Mesh receive-side media boundary: only register (and therefore play) a
+ // remote track the sender's server-attested role and the room's media
+ // policy allow. On LiveKit the SFU enforces publish permissions instead.
+ #registerRemoteTrack(roomId, userId, track, streams) {
+ const room = this.voiceRooms?.roomById(roomId);
+ if (!remoteTrackAllowed(room, userId, track, streams)) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] dropping ${track?.kind} track from user ${userId}: not allowed to publish in room ${roomId}`
+ );
+ try {
+ track?.stop();
+ } catch {
+ // a remote track may already be ended
+ }
+ return;
+ }
+
+ this.#remoteStreamRegistry.register(roomId, userId, track, streams);
+ }
+
+ // Whether the local user may attach media to peers in this room. Honest
+ // stage listeners keep their pre-negotiated transceivers receive-only;
+ // the receiving side's #registerRemoteTrack is the actual boundary.
+ #canPublishMediaIn(roomId) {
+ const room = this.voiceRooms?.roomById(roomId);
+ return !room || this.#canSpeakInRoom(room);
+ }
+
+ #removeAllRemoteStreams(roomId) {
+ this.#transcription.detachRoom(roomId);
+ this.#remoteStreamRegistry
+ .clearRoom(roomId)
+ .forEach((userId) => this.#audioMonitor.teardown(roomId, userId));
+ }
+
+ #removeRemoteStream(roomId, remoteUserId) {
+ if (!this.#remoteStreamRegistry.remove(roomId, remoteUserId)) {
+ return;
+ }
+
+ this.#transcription.detach(roomId, remoteUserId);
+ this.#audioMonitor.teardown(roomId, remoteUserId);
+ this.#participantAudio.untrackElement(roomId, remoteUserId);
+ }
+
+ #bumpConnectionRevision() {
+ this.connectionRevision++;
+ }
+
+ #heartbeatPayload(roomId) {
+ const data = {
+ participant_session_id: this.#roomSessions.get(roomId),
+ };
+ if (this.idleState !== this.#idleTracker.lastBroadcastedIdleState) {
+ data.idle_state = this.idleState;
+ this.#idleTracker.lastBroadcastedIdleState = this.idleState;
+ }
+ return data;
+ }
+
+ #handleJoinFailure(roomId) {
+ this.#connectingRoomIds.delete(roomId);
+ this.#bumpConnectionRevision();
+ this.#activeRoomIds.delete(roomId);
+ this.#heartbeat.stop(roomId);
+ this.#removeLocalParticipant(roomId);
+ this.#teardownRoom(roomId);
+
+ if (this.#activeRoomIds.size === 0) {
+ this.#localAudio.stop();
+ }
+ }
+
+ #syncLocalStreamState() {
+ this.#applyLocalTrackState(this.localStream);
+
+ if (!this.currentUser?.id) {
+ return;
+ }
+
+ for (const roomId of this.#activeRoomIds) {
+ if (this.localStream) {
+ this.#audioMonitor.ensure(
+ roomId,
+ this.currentUser.id,
+ this.localStream,
+ true
+ );
+ } else {
+ this.#audioMonitor.teardown(roomId, this.currentUser.id);
+ }
+ }
+
+ this.#transcription.syncLocalTap();
+ }
+
+ #applyLocalTrackState(stream) {
+ for (const track of stream?.getAudioTracks?.() || []) {
+ track.enabled = this.audioEnabled;
+ }
+ }
+
+ async #replaceTrackOnAllPeers() {
+ const newTrack = this.localStream?.getAudioTracks()?.[0];
+ if (!newTrack) {
+ return;
+ }
+
+ await this.#livekit.replaceAudioTrack(newTrack);
+ await this.#peerManager.replaceMicTrack(newTrack);
+ }
+
+ // --- Idle tracker callbacks ---
+
+ #handleIdleStateChange(newState, wasAfk) {
+ if (newState === "active" && this.idleState !== "active") {
+ this.idleState = "active";
+ this.#idleTracker.lastBroadcastedIdleState = null;
+
+ for (const roomId of this.#activeRoomIds) {
+ this.voiceRooms?.setParticipantIdleState(
+ roomId,
+ this.currentUser?.id,
+ "active"
+ );
+ }
+
+ if (wasAfk && this.#idleTracker.wasAutoMuted) {
+ this.toasts.success({
+ duration: 5000,
+ data: {
+ message: i18n("voice.idle.auto_muted"),
+ actions: [
+ {
+ label: i18n("voice.idle.click_to_unmute"),
+ class: "btn-primary",
+ action: () => this.toggleMute(),
+ },
+ ],
+ },
+ });
+ }
+ } else if (newState === "idle" && this.idleState !== "idle") {
+ this.idleState = "idle";
+ this.#idleTracker.lastBroadcastedIdleState = null;
+
+ for (const roomId of this.#activeRoomIds) {
+ this.voiceRooms?.setParticipantIdleState(
+ roomId,
+ this.currentUser?.id,
+ "idle"
+ );
+ }
+ }
+ }
+
+ #handleAutoMute() {
+ if (this.idleState !== "afk") {
+ this.idleState = "afk";
+ this.#idleTracker.lastBroadcastedIdleState = null;
+
+ if (this.audioEnabled) {
+ this.#setMicEnabled(false);
+ this.#broadcastMuteState();
+ }
+
+ for (const roomId of this.#activeRoomIds) {
+ this.voiceRooms?.setParticipantIdleState(
+ roomId,
+ this.currentUser?.id,
+ "afk"
+ );
+ }
+ }
+ }
+
+ #handleIdleDisconnect() {
+ const roomNames = [];
+ for (const roomId of this.#activeRoomIds) {
+ const room = this.voiceRooms?.roomById(roomId);
+ if (room) {
+ roomNames.push(room.name);
+ }
+ }
+
+ for (const roomId of [...this.#activeRoomIds]) {
+ this.leave({ id: roomId });
+ }
+
+ const name = roomNames[0] || "the room";
+ this.toasts.default({
+ duration: 8000,
+ data: { message: i18n("voice.idle.disconnected", { room: name }) },
+ });
+ }
+
+ // --- Push-to-Talk ---
+
+ #handlePttPress() {
+ this.pttActive = true;
+ this.#setMicEnabled(true);
+ this.#broadcastMuteState();
+ }
+
+ #handlePttRelease() {
+ this.pttActive = false;
+ this.#setMicEnabled(false);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-create-room.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-create-room.gjs
new file mode 100644
index 00000000000..c3fc161303b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-create-room.gjs
@@ -0,0 +1,43 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import VoiceRoomForm from "discourse/plugins/voice/discourse/components/voice-room-form";
+
+export default class VoiceCreateRoomModal extends Component {
+ @service voiceRooms;
+ @service toasts;
+
+ @action
+ async handleSubmit(data) {
+ try {
+ const result = await ajax("/voice/rooms", {
+ type: "POST",
+ data: { room: data },
+ });
+ this.voiceRooms.handleDirectoryEvent({
+ type: "created",
+ room: result.room,
+ });
+ this.toasts.success({ data: { message: i18n("voice.room.created") } });
+ this.args.closeModal();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.sidebar.create"}}
+ class="voice-create-room-modal"
+ >
+ <:body>
+ <VoiceRoomForm @onSubmit={{this.handleSubmit}} />
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-incoming-call.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-incoming-call.gjs
new file mode 100644
index 00000000000..78962fa95a3
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-incoming-call.gjs
@@ -0,0 +1,91 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceIncomingCallModal extends Component {
+ #expiryTimer;
+
+ constructor() {
+ super(...arguments);
+ // An unanswered call stops ringing on its own — the modal closing is what
+ // stops the ringtone, so the expiry lives here.
+ this.#expiryTimer = setTimeout(
+ () => this.args.closeModal(),
+ this.args.model.remainingMs
+ );
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ clearTimeout(this.#expiryTimer);
+ }
+
+ get ring() {
+ return this.args.model.ring;
+ }
+
+ get caller() {
+ return {
+ username: this.ring.caller_username,
+ name: this.ring.caller_name,
+ avatar_template: this.ring.caller_avatar_template,
+ };
+ }
+
+ get displayName() {
+ return prioritizeNameInUx(this.caller.name)
+ ? this.caller.name
+ : this.caller.username;
+ }
+
+ @action
+ answer() {
+ this.args.closeModal();
+ this.args.model.calls.answer(this.ring);
+ }
+
+ @action
+ decline() {
+ this.args.closeModal();
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.call.incoming_title"}}
+ class="voice-incoming-call-modal"
+ >
+ <:body>
+ <div class="voice-incoming-call-modal__caller">
+ <div class="voice-incoming-call-modal__avatar">
+ {{dAvatar this.caller imageSize="huge"}}
+ </div>
+ <span
+ class="voice-incoming-call-modal__name"
+ >{{this.displayName}}</span>
+ <span class="voice-incoming-call-modal__state">
+ {{i18n "voice.call.incoming_state"}}
+ </span>
+ </div>
+ </:body>
+ <:footer>
+ <DButton
+ @action={{this.answer}}
+ @icon="phone"
+ @label="voice.call.answer"
+ class="btn-primary voice-incoming-call-modal__answer"
+ />
+ <DButton
+ @action={{this.decline}}
+ @icon="phone-slash"
+ @label="voice.call.decline"
+ class="btn-danger voice-incoming-call-modal__decline"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-invite-users.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-invite-users.gjs
new file mode 100644
index 00000000000..98946722928
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-invite-users.gjs
@@ -0,0 +1,235 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { durationTiny } from "discourse/lib/formatter";
+import { clipboardCopy } from "discourse/lib/utilities";
+import UserChooser from "discourse/select-kit/components/user-chooser";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceInviteUsersModal extends Component {
+ @service currentUser;
+ @service router;
+ @service toasts;
+
+ @tracked suggestions = [];
+ @tracked loadingSuggestions = true;
+ @tracked selectedUsernames = [];
+ @tracked invitedUsernames = [];
+ @tracked inviting = false;
+
+ constructor() {
+ super(...arguments);
+ this.loadSuggestions();
+ }
+
+ get room() {
+ return this.args.model.room;
+ }
+
+ get inviteUrl() {
+ const url = this.router.urlFor(
+ "voice-room-invite",
+ this.room.slug,
+ this.currentUser.username_lower
+ );
+ return new URL(url, window.location.origin).href;
+ }
+
+ get suggestionRows() {
+ return this.suggestions.map((suggestion) => ({
+ ...suggestion,
+ timeTogether: durationTiny(suggestion.total_seconds),
+ invited: this.invitedUsernames.includes(suggestion.username),
+ }));
+ }
+
+ async loadSuggestions() {
+ try {
+ const result = await ajax(
+ `/voice/rooms/${this.room.id}/invites/suggestions`
+ );
+ this.suggestions = result.suggestions;
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loadingSuggestions = false;
+ }
+ }
+
+ async #invite(usernames) {
+ this.inviting = true;
+ try {
+ const result = await ajax(`/voice/rooms/${this.room.id}/invites`, {
+ type: "POST",
+ data: { usernames },
+ });
+ this.invitedUsernames = [
+ ...this.invitedUsernames,
+ ...result.invited_usernames,
+ ];
+ if (result.invited_usernames.length) {
+ this.toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("voice.invite.sent", {
+ count: result.invited_usernames.length,
+ }),
+ },
+ });
+ }
+ if (result.skipped_usernames.length) {
+ this.toasts.warning({
+ data: {
+ message: i18n("voice.invite.skipped", {
+ usernames: result.skipped_usernames
+ .map((username) => `@${username}`)
+ .join(", "),
+ }),
+ },
+ });
+ }
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.inviting = false;
+ }
+ }
+
+ @action
+ setSelectedUsernames(usernames) {
+ this.selectedUsernames = usernames;
+ }
+
+ @action
+ async inviteSelected() {
+ if (!this.selectedUsernames.length) {
+ return;
+ }
+ await this.#invite(this.selectedUsernames);
+ this.selectedUsernames = [];
+ }
+
+ @action
+ async inviteSuggestion(suggestion) {
+ await this.#invite([suggestion.username]);
+ }
+
+ @action
+ copyLink() {
+ clipboardCopy(this.inviteUrl);
+ this.toasts.success({
+ duration: "short",
+ data: { message: i18n("voice.room.link_copied") },
+ });
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.invite.title" room_name=this.room.name}}
+ class="voice-invite-modal"
+ >
+ <:body>
+ <div class="voice-invite-modal__search">
+ <span class="voice-invite-modal__label">
+ {{i18n "voice.invite.search_label"}}
+ </span>
+ <div class="voice-invite-modal__search-row">
+ <UserChooser
+ @value={{this.selectedUsernames}}
+ @onChange={{this.setSelectedUsernames}}
+ @options={{hash
+ excludeCurrentUser=true
+ filterPlaceholder="voice.invite.search_placeholder"
+ }}
+ class="voice-invite-modal__user-chooser"
+ />
+ <DButton
+ @action={{this.inviteSelected}}
+ @icon="paper-plane"
+ @label="voice.invite.send"
+ @disabled={{this.inviting}}
+ class="btn-primary voice-invite-modal__send"
+ />
+ </div>
+ </div>
+
+ {{#if this.loadingSuggestions}}
+ <div class="voice-invite-modal__loading">
+ <div class="spinner small"></div>
+ {{i18n "loading"}}
+ </div>
+ {{else if this.suggestionRows.length}}
+ <div class="voice-invite-modal__suggestions">
+ <h3 class="voice-invite-modal__section-title">
+ {{i18n "voice.invite.suggestions_title"}}
+ </h3>
+ <div class="voice-invite-modal__suggestion-list">
+ {{#each this.suggestionRows as |suggestion|}}
+ <div class="voice-invite-modal__suggestion">
+ <div class="voice-invite-modal__suggestion-avatar">
+ {{dAvatar suggestion imageSize="medium"}}
+ </div>
+ <div class="voice-invite-modal__suggestion-details">
+ <span
+ class="voice-invite-modal__suggestion-username"
+ >{{suggestion.username}}</span>
+ <span class="voice-invite-modal__suggestion-time">
+ {{i18n
+ "voice.invite.time_together"
+ duration=suggestion.timeTogether
+ }}
+ </span>
+ </div>
+ {{#if suggestion.invited}}
+ <span class="voice-invite-modal__suggestion-invited">
+ {{dIcon "check"}}
+ {{i18n "voice.invite.invited"}}
+ </span>
+ {{else}}
+ <DButton
+ @action={{fn this.inviteSuggestion suggestion}}
+ @icon="user-plus"
+ @label="voice.invite.invite"
+ @disabled={{this.inviting}}
+ class="btn-small voice-invite-modal__suggestion-invite"
+ />
+ {{/if}}
+ </div>
+ {{/each}}
+ </div>
+ </div>
+ {{/if}}
+
+ <div class="voice-invite-modal__link">
+ <label class="voice-invite-modal__label" for="voice-invite-link">
+ {{i18n "voice.invite.link_label"}}
+ </label>
+ <div class="voice-invite-modal__link-row">
+ <input
+ id="voice-invite-link"
+ type="text"
+ readonly
+ value={{this.inviteUrl}}
+ class="voice-invite-modal__link-input"
+ />
+ <DButton
+ @action={{this.copyLink}}
+ @icon="copy"
+ @label="voice.invite.copy"
+ class="voice-invite-modal__copy"
+ />
+ </div>
+ </div>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-mesh-privacy-warning.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-mesh-privacy-warning.gjs
new file mode 100644
index 00000000000..e25db3dc7d5
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-mesh-privacy-warning.gjs
@@ -0,0 +1,119 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const MESH_PRIVACY_ACK_KEY = "voice_mesh_privacy_ack";
+
+// Guards against a repeat join request (double click, sidebar plus room
+// page) replacing the modal out from under the first one.
+let warningOpen = false;
+
+function acknowledged() {
+ try {
+ return localStorage.getItem(MESH_PRIVACY_ACK_KEY) === "true";
+ } catch {
+ return false;
+ }
+}
+
+function rememberAcknowledgement() {
+ try {
+ localStorage.setItem(MESH_PRIVACY_ACK_KEY, "true");
+ } catch {
+ // ignore storage errors
+ }
+}
+
+// Mesh joins connect participants' browsers directly, so everyone in the
+// room can learn everyone else's IP address. Resolves to whether the join
+// may proceed, gating mesh rooms on an explicit acknowledgement; "don't
+// show this again" persists per device.
+export async function confirmMeshPrivacy(
+ room,
+ { currentUser, modal, siteSettings }
+) {
+ if (
+ !siteSettings.voice_mesh_privacy_warning_enabled ||
+ !currentUser ||
+ room.expected_transport !== "mesh"
+ ) {
+ return true;
+ }
+
+ if (acknowledged()) {
+ return true;
+ }
+
+ if (warningOpen) {
+ return false;
+ }
+
+ warningOpen = true;
+ try {
+ const result = await modal.show(VoiceMeshPrivacyWarningModal);
+ if (!result?.join) {
+ return false;
+ }
+ if (result.dontShowAgain) {
+ rememberAcknowledgement();
+ }
+ return true;
+ } finally {
+ warningOpen = false;
+ }
+}
+
+// Resolves through `closeModal` with `{ join: true, dontShowAgain }` when the
+// user accepts; cancel/escape/backdrop resolve with nothing.
+export default class VoiceMeshPrivacyWarningModal extends Component {
+ @tracked dontShowAgain = false;
+
+ @action
+ updateDontShowAgain(event) {
+ this.dontShowAgain = event.target.checked;
+ }
+
+ @action
+ join() {
+ this.args.closeModal({ join: true, dontShowAgain: this.dontShowAgain });
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.mesh_privacy_warning.title"}}
+ class="voice-mesh-privacy-warning-modal"
+ >
+ <:body>
+ <p class="voice-mesh-privacy-warning-modal__body">
+ {{i18n "voice.mesh_privacy_warning.body"}}
+ </p>
+ <label class="voice-mesh-privacy-warning-modal__dont-show-again">
+ <input
+ type="checkbox"
+ checked={{this.dontShowAgain}}
+ {{on "change" this.updateDontShowAgain}}
+ />
+ {{i18n "voice.mesh_privacy_warning.dont_show_again"}}
+ </label>
+ </:body>
+ <:footer>
+ <DButton
+ @action={{this.join}}
+ @icon="phone"
+ @label="voice.mesh_privacy_warning.join"
+ class="btn-primary voice-mesh-privacy-warning-modal__join"
+ />
+ <DButton
+ @action={{@closeModal}}
+ @label="voice.mesh_privacy_warning.cancel"
+ class="btn-flat voice-mesh-privacy-warning-modal__cancel"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-mic-permission.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-mic-permission.gjs
new file mode 100644
index 00000000000..998df73fa2c
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-mic-permission.gjs
@@ -0,0 +1,69 @@
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const PERMISSION_ERROR_NAMES = [
+ "NotAllowedError",
+ "PermissionDeniedError",
+ "SecurityError",
+];
+
+// Guards against a repeat join request (double click, sidebar plus room
+// page) stacking a second copy of the modal.
+let helpOpen = false;
+
+// Tells the user why microphone acquisition failed. A permission failure
+// usually means a block saved in the browser's site settings (often from a
+// past "deny"), so getUserMedia rejects with no prompt — the modal is the
+// only way the user learns what to fix. Other failures (no device, device
+// in use) get a toast.
+export function reportMicAcquisitionFailure(error, { modal, toasts }) {
+ if (PERMISSION_ERROR_NAMES.includes(error?.name)) {
+ showMicPermissionHelp(modal);
+ } else {
+ toasts.error({
+ duration: 8000,
+ data: { message: i18n("voice.room.mic_unavailable") },
+ });
+ }
+}
+
+// Purely educational; resolves once dismissed.
+async function showMicPermissionHelp(modal) {
+ if (helpOpen) {
+ return;
+ }
+
+ helpOpen = true;
+ try {
+ await modal.show(VoiceMicPermissionModal);
+ } finally {
+ helpOpen = false;
+ }
+}
+
+const VoiceMicPermissionModal = <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.mic_permission.title"}}
+ class="voice-mic-permission-modal"
+ >
+ <:body>
+ <p class="voice-mic-permission-modal__body">
+ {{i18n "voice.mic_permission.body"}}
+ </p>
+ <p class="voice-mic-permission-modal__instructions">
+ {{i18n "voice.mic_permission.instructions"}}
+ </p>
+ </:body>
+ <:footer>
+ <DButton
+ @action={{@closeModal}}
+ @label="voice.mic_permission.ok"
+ class="btn-primary voice-mic-permission-modal__ok"
+ />
+ </:footer>
+ </DModal>
+</template>;
+
+export default VoiceMicPermissionModal;
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-room-info.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-room-info.gjs
new file mode 100644
index 00000000000..95efb00230a
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-room-info.gjs
@@ -0,0 +1,357 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import UserChooser from "discourse/select-kit/components/user-chooser";
+import { eq, notEq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import VoiceRoomForm from "discourse/plugins/voice/discourse/components/voice-room-form";
+import roomIcon from "discourse/plugins/voice/discourse/lib/voice/room-icon";
+
+export default class VoiceRoomInfoModal extends Component {
+ @service voiceRooms;
+ @service toasts;
+
+ @tracked memberships = [];
+ @tracked loading = false;
+ @tracked selectedUsernames = [];
+ @tracked selectedRole = "participant";
+ @tracked addingMember = false;
+ @tracked isEditing;
+
+ constructor() {
+ super(...arguments);
+ this.isEditing = this.args.model.isEditing ?? false;
+ if (this.showMembershipManagement && !this.isEditing) {
+ this.loadMemberships();
+ }
+ }
+
+ get room() {
+ return this.args.model.room;
+ }
+
+ get showMembershipManagement() {
+ return (
+ this.room.can_manage &&
+ (!this.room.public || this.room.room_type === "stage")
+ );
+ }
+
+ get roleOptions() {
+ const options = [
+ {
+ id: "participant",
+ name: i18n("voice.room_info.members.participant"),
+ },
+ ];
+
+ if (this.room.room_type === "stage") {
+ options.push({
+ id: "speaker",
+ name: i18n("voice.room_info.members.speaker"),
+ });
+ }
+
+ options.push({
+ id: "moderator",
+ name: i18n("voice.room_info.members.moderator"),
+ });
+
+ return options;
+ }
+
+ async loadMemberships() {
+ this.loading = true;
+ try {
+ const result = await ajax(`/voice/rooms/${this.room.id}/memberships`);
+ this.memberships = result.memberships;
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ startEditing() {
+ this.isEditing = true;
+ }
+
+ @action
+ stopEditing() {
+ this.isEditing = false;
+ if (this.showMembershipManagement) {
+ this.loadMemberships();
+ }
+ }
+
+ @action
+ async handleEdit(data) {
+ try {
+ const result = await ajax(`/voice/rooms/${this.room.id}`, {
+ type: "PUT",
+ data: { room: data },
+ });
+ this.voiceRooms.handleDirectoryEvent({
+ type: "updated",
+ room: result.room,
+ });
+ this.toasts.success({ data: { message: i18n("voice.room.updated") } });
+ this.args.closeModal();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ setSelectedUsernames(usernames) {
+ this.selectedUsernames = usernames;
+ }
+
+ @action
+ setSelectedRole(role) {
+ this.selectedRole = role;
+ }
+
+ @action
+ async addMember() {
+ if (!this.selectedUsernames.length) {
+ return;
+ }
+
+ this.addingMember = true;
+ try {
+ for (const username of this.selectedUsernames) {
+ await ajax(`/voice/rooms/${this.room.id}/memberships`, {
+ type: "POST",
+ data: { username, role: this.selectedRole },
+ });
+ }
+ this.selectedUsernames = [];
+ this.selectedRole = "participant";
+ await this.loadMemberships();
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.addingMember = false;
+ }
+ }
+
+ @action
+ async updateMemberRole(membership, role) {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/memberships/${membership.id}`, {
+ type: "PUT",
+ data: { role },
+ });
+ await this.loadMemberships();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async removeMember(membership) {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/memberships/${membership.id}`, {
+ type: "DELETE",
+ });
+ await this.loadMemberships();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{if this.isEditing (i18n "voice.room.edit")}}
+ class="voice-room-info-modal"
+ >
+ <:body>
+ {{#if this.isEditing}}
+ <div class="voice-room-info-modal__edit-form">
+ <VoiceRoomForm
+ @room={{this.room}}
+ @onSubmit={{this.handleEdit}}
+ @onManageMembers={{this.stopEditing}}
+ />
+ </div>
+ {{else}}
+ <div class="voice-room-info-modal__header">
+ <div class="voice-room-info-modal__icon">
+ {{dIcon (roomIcon this.room)}}
+ {{#unless this.room.public}}
+ {{dIcon "lock" class="voice-room-info-modal__icon-badge"}}
+ {{/unless}}
+ </div>
+ <div class="voice-room-info-modal__header-content">
+ <h2
+ class="voice-room-info-modal__room-name"
+ >{{this.room.name}}</h2>
+ {{#if this.room.cooked_description}}
+ <div
+ class="voice-room-info-modal__description cooked"
+ >{{trustHTML this.room.cooked_description}}</div>
+ {{/if}}
+ </div>
+ {{#if this.room.can_manage}}
+ <DButton
+ @action={{this.startEditing}}
+ @icon="pencil"
+ @title="voice.room.edit"
+ class="btn-flat voice-room-info-modal__edit-btn"
+ />
+ {{/if}}
+ </div>
+
+ <div class="voice-room-info-modal__stats">
+ <div class="voice-room-info-modal__stat">
+ <span class="voice-room-info-modal__stat-value">
+ {{#if this.room.public}}
+ {{dIcon "globe"}}
+ {{else}}
+ {{dIcon "lock"}}
+ {{/if}}
+ </span>
+ <span class="voice-room-info-modal__stat-label">
+ {{if
+ this.room.public
+ (i18n "voice.room_info.public")
+ (i18n "voice.room_info.private")
+ }}
+ </span>
+ </div>
+
+ <div class="voice-room-info-modal__stat">
+ <span
+ class="voice-room-info-modal__stat-value"
+ >{{this.room.member_count}}</span>
+ <span class="voice-room-info-modal__stat-label">{{i18n
+ "voice.room_info.member_count"
+ }}</span>
+ </div>
+
+ {{#if this.room.max_participants}}
+ <div class="voice-room-info-modal__stat">
+ <span
+ class="voice-room-info-modal__stat-value"
+ >{{this.room.max_participants}}</span>
+ <span class="voice-room-info-modal__stat-label">{{i18n
+ "voice.room_info.max_participants"
+ }}</span>
+ </div>
+ {{/if}}
+ </div>
+
+ {{#if this.showMembershipManagement}}
+ <div class="voice-room-info-modal__members">
+ <div class="voice-room-info-modal__section-header">
+ {{dIcon "users"}}
+ <h3>{{i18n "voice.room_info.members.title"}}</h3>
+ </div>
+
+ {{#if this.loading}}
+ <div class="voice-room-info-modal__loading">
+ <div class="spinner small"></div>
+ {{i18n "loading"}}
+ </div>
+ {{else}}
+ <div class="voice-room-info-modal__member-list">
+ {{#each this.memberships as |membership|}}
+ <div
+ class="voice-room-info-modal__member
+ {{if
+ (eq membership.user_id this.room.creator_id)
+ '--creator'
+ }}"
+ >
+ <div class="voice-room-info-modal__member-avatar">
+ {{dAvatar membership.user imageSize="medium"}}
+ </div>
+ <div class="voice-room-info-modal__member-details">
+ <span
+ class="voice-room-info-modal__member-username"
+ >{{membership.user.username}}</span>
+ {{#if (eq membership.user_id this.room.creator_id)}}
+ <span
+ class="voice-room-info-modal__member-role --creator"
+ >
+ {{dIcon "crown"}}
+ {{i18n "voice.room_info.members.creator"}}
+ </span>
+ {{else}}
+ <span
+ class="voice-room-info-modal__member-role --{{membership.role_name}}"
+ >
+ {{membership.role_name}}
+ </span>
+ {{/if}}
+ </div>
+
+ {{#if (notEq membership.user_id this.room.creator_id)}}
+ <div class="voice-room-info-modal__member-actions">
+ <ComboBox
+ @content={{this.roleOptions}}
+ @value={{membership.role_name}}
+ @onChange={{fn this.updateMemberRole membership}}
+ @options={{hash none=false}}
+ class="voice-room-info-modal__role-select"
+ />
+ <DButton
+ @action={{fn this.removeMember membership}}
+ @icon="xmark"
+ @title="voice.room_info.members.remove"
+ class="btn-flat btn-small voice-room-info-modal__remove-btn"
+ />
+ </div>
+ {{/if}}
+ </div>
+ {{/each}}
+ </div>
+
+ <div class="voice-room-info-modal__add-member">
+ <div class="voice-room-info-modal__add-row">
+ <UserChooser
+ @value={{this.selectedUsernames}}
+ @onChange={{this.setSelectedUsernames}}
+ @options={{hash
+ excludeCurrentUser=false
+ filterPlaceholder="voice.room_info.members.add_placeholder"
+ }}
+ class="voice-room-info-modal__user-chooser"
+ />
+ <ComboBox
+ @content={{this.roleOptions}}
+ @value={{this.selectedRole}}
+ @onChange={{this.setSelectedRole}}
+ @options={{hash none=false}}
+ class="voice-room-info-modal__role-chooser"
+ />
+ <DButton
+ @action={{this.addMember}}
+ @icon="plus"
+ @disabled={{this.addingMember}}
+ @title="voice.room_info.members.add_button"
+ class="btn-primary voice-room-info-modal__add-btn"
+ />
+ </div>
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+ {{/if}}
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-video-settings.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-video-settings.gjs
new file mode 100644
index 00000000000..e159834916a
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-video-settings.gjs
@@ -0,0 +1,384 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import { and, not, or } from "discourse/truth-helpers";
+import DModal from "discourse/ui-kit/d-modal";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import { i18n } from "discourse-i18n";
+import BackgroundBlurManager from "../../lib/voice/background-blur";
+import {
+ cameraConstraints,
+ enumerateVideoDevices,
+ SYSTEM_DEFAULT_DEVICE_ID,
+} from "../../lib/voice/media-devices";
+
+export default class VoiceVideoSettingsModal extends Component {
+ @service voiceWebrtc;
+
+ @tracked videoDevices = [];
+ @tracked previewStream = null;
+ @tracked previewError = false;
+ @tracked busy = false;
+
+ #previewRawStream = null;
+ #previewBlur = null;
+ #previewEpoch = 0;
+ #onDeviceChange = () => this.refreshDevices();
+
+ constructor() {
+ super(...arguments);
+ if (this.usingLiveStream) {
+ this.refreshDevices();
+ } else {
+ this.startPreview();
+ }
+ navigator.mediaDevices?.addEventListener?.(
+ "devicechange",
+ this.#onDeviceChange
+ );
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ navigator.mediaDevices?.removeEventListener?.(
+ "devicechange",
+ this.#onDeviceChange
+ );
+ this.#stopPreview();
+ }
+
+ get blurAvailable() {
+ return this.voiceWebrtc.videoBlurAvailable;
+ }
+
+ get blurSupported() {
+ return this.voiceWebrtc.videoBlurSupported;
+ }
+
+ get blurUsable() {
+ return this.blurAvailable && this.blurSupported;
+ }
+
+ get blurEnabled() {
+ return this.voiceWebrtc.videoBlurEnabled;
+ }
+
+ get blurAmount() {
+ return this.voiceWebrtc.videoBlurAmount;
+ }
+
+ get usingLiveStream() {
+ return this.voiceWebrtc.localVideoKind === "camera";
+ }
+
+ get cameraQualityOptions() {
+ return this.voiceWebrtc.allowedCameraQualityTiers().map((tier) => ({
+ id: tier,
+ name: i18n(`voice.quality.${tier}`),
+ }));
+ }
+
+ get screenQualityOptions() {
+ return this.voiceWebrtc.allowedScreenQualityTiers().map((tier) => ({
+ id: tier,
+ name: i18n(`voice.quality.${tier}`),
+ }));
+ }
+
+ get screenContentOptions() {
+ return ["text", "motion"].map((content) => ({
+ id: content,
+ name: i18n(`voice.video_settings.screen_content_${content}`),
+ }));
+ }
+
+ get showCameraQuality() {
+ return this.cameraQualityOptions.length > 1;
+ }
+
+ get showScreenQuality() {
+ return this.screenQualityOptions.length > 1;
+ }
+
+ get stream() {
+ return this.usingLiveStream
+ ? this.voiceWebrtc.localVideoStream
+ : this.previewStream;
+ }
+
+ async startPreview() {
+ this.#stopPreview();
+ const epoch = ++this.#previewEpoch;
+ this.previewError = false;
+
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ video: cameraConstraints(
+ this.voiceWebrtc.videoInputDeviceId,
+ this.voiceWebrtc.effectiveCameraQuality()
+ ),
+ });
+ } catch {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.previewError = true;
+ }
+ return;
+ }
+
+ if (epoch !== this.#previewEpoch || this.isDestroying || this.isDestroyed) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+
+ this.#previewRawStream = stream;
+ await this.#applyPreviewEffect(epoch);
+ await this.refreshDevices();
+ }
+
+ async refreshDevices() {
+ const inputs = await enumerateVideoDevices();
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.videoDevices = [
+ {
+ id: SYSTEM_DEFAULT_DEVICE_ID,
+ name: i18n("voice.devices.system_default"),
+ },
+ ...inputs,
+ ];
+ }
+
+ async #applyPreviewEffect(epoch = this.#previewEpoch) {
+ this.#previewBlur?.teardown();
+ this.#previewBlur = null;
+
+ if (!this.#previewRawStream) {
+ return;
+ }
+
+ if (this.blurEnabled && this.blurUsable) {
+ const manager = new BackgroundBlurManager();
+ const rawStream = this.#previewRawStream;
+ try {
+ const processed = await manager.setup(rawStream, this.blurAmount);
+ if (
+ epoch !== this.#previewEpoch ||
+ this.isDestroying ||
+ this.isDestroyed
+ ) {
+ manager.teardown();
+ return;
+ }
+ this.#previewBlur = manager;
+ this.previewStream = processed;
+ return;
+ } catch {
+ manager.teardown();
+ }
+
+ if (epoch !== this.#previewEpoch) {
+ return;
+ }
+ }
+
+ this.previewStream = this.#previewRawStream;
+ }
+
+ #stopPreview() {
+ this.#previewEpoch++;
+ this.#previewBlur?.teardown();
+ this.#previewBlur = null;
+
+ if (this.#previewRawStream) {
+ this.#previewRawStream.getTracks().forEach((track) => track.stop());
+ this.#previewRawStream = null;
+ }
+
+ this.previewStream = null;
+ }
+
+ @action
+ async onCameraChange(deviceId) {
+ await this.voiceWebrtc.setVideoInputDevice(deviceId);
+ if (!this.usingLiveStream) {
+ await this.startPreview();
+ }
+ }
+
+ @action
+ async onCameraQualityChange(tier) {
+ this.voiceWebrtc.setCameraQuality(tier);
+ if (!this.usingLiveStream) {
+ await this.startPreview();
+ }
+ }
+
+ @action
+ async toggleBlur() {
+ if (this.busy || !this.blurUsable) {
+ return;
+ }
+
+ this.busy = true;
+ try {
+ await this.voiceWebrtc.toggleVideoBlur();
+ if (!this.usingLiveStream) {
+ await this.#applyPreviewEffect();
+ }
+ } finally {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.busy = false;
+ }
+ }
+ }
+
+ @action
+ onAmountChange(event) {
+ const value = parseInt(event.target.value, 10);
+ this.voiceWebrtc.setVideoBlurAmount(value);
+ this.#previewBlur?.setAmount(value);
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.video_settings.title"}}
+ class="voice-video-settings-modal"
+ >
+ <:body>
+ <div class="voice-video-settings">
+ <div class="voice-video-settings__preview">
+ {{#if this.previewError}}
+ <p class="voice-video-settings__camera-error">
+ {{i18n "voice.video_settings.camera_error"}}
+ </p>
+ {{else if this.stream}}
+ <video
+ {{didInsert
+ (fn this.voiceWebrtc.attachVideoStream this.stream)
+ }}
+ {{didUpdate
+ (fn this.voiceWebrtc.attachVideoStream this.stream)
+ this.stream
+ }}
+ muted
+ autoplay
+ playsinline
+ ></video>
+ {{/if}}
+ </div>
+
+ <div class="voice-video-settings__field">
+ <label class="voice-video-settings__label">
+ {{i18n "voice.video_settings.camera"}}
+ </label>
+ <ComboBox
+ @content={{this.videoDevices}}
+ @value={{this.voiceWebrtc.videoInputDeviceId}}
+ @onChange={{this.onCameraChange}}
+ @options={{hash none=false}}
+ class="voice-video-settings__camera-select"
+ />
+ </div>
+
+ {{#if this.showCameraQuality}}
+ <div class="voice-video-settings__field">
+ <label class="voice-video-settings__label">
+ {{i18n "voice.video_settings.camera_quality"}}
+ </label>
+ <ComboBox
+ @content={{this.cameraQualityOptions}}
+ @value={{this.voiceWebrtc.cameraQuality}}
+ @onChange={{this.onCameraQualityChange}}
+ @options={{hash none=false}}
+ class="voice-video-settings__camera-quality-select"
+ />
+ <p class="voice-video-settings__hint">
+ {{i18n "voice.video_settings.camera_quality_hint"}}
+ </p>
+ </div>
+ {{/if}}
+
+ {{#if this.showScreenQuality}}
+ <div class="voice-video-settings__field">
+ <label class="voice-video-settings__label">
+ {{i18n "voice.video_settings.screen_quality"}}
+ </label>
+ <ComboBox
+ @content={{this.screenQualityOptions}}
+ @value={{this.voiceWebrtc.screenQuality}}
+ @onChange={{this.voiceWebrtc.setScreenQuality}}
+ @options={{hash none=false}}
+ class="voice-video-settings__screen-quality-select"
+ />
+ <p class="voice-video-settings__hint">
+ {{i18n "voice.video_settings.screen_quality_hint"}}
+ </p>
+ </div>
+ {{/if}}
+
+ <div class="voice-video-settings__field">
+ <label class="voice-video-settings__label">
+ {{i18n "voice.video_settings.screen_content"}}
+ </label>
+ <ComboBox
+ @content={{this.screenContentOptions}}
+ @value={{this.voiceWebrtc.screenContent}}
+ @onChange={{this.voiceWebrtc.setScreenContent}}
+ @options={{hash none=false}}
+ class="voice-video-settings__screen-content-select"
+ />
+ <p class="voice-video-settings__hint">
+ {{i18n "voice.video_settings.screen_content_hint"}}
+ </p>
+ </div>
+
+ {{#if this.blurAvailable}}
+ <div class="voice-video-settings__field">
+ <DToggleSwitch
+ @state={{this.blurEnabled}}
+ @label="voice.video_settings.background_blur"
+ disabled={{or this.busy (not this.blurSupported)}}
+ {{on "click" this.toggleBlur}}
+ />
+ {{#unless this.blurSupported}}
+ <p class="voice-video-settings__hint">
+ {{i18n "voice.video_settings.not_supported"}}
+ </p>
+ {{/unless}}
+ </div>
+
+ {{#if (and this.blurEnabled this.blurSupported)}}
+ <div class="voice-video-settings__field">
+ <label
+ class="voice-video-settings__label"
+ for="voice-video-settings-blur-amount"
+ >
+ {{i18n "voice.video_settings.blur_amount"}}
+ </label>
+ <input
+ type="range"
+ id="voice-video-settings-blur-amount"
+ min="0"
+ max="100"
+ value={{this.blurAmount}}
+ class="voice-video-settings__blur-slider"
+ {{on "input" this.onAmountChange}}
+ />
+ </div>
+ {{/if}}
+ {{/if}}
+ </div>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/modal/voice-voice-settings.gjs b/plugins/voice/assets/javascripts/discourse/components/modal/voice-voice-settings.gjs
new file mode 100644
index 00000000000..607b1497777
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/modal/voice-voice-settings.gjs
@@ -0,0 +1,482 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import { i18n } from "discourse-i18n";
+import { NOISE_SUPPRESSION_MODES } from "../../lib/voice/audio-processing";
+import { rmsToPercent, sampleRms } from "../../lib/voice/input-gate";
+import {
+ applyOutputDevice,
+ audioConstraints,
+ enumerateAudioDevices,
+ outputSelectionSupported,
+ SYSTEM_DEFAULT_DEVICE_ID,
+} from "../../lib/voice/media-devices";
+import { prefetchEngineAssets } from "../../lib/voice/noise-suppression";
+import {
+ engineForMode,
+ noiseSuppressionModeLabel,
+} from "../../lib/voice/ns-engines";
+
+const METER_INTERVAL_MS = 50;
+
+export default class VoiceVoiceSettingsModal extends Component {
+ @service voiceWebrtc;
+
+ @tracked inputDevices = [];
+ @tracked outputDevices = [];
+ @tracked level = 0;
+ @tracked micError = false;
+ @tracked testingOutput = false;
+
+ #previewStream = null;
+ #previewContext = null;
+ #meterTimer = null;
+ #onDeviceChange = () => this.refreshDevices();
+
+ constructor() {
+ super(...arguments);
+ this.startPreview();
+ // Someone opening voice settings may be about to enable suppression;
+ // warming the model bytes makes that toggle near-instant.
+ const engine = engineForMode(this.voiceWebrtc.noiseSuppressionMode);
+ if (engine) {
+ prefetchEngineAssets(engine).catch(() => {});
+ }
+ navigator.mediaDevices?.addEventListener?.(
+ "devicechange",
+ this.#onDeviceChange
+ );
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ navigator.mediaDevices?.removeEventListener?.(
+ "devicechange",
+ this.#onDeviceChange
+ );
+ this.#stopPreview();
+ }
+
+ get outputSupported() {
+ return outputSelectionSupported();
+ }
+
+ get showOutputPrompt() {
+ return (
+ this.outputSupported &&
+ this.outputDevices.length <= 1 &&
+ !!navigator.mediaDevices?.selectAudioOutput
+ );
+ }
+
+ get gateThreshold() {
+ return this.voiceWebrtc.gateThreshold;
+ }
+
+ get busy() {
+ return this.voiceWebrtc.noiseSuppressionState === "starting";
+ }
+
+ get noiseSuppressionModeOptions() {
+ return NOISE_SUPPRESSION_MODES.map((mode) => ({
+ id: mode,
+ name: noiseSuppressionModeLabel(mode),
+ }));
+ }
+
+ get qualityOptions() {
+ return this.voiceWebrtc.allowedVoiceQualityTiers().map((tier) => ({
+ id: tier,
+ name: i18n(`voice.quality.${tier}`),
+ }));
+ }
+
+ get showQuality() {
+ return this.qualityOptions.length > 1;
+ }
+
+ get gateOpen() {
+ return this.gateThreshold === 0 || this.level >= this.gateThreshold;
+ }
+
+ get meterFillStyle() {
+ return trustHTML(`width: ${Math.round(this.level)}%`);
+ }
+
+ get thresholdMarkerStyle() {
+ return trustHTML(`left: ${this.gateThreshold}%`);
+ }
+
+ async startPreview() {
+ this.#stopPreview();
+ this.micError = false;
+
+ let stream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: audioConstraints(this.voiceWebrtc.inputDeviceId),
+ });
+ } catch {
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.micError = true;
+ this.level = 0;
+ }
+ return;
+ }
+
+ if (this.isDestroying || this.isDestroyed) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+
+ this.#previewStream = stream;
+
+ try {
+ const context = new AudioContext();
+ if (context.state === "suspended") {
+ context.resume().catch(() => {});
+ }
+ const source = context.createMediaStreamSource(stream);
+ const analyser = context.createAnalyser();
+ analyser.fftSize = 512;
+ source.connect(analyser);
+ this.#previewContext = context;
+
+ const dataArray = new Uint8Array(analyser.frequencyBinCount);
+ const sample = () => {
+ this.level = rmsToPercent(sampleRms(analyser, dataArray));
+ this.#meterTimer = setTimeout(sample, METER_INTERVAL_MS);
+ };
+ sample();
+ } catch {
+ this.micError = true;
+ }
+
+ await this.refreshDevices();
+ }
+
+ async refreshDevices() {
+ const { inputs, outputs } = await enumerateAudioDevices();
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ const defaultOption = {
+ id: SYSTEM_DEFAULT_DEVICE_ID,
+ name: i18n("voice.devices.system_default"),
+ };
+ this.inputDevices = [defaultOption, ...inputs];
+ this.outputDevices = [defaultOption, ...outputs];
+ }
+
+ @action
+ async onInputChange(deviceId) {
+ await this.voiceWebrtc.setInputDevice(deviceId);
+ await this.startPreview();
+ }
+
+ @action
+ onOutputChange(deviceId) {
+ this.voiceWebrtc.setOutputDevice(deviceId);
+ }
+
+ @action
+ async chooseOutputDevice() {
+ try {
+ const device = await navigator.mediaDevices.selectAudioOutput();
+ this.voiceWebrtc.setOutputDevice(device.deviceId);
+ await this.refreshDevices();
+ } catch {}
+ }
+
+ @action
+ onThresholdChange(event) {
+ this.voiceWebrtc.setGateThreshold(parseInt(event.target.value, 10));
+ }
+
+ @action
+ onNoiseSuppressionModeChange(mode) {
+ if (this.busy) {
+ return;
+ }
+ // Serialization and state live in the audio pipeline; "starting" flows
+ // back through noiseSuppressionState.
+ this.voiceWebrtc.setNoiseSuppressionMode(mode);
+ }
+
+ @action
+ async toggleEchoCancellation() {
+ await this.voiceWebrtc.setEchoCancellation(
+ !this.voiceWebrtc.echoCancellation
+ );
+ // Processing changes swap the capture out from under the level meter.
+ await this.startPreview();
+ }
+
+ get subtitlesAvailable() {
+ return this.voiceWebrtc.subtitlesAvailable;
+ }
+
+ @action
+ toggleSubtitles() {
+ this.voiceWebrtc.toggleSubtitles();
+ }
+
+ @action
+ async toggleAutoGainControl() {
+ await this.voiceWebrtc.setAutoGainControl(
+ !this.voiceWebrtc.autoGainControl
+ );
+ await this.startPreview();
+ }
+
+ @action
+ async playOutputTest() {
+ if (this.testingOutput) {
+ return;
+ }
+ this.testingOutput = true;
+
+ try {
+ const context = new AudioContext();
+ const destination = context.createMediaStreamDestination();
+ const now = context.currentTime;
+
+ [523.25, 659.25].forEach((frequency, index) => {
+ const oscillator = context.createOscillator();
+ const gain = context.createGain();
+ oscillator.frequency.value = frequency;
+ const start = now + index * 0.15;
+ gain.gain.setValueAtTime(0.2, start);
+ gain.gain.exponentialRampToValueAtTime(0.001, start + 0.3);
+ oscillator.connect(gain).connect(destination);
+ oscillator.start(start);
+ oscillator.stop(start + 0.3);
+ });
+
+ const element = new Audio();
+ element.srcObject = destination.stream;
+ applyOutputDevice(element, this.voiceWebrtc.outputDeviceId);
+ await element.play();
+
+ setTimeout(() => {
+ element.pause();
+ element.srcObject = null;
+ context.close().catch(() => {});
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.testingOutput = false;
+ }
+ }, 700);
+ } catch {
+ this.testingOutput = false;
+ }
+ }
+
+ #stopPreview() {
+ if (this.#meterTimer) {
+ clearTimeout(this.#meterTimer);
+ this.#meterTimer = null;
+ }
+
+ if (this.#previewContext) {
+ try {
+ this.#previewContext.close();
+ } catch {}
+ this.#previewContext = null;
+ }
+
+ if (this.#previewStream) {
+ this.#previewStream.getTracks().forEach((track) => track.stop());
+ this.#previewStream = null;
+ }
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "voice.voice_settings.title"}}
+ class="voice-voice-settings-modal"
+ >
+ <:body>
+ <div class="voice-voice-settings">
+ <div class="voice-voice-settings__field">
+ <label class="voice-voice-settings__label">
+ {{i18n "voice.voice_settings.input_device"}}
+ </label>
+ <ComboBox
+ @content={{this.inputDevices}}
+ @value={{this.voiceWebrtc.inputDeviceId}}
+ @onChange={{this.onInputChange}}
+ @options={{hash none=false}}
+ class="voice-voice-settings__input-select"
+ />
+ </div>
+
+ {{#if this.outputSupported}}
+ <div class="voice-voice-settings__field">
+ <label class="voice-voice-settings__label">
+ {{i18n "voice.voice_settings.output_device"}}
+ </label>
+ <div class="voice-voice-settings__output-row">
+ {{#if this.showOutputPrompt}}
+ <DButton
+ @action={{this.chooseOutputDevice}}
+ @icon="headphones"
+ @label="voice.voice_settings.choose_output"
+ class="voice-voice-settings__choose-output-btn"
+ />
+ {{else}}
+ <ComboBox
+ @content={{this.outputDevices}}
+ @value={{this.voiceWebrtc.outputDeviceId}}
+ @onChange={{this.onOutputChange}}
+ @options={{hash none=false}}
+ class="voice-voice-settings__output-select"
+ />
+ {{/if}}
+ <DButton
+ @action={{this.playOutputTest}}
+ @icon="play"
+ @label="voice.voice_settings.test_output"
+ @disabled={{this.testingOutput}}
+ class="voice-voice-settings__test-output-btn"
+ />
+ </div>
+ </div>
+ {{/if}}
+
+ <div class="voice-voice-settings__field">
+ <label class="voice-voice-settings__label">
+ {{i18n "voice.voice_settings.mic_test"}}
+ </label>
+ {{#if this.micError}}
+ <p class="voice-voice-settings__mic-error">
+ {{i18n "voice.voice_settings.mic_error"}}
+ </p>
+ {{else}}
+ <div
+ class="voice-voice-settings__meter
+ {{if this.gateOpen '--open'}}"
+ >
+ <span
+ class="voice-voice-settings__meter-fill"
+ style={{this.meterFillStyle}}
+ ></span>
+ {{#if this.gateThreshold}}
+ <span
+ class="voice-voice-settings__meter-threshold"
+ style={{this.thresholdMarkerStyle}}
+ ></span>
+ {{/if}}
+ </div>
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.mic_test_hint"}}
+ </p>
+ {{/if}}
+ </div>
+
+ <div class="voice-voice-settings__field">
+ <label
+ class="voice-voice-settings__label"
+ for="voice-voice-settings-sensitivity"
+ >
+ {{i18n "voice.voice_settings.input_sensitivity"}}
+ </label>
+ <input
+ type="range"
+ id="voice-voice-settings-sensitivity"
+ min="0"
+ max="100"
+ value={{this.gateThreshold}}
+ class="voice-voice-settings__sensitivity-slider"
+ {{on "input" this.onThresholdChange}}
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.input_sensitivity_hint"}}
+ </p>
+ </div>
+
+ <div class="voice-voice-settings__field">
+ <label class="voice-voice-settings__label">
+ {{i18n "voice.voice_settings.noise_suppression"}}
+ </label>
+ <ComboBox
+ @content={{this.noiseSuppressionModeOptions}}
+ @value={{this.voiceWebrtc.noiseSuppressionMode}}
+ @onChange={{this.onNoiseSuppressionModeChange}}
+ @options={{hash none=false disabled=this.busy}}
+ class="voice-voice-settings__noise-suppression-select"
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.noise_suppression_hint"}}
+ </p>
+ </div>
+
+ <div class="voice-voice-settings__field">
+ <DToggleSwitch
+ @state={{this.voiceWebrtc.echoCancellation}}
+ @label="voice.voice_settings.echo_cancellation"
+ class="voice-voice-settings__echo-cancellation-toggle"
+ {{on "click" this.toggleEchoCancellation}}
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.echo_cancellation_hint"}}
+ </p>
+ </div>
+
+ <div class="voice-voice-settings__field">
+ <DToggleSwitch
+ @state={{this.voiceWebrtc.autoGainControl}}
+ @label="voice.voice_settings.auto_gain_control"
+ class="voice-voice-settings__auto-gain-toggle"
+ {{on "click" this.toggleAutoGainControl}}
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.auto_gain_control_hint"}}
+ </p>
+ </div>
+
+ {{#if this.subtitlesAvailable}}
+ <div class="voice-voice-settings__field">
+ <DToggleSwitch
+ @state={{this.voiceWebrtc.subtitlesEnabled}}
+ @label="voice.voice_settings.subtitles"
+ class="voice-voice-settings__subtitles-toggle"
+ {{on "click" this.toggleSubtitles}}
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.subtitles_hint"}}
+ </p>
+ </div>
+ {{/if}}
+
+ {{#if this.showQuality}}
+ <div class="voice-voice-settings__field">
+ <label class="voice-voice-settings__label">
+ {{i18n "voice.voice_settings.quality"}}
+ </label>
+ <ComboBox
+ @content={{this.qualityOptions}}
+ @value={{this.voiceWebrtc.voiceQuality}}
+ @onChange={{this.voiceWebrtc.setVoiceQuality}}
+ @options={{hash none=false}}
+ class="voice-voice-settings__quality-select"
+ />
+ <p class="voice-voice-settings__hint">
+ {{i18n "voice.voice_settings.quality_hint"}}
+ </p>
+ </div>
+ {{/if}}
+ </div>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/reviewable/voice-user.gjs b/plugins/voice/assets/javascripts/discourse/components/reviewable/voice-user.gjs
new file mode 100644
index 00000000000..5044d451d99
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/reviewable/voice-user.gjs
@@ -0,0 +1,30 @@
+import ReviewableCreatedBy from "discourse/components/reviewable/created-by";
+import getURL from "discourse/lib/get-url";
+import { i18n } from "discourse-i18n";
+
+export default <template>
+ <div class="review-item__meta-content">
+ <div class="review-item__meta-label">{{i18n
+ "voice.review.flagged_in"
+ }}</div>
+
+ <div class="review-item__meta-topic-title">
+ <a href={{getURL @reviewable.room_url}}>{{@reviewable.room_name}}</a>
+ </div>
+
+ <div class="review-item__meta-label">{{i18n "review.review_user"}}</div>
+
+ <div class="review-item__meta-flagged-user">
+ <ReviewableCreatedBy @user={{@reviewable.target_created_by}} />
+ </div>
+ </div>
+
+ <div class="review-item__post">
+ <div class="review-item__post-content-wrapper">
+ <div class="review-item__post-content">
+ {{@reviewable.message}}
+ {{yield}}
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-back-to-voice-room-button.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-back-to-voice-room-button.gjs
new file mode 100644
index 00000000000..e1633e8cf9e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-back-to-voice-room-button.gjs
@@ -0,0 +1,86 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { bind } from "discourse/lib/decorators";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+// Which room (if any) a thread came from is immutable once the thread is
+// created, so both hits and 404s are cached for the page's lifetime — one
+// lookup per thread, no matter how often its header re-renders. Transient
+// failures are evicted so a network flake can't hide the button for good.
+const roomByThread = new Map();
+
+function roomForThread(threadId) {
+ if (!roomByThread.has(threadId)) {
+ roomByThread.set(
+ threadId,
+ ajax(`/voice/chat_threads/${threadId}.json`).catch((error) => {
+ if (error?.jqXHR?.status !== 404) {
+ roomByThread.delete(threadId);
+ }
+ return null;
+ })
+ );
+ }
+ return roomByThread.get(threadId);
+}
+
+export default class VoiceBackToVoiceRoomButton extends Component {
+ @service router;
+ @service siteSettings;
+
+ get thread() {
+ return this.args.outletArgs?.thread;
+ }
+
+ get shouldLookup() {
+ return (
+ this.siteSettings.voice_enabled &&
+ this.siteSettings.voice_chat_enabled &&
+ this.siteSettings.chat_enabled &&
+ this.thread?.id &&
+ !this.thread.staged
+ );
+ }
+
+ @bind
+ loadRoom(threadId) {
+ return roomForThread(threadId);
+ }
+
+ @action
+ async openRoom(room) {
+ const chatActive = await ajax(
+ `/voice/chat_threads/${this.thread.id}.json`
+ ).then(
+ (fresh) => !!fresh.chat_active,
+ () => false // If the lookup fails, assume the chat is inactive and let the room page handle it.
+ );
+
+ this.router.transitionTo("voice-room", room.slug, {
+ queryParams: { join: true, chat: chatActive },
+ });
+ }
+
+ <template>
+ {{#if this.shouldLookup}}
+ <DAsyncContent @asyncData={{this.loadRoom}} @context={{this.thread.id}}>
+ <:loading></:loading>
+ <:content as |room|>
+ {{#if room}}
+ <DButton
+ class="btn-transparent no-text c-navbar__back-to-voice-room"
+ @icon="microphone-lines"
+ @translatedTitle={{i18n "voice.chat.back_to_voice_room"}}
+ @action={{fn this.openRoom room}}
+ />
+ {{/if}}
+ </:content>
+ </DAsyncContent>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-context-menu.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-context-menu.gjs
new file mode 100644
index 00000000000..d0018dd2bc0
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-context-menu.gjs
@@ -0,0 +1,563 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import FlagModal from "discourse/components/modal/flag";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { not } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import { humanKeyName } from "../lib/voice/ptt-utils";
+import VoiceFlag from "../lib/voice-flag";
+import VoiceVoiceSettingsModal from "./modal/voice-voice-settings";
+import VoicePttKeyCapture from "./voice-ptt-key-capture";
+
+export default class VoiceParticipantSidebarContextMenu extends Component {
+ @service currentUser;
+ @service modal;
+ @service voiceWebrtc;
+ @service siteSettings;
+
+ @tracked volume = 100;
+ @tracked isMuted = false;
+ @tracked showKeyCapture = false;
+
+ constructor() {
+ super(...arguments);
+ const { room, participant } = this.args.data;
+ this.volume = Math.round(
+ this.voiceWebrtc.getParticipantVolume(room.id, participant.id) * 100
+ );
+ this.isMuted = this.voiceWebrtc.isParticipantMuted(room.id, participant.id);
+ }
+
+ get room() {
+ return this.args.data.room;
+ }
+
+ get participant() {
+ return this.args.data.participant;
+ }
+
+ get isCurrentUser() {
+ return this.args.data.isCurrentUser;
+ }
+
+ get canManageRoom() {
+ return this.args.data.canManageRoom;
+ }
+
+ get canSpotlight() {
+ return !!this.args.data.onSpotlight;
+ }
+
+ get isSpotlighted() {
+ return !!this.args.data.isSpotlighted;
+ }
+
+ get spotlightLabel() {
+ return this.isSpotlighted
+ ? i18n("voice.participant.remove_spotlight")
+ : i18n("voice.participant.spotlight");
+ }
+
+ get canKick() {
+ return this.canManageRoom && this.participant.id !== this.room.creator_id;
+ }
+
+ get canFlag() {
+ return !!this.currentUser && this.participant.id > 0;
+ }
+
+ get isStageRoom() {
+ return this.room.room_type === "stage";
+ }
+
+ get isListenerInStage() {
+ if (!this.isStageRoom || !this.isCurrentUser) {
+ return false;
+ }
+ const role = this.participant.role;
+ return role !== "moderator" && role !== "speaker";
+ }
+
+ get participantIsSpeakerOrMod() {
+ const role = this.participant.role;
+ return role === "moderator" || role === "speaker";
+ }
+
+ get canPromoteToSpeaker() {
+ return (
+ this.canManageRoom &&
+ this.isStageRoom &&
+ !this.isCurrentUser &&
+ !this.participantIsSpeakerOrMod
+ );
+ }
+
+ get canDemoteToListener() {
+ return (
+ this.canManageRoom &&
+ this.isStageRoom &&
+ !this.isCurrentUser &&
+ this.participant.role === "speaker"
+ );
+ }
+
+ get canDismissRequest() {
+ return (
+ this.canManageRoom &&
+ this.isStageRoom &&
+ !this.isCurrentUser &&
+ !!this.participant.hand_raised_at
+ );
+ }
+
+ get handRaised() {
+ return !!this.participant.hand_raised_at;
+ }
+
+ get raiseHandLabel() {
+ return this.handRaised
+ ? i18n("voice.stage.lower_hand")
+ : i18n("voice.stage.raise_hand");
+ }
+
+ get muteLabel() {
+ return this.isMuted
+ ? i18n("voice.participant.unmute")
+ : i18n("voice.participant.mute");
+ }
+
+ get muteIcon() {
+ return this.isMuted ? "volume-xmark" : "volume-high";
+ }
+
+ get micIcon() {
+ return this.voiceWebrtc.audioEnabled ? "microphone" : "microphone-slash";
+ }
+
+ get micLabel() {
+ return this.voiceWebrtc.audioEnabled
+ ? i18n("voice.room.mic_on")
+ : i18n("voice.room.mic_off");
+ }
+
+ get deafenIcon() {
+ return this.voiceWebrtc.deafened ? "volume-xmark" : "volume-high";
+ }
+
+ get deafenLabel() {
+ return this.voiceWebrtc.deafened
+ ? i18n("voice.room.deafen_off")
+ : i18n("voice.room.deafen_on");
+ }
+
+ get isPttEnabled() {
+ return this.voiceWebrtc.pttEnabled;
+ }
+
+ get pttToggleLabel() {
+ return this.isPttEnabled
+ ? i18n("voice.ptt.disable")
+ : i18n("voice.ptt.enable");
+ }
+
+ get pttKeyLabel() {
+ return i18n("voice.ptt.configure_key", {
+ key: humanKeyName(this.voiceWebrtc.pttKey),
+ });
+ }
+
+ get micDisabledByPtt() {
+ return this.isCurrentUser && this.isPttEnabled;
+ }
+
+ get showAutoStatusToggle() {
+ return this.isCurrentUser && this.siteSettings.voice_auto_status_enabled;
+ }
+
+ get autoStatusLabel() {
+ return this.voiceWebrtc.autoStatusEnabled
+ ? i18n("voice.status.auto_update_on")
+ : i18n("voice.status.auto_update_off");
+ }
+
+ @action
+ onVolumeChange(event) {
+ this.volume = parseInt(event.target.value, 10);
+ this.voiceWebrtc.setParticipantVolume(
+ this.room.id,
+ this.participant.id,
+ this.volume / 100
+ );
+ }
+
+ @action
+ toggleMute() {
+ this.isMuted = this.voiceWebrtc.toggleParticipantMute(
+ this.room.id,
+ this.participant.id
+ );
+ }
+
+ @action
+ toggleSpotlight() {
+ this.args.data.onSpotlight(this.participant.id);
+ this.args.close();
+ }
+
+ @action
+ async kick() {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/kick`, {
+ type: "DELETE",
+ data: { user_id: this.participant.id },
+ });
+ this.args.close();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ flag() {
+ this.args.close();
+ this.modal.show(FlagModal, {
+ model: {
+ flagTarget: new VoiceFlag(this.room),
+ flagModel: {
+ id: this.participant.id,
+ user_id: this.participant.id,
+ username: this.participant.username,
+ },
+ setHidden: () => {},
+ },
+ });
+ }
+
+ @action
+ toggleMic() {
+ this.voiceWebrtc.toggleMute();
+ }
+
+ @action
+ toggleDeafen() {
+ this.voiceWebrtc.toggleDeafen();
+ }
+
+ @action
+ toggleAutoStatus() {
+ this.voiceWebrtc.toggleAutoStatus();
+ }
+
+ @action
+ openVoiceSettings() {
+ this.args.close();
+ this.modal.show(VoiceVoiceSettingsModal);
+ }
+
+ @action
+ togglePtt() {
+ if (this.isPttEnabled) {
+ this.voiceWebrtc.disablePtt();
+ } else {
+ this.voiceWebrtc.enablePtt();
+ }
+ }
+
+ @action
+ openKeyCapture() {
+ this.showKeyCapture = true;
+ }
+
+ @action
+ onKeyCaptureConfirm(keyCode) {
+ this.voiceWebrtc.setPttKey(keyCode);
+ this.showKeyCapture = false;
+ }
+
+ @action
+ onKeyCaptureCancel() {
+ this.showKeyCapture = false;
+ }
+
+ @action
+ async toggleRaiseHand() {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/request_to_speak`, {
+ type: this.handRaised ? "DELETE" : "POST",
+ data: {
+ participant_session_id: this.voiceWebrtc.participantSessionIdFor(
+ this.room.id
+ ),
+ },
+ });
+ this.args.close();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async dismissRequest() {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/request_to_speak`, {
+ type: "DELETE",
+ data: { user_id: this.participant.id },
+ });
+ this.args.close();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async promoteToSpeaker() {
+ await this.#changeParticipantRole("speaker");
+ }
+
+ @action
+ async demoteToListener() {
+ await this.#changeParticipantRole("participant");
+ }
+
+ async #changeParticipantRole(newRole) {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/memberships`, {
+ type: "POST",
+ data: { user_id: this.participant.id, role: newRole },
+ });
+ this.args.close();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DDropdownMenu class="voice-participant-sidebar-context-menu" as |dropdown|>
+ {{#if this.canSpotlight}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleSpotlight}}
+ @icon="person-chalkboard"
+ @translatedLabel={{this.spotlightLabel}}
+ @translatedTitle={{this.spotlightLabel}}
+ @ariaPressed={{this.isSpotlighted}}
+ class="voice-participant-sidebar-context-menu__spotlight-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.isCurrentUser}}
+ {{#unless this.isListenerInStage}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleMic}}
+ @icon={{this.micIcon}}
+ @translatedLabel={{this.micLabel}}
+ @translatedTitle={{if
+ this.micDisabledByPtt
+ (i18n "voice.ptt.controlled_by_ptt")
+ this.micLabel
+ }}
+ @disabled={{this.micDisabledByPtt}}
+ class="voice-participant-sidebar-context-menu__mic-btn
+ {{if this.micDisabledByPtt '--disabled-by-ptt'}}"
+ />
+ {{#if this.micDisabledByPtt}}
+ <span
+ class="voice-participant-sidebar-context-menu__ptt-hint"
+ >{{i18n "voice.ptt.controlled_by_ptt"}}</span>
+ {{/if}}
+ </dropdown.item>
+ {{/unless}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleDeafen}}
+ @icon={{this.deafenIcon}}
+ @translatedLabel={{this.deafenLabel}}
+ @translatedTitle={{this.deafenLabel}}
+ class="voice-participant-sidebar-context-menu__deafen-btn"
+ />
+ </dropdown.item>
+ {{#unless this.isListenerInStage}}
+ <dropdown.item>
+ <DButton
+ @action={{this.togglePtt}}
+ @icon={{if this.isPttEnabled "walkie-talkie" "walkie-talkie"}}
+ @translatedLabel={{this.pttToggleLabel}}
+ @translatedTitle={{this.pttToggleLabel}}
+ class="voice-participant-sidebar-context-menu__ptt-btn
+ {{if this.isPttEnabled '--active'}}"
+ />
+ </dropdown.item>
+ {{#if this.isPttEnabled}}
+ <dropdown.item>
+ {{#if this.showKeyCapture}}
+ <VoicePttKeyCapture
+ @onConfirm={{this.onKeyCaptureConfirm}}
+ @onCancel={{this.onKeyCaptureCancel}}
+ />
+ {{else}}
+ <DButton
+ @action={{this.openKeyCapture}}
+ @icon="keyboard"
+ @translatedLabel={{this.pttKeyLabel}}
+ @translatedTitle={{this.pttKeyLabel}}
+ class="voice-participant-sidebar-context-menu__ptt-key-btn"
+ />
+ {{/if}}
+ </dropdown.item>
+ {{/if}}
+ {{/unless}}
+ <dropdown.item>
+ <DButton
+ @action={{this.openVoiceSettings}}
+ @icon="gear"
+ @label="voice.voice_settings.open"
+ @title="voice.voice_settings.open"
+ class="voice-participant-sidebar-context-menu__voice-settings-btn"
+ />
+ </dropdown.item>
+ {{#if this.showAutoStatusToggle}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleAutoStatus}}
+ @icon={{if
+ this.voiceWebrtc.autoStatusEnabled
+ "square-check"
+ "far-square"
+ }}
+ @translatedLabel={{this.autoStatusLabel}}
+ @translatedTitle={{this.autoStatusLabel}}
+ class="voice-participant-sidebar-context-menu__auto-status-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.isListenerInStage}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleRaiseHand}}
+ @icon="hand"
+ @translatedLabel={{this.raiseHandLabel}}
+ @translatedTitle={{this.raiseHandLabel}}
+ class="voice-participant-sidebar-context-menu__raise-hand-btn
+ {{if this.handRaised '--active'}}"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <span
+ class="voice-participant-sidebar-context-menu__stage-hint"
+ >{{i18n "voice.room.listeners_cannot_unmute"}}</span>
+ </dropdown.item>
+ {{/if}}
+ {{else}}
+ {{#if this.participantIsSpeakerOrMod}}
+ <dropdown.item class="voice-participant-sidebar-context-menu__volume">
+ <label class="voice-participant-sidebar-context-menu__volume-label">
+ {{i18n "voice.participant.volume"}}
+ </label>
+ <input
+ type="range"
+ min="0"
+ max="100"
+ value={{this.volume}}
+ class="voice-participant-sidebar-context-menu__volume-slider"
+ {{on "input" this.onVolumeChange}}
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleMute}}
+ @icon={{this.muteIcon}}
+ @translatedLabel={{this.muteLabel}}
+ @translatedTitle={{this.muteLabel}}
+ class="voice-participant-sidebar-context-menu__mute-btn"
+ />
+ </dropdown.item>
+ {{else if (not this.isStageRoom)}}
+ <dropdown.item class="voice-participant-sidebar-context-menu__volume">
+ <label class="voice-participant-sidebar-context-menu__volume-label">
+ {{i18n "voice.participant.volume"}}
+ </label>
+ <input
+ type="range"
+ min="0"
+ max="100"
+ value={{this.volume}}
+ class="voice-participant-sidebar-context-menu__volume-slider"
+ {{on "input" this.onVolumeChange}}
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleMute}}
+ @icon={{this.muteIcon}}
+ @translatedLabel={{this.muteLabel}}
+ @translatedTitle={{this.muteLabel}}
+ class="voice-participant-sidebar-context-menu__mute-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.canPromoteToSpeaker}}
+ <dropdown.item>
+ <DButton
+ @action={{this.promoteToSpeaker}}
+ @icon="microphone"
+ @label="voice.stage.make_speaker"
+ @title="voice.stage.make_speaker"
+ class="voice-participant-sidebar-context-menu__promote-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.canDemoteToListener}}
+ <dropdown.item>
+ <DButton
+ @action={{this.demoteToListener}}
+ @icon="volume-xmark"
+ @label="voice.stage.move_to_listeners"
+ @title="voice.stage.move_to_listeners"
+ class="voice-participant-sidebar-context-menu__demote-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.canDismissRequest}}
+ <dropdown.item>
+ <DButton
+ @action={{this.dismissRequest}}
+ @icon="xmark"
+ @label="voice.stage.dismiss_request_menu"
+ @title="voice.stage.dismiss_request_menu"
+ class="voice-participant-sidebar-context-menu__dismiss-request-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.canFlag}}
+ <dropdown.item>
+ <DButton
+ @action={{this.flag}}
+ @icon="flag"
+ @label="voice.participant.flag"
+ @title="voice.participant.flag"
+ class="voice-participant-sidebar-context-menu__flag-btn"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.canKick}}
+ <dropdown.item>
+ <DButton
+ @action={{this.kick}}
+ @icon="right-from-bracket"
+ @label="voice.participant.kick"
+ @title="voice.participant.kick"
+ class="voice-participant-sidebar-context-menu__kick-btn btn-danger"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{/if}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-suffix.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-suffix.gjs
new file mode 100644
index 00000000000..78064677592
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-participant-sidebar-suffix.gjs
@@ -0,0 +1,28 @@
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+
+const VoiceParticipantSidebarSuffix = <template>
+ {{! Always rendered, even with no icons — this is the element that pushes
+ itself and the hover menu button to the right edge of the row. }}
+ <span class="voice-participant-suffix">
+ {{#if @suffixArgs.isHandRaised}}
+ {{dIcon "hand" title="voice.participant.status_hand_raised"}}
+ {{/if}}
+ {{#if @suffixArgs.isScreenSharing}}
+ {{dIcon "display" title="voice.participant.status_screen_sharing"}}
+ {{/if}}
+ {{#if @suffixArgs.isVideoOn}}
+ {{dIcon "video" title="voice.participant.status_video"}}
+ {{/if}}
+ {{#if @suffixArgs.isPtt}}
+ {{dIcon "walkie-talkie" title="voice.participant.status_ptt"}}
+ {{/if}}
+ {{#if @suffixArgs.isMuted}}
+ {{dIcon "microphone-slash" title="voice.participant.status_muted"}}
+ {{/if}}
+ {{#if @suffixArgs.isDeafened}}
+ {{dIcon "volume-xmark" title="voice.participant.status_deafened"}}
+ {{/if}}
+ </span>
+</template>;
+
+export default VoiceParticipantSidebarSuffix;
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-ptt-key-capture.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-ptt-key-capture.gjs
new file mode 100644
index 00000000000..2c4a9827e7e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-ptt-key-capture.gjs
@@ -0,0 +1,86 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { modifier as modifierFn } from "ember-modifier";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import { humanKeyName } from "../lib/voice/ptt-utils";
+
+const RESERVED_KEYS = new Set(["Escape", "Tab", "Enter"]);
+
+export default class VoicePttKeyCapture extends Component {
+ @tracked capturedKey = null;
+ @tracked isReserved = false;
+
+ autoFocus = modifierFn((element) => {
+ element.focus();
+ });
+
+ get displayText() {
+ if (this.isReserved) {
+ return i18n("voice.ptt.reserved_key");
+ }
+ if (this.capturedKey) {
+ return humanKeyName(this.capturedKey);
+ }
+ return i18n("voice.ptt.press_key");
+ }
+
+ @action
+ onKeyDown(event) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (RESERVED_KEYS.has(event.code)) {
+ this.isReserved = true;
+ this.capturedKey = null;
+ return;
+ }
+
+ this.isReserved = false;
+ this.capturedKey = event.code;
+ }
+
+ @action
+ confirm() {
+ if (this.capturedKey && !this.isReserved) {
+ this.args.onConfirm?.(this.capturedKey);
+ }
+ }
+
+ @action
+ cancel() {
+ this.args.onCancel?.();
+ }
+
+ <template>
+ <div
+ class="voice-ptt-key-capture"
+ {{on "keydown" this.onKeyDown}}
+ {{this.autoFocus}}
+ tabindex="0"
+ >
+ <span
+ class="voice-ptt-key-capture__display
+ {{if this.isReserved 'voice-ptt-key-capture__display--error'}}
+ {{if this.capturedKey 'voice-ptt-key-capture__display--captured'}}"
+ >
+ {{this.displayText}}
+ </span>
+ <div class="voice-ptt-key-capture__actions">
+ <DButton
+ @action={{this.confirm}}
+ @icon="check"
+ @disabled={{if this.capturedKey false true}}
+ class="btn-flat btn-small voice-ptt-key-capture__confirm"
+ />
+ <DButton
+ @action={{this.cancel}}
+ @icon="xmark"
+ class="btn-flat btn-small voice-ptt-key-capture__cancel"
+ />
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-room-form.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-room-form.gjs
new file mode 100644
index 00000000000..0229bb847d8
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-room-form.gjs
@@ -0,0 +1,342 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import BackButton from "discourse/components/back-button";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceRoomForm extends Component {
+ @service site;
+ @service siteSettings;
+ @service chatApi;
+
+ @tracked isSaving = false;
+ @tracked chatChannels = [];
+
+ get isAdminContext() {
+ return !this.args.onSubmit;
+ }
+
+ get formData() {
+ return {
+ name: this.args.room?.name || "",
+ slug: this.args.room?.slug || "",
+ description: this.args.room?.description || "",
+ public: this.args.room?.public ?? false,
+ room_type: this.args.room?.room_type || "open",
+ max_participants: this.args.room?.max_participants || null,
+ video_enabled: this.args.room?.video_enabled ?? true,
+ livekit_enabled: this.args.room?.livekit_enabled ?? false,
+ chat_channel_id: this.args.room?.chat_channel_id || null,
+ chat_idle_minutes: this.args.room?.chat_idle_minutes ?? 15,
+ max_quality_profile:
+ this.args.room?.max_quality_profile || "site_default",
+ };
+ }
+
+ get showVideoToggle() {
+ return this.siteSettings.voice_video_enabled;
+ }
+
+ get showLivekitToggle() {
+ return this.site.voice_livekit_per_room_available;
+ }
+
+ get showChatSettings() {
+ return (
+ this.siteSettings.chat_enabled && this.siteSettings.voice_chat_enabled
+ );
+ }
+
+ @action
+ async loadChatChannels() {
+ if (!this.showChatSettings) {
+ return;
+ }
+ try {
+ const collection = this.chatApi.channels();
+ await collection.load();
+ this.chatChannels = (collection.items ?? []).filter(
+ (channel) => channel.threadingEnabled
+ );
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ get maxParticipantsValidation() {
+ return "integer|number:2,200";
+ }
+
+ isStageType(roomType) {
+ return roomType === "stage";
+ }
+
+ get roomTypeOptions() {
+ return [
+ {
+ id: "open",
+ name: i18n("voice.room.type_open"),
+ description: i18n("voice.room.type_open_description"),
+ },
+ {
+ id: "stage",
+ name: i18n("voice.room.type_stage"),
+ description: i18n("voice.room.type_stage_description"),
+ },
+ ];
+ }
+
+ get qualityProfileOptions() {
+ return ["site_default", "standard", "high", "maximum"].map((profile) => ({
+ id: profile,
+ name:
+ profile === "site_default"
+ ? i18n("voice.admin.room.quality_site_default")
+ : i18n(`voice.quality.${profile}`),
+ }));
+ }
+
+ get submitLabel() {
+ if (this.isAdminContext) {
+ return this.args.room?.id ? "voice.admin.update" : "voice.admin.create";
+ }
+ return "voice.room.save";
+ }
+
+ @action
+ async handleSubmit(data) {
+ this.isSaving = true;
+
+ try {
+ if (this.args.onSubmit) {
+ await this.args.onSubmit(data);
+ } else {
+ const room = this.args.room;
+ room.setProperties(data);
+ await room.save();
+ this.args.onSave?.(room);
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.isSaving = false;
+ }
+ }
+
+ <template>
+ <div class="voice-room-form {{if this.isAdminContext 'admin-detail'}}">
+ {{#if this.isAdminContext}}
+ <BackButton
+ @label="voice.admin.back"
+ @route="adminPlugins.show.voice-rooms.index"
+ class="voice-admin-back"
+ />
+ {{/if}}
+
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.handleSubmit}}
+ class="voice-room-form__form"
+ as |form data|
+ >
+ <form.Field
+ @type="input"
+ @name="name"
+ @title={{i18n "voice.admin.room.name"}}
+ @format="full"
+ @validation="required|length:1,80"
+ @placeholder={{i18n "voice.admin.room.name_placeholder"}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @type="input"
+ @name="slug"
+ @title={{i18n "voice.admin.room.slug"}}
+ @description={{i18n "voice.admin.room.slug_help"}}
+ @format="full"
+ @placeholder={{i18n "voice.admin.room.slug_placeholder"}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @type="textarea"
+ @name="description"
+ @title={{i18n "voice.admin.room.description"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @type="radio-group"
+ @name="room_type"
+ @title={{i18n "voice.admin.room.room_type"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control as |radioGroup|>
+ {{#each this.roomTypeOptions as |option|}}
+ <radioGroup.Radio @value={{option.id}}>
+ <strong>{{option.name}}</strong>
+ —
+ {{option.description}}
+ </radioGroup.Radio>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ {{#if (this.isStageType data.room_type)}}
+ <div class="voice-room-form__stage-hint">
+ {{i18n "voice.room.type_stage_hint"}}
+ </div>
+ {{/if}}
+
+ <form.Field
+ @type="toggle"
+ @name="public"
+ @title={{i18n "voice.admin.room.public"}}
+ @description={{i18n "voice.admin.room.public_help"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control />
+ {{#if @onManageMembers}}
+ <DButton
+ @action={{@onManageMembers}}
+ @icon="users"
+ @label="voice.admin.room.manage_members"
+ class="btn-link voice-room-form__manage-members
+ {{if data.public '--hidden'}}"
+ />
+ {{/if}}
+ </form.Field>
+
+ {{#if this.showVideoToggle}}
+ <form.Field
+ @type="toggle"
+ @name="video_enabled"
+ @title={{i18n "voice.admin.room.video_enabled"}}
+ @description={{if
+ (this.isStageType data.room_type)
+ (i18n "voice.admin.room.video_enabled_stage_help")
+ (i18n "voice.admin.room.video_enabled_help")
+ }}
+ @format="full"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ {{/if}}
+
+ {{#if this.showLivekitToggle}}
+ <form.Field
+ @type="toggle"
+ @name="livekit_enabled"
+ @title={{i18n "voice.admin.room.livekit_enabled"}}
+ @description={{i18n "voice.admin.room.livekit_enabled_help"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ {{/if}}
+
+ <form.Field
+ @type="input-number"
+ @name="max_participants"
+ @title={{i18n "voice.admin.room.max_participants"}}
+ @description={{i18n "voice.admin.room.max_participants_help"}}
+ @validation={{this.maxParticipantsValidation}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <details class="voice-room-form__quality">
+ <summary>{{i18n "voice.admin.room.quality_section"}}</summary>
+
+ <form.Field
+ @type="select"
+ @name="max_quality_profile"
+ @title={{i18n "voice.admin.room.max_quality_profile"}}
+ @description={{i18n "voice.admin.room.max_quality_profile_help"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control @includeNone={{false}} as |select|>
+ {{#each this.qualityProfileOptions as |option|}}
+ <select.Option @value={{option.id}}>
+ {{option.name}}
+ </select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+ </details>
+
+ {{#if this.showChatSettings}}
+ <div
+ class="voice-room-form__chat"
+ {{didInsert this.loadChatChannels}}
+ >
+ <form.Field
+ @type="select"
+ @name="chat_channel_id"
+ @title={{i18n "voice.admin.room.chat_channel"}}
+ @description={{i18n "voice.admin.room.chat_channel_help"}}
+ @format="full"
+ as |field|
+ >
+ <field.Control as |select|>
+ {{#each this.chatChannels as |channel|}}
+ <select.Option
+ @value={{channel.id}}
+ >{{channel.title}}</select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ {{#unless this.chatChannels.length}}
+ <div class="voice-room-form__chat-empty">
+ {{i18n "voice.admin.room.chat_channel_none"}}
+ </div>
+ {{/unless}}
+
+ {{#if data.chat_channel_id}}
+ <form.Field
+ @type="input-number"
+ @name="chat_idle_minutes"
+ @title={{i18n "voice.admin.room.chat_idle_minutes"}}
+ @description={{i18n "voice.admin.room.chat_idle_minutes_help"}}
+ @validation="integer|number:2,1440"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <div class="voice-room-form__chat-preview">
+ {{i18n "voice.admin.room.chat_thread_hint"}}
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+
+ <form.Submit
+ @label={{this.submitLabel}}
+ @disabled={{this.isSaving}}
+ class="voice-room-form__submit"
+ />
+ </Form>
+ </div>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice-room-sidebar-context-menu.gjs b/plugins/voice/assets/javascripts/discourse/components/voice-room-sidebar-context-menu.gjs
new file mode 100644
index 00000000000..3b50eef757b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice-room-sidebar-context-menu.gjs
@@ -0,0 +1,155 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { clipboardCopy } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import VoiceInviteUsersModal from "./modal/voice-invite-users";
+import VoiceRoomInfoModal from "./modal/voice-room-info";
+
+export default class VoiceRoomSidebarContextMenu extends Component {
+ @service modal;
+ @service voiceWebrtc;
+ @service router;
+ @service toasts;
+
+ get room() {
+ return this.args.data.room;
+ }
+
+ get isConnected() {
+ return this.voiceWebrtc.connectionStateFor(this.room.id) === "connected";
+ }
+
+ @action
+ openRoomPage() {
+ this.router.transitionTo("voice-room", this.room.slug);
+ this.args.close();
+ }
+
+ @action
+ openRoomInfo() {
+ this.modal.show(VoiceRoomInfoModal, { model: { room: this.room } });
+ this.args.close();
+ }
+
+ @action
+ openInviteModal() {
+ this.modal.show(VoiceInviteUsersModal, { model: { room: this.room } });
+ this.args.close();
+ }
+
+ @action
+ copyRoomLink() {
+ const url = this.router.urlFor("voice-room", this.room.slug);
+ clipboardCopy(new URL(url, window.location.origin).href);
+ this.toasts.success({
+ duration: "short",
+ data: { message: i18n("voice.room.link_copied") },
+ });
+ this.args.close();
+ }
+
+ @action
+ editRoom() {
+ this.modal.show(VoiceRoomInfoModal, {
+ model: { room: this.room, isEditing: true },
+ });
+ this.args.close();
+ }
+
+ @action
+ toggleCallWidget() {
+ this.voiceWebrtc.toggleCallWidgetHidden();
+ this.args.close();
+ }
+
+ @action
+ leaveRoom() {
+ this.voiceWebrtc.leave(this.room);
+ this.args.close();
+ }
+
+ <template>
+ <DDropdownMenu class="voice-room-sidebar-context-menu" as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{this.openRoomPage}}
+ @icon="expand"
+ @label="voice.room.open_page"
+ @title="voice.room.open_page"
+ class="voice-room-sidebar-context-menu__open-page"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{this.openRoomInfo}}
+ @icon="circle-info"
+ @label="voice.room.info"
+ @title="voice.room.info"
+ class="voice-room-sidebar-context-menu__room-info"
+ />
+ </dropdown.item>
+ {{#if this.room.can_invite}}
+ <dropdown.item>
+ <DButton
+ @action={{this.openInviteModal}}
+ @icon="user-plus"
+ @label="voice.invite.menu"
+ @title="voice.invite.menu"
+ class="voice-room-sidebar-context-menu__invite"
+ />
+ </dropdown.item>
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{this.copyRoomLink}}
+ @icon="link"
+ @label="voice.room.copy_link"
+ @title="voice.room.copy_link"
+ class="voice-room-sidebar-context-menu__copy-link"
+ />
+ </dropdown.item>
+ {{#if this.room.can_manage}}
+ <dropdown.item>
+ <DButton
+ @action={{this.editRoom}}
+ @icon="pencil"
+ @label="voice.room.edit"
+ @title="voice.room.edit"
+ class="voice-room-sidebar-context-menu__edit-room"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.isConnected}}
+ <dropdown.item>
+ <DButton
+ @action={{this.toggleCallWidget}}
+ @icon={{if this.voiceWebrtc.callWidgetHidden "eye" "eye-slash"}}
+ @label={{if
+ this.voiceWebrtc.callWidgetHidden
+ "voice.widget.show"
+ "voice.widget.hide"
+ }}
+ @title={{if
+ this.voiceWebrtc.callWidgetHidden
+ "voice.widget.show"
+ "voice.widget.hide"
+ }}
+ class="voice-room-sidebar-context-menu__toggle-widget"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{this.leaveRoom}}
+ @icon="phone-slash"
+ @label="voice.room.leave"
+ @title="voice.room.leave"
+ class="voice-room-sidebar-context-menu__leave-room --danger"
+ />
+ </dropdown.item>
+ {{/if}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/call-button.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/call-button.gjs
new file mode 100644
index 00000000000..f451a00913b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/call-button.gjs
@@ -0,0 +1,36 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import icon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { unlockAudio } from "../../lib/voice/sound-effects";
+
+export default class VoiceCallButton extends Component {
+ @service("voice-calls") voiceCalls;
+
+ // A plain button: the click must synchronously unlock the AudioContext so
+ // the waiting tone can play once the call request round-trips, and deferred
+ // action wrappers can outlive that activation.
+ @action
+ async call() {
+ unlockAudio();
+ try {
+ await this.voiceCalls.callUser(this.args.user.username);
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <button
+ type="button"
+ class="btn btn-icon-text btn-primary voice-call-button__button"
+ {{on "click" this.call}}
+ >
+ {{icon "phone"}}
+ <span class="d-button-label">{{i18n "voice.call.button"}}</span>
+ </button>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/call-controls.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/call-controls.gjs
new file mode 100644
index 00000000000..cd5661a15d1
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/call-controls.gjs
@@ -0,0 +1,614 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ isAiMode,
+ NOISE_SUPPRESSION_MODES,
+} from "../../lib/voice/audio-processing";
+import {
+ enumerateAudioDevices,
+ enumerateVideoDevices,
+ outputSelectionSupported,
+ SYSTEM_DEFAULT_DEVICE_ID,
+} from "../../lib/voice/media-devices";
+import { prefetchEngineAssets } from "../../lib/voice/noise-suppression";
+import {
+ engineForMode,
+ noiseSuppressionModeLabel,
+} from "../../lib/voice/ns-engines";
+import { queuePosition } from "../../lib/voice/speak-queue";
+import VoiceVideoSettingsModal from "../modal/voice-video-settings";
+import VoiceVoiceSettingsModal from "../modal/voice-voice-settings";
+import VoiceCallSubmenu from "./call-submenu";
+
+const AUDIO_MENU = "voice-audio-menu";
+const VIDEO_MENU = "voice-video-menu";
+const SUBMENU = "voice-call-submenu";
+
+// The audio/video capture controls shared by the room page and the persistent
+// call widget: mic and camera "combo" buttons (a toggle plus a caret opening
+// device pickers and settings), plus the deafen and screen-share buttons.
+//
+// Hosts render this inside their own `__controls` footer and append their
+// context-specific tail (overflow menu, leave button, etc.) as siblings.
+export default class VoiceCallControls extends Component {
+ @service currentUser;
+ @service dialog;
+ @service menu;
+ @service modal;
+ @service voiceWebrtc;
+ @service siteSettings;
+
+ @tracked audioInputDevices = [];
+ @tracked audioOutputDevices = [];
+ @tracked videoInputDevices = [];
+ @tracked recordingPending = false;
+
+ get room() {
+ return this.args.room;
+ }
+
+ get videoAllowed() {
+ return this.voiceWebrtc.videoAllowedIn(this.room);
+ }
+
+ get cameraActive() {
+ return this.voiceWebrtc.localVideoKind === "camera";
+ }
+
+ get screenShareActive() {
+ return this.voiceWebrtc.localVideoKind === "screen";
+ }
+
+ get cameraDisabled() {
+ return (
+ !this.cameraActive && !this.voiceWebrtc.canPublishVideo(this.room?.id)
+ );
+ }
+
+ get screenShareDisabled() {
+ return (
+ !this.screenShareActive &&
+ !this.voiceWebrtc.canPublishVideo(this.room?.id)
+ );
+ }
+
+ get showScreenShare() {
+ return this.videoAllowed && this.voiceWebrtc.screenShareSupported;
+ }
+
+ get #ownParticipant() {
+ return (this.room?.active_participants || []).find(
+ (participant) => Number(participant?.id) === this.currentUser?.id
+ );
+ }
+
+ get isStageListener() {
+ if (this.room?.room_type !== "stage") {
+ return false;
+ }
+ const role = this.#ownParticipant?.role;
+ return !!this.#ownParticipant && role !== "moderator" && role !== "speaker";
+ }
+
+ get handRaisedAt() {
+ return this.#ownParticipant?.hand_raised_at;
+ }
+
+ get raiseHandTitle() {
+ if (!this.handRaisedAt) {
+ return i18n("voice.stage.raise_hand");
+ }
+
+ const position = queuePosition(this.room, this.currentUser?.id);
+ const lowerHand = i18n("voice.stage.lower_hand");
+ return position
+ ? `${lowerHand} — ${i18n("voice.stage.queue_position", { position })}`
+ : lowerHand;
+ }
+
+ get noiseSuppressionOn() {
+ return this.voiceWebrtc.noiseSuppressionState === "on";
+ }
+
+ get noiseSuppressionStarting() {
+ return this.voiceWebrtc.noiseSuppressionState === "starting";
+ }
+
+ // Standard (native) suppression is the browser default everywhere, so
+ // only the AI mode earns an indicator.
+ get showNoiseSuppressionBadge() {
+ return (
+ this.voiceWebrtc.audioEnabled &&
+ isAiMode(this.voiceWebrtc.noiseSuppressionMode) &&
+ this.voiceWebrtc.noiseSuppressionState !== "off"
+ );
+ }
+
+ get currentNoiseSuppressionModeName() {
+ return noiseSuppressionModeLabel(this.voiceWebrtc.noiseSuppressionMode);
+ }
+
+ get micTitle() {
+ if (this.voiceWebrtc.pttEnabled) {
+ return i18n("voice.ptt.controlled_by_ptt");
+ }
+ const title = this.voiceWebrtc.audioEnabled
+ ? i18n("voice.room.mic_on")
+ : i18n("voice.room.mic_off");
+ if (this.showNoiseSuppressionBadge && this.noiseSuppressionOn) {
+ return `${title} — ${i18n("voice.room.noise_suppression_active")}`;
+ }
+ return title;
+ }
+
+ get cameraTitle() {
+ return this.cameraActive
+ ? i18n("voice.video.camera_off")
+ : i18n("voice.video.camera_on");
+ }
+
+ get screenShareTitle() {
+ return this.screenShareActive
+ ? i18n("voice.video.screen_share_stop")
+ : i18n("voice.video.screen_share_start");
+ }
+
+ get deafenTitle() {
+ return this.voiceWebrtc.deafened
+ ? i18n("voice.room.deafen_off")
+ : i18n("voice.room.deafen_on");
+ }
+
+ get audioOutputSupported() {
+ return outputSelectionSupported();
+ }
+
+ get canRecord() {
+ return (
+ this.room?.can_manage &&
+ this.siteSettings.voice_livekit_recording_enabled &&
+ this.voiceWebrtc.isLivekitRoom(this.room?.id)
+ );
+ }
+
+ get recordingActive() {
+ return !!this.room?.recording;
+ }
+
+ get recordTitle() {
+ return this.recordingActive
+ ? i18n("voice.room.recording_stop")
+ : i18n("voice.room.recording_start");
+ }
+
+ @action
+ toggleMute() {
+ this.voiceWebrtc.toggleMute();
+ }
+
+ @action
+ toggleDeafen() {
+ this.voiceWebrtc.toggleDeafen();
+ }
+
+ @action
+ toggleCamera() {
+ this.voiceWebrtc.toggleCamera();
+ }
+
+ @action
+ toggleScreenShare() {
+ this.voiceWebrtc.toggleScreenShare();
+ }
+
+ @action
+ async toggleRaiseHand() {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/request_to_speak`, {
+ type: this.handRaisedAt ? "DELETE" : "POST",
+ data: {
+ participant_session_id: this.voiceWebrtc.participantSessionIdFor(
+ this.room.id
+ ),
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ toggleRecording() {
+ const stopping = this.recordingActive;
+
+ this.dialog.yesNoConfirm({
+ message: stopping
+ ? i18n("voice.room.recording_stop_confirm")
+ : i18n("voice.room.recording_confirm"),
+ didConfirm: async () => {
+ this.recordingPending = true;
+ try {
+ // The room-wide "recording" broadcast flips the button and shows
+ // the indicator; no local state to update here.
+ await ajax(`/voice/rooms/${this.room.id}/recording`, {
+ type: stopping ? "DELETE" : "POST",
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.recordingPending = false;
+ }
+ },
+ });
+ }
+
+ @action
+ openVoiceSettings(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceVoiceSettingsModal);
+ }
+
+ @action
+ openVideoSettings(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceVideoSettingsModal);
+ }
+
+ #systemDefaultDevice() {
+ return {
+ id: SYSTEM_DEFAULT_DEVICE_ID,
+ name: i18n("voice.devices.system_default"),
+ };
+ }
+
+ get currentInputDeviceName() {
+ return this.audioInputDevices.find(
+ (device) => device.id === this.voiceWebrtc.inputDeviceId
+ )?.name;
+ }
+
+ get currentOutputDeviceName() {
+ return this.audioOutputDevices.find(
+ (device) => device.id === this.voiceWebrtc.outputDeviceId
+ )?.name;
+ }
+
+ get currentVideoDeviceName() {
+ return this.videoInputDevices.find(
+ (device) => device.id === this.voiceWebrtc.videoInputDeviceId
+ )?.name;
+ }
+
+ @action
+ openNoiseSuppressionMenu(_actionArg, event) {
+ this.#openSubmenu(
+ event,
+ AUDIO_MENU,
+ NOISE_SUPPRESSION_MODES.map((mode) => ({
+ id: mode,
+ label: noiseSuppressionModeLabel(mode),
+ selected: mode === this.voiceWebrtc.noiseSuppressionMode,
+ })),
+ (mode) => this.voiceWebrtc.setNoiseSuppressionMode(mode)
+ );
+ }
+
+ @action
+ async loadAudioDevices() {
+ // If the persisted mode is an AI engine, warming its assets makes the
+ // next enable (rejoin, unmute) near-instant.
+ const engine = engineForMode(this.voiceWebrtc.noiseSuppressionMode);
+ if (engine) {
+ prefetchEngineAssets(engine).catch(() => {});
+ }
+ const { inputs, outputs } = await enumerateAudioDevices();
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ const defaultDevice = this.#systemDefaultDevice();
+ this.audioInputDevices = [defaultDevice, ...inputs];
+ this.audioOutputDevices = [defaultDevice, ...outputs];
+ }
+
+ @action
+ async loadVideoDevices() {
+ const inputs = await enumerateVideoDevices();
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this.videoInputDevices = [this.#systemDefaultDevice(), ...inputs];
+ }
+
+ // Opened programmatically (not a nested <DMenu>) so the trigger stays a
+ // normal full-width menu item, matching core's channel context menu.
+ #openSubmenu(event, parentMenu, items, onSelect) {
+ // Anchor to the row button, not the clicked icon/label, so the submenu
+ // opens flush to the row's right edge.
+ const anchor = event.target.closest(".btn") ?? event.target;
+ this.menu.show(anchor, {
+ identifier: SUBMENU,
+ groupIdentifier: SUBMENU,
+ component: VoiceCallSubmenu,
+ placement: "right-start",
+ offset: { mainAxis: 8, crossAxis: -5 },
+ modalForMobile: true,
+ data: {
+ items,
+ onSelect: (id) => {
+ onSelect(id);
+ this.menu.close(parentMenu);
+ },
+ },
+ });
+ }
+
+ #deviceItems(devices, currentId) {
+ return devices.map((device) => ({
+ id: device.id,
+ label: device.name,
+ selected: device.id === currentId,
+ }));
+ }
+
+ @action
+ openInputDeviceMenu(_actionArg, event) {
+ this.#openSubmenu(
+ event,
+ AUDIO_MENU,
+ this.#deviceItems(this.audioInputDevices, this.voiceWebrtc.inputDeviceId),
+ (id) => this.voiceWebrtc.setInputDevice(id)
+ );
+ }
+
+ @action
+ openOutputDeviceMenu(_actionArg, event) {
+ this.#openSubmenu(
+ event,
+ AUDIO_MENU,
+ this.#deviceItems(
+ this.audioOutputDevices,
+ this.voiceWebrtc.outputDeviceId
+ ),
+ (id) => this.voiceWebrtc.setOutputDevice(id)
+ );
+ }
+
+ @action
+ openCameraMenu(_actionArg, event) {
+ this.#openSubmenu(
+ event,
+ VIDEO_MENU,
+ this.#deviceItems(
+ this.videoInputDevices,
+ this.voiceWebrtc.videoInputDeviceId
+ ),
+ (id) => this.voiceWebrtc.setVideoInputDevice(id)
+ );
+ }
+
+ <template>
+ <div class="voice-call-controls__combo">
+ <DButton
+ @action={{this.toggleMute}}
+ @icon={{if
+ this.voiceWebrtc.audioEnabled
+ "microphone"
+ "microphone-slash"
+ }}
+ @translatedTitle={{this.micTitle}}
+ @disabled={{this.voiceWebrtc.pttEnabled}}
+ class={{dConcatClass
+ "btn-default voice-call-controls__combo-main"
+ (if this.voiceWebrtc.audioEnabled "" "--off")
+ }}
+ >
+ {{#if this.showNoiseSuppressionBadge}}
+ <span
+ class={{dConcatClass
+ "voice-call-controls__ns-badge"
+ (if this.noiseSuppressionStarting "--starting")
+ }}
+ aria-hidden="true"
+ >
+ {{dIcon "discourse-sparkles"}}
+ </span>
+ {{/if}}
+ </DButton>
+ <DMenu
+ @identifier="voice-audio-menu"
+ @icon="angle-down"
+ @title={{i18n "voice.room.audio_options"}}
+ @ariaLabel={{i18n "voice.room.audio_options"}}
+ @placement="top-end"
+ @onShow={{this.loadAudioDevices}}
+ @triggerClass="btn-default voice-call-controls__combo-caret"
+ >
+ <:content as |audioMenu|>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{this.openInputDeviceMenu}}
+ @forwardEvent={{true}}
+ @icon="microphone"
+ @label="voice.voice_settings.input_audio"
+ @suffixIcon="angle-right"
+ class="btn-transparent voice-call-menu__device-row"
+ >
+ {{#if this.currentInputDeviceName}}
+ <span class="voice-call-menu__current-device">
+ {{this.currentInputDeviceName}}
+ </span>
+ {{/if}}
+ </DButton>
+ </dropdown.item>
+ {{#if this.audioOutputSupported}}
+ <dropdown.item>
+ <DButton
+ @action={{this.openOutputDeviceMenu}}
+ @forwardEvent={{true}}
+ @icon="volume-high"
+ @label="voice.voice_settings.output_audio"
+ @suffixIcon="angle-right"
+ class="btn-transparent voice-call-menu__device-row"
+ >
+ {{#if this.currentOutputDeviceName}}
+ <span class="voice-call-menu__current-device">
+ {{this.currentOutputDeviceName}}
+ </span>
+ {{/if}}
+ </DButton>
+ </dropdown.item>
+ {{/if}}
+ <dropdown.divider />
+ <dropdown.item>
+ <DButton
+ @action={{this.openNoiseSuppressionMenu}}
+ @forwardEvent={{true}}
+ @icon="discourse-sparkles"
+ @label="voice.voice_settings.noise_suppression"
+ @suffixIcon="angle-right"
+ @disabled={{this.noiseSuppressionStarting}}
+ class="btn-transparent voice-call-menu__device-row voice-call-menu__noise-suppression"
+ >
+ <span class="voice-call-menu__current-device">
+ {{this.currentNoiseSuppressionModeName}}
+ </span>
+ </DButton>
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openVoiceSettings audioMenu.close}}
+ @icon="sliders"
+ @label="voice.voice_settings.audio_settings"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ {{#if this.isStageListener}}
+ <DButton
+ @action={{this.toggleRaiseHand}}
+ @icon="hand"
+ @translatedTitle={{this.raiseHandTitle}}
+ class={{dConcatClass
+ "btn-default voice-call-controls__raise-hand"
+ (if this.handRaisedAt "--active")
+ }}
+ />
+ {{/if}}
+ {{! Capture buttons are plain <button>s on purpose: DButton defers its
+ action via next(), which lands outside the click event dispatch — Firefox
+ only allows getDisplayMedia during the actual dispatch, so a deferred call
+ throws NotAllowedError. }}
+ {{#if this.videoAllowed}}
+ <div class="voice-call-controls__combo">
+ <button
+ type="button"
+ class={{dConcatClass
+ "btn btn-icon no-text btn-default voice-call-controls__combo-main"
+ (if this.cameraActive "--active")
+ }}
+ title={{this.cameraTitle}}
+ aria-label={{this.cameraTitle}}
+ disabled={{this.cameraDisabled}}
+ {{on "click" this.toggleCamera}}
+ >
+ {{dIcon (if this.cameraActive "video" "video-slash")}}
+ {{! Zero-width space: matches DButton so an icon-only button keeps
+ full button height and aligns with its DButton siblings. }}
+ <span aria-hidden="true">&#8203;</span>
+ </button>
+ <DMenu
+ @identifier="voice-video-menu"
+ @icon="angle-down"
+ @title={{i18n "voice.room.video_options"}}
+ @ariaLabel={{i18n "voice.room.video_options"}}
+ @placement="top-end"
+ @onShow={{this.loadVideoDevices}}
+ @triggerClass="btn-default voice-call-controls__combo-caret"
+ >
+ <:content as |videoMenu|>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{this.openCameraMenu}}
+ @forwardEvent={{true}}
+ @icon="video"
+ @label="voice.video_settings.camera"
+ @suffixIcon="angle-right"
+ class="btn-transparent voice-call-menu__device-row"
+ >
+ {{#if this.currentVideoDeviceName}}
+ <span class="voice-call-menu__current-device">
+ {{this.currentVideoDeviceName}}
+ </span>
+ {{/if}}
+ </DButton>
+ </dropdown.item>
+ <dropdown.divider />
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openVideoSettings videoMenu.close}}
+ @icon="sliders"
+ @label="voice.video_settings.title"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ {{/if}}
+ <DButton
+ @action={{this.toggleDeafen}}
+ @icon={{if this.voiceWebrtc.deafened "volume-xmark" "ear-listen"}}
+ @translatedTitle={{this.deafenTitle}}
+ class={{dConcatClass
+ "btn-default"
+ (if this.voiceWebrtc.deafened "--off" "")
+ }}
+ />
+ {{#if this.canRecord}}
+ <DButton
+ @action={{this.toggleRecording}}
+ @icon="record-vinyl"
+ @translatedTitle={{this.recordTitle}}
+ @disabled={{this.recordingPending}}
+ class={{dConcatClass
+ "btn-default voice-call-controls__record"
+ (if this.recordingActive "--recording")
+ }}
+ />
+ {{/if}}
+ {{#if this.showScreenShare}}
+ <button
+ type="button"
+ class={{dConcatClass
+ "btn btn-icon no-text btn-default"
+ (if this.screenShareActive "--active")
+ }}
+ title={{this.screenShareTitle}}
+ aria-label={{this.screenShareTitle}}
+ disabled={{this.screenShareDisabled}}
+ {{on "click" this.toggleScreenShare}}
+ >
+ {{dIcon "display"}}
+ <span aria-hidden="true">&#8203;</span>
+ </button>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/call-submenu.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/call-submenu.gjs
new file mode 100644
index 00000000000..87955e90851
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/call-submenu.gjs
@@ -0,0 +1,34 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+// Side submenu for the call menus (device pickers, layout switcher), opened
+// via the `menu` service — see VoiceRoomPage.
+export default class VoiceCallSubmenu extends Component {
+ @action
+ select(id) {
+ this.args.data.onSelect(id);
+ this.args.close?.();
+ }
+
+ <template>
+ <DDropdownMenu as |dropdown|>
+ {{#each @data.items key="id" as |item|}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.select item.id}}
+ @icon={{item.icon}}
+ @translatedLabel={{item.label}}
+ class={{dConcatClass
+ "btn-transparent"
+ (if item.selected "-selected")
+ }}
+ />
+ </dropdown.item>
+ {{/each}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/call-widget.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/call-widget.gjs
new file mode 100644
index 00000000000..9bb2b8ffae5
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/call-widget.gjs
@@ -0,0 +1,847 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { concat, fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { next } from "@ember/runloop";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { avatarUrl } from "discourse/lib/avatar-utils";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import { i18n } from "discourse-i18n";
+import { activeRingingEntries } from "../../lib/voice/ringing";
+import {
+ computeWidgetGrid,
+ trackGridSize,
+} from "../../lib/voice/video-grid-layout";
+import VoiceInviteUsersModal from "../modal/voice-invite-users";
+import VoiceRoomInfoModal from "../modal/voice-room-info";
+import VoiceCallControls from "./call-controls";
+import VoiceRecordingBadge from "./recording-badge";
+import VoiceRingingTile from "./ringing-tile";
+import VoiceTranscriptBadge from "./transcript-badge";
+import VoiceVideoTile from "./video-tile";
+
+const WIDGET_VIDEO_TILE_BUDGET = 4;
+const WIDGET_VIEWPORT_MARGIN = 16;
+const WIDGET_MIN_WIDTH = 300;
+const WIDGET_MIN_HEIGHT = 180;
+const WIDGET_EXTRA_MINIMIZED_WIDTH = 118;
+const WIDGET_EXTRA_MINIMIZED_HEIGHT = 52;
+const WIDGET_MAX_WIDTH_RATIO = 0.5;
+const WIDGET_MAX_HEIGHT_RATIO = 0.5;
+const WIDGET_SIZE_KEY = "voice-widget-size";
+const DRAG_THRESHOLD = 3;
+const RESIZE_CORNERS = ["nw", "ne", "sw", "se"];
+
+function clamp(value, min, max) {
+ if (max < min) {
+ return min;
+ }
+ return Math.min(Math.max(value, min), max);
+}
+
+export default class VoiceCallWidget extends Component {
+ @service capabilities;
+ @service currentUser;
+ @service modal;
+ @service router;
+ @service voiceRooms;
+ @service voiceWebrtc;
+ @service keyValueStore;
+
+ @tracked widgetWidth = null;
+ @tracked widgetHeight = null;
+ @tracked posLeft = null;
+ @tracked posTop = null;
+ @tracked dragging = false;
+ @tracked resizing = false;
+ @tracked extraMinimized = false;
+ @tracked tileAreaWidth = 0;
+ @tracked tileAreaHeight = 0;
+ @tracked tileAreaGap = 0;
+
+ // Ring windows expire by wall clock, which nothing tracked observes — a
+ // coarse ticker re-evaluates them so "Calling…" tiles disappear on time.
+ @tracked ringingClock = Date.now();
+
+ resizeCorners = RESIZE_CORNERS;
+
+ widgetElement = null;
+ dragState = null;
+ resizeState = null;
+ #ringingTicker = null;
+
+ constructor() {
+ super(...arguments);
+ this.#loadSize();
+
+ // The widget is always mounted, so the tick only touches tracked state
+ // while an ephemeral call could actually be showing ringing tiles.
+ this.#ringingTicker = setInterval(() => {
+ if (this.room?.ephemeral) {
+ this.ringingClock = Date.now();
+ }
+ }, 5000);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ clearInterval(this.#ringingTicker);
+ this.#removeResizeListeners();
+ this.#removeDragListeners();
+ window.clearTimeout(this.dragHoldTimer);
+ this.stopWatchingWidgetRoom();
+ }
+
+ #loadSize() {
+ const raw = this.keyValueStore.get(WIDGET_SIZE_KEY);
+ if (!raw) {
+ return;
+ }
+ try {
+ const { width, height, extraMinimized } = JSON.parse(raw);
+ this.extraMinimized = !!extraMinimized;
+ this.widgetWidth = this.extraMinimized ? null : this.#clampWidth(width);
+ this.widgetHeight = this.extraMinimized
+ ? null
+ : this.#clampHeight(height);
+ } catch {
+ this.widgetWidth = null;
+ this.widgetHeight = null;
+ this.extraMinimized = false;
+ }
+ }
+
+ #saveSize() {
+ this.keyValueStore.set({
+ key: WIDGET_SIZE_KEY,
+ value: JSON.stringify({
+ width: this.widgetWidth,
+ height: this.widgetHeight,
+ extraMinimized: this.extraMinimized,
+ }),
+ });
+ }
+
+ #clampWidth(width) {
+ if (!width) {
+ return null;
+ }
+ return clamp(
+ width,
+ WIDGET_MIN_WIDTH,
+ Math.min(
+ window.innerWidth * WIDGET_MAX_WIDTH_RATIO,
+ window.innerWidth - WIDGET_VIEWPORT_MARGIN * 2
+ )
+ );
+ }
+
+ #clampHeight(height) {
+ if (!height) {
+ return null;
+ }
+ return clamp(
+ height,
+ WIDGET_MIN_HEIGHT,
+ Math.min(
+ window.innerHeight * WIDGET_MAX_HEIGHT_RATIO,
+ window.innerHeight - WIDGET_VIEWPORT_MARGIN * 2
+ )
+ );
+ }
+
+ get room() {
+ const activeRoomId = this.voiceWebrtc.activeRoomId;
+ if (!activeRoomId) {
+ return null;
+ }
+
+ return (
+ this.voiceRooms.rooms.find(
+ (room) => Number(room.id) === Number(activeRoomId)
+ ) ?? this.voiceWebrtc.activeRoom
+ );
+ }
+
+ get shouldRender() {
+ return (
+ !!this.room &&
+ !this.onActiveRoomPage &&
+ !this.voiceWebrtc.callWidgetHidden
+ );
+ }
+
+ get onActiveRoomPage() {
+ const currentRoute = this.router.currentRoute;
+ return (
+ currentRoute?.name === "voice-room" &&
+ currentRoute?.params?.slug === this.room?.slug
+ );
+ }
+
+ get participants() {
+ return this.room?.active_participants || [];
+ }
+
+ get ringingEntries() {
+ return activeRingingEntries(this.room, this.ringingClock);
+ }
+
+ get grid() {
+ return computeWidgetGrid({
+ width: this.tileAreaWidth,
+ height: this.tileAreaHeight,
+ // Ringing pseudo-tiles occupy grid cells like everyone else so tile
+ // sizing accounts for them.
+ count: this.participants.length + this.ringingEntries.length,
+ gap: this.tileAreaGap,
+ });
+ }
+
+ // Screen shares beat cameras beat everything else for the scarce widget
+ // slots. Selection only — render order stays the roster's canonical order,
+ // so tiles don't reshuffle when someone toggles a camera; a promoted
+ // participant swaps in where the roster places them.
+ @cached
+ get visibleParticipants() {
+ const participants = this.participants;
+ // Ringing pseudo-tiles always render, so they claim their share of the
+ // grid's slots before participants are picked for the rest.
+ const shown = Math.max(
+ 0,
+ (this.grid?.shown ?? participants.length + this.ringingEntries.length) -
+ this.ringingEntries.length
+ );
+ if (shown >= participants.length) {
+ return participants;
+ }
+
+ const prioritized = [...participants].sort(
+ (a, b) => this.#tileRank(a) - this.#tileRank(b)
+ );
+ const visibleIds = new Set(
+ prioritized.slice(0, shown).map((participant) => participant.id)
+ );
+ return participants.filter((participant) => visibleIds.has(participant.id));
+ }
+
+ get hiddenParticipants() {
+ const visibleIds = new Set(
+ this.visibleParticipants.map((participant) => participant.id)
+ );
+ return this.participants.filter(
+ (participant) => !visibleIds.has(participant.id)
+ );
+ }
+
+ #tileRank(participant) {
+ if (participant.id === this.currentUser?.id) {
+ const kind = this.voiceWebrtc.localVideoKind;
+ return kind === "screen" ? 0 : kind ? 1 : 2;
+ }
+ if (participant.is_screen_sharing) {
+ return 0;
+ }
+ return participant.is_video_on ? 1 : 2;
+ }
+
+ #isPublishing(participant) {
+ if (participant.id === this.currentUser?.id) {
+ return !!this.voiceWebrtc.localVideoKind;
+ }
+ return participant.is_video_on || participant.is_screen_sharing;
+ }
+
+ get tiles() {
+ const visible = this.visibleParticipants;
+
+ // The live-video budget follows the same priority as slot selection, so a
+ // screen share is never demoted to an avatar by roster-earlier cameras.
+ const budgeted = new Set(
+ [...visible]
+ .sort((a, b) => this.#tileRank(a) - this.#tileRank(b))
+ .filter((participant) => this.#isPublishing(participant))
+ .slice(0, WIDGET_VIDEO_TILE_BUDGET)
+ .map((participant) => participant.id)
+ );
+
+ return visible.map((participant) => ({
+ participant,
+ isSelf: participant.id === this.currentUser?.id,
+ showVideo: budgeted.has(participant.id),
+ }));
+ }
+
+ get overflowCount() {
+ return this.hiddenParticipants.length;
+ }
+
+ get overflowAvatars() {
+ return this.hiddenParticipants.slice(0, 3).map((participant) => ({
+ id: participant.id,
+ src: avatarUrl(participant.avatar_template, "small"),
+ }));
+ }
+
+ get overflowTitle() {
+ return i18n("voice.widget.overflow_tile", { count: this.overflowCount });
+ }
+
+ get overflowLabel() {
+ return i18n("voice.widget.overflow_count", { count: this.overflowCount });
+ }
+
+ get tilesStyle() {
+ const grid = this.grid;
+ if (!grid) {
+ return null;
+ }
+ return trustHTML(
+ `--voice-tile-width: ${grid.tileWidth}px; --voice-tile-height: ${grid.tileHeight}px;`
+ );
+ }
+
+ get openRoomTitle() {
+ return i18n("voice.room.open_page");
+ }
+
+ get chatAvailable() {
+ return !!this.room?.chat_available;
+ }
+
+ get chatTitle() {
+ return i18n("voice.widget.open_chat");
+ }
+
+ get expandWidgetTitle() {
+ return i18n("voice.widget.expand");
+ }
+
+ get widgetStyle() {
+ const parts = [];
+
+ if (this.capabilities.touch) {
+ if (this.posTop !== null) {
+ const h = this.widgetElement?.offsetHeight ?? 0;
+ const top = clamp(
+ this.posTop,
+ WIDGET_VIEWPORT_MARGIN,
+ Math.max(
+ WIDGET_VIEWPORT_MARGIN,
+ window.innerHeight - h - WIDGET_VIEWPORT_MARGIN
+ )
+ );
+ parts.push(`inset-block-start: ${top}px;`, "inset-block-end: auto;");
+ }
+ return parts.length ? trustHTML(parts.join(" ")) : null;
+ }
+
+ const width = this.extraMinimized
+ ? WIDGET_EXTRA_MINIMIZED_WIDTH
+ : this.#clampWidth(this.widgetWidth);
+ const height = this.extraMinimized
+ ? WIDGET_EXTRA_MINIMIZED_HEIGHT
+ : this.#clampHeight(this.widgetHeight);
+
+ if (width) {
+ parts.push(`width: ${width}px;`);
+ }
+ if (height) {
+ parts.push(`height: ${height}px; max-height: ${height}px;`);
+ }
+
+ if (this.posLeft !== null && this.posTop !== null) {
+ const w = width ?? this.widgetElement?.offsetWidth ?? 0;
+ const h = height ?? this.widgetElement?.offsetHeight ?? 0;
+ const left = clamp(
+ this.posLeft,
+ WIDGET_VIEWPORT_MARGIN,
+ Math.max(
+ WIDGET_VIEWPORT_MARGIN,
+ window.innerWidth - w - WIDGET_VIEWPORT_MARGIN
+ )
+ );
+ const top = clamp(
+ this.posTop,
+ WIDGET_VIEWPORT_MARGIN,
+ Math.max(
+ WIDGET_VIEWPORT_MARGIN,
+ window.innerHeight - h - WIDGET_VIEWPORT_MARGIN
+ )
+ );
+ parts.push(
+ `inset-inline-start: ${left}px;`,
+ "inset-inline-end: auto;",
+ `inset-block-start: ${top}px;`,
+ "inset-block-end: auto;"
+ );
+ }
+
+ return parts.length ? trustHTML(parts.join(" ")) : null;
+ }
+
+ @action
+ openRoom() {
+ if (this.room?.slug) {
+ this.router.transitionTo("voice-room", this.room.slug);
+ }
+ }
+
+ @action
+ startDrag(event) {
+ if (event.type === "mousedown" && event.button !== 0) {
+ return;
+ }
+ if (!this.widgetElement) {
+ return;
+ }
+
+ const point = this.#eventPoint(event);
+ if (!point) {
+ return;
+ }
+
+ const rect = this.widgetElement.getBoundingClientRect();
+ this.dragState = {
+ startX: point.x,
+ startY: point.y,
+ originLeft: rect.left,
+ originTop: rect.top,
+ width: rect.width,
+ height: rect.height,
+ armed: false,
+ };
+
+ window.addEventListener("mousemove", this.dragWidget);
+ window.addEventListener("touchmove", this.dragWidget, { passive: false });
+ window.addEventListener("mouseup", this.stopDrag);
+ window.addEventListener("touchend", this.stopDrag);
+
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ }
+
+ @action
+ dragWidget(event) {
+ const state = this.dragState;
+ if (!state) {
+ return;
+ }
+
+ const point = this.#eventPoint(event);
+ if (!point) {
+ return;
+ }
+
+ const dx = point.x - state.startX;
+ const dy = point.y - state.startY;
+
+ if (!state.armed) {
+ if (Math.max(Math.abs(dx), Math.abs(dy)) < DRAG_THRESHOLD) {
+ return;
+ }
+ state.armed = true;
+ this.dragging = true;
+ }
+
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+
+ this.posTop = clamp(
+ state.originTop + dy,
+ WIDGET_VIEWPORT_MARGIN,
+ window.innerHeight - state.height - WIDGET_VIEWPORT_MARGIN
+ );
+
+ if (!this.capabilities.touch) {
+ this.posLeft = clamp(
+ state.originLeft + dx,
+ WIDGET_VIEWPORT_MARGIN,
+ window.innerWidth - state.width - WIDGET_VIEWPORT_MARGIN
+ );
+ }
+ }
+
+ @action
+ stopDrag() {
+ this.#removeDragListeners();
+ this.dragState = null;
+ this.dragging = false;
+ }
+
+ @action
+ startResize(corner, event) {
+ if (event.type === "mousedown" && event.button !== 0) {
+ return;
+ }
+ if (!this.widgetElement) {
+ return;
+ }
+
+ const rect = this.widgetElement.getBoundingClientRect();
+ const onLeft = corner === "nw" || corner === "sw";
+ const onTop = corner === "nw" || corner === "ne";
+
+ this.resizeState = {
+ onLeft,
+ onTop,
+ anchorX: onLeft ? rect.right : rect.left,
+ anchorY: onTop ? rect.bottom : rect.top,
+ };
+ this.resizing = true;
+
+ window.addEventListener("mousemove", this.resizeWidget);
+ window.addEventListener("touchmove", this.resizeWidget, { passive: false });
+ window.addEventListener("mouseup", this.stopResize);
+ window.addEventListener("touchend", this.stopResize);
+
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ event.stopPropagation();
+ }
+
+ @action
+ resizeWidget(event) {
+ const state = this.resizeState;
+ if (!state) {
+ return;
+ }
+
+ const point = this.#eventPoint(event);
+ if (!point) {
+ return;
+ }
+
+ const maxWidth = Math.min(
+ window.innerWidth * WIDGET_MAX_WIDTH_RATIO,
+ state.onLeft
+ ? state.anchorX - WIDGET_VIEWPORT_MARGIN
+ : window.innerWidth - state.anchorX - WIDGET_VIEWPORT_MARGIN
+ );
+ const maxHeight = Math.min(
+ window.innerHeight * WIDGET_MAX_HEIGHT_RATIO,
+ state.onTop
+ ? state.anchorY - WIDGET_VIEWPORT_MARGIN
+ : window.innerHeight - state.anchorY - WIDGET_VIEWPORT_MARGIN
+ );
+
+ const rawWidth = Math.abs(point.x - state.anchorX);
+ const rawHeight = Math.abs(point.y - state.anchorY);
+
+ if (rawWidth < WIDGET_MIN_WIDTH || rawHeight < WIDGET_MIN_HEIGHT) {
+ this.extraMinimized = true;
+ this.widgetWidth = null;
+ this.widgetHeight = null;
+ this.posLeft = null;
+ this.posTop = null;
+
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ return;
+ }
+
+ const width = clamp(rawWidth, WIDGET_MIN_WIDTH, maxWidth);
+ const height = clamp(rawHeight, WIDGET_MIN_HEIGHT, maxHeight);
+
+ this.extraMinimized = false;
+ this.widgetWidth = width;
+ this.widgetHeight = height;
+ this.posLeft = state.onLeft ? state.anchorX - width : state.anchorX;
+ this.posTop = state.onTop ? state.anchorY - height : state.anchorY;
+
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ }
+
+ @action
+ stopResize() {
+ if (!this.resizeState) {
+ return;
+ }
+
+ this.#removeResizeListeners();
+ this.resizeState = null;
+ this.resizing = false;
+ this.#saveSize();
+ }
+
+ #removeResizeListeners() {
+ window.removeEventListener("mousemove", this.resizeWidget);
+ window.removeEventListener("touchmove", this.resizeWidget);
+ window.removeEventListener("mouseup", this.stopResize);
+ window.removeEventListener("touchend", this.stopResize);
+ }
+
+ #removeDragListeners() {
+ window.removeEventListener("mousemove", this.dragWidget);
+ window.removeEventListener("touchmove", this.dragWidget);
+ window.removeEventListener("mouseup", this.stopDrag);
+ window.removeEventListener("touchend", this.stopDrag);
+ }
+
+ #eventPoint(event) {
+ const touch =
+ event.touches?.[0] ||
+ event.changedTouches?.[0] ||
+ (event.clientX != null ? event : null);
+ return touch ? { x: touch.clientX, y: touch.clientY } : null;
+ }
+
+ @action
+ leaveRoom() {
+ this.voiceWebrtc.leave(this.room);
+ }
+
+ @action
+ expandWidget() {
+ this.extraMinimized = false;
+ this.widgetWidth = null;
+ this.widgetHeight = null;
+ this.posLeft = null;
+ this.posTop = null;
+ this.#saveSize();
+ }
+
+ @action
+ openChat() {
+ if (this.room?.slug) {
+ this.router.transitionTo("voice-room", this.room.slug, {
+ queryParams: { chat: true },
+ });
+ }
+ }
+
+ @action
+ openChatFromMenu(closeMenu) {
+ closeMenu?.();
+ this.openChat();
+ }
+
+ @action
+ openRoomInfo(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceRoomInfoModal, { model: { room: this.room } });
+ }
+
+ @action
+ openInviteModal(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceInviteUsersModal, { model: { room: this.room } });
+ }
+
+ @action
+ noopAspect() {}
+
+ @action
+ updateTileAreaSize(width, height, gap) {
+ this.tileAreaWidth = width;
+ this.tileAreaHeight = height;
+ this.tileAreaGap = gap;
+ }
+
+ @action
+ registerWidget(element) {
+ this.widgetElement = element;
+ this.watchWidgetRoom();
+ }
+
+ @action
+ watchWidgetRoom() {
+ const roomId = this.room?.id;
+ if (!roomId) {
+ return;
+ }
+
+ next(this, () => {
+ if (this.isDestroying || this.isDestroyed || this.room?.id !== roomId) {
+ return;
+ }
+
+ this.voiceWebrtc.setWatching(roomId, true);
+ });
+ }
+
+ stopWatchingWidgetRoom() {
+ const roomId = this.room?.id;
+ if (roomId) {
+ this.voiceWebrtc.setWatching(roomId, false, { keepVideo: true });
+ }
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding, ember/template-no-invalid-interactive }}
+ {{#if this.shouldRender}}
+ <section
+ class={{dConcatClass
+ "voice-call-widget"
+ (if this.resizing "--resizing")
+ (if this.dragging "--dragging")
+ (if this.extraMinimized "--extra-minimized")
+ }}
+ style={{this.widgetStyle}}
+ data-room-id={{this.room.id}}
+ aria-label={{i18n "voice.widget.title" room=this.room.name}}
+ {{didInsert this.registerWidget}}
+ {{didInsert this.watchWidgetRoom this.room.id}}
+ {{on "pointermove" this.dragWidget}}
+ {{on "pointerup" this.stopDrag}}
+ {{on "pointercancel" this.stopDrag}}
+ >
+ {{#unless this.extraMinimized}}
+ <header class="voice-call-widget__header">
+ <div
+ class="voice-call-widget__room"
+ role="heading"
+ aria-level="2"
+ {{on "mousedown" this.startDrag}}
+ {{on "touchstart" this.startDrag}}
+ >
+ <span
+ class="voice-call-widget__room-name"
+ >{{this.room.name}}</span>
+ <VoiceRecordingBadge @room={{this.room}} />
+ <VoiceTranscriptBadge @room={{this.room}} />
+ </div>
+ </header>
+
+ <div
+ class="voice-call-widget__tiles"
+ style={{this.tilesStyle}}
+ {{trackGridSize this.updateTileAreaSize}}
+ >
+ {{#each this.tiles key="participant.id" as |tile|}}
+ <VoiceVideoTile
+ @room={{this.room}}
+ @participant={{tile.participant}}
+ @isSelf={{tile.isSelf}}
+ @showVideo={{tile.showVideo}}
+ @onAspect={{this.noopAspect}}
+ />
+ {{/each}}
+
+ {{#each this.ringingEntries key="user.id" as |entry|}}
+ <VoiceRingingTile @user={{entry.user}} />
+ {{/each}}
+
+ {{#if this.overflowCount}}
+ <button
+ type="button"
+ class="voice-call-widget__overflow-tile"
+ title={{this.overflowTitle}}
+ aria-label={{this.overflowTitle}}
+ {{on "click" this.openRoom}}
+ >
+ <span
+ class="voice-call-widget__overflow-avatars"
+ aria-hidden="true"
+ >
+ {{#each this.overflowAvatars key="id" as |avatar|}}
+ <img src={{avatar.src}} alt="" />
+ {{/each}}
+ </span>
+ <span
+ class="voice-call-widget__overflow-count"
+ aria-hidden="true"
+ >{{this.overflowLabel}}</span>
+ </button>
+ {{/if}}
+ </div>
+ {{/unless}}
+
+ <footer class="voice-call-widget__controls">
+ {{#if this.extraMinimized}}
+ <DButton
+ @action={{this.expandWidget}}
+ @icon="expand"
+ @translatedTitle={{this.expandWidgetTitle}}
+ class="voice-call-widget__expand"
+ />
+ {{else}}
+ <VoiceCallControls @room={{this.room}} />
+ <DButton
+ @action={{this.openRoom}}
+ @icon="expand"
+ @translatedTitle={{this.openRoomTitle}}
+ class="btn-default"
+ />
+ <DMenu
+ @identifier="voice-widget-room-menu"
+ @icon="ellipsis-vertical"
+ @title={{i18n "voice.room.more"}}
+ @ariaLabel={{i18n "voice.room.more"}}
+ @placement="top-end"
+ @modalForMobile={{true}}
+ @triggerClass="btn-default"
+ >
+ <:content as |roomMenu|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.chatAvailable}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openChatFromMenu roomMenu.close}}
+ @icon="far-comment"
+ @translatedLabel={{this.chatTitle}}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.room.can_invite}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openInviteModal roomMenu.close}}
+ @icon="user-plus"
+ @label="voice.invite.menu"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openRoomInfo roomMenu.close}}
+ @icon="circle-info"
+ @label="voice.room.info"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <DButton
+ @action={{this.leaveRoom}}
+ @icon="phone-slash"
+ @ariaLabel="voice.room.leave"
+ class="btn-danger voice-call-widget__leave"
+ />
+ </footer>
+
+ {{#unless this.capabilities.touch}}
+ {{#each this.resizeCorners as |corner|}}
+ {{#unless this.extraMinimized}}
+ <div
+ class={{dConcatClass
+ "voice-call-widget__resize"
+ (concat "--" corner)
+ }}
+ aria-hidden="true"
+ {{on "mousedown" (fn this.startResize corner)}}
+ {{on "touchstart" (fn this.startResize corner)}}
+ ></div>
+ {{/unless}}
+ {{/each}}
+ {{/unless}}
+ </section>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/caption-overlay.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/caption-overlay.gjs
new file mode 100644
index 00000000000..0f021c1c3a0
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/caption-overlay.gjs
@@ -0,0 +1,68 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+
+const MAX_VISIBLE_LINES = 3;
+const LINE_TTL_MS = 10000;
+const PRUNE_INTERVAL_MS = 1000;
+
+export default class VoiceCaptionOverlay extends Component {
+ @service voiceWebrtc;
+
+ // Bumped on a timer so lines fall off the overlay once they go stale,
+ // not only when a newer caption pushes them out.
+ @tracked now = Date.now();
+
+ #pruneTimer = setInterval(() => {
+ this.now = Date.now();
+ }, PRUNE_INTERVAL_MS);
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ clearInterval(this.#pruneTimer);
+ }
+
+ get visibleCaptions() {
+ const cutoff = this.now - LINE_TTL_MS;
+ return this.voiceWebrtc
+ .captionsFor(this.args.room.id)
+ .filter((caption) => caption.at > cutoff)
+ .slice(-MAX_VISIBLE_LINES);
+ }
+
+ get showLoading() {
+ return this.voiceWebrtc.subtitlesLoading && !this.visibleCaptions.length;
+ }
+
+ get loadingLabel() {
+ const percent = this.voiceWebrtc.subtitlesProgress;
+ if (percent !== null) {
+ return i18n("voice.subtitles.downloading", { percent });
+ }
+ return i18n("voice.subtitles.loading");
+ }
+
+ <template>
+ {{#if this.voiceWebrtc.subtitlesEnabled}}
+ <div class="voice-captions" aria-live="polite">
+ {{#if this.showLoading}}
+ <p class="voice-captions__line --loading">
+ {{this.loadingLabel}}
+ </p>
+ {{else}}
+ {{#each this.visibleCaptions key="id" as |caption|}}
+ <p class="voice-captions__line {{if caption.interim '--interim'}}">
+ {{#if caption.username}}
+ <span
+ class="voice-captions__speaker"
+ >{{caption.username}}</span>
+ {{/if}}
+ {{caption.text}}
+ </p>
+ {{/each}}
+ {{/if}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/chat-panel.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/chat-panel.gjs
new file mode 100644
index 00000000000..8f34ae4fc98
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/chat-panel.gjs
@@ -0,0 +1,354 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { array } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import EmojiPicker from "discourse/components/emoji-picker";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { optionalRequire } from "discourse/lib/utilities";
+import { and } from "discourse/truth-helpers";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceChatPanel extends Component {
+ @service chat;
+ @service chatChannelsManager;
+ @service messageBus;
+ @service router;
+
+ @tracked loading = true;
+ @tracked unavailable = false;
+ @tracked channel = null;
+ @tracked thread = null;
+ @tracked draft = "";
+ @tracked sending = false;
+ @tracked hideSkeleton = false;
+
+ // Resolved at runtime rather than statically imported: cross-plugin static
+ // imports aren't resolvable in the compiled plugin bundle and break the
+ // whole bundle load.
+ chatThread = optionalRequire(
+ "discourse/plugins/chat/discourse/components/chat-thread"
+ );
+ // Chat's own loading skeleton doubles as the panel's loading state, so the
+ // hand-off to the thread's identical skeleton reads as one continuous load
+ // instead of a spinner flashing into a skeleton.
+ chatSkeleton = optionalRequire(
+ "discourse/plugins/chat/discourse/components/chat-skeleton"
+ );
+
+ textareaElement = null;
+ #sessionPath = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#unsubscribeSession();
+ this.#deactivate();
+ }
+
+ get room() {
+ return this.args.room;
+ }
+
+ get canOpenInChat() {
+ return !!this.thread;
+ }
+
+ get sendDisabled() {
+ return this.sending || this.draft.trim().length === 0;
+ }
+
+ @action
+ async loadSession() {
+ this.#subscribeSession();
+
+ try {
+ // POST prepares the session: it rolls a stale session over and follows
+ // us on the channel so chat's own message endpoints accept our posts.
+ // The thread itself only comes into existence with the first message.
+ const data = await ajax(`/voice/rooms/${this.room.id}/chat_session`, {
+ type: "POST",
+ });
+ await this.#applyState(data);
+ } catch (e) {
+ this.unavailable = true;
+ popupAjaxError(e);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async onSessionMessage() {
+ try {
+ const data = await ajax(`/voice/rooms/${this.room.id}/chat_session`);
+ await this.#applyState(data);
+ } catch {
+ // A transient refresh failure only delays the panel following a session
+ // change; the next signal or reopen retries.
+ }
+ }
+
+ async #applyState(data) {
+ if (!data?.channel_id || !data?.thread_id) {
+ return;
+ }
+ if (this.thread?.id === data.thread_id && this.channel) {
+ return;
+ }
+
+ const channel = await this.chatChannelsManager.find(data.channel_id);
+ if (!channel.isFollowing) {
+ // The server already followed us when the session was ensured; this only
+ // refreshes a channel that was cached client-side before that happened.
+ await this.chatChannelsManager.follow(channel);
+ }
+ const thread = await channel.threadsManager.find(
+ channel.id,
+ data.thread_id
+ );
+
+ this.channel = channel;
+ this.thread = thread;
+
+ // ChatThreadPane and the composer resolve "the current thread" from this
+ // global active state, exactly like the chat drawer's router sets it —
+ // without it, sending and message actions break outside chat's own routes.
+ this.chat.activeChannel = channel;
+ channel.activeThread = thread;
+ }
+
+ #deactivate() {
+ if (this.channel && this.chat.activeChannel === this.channel) {
+ // Also clears the channel's activeThread (the setter handles it).
+ this.chat.activeChannel = null;
+ }
+ }
+
+ #subscribeSession() {
+ if (this.#sessionPath) {
+ return;
+ }
+ this.#sessionPath = `/voice/rooms/${this.room.id}/chat`;
+ this.messageBus.subscribe(this.#sessionPath, this.onSessionMessage);
+ }
+
+ #unsubscribeSession() {
+ if (this.#sessionPath) {
+ this.messageBus.unsubscribe(this.#sessionPath, this.onSessionMessage);
+ this.#sessionPath = null;
+ }
+ }
+
+ @action
+ interceptEscape(event) {
+ if (event.key !== "Escape") {
+ return;
+ }
+ if (this.thread?.draft?.editing) {
+ // Let the composer's own handler cancel the in-progress edit.
+ return;
+ }
+ // The thread composer's Escape handler "closes the pane" by routing to the
+ // chat channel page, which would navigate away from the room — swallow it.
+ event.stopPropagation();
+ }
+
+ @action
+ openInChat() {
+ if (!this.thread) {
+ return;
+ }
+ this.router.transitionTo("chat.channel.thread", ...this.thread.routeModels);
+ }
+
+ @action
+ registerTextarea(element) {
+ this.textareaElement = element;
+ }
+
+ @action
+ updateDraft(event) {
+ this.draft = event.target.value;
+ this.#autogrow();
+ }
+
+ @action
+ onKeydown(event) {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ this.sendFirstMessage();
+ }
+ }
+
+ @action
+ insertEmoji(emoji) {
+ const code = `:${emoji}:`;
+ const element = this.textareaElement;
+
+ if (!element) {
+ this.draft = `${this.draft}${code}`;
+ return;
+ }
+
+ const value = element.value;
+ const start = element.selectionStart ?? value.length;
+ const end = element.selectionEnd ?? value.length;
+ const nextValue = `${value.slice(0, start)}${code}${value.slice(end)}`;
+ element.value = nextValue;
+ this.draft = nextValue;
+ this.#autogrow();
+
+ element.focus();
+ const caret = start + code.length;
+ element.setSelectionRange(caret, caret);
+ }
+
+ // Sends the session's opening message, which creates the thread it roots —
+ // the panel then swaps to chat's own thread UI and every later message goes
+ // through chat's own composer instead.
+ @action
+ async sendFirstMessage() {
+ if (this.sendDisabled) {
+ return;
+ }
+
+ this.sending = true;
+ // The freshly created thread holds only this message, which loads faster
+ // than the thread's skeleton can finish appearing — keep the skeleton out
+ // of this swap so it doesn't flash.
+ this.hideSkeleton = true;
+ try {
+ const data = await ajax(`/voice/rooms/${this.room.id}/chat_message`, {
+ type: "POST",
+ data: { message: this.draft },
+ });
+ // Swap to the thread UI before clearing anything: the starter composer
+ // keeps the typed text until the native thread replaces it, so the panel
+ // doesn't flash an empty "no chat yet" state mid-send. Clearing only on
+ // success also means a rejection (a duplicate, rate limit, …) doesn't
+ // eat what the user typed.
+ await this.#applyState(data);
+ this.draft = "";
+ if (this.textareaElement) {
+ this.textareaElement.value = "";
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.sending = false;
+ }
+ }
+
+ #autogrow() {
+ const element = this.textareaElement;
+ if (!element) {
+ return;
+ }
+ element.style.height = "auto";
+ element.style.height = `${element.scrollHeight}px`;
+ }
+
+ <template>
+ <section
+ class="voice-chat"
+ aria-label={{i18n "voice.chat.title"}}
+ {{didInsert this.loadSession}}
+ >
+ <header class="voice-chat__header">
+ <h2 class="voice-chat__title">
+ {{i18n "voice.chat.title"}}
+ </h2>
+ {{#if this.canOpenInChat}}
+ <button
+ type="button"
+ class="btn btn-transparent btn-icon no-text voice-chat__open-in-chat"
+ title={{i18n "voice.chat.open_in_chat"}}
+ aria-label={{i18n "voice.chat.open_in_chat"}}
+ {{on "click" this.openInChat}}
+ >
+ {{dIcon "up-right-from-square"}}
+ </button>
+ {{/if}}
+ {{#if @onClose}}
+ <button
+ type="button"
+ class="btn btn-icon no-text voice-chat__close"
+ title={{i18n "voice.chat.close"}}
+ aria-label={{i18n "voice.chat.close"}}
+ {{on "click" @onClose}}
+ >
+ {{dIcon "xmark"}}
+ </button>
+ {{/if}}
+ </header>
+
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div
+ class="voice-chat__body {{if this.hideSkeleton '--hide-skeleton'}}"
+ {{on "keydown" this.interceptEscape capture=true}}
+ >
+ {{#if this.loading}}
+ {{#if this.chatSkeleton}}
+ <this.chatSkeleton />
+ {{else}}
+ <DConditionalLoadingSpinner @condition={{true}} />
+ {{/if}}
+ {{else if (and this.chatThread this.thread)}}
+ {{#each (array this.thread) key="id" as |thread|}}
+ <this.chatThread @thread={{thread}} />
+ {{/each}}
+ {{else if this.unavailable}}
+ <div class="voice-chat__empty">
+ {{dIcon "far-comment"}}
+ <p class="voice-chat__empty-title">
+ {{i18n "voice.chat.unavailable"}}
+ </p>
+ </div>
+ {{else}}
+ <div class="voice-chat__empty">
+ {{dIcon "far-comment"}}
+ <p class="voice-chat__empty-title">
+ {{i18n "voice.chat.empty_title"}}
+ </p>
+ <p class="voice-chat__empty-body">
+ {{i18n "voice.chat.empty_body"}}
+ </p>
+ </div>
+ <footer class="voice-chat__composer">
+ <div class="voice-chat__composer-inner">
+ <EmojiPicker
+ @context="voice-chat"
+ @didSelectEmoji={{this.insertEmoji}}
+ @btnClass="btn-transparent voice-chat__emoji"
+ />
+ <textarea
+ class="voice-chat__input"
+ rows="1"
+ placeholder={{i18n "voice.chat.composer_placeholder"}}
+ aria-label={{i18n "voice.chat.composer_placeholder"}}
+ {{didInsert this.registerTextarea}}
+ {{on "input" this.updateDraft}}
+ {{on "keydown" this.onKeydown}}
+ ></textarea>
+ <button
+ type="button"
+ class="btn btn-transparent btn-icon no-text voice-chat__send"
+ title={{i18n "voice.chat.send"}}
+ aria-label={{i18n "voice.chat.send"}}
+ disabled={{this.sendDisabled}}
+ {{on "click" this.sendFirstMessage}}
+ >
+ {{dIcon "paper-plane"}}
+ </button>
+ </div>
+ </footer>
+ {{/if}}
+ </div>
+ </section>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/global-call-layer.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/global-call-layer.gjs
new file mode 100644
index 00000000000..b8a1063ad95
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/global-call-layer.gjs
@@ -0,0 +1,7 @@
+import VoiceCallWidget from "./call-widget";
+import VoiceVoiceCanvas from "./voice-canvas";
+
+export default <template>
+ <VoiceVoiceCanvas />
+ <VoiceCallWidget />
+</template>
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/recording-badge.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/recording-badge.gjs
new file mode 100644
index 00000000000..278e2bc0f35
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/recording-badge.gjs
@@ -0,0 +1,24 @@
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+// The room-wide "this call is being recorded" indicator. Rendered wherever a
+// room's call is shown (full page, floating widget) so nobody can be in a
+// recorded call without seeing it.
+const VoiceRecordingBadge = <template>
+ {{#if @room.recording}}
+ <span
+ class="voice-recording-badge"
+ title={{i18n
+ "voice.room.recording_indicator_title"
+ [email protected]_by.username
+ }}
+ >
+ {{dIcon "record-vinyl"}}
+ <span class="voice-recording-badge__label">
+ {{i18n "voice.room.recording_indicator"}}
+ </span>
+ </span>
+ {{/if}}
+</template>;
+
+export default VoiceRecordingBadge;
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/ringing-tile.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/ringing-tile.gjs
new file mode 100644
index 00000000000..d440a990098
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/ringing-tile.gjs
@@ -0,0 +1,20 @@
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+// A grid tile for someone who is being rung but hasn't picked up: styled
+// apart from real participant tiles so nobody mistakes them for present.
+const VoiceRingingTile = <template>
+ <div class="voice-video-tile voice-ringing-tile" ...attributes>
+ <div class="voice-ringing-tile__animation">
+ {{! Placeholder — a bespoke ringing SVG animation will replace this icon }}
+ {{dIcon "phone-volume"}}
+ </div>
+ <div class="voice-video-tile__info">
+ <span class="voice-video-tile__name">
+ {{i18n "voice.call.calling" [email protected]}}
+ </span>
+ </div>
+ </div>
+</template>;
+
+export default VoiceRingingTile;
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/room-page.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/room-page.gjs
new file mode 100644
index 00000000000..2b5f7b451a2
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/room-page.gjs
@@ -0,0 +1,824 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { cancel, next } from "@ember/runloop";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import DMenu from "discourse/float-kit/components/d-menu";
+import discourseLater from "discourse/lib/later";
+import { defaultHomepage } from "discourse/lib/utilities";
+import { or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { toggleFullscreen, trackFullscreen } from "../../lib/voice/fullscreen";
+import { activeRingingEntries } from "../../lib/voice/ringing";
+import { speakQueue } from "../../lib/voice/speak-queue";
+import {
+ bestRowHeight,
+ DEFAULT_TILE_ASPECT,
+ trackGridSize,
+} from "../../lib/voice/video-grid-layout";
+import VoiceInviteUsersModal from "../modal/voice-invite-users";
+import VoiceRoomInfoModal from "../modal/voice-room-info";
+import VoiceCallControls from "./call-controls";
+import VoiceCallSubmenu from "./call-submenu";
+import VoiceCaptionOverlay from "./caption-overlay";
+import VoiceChatPanel from "./chat-panel";
+import VoiceRecordingBadge from "./recording-badge";
+import VoiceRingingTile from "./ringing-tile";
+import VoiceSpeakQueue from "./speak-queue";
+import VoiceTranscriptBadge from "./transcript-badge";
+import VoiceVideoTile from "./video-tile";
+
+const ROOM_MENU = "voice-room-menu";
+const SUBMENU = "voice-call-submenu";
+// Keep in sync with the `voice-room` path in voice-route-map.js
+const ROOM_PATH_PREFIX = "/voice/r/";
+
+const MOBILE_VIDEO_TILE_BUDGET = 4;
+const LAYOUT_PRESENTATION = "presentation";
+const LAYOUT_TILED = "tiled";
+
+export default class VoiceRoomPage extends Component {
+ @service capabilities;
+ @service currentUser;
+ @service menu;
+ @service modal;
+ @service routeHistory;
+ @service router;
+ @service voiceRooms;
+ @service voiceWebrtc;
+
+ @tracked gridWidth = 0;
+ @tracked gridHeight = 0;
+ @tracked gridGap = 0;
+ @tracked tileAspects = new Map();
+ @tracked gridFullscreen = false;
+ // Stage rooms mirror a workshop: chat panel open, presenter featured.
+ @tracked chatOpen = !!this.args.openChat || this.#isStageRoom;
+ @tracked chatClosing = false;
+ @tracked layoutMode = this.#isStageRoom ? LAYOUT_PRESENTATION : LAYOUT_TILED;
+ @tracked spotlightParticipantId = null;
+
+ // Ring windows expire by wall clock, which nothing tracked observes — a
+ // coarse ticker re-evaluates them so "Calling…" tiles disappear on time.
+ @tracked ringingClock = Date.now();
+
+ gridElement = null;
+ trackGridSize = trackGridSize;
+ trackFullscreen = trackFullscreen;
+ #chatCloseFallback = null;
+ #ringingTicker = null;
+
+ constructor() {
+ super(...arguments);
+ if (this.args.room?.ephemeral) {
+ this.#ringingTicker = setInterval(() => {
+ this.ringingClock = Date.now();
+ }, 5000);
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ clearInterval(this.#ringingTicker);
+ cancel(this.#chatCloseFallback);
+ const voiceWebrtc = this.voiceWebrtc;
+ const roomId = this.args.room.id;
+ const keepVideo = voiceWebrtc.isActiveRoom(roomId);
+
+ next(() => {
+ voiceWebrtc.setWatching(roomId, false, { keepVideo });
+ });
+ }
+
+ get #isStageRoom() {
+ return this.args.room?.room_type === "stage";
+ }
+
+ get isStageRoom() {
+ return this.#isStageRoom;
+ }
+
+ get speakQueueCount() {
+ return speakQueue(this.room).length;
+ }
+
+ get room() {
+ return (
+ this.voiceRooms.rooms.find((room) => room.id === this.args.room.id) ??
+ this.args.room
+ );
+ }
+
+ get connectionState() {
+ return this.voiceWebrtc.connectionStateFor(this.room.id);
+ }
+
+ get joined() {
+ return this.connectionState === "connected";
+ }
+
+ get connecting() {
+ return this.connectionState === "connecting";
+ }
+
+ get participants() {
+ return this.room.active_participants || [];
+ }
+
+ get tiles() {
+ const budget = this.capabilities.viewport.md
+ ? Infinity
+ : MOBILE_VIDEO_TILE_BUDGET;
+ const videoParticipantIds = new Set();
+
+ const spotlightParticipant = this.participants.find(
+ (participant) => participant.id === this.spotlightParticipantId
+ );
+ if (spotlightParticipant && this.#isPublishing(spotlightParticipant)) {
+ videoParticipantIds.add(spotlightParticipant.id);
+ }
+
+ for (const participant of this.participants) {
+ if (videoParticipantIds.size >= budget) {
+ break;
+ }
+ if (this.#isPublishing(participant)) {
+ videoParticipantIds.add(participant.id);
+ }
+ }
+
+ return this.participants.map((participant) => {
+ const isSelf = participant.id === this.currentUser?.id;
+ return {
+ participant,
+ isSelf,
+ showVideo: videoParticipantIds.has(participant.id),
+ spotlighted: participant.id === this.spotlightParticipantId,
+ };
+ });
+ }
+
+ #isPublishing(participant) {
+ if (participant.id === this.currentUser?.id) {
+ return !!this.voiceWebrtc.localVideoKind;
+ }
+ return participant.is_video_on || participant.is_screen_sharing;
+ }
+
+ get ringingEntries() {
+ return activeRingingEntries(this.room, this.ringingClock);
+ }
+
+ get presentationTile() {
+ return (
+ this.tiles.find((tile) => tile.spotlighted) ??
+ this.tiles.find((tile) => tile.participant.is_screen_sharing) ??
+ this.tiles.find((tile) => tile.showVideo && !tile.isSelf) ??
+ this.tiles.find((tile) => tile.showVideo) ??
+ this.tiles.find((tile) =>
+ ["moderator", "speaker"].includes(tile.participant.role)
+ ) ??
+ this.tiles[0]
+ );
+ }
+
+ get presentationRailTiles() {
+ const featuredId = this.presentationTile?.participant.id;
+ return this.tiles.filter((tile) => tile.participant.id !== featuredId);
+ }
+
+ get tiledLayout() {
+ return this.layoutMode === LAYOUT_TILED;
+ }
+
+ get presentationLayout() {
+ return this.layoutMode === LAYOUT_PRESENTATION;
+ }
+
+ @action
+ toggleSpotlight(participantId) {
+ this.spotlightParticipantId =
+ this.spotlightParticipantId === participantId ? null : participantId;
+ this.layoutMode = LAYOUT_PRESENTATION;
+ }
+
+ @action
+ setLayoutMode(layoutMode) {
+ this.spotlightParticipantId = null;
+ this.layoutMode = layoutMode;
+ }
+
+ @action
+ reconcileSpotlight() {
+ if (
+ this.spotlightParticipantId &&
+ !this.participants.some(
+ (participant) => participant.id === this.spotlightParticipantId
+ )
+ ) {
+ this.spotlightParticipantId = null;
+ }
+ }
+
+ @action
+ updateGridSize(width, height, gap) {
+ this.gridWidth = width;
+ this.gridHeight = height;
+ this.gridGap = gap;
+ }
+
+ @action
+ registerGrid(element) {
+ this.gridElement = element;
+ }
+
+ @action
+ autoJoinIfRequested() {
+ if (!this.args.autoJoin) {
+ return;
+ }
+
+ next(this, () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ // Consume the param so a refresh or back-navigation doesn't rejoin a
+ // call the user has since left.
+ this.router.transitionTo({ queryParams: { join: false } });
+
+ if (!this.joined && !this.connecting) {
+ this.joinRoom();
+ }
+ });
+ }
+
+ @action
+ watchRoom() {
+ next(this, () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.voiceWebrtc.setWatching(this.args.room.id, true);
+ });
+ }
+
+ @action
+ setGridFullscreen(isFullscreen) {
+ this.gridFullscreen = isFullscreen;
+ }
+
+ @action
+ toggleGridFullscreen() {
+ toggleFullscreen(this.gridElement);
+ }
+
+ get layoutIcon() {
+ return this.presentationLayout ? "person-chalkboard" : "table-cells";
+ }
+
+ get gridFullscreenTitle() {
+ return this.gridFullscreen
+ ? i18n("voice.video.exit_fullscreen")
+ : i18n("voice.video.fullscreen_all");
+ }
+
+ @action
+ reportTileAspect(participantId, aspect) {
+ const current = this.tileAspects.get(participantId) ?? null;
+ if (current === aspect) {
+ return;
+ }
+
+ const nextAspects = new Map(this.tileAspects);
+ if (aspect) {
+ nextAspects.set(participantId, aspect);
+ } else {
+ nextAspects.delete(participantId);
+ }
+ this.tileAspects = nextAspects;
+ }
+
+ get gridStyle() {
+ if (
+ !this.tiledLayout ||
+ !this.tiles.length ||
+ !this.gridWidth ||
+ !this.gridHeight
+ ) {
+ return null;
+ }
+
+ const aspects = [
+ ...this.tiles.map(
+ (tile) =>
+ this.tileAspects.get(tile.participant.id) ?? DEFAULT_TILE_ASPECT
+ ),
+ ...this.ringingEntries.map(() => DEFAULT_TILE_ASPECT),
+ ];
+
+ const rowHeight = bestRowHeight(
+ this.gridWidth,
+ this.gridHeight,
+ aspects,
+ this.gridGap
+ );
+
+ if (rowHeight <= 0) {
+ return null;
+ }
+
+ return trustHTML(`--voice-tile-height: ${rowHeight}px;`);
+ }
+
+ @action
+ joinRoom() {
+ if (!this.currentUser) {
+ getOwner(this).lookup("route:application").send("showLogin");
+ return;
+ }
+ this.voiceWebrtc.join(this.room);
+
+ // `?widget` asks for the call to live in the floating widget, which is a
+ // preference the join consumes, the same way `?chat` opens the chat panel.
+ if (this.args.dockOnJoin) {
+ this.voiceWebrtc.setCallWidgetHidden(false);
+ this.dockRoom();
+ }
+ }
+
+ @action
+ leaveRoom() {
+ this.voiceWebrtc.leave(this.room);
+ }
+
+ @action
+ dockRoom() {
+ // Docking keeps the call and drops the page, so the user should get their
+ // place back rather than a reset: return to where they came from, replacing
+ // the room page so going back does not land on it again.
+ //
+ // Every room page is skipped, not just the current URL: consuming `?join`
+ // leaves this room in the history under a different spelling, and returning
+ // to it would look like docking did nothing.
+ const previousURL = this.routeHistory.history.find(
+ (url) => !url.startsWith(ROOM_PATH_PREFIX)
+ );
+
+ if (previousURL) {
+ this.router.replaceWith(previousURL);
+ return;
+ }
+
+ // Nothing to return to, e.g. the room page was opened directly.
+ this.router.replaceWith(`discovery.${defaultHomepage()}`);
+ }
+
+ get chatAvailable() {
+ return this.room.chat_available;
+ }
+
+ get chatVisible() {
+ return this.chatOpen && this.joined && this.chatAvailable;
+ }
+
+ get chatToggleTitle() {
+ return this.chatOpen ? i18n("voice.chat.close") : i18n("voice.chat.open");
+ }
+
+ @action
+ toggleChat() {
+ this.setChatOpen(!this.chatOpen);
+ }
+
+ @action
+ closeChat() {
+ this.setChatOpen(false);
+ }
+
+ setChatOpen(open) {
+ cancel(this.#chatCloseFallback);
+ if (open) {
+ this.chatClosing = false;
+ } else if (this.chatVisible) {
+ // Keep the panel mounted while its exit animation plays; unmounting is
+ // deferred to chatAnimationEnded. If the animation never runs (a theme
+ // or user stylesheet can disable it outright), don't leave the panel
+ // mounted forever.
+ this.chatClosing = true;
+ this.#chatCloseFallback = discourseLater(() => {
+ this.chatClosing = false;
+ }, 500);
+ }
+ this.chatOpen = open;
+ this.router.transitionTo({ queryParams: { chat: open } });
+ }
+
+ get chatRendered() {
+ return this.chatVisible || this.chatClosing;
+ }
+
+ @action
+ chatAnimationEnded(event) {
+ if (
+ event.target === event.currentTarget &&
+ event.animationName.endsWith("-out")
+ ) {
+ cancel(this.#chatCloseFallback);
+ this.chatClosing = false;
+ }
+ }
+
+ @action
+ openRoomInfo(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceRoomInfoModal, { model: { room: this.room } });
+ }
+
+ @action
+ openInviteModal(closeMenu) {
+ closeMenu?.();
+ this.modal.show(VoiceInviteUsersModal, { model: { room: this.room } });
+ }
+
+ @action
+ dockAndClose(closeMenu) {
+ closeMenu?.();
+ this.dockRoom();
+ }
+
+ @action
+ toggleChatFromMenu(closeMenu) {
+ closeMenu?.();
+ this.toggleChat();
+ }
+
+ get transcriptAvailable() {
+ return this.voiceWebrtc.subtitlesAvailable;
+ }
+
+ get transcribing() {
+ return this.voiceWebrtc.isTranscribingRoom(this.room.id);
+ }
+
+ get transcriptToggleTitle() {
+ return this.transcribing
+ ? i18n("voice.transcript.stop")
+ : i18n("voice.transcript.start");
+ }
+
+ @action
+ toggleTranscriptFromMenu(closeMenu) {
+ closeMenu?.();
+ this.voiceWebrtc.toggleTranscriptRecording(this.room.id);
+ }
+
+ get transcriptDraftable() {
+ return (
+ this.voiceWebrtc.transcriptEntries.length > 0 &&
+ Number(this.voiceWebrtc.transcriptEntriesRoomId) === Number(this.room.id)
+ );
+ }
+
+ get transcriptDraftLabel() {
+ return this.transcribing
+ ? i18n("voice.transcript.stop_and_open")
+ : i18n("voice.transcript.draft_topic");
+ }
+
+ @action
+ draftTranscriptTopic(closeMenu) {
+ closeMenu?.();
+ this.voiceWebrtc.openTranscriptDraft();
+ }
+
+ // Opened programmatically (not a nested <DMenu>) so the trigger stays a
+ // normal full-width menu item, matching core's channel context menu.
+ #openSubmenu(event, parentMenu, items, onSelect) {
+ // Anchor to the row button, not the clicked icon/label, so the submenu
+ // opens flush to the row's right edge.
+ const anchor = event.target.closest(".btn") ?? event.target;
+ this.menu.show(anchor, {
+ identifier: SUBMENU,
+ groupIdentifier: SUBMENU,
+ component: VoiceCallSubmenu,
+ placement: "right-start",
+ offset: { mainAxis: 8, crossAxis: -5 },
+ modalForMobile: true,
+ data: {
+ items,
+ onSelect: (id) => {
+ onSelect(id);
+ this.menu.close(parentMenu);
+ },
+ },
+ });
+ }
+
+ @action
+ openLayoutMenu(_actionArg, event) {
+ this.#openSubmenu(
+ event,
+ ROOM_MENU,
+ [
+ {
+ id: LAYOUT_PRESENTATION,
+ label: i18n("voice.video.layout_presentation"),
+ icon: "person-chalkboard",
+ selected: this.presentationLayout,
+ },
+ {
+ id: LAYOUT_TILED,
+ label: i18n("voice.video.layout_tiled"),
+ icon: "table-cells",
+ selected: this.tiledLayout,
+ },
+ ],
+ this.setLayoutMode
+ );
+ }
+
+ <template>
+ <section
+ class={{dConcatClass
+ "voice-room-page"
+ (if this.chatVisible "--chat-open")
+ (if this.presentationLayout "--presentation")
+ (if this.tiledLayout "--tiled")
+ }}
+ {{didInsert this.watchRoom}}
+ {{didInsert this.autoJoinIfRequested}}
+ {{didUpdate this.reconcileSpotlight this.participants}}
+ >
+ <div class="voice-room-page__body">
+ <div class="voice-room-page__main">
+ <header class="voice-room-page__header">
+ <div class="voice-room-page__title-row">
+ <h1 class="voice-room-page__title">{{this.room.name}}</h1>
+ <VoiceRecordingBadge @room={{this.room}} />
+ <VoiceTranscriptBadge @room={{this.room}} />
+ </div>
+ {{#if this.room.description_excerpt}}
+ <p class="voice-room-page__description">
+ {{this.room.description_excerpt}}
+ </p>
+ {{/if}}
+ </header>
+
+ <div class="voice-room-page__stage">
+ {{#if this.tiles.length}}
+ {{#if this.presentationLayout}}
+ <div class="voice-room-page__presentation">
+ <div class="voice-room-page__presentation-main">
+ <VoiceVideoTile
+ @room={{this.room}}
+ @participant={{this.presentationTile.participant}}
+ @isSelf={{this.presentationTile.isSelf}}
+ @showVideo={{this.presentationTile.showVideo}}
+ @onSpotlight={{this.toggleSpotlight}}
+ @spotlighted={{this.presentationTile.spotlighted}}
+ @onAspect={{this.reportTileAspect}}
+ />
+ </div>
+
+ {{#if
+ (or
+ this.presentationRailTiles.length
+ this.ringingEntries.length
+ )
+ }}
+ <div class="voice-room-page__presentation-rail">
+ {{#each
+ this.presentationRailTiles key="participant.id"
+ as |tile|
+ }}
+ <VoiceVideoTile
+ @room={{this.room}}
+ @participant={{tile.participant}}
+ @isSelf={{tile.isSelf}}
+ @showVideo={{tile.showVideo}}
+ @onSpotlight={{this.toggleSpotlight}}
+ @spotlighted={{tile.spotlighted}}
+ @onAspect={{this.reportTileAspect}}
+ />
+ {{/each}}
+ {{#each this.ringingEntries key="user.id" as |entry|}}
+ <VoiceRingingTile @user={{entry.user}} />
+ {{/each}}
+ </div>
+ {{/if}}
+ </div>
+ {{else}}
+ <div
+ class="voice-room-page__grid"
+ style={{this.gridStyle}}
+ {{didInsert this.registerGrid}}
+ {{this.trackGridSize this.updateGridSize}}
+ {{this.trackFullscreen this.setGridFullscreen}}
+ >
+ <button
+ type="button"
+ class="btn btn-icon no-text voice-room-page__fullscreen"
+ title={{this.gridFullscreenTitle}}
+ aria-label={{this.gridFullscreenTitle}}
+ {{on "click" this.toggleGridFullscreen}}
+ >
+ {{dIcon (if this.gridFullscreen "compress" "expand")}}
+ </button>
+
+ {{#each this.tiles key="participant.id" as |tile|}}
+ <VoiceVideoTile
+ @room={{this.room}}
+ @participant={{tile.participant}}
+ @isSelf={{tile.isSelf}}
+ @showVideo={{tile.showVideo}}
+ @onSpotlight={{this.toggleSpotlight}}
+ @spotlighted={{tile.spotlighted}}
+ @onAspect={{this.reportTileAspect}}
+ />
+ {{/each}}
+ {{#each this.ringingEntries key="user.id" as |entry|}}
+ <VoiceRingingTile @user={{entry.user}} />
+ {{/each}}
+ </div>
+ {{/if}}
+ {{else}}
+ <div class="voice-room-page__empty">
+ {{i18n "voice.room_page.empty"}}
+ </div>
+ {{/if}}
+ {{#if this.joined}}
+ <VoiceCaptionOverlay @room={{this.room}} />
+ {{/if}}
+
+ <footer class="voice-room-page__controls">
+ {{#if this.joined}}
+ <VoiceCallControls @room={{this.room}} />
+ {{#if this.isStageRoom}}
+ <DMenu
+ @identifier="voice-speak-queue-menu"
+ @title={{i18n "voice.stage.queue_title"}}
+ @ariaLabel={{i18n "voice.stage.queue_title"}}
+ @placement="top-end"
+ @modalForMobile={{true}}
+ @triggerClass="btn-default voice-speak-queue-trigger"
+ >
+ <:trigger>
+ {{dIcon "list-ol"}}
+ {{#if this.speakQueueCount}}
+ <span
+ class="voice-speak-queue-trigger__count"
+ >{{this.speakQueueCount}}</span>
+ {{/if}}
+ </:trigger>
+ <:content>
+ <VoiceSpeakQueue @room={{this.room}} />
+ </:content>
+ </DMenu>
+ {{/if}}
+ <DMenu
+ @identifier="voice-room-menu"
+ @icon="ellipsis-vertical"
+ @title={{i18n "voice.room.more"}}
+ @ariaLabel={{i18n "voice.room.more"}}
+ @placement="top-end"
+ @modalForMobile={{true}}
+ @triggerClass="btn-default"
+ >
+ <:content as |roomMenu|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.chatAvailable}}
+ <dropdown.item>
+ <DButton
+ @action={{fn
+ this.toggleChatFromMenu
+ roomMenu.close
+ }}
+ @icon={{if
+ this.chatVisible
+ "comment-slash"
+ "far-comment"
+ }}
+ @translatedLabel={{this.chatToggleTitle}}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{this.openLayoutMenu}}
+ @forwardEvent={{true}}
+ @icon={{this.layoutIcon}}
+ @label="voice.room.layout"
+ @suffixIcon="angle-right"
+ class="btn-transparent voice-room-page__layout-trigger"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.dockAndClose roomMenu.close}}
+ @icon="compress"
+ @label="voice.room.widget_mode"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{#if this.room.can_invite}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openInviteModal roomMenu.close}}
+ @icon="user-plus"
+ @label="voice.invite.menu"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if this.transcriptAvailable}}
+ <dropdown.item>
+ <DButton
+ @action={{fn
+ this.toggleTranscriptFromMenu
+ roomMenu.close
+ }}
+ @icon={{if
+ this.transcribing
+ "stop"
+ "closed-captioning"
+ }}
+ @translatedLabel={{this.transcriptToggleTitle}}
+ class={{dConcatClass
+ "btn-transparent voice-room-page__transcript-toggle"
+ (if this.transcribing "--recording")
+ }}
+ />
+ </dropdown.item>
+ {{#if this.transcriptDraftable}}
+ <dropdown.item>
+ <DButton
+ @action={{fn
+ this.draftTranscriptTopic
+ roomMenu.close
+ }}
+ @icon="far-file-lines"
+ @translatedLabel={{this.transcriptDraftLabel}}
+ class="btn-transparent voice-room-page__transcript-draft"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openRoomInfo roomMenu.close}}
+ @icon="circle-info"
+ @label="voice.room.info"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ <DButton
+ @action={{this.leaveRoom}}
+ @icon="phone-slash"
+ @label="voice.room.leave"
+ class="btn-danger voice-room-page__leave"
+ />
+ {{else}}
+ <DButton
+ @action={{this.joinRoom}}
+ @icon="phone"
+ @label="voice.room.join"
+ @disabled={{this.connecting}}
+ @isLoading={{this.connecting}}
+ class="btn-primary voice-room-page__join"
+ />
+ {{/if}}
+ </footer>
+ </div>
+ </div>
+
+ {{#if this.chatRendered}}
+ <aside
+ class={{dConcatClass
+ "voice-room-page__sidebar"
+ (if this.chatClosing "--closing")
+ }}
+ {{on "animationend" this.chatAnimationEnded}}
+ >
+ <VoiceChatPanel @room={{this.room}} @onClose={{this.closeChat}} />
+ </aside>
+ {{/if}}
+ </div>
+ </section>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/speak-queue.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/speak-queue.gjs
new file mode 100644
index 00000000000..a8820cc97ee
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/speak-queue.gjs
@@ -0,0 +1,132 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import DButton from "discourse/ui-kit/d-button";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import { i18n } from "discourse-i18n";
+import { speakQueue } from "../../lib/voice/speak-queue";
+
+// The ordered request-to-speak queue of a stage room. Everyone sees the
+// order; moderators get approve/dismiss controls, a queued viewer can lower
+// their own hand.
+export default class VoiceSpeakQueue extends Component {
+ @service currentUser;
+ @service voiceWebrtc;
+
+ get room() {
+ return this.args.room;
+ }
+
+ get canManage() {
+ return this.room?.can_manage;
+ }
+
+ get entries() {
+ return speakQueue(this.room).map((participant, index) => ({
+ participant,
+ position: index + 1,
+ isSelf: Number(participant.id) === this.currentUser?.id,
+ name: prioritizeNameInUx(participant.name)
+ ? participant.name
+ : participant.username,
+ }));
+ }
+
+ @action
+ async approve(participant) {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/memberships`, {
+ type: "POST",
+ data: { user_id: participant.id, role: "speaker" },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async dismiss(participant) {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/request_to_speak`, {
+ type: "DELETE",
+ data: { user_id: participant.id },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async lowerHand() {
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/request_to_speak`, {
+ type: "DELETE",
+ data: {
+ participant_session_id: this.voiceWebrtc.participantSessionIdFor(
+ this.room.id
+ ),
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <div class="voice-speak-queue">
+ <h3 class="voice-speak-queue__title">
+ {{i18n "voice.stage.queue_title"}}
+ </h3>
+ {{#if this.entries.length}}
+ <ul class="voice-speak-queue__list">
+ {{#each this.entries key="participant.id" as |entry|}}
+ <li
+ class={{dConcatClass
+ "voice-speak-queue__item"
+ (if entry.isSelf "--self")
+ }}
+ >
+ <span
+ class="voice-speak-queue__position"
+ >{{entry.position}}</span>
+ {{dAvatar entry.participant imageSize="small"}}
+ <span class="voice-speak-queue__name">{{entry.name}}</span>
+ <span class="voice-speak-queue__actions">
+ {{#if this.canManage}}
+ <DButton
+ @action={{fn this.approve entry.participant}}
+ @icon="check"
+ @title="voice.stage.approve_request"
+ class="btn-transparent voice-speak-queue__approve"
+ />
+ <DButton
+ @action={{fn this.dismiss entry.participant}}
+ @icon="xmark"
+ @title="voice.stage.dismiss_request"
+ class="btn-transparent voice-speak-queue__dismiss"
+ />
+ {{else if entry.isSelf}}
+ <DButton
+ @action={{this.lowerHand}}
+ @icon="xmark"
+ @title="voice.stage.lower_hand"
+ class="btn-transparent voice-speak-queue__lower"
+ />
+ {{/if}}
+ </span>
+ </li>
+ {{/each}}
+ </ul>
+ {{else}}
+ <div class="voice-speak-queue__empty">
+ {{i18n "voice.stage.queue_empty"}}
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/transcript-badge.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/transcript-badge.gjs
new file mode 100644
index 00000000000..963190857f6
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/transcript-badge.gjs
@@ -0,0 +1,83 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+// The transcript consent signal: a quiet pill rendered wherever a room's
+// call is shown, so nobody can be transcribed without a way of noticing.
+// Deliberately calmer than the recording badge — the transcript never
+// leaves the recorder's browser.
+export default class VoiceTranscriptBadge extends Component {
+ @service currentUser;
+ @service voiceWebrtc;
+
+ get selfTranscribing() {
+ return this.voiceWebrtc.isTranscribingRoom(this.args.room.id);
+ }
+
+ get otherTranscribers() {
+ return (this.args.room.active_participants || [])
+ .filter(
+ (participant) =>
+ participant?.is_transcribing &&
+ Number(participant.id) !== this.currentUser?.id
+ )
+ .map((participant) => participant.username);
+ }
+
+ get visible() {
+ return this.selfTranscribing || this.otherTranscribers.length > 0;
+ }
+
+ get transcriberNames() {
+ const names = this.otherTranscribers;
+ if (this.selfTranscribing) {
+ names.unshift(i18n("voice.transcript.transcriber_you"));
+ }
+ return names;
+ }
+
+ get tooltip() {
+ const names = this.transcriberNames;
+ if (this.selfTranscribing && names.length === 1) {
+ return i18n("voice.transcript.indicator_tooltip_self");
+ }
+ return i18n("voice.transcript.indicator_tooltip", {
+ count: names.length,
+ usernames: names.join(", "),
+ });
+ }
+
+ // While the model is still loading/downloading there would otherwise be no
+ // feedback at all when captions are off, so the badge doubles as progress.
+ get label() {
+ if (this.selfTranscribing && this.voiceWebrtc.subtitlesLoading) {
+ const percent = this.voiceWebrtc.subtitlesProgress;
+ return percent !== null
+ ? i18n("voice.subtitles.downloading", { percent })
+ : i18n("voice.subtitles.loading");
+ }
+ return i18n("voice.transcript.indicator");
+ }
+
+ <template>
+ {{#if this.visible}}
+ <DTooltip
+ @identifier="voice-transcript-badge"
+ @placement="bottom"
+ class="voice-transcript-badge"
+ >
+ <:trigger>
+ {{dIcon "closed-captioning"}}
+ <span class="voice-transcript-badge__label">
+ {{this.label}}
+ </span>
+ </:trigger>
+ <:content>
+ {{this.tooltip}}
+ </:content>
+ </DTooltip>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs
new file mode 100644
index 00000000000..d07a752eb0e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/video-tile.gjs
@@ -0,0 +1,229 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import { avatarUrl } from "discourse/lib/avatar-utils";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ toggleTileFullscreen,
+ trackFullscreen,
+} from "../../lib/voice/fullscreen";
+import {
+ DEFAULT_TILE_ASPECT,
+ trackVideoAspect,
+} from "../../lib/voice/video-grid-layout";
+import virtualElementFromEvent from "../../lib/voice/virtual-element-from-event";
+import VoiceParticipantSidebarContextMenu from "../voice-participant-sidebar-context-menu";
+
+export default class VoiceVideoTile extends Component {
+ @service menu;
+ @service voiceRooms;
+ @service voiceWebrtc;
+
+ @tracked aspect = null;
+ @tracked isFullscreen = false;
+
+ trackVideoAspect = trackVideoAspect;
+ trackFullscreen = trackFullscreen;
+
+ get participant() {
+ return this.args.participant;
+ }
+
+ get isSpeaking() {
+ return this.voiceRooms.isParticipantSpeaking(
+ this.args.room?.id,
+ this.participant.id
+ );
+ }
+
+ get tileStyle() {
+ return trustHTML(`aspect-ratio: ${this.aspect ?? DEFAULT_TILE_ASPECT};`);
+ }
+
+ @action
+ handleAspect(aspect) {
+ this.aspect = aspect;
+ this.args.onAspect?.(this.participant.id, aspect);
+ }
+
+ @action
+ setFullscreen(isFullscreen) {
+ this.isFullscreen = isFullscreen;
+ }
+
+ @action
+ toggleFullscreen(event) {
+ toggleTileFullscreen(event.currentTarget.closest(".voice-video-tile"));
+ }
+
+ // The menu only offers audio controls for a call the user is in, so
+ // page visitors who haven't joined the room don't get one.
+ get canShowMenu() {
+ return (
+ this.voiceWebrtc.connectionStateFor(this.args.room?.id) === "connected"
+ );
+ }
+
+ @action
+ openContextMenu(event) {
+ if (!this.canShowMenu) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ this.#showParticipantMenu(virtualElementFromEvent(event), "bottom-start");
+ }
+
+ @action
+ openTileMenu(event) {
+ event.stopPropagation();
+ this.#showParticipantMenu(event.currentTarget, "top-end");
+ }
+
+ #showParticipantMenu(anchor, placement) {
+ this.menu.show(anchor, {
+ identifier: "voice-participant-menu",
+ component: VoiceParticipantSidebarContextMenu,
+ placement,
+ modalForMobile: true,
+ data: {
+ room: this.args.room,
+ participant: this.participant,
+ canManageRoom: this.args.room?.can_manage,
+ isCurrentUser: this.args.isSelf,
+ isSpotlighted: this.args.spotlighted,
+ onSpotlight: this.args.onSpotlight,
+ },
+ });
+ }
+
+ get fullscreenTitle() {
+ return this.isFullscreen
+ ? i18n("voice.video.exit_fullscreen")
+ : i18n("voice.video.fullscreen");
+ }
+
+ get stream() {
+ if (this.args.isSelf) {
+ return this.voiceWebrtc.localVideoStream;
+ }
+
+ return this.voiceWebrtc.remoteStreamFor(
+ this.args.room.id,
+ this.participant.id
+ );
+ }
+
+ get publishingKind() {
+ if (this.args.isSelf) {
+ return this.voiceWebrtc.localVideoKind;
+ }
+
+ if (this.participant.is_screen_sharing) {
+ return "screen";
+ }
+
+ if (this.participant.is_video_on) {
+ return "camera";
+ }
+
+ return null;
+ }
+
+ get showVideo() {
+ return this.args.showVideo && !!this.publishingKind && !!this.stream;
+ }
+
+ get avatarSrc() {
+ return avatarUrl(this.participant.avatar_template, "huge");
+ }
+
+ get displayName() {
+ return prioritizeNameInUx(this.participant.name)
+ ? this.participant.name
+ : this.participant.username;
+ }
+
+ <template>
+ <div
+ class={{dConcatClass
+ "voice-video-tile"
+ (if this.showVideo "--video" "--avatar")
+ (if (eq this.publishingKind "screen") "--screen")
+ (if @isSelf "--self")
+ (if this.isSpeaking "--speaking")
+ }}
+ data-user-id={{this.participant.id}}
+ style={{this.tileStyle}}
+ {{this.trackFullscreen this.setFullscreen}}
+ {{on "contextmenu" this.openContextMenu}}
+ >
+ {{#if this.showVideo}}
+ <video
+ class="voice-video-tile__video"
+ {{didInsert (fn this.voiceWebrtc.attachVideoStream this.stream)}}
+ {{didUpdate
+ (fn this.voiceWebrtc.attachVideoStream this.stream)
+ this.stream
+ }}
+ {{this.trackVideoAspect this.handleAspect}}
+ muted
+ autoplay
+ playsinline
+ ></video>
+ {{else}}
+ <div class="voice-video-tile__avatar">
+ <img src={{this.avatarSrc}} alt={{this.displayName}} />
+ </div>
+ {{/if}}
+
+ <div class="voice-video-tile__info">
+ <span class="voice-video-tile__name">{{this.displayName}}</span>
+ {{#if this.participant.is_muted}}
+ {{dIcon "microphone-slash"}}
+ {{/if}}
+ {{#if this.participant.is_deafened}}
+ {{dIcon "volume-xmark"}}
+ {{/if}}
+ {{#if (eq this.publishingKind "screen")}}
+ {{dIcon "display"}}
+ {{/if}}
+ </div>
+
+ {{#if this.canShowMenu}}
+ <button
+ type="button"
+ class="btn btn-icon no-text voice-video-tile__menu"
+ title={{i18n "voice.participant.menu_title"}}
+ aria-label={{i18n "voice.participant.menu_title"}}
+ {{on "click" this.openTileMenu}}
+ >
+ {{dIcon "ellipsis-vertical"}}
+ </button>
+ {{/if}}
+
+ {{#if this.showVideo}}
+ <button
+ type="button"
+ class="btn btn-icon no-text voice-video-tile__fullscreen"
+ title={{this.fullscreenTitle}}
+ aria-label={{this.fullscreenTitle}}
+ {{on "click" this.toggleFullscreen}}
+ >
+ {{dIcon (if this.isFullscreen "compress" "expand")}}
+ </button>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/components/voice/voice-canvas.gjs b/plugins/voice/assets/javascripts/discourse/components/voice/voice-canvas.gjs
new file mode 100644
index 00000000000..8a24602fdd1
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/components/voice/voice-canvas.gjs
@@ -0,0 +1,56 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+
+export default class VoiceVoiceCanvas extends Component {
+ @service voiceWebrtc;
+
+ get localStream() {
+ return this.voiceWebrtc.localStream;
+ }
+
+ get remoteStreams() {
+ return this.voiceWebrtc.remoteStreams;
+ }
+
+ get remoteScreenAudioStreams() {
+ return this.voiceWebrtc.remoteScreenAudioStreams;
+ }
+
+ <template>
+ <section class="voice-voice-canvas">
+ {{#if this.localStream}}
+ <audio
+ {{didInsert (fn this.voiceWebrtc.attachStream this.localStream)}}
+ {{didUpdate
+ (fn this.voiceWebrtc.attachStream this.localStream)
+ this.localStream
+ }}
+ autoplay
+ muted
+ playsinline
+ />
+ {{/if}}
+
+ {{#each this.remoteStreams key="id" as |stream|}}
+ <audio
+ {{didInsert (fn this.voiceWebrtc.attachStream stream)}}
+ {{didUpdate (fn this.voiceWebrtc.attachStream stream) stream}}
+ autoplay
+ playsinline
+ />
+ {{/each}}
+
+ {{#each this.remoteScreenAudioStreams key="id" as |stream|}}
+ <audio
+ {{didInsert (fn this.voiceWebrtc.attachStream stream)}}
+ {{didUpdate (fn this.voiceWebrtc.attachStream stream) stream}}
+ autoplay
+ playsinline
+ />
+ {{/each}}
+ </section>
+ </template>
+}
diff --git a/plugins/voice/assets/javascripts/discourse/connectors/user-card-below-message-button/voice-call-button.gjs b/plugins/voice/assets/javascripts/discourse/connectors/user-card-below-message-button/voice-call-button.gjs
new file mode 100644
index 00000000000..3db99d8f918
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/connectors/user-card-below-message-button/voice-call-button.gjs
@@ -0,0 +1,11 @@
+import VoiceCallButton from "../../components/voice/call-button";
+
+const VoiceCardCallButton = <template>
+ {{#if @outletArgs.user.voice_can_call}}
+ <li class="user-card-below-message-button voice-call-button">
+ <VoiceCallButton @user={{@outletArgs.user}} />
+ </li>
+ {{/if}}
+</template>;
+
+export default VoiceCardCallButton;
diff --git a/plugins/voice/assets/javascripts/discourse/connectors/user-profile-controls/voice-call-button.gjs b/plugins/voice/assets/javascripts/discourse/connectors/user-profile-controls/voice-call-button.gjs
new file mode 100644
index 00000000000..32f943373d7
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/connectors/user-profile-controls/voice-call-button.gjs
@@ -0,0 +1,11 @@
+import VoiceCallButton from "../../components/voice/call-button";
+
+const VoiceProfileCallButton = <template>
+ {{#if @outletArgs.model.voice_can_call}}
+ <li class="voice-call-button">
+ <VoiceCallButton @user={{@outletArgs.model}} />
+ </li>
+ {{/if}}
+</template>;
+
+export default VoiceProfileCallButton;
diff --git a/plugins/voice/assets/javascripts/discourse/controllers/voice-room.js b/plugins/voice/assets/javascripts/discourse/controllers/voice-room.js
new file mode 100644
index 00000000000..97a043074e4
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/controllers/voice-room.js
@@ -0,0 +1,15 @@
+import Controller from "@ember/controller";
+import urlFlagSet from "discourse/plugins/voice/discourse/lib/voice/url-flag";
+
+export default class VoiceRoomController extends Controller {
+ queryParams = ["chat", "join", "widget"];
+ chat = false;
+ join = false;
+ // Typed as a string rather than a boolean so that a valueless `?widget`
+ // survives deserialization as "" instead of being coerced to false.
+ widget = null;
+
+ get dockOnJoin() {
+ return urlFlagSet(this.widget);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-admin-plugin-configuration-nav.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-admin-plugin-configuration-nav.js
new file mode 100644
index 00000000000..e59d05b607d
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-admin-plugin-configuration-nav.js
@@ -0,0 +1,32 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+const PLUGIN_ID = "voice";
+
+export default {
+ name: "voice-admin-plugin-configuration-nav",
+
+ initialize(container) {
+ const currentUser = container.lookup("service:current-user");
+ if (!currentUser?.admin) {
+ return;
+ }
+
+ withPluginApi((api) => {
+ api.setAdminPluginIcon(PLUGIN_ID, "microphone-lines");
+ api.addAdminPluginConfigurationNav(PLUGIN_ID, [
+ {
+ label: "voice.admin.dashboard_title",
+ route: "adminPlugins.show.voice-dashboard",
+ },
+ {
+ label: "voice.admin.rooms_title",
+ route: "adminPlugins.show.voice-rooms",
+ },
+ {
+ label: "voice.admin.recordings_title",
+ route: "adminPlugins.show.voice-recordings",
+ },
+ ]);
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-call-ring.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-call-ring.js
new file mode 100644
index 00000000000..7e403e9d79a
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-call-ring.js
@@ -0,0 +1,9 @@
+import { apiInitializer } from "discourse/lib/api";
+
+export default apiInitializer((api) => {
+ // Rings arrive over MessageBus whether or not any voice UI is on screen,
+ // so the calls service starts listening as soon as the app boots.
+ if (api.getCurrentUser()) {
+ api.container.lookup("service:voice-calls").listen();
+ }
+});
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-chat-thread-navbar.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-chat-thread-navbar.js
new file mode 100644
index 00000000000..737e5fe3fa9
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-chat-thread-navbar.js
@@ -0,0 +1,6 @@
+import { apiInitializer } from "discourse/lib/api";
+import VoiceBackToVoiceRoomButton from "discourse/plugins/voice/discourse/components/voice-back-to-voice-room-button";
+
+export default apiInitializer((api) => {
+ api.renderInOutlet("chat-thread-navbar-actions", VoiceBackToVoiceRoomButton);
+});
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-defer-refresh-in-call.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-defer-refresh-in-call.js
new file mode 100644
index 00000000000..21e54e52d91
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-defer-refresh-in-call.js
@@ -0,0 +1,14 @@
+import { apiInitializer } from "discourse/lib/api";
+
+export default apiInitializer((api) => {
+ // When a new client version is deployed, core turns the next navigation
+ // into a full page load. That would drop the user from their voice room,
+ // so hold the refresh until the call is over.
+ api.registerValueTransformer(
+ "full-page-refresh-on-navigation",
+ ({ value }) => {
+ const webrtc = api.container.lookup("service:voice-webrtc");
+ return webrtc?.hasActiveRoom ? false : value;
+ }
+ );
+});
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-hashtag-type.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-hashtag-type.js
new file mode 100644
index 00000000000..5789094b737
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-hashtag-type.js
@@ -0,0 +1,13 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import RoomHashtagType from "../lib/hashtag-types/room";
+
+export default {
+ name: "voice-hashtag-type",
+ before: "hashtag-css-generator",
+
+ initialize(owner) {
+ withPluginApi((api) => {
+ api.registerHashtagType("room", new RoomHashtagType(owner));
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-notifications.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-notifications.js
new file mode 100644
index 00000000000..2d75fe96df0
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-notifications.js
@@ -0,0 +1,56 @@
+import getURL from "discourse/lib/get-url";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { i18n } from "discourse-i18n";
+
+export default {
+ name: "voice-notifications",
+
+ initialize() {
+ withPluginApi((api) => {
+ api.registerNotificationTypeRenderer(
+ "voice_invitation",
+ (NotificationTypeBase) => {
+ return class extends NotificationTypeBase {
+ // An invitation into an ephemeral room is a call.
+ get isCall() {
+ return !!this.notification.data.call;
+ }
+
+ get linkTitle() {
+ return i18n(
+ this.isCall
+ ? "notifications.titles.voice_call"
+ : "notifications.titles.voice_invitation"
+ );
+ }
+
+ get icon() {
+ return this.isCall ? "phone" : "microphone-lines";
+ }
+
+ get linkHref() {
+ const data = this.notification.data;
+ // Carries the inviter so joining from the notification credits
+ // them, the same as a shared invite link.
+ return getURL(
+ `/voice/r/${data.room_slug}/invited-by/${encodeURIComponent(
+ data.display_username.toLowerCase()
+ )}`
+ );
+ }
+
+ get description() {
+ if (this.isCall) {
+ return i18n("notifications.voice_call");
+ }
+
+ return i18n("notifications.voice_invitation", {
+ room_name: this.notification.data.room_name,
+ });
+ }
+ };
+ }
+ );
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js
new file mode 100644
index 00000000000..a1d2137e6bd
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-sidebar.js
@@ -0,0 +1,828 @@
+import { later, next } from "@ember/runloop";
+import noop from "discourse/helpers/noop";
+import { avatarUrl } from "discourse/lib/avatar-utils";
+import getURL from "discourse/lib/get-url";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import { i18n } from "discourse-i18n";
+import VoiceCreateRoomModal from "discourse/plugins/voice/discourse/components/modal/voice-create-room";
+import VoiceParticipantSidebarContextMenu from "discourse/plugins/voice/discourse/components/voice-participant-sidebar-context-menu";
+import VoiceParticipantSidebarSuffix from "discourse/plugins/voice/discourse/components/voice-participant-sidebar-suffix";
+import VoiceRoomSidebarContextMenu from "discourse/plugins/voice/discourse/components/voice-room-sidebar-context-menu";
+import buildAnonRoomsSection from "../lib/voice/anon-rooms-section";
+import { humanKeyName } from "../lib/voice/ptt-utils";
+import roomIcon, { roomBadge } from "../lib/voice/room-icon";
+import virtualElementFromEvent from "../lib/voice/virtual-element-from-event";
+
+const LINK_NAME_PREFIX = "voice-room-";
+const CHAT_PANEL = "chat";
+let sidebarClickHandler;
+let sidebarContextMenuHandler;
+
+export default {
+ name: "voice-sidebar",
+ initialize(owner) {
+ withPluginApi((api) => {
+ const currentUser = api.getCurrentUser();
+ const siteSettings = owner.lookup("service:site-settings");
+ const site = owner.lookup("service:site");
+
+ if (!siteSettings.voice_enabled) {
+ return;
+ }
+
+ // Anonymous visitors only see the sidebar when Voice is open to
+ // everyone. They can browse public rooms but are sent to log in on click.
+ if (!currentUser && !site.voice_public_access) {
+ return;
+ }
+
+ const roomsService = owner.lookup("service:voice-rooms");
+
+ if (!currentUser) {
+ // API sections render after Discourse's normal navigation sections,
+ // matching the location of the logged-in rooms section.
+ api.addSidebarSection(buildAnonRoomsSection(roomsService));
+
+ if (sidebarClickHandler) {
+ document.removeEventListener("click", sidebarClickHandler);
+ }
+
+ sidebarClickHandler = (event) => {
+ const anchor =
+ event
+ .composedPath?.()
+ ?.find?.(
+ (node) =>
+ node instanceof HTMLElement &&
+ node.matches?.(
+ ".sidebar-section-link[data-link-name^='voice-']"
+ )
+ ) ||
+ event.target?.closest?.(
+ ".sidebar-section-link[data-link-name^='voice-']"
+ );
+
+ if (!anchor) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ owner.lookup("route:application").send("showLogin");
+ };
+
+ document.addEventListener("click", sidebarClickHandler);
+ return;
+ }
+
+ const voiceWebrtc = owner.lookup("service:voice-webrtc");
+ const routerService = owner.lookup("service:router");
+ const menuService = owner.lookup("service:menu");
+ const modalService = owner.lookup("service:modal");
+ const capabilities = owner.lookup("service:capabilities");
+ const sidebarState = owner.lookup("service:sidebar-state");
+
+ const buildRoomsSection =
+ ({ sectionName, chatPanel } = {}) =>
+ (BaseSection, BaseLink) => {
+ const RoomsLink = class extends BaseLink {
+ constructor({ room, webrtcService, user, menu }) {
+ super(...arguments);
+ this.room = room;
+ this.voiceWebrtc = webrtcService;
+ this.currentUser = user;
+ this.menuService = menu;
+ }
+
+ get hoverType() {
+ return "icon";
+ }
+
+ get hoverValue() {
+ if (!this.currentUser || capabilities.isIpadOS) {
+ return null;
+ }
+ return "ellipsis-vertical";
+ }
+
+ get hoverTitle() {
+ return i18n("voice.room.menu_title");
+ }
+
+ get hoverAction() {
+ if (!this.currentUser || capabilities.isIpadOS) {
+ return noop;
+ }
+
+ return (event, onMenuClose) => {
+ event.stopPropagation();
+ event.preventDefault();
+
+ const anchor =
+ event.target.closest(".sidebar-section-link") || event.target;
+
+ this.menuService.show(anchor, {
+ identifier: "voice-room-menu",
+ component: VoiceRoomSidebarContextMenu,
+ placement: "right",
+ data: { room: this.room },
+ onClose: onMenuClose,
+ });
+ };
+ }
+
+ get name() {
+ return `voice-room-${this.room.id}`;
+ }
+
+ get classNames() {
+ const classes = ["voice-sidebar-link"];
+ const state = this.voiceWebrtc.connectionStateFor(this.room.id);
+
+ if (state === "connected") {
+ classes.push("sidebar-section-link--active");
+ } else if (state === "connecting") {
+ classes.push("voice-sidebar-link--connecting");
+ }
+
+ return classes.join(" ");
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get title() {
+ const state = this.voiceWebrtc.connectionStateFor(this.room.id);
+
+ if (state === "connecting") {
+ return i18n("voice.room.connecting");
+ }
+
+ if (state === "connected") {
+ return i18n("voice.room.open_page");
+ }
+
+ return (
+ this.room.description_excerpt ||
+ this.room.name ||
+ i18n("voice.room.join")
+ );
+ }
+
+ get text() {
+ return this.room.name;
+ }
+
+ get prefixType() {
+ return "icon";
+ }
+
+ get prefixValue() {
+ return roomIcon(this.room);
+ }
+
+ get prefixBadge() {
+ return roomBadge(this.room);
+ }
+
+ get #hasActiveVideo() {
+ return (this.room.active_participants || []).some(
+ (participant) =>
+ participant?.is_video_on || participant?.is_screen_sharing
+ );
+ }
+
+ get suffixType() {
+ if (
+ this.voiceWebrtc.connectionStateFor(this.room.id) ===
+ "connecting" ||
+ this.#hasActiveVideo
+ ) {
+ return "icon";
+ }
+ return null;
+ }
+
+ get suffixValue() {
+ if (
+ this.voiceWebrtc.connectionStateFor(this.room.id) ===
+ "connecting"
+ ) {
+ return "spinner";
+ }
+ if (this.#hasActiveVideo) {
+ return "video";
+ }
+ return null;
+ }
+
+ getParticipantsForSummary() {
+ const participants = this.room.active_participants || [];
+
+ if (!this.currentUser) {
+ return participants;
+ }
+
+ if (
+ this.voiceWebrtc.connectionStateFor(this.room.id) !==
+ "connected"
+ ) {
+ return participants;
+ }
+
+ if (
+ participants.some(
+ (participant) => participant?.id === this.currentUser.id
+ )
+ ) {
+ return participants;
+ }
+
+ return [
+ ...participants,
+ {
+ id: this.currentUser.id,
+ username: this.currentUser.username,
+ name: this.currentUser.name,
+ avatar_template: this.currentUser.avatar_template,
+ },
+ ];
+ }
+ };
+
+ const ParticipantLink = class extends BaseLink {
+ constructor({
+ room,
+ participant,
+ webrtcService,
+ user,
+ menu,
+ canManageRoom,
+ isListener,
+ isFirstListener,
+ }) {
+ super(...arguments);
+ this.room = room;
+ this.participant = participant;
+ this.voiceWebrtc = webrtcService;
+ this.currentUser = user;
+ this.menuService = menu;
+ this.canManageRoom = canManageRoom;
+ this.isStageListener = isListener || false;
+ this.isFirstListener = isFirstListener || false;
+ }
+
+ get #isCurrentUser() {
+ return this.participant.id === this.currentUser?.id;
+ }
+
+ get #showMenu() {
+ return (
+ !capabilities.isIpadOS &&
+ !!this.currentUser &&
+ this.voiceWebrtc.connectionStateFor(this.room.id) ===
+ "connected"
+ );
+ }
+
+ get #isAudiblySpeaking() {
+ return (
+ roomsService.isParticipantSpeaking(
+ this.room.id,
+ this.participant.id
+ ) &&
+ !this.participant.is_muted &&
+ !this.participant.is_deafened
+ );
+ }
+
+ get #isHandRaised() {
+ return (
+ this.room.room_type === "stage" &&
+ !!this.participant.hand_raised_at
+ );
+ }
+
+ get hoverType() {
+ return this.#showMenu ? "icon" : null;
+ }
+
+ get hoverValue() {
+ return this.#showMenu ? "ellipsis-vertical" : null;
+ }
+
+ get hoverTitle() {
+ return i18n("voice.participant.menu_title");
+ }
+
+ get hoverAction() {
+ if (!this.#showMenu) {
+ return noop;
+ }
+
+ return (event, onMenuClose) => {
+ event.stopPropagation();
+ event.preventDefault();
+
+ const anchor =
+ event.target.closest(".sidebar-section-link") || event.target;
+
+ this.menuService.show(anchor, {
+ identifier: "voice-participant-menu",
+ component: VoiceParticipantSidebarContextMenu,
+ placement: "right",
+ data: {
+ room: this.room,
+ participant: this.participant,
+ canManageRoom: this.canManageRoom,
+ isCurrentUser: this.#isCurrentUser,
+ },
+ onClose: onMenuClose,
+ });
+ };
+ }
+
+ get name() {
+ return `voice-participant-${this.room.id}-${this.participant.id}`;
+ }
+
+ get classNames() {
+ const classes = ["voice-sidebar-participant"];
+
+ if (this.isStageListener) {
+ classes.push("voice-sidebar-participant--listener");
+ }
+
+ if (this.isFirstListener) {
+ classes.push("voice-sidebar-participant--listeners-start");
+ }
+
+ if (this.#isAudiblySpeaking) {
+ classes.push("voice-sidebar-participant--speaking");
+ }
+
+ if (this.participant.is_muted) {
+ classes.push("voice-sidebar-participant--muted");
+ }
+
+ if (this.participant.is_deafened) {
+ classes.push("voice-sidebar-participant--deafened");
+ }
+
+ if (this.#isHandRaised) {
+ classes.push("voice-sidebar-participant--hand-raised");
+ }
+
+ if (this.participant.idle_state === "idle") {
+ classes.push("voice-sidebar-participant--idle");
+ } else if (this.participant.idle_state === "afk") {
+ classes.push("voice-sidebar-participant--afk");
+ }
+
+ return classes.join(" ");
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get #displayName() {
+ return prioritizeNameInUx(this.participant.name)
+ ? this.participant.name
+ : this.participant.username;
+ }
+
+ get title() {
+ let title = this.#displayName;
+ if (this.#isCurrentUser && this.voiceWebrtc.pttEnabled) {
+ title = `${title} — ${i18n("voice.ptt.badge", { key: humanKeyName(this.voiceWebrtc.pttKey) })}`;
+ }
+ // The speaking wave is a CSS pseudo-element and can't carry
+ // its own accessible label, so surface the state here instead.
+ if (this.#isAudiblySpeaking) {
+ title = `${title} — ${i18n("voice.participant.status_speaking")}`;
+ }
+ return title;
+ }
+
+ get text() {
+ return this.#displayName;
+ }
+
+ // A custom suffix component (instead of the single suffixValue
+ // slot) so every state icon can show simultaneously on the right
+ // edge. The speaking wave renders over the avatar via the
+ // `--speaking` class.
+ get suffixComponent() {
+ return VoiceParticipantSidebarSuffix;
+ }
+
+ get suffixArgs() {
+ return {
+ isHandRaised: this.#isHandRaised,
+ isScreenSharing: this.participant.is_screen_sharing,
+ isVideoOn: this.participant.is_video_on,
+ isPtt: this.#isCurrentUser && this.voiceWebrtc.pttEnabled,
+ isMuted: this.participant.is_muted,
+ isDeafened: this.participant.is_deafened,
+ };
+ }
+
+ get prefixType() {
+ return "image";
+ }
+
+ get prefixValue() {
+ return avatarUrl(this.participant.avatar_template, "small");
+ }
+ };
+
+ const ListenerCountLink = class extends BaseLink {
+ constructor({ room, count }) {
+ super(...arguments);
+ this.room = room;
+ this.count = count;
+ }
+
+ get name() {
+ return `voice-listener-count-${this.room.id}`;
+ }
+
+ get classNames() {
+ return "voice-sidebar-participant voice-sidebar-participant--listener-count";
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get text() {
+ return i18n("voice.stage.more_listeners", {
+ count: this.count,
+ });
+ }
+
+ get prefixType() {
+ return "icon";
+ }
+
+ get prefixValue() {
+ return "users";
+ }
+ };
+
+ const RoomsSection = class extends BaseSection {
+ name = sectionName;
+ text = i18n("voice.sidebar.title");
+ title = i18n("voice.sidebar.title");
+
+ constructor() {
+ super(...arguments);
+ this.voiceRooms = roomsService;
+ }
+
+ get actions() {
+ if (this.voiceRooms?.canCreateRoom) {
+ return [
+ {
+ id: "createVoiceRoom",
+ title: i18n("voice.sidebar.create"),
+ action: () => modalService.show(VoiceCreateRoomModal),
+ },
+ ];
+ }
+ return [];
+ }
+
+ get actionsIcon() {
+ return "plus";
+ }
+
+ get displaySection() {
+ // In combined mode the main-panel copy already renders; avoid a duplicate.
+ if (chatPanel && sidebarState.combinedMode) {
+ return false;
+ }
+
+ return (
+ (this.voiceRooms?.rooms?.length || 0) > 0 ||
+ this.voiceRooms?.canCreateRoom
+ );
+ }
+
+ get links() {
+ const result = [];
+
+ for (const room of this.voiceRooms?.rooms || []) {
+ const roomLink = new RoomsLink({
+ room,
+ webrtcService: voiceWebrtc,
+ user: currentUser,
+ menu: menuService,
+ });
+ result.push(roomLink);
+
+ const canManageRoom = room.can_manage;
+ const participants = roomLink.getParticipantsForSummary();
+
+ if (room.room_type === "stage" && participants.length > 0) {
+ const speakers = participants.filter((p) => {
+ const role = p.role;
+ return role === "moderator" || role === "speaker";
+ });
+ const listeners = participants.filter((p) => {
+ const role = p.role;
+ return role !== "moderator" && role !== "speaker";
+ });
+
+ for (const participant of speakers) {
+ result.push(
+ new ParticipantLink({
+ room,
+ participant,
+ webrtcService: voiceWebrtc,
+ user: currentUser,
+ menu: menuService,
+ canManageRoom,
+ })
+ );
+ }
+
+ const maxVisibleListeners = 5;
+ const visibleListeners = listeners.slice(
+ 0,
+ maxVisibleListeners
+ );
+
+ visibleListeners.forEach((participant, index) => {
+ result.push(
+ new ParticipantLink({
+ room,
+ participant,
+ webrtcService: voiceWebrtc,
+ user: currentUser,
+ menu: menuService,
+ canManageRoom,
+ isListener: true,
+ isFirstListener: index === 0,
+ })
+ );
+ });
+
+ if (listeners.length > maxVisibleListeners) {
+ result.push(
+ new ListenerCountLink({
+ room,
+ count: listeners.length - maxVisibleListeners,
+ })
+ );
+ }
+ } else {
+ for (const participant of participants) {
+ result.push(
+ new ParticipantLink({
+ room,
+ participant,
+ webrtcService: voiceWebrtc,
+ user: currentUser,
+ menu: menuService,
+ canManageRoom,
+ })
+ );
+ }
+ }
+ }
+
+ return result;
+ }
+ };
+
+ return RoomsSection;
+ };
+
+ api.addSidebarSection(buildRoomsSection({ sectionName: "voice-rooms" }));
+
+ // Mirror the section into the chat panel so rooms stay visible in the
+ // full-screen chat separate sidebar. The chat panel is registered by the
+ // chat plugin's own initializer, whose relative order isn't guaranteed,
+ // so poll until the panel shows up. The panel may also have rendered by
+ // then, and pushes into its sections array aren't tracked, so reassign
+ // the array to make a late-registered section render.
+ const registerChatRoomsSection = () => {
+ const foundChatPanel = (sidebarState.panels || []).find(
+ (panel) => panel.key === CHAT_PANEL
+ );
+
+ if (!foundChatPanel) {
+ return false;
+ }
+
+ api.addSidebarSection(
+ buildRoomsSection({
+ sectionName: "voice-rooms-chat",
+ chatPanel: true,
+ }),
+ CHAT_PANEL
+ );
+ foundChatPanel.sections = [...foundChatPanel.sections];
+ return true;
+ };
+
+ if (siteSettings.chat_enabled && !registerChatRoomsSection()) {
+ // The panel never appears for users who can't chat; give up quietly
+ // after a few seconds.
+ let attempts = 0;
+ const retryRegistration = () => {
+ if (registerChatRoomsSection() || ++attempts >= 50) {
+ return;
+ }
+ later(retryRegistration, 100);
+ };
+ next(retryRegistration);
+ }
+
+ if (sidebarClickHandler) {
+ document.removeEventListener("click", sidebarClickHandler);
+ }
+
+ sidebarClickHandler = async (event) => {
+ const findAnchor = (selector) =>
+ event
+ .composedPath?.()
+ ?.find?.(
+ (node) => node instanceof HTMLElement && node.matches?.(selector)
+ ) || event.target?.closest?.(selector);
+
+ const participantAnchor = findAnchor(
+ ".sidebar-section-link[data-link-name^='voice-participant-']"
+ );
+
+ const roomAnchor = findAnchor(
+ ".sidebar-section-link[data-link-name^='voice-room-']"
+ );
+
+ if (participantAnchor) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+
+ if (!roomAnchor) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const linkName = roomAnchor.dataset?.linkName;
+ if (!linkName?.startsWith(LINK_NAME_PREFIX)) {
+ return;
+ }
+
+ const roomId = parseInt(
+ linkName.substring(LINK_NAME_PREFIX.length),
+ 10
+ );
+ const room = Number.isNaN(roomId)
+ ? null
+ : roomsService.roomById(roomId);
+
+ if (!room) {
+ return;
+ }
+
+ const connectionState = voiceWebrtc.connectionStateFor(room.id);
+
+ if (event.shiftKey) {
+ // Hand the call over cleanly: two windows joined as the same user
+ // would fight over presence.
+ if (connectionState === "connected") {
+ voiceWebrtc.leave(room);
+ }
+
+ window.open(getURL(`/voice/r/${room.slug}?join`));
+ return;
+ }
+
+ if (connectionState === "connecting") {
+ return;
+ }
+
+ if (connectionState === "connected") {
+ const currentRoute = routerService.currentRoute;
+ const onRoomPage =
+ currentRoute?.name === "voice-room" &&
+ currentRoute?.params?.slug === room.slug;
+
+ if (!onRoomPage) {
+ routerService.transitionTo("voice-room", room.slug);
+ }
+ } else {
+ await voiceWebrtc.join(room);
+ }
+ };
+
+ document.addEventListener("click", sidebarClickHandler);
+
+ if (sidebarContextMenuHandler) {
+ document.removeEventListener("contextmenu", sidebarContextMenuHandler);
+ }
+
+ sidebarContextMenuHandler = (event) => {
+ const findAnchor = (selector) =>
+ event
+ .composedPath?.()
+ ?.find?.(
+ (node) => node instanceof HTMLElement && node.matches?.(selector)
+ ) || event.target?.closest?.(selector);
+
+ const participantAnchor = findAnchor(
+ ".sidebar-section-link[data-link-name^='voice-participant-']"
+ );
+
+ if (participantAnchor) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ const linkName = participantAnchor.dataset?.linkName;
+ const suffix = linkName?.replace("voice-participant-", "");
+ const dashIdx = suffix?.indexOf("-");
+ if (!suffix || dashIdx < 1) {
+ return;
+ }
+
+ const roomId = parseInt(suffix.substring(0, dashIdx), 10);
+ const participantId = parseInt(suffix.substring(dashIdx + 1), 10);
+ const room = roomsService.roomById(roomId);
+ if (!room) {
+ return;
+ }
+
+ const participant = (room.active_participants || []).find(
+ (p) => p.id === participantId
+ );
+ if (!participant) {
+ return;
+ }
+
+ // The menu only offers audio controls for a call the user is in.
+ if (voiceWebrtc.connectionStateFor(room.id) !== "connected") {
+ return;
+ }
+
+ menuService.show(virtualElementFromEvent(event), {
+ identifier: "voice-participant-menu",
+ component: VoiceParticipantSidebarContextMenu,
+ placement: "bottom-start",
+ data: {
+ room,
+ participant,
+ canManageRoom: room.can_manage,
+ isCurrentUser: participant.id === currentUser?.id,
+ },
+ });
+ return;
+ }
+
+ const roomAnchor = findAnchor(
+ ".sidebar-section-link[data-link-name^='voice-room-']"
+ );
+
+ if (!roomAnchor) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ const linkName = roomAnchor.dataset?.linkName;
+ if (!linkName?.startsWith(LINK_NAME_PREFIX)) {
+ return;
+ }
+
+ const roomId = parseInt(
+ linkName.substring(LINK_NAME_PREFIX.length),
+ 10
+ );
+ const room = Number.isNaN(roomId)
+ ? null
+ : roomsService.roomById(roomId);
+
+ if (!room) {
+ return;
+ }
+
+ menuService.show(virtualElementFromEvent(event), {
+ identifier: "voice-room-menu",
+ component: VoiceRoomSidebarContextMenu,
+ placement: "bottom-start",
+ data: { room },
+ });
+ };
+
+ document.addEventListener("contextmenu", sidebarContextMenuHandler);
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-transcript-draft-icon.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-transcript-draft-icon.js
new file mode 100644
index 00000000000..e782714c368
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-transcript-draft-icon.js
@@ -0,0 +1,16 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { TRANSCRIPT_DRAFT_KEY_PREFIX } from "../lib/voice/transcript-draft-sync";
+
+export default {
+ name: "voice-transcript-draft-icon",
+
+ initialize() {
+ withPluginApi((api) => {
+ api.registerValueTransformer("draft-icon", ({ value, context }) => {
+ return context.draft?.draft_key?.startsWith(TRANSCRIPT_DRAFT_KEY_PREFIX)
+ ? "closed-captioning"
+ : value;
+ });
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/initializers/voice-voice-canvas.js b/plugins/voice/assets/javascripts/discourse/initializers/voice-voice-canvas.js
new file mode 100644
index 00000000000..c89fd33495c
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/initializers/voice-voice-canvas.js
@@ -0,0 +1,19 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import VoiceGlobalCallLayer from "discourse/plugins/voice/discourse/components/voice/global-call-layer";
+
+export default {
+ name: "voice-voice-canvas",
+
+ initialize(owner) {
+ withPluginApi((api) => {
+ const currentUser = api.getCurrentUser();
+ const siteSettings = owner.lookup("service:site-settings");
+
+ if (!currentUser || !siteSettings.voice_enabled) {
+ return;
+ }
+
+ api.renderInOutlet("below-site-header", VoiceGlobalCallLayer);
+ });
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/lib/hashtag-types/room.js b/plugins/voice/assets/javascripts/discourse/lib/hashtag-types/room.js
new file mode 100644
index 00000000000..9a89fcfeaf6
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/hashtag-types/room.js
@@ -0,0 +1,20 @@
+import HashtagTypeBase from "discourse/lib/hashtag-types/base";
+import { iconHTML } from "discourse/lib/icon-library";
+
+export default class RoomHashtagType extends HashtagTypeBase {
+ get type() {
+ return "room";
+ }
+
+ get preloadedData() {
+ return [];
+ }
+
+ generateColorCssClasses() {
+ return [];
+ }
+
+ generateIconHTML(hashtag) {
+ return iconHTML(hashtag.icon || "microphone-lines");
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice-flag.js b/plugins/voice/assets/javascripts/discourse/lib/voice-flag.js
new file mode 100644
index 00000000000..ea66929c309
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice-flag.js
@@ -0,0 +1,63 @@
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+
+export default class VoiceFlag {
+ constructor(room) {
+ this.room = room;
+ }
+
+ title() {
+ return "flagging.title";
+ }
+
+ customSubmitLabel() {
+ return "flagging.notify_action";
+ }
+
+ submitLabel() {
+ return "flagging.action";
+ }
+
+ targetsTopic() {
+ return false;
+ }
+
+ editable() {
+ return false;
+ }
+
+ // A participant has no post or chat message to give the flag context, so
+ // only the free-form "something else" flag is offered; a single option is
+ // auto-selected by the modal.
+ flagsAvailable(flagModal) {
+ return flagModal.site.flagTypes
+ .filter((flagType) => flagType.name_key === "notify_moderators")
+ .map((flagType) => {
+ flagType.set(
+ "description",
+ i18n("voice.flagging.notify_moderators_description", {
+ defaultValue: flagType.description,
+ })
+ );
+ return flagType;
+ });
+ }
+
+ async create(flagModal, opts) {
+ flagModal.args.closeModal();
+
+ try {
+ await ajax(`/voice/rooms/${this.room.id}/flag`, {
+ type: "POST",
+ data: {
+ user_id: flagModal.args.model.flagModel.user_id,
+ flag_type_id: flagModal.selected.id,
+ message: opts.message,
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/anon-rooms-section.js b/plugins/voice/assets/javascripts/discourse/lib/voice/anon-rooms-section.js
new file mode 100644
index 00000000000..8daea372236
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/anon-rooms-section.js
@@ -0,0 +1,219 @@
+import { avatarUrl } from "discourse/lib/avatar-utils";
+import { prioritizeNameInUx } from "discourse/lib/settings";
+import { i18n } from "discourse-i18n";
+import roomIcon, { roomBadge } from "./room-icon";
+
+export default function buildAnonRoomsSection(roomsService) {
+ return (BaseSection, BaseLink) => {
+ class RoomLink extends BaseLink {
+ constructor(room) {
+ super(...arguments);
+ this.room = room;
+ }
+
+ get name() {
+ return `voice-room-${this.room.id}`;
+ }
+
+ get classNames() {
+ return "voice-sidebar-link";
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get title() {
+ return (
+ this.room.description_excerpt ||
+ this.room.name ||
+ i18n("voice.room.join")
+ );
+ }
+
+ get text() {
+ return this.room.name;
+ }
+
+ get prefixType() {
+ return "icon";
+ }
+
+ get prefixValue() {
+ return roomIcon(this.room);
+ }
+
+ get prefixBadge() {
+ return roomBadge(this.room);
+ }
+ }
+
+ class ParticipantLink extends BaseLink {
+ constructor(room, participant, options = {}) {
+ super(...arguments);
+ this.room = room;
+ this.participant = participant;
+ this.isStageListener = options.isListener || false;
+ this.isFirstListener = options.isFirstListener || false;
+ }
+
+ get name() {
+ return `voice-participant-${this.room.id}-${this.participant.id}`;
+ }
+
+ get classNames() {
+ const classes = ["voice-sidebar-participant"];
+
+ if (this.isStageListener) {
+ classes.push("voice-sidebar-participant--listener");
+ }
+
+ if (this.isFirstListener) {
+ classes.push("voice-sidebar-participant--listeners-start");
+ }
+
+ // Speaking is detected client-side from live media streams, which
+ // anonymous visitors never hold.
+ if (this.participant.is_muted) {
+ classes.push("voice-sidebar-participant--muted");
+ }
+
+ if (this.participant.is_deafened) {
+ classes.push("voice-sidebar-participant--deafened");
+ }
+
+ if (this.participant.idle_state === "idle") {
+ classes.push("voice-sidebar-participant--idle");
+ } else if (this.participant.idle_state === "afk") {
+ classes.push("voice-sidebar-participant--afk");
+ }
+
+ return classes.join(" ");
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get displayName() {
+ return prioritizeNameInUx(this.participant.name)
+ ? this.participant.name
+ : this.participant.username;
+ }
+
+ get title() {
+ return this.displayName;
+ }
+
+ get text() {
+ return this.displayName;
+ }
+
+ get prefixType() {
+ return "image";
+ }
+
+ get prefixValue() {
+ return avatarUrl(this.participant.avatar_template, "small");
+ }
+ }
+
+ class ListenerCountLink extends BaseLink {
+ constructor(room, count) {
+ super(...arguments);
+ this.room = room;
+ this.count = count;
+ }
+
+ get name() {
+ return `voice-listener-count-${this.room.id}`;
+ }
+
+ get classNames() {
+ return "voice-sidebar-participant voice-sidebar-participant--listener-count";
+ }
+
+ get href() {
+ return "#";
+ }
+
+ get title() {
+ return this.text;
+ }
+
+ get text() {
+ return i18n("voice.stage.more_listeners", { count: this.count });
+ }
+
+ get prefixType() {
+ return "icon";
+ }
+
+ get prefixValue() {
+ return "users";
+ }
+ }
+
+ return class AnonRoomsSection extends BaseSection {
+ name = "voice-rooms";
+ text = i18n("voice.sidebar.title");
+ title = i18n("voice.sidebar.title");
+
+ get displaySection() {
+ return (roomsService.rooms?.length || 0) > 0;
+ }
+
+ get links() {
+ const links = [];
+
+ for (const room of roomsService.rooms || []) {
+ links.push(new RoomLink(room));
+
+ const participants = room.active_participants || [];
+
+ if (room.room_type === "stage" && participants.length > 0) {
+ const speakers = participants.filter((participant) => {
+ const role = participant.role;
+ return role === "moderator" || role === "speaker";
+ });
+ const listeners = participants.filter((participant) => {
+ const role = participant.role;
+ return role !== "moderator" && role !== "speaker";
+ });
+
+ for (const participant of speakers) {
+ links.push(new ParticipantLink(room, participant));
+ }
+
+ const maxVisibleListeners = 5;
+ listeners
+ .slice(0, maxVisibleListeners)
+ .forEach((participant, index) => {
+ links.push(
+ new ParticipantLink(room, participant, {
+ isListener: true,
+ isFirstListener: index === 0,
+ })
+ );
+ });
+
+ if (listeners.length > maxVisibleListeners) {
+ links.push(
+ new ListenerCountLink(
+ room,
+ listeners.length - maxVisibleListeners
+ )
+ );
+ }
+ } else {
+ for (const participant of participants) {
+ links.push(new ParticipantLink(room, participant));
+ }
+ }
+ }
+
+ return links;
+ }
+ };
+ };
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js
new file mode 100644
index 00000000000..4f3713f5888
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js
@@ -0,0 +1,236 @@
+const SAMPLE_INTERVAL_MS = 100;
+const FFT_SIZE = 2048;
+
+// Detection uses an adaptive noise floor with hysteresis: speech must clear
+// the floor by a wide margin to start, but only a narrow one to continue, so
+// quiet trailing syllables don't flap the indicator. RMS values are on the
+// float sample scale (0..1).
+const MIN_START_RMS = 0.006;
+const MIN_SUSTAIN_RMS = 0.003;
+const START_FLOOR_MULTIPLIER = 3;
+const SUSTAIN_FLOOR_MULTIPLIER = 1.6;
+const MAX_NOISE_FLOOR = 0.1;
+const INITIAL_NOISE_FLOOR = 0.02;
+
+// The floor adapts down fast but up slowly, so sustained speech isn't
+// absorbed into it.
+const FLOOR_DECAY = 0.3;
+const FLOOR_RISE = 0.02;
+
+// How long the signal may stay below the sustain threshold before the
+// speaker is considered done — covers pauses between words.
+const HANGOVER_MS = 700;
+
+export default class AudioMonitor {
+ static peerKey(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ #monitors = new Map();
+ #audioContext = null;
+ #sampleTimer = null;
+
+ #onSpeakingChange;
+ #onVoiceActivity;
+
+ constructor({ onSpeakingChange, onVoiceActivity }) {
+ this.#onSpeakingChange = onSpeakingChange;
+ this.#onVoiceActivity = onVoiceActivity;
+ }
+
+ ensure(roomId, userId, stream, isCurrentUser) {
+ if (!roomId || !userId || !stream) {
+ return;
+ }
+
+ const key = AudioMonitor.peerKey(roomId, userId);
+ const existing = this.#monitors.get(key);
+ if (existing?.stream === stream) {
+ return;
+ }
+
+ if (existing) {
+ this.teardown(roomId, userId);
+ }
+
+ try {
+ const audioContext = this.#ensureAudioContext();
+ if (!audioContext) {
+ return;
+ }
+
+ const source = audioContext.createMediaStreamSource(stream);
+ const analyser = audioContext.createAnalyser();
+ analyser.fftSize = FFT_SIZE;
+ source.connect(analyser);
+
+ this.#monitors.set(key, {
+ roomId,
+ userId,
+ stream,
+ source,
+ analyser,
+ isCurrentUser,
+ floatData: analyser.getFloatTimeDomainData
+ ? new Float32Array(analyser.fftSize)
+ : null,
+ byteData: analyser.getFloatTimeDomainData
+ ? null
+ : new Uint8Array(analyser.frequencyBinCount),
+ speaking: false,
+ lastVoiceAt: 0,
+ noiseFloor: INITIAL_NOISE_FLOOR,
+ });
+
+ this.#startSampling();
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to initialize audio monitor", error);
+ }
+ }
+
+ teardown(roomId, userId) {
+ if (!roomId || !userId) {
+ return;
+ }
+
+ const key = AudioMonitor.peerKey(roomId, userId);
+ const monitor = this.#monitors.get(key);
+ if (!monitor) {
+ return;
+ }
+
+ this.#stopMonitor(monitor);
+ this.#monitors.delete(key);
+ this.#onSpeakingChange(roomId, userId, false);
+ this.#maybeReleaseResources();
+ }
+
+ teardownRoom(roomId) {
+ Array.from(this.#monitors.keys()).forEach((key) => {
+ if (key.startsWith(`${roomId}:`)) {
+ const [, userId] = key.split(":");
+ this.teardown(roomId, Number(userId));
+ }
+ });
+ }
+
+ destroyAll() {
+ this.#monitors.forEach((monitor) => this.#stopMonitor(monitor));
+ this.#monitors.clear();
+ this.#maybeReleaseResources();
+ }
+
+ #ensureAudioContext() {
+ if (!this.#audioContext || this.#audioContext.state === "closed") {
+ const audioContextClass =
+ typeof window !== "undefined" &&
+ (window.AudioContext || window.webkitAudioContext);
+
+ if (!audioContextClass) {
+ return null;
+ }
+
+ this.#audioContext = new audioContextClass();
+ }
+
+ // Contexts created before a user gesture start suspended and only
+ // produce zeros; resume is safe to call repeatedly.
+ if (this.#audioContext.state === "suspended") {
+ this.#audioContext.resume?.().catch?.(() => {});
+ }
+
+ return this.#audioContext;
+ }
+
+ #startSampling() {
+ if (this.#sampleTimer) {
+ return;
+ }
+
+ const tick = () => {
+ this.#monitors.forEach((monitor) => this.#sampleMonitor(monitor));
+ this.#sampleTimer = setTimeout(tick, SAMPLE_INTERVAL_MS);
+ };
+
+ tick();
+ }
+
+ #sampleMonitor(monitor) {
+ const rms = this.#measureRms(monitor);
+
+ if (rms < monitor.noiseFloor) {
+ monitor.noiseFloor += (rms - monitor.noiseFloor) * FLOOR_DECAY;
+ } else if (!monitor.speaking) {
+ monitor.noiseFloor +=
+ (Math.min(rms, MAX_NOISE_FLOOR) - monitor.noiseFloor) * FLOOR_RISE;
+ }
+
+ const threshold = monitor.speaking
+ ? Math.max(MIN_SUSTAIN_RMS, monitor.noiseFloor * SUSTAIN_FLOOR_MULTIPLIER)
+ : Math.max(MIN_START_RMS, monitor.noiseFloor * START_FLOOR_MULTIPLIER);
+
+ if (rms >= threshold) {
+ monitor.lastVoiceAt = Date.now();
+
+ if (monitor.isCurrentUser) {
+ this.#onVoiceActivity();
+ }
+
+ if (!monitor.speaking) {
+ monitor.speaking = true;
+ this.#onSpeakingChange(monitor.roomId, monitor.userId, true);
+ }
+ } else if (
+ monitor.speaking &&
+ Date.now() - monitor.lastVoiceAt >= HANGOVER_MS
+ ) {
+ monitor.speaking = false;
+ this.#onSpeakingChange(monitor.roomId, monitor.userId, false);
+ }
+ }
+
+ #measureRms(monitor) {
+ const { analyser } = monitor;
+ let sum = 0;
+
+ if (monitor.floatData) {
+ analyser.getFloatTimeDomainData(monitor.floatData);
+ for (let i = 0; i < monitor.floatData.length; i++) {
+ sum += monitor.floatData[i] * monitor.floatData[i];
+ }
+ return Math.sqrt(sum / monitor.floatData.length);
+ }
+
+ analyser.getByteTimeDomainData(monitor.byteData);
+ for (let i = 0; i < monitor.byteData.length; i++) {
+ const deviation = (monitor.byteData[i] - 128) / 128;
+ sum += deviation * deviation;
+ }
+ return Math.sqrt(sum / monitor.byteData.length);
+ }
+
+ #stopMonitor(monitor) {
+ try {
+ monitor.source.disconnect();
+ } catch {
+ // ignore
+ }
+ }
+
+ #maybeReleaseResources() {
+ if (this.#monitors.size > 0) {
+ return;
+ }
+
+ if (this.#sampleTimer) {
+ clearTimeout(this.#sampleTimer);
+ this.#sampleTimer = null;
+ }
+
+ if (this.#audioContext) {
+ this.#audioContext.close?.();
+ this.#audioContext = null;
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/audio-processing.js b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-processing.js
new file mode 100644
index 00000000000..23d49d2c78e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-processing.js
@@ -0,0 +1,106 @@
+import { NS_ENGINES } from "./ns-engines";
+
+// Per-device preferences for the browser's microphone processing chain and
+// the noise suppression mode. Echo cancellation and automatic gain control
+// default to on (matching what browsers do when the constraints are absent);
+// they are stored only when the user turns one off.
+//
+// Noise suppression modes:
+// "none" — no filtering at all
+// "standard" — the browser's native noise suppression
+// "ai:<engine>" — an AI worklet engine (see ns-engines.js); native
+// suppression is turned OFF so the two filters don't
+// stack (stacked suppressors produce the classic
+// underwater/musical artifacts)
+
+const EC_STORAGE_KEY = "voice:echo-cancellation";
+const AGC_STORAGE_KEY = "voice:auto-gain-control";
+const NS_MODE_STORAGE_KEY = "voice:noise-suppression-mode";
+const LEGACY_NS_STORAGE_KEY = "voice:noise-suppression";
+
+export const NOISE_SUPPRESSION_MODES = [
+ "none",
+ "standard",
+ ...Object.keys(NS_ENGINES).map((id) => `ai:${id}`),
+];
+
+export function isAiMode(mode) {
+ return !!mode?.startsWith?.("ai:");
+}
+
+function readDefaultOnFlag(key) {
+ try {
+ return localStorage.getItem(key) !== "0";
+ } catch {
+ return true;
+ }
+}
+
+function storeDefaultOnFlag(key, enabled) {
+ try {
+ if (enabled) {
+ localStorage.removeItem(key);
+ } else {
+ localStorage.setItem(key, "0");
+ }
+ } catch {
+ // ignore storage errors
+ }
+}
+
+export function echoCancellationPreferred() {
+ return readDefaultOnFlag(EC_STORAGE_KEY);
+}
+
+export function setEchoCancellationPreferred(enabled) {
+ storeDefaultOnFlag(EC_STORAGE_KEY, enabled);
+}
+
+export function autoGainControlPreferred() {
+ return readDefaultOnFlag(AGC_STORAGE_KEY);
+}
+
+export function setAutoGainControlPreferred(enabled) {
+ storeDefaultOnFlag(AGC_STORAGE_KEY, enabled);
+}
+
+export function preferredNoiseSuppressionMode() {
+ try {
+ const mode = localStorage.getItem(NS_MODE_STORAGE_KEY);
+ if (NOISE_SUPPRESSION_MODES.includes(mode)) {
+ return mode;
+ }
+ // Two generations of stored values predate per-engine modes: the plain
+ // "ai" mode, and before that a boolean where "1" meant the DTLN worklet
+ // was on. Both meant DTLN.
+ if (mode === "ai" || localStorage.getItem(LEGACY_NS_STORAGE_KEY) === "1") {
+ return "ai:dtln";
+ }
+ } catch {
+ // fall through to the default
+ }
+ return "standard";
+}
+
+export function setPreferredNoiseSuppressionMode(mode) {
+ if (!NOISE_SUPPRESSION_MODES.includes(mode)) {
+ return;
+ }
+ try {
+ localStorage.setItem(NS_MODE_STORAGE_KEY, mode);
+ localStorage.removeItem(LEGACY_NS_STORAGE_KEY);
+ } catch {
+ // ignore storage errors
+ }
+}
+
+// The audio-processing member of getUserMedia constraints. Explicit even for
+// the defaults, so what the pipeline believes and what the browser applies
+// can't drift apart.
+export function processingConstraints() {
+ return {
+ echoCancellation: echoCancellationPreferred(),
+ autoGainControl: autoGainControlPreferred(),
+ noiseSuppression: preferredNoiseSuppressionMode() === "standard",
+ };
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js b/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js
new file mode 100644
index 00000000000..407854fed0a
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js
@@ -0,0 +1,360 @@
+// Camera background blur.
+//
+// Runs the raw camera stream through MediaPipe selfie segmentation and
+// composites each frame on a canvas — blurred frame behind, sharp person
+// cutout in front — then captures the canvas as the outgoing stream.
+// Mirrors the NoiseSuppressionManager contract: setup(raw stream) returns
+// the processed stream; the caller keeps ownership of the raw stream.
+
+import { voiceAssetUrl } from "./voice-assets";
+
+const ENABLED_KEY = "voice_video_blur_enabled";
+const AMOUNT_KEY = "voice_video_blur_amount";
+
+// Bounds the wait for the hidden <video> to start playing. Without it, a
+// raw stream whose track ends mid-setup could hang the caller forever.
+const PLAY_TIMEOUT_MS = 10000;
+
+export const DEFAULT_BLUR_AMOUNT = 50;
+
+// Blur radius in px at 720p with the slider at 100; scales with the actual
+// frame height so the effect looks the same at any capture resolution.
+const MAX_BLUR_PX = 40;
+
+// Feather the upscaled mask so the person edge blends instead of cutting.
+const MASK_FEATHER_PX = 3;
+
+// The wasm runtime and model stay resident after first use so re-enabling
+// blur is instant; every manager instance shares one segmenter.
+let segmenterPromise = null;
+
+// VIDEO-mode segmentation requires strictly increasing timestamps across
+// all users of the shared segmenter.
+let lastTimestamp = 0;
+
+function mediapipeBase() {
+ return voiceAssetUrl("mediapipe");
+}
+
+async function loadSegmenter() {
+ segmenterPromise ||= (async () => {
+ const base = mediapipeBase();
+ const vision = await import(/* @vite-ignore */ `${base}/vision_bundle.js`);
+ const fileset = await vision.FilesetResolver.forVisionTasks(`${base}/wasm`);
+ return await vision.ImageSegmenter.createFromOptions(fileset, {
+ baseOptions: {
+ modelAssetPath: `${base}/selfie_segmenter.tflite`,
+ delegate: "GPU",
+ },
+ runningMode: "VIDEO",
+ outputConfidenceMasks: true,
+ outputCategoryMask: false,
+ });
+ })();
+
+ try {
+ return await segmenterPromise;
+ } catch (error) {
+ // Allow a retry after a transient failure (e.g. offline asset fetch).
+ segmenterPromise = null;
+ throw error;
+ }
+}
+
+export default class BackgroundBlurManager {
+ static isSupported() {
+ return (
+ typeof HTMLCanvasElement !== "undefined" &&
+ typeof HTMLCanvasElement.prototype.captureStream === "function" &&
+ typeof WebAssembly !== "undefined"
+ );
+ }
+
+ static isPreferred() {
+ try {
+ return localStorage.getItem(ENABLED_KEY) === "1";
+ } catch {
+ return false;
+ }
+ }
+
+ static setPreference(enabled) {
+ try {
+ if (enabled) {
+ localStorage.setItem(ENABLED_KEY, "1");
+ } else {
+ localStorage.removeItem(ENABLED_KEY);
+ }
+ } catch {
+ // ignore storage errors
+ }
+ }
+
+ static storedAmount() {
+ try {
+ const value = parseInt(localStorage.getItem(AMOUNT_KEY), 10);
+ if (Number.isFinite(value)) {
+ return Math.max(0, Math.min(100, value));
+ }
+ } catch {
+ // ignore storage errors
+ }
+ return DEFAULT_BLUR_AMOUNT;
+ }
+
+ static storeAmount(value) {
+ try {
+ localStorage.setItem(AMOUNT_KEY, String(value));
+ } catch {
+ // ignore storage errors
+ }
+ }
+
+ #video = null;
+ #outputCanvas = null;
+ #outputCtx = null;
+ #personCanvas = null;
+ #personCtx = null;
+ #maskCanvas = null;
+ #maskCtx = null;
+ #maskImageData = null;
+ #segmenter = null;
+ #stream = null;
+ #running = false;
+ #frameCallbackId = null;
+ #timerId = null;
+ #amount = DEFAULT_BLUR_AMOUNT;
+ #onVisibilityChange = () => this.#rescheduleRender();
+
+ get active() {
+ return this.#running;
+ }
+
+ get stream() {
+ return this.#stream;
+ }
+
+ setAmount(value) {
+ this.#amount = Math.max(0, Math.min(100, value));
+ }
+
+ async setup(rawStream, amount = BackgroundBlurManager.storedAmount()) {
+ this.#amount = Math.max(0, Math.min(100, amount));
+
+ const rawTrack = rawStream.getVideoTracks()[0];
+ if (!rawTrack || rawTrack.readyState !== "live") {
+ throw new Error("raw video stream is not live");
+ }
+
+ this.#segmenter = await loadSegmenter();
+
+ const video = document.createElement("video");
+ video.muted = true;
+ video.playsInline = true;
+ video.srcObject = rawStream;
+
+ let playTimer;
+ try {
+ await Promise.race([
+ video.play(),
+ new Promise((_, reject) => {
+ playTimer = setTimeout(
+ () => reject(new Error("camera stream failed to start")),
+ PLAY_TIMEOUT_MS
+ );
+ }),
+ ]);
+ } finally {
+ clearTimeout(playTimer);
+ }
+
+ this.#video = video;
+ this.#outputCanvas = document.createElement("canvas");
+ this.#outputCtx = this.#outputCanvas.getContext("2d");
+ this.#personCanvas = document.createElement("canvas");
+ this.#personCtx = this.#personCanvas.getContext("2d");
+ this.#maskCanvas = document.createElement("canvas");
+ this.#maskCtx = this.#maskCanvas.getContext("2d");
+
+ this.#running = true;
+ document.addEventListener("visibilitychange", this.#onVisibilityChange);
+
+ // Paint the first frame before capturing so the track never starts black.
+ this.#renderFrame();
+ this.#scheduleRender();
+
+ this.#stream = this.#outputCanvas.captureStream();
+ return this.#stream;
+ }
+
+ teardown() {
+ this.#running = false;
+ document.removeEventListener("visibilitychange", this.#onVisibilityChange);
+ this.#cancelScheduledRender();
+
+ this.#stream?.getTracks().forEach((track) => track.stop());
+ this.#stream = null;
+
+ if (this.#video) {
+ this.#video.srcObject = null;
+ this.#video = null;
+ }
+
+ // The shared segmenter stays loaded for the next enable.
+ this.#segmenter = null;
+ this.#outputCanvas = null;
+ this.#outputCtx = null;
+ this.#personCanvas = null;
+ this.#personCtx = null;
+ this.#maskCanvas = null;
+ this.#maskCtx = null;
+ this.#maskImageData = null;
+ }
+
+ #scheduleRender() {
+ if (!this.#running) {
+ return;
+ }
+
+ // rVFC/rAF stall in hidden tabs, which would freeze the outgoing video
+ // for everyone watching; fall back to a timer (browser-clamped, but the
+ // stream keeps moving).
+ if (document.hidden || !this.#video.requestVideoFrameCallback) {
+ const delay = document.hidden ? 100 : 1000 / 30;
+ this.#timerId = setTimeout(() => this.#render(), delay);
+ } else {
+ this.#frameCallbackId = this.#video.requestVideoFrameCallback(() =>
+ this.#render()
+ );
+ }
+ }
+
+ #cancelScheduledRender() {
+ if (this.#frameCallbackId && this.#video?.cancelVideoFrameCallback) {
+ this.#video.cancelVideoFrameCallback(this.#frameCallbackId);
+ }
+ this.#frameCallbackId = null;
+
+ if (this.#timerId) {
+ clearTimeout(this.#timerId);
+ this.#timerId = null;
+ }
+ }
+
+ #rescheduleRender() {
+ if (!this.#running) {
+ return;
+ }
+ this.#cancelScheduledRender();
+ this.#scheduleRender();
+ }
+
+ #render() {
+ if (!this.#running) {
+ return;
+ }
+
+ try {
+ this.#renderFrame();
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] background blur frame failed", error);
+ }
+
+ this.#scheduleRender();
+ }
+
+ #renderFrame() {
+ const video = this.#video;
+ const width = video.videoWidth;
+ const height = video.videoHeight;
+
+ if (!width || !height) {
+ return;
+ }
+
+ if (
+ this.#outputCanvas.width !== width ||
+ this.#outputCanvas.height !== height
+ ) {
+ this.#outputCanvas.width = width;
+ this.#outputCanvas.height = height;
+ this.#personCanvas.width = width;
+ this.#personCanvas.height = height;
+ }
+
+ const timestamp = Math.max(performance.now(), lastTimestamp + 1);
+ lastTimestamp = timestamp;
+
+ // Callback form: the mask is only valid inside the callback, which runs
+ // synchronously, so the mask canvas is current for the composite below.
+ this.#segmenter.segmentForVideo(video, timestamp, (result) =>
+ this.#paintMask(result)
+ );
+
+ // Person cutout: upscaled + feathered mask, then keep only the video
+ // pixels where the mask is opaque.
+ const personCtx = this.#personCtx;
+ personCtx.clearRect(0, 0, width, height);
+ personCtx.filter = `blur(${MASK_FEATHER_PX}px)`;
+ personCtx.drawImage(this.#maskCanvas, 0, 0, width, height);
+ personCtx.filter = "none";
+ personCtx.globalCompositeOperation = "source-in";
+ personCtx.drawImage(video, 0, 0, width, height);
+ personCtx.globalCompositeOperation = "source-over";
+
+ // Blurred background, overscanned so the blur doesn't produce
+ // semi-transparent edges, with the person composited on top.
+ const ctx = this.#outputCtx;
+ const blurPx = Math.round(
+ (this.#amount / 100) * MAX_BLUR_PX * (height / 720)
+ );
+
+ if (blurPx > 0) {
+ ctx.filter = `blur(${blurPx}px)`;
+ ctx.drawImage(
+ video,
+ -blurPx,
+ -blurPx,
+ width + blurPx * 2,
+ height + blurPx * 2
+ );
+ ctx.filter = "none";
+ } else {
+ ctx.drawImage(video, 0, 0, width, height);
+ }
+
+ ctx.drawImage(this.#personCanvas, 0, 0);
+ }
+
+ #paintMask(result) {
+ const masks = result.confidenceMasks;
+ if (!masks?.length) {
+ return;
+ }
+
+ // The selfie model has categories background(0) / person(1); some builds
+ // emit a single person-confidence mask instead.
+ const mask = masks.length > 1 ? masks[1] : masks[0];
+ const { width, height } = mask;
+
+ if (
+ !this.#maskImageData ||
+ this.#maskImageData.width !== width ||
+ this.#maskImageData.height !== height
+ ) {
+ this.#maskCanvas.width = width;
+ this.#maskCanvas.height = height;
+ this.#maskImageData = this.#maskCtx.createImageData(width, height);
+ this.#maskImageData.data.fill(255);
+ }
+
+ const values = mask.getAsFloat32Array();
+ const data = this.#maskImageData.data;
+ for (let i = 0; i < values.length; i++) {
+ data[i * 4 + 3] = values[i] * 255;
+ }
+
+ this.#maskCtx.putImageData(this.#maskImageData, 0, 0);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/call-alert-dedup.js b/plugins/voice/assets/javascripts/discourse/lib/voice/call-alert-dedup.js
new file mode 100644
index 00000000000..a511a1b16fa
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/call-alert-dedup.js
@@ -0,0 +1,49 @@
+import KeyValueStore from "discourse/lib/key-value-store";
+
+const STORE_CONTEXT = "discourse_voice_call_alerts_";
+const STORE_KEY = "handled";
+const EXPIRY_MS = 5 * 60 * 1000;
+const MAX_ENTRIES = 50;
+
+const store = new KeyValueStore(STORE_CONTEXT);
+
+function readEntries() {
+ const now = Date.now();
+ return (store.getObject(STORE_KEY) || []).filter(
+ (entry) => now - entry.at < EXPIRY_MS
+ );
+}
+
+function writeEntries(entries) {
+ store.setObject({ key: STORE_KEY, value: entries.slice(-MAX_ENTRIES) });
+}
+
+// Every open tab receives the same ring event (hidden tabs get it from the
+// MessageBus backlog when they wake) — the first tab to handle it records it
+// here so the others don't also ring and stack answer modals.
+export function claimCallAlert(key) {
+ if (!key) {
+ return true;
+ }
+
+ const entries = readEntries();
+
+ if (entries.some((entry) => entry.key === key)) {
+ return false;
+ }
+
+ entries.push({ key, at: Date.now() });
+ writeEntries(entries);
+
+ return true;
+}
+
+// For claims that turned out unusable in this tab, so another tab can still
+// take the ring.
+export function releaseCallAlert(key) {
+ if (!key) {
+ return;
+ }
+
+ writeEntries(readEntries().filter((entry) => entry.key !== key));
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/call-constants.js b/plugins/voice/assets/javascripts/discourse/lib/voice/call-constants.js
new file mode 100644
index 00000000000..fbc3e47cc2c
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/call-constants.js
@@ -0,0 +1,4 @@
+// How long a call rings before giving up, mirrored server-side by
+// Voice::RoomInviter::RING_SECONDS. Payloads carry their own ring_seconds;
+// this is the fallback and the cap for locally started loops.
+export const RING_SECONDS = 60;
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/fullscreen.js b/plugins/voice/assets/javascripts/discourse/lib/voice/fullscreen.js
new file mode 100644
index 00000000000..bdbadefca6d
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/fullscreen.js
@@ -0,0 +1,51 @@
+import { modifier } from "ember-modifier";
+
+function fullscreenElement() {
+ return document.fullscreenElement || document.webkitFullscreenElement || null;
+}
+
+// Toggle fullscreen for an element. Must be called synchronously from a user
+// gesture — the Fullscreen API consumes transient activation just like
+// getDisplayMedia, so the caller has to be a plain click handler, not a
+// DButton (which defers via next()). When `fallbackVideo` is set and the
+// element can't go fullscreen itself, the first descendant <video> is used
+// instead (iOS Safari only allows the media element to go fullscreen).
+export function toggleFullscreen(element, { fallbackVideo = false } = {}) {
+ if (!element) {
+ return;
+ }
+
+ if (fullscreenElement()) {
+ (document.exitFullscreen || document.webkitExitFullscreen)?.call(document);
+ return;
+ }
+
+ if (element.requestFullscreen) {
+ element.requestFullscreen().catch(() => {});
+ } else if (element.webkitRequestFullscreen) {
+ // Safari on macOS.
+ element.webkitRequestFullscreen();
+ } else if (fallbackVideo) {
+ element.querySelector("video")?.webkitEnterFullscreen?.();
+ }
+}
+
+// A single tile can fall back to its own <video> on iOS, where container
+// fullscreen is unsupported.
+export function toggleTileFullscreen(tile) {
+ toggleFullscreen(tile, { fallbackVideo: true });
+}
+
+// Reports whether `element` is the current fullscreen element, updating on
+// every fullscreen change so a tile can flip its enter/exit affordance.
+export const trackFullscreen = modifier((element, [onChange]) => {
+ const update = () => onChange(fullscreenElement() === element);
+
+ document.addEventListener("fullscreenchange", update);
+ document.addEventListener("webkitfullscreenchange", update);
+
+ return () => {
+ document.removeEventListener("fullscreenchange", update);
+ document.removeEventListener("webkitfullscreenchange", update);
+ };
+});
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js
new file mode 100644
index 00000000000..75c4dc91152
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js
@@ -0,0 +1,79 @@
+import { ajax } from "discourse/lib/ajax";
+
+const HEARTBEAT_INTERVAL_MS = 10000;
+
+// Keeps per-room presence alive server-side. A heartbeat rejected with a
+// membership-shaped status means the server no longer recognizes the
+// session; onExpelled lets the caller unwind the call.
+export default class HeartbeatManager {
+ #timers = new Map();
+ #inFlight = new Set();
+
+ #isActiveRoom;
+ #buildPayload;
+ #onExpelled;
+
+ constructor({ isActiveRoom, buildPayload, onExpelled }) {
+ this.#isActiveRoom = isActiveRoom;
+ this.#buildPayload = buildPayload;
+ this.#onExpelled = onExpelled;
+ }
+
+ start(roomId) {
+ if (this.#timers.has(roomId)) {
+ return;
+ }
+
+ const timer = setInterval(() => this.#beat(roomId), HEARTBEAT_INTERVAL_MS);
+ this.#timers.set(roomId, timer);
+ }
+
+ stop(roomId) {
+ const timer = this.#timers.get(roomId);
+ if (timer) {
+ clearInterval(timer);
+ this.#timers.delete(roomId);
+ this.#inFlight.delete(roomId);
+ // eslint-disable-next-line no-console
+ console.log(`[voice] heartbeat stopped for room ${roomId}`);
+ }
+ }
+
+ stopAll() {
+ for (const roomId of [...this.#timers.keys()]) {
+ this.stop(roomId);
+ }
+ }
+
+ async #beat(roomId) {
+ if (!this.#isActiveRoom(roomId)) {
+ this.stop(roomId);
+ return;
+ }
+
+ if (this.#inFlight.has(roomId)) {
+ return;
+ }
+
+ this.#inFlight.add(roomId);
+
+ try {
+ await ajax(`/voice/rooms/${roomId}/heartbeat`, {
+ type: "POST",
+ data: this.#buildPayload(roomId),
+ });
+ // eslint-disable-next-line no-console
+ console.log(`[voice] heartbeat sent for room ${roomId}`);
+ } catch (error) {
+ const status = error?.jqXHR?.status || error?.status;
+ // eslint-disable-next-line no-console
+ console.warn(`[voice] heartbeat failed for room ${roomId}`, error);
+
+ if (status === 403 || status === 404 || status === 410) {
+ this.#onExpelled(roomId);
+ }
+ } finally {
+ this.#inFlight.delete(roomId);
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/idle-tracker.js b/plugins/voice/assets/javascripts/discourse/lib/voice/idle-tracker.js
new file mode 100644
index 00000000000..d717d889c89
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/idle-tracker.js
@@ -0,0 +1,164 @@
+// Site settings express the idle ladder in minutes; a later stage set at or
+// below an earlier one disables the earlier stage rather than firing out of
+// order.
+export function idleThresholds(siteSettings) {
+ let idleMs = siteSettings.voice_idle_threshold_minutes * 60 * 1000;
+ let afkMs = siteSettings.voice_afk_auto_mute_threshold_minutes * 60 * 1000;
+ let disconnectMs =
+ siteSettings.voice_afk_disconnect_threshold_minutes * 60 * 1000;
+
+ if (afkMs > 0 && idleMs > 0 && idleMs >= afkMs) {
+ idleMs = 0;
+ }
+ if (disconnectMs > 0 && afkMs > 0 && afkMs >= disconnectMs) {
+ afkMs = 0;
+ }
+ if (disconnectMs > 0 && idleMs > 0 && idleMs >= disconnectMs) {
+ idleMs = 0;
+ }
+
+ return { idleMs, afkMs, disconnectMs };
+}
+
+export default class IdleTracker {
+ #lastActivityAt = 0;
+ #idleCheckTimerId = null;
+ #activityThrottled = false;
+ #wasAutoMuted = false;
+ #lastBroadcastedIdleState = null;
+ #boundActivityHandler = null;
+ #voiceActivityThrottled = false;
+
+ #onIdleStateChange;
+ #onAutoMute;
+ #onDisconnect;
+ #getThresholds;
+
+ constructor({ onIdleStateChange, onAutoMute, onDisconnect, getThresholds }) {
+ this.#onIdleStateChange = onIdleStateChange;
+ this.#onAutoMute = onAutoMute;
+ this.#onDisconnect = onDisconnect;
+ this.#getThresholds = getThresholds;
+ }
+
+ get wasAutoMuted() {
+ return this.#wasAutoMuted;
+ }
+
+ set wasAutoMuted(value) {
+ this.#wasAutoMuted = value;
+ }
+
+ get lastBroadcastedIdleState() {
+ return this.#lastBroadcastedIdleState;
+ }
+
+ set lastBroadcastedIdleState(value) {
+ this.#lastBroadcastedIdleState = value;
+ }
+
+ start() {
+ if (this.#idleCheckTimerId) {
+ return;
+ }
+
+ this.#lastActivityAt = Date.now();
+ this.#wasAutoMuted = false;
+ this.#lastBroadcastedIdleState = null;
+
+ this.#boundActivityHandler = () => this.resetActivity();
+ const events = [
+ "mousemove",
+ "mousedown",
+ "keydown",
+ "scroll",
+ "touchstart",
+ ];
+ events.forEach((event) => {
+ document.addEventListener(event, this.#boundActivityHandler, {
+ passive: true,
+ });
+ });
+
+ this.#idleCheckTimerId = setInterval(() => this.#check(), 30000);
+ }
+
+ stop() {
+ if (this.#idleCheckTimerId) {
+ clearInterval(this.#idleCheckTimerId);
+ this.#idleCheckTimerId = null;
+ }
+
+ if (this.#boundActivityHandler) {
+ const events = [
+ "mousemove",
+ "mousedown",
+ "keydown",
+ "scroll",
+ "touchstart",
+ ];
+ events.forEach((event) => {
+ document.removeEventListener(event, this.#boundActivityHandler);
+ });
+ this.#boundActivityHandler = null;
+ }
+
+ this.#wasAutoMuted = false;
+ this.#activityThrottled = false;
+ this.#voiceActivityThrottled = false;
+ this.#lastBroadcastedIdleState = null;
+ }
+
+ resetActivity() {
+ if (this.#activityThrottled) {
+ this.#lastActivityAt = Date.now();
+ return;
+ }
+
+ this.#lastActivityAt = Date.now();
+ this.#activityThrottled = true;
+ setTimeout(() => {
+ this.#activityThrottled = false;
+ }, 10000);
+
+ this.#onIdleStateChange("active", this.#wasAutoMuted);
+ }
+
+ onVoiceActivity() {
+ if (this.#voiceActivityThrottled) {
+ return;
+ }
+
+ this.#voiceActivityThrottled = true;
+ setTimeout(() => {
+ this.#voiceActivityThrottled = false;
+ }, 10000);
+
+ this.resetActivity();
+ }
+
+ #check() {
+ const { idleMs, afkMs, disconnectMs } = this.#getThresholds();
+ const elapsed = Date.now() - this.#lastActivityAt;
+
+ if (disconnectMs > 0 && elapsed >= disconnectMs) {
+ this.#onDisconnect();
+ return;
+ }
+
+ if (afkMs > 0 && elapsed >= afkMs) {
+ this.#wasAutoMuted = true;
+ this.#lastBroadcastedIdleState = null;
+ this.#onAutoMute();
+ return;
+ }
+
+ if (idleMs > 0 && elapsed >= idleMs) {
+ this.#lastBroadcastedIdleState = null;
+ this.#onIdleStateChange("idle", false);
+ return;
+ }
+
+ this.#onIdleStateChange("active", false);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/input-gate.js b/plugins/voice/assets/javascripts/discourse/lib/voice/input-gate.js
new file mode 100644
index 00000000000..1065db3afad
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/input-gate.js
@@ -0,0 +1,159 @@
+const SAMPLE_INTERVAL_MS = 50;
+const RELEASE_HOLD_MS = 400;
+const THRESHOLD_STORAGE_KEY = "voice_gate_threshold";
+
+// Full scale for the sensitivity slider and the settings meter, in byte
+// time-domain RMS units (speech peaks land mid-range). Because both the
+// meter and the slider map linearly onto this value, a slider value of N
+// sits at N% of the meter — the threshold marker lines up with no extra
+// conversion.
+export const METER_MAX_RMS = 50;
+
+export function sliderToRms(value) {
+ return (Math.max(0, Math.min(100, value)) / 100) * METER_MAX_RMS;
+}
+
+export function rmsToPercent(rms) {
+ return Math.max(0, Math.min(100, (rms / METER_MAX_RMS) * 100));
+}
+
+export function sampleRms(analyser, dataArray) {
+ analyser.getByteTimeDomainData(dataArray);
+ let sum = 0;
+ for (let i = 0; i < dataArray.length; i++) {
+ const deviation = dataArray[i] - 128;
+ sum += deviation * deviation;
+ }
+ return Math.sqrt(sum / dataArray.length);
+}
+
+// A noise gate for the outgoing mic stream: audio only passes while the
+// input level is above the user's sensitivity threshold. The gate holds
+// open briefly after the level drops so words aren't clipped mid-sentence,
+// and gain changes are ramped to avoid clicks.
+export default class InputGateManager {
+ static storedSliderValue() {
+ try {
+ const stored = parseInt(localStorage.getItem(THRESHOLD_STORAGE_KEY), 10);
+ if (Number.isFinite(stored)) {
+ return Math.max(0, Math.min(100, stored));
+ }
+ } catch {
+ // ignore storage errors
+ }
+ return 0;
+ }
+
+ static storeSliderValue(value) {
+ try {
+ if (value > 0) {
+ localStorage.setItem(THRESHOLD_STORAGE_KEY, String(value));
+ } else {
+ localStorage.removeItem(THRESHOLD_STORAGE_KEY);
+ }
+ } catch {
+ // ignore storage errors
+ }
+ }
+
+ #context = null;
+ #source = null;
+ #analyser = null;
+ #gain = null;
+ #dataArray = null;
+ #sampleTimer = null;
+ #thresholdRms = 0;
+ #open = false;
+ #holdUntil = 0;
+
+ get active() {
+ return this.#context !== null;
+ }
+
+ setup(upstream, thresholdRms) {
+ this.teardown();
+
+ const context = new AudioContext();
+ if (context.state === "suspended") {
+ context.resume().catch(() => {});
+ }
+
+ const source = context.createMediaStreamSource(upstream);
+ const analyser = context.createAnalyser();
+ analyser.fftSize = 512;
+ const gain = context.createGain();
+ const destination = context.createMediaStreamDestination();
+
+ source.connect(analyser);
+ source.connect(gain);
+ gain.connect(destination);
+
+ // Start closed; the first sample above the threshold opens it.
+ gain.gain.value = 0;
+
+ this.#context = context;
+ this.#source = source;
+ this.#analyser = analyser;
+ this.#gain = gain;
+ this.#dataArray = new Uint8Array(analyser.frequencyBinCount);
+ this.#thresholdRms = thresholdRms;
+ this.#open = false;
+ this.#holdUntil = 0;
+
+ this.#sample();
+
+ return destination.stream;
+ }
+
+ setThreshold(thresholdRms) {
+ this.#thresholdRms = thresholdRms;
+ }
+
+ teardown() {
+ if (this.#sampleTimer) {
+ clearTimeout(this.#sampleTimer);
+ this.#sampleTimer = null;
+ }
+
+ if (this.#source) {
+ try {
+ this.#source.disconnect();
+ } catch {
+ // ignore
+ }
+ this.#source = null;
+ }
+
+ if (this.#context) {
+ try {
+ this.#context.close();
+ } catch {
+ // ignore
+ }
+ this.#context = null;
+ }
+
+ this.#analyser = null;
+ this.#gain = null;
+ this.#dataArray = null;
+ this.#open = false;
+ }
+
+ #sample() {
+ const rms = sampleRms(this.#analyser, this.#dataArray);
+ const now = performance.now();
+
+ if (rms >= this.#thresholdRms) {
+ this.#holdUntil = now + RELEASE_HOLD_MS;
+ if (!this.#open) {
+ this.#open = true;
+ this.#gain.gain.setTargetAtTime(1, this.#context.currentTime, 0.005);
+ }
+ } else if (this.#open && now >= this.#holdUntil) {
+ this.#open = false;
+ this.#gain.gain.setTargetAtTime(0, this.#context.currentTime, 0.03);
+ }
+
+ this.#sampleTimer = setTimeout(() => this.#sample(), SAMPLE_INTERVAL_MS);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/invite-ref.js b/plugins/voice/assets/javascripts/discourse/lib/voice/invite-ref.js
new file mode 100644
index 00000000000..e0a65d92d9b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/invite-ref.js
@@ -0,0 +1,19 @@
+// The inviter username carried by an invite URL the user arrived through
+// (/voice/r/:slug/invited-by/:username), held until they actually join that
+// room so the server credits the inviter on a real join, not a page view.
+let pendingInviteRef = null;
+
+export function setPendingInviteRef(roomSlug, username) {
+ pendingInviteRef = { roomSlug, username };
+}
+
+// Returns the inviter username when the pending ref belongs to this room,
+// clearing it either way once the room matches.
+export function consumePendingInviteRef(room) {
+ if (!pendingInviteRef || pendingInviteRef.roomSlug !== room.slug) {
+ return null;
+ }
+ const { username } = pendingInviteRef;
+ pendingInviteRef = null;
+ return username;
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js
new file mode 100644
index 00000000000..5f690572819
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js
@@ -0,0 +1,303 @@
+import { ajax } from "discourse/lib/ajax";
+import LivekitRoomSession from "./livekit-session";
+
+// Owns the livekit sessions for SFU-transport rooms: connecting on join,
+// reconnect/teardown on disconnects, and the roster bookkeeping that mesh
+// rooms get for free from peer churn.
+export default class LivekitCoordinator {
+ #sessions = new Map();
+ // Last-seen roster ids per livekit room. Mesh derives join/leave sounds and
+ // participant cleanup from peer churn; livekit rooms derive both from this
+ // roster diff instead.
+ #rosterIds = new Map();
+
+ #getCurrentUserId;
+ #getParticipantSessionId;
+ #onParticipantSessionRenewed;
+ #getLocalStream;
+ #getLocalVideoTrack;
+ #getLocalScreenAudioTrack;
+ #getLocalVideoKind;
+ #getVideoPublisherCount;
+ #getQualityTiers;
+ #onTrack;
+ #removeRemoteStream;
+ #getRemoteUserIds;
+ #bumpConnectionRevision;
+ #isActiveRoom;
+ #isConnectingRoom;
+ #isJoinCurrent;
+ #leave;
+ #unwindFailedJoin;
+ #showError;
+ #showNotice;
+
+ constructor({
+ getCurrentUserId,
+ getParticipantSessionId = () => undefined,
+ onParticipantSessionRenewed = () => {},
+ getLocalStream,
+ getLocalVideoTrack,
+ getLocalScreenAudioTrack,
+ getLocalVideoKind,
+ getVideoPublisherCount,
+ getQualityTiers,
+ onTrack,
+ removeRemoteStream,
+ getRemoteUserIds,
+ bumpConnectionRevision,
+ isActiveRoom,
+ isConnectingRoom,
+ isJoinCurrent,
+ leave,
+ unwindFailedJoin,
+ showError,
+ showNotice,
+ }) {
+ this.#getCurrentUserId = getCurrentUserId;
+ this.#getParticipantSessionId = getParticipantSessionId;
+ this.#onParticipantSessionRenewed = onParticipantSessionRenewed;
+ this.#getLocalStream = getLocalStream;
+ this.#getLocalVideoTrack = getLocalVideoTrack;
+ this.#getLocalScreenAudioTrack = getLocalScreenAudioTrack;
+ this.#getLocalVideoKind = getLocalVideoKind;
+ this.#getVideoPublisherCount = getVideoPublisherCount;
+ this.#getQualityTiers = getQualityTiers;
+ this.#onTrack = onTrack;
+ this.#removeRemoteStream = removeRemoteStream;
+ this.#getRemoteUserIds = getRemoteUserIds;
+ this.#bumpConnectionRevision = bumpConnectionRevision;
+ this.#isActiveRoom = isActiveRoom;
+ this.#isConnectingRoom = isConnectingRoom;
+ this.#isJoinCurrent = isJoinCurrent;
+ this.#leave = leave;
+ this.#unwindFailedJoin = unwindFailedJoin;
+ this.#showError = showError;
+ this.#showNotice = showNotice;
+ }
+
+ sessionFor(roomId) {
+ return this.#sessions.get(roomId);
+ }
+
+ disconnectRoom(roomId) {
+ this.#rosterIds.delete(roomId);
+
+ const session = this.#sessions.get(roomId);
+ if (session) {
+ this.#sessions.delete(roomId);
+ session.disconnect();
+ }
+ }
+
+ destroy() {
+ this.#sessions.forEach((session) => session.disconnect());
+ this.#sessions.clear();
+ this.#rosterIds.clear();
+ }
+
+ // The server already minted this room's token, so from here a failure is
+ // client-side (firewall blocking the SFU, unsupported browser). Follow the
+ // mic-failure precedent: tell the server we left, then unwind the local
+ // join. Never fall back to mesh client-side — other clients may reach the
+ // SFU fine, and a lone mesh joiner would split future joins.
+ async connect(room, livekit, revision) {
+ let failureMessage = null;
+
+ if (!LivekitRoomSession.isBrowserSupported()) {
+ failureMessage = "voice.livekit.browser_unsupported";
+ } else if (!livekit?.url || !livekit?.token) {
+ failureMessage = "voice.livekit.connect_failed";
+ } else {
+ const session = this.#buildSession(room.id);
+ this.#sessions.set(room.id, session);
+
+ try {
+ await session.connect(livekit.url, livekit.token);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to connect to the media server for room ${room.id}`,
+ error
+ );
+ failureMessage = error?.unsupportedBrowser
+ ? "voice.livekit.browser_unsupported"
+ : "voice.livekit.connect_failed";
+
+ if (this.#sessions.get(room.id) === session) {
+ this.#sessions.delete(room.id);
+ }
+ session.disconnect();
+ }
+ }
+
+ if (failureMessage) {
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: {
+ participant_session_id: this.#getParticipantSessionId(room.id),
+ },
+ });
+ this.#unwindFailedJoin(room.id);
+ this.#showError(failureMessage);
+ return false;
+ }
+
+ if (!this.#isJoinCurrent(revision)) {
+ // Superseded while connecting; the superseding join already tore this
+ // room down (disconnecting the session), so only the server needs
+ // telling.
+ ajax(`/voice/rooms/${room.id}/leave`, {
+ type: "DELETE",
+ data: {
+ participant_session_id: this.#getParticipantSessionId(room.id),
+ },
+ });
+ return false;
+ }
+
+ return true;
+ }
+
+ #buildSession(roomId) {
+ return new LivekitRoomSession({
+ roomId,
+ currentUserId: this.#getCurrentUserId(),
+ getLocalStream: this.#getLocalStream,
+ getLocalVideoTrack: this.#getLocalVideoTrack,
+ getLocalScreenAudioTrack: this.#getLocalScreenAudioTrack,
+ getLocalVideoKind: this.#getLocalVideoKind,
+ getVideoPublisherCount: () => this.#getVideoPublisherCount(roomId),
+ onTrack: (id, userId, track, streams) =>
+ this.#onTrack(id, userId, track, streams),
+ onParticipantGone: (id, userId) => this.#removeRemoteStream(id, userId),
+ onDisconnected: (kind, reason) =>
+ this.#handleDisconnected(roomId, kind, reason),
+ onConnectionChange: () => this.#bumpConnectionRevision(),
+ mintToken: async () => {
+ const response = await ajax(`/voice/rooms/${roomId}/livekit_token`, {
+ type: "POST",
+ });
+ // The token endpoint re-establishes presence, so it rotates the
+ // participant session heartbeat/state must keep sending.
+ this.#onParticipantSessionRenewed(
+ roomId,
+ response?.participant_session_id
+ );
+ return response;
+ },
+ getQualityTiers: () => this.#getQualityTiers(roomId),
+ });
+ }
+
+ async #handleDisconnected(roomId, kind, reason) {
+ const session = this.#sessions.get(roomId);
+ if (!session || !this.#isActiveRoom(roomId)) {
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] disconnected from the media server for room ${roomId} (${reason})`
+ );
+
+ if (kind === "duplicate_identity") {
+ // A newer tab for the same user took over the media session. Its join
+ // overwrote our session id server-side, so a normal leave would close
+ // the new tab's session row and drop the user from the roster —
+ // tear down locally only.
+ this.#leave(roomId, { skipServer: true });
+ this.#showNotice("voice.livekit.duplicate_tab");
+ return;
+ }
+
+ this.#bumpConnectionRevision();
+ const outcome = await session.reconnectWithToken();
+
+ if (outcome === "reconnected") {
+ this.#bumpConnectionRevision();
+ } else if (outcome === "gone") {
+ // The room instance ended while we were disconnected; leave cleanly
+ // and offer a rejoin.
+ this.#leave(roomId);
+ this.#showNotice("voice.livekit.room_ended");
+ } else if (outcome === "failed") {
+ this.#leave(roomId);
+ this.#showError("voice.livekit.reconnect_failed");
+ }
+ // "aborted": the session was torn down (leave, new join) mid-ladder.
+ }
+
+ // Mesh gets participant cleanup for free by destroying peers on the roster
+ // diff. The SFU doesn't consult our roster, so a participant expelled from
+ // it (heartbeat TTL expiry, kick with a failed server-side eviction) would
+ // stay audible forever — voice-canvas plays every stream in
+ // `remoteStreams`. Drop registry entries and subscriptions for identities
+ // absent from the roster, and derive the join/leave sounds mesh derives
+ // from peer churn.
+ syncRoster(roomId, participants) {
+ const currentUserId = this.#getCurrentUserId();
+ const known = this.#rosterIds.get(roomId) || new Set();
+ const next = new Set();
+ let hasNewPeer = false;
+ let hasPeerLeft = false;
+
+ for (const participant of participants) {
+ const participantId = Number(participant?.id);
+ if (
+ !participantId ||
+ participantId <= 0 ||
+ participantId === currentUserId
+ ) {
+ continue;
+ }
+
+ next.add(participantId);
+
+ // Mirror the mesh rule: the initial roster processed while the join is
+ // still connecting represents people already there, not arrivals.
+ if (
+ !known.has(participantId) &&
+ (known.size > 0 || !this.#isConnectingRoom(roomId))
+ ) {
+ hasNewPeer = true;
+ }
+ }
+
+ for (const knownId of known) {
+ if (!next.has(knownId)) {
+ hasPeerLeft = true;
+ }
+ }
+
+ this.#rosterIds.set(roomId, next);
+
+ const session = this.#sessions.get(roomId);
+ for (const entryUserId of this.#getRemoteUserIds(roomId)) {
+ if (
+ entryUserId &&
+ entryUserId !== currentUserId &&
+ !next.has(entryUserId)
+ ) {
+ session?.dropParticipant(entryUserId);
+ this.#removeRemoteStream(roomId, entryUserId);
+ }
+ }
+
+ return { hasNewPeer, hasPeerLeft };
+ }
+
+ async replaceAudioTrack(newTrack) {
+ for (const [roomId, session] of this.#sessions) {
+ try {
+ await session.replaceAudioTrack(newTrack);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to replace the published audio track for room ${roomId}`,
+ error
+ );
+ }
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js
new file mode 100644
index 00000000000..a6bc8bea427
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js
@@ -0,0 +1,686 @@
+// LiveKit room session.
+//
+// One instance per active room on the "livekit" transport, owned by the
+// voice-webrtc service. Bridges the vendored livekit-client SDK to the
+// same callbacks PeerManager uses, so the remote-media registry and every
+// UI component work unchanged on both transports. Callback-injected in the
+// same style as PeerManager; a fake SDK module can be injected via `loadSdk`
+// (or the module-level test override), which is what makes it unit-testable.
+
+import {
+ cameraEncodingFor,
+ screenEncodingFor,
+ voiceBitrateFor,
+} from "./video-quality";
+import { voiceAssetAppUrl } from "./voice-assets";
+
+// The SDK bundle sits in the plugin's public dir, which static asset CDNs
+// never receive. Anchor to the page URL because this compiled chunk may
+// itself be served from a CDN origin, and a dynamic import() of a bare path
+// would resolve against the chunk's origin, not the site's. The loaded
+// module stays resident so rejoins are instant; never evaluated for mesh
+// rooms. The bundle keeps a .js extension (despite being ESM) because
+// module scripts require a JavaScript MIME type and neither Rails' static
+// file server nor stock nginx maps .mjs to one.
+let sdkPromise = null;
+let sdkLoaderOverride = null;
+
+// Reconnect ladder: wait entry N, then mint a fresh token and connect.
+let reconnectDelaysMs = [0, 1000, 2000];
+
+async function defaultLoadSdk() {
+ sdkPromise ||= import(
+ /* @vite-ignore */ voiceAssetAppUrl("livekit/livekit-client.js")
+ );
+
+ try {
+ return await sdkPromise;
+ } catch (error) {
+ // Allow a retry after a transient failure (e.g. offline asset fetch).
+ sdkPromise = null;
+ throw error;
+ }
+}
+
+export function setLivekitSdkLoaderForTesting(loader) {
+ sdkLoaderOverride = loader;
+ sdkPromise = null;
+}
+
+export function setLivekitReconnectDelaysForTesting(delays) {
+ reconnectDelaysMs = delays ?? [0, 1000, 2000];
+}
+
+function wait(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+// Publish ceilings mirror the mesh sender ladder's top rungs for the active
+// quality tier and the capture-time caps; simulcast gives the SFU lower
+// layers to hand to constrained subscribers instead of the mesh's
+// per-watcher encoder ladder. Unlike the mesh, higher tiers here cost the
+// publisher a single encode regardless of viewer count.
+// Content audio: higher Opus ceiling than the speech default so screen audio
+// doesn't sound underwater.
+const SCREEN_AUDIO_BITRATE = 128_000;
+// Camera subscriptions drop to the LOW simulcast layer above this many
+// active video publishers — the same threshold the mesh bitrate ladder uses.
+const LOW_LAYER_PUBLISHER_THRESHOLD = 6;
+
+export default class LivekitRoomSession {
+ // Cheap pre-load check so obviously unsupported browsers fail with a
+ // translated toast instead of a dynamic-import error; the SDK's own
+ // isBrowserSupported() runs again after the bundle loads.
+ static isBrowserSupported() {
+ return (
+ typeof RTCPeerConnection !== "undefined" &&
+ typeof WebSocket !== "undefined"
+ );
+ }
+
+ #roomId;
+ #currentUserId;
+ #loadSdk;
+ #getLocalStream;
+ #getLocalVideoTrack;
+ #getLocalScreenAudioTrack;
+ #getLocalVideoKind;
+ #getVideoPublisherCount;
+ #onTrack;
+ #onParticipantGone;
+ #onDisconnected;
+ #onConnectionChange;
+ #mintToken;
+ #getQualityTiers;
+
+ #sdk = null;
+ #room = null;
+ #micPublication = null;
+ #videoPublication = null;
+ #videoKind = null;
+ #screenAudioPublication = null;
+ #watchingVideo = false;
+ #closed = false;
+ #reconnecting = false;
+
+ constructor({
+ roomId,
+ currentUserId,
+ loadSdk,
+ getLocalStream,
+ getLocalVideoTrack,
+ getLocalScreenAudioTrack,
+ getLocalVideoKind,
+ getVideoPublisherCount,
+ onTrack,
+ onParticipantGone,
+ onDisconnected,
+ onConnectionChange,
+ mintToken,
+ getQualityTiers,
+ }) {
+ this.#roomId = roomId;
+ this.#currentUserId = currentUserId;
+ this.#loadSdk = loadSdk ?? sdkLoaderOverride ?? defaultLoadSdk;
+ this.#getLocalStream = getLocalStream;
+ this.#getLocalVideoTrack = getLocalVideoTrack;
+ this.#getLocalScreenAudioTrack = getLocalScreenAudioTrack;
+ this.#getLocalVideoKind = getLocalVideoKind;
+ this.#getVideoPublisherCount = getVideoPublisherCount;
+ this.#onTrack = onTrack;
+ this.#onParticipantGone = onParticipantGone;
+ this.#onDisconnected = onDisconnected;
+ this.#onConnectionChange = onConnectionChange;
+ this.#mintToken = mintToken;
+ this.#getQualityTiers = getQualityTiers;
+ }
+
+ // Effective tiers already clamped by the service (user choice vs room and
+ // site caps). Read at publish time, so a changed preference applies on the
+ // next publish without renegotiating current ones.
+ #qualityTiers() {
+ return this.#getQualityTiers?.() ?? {};
+ }
+
+ async connect(wsUrl, token) {
+ this.#sdk ||= await this.#loadSdk();
+
+ if (
+ typeof this.#sdk.isBrowserSupported === "function" &&
+ !this.#sdk.isBrowserSupported()
+ ) {
+ const error = new Error("LiveKit is not supported in this browser");
+ error.unsupportedBrowser = true;
+ throw error;
+ }
+
+ // adaptiveStream keys quality off attached-element visibility, which is
+ // incompatible with service-owned elements (it would pause "invisible"
+ // video); subscriber-side quality is managed explicitly instead.
+ const room = new this.#sdk.Room({
+ adaptiveStream: false,
+ dynacast: true,
+ });
+
+ this.#wireRoomEvents(room);
+
+ try {
+ await room.connect(wsUrl, token);
+ } catch (error) {
+ room.removeAllListeners?.();
+ throw error;
+ }
+
+ // The session may have been torn down while the connect was in flight
+ // (superseded join, leave); adopting the room now would leave a ghost
+ // connection to the SFU that nothing owns.
+ if (this.#closed) {
+ room.removeAllListeners?.();
+ try {
+ await room.disconnect();
+ } catch {
+ // Nothing to clean up.
+ }
+ return;
+ }
+
+ this.#room = room;
+ this.#micPublication = null;
+ this.#videoPublication = null;
+ this.#videoKind = null;
+ this.#screenAudioPublication = null;
+ await this.#publishMicrophone();
+
+ // A ladder reconnect lands on a fresh Room; whatever camera or screen
+ // share was live before the drop must be republished.
+ await this.syncLocalVideo(
+ this.#getLocalVideoTrack?.(),
+ this.#getLocalScreenAudioTrack?.(),
+ this.#getLocalVideoKind?.()
+ );
+ }
+
+ async disconnect() {
+ this.#closed = true;
+ const room = this.#room;
+ this.#room = null;
+ this.#micPublication = null;
+ this.#videoPublication = null;
+ this.#videoKind = null;
+ this.#screenAudioPublication = null;
+
+ try {
+ await room?.disconnect();
+ } catch {
+ // The room may already be closed; nothing to clean up.
+ }
+ }
+
+ // NS toggle, mic device switch, and gate crossings produce a brand-new
+ // outgoing track; move the live publication onto it.
+ async replaceAudioTrack(track) {
+ if (!this.#room || !track) {
+ return;
+ }
+
+ if (this.#micPublication?.track) {
+ await this.#micPublication.track.replaceTrack(track);
+ } else {
+ await this.#publishMicrophone();
+ }
+ }
+
+ // Brings the video and screen-audio publications in line with the local
+ // capture state. The mesh equivalent gates per watching peer; on the SFU
+ // media is published once and receive gating moves to the subscriber side.
+ async syncLocalVideo(videoTrack, screenAudioTrack, kind) {
+ if (!this.#room) {
+ return;
+ }
+
+ await this.#syncVideoPublication(videoTrack ?? null, kind ?? null);
+ await this.#syncScreenAudioPublication(
+ videoTrack ? (screenAudioTrack ?? null) : null
+ );
+ }
+
+ // Receive gating for the watching state: non-watchers unsubscribe from
+ // camera, screen, and screen-audio publications so they cost no downlink.
+ // Microphones are never gated. Publications created while not watching are
+ // caught by the TrackPublished and TrackSubscribed handlers.
+ setVideoSubscriptionsEnabled(watching) {
+ this.#watchingVideo = !!watching;
+
+ this.#room?.remoteParticipants?.forEach((participant) => {
+ participant.trackPublications?.forEach((publication) => {
+ this.#applyDesiredSubscription(publication);
+ });
+ });
+ }
+
+ // Re-picks simulcast layers for current subscriptions; called when the
+ // room's video publisher count changes.
+ updateSubscriberQuality() {
+ this.#room?.remoteParticipants?.forEach((participant) => {
+ participant.trackPublications?.forEach((publication) => {
+ if (publication?.isSubscribed) {
+ this.#applySubscriberQuality(publication);
+ }
+ });
+ });
+ }
+
+ // Role changes flip whether the local user may hold a live microphone
+ // publication; re-evaluate against the current local stream. The media
+ // session itself survives the role change (unlike mesh peer rebuilds).
+ async refreshPublications() {
+ if (!this.#room) {
+ return;
+ }
+
+ const track = this.#getLocalStream?.()?.getAudioTracks?.()?.[0];
+
+ if (!track) {
+ const publication = this.#micPublication;
+ this.#micPublication = null;
+ await this.#unpublish(publication);
+ return;
+ }
+
+ if (this.#micPublication?.track) {
+ if (this.#micPublication.track.mediaStreamTrack !== track) {
+ await this.#micPublication.track.replaceTrack(track);
+ }
+ return;
+ }
+
+ await this.#publishMicrophone();
+ }
+
+ // The SFU doesn't consult the plugin's roster, so a participant expelled
+ // from it can still hold live subscriptions; drop them explicitly.
+ dropParticipant(userId) {
+ const participant = this.#room?.remoteParticipants?.get(String(userId));
+
+ participant?.trackPublications?.forEach((publication) => {
+ try {
+ publication.setSubscribed(false);
+ } catch {
+ // Already unsubscribed or tearing down.
+ }
+ });
+ }
+
+ // Terminal-disconnect recovery: up to three attempts, each awaiting a
+ // freshly minted token (the old one is likely past its 10-minute TTL).
+ // Resolves "reconnected", "gone" (server says the room instance ended),
+ // "aborted" (session torn down mid-ladder), or "failed" (exhausted).
+ async reconnectWithToken() {
+ if (this.#reconnecting) {
+ return "failed";
+ }
+ this.#reconnecting = true;
+
+ try {
+ for (const delayMs of reconnectDelaysMs) {
+ if (delayMs > 0) {
+ await wait(delayMs);
+ }
+ if (this.#closed) {
+ return "aborted";
+ }
+
+ let minted;
+ try {
+ minted = await this.#mintToken();
+ } catch (error) {
+ if ((error?.jqXHR?.status ?? error?.status) === 410) {
+ return "gone";
+ }
+ continue;
+ }
+
+ if (this.#closed) {
+ return "aborted";
+ }
+
+ try {
+ await this.connect(minted.url, minted.token);
+ return this.#closed ? "aborted" : "reconnected";
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] reconnect attempt failed for room ${this.#roomId}`,
+ error
+ );
+ }
+ }
+
+ return this.#closed ? "aborted" : "failed";
+ } finally {
+ this.#reconnecting = false;
+ }
+ }
+
+ async #syncVideoPublication(track, kind) {
+ // A camera→screen switch changes the publication source, so the old
+ // publication can't be retracked in place.
+ if (this.#videoPublication && (!track || this.#videoKind !== kind)) {
+ const publication = this.#videoPublication;
+ this.#videoPublication = null;
+ this.#videoKind = null;
+ await this.#unpublish(publication);
+ }
+
+ if (!track || !kind) {
+ return;
+ }
+
+ if (this.#videoPublication?.track) {
+ // Same kind, new track: device switch or blur pipeline swap.
+ if (this.#videoPublication.track.mediaStreamTrack !== track) {
+ await this.#videoPublication.track.replaceTrack(track);
+ }
+ return;
+ }
+
+ const { Track } = this.#sdk;
+ const tiers = this.#qualityTiers();
+ const encoding =
+ kind === "screen"
+ ? screenEncodingFor(tiers.screen)
+ : cameraEncodingFor(tiers.camera);
+ const livekitEncoding = {
+ maxBitrate: encoding.maxBitrate,
+ maxFramerate: encoding.maxFramerate,
+ };
+ const options =
+ kind === "screen"
+ ? {
+ source: Track.Source.ScreenShare,
+ simulcast: true,
+ screenShareEncoding: livekitEncoding,
+ }
+ : {
+ source: Track.Source.Camera,
+ simulcast: true,
+ videoEncoding: livekitEncoding,
+ };
+
+ try {
+ this.#videoPublication = await this.#room.localParticipant.publishTrack(
+ track,
+ options
+ );
+ this.#videoKind = kind;
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to publish ${kind} video for room ${this.#roomId}`,
+ error
+ );
+ }
+ }
+
+ async #syncScreenAudioPublication(track) {
+ const current = this.#screenAudioPublication;
+ if (current && current.track?.mediaStreamTrack !== track) {
+ this.#screenAudioPublication = null;
+ await this.#unpublish(current);
+ }
+
+ if (!track || this.#screenAudioPublication) {
+ return;
+ }
+
+ try {
+ this.#screenAudioPublication =
+ await this.#room.localParticipant.publishTrack(track, {
+ source: this.#sdk.Track.Source.ScreenShareAudio,
+ // DTX is tuned for speech pauses and would gate content audio.
+ dtx: false,
+ audioBitrate: SCREEN_AUDIO_BITRATE,
+ });
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to publish screen audio for room ${this.#roomId}`,
+ error
+ );
+ }
+ }
+
+ async #unpublish(publication) {
+ if (!publication?.track || !this.#room) {
+ return;
+ }
+
+ try {
+ // The service owns capture-track lifecycle; never stop on unpublish
+ // (a blur pipeline may still be feeding the track).
+ await this.#room.localParticipant.unpublishTrack(
+ publication.track,
+ false
+ );
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to unpublish a track for room ${this.#roomId}`,
+ error
+ );
+ }
+ }
+
+ #isWatchGatedSource(source) {
+ const { Track } = this.#sdk;
+ return (
+ source === Track.Source.Camera ||
+ source === Track.Source.ScreenShare ||
+ source === Track.Source.ScreenShareAudio
+ );
+ }
+
+ #applyDesiredSubscription(publication) {
+ if (!this.#isWatchGatedSource(publication?.source)) {
+ return;
+ }
+
+ try {
+ publication.setSubscribed(this.#watchingVideo);
+ } catch {
+ // The publication is tearing down; nothing to gate.
+ }
+ }
+
+ // With adaptiveStream off the SDK would leave every subscription on the
+ // HIGH simulcast layer, regressing downlink vs the mesh ladder in big
+ // rooms; pick layers explicitly instead.
+ #applySubscriberQuality(publication) {
+ const { Track, VideoQuality } = this.#sdk;
+
+ let quality;
+ if (publication?.source === Track.Source.ScreenShare) {
+ quality = VideoQuality.HIGH;
+ } else if (publication?.source === Track.Source.Camera) {
+ const publisherCount = this.#getVideoPublisherCount?.() ?? 0;
+ quality =
+ publisherCount > LOW_LAYER_PUBLISHER_THRESHOLD
+ ? VideoQuality.LOW
+ : VideoQuality.MEDIUM;
+ } else {
+ return;
+ }
+
+ try {
+ publication.setVideoQuality(quality);
+ } catch {
+ // The publication is tearing down; the next subscription re-applies.
+ }
+ }
+
+ #userIdFrom(participant) {
+ // LiveKit identity is String(user.id); registry keys must be numeric so
+ // remoteStreamFor(roomId, userId) matches roster participant ids.
+ const userId = Number(participant?.identity);
+ if (!Number.isFinite(userId) || userId <= 0) {
+ return null;
+ }
+ return userId === this.#currentUserId ? null : userId;
+ }
+
+ #wireRoomEvents(room) {
+ const { RoomEvent, Track, DisconnectReason } = this.#sdk;
+
+ room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
+ const userId = this.#userIdFrom(participant);
+ if (!userId) {
+ return;
+ }
+
+ // Auto-subscribe can deliver watch-gated media before the gate applies
+ // (publications that already existed when the room connected); drop the
+ // subscription instead of registering a soundtrack or video nobody is
+ // watching.
+ if (
+ this.#isWatchGatedSource(publication?.source) &&
+ !this.#watchingVideo
+ ) {
+ this.#applyDesiredSubscription(publication);
+ return;
+ }
+
+ if (track.kind === "video") {
+ this.#applySubscriberQuality(publication);
+ }
+
+ // A bare audio track (empty streams argument) is how screen audio is
+ // told apart from mic audio in #registerRemoteTrack; every other kind
+ // must arrive with a stream attached.
+ const isScreenAudio =
+ publication?.source === Track.Source.ScreenShareAudio;
+ const streams = isScreenAudio
+ ? []
+ : [track.mediaStream ?? new MediaStream()];
+
+ this.#onTrack(this.#roomId, userId, track.mediaStreamTrack, streams);
+ });
+
+ room.on(RoomEvent.TrackPublished, (publication) => {
+ // A camera or screen published while this client isn't watching must
+ // start unsubscribed; auto-subscribe only covers what existed at
+ // connect time.
+ this.#applyDesiredSubscription(publication);
+ });
+
+ room.on(RoomEvent.ParticipantPermissionsChanged, (_prev, participant) => {
+ if (participant !== room.localParticipant) {
+ return;
+ }
+
+ // A server-side permission update (e.g. a promotion synced by the
+ // backend) lets the mic publish without a reconnect.
+ this.refreshPublications().catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to refresh publications for room ${this.#roomId}`,
+ error
+ );
+ });
+ });
+
+ room.on(RoomEvent.TrackUnsubscribed, (track, publication, participant) => {
+ const userId = this.#userIdFrom(participant);
+ if (!userId) {
+ return;
+ }
+
+ // Losing the microphone (server-side unpublish, e.g. a permission
+ // revocation) drops the participant's media entry; it is rebuilt from
+ // scratch if the mic is ever re-subscribed. Video and screen-audio
+ // subscriptions come and go with watching state, so they must not
+ // tear the entry down.
+ if (publication?.source === Track.Source.Microphone) {
+ this.#onParticipantGone(this.#roomId, userId);
+ }
+ });
+
+ room.on(RoomEvent.ParticipantDisconnected, (participant) => {
+ const userId = this.#userIdFrom(participant);
+ if (userId) {
+ this.#onParticipantGone(this.#roomId, userId);
+ }
+ });
+
+ room.on(RoomEvent.Disconnected, (reason) => {
+ if (room !== this.#room || this.#closed) {
+ return;
+ }
+
+ this.#room = null;
+ this.#micPublication = null;
+ this.#videoPublication = null;
+ this.#videoKind = null;
+ this.#screenAudioPublication = null;
+
+ if (reason === DisconnectReason.CLIENT_INITIATED) {
+ return;
+ }
+
+ const kind =
+ reason === DisconnectReason.DUPLICATE_IDENTITY
+ ? "duplicate_identity"
+ : "terminal";
+ this.#onDisconnected(kind, DisconnectReason[reason] ?? String(reason));
+ });
+
+ room.on(RoomEvent.Reconnecting, () => {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice-livekit] connection interrupted for room ${this.#roomId}; SDK is resuming`
+ );
+ this.#onConnectionChange("reconnecting");
+ });
+
+ room.on(RoomEvent.Reconnected, () => {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice-livekit] connection resumed for room ${this.#roomId}`
+ );
+ this.#onConnectionChange("connected");
+ });
+ }
+
+ async #publishMicrophone() {
+ const track = this.#getLocalStream?.()?.getAudioTracks?.()?.[0];
+ if (!track || !this.#room) {
+ return;
+ }
+
+ try {
+ // The pipeline's processed tracks publish as-is; mute/PTT keep
+ // flipping track.enabled, so the SFU carries DTX-suppressed silence
+ // instead of a mute/unmute renegotiation.
+ const micOptions = {
+ source: this.#sdk.Track.Source.Microphone,
+ dtx: true,
+ red: true,
+ };
+ const voiceBitrate = voiceBitrateFor(this.#qualityTiers().voice);
+ if (voiceBitrate) {
+ micOptions.audioBitrate = voiceBitrate;
+ }
+ this.#micPublication = await this.#room.localParticipant.publishTrack(
+ track,
+ micOptions
+ );
+ } catch (error) {
+ // A rejected publish (e.g. a stale token after a role change) must
+ // not fail the join — the user can still listen.
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to publish microphone for room ${this.#roomId}`,
+ error
+ );
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/local-audio-pipeline.js b/plugins/voice/assets/javascripts/discourse/lib/voice/local-audio-pipeline.js
new file mode 100644
index 00000000000..cd82df210ee
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/local-audio-pipeline.js
@@ -0,0 +1,405 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ autoGainControlPreferred,
+ echoCancellationPreferred,
+ isAiMode,
+ preferredNoiseSuppressionMode,
+ setAutoGainControlPreferred,
+ setEchoCancellationPreferred,
+ setPreferredNoiseSuppressionMode,
+} from "./audio-processing";
+import InputGateManager, { sliderToRms } from "./input-gate";
+import {
+ audioConstraints,
+ preferredInputDeviceId,
+ setPreferredInputDeviceId,
+} from "./media-devices";
+import NoiseSuppressionManager, { SupersededError } from "./noise-suppression";
+import { engineForMode } from "./ns-engines";
+
+// Owns the local microphone pipeline: raw mic (with the browser's echo
+// cancellation / auto gain / native noise suppression applied per the stored
+// preferences) → optional AI noise suppression → optional input gate → the
+// published `stream`. All restructures of the pipeline (device switch,
+// processing changes, suppression mode, gate crossing zero) notify the
+// service so it can re-sync monitors and move peers onto the new track.
+export default class LocalAudioPipeline {
+ // "none" | "standard" (browser native) | "ai:<engine>" (see ns-engines.js).
+ @tracked noiseSuppressionMode = preferredNoiseSuppressionMode();
+
+ // "off" | "starting" | "on" — the AI worklet's lifecycle; "on" means the
+ // ready handshake confirmed it is filtering. Always "off" outside AI modes.
+ @tracked noiseSuppressionState = "off";
+
+ @tracked echoCancellation = echoCancellationPreferred();
+ @tracked autoGainControl = autoGainControlPreferred();
+ @tracked stream = null;
+ @tracked gateThreshold = InputGateManager.storedSliderValue();
+ @tracked inputDeviceId = preferredInputDeviceId();
+
+ // Why the last acquisition failed (a getUserMedia DOMException); lets the
+ // service distinguish a browser-level permission block from a missing or
+ // busy device. Null after a successful acquisition.
+ lastAcquisitionError = null;
+
+ #rawStream = null;
+ #upstream = null;
+ #noiseSuppression;
+ #inputGate;
+ #onStreamChanged;
+ #onSuppressionFailed;
+ #replaceTrackOnPeers;
+
+ // Serializes every pipeline restructure. Suppression setup awaits a
+ // multi-second worklet handshake, and restructures can be triggered from
+ // several controls at once; interleaving a mode change with a device
+ // switch corrupts which stream peers end up on.
+ #queue = Promise.resolve();
+
+ constructor({ onStreamChanged, onSuppressionFailed, replaceTrackOnPeers }) {
+ this.#onStreamChanged = onStreamChanged;
+ this.#onSuppressionFailed = onSuppressionFailed;
+ this.#replaceTrackOnPeers = replaceTrackOnPeers;
+
+ this.#noiseSuppression = new NoiseSuppressionManager({
+ onRuntimeFailure: () => this.#handleSuppressionRuntimeFailure(),
+ });
+
+ this.#inputGate = new InputGateManager();
+ }
+
+ get noiseSuppressionEnabled() {
+ return this.noiseSuppressionState === "on";
+ }
+
+ #serialize(task) {
+ const run = this.#queue.then(task, task);
+ this.#queue = run.then(
+ () => {},
+ () => {}
+ );
+ return run;
+ }
+
+ acquireMicrophone() {
+ return this.#serialize(() => this.#acquireMicrophone());
+ }
+
+ async #acquireMicrophone() {
+ try {
+ const rawStream = await navigator.mediaDevices.getUserMedia({
+ audio: audioConstraints(this.inputDeviceId),
+ });
+ this.lastAcquisitionError = null;
+ // eslint-disable-next-line no-console
+ console.log("[voice] local stream obtained");
+
+ this.#rawStream = rawStream;
+
+ try {
+ // A failed DTLN setup here is transient (the preference survives;
+ // the next acquisition retries) and already fell back to the raw
+ // stream, which has native suppression off in AI mode — no reacquire
+ // mid-join, the user can flip the mode if it persists.
+ await this.#buildProcessedStream(rawStream);
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ return true;
+ }
+ throw error;
+ }
+
+ return true;
+ } catch (error) {
+ this.lastAcquisitionError = error;
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to obtain local stream", error);
+ return false;
+ }
+ }
+
+ setNoiseSuppressionMode(mode) {
+ return this.#serialize(() => this.#setNoiseSuppressionMode(mode));
+ }
+
+ async #setNoiseSuppressionMode(mode) {
+ if (mode === this.noiseSuppressionMode) {
+ return;
+ }
+
+ const previousMode = this.noiseSuppressionMode;
+ this.noiseSuppressionMode = mode;
+ setPreferredNoiseSuppressionMode(mode);
+
+ // Without a live mic the stored preference applies on next acquisition.
+ if (!this.#rawStream) {
+ return;
+ }
+
+ let reacquired;
+ try {
+ // Native suppression is part of the getUserMedia constraints, so any
+ // mode change needs a fresh capture, not just a graph restructure.
+ reacquired = await this.#reacquire({ userGesture: true });
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ return;
+ }
+ // Capture failed: the current stream is untouched, so just undo the
+ // preference.
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to apply noise suppression mode", error);
+ this.noiseSuppressionMode = previousMode;
+ setPreferredNoiseSuppressionMode(previousMode);
+ return;
+ }
+
+ if (reacquired) {
+ // eslint-disable-next-line no-console
+ console.log(`[voice] noise suppression mode: ${mode}`);
+ return;
+ }
+
+ // AI setup failed on an explicit user action: put the preference back
+ // and tell them, mirroring the old toggle's revert behavior.
+ this.noiseSuppressionMode = previousMode;
+ setPreferredNoiseSuppressionMode(previousMode);
+ this.#onSuppressionFailed();
+ try {
+ await this.#reacquire({ userGesture: true });
+ } catch (error) {
+ if (!(error instanceof SupersededError)) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to restore previous mode", error);
+ }
+ }
+ }
+
+ setEchoCancellation(enabled) {
+ return this.#serialize(() => {
+ this.echoCancellation = enabled;
+ setEchoCancellationPreferred(enabled);
+ return this.#reacquireQuietly();
+ });
+ }
+
+ setAutoGainControl(enabled) {
+ return this.#serialize(() => {
+ this.autoGainControl = enabled;
+ setAutoGainControlPreferred(enabled);
+ return this.#reacquireQuietly();
+ });
+ }
+
+ setInputDevice(deviceId) {
+ return this.#serialize(() => this.#setInputDevice(deviceId));
+ }
+
+ async #setInputDevice(deviceId) {
+ const previousDeviceId = this.inputDeviceId;
+ this.inputDeviceId = deviceId;
+ setPreferredInputDeviceId(deviceId);
+
+ if (!this.#rawStream) {
+ return true;
+ }
+
+ try {
+ await this.#reacquire({ userGesture: true, exactDevice: true });
+ return true;
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ return true;
+ }
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to switch input device", error);
+ this.inputDeviceId = previousDeviceId;
+ setPreferredInputDeviceId(previousDeviceId);
+ return false;
+ }
+ }
+
+ async setGateThreshold(value) {
+ const clamped = Math.max(0, Math.min(100, Math.round(value)));
+ this.gateThreshold = clamped;
+ InputGateManager.storeSliderValue(clamped);
+
+ if (!this.#upstream) {
+ return;
+ }
+
+ // Adjusting an already-running gate is just a new compare value; only
+ // crossing zero (gate off ↔ on) restructures the pipeline and needs the
+ // peers' senders updated.
+ if (this.#inputGate.active && clamped > 0) {
+ this.#inputGate.setThreshold(sliderToRms(clamped));
+ return;
+ }
+ if (!this.#inputGate.active && clamped === 0) {
+ return;
+ }
+
+ this.#setOutgoingStream(this.#upstream);
+ await this.#replaceTrackOnPeers();
+ }
+
+ // Intentionally synchronous and not serialized: leaving the room must take
+ // effect immediately. teardown() bumps the suppression epoch, so any
+ // in-flight setup unwinds as superseded instead of publishing a stream.
+ stop() {
+ this.#noiseSuppression.teardown();
+ this.noiseSuppressionState = "off";
+ this.#inputGate.teardown();
+ this.#upstream = null;
+
+ if (this.#rawStream) {
+ this.#rawStream.getTracks().forEach((track) => track.stop());
+ this.#rawStream = null;
+ }
+
+ if (this.stream) {
+ this.stream.getTracks().forEach((track) => track.stop());
+ this.stream = null;
+ }
+
+ this.#onStreamChanged();
+ }
+
+ // Captures a fresh raw stream under the current constraints and rebuilds
+ // the processed pipeline on it. Returns false when the DTLN setup failed
+ // (the raw stream is published instead); throws SupersededError or
+ // getUserMedia errors.
+ async #reacquire({ userGesture = false, exactDevice = false } = {}) {
+ const newRawStream = await navigator.mediaDevices.getUserMedia({
+ audio: audioConstraints(this.inputDeviceId, { exact: exactDevice }),
+ });
+
+ const oldRawStream = this.#rawStream;
+ this.#rawStream = newRawStream;
+
+ let suppressionOk;
+ try {
+ suppressionOk = await this.#buildProcessedStream(newRawStream, {
+ userGesture,
+ });
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ // The superseding restructure owns the published stream; this
+ // capture is going nowhere.
+ newRawStream.getTracks().forEach((track) => track.stop());
+ }
+ throw error;
+ }
+
+ oldRawStream?.getTracks().forEach((track) => track.stop());
+ await this.#replaceTrackOnPeers();
+ return suppressionOk;
+ }
+
+ // For EC/AGC changes: a capture failure just keeps the current stream (the
+ // preference still applies on the next acquisition).
+ async #reacquireQuietly() {
+ if (!this.#rawStream) {
+ return;
+ }
+ try {
+ await this.#reacquire({ userGesture: true });
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ return;
+ }
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to apply audio processing change", error);
+ }
+ }
+
+ // Builds suppression + gate on top of a raw stream and publishes the
+ // result. Returns false when AI mode was requested but the worklet setup
+ // failed (raw stream published as fallback). Throws SupersededError.
+ async #buildProcessedStream(rawStream, { userGesture = false } = {}) {
+ this.#noiseSuppression.teardown();
+
+ const engine = engineForMode(this.noiseSuppressionMode);
+ if (!engine) {
+ this.noiseSuppressionState = "off";
+ this.#setOutgoingStream(rawStream);
+ return true;
+ }
+
+ this.noiseSuppressionState = "starting";
+ try {
+ const suppressed = await this.#noiseSuppression.setup(rawStream, engine, {
+ userGesture,
+ });
+ this.noiseSuppressionState = "on";
+ this.#setOutgoingStream(suppressed);
+ // eslint-disable-next-line no-console
+ console.log("[voice] AI noise suppression enabled");
+ return true;
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ throw error;
+ }
+ // eslint-disable-next-line no-console
+ console.warn("[voice] AI noise suppression setup failed", error);
+ this.noiseSuppressionState = "off";
+ this.#setOutgoingStream(rawStream);
+ return false;
+ }
+ }
+
+ // The worklet reported a mid-call breakdown (repeated engine failures or a
+ // late init error): drop back to standard suppression so peers don't keep
+ // listening through a dead passthrough graph or an unfiltered mic.
+ #handleSuppressionRuntimeFailure() {
+ this.#serialize(async () => {
+ if (!isAiMode(this.noiseSuppressionMode) || !this.#rawStream) {
+ return;
+ }
+ this.noiseSuppressionMode = "standard";
+ setPreferredNoiseSuppressionMode("standard");
+ this.#onSuppressionFailed();
+ try {
+ await this.#reacquire();
+ } catch (error) {
+ if (error instanceof SupersededError) {
+ return;
+ }
+ // Capture failed: publish what we still have rather than nothing.
+ // eslint-disable-next-line no-console
+ console.warn(
+ "[voice] failed to reacquire after suppression breakdown",
+ error
+ );
+ this.#noiseSuppression.teardown();
+ this.noiseSuppressionState = "off";
+ this.#setOutgoingStream(this.#rawStream);
+ await this.#replaceTrackOnPeers();
+ }
+ });
+ }
+
+ // Final hop of the pipeline: the `upstream` argument is the raw mic or the
+ // noise-suppressed stream; the gate wraps it when enabled.
+ #setOutgoingStream(upstream) {
+ this.#upstream = upstream;
+ this.#inputGate.teardown();
+
+ let stream = upstream;
+ if (upstream && this.gateThreshold > 0) {
+ try {
+ stream = this.#inputGate.setup(
+ upstream,
+ sliderToRms(this.gateThreshold)
+ );
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to set up input gate", error);
+ stream = upstream;
+ }
+ }
+
+ this.stream = stream;
+ this.#onStreamChanged();
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/local-video-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/local-video-manager.js
new file mode 100644
index 00000000000..1dec8a72fbd
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/local-video-manager.js
@@ -0,0 +1,732 @@
+import { tracked } from "@glimmer/tracking";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import BackgroundBlurManager from "./background-blur";
+import {
+ cameraConstraints,
+ preferredVideoInputDeviceId,
+ setPreferredVideoInputDeviceId,
+} from "./media-devices";
+import PeerManager from "./peer-manager";
+import { SCREEN_CONTENT_MOTION } from "./quality-preferences";
+import {
+ applyScreenAudioQuality,
+ applyVideoQuality,
+ screenCaptureFramerate,
+} from "./video-quality";
+
+// Owns the local video pipeline: camera/screen capture, the optional
+// background-blur wrap, device switching, per-peer sender sync and the
+// is_video_on/is_screen_sharing state broadcast.
+export default class LocalVideoManager {
+ @tracked stream = null;
+ @tracked kind = null;
+ @tracked blurEnabled = BackgroundBlurManager.isPreferred();
+ @tracked blurAmount = BackgroundBlurManager.storedAmount();
+ @tracked inputDeviceId = preferredVideoInputDeviceId();
+
+ #rawStream = null;
+ #backgroundBlur = null;
+
+ // All async mutations of the video pipeline (blur toggle, device switch)
+ // run through this queue so they can't interleave, and each op validates
+ // the epoch after every await so a camera stop/restart during the await
+ // (which can take seconds on first model load) is detected instead of
+ // resurrecting streams that were already stopped.
+ #queue = Promise.resolve();
+ #epoch = 0;
+
+ #peerManager;
+ #getParticipantSessionId;
+ #getLivekitSession;
+ #isMeshRoom;
+ #isActiveRoom;
+ #isConnectingRoom;
+ #getFirstActiveRoomId;
+ #getActiveRoomId;
+ #getRoom;
+ #canPublishVideo;
+ #getCameraQuality;
+ #getScreenQuality;
+ #getScreenContent;
+ #isBlurAllowed;
+ #setParticipantVideoState;
+ #showError;
+
+ constructor(options) {
+ this.#peerManager = options.peerManager;
+ this.#getParticipantSessionId =
+ options.getParticipantSessionId ?? (() => undefined);
+ this.#getLivekitSession = options.getLivekitSession;
+ this.#isMeshRoom = options.isMeshRoom;
+ this.#isActiveRoom = options.isActiveRoom;
+ this.#isConnectingRoom = options.isConnectingRoom;
+ this.#getFirstActiveRoomId = options.getFirstActiveRoomId;
+ this.#getActiveRoomId = options.getActiveRoomId;
+ this.#getRoom = options.getRoom;
+ this.#canPublishVideo = options.canPublishVideo;
+ this.#getCameraQuality = options.getCameraQuality;
+ this.#getScreenQuality = options.getScreenQuality;
+ this.#getScreenContent = options.getScreenContent;
+ this.#isBlurAllowed = options.isBlurAllowed;
+ this.#setParticipantVideoState = options.setParticipantVideoState;
+ this.#showError = options.showError;
+ }
+
+ get blurSupported() {
+ return BackgroundBlurManager.isSupported();
+ }
+
+ get track() {
+ return this.stream?.getVideoTracks()?.[0] || null;
+ }
+
+ get screenAudioTrack() {
+ if (this.kind !== "screen") {
+ return null;
+ }
+ return this.stream?.getAudioTracks()?.[0] || null;
+ }
+
+ trackFor(roomId, remoteUserId) {
+ const track = this.track;
+ if (!track) {
+ return null;
+ }
+
+ if (!this.#isActiveRoom(roomId) && !this.#isConnectingRoom(roomId)) {
+ return null;
+ }
+
+ const room = this.#getRoom(roomId);
+ const participant = (room?.active_participants || []).find(
+ (entry) => Number(entry?.id) === Number(remoteUserId)
+ );
+
+ return participant?.watching_video ? track : null;
+ }
+
+ screenAudioTrackFor(roomId, remoteUserId) {
+ if (!this.screenAudioTrack) {
+ return null;
+ }
+ return this.trackFor(roomId, remoteUserId) ? this.screenAudioTrack : null;
+ }
+
+ destroy() {
+ this.stream?.getTracks().forEach((track) => track.stop());
+ this.stream = null;
+ this.kind = null;
+ this.#teardownEffects();
+ }
+
+ async toggleCamera() {
+ if (this.kind === "camera") {
+ await this.stop();
+ return;
+ }
+
+ await this.start("camera");
+ }
+
+ async toggleScreenShare() {
+ if (this.kind === "screen") {
+ await this.stop();
+ return;
+ }
+
+ await this.start("screen");
+ }
+
+ #enqueueOp(operation) {
+ const run = this.#queue.then(operation, operation);
+ this.#queue = run.catch(() => {});
+ return run;
+ }
+
+ toggleBlur() {
+ return this.#enqueueOp(() => this.#toggleBlurOp());
+ }
+
+ async #toggleBlurOp() {
+ const enabled = !this.blurEnabled;
+ this.blurEnabled = enabled;
+ BackgroundBlurManager.setPreference(enabled);
+ await this.#reconcileBlurOp();
+ }
+
+ // Brings the pipeline in line with the current preference: wraps or
+ // unwraps the published camera stream. A no-op when the camera is off
+ // (the preference simply applies at the next camera start) or when the
+ // pipeline already matches.
+ async #reconcileBlurOp() {
+ if (this.kind !== "camera") {
+ return;
+ }
+
+ const wantBlur =
+ this.blurEnabled && this.#isBlurAllowed() && this.blurSupported;
+
+ if (wantBlur === !!this.#backgroundBlur) {
+ return;
+ }
+
+ if (wantBlur) {
+ const raw = this.stream;
+ const epoch = this.#epoch;
+ const result = await this.#createBackgroundBlur(raw);
+
+ // The camera may have been stopped or replaced, or blur toggled back
+ // off, while the model loaded.
+ if (epoch !== this.#epoch || this.stream !== raw) {
+ result?.manager.teardown();
+ return;
+ }
+
+ if (!result) {
+ this.#revertBlurPreference();
+ return;
+ }
+
+ if (!this.blurEnabled) {
+ result.manager.teardown();
+ return;
+ }
+
+ this.#backgroundBlur = result.manager;
+ this.#rawStream = raw;
+ this.stream = result.processed;
+ } else {
+ this.stream = this.#rawStream;
+ this.#teardownEffects();
+ }
+
+ const roomId = this.#getFirstActiveRoomId();
+ if (roomId) {
+ await this.syncSenders(roomId);
+ }
+ }
+
+ #revertBlurPreference() {
+ this.blurEnabled = false;
+ BackgroundBlurManager.setPreference(false);
+ this.#showError("voice.video_settings.blur_failed");
+ }
+
+ setBlurAmount(value) {
+ const clamped = Math.max(0, Math.min(100, Math.round(value)));
+ this.blurAmount = clamped;
+ BackgroundBlurManager.storeAmount(clamped);
+ this.#backgroundBlur?.setAmount(clamped);
+ }
+
+ setInputDevice(deviceId) {
+ return this.#enqueueOp(() => this.#setInputDeviceOp(deviceId));
+ }
+
+ async #setInputDeviceOp(deviceId) {
+ const previousDeviceId = this.inputDeviceId;
+ this.inputDeviceId = deviceId;
+
+ if (this.kind !== "camera") {
+ setPreferredVideoInputDeviceId(deviceId);
+ return true;
+ }
+
+ const epoch = this.#epoch;
+ const constraints = {
+ video: cameraConstraints(deviceId, this.#getCameraQuality(), {
+ exact: true,
+ }),
+ };
+
+ let newStream;
+ try {
+ newStream = await navigator.mediaDevices.getUserMedia(constraints);
+ } catch (error) {
+ if (!this.#cameraBusyError(error)) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to switch camera", error);
+ this.inputDeviceId = previousDeviceId;
+ this.#showSwitchError(error);
+ return false;
+ }
+
+ if (epoch !== this.#epoch || this.kind !== "camera") {
+ setPreferredVideoInputDeviceId(deviceId);
+ return true;
+ }
+
+ // Phones expose a single camera pipeline: the next device can't open
+ // while the current one is still capturing, so release ours and retry.
+ this.#stopCurrentCapture();
+
+ try {
+ newStream = await navigator.mediaDevices.getUserMedia(constraints);
+ } catch (retryError) {
+ return this.#rollbackSwitch(previousDeviceId, epoch, retryError);
+ }
+ }
+
+ setPreferredVideoInputDeviceId(deviceId);
+ return this.#swapCameraStream(newStream, epoch);
+ }
+
+ // Failure modes for busy hardware, as opposed to a denied permission or a
+ // missing device.
+ #cameraBusyError(error) {
+ return error?.name === "NotReadableError" || error?.name === "AbortError";
+ }
+
+ #stopCurrentCapture() {
+ const capture = this.#rawStream ?? this.stream;
+ capture?.getVideoTracks().forEach((track) => track.stop());
+ }
+
+ #showSwitchError(error) {
+ this.#showError(
+ error?.name === "NotAllowedError"
+ ? "voice.video.camera_switch_denied"
+ : "voice.video.camera_switch_failed"
+ );
+ }
+
+ // The old capture was already released for the retry, so a failed switch
+ // can't silently keep the previous stream: reacquire it, and if even that
+ // fails treat the camera as gone.
+ async #rollbackSwitch(previousDeviceId, epoch, error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to switch camera", error);
+ this.inputDeviceId = previousDeviceId;
+
+ if (epoch === this.#epoch && this.kind === "camera") {
+ let previousStream;
+ try {
+ previousStream = await navigator.mediaDevices.getUserMedia({
+ video: cameraConstraints(previousDeviceId, this.#getCameraQuality()),
+ });
+ } catch {
+ await this.stop();
+ }
+
+ if (previousStream) {
+ await this.#swapCameraStream(previousStream, epoch);
+ }
+ }
+
+ this.#showSwitchError(error);
+ return false;
+ }
+
+ async #swapCameraStream(newStream, epoch) {
+ const track = newStream.getVideoTracks()[0];
+
+ // The camera may have been stopped while the new capture started; the
+ // preference is kept but nothing is swapped.
+ if (epoch !== this.#epoch || this.kind !== "camera") {
+ newStream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return true;
+ }
+
+ if (!track) {
+ newStream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return false;
+ }
+
+ track.contentHint = "motion";
+ track.addEventListener("ended", () => this.#handleTrackEnded(), {
+ once: true,
+ });
+
+ const oldStream = this.stream;
+ const oldRaw = this.#rawStream;
+
+ let outgoingStream = newStream;
+ let blurResult = null;
+
+ if (this.#backgroundBlur) {
+ blurResult = await this.#createBackgroundBlur(newStream);
+
+ if (
+ epoch !== this.#epoch ||
+ this.kind !== "camera" ||
+ this.stream !== oldStream
+ ) {
+ blurResult?.manager.teardown();
+ newStream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return true;
+ }
+
+ if (blurResult) {
+ outgoingStream = blurResult.processed;
+ } else {
+ this.#revertBlurPreference();
+ }
+ }
+
+ this.#backgroundBlur?.teardown();
+ this.#backgroundBlur = blurResult?.manager ?? null;
+ this.#rawStream = blurResult ? newStream : null;
+ this.stream = outgoingStream;
+
+ oldStream?.getTracks().forEach((streamTrack) => streamTrack.stop());
+ if (oldRaw && oldRaw !== oldStream) {
+ oldRaw.getTracks().forEach((streamTrack) => streamTrack.stop());
+ }
+
+ const roomId = this.#getFirstActiveRoomId();
+ if (roomId) {
+ await this.syncSenders(roomId);
+ }
+
+ return true;
+ }
+
+ // Builds the blur pipeline without touching manager state, so callers can
+ // validate that the world hasn't changed across the await before wiring
+ // the result in. Returns null when the effect can't start (asset fetch
+ // failed, GPU unavailable, …).
+ async #createBackgroundBlur(rawStream) {
+ const manager = new BackgroundBlurManager();
+ try {
+ const processed = await manager.setup(rawStream, this.blurAmount);
+ processed.getVideoTracks().forEach((track) => {
+ track.contentHint = "motion";
+ });
+ return { manager, processed };
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to start background blur", error);
+ manager.teardown();
+ return null;
+ }
+ }
+
+ #teardownEffects() {
+ this.#backgroundBlur?.teardown();
+ this.#backgroundBlur = null;
+
+ if (this.#rawStream) {
+ if (this.#rawStream !== this.stream) {
+ this.#rawStream.getTracks().forEach((track) => track.stop());
+ }
+ this.#rawStream = null;
+ }
+ }
+
+ async start(kind) {
+ const roomId = this.#getFirstActiveRoomId();
+ if (!roomId) {
+ return;
+ }
+
+ if (!this.#canPublishVideo(roomId)) {
+ this.#showError("voice.video.publisher_limit");
+ return;
+ }
+
+ // Capture must be the first await: Firefox only allows getDisplayMedia
+ // while the click's transient activation is alive, and awaiting anything
+ // else first (e.g. stopping the current camera) consumes it. The old
+ // stream is torn down after the picker succeeds, which also keeps the
+ // camera running when the user cancels the picker.
+ let stream;
+ try {
+ if (kind === "screen") {
+ // Tab/system audio rides along for watch-along use. Voice processing
+ // is disabled because it is tuned for speech and mangles content
+ // audio; browsers without display-audio support just return no audio
+ // track. The user can still untick audio in the picker.
+ stream = await navigator.mediaDevices.getDisplayMedia({
+ video: {
+ frameRate: {
+ max: screenCaptureFramerate(this.#getScreenQuality(roomId)),
+ },
+ },
+ audio: {
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false,
+ },
+ systemAudio: "include",
+ });
+ } else {
+ stream = await navigator.mediaDevices.getUserMedia({
+ video: cameraConstraints(
+ this.inputDeviceId,
+ this.#getCameraQuality(roomId)
+ ),
+ });
+ }
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(`[voice] failed to obtain ${kind} stream`, error);
+ if (error?.name !== "NotAllowedError" && error?.name !== "AbortError") {
+ this.#showError("voice.video.capture_failed");
+ }
+ return;
+ }
+
+ // The user may have left the room while the capture picker was open.
+ if (!this.#isActiveRoom(roomId)) {
+ stream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return;
+ }
+
+ if (this.kind) {
+ await this.stop({ broadcast: false });
+ }
+
+ const track = stream.getVideoTracks()[0];
+ if (!track) {
+ stream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return;
+ }
+
+ // Steers the encoder's sharpness/smoothness trade-off; the matching
+ // degradationPreference is applied per-sender in applyVideoQuality.
+ if (kind === "screen" && "contentHint" in track) {
+ track.contentHint =
+ this.#getScreenContent() === SCREEN_CONTENT_MOTION
+ ? "motion"
+ : "detail";
+ }
+
+ const epoch = ++this.#epoch;
+
+ track.contentHint = kind === "screen" ? "detail" : "motion";
+ track.addEventListener("ended", () => this.#handleTrackEnded(), {
+ once: true,
+ });
+
+ const audioTrack =
+ kind === "screen" ? stream.getAudioTracks()[0] : undefined;
+ if (audioTrack) {
+ audioTrack.contentHint = "music";
+ }
+
+ let outgoingStream = stream;
+ if (
+ kind === "camera" &&
+ this.blurEnabled &&
+ this.#isBlurAllowed() &&
+ this.blurSupported
+ ) {
+ const result = await this.#createBackgroundBlur(stream);
+
+ if (epoch !== this.#epoch || !this.#isActiveRoom(roomId)) {
+ result?.manager.teardown();
+ stream.getTracks().forEach((streamTrack) => streamTrack.stop());
+ return;
+ }
+
+ if (result) {
+ this.#backgroundBlur = result.manager;
+ this.#rawStream = stream;
+ outgoingStream = result.processed;
+ } else {
+ this.#revertBlurPreference();
+ }
+ }
+
+ this.stream = outgoingStream;
+ this.kind = kind;
+
+ try {
+ await this.#broadcastState(roomId);
+ } catch (error) {
+ await this.stop({ broadcast: false });
+ popupAjaxError(error);
+ return;
+ }
+
+ await this.syncSenders(roomId);
+
+ // Applies any blur preference change that raced this startup (e.g. the
+ // toggle was flipped while the model loaded for the initial wrap).
+ this.#enqueueOp(() => this.#reconcileBlurOp());
+ }
+
+ async stop({ broadcast = true } = {}) {
+ // Invalidates any queued pipeline op that is mid-await on this session.
+ this.#epoch++;
+
+ const roomId = this.#getFirstActiveRoomId();
+ const stream = this.stream;
+
+ this.stream = null;
+ this.kind = null;
+
+ stream?.getTracks().forEach((track) => track.stop());
+ this.#teardownEffects();
+
+ if (roomId) {
+ await this.syncSenders(roomId);
+ if (broadcast) {
+ this.#broadcastState(roomId).catch(() => {});
+ }
+ }
+ }
+
+ #handleTrackEnded() {
+ if (!this.kind) {
+ return;
+ }
+ this.stop().catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to stop local video", error);
+ });
+ }
+
+ #applyContentHint() {
+ if (this.kind !== "screen") {
+ return;
+ }
+ const track = this.stream?.getVideoTracks?.()?.[0];
+ if (track && "contentHint" in track) {
+ track.contentHint =
+ this.#getScreenContent() === SCREEN_CONTENT_MOTION
+ ? "motion"
+ : "detail";
+ }
+ }
+
+ // Live re-apply after a preference change: encoder ceilings are cheap
+ // (setParameters, no renegotiation) and camera capture follows via
+ // applyConstraints. Screen capture framerate and LiveKit publish options
+ // are fixed at capture/publish time and pick up the change on the next
+ // share or join.
+ async refreshQuality({ contentHintChanged = false } = {}) {
+ if (contentHintChanged) {
+ this.#applyContentHint();
+ }
+
+ const roomId = this.#getActiveRoomId();
+ if (!roomId || !this.kind) {
+ return;
+ }
+
+ if (this.kind === "camera") {
+ const track =
+ this.#rawStream?.getVideoTracks?.()?.[0] ??
+ this.stream?.getVideoTracks?.()?.[0];
+ if (track) {
+ try {
+ await track.applyConstraints(
+ cameraConstraints(
+ this.inputDeviceId,
+ this.#getCameraQuality(roomId)
+ )
+ );
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to re-apply camera constraints", error);
+ }
+ }
+ }
+
+ await this.#applyQuality(roomId);
+ }
+
+ // Each peer has a dedicated sender, so video is only attached toward peers
+ // currently watching the room page — every skipped peer saves an entire
+ // encoder session, not just bandwidth.
+ async syncSenders(roomId) {
+ if (!this.#isMeshRoom(roomId)) {
+ // The SFU is published to once regardless of watchers; per-watcher
+ // receive gating happens on the subscriber side instead
+ // (setVideoSubscriptionsEnabled).
+ await this.#getLivekitSession(roomId)?.syncLocalVideo(
+ this.track,
+ this.screenAudioTrack,
+ this.kind
+ );
+ return;
+ }
+
+ const peers = this.#peerManager.getRoomPeers(roomId);
+ if (!peers) {
+ return;
+ }
+
+ for (const [remoteUserId, pc] of peers) {
+ const desired = this.trackFor(roomId, remoteUserId);
+
+ const transceiver = PeerManager.videoTransceiverFor(pc);
+ if (transceiver && transceiver.sender.track !== desired) {
+ try {
+ await transceiver.sender.replaceTrack(desired);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to sync video sender for user ${remoteUserId}`,
+ error
+ );
+ }
+ }
+
+ // Screen audio follows the same watching gate as the video track, so
+ // non-watchers don't get a soundtrack without a picture.
+ const desiredAudio = desired ? this.screenAudioTrack : null;
+ const audioTransceiver = PeerManager.screenAudioTransceiverFor(pc);
+ if (audioTransceiver && audioTransceiver.sender.track !== desiredAudio) {
+ try {
+ await audioTransceiver.sender.replaceTrack(desiredAudio);
+ if (desiredAudio) {
+ await applyScreenAudioQuality(audioTransceiver.sender);
+ }
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to sync screen audio sender for user ${remoteUserId}`,
+ error
+ );
+ }
+ }
+ }
+
+ await this.#applyQuality(roomId);
+ }
+
+ async #applyQuality(roomId) {
+ const peers = this.#peerManager.getRoomPeers(roomId);
+ if (!peers || !this.kind) {
+ return;
+ }
+
+ const sendingSenders = [];
+ for (const [, pc] of peers) {
+ const sender = PeerManager.videoTransceiverFor(pc)?.sender;
+ if (sender?.track) {
+ sendingSenders.push(sender);
+ }
+ }
+
+ await applyVideoQuality(sendingSenders, this.kind, {
+ tier:
+ this.kind === "screen"
+ ? this.#getScreenQuality(roomId)
+ : this.#getCameraQuality(roomId),
+ screenContent: this.#getScreenContent(),
+ });
+ }
+
+ #broadcastState(roomId) {
+ const video = this.kind === "camera";
+ const screen = this.kind === "screen";
+
+ this.#setParticipantVideoState(roomId, {
+ is_video_on: video,
+ is_screen_sharing: screen,
+ });
+
+ return ajax(`/voice/rooms/${roomId}/state`, {
+ type: "POST",
+ data: {
+ video,
+ screen,
+ participant_session_id: this.#getParticipantSessionId(roomId),
+ },
+ });
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js b/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js
new file mode 100644
index 00000000000..a8188224640
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js
@@ -0,0 +1,210 @@
+import { i18n } from "discourse-i18n";
+import { processingConstraints } from "./audio-processing";
+
+const INPUT_STORAGE_KEY = "voice_audio_input_device";
+const OUTPUT_STORAGE_KEY = "voice_audio_output_device";
+const VIDEO_INPUT_STORAGE_KEY = "voice_video_input_device";
+
+// Sentinel meaning "no explicit device": getUserMedia runs without a
+// deviceId constraint and playback sticks to the browser default sink.
+export const SYSTEM_DEFAULT_DEVICE_ID = "system_default";
+
+function readStoredDevice(key) {
+ try {
+ return localStorage.getItem(key) || SYSTEM_DEFAULT_DEVICE_ID;
+ } catch {
+ return SYSTEM_DEFAULT_DEVICE_ID;
+ }
+}
+
+function storeDevice(key, deviceId) {
+ try {
+ if (!deviceId || deviceId === SYSTEM_DEFAULT_DEVICE_ID) {
+ localStorage.removeItem(key);
+ } else {
+ localStorage.setItem(key, deviceId);
+ }
+ } catch {
+ // ignore storage errors
+ }
+}
+
+export function preferredInputDeviceId() {
+ return readStoredDevice(INPUT_STORAGE_KEY);
+}
+
+export function setPreferredInputDeviceId(deviceId) {
+ storeDevice(INPUT_STORAGE_KEY, deviceId);
+}
+
+export function preferredOutputDeviceId() {
+ return readStoredDevice(OUTPUT_STORAGE_KEY);
+}
+
+export function setPreferredOutputDeviceId(deviceId) {
+ storeDevice(OUTPUT_STORAGE_KEY, deviceId);
+}
+
+export function preferredVideoInputDeviceId() {
+ return readStoredDevice(VIDEO_INPUT_STORAGE_KEY);
+}
+
+export function setPreferredVideoInputDeviceId(deviceId) {
+ storeDevice(VIDEO_INPUT_STORAGE_KEY, deviceId);
+}
+
+// exact: a switch must land on the requested device or fail loudly; the
+// browser can satisfy a soft request from the already-open device.
+export function audioConstraints(
+ deviceId = preferredInputDeviceId(),
+ { exact = false } = {}
+) {
+ const constraints = processingConstraints();
+ if (deviceId && deviceId !== SYSTEM_DEFAULT_DEVICE_ID) {
+ constraints.deviceId = exact ? { exact: deviceId } : { ideal: deviceId };
+ }
+ return constraints;
+}
+
+// Capture dimensions per quality tier; the encoder ceilings in
+// video-quality.js scale from whatever was captured, so both move together.
+const CAMERA_CAPTURE = {
+ standard: { width: 1280, height: 720, frameRate: 24 },
+ high: { width: 1920, height: 1080, frameRate: 24 },
+ maximum: { width: 1920, height: 1080, frameRate: 30 },
+};
+
+// Ideal dimensions match the device orientation so a phone held in portrait
+// sends an upright portrait frame; the grid lays out whatever aspect the
+// camera actually delivers. The swap only applies on touch devices: the
+// orientation media query tracks the viewport, and a tall desktop window
+// must not make Chromium center-crop a landscape webcam into portrait.
+export function cameraConstraints(
+ deviceId = preferredVideoInputDeviceId(),
+ tier = "standard",
+ { exact = false } = {}
+) {
+ const capture = CAMERA_CAPTURE[tier] ?? CAMERA_CAPTURE.standard;
+ const rotatesWithScreen =
+ navigator.userAgentData?.mobile ??
+ window.matchMedia?.("(pointer: coarse)")?.matches ??
+ false;
+ const portrait =
+ rotatesWithScreen &&
+ (window.matchMedia?.("(orientation: portrait)")?.matches ?? false);
+ const [idealWidth, idealHeight] = portrait
+ ? [capture.height, capture.width]
+ : [capture.width, capture.height];
+
+ // frameRate needs an ideal, not just a ceiling: with only a max, every
+ // lower rate satisfies the constraint equally and Chromium can settle on
+ // a webcam's 5fps uncompressed modes.
+ const constraints = {
+ width: { ideal: idealWidth },
+ height: { ideal: idealHeight },
+ frameRate: { ideal: capture.frameRate, max: capture.frameRate },
+ };
+
+ if (deviceId && deviceId !== SYSTEM_DEFAULT_DEVICE_ID) {
+ constraints.deviceId = exact ? { exact: deviceId } : { ideal: deviceId };
+ }
+
+ return constraints;
+}
+
+export function outputSelectionSupported() {
+ return (
+ typeof HTMLMediaElement !== "undefined" &&
+ "setSinkId" in HTMLMediaElement.prototype
+ );
+}
+
+export async function enumerateAudioDevices() {
+ const inputs = [];
+ const outputs = [];
+
+ if (!navigator.mediaDevices?.enumerateDevices) {
+ return { inputs, outputs };
+ }
+
+ let devices;
+ try {
+ devices = await navigator.mediaDevices.enumerateDevices();
+ } catch {
+ return { inputs, outputs };
+ }
+
+ for (const device of devices) {
+ if (device.kind !== "audioinput" && device.kind !== "audiooutput") {
+ continue;
+ }
+
+ // Before mic permission is granted browsers return placeholder entries
+ // with empty deviceIds; they can't be selected, so skip them.
+ if (!device.deviceId) {
+ continue;
+ }
+
+ const list = device.kind === "audioinput" ? inputs : outputs;
+ list.push({
+ id: device.deviceId,
+ name:
+ device.label ||
+ i18n("voice.devices.unknown_device", {
+ index: list.length + 1,
+ }),
+ });
+ }
+
+ return { inputs, outputs };
+}
+
+export async function enumerateVideoDevices() {
+ const inputs = [];
+
+ if (!navigator.mediaDevices?.enumerateDevices) {
+ return inputs;
+ }
+
+ let devices;
+ try {
+ devices = await navigator.mediaDevices.enumerateDevices();
+ } catch {
+ return inputs;
+ }
+
+ for (const device of devices) {
+ if (device.kind !== "videoinput" || !device.deviceId) {
+ continue;
+ }
+
+ inputs.push({
+ id: device.deviceId,
+ name:
+ device.label ||
+ i18n("voice.devices.unknown_device", {
+ index: inputs.length + 1,
+ }),
+ });
+ }
+
+ return inputs;
+}
+
+export function applyOutputDevice(element, deviceId) {
+ if (!outputSelectionSupported() || typeof element?.setSinkId !== "function") {
+ return;
+ }
+
+ const sinkId =
+ !deviceId || deviceId === SYSTEM_DEFAULT_DEVICE_ID ? "" : deviceId;
+
+ if (element.sinkId === sinkId) {
+ return;
+ }
+
+ element.setSinkId(sinkId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to set audio output device", error);
+ });
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/mesh-signal-handler.js b/plugins/voice/assets/javascripts/discourse/lib/voice/mesh-signal-handler.js
new file mode 100644
index 00000000000..91aabe3f1e3
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/mesh-signal-handler.js
@@ -0,0 +1,288 @@
+import PeerManager from "./peer-manager";
+import { iceUfrag } from "./sdp-utils";
+import { participantCanSpeak } from "./stage-roles";
+
+// Handles incoming mesh WebRTC signals (offer/answer/candidate): glare
+// resolution, ICE-restart detection, pending-candidate queueing, and the
+// policies deciding whether a peer connection should exist at all.
+export default class MeshSignalHandler {
+ #peerManager;
+ #signaling;
+ #presencePending;
+ #getCurrentUserId;
+ #isActiveRoom;
+ #getRoom;
+ #isRoleChangeInProgress;
+ #addProvisionalParticipant;
+ #onOfferHandled;
+
+ constructor({
+ peerManager,
+ signaling,
+ presencePending,
+ getCurrentUserId,
+ isActiveRoom,
+ getRoom,
+ isRoleChangeInProgress,
+ addProvisionalParticipant = () => {},
+ onOfferHandled,
+ }) {
+ this.#peerManager = peerManager;
+ this.#signaling = signaling;
+ this.#presencePending = presencePending;
+ this.#getCurrentUserId = getCurrentUserId;
+ this.#isActiveRoom = isActiveRoom;
+ this.#getRoom = getRoom;
+ this.#isRoleChangeInProgress = isRoleChangeInProgress;
+ this.#addProvisionalParticipant = addProvisionalParticipant;
+ this.#onOfferHandled = onOfferHandled;
+ }
+
+ shouldMaintainPeerConnection(roomId, remoteUserId) {
+ if (!this.#isActiveRoom(roomId)) {
+ return false;
+ }
+
+ const room = this.#getRoom(roomId);
+ if (!room) {
+ return false;
+ }
+
+ const participant = (room.active_participants || []).find(
+ (entry) => Number(entry?.id) === Number(remoteUserId)
+ );
+
+ if (!participant) {
+ return false;
+ }
+
+ if (room.room_type !== "stage") {
+ return true;
+ }
+
+ const iCanSpeak = participantCanSpeak(room, this.#getCurrentUserId());
+ const theyCanSpeak =
+ participant.role === "moderator" || participant.role === "speaker";
+
+ return iCanSpeak || theyCanSpeak;
+ }
+
+ // A relayed signal is server-attested proof the sender holds a live
+ // participant session in this room: the server only relays for senders who
+ // joined and only to recipients still present. The local roster
+ // (active_participants) lags behind that relay when two peers join
+ // near-simultaneously, so shouldMaintainPeerConnection can still be false at
+ // the instant the offer arrives. Gating offers on the local roster silently
+ // drops that legitimate first offer and strands the media connection (the
+ // sender finishes gathering before we ever engage, so its candidates are
+ // never re-sent). Honor early offers in non-stage rooms, where peering does
+ // not depend on the sender's presence-derived speaker role. Stage rooms keep
+ // strict gating for exactly that reason.
+ #canEngageEarlyOffer(roomId) {
+ if (!this.#isActiveRoom(roomId)) {
+ return false;
+ }
+ const room = this.#getRoom(roomId);
+ return !!room && room.room_type !== "stage";
+ }
+
+ // Whether we should set up / keep a peer for a signal of the given type.
+ // Falls back to the implicit-presence rule above for offers.
+ #shouldEngagePeer(roomId, remoteUserId, signalType) {
+ if (this.shouldMaintainPeerConnection(roomId, remoteUserId)) {
+ return true;
+ }
+ return (
+ (signalType === "offer" || signalType === "candidate") &&
+ this.#canEngageEarlyOffer(roomId)
+ );
+ }
+
+ // The relay batches one envelope per recipient (payload.events, in send
+ // order); a single-event payload.data is still accepted for compatibility.
+ async handle(roomId, payload) {
+ const events = Array.isArray(payload.events)
+ ? payload.events
+ : payload.data
+ ? [payload.data]
+ : [];
+
+ for (const data of events) {
+ await this.#handleEvent(roomId, payload, data);
+ }
+ }
+
+ async #handleEvent(roomId, payload, data) {
+ const remoteUserId = Number(payload.sender_id);
+
+ if (!Number.isFinite(remoteUserId) || remoteUserId <= 0) {
+ return;
+ }
+
+ if (remoteUserId === this.#getCurrentUserId()) {
+ return;
+ }
+
+ if (this.#isRoleChangeInProgress(roomId)) {
+ return;
+ }
+
+ this.#peerManager.clearPeerRestart(roomId, remoteUserId);
+
+ const hadPeer = this.#peerManager.has(roomId, remoteUserId);
+ if (!hadPeer && data?.type === "candidate") {
+ if (this.#canEngageEarlyOffer(roomId)) {
+ this.#peerManager.queuePendingCandidate(
+ roomId,
+ remoteUserId,
+ data.candidate
+ );
+ }
+ return;
+ }
+
+ if (!hadPeer && !this.#shouldEngagePeer(roomId, remoteUserId, data?.type)) {
+ return;
+ }
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] 📥 received ${data.type} from user ${remoteUserId} in room ${roomId}`
+ );
+ let pc = await this.#peerManager.create(roomId, remoteUserId);
+ if (!pc) {
+ return;
+ }
+
+ if (!this.#shouldEngagePeer(roomId, remoteUserId, data?.type)) {
+ this.#peerManager.destroy(roomId, remoteUserId);
+ return;
+ }
+
+ if (data.type === "offer") {
+ this.#peerManager.clearOfferRetry(roomId, remoteUserId);
+ if (!this.shouldMaintainPeerConnection(roomId, remoteUserId)) {
+ this.#presencePending.mark(roomId, remoteUserId);
+ // Media may flow before the roster broadcast lands; render the
+ // server-serialized sender immediately so nobody receives audio while
+ // invisible. The next roster broadcast reconciles it.
+ if (payload.sender) {
+ this.#addProvisionalParticipant(roomId, payload.sender);
+ }
+ }
+
+ // If the remote restarted its ICE session — it left and rejoined, so its
+ // offer carries fresh ICE credentials — renegotiating on the old, dead
+ // transport won't recover. Tear the stale peer down and rebuild it so ICE
+ // starts clean. Detected by a changed ice-ufrag vs our current remote
+ // description; a merely resent offer keeps the same ufrag and is left
+ // alone. Skip while mid-glare (have-local-offer), which the block below
+ // already resolves.
+ if (pc.signalingState !== "have-local-offer") {
+ const priorUfrag = iceUfrag(pc.remoteDescription?.sdp);
+ const incomingUfrag = iceUfrag(data.sdp);
+ if (priorUfrag && incomingUfrag && priorUfrag !== incomingUfrag) {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] remote ICE restart from user ${remoteUserId}; recreating peer`
+ );
+ this.#peerManager.destroy(roomId, remoteUserId);
+ pc = await this.#peerManager.create(roomId, remoteUserId);
+ if (!pc) {
+ return;
+ }
+ }
+ }
+
+ if (pc.signalingState === "have-local-offer") {
+ if (this.#getCurrentUserId() < remoteUserId) {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] glare detected, rolling back local offer for user ${remoteUserId}`
+ );
+ await pc.setLocalDescription({ type: "rollback" });
+ } else {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] glare detected, ignoring remote offer from user ${remoteUserId}`
+ );
+ return;
+ }
+ }
+
+ try {
+ await pc.setRemoteDescription(new RTCSessionDescription(data));
+ const room = this.#getRoom(roomId);
+ const canPublish =
+ !room || participantCanSpeak(room, this.#getCurrentUserId());
+ PeerManager.alignVideoTransceiverForAnswer(pc, { canPublish });
+ PeerManager.alignScreenAudioTransceiverForAnswer(pc, { canPublish });
+ await this.#peerManager.flushPendingCandidates(
+ roomId,
+ remoteUserId,
+ pc
+ );
+ const answer = await pc.createAnswer();
+ await pc.setLocalDescription(answer);
+ this.#signaling.send(roomId, remoteUserId, answer).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to send answer", error);
+ });
+
+ await this.#onOfferHandled(roomId);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to handle offer from user ${remoteUserId}`,
+ error
+ );
+ }
+ } else if (data.type === "answer") {
+ this.#peerManager.clearOfferRetry(roomId, remoteUserId);
+
+ if (pc.signalingState !== "have-local-offer") {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] ignoring answer in state ${pc.signalingState} from user ${remoteUserId}`
+ );
+ return;
+ }
+
+ try {
+ await pc.setRemoteDescription(new RTCSessionDescription(data));
+ await this.#peerManager.flushPendingCandidates(
+ roomId,
+ remoteUserId,
+ pc
+ );
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to handle answer from user ${remoteUserId}`,
+ error
+ );
+ }
+ } else if (data.type === "candidate") {
+ this.#peerManager.clearOfferRetry(roomId, remoteUserId);
+
+ if (!pc.remoteDescription) {
+ this.#peerManager.queuePendingCandidate(
+ roomId,
+ remoteUserId,
+ data.candidate
+ );
+ return;
+ }
+
+ try {
+ await pc.addIceCandidate(new RTCIceCandidate(data.candidate));
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to add ICE candidate from user ${remoteUserId}`,
+ error
+ );
+ }
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/noise-suppression.js b/plugins/voice/assets/javascripts/discourse/lib/voice/noise-suppression.js
new file mode 100644
index 00000000000..49fb25d68e8
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/noise-suppression.js
@@ -0,0 +1,271 @@
+import { nsUrl } from "./ns-engines";
+
+// How long setup() waits for the worklet's "ready" handshake. Instantiating
+// the (already fetched) wasm and warming the model up takes well under a
+// second on weak hardware; the margin covers a cold audio thread.
+const READY_TIMEOUT_MS = 10000;
+
+// How long a user-gesture setup() waits for the AudioContext to leave
+// "suspended" before falling back to the statechange-driven re-resume.
+const RESUME_WAIT_MS = 1000;
+
+// Thrown by setup() when a newer setup()/teardown() superseded it (device
+// switch, rapid toggling, leaving the room). Callers must treat it as a
+// no-op, not a failure: the superseding call owns the pipeline state now.
+export class SupersededError extends Error {
+ constructor() {
+ super("noise suppression setup superseded");
+ this.name = "SupersededError";
+ }
+}
+
+const assetPromises = new Map();
+
+function fetchBytes(file) {
+ if (!assetPromises.has(file)) {
+ assetPromises.set(
+ file,
+ fetch(nsUrl(file))
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`${file} fetch failed: ${response.status}`);
+ }
+ return response.arrayBuffer();
+ })
+ .catch((error) => {
+ // A failed fetch is not cached, so a flaky connection doesn't
+ // brick the feature until reload.
+ assetPromises.delete(file);
+ throw error;
+ })
+ );
+ }
+ return assetPromises.get(file);
+}
+
+// Fetching an engine's model once and keeping the bytes lets re-enables and
+// device switches skip the network entirely.
+export function prefetchEngineAssets(engine) {
+ const assets = { wasm: fetchBytes(engine.wasmFile) };
+ if (engine.modelFile) {
+ assets.model = fetchBytes(engine.modelFile);
+ }
+ return Promise.all(Object.values(assets)).then(async () => ({
+ wasm: await assets.wasm,
+ model: engine.modelFile ? await assets.model : undefined,
+ }));
+}
+
+function timeout(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export default class NoiseSuppressionManager {
+ #context = null;
+ #source = null;
+ #node = null;
+ #epoch = 0;
+ #abortReady = null;
+
+ #onRuntimeFailure;
+
+ constructor({ onRuntimeFailure } = {}) {
+ this.#onRuntimeFailure = onRuntimeFailure;
+ }
+
+ get active() {
+ return this.#context !== null;
+ }
+
+ // Resolves with the suppressed MediaStream only after the worklet has
+ // confirmed the model is loaded and filtering (the "ready" handshake), so
+ // a resolved setup() means noise suppression is actually working. Throws
+ // SupersededError when a newer setup()/teardown() takes over mid-flight.
+ // `engine` is a descriptor from ns-engines.js.
+ async setup(rawStream, engine, { userGesture = false } = {}) {
+ const epoch = ++this.#epoch;
+ const superseded = () => epoch !== this.#epoch;
+
+ const assets = await prefetchEngineAssets(engine);
+ if (superseded()) {
+ throw new SupersededError();
+ }
+
+ const audioContext = new AudioContext();
+
+ // A fresh context starts suspended without recent user activation (e.g.
+ // rejoining a room after a reload) and a suspended context outputs
+ // silence. statechange re-resumes after OS-level interruptions
+ // (Bluetooth profile switches, phone calls).
+ const keepRunning = () => {
+ if (audioContext.state !== "running") {
+ audioContext.resume().catch(() => {});
+ }
+ };
+ audioContext.onstatechange = keepRunning;
+
+ const abort = () => {
+ audioContext.onstatechange = null;
+ try {
+ audioContext.close();
+ } catch {
+ // ignore
+ }
+ };
+
+ if (userGesture) {
+ // Inside a click handler resume() should settle immediately; if it
+ // stays pending (browser quirk), keepRunning picks it up later rather
+ // than failing a toggle that would otherwise work.
+ await Promise.race([
+ audioContext.resume().catch(() => {}),
+ timeout(RESUME_WAIT_MS),
+ ]);
+ } else {
+ keepRunning();
+ }
+
+ if (superseded()) {
+ abort();
+ throw new SupersededError();
+ }
+
+ try {
+ // Worklet modules (unlike Workers) may load cross-origin, so the
+ // bundle rides the CDN too.
+ await audioContext.audioWorklet.addModule(nsUrl(engine.workletFile));
+ } catch (error) {
+ abort();
+ throw error;
+ }
+
+ if (superseded()) {
+ abort();
+ throw new SupersededError();
+ }
+
+ // The engines are mono. Forcing one channel downmixes stereo mics ahead
+ // of the worklet; left at the defaults the node mirrors the input's
+ // channel count and a stereo mic ships a silent right channel.
+ const workletNode = new AudioWorkletNode(
+ audioContext,
+ "noise-suppression-processor",
+ {
+ channelCount: 1,
+ channelCountMode: "explicit",
+ outputChannelCount: [1],
+ }
+ );
+
+ try {
+ await this.#awaitReady(workletNode, assets, superseded);
+ } catch (error) {
+ abort();
+ throw error;
+ }
+
+ if (superseded()) {
+ abort();
+ throw new SupersededError();
+ }
+
+ // Live messages after the handshake mean the filter broke mid-call;
+ // hand the pipeline the failure so it can fall back to the raw track.
+ workletNode.port.onmessage = (event) => {
+ const type = event.data?.type;
+ if ((type === "bypass" || type === "error") && !superseded()) {
+ this.#onRuntimeFailure?.();
+ }
+ };
+
+ // Audio only starts flowing through the node now that the model is
+ // confirmed live; before this point the worklet would pass raw audio
+ // through (fail-open) and the toggle would silently lie.
+ const source = audioContext.createMediaStreamSource(rawStream);
+ const destination = audioContext.createMediaStreamDestination();
+ destination.channelCount = 1;
+ source.connect(workletNode);
+ workletNode.connect(destination);
+
+ this.#context = audioContext;
+ this.#source = source;
+ this.#node = workletNode;
+
+ return destination.stream;
+ }
+
+ #awaitReady(workletNode, assets, superseded) {
+ return new Promise((resolve, reject) => {
+ let timer = null;
+ const settle = (fn, value) => {
+ clearTimeout(timer);
+ workletNode.port.onmessage = null;
+ this.#abortReady = null;
+ fn(value);
+ };
+
+ // teardown()/a newer setup() must not leave this parked for the full
+ // timeout — reject immediately so the superseded caller unwinds.
+ this.#abortReady = () => settle(reject, new SupersededError());
+
+ workletNode.port.onmessage = (event) => {
+ const { type, message } = event.data || {};
+ if (superseded()) {
+ settle(reject, new SupersededError());
+ } else if (type === "ready") {
+ settle(resolve);
+ } else if (type === "error") {
+ settle(reject, new Error(`engine init failed: ${message}`));
+ }
+ };
+
+ timer = setTimeout(() => {
+ settle(reject, new Error("worklet ready handshake timed out"));
+ }, READY_TIMEOUT_MS);
+
+ // The cached bytes stay usable: copies are transferred, not the cache.
+ const payload = { wasm: assets.wasm.slice(0) };
+ if (assets.model) {
+ payload.model = assets.model.slice(0);
+ }
+ workletNode.port.postMessage(
+ { type: "init", assets: payload },
+ Object.values(payload)
+ );
+ });
+ }
+
+ teardown() {
+ this.#epoch++;
+ this.#abortReady?.();
+
+ if (this.#source) {
+ try {
+ this.#source.disconnect();
+ } catch {
+ // ignore
+ }
+ this.#source = null;
+ }
+
+ if (this.#node) {
+ this.#node.port.onmessage = null;
+ try {
+ this.#node.disconnect();
+ } catch {
+ // ignore
+ }
+ this.#node = null;
+ }
+
+ if (this.#context) {
+ this.#context.onstatechange = null;
+ try {
+ this.#context.close();
+ } catch {
+ // ignore
+ }
+ this.#context = null;
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/ns-engines.js b/plugins/voice/assets/javascripts/discourse/lib/voice/ns-engines.js
new file mode 100644
index 00000000000..af4ed4a4178
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/ns-engines.js
@@ -0,0 +1,42 @@
+import { i18n } from "discourse-i18n";
+
+export { voiceAssetUrl as nsUrl } from "./voice-assets";
+
+// The selectable AI noise-suppression engines. Every engine ships a worklet
+// bundle speaking the same protocol (src/ns-worklet/runtime.js in the
+// discourse_voice_assets gem, which vendors the built assets): asset bytes
+// posted in, ready/error handshake out, mono frames filtered at the
+// engine's own rate. Filenames are the gem's stable names, resolved to
+// versioned URLs through nsUrl().
+//
+// Order here is the order shown in the mode selectors.
+export const NS_ENGINES = {
+ rnnoise: {
+ workletFile: "rnnoise/rnnoise-worklet.js",
+ wasmFile: "rnnoise/rnnoise.wasm",
+ },
+ dtln: {
+ workletFile: "dtln/dtln-worklet.js",
+ wasmFile: "dtln/dtln.wasm",
+ },
+ dfn3: {
+ workletFile: "dfn3/dfn3-worklet.js",
+ wasmFile: "dfn3/dfn3.wasm",
+ modelFile: "dfn3/dfn3-model.bin",
+ },
+};
+
+export function engineForMode(mode) {
+ if (!mode?.startsWith?.("ai:")) {
+ return null;
+ }
+ return NS_ENGINES[mode.slice(3)] ?? null;
+}
+
+// "ai:dtln" → the "…noise_suppression_modes.ai_dtln" translation ("ai:dtln"
+// itself stays the stored/mode value; colons just make poor YAML keys).
+export function noiseSuppressionModeLabel(mode) {
+ return i18n(
+ `voice.voice_settings.noise_suppression_modes.${mode.replace(":", "_")}`
+ );
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/participant-audio.js b/plugins/voice/assets/javascripts/discourse/lib/voice/participant-audio.js
new file mode 100644
index 00000000000..8a08887fe1d
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/participant-audio.js
@@ -0,0 +1,90 @@
+import { applyOutputDevice } from "./media-devices";
+
+// Per-participant playback state: which media elements a remote user's audio
+// plays through, plus the local volume and mute the listener chose for them.
+// Deafen state stays with the caller and is consulted through a callback so
+// it applies uniformly whenever settings are (re)applied.
+export default class ParticipantAudio {
+ #elements = new Map();
+ #volumes = new Map();
+ #muted = new Map();
+
+ #isDeafened;
+
+ constructor({ isDeafened }) {
+ this.#isDeafened = isDeafened;
+ }
+
+ #key(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ trackElement(roomId, userId, element, role = "voice") {
+ const key = this.#key(roomId, userId);
+ const elements = this.#elements.get(key) || {};
+ elements[role] = element;
+ this.#elements.set(key, elements);
+ }
+
+ untrackElement(roomId, userId) {
+ this.#elements.delete(this.#key(roomId, userId));
+ }
+
+ setVolume(roomId, userId, volume) {
+ const clamped = Math.max(0, Math.min(1, volume));
+ this.#volumes.set(this.#key(roomId, userId), clamped);
+ this.apply(roomId, userId);
+ }
+
+ volumeFor(roomId, userId) {
+ return this.#volumes.get(this.#key(roomId, userId)) ?? 1;
+ }
+
+ toggleMuted(roomId, userId) {
+ const key = this.#key(roomId, userId);
+ const newMutedState = !(this.#muted.get(key) ?? false);
+ this.#muted.set(key, newMutedState);
+ this.apply(roomId, userId);
+ return newMutedState;
+ }
+
+ isMuted(roomId, userId) {
+ return this.#muted.get(this.#key(roomId, userId)) ?? false;
+ }
+
+ apply(roomId, userId) {
+ const key = this.#key(roomId, userId);
+ const elements = this.#elements.get(key);
+ if (!elements) {
+ return;
+ }
+
+ this.#applyTo(key, elements);
+ }
+
+ applyAll() {
+ for (const [key, elements] of this.#elements) {
+ this.#applyTo(key, elements);
+ }
+ }
+
+ setOutputDevice(deviceId) {
+ for (const [, elements] of this.#elements) {
+ for (const element of Object.values(elements)) {
+ applyOutputDevice(element, deviceId);
+ }
+ }
+ }
+
+ #applyTo(key, elements) {
+ const muted = this.#isDeafened() || (this.#muted.get(key) ?? false);
+ const volume = this.#volumes.get(key) ?? 1;
+
+ for (const element of Object.values(elements)) {
+ element.muted = muted;
+ if (!muted) {
+ element.volume = volume;
+ }
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js
new file mode 100644
index 00000000000..d7b5e94bfb7
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js
@@ -0,0 +1,751 @@
+// The screen-share audio m-line is pre-negotiated like the video one, but
+// both audio transceivers on a connection report kind "audio", so the screen
+// one is remembered per connection instead of being inferred from m-line
+// order at every lookup.
+const screenAudioTransceivers = new WeakMap();
+
+const DEFAULT_TIMING = {
+ offerRetryBaseDelayMs: 400,
+ maxOfferRetryDelayMs: 5000,
+ restartImmediateDelayMs: 200,
+ restartDisconnectedDelayMs: 1500,
+ maxRestartDelayMs: 5000,
+ // A healthy connect completes in ~1s (sub-second once ICE checks start).
+ // With a relay-only transport there are no host/srflx fallback candidates,
+ // so an initial negotiation race or a slow/failed relay allocation can
+ // leave the peer stuck in "new" with nothing to fall back to — this timeout
+ // is the only thing that rescues it via a restart. Keep it short so a stall
+ // recovers in seconds rather than tens of seconds; the generous headroom
+ // over a real connect avoids tearing down a peer that is merely still
+ // connecting.
+ connectionTimeoutMs: 8000,
+};
+
+let timing = DEFAULT_TIMING;
+
+// Tests race these wall-clock delays against their own progress, which flakes
+// under CI load; overriding them keeps each test's timers either far out of
+// its window or fast enough to await deterministically. Pass null to restore
+// the defaults.
+export function setPeerTimingForTesting(overrides) {
+ timing = overrides ? { ...DEFAULT_TIMING, ...overrides } : DEFAULT_TIMING;
+}
+
+export default class PeerManager {
+ static #maxRestartAttempts = 5;
+ static #maxOfferRetries = 8;
+
+ static peerKey(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ // Prefer the transceiver associated with a negotiated m-line (mid set):
+ // on the answerer side the connection can briefly hold two video
+ // transceivers — the negotiated one and the unassociated pre-allocated one.
+ static videoTransceiverFor(pc) {
+ const videoTransceivers = pc
+ .getTransceivers()
+ .filter((transceiver) => transceiver.receiver?.track?.kind === "video");
+
+ return (
+ videoTransceivers.find((transceiver) => transceiver.mid !== null) ??
+ videoTransceivers[0]
+ );
+ }
+
+ static screenAudioTransceiverFor(pc) {
+ return screenAudioTransceivers.get(pc) || null;
+ }
+
+ // The screen-share audio sender also carries kind "audio"; mic-wide
+ // operations (voice quality, device switches) must only touch this one.
+ static micSenderFor(pc) {
+ const screenAudioSender = PeerManager.screenAudioTransceiverFor(pc)?.sender;
+ return (
+ pc
+ .getSenders()
+ .find(
+ (sender) =>
+ sender.track?.kind === "audio" && sender !== screenAudioSender
+ ) ?? null
+ );
+ }
+
+ // Per JSEP, applying a remote offer only reuses transceivers created via
+ // addTrack — never the pre-allocated addTransceiver one — so the answerer
+ // gets a fresh recvonly transceiver for the offered video m-line and could
+ // never send video back. Called between setRemoteDescription(offer) and
+ // createAnswer: flips the associated transceiver to sendrecv (the answer
+ // then carries it, no renegotiation) and migrates any track off the now
+ // orphaned pre-allocated transceiver.
+ // Answerers whose server-side role cannot publish keep the m-line
+ // receive-only: defense in depth on top of the receive-side track policy.
+ static alignVideoTransceiverForAnswer(pc, { canPublish = true } = {}) {
+ const videoTransceivers = pc
+ .getTransceivers()
+ .filter((transceiver) => transceiver.receiver?.track?.kind === "video");
+
+ const associated = videoTransceivers.find(
+ (transceiver) => transceiver.mid !== null
+ );
+ if (!associated) {
+ return;
+ }
+
+ const direction = canPublish ? "sendrecv" : "recvonly";
+ if (associated.direction !== direction) {
+ associated.direction = direction;
+ }
+
+ const orphan = videoTransceivers.find(
+ (transceiver) => transceiver !== associated && transceiver.mid === null
+ );
+ const orphanTrack = orphan?.sender?.track;
+ if (orphanTrack && !associated.sender.track) {
+ associated.sender.replaceTrack(orphanTrack).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to migrate video track", error);
+ });
+ orphan.sender.replaceTrack(null).catch(() => {});
+ }
+ }
+
+ // Same JSEP problem as the video m-line, for the screen-audio one: the
+ // answerer's pre-allocated transceiver is never reused, so the negotiated
+ // transceiver must be flipped to sendrecv and adopted as the screen-audio
+ // slot. The mic m-line always precedes the screen-audio m-line (the mic
+ // track is added before the pre-allocated transceivers, and fresh answerer
+ // transceivers are created in m-line order), so among the audio
+ // transceivers associated with an m-line the screen one is the last.
+ static alignScreenAudioTransceiverForAnswer(pc, { canPublish = true } = {}) {
+ const associated = pc
+ .getTransceivers()
+ .filter(
+ (transceiver) =>
+ transceiver.receiver?.track?.kind === "audio" &&
+ transceiver.mid !== null
+ );
+
+ // A single audio m-line means the remote is an older client that doesn't
+ // negotiate screen audio; leave the pre-allocated transceiver idle.
+ if (associated.length < 2) {
+ return;
+ }
+
+ const screenTransceiver = associated[associated.length - 1];
+ const direction = canPublish ? "sendrecv" : "recvonly";
+ if (screenTransceiver.direction !== direction) {
+ screenTransceiver.direction = direction;
+ }
+
+ const orphan = screenAudioTransceivers.get(pc);
+ if (orphan && orphan !== screenTransceiver) {
+ const orphanTrack = orphan.sender?.track;
+ if (orphanTrack && !screenTransceiver.sender.track) {
+ screenTransceiver.sender.replaceTrack(orphanTrack).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to migrate screen audio track", error);
+ });
+ orphan.sender.replaceTrack(null).catch(() => {});
+ }
+ }
+
+ screenAudioTransceivers.set(pc, screenTransceiver);
+ }
+
+ #peerConnections = new Map();
+ #destroyed = false;
+ #offerRetryTimers = new Map();
+ #offerRetryAttempts = new Map();
+ #peerReconnectTimers = new Map();
+ #restartAttempts = new Map();
+ #connectionTimeouts = new Map();
+ #pendingCandidates = new Map();
+
+ #getIceServers;
+ #getIceTransportPolicy;
+ #canPublishMedia;
+ #getLocalStream;
+ #getLocalVideoTrack;
+ #getLocalScreenAudioTrack;
+ #sendSignal;
+ #flushQueuedSignals;
+ #onTrack;
+ #clearSignalQueue;
+ #onPeerDestroyed;
+ #onPeerConnected;
+ #shouldRestartPeer;
+
+ constructor({
+ getIceServers,
+ getIceTransportPolicy = () => "all",
+ canPublishMedia = () => true,
+ getLocalStream,
+ getLocalVideoTrack = () => null,
+ getLocalScreenAudioTrack = () => null,
+ sendSignal,
+ flushQueuedSignals,
+ onTrack,
+ clearSignalQueue,
+ onPeerDestroyed,
+ onPeerConnected = () => {},
+ shouldRestartPeer = () => true,
+ }) {
+ this.#getIceServers = getIceServers;
+ this.#getIceTransportPolicy = getIceTransportPolicy;
+ this.#canPublishMedia = canPublishMedia;
+ this.#getLocalStream = getLocalStream;
+ this.#getLocalVideoTrack = getLocalVideoTrack;
+ this.#getLocalScreenAudioTrack = getLocalScreenAudioTrack;
+ this.#sendSignal = sendSignal;
+ this.#flushQueuedSignals = flushQueuedSignals;
+ this.#onTrack = onTrack;
+ this.#clearSignalQueue = clearSignalQueue;
+ this.#onPeerDestroyed = onPeerDestroyed;
+ this.#onPeerConnected = onPeerConnected;
+ this.#shouldRestartPeer = shouldRestartPeer;
+ }
+
+ has(roomId, userId) {
+ const peers = this.#peerConnections.get(roomId);
+ return peers?.has(userId) ?? false;
+ }
+
+ get(roomId, userId) {
+ return this.#peerConnections.get(roomId)?.get(userId);
+ }
+
+ getRoomPeers(roomId) {
+ return this.#peerConnections.get(roomId);
+ }
+
+ remoteVideoTrack(roomId, userId) {
+ const pc = this.get(roomId, userId);
+ if (!pc) {
+ return null;
+ }
+
+ return PeerManager.videoTransceiverFor(pc)?.receiver?.track || null;
+ }
+
+ allPeerConnections() {
+ return this.#peerConnections;
+ }
+
+ micSendersFor(roomId) {
+ const senders = [];
+ for (const [, pc] of this.#peerConnections.get(roomId) || []) {
+ const sender = PeerManager.micSenderFor(pc);
+ if (sender?.track) {
+ senders.push(sender);
+ }
+ }
+ return senders;
+ }
+
+ async replaceMicTrack(newTrack) {
+ for (const [, peers] of this.#peerConnections) {
+ for (const [, pc] of peers) {
+ const sender = PeerManager.micSenderFor(pc);
+ if (sender) {
+ try {
+ await sender.replaceTrack(newTrack);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to replace track on peer", error);
+ }
+ }
+ }
+ }
+ }
+
+ async create(roomId, remoteUserId) {
+ if (this.#destroyed) {
+ return null;
+ }
+
+ let roomPeers = this.#peerConnections.get(roomId);
+ if (!roomPeers) {
+ roomPeers = new Map();
+ this.#peerConnections.set(roomId, roomPeers);
+ }
+
+ if (roomPeers.has(remoteUserId)) {
+ return roomPeers.get(remoteUserId);
+ }
+
+ const pc = new RTCPeerConnection({
+ iceServers: this.#getIceServers(),
+ iceTransportPolicy: this.#getIceTransportPolicy(),
+ });
+ roomPeers.set(remoteUserId, pc);
+
+ const localStream = this.#getLocalStream();
+ if (localStream) {
+ for (const track of localStream.getTracks()) {
+ pc.addTrack(track, localStream);
+ }
+ }
+
+ // The video m-line is negotiated up-front so that turning a camera or
+ // screen share on later is a plain replaceTrack with no renegotiation —
+ // the signaling layer only supports one-shot negotiation at peer setup.
+ // An idle sender transmits nothing. When the local role cannot publish
+ // (stage listener) the m-line is receive-only; a promotion rebuilds all
+ // peers, so the direction never needs to change on a live connection.
+ const canPublish = this.#canPublishMedia(roomId);
+ const videoTransceiver = pc.addTransceiver("video", {
+ direction: canPublish ? "sendrecv" : "recvonly",
+ });
+ const videoTrack = this.#getLocalVideoTrack(roomId, remoteUserId);
+ if (videoTrack) {
+ videoTransceiver.sender.replaceTrack(videoTrack).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to attach video track", error);
+ });
+ }
+
+ // A second audio m-line, pre-negotiated for the same reason as video,
+ // carries tab/system audio during a screen share. It stays separate from
+ // the mic m-line so voice mute/PTT and receiver-side speaking detection
+ // never touch content audio.
+ const screenAudioTransceiver = pc.addTransceiver("audio", {
+ direction: canPublish ? "sendrecv" : "recvonly",
+ });
+ screenAudioTransceivers.set(pc, screenAudioTransceiver);
+ const screenAudioTrack = this.#getLocalScreenAudioTrack(
+ roomId,
+ remoteUserId
+ );
+ if (screenAudioTrack) {
+ screenAudioTransceiver.sender
+ .replaceTrack(screenAudioTrack)
+ .catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to attach screen audio track", error);
+ });
+ }
+
+ pc.ontrack = (event) => {
+ this.#onTrack(roomId, remoteUserId, event.track, event.streams);
+ };
+
+ pc.onicecandidate = (event) => {
+ if (event.candidate) {
+ const candidatePayload =
+ typeof event.candidate.toJSON === "function"
+ ? event.candidate.toJSON()
+ : {
+ candidate: event.candidate.candidate,
+ sdpMid: event.candidate.sdpMid,
+ sdpMLineIndex: event.candidate.sdpMLineIndex,
+ usernameFragment: event.candidate.usernameFragment,
+ };
+
+ this.#sendSignal(roomId, remoteUserId, {
+ type: "candidate",
+ candidate: candidatePayload,
+ }).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to send candidate", error);
+ });
+ } else {
+ this.#flushQueuedSignals(roomId, remoteUserId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush signal queue", error);
+ });
+ }
+ };
+
+ pc.onicegatheringstatechange = () => {
+ if (pc.iceGatheringState === "complete") {
+ this.#flushQueuedSignals(roomId, remoteUserId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush signal queue", error);
+ });
+ }
+ };
+
+ pc.onicecandidateerror = (event) => {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] ICE candidate error for user ${remoteUserId}`,
+ event
+ );
+ };
+
+ pc.onconnectionstatechange = () => {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] connectionState ${pc.connectionState} for user ${remoteUserId}`
+ );
+ if (pc.connectionState === "connected") {
+ this.#clearOfferRetry(roomId, remoteUserId);
+ this.#clearPeerRestart(roomId, remoteUserId);
+ this.#clearConnectionTimeout(roomId, remoteUserId);
+ this.#onPeerConnected(roomId, remoteUserId, pc);
+ return;
+ }
+
+ if (pc.connectionState === "failed") {
+ this.#clearOfferRetry(roomId, remoteUserId);
+ this.#clearConnectionTimeout(roomId, remoteUserId);
+ this.#schedulePeerRestart(roomId, remoteUserId, { immediate: true });
+ return;
+ }
+
+ if (pc.connectionState === "disconnected") {
+ this.#schedulePeerRestart(roomId, remoteUserId);
+ return;
+ }
+
+ if (pc.connectionState === "closed") {
+ this.destroy(roomId, remoteUserId, { closeConnection: false });
+ }
+ };
+
+ pc.oniceconnectionstatechange = () => {
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] iceConnectionState ${pc.iceConnectionState} for user ${remoteUserId}`
+ );
+ if (pc.iceConnectionState === "failed") {
+ this.#schedulePeerRestart(roomId, remoteUserId, { immediate: true });
+ } else if (pc.iceConnectionState === "disconnected") {
+ this.#schedulePeerRestart(roomId, remoteUserId);
+ }
+ };
+
+ this.#startConnectionTimeout(roomId, remoteUserId, pc);
+
+ return pc;
+ }
+
+ destroy(
+ roomId,
+ remoteUserId,
+ { resetRestartAttempts = true, closeConnection = true } = {}
+ ) {
+ const peers = this.#peerConnections.get(roomId);
+ const pc = peers?.get(remoteUserId);
+
+ if (pc) {
+ pc.ontrack = null;
+ pc.onicecandidate = null;
+ pc.onconnectionstatechange = null;
+ pc.oniceconnectionstatechange = null;
+ pc.onicegatheringstatechange = null;
+ pc.onicecandidateerror = null;
+
+ if (closeConnection) {
+ try {
+ pc.close();
+ } catch {
+ // ignore close errors
+ }
+ }
+
+ peers.delete(remoteUserId);
+ }
+
+ this.#clearOfferRetry(roomId, remoteUserId);
+ if (resetRestartAttempts) {
+ this.#clearPeerRestart(roomId, remoteUserId);
+ } else {
+ this.#clearPeerRestartTimer(roomId, remoteUserId);
+ }
+ this.#clearConnectionTimeout(roomId, remoteUserId);
+ this.#clearPendingCandidates(roomId, remoteUserId);
+ this.#clearSignalQueue(roomId, remoteUserId);
+ this.#onPeerDestroyed(roomId, remoteUserId);
+ }
+
+ destroyRoom(roomId) {
+ const peers = this.#peerConnections.get(roomId);
+ if (peers) {
+ Array.from(peers.keys()).forEach((remoteUserId) => {
+ this.destroy(roomId, remoteUserId);
+ });
+ this.#peerConnections.delete(roomId);
+ }
+ }
+
+ async initiateOffer(roomId, remoteUserId) {
+ const peers = this.#peerConnections.get(roomId);
+ const pc = peers?.get(remoteUserId);
+
+ if (!pc) {
+ return;
+ }
+
+ if (pc.signalingState !== "stable") {
+ // An inbound offer/answer is already mid-flight on this peer; the
+ // inbound handler will drive negotiation. The connection timeout in
+ // #startConnectionTimeout is the safety net if it stalls.
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] skipping offer for user ${remoteUserId}: signalingState=${pc.signalingState}`
+ );
+ return;
+ }
+
+ try {
+ const offer = await pc.createOffer();
+ await pc.setLocalDescription(offer);
+ this.#sendSignal(roomId, remoteUserId, offer).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to send offer", error);
+ });
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to create offer", error);
+ }
+ }
+
+ scheduleOfferRetry(roomId, remoteUserId, delay = null) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+
+ if (this.#destroyed || this.#offerRetryTimers.has(key)) {
+ return;
+ }
+
+ delay ??= timing.offerRetryBaseDelayMs;
+
+ const attempts = this.#offerRetryAttempts.get(key) || 0;
+
+ if (attempts >= PeerManager.#maxOfferRetries) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] max offer retries (${PeerManager.#maxOfferRetries}) reached for user ${remoteUserId}`
+ );
+ return;
+ }
+
+ const actualDelay = Math.min(
+ delay * Math.pow(2, attempts),
+ timing.maxOfferRetryDelayMs
+ );
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] scheduling offer retry for user ${remoteUserId} (attempt ${attempts + 1}/${PeerManager.#maxOfferRetries}, delay ${actualDelay}ms)`
+ );
+
+ const timer = setTimeout(async () => {
+ this.#offerRetryTimers.delete(key);
+ this.#offerRetryAttempts.set(key, attempts + 1);
+ await this.initiateOffer(roomId, remoteUserId);
+ }, actualDelay);
+
+ this.#offerRetryTimers.set(key, timer);
+ }
+
+ clearOfferRetry(roomId, remoteUserId) {
+ this.#clearOfferRetry(roomId, remoteUserId);
+ }
+
+ clearPeerRestart(roomId, remoteUserId) {
+ this.#clearPeerRestart(roomId, remoteUserId);
+ }
+
+ queuePendingCandidate(roomId, remoteUserId, candidate) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ const queue = this.#pendingCandidates.get(key) || [];
+ queue.push(candidate);
+ this.#pendingCandidates.set(key, queue);
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] queued ICE candidate for user ${remoteUserId} (${queue.length} pending)`
+ );
+ }
+
+ async flushPendingCandidates(roomId, remoteUserId, pc) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ const candidates = this.#pendingCandidates.get(key);
+
+ if (!candidates?.length) {
+ return;
+ }
+
+ this.#pendingCandidates.delete(key);
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] flushing ${candidates.length} queued ICE candidates for user ${remoteUserId}`
+ );
+
+ for (const candidate of candidates) {
+ try {
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] failed to add queued ICE candidate for user ${remoteUserId}`,
+ error
+ );
+ }
+ }
+ }
+
+ async restart(roomId, remoteUserId) {
+ if (this.#destroyed) {
+ return;
+ }
+
+ if (!this.#shouldRestartPeer(roomId, remoteUserId)) {
+ this.#clearPeerRestart(roomId, remoteUserId);
+ return;
+ }
+
+ this.destroy(roomId, remoteUserId, { resetRestartAttempts: false });
+
+ await this.create(roomId, remoteUserId);
+
+ if (!this.#shouldRestartPeer(roomId, remoteUserId)) {
+ this.destroy(roomId, remoteUserId);
+ return;
+ }
+
+ await this.initiateOffer(roomId, remoteUserId);
+ }
+
+ // Terminal: the manager schedules no further timers and creates no further
+ // connections afterwards, so in-flight async (a restart mid-await, a late
+ // retry) lands on a no-op instead of resurrecting state.
+ destroyAll() {
+ this.#destroyed = true;
+
+ for (const [roomId, peers] of this.#peerConnections) {
+ for (const remoteUserId of Array.from(peers.keys())) {
+ this.destroy(roomId, remoteUserId);
+ }
+ }
+ this.#peerConnections.clear();
+
+ this.#peerReconnectTimers.forEach((timer) => clearTimeout(timer));
+ this.#peerReconnectTimers.clear();
+ this.#offerRetryTimers.forEach((timer) => clearTimeout(timer));
+ this.#offerRetryTimers.clear();
+ this.#offerRetryAttempts.clear();
+ this.#restartAttempts.clear();
+ this.#connectionTimeouts.forEach((timer) => clearTimeout(timer));
+ this.#connectionTimeouts.clear();
+ this.#pendingCandidates.clear();
+ }
+
+ // --- private ---
+
+ #startConnectionTimeout(roomId, remoteUserId, pc) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+
+ if (this.#destroyed || this.#connectionTimeouts.has(key)) {
+ return;
+ }
+
+ const timer = setTimeout(() => {
+ this.#connectionTimeouts.delete(key);
+
+ // Only rescue a peer that never started ICE (still "new" — e.g. a
+ // relay-only transport whose relay allocation produced no candidate).
+ // A peer in "connecting"/"checking" is mid-negotiation and may simply
+ // need more time (relay-to-relay checks can take >10s); restarting it
+ // here throws away progress and re-floods signaling, which can trip
+ // rate limits and turn a slow connect into an endless restart storm.
+ // ICE's own failure detection (oniceconnectionstatechange -> "failed")
+ // and the disconnected/failed handlers restart those if checks truly
+ // fail, so they are covered without an app-level teardown.
+ if (pc.connectionState === "new") {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] connection stuck in "new" (${timing.connectionTimeoutMs}ms) for user ${remoteUserId}; restarting`
+ );
+ this.#schedulePeerRestart(roomId, remoteUserId, { immediate: true });
+ }
+ }, timing.connectionTimeoutMs);
+
+ this.#connectionTimeouts.set(key, timer);
+ }
+
+ #clearConnectionTimeout(roomId, remoteUserId) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ const timer = this.#connectionTimeouts.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#connectionTimeouts.delete(key);
+ }
+ }
+
+ #clearOfferRetry(roomId, remoteUserId) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ const timer = this.#offerRetryTimers.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#offerRetryTimers.delete(key);
+ }
+
+ this.#offerRetryAttempts.delete(key);
+ }
+
+ #schedulePeerRestart(roomId, remoteUserId, options = {}) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+
+ if (this.#destroyed || this.#peerReconnectTimers.has(key)) {
+ return;
+ }
+
+ const attempts = this.#restartAttempts.get(key) || 0;
+
+ if (attempts >= PeerManager.#maxRestartAttempts) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice] max restart attempts (${PeerManager.#maxRestartAttempts}) reached for user ${remoteUserId}`
+ );
+ return;
+ }
+
+ const baseDelay = options.immediate
+ ? timing.restartImmediateDelayMs
+ : timing.restartDisconnectedDelayMs;
+ const delay = Math.min(
+ baseDelay * Math.pow(2, attempts),
+ timing.maxRestartDelayMs
+ );
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] scheduling peer restart for user ${remoteUserId} (attempt ${attempts + 1}/${PeerManager.#maxRestartAttempts}, delay ${delay}ms)`
+ );
+
+ const timer = setTimeout(() => {
+ this.#peerReconnectTimers.delete(key);
+ this.#restartAttempts.set(key, attempts + 1);
+ this.restart(roomId, remoteUserId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to restart peer connection", error);
+ });
+ }, delay);
+
+ this.#peerReconnectTimers.set(key, timer);
+ }
+
+ #clearPeerRestart(roomId, remoteUserId) {
+ this.#clearPeerRestartTimer(roomId, remoteUserId);
+ this.#restartAttempts.delete(PeerManager.peerKey(roomId, remoteUserId));
+ }
+
+ #clearPeerRestartTimer(roomId, remoteUserId) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ const timer = this.#peerReconnectTimers.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#peerReconnectTimers.delete(key);
+ }
+ }
+
+ #clearPendingCandidates(roomId, remoteUserId) {
+ const key = PeerManager.peerKey(roomId, remoteUserId);
+ this.#pendingCandidates.delete(key);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/presence-pending-peers.js b/plugins/voice/assets/javascripts/discourse/lib/voice/presence-pending-peers.js
new file mode 100644
index 00000000000..ba61adb5585
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/presence-pending-peers.js
@@ -0,0 +1,62 @@
+const PRESENCE_GRACE_MS = 15000;
+
+// Peers engaged from an early offer before presence caught up. Each gets a
+// grace window; when it expires without presence confirming the peer,
+// onExpired lets the caller decide whether to tear the connection down.
+export default class PresencePendingPeers {
+ #keys = new Set();
+ #timers = new Map();
+
+ #onExpired;
+
+ constructor({ onExpired }) {
+ this.#onExpired = onExpired;
+ }
+
+ #key(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ mark(roomId, userId) {
+ const key = this.#key(roomId, userId);
+ if (this.#keys.has(key)) {
+ return;
+ }
+
+ this.#keys.add(key);
+
+ const timer = setTimeout(() => {
+ this.#timers.delete(key);
+ this.#keys.delete(key);
+ this.#onExpired(roomId, userId);
+ }, PRESENCE_GRACE_MS);
+
+ this.#timers.set(key, timer);
+ }
+
+ clear(roomId, userId) {
+ const key = this.#key(roomId, userId);
+ const timer = this.#timers.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#timers.delete(key);
+ }
+
+ this.#keys.delete(key);
+ }
+
+ has(roomId, userId) {
+ return this.#keys.has(this.#key(roomId, userId));
+ }
+
+ clearAll(roomId = null) {
+ for (const [key, timer] of this.#timers) {
+ if (roomId === null || key.startsWith(`${roomId}:`)) {
+ clearTimeout(timer);
+ this.#timers.delete(key);
+ this.#keys.delete(key);
+ }
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-manager.js
new file mode 100644
index 00000000000..c109d857ed2
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-manager.js
@@ -0,0 +1,206 @@
+import { cancel } from "@ember/runloop";
+import discourseLater from "discourse/lib/later";
+
+const PTT_MUTE_DEBOUNCE_MS = 200;
+const PTT_RESERVED_KEYS = new Set(["Escape", "Tab", "Enter"]);
+const PTT_STORAGE_ENABLED = "voice_ptt_enabled";
+const PTT_STORAGE_KEY = "voice_ptt_key";
+const PTT_DEFAULT_KEY = "Space";
+
+export { PTT_RESERVED_KEYS };
+
+export default class PttManager {
+ #enabled = false;
+ #key = PTT_DEFAULT_KEY;
+ #active = false;
+ #listening = false;
+ #muteDebounceTimer = null;
+ #keyDownHandler = null;
+ #keyUpHandler = null;
+ #visibilityHandler = null;
+
+ #onPress;
+ #onReleaseImmediate;
+ #onReleaseDebounced;
+ #isConnected;
+
+ constructor({
+ onPress,
+ onReleaseImmediate,
+ onReleaseDebounced,
+ isConnected,
+ }) {
+ this.#onPress = onPress;
+ this.#onReleaseImmediate = onReleaseImmediate;
+ this.#onReleaseDebounced = onReleaseDebounced;
+ this.#isConnected = isConnected;
+
+ this.#enabled = localStorage.getItem(PTT_STORAGE_ENABLED) === "true";
+ this.#key = localStorage.getItem(PTT_STORAGE_KEY) || PTT_DEFAULT_KEY;
+ }
+
+ get enabled() {
+ return this.#enabled;
+ }
+
+ get key() {
+ return this.#key;
+ }
+
+ get active() {
+ return this.#active;
+ }
+
+ enable() {
+ this.#enabled = true;
+ this.#active = false;
+ localStorage.setItem(PTT_STORAGE_ENABLED, "true");
+ }
+
+ disable() {
+ if (this.#active) {
+ this.#doRelease();
+ }
+ this.#enabled = false;
+ this.#active = false;
+ localStorage.setItem(PTT_STORAGE_ENABLED, "false");
+ this.stopListening();
+ }
+
+ setKey(keyCode) {
+ if (PTT_RESERVED_KEYS.has(keyCode)) {
+ return false;
+ }
+ this.#key = keyCode;
+ localStorage.setItem(PTT_STORAGE_KEY, keyCode);
+ return true;
+ }
+
+ startListening() {
+ if (this.#listening) {
+ return;
+ }
+ this.#listening = true;
+
+ this.#keyDownHandler = (event) => this.#onKeyDown(event);
+ this.#keyUpHandler = (event) => this.#onKeyUp(event);
+ this.#visibilityHandler = () => this.#onVisibilityChange();
+
+ document.addEventListener("keydown", this.#keyDownHandler);
+ document.addEventListener("keyup", this.#keyUpHandler);
+ document.addEventListener("visibilitychange", this.#visibilityHandler);
+ }
+
+ stopListening() {
+ if (!this.#listening) {
+ return;
+ }
+ this.#listening = false;
+
+ if (this.#keyDownHandler) {
+ document.removeEventListener("keydown", this.#keyDownHandler);
+ this.#keyDownHandler = null;
+ }
+ if (this.#keyUpHandler) {
+ document.removeEventListener("keyup", this.#keyUpHandler);
+ this.#keyUpHandler = null;
+ }
+ if (this.#visibilityHandler) {
+ document.removeEventListener("visibilitychange", this.#visibilityHandler);
+ this.#visibilityHandler = null;
+ }
+ this.#cancelDebounce();
+ }
+
+ resetActive() {
+ this.#active = false;
+ }
+
+ destroy() {
+ this.stopListening();
+ }
+
+ // --- Private ---
+
+ #onKeyDown(event) {
+ if (!this.#enabled || !this.#isConnected()) {
+ return;
+ }
+
+ if (event.code !== this.#key) {
+ return;
+ }
+
+ if (this.#isTypingInInput()) {
+ return;
+ }
+
+ event.preventDefault();
+
+ if (event.repeat || this.#active) {
+ return;
+ }
+
+ this.#cancelDebounce();
+ this.#active = true;
+ this.#onPress();
+ }
+
+ #onKeyUp(event) {
+ if (!this.#enabled || event.code !== this.#key) {
+ return;
+ }
+
+ if (!this.#isTypingInInput()) {
+ event.preventDefault();
+ }
+
+ if (!this.#active) {
+ return;
+ }
+
+ this.#doRelease();
+ }
+
+ #doRelease() {
+ this.#active = false;
+ this.#onReleaseImmediate();
+ this.#cancelDebounce();
+
+ this.#muteDebounceTimer = discourseLater(
+ this,
+ () => {
+ this.#muteDebounceTimer = null;
+ this.#onReleaseDebounced();
+ },
+ PTT_MUTE_DEBOUNCE_MS
+ );
+ }
+
+ #onVisibilityChange() {
+ if (document.hidden && this.#active) {
+ this.#doRelease();
+ }
+ }
+
+ #cancelDebounce() {
+ if (this.#muteDebounceTimer) {
+ cancel(this.#muteDebounceTimer);
+ this.#muteDebounceTimer = null;
+ }
+ }
+
+ #isTypingInInput() {
+ const el = document.activeElement;
+ if (!el) {
+ return false;
+ }
+ const tag = el.tagName;
+ return (
+ tag === "INPUT" ||
+ tag === "TEXTAREA" ||
+ tag === "SELECT" ||
+ el.isContentEditable
+ );
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-utils.js b/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-utils.js
new file mode 100644
index 00000000000..97f26adaafc
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/ptt-utils.js
@@ -0,0 +1,12 @@
+export function humanKeyName(code) {
+ if (code.startsWith("Key")) {
+ return code.slice(3);
+ }
+ if (code.startsWith("Digit")) {
+ return code.slice(5);
+ }
+ if (code.startsWith("Numpad")) {
+ return "Num " + code.slice(6);
+ }
+ return code.replace(/([a-z])([A-Z])/g, "$1 $2");
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/quality-preferences.js b/plugins/voice/assets/javascripts/discourse/lib/voice/quality-preferences.js
new file mode 100644
index 00000000000..c81c6e361cd
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/quality-preferences.js
@@ -0,0 +1,99 @@
+// User-facing quality tiers, ordered lowest to highest. The user's stored
+// choice is a preference, not a guarantee: the effective tier is the lowest
+// of the user's choice, the room's cap, and the site setting cap, and the
+// per-connection bandwidth estimator still adapts below whatever ceiling the
+// tier sets.
+export const QUALITY_STANDARD = "standard";
+export const QUALITY_HIGH = "high";
+export const QUALITY_MAXIMUM = "maximum";
+
+export const QUALITY_TIERS = [QUALITY_STANDARD, QUALITY_HIGH, QUALITY_MAXIMUM];
+
+export const SCREEN_CONTENT_TEXT = "text";
+export const SCREEN_CONTENT_MOTION = "motion";
+
+const VOICE_STORAGE_KEY = "voice_voice_quality";
+const CAMERA_STORAGE_KEY = "voice_camera_quality";
+const SCREEN_STORAGE_KEY = "voice_screen_quality";
+const SCREEN_CONTENT_STORAGE_KEY = "voice_screen_content";
+
+function readStored(key, allowed, fallback) {
+ try {
+ const value = localStorage.getItem(key);
+ return allowed.includes(value) ? value : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+function store(key, value, fallback) {
+ try {
+ if (!value || value === fallback) {
+ localStorage.removeItem(key);
+ } else {
+ localStorage.setItem(key, value);
+ }
+ } catch {
+ // ignore storage errors
+ }
+}
+
+export function preferredVoiceQuality() {
+ return readStored(VOICE_STORAGE_KEY, QUALITY_TIERS, QUALITY_STANDARD);
+}
+
+export function setPreferredVoiceQuality(tier) {
+ store(VOICE_STORAGE_KEY, tier, QUALITY_STANDARD);
+}
+
+export function preferredCameraQuality() {
+ return readStored(CAMERA_STORAGE_KEY, QUALITY_TIERS, QUALITY_STANDARD);
+}
+
+export function setPreferredCameraQuality(tier) {
+ store(CAMERA_STORAGE_KEY, tier, QUALITY_STANDARD);
+}
+
+export function preferredScreenQuality() {
+ return readStored(SCREEN_STORAGE_KEY, QUALITY_TIERS, QUALITY_STANDARD);
+}
+
+export function setPreferredScreenQuality(tier) {
+ store(SCREEN_STORAGE_KEY, tier, QUALITY_STANDARD);
+}
+
+export function preferredScreenContent() {
+ return readStored(
+ SCREEN_CONTENT_STORAGE_KEY,
+ [SCREEN_CONTENT_TEXT, SCREEN_CONTENT_MOTION],
+ SCREEN_CONTENT_TEXT
+ );
+}
+
+export function setPreferredScreenContent(content) {
+ store(SCREEN_CONTENT_STORAGE_KEY, content, SCREEN_CONTENT_TEXT);
+}
+
+// Tiers a user may pick given the caps: everything up to the lowest cap.
+export function allowedQualityTiers(...caps) {
+ const highest = clampQuality(QUALITY_MAXIMUM, ...caps);
+ return QUALITY_TIERS.slice(0, QUALITY_TIERS.indexOf(highest) + 1);
+}
+
+// Lowest of the given tiers; null/undefined caps (e.g. a room with no
+// room-level cap) don't constrain.
+export function clampQuality(tier, ...caps) {
+ let rank = QUALITY_TIERS.indexOf(tier);
+ if (rank === -1) {
+ rank = 0;
+ }
+
+ for (const cap of caps) {
+ const capRank = QUALITY_TIERS.indexOf(cap);
+ if (capRank !== -1 && capRank < rank) {
+ rank = capRank;
+ }
+ }
+
+ return QUALITY_TIERS[rank];
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/remote-stream-registry.js b/plugins/voice/assets/javascripts/discourse/lib/voice/remote-stream-registry.js
new file mode 100644
index 00000000000..54db9702f6e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/remote-stream-registry.js
@@ -0,0 +1,154 @@
+// Each remote user gets one registry-owned MediaStream that incoming mic
+// audio and video tracks are merged into. Mic audio arrives with the
+// sender's stream attached, but the pre-negotiated video and screen-audio
+// transceivers deliver bare tracks (no stream), so keying the registry on
+// incoming stream identity would make those tracks clobber the user's
+// audio entry — and a bare audio track is how screen audio is told apart
+// from mic audio. Screen audio lives in its own per-user stream with its
+// own sink, keeping it out of the speaking detector and letting one media
+// element never juggle two audio tracks.
+export default class RemoteStreamRegistry {
+ #streams = new Map();
+ #streamToParticipant = new WeakMap();
+
+ #onChange;
+ #onMicTrack;
+
+ constructor({ onChange, onMicTrack }) {
+ this.#onChange = onChange;
+ this.#onMicTrack = onMicTrack;
+ }
+
+ allStreams() {
+ return Array.from(this.#streams.values())
+ .filter(Array.isArray)
+ .flat()
+ .map((entry) => entry.stream);
+ }
+
+ allScreenAudioStreams() {
+ return Array.from(this.#streams.values())
+ .filter(Array.isArray)
+ .flat()
+ .map((entry) => entry.screenAudioStream)
+ .filter(Boolean);
+ }
+
+ streamsFor(roomId) {
+ return (this.#streams.get(roomId) || []).map((entry) => entry.stream);
+ }
+
+ streamFor(roomId, userId) {
+ return (this.#streams.get(roomId) || []).find(
+ (entry) => Number(entry?.userId) === Number(userId)
+ )?.stream;
+ }
+
+ userIdsFor(roomId) {
+ return (this.#streams.get(roomId) || []).map((entry) =>
+ Number(entry?.userId)
+ );
+ }
+
+ participantFor(stream) {
+ return this.#streamToParticipant.get(stream);
+ }
+
+ register(roomId, userId, track, streams) {
+ if (!roomId || !userId || !track) {
+ return;
+ }
+
+ const roomStreams = this.#streams.get(roomId) || [];
+ const existingIndex = roomStreams.findIndex(
+ (entry) => Number(entry?.userId) === Number(userId)
+ );
+
+ let entry;
+ const next = [...roomStreams];
+ if (existingIndex >= 0) {
+ entry = next[existingIndex];
+ } else {
+ entry = { userId, stream: new MediaStream() };
+ next.push(entry);
+ }
+
+ const isScreenAudio = track.kind === "audio" && !streams?.length;
+
+ if (isScreenAudio) {
+ if (!entry.screenAudioStream) {
+ entry.screenAudioStream = new MediaStream();
+ }
+ const existingTracks = entry.screenAudioStream.getTracks();
+ if (!existingTracks.includes(track)) {
+ existingTracks.forEach((existing) =>
+ entry.screenAudioStream.removeTrack(existing)
+ );
+ entry.screenAudioStream.addTrack(track);
+ }
+ this.#streamToParticipant.set(entry.screenAudioStream, {
+ roomId,
+ userId,
+ screenAudio: true,
+ });
+ } else {
+ const existingTracks = entry.stream.getTracks();
+ if (!existingTracks.includes(track)) {
+ existingTracks
+ .filter((existing) => existing.kind === track.kind)
+ .forEach((existing) => entry.stream.removeTrack(existing));
+ entry.stream.addTrack(track);
+ }
+ }
+
+ this.#streams.set(roomId, next);
+ this.#streamToParticipant.set(entry.stream, { roomId, userId });
+ this.#onChange();
+
+ if (track.kind === "audio" && !isScreenAudio) {
+ this.#onMicTrack(roomId, userId, entry.stream);
+ }
+ }
+
+ remove(roomId, userId) {
+ if (!roomId || !userId) {
+ return false;
+ }
+
+ const roomStreams = this.#streams.get(roomId);
+ if (!roomStreams?.length) {
+ return false;
+ }
+
+ const filtered = roomStreams.filter(
+ (entry) => Number(entry?.userId) !== Number(userId)
+ );
+
+ if (filtered.length === roomStreams.length) {
+ return false;
+ }
+
+ if (filtered.length) {
+ this.#streams.set(roomId, filtered);
+ } else {
+ this.#streams.delete(roomId);
+ }
+
+ this.#onChange();
+ return true;
+ }
+
+ clearRoom(roomId) {
+ const entries = this.#streams.get(roomId);
+ if (!entries?.length) {
+ if (this.#streams.delete(roomId)) {
+ this.#onChange();
+ }
+ return [];
+ }
+
+ this.#streams.delete(roomId);
+ this.#onChange();
+ return entries.map((entry) => Number(entry.userId));
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/ringing.js b/plugins/voice/assets/javascripts/discourse/lib/voice/ringing.js
new file mode 100644
index 00000000000..03d02084c9d
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/ringing.js
@@ -0,0 +1,24 @@
+import { RING_SECONDS } from "./call-constants";
+
+// People an ephemeral call room is still reaching out to: rung, not yet
+// present, and within the ring window. `nowMs` comes from the caller's
+// clock tick so expiry re-evaluates over time (getters alone never would).
+export function activeRingingEntries(room, nowMs) {
+ if (!room?.ephemeral) {
+ return [];
+ }
+
+ const presentIds = new Set(
+ (room.active_participants || []).map((participant) =>
+ Number(participant?.id)
+ )
+ );
+ const cutoff = nowMs - RING_SECONDS * 1000;
+
+ return (room.ringing || []).filter(
+ (entry) =>
+ entry.user &&
+ !presentIds.has(Number(entry.user.id)) &&
+ entry.notified_at * 1000 > cutoff
+ );
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/room-icon.js b/plugins/voice/assets/javascripts/discourse/lib/voice/room-icon.js
new file mode 100644
index 00000000000..1e69333a0de
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/room-icon.js
@@ -0,0 +1,7 @@
+export default function roomIcon(room) {
+ return room.room_type === "stage" ? "podcast" : "microphone-lines";
+}
+
+export function roomBadge(room) {
+ return room.public ? null : "lock";
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/room-message-queue.js b/plugins/voice/assets/javascripts/discourse/lib/voice/room-message-queue.js
new file mode 100644
index 00000000000..a0b93cfc93b
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/room-message-queue.js
@@ -0,0 +1,28 @@
+export default class RoomMessageQueue {
+ #queues = new Map();
+
+ enqueue(roomId, handler) {
+ const previous = this.#queues.get(roomId) || Promise.resolve();
+ const next = previous.catch(() => {}).then(handler);
+
+ this.#queues.set(roomId, next);
+
+ const cleanup = () => {
+ if (this.#queues.get(roomId) === next) {
+ this.#queues.delete(roomId);
+ }
+ };
+
+ next.then(cleanup, cleanup);
+
+ return next;
+ }
+
+ clear(roomId) {
+ this.#queues.delete(roomId);
+ }
+
+ clearAll() {
+ this.#queues.clear();
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js b/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js
new file mode 100644
index 00000000000..b5e2441c7cb
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js
@@ -0,0 +1,402 @@
+import { i18n } from "discourse-i18n";
+import {
+ playUserJoinedSound,
+ playUserLeftSound,
+ stopCallSounds,
+} from "./sound-effects";
+import { participantCanSpeak } from "./stage-roles";
+
+// Handles the roster-shaped room messages ("participants", "role_change",
+// "hand_raise"): diffing the roster into mesh peer create/destroy (or the
+// livekit roster sync), rebuilding the call topology around stage role
+// changes, and the join/leave/hand-raise user feedback.
+export default class RosterHandler {
+ #roleChangeInProgress = new Set();
+
+ #peerManager;
+ #signaling;
+ #presencePending;
+ #livekit;
+ #toasts;
+ #getCurrentUserId;
+ #getChatSound;
+ #getRoom;
+ #isActiveRoom;
+ #isConnectingRoom;
+ #isMeshRoom;
+ #registerTrack;
+ #getRemoteUserIds;
+ #removeRemoteStream;
+ #removeAllRemoteStreams;
+ #getLocalVideoKind;
+ #syncVideoSenders;
+ #stopLocalVideo;
+ #getLocalStream;
+ #acquireMicrophone;
+ #setMicEnabled;
+ #stopLocalAudio;
+ #ensureLocalAudioMonitor;
+
+ constructor({
+ peerManager,
+ signaling,
+ presencePending,
+ livekit,
+ toasts,
+ getCurrentUserId,
+ getChatSound,
+ getRoom,
+ isActiveRoom,
+ isConnectingRoom,
+ isMeshRoom,
+ registerTrack,
+ getRemoteUserIds = () => [],
+ removeRemoteStream,
+ removeAllRemoteStreams,
+ getLocalVideoKind,
+ syncVideoSenders,
+ stopLocalVideo,
+ getLocalStream,
+ acquireMicrophone,
+ setMicEnabled,
+ stopLocalAudio,
+ ensureLocalAudioMonitor,
+ }) {
+ this.#peerManager = peerManager;
+ this.#signaling = signaling;
+ this.#presencePending = presencePending;
+ this.#livekit = livekit;
+ this.#toasts = toasts;
+ this.#getCurrentUserId = getCurrentUserId;
+ this.#getChatSound = getChatSound;
+ this.#getRoom = getRoom;
+ this.#isActiveRoom = isActiveRoom;
+ this.#isConnectingRoom = isConnectingRoom;
+ this.#isMeshRoom = isMeshRoom;
+ this.#registerTrack = registerTrack;
+ this.#getRemoteUserIds = getRemoteUserIds;
+ this.#removeRemoteStream = removeRemoteStream;
+ this.#removeAllRemoteStreams = removeAllRemoteStreams;
+ this.#getLocalVideoKind = getLocalVideoKind;
+ this.#syncVideoSenders = syncVideoSenders;
+ this.#stopLocalVideo = stopLocalVideo;
+ this.#getLocalStream = getLocalStream;
+ this.#acquireMicrophone = acquireMicrophone;
+ this.#setMicEnabled = setMicEnabled;
+ this.#stopLocalAudio = stopLocalAudio;
+ this.#ensureLocalAudioMonitor = ensureLocalAudioMonitor;
+ }
+
+ isRoleChangeInProgress(roomId) {
+ return this.#roleChangeInProgress.has(roomId);
+ }
+
+ async handleParticipants(roomId, payload) {
+ const participants = payload.participants || [];
+ const participantIds = new Set(
+ participants.map((participant) => Number(participant.id))
+ );
+ const currentUserId = this.#getCurrentUserId();
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] handleParticipants room=${roomId}, participants=[${Array.from(participantIds)}], currentUser=${currentUserId}`
+ );
+
+ if (this.#roleChangeInProgress.has(roomId)) {
+ return;
+ }
+
+ const room = this.#getRoom(roomId);
+ const isStage = room?.room_type === "stage";
+ const iCanSpeak = room ? participantCanSpeak(room, currentUserId) : true;
+
+ let hasPeerLeft = false;
+ let hasNewPeer = false;
+
+ // Peer create/destroy and the presence-pending machinery are mesh-only;
+ // other transports carry media outside the roster diff.
+ if (this.#isMeshRoom(roomId)) {
+ const peers = this.#peerManager.getRoomPeers(roomId);
+ const existingPeerIds = new Set(peers?.keys() || []);
+
+ peers?.forEach((pc, remoteUserId) => {
+ if (!participantIds.has(remoteUserId)) {
+ if (this.#presencePending.has(roomId, remoteUserId)) {
+ return;
+ }
+ hasPeerLeft = true;
+ this.#peerManager.destroy(roomId, remoteUserId);
+ }
+ });
+
+ for (const participant of participants) {
+ const participantId = Number(participant.id);
+ if (!participantId || participantId <= 0) {
+ continue;
+ }
+ if (participantId === currentUserId) {
+ continue;
+ }
+
+ if (isStage) {
+ const theyCanSpeak =
+ participant.role === "moderator" || participant.role === "speaker";
+ const shouldConnect = iCanSpeak || theyCanSpeak;
+
+ if (!shouldConnect) {
+ if (this.#peerManager.has(roomId, participantId)) {
+ this.#peerManager.destroy(roomId, participantId);
+ }
+ continue;
+ }
+ }
+
+ if (!this.#peerManager.has(roomId, participantId)) {
+ if (existingPeerIds.size > 0 || !this.#isConnectingRoom(roomId)) {
+ hasNewPeer = true;
+ }
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] creating peer connection to user ${participantId}`
+ );
+
+ await this.#createAndOfferPeer(roomId, participantId);
+ } else {
+ this.#presencePending.clear(roomId, participantId);
+ }
+ }
+ } else {
+ ({ hasNewPeer, hasPeerLeft } = this.#livekit.syncRoster(
+ roomId,
+ participants
+ ));
+ }
+
+ if (this.#isActiveRoom(roomId)) {
+ if (hasNewPeer) {
+ // If this client was ringing (caller waiting alone in a call room),
+ // someone arriving means the call was answered.
+ stopCallSounds();
+ playUserJoinedSound(this.#getChatSound());
+ } else if (hasPeerLeft) {
+ playUserLeftSound(this.#getChatSound());
+ }
+ }
+
+ this.#syncRemoteVideoTracks(roomId, participants);
+ this.#dropDisallowedStreams(roomId, participants, { isStage });
+
+ if (!this.#isMeshRoom(roomId)) {
+ // Publisher-count changes move camera subscriptions between simulcast
+ // layers.
+ this.#livekit.sessionFor(roomId)?.updateSubscriberQuality();
+ }
+
+ if (this.#getLocalVideoKind()) {
+ await this.#syncVideoSenders(roomId);
+ }
+ }
+
+ #syncRemoteVideoTracks(roomId, participants) {
+ for (const participant of participants || []) {
+ const participantId = Number(participant?.id);
+ if (!participantId || participantId === this.#getCurrentUserId()) {
+ continue;
+ }
+
+ if (!participant.is_video_on && !participant.is_screen_sharing) {
+ continue;
+ }
+
+ const track = this.#peerManager.remoteVideoTrack(roomId, participantId);
+ if (track) {
+ this.#registerTrack(roomId, participantId, track);
+ }
+ }
+ }
+
+ // Re-evaluates playing media against the fresh roster: a mesh participant
+ // demoted to a role that cannot publish must stop being heard immediately,
+ // even when the demotion arrives as a roster refresh rather than a
+ // role_change message. The receive-side track policy stops new tracks;
+ // this drops the ones already registered.
+ #dropDisallowedStreams(roomId, participants, { isStage }) {
+ if (!isStage || !this.#isMeshRoom(roomId)) {
+ return;
+ }
+
+ const allowedToPublish = new Set(
+ participants
+ .filter(
+ (participant) =>
+ participant.role === "moderator" || participant.role === "speaker"
+ )
+ .map((participant) => Number(participant.id))
+ );
+
+ for (const userId of this.#getRemoteUserIds(roomId)) {
+ if (!allowedToPublish.has(userId)) {
+ this.#removeRemoteStream(roomId, userId);
+ }
+ }
+ }
+
+ async handleRoleChange(roomId, payload) {
+ const targetUserId = Number(payload.user_id);
+ const newRole = payload.role;
+
+ if (targetUserId === this.#getCurrentUserId()) {
+ await this.#handleOwnRoleChange(roomId, newRole);
+ } else {
+ this.#handlePeerRoleChange(roomId, targetUserId);
+ }
+ }
+
+ async #handleOwnRoleChange(roomId, newRole) {
+ const canSpeak = newRole === "speaker" || newRole === "moderator";
+
+ // Block handleParticipants while we reconfigure the local stream,
+ // so the subsequent "participants" broadcast doesn't create peers
+ // before the mic is ready.
+ this.#roleChangeInProgress.add(roomId);
+
+ // Destroy all existing peers immediately. Mesh-only: on other transports
+ // the media session survives a role change untouched, so wiping the
+ // remote registry would silence everyone until they republished.
+ if (this.#isMeshRoom(roomId)) {
+ this.#peerManager.destroyRoom(roomId);
+ this.#removeAllRemoteStreams(roomId);
+ this.#signaling.clearForRoom(roomId);
+ this.#signaling.clearHttpQueue(roomId);
+ }
+
+ if (canSpeak) {
+ if (!this.#getLocalStream()) {
+ // The acquisition callback owns the user-facing failure feedback
+ // (permission help modal or toast).
+ const acquired = await this.#acquireMicrophone();
+ if (!acquired) {
+ this.#roleChangeInProgress.delete(roomId);
+ return;
+ }
+
+ this.#setMicEnabled(true);
+ }
+
+ this.#ensureLocalAudioMonitor(roomId);
+
+ this.#toasts.success({
+ duration: 5000,
+ data: { message: i18n("voice.stage.promoted_to_speaker") },
+ });
+ } else {
+ if (this.#getLocalVideoKind()) {
+ await this.#stopLocalVideo();
+ }
+ this.#stopLocalAudio();
+ this.#setMicEnabled(false);
+ this.#toasts.default({
+ duration: 5000,
+ data: { message: i18n("voice.stage.demoted_to_listener") },
+ });
+ }
+
+ this.#roleChangeInProgress.delete(roomId);
+
+ // Rebuild peers now that the local stream is ready (or stopped).
+ // Mesh-only: peer rebuilds are meaningless on other transports.
+ if (this.#isMeshRoom(roomId)) {
+ this.#reconnectAllPeers(roomId);
+ } else {
+ // The SFU connection survives the role change; just publish or release
+ // the microphone to match the new role.
+ try {
+ await this.#livekit.sessionFor(roomId)?.refreshPublications();
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[voice-livekit] failed to refresh publications after a role change in room ${roomId}`,
+ error
+ );
+ }
+ }
+ }
+
+ handleHandRaise(roomId, payload) {
+ const targetUserId = Number(payload.user_id);
+ const isSelf = targetUserId === this.#getCurrentUserId();
+
+ if (isSelf && !payload.raised && payload.reason === "dismissed") {
+ this.#toasts.default({
+ duration: 5000,
+ data: { message: i18n("voice.stage.request_dismissed") },
+ });
+ return;
+ }
+
+ const room = this.#getRoom(roomId);
+ if (!isSelf && payload.raised && room?.can_manage) {
+ const participant = (room.active_participants || []).find(
+ (p) => Number(p?.id) === targetUserId
+ );
+ if (participant) {
+ this.#toasts.default({
+ duration: 5000,
+ data: {
+ message: i18n("voice.stage.hand_raised_toast", {
+ username: participant.username,
+ }),
+ },
+ });
+ }
+ }
+ }
+
+ #handlePeerRoleChange(roomId, userId) {
+ // Destroy the stale peer; the subsequent "participants" broadcast
+ // from the server will rebuild connections with the correct topology.
+ if (this.#peerManager.has(roomId, userId)) {
+ this.#peerManager.destroy(roomId, userId);
+ this.#removeRemoteStream(roomId, userId);
+ }
+ }
+
+ async #createAndOfferPeer(roomId, remoteUserId) {
+ await this.#peerManager.create(roomId, remoteUserId);
+ if (this.#getCurrentUserId() <= remoteUserId) {
+ await this.#peerManager.initiateOffer(roomId, remoteUserId);
+ } else {
+ this.#peerManager.scheduleOfferRetry(roomId, remoteUserId);
+ }
+ }
+
+ #reconnectAllPeers(roomId) {
+ this.#peerManager.destroyRoom(roomId);
+ this.#removeAllRemoteStreams(roomId);
+ this.#signaling.clearForRoom(roomId);
+ this.#signaling.clearHttpQueue(roomId);
+
+ const room = this.#getRoom(roomId);
+ if (!room) {
+ return;
+ }
+
+ const participants = room.active_participants || [];
+ const iCanSpeak = participantCanSpeak(room, this.#getCurrentUserId());
+
+ for (const participant of participants) {
+ const participantId = Number(participant?.id);
+ if (participantId === this.#getCurrentUserId()) {
+ continue;
+ }
+
+ const theyCanSpeak = participantCanSpeak(room, participantId);
+ const shouldConnect = iCanSpeak || theyCanSpeak;
+
+ if (shouldConnect) {
+ this.#createAndOfferPeer(roomId, participantId);
+ }
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/sdp-utils.js b/plugins/voice/assets/javascripts/discourse/lib/voice/sdp-utils.js
new file mode 100644
index 00000000000..2cdf84d3ae9
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/sdp-utils.js
@@ -0,0 +1,7 @@
+// Extract the ICE username fragment from an SDP. A new value vs the prior
+// remote description signals the peer restarted its ICE session (e.g. left
+// and rejoined), which needs a fresh peer rather than a renegotiation.
+export function iceUfrag(sdp) {
+ const match = sdp?.match(/^a=ice-ufrag:(\S+)/m);
+ return match ? match[1] : null;
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js b/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js
new file mode 100644
index 00000000000..60047e7cc78
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js
@@ -0,0 +1,423 @@
+import { ajax } from "discourse/lib/ajax";
+
+export default class SignalingManager {
+ static #defaultCandidateBatchDelayMs = 75;
+ static #defaultCandidateBatchSize = 5;
+ static #defaultHttpBatchDelayMs = 200;
+ // The server rejects batches with more than 25 events for one recipient;
+ // flushing at 20 keeps a candidate batch appended mid-window under that cap.
+ static #httpFlushEventThreshold = 20;
+
+ static peerKey(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ static #buildPayload(messages) {
+ if (messages.length === 1) {
+ const [message] = messages;
+
+ if (message.events.length === 1) {
+ return {
+ ...message.events[0],
+ recipient_id: message.recipient_id,
+ };
+ }
+
+ return {
+ recipient_id: message.recipient_id,
+ events: message.events,
+ };
+ }
+
+ return {
+ messages: messages.map((message) => ({
+ recipient_id: message.recipient_id,
+ events: message.events,
+ })),
+ };
+ }
+
+ #candidateBatchDelayMs;
+ #candidateBatchSize;
+ #httpBatchDelayMs;
+
+ #destroyed = false;
+ #signalQueues = new Map();
+ #signalFlushTimers = new Map();
+ #httpSignalQueues = new Map();
+ #httpSignalFlushTimers = new Map();
+
+ #isActiveRoom;
+ #hasPeer;
+ #getParticipantSessionId;
+ #requestSignals;
+
+ constructor({
+ isActiveRoom,
+ hasPeer,
+ getParticipantSessionId = () => undefined,
+ requestSignals,
+ candidateBatchDelayMs = SignalingManager.#defaultCandidateBatchDelayMs,
+ candidateBatchSize = SignalingManager.#defaultCandidateBatchSize,
+ httpBatchDelayMs = SignalingManager.#defaultHttpBatchDelayMs,
+ }) {
+ this.#isActiveRoom = isActiveRoom;
+ this.#hasPeer = hasPeer;
+ this.#getParticipantSessionId = getParticipantSessionId;
+ this.#requestSignals =
+ requestSignals ??
+ ((roomId, payload) =>
+ ajax(`/voice/rooms/${roomId}/signal`, {
+ type: "POST",
+ data: {
+ payload,
+ participant_session_id: this.#getParticipantSessionId(roomId),
+ },
+ }));
+ this.#candidateBatchDelayMs = candidateBatchDelayMs;
+ this.#candidateBatchSize = candidateBatchSize;
+ this.#httpBatchDelayMs = httpBatchDelayMs;
+ }
+
+ async send(roomId, recipientId, payload) {
+ if (this.#destroyed || !roomId || !recipientId || !payload) {
+ return;
+ }
+
+ if (!this.#isActiveRoom(roomId)) {
+ return;
+ }
+
+ if (!this.#hasPeer(roomId, recipientId)) {
+ return;
+ }
+
+ if (payload.type === "candidate") {
+ this.#queue(roomId, recipientId, payload);
+ return;
+ }
+
+ await this.flushQueued(roomId, recipientId);
+
+ if (!this.#isActiveRoom(roomId) || !this.#hasPeer(roomId, recipientId)) {
+ return;
+ }
+
+ await this.#postSignals(roomId, recipientId, [payload]);
+ }
+
+ #queue(roomId, recipientId, payload) {
+ const key = SignalingManager.peerKey(roomId, recipientId);
+ const queue = this.#signalQueues.get(key) || [];
+ queue.push(payload);
+ this.#signalQueues.set(key, queue);
+
+ if (queue.length >= this.#candidateBatchSize) {
+ this.flushQueued(roomId, recipientId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush signal queue", error);
+ });
+ return;
+ }
+
+ const existingTimer = this.#signalFlushTimers.get(key);
+ if (existingTimer) {
+ clearTimeout(existingTimer);
+ }
+
+ const timer = setTimeout(() => {
+ this.#signalFlushTimers.delete(key);
+ this.flushQueued(roomId, recipientId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush signal queue", error);
+ });
+ }, this.#candidateBatchDelayMs);
+
+ this.#signalFlushTimers.set(key, timer);
+ }
+
+ async flushQueued(roomId, recipientId) {
+ const key = SignalingManager.peerKey(roomId, recipientId);
+ const queue = this.#signalQueues.get(key);
+
+ if (!queue?.length) {
+ return;
+ }
+
+ this.#signalQueues.delete(key);
+
+ const timer = this.#signalFlushTimers.get(key);
+ if (timer) {
+ clearTimeout(timer);
+ this.#signalFlushTimers.delete(key);
+ }
+
+ if (!this.#isActiveRoom(roomId) || !this.#hasPeer(roomId, recipientId)) {
+ return;
+ }
+
+ await this.#postSignals(roomId, recipientId, queue);
+ }
+
+ async #postSignals(roomId, recipientId, events) {
+ if (!events?.length || !this.#isActiveRoom(roomId)) {
+ return;
+ }
+
+ await this.#enqueueHttp(roomId, recipientId, events);
+ }
+
+ #enqueueHttp(roomId, recipientId, events) {
+ if (this.#destroyed || !roomId || !recipientId || !events?.length) {
+ return Promise.resolve();
+ }
+
+ let entry = this.#httpSignalQueues.get(roomId);
+
+ if (!entry) {
+ entry = {
+ recipients: new Map(),
+ pending: [],
+ };
+
+ this.#httpSignalQueues.set(roomId, entry);
+ }
+
+ const roomQueue = entry.recipients;
+ const existingEvents = roomQueue.get(recipientId);
+
+ if (existingEvents) {
+ existingEvents.push(...events);
+ } else {
+ roomQueue.set(recipientId, [...events]);
+ }
+
+ const promise = new Promise((resolve, reject) => {
+ entry.pending.push({ recipientId, resolve, reject });
+ });
+
+ const queuedEvents = roomQueue.get(recipientId);
+ if (queuedEvents.length >= SignalingManager.#httpFlushEventThreshold) {
+ const timer = this.#httpSignalFlushTimers.get(roomId);
+ if (timer) {
+ clearTimeout(timer);
+ this.#httpSignalFlushTimers.delete(roomId);
+ }
+ this.#flushHttp(roomId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush HTTP signal queue", error);
+ });
+ } else {
+ this.#scheduleHttpFlush(roomId);
+ }
+
+ return promise;
+ }
+
+ #scheduleHttpFlush(roomId) {
+ if (this.#destroyed || this.#httpSignalFlushTimers.has(roomId)) {
+ return;
+ }
+
+ const timer = setTimeout(() => {
+ this.#httpSignalFlushTimers.delete(roomId);
+ this.#flushHttp(roomId).catch((error) => {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to flush HTTP signal queue", error);
+ });
+ }, this.#httpBatchDelayMs);
+
+ this.#httpSignalFlushTimers.set(roomId, timer);
+ }
+
+ async #flushHttp(roomId) {
+ const entry = this.#httpSignalQueues.get(roomId);
+ if (!entry) {
+ return;
+ }
+
+ if (!this.#isActiveRoom(roomId)) {
+ entry.recipients?.clear?.();
+ this.#settlePending(entry.pending.splice(0), "resolve");
+ this.#httpSignalQueues.delete(roomId);
+ return;
+ }
+
+ const roomQueue = entry.recipients;
+ const pending = entry.pending;
+ entry.recipients = new Map();
+ entry.pending = [];
+
+ if (!roomQueue?.size) {
+ this.#settlePending(pending, "resolve");
+ if (!entry.recipients.size && !entry.pending.length) {
+ this.#httpSignalQueues.delete(roomId);
+ }
+ return;
+ }
+
+ const messages = [];
+ const activeRecipientIds = new Set();
+
+ roomQueue.forEach((events, recipientId) => {
+ if (!events?.length || !this.#hasPeer(roomId, recipientId)) {
+ return;
+ }
+
+ messages.push({
+ recipient_id: recipientId,
+ events,
+ });
+ activeRecipientIds.add(recipientId);
+ });
+
+ const [batchPending, droppedPending] = this.#partitionPending(
+ pending,
+ activeRecipientIds
+ );
+ this.#settlePending(droppedPending, "resolve");
+
+ if (!messages.length) {
+ this.#settlePending(batchPending, "resolve");
+ if (!entry.recipients.size && !entry.pending.length) {
+ this.#httpSignalQueues.delete(roomId);
+ }
+ return;
+ }
+
+ const payload = SignalingManager.#buildPayload(messages);
+
+ // eslint-disable-next-line no-console
+ console.log(
+ `[voice] 🚀 sending ${messages.length} batched signal recipient(s) in room ${roomId}`
+ );
+
+ try {
+ await this.#requestSignals(roomId, payload);
+
+ this.#settlePending(batchPending, "resolve");
+ } catch (error) {
+ this.#settlePending(batchPending, "reject", error);
+ throw error;
+ } finally {
+ if (!entry.recipients.size && !entry.pending.length) {
+ this.#httpSignalQueues.delete(roomId);
+ }
+ }
+ }
+
+ clearForPeer(roomId, recipientId) {
+ const key = SignalingManager.peerKey(roomId, recipientId);
+ const timer = this.#signalFlushTimers.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#signalFlushTimers.delete(key);
+ }
+
+ this.#signalQueues.delete(key);
+
+ const entry = this.#httpSignalQueues.get(roomId);
+ if (!entry) {
+ return;
+ }
+
+ entry.recipients?.delete?.(recipientId);
+
+ const [clearedPending, retainedPending] = this.#partitionPending(
+ entry.pending,
+ new Set(),
+ recipientId
+ );
+
+ entry.pending = retainedPending;
+ this.#settlePending(clearedPending, "resolve");
+
+ if (!entry.recipients.size && !entry.pending.length) {
+ this.#httpSignalQueues.delete(roomId);
+ }
+ }
+
+ clearForRoom(roomId) {
+ const prefix = `${roomId}:`;
+
+ Array.from(this.#signalQueues.keys()).forEach((key) => {
+ if (!key.startsWith(prefix)) {
+ return;
+ }
+
+ const timer = this.#signalFlushTimers.get(key);
+
+ if (timer) {
+ clearTimeout(timer);
+ this.#signalFlushTimers.delete(key);
+ }
+
+ this.#signalQueues.delete(key);
+ });
+ }
+
+ clearHttpQueue(roomId) {
+ const timer = this.#httpSignalFlushTimers.get(roomId);
+ if (timer) {
+ clearTimeout(timer);
+ this.#httpSignalFlushTimers.delete(roomId);
+ }
+
+ const entry = this.#httpSignalQueues.get(roomId);
+ if (!entry) {
+ return;
+ }
+
+ entry.recipients?.clear?.();
+ this.#settlePending(entry.pending || [], "resolve");
+ entry.pending = [];
+ this.#httpSignalQueues.delete(roomId);
+ }
+
+ // Terminal: no further signals are queued or flushed afterwards, so a
+ // continuation resumed after teardown cannot schedule a late HTTP flush.
+ destroy() {
+ this.#destroyed = true;
+
+ this.#signalFlushTimers.forEach((timer) => clearTimeout(timer));
+ this.#signalFlushTimers.clear();
+ this.#httpSignalFlushTimers.forEach((timer) => clearTimeout(timer));
+ this.#httpSignalFlushTimers.clear();
+ this.#httpSignalQueues.forEach((entry) => {
+ this.#settlePending(entry?.pending || [], "resolve");
+ });
+ this.#httpSignalQueues.clear();
+ this.#signalQueues.clear();
+ }
+
+ #partitionPending(pending, allowedRecipientIds, clearedRecipientId = null) {
+ const batchPending = [];
+ const retainedPending = [];
+
+ for (const entry of pending || []) {
+ if (clearedRecipientId !== null) {
+ if (entry.recipientId === clearedRecipientId) {
+ batchPending.push(entry);
+ } else {
+ retainedPending.push(entry);
+ }
+ continue;
+ }
+
+ if (allowedRecipientIds.has(entry.recipientId)) {
+ batchPending.push(entry);
+ } else {
+ retainedPending.push(entry);
+ }
+ }
+
+ return [batchPending, retainedPending];
+ }
+
+ #settlePending(pending, action, error = null) {
+ for (const entry of pending || []) {
+ entry?.[action]?.(error);
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/sound-effects.js b/plugins/voice/assets/javascripts/discourse/lib/voice/sound-effects.js
new file mode 100644
index 00000000000..150508d3491
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/sound-effects.js
@@ -0,0 +1,608 @@
+import { RING_SECONDS } from "./call-constants";
+
+let sharedCtx = null;
+
+async function getAudioContext() {
+ if (!sharedCtx || sharedCtx.state === "closed") {
+ sharedCtx = new AudioContext();
+ }
+ if (sharedCtx.state === "suspended") {
+ await sharedCtx.resume();
+ }
+ return sharedCtx;
+}
+
+const CUE_PATTERNS = {
+ connected: {
+ direction: "up",
+ notes: [
+ { frequency: 523.25, offset: 0, duration: 0.15, gain: 0.15 },
+ { frequency: 659.25, offset: 0.1, duration: 0.15, gain: 0.15 },
+ ],
+ },
+ disconnected: {
+ direction: "down",
+ notes: [
+ { frequency: 659.25, offset: 0, duration: 0.15, gain: 0.15 },
+ { frequency: 523.25, offset: 0.1, duration: 0.15, gain: 0.15 },
+ ],
+ },
+ joined: {
+ direction: "up",
+ notes: [{ frequency: 659.25, offset: 0, duration: 0.1, gain: 0.12 }],
+ },
+ left: {
+ direction: "down",
+ notes: [{ frequency: 523.25, offset: 0, duration: 0.1, gain: 0.12 }],
+ },
+ muted: {
+ direction: "down",
+ notes: [{ frequency: 392, offset: 0, duration: 0.08, gain: 0.1 }],
+ },
+ unmuted: {
+ direction: "up",
+ notes: [{ frequency: 440, offset: 0, duration: 0.08, gain: 0.1 }],
+ },
+ deafened: {
+ direction: "down",
+ notes: [
+ { frequency: 392, offset: 0, duration: 0.07, gain: 0.1 },
+ { frequency: 293.66, offset: 0.07, duration: 0.07, gain: 0.1 },
+ ],
+ },
+ undeafened: {
+ direction: "up",
+ notes: [
+ { frequency: 293.66, offset: 0, duration: 0.07, gain: 0.1 },
+ { frequency: 392, offset: 0.07, duration: 0.07, gain: 0.1 },
+ ],
+ },
+};
+
+async function playCue(cueName, soundName) {
+ try {
+ const ctx = await getAudioContext();
+ const theme = SOUND_THEMES[normalizeSoundName(soundName)];
+ theme.cue(ctx, ctx.destination, CUE_PATTERNS[cueName], ctx.currentTime);
+ } catch {
+ // audio not available
+ }
+}
+
+export function playConnectedSound(soundName) {
+ return playCue("connected", soundName);
+}
+
+export function playDisconnectedSound(soundName) {
+ return playCue("disconnected", soundName);
+}
+
+export function playUserJoinedSound(soundName) {
+ return playCue("joined", soundName);
+}
+
+export function playUserLeftSound(soundName) {
+ return playCue("left", soundName);
+}
+
+export function playMuteSound(soundName) {
+ return playCue("muted", soundName);
+}
+
+export function playUnmuteSound(soundName) {
+ return playCue("unmuted", soundName);
+}
+
+export function playDeafenSound(soundName) {
+ return playCue("deafened", soundName);
+}
+
+export function playUndeafenSound(soundName) {
+ return playCue("undeafened", soundName);
+}
+
+let ringtoneTimer = null;
+let waitingTimer = null;
+
+export const DEFAULT_SOUND_NAME = "classic";
+
+const MIN_GAIN = 0.001;
+const CALL_SOUND_START_DELAY = 0.05;
+
+function playCallOscillator(
+ ctx,
+ output,
+ { type = "sine", frequency, startTime, duration, gain: maxGain, attack = 0 }
+) {
+ const oscillator = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ oscillator.type = type;
+ oscillator.frequency.value = frequency;
+ if (attack > 0) {
+ gain.gain.setValueAtTime(MIN_GAIN, startTime);
+ gain.gain.linearRampToValueAtTime(maxGain, startTime + attack);
+ } else {
+ gain.gain.setValueAtTime(maxGain, startTime);
+ }
+ gain.gain.exponentialRampToValueAtTime(MIN_GAIN, startTime + duration);
+
+ oscillator.connect(gain).connect(output);
+ oscillator.start(startTime);
+ oscillator.stop(startTime + duration + 0.02);
+}
+
+function playCallSweep(
+ ctx,
+ output,
+ { type = "sine", from, to, startTime, rampDuration, duration, gain: maxGain }
+) {
+ const oscillator = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ oscillator.type = type;
+ oscillator.frequency.setValueAtTime(from, startTime);
+ oscillator.frequency.exponentialRampToValueAtTime(
+ to,
+ startTime + rampDuration
+ );
+ gain.gain.setValueAtTime(maxGain, startTime);
+ gain.gain.exponentialRampToValueAtTime(MIN_GAIN, startTime + duration);
+
+ oscillator.connect(gain).connect(output);
+ oscillator.start(startTime);
+ oscillator.stop(startTime + duration + 0.02);
+}
+
+function playClassicCue(ctx, output, pattern, startTime) {
+ pattern.notes.forEach(({ offset, ...note }) => {
+ playCallOscillator(ctx, output, {
+ ...note,
+ startTime: startTime + offset,
+ });
+ });
+}
+
+function playSoftCue(ctx, output, pattern, startTime) {
+ pattern.notes.forEach(({ frequency, offset, duration, gain }) => {
+ playCallOscillator(ctx, output, {
+ frequency: frequency * (2 / 3),
+ startTime: startTime + offset * 1.2,
+ duration: duration * 1.5,
+ gain: gain * 0.85,
+ attack: 0.025,
+ });
+ });
+}
+
+function playRetroCue(ctx, output, pattern, startTime) {
+ pattern.notes.forEach(({ frequency, offset, duration, gain }) => {
+ playCallOscillator(ctx, output, {
+ type: "square",
+ frequency,
+ startTime: startTime + offset * 0.8,
+ duration: Math.max(duration * 0.8, 0.06),
+ gain: gain * 0.28,
+ });
+ });
+}
+
+function playBubbleCue(ctx, output, pattern, startTime) {
+ const rises = pattern.direction === "up";
+
+ pattern.notes.forEach(({ frequency, offset, duration, gain }) => {
+ const sweepDuration = Math.max(duration * 1.4, 0.12);
+ playCallSweep(ctx, output, {
+ from: frequency * (rises ? 0.72 : 1.28),
+ to: frequency * (rises ? 1.18 : 0.82),
+ startTime: startTime + offset,
+ rampDuration: sweepDuration * 0.65,
+ duration: sweepDuration,
+ gain: gain * 0.85,
+ });
+ });
+}
+
+function playEtherealCue(ctx, output, pattern, startTime) {
+ pattern.notes.forEach(({ frequency, offset, duration, gain }) => {
+ playCallOscillator(ctx, output, {
+ frequency,
+ startTime: startTime + offset * 1.4,
+ duration: Math.max(duration * 2.8, 0.28),
+ gain: gain * 0.4,
+ attack: 0.05,
+ });
+ });
+}
+
+const SOUND_THEMES = {
+ classic: {
+ cue: playClassicCue,
+ ringtone(ctx, output, startTime) {
+ const notes = [523.25, 659.25, 783.99, 1046.5];
+ [0, 0.45].forEach((offset) => {
+ notes.forEach((frequency, index) => {
+ playCallOscillator(ctx, output, {
+ frequency,
+ startTime: startTime + offset + index * 0.075,
+ duration: index === 3 ? 0.22 : 0.12,
+ gain: 0.14,
+ });
+ });
+ });
+ },
+ ringtoneCycle: 1.7,
+
+ waiting(ctx, output, startTime) {
+ playCallOscillator(ctx, output, {
+ frequency: 523.25,
+ startTime,
+ duration: 1.1,
+ gain: 0.12,
+ attack: 0.08,
+ });
+ playCallOscillator(ctx, output, {
+ frequency: 659.25,
+ startTime: startTime + 0.04,
+ duration: 1.1,
+ gain: 0.12,
+ attack: 0.08,
+ });
+ },
+ waitingCycle: 2,
+ },
+
+ soft: {
+ cue: playSoftCue,
+ ringtone(ctx, output, startTime) {
+ [0, 0.68].forEach((offset) => {
+ [349.23, 440, 523.25].forEach((frequency, index) => {
+ playCallOscillator(ctx, output, {
+ frequency,
+ startTime: startTime + offset + index * 0.11,
+ duration: index === 2 ? 0.45 : 0.28,
+ gain: 0.12,
+ });
+ });
+ });
+ },
+ ringtoneCycle: 2.1,
+
+ waiting(ctx, output, startTime) {
+ playCallOscillator(ctx, output, {
+ frequency: 349.23,
+ startTime,
+ duration: 1.15,
+ gain: 0.1,
+ attack: 0.1,
+ });
+ playCallOscillator(ctx, output, {
+ frequency: 466.16,
+ startTime: startTime + 0.08,
+ duration: 1.05,
+ gain: 0.09,
+ attack: 0.1,
+ });
+ },
+ waitingCycle: 2.1,
+ },
+
+ retro: {
+ cue: playRetroCue,
+ ringtone(ctx, output, startTime) {
+ [0, 0.42].forEach((offset) => {
+ [392, 493.88, 587.33, 783.99].forEach((frequency, index) => {
+ playCallOscillator(ctx, output, {
+ type: "square",
+ frequency,
+ startTime: startTime + offset + index * 0.07,
+ duration: index === 3 ? 0.16 : 0.1,
+ gain: 0.035,
+ });
+ });
+ });
+ },
+ ringtoneCycle: 1.55,
+
+ waiting(ctx, output, startTime) {
+ [0, 0.18].forEach((offset, index) => {
+ playCallOscillator(ctx, output, {
+ type: "square",
+ frequency: index === 0 ? 392 : 493.88,
+ startTime: startTime + offset,
+ duration: 0.14,
+ gain: 0.025,
+ });
+ });
+ },
+ waitingCycle: 1.3,
+ },
+
+ bubble: {
+ cue: playBubbleCue,
+ ringtone(ctx, output, startTime) {
+ [0, 0.48].forEach((offset) => {
+ playCallSweep(ctx, output, {
+ from: 300,
+ to: 700,
+ startTime: startTime + offset,
+ rampDuration: 0.1,
+ duration: 0.16,
+ gain: 0.13,
+ });
+ playCallSweep(ctx, output, {
+ from: 420,
+ to: 980,
+ startTime: startTime + offset + 0.13,
+ rampDuration: 0.11,
+ duration: 0.18,
+ gain: 0.11,
+ });
+ });
+ },
+ ringtoneCycle: 1.55,
+
+ waiting(ctx, output, startTime) {
+ playCallSweep(ctx, output, {
+ from: 280,
+ to: 620,
+ startTime,
+ rampDuration: 0.22,
+ duration: 0.42,
+ gain: 0.09,
+ });
+ },
+ waitingCycle: 1.5,
+ },
+
+ ethereal: {
+ cue: playEtherealCue,
+ ringtone(ctx, output, startTime) {
+ [523.25, 659.25, 783.99].forEach((frequency) => {
+ playCallOscillator(ctx, output, {
+ frequency,
+ startTime,
+ duration: 1.4,
+ gain: 0.045,
+ attack: 0.12,
+ });
+ });
+ playCallSweep(ctx, output, {
+ from: 880,
+ to: 1320,
+ startTime: startTime + 0.18,
+ rampDuration: 0.3,
+ duration: 1.05,
+ gain: 0.035,
+ });
+ },
+ ringtoneCycle: 2.15,
+
+ waiting(ctx, output, startTime) {
+ [440, 554.37, 659.25].forEach((frequency) => {
+ playCallOscillator(ctx, output, {
+ frequency,
+ startTime,
+ duration: 1.65,
+ gain: 0.035,
+ attack: 0.18,
+ });
+ });
+ },
+ waitingCycle: 2.4,
+ },
+};
+
+export function normalizeSoundName(name) {
+ return SOUND_THEMES[name] ? name : DEFAULT_SOUND_NAME;
+}
+
+// The loops stop themselves at the ring window so no caller has to remember
+// to. Explicit stops (answer, decline, hang up) come sooner.
+const MAX_CALL_LOOP_MS = RING_SECONDS * 1000;
+
+// Bumped on every start/stop so an in-flight start that was parked on an
+// AudioContext await can tell it has been superseded and must not begin
+// playing (e.g. a ringtone start that only unblocks once the user joins).
+let callSoundGeneration = 0;
+
+// All loop audio routes through this node so stopping can silence tones the
+// scheduler already queued, not just cancel the next cycle.
+let callLoopGain = null;
+
+// Ringing is triggered by a MessageBus event, not a user gesture. Without a
+// prior gesture the context may not only refuse to resume — resume() can sit
+// pending until the next gesture, so awaiting it outright would start the
+// sound at whatever the user does next. Race it against a short timeout and
+// report the state we actually reached.
+async function runningAudioContext() {
+ if (!sharedCtx || sharedCtx.state === "closed") {
+ sharedCtx = new AudioContext();
+ }
+ if (sharedCtx.state === "suspended") {
+ await Promise.race([
+ sharedCtx.resume().catch(() => {}),
+ new Promise((resolve) => setTimeout(resolve, 300)),
+ ]);
+ }
+ return sharedCtx.state === "running" ? sharedCtx : null;
+}
+
+// Warms up the shared AudioContext inside a user gesture so sounds scheduled
+// after later awaits (e.g. once a call request round-trips) still play.
+export function unlockAudio() {
+ getAudioContext().catch(() => {});
+}
+
+/**
+ * Start the looping incoming-call ringtone on the callee's device.
+ *
+ * @param {string} [soundName] the listener's chat notification sound name
+ * @returns {Promise<boolean>} whether audio is actually playing
+ */
+export async function startRingtone(soundName) {
+ stopCallSounds();
+ const generation = ++callSoundGeneration;
+ try {
+ const ctx = await runningAudioContext();
+ if (!ctx || generation !== callSoundGeneration) {
+ return false;
+ }
+
+ const output = ctx.createGain();
+ output.connect(ctx.destination);
+ callLoopGain = output;
+
+ let nextTime = ctx.currentTime + CALL_SOUND_START_DELAY;
+ const startedAt = Date.now();
+ const theme = SOUND_THEMES[normalizeSoundName(soundName)];
+
+ const schedule = () => {
+ if (!ringtoneTimer || generation !== callSoundGeneration) {
+ return;
+ }
+ if (Date.now() - startedAt >= MAX_CALL_LOOP_MS) {
+ stopCallSounds();
+ return;
+ }
+
+ theme.ringtone(ctx, output, nextTime);
+ nextTime += theme.ringtoneCycle;
+
+ ringtoneTimer = setTimeout(
+ schedule,
+ Math.max((theme.ringtoneCycle - 0.2) * 1000, 200)
+ );
+ };
+
+ ringtoneTimer = true;
+ schedule();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Start the looping waiting (ringback) tone on the caller's device.
+ *
+ * @param {number} [maxDurationMs] cap below the full ring window, e.g. when
+ * resuming partway through an already-running ring
+ * @param {string} [soundName] the listener's chat notification sound name
+ * @returns {Promise<boolean>} whether audio is actually playing
+ */
+export async function startWaitingSound(
+ maxDurationMs = MAX_CALL_LOOP_MS,
+ soundName
+) {
+ stopCallSounds();
+ const generation = ++callSoundGeneration;
+ const capMs = Math.min(maxDurationMs, MAX_CALL_LOOP_MS);
+ if (capMs <= 0) {
+ return false;
+ }
+ try {
+ const ctx = await runningAudioContext();
+ if (!ctx || generation !== callSoundGeneration) {
+ return false;
+ }
+
+ const output = ctx.createGain();
+ output.connect(ctx.destination);
+ callLoopGain = output;
+
+ let nextTime = ctx.currentTime + CALL_SOUND_START_DELAY;
+ const startedAt = Date.now();
+ const theme = SOUND_THEMES[normalizeSoundName(soundName)];
+
+ const schedule = () => {
+ if (!waitingTimer || generation !== callSoundGeneration) {
+ return;
+ }
+ if (Date.now() - startedAt >= capMs) {
+ stopCallSounds();
+ return;
+ }
+
+ theme.waiting(ctx, output, nextTime);
+ nextTime += theme.waitingCycle;
+
+ waitingTimer = setTimeout(
+ schedule,
+ Math.max((theme.waitingCycle - 0.2) * 1000, 200)
+ );
+ };
+
+ waitingTimer = true;
+ schedule();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Stop whichever call loop (ringtone or waiting tone) is active.
+ */
+export function stopCallSounds() {
+ // Invalidates starts still parked on the AudioContext await, so a ringtone
+ // blocked on a missing user gesture can't begin playing after the fact.
+ callSoundGeneration++;
+
+ if (ringtoneTimer) {
+ clearTimeout(ringtoneTimer);
+ ringtoneTimer = null;
+ }
+ if (waitingTimer) {
+ clearTimeout(waitingTimer);
+ waitingTimer = null;
+ }
+
+ // Cutting the loop's shared output silences tones already scheduled on the
+ // context, which cancelling the next cycle alone would let ring out.
+ if (callLoopGain) {
+ try {
+ callLoopGain.disconnect();
+ } catch {
+ // already disconnected
+ }
+ callLoopGain = null;
+ }
+}
+
+export function resetSoundEffectsForTesting() {
+ stopCallSounds();
+ try {
+ sharedCtx?.close?.();
+ } catch {
+ // already closed
+ }
+ sharedCtx = null;
+}
+
+export function schedulePlaybackResume(element, pendingPlaybackElements) {
+ if (
+ !element ||
+ typeof document === "undefined" ||
+ pendingPlaybackElements.has(element)
+ ) {
+ return;
+ }
+
+ pendingPlaybackElements.add(element);
+
+ const resume = () => {
+ try {
+ element.play?.();
+ } catch {
+ // ignore subsequent failures
+ }
+
+ document.removeEventListener("pointerdown", resume);
+ document.removeEventListener("keydown", resume);
+ pendingPlaybackElements.delete(element);
+ };
+
+ document.addEventListener("pointerdown", resume, { once: true });
+ document.addEventListener("keydown", resume, { once: true });
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/speak-queue.js b/plugins/voice/assets/javascripts/discourse/lib/voice/speak-queue.js
new file mode 100644
index 00000000000..21b84a93355
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/speak-queue.js
@@ -0,0 +1,27 @@
+// The request-to-speak queue is derived state: raised hands ride the
+// participants payload as `hand_raised_at`, so ordering is recomputed from
+// the roster instead of being tracked separately.
+export function speakQueue(room) {
+ if (room?.room_type !== "stage") {
+ return [];
+ }
+
+ return (room.active_participants || [])
+ .filter((participant) => participant?.hand_raised_at)
+ .sort(
+ (a, b) =>
+ a.hand_raised_at - b.hand_raised_at || Number(a.id) - Number(b.id)
+ );
+}
+
+export function queuePosition(room, userId) {
+ const targetId = Number(userId);
+ if (!targetId) {
+ return null;
+ }
+
+ const index = speakQueue(room).findIndex(
+ (participant) => Number(participant.id) === targetId
+ );
+ return index === -1 ? null : index + 1;
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/stage-roles.js b/plugins/voice/assets/javascripts/discourse/lib/voice/stage-roles.js
new file mode 100644
index 00000000000..d0fa69daf87
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/stage-roles.js
@@ -0,0 +1,35 @@
+// Stage rooms gate speaking on the participant's role; every other room type
+// lets anyone speak.
+export function participantCanSpeak(room, userId) {
+ if (room.room_type !== "stage") {
+ return true;
+ }
+
+ const participant = (room.active_participants || []).find(
+ (p) => Number(p?.id) === Number(userId)
+ );
+ const role = participant?.role;
+ return role === "moderator" || role === "speaker";
+}
+
+// Receive-side media policy. Remote client state (muted, role shown in the
+// UI) is not proof of what a peer put into its connection: a modified
+// listener can attach a microphone track the server would never let it
+// unmute. The server-broadcast roster and room capabilities are the
+// authority, so a track is only registered and played when the sender's
+// server-side role and the room's media policy allow publishing it.
+//
+// Mic audio arrives with the sender's stream attached; the pre-negotiated
+// screen-audio transceiver delivers a bare track (see RemoteStreamRegistry).
+export function remoteTrackAllowed(room, userId, track, streams) {
+ if (!room || !track) {
+ return false;
+ }
+
+ const isScreenAudio = track.kind === "audio" && !streams?.length;
+ if ((track.kind === "video" || isScreenAudio) && !room.video_allowed) {
+ return false;
+ }
+
+ return participantCanSpeak(room, userId);
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js b/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js
new file mode 100644
index 00000000000..4d1eedec7b1
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js
@@ -0,0 +1,602 @@
+import { voiceAssetAppUrl, voiceAssetUrl } from "./voice-assets";
+
+// Stable filenames in the discourse_voice_assets gem's stt/ directory.
+const STT_WORKER_FILE = "subtitles-worker.js";
+const VAD_BUNDLE_FILE = "vad.js";
+const ORT_WASM_JS_FILE = "ort/ort-wasm-simd-threaded.jsep.js";
+const ORT_WASM_BINARY_FILE = "ort/ort-wasm-simd-threaded.jsep.wasm";
+const VAD_ASSET_DIR = "vad/";
+
+// Live subtitles for room participants.
+//
+// Viewer-side: the user who turns subtitles on runs speech-to-text locally
+// on the audio they already receive, so nothing is required from the other
+// participants and no audio ever leaves the browser. Each participant's mic
+// stream gets its own Silero VAD (finding utterance boundaries); committed
+// utterances are transcribed by a single shared Parakeet model living in a
+// Web Worker (WebGPU encoder), which serializes jobs across speakers.
+//
+// The runtime bundles are served from the plugin's public dir and only
+// fetched the first time subtitles are enabled; the ~2.5GB model weights
+// come from the `voice_stt_model_base_url` source (Discourse's
+// HuggingFace model repository by default), kept in a durable Cache API store.
+
+const PREFERENCE_KEY = "voice:subtitles";
+
+// If neither "ready" nor "error" arrives in this window, something wedged
+// (e.g. a stalled model download on the last byte); fail like an error so
+// the toggle never shows an enabled-but-dead state. Generous because it
+// includes the first-run model download.
+const READY_TIMEOUT_MS = 30 * 60 * 1000;
+
+// Interim captions: while a speaker keeps talking, the utterance-so-far is
+// re-transcribed on a cadence and shown as a provisional line, so long
+// sentences don't sit uncaptioned until the speaker pauses. The final
+// (speech-end) pass replaces the provisional text.
+const VAD_SAMPLE_RATE = 16000;
+const INTERIM_MIN_SAMPLES = 1 * VAD_SAMPLE_RATE;
+const INTERIM_INTERVAL_SAMPLES = 1.5 * VAD_SAMPLE_RATE;
+// Interims re-encode the whole snapshot, so very long monologues slide: only
+// the newest audio is transcribed provisionally; the final pass still covers
+// the full utterance.
+const INTERIM_WINDOW_MAX_SAMPLES = 15 * VAD_SAMPLE_RATE;
+
+// The bundle stays resident after first use so re-enabling is instant.
+let vadModulePromise = null;
+
+function sttUrl(file) {
+ return voiceAssetUrl(`stt/${file}`);
+}
+
+// The one exception: workers must be same-origin, so the (small) worker
+// script always loads from the app. Everything it fetches uses sttUrl.
+function workerUrl() {
+ return voiceAssetAppUrl(`stt/${STT_WORKER_FILE}`);
+}
+
+async function loadVadModule() {
+ vadModulePromise ||= import(/* @vite-ignore */ sttUrl(VAD_BUNDLE_FILE));
+ try {
+ return await vadModulePromise;
+ } catch (error) {
+ // Allow a retry after a transient failure (e.g. offline asset fetch).
+ vadModulePromise = null;
+ throw error;
+ }
+}
+
+export default class SubtitlesManager {
+ static isSupported() {
+ return (
+ typeof WebAssembly !== "undefined" &&
+ typeof AudioWorkletNode !== "undefined" &&
+ typeof Worker !== "undefined" &&
+ !!navigator.gpu
+ );
+ }
+
+ #taps = new Map();
+ #enabled = false;
+ #epoch = 0;
+
+ #worker = null;
+ #workerReady = false;
+ #readyTimer = null;
+ #jobCounter = 0;
+ #utteranceCounter = 0;
+ #retracted = new Set();
+ // Utterance start wall-clocks, captured at speech start. Kept manager-side
+ // (not round-tripped through the worker) and read back when captions
+ // arrive, since results lag speech by the transcription latency.
+ #utteranceStarts = new Map();
+ #modelBaseUrl = null;
+ // Set while the worker reports it can't transcribe faster than realtime:
+ // interim snapshots are optional work, so they are shed first.
+ #interimsSuspended = false;
+
+ #onCaption;
+ #onLoadingChange;
+ #onProgress;
+ #onError;
+ #loadVad;
+ #createWorker;
+
+ constructor({
+ onCaption,
+ onLoadingChange,
+ onProgress,
+ onError,
+ // Injectable for tests; production always uses the shipped assets.
+ loadVad = loadVadModule,
+ createWorker = () => new Worker(workerUrl()),
+ }) {
+ this.#onCaption = onCaption;
+ this.#onLoadingChange = onLoadingChange;
+ this.#onProgress = onProgress;
+ this.#onError = onError;
+ this.#loadVad = loadVad;
+ this.#createWorker = createWorker;
+ }
+
+ get enabled() {
+ return this.#enabled;
+ }
+
+ get loading() {
+ if (this.#worker && !this.#workerReady) {
+ return true;
+ }
+ for (const tap of this.#taps.values()) {
+ if (!tap.ready) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ setEnabled(enabled, { modelBaseUrl = null } = {}) {
+ this.#modelBaseUrl = modelBaseUrl;
+ if (this.#enabled === enabled) {
+ return;
+ }
+
+ this.#enabled = enabled;
+ if (!enabled) {
+ this.#epoch++;
+ for (const key of [...this.#taps.keys()]) {
+ this.#removeTap(key);
+ }
+ this.#terminateWorker();
+ this.#utteranceStarts.clear();
+ }
+ }
+
+ async attach(roomId, userId, stream) {
+ if (!this.#enabled || !stream) {
+ return;
+ }
+
+ // The model (and its potentially long first download) only starts once
+ // there is actually someone to transcribe — never on page load.
+ this.#ensureWorker(this.#modelBaseUrl);
+
+ const key = this.#key(roomId, userId);
+ const trackId = stream.getAudioTracks()[0]?.id;
+ const existing = this.#taps.get(key);
+ if (existing?.trackId === trackId) {
+ return;
+ }
+ // A restarted peer connection replaces the audio track inside the same
+ // registry stream; the old source node only ever yields silence from
+ // that point, so rebuild the tap on the new track.
+ if (existing) {
+ this.#removeTap(key);
+ }
+
+ const epoch = this.#epoch;
+ const tap = {
+ roomId,
+ userId,
+ trackId,
+ vad: null,
+ ready: false,
+ speaking: false,
+ utteranceId: 0,
+ frames: [],
+ bufferedSamples: 0,
+ samplesSinceInterim: 0,
+ interimSent: false,
+ };
+ this.#taps.set(key, tap);
+ this.#onLoadingChange();
+
+ let vadModule;
+ try {
+ vadModule = await this.#loadVad();
+ } catch (error) {
+ this.#taps.delete(key);
+ this.#onError(error);
+ return;
+ }
+
+ if (epoch !== this.#epoch || this.#taps.get(key) !== tap) {
+ this.#onLoadingChange();
+ return;
+ }
+
+ let vad;
+ try {
+ vad = await vadModule.MicVAD.new({
+ model: "v5",
+ baseAssetPath: sttUrl(VAD_ASSET_DIR),
+ // Assigned verbatim to ort's env, which accepts explicit {mjs, wasm}
+ // URLs — needed because the module glue ships under a .js name (the
+ // .mjs extension gets a non-JavaScript MIME type from nginx).
+ onnxWASMBasePath: {
+ mjs: sttUrl(ORT_WASM_JS_FILE),
+ wasm: sttUrl(ORT_WASM_BINARY_FILE),
+ },
+ // The "mic" is a remote WebRTC stream the registry owns; the VAD
+ // must never stop its tracks when pausing.
+ getStream: async () => stream,
+ pauseStream: async () => {},
+ resumeStream: async () => stream,
+ startOnLoad: false,
+ onSpeechStart: () => this.#handleSpeechStart(tap, epoch),
+ onFrameProcessed: (_probabilities, frame) =>
+ this.#handleFrame(tap, epoch, frame),
+ onSpeechEnd: (audio) => this.#handleUtterance(tap, epoch, audio),
+ onVADMisfire: () => this.#handleMisfire(tap, epoch),
+ });
+ } catch (error) {
+ if (this.#taps.get(key) === tap) {
+ this.#removeTap(key);
+ this.#onError(error);
+ }
+ return;
+ }
+
+ // A detach or disable may have superseded this tap while the VAD was
+ // loading.
+ if (epoch !== this.#epoch || this.#taps.get(key) !== tap) {
+ this.#teardownVad(vad);
+ return;
+ }
+
+ tap.vad = vad;
+ try {
+ await vad.start();
+ } catch (error) {
+ if (this.#taps.get(key) === tap) {
+ this.#removeTap(key);
+ this.#onError(error);
+ }
+ return;
+ }
+
+ if (epoch !== this.#epoch || this.#taps.get(key) !== tap) {
+ this.#teardownVad(vad);
+ return;
+ }
+
+ tap.ready = true;
+ this.#onLoadingChange();
+ }
+
+ detach(roomId, userId) {
+ this.#removeTap(this.#key(roomId, userId));
+ }
+
+ detachRoom(roomId) {
+ for (const [key, tap] of [...this.#taps]) {
+ if (Number(tap.roomId) === Number(roomId)) {
+ this.#removeTap(key);
+ }
+ }
+ }
+
+ destroy() {
+ this.setEnabled(false);
+ }
+
+ isPreferred() {
+ try {
+ return localStorage.getItem(PREFERENCE_KEY) === "1";
+ } catch {
+ return false;
+ }
+ }
+
+ setPreference(enabled) {
+ try {
+ if (enabled) {
+ localStorage.setItem(PREFERENCE_KEY, "1");
+ } else {
+ localStorage.removeItem(PREFERENCE_KEY);
+ }
+ } catch {
+ // ignore storage errors
+ }
+ }
+
+ #ensureWorker(modelBaseUrl) {
+ if (this.#worker) {
+ return;
+ }
+
+ // Best effort, window-only API: asks the browser to exempt the origin's
+ // storage (the multi-GB cached model) from eviction. Chromium decides
+ // silently, but Firefox shows a permission prompt — so this must only
+ // run here, when transcription is actually starting in a room, never on
+ // plain page load.
+ navigator.storage?.persist?.().catch(() => {});
+
+ let worker;
+ try {
+ worker = this.#createWorker();
+ } catch (error) {
+ this.#onError(error);
+ return;
+ }
+
+ this.#worker = worker;
+ this.#workerReady = false;
+ this.#onLoadingChange();
+
+ worker.onmessage = (event) => this.#handleWorkerMessage(worker, event);
+ worker.onerror = (event) => {
+ if (this.#worker === worker) {
+ this.#failWorker(new Error(event.message || "subtitles worker error"));
+ }
+ };
+
+ this.#readyTimer = setTimeout(() => {
+ if (this.#worker === worker && !this.#workerReady) {
+ this.#failWorker(new Error("subtitles model load timed out"));
+ }
+ }, READY_TIMEOUT_MS);
+
+ worker.postMessage({
+ type: "init",
+ config: {
+ modelBaseUrl: modelBaseUrl || null,
+ ortWasmJsUrl: sttUrl(ORT_WASM_JS_FILE),
+ ortWasmBinaryUrl: sttUrl(ORT_WASM_BINARY_FILE),
+ },
+ });
+ }
+
+ #handleWorkerMessage(worker, event) {
+ if (this.#worker !== worker) {
+ return;
+ }
+
+ const message = event.data || {};
+ switch (message.type) {
+ case "progress":
+ this.#onProgress(message);
+ break;
+ case "ready":
+ clearTimeout(this.#readyTimer);
+ this.#workerReady = true;
+ this.#onLoadingChange();
+ break;
+ case "error":
+ this.#failWorker(new Error(message.message));
+ break;
+ case "throughput":
+ this.#interimsSuspended = !!message.slow;
+ break;
+ case "caption": {
+ if (!this.#enabled) {
+ break;
+ }
+ // The speaker's tap is gone (they left, or their room was left);
+ // captions from jobs still in flight at that point are stale.
+ if (!this.#taps.has(this.#key(message.roomId, message.userId))) {
+ break;
+ }
+ // The utterance was retracted (VAD misfire) while this job was in
+ // flight; showing its text would resurrect a withdrawn line.
+ if (this.#retracted.delete(message.utteranceId)) {
+ break;
+ }
+ const startedAt = this.#utteranceStarts.get(message.utteranceId);
+ if (!message.interim) {
+ this.#utteranceStarts.delete(message.utteranceId);
+ }
+ const text = message.text?.trim();
+ if (text) {
+ this.#onCaption(message.roomId, message.userId, {
+ id: message.utteranceId,
+ text,
+ final: !message.interim,
+ startedAt,
+ });
+ } else if (!message.interim) {
+ // An empty final (the model heard nothing intelligible) must clear
+ // any provisional line the interims put up.
+ this.#onCaption(message.roomId, message.userId, {
+ id: message.utteranceId,
+ text: null,
+ final: true,
+ startedAt,
+ });
+ }
+ break;
+ }
+ case "job-error":
+ // A single bad utterance isn't fatal; keep going but surface it.
+ // eslint-disable-next-line no-console
+ console.warn("[voice] subtitles transcription error", message);
+ break;
+ }
+ }
+
+ #live(tap, epoch) {
+ return epoch === this.#epoch && this.#enabled;
+ }
+
+ #handleSpeechStart(tap, epoch) {
+ if (!this.#live(tap, epoch)) {
+ return;
+ }
+ tap.speaking = true;
+ tap.utteranceId = ++this.#utteranceCounter;
+ this.#noteUtteranceStart(tap.utteranceId);
+ tap.frames = [];
+ tap.bufferedSamples = 0;
+ tap.samplesSinceInterim = 0;
+ tap.interimSent = false;
+ }
+
+ // Fires for every VAD frame; only frames inside an utterance are kept, and
+ // once enough new audio accumulates the snapshot-so-far is transcribed as
+ // a provisional caption.
+ #handleFrame(tap, epoch, frame) {
+ if (!this.#live(tap, epoch) || !tap.speaking) {
+ return;
+ }
+
+ // Under sustained transcription backlog the provisional passes are shed
+ // entirely; the final (speech-end) pass still covers the utterance.
+ if (this.#interimsSuspended) {
+ tap.frames = [];
+ tap.bufferedSamples = 0;
+ tap.samplesSinceInterim = 0;
+ return;
+ }
+
+ tap.frames.push(frame.slice());
+ tap.bufferedSamples += frame.length;
+ tap.samplesSinceInterim += frame.length;
+
+ while (
+ tap.bufferedSamples > INTERIM_WINDOW_MAX_SAMPLES &&
+ tap.frames.length > 1
+ ) {
+ tap.bufferedSamples -= tap.frames.shift().length;
+ }
+
+ if (
+ tap.bufferedSamples >= INTERIM_MIN_SAMPLES &&
+ tap.samplesSinceInterim >= INTERIM_INTERVAL_SAMPLES
+ ) {
+ tap.samplesSinceInterim = 0;
+
+ const snapshot = new Float32Array(tap.bufferedSamples);
+ let offset = 0;
+ for (const chunk of tap.frames) {
+ snapshot.set(chunk, offset);
+ offset += chunk.length;
+ }
+ if (this.#postTranscribe(tap, snapshot, true)) {
+ tap.interimSent = true;
+ }
+ }
+ }
+
+ #handleUtterance(tap, epoch, audio) {
+ if (!this.#live(tap, epoch)) {
+ return;
+ }
+ tap.speaking = false;
+ tap.frames = [];
+ tap.bufferedSamples = 0;
+ if (!tap.utteranceId) {
+ tap.utteranceId = ++this.#utteranceCounter;
+ this.#noteUtteranceStart(tap.utteranceId);
+ }
+ this.#postTranscribe(tap, audio, false);
+ }
+
+ // Too short to be speech after all: withdraw any provisional line and make
+ // sure an in-flight interim result can't resurrect it.
+ #handleMisfire(tap, epoch) {
+ tap.speaking = false;
+ tap.frames = [];
+ tap.bufferedSamples = 0;
+ this.#utteranceStarts.delete(tap.utteranceId);
+
+ if (!this.#live(tap, epoch) || !tap.interimSent) {
+ return;
+ }
+ tap.interimSent = false;
+ this.#retracted.add(tap.utteranceId);
+ if (this.#retracted.size > 200) {
+ this.#retracted.clear();
+ }
+ this.#onCaption(tap.roomId, tap.userId, {
+ id: tap.utteranceId,
+ text: null,
+ final: true,
+ });
+ }
+
+ #postTranscribe(tap, audio, interim) {
+ if (!this.#enabled || !this.#worker || !this.#workerReady) {
+ return false;
+ }
+
+ // Respect the view bounds: the audio may be a window into a larger
+ // buffer, and slice(0) of the raw buffer would ship the wrong bytes.
+ const pcm = audio.buffer.slice(
+ audio.byteOffset,
+ audio.byteOffset + audio.byteLength
+ );
+ this.#worker.postMessage(
+ {
+ type: "transcribe",
+ jobId: ++this.#jobCounter,
+ roomId: tap.roomId,
+ userId: tap.userId,
+ utteranceId: tap.utteranceId,
+ interim,
+ pcm,
+ // Stamped here (not in the worker) because heavy jobs block the
+ // worker's event loop, delaying its onmessage arbitrarily.
+ sentAt: Date.now(),
+ },
+ [pcm]
+ );
+ return true;
+ }
+
+ #failWorker(error) {
+ this.#terminateWorker();
+ this.#onError(error);
+ }
+
+ #terminateWorker() {
+ clearTimeout(this.#readyTimer);
+ this.#readyTimer = null;
+ if (this.#worker) {
+ this.#worker.terminate();
+ this.#worker = null;
+ }
+ this.#workerReady = false;
+ this.#interimsSuspended = false;
+ }
+
+ // Entries are removed when the final caption (or a misfire) lands; the cap
+ // only guards against utterances whose results never arrive at all.
+ #noteUtteranceStart(utteranceId) {
+ if (this.#utteranceStarts.size > 200) {
+ this.#utteranceStarts.clear();
+ }
+ this.#utteranceStarts.set(utteranceId, Date.now());
+ }
+
+ #key(roomId, userId) {
+ return `${roomId}:${userId}`;
+ }
+
+ #removeTap(key) {
+ const tap = this.#taps.get(key);
+ if (!tap) {
+ return;
+ }
+
+ this.#taps.delete(key);
+ if (tap.vad) {
+ this.#teardownVad(tap.vad);
+ }
+ // Discard whatever this speaker still has waiting in the transcription
+ // queue; a detached tap's captions would be dropped on arrival anyway,
+ // so transcribing them is pure backlog.
+ this.#worker?.postMessage({
+ type: "flush",
+ roomId: tap.roomId,
+ userId: tap.userId,
+ });
+ this.#onLoadingChange();
+ }
+
+ #teardownVad(vad) {
+ try {
+ vad.destroy();
+ } catch {
+ // ignore
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-draft-sync.js b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-draft-sync.js
new file mode 100644
index 00000000000..f55a739d7cc
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-draft-sync.js
@@ -0,0 +1,93 @@
+const SAVE_INTERVAL_MS = 10_000;
+
+// new_topic-prefixed so core's drafts list and resume flow treat these as
+// normal new-topic drafts; the rest marks them as ours (see the draft-icon
+// transformer registration).
+export const TRANSCRIPT_DRAFT_KEY_PREFIX = "new_topic_voice_";
+
+// Mirrors an in-progress transcript into a server-side topic draft so the
+// recording survives a crashed tab and shows up in the user's drafts like
+// any half-written topic. Saves ride a fixed cadence and only when entries
+// changed.
+//
+// The sync only ever runs while recording — opening the draft stops the
+// recording first, so the composer never competes with it. A sequence
+// conflict therefore means another client wrote the draft; that copy wins
+// and this sync goes quiet for good.
+export default class TranscriptDraftSync {
+ #save;
+ #buildData;
+ #timer = null;
+ #saving = false;
+ #dirty = false;
+ #sequence = 0;
+ #conflicted = false;
+ #key = null;
+
+ constructor({ save, buildData }) {
+ this.#save = save;
+ this.#buildData = buildData;
+ }
+
+ get key() {
+ return this.#key;
+ }
+
+ get sequence() {
+ return this.#sequence;
+ }
+
+ start(roomId, startedAt) {
+ this.dispose();
+ this.#key = `${TRANSCRIPT_DRAFT_KEY_PREFIX}${roomId}_${startedAt}`;
+ this.#sequence = 0;
+ this.#dirty = false;
+ this.#conflicted = false;
+ this.#timer = setInterval(() => this.flush(), SAVE_INTERVAL_MS);
+ }
+
+ markDirty() {
+ this.#dirty = true;
+ }
+
+ // Stops the cadence and flushes what's pending. The key survives so the
+ // finished draft can still be opened.
+ async stop() {
+ clearInterval(this.#timer);
+ this.#timer = null;
+ await this.flush();
+ }
+
+ dispose() {
+ clearInterval(this.#timer);
+ this.#timer = null;
+ this.#key = null;
+ }
+
+ async flush() {
+ if (!this.#key || this.#conflicted || this.#saving || !this.#dirty) {
+ return;
+ }
+
+ const data = this.#buildData();
+ if (!data) {
+ return;
+ }
+
+ this.#saving = true;
+ this.#dirty = false;
+ try {
+ const result = await this.#save(this.#key, this.#sequence, data);
+ this.#sequence = result?.draft_sequence ?? this.#sequence;
+ } catch (error) {
+ if (error?.jqXHR?.status === 409) {
+ this.#conflicted = true;
+ } else {
+ // Transient failure (network, logout race): retry next tick.
+ this.#dirty = true;
+ }
+ } finally {
+ this.#saving = false;
+ }
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-markdown.js b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-markdown.js
new file mode 100644
index 00000000000..f585dae3e47
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-markdown.js
@@ -0,0 +1,21 @@
+import { i18n } from "discourse-i18n";
+
+// Renders a recorded transcript as post markdown. When chat is enabled the
+// entries reuse chat's transcript markup — one chained [chat] block per
+// utterance, which cooks into the familiar quoted-conversation look — with
+// the utterance id standing in for the message id and no channel attributes,
+// so nothing links anywhere. Without chat the markup wouldn't cook, so plain
+// bbcode quotes are used instead.
+export function transcriptToMarkdown(entries, { chatMarkup = true } = {}) {
+ return entries
+ .map((entry) => {
+ const username =
+ entry.username || i18n("voice.transcript.unknown_speaker");
+ if (chatMarkup) {
+ const timestamp = new Date(entry.startedAt).toISOString();
+ return `[chat quote="${username};${entry.utteranceId};${timestamp}" chained="true"]\n${entry.text}\n[/chat]`;
+ }
+ return `[quote="${username}"]\n${entry.text}\n[/quote]`;
+ })
+ .join("\n\n");
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-recorder.js b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-recorder.js
new file mode 100644
index 00000000000..f9d6460e6de
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/transcript-recorder.js
@@ -0,0 +1,105 @@
+// Accumulates a meeting transcript from the subtitles pipeline: one entry per
+// final utterance, with the speaker and the utterance's start wall-clock.
+//
+// Recording is scoped to a single room. Interim captions never land here —
+// only finals do — and a null-text final withdraws the entry (a VAD misfire,
+// or the model hearing nothing intelligible). Entries survive stop() so the
+// finished transcript can be consumed; they are discarded when a new
+// recording starts.
+export default class TranscriptRecorder {
+ #entries = [];
+ #onChange;
+ #roomId = null;
+ // Which room the kept entries belong to; unlike #roomId it survives stop()
+ // so a consumer can still attribute the finished transcript.
+ #entriesRoomId = null;
+ #startedAt = null;
+
+ constructor({ onChange }) {
+ this.#onChange = onChange;
+ }
+
+ get recording() {
+ return this.#roomId !== null;
+ }
+
+ get roomId() {
+ return this.#roomId;
+ }
+
+ get entriesRoomId() {
+ return this.#entriesRoomId;
+ }
+
+ get startedAt() {
+ return this.#startedAt;
+ }
+
+ get entries() {
+ return this.#entries;
+ }
+
+ start(roomId) {
+ this.#roomId = roomId;
+ this.#entriesRoomId = roomId;
+ this.#startedAt = Date.now();
+ this.#entries = [];
+ this.#onChange();
+ }
+
+ stop() {
+ this.#roomId = null;
+ this.#onChange();
+ }
+
+ record(
+ roomId,
+ userId,
+ username,
+ { id: utteranceId, text, final, startedAt }
+ ) {
+ if (!final || !this.recording || Number(roomId) !== Number(this.#roomId)) {
+ return;
+ }
+
+ const index = this.#entries.findIndex(
+ (entry) => entry.utteranceId === utteranceId
+ );
+
+ if (!text) {
+ if (index !== -1) {
+ this.#entries = this.#entries.filter((_, i) => i !== index);
+ this.#onChange();
+ }
+ return;
+ }
+
+ if (index !== -1) {
+ this.#entries = this.#entries.map((entry, i) =>
+ i === index ? { ...entry, text } : entry
+ );
+ this.#onChange();
+ return;
+ }
+
+ const entry = {
+ utteranceId,
+ userId,
+ username,
+ text,
+ startedAt: startedAt ?? Date.now(),
+ };
+
+ // Insert in utterance-start order: worker jobs serialize across speakers,
+ // so with overlapping speech results can arrive out of speaking order.
+ const insertAt = this.#entries.findLastIndex(
+ (existing) => existing.startedAt <= entry.startedAt
+ );
+ this.#entries = [
+ ...this.#entries.slice(0, insertAt + 1),
+ entry,
+ ...this.#entries.slice(insertAt + 1),
+ ];
+ this.#onChange();
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js b/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js
new file mode 100644
index 00000000000..db4cd186fda
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js
@@ -0,0 +1,413 @@
+import { tracked } from "@glimmer/tracking";
+import { ajax } from "discourse/lib/ajax";
+import Composer from "discourse/models/composer";
+import Draft from "discourse/models/draft";
+import { i18n } from "discourse-i18n";
+import SubtitlesManager from "./subtitles";
+import TranscriptDraftSync from "./transcript-draft-sync";
+import { transcriptToMarkdown } from "./transcript-markdown";
+import TranscriptRecorder from "./transcript-recorder";
+
+// Owns the speech-to-text pipeline and both of its consumers: the caption
+// overlay and the transcript recorder (with its composer-draft sync). The
+// webrtc service delegates its subtitles/transcript API here and forwards
+// stream attach/detach events as rooms and participants come and go.
+export default class TranscriptionCoordinator {
+ @tracked enabled = false;
+ @tracked loading = false;
+ @tracked progress = null;
+ @tracked captions = [];
+ @tracked revision = 0;
+
+ #subtitles;
+ #transcript;
+ #transcriptDraft;
+ #captionCounter = 0;
+
+ #siteSettings;
+ #getParticipantSessionId;
+ #getCurrentUserId;
+ #getRoom;
+ #isActiveRoom;
+ #getActiveRoomIds;
+ #getRemoteUserIds;
+ #getRemoteStream;
+ #getLocalStream;
+ #setParticipantTranscribing;
+ #saveDraft;
+ #openComposer;
+ #showError;
+
+ constructor({
+ siteSettings,
+ getParticipantSessionId = () => undefined,
+ getCurrentUserId,
+ getRoom,
+ isActiveRoom,
+ getActiveRoomIds,
+ getRemoteUserIds,
+ getRemoteStream,
+ getLocalStream,
+ setParticipantTranscribing,
+ saveDraft,
+ openComposer,
+ showError,
+ }) {
+ this.#siteSettings = siteSettings;
+ this.#getParticipantSessionId = getParticipantSessionId;
+ this.#getCurrentUserId = getCurrentUserId;
+ this.#getRoom = getRoom;
+ this.#isActiveRoom = isActiveRoom;
+ this.#getActiveRoomIds = getActiveRoomIds;
+ this.#getRemoteUserIds = getRemoteUserIds;
+ this.#getRemoteStream = getRemoteStream;
+ this.#getLocalStream = getLocalStream;
+ this.#setParticipantTranscribing = setParticipantTranscribing;
+ this.#saveDraft = saveDraft;
+ this.#openComposer = openComposer;
+ this.#showError = showError;
+
+ this.#transcript = new TranscriptRecorder({
+ onChange: () => {
+ this.revision++;
+ this.#transcriptDraft?.markDirty();
+ },
+ });
+
+ this.#transcriptDraft = new TranscriptDraftSync({
+ save: (key, sequence, data) => this.#saveDraft(key, sequence, data),
+ buildData: () => this.#draftData(),
+ });
+
+ this.#subtitles = new SubtitlesManager({
+ onCaption: (roomId, userId, utterance) => {
+ this.#upsertCaption(roomId, userId, utterance);
+ this.#transcript.record(
+ roomId,
+ userId,
+ this.#participantUsername(roomId, userId),
+ utterance
+ );
+ },
+ onLoadingChange: () => {
+ this.loading = this.#subtitles.loading;
+ if (!this.loading) {
+ this.progress = null;
+ }
+ },
+ onProgress: ({ loaded, total }) => {
+ if (total > 0) {
+ this.progress = Math.min(100, Math.round((loaded / total) * 100));
+ }
+ },
+ onError: (error) => this.#handleError(error),
+ });
+
+ this.enabled = this.available && this.#subtitles.isPreferred();
+ this.#subtitles.setEnabled(this.enabled, {
+ modelBaseUrl: this.#modelBaseUrl,
+ });
+ }
+
+ destroy() {
+ this.#subtitles.destroy();
+ this.#transcriptDraft.dispose();
+ }
+
+ get available() {
+ return (
+ !!this.#siteSettings.voice_subtitles_enabled &&
+ SubtitlesManager.isSupported()
+ );
+ }
+
+ get #modelBaseUrl() {
+ return this.#siteSettings.voice_stt_model_base_url || null;
+ }
+
+ toggle() {
+ this.enabled = !this.enabled;
+ this.#subtitles.setPreference(this.enabled);
+ this.#syncSttEngine();
+ }
+
+ get recording() {
+ this.revision;
+ return this.#transcript.recording;
+ }
+
+ get roomId() {
+ this.revision;
+ return this.#transcript.roomId;
+ }
+
+ get entries() {
+ this.revision;
+ return this.#transcript.entries;
+ }
+
+ get entriesRoomId() {
+ this.revision;
+ return this.#transcript.entriesRoomId;
+ }
+
+ get startedAt() {
+ this.revision;
+ return this.#transcript.startedAt;
+ }
+
+ isTranscribingRoom(roomId) {
+ return this.recording && Number(this.roomId) === Number(roomId);
+ }
+
+ toggleRecording(roomId) {
+ if (this.recording) {
+ this.#stopRecording();
+ return;
+ }
+
+ if (!this.available || !this.#isActiveRoom(roomId)) {
+ return;
+ }
+
+ this.#transcript.start(roomId);
+ this.#transcriptDraft.start(roomId, this.#transcript.startedAt);
+ this.#syncSttEngine();
+ this.#broadcastTranscribingState(roomId, true);
+ }
+
+ // Leaving the recorded room ends the recording; the transcript gathered so
+ // far is kept for consumption.
+ stopIfTranscribing(roomId) {
+ if (this.isTranscribingRoom(roomId)) {
+ this.#stopRecording();
+ }
+ }
+
+ #stopRecording() {
+ if (!this.#transcript.recording) {
+ return;
+ }
+
+ const roomId = this.#transcript.roomId;
+ // Entries survive the stop so the finished transcript can be consumed.
+ this.#transcript.stop();
+ // Flushes the last utterances into the draft; the draft itself stays.
+ const flushed = this.#transcriptDraft.stop();
+ const currentUserId = this.#getCurrentUserId();
+ if (currentUserId) {
+ this.#subtitles.detach(roomId, currentUserId);
+ }
+ this.#syncSttEngine();
+ this.#broadcastTranscribingState(roomId, false);
+ return flushed;
+ }
+
+ // The consent signal: a roster flag every participant's client renders as
+ // a quiet badge. Best effort — the transcript itself never leaves this
+ // browser. Skipped when the room is already gone (leave teardown), since
+ // the roster dies with the membership.
+ #broadcastTranscribingState(roomId, transcribing) {
+ if (!this.#isActiveRoom(roomId)) {
+ return;
+ }
+
+ this.#setParticipantTranscribing(roomId, transcribing);
+ ajax(`/voice/rooms/${roomId}/state`, {
+ type: "POST",
+ data: {
+ transcribing,
+ participant_session_id: this.#getParticipantSessionId(roomId),
+ },
+ }).catch(() => {});
+ }
+
+ // The speech-to-text pipeline serves two consumers: the caption overlay
+ // (enabled) and the transcript recorder. It runs while either wants it,
+ // tapping every remote stream plus — only while recording — the local mic,
+ // so the transcript includes the current user.
+ #syncSttEngine() {
+ const enabled = this.enabled || this.recording;
+ this.#subtitles.setEnabled(enabled, {
+ modelBaseUrl: this.#modelBaseUrl,
+ });
+
+ if (!enabled) {
+ this.captions = [];
+ return;
+ }
+
+ for (const roomId of this.#getActiveRoomIds()) {
+ for (const userId of this.#getRemoteUserIds(roomId)) {
+ this.#subtitles.attach(
+ roomId,
+ userId,
+ this.#getRemoteStream(roomId, userId)
+ );
+ }
+ }
+ this.syncLocalTap();
+ }
+
+ #draftData() {
+ const entries = this.#transcript.entries;
+ if (!entries.length) {
+ return null;
+ }
+
+ const room = this.#getRoom(this.#transcript.entriesRoomId);
+ return {
+ reply: transcriptToMarkdown(entries, {
+ chatMarkup: !!this.#siteSettings.chat_enabled,
+ }),
+ title: i18n("voice.transcript.draft_title", {
+ room: room?.name ?? "",
+ }),
+ action: Composer.CREATE_TOPIC,
+ archetypeId: "regular",
+ };
+ }
+
+ // Hands the transcript over to the composer: recording stops, the last
+ // utterances are flushed into the draft, and the draft opens for editing.
+ // The server copy wins — the user may have edited it in another session.
+ async openDraft() {
+ const draftKey = this.#transcriptDraft.key;
+ if (!draftKey) {
+ return;
+ }
+
+ await this.#stopRecording();
+
+ let draft = null;
+ let draftSequence = this.#transcriptDraft.sequence;
+ try {
+ const result = await Draft.get(draftKey);
+ draft = result.draft;
+ draftSequence = result.draft_sequence ?? draftSequence;
+ } catch {
+ // fall through to the locally built copy
+ }
+ draft ||= this.#draftData();
+ if (!draft) {
+ return;
+ }
+
+ this.#openComposer({ draft, draftKey, draftSequence });
+ }
+
+ // Mirrors the local pipeline into the transcriber while recording. Safe to
+ // call repeatedly: attach is a no-op for an unchanged track and rebuilds
+ // the tap when a device switch or suppression change replaced it.
+ syncLocalTap() {
+ const currentUserId = this.#getCurrentUserId();
+ if (!this.recording || !currentUserId) {
+ return;
+ }
+
+ const roomId = this.roomId;
+ const localStream = this.#getLocalStream();
+ if (localStream) {
+ this.#subtitles.attach(roomId, currentUserId, localStream);
+ } else {
+ this.#subtitles.detach(roomId, currentUserId);
+ }
+ }
+
+ attachRemote(roomId, userId, stream) {
+ this.#subtitles.attach(roomId, userId, stream);
+ }
+
+ detach(roomId, userId) {
+ this.#subtitles.detach(roomId, userId);
+ }
+
+ detachRoom(roomId) {
+ this.#subtitles.detachRoom(roomId);
+ // Rejoining should start with a clean overlay, not replay whatever was
+ // on screen (or still in the transcription queue) when we left.
+ if (this.captions.length) {
+ this.captions = this.captions.filter(
+ (caption) => Number(caption.roomId) !== Number(roomId)
+ );
+ }
+ }
+
+ captionsFor(roomId) {
+ return this.captions.filter(
+ (caption) => Number(caption.roomId) === Number(roomId)
+ );
+ }
+
+ // One caption line per utterance: interim passes update the line in place
+ // while the speaker is still talking, the final pass replaces it, and a
+ // null text withdraws it (VAD misfire, or a final that heard nothing).
+ #upsertCaption(roomId, userId, { id: utteranceId, text, final }) {
+ const existingIndex = this.captions.findIndex(
+ (caption) =>
+ caption.utteranceId === utteranceId &&
+ Number(caption.userId) === Number(userId) &&
+ Number(caption.roomId) === Number(roomId)
+ );
+
+ if (!text) {
+ if (existingIndex !== -1) {
+ this.captions = this.captions.filter(
+ (_, index) => index !== existingIndex
+ );
+ }
+ return;
+ }
+
+ if (existingIndex !== -1) {
+ this.captions = this.captions.map((caption, index) =>
+ index === existingIndex
+ ? { ...caption, text, interim: !final, at: Date.now() }
+ : caption
+ );
+ return;
+ }
+
+ // Captions carry a display-name snapshot so a line outlives its speaker
+ // leaving the roster.
+ this.captions = [
+ ...this.captions.slice(-19),
+ {
+ id: ++this.#captionCounter,
+ utteranceId,
+ roomId,
+ userId,
+ username: this.#participantUsername(roomId, userId),
+ text,
+ interim: !final,
+ at: Date.now(),
+ },
+ ];
+ }
+
+ #participantUsername(roomId, userId) {
+ return (this.#getRoom(roomId)?.active_participants || []).find(
+ (p) => Number(p?.id) === Number(userId)
+ )?.username;
+ }
+
+ // Model or runtime failures turn the toggles back off (mirroring the noise
+ // suppression contract) so the UI never shows an enabled-but-dead state.
+ #handleError(error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] subtitles failed", error);
+
+ if (!this.enabled && !this.recording) {
+ return;
+ }
+
+ this.enabled = false;
+ this.#subtitles.setPreference(false);
+ if (this.#transcript.recording) {
+ this.#transcript.stop();
+ }
+ this.#subtitles.setEnabled(false);
+ this.captions = [];
+ this.#showError("voice.voice_settings.subtitles_failed");
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/url-flag.js b/plugins/voice/assets/javascripts/discourse/lib/voice/url-flag.js
new file mode 100644
index 00000000000..85172b265a0
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/url-flag.js
@@ -0,0 +1,6 @@
+// A valueless flag (`?widget`) arrives as an empty string, which is the
+// spelling a hand-written link is most likely to use, while an explicit
+// `?widget=false` has to keep reading as absent.
+export default function urlFlagSet(value) {
+ return value === "" || value === true || value === "true" || value === "1";
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/video-grid-layout.js b/plugins/voice/assets/javascripts/discourse/lib/voice/video-grid-layout.js
new file mode 100644
index 00000000000..b86bedd7732
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/video-grid-layout.js
@@ -0,0 +1,216 @@
+import { modifier } from "ember-modifier";
+
+// Fallback aspect (width / height) for tiles whose media hasn't reported its
+// intrinsic size yet, and for avatar-only tiles. Matches a landscape camera.
+export const DEFAULT_TILE_ASPECT = 16 / 9;
+
+// Greedy in-order row packing at a candidate uniform row height: walk the
+// tiles, start a new row whenever the next tile would overflow the width.
+// Returns the row count, or Infinity if a single tile is wider than the row.
+function rowsAtHeight(aspects, containerWidth, gap, height) {
+ let rows = 1;
+ let rowWidth = 0;
+
+ for (const aspect of aspects) {
+ const tileWidth = height * aspect;
+ if (tileWidth > containerWidth) {
+ return Infinity;
+ }
+
+ const needed = rowWidth === 0 ? tileWidth : gap + tileWidth;
+ if (rowWidth + needed > containerWidth) {
+ rows += 1;
+ rowWidth = tileWidth;
+ } else {
+ rowWidth += needed;
+ }
+ }
+
+ return rows;
+}
+
+// Largest uniform row height at which all tiles — each rendered at its own
+// aspect ratio (width = height * aspect) — fit the container, packed into rows.
+// Tiles share a height and vary in width, so portrait and landscape feeds sit
+// side by side without cropping or distortion. For a room where every tile has
+// the same aspect this converges to the same optimum as a column-count search;
+// mixed-aspect rooms get a justified-gallery layout. The grid uses
+// `contain: size`, so the result never feeds back into the container size —
+// without it, oversized tiles (e.g. right after exiting fullscreen) would
+// grow the grid, the remeasure would see the inflated box, and the layout
+// would lock there.
+export function bestRowHeight(containerWidth, containerHeight, aspects, gap) {
+ const count = aspects.length;
+ if (!count || containerWidth <= 0 || containerHeight <= 0) {
+ return 0;
+ }
+
+ const fits = (height) => {
+ const rows = rowsAtHeight(aspects, containerWidth, gap, height);
+ if (!isFinite(rows)) {
+ return false;
+ }
+ return rows * height + (rows - 1) * gap <= containerHeight;
+ };
+
+ let low = 0;
+ let high = containerHeight;
+ for (let i = 0; i < 40; i++) {
+ const mid = (low + high) / 2;
+ if (fits(mid)) {
+ low = mid;
+ } else {
+ high = mid;
+ }
+ }
+
+ // The search converges from just below the true maximum, so flooring can
+ // shed the last pixel at an exact boundary (e.g. one tile in a container of
+ // its own height). Reclaim it when the rounded-up height still fits.
+ const rowHeight = Math.floor(low);
+ return fits(rowHeight + 1) ? rowHeight + 1 : rowHeight;
+}
+
+// The widget grid trades the room page's per-tile aspect fidelity for uniform
+// tiles that pack a small box predictably; cover-cropping absorbs the
+// difference between a feed's real aspect and the cell's.
+const WIDGET_TILE_MIN_ASPECT = 4 / 3;
+
+// Smallest tile that still reads at a glance: avatar, name, status icons.
+const WIDGET_TILE_MIN_WIDTH = 88;
+const WIDGET_TILE_MIN_HEIGHT = 66;
+
+// Visual ceiling for the widget. Past this a floating mini-view stops being
+// glanceable no matter how much space it has; the room page is the place for
+// big grids.
+const WIDGET_MAX_SLOTS = 12;
+
+// Largest uniform tile for `slots` tiles in a width×height box: try every
+// column count, size the cell, clamp the tile's aspect to the allowed band,
+// keep the arrangement with the biggest tile. Ties prefer more columns — when
+// tiles are height-constrained a wider grid uses the slack width, and it
+// makes an unfloored tile width that fits `cols + 1` per line impossible
+// (that arrangement would have scored at least as high and won the tie).
+function bestGridForSlots(slots, width, height, gap) {
+ let best = null;
+
+ for (let cols = 1; cols <= slots; cols++) {
+ const rows = Math.ceil(slots / cols);
+ const cellWidth = (width - (cols - 1) * gap) / cols;
+ const cellHeight = (height - (rows - 1) * gap) / rows;
+ if (cellWidth <= 0 || cellHeight <= 0) {
+ continue;
+ }
+
+ const aspect = Math.min(
+ Math.max(cellWidth / cellHeight, WIDGET_TILE_MIN_ASPECT),
+ DEFAULT_TILE_ASPECT
+ );
+ const tileWidth = Math.min(cellWidth, cellHeight * aspect);
+ const tileHeight = tileWidth / aspect;
+ const area = tileWidth * tileHeight;
+
+ if (!best || area >= best.area) {
+ best = { cols, rows, tileWidth, tileHeight, area };
+ }
+ }
+
+ return best;
+}
+
+// Uniform grid for the floating call widget: show as many participants as fit
+// above the legibility floor, and collapse the rest into one overflow slot
+// (rendered as a "+N" tile). The search walks candidate slot counts downward —
+// fewer slots mean bigger tiles — and returns the first arrangement whose
+// tiles clear the floor, so the tile size adapts to the box and the crowd
+// instead of a fixed column template. When the box is too small for even two
+// legible slots, the floor yields rather than the tiles vanishing. Overflow is
+// never exactly one: a "+1" tile would spend the slot the hidden person could
+// have used, so the smallest overflow absorbs two.
+export function computeWidgetGrid({ width, height, count, gap }) {
+ if (!count || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ const minSlots = Math.min(count, 2);
+ let fallback = null;
+
+ for (
+ let slots = Math.min(count, WIDGET_MAX_SLOTS);
+ slots >= minSlots;
+ slots--
+ ) {
+ const grid = bestGridForSlots(slots, width, height, gap);
+ if (!grid) {
+ continue;
+ }
+
+ const shown = slots === count ? count : slots - 1;
+
+ // Flooring to whole pixels can shed just enough width that cols + 1 tiles
+ // squeeze onto one flex line, breaking the solved grid. The unfloored
+ // width never fits an extra tile (see bestGridForSlots), so when the
+ // floored one does, nudge it back above that threshold — fractional, and
+ // still below the width that was proven to fit.
+ let tileWidth = Math.floor(grid.tileWidth);
+ const extraTileLimit = (width - grid.cols * gap) / (grid.cols + 1);
+ if (tileWidth <= extraTileLimit) {
+ tileWidth = (extraTileLimit + grid.tileWidth) / 2;
+ }
+
+ const layout = {
+ shown,
+ overflow: count - shown,
+ cols: grid.cols,
+ rows: grid.rows,
+ tileWidth,
+ tileHeight: Math.floor(grid.tileHeight),
+ };
+
+ if (
+ grid.tileWidth >= WIDGET_TILE_MIN_WIDTH &&
+ grid.tileHeight >= WIDGET_TILE_MIN_HEIGHT
+ ) {
+ return layout;
+ }
+
+ fallback = layout;
+ }
+
+ return fallback;
+}
+
+// Reports the grid's content box (and resolved gap) to `onResize` whenever it
+// changes, so the layout can be recomputed for the available space.
+export const trackGridSize = modifier((element, [onResize]) => {
+ const observer = new ResizeObserver((entries) => {
+ const { width, height } = entries[0].contentRect;
+ const gap = parseFloat(getComputedStyle(element).rowGap) || 0;
+ onResize(width, height, gap);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+});
+
+// Reports a media element's intrinsic aspect ratio (width / height) to
+// `onAspect` once metadata loads and again whenever it changes — e.g. a phone
+// rotating mid-call fires `resize`. Reports null on teardown so the consumer
+// can fall back to the default for an avatar tile.
+export const trackVideoAspect = modifier((element, [onAspect]) => {
+ const report = () => {
+ const { videoWidth, videoHeight } = element;
+ if (videoWidth > 0 && videoHeight > 0) {
+ onAspect(videoWidth / videoHeight);
+ }
+ };
+
+ element.addEventListener("loadedmetadata", report);
+ element.addEventListener("resize", report);
+ report();
+
+ return () => {
+ element.removeEventListener("loadedmetadata", report);
+ element.removeEventListener("resize", report);
+ onAspect(null);
+ };
+});
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js b/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js
new file mode 100644
index 00000000000..0abd0797ad9
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js
@@ -0,0 +1,164 @@
+import {
+ QUALITY_HIGH,
+ QUALITY_MAXIMUM,
+ QUALITY_STANDARD,
+ SCREEN_CONTENT_MOTION,
+} from "./quality-preferences";
+
+// Mesh budget: every watcher costs the sender a full encode, so resolution
+// and bitrate scale down as the watcher count grows. Each connection's
+// bandwidth estimator still adapts per-link below these ceilings.
+//
+// The quality tier moves the ladder's rungs; "maximum" pins the top rung and
+// opts out of watcher-count downscaling entirely — the user has explicitly
+// accepted the multiplied upload/CPU cost, and congestion control still
+// protects each individual link.
+const SCREEN_ENCODINGS = {
+ [QUALITY_STANDARD]: {
+ maxBitrate: 2_500_000,
+ scaleResolutionDownBy: 1,
+ maxFramerate: 15,
+ },
+ [QUALITY_HIGH]: {
+ maxBitrate: 6_000_000,
+ scaleResolutionDownBy: 1,
+ maxFramerate: 30,
+ },
+ [QUALITY_MAXIMUM]: {
+ maxBitrate: 15_000_000,
+ scaleResolutionDownBy: 1,
+ maxFramerate: 60,
+ },
+};
+
+const CAMERA_LADDERS = {
+ [QUALITY_STANDARD]: [
+ { maxBitrate: 1_200_000, scaleResolutionDownBy: 1, maxFramerate: 24 },
+ { maxBitrate: 700_000, scaleResolutionDownBy: 1.5, maxFramerate: 24 },
+ { maxBitrate: 400_000, scaleResolutionDownBy: 2, maxFramerate: 15 },
+ ],
+ [QUALITY_HIGH]: [
+ { maxBitrate: 2_500_000, scaleResolutionDownBy: 1, maxFramerate: 24 },
+ { maxBitrate: 1_200_000, scaleResolutionDownBy: 1.5, maxFramerate: 24 },
+ { maxBitrate: 700_000, scaleResolutionDownBy: 2, maxFramerate: 15 },
+ ],
+};
+
+const CAMERA_MAXIMUM_ENCODING = {
+ maxBitrate: 8_000_000,
+ scaleResolutionDownBy: 1,
+ maxFramerate: 30,
+};
+
+// Opus speech defaults are left alone on the standard tier; higher tiers
+// raise the ceiling for good microphones. Bandwidth is negligible next to
+// video either way.
+const VOICE_BITRATES = {
+ [QUALITY_STANDARD]: null,
+ [QUALITY_HIGH]: 64_000,
+ [QUALITY_MAXIMUM]: 128_000,
+};
+
+export function screenCaptureFramerate(tier) {
+ return SCREEN_ENCODINGS[tier]?.maxFramerate ?? 15;
+}
+
+function encodingFor(kind, senderCount, tier = QUALITY_STANDARD) {
+ if (kind === "screen") {
+ return SCREEN_ENCODINGS[tier] ?? SCREEN_ENCODINGS[QUALITY_STANDARD];
+ }
+
+ if (tier === QUALITY_MAXIMUM) {
+ return CAMERA_MAXIMUM_ENCODING;
+ }
+
+ const ladder = CAMERA_LADDERS[tier] ?? CAMERA_LADDERS[QUALITY_STANDARD];
+ if (senderCount <= 3) {
+ return ladder[0];
+ }
+ if (senderCount <= 6) {
+ return ladder[1];
+ }
+ return ladder[2];
+}
+
+export function cameraEncodingFor(tier) {
+ return encodingFor("camera", 1, tier);
+}
+
+export function screenEncodingFor(tier) {
+ return encodingFor("screen", 1, tier);
+}
+
+export async function applyVideoQuality(
+ senders,
+ kind,
+ { tier = QUALITY_STANDARD, screenContent } = {}
+) {
+ if (!senders.length) {
+ return;
+ }
+
+ const encoding = encodingFor(kind, senders.length, tier);
+ const preserveMotion =
+ kind !== "screen" || screenContent === SCREEN_CONTENT_MOTION;
+
+ for (const sender of senders) {
+ try {
+ const parameters = sender.getParameters();
+ parameters.degradationPreference = preserveMotion
+ ? "maintain-framerate"
+ : "maintain-resolution";
+ if (!parameters.encodings?.length) {
+ parameters.encodings = [{}];
+ }
+ Object.assign(parameters.encodings[0], encoding);
+ await sender.setParameters(parameters);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to apply video quality", error);
+ }
+ }
+}
+
+export async function applyVoiceQuality(senders, tier = QUALITY_STANDARD) {
+ const bitrate = VOICE_BITRATES[tier];
+
+ for (const sender of senders) {
+ try {
+ const parameters = sender.getParameters();
+ if (!parameters.encodings?.length) {
+ parameters.encodings = [{}];
+ }
+ if (bitrate) {
+ parameters.encodings[0].maxBitrate = bitrate;
+ } else {
+ delete parameters.encodings[0].maxBitrate;
+ }
+ await sender.setParameters(parameters);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to apply voice quality", error);
+ }
+ }
+}
+
+export function voiceBitrateFor(tier) {
+ return VOICE_BITRATES[tier] ?? null;
+}
+
+// Opus defaults target speech bitrates; content audio gets a higher ceiling
+// so music doesn't sound underwater. Still small next to the video budget.
+export async function applyScreenAudioQuality(sender) {
+ try {
+ const parameters = sender.getParameters();
+ if (!parameters.encodings?.length) {
+ parameters.encodings = [{}];
+ }
+ parameters.encodings[0].maxBitrate = 128_000;
+ await sender.setParameters(parameters);
+ } catch (error) {
+ // eslint-disable-next-line no-console
+ console.warn("[voice] failed to apply screen audio quality", error);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js b/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js
new file mode 100644
index 00000000000..e410330387f
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/virtual-element-from-event.js
@@ -0,0 +1,27 @@
+/**
+ * Builds a float-kit trigger anchored at the pointer position of an event,
+ * so imperative menus open where the user clicked instead of at the edge of
+ * the element that received the event.
+ *
+ * @param {MouseEvent} event
+ * @returns {import("@floating-ui/dom").VirtualElement}
+ */
+export default function virtualElementFromEvent(event) {
+ const { clientX, clientY, target } = event;
+
+ return {
+ getBoundingClientRect() {
+ return {
+ x: clientX,
+ y: clientY,
+ top: clientY,
+ bottom: clientY,
+ left: clientX,
+ right: clientX,
+ width: 0,
+ height: 0,
+ };
+ },
+ contextElement: target instanceof HTMLElement ? target : undefined,
+ };
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/voice-assets.js b/plugins/voice/assets/javascripts/discourse/lib/voice/voice-assets.js
new file mode 100644
index 00000000000..6a1ddf6f950
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/voice-assets.js
@@ -0,0 +1,26 @@
+import getURL, { getURLWithCDN } from "discourse/lib/get-url";
+import Site from "discourse/models/site";
+
+// The heavyweight media assets (wasm engines, ML models, SDK bundles) ship in
+// the discourse_voice_assets gem under stable filenames; the server mounts
+// its vendor tree at a gem-version-stamped path and publishes that base here
+// (versioned URLs bust the immutable /plugins/ caches on a gem bump, so
+// nothing client-side changes when the gem does).
+function basePath() {
+ return Site.current().voice_assets_path;
+}
+
+// Assets ride the app-proxying CDN (getURLWithCDN's cdn), which serves the
+// plugin's public dir. Absolutized against the page URL because the compiled
+// chunk calling this may itself be served from a CDN origin, and a dynamic
+// import() of a bare path would resolve against the chunk's origin, not the
+// site's.
+export function voiceAssetUrl(file) {
+ return new URL(getURLWithCDN(`${basePath()}/${file}`), window.location).href;
+}
+
+// Same-origin variant: workers must load from the app origin (everything
+// they fetch afterwards can still use voiceAssetUrl).
+export function voiceAssetAppUrl(file) {
+ return new URL(getURL(`${basePath()}/${file}`), window.location).href;
+}
diff --git a/plugins/voice/assets/javascripts/discourse/routes/voice-room-invite.js b/plugins/voice/assets/javascripts/discourse/routes/voice-room-invite.js
new file mode 100644
index 00000000000..f6887ac120e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/routes/voice-room-invite.js
@@ -0,0 +1,17 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+import { setPendingInviteRef } from "discourse/plugins/voice/discourse/lib/voice/invite-ref";
+
+// An invite link (/voice/r/:slug/invited-by/:username) is the room page
+// with the inviter remembered: the ref is held until the user actually joins
+// the call, so the server credits the inviter on a real join, not a page view.
+export default class VoiceRoomInviteRoute extends DiscourseRoute {
+ @service router;
+
+ model(params, transition) {
+ setPendingInviteRef(params.slug, params.username);
+ this.router.replaceWith("voice-room", params.slug, {
+ queryParams: transition.to.queryParams,
+ });
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/routes/voice-room.js b/plugins/voice/assets/javascripts/discourse/routes/voice-room.js
new file mode 100644
index 00000000000..6eb7854116e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/routes/voice-room.js
@@ -0,0 +1,63 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { defaultHomepage } from "discourse/lib/utilities";
+import DiscourseRoute from "discourse/routes/discourse";
+import urlFlagSet from "discourse/plugins/voice/discourse/lib/voice/url-flag";
+
+export default class VoiceRoomRoute extends DiscourseRoute {
+ @service currentUser;
+ @service voiceRooms;
+ @service voiceWebrtc;
+ @service router;
+
+ async model(params) {
+ await this.voiceRooms.ready;
+
+ const room = this.voiceRooms.roomBySlug(params.slug);
+ if (room) {
+ return room;
+ }
+
+ const response = await ajax(`/voice/rooms/${params.slug}.json`);
+ return response.room;
+ }
+
+ afterModel(room, transition) {
+ if (!this.#widgetJoinRequested(transition)) {
+ return;
+ }
+
+ this.voiceWebrtc.setCallWidgetHidden(false);
+ this.voiceWebrtc.join(room);
+
+ // The widget only renders off the room page, so the room page is never
+ // entered: navigating within the app stays put, and a full page load lands
+ // on the homepage with the call already floating.
+ if (transition.from) {
+ transition.abort();
+ return;
+ }
+
+ this.router.replaceWith(`discovery.${defaultHomepage()}`);
+ }
+
+ titleToken() {
+ return this.currentModel?.name;
+ }
+
+ // `widget` says where a call should live, not that there should be one, so it
+ // composes with `join` instead of implying it. Skipping the room page is only
+ // right when both are asked for: `?widget` on its own opens the room page,
+ // which then docks whatever the user joins from there.
+ #widgetJoinRequested(transition) {
+ // Anonymous visitors cannot join a call, so they get the room page and its
+ // login prompt instead.
+ if (!this.currentUser) {
+ return false;
+ }
+
+ const { join, widget } = transition.to?.queryParams ?? {};
+
+ return urlFlagSet(widget) && urlFlagSet(join);
+ }
+}
diff --git a/plugins/voice/assets/javascripts/discourse/templates/voice-room.gjs b/plugins/voice/assets/javascripts/discourse/templates/voice-room.gjs
new file mode 100644
index 00000000000..cb19284101d
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/templates/voice-room.gjs
@@ -0,0 +1,10 @@
+import VoiceRoomPage from "discourse/plugins/voice/discourse/components/voice/room-page";
+
+export default <template>
+ <VoiceRoomPage
+ @room={{@model}}
+ @openChat={{@controller.chat}}
+ @autoJoin={{@controller.join}}
+ @dockOnJoin={{@controller.dockOnJoin}}
+ />
+</template>
diff --git a/plugins/voice/assets/javascripts/discourse/voice-route-map.js b/plugins/voice/assets/javascripts/discourse/voice-route-map.js
new file mode 100644
index 00000000000..9ee19cbc961
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/voice-route-map.js
@@ -0,0 +1,6 @@
+export default function () {
+ this.route("voice-room", { path: "/voice/r/:slug" });
+ this.route("voice-room-invite", {
+ path: "/voice/r/:slug/invited-by/:username",
+ });
+}
diff --git a/plugins/voice/assets/stylesheets/common/voice-admin.scss b/plugins/voice/assets/stylesheets/common/voice-admin.scss
new file mode 100644
index 00000000000..4484a52e895
--- /dev/null
+++ b/plugins/voice/assets/stylesheets/common/voice-admin.scss
@@ -0,0 +1,194 @@
+.voice-rooms-table {
+ margin-top: 1.5em;
+
+ .voice-rooms {
+ .voice-rooms__name {
+ font-weight: 600;
+ }
+
+ .voice-rooms__controls {
+ display: flex;
+ gap: 0.5em;
+ justify-content: flex-end;
+ }
+ }
+}
+
+.voice-dashboard {
+ &__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-top: 1.5em;
+ margin-bottom: 1em;
+
+ h2 {
+ margin: 0;
+ }
+ }
+
+ &__stats-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 1em;
+ margin-bottom: 1.5em;
+ }
+
+ &__card {
+ display: flex;
+ flex-direction: column;
+ padding: 1em;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ }
+
+ &__card-value {
+ font-size: var(--font-up-3);
+ font-weight: 700;
+ color: var(--primary);
+ }
+
+ &__card-label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin-top: 0.25em;
+ }
+
+ &__user-cell {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ }
+
+ &__empty {
+ padding: 2em;
+ text-align: center;
+ color: var(--primary-medium);
+ }
+
+ h3 {
+ margin-top: 1.5em;
+ margin-bottom: 0.5em;
+ }
+}
+
+.voice-livekit-status {
+ margin-top: 2em;
+ padding: 1em;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+
+ h3 {
+ margin: 0;
+ }
+ }
+
+ &__checks {
+ list-style: none;
+ margin: 1em 0;
+ padding: 0;
+ }
+
+ &__check {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5em;
+ padding: 0.25em 0;
+ }
+
+ &__check,
+ &__room-diff {
+ .d-icon {
+ align-self: center;
+ }
+
+ &.--ok .d-icon,
+ .--ok .d-icon {
+ color: var(--success);
+ }
+
+ &.--warning .d-icon,
+ .--warning .d-icon {
+ color: var(--highlight-high);
+ }
+
+ &.--error .d-icon,
+ .--error .d-icon {
+ color: var(--danger);
+ }
+ }
+
+ &__rooms {
+ margin-top: 0.5em;
+ }
+
+ &__load-failed,
+ &__no-rooms {
+ color: var(--primary-medium);
+ }
+
+ h4 {
+ margin: 1em 0 0.25em;
+ }
+}
+
+.voice-recordings {
+ &__status-badge {
+ display: inline-block;
+ padding: 0.1em 0.5em;
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+
+ &.--recording {
+ background: var(--danger-low);
+ color: var(--danger);
+ }
+
+ &.--completed {
+ background: var(--success-low);
+ color: var(--success);
+ }
+
+ &.--failed {
+ background: var(--primary-low);
+ color: var(--primary-high);
+ }
+ }
+
+ &__file code {
+ font-size: var(--font-down-1);
+ word-break: break-all;
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ }
+
+ &__load-more {
+ margin-top: 0.5em;
+ }
+}
+
+.voice-livekit-status__webhook-config {
+ margin: 0.5em 0 1em;
+
+ p {
+ margin-bottom: 0.25em;
+ color: var(--primary-medium);
+ }
+
+ pre {
+ margin: 0;
+ padding: 0.5em 0.75em;
+ background: var(--primary-very-low);
+ font-size: var(--font-down-1);
+ overflow-x: auto;
+ }
+}
diff --git a/plugins/voice/assets/stylesheets/common/voice-chat.scss b/plugins/voice/assets/stylesheets/common/voice-chat.scss
new file mode 100644
index 00000000000..21452cc52c8
--- /dev/null
+++ b/plugins/voice/assets/stylesheets/common/voice-chat.scss
@@ -0,0 +1,163 @@
+.voice-chat {
+ // border-box so the 22rem min-width (set by the room sidebar) includes the
+ // borders — content-box would make the panel 2px wider than the sidebar,
+ // whose overflow: hidden then clips the right border off.
+ box-sizing: border-box;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-height: 0;
+ width: 100%;
+ overflow: hidden;
+ border: 1px solid var(--primary-low);
+ border-radius: 0.75rem;
+ background: var(--secondary);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-3);
+ border-block-end: 1px solid var(--primary-low);
+ }
+
+ &__title {
+ margin: 0;
+ font-size: var(--font-0);
+ font-weight: 600;
+ }
+
+ &__open-in-chat {
+ margin-inline-start: auto;
+ }
+
+ &__close {
+ margin-inline-start: auto;
+
+ // The chat toggle in the room's control bar is the close affordance; only
+ // the narrow-viewport layout needs an X of its own, because there the
+ // panel becomes a drawer overlaying that control bar. Breakpoint matches
+ // the sidebar drawer in voice-room-page.scss.
+ display: none;
+
+ @media (width <= 1000px) {
+ display: inline-flex;
+ }
+ }
+
+ &__body {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-height: 0;
+
+ .loading-container {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ // The chat plugin sizes .chat-thread to the viewport via its chat-height()
+ // mixin (including mobile/footer-nav variants); inside the room panel the
+ // panel itself is the bounding box. The fade eases the loading-state →
+ // thread swap so it doesn't read as a flicker.
+ .chat-thread {
+ height: 100% !important;
+ animation: voice-chat-fade-in 0.15s ease-out;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+
+ // A thread freshly created from the starter composer holds only that one
+ // message, which loads faster than the skeleton can finish appearing — so
+ // that swap suppresses it instead of flashing it.
+ &.--hide-skeleton .chat-skeleton {
+ display: none;
+ }
+
+ // The panel header's open-in-chat button is the single link out to the
+ // thread; the original message's own "See in <channel>" chip duplicates
+ // it in a cramped space.
+ .chat-message-info__original-message {
+ display: none;
+ }
+ }
+
+ &__empty {
+ margin: auto;
+ padding: var(--space-4);
+ text-align: center;
+ color: var(--primary-medium);
+
+ .d-icon {
+ font-size: 2rem;
+ color: var(--primary-low-mid);
+ }
+ }
+
+ &__empty-title {
+ margin: var(--space-2) 0 var(--space-1);
+ color: var(--primary-high);
+ font-weight: 600;
+ }
+
+ &__empty-body {
+ margin: 0;
+ font-size: var(--font-down-1);
+ }
+
+ // Only the session's very first message goes through this starter composer;
+ // once the thread exists the native chat composer replaces it.
+ &__composer {
+ padding: var(--space-2) var(--space-3);
+ border-block-start: 1px solid var(--primary-low);
+ }
+
+ &__composer-inner {
+ display: flex;
+ align-items: flex-end;
+ gap: var(--space-1);
+ border: 1px solid var(--d-chat-input-border-color);
+ border-radius: var(--d-border-radius-large);
+ background: var(--d-chat-input-bg-color);
+
+ &:focus-within {
+ box-shadow: var(--d-chat-input-focused-shadow);
+ }
+ }
+
+ &__input {
+ flex: 1;
+ min-width: 0;
+ max-height: 8rem;
+ margin: 0;
+ padding: var(--space-2) 0;
+ border: 0;
+ background: transparent;
+ line-height: 1.3;
+ resize: none;
+
+ // The wrapper's focus-within shadow is the focus indicator (matching
+ // chat's own composer), not core's default textarea outline.
+ &:focus {
+ outline: none;
+ }
+ }
+
+ &__send {
+ flex: 0 0 auto;
+ }
+}
+
+@keyframes voice-chat-fade-in {
+ from {
+ opacity: 0;
+ }
+
+ to {
+ opacity: 1;
+ }
+}
diff --git a/plugins/voice/assets/stylesheets/common/voice-room-page.scss b/plugins/voice/assets/stylesheets/common/voice-room-page.scss
new file mode 100644
index 00000000000..771251997a9
--- /dev/null
+++ b/plugins/voice/assets/stylesheets/common/voice-room-page.scss
@@ -0,0 +1,908 @@
+// One step above the fixed site header so a widget dragged to the top edge
+// stays visible and grabbable, while everything that already outranked the
+// header (mobile composer, fullscreen layers, modals) keeps outranking the
+// widget. Menus opened from the widget sit one step higher still.
+$voice-widget-z: z("header") + 1;
+
+.voice-call-widget {
+ position: fixed;
+ inset-inline-end: max(1rem, env(safe-area-inset-right));
+ inset-block-end: max(1rem, env(safe-area-inset-bottom));
+ z-index: $voice-widget-z;
+
+ // border-box so the inline width/height set during resize match the
+ // border-box geometry the resize math measures (getBoundingClientRect);
+ // otherwise padding + border push the rendered box past the viewport.
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: 0.65rem;
+ width: min(24rem, calc(100vw - 2rem));
+
+ // Definite (not content-driven) height: the tile grid solves against the
+ // measured tile area, so the area must be settled before the tiles size —
+ // a content-driven box would chase its own layout.
+ height: min(21rem, 60vh);
+ padding: var(--space-3);
+ border: 1px solid var(--primary-low);
+ border-radius: 0.75rem;
+ background: var(--secondary);
+ box-shadow: 0 0.5rem 1.5rem rgb(0 0 0 / 20%);
+
+ &__header {
+ min-width: 0;
+ }
+
+ &__room {
+ width: 100%;
+ min-width: 0;
+ cursor: grab;
+ touch-action: none;
+ user-select: none;
+ }
+
+ &__room-name {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ // Tiles are uniform, sized by computeWidgetGrid from this box's measured
+ // size; flex wrapping breaks lines exactly at the solved column count and
+ // centers partial rows. `contain: size` keeps a transiently oversized tile
+ // from feeding back into the measurement (see video-grid-layout.js).
+ &__tiles {
+ flex: 1;
+ min-height: 0;
+ contain: size;
+ display: flex;
+ flex-wrap: wrap;
+ align-content: center;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ overflow: hidden;
+ }
+
+ .voice-video-tile {
+ flex: 0 0 auto;
+ width: var(--voice-tile-width, 45%);
+ height: var(--voice-tile-height, 5rem);
+ min-height: 0;
+ transition:
+ width 0.2s ease-out,
+ height 0.2s ease-out;
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+ }
+
+ &__overflow-tile {
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.25rem;
+ width: var(--voice-tile-width, 45%);
+ height: var(--voice-tile-height, 5rem);
+ overflow: hidden;
+ padding: 0;
+ border: none;
+ border-radius: 0.5em;
+ background: var(--primary-very-low);
+ color: var(--primary-high);
+ cursor: pointer;
+ transition:
+ width 0.2s ease-out,
+ height 0.2s ease-out,
+ background 0.15s ease;
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+
+ &:hover,
+ &:focus-visible {
+ background: var(--primary-low);
+ color: var(--primary);
+ }
+ }
+
+ &__overflow-avatars {
+ display: flex;
+
+ img {
+ width: 1.75rem;
+ height: 1.75rem;
+ border: 2px solid var(--secondary);
+ border-radius: 50%;
+
+ &:not(:first-child) {
+ margin-inline-start: -0.6rem;
+ }
+ }
+ }
+
+ &__overflow-count {
+ font-weight: 700;
+ font-size: var(--font-down-1);
+ }
+
+ .voice-video-tile__fullscreen {
+ display: none;
+ }
+
+ .voice-video-tile__avatar img {
+ width: 2.75rem;
+ height: 2.75rem;
+ }
+
+ .voice-video-tile__info {
+ font-size: var(--font-down-2);
+ }
+
+ &__controls {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+
+ // Stretch (not center) so every control shares the tallest button's height;
+ // icon-only DMenu triggers render a few px shorter otherwise. See the
+ // matching note on .voice-room-page__controls.
+ align-items: stretch;
+ gap: 0.35rem;
+
+ .--off,
+ .--active {
+ color: var(--tertiary);
+ }
+ }
+
+ &.--resizing {
+ user-select: none;
+ }
+
+ &.--extra-minimized {
+ width: auto;
+ min-width: 0;
+ height: auto;
+ padding: var(--space-2);
+
+ .voice-call-widget__controls {
+ flex-wrap: nowrap;
+ }
+ }
+
+ &.--dragging {
+ user-select: none;
+
+ .voice-call-widget__room {
+ cursor: grabbing;
+ }
+ }
+
+ // Corner hit targets for resizing. Dragging a corner moves that corner while
+ // the diagonal corner stays anchored in place. Corner-specific cursors, not
+ // the double-headed nwse/nesw pair: Firefox on macOS has no glyphs for those
+ // and falls back to the default arrow, hiding the resize affordance.
+ &__resize {
+ position: absolute;
+ z-index: 2;
+ width: 16px;
+ height: 16px;
+ touch-action: none;
+
+ &.--nw {
+ inset-block-start: -5px;
+ inset-inline-start: -5px;
+ cursor: nw-resize;
+ }
+
+ &.--ne {
+ inset-block-start: -5px;
+ inset-inline-end: -5px;
+ cursor: ne-resize;
+ }
+
+ &.--sw {
+ inset-block-end: -5px;
+ inset-inline-start: -5px;
+ cursor: sw-resize;
+ }
+
+ &.--se {
+ inset-block-end: -5px;
+ inset-inline-end: -5px;
+ cursor: se-resize;
+ }
+ }
+}
+
+// On touch devices the widget is a full-width bottom dock: corner resize is
+// hidden (component-side) and the header only drags it vertically, since
+// free positioning and tiny corner handles are awkward with a finger.
+html.discourse-touch .voice-call-widget {
+ inset-inline: 0.5rem;
+ width: auto;
+ height: min(19rem, 45vh);
+
+ &.--extra-minimized {
+ height: auto;
+ }
+}
+
+.voice-room-page {
+ display: flex;
+ flex-direction: column;
+ gap: 1em;
+
+ // A definite height (not just a floor) so the flex chain below actually
+ // constrains: without it a transiently oversized video tile stretches the
+ // whole page and pushes the control bar below the fold.
+ height: calc(100dvh - var(--header-offset, 4em) - 6em);
+
+ &__title-row {
+ display: flex;
+ align-items: center;
+ gap: 0.75em;
+ min-width: 0;
+ }
+
+ &__title {
+ margin: 0;
+ }
+
+ &__description {
+ margin: 0;
+ color: var(--primary-high);
+ overflow-wrap: anywhere;
+ }
+
+ // The video column and the chat sidebar sit side by side; the column flexes
+ // and the sidebar takes a fixed width. min-height: 0 lets the grid and the
+ // chat message list scroll instead of pushing the page taller.
+ &__body {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ gap: var(--space-4);
+ }
+
+ &__main {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+ }
+
+ &__sidebar {
+ flex: 0 0 22rem;
+ width: 22rem;
+ min-height: 0;
+ display: flex;
+ overflow: hidden;
+
+ // Animating the width (not just fading in place) makes the whole layout
+ // ease — the video column and controls resize smoothly instead of
+ // jumping the moment the panel claims its space.
+ animation: voice-sidebar-in 0.25s ease-out;
+
+ &.--closing {
+ animation: voice-sidebar-out 0.2s ease-in forwards;
+ }
+
+ // The panel keeps its full-width layout and gets revealed/clipped by the
+ // animating box, rather than squishing and rewrapping every frame.
+ .voice-chat {
+ min-width: 22rem;
+ }
+
+ // A (near) zero duration rather than none: leaving the closing state
+ // waits on animationend, which `animation: none` would never fire.
+ @media (prefers-reduced-motion: reduce) {
+ animation-duration: 0.01s;
+ }
+ }
+
+ &__chat-toggle {
+ &.--active {
+ color: var(--tertiary);
+ }
+ }
+
+ // Meet-style column: the video grid fills the space with tiles centered,
+ // and the control bar sits on the bottom row, level with the chat panel's
+ // composer next door.
+ &__stage {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ row-gap: 0.75em;
+ }
+
+ &__presentation {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(9rem, 13rem);
+ gap: var(--space-2);
+ }
+
+ &__presentation-main {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+
+ .voice-video-tile {
+ width: 100%;
+ height: 100%;
+ border-radius: calc(var(--d-border-radius) - 1px);
+ }
+
+ .voice-video-tile.--screen .voice-video-tile__video,
+ .voice-video-tile.--avatar .voice-video-tile__video {
+ object-fit: contain;
+ }
+ }
+
+ &__presentation-rail {
+ min-width: 0;
+ min-height: 0;
+ display: grid;
+ grid-auto-rows: minmax(5rem, 8rem);
+ gap: var(--space-2);
+ align-content: start;
+ overflow: auto;
+ padding-inline-end: 1px;
+
+ .voice-video-tile {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ &__grid {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+
+ // The tile height is computed from this element's measured size, so its
+ // own size must never derive from the tiles: after exiting fullscreen the
+ // still-huge tiles would inflate the grid (the page only has a
+ // min-height), the remeasure would see that inflated box, and the layout
+ // would lock there instead of shrinking back.
+ contain: size;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5em;
+ align-content: center;
+ align-items: center;
+ justify-content: center;
+
+ // While the sidebar animates, tiles rewrap faster than their height
+ // recomputes — clip the transient overflow so it can't spill over the
+ // control bar below.
+ overflow: hidden;
+
+ &:fullscreen {
+ background: #000;
+ padding: 0.5em;
+ }
+ }
+
+ // Top-left so it never collides with the per-tile fullscreen buttons
+ // (top-right). Visible in fullscreen too, since it lives inside the grid.
+ &__fullscreen {
+ position: absolute;
+ inset-block-start: 0.35em;
+ inset-inline-start: 0.35em;
+ z-index: 1;
+ color: #fff;
+ background: rgb(0 0 0 / 45%);
+
+ .d-icon {
+ color: #fff;
+ }
+
+ html.discourse-no-touch & {
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ }
+ }
+
+ html.discourse-no-touch &__grid:hover &__fullscreen,
+ &__fullscreen:focus-visible {
+ opacity: 1;
+ }
+
+ &__empty {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--primary-medium);
+ }
+
+ &__controls {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+
+ // Stretch (not center) so every control shares the tallest button's height.
+ // Icon-only DMenu triggers (e.g. the overflow menu) render a few px shorter
+ // than their DButton/plain-<button> siblings; stretching equalizes them the
+ // same way the combo wrapper stretches its caret.
+ align-items: stretch;
+ gap: 0.5em;
+
+ .--off,
+ .--active {
+ color: var(--tertiary);
+ }
+ }
+}
+
+// Split "combo" button (mic/camera) shared by VoiceCallControls in both the
+// room page and the widget: the main toggle and its caret read as one button.
+// The main button drops its trailing border so the caret's leading border is
+// the only divider between them.
+.voice-call-controls__combo {
+ display: inline-flex;
+ align-items: stretch;
+
+ .voice-call-controls__combo-main {
+ position: relative;
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ border-inline-end: none !important; // ensure core hover/active/focus rules don't restore the border
+ }
+
+ // Same look as the sidebar room lock: a tiny unobtrusive glyph tucked
+ // into the button's top-right corner, no backdrop.
+ .voice-call-controls__ns-badge {
+ position: absolute;
+ top: 0.15em;
+ right: 0.2em;
+ display: flex;
+
+ .d-icon {
+ width: 0.5rem;
+ height: 0.5rem;
+ }
+
+ &.--starting {
+ animation: voice-ns-badge-pulse 1s ease-in-out infinite;
+ }
+ }
+
+ .voice-call-controls__combo-caret {
+ margin-inline-start: 0;
+ padding-inline: 0.4em;
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ border-inline-start: 1px solid var(--primary-low-mid);
+ }
+}
+
+// Live subtitles. A zero-height flow child between the video area and the
+// control bar: lines are packed toward the bottom so they overflow upward,
+// floating over the tiles without shifting the layout when they appear.
+.voice-captions {
+ align-self: center;
+ width: min(100%, 46rem);
+ height: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ align-items: center;
+ row-gap: 0.25em;
+ z-index: 1;
+ pointer-events: none;
+
+ &__line {
+ margin: 0;
+ padding: 0.25em 0.75em;
+ max-width: 100%;
+ border-radius: var(--d-border-radius);
+ background: rgb(0 0 0 / 65%);
+ color: #fff;
+ text-align: center;
+ text-wrap: balance;
+
+ &.--loading {
+ color: rgb(255 255 255 / 75%);
+ font-style: italic;
+ }
+
+ // Provisional text that will be replaced when the speaker pauses.
+ &.--interim {
+ color: rgb(255 255 255 / 85%);
+ }
+ }
+
+ &__speaker {
+ font-weight: bold;
+
+ &::after {
+ content: ":";
+ }
+ }
+}
+
+@keyframes voice-ns-badge-pulse {
+ 50% {
+ opacity: 0.4;
+ }
+}
+
+.voice-speak-queue-trigger {
+ position: relative;
+
+ .voice-speak-queue-trigger__count {
+ position: absolute;
+ top: -0.4em;
+ right: -0.4em;
+ min-width: 1.6em;
+ padding: 0 0.3em;
+ border-radius: 1em;
+ background: var(--tertiary);
+ color: var(--secondary);
+ font-size: var(--font-down-2);
+ line-height: 1.6em;
+ text-align: center;
+ }
+}
+
+.voice-speak-queue {
+ min-width: 16em;
+ padding: 0.5em;
+
+ &__title {
+ margin: 0 0 0.5em;
+ font-size: var(--font-0);
+ }
+
+ &__list {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 0.25em;
+ }
+
+ &__item {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ padding: 0.25em;
+ border-radius: var(--d-border-radius);
+
+ &.--self {
+ background: var(--tertiary-very-low);
+ }
+ }
+
+ &__position {
+ min-width: 1.5em;
+ text-align: center;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__name {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__actions {
+ display: inline-flex;
+ gap: 0.25em;
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ padding: 0.5em;
+ }
+}
+
+// Float-kit menus portal to a body-level layer at z("dropdown") (300), but the
+// persistent call widget sits above the site header and would otherwise cover
+// any menu opened from it. Lift the call menus above the widget. Harmless on
+// the room page, which has no competing high-z layer.
+.fk-d-menu[data-identifier^="voice-"] {
+ z-index: $voice-widget-z + 1;
+}
+
+// Below this the 22rem sidebar would squash the video column into a sliver,
+// so instead of sitting beside it the panel becomes a full-height drawer over
+// the page (above the docked call widget). Keep in sync with the close-button
+// breakpoint in voice-chat.scss.
+@media (width <= 1000px) {
+ .voice-room-page__presentation {
+ grid-template-columns: 1fr;
+ grid-template-rows: minmax(0, 1fr) auto;
+ }
+
+ .voice-room-page__presentation-rail {
+ grid-auto-flow: column;
+ grid-auto-columns: minmax(8rem, 11rem);
+ grid-auto-rows: 6rem;
+ overflow-x: auto;
+ overflow-y: hidden;
+ padding-block-end: 1px;
+ }
+
+ .voice-room-page__sidebar {
+ position: fixed;
+ inset-block: var(--header-offset, 4em) 0;
+ inset-inline: 0;
+ z-index: 1050;
+ flex: none;
+ width: auto;
+ background: var(--secondary);
+ animation-name: voice-drawer-in;
+
+ &.--closing {
+ animation-name: voice-drawer-out;
+ }
+
+ .voice-chat {
+ min-width: 0;
+ }
+ }
+}
+
+.voice-video-tile {
+ position: relative;
+ flex: 0 0 auto;
+
+ // Rows share a height (computed per layout, published as
+ // --voice-tile-height); each tile sets its own aspect-ratio inline from
+ // its measured video, so portrait and landscape feeds coexist without
+ // cropping. The fallback height covers first paint before measurement.
+ height: var(--voice-tile-height, 12em);
+
+ // The computed height always lags the layout by a beat (resize observer →
+ // re-render); the hard cap keeps a stale value from ever growing the tile
+ // past the grid box, and the transition hides the catch-up step.
+ max-height: 100%;
+ transition: height 0.2s ease-out;
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+ width: auto;
+ max-width: 100%;
+ border-radius: 0.5em;
+ overflow: hidden;
+ background: var(--primary-very-low);
+
+ // An overlay rather than an inset outline: the video fills the tile and
+ // paints over the tile's own outline, so the ring only ever showed on
+ // avatar tiles.
+ &.--speaking::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ border: 3px solid var(--success);
+ border-radius: inherit;
+ pointer-events: none;
+ }
+
+ // When the tile itself is fullscreen it fills the screen at the screen's
+ // aspect, so show the whole frame rather than cropping it to fill.
+ &:fullscreen {
+ border-radius: 0;
+ background: #000;
+ }
+
+ &:fullscreen &__video {
+ object-fit: contain;
+ }
+
+ &__video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+
+ &__fullscreen,
+ &__menu {
+ position: absolute;
+ inset-inline-end: 0.35em;
+ color: #fff;
+ background: rgb(0 0 0 / 45%);
+
+ .d-icon {
+ color: #fff;
+ }
+
+ // Discoverable on touch (no hover); revealed on hover/focus on pointer
+ // devices to keep the tile clean.
+ html.discourse-no-touch & {
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ }
+ }
+
+ &__fullscreen {
+ inset-block-start: 0.35em;
+ }
+
+ &__menu {
+ inset-block-end: 0.35em;
+ }
+
+ html.discourse-no-touch &:hover &__fullscreen,
+ html.discourse-no-touch &:hover &__menu,
+ &__fullscreen:focus-visible,
+ &__menu:focus-visible {
+ opacity: 1;
+ }
+
+ &.--self:not(.--screen) &__video {
+ transform: scaleX(-1);
+ }
+
+ &.--screen &__video {
+ object-fit: contain;
+ background: var(--primary-very-high);
+ }
+
+ &__avatar {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+
+ img {
+ width: 4em;
+ height: 4em;
+ border-radius: 50%;
+ }
+ }
+
+ &__info {
+ position: absolute;
+ inset-block-end: 0;
+ inset-inline: 0;
+ display: flex;
+ align-items: center;
+ gap: 0.35em;
+ padding: 0.25em 0.5em;
+
+ // Keep the name and status icons clear of the corner menu trigger.
+ padding-inline-end: 2.75em;
+ font-size: var(--font-down-1);
+
+ // Subtitle-style fixed colors, deliberately not palette vars: this text
+ // sits on arbitrary video frames, which don't change with the color
+ // scheme, so inverting with the theme is exactly what breaks it.
+ color: #fff;
+ text-shadow:
+ 0 1px 2px rgb(0 0 0 / 80%),
+ 0 0 4px rgb(0 0 0 / 50%);
+
+ .d-icon {
+ color: #fff;
+ filter: drop-shadow(0 1px 1px rgb(0 0 0 / 80%));
+ }
+ }
+
+ &__name {
+ overflow-wrap: anywhere;
+ }
+}
+
+@keyframes voice-sidebar-in {
+ from {
+ flex-basis: 0;
+ width: 0;
+ opacity: 0;
+ }
+
+ to {
+ flex-basis: 22rem;
+ width: 22rem;
+ opacity: 1;
+ }
+}
+
+@keyframes voice-sidebar-out {
+ from {
+ flex-basis: 22rem;
+ width: 22rem;
+ opacity: 1;
+ }
+
+ to {
+ flex-basis: 0;
+ width: 0;
+ opacity: 0;
+ }
+}
+
+// The narrow-viewport drawer overlays the page instead of participating in
+// its layout, so it slides over from the edge rather than animating width.
+@keyframes voice-drawer-in {
+ from {
+ transform: translateX(100%);
+ }
+
+ to {
+ transform: none;
+ }
+}
+
+@keyframes voice-drawer-out {
+ from {
+ transform: none;
+ }
+
+ to {
+ transform: translateX(100%);
+ }
+}
+
+.voice-ringing-tile {
+ // No measured video to derive a shape from — assume the default tile
+ // aspect so it packs into the grid like everyone else.
+ aspect-ratio: 16 / 9;
+ border: 1px dashed var(--primary-low-mid);
+ background: var(--primary-very-low);
+
+ &__animation {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+
+ // Placeholder styling until the bespoke ringing SVG animation replaces
+ // the icon.
+ .d-icon {
+ font-size: var(--font-up-4);
+ color: var(--primary-medium);
+ animation: voice-ringing-pulse 1.4s ease-in-out infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+ }
+
+ .voice-video-tile__name {
+ font-style: italic;
+ }
+}
+
+@keyframes voice-ringing-pulse {
+ 0%,
+ 100% {
+ transform: scale(1);
+ opacity: 0.6;
+ }
+
+ 50% {
+ transform: scale(1.15);
+ opacity: 1;
+ }
+}
diff --git a/plugins/voice/assets/stylesheets/common/voice.scss b/plugins/voice/assets/stylesheets/common/voice.scss
new file mode 100644
index 00000000000..53f68505e32
--- /dev/null
+++ b/plugins/voice/assets/stylesheets/common/voice.scss
@@ -0,0 +1,1299 @@
+.sidebar-section-link.voice-sidebar-link {
+ .sidebar-section-link-suffix {
+ font-size: var(--font-down-2);
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+
+ &.voice-sidebar-link--connecting .sidebar-section-link-suffix .d-icon {
+ animation: spin 1s linear infinite;
+ }
+}
+
+.voice-sidebar-participant {
+ // Indent so participant avatars start where the room name text starts,
+ // making rows read unambiguously as children of the room above.
+ padding-left: calc(
+ var(--d-sidebar-row-horizontal-padding) +
+ var(--d-sidebar-section-link-prefix-width) +
+ var(--d-sidebar-section-link-prefix-margin-right)
+ );
+ position: relative;
+
+ .sidebar-section-link-prefix {
+ position: relative;
+
+ img {
+ width: 1.25rem;
+ height: 1.25rem;
+ border-radius: 50%;
+ transition:
+ opacity 0.3s ease,
+ filter 0.3s ease;
+ }
+ }
+
+ .sidebar-section-link-content-text {
+ font-size: var(--font-down-1);
+ color: var(--primary-high);
+ }
+
+ &--muted,
+ &--deafened {
+ .sidebar-section-link-prefix img {
+ opacity: 0.5;
+ }
+
+ .sidebar-section-link-content-text {
+ opacity: 0.7;
+ }
+ }
+
+ // Every applicable state icon renders together, in a fixed order
+ // (hand raised, screenshare, camera, PTT, muted, deafened), at one size
+ // and color.
+ .voice-participant-suffix {
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ flex-shrink: 0;
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+
+ // A raised hand is a request waiting on someone — accent it so it reads
+ // over the passive state icons.
+ .d-icon-hand {
+ color: var(--tertiary);
+ }
+ }
+
+ // The hover button already reserves space on the right; without this its
+ // own auto margin would pull the suffix icons away from the right edge.
+ .sidebar-section-link-hover {
+ margin-left: 0;
+ }
+
+ &--idle,
+ &--afk {
+ .sidebar-section-link-prefix {
+ &::after {
+ content: "";
+ position: absolute;
+ right: -2px;
+ bottom: -2px;
+ height: 0.5rem;
+ width: 0.5rem;
+ background-color: var(--primary-medium);
+ border-radius: 50%;
+ border: 1.5px solid var(--secondary);
+
+ // moon (FA solid)
+ mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 384 512'%3E%3Cpath d='M223.5 32C100 32 0 132.3 0 256S100 480 223.5 480c60.6 0 115.5-24.2 155.8-63.4c5-4.9 6.3-12.5 3.1-18.7s-10.1-9.7-17-8.5c-9.8 1.7-19.8 2.6-30.1 2.6c-96.9 0-175.5-78.8-175.5-176c0-65.8 36-123.1 89.3-153.3c6.1-3.5 9.2-10.5 7.7-17.3s-7.3-11.9-14.3-12.5c-6.3-.5-12.6-.8-19-.8z'/%3E%3C/svg%3E");
+ mask-size: contain;
+ mask-repeat: no-repeat;
+ mask-position: center;
+ }
+ }
+ }
+
+ &--listener {
+ .sidebar-section-link-prefix img {
+ opacity: 0.5;
+ }
+
+ .sidebar-section-link-content-text {
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ }
+ }
+
+ &--listeners-start {
+ border-top: 1px solid var(--primary-low);
+ padding-top: 0.25rem;
+ margin-top: 0.25rem;
+ }
+
+ &--listener-count {
+ .sidebar-section-link-content-text {
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+ }
+
+ &--idle {
+ .sidebar-section-link-prefix img {
+ opacity: 0.6;
+ transition: opacity 0.3s ease;
+ }
+
+ .sidebar-section-link-content-text {
+ opacity: 0.6;
+ transition: opacity 0.3s ease;
+ }
+ }
+
+ &--afk {
+ .sidebar-section-link-prefix img {
+ opacity: 0.4;
+ filter: grayscale(100%);
+ transition:
+ opacity 0.3s ease,
+ filter 0.3s ease;
+ }
+
+ .sidebar-section-link-content-text {
+ opacity: 0.5;
+ transition: opacity 0.3s ease;
+ }
+ }
+
+ // While speaking, the wave takes over the avatar: the picture fades behind
+ // a backdrop disc (so the wave stays legible over photo avatars) with the
+ // animated bars centered on top. Last so it wins over the idle/afk badge.
+ &--speaking {
+ .sidebar-section-link-content-text {
+ color: var(--primary);
+ }
+
+ .sidebar-section-link-prefix {
+ img {
+ opacity: 0.25;
+ }
+
+ &::before {
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ height: 1.25rem;
+ width: 1.25rem;
+ border-radius: 50%;
+ background: var(--d-sidebar-background);
+ opacity: 0.4;
+ }
+
+ &::after {
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ height: 0.875rem;
+ width: 0.8125rem;
+ border: none;
+ border-radius: 0;
+ mask-image: none;
+ background:
+ linear-gradient(var(--success), var(--success)) 0 50%,
+ linear-gradient(var(--success), var(--success)) 5px 50%,
+ linear-gradient(var(--success), var(--success)) 10px 50%;
+ background-size:
+ 3px 40%,
+ 3px 70%,
+ 3px 50%;
+ background-repeat: no-repeat;
+ animation: voice-audio-bars 0.8s ease-in-out infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+ }
+ }
+}
+
+@keyframes voice-audio-bars {
+ 0%,
+ 100% {
+ background-size:
+ 3px 40%,
+ 3px 70%,
+ 3px 50%;
+ }
+
+ 25% {
+ background-size:
+ 3px 70%,
+ 3px 40%,
+ 3px 80%;
+ }
+
+ 50% {
+ background-size:
+ 3px 50%,
+ 3px 90%,
+ 3px 40%;
+ }
+
+ 75% {
+ background-size:
+ 3px 80%,
+ 3px 50%,
+ 3px 70%;
+ }
+}
+
+.voice-room {
+ padding: 1.5em;
+
+ &__header {
+ margin-bottom: 1em;
+
+ h1 {
+ margin: 0;
+ font-size: var(--font-up-2);
+ }
+
+ p {
+ color: var(--primary-medium);
+ }
+ }
+
+ &__participants {
+ margin-bottom: 1em;
+
+ ul {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: grid;
+ gap: 0.25em;
+ }
+
+ li {
+ display: flex;
+ gap: 0.5em;
+ align-items: center;
+ }
+ }
+
+ &__controls {
+ margin-bottom: 1em;
+ }
+}
+
+.voice-voice-canvas {
+ position: absolute;
+ width: 0;
+ height: 0;
+ overflow: hidden;
+
+ audio {
+ width: 0;
+ height: 0;
+ opacity: 0;
+ }
+}
+
+// Core lays the toggle field out as a single flex row, which crams the
+// description beside the control once the field goes full width. Regroup it:
+// title and description stacked on the left, control centered on the right.
+.voice-room-form__form {
+ .form-kit__field-toggle {
+ box-sizing: border-box;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ column-gap: 1rem;
+ align-items: center;
+
+ .form-kit__container-title,
+ .form-kit__container-description {
+ grid-column: 1;
+ width: auto;
+ min-width: 0;
+ }
+
+ .form-kit__container-content {
+ grid-column: 2;
+ grid-row: 1 / span 2;
+ width: auto;
+ min-width: 0;
+ }
+ }
+
+ .voice-room-form__manage-members {
+ padding: 0;
+ font-size: var(--font-down-1);
+
+ // Keep the card height stable so toggling doesn't shift the control
+ // under the pointer mid-click.
+ &.--hidden {
+ visibility: hidden;
+ }
+ }
+}
+
+.voice-room-form {
+ .voice-admin-back {
+ margin-bottom: 1em;
+ }
+
+ .voice-room-form__form {
+ max-width: 600px;
+ }
+
+ // `.form-kit` spaces its own direct children with a flex gap; wrapping the
+ // chat fields in this container opts them out of that, so it needs the same
+ // treatment to keep a consistent rhythm with the rest of the form.
+ .voice-room-form__chat {
+ display: flex;
+ flex-direction: column;
+ gap: 1.5em;
+ align-items: flex-start;
+ }
+
+ .voice-room-form__quality {
+ align-self: stretch;
+
+ summary {
+ cursor: pointer;
+ font-weight: bold;
+ color: var(--primary-high);
+ }
+
+ .form-kit__field {
+ margin-top: 1em;
+ }
+ }
+}
+
+.voice-create-room-modal {
+ .voice-room-form__form {
+ max-width: 100%;
+ }
+
+ .form-kit__field-toggle {
+ background: var(--primary-very-low);
+ border-radius: 8px;
+ padding: 0.75rem 1rem;
+ }
+
+ .form-kit__field-input-number .form-kit__container-content {
+ width: var(--form-kit-large-input);
+ }
+}
+
+.voice-room-sidebar-context-menu {
+ .btn {
+ width: 100%;
+ justify-content: flex-start;
+ }
+}
+
+.voice-participant-sidebar-context-menu {
+ min-width: 200px;
+
+ .btn {
+ width: 100%;
+ justify-content: flex-start;
+ }
+
+ &__volume {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ padding: 0.5rem 0.75rem;
+ }
+
+ &__volume-label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__volume-slider {
+ width: 100%;
+ cursor: pointer;
+ }
+
+ &__kick-btn {
+ color: var(--danger);
+
+ &:hover {
+ background: var(--danger-low);
+ }
+ }
+
+ &__mic-btn.--disabled-by-ptt {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ &__ptt-hint {
+ display: block;
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ padding: 0 0.75rem 0.25rem;
+ }
+
+ &__ptt-btn.--active {
+ color: var(--tertiary);
+ }
+
+ &__stage-hint {
+ display: block;
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ padding: 0.25rem 0.75rem;
+ font-style: italic;
+ }
+
+ &__promote-btn {
+ color: var(--success);
+ }
+
+ &__demote-btn {
+ color: var(--primary-medium);
+ }
+}
+
+.voice-ptt-key-capture {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: 0.35rem;
+ padding: 0.5rem 0.75rem;
+ outline: none;
+
+ &__display {
+ flex: 1;
+ padding: 0.35rem 0.5rem;
+ border: 1px dashed var(--primary-low-mid);
+ border-radius: 4px;
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ text-align: center;
+
+ &--captured {
+ border-color: var(--tertiary);
+ border-style: solid;
+ color: var(--primary);
+ font-weight: 600;
+ }
+
+ &--error {
+ border-color: var(--danger);
+ border-style: solid;
+ color: var(--danger);
+ }
+ }
+
+ &__actions {
+ display: flex;
+ flex-direction: row;
+ gap: 0.15rem;
+ flex-shrink: 0;
+ }
+
+ .btn.btn-flat.voice-ptt-key-capture__confirm:not(:disabled) {
+ color: var(--success);
+
+ .d-icon {
+ color: var(--success);
+ }
+
+ &:hover {
+ background: var(--success-low);
+ }
+ }
+
+ .btn.btn-flat.voice-ptt-key-capture__cancel {
+ color: var(--danger);
+
+ .d-icon {
+ color: var(--danger);
+ }
+
+ &:hover {
+ background: var(--danger-low);
+ }
+ }
+}
+
+.voice-sidebar-participant__ptt-badge {
+ font-size: var(--font-down-2);
+ color: var(--tertiary);
+ font-weight: 600;
+ margin-left: 0.25rem;
+}
+
+.voice-room-info-modal {
+ .d-modal__body {
+ padding: 0;
+ }
+
+ &__header {
+ display: flex;
+ align-items: flex-start;
+ gap: 1rem;
+ padding: 1.5rem;
+ background: linear-gradient(
+ 135deg,
+ var(--tertiary-low) 0%,
+ var(--tertiary-very-low) 100%
+ );
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ &__icon {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 3.5rem;
+ height: 3.5rem;
+ background: var(--tertiary);
+ border-radius: 12px;
+ flex-shrink: 0;
+
+ .d-icon {
+ color: var(--secondary);
+ font-size: 1.5rem;
+ }
+ }
+
+ &__icon-badge.d-icon {
+ position: absolute;
+ top: -0.4rem;
+ right: -0.4rem;
+ font-size: var(--font-down-2);
+ padding: 0.2rem;
+ background: var(--tertiary);
+ border-radius: var(--token-radius-full);
+ }
+
+ &__header-content {
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__room-name {
+ margin: 0 0 0.25rem;
+ font-size: var(--font-up-3);
+ font-weight: 700;
+ color: var(--primary);
+ line-height: 1.2;
+ }
+
+ &__description {
+ margin: 0;
+ color: var(--primary-high);
+ font-size: var(--font-0);
+ line-height: 1.4;
+ }
+
+ &__stats {
+ display: flex;
+ gap: 0.5rem;
+ padding: 1rem 1.5rem;
+ background: var(--secondary);
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ &__stat {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ flex: 1;
+ padding: 0.75rem;
+ background: var(--primary-very-low);
+ border-radius: 8px;
+ text-align: center;
+ gap: 0.25rem;
+ }
+
+ &__stat-value {
+ font-size: var(--font-up-2);
+ font-weight: 700;
+ color: var(--primary);
+
+ .d-icon {
+ font-size: 1.25rem;
+ color: var(--primary-medium);
+ }
+ }
+
+ &__stat-label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ font-weight: 500;
+ }
+
+ &__members {
+ padding: 1.5rem;
+ }
+
+ &__section-header {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin-bottom: 1rem;
+ padding-bottom: 0.75rem;
+ border-bottom: 2px solid var(--tertiary-low);
+
+ .d-icon {
+ color: var(--tertiary);
+ font-size: 1.1rem;
+ }
+
+ h3 {
+ margin: 0;
+ font-size: var(--font-up-1);
+ font-weight: 600;
+ color: var(--primary);
+ }
+ }
+
+ &__loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.75rem;
+ padding: 2rem;
+ color: var(--primary-medium);
+ }
+
+ &__member-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ margin-bottom: 1.25rem;
+ max-height: 300px;
+ overflow-y: auto;
+ }
+
+ &__member {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.75rem;
+ background: var(--primary-very-low);
+ border-radius: 8px;
+ transition: background 0.15s ease;
+
+ &:hover {
+ background: var(--primary-low);
+ }
+
+ &.--creator {
+ background: linear-gradient(
+ 135deg,
+ var(--tertiary-very-low) 0%,
+ var(--primary-very-low) 100%
+ );
+ border: 1px solid var(--tertiary-low);
+
+ &:hover {
+ background: linear-gradient(
+ 135deg,
+ var(--tertiary-low) 0%,
+ var(--primary-low) 100%
+ );
+ }
+ }
+ }
+
+ &__member-avatar {
+ flex-shrink: 0;
+
+ img {
+ border-radius: 50%;
+ box-shadow: 0 1px 3px rgb(0, 0, 0, 0.1);
+ }
+ }
+
+ &__member-details {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ }
+
+ &__member-username {
+ font-weight: 600;
+ color: var(--primary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__member-role {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ text-transform: capitalize;
+
+ &.--creator {
+ color: var(--tertiary);
+ font-weight: 500;
+
+ .d-icon {
+ font-size: 0.75rem;
+ color: var(--tertiary);
+ }
+ }
+
+ &.--moderator {
+ color: var(--success);
+ }
+ }
+
+ &__member-actions {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-shrink: 0;
+ }
+
+ &__role-select {
+ min-width: 110px;
+
+ .select-kit-header {
+ padding: 0.35rem 0.5rem;
+ }
+ }
+
+ &__remove-btn {
+ color: var(--primary-medium);
+ padding: 0.4rem;
+
+ &:hover {
+ color: var(--danger);
+ background: var(--danger-low);
+ }
+
+ .d-icon {
+ font-size: 0.85rem;
+ }
+ }
+
+ &__add-member {
+ padding-top: 1rem;
+ border-top: 1px solid var(--primary-low);
+ }
+
+ &__add-row {
+ display: flex;
+ gap: 0.5rem;
+ align-items: stretch;
+ }
+
+ &__user-chooser {
+ flex: 1;
+ min-width: 180px;
+ }
+
+ &__role-chooser {
+ width: 120px;
+ flex-shrink: 0;
+ }
+
+ &__add-btn {
+ flex-shrink: 0;
+ padding: 0.5rem 0.75rem;
+ }
+
+ &__edit-btn {
+ flex-shrink: 0;
+ align-self: flex-start;
+ }
+
+ &__edit-form {
+ padding: 1.5rem;
+
+ .voice-room-form__form {
+ max-width: 100%;
+ }
+
+ .form-kit__field-toggle {
+ background: var(--primary-very-low);
+ border-radius: 8px;
+ padding: 0.75rem 1rem;
+ }
+
+ .form-kit__field-input-number .form-kit__container-content {
+ width: var(--form-kit-large-input);
+ }
+ }
+}
+
+.voice-voice-settings {
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+
+ &__field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+
+ .combo-box {
+ width: 100%;
+ }
+ }
+
+ &__label {
+ font-weight: bold;
+ margin-bottom: 0;
+ }
+
+ &__output-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+
+ .combo-box {
+ flex: 1;
+ min-width: 0;
+ }
+ }
+
+ &__choose-output-btn {
+ flex: 1;
+ justify-content: flex-start;
+ }
+
+ &__meter {
+ position: relative;
+ height: 0.75rem;
+ border-radius: 0.375rem;
+ background: var(--primary-low);
+
+ &.--open .voice-voice-settings__meter-fill {
+ background: var(--success);
+ }
+ }
+
+ &__meter-fill {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ border-radius: inherit;
+ background: var(--primary-medium);
+ transition: width 0.05s linear;
+ }
+
+ &__meter-threshold {
+ position: absolute;
+ top: -0.15rem;
+ bottom: -0.15rem;
+ width: 2px;
+ border-radius: 1px;
+ background: var(--tertiary);
+ }
+
+ &__sensitivity-slider {
+ width: 100%;
+ cursor: pointer;
+ }
+
+ &__hint {
+ margin: 0;
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__mic-error {
+ margin: 0;
+ color: var(--danger);
+ }
+}
+
+.voice-video-settings {
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+
+ &__preview {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ aspect-ratio: 16 / 9;
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+ overflow: hidden;
+
+ video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ }
+
+ &__field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+ }
+
+ &__label {
+ font-weight: bold;
+ margin-bottom: 0;
+ }
+
+ &__blur-slider {
+ width: 100%;
+ cursor: pointer;
+ }
+
+ &__hint {
+ margin: 0;
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__camera-error {
+ margin: 0;
+ padding: 1rem;
+ color: var(--danger);
+ }
+}
+
+// A quiet pill: the label stays muted like any secondary metadata; only the
+// small dot carries the "live" red.
+.voice-recording-badge {
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ gap: 0.4em;
+ padding: 0.15em 0.65em;
+ border: 1px solid var(--primary-low-mid);
+ border-radius: 1em;
+ background: var(--primary-very-low);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: normal;
+ line-height: var(--line-height-medium);
+ vertical-align: middle;
+
+ .d-icon {
+ width: 0.5em;
+ height: 0.5em;
+ color: var(--danger);
+ animation: voice-recording-pulse 2s ease-in-out infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+}
+
+// Same quiet pill as the recording badge, minus the "live" red: the
+// transcript is local to this user, not a room-wide broadcast.
+.voice-transcript-badge {
+ display: inline-flex;
+ align-items: center;
+ flex-shrink: 0;
+ gap: 0.4em;
+
+ .fk-d-tooltip__trigger-container {
+ align-items: center;
+ gap: 0.4em;
+ }
+ padding: 0.15em 0.65em;
+ border: 1px solid var(--primary-low-mid);
+ border-radius: 1em;
+ background: var(--primary-very-low);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: normal;
+ line-height: var(--line-height-medium);
+ vertical-align: middle;
+
+ .d-icon {
+ width: 0.85em;
+ height: 0.85em;
+ color: var(--tertiary);
+ animation: voice-recording-pulse 2s ease-in-out infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+}
+
+.fk-d-tooltip__content.voice-transcript-badge-content {
+ font-size: var(--font-down-1);
+}
+
+.voice-room-page__transcript-toggle {
+ &.--recording {
+ .d-icon {
+ color: var(--danger);
+ }
+ }
+}
+
+.voice-call-controls__record {
+ &.--recording {
+ .d-icon {
+ color: var(--danger);
+ animation: voice-recording-pulse 2s ease-in-out infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ }
+ }
+}
+
+@keyframes voice-recording-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+.voice-call-menu__device-row {
+ .d-button-label {
+ flex: 1 1 auto;
+ text-align: left;
+ }
+
+ .voice-call-menu__current-device {
+ max-width: 11em;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ color: var(--primary-medium);
+ }
+
+ .d-button__suffix-icon {
+ margin-left: 0;
+ }
+}
+
+.voice-invite-modal {
+ .d-modal__body {
+ display: flex;
+ flex-direction: column;
+ gap: 1.5rem;
+ }
+
+ &__label {
+ display: block;
+ margin-bottom: 0.5rem;
+ font-weight: 600;
+ color: var(--primary);
+ }
+
+ &__search-row,
+ &__link-row {
+ display: flex;
+ gap: 0.5rem;
+ align-items: flex-start;
+ }
+
+ &__user-chooser {
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__section-title {
+ margin: 0 0 0.75rem;
+ font-size: var(--font-0);
+ font-weight: 600;
+ color: var(--primary);
+ }
+
+ &__suggestion-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ max-height: 16rem;
+ overflow-y: auto;
+ }
+
+ &__suggestion {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.5rem;
+ border-radius: 8px;
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__suggestion-details {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__suggestion-username {
+ font-weight: 600;
+ color: var(--primary);
+ }
+
+ &__suggestion-time {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__suggestion-invited {
+ display: flex;
+ align-items: center;
+ gap: 0.35rem;
+ color: var(--success);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--success);
+ }
+ }
+
+ &__link-input {
+ flex: 1;
+ min-width: 0;
+ margin-bottom: 0;
+ color: var(--primary-medium);
+ }
+
+ &__loading {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ color: var(--primary-medium);
+ }
+}
+
+.voice-mesh-privacy-warning-modal {
+ .d-modal__container {
+ max-width: 32rem;
+ }
+
+ &__body {
+ margin: 0;
+ }
+
+ &__dont-show-again {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin: 1rem 0 0;
+ color: var(--primary-medium);
+
+ input[type="checkbox"] {
+ margin: 0;
+ }
+ }
+}
+
+.voice-mic-permission-modal {
+ .d-modal__container {
+ max-width: 32rem;
+ }
+
+ &__body {
+ margin: 0;
+ }
+
+ &__instructions {
+ margin: 1rem 0 0;
+ }
+}
+
+.voice-incoming-call-modal {
+ .d-modal__container {
+ max-width: 22rem;
+ }
+
+ &__caller {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.25rem;
+ padding: 1rem 0 0.5rem;
+ text-align: center;
+ }
+
+ &__avatar {
+ position: relative;
+ margin-bottom: 1rem;
+
+ img.avatar {
+ display: block;
+ }
+
+ // Rings pulsing outward from the avatar, echoing the ringtone.
+ &::before,
+ &::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ border-radius: 50%;
+ border: 2px solid var(--tertiary);
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ @media (prefers-reduced-motion: no-preference) {
+ &::before {
+ animation: voice-call-pulse 2s ease-out infinite;
+ }
+
+ &::after {
+ animation: voice-call-pulse 2s ease-out 1s infinite;
+ }
+ }
+ }
+
+ &__name {
+ font-size: var(--font-up-3);
+ font-weight: bold;
+ overflow-wrap: anywhere;
+ }
+
+ &__state {
+ color: var(--primary-medium);
+ }
+
+ .d-modal__footer {
+ justify-content: center;
+ gap: 1rem;
+ }
+
+ // btn-primary supplies the contrast text/icon colors; only the surface
+ // changes to the universal answer-a-call green.
+ &__answer.btn-primary {
+ background: var(--success);
+
+ &:hover,
+ &:focus-visible {
+ background: var(--success-hover);
+ }
+ }
+}
+
+@keyframes voice-call-pulse {
+ 0% {
+ transform: scale(1);
+ opacity: 0.5;
+ }
+
+ 100% {
+ transform: scale(1.6);
+ opacity: 0;
+ }
+}
diff --git a/plugins/voice/config/locales/client.en.yml b/plugins/voice/config/locales/client.en.yml
new file mode 100644
index 00000000000..01cfc89d59a
--- /dev/null
+++ b/plugins/voice/config/locales/client.en.yml
@@ -0,0 +1,407 @@
+en:
+ js:
+ voice:
+ sidebar:
+ title: "Voice rooms"
+ create: "Create room"
+ empty: "No voice rooms yet."
+ room:
+ join: "Join voice room"
+ leave: "Leave room"
+ info: "Room info"
+ edit: "Edit room"
+ copy_link: "Copy link"
+ link_copied: "Link copied to clipboard"
+ menu_title: "Room options"
+ created: "Room created successfully."
+ updated: "Room updated successfully."
+ save: "Save"
+ connecting: "Connecting to peers…"
+ disconnected: "You left the room."
+ participants: "Listeners"
+ mic_on: "Mute microphone"
+ mic_off: "Unmute microphone"
+ noise_suppression_active: "Noise suppression active"
+ connection_error: "We couldn't start a WebRTC session. Please ensure your browser has microphone permissions."
+ mic_unavailable: "We couldn't access your microphone. Check that it is connected and not in use by another app, then try again."
+ deafen_on: "Deafen"
+ deafen_off: "Undeafen"
+ type_open: "Open"
+ type_open_description: "Everyone can speak"
+ type_stage: "Stage"
+ type_stage_description: "Only speakers and moderators can unmute"
+ type_stage_hint: "Participants join as listeners. Moderators can promote listeners to speakers."
+ listeners_cannot_unmute: "Only speakers can unmute in this room."
+ open_page: "Show full room view"
+ widget_mode: "Widget view"
+ settings: "Call settings"
+ more: "More options"
+ audio_options: "Audio options"
+ video_options: "Video options"
+ layout: "Layout"
+ recording_start: "Start recording"
+ recording_stop: "Stop recording"
+ recording_confirm: "Start recording this call? Every participant will see a recording indicator."
+ recording_stop_confirm: "Stop recording this call?"
+ recording_indicator: "Recording"
+ recording_indicator_title: "Recording started by %{username}"
+ recording_started_toast: "This call is now being recorded."
+ recording_stopped_toast: "The recording has stopped."
+ room_page:
+ empty: "No one is here yet — join to get things started."
+ widget:
+ title: "Active voice room: %{room}"
+ open_chat: "Open room chat"
+ expand: "Expand call widget"
+ hide: "Hide call widget"
+ show: "Show call widget"
+ overflow_tile:
+ one: "Show %{count} more participant"
+ other: "Show %{count} more participants"
+ overflow_count: "+%{count}"
+ chat:
+ title: "Chat"
+ open: "Open chat"
+ close: "Close chat"
+ unavailable: "Chat is unavailable right now."
+ empty_title: "No chat yet"
+ empty_body: "Send a message to get the conversation started."
+ composer_placeholder: "Message the room…"
+ send: "Send"
+ open_in_chat: "Open in chat"
+ back_to_voice_room: "Back to voice room"
+ video:
+ camera_on: "Turn on camera"
+ camera_off: "Turn off camera"
+ screen_share_start: "Share your screen"
+ screen_share_stop: "Stop sharing your screen"
+ publisher_limit: "The maximum number of simultaneous video streams has been reached."
+ capture_failed: "We couldn't start your camera or screen share. Check your browser permissions."
+ camera_switch_denied: "We couldn't switch cameras. Check your browser's camera permissions."
+ camera_switch_failed: "We couldn't start that camera. It may be in use by another app or unavailable."
+ room_disabled: "Video was turned off in this room."
+ fullscreen: "Full screen"
+ exit_fullscreen: "Exit full screen"
+ fullscreen_all: "Full-screen all videos"
+ layout: "Video layout"
+ layout_presentation: "Presentation layout"
+ layout_tiled: "Tiled layout"
+ ptt:
+ enable: "Push to Talk"
+ disable: "Disable Push to Talk"
+ configure_key: "PTT Key: %{key}"
+ press_key: "Press a key…"
+ reserved_key: "This key is reserved."
+ controlled_by_ptt: "Controlled by Push to Talk"
+ badge: "PTT: %{key}"
+ idle:
+ auto_muted: "You were auto-muted after being idle."
+ click_to_unmute: "Click to unmute."
+ disconnected: "You were disconnected from %{room} due to inactivity."
+ livekit:
+ browser_unsupported: "Your browser can't connect to this site's voice server. Try updating it or using a different browser."
+ connect_failed: "Your network cannot reach the voice server. Check your connection or contact your administrator."
+ reconnect_failed: "The connection to the voice server was lost, so you left the call. Rejoin to reconnect."
+ room_ended: "The call ended while you were disconnected. Rejoin to start a new one."
+ duplicate_tab: "This call continued in another tab or window, so this one was disconnected."
+ mic_permission:
+ title: "Your microphone is blocked"
+ body: "Voice rooms need microphone access, but your browser is blocking it for this site — usually because access was denied here before and the browser recorded that choice."
+ instructions: "To fix it, open the site permissions in your browser (the lock or settings icon next to the address bar), allow the microphone, and try joining again."
+ ok: "Got it"
+ mesh_privacy_warning:
+ title: "Before you join this room"
+ body: "This room connects participants directly to each other, so while you are in the call other participants may be able to see your IP address. This is how peer-to-peer calls work and is usually harmless, but join only if you are comfortable with it."
+ join: "Join room"
+ cancel: "Cancel"
+ dont_show_again: "Don't show this again"
+ status:
+ auto_update_on: "Auto-update status"
+ auto_update_off: "Auto-update status"
+ devices:
+ system_default: "System default"
+ unknown_device: "Device %{index}"
+ quality:
+ standard: "Standard"
+ high: "High"
+ maximum: "Maximum"
+ video_settings:
+ title: "Video settings"
+ camera: "Camera"
+ background_blur: "Blur my background"
+ blur_amount: "Blur amount"
+ blur_failed: "Background blur couldn't be started, so it was turned off."
+ camera_error: "We couldn't access your camera. Check your browser permissions."
+ not_supported: "Background blur isn't supported by this browser."
+ camera_quality: "Camera quality"
+ camera_quality_hint: "Higher settings send sharper video but use more bandwidth and CPU, especially with several viewers. Maximum keeps full quality no matter how many people are watching."
+ screen_quality: "Screen share quality"
+ screen_quality_hint: "Higher settings allow sharper, smoother screen shares at the cost of bandwidth. Maximum suits fast, stable connections sharing high-resolution screens."
+ screen_content: "Optimize screen share for"
+ screen_content_text: "Text sharpness"
+ screen_content_motion: "Smooth motion"
+ screen_content_hint: "Text keeps the image crisp and lets the frame rate drop; motion keeps playback smooth and lets sharpness drop."
+ voice_settings:
+ title: "Voice settings"
+ open: "Voice settings"
+ input_audio: "Input"
+ output_audio: "Output"
+ audio_settings: "Audio settings"
+ input_device: "Input device"
+ output_device: "Output device"
+ mic_test: "Microphone test"
+ mic_test_hint: "Speak into your microphone — the bar shows your input level."
+ mic_error: "We couldn't access your microphone. Check your browser permissions and device selection."
+ input_sensitivity: "Input sensitivity"
+ input_sensitivity_hint: "Sound below this level won't be transmitted. Set to zero to always transmit."
+ noise_suppression: "Noise suppression"
+ noise_suppression_hint: "Filters noise like fans and keyboard clicks from your microphone. AI noise cancellation is stronger but uses more resources."
+ noise_suppression_modes:
+ none: "None"
+ standard: "Standard"
+ ai_rnnoise: "AI — RNNoise (lightweight)"
+ ai_dtln: "AI — DTLN (balanced)"
+ ai_dfn3: "AI — DeepFilterNet (best quality)"
+ noise_suppression_failed: "AI noise cancellation couldn't run, so it was switched off."
+ echo_cancellation: "Echo cancellation"
+ echo_cancellation_hint: "Prevents others from hearing their own audio through your microphone."
+ auto_gain_control: "Automatic gain control"
+ auto_gain_control_hint: "Keeps your volume steady by adjusting the microphone level automatically."
+ subtitles: "Show live subtitles"
+ subtitles_hint: "Generates captions for what others say, on your device — nothing is sent anywhere. Requires a GPU-capable browser and downloads a ~2.5 GB model once."
+ subtitles_failed: "Subtitles couldn't be started, so they were turned off."
+ test_output: "Test"
+ choose_output: "Choose output device"
+ quality: "Audio quality"
+ quality_hint: "Higher settings improve fidelity for good microphones at a small bandwidth cost. Standard is tuned for speech."
+ subtitles:
+ loading: "Preparing subtitles…"
+ downloading: "Downloading subtitles model… %{percent}%"
+ transcript:
+ start: "Record transcript"
+ stop: "Stop transcript recording"
+ indicator: "Transcribing"
+ indicator_tooltip:
+ one: "%{usernames} is transcribing"
+ other: "%{usernames} are transcribing"
+ indicator_tooltip_self: "You are transcribing"
+ transcriber_you: "You"
+ draft_topic: "Open transcript draft"
+ stop_and_open: "Stop recording and open draft"
+ draft_title: "Call transcript: %{room}"
+ unknown_speaker: "unknown speaker"
+ stage:
+ promoted_to_speaker: "You've been made a speaker."
+ demoted_to_listener: "You've been moved to listeners."
+ speakers: "Speakers"
+ listeners: "Listeners"
+ more_listeners: "+%{count} more"
+ make_speaker: "Make speaker"
+ move_to_listeners: "Move to listeners"
+ room_now_open: "This room is now open — you can speak."
+ raise_hand: "Raise hand"
+ lower_hand: "Lower hand"
+ hand_raised_toast: "%{username} raised their hand to speak."
+ request_dismissed: "Your request to speak was dismissed."
+ queue_title: "Requests to speak"
+ queue_empty: "No pending requests."
+ queue_position: "You're #%{position} in line."
+ approve_request: "Approve"
+ dismiss_request: "Dismiss"
+ dismiss_request_menu: "Dismiss request to speak"
+ participant:
+ spotlight: "Spotlight for me"
+ remove_spotlight: "Remove from spotlight"
+ menu_title: "Participant options"
+ volume: "Volume"
+ mute: "Mute"
+ unmute: "Unmute"
+ kick: "Kick from room"
+ flag: "Flag"
+ status_speaking: "Speaking"
+ status_muted: "Muted"
+ status_deafened: "Deafened"
+ status_screen_sharing: "Sharing screen"
+ status_video: "Camera on"
+ status_ptt: "Push to talk enabled"
+ status_hand_raised: "Wants to speak"
+ flagging:
+ notify_moderators_description: "This participant requires staff attention for a reason not listed above."
+ review:
+ flagged_in: "Flagged in"
+ reviewables:
+ actions:
+ agree_and_keep:
+ title: "Agree"
+ description: "Agree with the flag."
+ agree_and_suspend:
+ title: "Suspend user"
+ description: "Agree with the flag and suspend the user."
+ agree_and_silence:
+ title: "Silence user"
+ description: "Agree with the flag and silence the user."
+ disagree:
+ title: "Disagree"
+ description: "Disagree with the flag."
+ ignore:
+ title: "Ignore flag"
+ description: "Remove the flag from the queue without taking action."
+ room_info:
+ title: "Room Info"
+ status: "Status"
+ public: "Public"
+ private: "Private"
+ member_count: "Members"
+ max_participants: "Max participants"
+ members:
+ title: "Manage Members"
+ add: "Add member"
+ add_placeholder: "Enter username..."
+ add_button: "Add"
+ role: "Role"
+ moderator: "Moderator"
+ speaker: "Speaker"
+ participant: "Participant"
+ remove: "Remove"
+ creator: "Creator"
+ call:
+ button: "Call"
+ calling: "Calling %{username}…"
+ incoming_title: "Incoming call"
+ incoming_state: "is calling you…"
+ answer: "Answer"
+ decline: "Decline"
+ invite:
+ title: "Invite to %{room_name}"
+ menu: "Invite people"
+ search_label: "Invite by name"
+ search_placeholder: "Search users..."
+ send: "Send invite"
+ invite: "Invite"
+ invited: "Invited"
+ suggestions_title: "People you've shared this room with"
+ time_together: "%{duration} together recently"
+ link_label: "Or share an invite link"
+ copy: "Copy"
+ sent:
+ one: "Invite sent."
+ other: "%{count} invites sent."
+ skipped: "%{usernames} can't be invited because they don't have access to voice rooms."
+ memberships:
+ add_user: "Add participant"
+ remove_user: "Remove participant"
+ admin:
+ title: "Voice"
+ dashboard_title: "Dashboard"
+ recordings_title: "Recordings"
+ recordings:
+ description: "Call recordings produced by the LiveKit egress service. Files stay on the storage configured on the recording server; completed recordings link to that location when it is a URL."
+ room: "Room"
+ requested_by: "Requested by"
+ status: "Status"
+ started_at: "Started"
+ duration: "Duration"
+ file: "File"
+ download: "Download"
+ load_more: "Load more"
+ empty: "No recordings yet. Room moderators can record calls that run on the LiveKit media server."
+ status_recording: "Recording"
+ status_completed: "Completed"
+ status_failed: "Failed"
+ dashboard:
+ overview: "Overview"
+ total_sessions: "Total sessions"
+ unique_users: "Unique users"
+ avg_duration: "Avg. session duration"
+ top_rooms: "Top rooms"
+ room_name: "Room"
+ deleted_room: "(deleted room)"
+ deleted_user: "(deleted user)"
+ top_users: "Top users"
+ user: "User"
+ sessions: "Sessions"
+ total_time: "Total time"
+ no_data: "No voice activity in this period."
+ livekit:
+ title: "LiveKit media server"
+ refresh: "Refresh"
+ load_failed: "Could not load the LiveKit status. Try refreshing."
+ config_ok: "Configured — room policy: %{policy}"
+ config_missing: "Not configured — missing settings: %{settings}"
+ token_ok: "Access tokens can be signed with the configured key pair"
+ token_error: "Access token signing failed: %{error}"
+ server_ok:
+ one: "Server reachable in %{latency} ms — %{count} active room"
+ other: "Server reachable in %{latency} ms — %{count} active rooms"
+ server_error: "Server unreachable: %{error}"
+ probe_ok: "Last connectivity check passed"
+ probe_failed: "Last connectivity check failed"
+ probe_never: "No automatic connectivity check has run yet — one runs whenever a LiveKit setting is saved."
+ webhook_received: "Last webhook received"
+ webhook_never: "No webhooks received yet — optional, but they speed up presence cleanup after abrupt disconnects and recording delivery."
+ webhook_config_hint: "To enable webhooks, add this to the LiveKit server's configuration file (livekit.yaml) and restart it:"
+ rooms_title: "Live calls on LiveKit"
+ room: "Room"
+ discourse_participants: "In the roster"
+ livekit_participants: "Connected to LiveKit"
+ room_status: "Status"
+ in_sync: "In sync"
+ missing_on_livekit: "In the roster but not connected: %{users}"
+ missing_in_presence: "Connected but not in the roster: %{users}"
+ room_error: "Could not list participants: %{error}"
+ no_rooms: "No live calls are using LiveKit right now."
+ rooms_title: "Voice rooms"
+ create_room: "Add room"
+ edit: "Edit"
+ update: "Update"
+ create: "Create"
+ back: "Back"
+ no_rooms_yet: "No voice rooms configured yet."
+ room_created: "Room created successfully."
+ room_updated: "Room updated successfully."
+ destroy_room:
+ confirm: "Are you sure you want to delete '%{name}'?"
+ end_call:
+ title: "End live call"
+ confirm: "End the live call in '%{name}'? Everyone in the call will be disconnected."
+ room:
+ name: "Name"
+ name_placeholder: "Room name"
+ slug: "Slug"
+ slug_placeholder: "room-slug"
+ slug_help: "Used in the room's URL. Leave empty to generate one from the name."
+ description: "Description"
+ public: "Public"
+ public_help: "Public rooms are visible to all users."
+ manage_members: "Manage members"
+ room_type: "Room type"
+ max_participants: "Max participants"
+ max_participants_help: "Maximum participants allowed (2-50, or 2-200 for Stage rooms)."
+ video_enabled: "Video"
+ video_enabled_help: "Allow participants to share their camera and screen in this room."
+ video_enabled_stage_help: "Allow speakers and moderators to share their camera and screen in this room. Listeners can only watch."
+ livekit_enabled: "Use media server (SFU)"
+ livekit_enabled_help: "Route this room's calls through the site's LiveKit media server instead of the peer-to-peer mesh. A call already in progress is not affected — the room switches when its next call starts."
+ chat_channel: "Chat channel"
+ chat_channel_help: "Each session opens a thread here. Only channels with threading enabled are listed."
+ chat_channel_none: "No channels with threading enabled. Turn it on in a channel's settings first."
+ chat_idle_minutes: "New thread after idle (minutes)"
+ chat_idle_minutes_help: "Minutes of inactivity before the next message starts a fresh thread."
+ chat_thread_hint: "The first message someone sends starts the thread, titled after the room."
+ quality_section: "Quality"
+ max_quality_profile: "Maximum quality"
+ max_quality_profile_help: "Caps the voice, camera and screen share quality participants can pick in this room. Site default applies no room-level cap; site settings always apply."
+ quality_site_default: "Site default"
+ member_count: "Members"
+ creator: "Created by"
+ created_at: "Created"
+ notifications:
+ voice_invitation: "invited you to join %{room_name}"
+ voice_call: "is calling you"
+ titles:
+ voice_invitation: "Voice room invite"
+ voice_call: "Incoming voice call"
+ review:
+ types:
+ reviewable_voice_user:
+ title: "Flagged voice room participant"
diff --git a/plugins/voice/config/locales/client.tr_TR.yml b/plugins/voice/config/locales/client.tr_TR.yml
new file mode 100644
index 00000000000..1b33a8d0454
--- /dev/null
+++ b/plugins/voice/config/locales/client.tr_TR.yml
@@ -0,0 +1,402 @@
+tr_TR:
+ js:
+ voice:
+ sidebar:
+ title: "Sesli odalar"
+ create: "Oda oluştur"
+ empty: "Henüz sesli oda yok."
+ room:
+ join: "Sesli odaya katıl"
+ leave: "Odadan ayrıl"
+ info: "Oda bilgileri"
+ edit: "Odayı düzenle"
+ copy_link: "Bağlantıyı kopyala"
+ link_copied: "Bağlantı panoya kopyalandı"
+ menu_title: "Oda seçenekleri"
+ created: "Oda başarıyla oluşturuldu."
+ updated: "Oda başarıyla güncellendi."
+ save: "Kaydet"
+ connecting: "Diğer katılımcılara bağlanılıyor…"
+ disconnected: "Odadan ayrıldınız."
+ participants: "Dinleyiciler"
+ mic_on: "Mikrofonu kapat"
+ mic_off: "Mikrofonu aç"
+ noise_suppression_active: "Gürültü engelleme etkin"
+ connection_error: "WebRTC oturumu başlatılamadı. Tarayıcınızın mikrofon iznine sahip olduğundan emin olun."
+ deafen_on: "Sesi kapat"
+ deafen_off: "Sesi aç"
+ type_open: "Açık"
+ type_open_description: "Herkes konuşabilir"
+ type_stage: "Sahne"
+ type_stage_description: "Yalnızca konuşmacılar ve moderatörler mikrofonlarını açabilir"
+ type_stage_hint: "Katılımcılar dinleyici olarak katılır. Moderatörler dinleyicileri konuşmacı yapabilir."
+ listeners_cannot_unmute: "Bu odada yalnızca konuşmacılar mikrofonlarını açabilir."
+ open_page: "Tam oda görünümünü aç"
+ widget_mode: "Küçük pencere görünümü"
+ settings: "Arama ayarları"
+ more: "Diğer seçenekler"
+ audio_options: "Ses seçenekleri"
+ video_options: "Video seçenekleri"
+ layout: "Düzen"
+ recording_start: "Kaydı başlat"
+ recording_stop: "Kaydı durdur"
+ recording_confirm: "Bu görüşme kaydedilsin mi? Tüm katılımcılar kayıt göstergesini görecektir."
+ recording_stop_confirm: "Bu görüşmenin kaydı durdurulsun mu?"
+ recording_indicator: "Kaydediliyor"
+ recording_indicator_title: "Kaydı %{username} başlattı"
+ recording_started_toast: "Bu görüşme artık kaydediliyor."
+ recording_stopped_toast: "Kayıt durduruldu."
+ room_page:
+ empty: "Henüz kimse yok — sohbeti başlatmak için katılın."
+ widget:
+ title: "Etkin sesli oda: %{room}"
+ open_chat: "Oda sohbetini aç"
+ expand: "Görüşme penceresini genişlet"
+ hide: "Görüşme penceresini gizle"
+ show: "Görüşme penceresini göster"
+ overflow_tile:
+ one: "%{count} katılımcı daha göster"
+ other: "%{count} katılımcı daha göster"
+ overflow_count: "+%{count}"
+ chat:
+ title: "Sohbet"
+ open: "Sohbeti aç"
+ close: "Sohbeti kapat"
+ unavailable: "Sohbet şu anda kullanılamıyor."
+ empty_title: "Henüz mesaj yok"
+ empty_body: "Sohbeti başlatmak için bir mesaj gönderin."
+ composer_placeholder: "Odaya mesaj gönderin…"
+ send: "Gönder"
+ open_in_chat: "Sohbette aç"
+ back_to_voice_room: "Sesli odaya dön"
+ video:
+ camera_on: "Kamerayı aç"
+ camera_off: "Kamerayı kapat"
+ screen_share_start: "Ekranını paylaş"
+ screen_share_stop: "Ekran paylaşımını durdur"
+ publisher_limit: "Aynı anda yayınlanabilecek en yüksek video akışı sayısına ulaşıldı."
+ capture_failed: "Kameranız veya ekran paylaşımınız başlatılamadı. Tarayıcı izinlerinizi kontrol edin."
+ camera_switch_denied: "Kamera değiştirilemedi. Tarayıcınızın kamera izinlerini kontrol edin."
+ camera_switch_failed: "Bu kamera başlatılamadı. Başka bir uygulama tarafından kullanılıyor veya kullanılamıyor olabilir."
+ room_disabled: "Bu odada video kapatıldı."
+ fullscreen: "Tam ekran"
+ exit_fullscreen: "Tam ekrandan çık"
+ fullscreen_all: "Tüm videoları tam ekran göster"
+ layout: "Video düzeni"
+ layout_presentation: "Sunum düzeni"
+ layout_tiled: "Döşeme düzeni"
+ ptt:
+ enable: "Bas Konuş"
+ disable: "Bas Konuş'u kapat"
+ configure_key: "Bas Konuş tuşu: %{key}"
+ press_key: "Bir tuşa basın…"
+ reserved_key: "Bu tuş ayrılmıştır."
+ controlled_by_ptt: "Bas Konuş tarafından denetleniyor"
+ badge: "Bas Konuş: %{key}"
+ idle:
+ auto_muted: "Etkin olmadığınız için mikrofonunuz otomatik olarak kapatıldı."
+ click_to_unmute: "Mikrofonu açmak için tıklayın."
+ disconnected: "Etkin olmadığınız için %{room} odasından çıkarıldınız."
+ livekit:
+ browser_unsupported: "Tarayıcınız bu sitenin ses sunucusuna bağlanamıyor. Tarayıcınızı güncelleyin veya farklı bir tarayıcı kullanın."
+ connect_failed: "Ağınız ses sunucusuna ulaşamıyor. Bağlantınızı kontrol edin veya yöneticinizle iletişime geçin."
+ reconnect_failed: "Ses sunucusuyla bağlantı kesildiği için görüşmeden ayrıldınız. Yeniden bağlanmak için odaya tekrar katılın."
+ room_ended: "Bağlantınız kesikken görüşme sona erdi. Yeni bir görüşme başlatmak için yeniden katılın."
+ duplicate_tab: "Bu görüşme başka bir sekme veya pencerede devam ettiği için buradaki bağlantı kesildi."
+ mesh_privacy_warning:
+ title: "Bu odaya katılmadan önce"
+ body: "Bu oda katılımcıları doğrudan birbirine bağlar. Bu nedenle görüşme sırasında diğer katılımcılar IP adresinizi görebilir. Eşler arası görüşmeler bu şekilde çalışır ve genellikle zararsızdır; yine de yalnızca bunu kabul ediyorsanız katılın."
+ join: "Odaya katıl"
+ cancel: "Vazgeç"
+ dont_show_again: "Bunu bir daha gösterme"
+ status:
+ auto_update_on: "Durumu otomatik güncelle"
+ auto_update_off: "Durumu otomatik güncelle"
+ devices:
+ system_default: "Sistem varsayılanı"
+ unknown_device: "Aygıt %{index}"
+ quality:
+ standard: "Standart"
+ high: "Yüksek"
+ maximum: "En yüksek"
+ video_settings:
+ title: "Video ayarları"
+ camera: "Kamera"
+ background_blur: "Arka planımı bulanıklaştır"
+ blur_amount: "Bulanıklık düzeyi"
+ blur_failed: "Arka plan bulanıklaştırma başlatılamadığı için kapatıldı."
+ camera_error: "Kameranıza erişilemedi. Tarayıcı izinlerinizi kontrol edin."
+ not_supported: "Bu tarayıcı arka plan bulanıklaştırmayı desteklemiyor."
+ camera_quality: "Kamera kalitesi"
+ camera_quality_hint: "Yüksek ayarlar daha net video gönderir ancak özellikle birden çok izleyici varken daha fazla bant genişliği ve işlemci kullanır. En yüksek ayar, kaç kişinin izlediğine bakılmaksızın tam kaliteyi korur."
+ screen_quality: "Ekran paylaşımı kalitesi"
+ screen_quality_hint: "Yüksek ayarlar daha fazla bant genişliği kullanarak daha net ve akıcı ekran paylaşımı sağlar. En yüksek ayar, yüksek çözünürlüklü ekran paylaşan hızlı ve kararlı bağlantılar için uygundur."
+ screen_content: "Ekran paylaşımını şunun için iyileştir"
+ screen_content_text: "Metin netliği"
+ screen_content_motion: "Akıcı hareket"
+ screen_content_hint: "Metin seçeneği görüntüyü net tutarken kare hızının düşmesine izin verir; hareket seçeneği oynatmayı akıcı tutarken netliğin düşmesine izin verir."
+ voice_settings:
+ title: "Ses ayarları"
+ open: "Ses ayarları"
+ input_audio: "Giriş"
+ output_audio: "Çıkış"
+ audio_settings: "Ses ayarları"
+ input_device: "Giriş aygıtı"
+ output_device: "Çıkış aygıtı"
+ mic_test: "Mikrofon testi"
+ mic_test_hint: "Mikrofonunuza konuşun — çubuk giriş düzeyinizi gösterir."
+ mic_error: "Mikrofonunuza erişilemedi. Tarayıcı izinlerini ve aygıt seçimini kontrol edin."
+ input_sensitivity: "Giriş duyarlılığı"
+ input_sensitivity_hint: "Bu düzeyin altındaki ses iletilmez. Her zaman iletmek için sıfıra ayarlayın."
+ noise_suppression: "Gürültü engelleme"
+ noise_suppression_hint: "Mikrofonunuzdan gelen fan ve klavye tıklaması gibi sesleri süzer. Yapay zekâ ile gürültü engelleme daha güçlüdür ancak daha fazla kaynak kullanır."
+ noise_suppression_modes:
+ none: "Yok"
+ standard: "Standart"
+ ai_rnnoise: "Yapay zekâ — RNNoise (hafif)"
+ ai_dtln: "Yapay zekâ — DTLN (dengeli)"
+ ai_dfn3: "Yapay zekâ — DeepFilterNet (en iyi kalite)"
+ noise_suppression_failed: "Yapay zekâ ile gürültü engelleme çalıştırılamadığı için kapatıldı."
+ echo_cancellation: "Yankı engelleme"
+ echo_cancellation_hint: "Diğer kişilerin kendi seslerini mikrofonunuz üzerinden duymasını önler."
+ auto_gain_control: "Otomatik kazanç denetimi"
+ auto_gain_control_hint: "Mikrofon düzeyini otomatik ayarlayarak ses seviyenizi dengede tutar."
+ subtitles: "Canlı altyazıları göster"
+ subtitles_hint: "Diğer kişilerin söyledikleri için altyazıları aygıtınızda oluşturur; hiçbir veri dışarı gönderilmez. GPU destekli bir tarayıcı gerektirir ve yaklaşık 2,5 GB boyutundaki modeli bir kez indirir."
+ subtitles_failed: "Altyazılar başlatılamadığı için kapatıldı."
+ test_output: "Test et"
+ choose_output: "Çıkış aygıtını seç"
+ quality: "Ses kalitesi"
+ quality_hint: "Yüksek ayarlar, az miktarda ek bant genişliği karşılığında iyi mikrofonların ses kalitesini artırır. Standart ayar konuşma için iyileştirilmiştir."
+ subtitles:
+ loading: "Altyazılar hazırlanıyor…"
+ downloading: "Altyazı modeli indiriliyor… %{percent}%"
+ transcript:
+ start: "Döküm kaydını başlat"
+ stop: "Döküm kaydını durdur"
+ indicator: "Yazıya aktarılıyor"
+ indicator_title: "Bu görüşmenin dökümünü aygıtınıza kaydediyorsunuz."
+ indicator_title_other: "%{usernames} bu görüşmenin dökümünü kaydediyor."
+ draft_topic: "Döküm taslağını aç"
+ stop_and_open: "Kaydı durdur ve taslağı aç"
+ draft_title: "Görüşme dökümü: %{room}"
+ unknown_speaker: "bilinmeyen konuşmacı"
+ stage:
+ promoted_to_speaker: "Konuşmacı yapıldınız."
+ demoted_to_listener: "Dinleyicilere taşındınız."
+ speakers: "Konuşmacılar"
+ listeners: "Dinleyiciler"
+ more_listeners: "+%{count} kişi daha"
+ make_speaker: "Konuşmacı yap"
+ move_to_listeners: "Dinleyicilere taşı"
+ room_now_open: "Bu oda artık açık — konuşabilirsiniz."
+ raise_hand: "Söz iste"
+ lower_hand: "Söz isteğini geri çek"
+ hand_raised_toast: "%{username} konuşmak için söz istedi."
+ request_dismissed: "Konuşma isteğiniz reddedildi."
+ queue_title: "Konuşma istekleri"
+ queue_empty: "Bekleyen istek yok."
+ queue_position: "Sırada %{position}. kişisiniz."
+ approve_request: "Onayla"
+ dismiss_request: "Reddet"
+ dismiss_request_menu: "Konuşma isteğini reddet"
+ participant:
+ spotlight: "Benim için öne çıkar"
+ remove_spotlight: "Öne çıkarmayı kaldır"
+ menu_title: "Katılımcı seçenekleri"
+ volume: "Ses düzeyi"
+ mute: "Mikrofonu kapat"
+ unmute: "Mikrofonu aç"
+ kick: "Odadan çıkar"
+ flag: "Bildir"
+ status_speaking: "Konuşuyor"
+ status_muted: "Mikrofonu kapalı"
+ status_deafened: "Sesi kapalı"
+ status_screen_sharing: "Ekranını paylaşıyor"
+ status_video: "Kamerası açık"
+ status_ptt: "Bas Konuş etkin"
+ status_hand_raised: "Konuşmak istiyor"
+ flagging:
+ notify_moderators_description: "Bu katılımcı, yukarıda listelenmeyen bir nedenle yetkililerin ilgisini gerektiriyor."
+ review:
+ flagged_in: "Bildirildiği yer"
+ reviewables:
+ actions:
+ agree_and_keep:
+ title: "Kabul et"
+ description: "Bildirimi kabul et."
+ agree_and_suspend:
+ title: "Kullanıcıyı askıya al"
+ description: "Bildirimi kabul et ve kullanıcıyı askıya al."
+ agree_and_silence:
+ title: "Kullanıcıyı sustur"
+ description: "Bildirimi kabul et ve kullanıcıyı sustur."
+ disagree:
+ title: "Reddet"
+ description: "Bildirimi reddet."
+ ignore:
+ title: "Bildirimi yok say"
+ description: "İşlem yapmadan bildirimi kuyruktan kaldır."
+ room_info:
+ title: "Oda bilgileri"
+ status: "Durum"
+ public: "Herkese açık"
+ private: "Özel"
+ member_count: "Üyeler"
+ max_participants: "En fazla katılımcı"
+ members:
+ title: "Üyeleri yönet"
+ add: "Üye ekle"
+ add_placeholder: "Kullanıcı adını girin…"
+ add_button: "Ekle"
+ role: "Rol"
+ moderator: "Moderatör"
+ speaker: "Konuşmacı"
+ participant: "Katılımcı"
+ remove: "Kaldır"
+ creator: "Oluşturan"
+ call:
+ button: "Ara"
+ calling: "%{username} aranıyor…"
+ incoming_title: "Gelen arama"
+ incoming_state: "sizi arıyor…"
+ answer: "Yanıtla"
+ decline: "Reddet"
+ invite:
+ title: "%{room_name} odasına davet et"
+ menu: "Kişileri davet et"
+ search_label: "Ada göre davet et"
+ search_placeholder: "Kullanıcı ara…"
+ send: "Davet gönder"
+ invite: "Davet et"
+ invited: "Davet edildi"
+ suggestions_title: "Bu odayı daha önce paylaştığınız kişiler"
+ time_together: "Yakın zamanda %{duration} birlikte"
+ link_label: "Veya bir davet bağlantısı paylaşın"
+ copy: "Kopyala"
+ sent:
+ one: "Davet gönderildi."
+ other: "%{count} davet gönderildi."
+ skipped: "%{usernames}, sesli odalara erişimi olmadığı için davet edilemiyor."
+ memberships:
+ add_user: "Katılımcı ekle"
+ remove_user: "Katılımcıyı kaldır"
+ admin:
+ title: "Voice"
+ dashboard_title: "Kontrol paneli"
+ recordings_title: "Kayıtlar"
+ recordings:
+ description: "LiveKit Egress hizmeti tarafından oluşturulan görüşme kayıtları. Dosyalar kayıt sunucusunda yapılandırılan depolama alanında kalır; tamamlanan kayıt, konum bir URL ise oraya bağlantı verir."
+ room: "Oda"
+ requested_by: "İsteyen"
+ status: "Durum"
+ started_at: "Başlangıç"
+ duration: "Süre"
+ file: "Dosya"
+ download: "İndir"
+ load_more: "Daha fazla yükle"
+ empty: "Henüz kayıt yok. Oda moderatörleri LiveKit medya sunucusunda çalışan görüşmeleri kaydedebilir."
+ status_recording: "Kaydediliyor"
+ status_completed: "Tamamlandı"
+ status_failed: "Başarısız"
+ dashboard:
+ overview: "Genel bakış"
+ total_sessions: "Toplam oturum"
+ unique_users: "Benzersiz kullanıcı"
+ avg_duration: "Ortalama oturum süresi"
+ top_rooms: "En etkin odalar"
+ room_name: "Oda"
+ deleted_room: "(silinmiş oda)"
+ deleted_user: "(silinmiş kullanıcı)"
+ top_users: "En etkin kullanıcılar"
+ user: "Kullanıcı"
+ sessions: "Oturumlar"
+ total_time: "Toplam süre"
+ no_data: "Bu dönemde sesli etkinlik yok."
+ livekit:
+ title: "LiveKit medya sunucusu"
+ refresh: "Yenile"
+ load_failed: "LiveKit durumu yüklenemedi. Yenilemeyi deneyin."
+ config_ok: "Yapılandırıldı — oda ilkesi: %{policy}"
+ config_missing: "Yapılandırılmadı — eksik ayarlar: %{settings}"
+ token_ok: "Yapılandırılmış anahtar çiftiyle erişim belirteçleri imzalanabilir"
+ token_error: "Erişim belirteci imzalanamadı: %{error}"
+ server_ok:
+ one: "Sunucuya %{latency} ms içinde ulaşıldı — %{count} etkin oda"
+ other: "Sunucuya %{latency} ms içinde ulaşıldı — %{count} etkin oda"
+ server_error: "Sunucuya ulaşılamıyor: %{error}"
+ probe_ok: "Son bağlantı denetimi başarılı"
+ probe_failed: "Son bağlantı denetimi başarısız"
+ probe_never: "Henüz otomatik bağlantı denetimi yapılmadı — bir LiveKit ayarı her kaydedildiğinde denetim çalışır."
+ webhook_received: "Son alınan webhook"
+ webhook_never: "Henüz webhook alınmadı — isteğe bağlıdır ancak ani bağlantı kesintilerinden sonra katılımcı durumunun temizlenmesini ve kayıt teslimini hızlandırır."
+ webhook_config_hint: "Webhook'ları etkinleştirmek için bunu LiveKit sunucusunun yapılandırma dosyasına (livekit.yaml) ekleyip sunucuyu yeniden başlatın:"
+ rooms_title: "LiveKit üzerindeki canlı görüşmeler"
+ room: "Oda"
+ discourse_participants: "Katılımcı listesinde"
+ livekit_participants: "LiveKit'e bağlı"
+ room_status: "Durum"
+ in_sync: "Eşzamanlı"
+ missing_on_livekit: "Listede olup LiveKit'e bağlı olmayanlar: %{users}"
+ missing_in_presence: "LiveKit'e bağlı olup listede olmayanlar: %{users}"
+ room_error: "Katılımcılar listelenemedi: %{error}"
+ no_rooms: "Şu anda LiveKit kullanan canlı görüşme yok."
+ rooms_title: "Sesli odalar"
+ create_room: "Oda ekle"
+ edit: "Düzenle"
+ update: "Güncelle"
+ create: "Oluştur"
+ back: "Geri"
+ no_rooms_yet: "Henüz sesli oda yapılandırılmadı."
+ room_created: "Oda başarıyla oluşturuldu."
+ room_updated: "Oda başarıyla güncellendi."
+ destroy_room:
+ confirm: "'%{name}' odasını silmek istediğinizden emin misiniz?"
+ end_call:
+ title: "Canlı görüşmeyi sonlandır"
+ confirm: "'%{name}' odasındaki canlı görüşme sonlandırılsın mı? Görüşmedeki herkesin bağlantısı kesilecektir."
+ room:
+ name: "Ad"
+ name_placeholder: "Oda adı"
+ slug: "Kısa ad"
+ slug_placeholder: "oda-kisa-adi"
+ slug_help: "Odanın URL'sinde kullanılır. Addan otomatik oluşturmak için boş bırakın."
+ description: "Açıklama"
+ public: "Herkese açık"
+ public_help: "Herkese açık odaları tüm kullanıcılar görebilir."
+ manage_members: "Üyeleri yönet"
+ room_type: "Oda türü"
+ max_participants: "En fazla katılımcı"
+ max_participants_help: "İzin verilen en fazla katılımcı sayısı (2-50; Sahne odaları için 2-200)."
+ video_enabled: "Video"
+ video_enabled_help: "Katılımcıların bu odada kameralarını ve ekranlarını paylaşmasına izin ver."
+ video_enabled_stage_help: "Konuşmacıların ve moderatörlerin bu odada kameralarını ve ekranlarını paylaşmasına izin ver. Dinleyiciler yalnızca izleyebilir."
+ livekit_enabled: "Medya sunucusunu (SFU) kullan"
+ livekit_enabled_help: "Bu odadaki görüşmeleri eşler arası ağ yerine sitenin LiveKit medya sunucusu üzerinden yönlendirir. Devam eden bir görüşme etkilenmez; oda bir sonraki görüşme başladığında geçiş yapar."
+ chat_channel: "Sohbet kanalı"
+ chat_channel_help: "Her oturum burada bir konu açar. Yalnızca konu özelliği etkin kanallar listelenir."
+ chat_channel_none: "Konu özelliği etkin kanal yok. Önce bir kanalın ayarlarından etkinleştirin."
+ chat_idle_minutes: "Boşta kalınca yeni konu (dakika)"
+ chat_idle_minutes_help: "Bir sonraki mesajın yeni bir konu başlatması için geçmesi gereken etkinlik dışı dakika sayısı."
+ chat_thread_title_template: "Konu başlangıcı"
+ chat_thread_title_template_help: "Her oturumu açmak için sistem tarafından gönderilir ve konu başlığı olarak yeniden kullanılır. {room}, {time} ve {date} değişkenlerini destekler. Konuların ilk mesajdan başlaması için boş bırakın."
+ chat_thread_title_placeholder: "{room} odasında saat {time} ekip toplantısı"
+ chat_thread_title_preview: "Önizleme:"
+ chat_no_template_hint: "Başlangıç iletisi yok — bir kişinin gönderdiği ilk mesaj konuyu başlatır."
+ quality_section: "Kalite"
+ max_quality_profile: "En yüksek kalite"
+ max_quality_profile_help: "Katılımcıların bu odada seçebileceği ses, kamera ve ekran paylaşımı kalitesini sınırlar. Site varsayılanı oda düzeyinde sınır uygulamaz; site ayarları her zaman geçerlidir."
+ quality_site_default: "Site varsayılanı"
+ member_count: "Üyeler"
+ creator: "Oluşturan"
+ created_at: "Oluşturulma"
+ notifications:
+ voice_invitation: "sizi %{room_name} odasına katılmaya davet etti"
+ voice_call: "sizi arıyor"
+ titles:
+ voice_invitation: "Sesli oda daveti"
+ voice_call: "Gelen sesli arama"
+ review:
+ types:
+ reviewable_voice_user:
+ title: "Bildirilen sesli oda katılımcısı"
diff --git a/plugins/voice/config/locales/server.en.yml b/plugins/voice/config/locales/server.en.yml
new file mode 100644
index 00000000000..097ef57344d
--- /dev/null
+++ b/plugins/voice/config/locales/server.en.yml
@@ -0,0 +1,242 @@
+en:
+ site_settings:
+ voice_enabled: "Enable the voice rooms plugin."
+ voice_allowed_groups: "Groups that can access voice rooms."
+ voice_create_room_allowed_groups: "Groups that can create new voice rooms."
+ voice_direct_calls_allowed_groups: "Groups that can start a direct call with another user from their user card or profile. Empty disables direct calls. Callers also need to be in {{setting:voice_allowed_groups}}; anyone with voice room access can receive a call."
+ voice_max_rooms_per_user: "Maximum number of voice rooms a single user can own. Temporary rooms created automatically by other features do not count."
+ voice_max_invites_per_day: "Maximum number of voice room invite notifications a single user can send per day. Repeated invites to the same person in the same room don't notify again (and don't count) until a day has passed."
+ voice_ephemeral_room_ttl_minutes: "Minutes a temporary room (created automatically by another feature, such as a direct call) can sit empty before it is deleted. Rooms with people in them are never deleted."
+ voice_participant_ttl_seconds: "Seconds to keep active speaker presence in Redis before automatic cleanup. Client heartbeat refreshes every 10 seconds."
+ voice_max_room_participants: "Maximum number of people who can be in a voice room at the same time. A room's own participant limit can lower this, but never raise it."
+ voice_auto_status_enabled: "Automatically set user status when they join a voice room (e.g. '🎙️ In Watercooler'). Requires the 'enable user status' site setting."
+ voice_mesh_privacy_warning_enabled: "Warn users before they join a peer-to-peer voice room that other participants may be able to see their IP address, with an option to not show the warning again on that device. Calls hosted on a LiveKit server never show the warning."
+ voice_badges_enabled: "Enable voice chat badges. Grants badges for voice room milestones like time spent, rooms visited, and connections made."
+ voice_idle_threshold_minutes: "Minutes of inactivity before a voice room participant is marked as idle. Set to 0 to disable."
+ voice_afk_auto_mute_threshold_minutes: "Minutes of inactivity before a voice room participant is automatically muted. Set to 0 to disable."
+ voice_afk_disconnect_threshold_minutes: "Minutes of inactivity before a voice room participant is automatically disconnected. Set to 0 to disable."
+ voice_video_enabled: "Enable camera video and screen sharing in voice rooms. Rooms can individually opt out via their room settings."
+ voice_video_max_publishers: "Maximum number of participants who can share video or their screen at the same time in a room. On peer-to-peer rooms, higher values increase CPU and bandwidth load for everyone watching; on rooms using a LiveKit media server, they mainly increase load on that server."
+ voice_video_background_blur_enabled: "Allow participants to blur their camera background. Segmentation runs on the publisher's device via MediaPipe, which increases CPU/GPU load while their camera is on."
+ voice_subtitles_enabled: "Allow participants to turn on live subtitles for other people's speech. Transcription runs entirely on the viewer's device via an NVIDIA Parakeet speech-to-text model (~2.5 GB, downloaded on first use, WebGPU required); no audio leaves the browser."
+ voice_stt_model_base_url: "Optional base URL for a self-hosted mirror of the subtitles model. When blank, the model files are downloaded on first use from Discourse's HuggingFace repository (Discourse/parakeet-tdt-0.6b-v3-onnx). A mirror must serve the same four files under their original names, reachable by browsers with CORS allowed — see docs/subtitles-model-mirror.md in the plugin."
+ voice_max_voice_quality: "Highest microphone audio quality participants may choose in their voice settings. Standard is the browser's speech default (~32 kbps); high (~64 kbps) and maximum (~128 kbps) improve fidelity for good microphones at the cost of bandwidth."
+ voice_max_camera_quality: "Highest camera quality participants may choose in their video settings. Standard captures at 720p; high captures at 1080p; maximum additionally stops automatic quality reduction as viewer count grows on peer-to-peer rooms, which multiplies the sender's upload bandwidth and CPU use."
+ voice_max_screen_share_quality: "Highest screen share quality participants may choose in their video settings. Standard targets 15 fps at a modest bitrate; high allows 30 fps at a higher bitrate; maximum allows 60 fps at a very high bitrate ceiling, letting fast connections share high-resolution screens at full quality."
+ voice_chat_enabled: "Allow voice rooms to be linked to a chat channel. Each chat session opens a thread in that channel; messages are real chat messages, so participants can also follow along in the chat UI."
+ voice_stun_servers: "STUN server URIs (stun:host:port), separated by |, used by peer-to-peer voice rooms for NAT traversal. Can be left empty when {{setting:voice_turn_secret_servers}} is configured — clients then discover their public address through the TURN server itself."
+ voice_turn_servers: "TURN server URIs (turn:host:port or turns:host:port), separated by |, used to relay voice traffic when a direct connection cannot be established. Authenticated with {{setting:voice_turn_username}} and {{setting:voice_turn_credential}}; for servers supporting short-lived credentials, use {{setting:voice_turn_secret_servers}} instead."
+ voice_turn_username: "Static username for the TURN servers in {{setting:voice_turn_servers}}."
+ voice_turn_credential: "Static password for the TURN servers in {{setting:voice_turn_servers}}."
+ voice_turn_secret: "Shared secret used to mint short-lived TURN credentials for the servers in {{setting:voice_turn_secret_servers}} (TURN REST API, coturn's use-auth-secret mode). Must match the secret configured on those TURN servers."
+ voice_turn_secret_servers: "TURN server URIs (turn:host:port or turns:host:port), separated by |, that authenticate with short-lived per-user credentials derived from {{setting:voice_turn_secret}} instead of a static username and password, so credentials cannot be reused by third parties."
+ voice_livekit_url: "WebSocket URL (wss://, or ws:// outside production) of a self-hosted LiveKit server. Together with the API key and secret, lets voice rooms use it as their media server (SFU) instead of the peer-to-peer mesh. The server must be reachable at a public address."
+ voice_livekit_api_key: "API key of the LiveKit server."
+ voice_livekit_api_secret: "API secret of the LiveKit server, used to sign short-lived room access tokens."
+ voice_livekit_room_policy: "Which rooms use the LiveKit media server instead of the peer-to-peer mesh. Changes never affect calls already in progress — each room switches when its next call starts."
+ voice_livekit_room_prefix: "Namespace prefix for room names on the LiveKit server. Leave empty to use the site's database name."
+ voice_livekit_mesh_fallback: "When a LiveKit access token cannot be issued and the room is empty, start the call on the peer-to-peer mesh instead of failing the join. Off by default because silent degradation can hide a LiveKit outage."
+ voice_livekit_recording_enabled: "Allow room moderators to record calls that run on the LiveKit media server. Recordings are produced by LiveKit's Egress service and stored wherever that deployment is configured to write (S3, GCS, local disk) — they are not uploaded to this site."
+ voice_livekit_recording_filepath: "Filepath passed to LiveKit Egress for recordings. Supports LiveKit's template placeholders such as {room_name}, {room_id}, {time} and {utc}; the file extension is added automatically."
+ errors:
+ voice_turn_secret_servers_requires_secret: "Set voice_turn_secret before adding TURN servers that use short-lived credentials."
+ voice_livekit_policy_requires_url: "Set voice_livekit_url to a valid wss:// URL before enabling a LiveKit room policy."
+ voice_livekit_url_invalid: "The LiveKit URL must be a ws:// or wss:// URL with a hostname and no embedded credentials."
+ voice_livekit_url_requires_wss: "The LiveKit URL must use wss:// in production."
+ voice_livekit_policy_requires_api_key: "Set voice_livekit_api_key before enabling a LiveKit room policy."
+ voice_livekit_policy_requires_api_secret: "Set voice_livekit_api_secret before enabling a LiveKit room policy."
+ voice:
+ defaults:
+ watercooler_description: "Join for casual drop-in voice chats with other community members."
+ chat:
+ default_thread_title: "Voice chat in %{room}"
+ default_thread_opener: "In %{room} - %{message}"
+ user_status:
+ in_room: "In %{room_name}"
+ in_private_room: "In a voice room"
+ afk_in_room: "AFK in %{room_name}"
+ afk_in_private_room: "AFK in a voice room"
+ errors:
+ not_enabled: "Voice rooms are disabled."
+ not_authorized: "You are not allowed to perform that action for this room."
+ room_limit: "You reached the maximum number of rooms you can create."
+ missing_payload: "Signal payload is required."
+ participant_session_required: "Your call session has expired. Rejoin the room to start a new one."
+ room_full: "This room is full."
+ invalid_signal: "The signal payload is malformed or exceeds the allowed size."
+ state_change_required: "A state change is required."
+ ephemeral_room_limit: "You have too many ongoing calls. End one before starting another."
+ cannot_call_user: "Sorry, you cannot call that user."
+ cannot_kick_self: "You cannot kick yourself from the room."
+ cannot_kick_creator: "You cannot kick the room creator."
+ listeners_cannot_unmute: "Listeners cannot unmute in a Stage room."
+ video_not_allowed: "Video is not enabled in this room."
+ video_publisher_limit: "The maximum number of simultaneous video streams for this room has been reached."
+ chat_unavailable: "Chat is not available for this room."
+ chat_requires_presence: "Join the voice room to use its chat."
+ flag_target_never_joined: "That user has not joined this room."
+ flag_already_handled: "Thanks, we have already been notified about this user and are looking into it."
+ chat_threading_disabled: "The linked chat channel no longer has threading enabled, so a chat session can't be started."
+ livekit_unavailable: "The voice server is unavailable. Contact your site administrator."
+ livekit_room_instance_ended: "This call has ended. Rejoin the room to start a new one."
+ livekit_no_signaling: "This room's call uses a media server; peer-to-peer signaling is disabled."
+ recording_unavailable: "Recording is not available for this call."
+ recording_already_active: "This call is already being recorded."
+ recording_not_active: "This call is not being recorded."
+ recording_failed: "The recording could not be started. Contact your site administrator."
+ recording_stop_failed: "The recording could not be stopped. Please try again."
+ reviewable_score_types:
+ notify_moderators:
+ pm_title: "A voice room participant requires staff attention"
+ pm_body: "@%{username} in the voice room [%{room_name}](%{link}) requires staff attention:\n\n%{message}"
+ reviewables:
+ actions:
+ agree_and_keep:
+ title: "Agree"
+ description: "Agree with the flag."
+ agree_and_suspend:
+ title: "Suspend user"
+ description: "Agree with the flag and suspend the user."
+ agree_and_silence:
+ title: "Silence user"
+ description: "Agree with the flag and silence the user."
+ disagree:
+ title: "Disagree"
+ description: "Disagree with the flag."
+ ignore:
+ title: "Ignore flag"
+ description: "Remove the flag from the queue without taking action."
+ invite_notification:
+ title: "%{username} invited you to %{room_name}"
+ excerpt: "Join the voice room %{room_name}"
+ call_notification:
+ title: "%{username} is calling you"
+ excerpt: "Join %{room_name} to answer"
+ call:
+ room_name: "📞 %{caller} + %{callee}"
+ recording_ready_pm:
+ title: "Your recording of %{room_name} is ready"
+ body_with_link: |
+ Your recording of the voice room **%{room_name}** (%{duration}) is ready:
+
+ [Download the recording](%{link})
+
+ Anyone with this link can access the recording — share it carefully.
+ body_with_path: |
+ Your recording of the voice room **%{room_name}** (%{duration}) has finished.
+
+ It is stored on the recording server at:
+
+ `%{filepath}`
+
+ Ask your site administrator for access.
+ unknown_duration: "unknown duration"
+ badges:
+ mic_check:
+ name: "Mic Check"
+ description: "Completed your first voice chat session."
+ long_description: "Awarded after spending at least 30 seconds in a voice room with another person."
+ rookie:
+ name: "Rookie"
+ description: "Spent 1 hour in voice chat."
+ long_description: "Awarded for accumulating 1 hour of total voice time."
+ chatterbox:
+ name: "Chatterbox"
+ description: "Spent 10 hours in voice chat."
+ long_description: "Awarded for accumulating 10 hours of total voice time."
+ silver_tongue:
+ name: "Silver Tongue"
+ description: "Spent 100 hours in voice chat."
+ long_description: "Awarded for accumulating 100 hours of total voice time."
+ icebreaker:
+ name: "Icebreaker"
+ description: "Joined a room full of strangers."
+ long_description: "Awarded for joining a voice room where you had no prior co-presence history with anyone."
+ social_butterfly:
+ name: "Social Butterfly"
+ description: "Chatted with 10 different people."
+ long_description: "Awarded for achieving co-presence with 10 or more distinct users."
+ life_of_the_party:
+ name: "Life of the Party"
+ description: "Chatted with 50 different people."
+ long_description: "Awarded for achieving co-presence with 50 or more distinct users."
+ familiar_face:
+ name: "Familiar Face"
+ description: "Spent 2 hours chatting with the same person."
+ long_description: "Awarded for achieving co-presence with one specific user for 2 or more hours total."
+ inner_circle:
+ name: "Inner Circle"
+ description: "Spent 10 hours chatting with the same person."
+ long_description: "Awarded for achieving co-presence with one specific user for 10 or more hours total."
+ partners_in_crime:
+ name: "Partners in Crime"
+ description: "Spent 50 hours chatting with the same person."
+ long_description: "Awarded for achieving co-presence with one specific user for 50 or more hours total."
+ explorer:
+ name: "Explorer"
+ description: "Joined 5 different voice rooms."
+ long_description: "Awarded for joining 5 different voice rooms."
+ nomad:
+ name: "Nomad"
+ description: "Joined 20 different voice rooms."
+ long_description: "Awarded for joining 20 different voice rooms."
+ omnipresent:
+ name: "Omnipresent"
+ description: "Joined 50 different voice rooms."
+ long_description: "Awarded for joining 50 different voice rooms."
+ patron:
+ name: "Patron"
+ description: "Visited the same room on 10 different days."
+ long_description: "Awarded for joining the same voice room on 10 distinct days."
+ barfly:
+ name: "Barfly"
+ description: "Visited the same room on 30 different days."
+ long_description: "Awarded for joining the same voice room on 30 distinct days."
+ the_mayor:
+ name: "The Mayor"
+ description: "Visited the same room on 100 different days."
+ long_description: "Awarded for joining the same voice room on 100 distinct days."
+ host:
+ name: "Host"
+ description: "Created your first voice room."
+ long_description: "Awarded for creating your first voice room."
+ crowd_puller:
+ name: "Crowd Puller"
+ description: "A room you created reached 50 total joins."
+ long_description: "Awarded when a voice room you created accumulates 50 or more total joins."
+ master_of_ceremonies:
+ name: "Master of Ceremonies"
+ description: "A room you created reached 500 total joins."
+ long_description: "Awarded when a voice room you created accumulates 500 or more total joins."
+ plus_one:
+ name: "Plus One"
+ description: "Someone joined a voice room through your invite."
+ long_description: "Awarded the first time a person you invited joins a voice room through your invite."
+ connector:
+ name: "Connector"
+ description: "10 people joined voice rooms through your invites."
+ long_description: "Awarded when 10 different people join voice rooms through your invites."
+ people_magnet:
+ name: "People Magnet"
+ description: "50 people joined voice rooms through your invites."
+ long_description: "Awarded when 50 different people join voice rooms through your invites."
+ night_owl:
+ name: "Night Owl"
+ description: "Chatted between midnight and 5 AM."
+ long_description: "Awarded for participating in a voice session between midnight and 5 AM in your local timezone."
+ early_bird:
+ name: "Early Bird"
+ description: "Chatted between 5 AM and 9 AM."
+ long_description: "Awarded for participating in a voice session between 5 AM and 9 AM in your local timezone."
+ packed_house:
+ name: "Packed House"
+ description: "Was in a room when it hit max capacity."
+ long_description: "Awarded for being in a voice room at the exact moment it reaches maximum capacity."
+ weekend_warrior:
+ name: "Weekend Warrior"
+ description: "Spent 5 hours chatting on weekends."
+ long_description: "Awarded for accumulating 5 or more hours of voice chat on weekends."
+ marathoner:
+ name: "Marathoner"
+ description: "Stayed in a single voice session for 4 hours."
+ long_description: "Awarded for staying in a single continuous voice session for 4 or more hours."
diff --git a/plugins/voice/config/locales/server.tr_TR.yml b/plugins/voice/config/locales/server.tr_TR.yml
new file mode 100644
index 00000000000..fe69a957aec
--- /dev/null
+++ b/plugins/voice/config/locales/server.tr_TR.yml
@@ -0,0 +1,233 @@
+tr_TR:
+ site_settings:
+ voice_enabled: "Voice sesli odalar eklentisini etkinleştir."
+ voice_allowed_groups: "Sesli odalara erişebilen gruplar."
+ voice_create_room_allowed_groups: "Yeni sesli oda oluşturabilen gruplar."
+ voice_direct_calls_allowed_groups: "Kullanıcı kartından veya profilinden başka bir kullanıcıyı doğrudan arayabilen gruplar. Boş bırakılırsa doğrudan aramalar kapatılır. Arayanların ayrıca {{setting:voice_allowed_groups}} içinde olması gerekir; sesli oda erişimi olan herkes arama alabilir."
+ voice_max_rooms_per_user: "Bir kullanıcının sahip olabileceği en fazla sesli oda sayısı. Diğer özellikler tarafından otomatik oluşturulan geçici odalar bu sınıra dahil değildir."
+ voice_max_invites_per_day: "Bir kullanıcının günde gönderebileceği en fazla sesli oda daveti bildirimi. Aynı odada aynı kişiye yinelenen davetler, bir gün geçene kadar yeniden bildirim göndermez ve sınıra dahil edilmez."
+ voice_ephemeral_room_ttl_minutes: "Başka bir özellik (örneğin doğrudan arama) tarafından otomatik oluşturulan geçici bir odanın silinmeden önce boş kalabileceği dakika sayısı. İçinde kişi bulunan odalar silinmez."
+ voice_participant_ttl_seconds: "Etkin konuşmacı durumunun otomatik temizlenmeden önce Redis'te tutulacağı saniye sayısı. İstemci yaşam sinyali her 10 saniyede yenilenir."
+ voice_auto_status_enabled: "Kullanıcı sesli odaya katıldığında durumunu otomatik ayarla (ör. '🎙️ Sohbet Odasında'). 'Kullanıcı durumunu etkinleştir' site ayarının açık olması gerekir."
+ voice_mesh_privacy_warning_enabled: "Kullanıcıları eşler arası sesli odaya katılmadan önce diğer katılımcıların IP adreslerini görebileceği konusunda uyar ve bu aygıtta uyarıyı bir daha göstermeme seçeneği sun. LiveKit sunucusunda barındırılan görüşmelerde uyarı gösterilmez."
+ voice_badges_enabled: "Sesli sohbet rozetlerini etkinleştir. Sesli odalarda geçirilen süre, ziyaret edilen odalar ve kurulan bağlantılar gibi dönüm noktaları için rozet verir."
+ voice_idle_threshold_minutes: "Sesli oda katılımcısının boşta olarak işaretlenmesi için geçmesi gereken etkinlik dışı dakika sayısı. Kapatmak için 0 yapın."
+ voice_afk_auto_mute_threshold_minutes: "Sesli oda katılımcısının mikrofonunun otomatik kapatılması için geçmesi gereken etkinlik dışı dakika sayısı. Kapatmak için 0 yapın."
+ voice_afk_disconnect_threshold_minutes: "Sesli oda katılımcısının bağlantısının otomatik kesilmesi için geçmesi gereken etkinlik dışı dakika sayısı. Kapatmak için 0 yapın."
+ voice_video_enabled: "Sesli odalarda kamera videosunu ve ekran paylaşımını etkinleştir. Her oda kendi ayarlarından bunları kapatabilir."
+ voice_video_max_publishers: "Bir odada aynı anda video veya ekran paylaşabilen en fazla katılımcı sayısı. Eşler arası odalarda yüksek değerler tüm izleyicilerin işlemci ve bant genişliği yükünü artırır; LiveKit medya sunucusu kullanan odalarda ise ağırlıklı olarak sunucu yükünü artırır."
+ voice_video_background_blur_enabled: "Katılımcıların kamera arka planını bulanıklaştırmasına izin ver. Bölümleme, yayıncının aygıtında MediaPipe ile çalışır ve kamera açıkken işlemci/GPU yükünü artırır."
+ voice_subtitles_enabled: "Katılımcıların diğer kişilerin konuşmaları için canlı altyazıları açmasına izin ver. Yazıya aktarma tamamen izleyicinin aygıtında NVIDIA Parakeet konuşmadan metne modeliyle çalışır (yaklaşık 2,5 GB, ilk kullanımda indirilir, WebGPU gerekir); ses tarayıcıdan dışarı çıkmaz."
+ voice_stt_model_base_url: "Altyazı modelinin kendi sunucunuzda barındırılan yansısı için isteğe bağlı temel URL. Boşken model dosyaları ilk kullanımda Discourse'un HuggingFace deposundan (Discourse/parakeet-tdt-0.6b-v3-onnx) indirilir. Yansı, özgün adlarıyla aynı dört dosyayı tarayıcıların CORS izniyle erişebileceği şekilde sunmalıdır; eklentideki docs/subtitles-model-mirror.md belgesine bakın."
+ voice_max_voice_quality: "Katılımcıların ses ayarlarında seçebileceği en yüksek mikrofon ses kalitesi. Standart, tarayıcının konuşma varsayılanıdır (yaklaşık 32 kbps); yüksek (yaklaşık 64 kbps) ve en yüksek (yaklaşık 128 kbps), bant genişliği karşılığında iyi mikrofonların ses kalitesini artırır."
+ voice_max_camera_quality: "Katılımcıların video ayarlarında seçebileceği en yüksek kamera kalitesi. Standart 720p, yüksek 1080p görüntü yakalar; en yüksek ise eşler arası odalarda izleyici sayısı arttıkça otomatik kalite düşürmeyi de durdurur ve göndericinin yükleme bant genişliği ile işlemci kullanımını katlar."
+ voice_max_screen_share_quality: "Katılımcıların video ayarlarında seçebileceği en yüksek ekran paylaşımı kalitesi. Standart makul bit hızında 15 fps, yüksek daha yüksek bit hızında 30 fps, en yüksek ise çok yüksek bit hızı sınırıyla 60 fps hedefler ve hızlı bağlantıların yüksek çözünürlüklü ekranları tam kalitede paylaşmasını sağlar."
+ voice_chat_enabled: "Sesli odaların bir sohbet kanalına bağlanmasına izin ver. Her sohbet oturumu o kanalda bir konu açar; iletiler gerçek sohbet iletileridir ve katılımcılar sohbet arayüzünden de takip edebilir."
+ voice_stun_servers: "Eşler arası sesli odalarda NAT geçişi için kullanılan ve | ile ayrılan STUN sunucusu URI'leri (stun:ana_makine:port). {{setting:voice_turn_secret_servers}} yapılandırıldığında boş bırakılabilir; istemciler genel adreslerini TURN sunucusunun kendisi üzerinden bulur."
+ voice_turn_servers: "Doğrudan bağlantı kurulamadığında ses trafiğini aktarmak için kullanılan ve | ile ayrılan TURN sunucusu URI'leri (turn:ana_makine:port veya turns:ana_makine:port). {{setting:voice_turn_username}} ve {{setting:voice_turn_credential}} ile kimlik doğrulanır; kısa ömürlü kimlik bilgilerini destekleyen sunucular için bunun yerine {{setting:voice_turn_secret_servers}} kullanın."
+ voice_turn_username: "{{setting:voice_turn_servers}} içindeki TURN sunucuları için sabit kullanıcı adı."
+ voice_turn_credential: "{{setting:voice_turn_servers}} içindeki TURN sunucuları için sabit parola."
+ voice_turn_secret: "{{setting:voice_turn_secret_servers}} içindeki sunucular için kısa ömürlü TURN kimlik bilgileri üretmekte kullanılan ortak gizli anahtar (TURN REST API, coturn use-auth-secret modu). Bu TURN sunucularında yapılandırılan gizli anahtarla aynı olmalıdır."
+ voice_turn_secret_servers: "Sabit kullanıcı adı ve parola yerine {{setting:voice_turn_secret}} üzerinden türetilen, kullanıcıya özel kısa ömürlü kimlik bilgileriyle doğrulama yapan ve | ile ayrılan TURN sunucusu URI'leri (turn:ana_makine:port veya turns:ana_makine:port). Böylece kimlik bilgileri üçüncü kişilerce yeniden kullanılamaz."
+ voice_livekit_url: "Kendi sunucunuzda barındırılan LiveKit sunucusunun WebSocket URL'si (ws:// veya wss://). API anahtarı ve gizli anahtarla birlikte sesli odaların eşler arası ağ yerine bu sunucuyu medya sunucusu (SFU) olarak kullanmasını sağlar."
+ voice_livekit_api_key: "LiveKit sunucusunun API anahtarı."
+ voice_livekit_api_secret: "Kısa ömürlü oda erişim belirteçlerini imzalamak için kullanılan LiveKit sunucusu API gizli anahtarı."
+ voice_livekit_room_policy: "Eşler arası ağ yerine LiveKit medya sunucusunu kullanacak odalar. Değişiklikler devam eden görüşmeleri etkilemez; her oda bir sonraki görüşme başladığında geçiş yapar."
+ voice_livekit_room_prefix: "LiveKit sunucusundaki oda adları için ad alanı ön eki. Sitenin veritabanı adını kullanmak için boş bırakın."
+ voice_livekit_mesh_fallback: "LiveKit erişim belirteci üretilemediğinde ve oda boşken katılımı başarısız kılmak yerine görüşmeyi eşler arası ağda başlat. Sessiz kalite düşüşü LiveKit kesintisini gizleyebileceği için varsayılan olarak kapalıdır."
+ voice_livekit_recording_enabled: "Oda moderatörlerinin LiveKit medya sunucusunda çalışan görüşmeleri kaydetmesine izin ver. Kayıtlar LiveKit Egress hizmeti tarafından oluşturulur ve kurulumun yazmak üzere yapılandırıldığı yerde (S3, GCS veya yerel disk) saklanır; bu siteye yüklenmez."
+ voice_livekit_recording_filepath: "Kayıtlar için LiveKit Egress'e gönderilen dosya yolu. {room_name}, {room_id}, {time} ve {utc} gibi LiveKit şablon değişkenlerini destekler; dosya uzantısı otomatik eklenir."
+ errors:
+ voice_turn_secret_servers_requires_secret: "Kısa ömürlü kimlik bilgileri kullanan TURN sunucularını eklemeden önce voice_turn_secret ayarını yapın."
+ voice_livekit_policy_requires_url: "Bir LiveKit oda ilkesini etkinleştirmeden önce voice_livekit_url ayarını ws:// veya wss:// URL'si olarak girin."
+ voice_livekit_policy_requires_api_key: "Bir LiveKit oda ilkesini etkinleştirmeden önce voice_livekit_api_key ayarını yapın."
+ voice_livekit_policy_requires_api_secret: "Bir LiveKit oda ilkesini etkinleştirmeden önce voice_livekit_api_secret ayarını yapın."
+ voice:
+ defaults:
+ watercooler_description: "Diğer topluluk üyeleriyle rahat ve anlık sesli sohbetler için katılın."
+ chat:
+ default_thread_title: "{room} odasında sesli sohbet"
+ user_status:
+ in_room: "%{room_name} odasında"
+ in_private_room: "Bir sesli odada"
+ afk_in_room: "%{room_name} odasında AFK"
+ afk_in_private_room: "Bir sesli odada AFK"
+ errors:
+ not_enabled: "Voice sesli odaları devre dışı."
+ not_authorized: "Bu oda için bu işlemi yapma izniniz yok."
+ room_limit: "Oluşturabileceğiniz en fazla oda sayısına ulaştınız."
+ missing_payload: "Sinyal verisi gereklidir."
+ cannot_call_user: "Üzgünüz, bu kullanıcıyı arayamazsınız."
+ cannot_kick_self: "Kendinizi odadan çıkaramazsınız."
+ cannot_kick_creator: "Odayı oluşturan kişiyi odadan çıkaramazsınız."
+ listeners_cannot_unmute: "Dinleyiciler Sahne odasında mikrofonlarını açamaz."
+ video_not_allowed: "Bu odada video etkin değil."
+ video_publisher_limit: "Bu odada aynı anda yayınlanabilecek en yüksek video akışı sayısına ulaşıldı."
+ chat_unavailable: "Bu oda için sohbet kullanılamıyor."
+ chat_requires_presence: "Sohbeti kullanmak için sesli odaya katılın."
+ flag_target_never_joined: "Bu kullanıcı odaya katılmadı."
+ flag_already_handled: "Teşekkürler, bu kullanıcı hakkında daha önce bilgilendirildik ve durumu inceliyoruz."
+ chat_threading_disabled: "Bağlı sohbet kanalında konu özelliği artık etkin değil, bu nedenle sohbet oturumu başlatılamıyor."
+ livekit_unavailable: "Ses sunucusu kullanılamıyor. Site yöneticinizle iletişime geçin."
+ livekit_room_instance_ended: "Bu görüşme sona erdi. Yeni bir görüşme başlatmak için odaya yeniden katılın."
+ livekit_no_signaling: "Bu odadaki görüşme bir medya sunucusu kullanıyor; eşler arası sinyalleşme devre dışı."
+ recording_unavailable: "Bu görüşmede kayıt kullanılamıyor."
+ recording_already_active: "Bu görüşme zaten kaydediliyor."
+ recording_not_active: "Bu görüşme kaydedilmiyor."
+ recording_failed: "Kayıt başlatılamadı. Site yöneticinizle iletişime geçin."
+ recording_stop_failed: "Kayıt durdurulamadı. Lütfen yeniden deneyin."
+ reviewable_score_types:
+ notify_moderators:
+ pm_title: "Bir sesli oda katılımcısı yetkililerin ilgisini gerektiriyor"
+ pm_body: "[%{room_name}](%{link}) sesli odasındaki @%{username} adlı kullanıcı yetkililerin ilgisini gerektiriyor:\n\n%{message}"
+ reviewables:
+ actions:
+ agree_and_keep:
+ title: "Kabul et"
+ description: "Bildirimi kabul et."
+ agree_and_suspend:
+ title: "Kullanıcıyı askıya al"
+ description: "Bildirimi kabul et ve kullanıcıyı askıya al."
+ agree_and_silence:
+ title: "Kullanıcıyı sustur"
+ description: "Bildirimi kabul et ve kullanıcıyı sustur."
+ disagree:
+ title: "Reddet"
+ description: "Bildirimi reddet."
+ ignore:
+ title: "Bildirimi yok say"
+ description: "İşlem yapmadan bildirimi kuyruktan kaldır."
+ invite_notification:
+ title: "%{username} sizi %{room_name} odasına davet etti"
+ excerpt: "%{room_name} sesli odasına katıl"
+ call_notification:
+ title: "%{username} sizi arıyor"
+ excerpt: "Yanıtlamak için %{room_name} odasına katıl"
+ call:
+ room_name: "📞 %{caller} + %{callee}"
+ recording_ready_pm:
+ title: "%{room_name} odasının kaydı hazır"
+ body_with_link: |
+ **%{room_name}** sesli odasının kaydı (%{duration}) hazır:
+
+ [Kaydı indir](%{link})
+
+ Bu bağlantıya sahip olan herkes kayda erişebilir; dikkatli paylaşın.
+ body_with_path: |
+ **%{room_name}** sesli odasının kaydı (%{duration}) tamamlandı.
+
+ Kayıt sunucusunda şu konumda saklanıyor:
+
+ `%{filepath}`
+
+ Erişim için site yöneticinize başvurun.
+ unknown_duration: "bilinmeyen süre"
+ badges:
+ mic_check:
+ name: "Mikrofon Kontrolü"
+ description: "İlk sesli sohbet oturumunu tamamladı."
+ long_description: "Başka bir kişiyle sesli odada en az 30 saniye geçirince verilir."
+ rookie:
+ name: "Çaylak"
+ description: "Sesli sohbette 1 saat geçirdi."
+ long_description: "Toplam 1 saat sesli sohbette geçirince verilir."
+ chatterbox:
+ name: "Geveze"
+ description: "Sesli sohbette 10 saat geçirdi."
+ long_description: "Toplam 10 saat sesli sohbette geçirince verilir."
+ silver_tongue:
+ name: "Gümüş Dil"
+ description: "Sesli sohbette 100 saat geçirdi."
+ long_description: "Toplam 100 saat sesli sohbette geçirince verilir."
+ icebreaker:
+ name: "Buzkıran"
+ description: "Yabancılarla dolu bir odaya katıldı."
+ long_description: "Daha önce birlikte bulunma geçmişi olmayan kişilerle dolu bir sesli odaya katılınca verilir."
+ social_butterfly:
+ name: "Sosyal Kelebek"
+ description: "10 farklı kişiyle sohbet etti."
+ long_description: "10 veya daha fazla farklı kullanıcıyla aynı anda sesli odada bulununca verilir."
+ life_of_the_party:
+ name: "Partinin Neşesi"
+ description: "50 farklı kişiyle sohbet etti."
+ long_description: "50 veya daha fazla farklı kullanıcıyla aynı anda sesli odada bulununca verilir."
+ familiar_face:
+ name: "Tanıdık Yüz"
+ description: "Aynı kişiyle 2 saat sohbet etti."
+ long_description: "Belirli bir kullanıcıyla toplam 2 saat veya daha uzun süre aynı anda sesli odada bulununca verilir."
+ inner_circle:
+ name: "Yakın Çevre"
+ description: "Aynı kişiyle 10 saat sohbet etti."
+ long_description: "Belirli bir kullanıcıyla toplam 10 saat veya daha uzun süre aynı anda sesli odada bulununca verilir."
+ partners_in_crime:
+ name: "Suç Ortakları"
+ description: "Aynı kişiyle 50 saat sohbet etti."
+ long_description: "Belirli bir kullanıcıyla toplam 50 saat veya daha uzun süre aynı anda sesli odada bulununca verilir."
+ explorer:
+ name: "Kâşif"
+ description: "5 farklı sesli odaya katıldı."
+ long_description: "5 farklı sesli odaya katılınca verilir."
+ nomad:
+ name: "Göçebe"
+ description: "20 farklı sesli odaya katıldı."
+ long_description: "20 farklı sesli odaya katılınca verilir."
+ omnipresent:
+ name: "Her Yerde"
+ description: "50 farklı sesli odaya katıldı."
+ long_description: "50 farklı sesli odaya katılınca verilir."
+ patron:
+ name: "Müdavim"
+ description: "Aynı odayı 10 farklı günde ziyaret etti."
+ long_description: "Aynı sesli odaya 10 farklı günde katılınca verilir."
+ barfly:
+ name: "Gedikli"
+ description: "Aynı odayı 30 farklı günde ziyaret etti."
+ long_description: "Aynı sesli odaya 30 farklı günde katılınca verilir."
+ the_mayor:
+ name: "Belediye Başkanı"
+ description: "Aynı odayı 100 farklı günde ziyaret etti."
+ long_description: "Aynı sesli odaya 100 farklı günde katılınca verilir."
+ host:
+ name: "Ev Sahibi"
+ description: "İlk sesli odasını oluşturdu."
+ long_description: "İlk sesli odayı oluşturunca verilir."
+ crowd_puller:
+ name: "Kalabalık Toplayan"
+ description: "Oluşturduğu bir oda toplam 50 katılıma ulaştı."
+ long_description: "Oluşturduğunuz bir sesli oda toplam 50 veya daha fazla katılıma ulaşınca verilir."
+ master_of_ceremonies:
+ name: "Tören Ustası"
+ description: "Oluşturduğu bir oda toplam 500 katılıma ulaştı."
+ long_description: "Oluşturduğunuz bir sesli oda toplam 500 veya daha fazla katılıma ulaşınca verilir."
+ plus_one:
+ name: "Artı Bir"
+ description: "Bir kişi davetiyle sesli odaya katıldı."
+ long_description: "Davet ettiğiniz bir kişi ilk kez davetiniz üzerinden sesli odaya katılınca verilir."
+ connector:
+ name: "Bağ Kurucu"
+ description: "10 kişi davetleriyle sesli odalara katıldı."
+ long_description: "10 farklı kişi davetleriniz üzerinden sesli odalara katılınca verilir."
+ people_magnet:
+ name: "İnsan Mıknatısı"
+ description: "50 kişi davetleriyle sesli odalara katıldı."
+ long_description: "50 farklı kişi davetleriniz üzerinden sesli odalara katılınca verilir."
+ night_owl:
+ name: "Gece Kuşu"
+ description: "Gece yarısı ile 05.00 arasında sohbet etti."
+ long_description: "Yerel saat diliminizde gece yarısı ile 05.00 arasında bir sesli oturuma katılınca verilir."
+ early_bird:
+ name: "Erkenci Kuş"
+ description: "05.00 ile 09.00 arasında sohbet etti."
+ long_description: "Yerel saat diliminizde 05.00 ile 09.00 arasında bir sesli oturuma katılınca verilir."
+ packed_house:
+ name: "Tıklım Tıklım"
+ description: "Bir oda tam kapasiteye ulaştığında oradaydı."
+ long_description: "Bir sesli odanın en yüksek kapasiteye ulaştığı anda odada bulununca verilir."
+ weekend_warrior:
+ name: "Hafta Sonu Savaşçısı"
+ description: "Hafta sonları 5 saat sohbet etti."
+ long_description: "Hafta sonlarında toplam 5 saat veya daha uzun süre sesli sohbette geçirince verilir."
+ marathoner:
+ name: "Maratoncu"
+ description: "Tek bir sesli oturumda 4 saat kaldı."
+ long_description: "Kesintisiz tek bir sesli oturumda 4 saat veya daha uzun süre kalınca verilir."
diff --git a/plugins/voice/config/routes.rb b/plugins/voice/config/routes.rb
new file mode 100644
index 00000000000..2cbabbc082c
--- /dev/null
+++ b/plugins/voice/config/routes.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+Voice::Engine.routes.draw do
+ resources :rooms do
+ member do
+ post :join
+ post :heartbeat
+ delete :leave
+ get :participants
+ post :signal
+ get :chat_session
+ post :chat_session, action: :ensure_chat_session, as: :ensure_chat_session
+ post :chat_message
+ post :toggle_mute
+ post :state
+ post :livekit_token
+ post :recording, action: :start_recording, as: :start_recording
+ delete :recording, action: :stop_recording, as: :stop_recording
+ delete :kick
+ post :flag
+ post :request_to_speak
+ delete :request_to_speak, action: :withdraw_request_to_speak, as: :withdraw_request_to_speak
+ end
+
+ resources :memberships, controller: "room_memberships", only: %i[index create update destroy]
+
+ resources :invites, only: %i[create] do
+ collection { get :suggestions }
+ end
+ end
+
+ resources :calls, only: %i[create]
+
+ # LiveKit server webhooks — machine-to-machine, authenticated by the
+ # signature on the request body, not by a user session.
+ post "livekit/webhook" => "livekit_webhooks#create"
+
+ get "contacts" => "contacts#index"
+ get "chat_threads/:id" => "chat_threads#show", :constraints => { id: /\d+/ }
+ get "r/:slug" => "page#show", :format => false
+ get "r/:slug/invited-by/:username" => "page#show", :format => false
+end
+
+Discourse::Application.routes.draw do
+ scope "/admin/plugins/voice", constraints: AdminConstraint.new do
+ scope format: false do
+ get "/voice-rooms" => "voice/admin#index"
+ get "/voice-rooms/new" => "voice/admin#new"
+ get "/voice-rooms/:id" => "voice/admin#edit"
+ get "/voice-dashboard" => "voice/admin#index"
+ get "/voice-recordings" => "voice/admin#index"
+ end
+
+ scope format: :json do
+ get "/rooms" => "voice/admin_rooms#index"
+ get "/rooms/:id" => "voice/admin_rooms#show"
+ post "/rooms" => "voice/admin_rooms#create"
+ put "/rooms/:id" => "voice/admin_rooms#update"
+ delete "/rooms/:id" => "voice/admin_rooms#destroy"
+ post "/rooms/:id/end_call" => "voice/admin_rooms#end_call"
+
+ get "/stats/overview" => "voice/admin_stats#overview"
+ get "/stats/rooms" => "voice/admin_stats#rooms"
+ get "/stats/users" => "voice/admin_stats#users"
+
+ get "/livekit/status" => "voice/admin_livekit#status"
+ post "/livekit/probe" => "voice/admin_livekit#probe"
+
+ get "/recordings" => "voice/admin_recordings#index"
+ end
+ end
+end
diff --git a/plugins/voice/config/settings.yml b/plugins/voice/config/settings.yml
new file mode 100644
index 00000000000..c6d185699e8
--- /dev/null
+++ b/plugins/voice/config/settings.yml
@@ -0,0 +1,155 @@
+plugins:
+ voice_enabled:
+ default: false
+ client: true
+ voice_allowed_groups:
+ type: group_list
+ list_type: compact
+ default: "4|5" # auto groups anonymous_users, logged_in_users
+ allow_any: false
+ refresh: true
+ disallowed_groups: "0"
+ voice_create_room_allowed_groups:
+ type: group_list
+ list_type: compact
+ default: "1|2|12" # auto groups admins, moderators, trust_level_2
+ allow_any: false
+ refresh: true
+ mandatory_values: "1" # auto group admins
+ disallowed_groups: "0|4"
+ voice_direct_calls_allowed_groups:
+ type: group_list
+ list_type: compact
+ default: ""
+ allow_any: false
+ refresh: true
+ disallowed_groups: "0|4"
+ voice_max_rooms_per_user:
+ default: 5
+ voice_max_invites_per_day:
+ default: 100
+ min: 1
+ max: 5000
+ voice_ephemeral_room_ttl_minutes:
+ default: 30
+ min: 5
+ max: 10080
+ voice_participant_ttl_seconds:
+ default: 30
+ voice_max_room_participants:
+ default: 50
+ min: 2
+ max: 200
+ voice_stun_servers:
+ default: "stun:stun.l.google.com:19302|stun:global.stun.twilio.com:3478"
+ voice_turn_servers:
+ default: ""
+ voice_turn_username:
+ default: ""
+ voice_turn_credential:
+ default: ""
+ secret: true
+ voice_turn_secret:
+ default: ""
+ secret: true
+ voice_turn_secret_servers:
+ default: ""
+ validator: "VoiceTurnSecretServersValidator"
+ voice_livekit_url:
+ default: ""
+ validator: "VoiceLivekitUrlValidator"
+ voice_livekit_api_key:
+ default: ""
+ voice_livekit_api_secret:
+ default: ""
+ secret: true
+ voice_livekit_room_policy:
+ default: "disabled"
+ type: enum
+ choices:
+ - disabled
+ - per_room
+ - all_rooms
+ validator: "VoiceLivekitPolicyValidator"
+ voice_livekit_room_prefix:
+ default: ""
+ voice_livekit_mesh_fallback:
+ default: false
+ voice_livekit_recording_enabled:
+ default: false
+ client: true
+ voice_livekit_recording_filepath:
+ default: "voice/{room_name}-{utc}"
+ voice_video_enabled:
+ default: true
+ client: true
+ voice_video_max_publishers:
+ default: 8
+ min: 2
+ max: 16
+ client: true
+ voice_video_background_blur_enabled:
+ default: true
+ client: true
+ voice_subtitles_enabled:
+ default: false
+ client: true
+ voice_stt_model_base_url:
+ default: ""
+ client: true
+ voice_max_voice_quality:
+ default: "maximum"
+ type: enum
+ client: true
+ choices:
+ - standard
+ - high
+ - maximum
+ voice_max_camera_quality:
+ default: "maximum"
+ type: enum
+ client: true
+ choices:
+ - standard
+ - high
+ - maximum
+ voice_max_screen_share_quality:
+ default: "maximum"
+ type: enum
+ client: true
+ choices:
+ - standard
+ - high
+ - maximum
+ voice_idle_threshold_minutes:
+ default: 5
+ min: 0
+ max: 60
+ client: true
+ voice_afk_auto_mute_threshold_minutes:
+ default: 15
+ min: 0
+ max: 120
+ client: true
+ voice_afk_disconnect_threshold_minutes:
+ default: 30
+ min: 0
+ max: 240
+ client: true
+ voice_auto_status_enabled:
+ default: true
+ client: true
+ voice_mesh_privacy_warning_enabled:
+ default: true
+ client: true
+ voice_badges_enabled:
+ default: false
+ voice_analytics_enabled:
+ default: true
+ voice_session_retention_days:
+ default: 400
+ min: 7
+ max: 3650
+ voice_chat_enabled:
+ default: true
+ client: true
diff --git a/plugins/voice/db/fixtures/001_badges.rb b/plugins/voice/db/fixtures/001_badges.rb
new file mode 100644
index 00000000000..16bea80978a
--- /dev/null
+++ b/plugins/voice/db/fixtures/001_badges.rb
@@ -0,0 +1,368 @@
+# frozen_string_literal: true
+
+voice_badge_group = "Voice"
+
+BadgeGrouping.seed(:name) do |g|
+ g.name = voice_badge_group
+ g.default_position = 15
+end
+
+voice_grouping = BadgeGrouping.find_by(name: voice_badge_group)
+
+duration_sql = "EXTRACT(EPOCH FROM (COALESCE(left_at, CURRENT_TIMESTAMP) - joined_at))"
+
+co_presence_distinct_partners = lambda { |min_count| <<~SQL }
+ SELECT uid user_id, current_timestamp granted_at FROM (
+ SELECT user_id_1 AS uid, user_id_2 AS partner_id
+ FROM voice_co_presences
+ GROUP BY user_id_1, user_id_2
+ HAVING SUM(total_seconds) >= 300
+ UNION ALL
+ SELECT user_id_2 AS uid, user_id_1 AS partner_id
+ FROM voice_co_presences
+ GROUP BY user_id_2, user_id_1
+ HAVING SUM(total_seconds) >= 300
+ ) sub
+ GROUP BY uid
+ HAVING COUNT(*) >= #{min_count}
+ SQL
+
+co_presence_with_one_partner = lambda { |min_seconds| <<~SQL }
+ SELECT DISTINCT uid user_id, current_timestamp granted_at FROM (
+ SELECT user_id_1 AS uid
+ FROM voice_co_presences
+ GROUP BY user_id_1, user_id_2
+ HAVING SUM(total_seconds) >= #{min_seconds}
+ UNION ALL
+ SELECT user_id_2 AS uid
+ FROM voice_co_presences
+ GROUP BY user_id_1, user_id_2
+ HAVING SUM(total_seconds) >= #{min_seconds}
+ ) sub
+ SQL
+
+loyalty_query = lambda { |min_days| <<~SQL }
+ SELECT DISTINCT user_id, current_timestamp granted_at FROM (
+ SELECT user_id, room_id
+ FROM voice_sessions
+ GROUP BY user_id, room_id
+ HAVING COUNT(DISTINCT DATE(joined_at)) >= #{min_days}
+ ) sub
+ SQL
+
+# -- Welcome (instant) --
+
+Badge.seed(:name) do |b|
+ b.name = "Mic Check"
+ b.default_icon = "microphone"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+# -- Airtime (scheduled) --
+
+{
+ "Rookie" => [BadgeType::Bronze, 1.hour.to_i],
+ "Chatterbox" => [BadgeType::Silver, 10.hours.to_i],
+ "Silver Tongue" => [BadgeType::Gold, 100.hours.to_i],
+}.each do |name, (type, threshold)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = "clock"
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = <<~SQL
+ SELECT user_id, current_timestamp granted_at
+ FROM voice_sessions
+ GROUP BY user_id
+ HAVING SUM(#{duration_sql}) >= #{threshold}
+ SQL
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Networker (instant: Icebreaker, scheduled: Social Butterfly, Life of the Party) --
+
+Badge.seed(:name) do |b|
+ b.name = "Icebreaker"
+ b.default_icon = "handshake"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+{
+ "Social Butterfly" => [BadgeType::Silver, 10],
+ "Life of the Party" => [BadgeType::Gold, 50],
+}.each do |name, (type, count)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = "users"
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = co_presence_distinct_partners.call(count)
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Bonding (scheduled) --
+
+{
+ "Familiar Face" => [BadgeType::Bronze, 2.hours.to_i],
+ "Inner Circle" => [BadgeType::Silver, 10.hours.to_i],
+ "Partners in Crime" => [BadgeType::Gold, 50.hours.to_i],
+}.each do |name, (type, threshold)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = "user-group"
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = co_presence_with_one_partner.call(threshold)
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Exploration (scheduled) --
+
+{
+ "Explorer" => [BadgeType::Bronze, 5],
+ "Nomad" => [BadgeType::Silver, 20],
+ "Omnipresent" => [BadgeType::Gold, 50],
+}.each do |name, (type, count)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = "compass"
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = <<~SQL
+ SELECT user_id, current_timestamp granted_at
+ FROM voice_sessions
+ GROUP BY user_id
+ HAVING COUNT(DISTINCT room_id) >= #{count}
+ SQL
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Loyalty (scheduled) --
+
+{
+ "Patron" => [BadgeType::Bronze, 10],
+ "Barfly" => [BadgeType::Silver, 30],
+ "The Mayor" => [BadgeType::Gold, 100],
+}.each do |name, (type, days)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = "calendar"
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = loyalty_query.call(days)
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Hosting (instant: Host, scheduled: Crowd Puller, Master of Ceremonies) --
+
+Badge.seed(:name) do |b|
+ b.name = "Host"
+ b.default_icon = "house"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+{
+ "Crowd Puller" => [BadgeType::Silver, 50, "bullhorn"],
+ "Master of Ceremonies" => [BadgeType::Gold, 500, "star"],
+}.each do |name, (type, count, icon)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = icon
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = <<~SQL
+ SELECT r.creator_id user_id, current_timestamp granted_at
+ FROM voice_rooms r
+ JOIN voice_sessions s ON s.room_id = r.id
+ GROUP BY r.creator_id
+ HAVING COUNT(s.id) >= #{count}
+ SQL
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Inviting (instant: Plus One, scheduled: Connector, People Magnet) --
+
+Badge.seed(:name) do |b|
+ b.name = "Plus One"
+ b.default_icon = "user-plus"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+{
+ "Connector" => [BadgeType::Silver, 10, "circle-nodes"],
+ "People Magnet" => [BadgeType::Gold, 50, "magnet"],
+}.each do |name, (type, count, icon)|
+ Badge.seed(:name) do |b|
+ b.name = name
+ b.default_icon = icon
+ b.badge_type_id = type
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = <<~SQL
+ SELECT invited_by_id user_id, current_timestamp granted_at
+ FROM voice_invites
+ WHERE redeemed_at IS NOT NULL
+ GROUP BY invited_by_id
+ HAVING COUNT(DISTINCT user_id) >= #{count}
+ SQL
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = type == BadgeType::Gold
+ b.system = true
+ end
+end
+
+# -- Standalone --
+
+Badge.seed(:name) do |b|
+ b.name = "Night Owl"
+ b.default_icon = "moon"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+Badge.seed(:name) do |b|
+ b.name = "Early Bird"
+ b.default_icon = "sun"
+ b.badge_type_id = BadgeType::Bronze
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+Badge.seed(:name) do |b|
+ b.name = "Packed House"
+ b.default_icon = "people-group"
+ b.badge_type_id = BadgeType::Silver
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+Badge.seed(:name) do |b|
+ b.name = "Weekend Warrior"
+ b.default_icon = "calendar-week"
+ b.badge_type_id = BadgeType::Silver
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = <<~SQL
+ SELECT user_id, current_timestamp granted_at
+ FROM voice_sessions
+ WHERE EXTRACT(DOW FROM joined_at) IN (0, 6)
+ GROUP BY user_id
+ HAVING SUM(#{duration_sql}) >= #{5.hours.to_i}
+ SQL
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.system = true
+end
+
+Badge.seed(:name) do |b|
+ b.name = "Marathoner"
+ b.default_icon = "trophy"
+ b.badge_type_id = BadgeType::Gold
+ b.multiple_grant = false
+ b.target_posts = false
+ b.show_posts = false
+ b.query = nil
+ b.default_badge_grouping_id = voice_grouping.id
+ b.trigger = Badge::Trigger::None
+ b.default_enabled = false
+ b.default_allow_title = true
+ b.system = true
+end
diff --git a/plugins/voice/db/migrate/20241107000000_create_voice_rooms.rb b/plugins/voice/db/migrate/20241107000000_create_voice_rooms.rb
new file mode 100644
index 00000000000..234060910d2
--- /dev/null
+++ b/plugins/voice/db/migrate/20241107000000_create_voice_rooms.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+class CreateVoiceRooms < ActiveRecord::Migration[7.0]
+ def change
+ create_table :voice_rooms do |t|
+ t.string :name, null: false
+ t.string :slug, null: false
+ t.text :description
+ t.boolean :public, default: false, null: false
+ t.integer :max_participants
+ t.references :creator, null: false, foreign_key: { to_table: :users }
+ t.timestamps
+ end
+
+ add_index :voice_rooms, :slug, unique: true
+
+ create_table :voice_room_memberships do |t|
+ t.references :room, null: false, foreign_key: { to_table: :voice_rooms }
+ t.references :user, null: false, foreign_key: true
+ t.integer :role, default: 0, null: false
+ t.timestamps
+ end
+
+ add_index :voice_room_memberships,
+ %i[room_id user_id],
+ unique: true,
+ name: "idx_voice_room_memberships_on_room_and_user"
+ end
+end
+# rubocop:enable Discourse/NoAddReferenceOrAliasesActiveRecordMigration
diff --git a/plugins/voice/db/migrate/20260220154336_add_cooked_description_to_voice_rooms.rb b/plugins/voice/db/migrate/20260220154336_add_cooked_description_to_voice_rooms.rb
new file mode 100644
index 00000000000..0146ded5146
--- /dev/null
+++ b/plugins/voice/db/migrate/20260220154336_add_cooked_description_to_voice_rooms.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddCookedDescriptionToVoiceRooms < ActiveRecord::Migration[7.2]
+ def change
+ add_column :voice_rooms, :cooked_description, :text
+ end
+end
diff --git a/plugins/voice/db/migrate/20260305162426_add_room_type_to_voice_rooms.rb b/plugins/voice/db/migrate/20260305162426_add_room_type_to_voice_rooms.rb
new file mode 100644
index 00000000000..1a1445f2e66
--- /dev/null
+++ b/plugins/voice/db/migrate/20260305162426_add_room_type_to_voice_rooms.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddRoomTypeToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :room_type, :integer, default: 0, null: false
+ end
+end
diff --git a/plugins/voice/db/migrate/20260305165400_create_voice_sessions.rb b/plugins/voice/db/migrate/20260305165400_create_voice_sessions.rb
new file mode 100644
index 00000000000..91eb6d1f1a6
--- /dev/null
+++ b/plugins/voice/db/migrate/20260305165400_create_voice_sessions.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+class CreateVoiceSessions < ActiveRecord::Migration[8.0]
+ def change
+ create_table :voice_sessions do |t|
+ t.references :user, null: false, foreign_key: true
+ t.references :room, null: false, foreign_key: { to_table: :voice_rooms }
+ t.datetime :joined_at, null: false
+ t.datetime :left_at
+ t.timestamps
+ end
+
+ add_index :voice_sessions, %i[user_id room_id joined_at]
+ add_index :voice_sessions, %i[room_id joined_at]
+ add_index :voice_sessions, %i[user_id joined_at]
+ add_index :voice_sessions,
+ :left_at,
+ where: "left_at IS NULL",
+ name: "idx_voice_sessions_orphaned"
+ end
+end
+# rubocop:enable Discourse/NoAddReferenceOrAliasesActiveRecordMigration
diff --git a/plugins/voice/db/migrate/20260305165401_create_voice_co_presences.rb b/plugins/voice/db/migrate/20260305165401_create_voice_co_presences.rb
new file mode 100644
index 00000000000..984bb2a03ec
--- /dev/null
+++ b/plugins/voice/db/migrate/20260305165401_create_voice_co_presences.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+class CreateVoiceCoPresences < ActiveRecord::Migration[8.0]
+ def change
+ create_table :voice_co_presences do |t|
+ t.integer :user_id_1, null: false
+ t.integer :user_id_2, null: false
+ t.date :date, null: false
+ t.integer :total_seconds, null: false, default: 0
+ t.integer :session_count, null: false, default: 0
+ t.timestamps
+ end
+
+ add_foreign_key :voice_co_presences, :users, column: :user_id_1
+ add_foreign_key :voice_co_presences, :users, column: :user_id_2
+
+ add_index :voice_co_presences,
+ %i[user_id_1 user_id_2 date],
+ unique: true,
+ name: "idx_voice_co_presences_unique"
+ add_index :voice_co_presences, %i[user_id_1 date]
+ add_index :voice_co_presences, %i[user_id_2 date]
+
+ reversible { |dir| dir.up { execute <<~SQL } }
+ ALTER TABLE voice_co_presences
+ ADD CONSTRAINT chk_voice_co_presences_user_order
+ CHECK (user_id_1 < user_id_2)
+ SQL
+ end
+end
diff --git a/plugins/voice/db/migrate/20260612135211_add_video_enabled_to_voice_rooms.rb b/plugins/voice/db/migrate/20260612135211_add_video_enabled_to_voice_rooms.rb
new file mode 100644
index 00000000000..c548d3bca23
--- /dev/null
+++ b/plugins/voice/db/migrate/20260612135211_add_video_enabled_to_voice_rooms.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddVideoEnabledToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :video_enabled, :boolean, null: false, default: true
+ end
+end
diff --git a/plugins/voice/db/migrate/20260630183841_add_chat_settings_to_voice_rooms.rb b/plugins/voice/db/migrate/20260630183841_add_chat_settings_to_voice_rooms.rb
new file mode 100644
index 00000000000..89262097e1d
--- /dev/null
+++ b/plugins/voice/db/migrate/20260630183841_add_chat_settings_to_voice_rooms.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+class AddChatSettingsToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :chat_channel_id, :bigint
+ add_column :voice_rooms, :chat_idle_minutes, :integer, default: 15, null: false
+ add_column :voice_rooms, :chat_thread_title_template, :string
+ add_index :voice_rooms, :chat_channel_id
+ end
+end
diff --git a/plugins/voice/db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms.rb b/plugins/voice/db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms.rb
new file mode 100644
index 00000000000..5a0144bed24
--- /dev/null
+++ b/plugins/voice/db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddLivekitEnabledToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :livekit_enabled, :boolean, null: false, default: false
+ end
+end
diff --git a/plugins/voice/db/migrate/20260717172530_create_voice_recordings.rb b/plugins/voice/db/migrate/20260717172530_create_voice_recordings.rb
new file mode 100644
index 00000000000..2ef3b2af767
--- /dev/null
+++ b/plugins/voice/db/migrate/20260717172530_create_voice_recordings.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class CreateVoiceRecordings < ActiveRecord::Migration[8.0]
+ def change
+ create_table :voice_recordings do |t|
+ t.bigint :room_id, null: false
+ t.bigint :started_by_id, null: false
+ t.string :egress_id, null: false
+ t.integer :status, null: false, default: 0
+ t.string :filepath, null: false
+ t.string :filename
+ t.string :location
+ t.bigint :duration_ms
+ t.bigint :size_bytes
+ t.datetime :started_at, null: false
+ t.datetime :ended_at
+ t.timestamps
+ end
+
+ add_index :voice_recordings, :egress_id, unique: true
+ add_index :voice_recordings, %i[room_id started_at]
+ end
+end
diff --git a/plugins/voice/db/migrate/20260728201053_add_max_quality_profile_to_voice_rooms.rb b/plugins/voice/db/migrate/20260728201053_add_max_quality_profile_to_voice_rooms.rb
new file mode 100644
index 00000000000..257dd7f52b3
--- /dev/null
+++ b/plugins/voice/db/migrate/20260728201053_add_max_quality_profile_to_voice_rooms.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddMaxQualityProfileToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :max_quality_profile, :integer
+ end
+end
diff --git a/plugins/voice/db/migrate/20260803144425_add_ephemeral_to_voice_rooms.rb b/plugins/voice/db/migrate/20260803144425_add_ephemeral_to_voice_rooms.rb
new file mode 100644
index 00000000000..749d312b810
--- /dev/null
+++ b/plugins/voice/db/migrate/20260803144425_add_ephemeral_to_voice_rooms.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+class AddEphemeralToVoiceRooms < ActiveRecord::Migration[8.0]
+ def change
+ add_column :voice_rooms, :ephemeral, :boolean, default: false, null: false
+ add_column :voice_rooms, :last_occupied_at, :datetime
+
+ # The cleanup job scans only ephemeral rooms; persistent rooms dominate
+ # the table, so a partial index keeps that scan cheap.
+ add_index :voice_rooms, :id, where: "ephemeral", name: "index_voice_rooms_on_ephemeral"
+ end
+end
diff --git a/plugins/voice/db/migrate/20260813160047_create_voice_invites.rb b/plugins/voice/db/migrate/20260813160047_create_voice_invites.rb
new file mode 100644
index 00000000000..8f306068e22
--- /dev/null
+++ b/plugins/voice/db/migrate/20260813160047_create_voice_invites.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class CreateVoiceInvites < ActiveRecord::Migration[8.0]
+ def change
+ # No user/room foreign keys: like sessions, invites are history that must
+ # not block (or be erased by) user and room deletion.
+ create_table :voice_invites do |t|
+ t.bigint :room_id, null: false
+ t.bigint :user_id, null: false
+ t.bigint :invited_by_id, null: false
+ t.integer :source, null: false, default: 0
+ t.datetime :redeemed_at
+ t.timestamps
+ end
+
+ add_index :voice_invites, %i[room_id user_id invited_by_id], unique: true
+ add_index :voice_invites, %i[user_id room_id]
+ add_index :voice_invites,
+ %i[invited_by_id user_id],
+ where: "redeemed_at IS NOT NULL",
+ name: "idx_voice_invites_redeemed"
+ end
+end
diff --git a/plugins/voice/db/migrate/20260824214603_mark_chat_thread_title_template_readonly.rb b/plugins/voice/db/migrate/20260824214603_mark_chat_thread_title_template_readonly.rb
new file mode 100644
index 00000000000..37f65fbede1
--- /dev/null
+++ b/plugins/voice/db/migrate/20260824214603_mark_chat_thread_title_template_readonly.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class MarkChatThreadTitleTemplateReadonly < ActiveRecord::Migration[8.0]
+ def up
+ Migration::ColumnDropper.mark_readonly(:voice_rooms, :chat_thread_title_template)
+ end
+
+ def down
+ Migration::ColumnDropper.drop_readonly(:voice_rooms, :chat_thread_title_template)
+ end
+end
diff --git a/plugins/voice/db/post_migrate/20260703134812_remove_voice_noise_suppression_setting.rb b/plugins/voice/db/post_migrate/20260703134812_remove_voice_noise_suppression_setting.rb
new file mode 100644
index 00000000000..b1932922d9b
--- /dev/null
+++ b/plugins/voice/db/post_migrate/20260703134812_remove_voice_noise_suppression_setting.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+class RemoveVoiceNoiseSuppressionSetting < ActiveRecord::Migration[8.0]
+ def up
+ execute "DELETE FROM site_settings WHERE name = 'voice_noise_suppression'"
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/voice/db/post_migrate/20260803163214_remove_voice_sessions_room_foreign_key.rb b/plugins/voice/db/post_migrate/20260803163214_remove_voice_sessions_room_foreign_key.rb
new file mode 100644
index 00000000000..ce25775540f
--- /dev/null
+++ b/plugins/voice/db/post_migrate/20260803163214_remove_voice_sessions_room_foreign_key.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+# Sessions are analytics history: they must survive their room's deletion,
+# which the FK made impossible (room destroy raised ForeignKeyViolation).
+class RemoveVoiceSessionsRoomForeignKey < ActiveRecord::Migration[8.0]
+ def up
+ remove_foreign_key :voice_sessions, column: :room_id, if_exists: true
+ end
+
+ def down
+ # Re-adding would fail once rows reference deleted rooms.
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/voice/db/post_migrate/20260803163818_remove_voice_user_foreign_keys.rb b/plugins/voice/db/post_migrate/20260803163818_remove_voice_user_foreign_keys.rb
new file mode 100644
index 00000000000..5fe95e25b1c
--- /dev/null
+++ b/plugins/voice/db/post_migrate/20260803163818_remove_voice_user_foreign_keys.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+# User deletion must not be blocked by voice rows; cleanup happens in the
+# plugin's user_destroyed handler instead (rooms reassigned to the system
+# user, memberships and co-presences removed, sessions kept as history).
+class RemoveVoiceUserForeignKeys < ActiveRecord::Migration[8.0]
+ def up
+ remove_foreign_key :voice_sessions, column: :user_id, if_exists: true
+ remove_foreign_key :voice_room_memberships, column: :user_id, if_exists: true
+ remove_foreign_key :voice_co_presences, column: :user_id_1, if_exists: true
+ remove_foreign_key :voice_co_presences, column: :user_id_2, if_exists: true
+ remove_foreign_key :voice_rooms, column: :creator_id, if_exists: true
+ end
+
+ def down
+ # Re-adding would fail once rows reference deleted users.
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/voice/db/post_migrate/20260824214608_drop_chat_thread_title_template_from_voice_rooms.rb b/plugins/voice/db/post_migrate/20260824214608_drop_chat_thread_title_template_from_voice_rooms.rb
new file mode 100644
index 00000000000..1ca95a3f283
--- /dev/null
+++ b/plugins/voice/db/post_migrate/20260824214608_drop_chat_thread_title_template_from_voice_rooms.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+class DropChatThreadTitleTemplateFromVoiceRooms < ActiveRecord::Migration[8.0]
+ DROPPED_COLUMNS = { voice_rooms: %i[chat_thread_title_template] }
+
+ def up
+ DROPPED_COLUMNS.each { |table, columns| Migration::ColumnDropper.execute_drop(table, columns) }
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/voice/db/post_migrate/20260831162602_rename_resenha_to_voice.rb b/plugins/voice/db/post_migrate/20260831162602_rename_resenha_to_voice.rb
new file mode 100644
index 00000000000..273b3b07fef
--- /dev/null
+++ b/plugins/voice/db/post_migrate/20260831162602_rename_resenha_to_voice.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+# The plugin was renamed from "resenha" to "voice". Fresh installs create the
+# voice_* schema directly (the historical migrations were rewritten); this
+# migration converts sites that migrated under the old name.
+class RenameResenhaToVoice < ActiveRecord::Migration[8.0]
+ RENAMED_TABLES = {
+ resenha_rooms: :voice_rooms,
+ resenha_room_memberships: :voice_room_memberships,
+ resenha_sessions: :voice_sessions,
+ resenha_co_presences: :voice_co_presences,
+ resenha_recordings: :voice_recordings,
+ resenha_invites: :voice_invites,
+ }
+
+ def up
+ RENAMED_TABLES.each do |old_name, new_name|
+ rename_table(old_name, new_name) if table_exists?(old_name) && !table_exists?(new_name)
+ end
+
+ # rename_table only renames conventionally named indexes; sweep up the
+ # custom-named ones, primary keys, and any readonly triggers/functions
+ # left by the column-drop lifecycle.
+ DB
+ .query_single(
+ "SELECT indexname FROM pg_indexes WHERE schemaname = 'public' AND indexname LIKE '%resenha%'",
+ )
+ .each { |index| execute "ALTER INDEX #{index} RENAME TO #{index.gsub("resenha", "voice")}" }
+
+ DB
+ .query(
+ "SELECT t.tgname, c.relname FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid " \
+ "WHERE NOT t.tgisinternal AND t.tgname LIKE '%resenha%'",
+ )
+ .each do |row|
+ execute "ALTER TRIGGER #{row.tgname} ON #{row.relname} RENAME TO #{row.tgname.gsub("resenha", "voice")}"
+ end
+
+ DB
+ .query_single(
+ "SELECT p.proname FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " \
+ "WHERE n.nspname = 'public' AND p.proname LIKE '%resenha%'",
+ )
+ .each do |function|
+ execute "ALTER FUNCTION #{function}() RENAME TO #{function.gsub("resenha", "voice")}"
+ end
+
+ execute <<~SQL
+ UPDATE site_settings
+ SET name = REPLACE(name, 'resenha_', 'voice_')
+ WHERE name LIKE 'resenha\\_%'
+ AND REPLACE(name, 'resenha_', 'voice_') NOT IN (SELECT name FROM site_settings)
+ SQL
+
+ # The old default admitted the deprecated `everyone` pseudogroup (0);
+ # anonymous_users + logged_in_users (4|5) is the equivalent going forward.
+ execute <<~SQL
+ UPDATE site_settings
+ SET value = '4|5'
+ WHERE name = 'voice_allowed_groups' AND value = '0'
+ SQL
+
+ execute <<~SQL
+ UPDATE reviewables
+ SET type = 'ReviewableVoiceUser'
+ WHERE type = 'ReviewableResenhaUser'
+ SQL
+
+ execute <<~SQL if table_exists?(:chat_thread_custom_fields)
+ UPDATE chat_thread_custom_fields
+ SET name = 'voice_room_id'
+ WHERE name = 'resenha_room_id'
+ SQL
+
+ execute <<~SQL
+ UPDATE badge_groupings
+ SET name = 'Voice'
+ WHERE name = 'Resenha'
+ AND NOT EXISTS (SELECT 1 FROM badge_groupings WHERE name = 'Voice')
+ SQL
+
+ # Cooked room hashtags and links embed the old /resenha mount point.
+ execute <<~SQL
+ UPDATE posts
+ SET baked_version = NULL
+ WHERE cooked LIKE '%/resenha/%'
+ SQL
+
+ execute <<~SQL if table_exists?(:chat_messages)
+ UPDATE chat_messages
+ SET cooked_version = NULL
+ WHERE cooked LIKE '%/resenha/%'
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/voice/docs/ARCHITECTURE.md b/plugins/voice/docs/ARCHITECTURE.md
new file mode 100644
index 00000000000..e543b7c0e6d
--- /dev/null
+++ b/plugins/voice/docs/ARCHITECTURE.md
@@ -0,0 +1,40 @@
+# Voice Plugin Architecture
+
+Voice adds lightweight WebRTC voice rooms to Discourse without proxying audio/video through the server. Media runs over one of two transports — the default peer-to-peer mesh, or an optional self-hosted [LiveKit](https://livekit.io) SFU (see [livekit.md](./livekit.md)) — while everything else (presence, sessions, roster, moderation) is transport-independent. It consists of the following layers:
+
+## Backend
+
+- **Models**
+ - `Voice::Room`: describes each voice space and keeps ownership, slug, visibility, and capacity metadata. Creator is automatically promoted to room moderator. Rooms flagged `ephemeral` are short-lived rooms created programmatically by other features and are excluded from every discovery surface (see [ephemeral-rooms.md](./ephemeral-rooms.md)).
+ - `Voice::RoomMembership`: links users to rooms while storing participant/moderator roles.
+- **Services**
+ - `Voice::ParticipantTracker`: stores the list of actively connected users per room in Redis with a short TTL. Join/leave actions refresh MessageBus subscribers. Also pins each live call's transport (`mesh` or `livekit`) so every participant of a call is on the same one; the pin clears when the room empties.
+ - `Voice::RoomBroadcaster`: emits participant snapshots to `/voice/rooms/:id` MessageBus channels so Ember clients can update sidebars in real time.
+ - `Voice::DirectoryBroadcaster`: keeps the sidebar list in sync across clients by broadcasting CRUD events to `/voice/rooms/index`. Skips ephemeral rooms, which never appear in the directory.
+ - `Voice::EphemeralRoomManager`: the only entry point for creating ephemeral rooms, plus their TTL-based reaping (driven by a scheduled job). Contract in [ephemeral-rooms.md](./ephemeral-rooms.md).
+ - `Voice::SignalRelay`: relays raw WebRTC SDP/ICE payloads between peers via MessageBus without touching media data (mesh rooms only).
+ - `Voice::Livekit`: mints short-lived, least-privilege LiveKit access tokens (HS256 JWT) and resolves whether a room is eligible for the SFU per `voice_livekit_room_policy`. `Voice::Livekit::RoomServiceClient` mirrors kicks, role changes, and room deletion to the LiveKit server best-effort via Twirp-JSON.
+- **Controllers**
+ - `RoomsController` exposes CRUD, join/leave, participant, and signaling endpoints.
+ - `RoomMembershipsController` lets moderators manage explicit memberships.
+- **Authorization**
+ - Guardian extensions gate room visibility, membership, and management. Site settings define who can create/manage rooms and cap per-user ownership tallies.
+
+## Frontend
+
+- **Services**
+ - `voice-rooms`: fetches initial room data, subscribes to MessageBus channels, updates tracked sidebar state, and forwards participant events to the UI.
+ - `voice-webrtc`: manages `navigator.mediaDevices` capture, maintains one `RTCPeerConnection` per peer (mesh) or one `LivekitRoomSession` per room (LiveKit), exchanges offers/answers/candidates through the `signal` endpoint on mesh rooms, and keeps remote audio elements synced. Both transports feed the same remote-media registry, so every component downstream is transport-agnostic; the vendored `livekit-client` bundle is dynamically imported only when a LiveKit room is joined.
+- **Sidebar Integration**
+ - `voice-sidebar` initializer registers a sidebar section with custom links for each room. Each link swaps its label with inline avatar thumbnails (plus a counter) so active participants are visible without modifying core sidebar components.
+- **Room UI**
+ - `voice-room` route/controller fetch full room metadata, render participant lists, and command the WebRTC service to join/leave rooms. `Voice::VoiceCanvas` mounts `<audio>` sinks for local and remote streams during active calls.
+ - Presentation layout automatically features the first screen share or active camera. A viewer can locally override that choice from a participant's video-tile menu; selecting a layout through the standard control restores automatic selection.
+
+## Message Flow
+
+1. User joins a room → `POST /voice/rooms/:id/join` resolves the call's transport (pinned in Redis for the call's lifetime), adds them to Redis, and broadcasts the participants list. For LiveKit calls the response also carries the server URL and a short-lived access token.
+2. Clients refresh presence with `POST /voice/rooms/:id/heartbeat` every 10 seconds (TTL is 30 seconds) without re-broadcasting participants.
+3. On mesh calls, each participant receiving the broadcast spins up `RTCPeerConnection` objects (only lower user IDs send offers to avoid glare) and relays SDP/ICE payloads via `POST /voice/rooms/:id/signal`. On LiveKit calls the client instead opens a single connection to the SFU and publishes/subscribes there; the `signal` endpoint rejects payloads for those rooms.
+4. Audio flows directly peer-to-peer (or through the site's own LiveKit server); Discourse only transports JSON signaling events.
+5. Sidebar avatars and the room screen update automatically as MessageBus notifications arrive — the roster is driven by Redis presence on both transports, never by media state.
diff --git a/plugins/voice/docs/ephemeral-rooms.md b/plugins/voice/docs/ephemeral-rooms.md
new file mode 100644
index 00000000000..43933aa3872
--- /dev/null
+++ b/plugins/voice/docs/ephemeral-rooms.md
@@ -0,0 +1,94 @@
+# Ephemeral rooms — backend interface
+
+Ephemeral rooms are short-lived `Voice::Room` records created by **other
+features**, not by a user filling in the room form: the backing room for a
+direct call between users, or a room spun up by an integration (e.g. an
+events/livestream plugin) for the duration of an event. This document is the
+contract for code that consumes them; there is no user-visible surface in the
+Voice plugin itself.
+
+## What "ephemeral" changes — and what it doesn't
+
+Ephemeral is a **lifecycle** flag, orthogonal to `room_type` (`open`/`stage`):
+a direct call is typically an ephemeral *open* room, an event stage an
+ephemeral *stage* room.
+
+An ephemeral room:
+
+- **Never appears in discovery surfaces**: the room directory (`GET
+ /voice/rooms`), directory MessageBus broadcasts on
+ `/voice/rooms/index`, and hashtag autocomplete/rendering all exclude it.
+ Whoever creates the room is responsible for surfacing it to its users.
+- **Cannot be created through the rooms API**: the `ephemeral` attribute is
+ not permitted in `RoomsController` or the admin rooms controller. The only
+ way in is `Voice::EphemeralRoomManager.create!`.
+- **Does not count** against `voice_max_rooms_per_user` (rooms are created
+ *for* users by features), and does not satisfy the default-room seeder's
+ "a room already exists" check.
+- **Is reaped automatically** once it sits empty past
+ `voice_ephemeral_room_ttl_minutes` (see Lifecycle below).
+
+Everything else behaves like any other room: `show`, `join`/`leave`,
+heartbeats, signaling, LiveKit transport resolution, chat sessions,
+recordings, and moderation all work unchanged, and the standard Guardian
+rules apply (`public` or membership gates joining; staff/creator/moderators
+manage). The room page at `/voice/r/:slug` renders it, so consumers can
+simply link users there.
+
+## Creating one
+
+```ruby
+# A direct call: both parties are moderators, so either can invite more
+# people mid-call (inviting is a moderator ability).
+room =
+ Voice::EphemeralRoomManager.create!(
+ creator: caller,
+ name: "Call",
+ moderators: [callee],
+ )
+
+# An event room: the host runs it, the audience are plain members.
+room =
+ Voice::EphemeralRoomManager.create!(
+ creator: host,
+ name: event.title,
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ members: attendees,
+ )
+```
+
+- The creator always gets a moderator membership (standard room behavior).
+- `moderators:` users get moderator memberships; `members:` users get
+ participant memberships. A user in both lists stays a moderator.
+- Any other `Voice::Room` attribute (`public`, `video_enabled`,
+ `max_participants`, `livekit_enabled`, …) passes through as a keyword.
+- Slugs get a random suffix (`call-a1b2c3d4`), so generic names never
+ collide with existing rooms — don't rely on a predictable slug; keep the
+ room's `id` (or the returned record) instead.
+
+## Lifecycle
+
+A scheduled job (every 5 minutes) walks ephemeral rooms:
+
+- Rooms with live participants get their `last_occupied_at` refreshed.
+- Rooms empty for longer than `voice_ephemeral_room_ttl_minutes`
+ (default 30, measured from `last_occupied_at`, or `created_at` if never
+ joined) are destroyed, including their LiveKit room and Redis presence
+ state.
+
+The TTL — rather than delete-on-empty — tolerates the gap between creation
+and the first join, and a call in which everyone's presence briefly lapses
+at once. Consumers must therefore treat the room as **disposable**: hold its
+id, not assumptions about its continued existence, and be prepared for a
+404 once a call has been over for a while. A consumer that finishes with a
+room early (call rejected, event cancelled) may destroy it immediately via
+`Voice::EphemeralRoomManager.destroy!(room)`, which performs the same full
+teardown.
+
+## Telling them apart
+
+- Ruby: `room.ephemeral?`, and the `Voice::Room.ephemeral` /
+ `Voice::Room.persistent` scopes.
+- Serialized rooms (`Voice::RoomSerializer`) carry an `ephemeral`
+ attribute, so client code can branch on it.
diff --git a/plugins/voice/docs/examples/voice-bots.example.json b/plugins/voice/docs/examples/voice-bots.example.json
new file mode 100644
index 00000000000..e4a6bfe8ead
--- /dev/null
+++ b/plugins/voice/docs/examples/voice-bots.example.json
@@ -0,0 +1,20 @@
+[
+ {
+ "username": "voice_bot_1",
+ "label": "Alice fake camera",
+ "color": "#2563eb",
+ "accent": "#f97316"
+ },
+ {
+ "username": "voice_bot_2",
+ "label": "Bob fake camera",
+ "color": "#16a34a",
+ "accent": "#7c3aed"
+ },
+ {
+ "username": "voice_bot_3",
+ "label": "Charlie fake camera",
+ "color": "#dc2626",
+ "accent": "#0891b2"
+ }
+]
diff --git a/plugins/voice/docs/livekit.md b/plugins/voice/docs/livekit.md
new file mode 100644
index 00000000000..fe33c607c07
--- /dev/null
+++ b/plugins/voice/docs/livekit.md
@@ -0,0 +1,237 @@
+# LiveKit media server (SFU) — deployment and operations
+
+By default Voice runs calls as a pure peer-to-peer mesh: every participant
+sends media to every other participant, and nothing touches the Discourse
+server. That is the right default for small rooms and zero-infrastructure
+installs, but upstream bandwidth grows with room size, so large rooms and
+many simultaneous video publishers eventually hit browser and network limits.
+
+Sites that need bigger calls can deploy their own [LiveKit](https://livekit.io)
+server and point the plugin at it. Rooms routed through LiveKit publish each
+track **once** to the SFU, which fans it out to subscribers — publisher
+upstream stays constant no matter how many people are in the room. Everything
+else (presence, sessions, badges, admin stats, the roster UI, mute/deafen,
+push-to-talk, noise suppression, background blur) works identically on both
+transports.
+
+This document is the operations guide: provisioning, network setup, Discourse
+configuration, verification, and day-2 operations. For the design itself see
+[roadmap/livekit-sfu.md](./roadmap/livekit-sfu.md).
+
+## How rooms pick a transport
+
+- The **server** decides the transport when the first participant joins, and
+ pins it (in Redis) for the life of that call. Everyone in a call is always
+ on the same transport; there is no mixed room and no client-side choice.
+- `voice_livekit_room_policy` controls the resolution: `disabled` (default,
+ everything mesh), `per_room` (rooms opt in individually via a room-form
+ checkbox), or `all_rooms`.
+- **Setting changes never affect a call already in progress.** A room switches
+ transport when its next call starts — i.e. after it empties. To force the
+ issue, see [Emergency levers](#emergency-levers).
+
+## Provisioning a LiveKit server
+
+A modest VM goes a long way: 2–4 cores is ample for most communities (audio
+is roughly hundreds of participants per core; 720p video roughly ~100 tracks
+per core). Run the open-source `livekit/livekit-server` (Docker or a single
+Go binary) with:
+
+- one `key: secret` API pair (generate with `livekit-server generate-keys`),
+- `use_external_ip: true` when the server sits behind NAT (cloud VMs almost
+ always do),
+- a single node — no Redis required; each room just has to fit on one node,
+- optionally, [webhook delivery](#webhook-reconciliation-optional) back to the
+ forum:
+
+ ```yaml
+ webhook:
+ api_key: <the same API key>
+ urls:
+ - https://forum.example/voice/livekit/webhook
+ ```
+
+## Network setup
+
+1. Put a reverse proxy (WebSocket upgrade + long timeouts) in front of
+ LiveKit's HTTP/signal port 7880, exposed as `wss://livekit.example.com`.
+2. Open **7881/TCP** (ICE over TCP fallback) and the **UDP port range**
+ (default 50000–60000, configurable) directly to the LiveKit host — media
+ does not go through the reverse proxy.
+3. Optionally enable LiveKit's embedded TURN on 443/TLS with its own hostname
+ and certificate for clients on networks that block everything else.
+
+**The classic failure is "connects but no media"**: signaling over wss works
+through the proxy, but RTP can't flow. Check `use_external_ip` and the UDP
+range/firewall first — this is almost always the cause.
+
+### Content Security Policy
+
+Browsers connect to the LiveKit host with WebSocket. Discourse core currently
+emits no `connect-src` directive of its own, so a stock install needs nothing.
+But if a CSP with `connect-src` is enforced by a proxy in front of
+**Discourse**, it must include the LiveKit wss host, or every join fails with
+a CSP violation in the console. (If core ever starts emitting `connect-src`
+by default, the plugin will need to register a CSP extension for the
+configured host — tracked as a known risk in the roadmap.)
+
+## Discourse configuration
+
+| Setting | Value |
+| --- | --- |
+| `voice_livekit_url` | `wss://livekit.example.com` (or `ws://` for plain-HTTP labs) |
+| `voice_livekit_api_key` | the API key |
+| `voice_livekit_api_secret` | the API secret |
+| `voice_livekit_room_policy` | `per_room` or `all_rooms` |
+| `voice_livekit_room_prefix` | optional room-name namespace; defaults to the site's database name |
+| `voice_livekit_mesh_fallback` | opt-in: when a token can't be minted and the room is empty, start on mesh instead of failing the join. Off by default — silent degradation hides outages |
+
+The policy setting validates that URL, key, and secret are present before it
+can leave `disabled`, so misconfiguration fails at save time, not at a user's
+first join. None of these settings are sent to clients; the URL and a
+short-lived (10 minute), single-room, single-user token reach the browser only
+in the join response of rooms actually resolved to LiveKit.
+
+Mesh rooms keep using the existing `voice_stun_servers` /
+`voice_turn_servers` settings; LiveKit brings its own ICE/TURN and ignores
+them.
+
+With `per_room` policy, room creators/managers get a "Use media server (SFU)"
+checkbox in the room form. Toggling it affects the room's next call, never a
+live one.
+
+## Verifying a deployment
+
+1. Join a LiveKit-routed room from two different networks and confirm you can
+ hear each other and see cameras.
+2. In `chrome://webrtc-internals`, a LiveKit call shows a **single**
+ PeerConnection to the SFU host (a mesh call shows one per participant).
+3. The join response (`POST /voice/rooms/:id/join` in devtools) carries
+ `"transport": "livekit"`.
+4. For an automated end-to-end check from a dev machine, see
+ [Local testing](#local-testing-and-the-gated-system-spec).
+
+If joins fail with "Voice server unavailable", the server rejected the token
+mint (bad key/secret or half-deleted config) — check `/logs` for entries
+prefixed `[voice-livekit]`. If joins fail with "Your network cannot reach
+the voice server", minting worked but the **client** couldn't reach the SFU
+(corporate firewall blocking WSS/UDP is the usual suspect) — this is
+deliberately never fallen back to mesh, because other participants may reach
+the SFU fine and a room must never split across transports.
+
+## Operations
+
+- **Settings changes** (URL, keys, policy) apply to each room's next call.
+ Live calls keep their pinned transport until the room empties.
+- **Ending a live call**: admins can end any room's call from
+ **Admin → Plugins → Voice** (the room list's "End call" action). It kicks
+ every participant, deletes the LiveKit room, and clears the transport pin,
+ so the next join re-resolves against current settings.
+- **Emergency levers**:
+ - `rake voice:clear_transport_pins` drops every pinned transport at once
+ (rooms re-resolve on their next join; occupants of a live call are not
+ disconnected, so prefer "End call" for occupied rooms).
+ - Setting the policy back to `disabled` stops new LiveKit calls immediately;
+ live ones finish on LiveKit.
+- **SFU outage mid-call**: clients ride out brief blips via the SDK's
+ auto-resume; on a hard disconnect they retry three times with fresh tokens,
+ then leave with a toast. Presence, sessions, and stats are unaffected
+ throughout — they ride Discourse heartbeats, not media.
+- **Kicks, role changes, room deletion** are synced to LiveKit best-effort;
+ LiveKit being down never fails a Discourse request (the client-side
+ enforcement still applies either way).
+
+## Webhook reconciliation (optional)
+
+With `webhook.urls` configured on the LiveKit server (see
+[Provisioning](#provisioning-a-livekit-server)), the plugin accepts signed
+webhook deliveries at `POST /voice/livekit/webhook` and uses them as a
+**reconcile-only backstop**:
+
+- `participant_left` / `participant_connection_aborted` expire the
+ participant's presence early, so someone whose connection died drops off the
+ roster in seconds instead of waiting out the heartbeat TTL.
+- `room_finished` clears the room's transport pin, so the next call
+ re-resolves against current settings right away.
+
+Webhooks never *create* presence and never touch session analytics — those
+ride Discourse heartbeats on both transports. If webhooks are undelivered
+(firewall, misconfigured URL), nothing breaks; the built-in TTLs just take a
+little longer to converge, so treat a stale delivery marker as a warning,
+never an outage.
+
+Deliveries are authenticated by the `Authorization` JWT LiveKit signs with the
+API secret, which includes a hash of the request body — no extra shared
+secret to configure. Rejected deliveries are logged to `/logs` prefixed
+`[voice-livekit]`.
+
+## Multisite / shared clusters
+
+- Use one API key pair per site.
+- Room names are namespaced with the site's database name by default
+ (`{db}-r{room_id}`), so sites on a shared LiveKit server can't collide;
+ `voice_livekit_room_prefix` overrides the prefix.
+- Webhooks are a partial fit here: LiveKit signs every delivery with the
+ single `webhook.api_key`, so with per-site key pairs only the site owning
+ that key can verify deliveries — the others safely reject them (403) and
+ fall back to the heartbeat TTLs. Sites that do verify still ignore events
+ for rooms outside their own name prefix.
+
+## Upgrades
+
+The client SDK is a pinned `livekit-client` bundle vendored in this repo
+(`livekit/livekit-client.js`, shipped in the discourse_voice_assets gem and
+rebuilt via its `scripts/build-livekit-bundle.sh`). Server upgrades within the same major
+version are safe; when bumping the vendored SDK, re-run the gated system spec
+below and the manual checklist against the server version you deploy.
+
+## Local testing and the gated system spec
+
+Run a disposable dev server (API key `devkey`, secret `secret`):
+
+```bash
+docker run --rm -p 7880:7880 livekit/livekit-server --dev
+```
+
+Then run the real-LiveKit system spec, which is skipped unless the URL is
+present:
+
+```bash
+VOICE_LIVEKIT_TEST_URL=ws://localhost:7880 \
+ bin/rspec plugins/voice/spec/system/voice_livekit_spec.rb
+```
+
+(When running on a dev machine add `CI=1`: outside CI, core pins every test
+browser to one fixed remote-debugging port, which breaks any system spec —
+this one included — that opens a second browser session.)
+
+It drives a two-browser camera call through the SFU using the same fake-media
+harness as the mesh specs — which also proves the fakes satisfy the LiveKit
+SDK (the plugin acquires media itself and hands the SDK finished tracks; the
+SDK never calls `getUserMedia`).
+
+The [local fake participants harness](./local-fake-participants.md) works
+against LiveKit-routed rooms unchanged, for the same reason.
+
+## Manual browser checklist
+
+`livekit-client` has real platform nuances the automated Chromium-only spec
+can't see (H.264 vs VP8 simulcast on Safari, autoplay policies against the
+plugin's service-owned media elements, mobile backgrounding). When bumping
+the vendored SDK or the server version, walk this list on **macOS Safari,
+iOS Safari, and Android Chrome** against a LiveKit-routed room:
+
+- [ ] Join the room; the roster shows you and speaking indicators track your mic.
+- [ ] Hear another participant's audio without tapping anything extra
+ (autoplay recovery may show its "click to enable audio" prompt once —
+ that's the existing, expected behavior).
+- [ ] Publish your camera; a second participant sees it.
+- [ ] Receive a screenshare (with its audio, when shared from a desktop
+ browser that supports tab audio).
+- [ ] Mute/unmute and push-to-talk still register on the other side.
+- [ ] Background the app (mobile) or sleep the laptop for ~30 s, come back:
+ the call reconnects on its own, or lands you back in the room after the
+ rejoin toast.
+- [ ] Join the same room from a second tab/device as the same user: the older
+ tab drops with the "continued in another tab" toast and the roster stays
+ correct.
diff --git a/plugins/voice/docs/local-fake-participants.md b/plugins/voice/docs/local-fake-participants.md
new file mode 100644
index 00000000000..324c5b2d2b2
--- /dev/null
+++ b/plugins/voice/docs/local-fake-participants.md
@@ -0,0 +1,96 @@
+# Local fake participants for Voice
+
+This developer-only harness opens several Playwright browser contexts, logs each one in as a bot user, injects fake camera/audio/screen-share media, and joins a Voice room. It is meant for local interactive WebRTC testing, not CI.
+
+## Quick start
+
+From the plugin checkout:
+
+```bash
+pnpm install
+DISCOURSE_URL=http://localhost:4200 ROOM=watercooler BOT_COUNT=3 \
+ pnpm voice:bots -- --headed --screenshots
+```
+
+By default the harness uses Discourse's development/test-only `/session/:username/become.json` login route. That means the named users must already exist and the target site must allow that route.
+
+## Bot config
+
+If `.local/voice-bots.json` exists, it is used instead of generated `voice_bot_N` usernames.
+
+Create it from the example:
+
+```bash
+mkdir -p .local
+cp docs/examples/voice-bots.example.json .local/voice-bots.json
+```
+
+Example:
+
+```json
+[
+ {
+ "username": "voice_bot_1",
+ "label": "Alice fake camera",
+ "color": "#2563eb",
+ "accent": "#f97316"
+ },
+ {
+ "username": "voice_bot_2",
+ "label": "Bob fake camera",
+ "color": "#16a34a",
+ "accent": "#7c3aed"
+ }
+]
+```
+
+You can also pass JSON directly:
+
+```bash
+VOICE_BOTS_JSON='[{"username":"alice"},{"username":"bob"}]' \
+ DISCOURSE_URL=http://localhost:4200 ROOM=watercooler pnpm voice:bots -- --headed
+```
+
+## Useful options
+
+```bash
+pnpm voice:bots -- --help
+```
+
+Common flags:
+
+- `--headed`: show browser windows.
+- `--screenshots`: write screenshots to `tmp/voice-bots/`.
+- `--trace`: write Playwright trace zips to `tmp/voice-bots/`.
+- `--record-video`: write Playwright videos to `tmp/voice-bots/`.
+- `--screen-share-bot 1`: make the first bot start fake screen share.
+- `--hold-ms 30000`: auto-close after 30 seconds; otherwise runs until Ctrl-C.
+- `--no-camera`: join without immediately starting camera.
+
+## Password login mode
+
+For non-development sites, use password login with credentials in the ignored local file:
+
+```json
+[
+ { "username": "voice_bot_1", "password": "local-only-password" },
+ { "username": "voice_bot_2", "password": "local-only-password" }
+]
+```
+
+Then run:
+
+```bash
+LOGIN_MODE=password DISCOURSE_URL=https://example.test ROOM=watercooler \
+ pnpm voice:bots -- --headed
+```
+
+Do not commit real credentials.
+
+## Notes
+
+- The harness works unchanged against rooms routed through a LiveKit server: the plugin acquires media itself (through these same fakes) and hands the SDK finished tracks, so `livekit-client` never calls `getUserMedia`.
+- Each bot uses a distinct canvas-backed camera stream with a visible label and animated frame marker.
+- Audio is a very-low-gain oscillator so the browser sees a real audio track without audible noise.
+- `getDisplayMedia` returns a separate fake screen-share canvas derived from the bot feed.
+- Browser logs are echoed with the bot username prefix.
diff --git a/plugins/voice/docs/roadmap/livekit-sfu.md b/plugins/voice/docs/roadmap/livekit-sfu.md
new file mode 100644
index 00000000000..1d5991fe650
--- /dev/null
+++ b/plugins/voice/docs/roadmap/livekit-sfu.md
@@ -0,0 +1,653 @@
+# Optional LiveKit SFU support
+
+This is the "SFU integration (future, separate effort)" scoped out of
+[video-screenshare.md](./video-screenshare.md). It is written to be executed by
+a coding agent, PR by PR (§9). Line references are against plugin commit
+`123a826` (2026-07-08) — re-verify before editing; treat method names as the
+stable anchors.
+
+**Goal**: enterprise customers who need many simultaneous video calls can
+deploy their own [LiveKit](https://livekit.io) server and point the plugin at
+it. Everyone else keeps the current pure-P2P mesh, byte-for-byte.
+
+**Non-goals**: mid-call mesh↔SFU migration, LiveKit Cloud billing integration,
+recording/egress (the token/room-name plumbing here is its prerequisite,
+nothing more), replacing mesh as the default.
+
+---
+
+## 1. Design summary
+
+LiveKit is added *beside* the mesh as a per-room transport branch inside
+`voice-webrtc.js` — not as a formal transport-interface refactor. The mesh
+path (glare handling, offer retries, ICE-restart detection, transceiver
+pre-allocation, join-race buffering in `peer-manager.js` / `signaling.js`) is
+battle-tested and is **not extracted, rewritten, or adapterized**. The service
+already has a natural seam, proven at three points:
+
+- **Outbound**: media reaches the transport at exactly three places —
+ peer creation (`peer-manager.js:209–250`), `#replaceTrackOnAllPeers`
+ (service ~:2630), and `#syncVideoSenders` (~:1414).
+- **Inbound**: all remote media enters through `#registerRemoteTrack(roomId,
+ userId, track, streams)` (~:2395) and leaves through `#removeRemoteStream`
+ (~:2454). Everything downstream (per-user MediaStream registry,
+ `attachStream`, volume/deafen, `AudioMonitor` speaking detection) operates on
+ plain MediaStreams.
+- **Control**: UI components consume only the service's public API; nothing
+ touches `RTCPeerConnection`.
+
+So:
+
+1. Each active room instance is tagged with a transport (`"mesh"` |
+ `"livekit"`), **decided by the server** in the join response and pinned in
+ Redis for the life of the room instance.
+2. Mesh-specific call sites get `if (this.#isMeshRoom(roomId))` guards — pure
+ additive guards that are tautologies for default installs.
+3. One new class, `LivekitRoomSession`, connects `livekit-client` to the *same*
+ callbacks `PeerManager` already uses (`#registerRemoteTrack`,
+ `#removeRemoteStream`), so the remote-media registry and every UI component
+ are untouched.
+
+Presence, sessions, badges, co-presence, user status, admin stats, sound
+effects, idle/AFK, and the roster UI all ride the existing REST
+join/heartbeat/leave/state + Redis + MessageBus stack, which never touches
+media — they are **identical on both transports by construction**.
+
+## 2. Key decisions
+
+| Decision | Choice | Why |
+|---|---|---|
+| Presence/sessions | Keep REST heartbeat + Redis + MessageBus for both transports; LiveKit webhooks are an optional reconcile-only backstop (PR 8) | Sessions, badges, co-presence, user status, admin stats, anon directory all key off `ParticipantTracker` + `Voice::Session`. Webhooks-as-authority would fork every consumer and break anon directory viewing. Heartbeats guarantee identical analytics on both transports with zero change. |
+| LiveKit JS delivery | Vendored ESM bundle under `public/javascripts/livekit/`, dynamic `import()` at join time | Matches the mediapipe precedent (`background-blur.js:39–51` dynamically imports vendored assets by URL). Zero LiveKit bytes shipped/parsed on the P2P path; no coupling to core's build. Pinned + checked in, rebuilt via a script like `scripts/build-dtln-worklet.sh`. |
+| Ruby dependency | No gem. Mint JWTs with core's `jwt` gem; hand-roll three Twirp-JSON RoomService calls (~60 lines) | The token is a stable, documented HS256 JWT; RoomService accepts plain JSON POSTs to `/twirp/livekit.RoomService/*` with a `roomAdmin` JWT bearer. Avoids plugin gem pinning/boot friction. |
+| Transport policy | Server-decided at join; pinned per live room instance; policy enum `disabled \| per_room \| all_rooms`. No threshold-based auto-cascade | Mid-call mesh→SFU migration requires dual-connection handoff — maximum risk, zero-regression antithesis. Static per-room-instance resolution covers the enterprise ask ("our town-hall room uses the SFU"). A static size-based variant is a 5-line resolver addition later if demand appears. |
+| Mute/PTT semantics | Keep `track.enabled` flipping on LiveKit too (silence frames through SFU, DTX-suppressed); do not use LiveKit `setMuted` | Identical code path on both transports (`toggleMute` ~:652, PTT ~:2767); zero divergence in PTT latency. Roster mute state already travels as presence metadata via `POST /state`, not media state. |
+| SDK options | `adaptiveStream: false`, `dynacast: true`, audio auto-subscribe on | `adaptiveStream` keys quality/pausing off attached-element visibility — incompatible with service-owned elements (would pause "invisible" video). `autoSubscribe: false` for audio risks a subscription bug meaning silence — the worst failure mode for a voice product. |
+| Client secrets | None of the new settings are `client: true` | URL + token reach the client only through the join response of rooms actually resolved to LiveKit. (Deliberately not repeating the TURN-credential-to-every-client pattern of `settings.yml:30–33`.) |
+
+## 3. Transport seam contract
+
+The exact call sites in `voice-webrtc.js` that branch on transport.
+`LivekitRoomSession` must satisfy the right-hand column.
+
+### Service → transport (outbound)
+
+| Call site (mesh today) | LiveKit branch |
+|---|---|
+| Peer create/destroy diff in `#handleParticipants` (~:1960–2012) → `#createAndOfferPeer` | None — SFU has no per-peer setup. Guard the block. **But** the roster diff still runs for livekit rooms to drop registry entries for identities absent from the roster (§5, ghost-participant rule). |
+| `#replaceTrackOnAllPeers(newTrack)` (~:2630) — NS toggle / mic switch / gate crossing | `session.replaceAudioTrack(newTrack)` → `LocalAudioTrack.replaceTrack()` |
+| `#syncVideoSenders` (~:1414) — per-watcher `replaceTrack` | `session.syncLocalVideo(videoTrack, screenAudioTrack, kind)` → publish/unpublish; receive gating moves to the subscriber side |
+| `#applyVideoQuality` / `#applyScreenAudioQuality` (~:1462, 1528) — mesh watcher-count bitrate ladder | Replaced by publish options + subscriber layer selection (§5, quality rules) |
+| `setWatching(roomId, watching)` (~:1141) — POST `/state` + publisher-side gating | Keep the POST (roster flags drive tiles on both transports) **plus** `session.setVideoSubscriptionsEnabled(watching)` |
+| `#reconnectAllPeers()` on role change (~:2248) | `session.refreshPublications()` — publish/release mic per new can-speak |
+| `leave()` → `#teardownRoom` (~:1704) | `session.disconnect()`, drop from session map. Existing peerManager/signaling teardown calls are no-ops for livekit rooms (empty maps) — no guards needed. |
+| `iceServers` / `iceTransportPolicy` getters (~:226–267) | Unused — LiveKit brings its own ICE/TURN. Getters stay mesh-only, unguarded. |
+
+### Transport → service (inbound) — the same callbacks PeerManager receives
+
+| LiveKit event | Service callback |
+|---|---|
+| `RoomEvent.TrackSubscribed(track, pub, participant)` | `#registerRemoteTrack(roomId, userId, track.mediaStreamTrack, streamsArg)` where `streamsArg = []` when `pub.source === ScreenShareAudio` — preserves the "bare audio track = screen audio" convention (~:2414) with zero change to `#registerRemoteTrack` — else `[participantStream]` |
+| `RoomEvent.TrackPublished` | Apply current watching state to the new publication: camera/screen/screen-audio publications created while `setWatching(false)` must start **unsubscribed**; microphone publications are always subscribed |
+| `RoomEvent.TrackUnsubscribed` / `ParticipantDisconnected` | `#removeRemoteStream(roomId, userId)` (~:2454) |
+| `RoomEvent.Disconnected(reason)` | `DUPLICATE_IDENTITY` → **local-only teardown** (§5); other terminal reasons → reconnect ladder (§7d), then `leave(room)` + toast |
+| `Reconnecting` / `Reconnected` | Log + tick `connectionRevision` |
+| `connect()` rejection | Client-unreachable-SFU failure path (§7f) |
+
+`userId` mapping: LiveKit `participant.identity` = `String(user.id)`. The
+session parses it back to a number before invoking callbacks so registry keys
+match roster participant ids — `remoteStreamFor(roomId, userId)`
+(video-tile.gjs) works unchanged.
+
+### Explicitly unchanged
+
+`lib/voice/peer-manager.js`, `lib/voice/signaling.js`,
+`room-message-queue.js`, all pipeline libs (`noise-suppression.js`,
+`input-gate.js`, `background-blur.js`, `audio-monitor.js`, `media-devices.js`,
+`ptt-manager.js`, `ptt-utils.js`, `sound-effects.js`), every component
+(call-controls, call-widget, room-page, video-tile, voice-canvas, chat-panel,
+settings modals, sidebar), all initializers, `voice-rooms.js`, and the whole
+public service API consumed by the UI
+(`join/leave/toggleMute/toggleDeafen/toggleCamera/toggleScreenShare/attachStream/attachVideoStream/remoteStreams/remoteScreenAudioStreams/remoteStreamFor/connectionStateFor/setWatching/canPublishVideo/videoAllowedIn/setInputDevice/setOutputDevice/setVideoInputDevice/localStream/localVideoStream/localVideoKind/audioEnabled/deafened/ptt*`).
+
+## 4. Server changes
+
+### Settings (`config/settings.yml`, after the TURN block)
+
+```yaml
+voice_livekit_url: # wss://livekit.example.com — empty = unavailable
+ default: ""
+voice_livekit_api_key:
+ default: ""
+voice_livekit_api_secret:
+ default: ""
+ secret: true
+voice_livekit_room_policy:
+ default: "disabled"
+ type: enum
+ choices: [disabled, per_room, all_rooms]
+ validator: "VoiceLivekitPolicyValidator"
+voice_livekit_room_prefix: # LiveKit room-name namespace override
+ default: ""
+voice_livekit_mesh_fallback: # opt-in: empty room + mint failure → pin mesh
+ default: false
+```
+
+None are `client: true`. `VoiceLivekitPolicyValidator` follows core's
+`lib/validators/*_validator.rb` convention: refuses any policy other than
+`disabled` unless `voice_livekit_url` (must be `ws://` or `wss://`),
+`voice_livekit_api_key`, and `voice_livekit_api_secret` are all present,
+with a specific translated error per missing field (`server.en.yml`). Admins
+get config-time failure, not first-join failure.
+
+`plugin.rb` serializes one Site attribute next to `voice_public_access`
+(plugin.rb:90): `voice_livekit_per_room_available` = configured **and**
+policy == `per_room`. It exists solely to gate the room-form checkbox — the
+client never needs the policy enum itself.
+
+### New: `lib/voice/livekit.rb`
+
+```ruby
+module Voice::Livekit
+ def self.configured? # url + key + secret all present
+ def self.available_for?(room) # configured? && (all_rooms || (per_room && room.livekit_enabled))
+ def self.room_name(room)
+ # default: "#{RailsMultisite::ConnectionManagement.current_db}-r#{room.id}"
+ # (room id, not slug — slugs are mutable); voice_livekit_room_prefix overrides the db prefix
+ end
+ def self.mint_token(user:, room:, guardian:) # HS256 JWT via core's `jwt` gem
+end
+```
+
+Token claims — least privilege, explicit:
+
+- `iss`: api key, `sub`: `user.id.to_s`, `name`: username, `exp`: now + 10 min
+- `video`: `room` = room_name, `roomJoin: true`, `canSubscribe: true`,
+ `canPublish` = `guardian.can_speak_in_voice_room?(room)`
+ (guardian_extension.rb:86–91), `canPublishSources` = mic always (when
+ canPublish) + `camera`/`screen_share`/`screen_share_audio` iff
+ `room.video_allowed?`, `canPublishData: false`,
+ `canUpdateOwnMetadata: false`, and explicitly `roomCreate: false`,
+ `roomList: false`, `roomAdmin: false`, `roomRecord: false`,
+ `recorder: false`, `hidden: false`.
+
+A leaked token can only join one room, as one user, for ≤10 minutes. Guardian
+remains the sole authority: tokens exist only for users who passed
+`ensure_can_join_voice_room!`. `voice_video_max_publishers` stays enforced
+where it is today (`rooms_controller#state`, rooms_controller.rb:207–210) —
+it's a roster-flag gate, transport-independent.
+
+### Transport pin: `app/services/voice/participant_tracker.rb`
+
+(NOT `lib/voice/` — the class lives in app/services, `KEY_NAMESPACE =
+"voice:room"`, `SAFETY_TTL = 30.minutes` at :5–7.)
+
+- New Redis key `voice:room:{id}:transport`; `pin_transport!(room_id,
+ transport)` uses `SET NX`; `pinned_transport(room_id)`;
+ `clear_transport_pin(room_id)`.
+- TTL = `2 × SiteSetting.voice_participant_ttl_seconds` (settings.yml:19,
+ default 30 s), refreshed on every join/heartbeat — a crashed room self-heals
+ in ~60 s instead of holding a stale transport.
+- Cleared explicitly when the room empties: on last leave in
+ `rooms_controller#leave`, with a backstop in
+ `Jobs::PublishRoomParticipants` (app/jobs/scheduled/publish_room_participants.rb),
+ which already sweeps recently-active rooms and can detect emptied ones.
+ Room-emptied cleanup also fires best-effort `delete_room` (below).
+
+### `app/controllers/voice/rooms_controller.rb`
+
+- **`#join`** (:95–128): before the presence add —
+ `transport = pinned || (Livekit.available_for?(room) ? "livekit" : "mesh")`;
+ pin it. Response gains `transport:` and, for livekit,
+ `livekit: { url:, token: }`. Mint failure handling per the §7 table.
+- **New `#livekit_token`** (`POST rooms/:id/livekit_token` in
+ `config/routes.rb`): `ensure_can_join_voice_room!` +
+ `RateLimiter.new(current_user, "voice-livekit-token", 10, 1.minute)`
+ (network-flap rejoins are the legitimate burst case). The endpoint
+ **re-adds presence + refreshes metadata itself** (same authz as heartbeat) —
+ it must not require existing Redis presence, because its one consumer is the
+ reconnect ladder that runs precisely when the 30 s presence TTL has lapsed.
+ If the pin is gone or re-resolved to mesh, return a distinct
+ `410 Gone` ("room instance ended") — the client stops the ladder, leaves
+ cleanly, and shows a rejoin toast.
+- **`#signal`** (:254): 422 when the room's pinned transport is livekit
+ (defense in depth).
+- **`#leave`**: clear the transport pin when the leaver was the last
+ participant.
+- **`#kick`** (:228): after the existing broadcasts, best-effort
+ `RoomServiceClient.remove_participant` (rescued + logged) — the client-side
+ `kicked` handler (~:2047) already forces leave; this evicts the media
+ session too.
+- **`#destroy`**: best-effort `delete_room`.
+
+### `app/controllers/voice/room_memberships_controller.rb`
+
+On role change in a livekit-pinned room, best-effort
+`RoomServiceClient.update_participant(permission: { can_publish: ... })` so a
+promoted stage listener can publish without reconnecting (client sees
+`ParticipantPermissionsChanged` → `refreshPublications()`). Fallback if the
+call fails: client re-mints via `livekit_token` and reconnects.
+
+### New: `lib/voice/livekit/room_service_client.rb` (~60 lines)
+
+Twirp-JSON POSTs — `RemoveParticipant`, `UpdateParticipant`, `DeleteRoom` — to
+`/twirp/livekit.RoomService/*` with a short-lived `roomAdmin` JWT bearer, via
+core HTTP conventions (`FinalDestination`/Excon). Timeout 2 s, always rescued:
+LiveKit being down must never fail a Discourse request. Every failure log
+prefixed `[voice-livekit]`.
+
+### Admin: emergency "End live call"
+
+Admin action (status panel or admin room list) that: calls `delete_room`,
+clears the transport pin, and iterates current participant ids publishing the
+**existing per-user `kicked` message** (`RoomBroadcaster#publish_kick`,
+room_broadcaster.rb:69–75) to each — zero client changes, `#handleKicked`
+already forces leave. Rejoining users re-resolve the transport. Also ship
+`rake voice:clear_transport_pins` for emergencies.
+
+### Admin health/diagnostics (own PR)
+
+1. Flipping LiveKit config enqueues a one-shot connectivity-probe job whose
+ result surfaces to the admin within seconds, not at first user join.
+2. `GET /admin/plugins/voice/livekit/status` (AdminConstraint) returns:
+ settings-present booleans (never values), a token self-mint check, a
+ RoomService `list_rooms` probe with latency + error string,
+ `last_webhook_at`, and currently pinned livekit rooms with a
+ Redis-presence vs LiveKit `list_participants` diff — the triage view for
+ "connects but no media" / ghost-participant support cases.
+3. Rendered as a card in `admin/assets/javascripts/admin/components/voice-dashboard.gjs`.
+4. A request spec asserts the API secret never appears in any serializer or
+ status payload.
+
+### Per-room policy surface
+
+- Migration: `add_column :voice_rooms, :livekit_enabled, :boolean,
+ default: false, null: false` (load `.skills/discourse-migration` first).
+- Permit `livekit_enabled` in both room param lists; expose on
+ `room_serializer.rb` to managers only. The live instance's transport is
+ never serialized — clients learn it at join.
+- `components/voice-room-form.gjs`: one FormKit checkbox ("Use media server
+ (SFU)") gated on `Site.voice_livekit_per_room_available`. Stale-form edge:
+ a form loaded before an admin flips policy can still submit
+ `livekit_enabled` — harmless (resolver re-checks policy at join); pin with a
+ request spec that the attribute is accepted-but-inert when policy no longer
+ allows it.
+
+### Webhooks (optional, PR 8 — reconcile-only)
+
+`POST /voice/livekit/webhook` (engine-scoped, skips CSRF + login), verifies
+the `Authorization` JWT (HS256, api key/secret) + SHA256 body hash. Handles
+`participant_left` **and** `participant_connection_aborted` by early-expiring
+Redis presence that LiveKit knows is gone (same removal path heartbeat-TTL
+uses); `room_finished` clears the transport pin. Every verified webhook
+`SETEX`es `voice:livekit:last_webhook_at` for the status panel (stale = warning,
+never error). Never creates presence; never touches `Session` rows —
+`CloseOrphanedSessions` remains the correctness backstop on both transports.
+
+## 5. Client changes
+
+### New: `lib/voice/livekit-session.js` (~350 lines)
+
+One instance per active LiveKit room, owned by the service, callback-injected
+in the same style as `PeerManager` (which is what makes it unit-testable):
+
+```js
+export default class LivekitRoomSession {
+ constructor({ roomId, currentUserId,
+ loadSdk, // async () => livekit-client module (injectable for tests)
+ getLocalStream, getLocalVideoTrack, getLocalScreenAudioTrack,
+ onTrack, // → #registerRemoteTrack
+ onParticipantGone, // → #removeRemoteStream
+ onDisconnected, // (reason)
+ onConnectionChange, // ticks connectionRevision
+ mintToken, // async () => ({ url, token }) — POST livekit_token
+ }) {}
+ async connect(wsUrl, token) // import SDK, new Room({ adaptiveStream: false, dynacast: true }), connect, publish current tracks
+ async disconnect()
+ async replaceAudioTrack(track)
+ async syncLocalVideo(videoTrack, screenAudioTrack, kind)
+ setVideoSubscriptionsEnabled(bool) // + TrackPublished handler applies it to late publications
+ async refreshPublications() // re-evaluate mic publish after role change
+ async reconnectWithToken() // ladder: 3 attempts, backoff, mintToken() each round
+ static isBrowserSupported() // SDK support check; unsupported → translated toast, not an opaque SDK error
+}
+```
+
+Default `loadSdk`:
+`import(getURL("/plugins/voice/javascripts/livekit/livekit-client.mjs"))` —
+never evaluated for mesh rooms.
+
+**Publish rules**
+- Mic: `publishTrack(localStream.getAudioTracks()[0], { source: Microphone,
+ dtx: true, red: true })`. The pipeline's AudioWorklet-destination tracks
+ publish cleanly — LiveKit accepts arbitrary `MediaStreamTrack`s. Mute/PTT
+ keep flipping `track.enabled`, untouched.
+- Camera: `{ source: Camera, simulcast: true, videoEncoding: <720p preset,
+ maxFramerate 24> }`; screen: `{ source: ScreenShare, simulcast: true,
+ screenShareEncoding: <maxFramerate 15> }` — mirror the capture-time caps and
+ contentHints currently set around ~:1279–1287, else SDK defaults apply.
+ Screen audio: `{ source: ScreenShareAudio }` + 128 kbps.
+- Publish mic only when the user can speak (stage rooms) — mirrors
+ `#canSpeakInRoom` (~:335); token grants enforce it server-side regardless.
+
+**Subscribe/quality rules** (replaces the mesh bitrate ladder — do not skip;
+with `adaptiveStream: false` the SDK defaults every subscription to the HIGH
+simulcast layer, which would regress downlink vs the mesh's 400 kbps ladder in
+big rooms):
+- Screenshare subscriptions: `setVideoQuality(HIGH)`.
+- Camera subscriptions: MEDIUM by default; LOW when the room has more than ~6
+ active video publishers (same threshold the mesh ladder uses at ~:1462).
+ Re-evaluate on publisher-count changes; the service already tracks
+ `videoPublisherCount(roomId)`.
+- `setWatching(false)` unsubscribes camera/screen/screen-audio publications;
+ mic publications are **always** subscribed. Late publications (published
+ while not watching) must be created unsubscribed via the `TrackPublished`
+ handler.
+
+**Disconnect handling**
+- `DUPLICATE_IDENTITY` (same user joined from a newer tab): **local-only
+ teardown** — session disconnect + client state cleanup that explicitly
+ **skips `DELETE /leave`**. A normal `leave()` here would close the *new*
+ tab's `Session` row (its id just overwrote `metadata[:session_id]` —
+ rooms_controller.rb:377–384), drop the user from the roster until the next
+ heartbeat, and clear their user status. Implement as an option on `leave`
+ (e.g. `leave(room, { skipServer: true })`) or a dedicated local teardown.
+ Unit test must assert no DELETE is issued.
+- Other terminal reasons / mid-call hard-down: reconnect ladder — up to 3
+ attempts with backoff, each awaiting a fresh `mintToken()`; on `410 Gone`
+ stop immediately, local teardown + rejoin toast; after exhaustion,
+ `leave(room)` + toast.
+
+### Modified: `app/services/voice-webrtc.js` (~200-line diff, all additive/guarded)
+
+1. State: `#roomTransports = new Map()` (roomId → transport, default `"mesh"`
+ when untagged so pre-tag messages/tests/old servers behave identically),
+ `#livekitSessions = new Map()`, helper `#isMeshRoom(roomId)`.
+2. `join(room)` (~:357): read `data.transport ?? "mesh"` and `data.livekit`
+ from the join response. After mic acquisition and the active-mark (~:463),
+ for livekit: `LivekitRoomSession.isBrowserSupported()` check, construct +
+ `connect(url, token)`. **On connect failure: fire
+ `ajax(.../leave, { type: "DELETE" })` before `#handleJoinFailure(room.id)`**
+ — the exact precedent of the mic-failure path at ~:431–437; otherwise the
+ user ghosts in the roster for the presence TTL and the Session row dangles.
+ Distinct translated toast ("your network cannot reach the voice server" —
+ different from the server-side mint-failure copy) + `[voice-livekit]`
+ console log. **No mesh fallback client-side ever** — other clients may
+ reach the SFU fine; falling back would split future joins.
+3. `#processRoomMessage` (~:1735): `signal` case early-returns for livekit
+ rooms.
+4. `#handleParticipants` (~:1941): guard the peer create/destroy block and
+ presence-pending machinery as mesh-only. Roster sync, join/leave sounds,
+ `#syncRemoteVideoTracks`, `#syncVideoSenders` stay common. **Livekit
+ ghost-participant rule**: for livekit rooms the roster diff additionally
+ drops registry entries (calls `#removeRemoteStream` and unsubscribes) for
+ identities absent from the roster — mesh gets this for free by destroying
+ the peer; without it, a participant expelled from the roster (heartbeat TTL
+ expiry, kick with failed `RemoveParticipant`) stays audible forever because
+ voice-canvas plays every stream in `remoteStreams`.
+5. `#handleRoleChange` (~:2090): mesh → existing `#reconnectAllPeers`; livekit
+ → mic acquire/release per new role + `session.refreshPublications()`.
+6. `#replaceTrackOnAllPeers` (~:2630): prepend fan-out to `#livekitSessions`;
+ the existing sender loop is a natural no-op for livekit rooms.
+7. `#syncVideoSenders` (~:1414) / `#broadcastVideoState` (~:1542): livekit
+ rooms delegate to `session.syncLocalVideo(...)`; the `POST /state`
+ broadcast stays identical on both transports.
+8. `setWatching` (~:1141): after the existing POST, call
+ `session.setVideoSubscriptionsEnabled(watching)` for livekit rooms.
+9. `leave` (~:512) / `#teardownRoom` (~:1704): disconnect + delete session;
+ support the `skipServer` local-only variant.
+10. Inbound wiring: bind session callbacks to `#registerRemoteTrack` /
+ `#removeRemoteStream` exactly as PeerManager is bound (~:137–141); add the
+ disconnect-reason handler.
+
+**Not touched**: `#handleSignal`, glare/ufrag logic, `#createAndOfferPeer`,
+`#shouldEngagePeer`, `iceServers`, PeerManager/SignalingManager construction,
+the entire local audio/video pipeline, remote registry internals,
+attach/volume/deafen/PTT/idle/audio-monitor code.
+
+### New: vendored SDK + build script
+
+- `public/javascripts/livekit/livekit-client.mjs` — single-file ESM bundle of
+ pinned `livekit-client` v2.x, built by new `scripts/build-livekit-bundle.sh`
+ (esbuild or webpack — webpack is already a devDependency) and checked in,
+ exactly like `dtln-worklet.js`.
+- `package.json`: `livekit-client` as **devDependency only** (build-time
+ input, never in the app graph) + a `build:livekit` script.
+- CI grep guard: no static import of `public/javascripts/livekit/` anywhere
+ under `assets/` — converts "zero LiveKit bytes on the P2P path" from a
+ review-time promise into a regression-tested invariant.
+
+## 6. Transport resolution
+
+Server-only, at join:
+
+```
+pinned = redis GET voice:room:{id}:transport
+if pinned → use pinned
+elsif Livekit.available_for?(room) → "livekit", pin
+else → "mesh", pin
+```
+
+- **All participants share one transport** — guaranteed by the pin; joiners
+ after the first ignore current settings. No client-side choice, no mixed
+ room, ever.
+- **Config changes affect only the next room instance** (first join after the
+ room empties / pin expires). Live calls are never migrated or split. Setting
+ descriptions state this explicitly. Emergency levers: admin "End live call",
+ `rake voice:clear_transport_pins`.
+
+## 7. Failure-mode policy
+
+| # | Failure | Behavior |
+|---|---|---|
+| a | Token mint fails, room EMPTY | Join fails: specific translated toast ("Voice server unavailable — contact your administrator"), `[voice-livekit]` log, status panel red. If `voice_livekit_mesh_fallback` is on (opt-in — silent degradation hides outages from ops) **and the room is empty**, pin mesh for this call and proceed. |
+| b | Token mint fails, room OCCUPIED on livekit | Join fails with the same toast. Never fall back — would split the call. |
+| c | Mid-call SFU blip | SDK auto-resume; heartbeats keep presence/sessions/badges unaffected throughout. |
+| d | Mid-call SFU hard-down | Reconnect ladder: 3 token-refetch attempts with backoff via `livekit_token`; then `leave()` + toast. |
+| e | Webhooks undeliverable | Zero correctness impact; status panel shows stale `last_webhook_at` as a warning. |
+| f | Mint succeeds but the CLIENT can't reach the SFU (corporate firewall blocking WSS/UDP — the most common enterprise failure) | Distinct toast ("your network cannot reach the voice server"), immediate `DELETE /leave` cleanup, `[voice-livekit]` console log. **No mesh fallback even under (a)'s setting** — other clients may reach the SFU fine. |
+| g | Pin says livekit, config half-deleted | Same as (a)/(b) — 503 with clear error; validator (§4) makes this hard to reach. |
+| h | Reconnect ladder finds pin gone/re-resolved (room instance ended while client slept) | `livekit_token` returns `410 Gone`; client stops the ladder, local teardown, rejoin toast. |
+
+## 8. Feature preservation matrix
+
+| Feature | Mesh mechanism | On LiveKit | Change |
+|---|---|---|---|
+| Mute | `track.enabled` + `/state` metadata | Identical (DTX silence through SFU) | None |
+| Deafen | Element-level `muted` on all sinks + mic force-mute | Identical — same service-owned elements | None |
+| PTT / input gate | `track.enabled` flips (~:2767); WebAudio gate → `#replaceTrackOnAllPeers` | Identical; fan-out extended | 1 branch |
+| DTLN noise suppression | Worklet pipeline → new track → `#replaceTrackOnAllPeers` | Same pipeline; `replaceAudioTrack` | Same branch |
+| Mic/output device switch | New gUM → replaceTrack / `setSinkId` on elements | Same; output path untouched | Same branch |
+| Background blur / camera switch | Canvas `captureStream()` → `localVideoStream` → `#syncVideoSenders` | Same processed track via `publishTrack` | `syncLocalVideo` |
+| Video on/off + publisher cap | `/state` flag + controller cap | Identical flag + cap; camera grant in token per `video_allowed?` | `syncLocalVideo` |
+| Screenshare + screen audio | Pre-negotiated 2nd transceiver; bare-track convention (~:2414) | `ScreenShare(+Audio)` sources; empty `streams` arg preserves the convention | Session only |
+| `setWatching` receive gating | Publisher-side per-peer replaceTrack + bitrate ladder | Subscriber-side `setSubscribed` + explicit layer selection (§5) | `setVideoSubscriptionsEnabled` |
+| Speaking indicators | `AudioMonitor` AnalyserNode on registry streams | Identical (LiveKit `ActiveSpeakersChanged` deliberately unused — one code path) | None |
+| Per-participant volume/mute | Element `volume`/`muted` maps | Identical | None |
+| Sound effects / autoplay recovery | Roster-diff driven | Identical (roster from MessageBus on both) | None |
+| Idle/AFK/auto-status | IdleTracker + heartbeat piggyback | Identical | None |
+| Stage rooms | Peering rules + `/state` unmute enforcement | Token `canPublish` + same `/state` enforcement; promotion → `UpdateParticipant` + `refreshPublications` | Role branch |
+| Kick | `kicked` MessageBus → client leave | Same + best-effort `RemoveParticipant` | Server call |
+| Reconnection | PeerManager restarts/backoff/ICE-restart | SDK resume → ladder (§7d) | Session |
+| Multi-tab | Undefined-ish (mesh peers keyed by userId collide) | Deterministic: `DUPLICATE_IDENTITY` drops the older tab via **local-only** teardown. Documented improvement, unit-tested | Handler |
+| Sessions/badges/co-presence/stats/user status | REST + jobs | **Identical — transport never touches them** | None |
+| Anon directory viewing | MessageBus + serializers | Identical (anons never get tokens) | None |
+
+## 9. Implementation phases (PR-sized, independently shippable)
+
+Order: 1 → 2 → 3 strictly sequential; 4/5/6 parallelizable after 3; 7/8/9
+last. Run `bin/lint --fix` on every change; JS tests run via CI.
+
+**PR 1 — P2P-only seam tagging (zero behavior change).**
+`voice-webrtc.js`: `#roomTransports`/`#isMeshRoom` defaulting mesh; guard
+the peer-build block in `#handleParticipants`, the `signal` dispatch, and
+`#handleRoleChange`'s rebuild; read `data.transport ?? "mesh"` in `join`.
+`rooms_controller.rb`: join response gains `transport: "mesh"`.
+*Acceptance*: entire existing JS suite (`voice-webrtc-test.js`,
+`peer-manager-test.js`, `signaling-test.js`), integration `.gjs` tests, and
+system specs pass **unmodified**; diff has no deletions of mesh logic.
+
+**PR 2 — Server: settings, validator, resolver, tokens, pin.**
+`settings.yml` + locales, `lib/validators/voice_livekit_policy_validator.rb`,
+`lib/voice/livekit.rb`, pin helpers in
+`app/services/voice/participant_tracker.rb`, `rooms_controller.rb`
+(resolution, join payload, `livekit_token` with presence re-add + rate limit +
+410 semantics, signal guard, pin-clear on last leave),
+`Jobs::PublishRoomParticipants` backstop, `config/routes.rb`, `plugin.rb`
+Site attr, request specs.
+*Acceptance*: LiveKit unconfigured → join responses byte-identical plus
+`transport: "mesh"`. Token decodes to the full §4 claim set across the
+guardian × room_type × video matrix (stage listener → `canPublish: false`;
+video-off room → no camera source; anon → no token path). Pin lifecycle spec:
+set on first join (NX under race), held across config change, cleared on
+empty, ~60 s expiry after crash, `livekit_token` works without presence and
+410s when the pin is gone. Mint failure follows §7a/b including the
+mesh-fallback setting. Secret never appears in any payload.
+
+**PR 3 — Client: vendored SDK + LivekitRoomSession, audio-only calls.**
+`scripts/build-livekit-bundle.sh`, checked-in bundle, package.json devDep,
+`lib/voice/livekit-session.js`, `voice-webrtc.js` (join/connect path with
+DELETE-/leave-on-failure, `#replaceTrackOnAllPeers` fan-out, leave/teardown +
+`skipServer`, disconnect-reason handling, ghost-participant roster rule), unit
+tests with a fake SDK injected via `loadSdk`.
+*Acceptance*: mesh tests untouched and green. LiveKit unit tests prove: SDK
+never loaded for mesh rooms (spy on `loadSdk`); mic published post-join; NS
+toggle → `replaceAudioTrack`; `TrackSubscribed` populates
+`remoteStreams`/`remoteStreamFor` with numeric userId keys; screen-audio
+convention preserved; `DUPLICATE_IDENTITY` → local-only teardown **with no
+DELETE /leave issued**; connect failure → DELETE /leave + join-failure path;
+roster expulsion drops the participant's media; reconnect ladder stops on 410.
+CI grep guard on static imports in place.
+
+**PR 4 — Client: video, screenshare, watching, quality, role change.**
+`livekit-session.js` (`syncLocalVideo`, `setVideoSubscriptionsEnabled` +
+`TrackPublished` late-publication handling, subscriber layer selection,
+publish encoding presets, `refreshPublications`), service branches
+(`#syncVideoSenders`/`#broadcastVideoState`/`setWatching`/`#handleRoleChange`).
+*Acceptance*: camera toggle publishes with simulcast + encoding preset and
+POSTs `/state` identically to mesh; screenshare lands in
+`remoteScreenAudioStreams`; `setWatching(false)` unsubscribes, and a camera
+published afterwards starts unsubscribed until `setWatching(true)`; layer
+selection: >6 publishers → LOW tiles, screenshare stays HIGH; role promotion
+publishes mic without reconnect. Mesh video tests untouched.
+
+**PR 5 — Server: moderation/lifecycle sync.**
+`lib/voice/livekit/room_service_client.rb` (3 Twirp calls),
+`rooms_controller#kick`/`#destroy`, `room_memberships_controller.rb`, "End
+live call" admin action (per-user `publish_kick` loop + `delete_room` + pin
+clear), `rake voice:clear_transport_pins`, WebMock specs.
+*Acceptance*: kick/role change/destroy fire Twirp calls on livekit-pinned
+rooms; LiveKit downtime never fails a Discourse request; mesh rooms make zero
+HTTP calls; End-live-call empties a room using only existing client message
+types.
+
+**PR 6 — Per-room policy surface.**
+Migration (load `.skills/discourse-migration` first), `room.rb`, serializer,
+both param permit lists, `voice-room-form.gjs` FormKit checkbox gated on
+`Site.voice_livekit_per_room_available`, locales.
+*Acceptance*: checkbox visible only when configured + policy `per_room`;
+toggling mid-call doesn't affect the live instance (pin precedence spec);
+stale-form submit is accepted-but-inert when policy changed; mesh-only
+installs see no form change.
+
+**PR 7 — Real-LiveKit testing, docs, runbook.**
+`spec/system/voice_livekit_spec.rb` (two-browser camera flow mirroring
+`voice_voice_rooms_spec.rb`, gated on `ENV["VOICE_LIVEKIT_TEST_URL"]`,
+docs show `docker run livekit/livekit-server --dev`); verify
+`voice_fake_media.rb` fakes satisfy the SDK (expected no-op — livekit-client
+uses `navigator.mediaDevices` and we publish our own tracks);
+`docs/local-fake-participants.md`, `README.md`, `ARCHITECTURE.md` updates;
+§10 runbook as an ops doc including CSP note; manual Safari + iOS/Android
+checklist (join, hear audio, publish camera, receive screenshare, reconnect
+after backgrounding — livekit-client has real platform nuances: H.264 vs VP8
+simulcast on Safari, autoplay vs service-owned elements);
+`isBrowserSupported()` guard wired to a translated toast; voice-bots README
+PR in the external repo (WSS/UDP egress; the "≥2 bots per room" mesh
+workaround does not apply to livekit rooms).
+*Acceptance*: gated system spec green against a dev container locally;
+ungated CI unchanged.
+
+**PR 8 (optional) — Webhook reconciliation.** Controller + route + verifier +
+specs per §4. *Acceptance*: signature/body-hash rejection paths;
+`participant_left`/`participant_connection_aborted` early-expire stale
+presence; `room_finished` clears the pin; `last_webhook_at` freshness marker;
+no effect on Session rows beyond existing TTL behavior.
+
+**PR 9 (optional) — Admin health panel.** Probe job, status endpoint,
+dashboard card, `[voice-livekit]` log audit, secret-never-serialized spec,
+per §4.
+
+## 10. Enterprise deployment runbook (sketch — full version ships in PR 7)
+
+1. Provision: 2–4 cores is ample (audio ≈ hundreds of participants/core,
+ 720p ≈ ~100 tracks/core). Run `livekit/livekit-server` (Docker or binary)
+ with one `key: secret` API pair, `use_external_ip: true` behind NAT,
+ `webhook.urls: [https://forum.example/voice/livekit/webhook]` if PR 8 is
+ deployed. Single node — no Redis needed; each room must fit one node.
+2. Network: reverse proxy (WebSocket upgrade + long timeouts) → 7880 as
+ `wss://livekit.example.com`; open 7881/TCP (ICE-TCP fallback) and the UDP
+ range; optionally embedded TURN on 443/TLS with its own hostname + cert.
+ Classic failure: "connects but no media" = missing
+ `use_external_ip`/firewalled UDP — check first. If a CSP is enforced at the
+ proxy in front of **Discourse**, `connect-src` must include the LiveKit wss
+ host (Discourse core currently emits no connect-src of its own — but see
+ risk 8).
+3. Discourse: set `voice_livekit_url` / `_api_key` / `_api_secret`; pick
+ `voice_livekit_room_policy`. Mesh rooms keep using the existing
+ STUN/TURN settings.
+4. Verify: PR 9's status panel, or join a livekit room from two networks and
+ confirm `transport: "livekit"` in the join response + a single PC to the
+ SFU in `chrome://webrtc-internals`.
+5. Operations: settings changes apply to the next room instance; force-flip a
+ live room via "End live call" or `rake voice:clear_transport_pins`. If
+ the SFU dies mid-call, clients run the reconnect ladder; presence/analytics
+ keep working (heartbeats are Discourse-side).
+6. Multisite / shared cluster: one API key pair per site; each site's webhook
+ URL listed in the LiveKit config; room names are DB-prefixed by default as
+ defense in depth.
+7. Upgrades: the client SDK bundle is pinned in-repo (`build:livekit` bumps
+ it); document the tested server version range in README.
+
+## 11. Risks
+
+1. **Vendored SDK ↔ server protocol drift** — pin + document the tested server
+ range; bumps are one-commit affairs via the build script.
+2. **`track.enabled` mute through SFU** — silence frames still consume (tiny,
+ DTX-suppressed) upstream. Accepted for path parity; SFU-side `setMuted` is
+ a later optimization behind the same seam.
+3. **Watcher-gating semantics shift** — mesh gates at the publisher
+ (non-watchers cost the publisher nothing); LiveKit publishes once
+ regardless. Publisher upstream is constant (the point of an SFU), but the
+ `voice_video_max_publishers` copy ("increases CPU for everyone") is wrong
+ for livekit rooms — locale nuance in PR 7.
+4. **Role-change permission race** — if `UpdateParticipant` fails and the
+ client publishes before re-mint, the SFU rejects the publish. Mitigation:
+ `refreshPublications` retries after `reconnectWithToken`; the `/state`
+ unmute rule still gates the roster flag.
+5. **`connectionStateFor` fidelity** — LiveKit `Reconnecting` doesn't surface
+ as `"connecting"` (mesh doesn't surface per-peer trouble either — parity,
+ not regression). Candidate follow-up.
+6. **Pinned-livekit + broken config = room unjoinable by design** — never
+ split a room; validator + runbook + explicit error copy mitigate.
+7. **Multi-tab behavior changes on livekit** (older tab drops
+ deterministically) — an improvement over mesh's undefined collision, but
+ document it and keep the local-only-teardown unit test.
+8. **Core CSP roadmap** — core plans to promote `connect_src` to an
+ extendable default directive (`lib/content_security_policy/builder.rb`
+ currently no-ops plugin connect_src extensions). When that lands, the
+ plugin must register a CSP extension for the configured
+ `voice_livekit_url` host or every LiveKit install breaks on a core
+ upgrade. Track it; cheap now, expensive to discover later.
+
+## 12. Open questions (product)
+
+1. Should `all_rooms` also cover audio-only rooms while `voice_video_enabled`
+ is off? Design says yes — audio-only is the cheapest LiveKit workload.
+2. Adopt LiveKit `ActiveSpeakersChanged` for speaking indicators on livekit
+ rooms eventually (saves N AudioContexts in large rooms)? Deferred — forks
+ the indicator path.
+3. Egress/HLS "broadcast stages" — confirm the room-name scheme now
+ (`{db}-r{id}`) so egress can key off it later.
+4. voice-bots at SFU scale: a lone bot *does* transmit to an SFU (the mesh
+ "≥2 bots" workaround is obsolete there) — downsize bot rosters for livekit
+ demo rooms?
diff --git a/plugins/voice/docs/roadmap/smart-notifications.md b/plugins/voice/docs/roadmap/smart-notifications.md
new file mode 100644
index 00000000000..cdc8b2daf69
--- /dev/null
+++ b/plugins/voice/docs/roadmap/smart-notifications.md
@@ -0,0 +1,107 @@
+# Smart Notifications
+
+## Overview
+
+Alert users when their frequent voice contacts join rooms. Uses co-presence
+data from the analytics system (see `analytics.md`) to determine relationship
+strength.
+
+## Prerequisites
+
+- Session tracking (analytics Phase 1) — `voice_sessions` table.
+- Co-presence tracking (analytics Phase 2) — `voice_co_presences` table.
+
+## "Your frequent contact joined a room"
+
+**Trigger:** A user joins a room.
+
+**Logic (in `RoomsController#join`, after recording the session):**
+
+1. Query the joining user's top contacts from `voice_co_presences`
+ (cached — see below).
+2. For each top contact who is currently online (Discourse presence) but NOT
+ in any voice room:
+ - Check if the room the user just joined is one the contact frequents
+ (from `voice_sessions` aggregation, also cached).
+ - If both conditions met (strong relationship + familiar room), send a
+ notification.
+
+**Notification content:**
+> "Alice joined Watercooler — you two have chatted 12 times this month"
+
+**Delivery:** Discourse MessageBus push to the contact's browser → rendered as
+a toast notification with a "Join" action button.
+
+## Caching strategy
+
+Computing top contacts and frequent rooms on every join would be expensive.
+
+- **Top contacts per user:** Cache in Redis as a sorted set
+ `voice:contacts:{user_id}` with score = aggregated `total_seconds` over
+ the last 30 days. Refresh every hour via a scheduled job, or invalidate
+ when `UpdateCoPresence` runs.
+- **Frequent rooms per user:** Cache as `voice:frequent_rooms:{user_id}`.
+ Refresh daily or on session close.
+- **Notification cooldown:** Don't notify the same user about the same contact
+ more than once per hour. Track in Redis:
+ `voice:notified:{user_id}:{contact_id}` with 1h TTL.
+
+## Thresholds
+
+Not every co-presence should trigger notifications. Minimum thresholds:
+
+- **Minimum co-presence time:** 30 minutes total within the lookback window
+ (avoids noise from one-time encounters).
+- **Minimum sessions:** 3 within the lookback window (avoids a single long
+ session skewing results).
+- **Recency lookback window:** 30 days (only co-presence rows with
+ `date >= today - 30 days` are considered — stale relationships naturally
+ drop out).
+- **Room familiarity:** Contact has visited the room at least twice in the
+ last 30 days (don't notify about unfamiliar rooms).
+
+All thresholds configurable via site settings.
+
+## Site settings
+
+```yaml
+voice_smart_notifications_enabled:
+ default: true
+
+voice_co_presence_min_seconds:
+ default: 1800
+ description: "Minimum co-presence time (seconds) before a relationship is considered for notifications"
+
+voice_co_presence_min_sessions:
+ default: 3
+
+voice_smart_notification_cooldown_minutes:
+ default: 60
+ min: 10
+ max: 1440
+```
+
+## User preferences
+
+Users can control notification behavior from their Discourse notification
+preferences (or a Voice-specific section):
+
+- **Enable/disable** smart room notifications (default: enabled).
+- **Quiet hours** — respect Discourse's existing Do Not Disturb setting.
+
+No per-contact granularity in the first version — either on or off globally.
+
+## Implementation plan
+
+1. Implement notification logic in room join flow.
+2. Add Redis caching for contacts and frequent rooms.
+3. Add notification cooldown.
+4. Add user preference toggle.
+5. Frontend toast with "Join" action button.
+
+## Privacy considerations
+
+- Smart notifications respect Discourse's existing block/ignore system — if
+ user A has blocked user B, no notifications are sent in either direction.
+- Co-presence data is symmetric — if Alice can see Bob as a top contact, Bob
+ can see Alice. There is no way to silently track someone.
diff --git a/plugins/voice/docs/roadmap/video-screenshare.md b/plugins/voice/docs/roadmap/video-screenshare.md
new file mode 100644
index 00000000000..7b664d894f7
--- /dev/null
+++ b/plugins/voice/docs/roadmap/video-screenshare.md
@@ -0,0 +1,371 @@
+# Video & Screen Sharing
+
+> **Revision note (2026-06-12):** this doc supersedes the original draft. Two
+> core decisions changed after a deep read of the WebRTC layer:
+>
+> 1. **Media strategy** — the original plan relied on `addTrack()` +
+> `onnegotiationneeded` renegotiation. The codebase has _no_ renegotiation
+> path (no `onnegotiationneeded` handler; glare handling, the ufrag restart
+> heuristic, and answer-state guards all assume one-shot negotiation at peer
+> setup). The new design pre-allocates video transceivers at peer creation
+> and toggles video with `replaceTrack()` — zero renegotiation, matching the
+> pattern noise suppression already uses.
+> 2. **UI** — a dedicated full-page room view (sidebar stays) replaces the
+> sliding video panel. Simpler, deep-linkable, and it doubles as the
+> subscription signal for who should receive video at all.
+>
+> Also new: a **per-room `video_enabled` toggle** and **subscription-gated
+> sending**, which raises the practical mesh ceiling well above the original
+> 3–5 stream estimate.
+
+## Overview
+
+Add optional camera video and screen sharing to voice rooms, staying **pure
+full-mesh P2P** — no SFU, no media through the server. Joining a room remains
+audio-first; video is something you opt into by opening the room's dedicated
+page and turning on your camera.
+
+Bandwidth is explicitly _not_ the constraint we design for (entry-level
+broadband upload is now in the hundreds of Mbps). The binding constraints are:
+
+- **CPU encoder sessions** — in a mesh, each `RTCPeerConnection` runs its own
+ independent video encoder. A participant sending video to 8 watchers runs 8
+ simultaneous encodes.
+- **Decode + render cost** on the receiving side, especially mobile.
+
+Both are attacked with the mesh topology's unique lever: every receiver has a
+dedicated sender, so we can decide **per peer** whether to send video at all,
+and at what resolution/bitrate. An SFU can't do better than simulcast here;
+mesh gets per-link adaptation natively.
+
+## Goals / non-goals
+
+**Goals**
+
+- Camera video and screen share in Open rooms, full mesh.
+- Dedicated room page with a video grid; Discourse sidebar (and the rooms
+ section in it) stays visible.
+- Audio experience is never degraded or destabilized by the video feature.
+- Per-room and site-wide opt-in.
+
+**Non-goals (for now)**
+
+- SFU integration (future, separate effort).
+- Video in Stage rooms (speakers-only video is a follow-on).
+- Recording, virtual backgrounds, reactions overlay.
+
+## Facts about the current architecture that shape the design
+
+From `voice-webrtc.js`, `peer-manager.js`, `signaling.js`:
+
+- **Negotiation is one-shot.** Offers/answers happen at peer setup. Glare is
+ resolved by user-ID ordering only during setup; answers in unexpected
+ signaling states are dropped; a changed ICE ufrag means "peer restarted —
+ tear down and rebuild" rather than "renegotiate".
+- **Mid-call media changes never renegotiate.** Noise suppression swaps the
+ outgoing audio track with `sender.replaceTrack()`
+ (`#replaceTrackOnAllPeers`); role changes rebuild peers wholesale
+ (`#reconnectAllPeers`).
+- **The signal relay is payload-opaque.** SDP with video m-lines flows through
+ `POST /voice/rooms/:id/signal` unchanged. No server work needed for media.
+- **Presence metadata is a free-form per-participant hash** in Redis
+ (`ParticipantTracker`), already carrying `is_muted` / `is_deafened` /
+ `idle_state`, broadcast via `RoomBroadcaster.publish_participants`. Video
+ flags slot straight in.
+- **Call state lives in the `voice-webrtc` service**, independent of routes —
+ which is why audio survives navigation today, and why a video _page_ can be
+ a pure view over service state.
+
+## Media plan: pre-allocated transceivers + `replaceTrack`
+
+### Peer setup
+
+At `PeerManager.create()`, alongside the existing audio `addTrack` calls, both
+sides add a video transceiver:
+
+```javascript
+pc.addTransceiver("video", { direction: "sendrecv" });
+```
+
+The video m-line is negotiated **once**, in the same initial offer/answer that
+already works. An idle negotiated video sender transmits nothing, so
+audio-only rooms pay no bandwidth or CPU cost.
+
+**Answerer alignment (JSEP gotcha).** Applying a remote offer only reuses
+local transceivers created via `addTrack` — never ones from `addTransceiver`,
+which are reserved for the local side's next offer. Left alone, the answerer
+gets a fresh `recvonly` transceiver for the offered video m-line and its
+pre-allocated transceiver is orphaned, so the answerer can receive video but
+never send it (one-directional video, surfaced as "the offerer's camera works,
+the answerer's doesn't"). Between `setRemoteDescription(offer)` and
+`createAnswer()`, the answerer therefore flips the associated transceiver's
+direction to `sendrecv` (the answer then carries it — still no renegotiation)
+and migrates any camera track off the orphan. Audio is unaffected because
+audio tracks go through `addTrack` and are reused per spec.
+
+### Camera on/off
+
+- **On:** acquire a _separate_ camera stream with its own
+ `getUserMedia({ video: ... })` call — never re-acquire or touch the mic
+ stream, so the noise-suppression chain is untouched — then
+ `transceiver.sender.replaceTrack(cameraTrack)` on each peer that should
+ receive video (see subscription gating below).
+- **Off:** `replaceTrack(null)` everywhere, stop the camera track (releases
+ the camera light), broadcast the state change.
+
+No renegotiation, no new signaling messages, no glare risk, ever.
+
+### Required fixes this surfaces
+
+1. **Per-user stream registry.** `#registerRemoteStream` keeps one stream per
+ user and _replaces_ it when a different stream arrives. With
+ `addTransceiver`, the incoming video track has no associated stream
+ (`event.streams` is empty), so the current `ontrack` fallback would create
+ a video-only `MediaStream` that clobbers the user's audio entry. Fix:
+ maintain one `MediaStream` per remote user and `addTrack()` incoming tracks
+ into it (or store `{ audioStream, videoStream }` per user).
+2. **Restart path must restore video.** `PeerManager.restart()` rebuilds the
+ peer from `getLocalStream()`. Centralize an "attach current local media"
+ step (audio tracks + video transceiver + current camera track if the peer
+ is a subscriber) used by both `create()` and restart.
+3. **UI must not key off `ontrack` for video.** The remote video track arrives
+ muted at initial negotiation, long before any camera turns on. Drive tile
+ visibility from the `is_video_on` presence flag (authoritative) plus the
+ track's `mute`/`unmute` events (frame-accurate).
+
+### Legacy peers
+
+Connections negotiated before this ships have audio-only SDPs with no video
+m-line. If a user enables camera against such a peer, fall back to the
+existing sledgehammer: the `#reconnectAllPeers`-style rebuild that role
+changes already use. Transitional code only.
+
+## Subscription-gated sending (the mesh superpower)
+
+Senders only attach the camera track toward peers who are **watching** — i.e.
+currently on the room's video page. Everyone else's sender keeps a null track.
+
+- Each non-watching peer skipped saves the sender an **entire encoder
+ session**, not just bandwidth.
+- The signal is free: entering/leaving the room page flips a `watching_video`
+ flag in presence metadata, which already broadcasts to the room.
+- Sidebar-only listeners (today's default UX) cost video senders nothing.
+
+This is what raises the practical ceiling from the old "3–5 video streams" to
+"~8 publishers, bounded by who is actually watching".
+
+## Quality budget
+
+Capture once at 720p; downscale per sender with
+`sender.setParameters({ encodings: [{ maxBitrate, scaleResolutionDownBy, maxFramerate }] })`,
+scaled by **watcher count**:
+
+| Watchers | Per-peer encoding | Upload @ 8 watchers | Encodes |
+| -------- | ----------------- | ------------------- | ------- |
+| ≤ 3 | 720p @ ~1.2 Mbps | — | ≤ 3 |
+| 4–6 | 480p @ ~700 kbps | ~3.5 Mbps | 4–6 |
+| 7+ | 360p @ ~400 kbps | ~2.8 Mbps | 7+ |
+
+Plus:
+
+- `track.contentHint = "motion"` (camera) / `"detail"` (screen share);
+ `degradationPreference: "maintain-framerate"` for camera.
+- Frame-rate caps: 24 fps, 15 fps in large rooms; screen share 15 fps.
+- Mesh gives per-link adaptation for free: each `RTCPeerConnection`'s
+ bandwidth estimator adapts to _that_ peer's downlink independently — one
+ weak peer never degrades what others receive. (This is the mesh-native
+ equivalent of simulcast; simulcast itself is an SFU mechanism and does not
+ apply.)
+- A user-selectable quality profile (High/Medium/Low, persisted in
+ `localStorage`) remains useful as a manual override for weak _sending_
+ hardware, layered under the automatic count-based ladder.
+- `voice_video_max_publishers` (default 8) as the honest backstop: camera
+ buttons disable past the cap, server rejects the flag. Audio mesh keeps
+ scaling beyond it.
+
+## UX: the room page
+
+### Navigation
+
+- Sidebar room rows gain an "open room" affordance (and/or clicking the room
+ name while connected navigates; click-to-join on the join button is
+ unchanged).
+- Route: **`/voice/r/:slug`**. The engine already serves JSON at
+ `/voice/rooms/:id`, so the page uses a distinct path. Server side: a route
+ that renders the Ember app shell (core chat's full-page route is the
+ reference pattern); client side: a plugin route map entry.
+- The Discourse sidebar — including the Voice rooms section — persists
+ automatically: the page renders in the regular content outlet.
+
+```
+┌──────────┬─────────────────────────────────┐
+│ Sidebar │ Room: Watercooler │
+│ │ ┌─────────┐ ┌─────────┐ │
+│ 🎙 Rooms │ │ Alice 🎥 │ │ Bob 🎥 │ │
+│ Water.. │ ├─────────┤ ├─────────┤ │
+│ 👤👤👤 │ │ Carol 👤 │ │ You 🎥 │ │
+│ Lounge │ └─────────┘ └─────────┘ │
+│ │ │
+│ (rest of │ [🎤] [🎧] [📷] [🖥️] [☎ leave] │
+│ sidebar) │ │
+└──────────┴─────────────────────────────────┘
+```
+
+- **The page works for every room, video-enabled or not.** Participants
+ without video render as avatar tiles with the existing speaking ring
+ (reusing `AudioMonitor` state). This makes the page a general "room view",
+ with video as an enhancement where allowed.
+- Being on the page = `watching_video: true` in presence; navigating away
+ flips it off and senders drop your video feed. Audio continues regardless
+ (service state is route-independent).
+- Layout: CSS grid, `auto-fit`/`minmax`, BEM classes
+ (`.voice-room-page`, `.voice-video-tile`, modifiers like `--speaking`,
+ `--screen-share`, `--self`).
+- Active-speaker spotlight and click-to-pin: follow-on, not v1.
+
+### Video tile anatomy (unchanged from original draft)
+
+- `<video>` with `object-fit: cover` (camera) / `contain` (screen share).
+- Bottom overlay: username, mute icon, camera/screen badge.
+- Speaking indicator: border glow driven by existing speaking detection.
+- Self view mirrored with `transform: scaleX(-1)` (camera only).
+- Camera-off: avatar centered on dark background.
+- Right-click: existing participant context menu (volume, mute, kick).
+
+### Controls bar
+
+Mic toggle, deafen, camera toggle, screen share, leave. Camera and screen
+share buttons render only when video is effectively enabled for the room
+(below) and disable with a tooltip when the publisher cap is reached.
+
+### Sidebar indicators
+
+- Camera icon next to participants with `is_video_on` in the room's expanded
+ participant rows.
+- A video badge on the room link itself when any participant is publishing,
+ so browsers of the sidebar can see "there's video happening here".
+
+## Per-room video toggle
+
+Video has a different social temperature than audio; room owners should
+control it.
+
+- **Schema:** `video_enabled` boolean on `voice_rooms`, `null: false`,
+ `default: true`.
+- **Effective rule:**
+
+ ```
+ video allowed in room = SiteSetting.voice_video_enabled &&
+ room.video_enabled &&
+ room.open? # stage rooms excluded in v1
+ ```
+
+- **Editing:** checkbox in the room create/edit form (FormKit), editable by
+ whoever can manage the room (creator/managers — existing
+ `can_manage_voice_room?` guardian); also exposed in the admin room UI.
+ Permitted in `rooms_controller#room_params` and serialized in
+ `RoomSerializer`.
+- **Enforcement:** server-side in the state endpoint (below) — reject
+ `is_video_on: true` / screen-share flags when video isn't allowed for the
+ room, mirroring how `toggle_mute` rejects listener unmutes in stage rooms.
+ Client hides the buttons; the server check is the real gate.
+- **Flipping it off live:** broadcast the room update (directory broadcaster
+ already pushes room CRUD); clients with active cameras stop sending
+ (`replaceTrack(null)`) and toast.
+
+## Server changes (small by design)
+
+1. **Migration:** add `video_enabled` to `voice_rooms` (see above).
+2. **Presence metadata keys:** `is_video_on`, `is_screen_sharing`,
+ `watching_video` — same mechanism as `is_muted`/`is_deafened`.
+3. **Endpoint:** generalize `toggle_mute` into (or add alongside it)
+ `POST /voice/rooms/:id/state` accepting the metadata booleans, with the
+ per-room enforcement above and the publisher-cap check
+ (count of participants with `is_video_on` ≥ `voice_video_max_publishers`
+ → 422).
+4. **Site settings** (`config/settings.yml`):
+
+ ```yaml
+ voice_video_enabled:
+ default: false
+ client: true
+ voice_video_max_publishers:
+ default: 8
+ min: 2
+ max: 16
+ client: true
+ ```
+
+ Off by default — admin opt-in, independent of voice.
+
+5. **Page route** rendering the app shell at `/voice/r/:slug`, guarded by
+ `ensure_can_join_voice_room!`-equivalent visibility (the room must be
+ visible to the user; joining still requires the explicit join action).
+
+Nothing changes in the signal relay.
+
+## Screen sharing
+
+Nearly free once camera works — it's the same transceiver machinery:
+
+- `getDisplayMedia({ video: { frameRate: { max: 15 } } })`, then
+ `replaceTrack` on the _same_ video transceiver.
+- **Camera XOR screen** per user (one video track each way), as in the
+ original draft — keeps transceiver count and UI simple.
+- Handle the browser's native "Stop sharing" via `track.onended`.
+- Hide the button where `getDisplayMedia` is unavailable (iOS Safari, most
+ Android browsers).
+- Screen tiles: `object-fit: contain`, no mirror, "Screen" badge; a screen
+ share auto-pins as the spotlight tile once spotlight exists.
+
+## Phasing
+
+1. **Foundation (no UI to speak of).** Video transceivers at peer setup,
+ separate camera stream, `replaceTrack` camera toggle (temporary debug
+ button), per-user stream registry fix, restart-path media reattachment,
+ `is_video_on` presence flag, site settings. Behind
+ `voice_video_enabled`; audio path untouched.
+2. **The page.** `/voice/r/:slug` route, tile grid (avatar tiles for all
+ rooms, video tiles where allowed), controls bar, sidebar indicators,
+ per-room `video_enabled` toggle + form + enforcement.
+3. **Boundary pushing.** `watching_video` subscription gating, watcher-count
+ bitrate/resolution ladder, publisher cap enforcement, quality profile
+ override, mobile tile limits.
+4. **Screen share + spotlight.** `getDisplayMedia`, camera XOR screen,
+ active-speaker/pin spotlight layout.
+
+## Edge cases
+
+- **Camera enable at publisher cap:** button disabled with tooltip; server
+ 422s as the real gate (client count can be stale).
+- **Two users enable camera simultaneously:** no interaction at all —
+ `replaceTrack` involves no signaling, so there is nothing to glare. (The
+ original draft's renegotiation-storm concern dissolves with this design.)
+- **User joins mid-video:** initial negotiation includes the video m-line;
+ watchers receive frames as soon as publishers' senders pick them up from
+ the `watching_video` broadcast. No renegotiation.
+- **Peer connection restart while camera on:** restart path reattaches the
+ camera track for subscribed peers (required fix #2).
+- **Room's `video_enabled` switched off mid-call:** publishers stop sending,
+ toast shown, tiles fall back to avatars.
+- **Mobile:** camera works; cap rendered tiles on small viewports (decode
+ cost), prefer the spotlight layout; backgrounding the browser stops the
+ camera — broadcast `is_video_on: false` on track end.
+- **PTT + video:** independent — PTT drives audio track `enabled`, video is a
+ separate track.
+- **Stage rooms:** excluded in v1 (`room.open?` in the effective rule).
+ Follow-on: speakers may publish, listeners are watch-only — falls out of
+ existing role logic since listeners already have no send path.
+- **Deafened users:** deafen is audio-only; they still see video. (Matches
+ Discord semantics.)
+
+## Future enhancements (out of scope)
+
+- Video in Stage rooms (speakers publish, listeners watch).
+- SFU integration for rooms beyond mesh limits.
+- Picture-in-picture via the native PiP API (supersedes the original draft's
+ `window.open` popout idea — far less machinery for the same need).
+- Active-speaker auto-spotlight, click-to-pin (phase 4 starts this).
+- Virtual backgrounds (segmentation model, WebGL) — note the DTLN worklet
+ already establishes the WASM-in-media-pipeline pattern.
+- Recording, reactions overlay.
diff --git a/plugins/voice/docs/roadmap/windows-hardware-mesh-screenshare.md b/plugins/voice/docs/roadmap/windows-hardware-mesh-screenshare.md
new file mode 100644
index 00000000000..00bbbb5fffc
--- /dev/null
+++ b/plugins/voice/docs/roadmap/windows-hardware-mesh-screenshare.md
@@ -0,0 +1,455 @@
+# Experimental Windows hardware mesh screen sharing
+
+## Status
+
+Proposed implementation plan. The feature remains disabled by default and is
+limited initially to Windows 11 systems with a supported NVIDIA GPU.
+
+## Objective
+
+Publish a game or display at up to 3840×2160 and 60 frames per second, with
+game or system audio, while encoding each quality layer only once in NVENC.
+Mesh rooms continue to send media directly between participants; Discourse
+only handles authorization, presence, and signaling.
+
+The initial implementation runs beside the existing Flutter/libwebrtc call:
+
+```text
+Primary call (unchanged) Experimental screen publisher
+Flutter + libwebrtc Rust + webrtc-rs
+├── microphone ├── Windows Graphics Capture
+├── camera ├── D3D11 color conversion
+├── incoming media ├── one NVENC H.264 encoder
+└── primary peer connections ├── WASAPI loopback + Opus
+ └── one screen peer connection per viewer
+```
+
+Captured frames and encoded H.264 access units are shared. RTP state,
+retransmission, congestion control, DTLS/SRTP, and ICE remain independent for
+each viewer.
+
+## Non-goals for the first release
+
+- AMD or Intel hardware encoding.
+- Windows versions earlier than Windows 11.
+- Linux or macOS changes.
+- Replacing the existing microphone, camera, receive, or rendering paths.
+- Game-process injection or capture hooks that may conflict with anti-cheat
+ software.
+- Silent fallback to software encoding.
+- Unlimited viewer counts or independent per-viewer quality adaptation.
+- LiveKit publishing through the Rust engine.
+
+## Success criteria
+
+On a supported Windows 11 and NVIDIA test system:
+
+- A game or display can be shared at 3840×2160 and 60 fps.
+- NVIDIA Video Encode utilization confirms that NVENC is active.
+- The publisher does not perform a CPU pixel readback in the steady-state
+ capture and encode path.
+- Adding viewers does not add encoder sessions for the same quality layer.
+- Game-process or system audio remains synchronized with video.
+- One slow viewer cannot stall capture or delivery to other viewers.
+- Voice and camera remain usable through the existing primary connection.
+- Unsupported systems fail closed with an actionable explanation.
+- Disabling the experiment restores the existing screen-sharing behavior.
+
+Initial performance targets should be measured rather than treated as release
+guarantees:
+
+- 95th-percentile capture-to-encoded-frame latency below 25 ms.
+- No sustained capture queue growth.
+- Less than 10% aggregate CPU use attributable to capture and publishing on
+ the reference system.
+- Audio/video drift remains within 50 ms during a 30-minute session.
+
+## Architecture
+
+### Capture and encoding
+
+Use Windows Graphics Capture (WGC) as the default source for windows and
+displays. Keep DXGI Desktop Duplication as a later fallback for display or
+exclusive-fullscreen cases that WGC cannot capture reliably.
+
+```text
+WGC frame pool
+ → ID3D11Texture2D (BGRA)
+ → GPU conversion and SDR/tone-map stage (NV12)
+ → registered D3D11 NVENC input resource
+ → H.264 Annex-B access unit
+ → reference-counted broadcast ring
+```
+
+The first encoder profile is:
+
+- H.264 with WebRTC-compatible profile and `packetization-mode=1`.
+- 3840×2160 at 60 fps when the source and GPU sustain it.
+- Low-latency tuning with no B-frames.
+- Repeat SPS/PPS on IDR frames.
+- Monotonic 90 kHz video timestamps.
+- Configurable bitrate with a provisional 25–40 Mbps range for 4K60.
+- Explicit force-IDR operation for consolidated PLI/FIR requests.
+
+HDR sources must either stay in an HDR-capable pipeline end to end or pass
+through an explicit GPU tone-mapping stage. The experiment should initially
+declare SDR output and test HDR desktops for correct conversion rather than
+allowing washed-out or clipped output.
+
+Direct NVIDIA Video Codec SDK integration is the intended production path.
+An FFmpeg `ddagrab`/`h264_nvenc` spike is acceptable for validating transport
+and performance, but it must not become an accidental permanent dependency.
+Any FFmpeg distribution requires a separate LGPL/GPL configuration and
+redistribution review.
+
+### Audio
+
+Use WASAPI process-loopback capture for game audio when the user selects a
+process. Include the process tree so child processes are captured. Offer
+endpoint-wide system loopback as a distinct option with a clear label.
+
+Audio is captured once, resampled to the Opus input format, encoded once, and
+fanned out to per-peer audio tracks. Use QPC-derived timestamps and bounded
+resampler correction to keep the audio clock aligned with the video clock.
+Microphone audio remains on the primary Flutter/libwebrtc connection.
+
+### Encoded-frame fan-out
+
+Current webrtc-rs tracks bind to one peer connection. Create one local video
+track and one local screen-audio track per viewer, and feed them from shared
+broadcast sources:
+
+```text
+Arc<EncodedVideoAccessUnit>
+ ├── bounded queue → peer A video track
+ ├── bounded queue → peer B video track
+ └── bounded queue → peer C video track
+
+Arc<EncodedOpusFrame>
+ ├── bounded queue → peer A audio track
+ ├── bounded queue → peer B audio track
+ └── bounded queue → peer C audio track
+```
+
+Packetization can occur per peer. Its cost is small compared with 4K encoding
+and it preserves peer-specific SSRCs, payload types, header extensions, and
+timestamps. A later optimization may packetize once and copy immutable RTP
+payloads while rewriting peer-specific headers.
+
+Never await all peer writes in the capture loop. Each peer has a bounded queue
+and worker. A congested peer drops complete non-keyframe access units rather
+than accumulating unbounded latency or blocking other peers.
+
+NACK/RTX caches, receiver reports, TWCC/GCC, pacing, and SRTP remain per peer.
+Only PLI/FIR requests are consolidated: debounce concurrent requests and ask
+NVENC for one IDR that is delivered to every viewer.
+
+### Quality adaptation
+
+The first version publishes one shared quality layer. All viewers therefore
+need enough downstream bandwidth for the configured stream. Apply both:
+
+- a small experimental viewer cap; and
+- per-peer overload detection that warns, sheds, or disconnects a viewer whose
+ queue repeatedly overflows.
+
+Do not globally lower quality to the weakest viewer without an explicit user
+choice.
+
+The next iteration can use a shared H.264 simulcast ladder, for example:
+
+| Layer | Target | Provisional bitrate |
+| --- | --- | --- |
+| High | 2160p60 | 25–40 Mbps |
+| Medium | 1080p60 | 8–12 Mbps |
+| Low | 720p30 | 2–4 Mbps |
+
+Each layer is encoded once and selected independently for each peer. Encoder
+work becomes proportional to the number of layers, not the number of viewers.
+The implementation must check the GPU's concurrent NVENC session capability
+before enabling multiple layers.
+
+Mesh upload bandwidth still scales with viewers. A 30 Mbps layer sent to four
+viewers requires approximately 120 Mbps of publisher upload before protocol
+overhead.
+
+## Signaling protocol
+
+The existing protocol assumes one peer connection per pair of users. Add a
+bounded connection discriminator while preserving the current behavior:
+
+```json
+{
+ "recipient_id": 123,
+ "connection_id": "screen",
+ "events": [
+ { "type": "offer", "sdp": "..." }
+ ]
+}
+```
+
+Allowed values initially are:
+
+- `primary`: existing voice/camera connection and the default when omitted.
+- `screen`: experimental screen video and audio connection.
+
+The server validates the value, groups batches by both recipient and
+connection ID, and preserves it in the MessageBus envelope. The discriminator
+must not be embedded in SDP or accepted as an arbitrary string.
+
+Advertise a `mesh_screen_connection_v1` capability in the native participant
+session metadata. The publisher creates secondary offers only for peers that
+advertise this capability. This is mandatory: an old client must never route a
+screen offer into its primary connection merely because it ignores an unknown
+field.
+
+For screen connections, the publisher always creates the offer and the viewer
+answers. This avoids glare because the connection has one publisher. Closing
+the secondary peer connections stops the share in the first version; inactive
+transceivers and secondary-connection reuse can be considered later.
+
+The existing room state update remains the source of truth for the visible
+`screen: true` participant state.
+
+## Native boundary
+
+Expose a narrow asynchronous interface from a Windows Rust library to Flutter.
+The exact bridge can use a C ABI with Dart FFI or generated bindings, but the
+application-facing contract should remain owned by discourse-native:
+
+```text
+probeCapability() -> capability details or unsupported reason
+listCaptureSources() -> windows and displays
+startShare(config, iceConfig, participantSession)
+addViewer(viewer, remoteCapability)
+handleSignal(viewerId, event)
+removeViewer(viewerId)
+stopShare()
+subscribeEvents() -> signal, state, stats, warning, failure
+```
+
+Do not expose NVIDIA, webrtc-rs, or raw FFI types to the Dart application.
+Events need correlation IDs and redacted diagnostics consistent with the
+existing Voice diagnostic capture.
+
+The capability result must verify all of the following:
+
+- Windows 11 is supported.
+- The selected capture and encode adapters are compatible.
+- An NVIDIA driver and NVENC H.264 session can be created.
+- The requested resolution, frame rate, and concurrent-session count are
+ supported.
+- Process-loopback audio is available when requested.
+
+If any check fails, the experimental path is unavailable. It must not silently
+fall back to software encoding while presenting itself as hardware sharing.
+
+## Rollout controls
+
+Add a client-visible, default-off plugin site setting:
+
+```text
+voice_windows_hardware_screen_share_enabled
+```
+
+It only allows the client to attempt the feature. The client must additionally
+pass the local runtime capability probe. A local runtime or build flag should
+also be able to disable the experiment independently for emergency rollback.
+
+The screen-share UI should label this path experimental, display the active
+encoder, capture resolution, frame rate, and estimated upload requirement, and
+allow falling back to existing screen sharing only through an explicit user
+choice.
+
+Start with an administrator/tester audience and a conservative viewer cap.
+Expand only after telemetry demonstrates stable capture, A/V sync, driver
+recovery, and network behavior.
+
+## Implementation milestones
+
+### 0. Windows build foundation
+
+- Create the generated Flutter Windows runner using the repository's documented
+ `flutter create` workflow.
+- Establish a Windows CI build with Visual Studio 2022 and the pinned Flutter
+ SDK.
+- Package and load a minimal Rust DLL from the Windows runner.
+- Add a deterministic Rust toolchain and dependency lock policy.
+- Confirm application signing and redistribution requirements.
+
+Exit: a Windows debug/release application loads a versioned Rust library and
+passes a bridge smoke test in CI and on Windows 11.
+
+### 1. Secondary-connection protocol
+
+- Add the default-off site setting and server translation.
+- Extend the signal validator, relay, and batching with `connection_id`.
+- Add `mesh_screen_connection_v1` capability negotiation.
+- Route `primary` signals exactly as before.
+- Add fake secondary screen transports to the web and native clients.
+- Implement lifecycle handling for roster changes, leave, kick, reconnect,
+ room destruction, and participant-session replacement.
+
+Exit: two capable clients establish and tear down a fake secondary connection
+without affecting primary voice; old clients never receive secondary offers.
+
+### 2. Rust WebRTC transport
+
+- Create one webrtc-rs peer connection per capable viewer.
+- Consume Voice ICE/TURN configuration.
+- Implement publisher-offers/viewer-answers signaling.
+- Publish synthetic H.264 and Opus fixtures.
+- Implement bounded per-peer queues and independent transport workers.
+- Surface connection state, RTCP keyframe requests, and stats through the
+ native boundary.
+
+Exit: a synthetic encoded stream reaches multiple browser viewers through
+direct ICE and TURN, with only one shared input stream.
+
+### 3. Windows capture and NVENC
+
+- Enumerate WGC window and display sources.
+- Capture D3D11 textures without CPU readback.
+- Convert BGRA/HDR inputs to NV12 SDR on the GPU.
+- Integrate NVENC H.264 low-latency encoding.
+- Fan out immutable access units to every viewer track.
+- Coalesce PLI/FIR and force IDR.
+- Handle resize, source closure, adapter/device loss, sleep, and driver reset.
+
+Exit: 4K60 video reaches multiple viewers while one NVENC session is active.
+
+### 4. Game and system audio
+
+- Add process-tree and endpoint-wide WASAPI loopback modes.
+- Encode one Opus stream and fan it out to viewer audio tracks.
+- Align QPC-derived audio and video timestamps.
+- Add bounded drift correction and discontinuity recovery.
+- Ensure stopping capture releases every COM, WASAPI, D3D11, and NVENC
+ resource.
+
+Exit: a 30-minute game share maintains the A/V drift target across multiple
+viewers.
+
+### 5. Hardening and experimental release
+
+- Add capability and failure UX.
+- Add redacted diagnostics and performance telemetry.
+- Test direct, STUN, TURN/UDP, TURN/TCP, and TURN/TLS paths.
+- Exercise packet loss, reordering, bandwidth collapse, and a slow viewer.
+- Test source resize, alt-tab, minimization, HDR desktop, GPU reset, sleep,
+ network changes, and participant churn.
+- Complete dependency, NVIDIA SDK, codec/patent, and FFmpeg licensing review.
+- Document the feature, limitations, expected upload, and rollback procedure.
+
+Exit: the feature can be enabled for a limited audience and disabled without a
+client release or impact to ordinary calls.
+
+### 6. Shared simulcast
+
+- Add two or three shared encoder layers.
+- Select layers using each peer's congestion and receiver feedback.
+- Switch at keyframe boundaries without recreating the call.
+- Enforce GPU encoder-session capability and thermal/load limits.
+
+Exit: heterogeneous viewers receive sustainable layers while encoder sessions
+remain proportional to the configured layer count.
+
+## Test strategy
+
+### Plugin tests
+
+- Reject unknown or malformed connection IDs.
+- Preserve the default `primary` behavior when the field is absent.
+- Keep batches for the same recipient but different connections separate.
+- Preserve the discriminator through the relay.
+- Enforce participant session, room permission, stage-role, rate-limit, and
+ LiveKit/mesh policy checks for secondary connections.
+- Never advertise or use the capability when the setting is disabled.
+
+### Dart and JavaScript tests
+
+- Route primary and screen signals to independent transports.
+- Gate offers on both the site setting and peer capability.
+- Restore the primary call when secondary setup or capture fails.
+- Tear down screen connections on stop, track end, roster removal, kick,
+ reconnect, account removal, and room destruction.
+- Keep participant screen state and tiles correct.
+- Verify diagnostics are redacted.
+
+### Rust tests
+
+- Feed one immutable access unit to N peer tracks.
+- Prove one blocked peer cannot block other peers.
+- Drop complete access units under pressure without corrupting H.264 framing.
+- Consolidate simultaneous PLI/FIR requests.
+- Maintain independent RTP sequence, SSRC, retransmission, and encryption
+ state.
+- Preserve A/V timestamp mapping and recover from discontinuities.
+- Release native resources on partial initialization failure and cancellation.
+
+### Windows integration matrix
+
+- Supported and unsupported NVIDIA generations and driver versions.
+- One through the configured maximum number of viewers.
+- 720p30, 1080p60, 1440p60, and 2160p60 sources.
+- Window, borderless game, full display, SDR, and HDR desktop sources.
+- Process audio, process tree, system audio, silent source, and device change.
+- Direct network, restrictive NAT, and every supported TURN transport.
+- Sustained packet loss, low receiver bandwidth, and publisher upload
+ saturation.
+
+Collect capture FPS, dropped frames, encode latency percentiles, queue depth,
+active NVENC sessions, CPU, GPU Video Encode utilization, outbound bitrate,
+packet loss, retransmissions, RTT, and A/V drift.
+
+## Security and privacy
+
+- Preserve the existing mesh IP-address warning and TURN behavior.
+- Treat window titles and process names as sensitive diagnostic data.
+- Do not log SDP, ICE addresses, access tokens, source titles, or unredacted
+ participant identifiers.
+- Require the existing room authorization and active participant session for
+ secondary signaling.
+- Bound event sizes, connection IDs, viewer counts, queues, and retry loops.
+- Do not permit remote participants to start capture or select a source.
+- Use the operating-system capture consent UI where WGC requires it.
+- Avoid injected game capture in the first release because of anti-cheat,
+ stability, and trust implications.
+
+## Dependencies and references
+
+Evaluate and pin dependencies only after a license and maintenance review.
+Useful implementation references include:
+
+- NVIDIA Video Codec SDK and its D3D11/DXGI samples:
+ <https://github.com/NVIDIA/video-sdk-samples>
+- Windows Graphics Capture documentation:
+ <https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture>
+- Windows application-loopback sample:
+ <https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/applicationloopbackaudio-sample/>
+- webrtc-rs broadcast example:
+ <https://github.com/webrtc-rs/webrtc/blob/f4844a0fd2702356b24379d3dd15576e3ad0a1fb/examples/broadcast/broadcast.rs>
+- Pion multi-binding RTP track:
+ <https://github.com/pion/webrtc/blob/main/track_local_static.go>
+- CaptureEngine, an MIT Windows capture and hardware-encoding reference:
+ <https://github.com/aufkrawall/capture-engine>
+- discord-stream-rs, a young Discord-oriented webrtc-rs/FFmpeg reference:
+ <https://github.com/Tky567/stream-discord-rs>
+
+Study GPL or source-available projects only as behavioral references unless a
+separate licensing decision explicitly permits incorporating them.
+
+## Decisions to resolve during the spike
+
+- Dart FFI versus generated bridge bindings.
+- Rust wrapper around the direct NVENC C API versus a narrow C++ capture/encode
+ core behind Rust.
+- WGC-only first release versus an early DXGI fallback.
+- Exact reference GPU, minimum driver, bitrate, viewer cap, and overload policy.
+- Whether the receiving secondary connection should initially use the existing
+ browser/native libwebrtc stack or a common Rust receiver on Windows.
+- Whether an FFmpeg prototype provides enough schedule advantage to justify its
+ temporary build and licensing cost.
+
+These decisions should be made from milestone measurements. They do not change
+the protocol boundary or the encode-once/per-peer-transport architecture.
diff --git a/plugins/voice/docs/security-review-2026-08-26.md b/plugins/voice/docs/security-review-2026-08-26.md
new file mode 100644
index 00000000000..54ed4dca5f2
--- /dev/null
+++ b/plugins/voice/docs/security-review-2026-08-26.md
@@ -0,0 +1,559 @@
+# Security review — 2026-08-26
+
+## Status
+
+This review covers Voice at commit `60fc027`, with native mesh WebRTC as the
+planned transport for Discourse free hosting. LiveKit is considered an optional
+bring-your-own-service integration and is discussed separately.
+
+The current recommendation is **not to enable mesh mode on free hosting until
+the release-blocking findings below are resolved**.
+
+This is a source review supported by the existing automated test suites. It is
+not a substitute for testing the deployed TURN, network, browser, and hosting
+configuration.
+
+## Threat model
+
+The review assumes:
+
+- customer site administrators are trusted to administer their Discourse site,
+ but are not trusted with access to hosting infrastructure;
+- ordinary authenticated users may be malicious;
+- public rooms may be joinable by every authenticated user, or by everyone when
+ anonymous browsing is enabled;
+- a malicious participant controls their browser and is not constrained by the
+ Voice client UI;
+- room presence and participant roles must be authoritative security
+ boundaries, rather than advisory client state;
+- denial-of-service resistance is important because the plugin will run on a
+ shared free-hosting platform.
+
+## Summary
+
+| Severity | Finding | Hosting status |
+| --- | --- | --- |
+| High | A room-eligible user can establish an invisible mesh connection and receive another participant's microphone | Release blocker |
+| High | Signaling, join, presence, and room capacity controls permit inexpensive amplification and resource exhaustion | Release blocker |
+| Medium | A stage listener can publish audio to speakers despite lacking permission to speak | Remediated — see finding 3 |
+| Medium | `logged_in_users` MessageBus delivery can expose room broadcasts to anonymous subscribers | Fix or prohibit the affected configuration |
+| Operational | Mesh reveals peer IP addresses and lacks a secure ephemeral TURN-only privacy mode | Hosting/privacy requirement |
+| High | The optional LiveKit URL creates a server-side request forgery boundary for customer administrators | Remediated — see finding 5 |
+
+## Release-blocking findings
+
+### 1. Invisible mesh microphone listener
+
+**Severity:** High
+
+**Status:** Remediated after this review — signaling, heartbeat, and state are
+now bound to a server-attested participant session minted by `join`, rotated
+by `livekit_token`, and revoked on leave/kick/TTL expiry; the relay drops
+recipients without a live session and carries the serialized sender so early
+offers render a visible participant. See the regression tests in
+`spec/requests/voice/rooms_controller_spec.rb`
+("#signal participant session enforcement").
+
+**Affected code:**
+
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#signal`
+- `app/services/voice/signal_relay.rb`
+- `assets/javascripts/discourse/lib/voice/mesh-signal-handler.js`
+- `assets/javascripts/discourse/lib/voice/peer-manager.js`
+- `assets/javascripts/discourse/lib/voice/presence-pending-peers.js`
+- `assets/javascripts/discourse/app/services/voice-webrtc.js`
+
+`RoomsController#signal` verifies that the sender is eligible to join the room,
+but it does not require either the sender or recipient to be actively present.
+It relays an authenticated sender ID to any positive recipient user ID.
+
+For non-stage rooms, `MeshSignalHandler` deliberately accepts an offer or ICE
+candidate when the sender is absent from `active_participants`. This handles a
+legitimate race where signaling can arrive before a roster update, but it also
+treats an offer from a non-present user as proof that the user shares the room.
+The server has not established that proof.
+
+When the victim accepts the offer, `PeerManager#create` immediately adds the
+victim's local microphone track to the new peer connection. The microphone is
+enabled by default for an active participant. The absent peer is retained for a
+15-second grace period, during which media can flow; repeated offers can create
+new connection windows.
+
+An authenticated user who is authorized to join an open room can therefore:
+
+1. identify an active participant from the room roster;
+2. send that participant an SDP offer without joining the room;
+3. receive the participant's SDP answer and ICE candidates; and
+4. receive the participant's enabled microphone while remaining absent from the
+ visible participant roster.
+
+This does not bypass private-room membership: the attacker must already be
+eligible to join the room. It does bypass the user's expectation that everyone
+receiving room media is visible as a participant.
+
+Existing coverage preserves the unsafe behavior:
+
+- `spec/requests/voice/rooms_controller_spec.rb` sends signals to recipients
+ who have not joined the room;
+- `test/javascripts/unit/services/voice-webrtc-test.js` includes
+ "honors an early offer from a participant whose presence has not propagated
+ yet" and asserts that an absent sender receives an answer.
+
+#### Design constraint
+
+Signaling was deliberately decoupled from client roster presence: gating WebRTC
+setup on the recipient's local `active_participants` snapshot caused months of
+intermittent connection failures, because MessageBus roster propagation races
+the first signals. That decoupling must be preserved. The fix is therefore a
+**server-attested participant session** established synchronously by `join`,
+not a requirement that roster presence has propagated before a signal is
+accepted.
+
+#### Required remediation
+
+- Have `join` create a random `participant_session_id`, store it in Redis
+ alongside presence, and return it to the client. This is server-authoritative
+ and synchronous, so it cannot race MessageBus roster delivery.
+- Require a valid, non-expired participant session for `signal`, `heartbeat`,
+ and `state`; the server verifies the session belongs to the authenticated
+ user and the current room instance before relaying.
+- Relay signals with a server-attested session marker so the recipient can
+ accept an early offer even when its local roster snapshot has not caught up.
+ Do not infer room membership from receipt of a client-created SDP offer, and
+ do not gate acceptance on the local roster.
+- Revoke the session's signaling authority on leave, kick, or presence TTL
+ expiry, and tear down the corresponding peer promptly.
+- Show a server-serialized "connecting" participant for an early offer instead
+ of an invisible media connection, so everyone receiving room media is
+ visible.
+- Regression tests must cover both the security boundary and the reliability
+ fix:
+ - delayed roster broadcast plus a valid participant session → offer accepted;
+ - user eligible for the room but without a participant session → signal
+ rejected;
+ - stale session after leave and rejoin → signal rejected;
+ - kick or TTL expiry → the session can no longer signal;
+ - recipient leaves while an offer is queued → offer discarded.
+
+### 2. Control-plane amplification and capacity bypass
+
+**Severity:** High for shared/free hosting
+
+**Status:** Remediated after this review. The implemented limits and their
+rationale:
+
+- Signaling schema: only `offer`, `answer`, and `candidate` events, with exact
+ per-type shapes, validated by `Voice::SignalValidator` — an SDP of at most
+ 32 KiB, a candidate body of at most 2 KiB restricted to the four standard
+ ICE fields, at most 25 events per recipient per request, recipients bounded
+ by the room's effective capacity minus one, 1 MiB of signal body per
+ request, and the unused arbitrary `metadata` field removed. Any violation
+ rejects the whole batch before anything is published. The relay now
+ publishes one MessageBus envelope per recipient carrying that recipient's
+ ordered event batch (previously one publish per event); the receiver
+ unpacks batches in order and still accepts legacy single events.
+- Signaling rate limits are accounted in relayed events, not HTTP requests,
+ so a full-room Trickle ICE burst passes while sustained abuse is cut off
+ before MessageBus work: 30 requests/10 s, 5,000 events/min per user
+ (roughly 4× a 50-person connect burst with an ICE restart), and 100,000
+ events/min per room (50 users bursting at once), via the weighted
+ `Voice::ControlPlaneLimiter`. The client's 75 ms candidate batching and
+ 200 ms HTTP batching are unchanged; it just flushes a recipient's batch
+ early at 20 events to stay under the per-recipient cap.
+- Capacity: presence is admitted atomically by a Lua script
+ (`ParticipantTracker.add_within_capacity`) that purges expired presence,
+ refreshes existing participants (even in a full room), and rejects new
+ joiners at the effective capacity — the lower of `room.max_participants`
+ and the new `voice_max_room_participants` site ceiling (default 50).
+ Concurrent joins cannot exceed the cap; a full room returns 422.
+- Join is rate limited (30/min per user) and idempotent: a repeat carrying
+ the live participant session refreshes the grant without rotating the
+ session, opening a second analytics session, re-firing badge/invite hooks,
+ or rebroadcasting the roster. A leave carrying a superseded session is
+ ignored, so a stale tab can never revoke a newer tab's session. Heartbeat
+ still recovers briefly-lapsed presence under a valid session; join remains
+ the only operation that grants participant authority initially.
+- Other control-plane endpoints: state changes require a supported field,
+ short-circuit (no write, no roster broadcast) when nothing changed, and are
+ limited to 40/10 s; invalid participant-session attempts are limited to
+ 30/min; hand raising requires the participant session while moderator
+ dismissals stay unaffected.
+- Direct calls: the daily invite budget is checked before the ephemeral room
+ is created, a failed ring destroys the room instead of orphaning it, live
+ ephemeral rooms are capped at 10 per creator under a distributed mutex, and
+ the co-presence job iterates pairs lazily under the site capacity ceiling
+ instead of materializing them.
+
+Regression tests: `spec/requests/voice/rooms_controller_spec.rb`
+("#signal validation", "#signal rate limits", the join capacity/idempotency
+and stale-leave tests), `spec/services/voice/participant_tracker_spec.rb`
+(".add_within_capacity", including a concurrency test),
+`spec/requests/voice/calls_controller_spec.rb`, and
+`spec/services/voice/ephemeral_room_manager_spec.rb`.
+
+**Affected code:**
+
+- `app/controllers/voice/rooms_controller.rb`
+- `app/services/voice/participant_tracker.rb`
+- `app/models/voice/room.rb`
+- `app/services/voice/signal_relay.rb`
+- `app/jobs/scheduled/voice/update_co_presence.rb`
+- `app/controllers/voice/calls_controller.rb`
+- `app/services/voice/ephemeral_room_manager.rb`
+- `app/services/voice/room_inviter.rb`
+
+Several individually inexpensive operations can be amplified into database,
+Redis, MessageBus, browser, and WebRTC work:
+
+- `signal` has no rate limit. It accepts arbitrary batched messages and events,
+ then emits one MessageBus publish per event. Signal types, recipient counts,
+ event counts, SDP size, and candidate size are not bounded locally.
+- `join` is not idempotent. With analytics enabled, every request creates a new
+ `Voice::Session`, even while the user already has active presence. Only the
+ newest session ID is retained in presence metadata.
+- `heartbeat` can create presence for a user who never called `join`.
+- `state` can write metadata and broadcast a full participant roster for a user
+ who is eligible to join but is not present.
+- `Room#max_participants` validates a configured value but `join` does not
+ enforce it. This is particularly dangerous for full-mesh rooms, whose peer
+ connection count grows quadratically.
+- the scheduled co-presence calculation materializes every pair of active users,
+ also creating quadratic work;
+- direct-call room creation happens before the daily invite limiter. Once the
+ invite limit is exhausted, repeated attempts can leave ephemeral rooms behind
+ until cleanup.
+
+#### Required remediation
+
+- Atomically enforce `max_participants` when establishing presence. The check
+ and add must not be separate raceable Redis operations.
+- Make `join` idempotent for the current room instance and create at most one
+ open analytics session per user and room instance.
+- Make `join` the only endpoint that establishes presence. Require a valid
+ participant session (see finding 1) for heartbeat, state changes, signaling,
+ hand raising, and similar participant actions.
+- Add per-user and per-room rate limits for join, state, heartbeat failures, and
+ signaling.
+- Allowlist `offer`, `answer`, and `candidate` signaling types and validate their
+ expected shapes.
+- Set explicit limits for recipients per request, events per recipient, SDP
+ bytes, candidate bytes, total request bytes, and queued pending candidates.
+- Apply direct-call and invite limits before creating an ephemeral room, and cap
+ the number of live ephemeral rooms per user.
+- Add load-oriented tests for room capacity and large/batched signal rejection.
+
+## Important mesh findings
+
+### 3. Stage publishing permissions are client-enforced
+
+**Severity:** Medium
+
+**Affected code:**
+
+- `assets/javascripts/discourse/lib/voice/roster-handler.js`
+- `assets/javascripts/discourse/lib/voice/mesh-signal-handler.js`
+- `assets/javascripts/discourse/lib/voice/peer-manager.js`
+- `assets/javascripts/discourse/lib/voice/remote-stream-registry.js`
+
+Stage listeners need peer connections to speakers so they can receive the
+stage. The mesh topology therefore retains a connection when either side may
+speak. A modified listener client can attach a microphone track to that
+connection even though the server would reject an unmute state change.
+
+The receiving speaker registers and plays incoming microphone tracks without
+checking whether the remote participant is a moderator or speaker. A malicious
+listener can consequently transmit audio to speakers and moderators. The audio
+is not automatically relayed to other listeners, but this still bypasses stage
+moderation and enables targeted disruption.
+
+The same trust boundary applies to other mesh media restrictions: client state
+such as muted, video enabled, and screen sharing is not proof of what a
+malicious browser put into its peer connection.
+
+#### Required remediation
+
+- On receipt of a media track, check the authoritative room role and room media
+ policy before registering or playing it.
+- Drop microphone, camera, screen, and screen-audio tracks that the remote role
+ is not allowed to publish.
+- Configure honest listener transceivers as receive-only, while treating that as
+ defense in depth rather than the security boundary.
+- Re-evaluate active tracks immediately after a role or room-policy change.
+- Add browser tests using a listener-created audio track rather than only UI
+ state transitions.
+
+**Status:** Remediated after this review (mesh receive-side media policy).
+
+- `remoteTrackAllowed` (`lib/voice/stage-roles.js`) is the receive-side
+ boundary: before a remote track is registered or played, the sender's role
+ in the server-broadcast roster and the room's media policy are checked.
+ In stage rooms only moderators and speakers may deliver any media; video
+ and screen-audio tracks additionally require the room's `video_allowed`.
+ Disallowed tracks are stopped and never reach the stream registry, the
+ audio monitor, transcription, or playback.
+- Both mesh registration paths go through the guard
+ (`VoiceWebrtcService#registerRemoteTrack`): `PeerManager`'s `ontrack`
+ and the roster handler's video re-registration. The LiveKit path is
+ unchanged: there the SFU enforces per-user publish grants server-side
+ (`canPublish`/`canPublishSources` on tokens and `UpdateParticipant`).
+- Re-evaluation on role change: a `role_change` message already tears down
+ the peer and its streams; additionally, every roster broadcast now sweeps
+ registered streams in stage mesh rooms and drops media from participants
+ whose fresh role cannot publish (covers demotions that arrive only as a
+ roster refresh).
+- Defense in depth: honest stage listeners now create their pre-negotiated
+ video and screen-audio transceivers as `recvonly` and answer speaker
+ offers `recvonly` (mic m-lines were already receive-only for listeners,
+ which hold no local stream). Promotions rebuild all peers, so directions
+ never change on a live connection. This is not the security boundary —
+ the receive-side check is.
+- Tests (`test/javascripts/unit/services/voice-webrtc-test.js`): a
+ listener-created microphone track arriving at a speaker is stopped and
+ never registered; a speaker's microphone still plays for listeners and
+ listener transceivers stay receive-only; video tracks are dropped in
+ rooms whose policy disallows video and register once allowed; a roster
+ refresh demoting a participant drops their already-registered media.
+ Existing multi-session system specs (stage speak queue, voice rooms,
+ video, subtitles) pass unchanged, confirming legitimate stage promotion
+ and media flows survive the new boundary.
+
+### 4. Logged-in-only MessageBus broadcasts may reach anonymous subscribers
+
+**Severity:** Medium
+
+**Affected code:**
+
+- `lib/voice.rb`, `Voice.public_room_message_bus_targets`
+- `app/services/voice/room_broadcaster.rb`
+- `app/services/voice/directory_broadcaster.rb`
+
+The `everyone`, `anonymous_users`, and `logged_in_users` automatic groups do not
+have enumerable `group_users` rows. Voice handles all three by publishing
+without MessageBus targets.
+
+That is correct when access is intentionally available to everyone, but it is
+not equivalent to `logged_in_users` on a site that permits anonymous browsing.
+The HTTP room directory denies anonymous access while predictable, untargeted
+room and directory channels can still deliver room metadata, participant
+identities, and participant state to an anonymous subscriber.
+
+#### Required remediation
+
+- Do not treat `logged_in_users` as equivalent to an unrestricted audience.
+- Add an authenticated delivery mechanism or omit sensitive payloads from
+ untargeted channels.
+- Until fixed, reject or host-lock the `logged_in_users` configuration on sites
+ where anonymous browsing is enabled.
+- Add an anonymous MessageBus test alongside the existing HTTP authorization
+ tests.
+
+## Mesh privacy and TURN requirements
+
+**Classification:** Operational/privacy requirement
+
+Mesh WebRTC media is encrypted between browsers, but direct ICE connectivity
+reveals network information to peers. The configured STUN service also observes
+the connecting public IP and request timing. The default configuration uses
+public Google and Twilio STUN endpoints.
+
+Voice provides a mesh privacy warning and enables it by default. For hosted
+service use, the warning should not be customer-disableable without an explicit
+hosting policy decision.
+
+Static TURN credentials are returned to every participant and can be reused for
+generic relay bandwidth. Secret-derived TURN credentials are better, but their
+current 12-hour validity is long for a public free-hosting service. The current
+transport policy also keeps direct connectivity enabled when secret-derived
+TURN is used, so it does not provide an ephemeral-credential relay-only mode.
+
+#### Hosting requirements
+
+- Document peer IP disclosure and the third-party STUN defaults.
+- Keep the mesh privacy warning enabled on hosted sites.
+- Operate TURN with bandwidth, allocation, and abuse quotas.
+- Use tenant- and user-attributable, short-lived TURN credentials; do not use a
+ shared static credential for the hosting offering.
+- Add a supported relay-only policy that works with secret-derived ephemeral
+ credentials for customers who require peer IP privacy.
+- Monitor TURN usage independently of Discourse request rate limits.
+
+## Optional BYOK LiveKit findings
+
+LiveKit is not part of the initial hosted offering. These findings are not mesh
+launch blockers if the settings and related outbound calls are unavailable to
+customer administrators.
+
+### 5. Customer-controlled LiveKit URL permits server-side requests
+
+**Severity:** High when exposed on shared hosting
+
+**Affected code:**
+
+- `config/settings.yml`
+- `app/validators/voice_livekit_policy_validator.rb`
+- `lib/voice/livekit/twirp.rb`
+- `lib/voice/livekit/health_check.rb`
+- `app/jobs/regular/voice_livekit_probe.rb`
+- `plugin.rb` setting-change callbacks
+
+The validator only requires a `ws://` or `wss://` prefix. `Twirp.post` converts
+that value to HTTP(S) and performs server-side POST requests to fixed LiveKit
+Twirp paths. It does not reject loopback, private, link-local, cloud metadata, or
+other hosting-internal addresses. Connectivity errors can expose HTTP status and
+a truncated response body to the administrator.
+
+A customer administrator could therefore use BYOK configuration and probes to
+reach services that are not otherwise exposed outside the hosting network.
+
+#### Required remediation
+
+- Keep the LiveKit settings locked or absent from customer administration until
+ this is fixed.
+- Require `wss://` in production.
+- Resolve and validate every destination address, rejecting loopback, private,
+ link-local, multicast, unspecified, and hosting-reserved ranges for both IPv4
+ and IPv6.
+- Revalidate on connection to address DNS rebinding and apply outbound network
+ policy as a second boundary.
+- Prefer an operator-owned egress proxy or explicit hostname allowlist.
+- Do not return upstream response bodies to customer administrators.
+
+**Status:** Remediated after this review (destination vetting via
+`FinalDestination`).
+
+- `Voice::Livekit::Twirp.post` now performs all LiveKit HTTP calls through
+ core's `FinalDestination::HTTP` instead of Excon. It resolves the host
+ itself, filters every resolved address against the private/loopback/
+ link-local/reserved IPv4+IPv6 ranges and `blocked_ip_blocks`, and hands
+ only vetted addresses to the socket layer — re-resolving on every connect,
+ which also addresses DNS rebinding. `allowed_internal_hosts` remains the
+ operator-controlled escape hatch for deliberate internal deployments.
+- A blocked destination surfaces to admins as a fixed message ("resolves to
+ an address this server is not allowed to reach"); sync calls fail closed
+ (return false) without raising into the triggering request.
+- New `VoiceLivekitUrlValidator` on `voice_livekit_url`: must be a bare
+ ws(s):// origin with a hostname and no embedded credentials, and `wss://`
+ is mandatory in production. `VoiceLivekitPolicyValidator` now requires
+ the URL to pass the same check before any non-disabled policy can be
+ enabled, so a pre-existing invalid URL cannot be activated.
+- Upstream response bodies no longer reach customer administrators: probe
+ and egress errors carry only the HTTP status code; the truncated body goes
+ to the server log for the operator.
+- Tests: `spec/lib/voice/livekit/room_service_client_spec.rb` (disallowed
+ address refused for probes and sync calls via
+ `FinalDestination::TestHelper.stub_to_fail`; probe errors exclude the
+ upstream body), `spec/lib/voice/livekit/egress_client_spec.rb` (error
+ results exclude the upstream body), and
+ `spec/validators/voice_livekit_url_validator_spec.rb` (shape checks,
+ credentials rejection, wss-required-in-production).
+- Still open from this finding's hosting guidance: an operator-owned egress
+ proxy / hostname allowlist as a second boundary, and keeping the settings
+ hidden from customer admins on shared hosting until finding 6 is also
+ resolved.
+
+### 6. LiveKit presence and media-session lifecycle diverge
+
+**Severity:** Medium to high when LiveKit is enabled
+
+`RoomsController#leave` removes Discourse presence but does not remove the
+participant's LiveKit media session unless the entire room becomes empty. A
+modified client can remain connected to the SFU while absent from the Discourse
+roster.
+
+Kicking calls `RemoveParticipant`, but the user remains eligible to request a
+new token for an open room. For self-hosted LiveKit, removal also does not revoke
+the cached token. LiveKit documents that self-hosted deployments must use short
+token TTLs and avoid issuing a replacement token after removal:
+
+<https://docs.livekit.io/frontends/reference/tokens-grants/#token-revocation>
+
+Before enabling BYOK, explicit leave should evict the SFU participant, kicks
+should create a room-instance deny entry, and token issuance should honor that
+entry.
+
+## Lower-priority observations
+
+### Contacts authorization
+
+`ContactsController#index` requires a logged-in user and analytics to be
+enabled, but does not call `guardian.can_access_voice?`. A user removed from
+the allowed groups can continue retrieving their own historical top contacts,
+durations, and session counts.
+
+### Client-controlled invite attribution
+
+`RoomsController#join` accepts `invited_by`, and `Voice::Invite.redeem!`
+creates a redeemed link-invite row without proving that a signed link or pending
+invite existed. A user can attribute their join to another user and influence
+invite analytics or badge hooks.
+
+Use signed invite tokens, or only redeem an existing server-created pending
+invite.
+
+### Analytics retention
+
+Analytics are enabled by default with 400-day retention. The scheduled purge
+removes sessions and co-presence, but invite history has no equivalent retention
+job. User deletion deliberately retains historical rows with removed user
+references.
+
+Before hosting, document collection, export, deletion, pseudonymization, and
+retention behavior for sessions, co-presence, invite attribution, and any
+recording metadata.
+
+## Positive security properties
+
+The review found several sound foundations:
+
+- Guardian checks consistently protect room visibility, private membership,
+ room management, invitations, and most participant actions.
+- authenticated state-changing endpoints retain normal Discourse CSRF
+ protection;
+- room descriptions use `PrettyText` cooking and templates use escaped output;
+- chat content and channel availability delegate to Chat's Guardian checks;
+- LiveKit participant tokens use room- and identity-scoped grants, short expiry,
+ role-dependent publishing, and no data/admin grants;
+- LiveKit webhooks verify a signed token and body hash before processing;
+- secret TURN and LiveKit settings are not exposed as client site settings;
+- mesh media travels directly between WebRTC peers rather than through the
+ Discourse application server;
+- browser speech-to-text is local by default rather than uploading call audio to
+ a transcription service.
+
+No obvious SQL injection, arbitrary file execution, unauthenticated room
+management, or direct template XSS path was identified during this review.
+
+## Verification performed
+
+The following checks were run against commit `60fc027`:
+
+- focused Ruby security-related suite: 188 examples, 0 failures;
+- Voice JavaScript suite: 181 tests, 0 failures;
+- production dependency audit: no reported advisories;
+- full dependency audit: 11 high, 4 moderate, and 1 low advisory, all reached
+ through lint/build dependency chains rather than the reviewed deployed
+ runtime bundles;
+- schema migrations were reviewed for current foreign-key, retention, and
+ cleanup behavior;
+- the plugin worktree was clean before this report was added.
+
+Passing tests confirm the currently implemented behavior; they do not mitigate
+the findings. In particular, current signaling tests explicitly permit absent
+senders and recipients.
+
+## Recommended remediation order
+
+1. ~~Bind signaling to server-attested participant sessions (created by `join`,
+ revoked on leave/kick/TTL) and add the invisible listener regression tests,
+ keeping WebRTC setup decoupled from roster propagation.~~ Done — see
+ finding 1's status.
+2. ~~Enforce room capacity atomically; make join idempotent; add rate, shape,
+ and size limits to the control plane.~~ Done — see finding 2's status.
+3. ~~Enforce stage publishing policy at the receiving browser.~~ Done — see
+ finding 3's status.
+4. Correct logged-in-only MessageBus delivery.
+5. Establish hosted TURN, privacy, retention, and monitoring policy.
+6. Lock LiveKit BYOK settings until SSRF and media-session lifecycle issues are
+ resolved. SSRF is done — see finding 5's status; the media-session
+ lifecycle divergence (finding 6) remains open.
+
diff --git a/plugins/voice/docs/security-review-2026-08-27.md b/plugins/voice/docs/security-review-2026-08-27.md
new file mode 100644
index 00000000000..6525e6b802e
--- /dev/null
+++ b/plugins/voice/docs/security-review-2026-08-27.md
@@ -0,0 +1,499 @@
+# Security review — 2026-08-27
+
+## Status
+
+This is a second-pass review of Voice at commit `5a2543b`. It follows
+`security-review-2026-08-26.md` and focuses on the native mesh WebRTC transport
+planned for Discourse free hosting with hosting-operated coturn instances.
+
+The first review's major signaling, capacity, stage-role, and LiveKit SSRF
+findings have received substantial remediation. This pass did not identify a
+new critical issue, but it found two High-severity ways to bypass guarantees
+that the first review considered resolved.
+
+The current recommendation remains **not to enable mesh mode on free hosting
+until findings 1 and 2 are fixed and the coturn launch requirements in finding
+6 are verified in the deployed environment**. Hosted video should remain
+disabled until finding 4 is fixed.
+
+This is a source review supported by automated tests and a direct Redis
+reproduction. It is not a substitute for testing deployed TURN, network,
+browser, observability, and hosting configuration.
+
+## Threat model
+
+This review retains the first review's threat model:
+
+- customer site administrators are trusted to administer their Discourse site,
+ but are not trusted with access to hosting infrastructure;
+- ordinary authenticated users may be malicious and may automate requests;
+- public rooms may be joinable by every authenticated user;
+- a malicious participant controls their browser and is not constrained by the
+ Voice client;
+- presence, room capacity, participant roles, and call termination must be
+ server-authoritative rather than cooperative client state;
+- existing peer connections continue carrying media until a peer explicitly
+ tears them down; and
+- denial-of-service and tenant isolation are release concerns on shared free
+ hosting.
+
+## Summary
+
+| Severity | Finding | Hosting status |
+| --- | --- | --- |
+| High | A session whose presence expired can re-enter a full room through heartbeat and exceed the room cap | Release blocker |
+| High | Tokenless repeated joins bypass idempotence and create unbounded analytics/control-plane work | Release blocker |
+| Medium | Access and moderation changes do not consistently revoke active media state | Fix before relying on private-room revocation or emergency call termination |
+| Medium | A modified mesh peer can bypass the video publisher cap | Keep hosted video disabled until fixed |
+| Medium | `logged_in_users` MessageBus broadcasts can still reach anonymous subscribers | Fix or prohibit the affected configuration |
+| Operational | Twelve-hour, non-tenant-scoped TURN credentials require strict shared-coturn isolation and quotas | Hosting launch requirement |
+| Low | Invite input is limited after constructing an unbounded SQL `IN` list | Harden before broad rollout |
+
+## Release-blocking findings
+
+### 1. A lapsed participant session can bypass room capacity
+
+**Severity:** High for shared/free hosting
+
+**Status:** Open
+
+**Affected code:**
+
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#heartbeat`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#livekit_token`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#signal`
+- `app/services/voice/participant_tracker.rb`
+- `app/services/voice/signal_relay.rb`
+
+`ParticipantTracker.add_within_capacity` correctly purges expired presence and
+atomically admits new participants up to the room cap. Participant sessions,
+however, live for twice the configured presence TTL so that a sleeping browser
+can recover after its roster presence lapses.
+
+Heartbeat validates that longer-lived session and then restores presence with
+plain `ParticipantTracker.add`, which does not enforce capacity. The optional
+LiveKit reconnect-token endpoint has the same uncapped restoration behavior.
+This assumes that an earlier capacity grant still reserves a slot, but roster
+expiry allows a different user to take that slot before the participant session
+expires.
+
+The bypass is:
+
+1. fill a room to capacity and retain the issued participant sessions;
+2. stop heartbeats until those participants disappear from live presence;
+3. let new users fill the released slots; and
+4. before the old sessions expire, resume heartbeat with those sessions.
+
+The old users are added without a capacity check. Once restored, they can keep
+heartbeating and remain above the cap indefinitely. Coordinated users can
+approximately double the configured room size. In mesh mode this is especially
+costly because peer connections and signaling grow quadratically.
+
+This pass reproduced the invariant break directly against test Redis. With a
+configured capacity of two, the atomic admission path filled the room with two
+new users, the original lapsed session remained valid, and the heartbeat
+restoration primitive produced:
+
+```json
+{
+ "participants": [900000002, 900000003, 900000001],
+ "configured_capacity": 2
+}
+```
+
+The same lifetime mismatch weakens signaling authority. `RoomsController#signal`
+requires a participant session but does not require current live presence, and
+`SignalRelay` accepts a recipient with a session even if their roster slot has
+expired. A participant session is therefore not equivalent to a current room
+slot during the second half of its lifetime.
+
+#### Required remediation
+
+- Replace every session-attested plain presence refresh with an atomic
+ capacity-aware refresh. A fresh participant already holding a slot must
+ refresh normally; a lapsed participant must reacquire a free slot or be
+ rejected.
+- When recovery finds a full room, revoke the stale participant session and
+ make the client perform a clean join later. Do not leave a session that can
+ continue signaling after its slot was denied.
+- Require both a valid participant session and current server-side presence for
+ signal senders and recipients. Checking Redis presence does not recreate the
+ client-side roster propagation race that participant sessions were designed
+ to avoid.
+- Apply the same primitive to heartbeat, repeat join, and LiveKit token refresh
+ so a check/add race cannot restore a slot without capacity enforcement.
+
+Regression tests should cover:
+
+- lapsed valid session plus available capacity → recovery succeeds;
+- lapsed valid session plus a full room → recovery fails, count stays at the
+ cap, and the session is revoked;
+- concurrent slot replacement and heartbeat recovery never exceed capacity;
+- a sender or recipient with a session but expired presence cannot signal; and
+- ordinary fresh heartbeats in a full room continue to work.
+
+### 2. Join idempotence depends on cooperative client input
+
+**Severity:** High for shared/free hosting
+
+**Status:** Open
+
+**Affected code:**
+
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#join`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#repeat_join?`
+- `app/jobs/scheduled/voice/close_orphaned_sessions.rb`
+- `app/models/voice/session.rb`
+
+The idempotent join branch only runs when the request supplies the exact current
+participant session ID and the user is still present. A malicious active
+participant can omit that parameter. Atomic admission then returns `:existing`,
+but the ordinary join path still:
+
+- rotates the participant session;
+- creates a new analytics `Session` row;
+- overwrites metadata to point at only the newest analytics session;
+- broadcasts a full participant roster; and
+- runs join hooks and invitation-related work.
+
+The per-user join limit is 30 requests per minute. Analytics are enabled by
+default, so one account can create up to 43,200 session rows per day while
+remaining in one room. Only the newest session is closed by a normal leave.
+`CloseOrphanedSessions` scans every open session every five minutes, but skips
+all of them while that user remains present. The attack therefore creates both
+persistent database growth and an increasingly expensive recurring scan.
+
+The previous review marked join idempotence resolved, but the implementation is
+idempotent only for a client that voluntarily echoes its current credential.
+Credentials cannot be treated as a reliable branch selector when the caller is
+the adversary.
+
+#### Required remediation
+
+- Make active presence authoritative. An already-present user without the
+ current session proof must not silently enter the full ordinary-join path.
+ Reject it, or handle it as an explicit takeover with narrowly scoped
+ semantics and a stricter rate limit.
+- Maintain at most one open analytics session per `(room_id, user_id)`. Reuse
+ or close the existing row before creating a replacement, and enforce the
+ invariant at the database layer where practical.
+- Ensure an intentional tab/device handoff closes or transfers the previous
+ participant and analytics session atomically.
+- Consider site-wide and source-IP limits in addition to the current per-user
+ limiter for the hosted service.
+- Do not rerun roster broadcasts or join hooks when admission reports that the
+ participant already exists unless an authoritative state transition occurred.
+
+Regression tests should cover:
+
+- an active participant omitting or supplying the wrong session ID cannot
+ create another open analytics session;
+- repeated valid joins remain side-effect free;
+- an explicit handoff, if supported, rotates the participant session while
+ retaining exactly one open analytics row; and
+- concurrent joins for one room/user cannot create multiple open sessions.
+
+## Other source findings
+
+### 3. Access revocation and call termination are not authoritative media revocation
+
+**Severity:** Medium
+
+**Status:** Open
+
+**Affected code:**
+
+- `app/controllers/voice/room_memberships_controller.rb`,
+ `RoomMembershipsController#destroy`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#update`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#destroy`
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#kick`
+- `app/controllers/voice/admin_rooms_controller.rb`,
+ `AdminRoomsController#destroy` and `#end_call`
+
+Removing a membership always demotes a present user to `participant`. That is
+reasonable for removing a role assignment in a public room, but in a private
+room membership is the user's access grant. Deleting it leaves the user in
+presence, retains their participant session, and broadcasts them as an ordinary
+participant.
+
+Guardian correctly denies that user on their next heartbeat, signal, or state
+request. That does not immediately stop an existing mesh peer connection:
+already-negotiated SRTP media continues until the other browsers receive a
+roster change and tear down the peer. With the default TTL and heartbeat
+cadence, the removed user can continue receiving media for approximately one
+presence-expiry window.
+
+Changing a public room to private has the same property for currently present
+non-members. The room update changes database authorization but does not evict
+participants who no longer qualify.
+
+The admin `end_call` action deletes the LiveKit room, clears the transport pin,
+and sends targeted `kicked` messages, but does not remove presence or revoke
+participant sessions. In mesh mode it relies entirely on each browser obeying
+the advisory message. Admin and room destroy similarly leave participant state
+to expire. A modified client can retain its old session, and stale state can
+cross into a subsequent call using the same room ID.
+
+Finally, a normal kick removes the current session but does not deny a new join.
+Join immediately clears the short-lived leave tombstone, so a user kicked from
+a public room can return immediately. This may be acceptable only if "kick"
+explicitly means "disconnect once" rather than moderation for the current call.
+
+#### Recommended remediation
+
+- Introduce one authoritative participant-eviction operation that closes the
+ analytics session, removes presence and metadata, revokes participant and SFU
+ credentials, clears status, broadcasts the final roster, and sends the
+ targeted client event.
+- Use it when private membership is removed, when an access-setting change
+ makes a participant ineligible, and for kick, room destruction, and admin
+ call termination.
+- Add a random call-instance ID or monotonically changing epoch to participant
+ sessions and signals. Rotate it on end-call so credentials from the previous
+ call can never address the next one.
+- Define kick semantics. If it is a moderation action, retain a deny entry for
+ the current call instance or until a manager explicitly allows re-entry.
+
+### 4. Mesh video publisher limits are advisory
+
+**Severity:** Medium when hosted video is enabled
+
+**Status:** Open; global video is disabled by default
+
+**Affected code:**
+
+- `app/controllers/voice/rooms_controller.rb`, `RoomsController#state`
+- `app/services/voice/signal_validator.rb`
+- `assets/javascripts/discourse/lib/voice/stage-roles.js`
+- `assets/javascripts/discourse/app/services/voice-webrtc.js`
+- `assets/javascripts/discourse/lib/voice/remote-stream-registry.js`
+
+The server enforces `voice_video_max_publishers` when a client reports
+`video: true` or `screen: true`. A modified mesh client does not have to report
+that state before adding video tracks to its peer connections.
+
+The receive-side policy verifies that video is enabled for the room and that a
+stage sender has a speaking role. It does not require server-attested
+`is_video_on` or `is_screen_sharing` state, nor does it require a publisher
+reservation. The unexpected track is registered. It may remain absent from the
+normal tile UI, but it still consumes peer and TURN bandwidth and browser media
+resources.
+
+The count/check/update in `RoomsController#state` is also non-atomic, allowing
+honest concurrent requests to exceed the limit. SDP validation limits bytes and
+event counts but does not limit audio/video/application media sections, so a
+malicious offer can attempt multiple unexpected tracks.
+
+#### Recommended remediation
+
+- Allocate video publisher leases atomically in Redis and represent the lease
+ in server-authoritative roster state.
+- Accept remote video only from a participant holding a current lease, and
+ stop/reject unexpected or duplicate tracks.
+- Define semantic SDP limits, including the permitted number of audio, video,
+ and data media sections.
+- Test direct attachment of video without a state grant, concurrent publisher
+ acquisition at the cap, duplicate tracks, and lease revocation.
+
+Keeping `voice_video_enabled` host-locked to false is an adequate temporary
+control for the planned voice-first mesh launch.
+
+### 5. Logged-in-only MessageBus delivery remains open
+
+**Severity:** Medium
+
+**Status:** Open from the 2026-08-26 review
+
+**Affected code:**
+
+- `lib/voice.rb`, `Voice.public_room_message_bus_targets`
+- `app/services/voice/room_broadcaster.rb`
+- `app/services/voice/directory_broadcaster.rb`
+
+`public_room_message_bus_targets` treats the `everyone`, `anonymous_users`, and
+`logged_in_users` pseudo-groups identically and publishes without targets.
+Untargeted MessageBus delivery reaches anonymous subscribers. This matches an
+administrator's intent for `everyone` or `anonymous_users`, but not for a site
+that deliberately selected `logged_in_users` while retaining anonymous web
+browsing.
+
+The result is a mismatch: anonymous HTTP requests cannot list those rooms, but
+an anonymous MessageBus client can subscribe to predictable channels and
+receive room directory entries, participant identities, roles, and state.
+
+Fix the delivery distinction or prohibit `logged_in_users` in that hosting
+configuration. Add an integration test that uses an actual anonymous
+MessageBus subscriber rather than asserting only that a publish has no target.
+
+## Hosting infrastructure finding
+
+### 6. Shared coturn requires tenant-scoped credentials and defense in depth
+
+**Severity:** Operational release blocker
+
+**Status:** Requires plugin changes and deployed-infrastructure verification
+
+**Affected code:**
+
+- `lib/voice/ice_config.rb`
+
+Voice issues standard coturn REST credentials with a 12-hour validity window
+and a username shaped as `<expiry>:<user_id>`. Any authorized user can extract
+the credential from a join response and use it from a separate TURN client for
+the remainder of that window. TURN authentication proves entitlement to use
+the relay; it does not bind traffic to a Voice room or WebRTC peer.
+
+Coturn strips the numeric expiry prefix before applying its per-user allocation
+quota. This means expiry rotation does not bypass `user-quota`, but the stable
+quota identity is only the numeric Discourse user ID. If multiple hosted sites
+share a coturn realm, unrelated users with the same ID share quota and
+attribution. A user on one tenant can consume the quota identity used by a user
+with the same ID on another tenant.
+
+Upstream references:
+
+- coturn quota normalization:
+ <https://github.com/coturn/coturn/blob/master/src/apps/relay/userdb.c#L344-L371>
+- coturn quota implementation:
+ <https://github.com/coturn/coturn/blob/master/src/apps/relay/userdb.c#L619-L657>
+- example configuration for `user-quota`, `total-quota`, `max-bps`,
+ `bps-capacity`, peer ACLs, and transport controls:
+ <https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf>
+
+Recent coturn advisories reinforce that authenticated TURN must be treated as
+an SSRF and capacity boundary:
+
+- IPv4-mapped loopback peer bypass, fixed in 4.13.0:
+ <https://github.com/coturn/coturn/security/advisories/GHSA-w4hf-cr3w-6h79>
+- peer-IP ACL/translated-address bypass, fixed in 4.13.1:
+ <https://github.com/coturn/coturn/security/advisories/GHSA-2x4g-wx24-48m4>
+- mobility allocation-quota bypass, fixed in 4.17.0:
+ <https://github.com/coturn/coturn/security/advisories/GHSA-f6hc-79w3-p8pq>
+
+The current upstream release reviewed here is 4.17.2:
+<https://github.com/coturn/coturn/releases/tag/4.17.2>.
+
+#### Required hosting controls
+
+- Include a stable, hosting-controlled tenant identifier in the username suffix,
+ for example `<expiry>:<tenant_id>:<user_id>`. Avoid customer-controlled host
+ names as the authoritative tenant ID.
+- Prefer a distinct secret/realm or stronger quota boundary per tenant where
+ operationally practical. A tenant-qualified username fixes per-user
+ collisions but does not create per-tenant total quotas in one shared realm.
+- Reduce credential validity from 12 hours to minutes and support safe
+ credential refresh for ICE restarts. Existing allocations should not require
+ a credential that remains mintable for the whole call duration.
+- Configure nonzero `user-quota`, `total-quota`, `max-bps`, and `bps-capacity`.
+ Coturn's defaults are unlimited.
+- Run coturn 4.17.2 or a later patched release. Do not enable mobility. Disable
+ RFC 6062 TCP relay when it is not needed; this is separate from accepting TURN
+ clients over TCP/TLS.
+- Explicitly deny loopback, private, link-local, multicast, ULA, cloud metadata,
+ container/service, and hosting control-plane ranges for both IPv4 and IPv6.
+- Enforce the same policy with network-level egress controls. Coturn cannot
+ infer every deployment-specific NAT64, translator, or routed private range.
+- Isolate relay hosts from databases, Redis, orchestration APIs, host agents,
+ and other privileged internal services.
+- Alert on allocations, ports, bandwidth, credential identities, authentication
+ failures, and tenant/site attribution. Test quota exhaustion and peer ACLs
+ from an untrusted client before launch.
+
+The source repository cannot establish that these deployment controls exist.
+They require a reviewed coturn configuration and network test in the hosting
+environment.
+
+## Lower-priority hardening
+
+### Invite input is bounded after query construction
+
+**Severity:** Low
+
+**Affected code:**
+
+- `app/controllers/voice/invites_controller.rb`, `InvitesController#create`
+
+The endpoint converts and deduplicates the complete `usernames` parameter,
+then places the complete list in `WHERE username_lower IN (...)`. The subsequent
+`limit(10)` restricts returned users, not the size of the Ruby allocation or SQL
+input list. The global request-body limit and a 10/minute per-user rate limit
+reduce impact, but an authorized user can still create avoidable parsing,
+allocation, and database work.
+
+Reject more than `MAX_USERS_PER_REQUEST` names before normalization and query
+construction. Add a request spec proving that an oversized list is rejected
+rather than silently truncated after querying.
+
+### Findings retained from the first review
+
+The following lower-priority observations from `security-review-2026-08-26.md`
+remain relevant and were not promoted by this pass:
+
+- contacts authorization should use the same Voice access predicate as the
+ rest of the plugin;
+- client-supplied invite attribution should be replaced with a server-issued
+ pending invite or signed token; and
+- analytics, invite, co-presence, recording, export, deletion, and
+ pseudonymization policy must be documented for hosting.
+
+The optional LiveKit media-session lifecycle remains outside the proposed
+hosted mesh configuration. The uncapped `livekit_token` presence restoration in
+finding 1 should nevertheless be fixed before enabling that integration.
+
+## Positive security properties
+
+The post-first-review changes materially improved the design:
+
+- signaling, heartbeat, and state require a server-issued participant session;
+- leave and ordinary kick revoke that session;
+- signal payloads have strict type, shape, recipient, event-count, and byte
+ limits;
+- per-user and per-room control-plane limits bound normal signaling requests;
+- the ordinary join admission check is atomic under concurrency;
+- stage receive-side policy stops unauthorized listener audio;
+- LiveKit configuration has explicit URL validation and outbound request
+ controls;
+- Guardian checks, CSRF protection, escaped templates, and Chat delegation
+ remain sound; and
+- the production JavaScript dependency audit reported no known vulnerabilities.
+
+No obvious SQL injection, arbitrary file execution, unauthenticated room
+management, direct template XSS, or secret-setting exposure was identified in
+this pass.
+
+## Verification performed
+
+The following checks were run against commit `5a2543b`:
+
+- focused server suite covering rooms, participant tracking, memberships,
+ admin room actions, and ICE configuration: 242 examples, 0 failures;
+- Voice JavaScript/QUnit run: 187 tests, 0 failures;
+- `pnpm audit --prod`: no known vulnerabilities;
+- direct test-Redis reproduction of the capacity bypass, with scoped cleanup;
+- review of current coturn quota source, configuration, releases, and 2026
+ security advisories; and
+- plugin diff/status checks before adding this report.
+
+Passing tests validate the intended cooperative flow but do not mitigate these
+findings. In particular, the current tests intentionally verify that a valid
+session restores lapsed presence, but do not fill the released capacity before
+that restoration. The end-call tests assert client messages and transport-pin
+cleanup without asserting authoritative presence/session revocation.
+
+## Recommended remediation order
+
+1. Make all presence restoration capacity-aware and require current presence
+ for signaling.
+2. Make join idempotence server-authoritative and enforce one open analytics
+ session per room/user.
+3. Establish and test the hosted coturn credential, quota, egress, version, and
+ tenant-isolation baseline.
+4. Centralize participant eviction, introduce call-instance epochs, and define
+ durable kick semantics.
+5. Correct logged-in-only MessageBus delivery or host-lock the affected
+ configuration.
+6. Keep hosted video disabled until publisher leases and receive-side
+ enforcement are authoritative.
+7. Bound invite input before SQL construction and complete the first review's
+ privacy/retention follow-ups.
diff --git a/plugins/voice/docs/subtitles-fp16-encoder.md b/plugins/voice/docs/subtitles-fp16-encoder.md
new file mode 100644
index 00000000000..2c7dd45c463
--- /dev/null
+++ b/plugins/voice/docs/subtitles-fp16-encoder.md
@@ -0,0 +1,166 @@
+# Subtitles: fp16 encoder
+
+Status (2026-08-26): **auto-selected and validated.** The worker picks fp16
+when the adapter exposes `shader-f16` and fp32 otherwise (Chromium on
+Linux). Root cause of the historical empty-string failure is diagnosed
+below. The fp16 path is validated end-to-end on real f16 hardware via
+Firefox on Linux (`STT_BROWSER=firefox` in the smoke harness), which —
+unlike Chromium — exposes `shader-f16` there.
+
+## Why we want it
+
+The Parakeet encoder runs on WebGPU in fp32 today:
+
+- Weights: `encoder-model.onnx.data` is ~2.4 GB in fp32; an fp16 encoder is
+ ~1.2 GB — half the download, disk cache, and resident VRAM.
+- Activations: onnxruntime-web's WebGPU execution provider keeps every freed
+ GPU buffer in a size-keyed free list for the lifetime of the session (no
+ eviction, no return to the driver). Since utterances arrive in many
+ distinct lengths, the pool converges to the union of all activation-buffer
+ sizes ever seen — observed growing from ~3.2 GB to ~5.5 GB over an hour of
+ live captioning. fp16 would halve every one of those buffers, on top of
+ halving the weights.
+
+On low-VRAM devices (e.g. 8 GB shared with the compositor and video decode)
+the fp32 footprint risks driver paging (massive slowdown) and eventually
+WebGPU device loss.
+
+## Symptom
+
+With an fp16 encoder, transcription **silently returns empty strings** on
+some machines — no error, no rejected promise, just blank output. The
+upstream demo (<https://ysdede.github.io/keet/>) shows the same failure
+here. This is noted in `src/stt-worker/worker.js` next to the
+`encoderQuant` default.
+
+## Root cause (diagnosed 2026-08-25)
+
+Three findings, established empirically on a Linux machine that reproduces
+the failure (RTX 5090, NVIDIA 610.57.04, Chromium 151):
+
+1. **Chromium on Linux does not expose the WebGPU `shader-f16` feature at
+ all** — on any GPU. The Vulkan driver advertises `shaderFloat16` and
+ 16-bit storage, but the adapter's feature set lacks `shader-f16`, and no
+ flag (`--enable-dawn-features`, `--enable-blink-features`,
+ `--enable-webgpu-developer-features`) turns it on. Per the Chromium
+ intent-to-ship for WebGPU f16, the feature shipped on macOS/ChromeOS
+ first and on Windows behind the DXC migration; Linux never got it.
+ "Works on some machines, fails on others" is **feature availability by
+ platform**, not driver numerics. (Firefox's WebGPU on the same
+ machine/driver _does_ expose `shader-f16` — the gap is Chromium's, not
+ Vulkan's.)
+2. **onnxruntime-web runs fp16 models anyway when the feature is missing.**
+ The JSEP WebGPU EP requests `shader-f16` on the device and prepends
+ `enable f16;` to WGSL _only if the adapter has it_, but never refuses an
+ fp16 model when it doesn't — execution proceeds and produces garbage
+ encodings, the decoder emits nothing, and no error surfaces. (Upstream
+ bug worth filing: this should be a hard error or a fallback.)
+3. **The fp16 exports themselves are numerically fine.** On the CPU EP,
+ both `grikdotnet/parakeet-tdt-0.6b-fp16` (full fp16, fp32 IO) and our
+ own mixed-precision exports match the fp32 encoder to cosine similarity
+ ≥ 0.999998 with zero NaN/Inf.
+
+The earlier overflow hypothesis is **disproved** for this model: scanning
+all float intermediates of the fp32 encoder over speech fixtures
+(`scripts/scan_overflow.py`) shows a global max |activation| of exactly
+10000.0 (the attention-mask fill constant) — far inside fp16's 65504 range.
+The transformers.js Whisper issue we cited
+(<https://github.com/huggingface/transformers.js/issues/1590>) is a
+different failure class.
+
+Community fp16 exports, for the record: `grikdotnet/parakeet-tdt-0.6b-fp16`
+(numerically clean, CUDA-validated only) and
+`Olicorne/parakeet-tdt-0.6b-v3-optimized-onnx` (fp16 files were a naive
+cast, withdrawn by the author 2026-08-23; repo remains interesting for its
+sharded fp32 encoder). Neither fails because of how it was exported — any
+fp16 export fails wherever `shader-f16` is unavailable.
+
+## Current behavior
+
+The worker (`src/stt-worker/worker.js`) resolves the encoder precision at
+init: an explicit `encoderQuant` of `"fp16"`/`"fp32"` is honored (the smoke
+harness forces it via `STT_ENCODER_QUANT`), anything else auto-selects via
+`adapter.features.has("shader-f16")`. fp16 loads the self-contained
+`encoder-model.fp16.onnx` from our model repo (fp32 IO, so parakeet.js's
+float32 feeds work unchanged); fp32 keeps the sidecar pair. Today that
+means fp16 for macOS/ChromeOS/newer-Windows Chrome, fp32 for all of Linux.
+
+Verified both ways on the same machine (RTX 5090):
+
+- Chromium (no `shader-f16`): auto picks fp32 and transcribes; forced fp16
+ reproduces the empty-string failure, as expected.
+- Firefox (`shader-f16` exposed): auto picks fp16 and the full smoke
+ harness passes — correct transcription and VAD utterances with the
+ shipped `encoder-model.fp16.onnx`.
+
+## Still open
+
+1. Consider an init warm-up canary (a fixture must transcribe to non-empty
+ text, else re-init as fp32) as a belt-and-braces fallback for genuinely
+ broken f16 drivers.
+2. Watch for Chromium enabling `shader-f16` on Linux, and consider filing
+ the ORT-web silent-execution bug upstream.
+3. The f16 kernels are only exercised on Firefox/Vulkan so far; Chromium's
+ Metal/D3D backends (where it will actually run fp16 in production) run
+ the same ORT WGSL but haven't been checked by us directly.
+
+Note: int8/fp8 are not alternatives for the encoder — WGSL has no 8-bit
+types (only packed DP4a-style dot products), ORT-web falls back off the
+WebGPU EP for quantized encoder ops (parakeet.js upgrades int8 encoder
+requests to fp32 on WebGPU backends), and fp8 does not exist in WebGPU at
+all. The int8 decoder already runs on WASM, unaffected.
+
+## Reproducing the diagnosis
+
+Checking any adapter takes one line in a devtools console:
+
+```js
+(await navigator.gpu.requestAdapter()).features.has("shader-f16");
+```
+
+The numeric findings came from running candidate encoders on
+onnxruntime's CPU EP against the fp32 reference (same mel input, compare
+outputs for NaN/Inf and cosine similarity), and from running the fp32
+encoder with all intermediates exposed as graph outputs to scan activation
+ranges. Mixed-precision exports were produced with onnxconverter-common's
+`convert_float_to_float16` (`keep_io_types=True`); none of that tooling is
+needed going forward, since the shipped fp16 file already exists in the
+model repo.
+
+The smoke harness (`scripts/smoke-stt-worker.mjs` in the
+discourse_voice_assets gem repository) now logs the adapter and
+launches Chromium with `Vulkan,VulkanFromANGLE,DefaultANGLEVulkan` —
+without the FromANGLE pair, headless Chromium silently falls back to
+SwiftShader (CPU rasterizer, no `shader-f16`, ~1000× slower encode), which
+is both a useless benchmark and an accidental repro of the no-f16 failure.
+
+## How to test
+
+The smoke harness exercises the real worker in headless Chromium; point it
+at a directory containing candidate files (the worker fetches
+`encoder-model.onnx`, `encoder-model.onnx.data` — a zero-byte file works
+for self-contained encoders — `decoder_joint-model.int8.onnx`, `vocab.txt`):
+
+```bash
+flite -t "the quick brown fox jumps over the lazy dog" /tmp/fix.wav
+STT_MODEL_DIR=/path/to/model-dir node scripts/smoke-stt-worker.mjs /tmp/fix.wav
+```
+
+Check the `adapter:` line in the output: on an adapter without
+`shader-f16`, an fp16-encoder FAIL only reproduces the availability bug and
+says nothing about the export's numerics. Use `STT_SMOKE_PORT` to give each
+model dir its own origin, since downloads are cached per-origin in the
+persistent profile.
+
+To exercise the fp16 path on Linux, run the harness in Firefox — the only
+browser exposing `shader-f16` here (WebGPU is enabled via prefs in a
+separate persistent profile):
+
+```bash
+STT_BROWSER=firefox STT_MODEL_DIR=/path/to/model-dir \
+ node scripts/smoke-stt-worker.mjs /tmp/fix.wav
+```
+
+The model dir needs `encoder-model.fp16.onnx` (self-contained; a zero-byte
+`encoder-model.onnx.data` still satisfies the fp32 branch if you force it)
+— auto-select picks fp16 there and the whole chain should PASS.
diff --git a/plugins/voice/docs/subtitles-model-mirror.md b/plugins/voice/docs/subtitles-model-mirror.md
new file mode 100644
index 00000000000..c26ab6fa477
--- /dev/null
+++ b/plugins/voice/docs/subtitles-model-mirror.md
@@ -0,0 +1,93 @@
+# Self-hosting the subtitles model (mirror)
+
+By default, live subtitles download the speech-to-text model on first use
+from Discourse's HuggingFace repository
+([Discourse/parakeet-tdt-0.6b-v3-onnx](https://huggingface.co/Discourse/parakeet-tdt-0.6b-v3-onnx),
+a clone of the upstream `ysdede/parakeet-tdt-0.6b-v3-onnx` export). Sites
+that can't (or don't want to) let browsers reach `huggingface.co` —
+airgapped deployments, enterprise networks, or anyone who prefers to
+control the bytes — can serve the model themselves and point the
+`voice_stt_model_base_url` site setting at their own mirror.
+
+Only the **model weights** are affected. The runtime bundles (worker, VAD,
+onnxruntime) are always served from the plugin's own `public/` directory and
+need no extra hosting.
+
+## What to mirror
+
+Four files from the
+[ysdede/parakeet-tdt-0.6b-v3-onnx](https://huggingface.co/ysdede/parakeet-tdt-0.6b-v3-onnx)
+repository (models are CC-BY-4.0; keep the repo's attribution requirements in
+mind), **keeping their exact filenames**, in a single flat directory:
+
+| File | Size | Purpose |
+| --- | --- | --- |
+| `encoder-model.onnx` | ~42 MB | fp32 encoder graph (runs on WebGPU) |
+| `encoder-model.onnx.data` | ~2.4 GB | encoder weights (external data referenced by the graph — the filename must not change) |
+| `decoder_joint-model.int8.onnx` | ~18 MB | int8 decoder/joint (runs on WASM) |
+| `vocab.txt` | ~100 KB | tokenizer vocabulary |
+
+```bash
+mkdir parakeet-tdt-0.6b-v3
+cd parakeet-tdt-0.6b-v3
+for f in encoder-model.onnx encoder-model.onnx.data \
+ decoder_joint-model.int8.onnx vocab.txt; do
+ curl -LO "https://huggingface.co/ysdede/parakeet-tdt-0.6b-v3-onnx/resolve/main/$f"
+done
+```
+
+No subdirectory structure is required or supported: the plugin requests
+`<base_url>/<filename>` for each of the four files, nothing else.
+
+## Hosting requirements
+
+The files are fetched by the **browser** (from a Web Worker on the forum's
+origin), not by the Discourse server, so the mirror must be reachable by your
+users and must speak CORS if it lives on a different origin:
+
+- `Access-Control-Allow-Origin: <forum origin>` (or `*`) on all four files.
+- HTTPS, if the forum is served over HTTPS (mixed content is blocked).
+- Correct `Content-Length` (any static file server does this) — it drives
+ the download progress shown in the caption overlay, and the ~2.4 GB file
+ arrives as one plain GET; resumable/range support is not needed.
+- Long-lived cache headers are still recommended (the files are immutable),
+ though the browser keeps a durable Cache API copy after the first
+ download, so mirrors are only re-hit when that storage is evicted.
+
+Example nginx location:
+
+```nginx
+location /models/parakeet-tdt-0.6b-v3/ {
+ root /var/www;
+ add_header Access-Control-Allow-Origin "https://forum.example.com";
+ add_header Cache-Control "public, max-age=31536000, immutable";
+}
+```
+
+Then set the site setting:
+
+```
+voice_stt_model_base_url = https://cdn.example.com/models/parakeet-tdt-0.6b-v3
+```
+
+(Trailing slash optional.)
+
+A custom mirror behaves exactly like the default source: streamed download
+progress in the caption overlay and a durable Cache API copy on the user's
+device.
+
+## Verifying a mirror
+
+The end-to-end smoke harness (in the discourse_voice_assets gem repository,
+alongside the shipped worker bundle) can run against a local copy of the
+mirror directory:
+
+```bash
+flite -t "the quick brown fox jumps over the lazy dog" /tmp/fix.wav
+STT_MODEL_DIR=/path/to/parakeet-tdt-0.6b-v3 \
+ node scripts/smoke-stt-worker.mjs /tmp/fix.wav
+```
+
+It loads the shipped worker in headless Chromium (WebGPU required), serves
+the model files from the given directory exactly as a mirror would, and
+fails unless the fixture transcribes.
diff --git a/plugins/voice/lib/tasks/voice.rake b/plugins/voice/lib/tasks/voice.rake
new file mode 100644
index 00000000000..67e635bf223
--- /dev/null
+++ b/plugins/voice/lib/tasks/voice.rake
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+# Emergency lever: drops every pinned voice-room transport so each room's
+# next join re-resolves against current settings. Calls already in progress
+# are not interrupted, but their next joiner may land on a different
+# transport than the current occupants — prefer the per-room "End live call"
+# admin action unless the media server is already unreachable.
+desc "Clear all pinned voice room transports"
+task "voice:clear_transport_pins" => :environment do
+ cleared = 0
+
+ Discourse
+ .redis
+ .scan_each(match: "#{Voice::ParticipantTracker::KEY_NAMESPACE}:*:transport") do |key|
+ Discourse.redis.del(key)
+ cleared += 1
+ end
+
+ puts "Cleared #{cleared} transport pin(s)."
+end
diff --git a/plugins/voice/lib/voice.rb b/plugins/voice/lib/voice.rb
new file mode 100644
index 00000000000..66c0520b624
--- /dev/null
+++ b/plugins/voice/lib/voice.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+module ::Voice
+ PLUGIN_NAME = "voice"
+ ROOM_CHANNEL_PREFIX = "/voice/rooms"
+ ROOM_INDEX_CHANNEL = "/voice/rooms/index"
+
+ # Chat::Thread custom field marking a thread as a room's voice session
+ # thread, so it can be traced back to its room long after the live session
+ # pointer in Redis has expired.
+ THREAD_ROOM_ID_FIELD = "voice_room_id"
+
+ def self.table_name_prefix
+ "voice_"
+ end
+
+ def self.enabled?
+ SiteSetting.voice_enabled
+ end
+
+ def self.room_channel(room_id)
+ "#{ROOM_CHANNEL_PREFIX}/#{room_id}"
+ end
+
+ def self.room_chat_channel(room_id)
+ "#{ROOM_CHANNEL_PREFIX}/#{room_id}/chat"
+ end
+
+ def self.room_index_channel
+ ROOM_INDEX_CHANNEL
+ end
+
+ # Pseudo-groups have no group_users rows, but a client's message-bus groups
+ # don't come only from that table (see config/initializers/004-message_bus.rb):
+ # logged-in clients carry the logged_in_users pseudo-group and anonymous
+ # clients carry anonymous_users, so targeting the allowed groups reaches
+ # exactly the visitors who may see public rooms — anonymous ones included,
+ # when they are admitted.
+ def self.public_room_message_bus_targets
+ { group_ids: SiteSetting.voice_allowed_groups_map }
+ end
+end
+
+require_relative "voice/engine"
+require_relative "voice/guardian_extension"
+require_relative "voice/ice_config"
+require_relative "voice/livekit"
+require_relative "voice/livekit/twirp"
+require_relative "voice/livekit/egress_client"
+require_relative "voice/livekit/health_check"
+require_relative "voice/livekit/room_service_client"
+require_relative "voice/livekit/webhook_verifier"
+require_relative "voice/room_hashtag_data_source"
+require_relative "voice/user_status_manager"
diff --git a/plugins/voice/lib/voice/engine.rb b/plugins/voice/lib/voice/engine.rb
new file mode 100644
index 00000000000..d8c2b7cfba9
--- /dev/null
+++ b/plugins/voice/lib/voice/engine.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+module Voice
+ class Engine < ::Rails::Engine
+ isolate_namespace Voice
+ engine_name PLUGIN_NAME
+ end
+end
diff --git a/plugins/voice/lib/voice/guardian_extension.rb b/plugins/voice/lib/voice/guardian_extension.rb
new file mode 100644
index 00000000000..b0e95d51fde
--- /dev/null
+++ b/plugins/voice/lib/voice/guardian_extension.rb
@@ -0,0 +1,148 @@
+# frozen_string_literal: true
+
+module Voice
+ module GuardianExtension
+ # Access means participating — joining rooms, calling, appearing in
+ # rosters — so it always requires authentication. Anonymous visitors are
+ # served read-only through voice_public_access? instead.
+ def can_access_voice?
+ SiteSetting.voice_enabled? && authenticated? &&
+ in_any_groups?(SiteSetting.voice_allowed_groups_map)
+ end
+
+ # Whether Voice is open to anonymous visitors, letting them browse (but
+ # not join) public rooms. Never true on login-required sites, where there
+ # are no anonymous visitors to serve.
+ def voice_public_access?
+ return false unless SiteSetting.voice_enabled?
+ return false if SiteSetting.login_required
+
+ SiteSetting.voice_allowed_groups_map.include?(Group::AUTO_GROUPS[:anonymous_users])
+ end
+
+ def can_create_voice_room?
+ return false unless can_access_voice?
+ user.in_any_groups?(SiteSetting.voice_create_room_allowed_groups_map)
+ end
+
+ # Starting a direct call is gated separately from receiving one: anyone
+ # with voice-room access can be called, but only these groups get the
+ # call button and the calls endpoint.
+ def can_start_voice_call?
+ return false unless can_access_voice?
+ user.in_any_groups?(SiteSetting.voice_direct_calls_allowed_groups_map)
+ end
+
+ # A specific user may be rung only by callers they could receive a
+ # personal message from: muting or ignoring the caller, disabling
+ # personal messages, or an allowlist that omits the caller all block the
+ # call. Staff are exempt, as they are for personal messages.
+ def can_call_voice_user?(target)
+ return false unless can_start_voice_call?
+ return false if target.blank? || target.bot? || target.id == user.id
+ return false unless target.guardian.can_access_voice?
+
+ !UserCommScreener.new(
+ acting_user: user,
+ target_user_ids: [target.id],
+ ).disallowing_pms_from_actor?(target.id)
+ end
+
+ # Being allowed to create rooms grants nothing over other people's rooms:
+ # a room is managed by site staff, its creator, and its moderators only.
+ def can_manage_voice_room?(room)
+ return false unless can_access_voice?
+ return false unless room
+
+ is_staff? || room.creator_id == user.id || room.moderator_ids.include?(user.id)
+ end
+
+ def ensure_can_manage_voice_room!(room)
+ unless can_manage_voice_room?(room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ def ensure_can_create_voice_room!
+ unless can_create_voice_room?
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ def can_join_voice_room?(room)
+ return false unless can_access_voice?
+ return false unless room
+
+ room.public? || room.member_ids.include?(user.id) || can_manage_voice_room?(room)
+ end
+
+ def ensure_can_join_voice_room!(room)
+ unless can_join_voice_room?(room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ # Inviting is sharing access you already have: anyone who can join a
+ # public room may invite others to it, while a private room's roster is a
+ # management concern — inviting there grants a membership.
+ def can_invite_to_voice_room?(room)
+ return false unless can_join_voice_room?(room)
+
+ room.public? || can_manage_voice_room?(room)
+ end
+
+ def ensure_can_invite_to_voice_room!(room)
+ unless can_invite_to_voice_room?(room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ def can_see_voice_room?(room)
+ return false unless room
+ return true if can_join_voice_room?(room)
+
+ # Anonymous and not-yet-authorized visitors may browse public rooms when
+ # access is open to everyone. Joining still requires authentication.
+ voice_public_access? && room.public?
+ end
+
+ def ensure_can_see_voice_room!(room)
+ unless can_see_voice_room?(room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ def can_flag_voice_user?(room, target_user)
+ return false unless can_join_voice_room?(room)
+ return false if target_user.blank? || target_user.bot?
+
+ target_user.id != user.id
+ end
+
+ def ensure_can_flag_voice_user!(room, target_user)
+ unless can_flag_voice_user?(room, target_user)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+
+ def can_speak_in_voice_room?(room)
+ return true if room.open?
+ return true if user&.admin?
+ membership = room.room_memberships.find { |m| m.user_id == user&.id }
+ membership&.can_speak? || false
+ end
+
+ # Only stage-room listeners have anything to request — anyone who can
+ # already speak (including admins and everyone in open rooms) cannot.
+ def can_request_to_speak_in_voice_room?(room)
+ return false unless can_join_voice_room?(room)
+ room.stage? && !can_speak_in_voice_room?(room)
+ end
+
+ def ensure_can_request_to_speak_in_voice_room!(room)
+ unless can_request_to_speak_in_voice_room?(room)
+ raise Discourse::InvalidAccess.new(I18n.t("voice.errors.not_authorized"))
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/ice_config.rb b/plugins/voice/lib/voice/ice_config.rb
new file mode 100644
index 00000000000..019cf6a85dd
--- /dev/null
+++ b/plugins/voice/lib/voice/ice_config.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module Voice
+ # Builds the RTCPeerConnection ICE configuration delivered to clients on
+ # room join. TURN servers come from two independent lists: voice_turn_servers
+ # uses the static username/password pair, while voice_turn_secret_servers
+ # gets credentials minted per user with the TURN REST API scheme (coturn's
+ # use-auth-secret), so both kinds of deployment can coexist.
+ module IceConfig
+ # coturn only checks the expiry embedded in the username when a new
+ # allocation is created, so this needs to outlast credential mint →
+ # peer creation gaps (late joiners, ICE restarts), not the call itself.
+ EPHEMERAL_CREDENTIAL_TTL = 12.hours
+
+ def self.payload(user)
+ { servers: servers(user), transport_policy: transport_policy }
+ end
+
+ def self.servers(user)
+ stun_urls.map { |url| { urls: url } } + static_turn_servers + ephemeral_turn_servers(user)
+ end
+
+ def self.static_turn_servers
+ username = SiteSetting.voice_turn_username
+ credential = SiteSetting.voice_turn_credential
+
+ static_turn_urls.map do |url|
+ server = { urls: url }
+ server[:username] = username if username.present?
+ server[:credential] = credential if credential.present?
+ server
+ end
+ end
+
+ def self.ephemeral_turn_servers(user)
+ return [] if ephemeral_turn_urls.empty? || SiteSetting.voice_turn_secret.blank?
+
+ username, credential = ephemeral_credentials(user)
+ ephemeral_turn_urls.map { |url| { urls: url, username: username, credential: credential } }
+ end
+
+ # Expiry-first username and HMAC-SHA1 credential are dictated by the
+ # TURN REST API spec. coturn drops the numeric expiry before applying
+ # user-quota, so the hostname:user_id remainder is the quota identity —
+ # without it, same-numbered users on different sites sharing a coturn
+ # realm would share quota. It also attributes relay traffic to a site
+ # in TURN server logs.
+ def self.ephemeral_credentials(user)
+ username =
+ "#{EPHEMERAL_CREDENTIAL_TTL.from_now.to_i}:#{Discourse.current_hostname}:#{user.id}"
+ digest = OpenSSL::HMAC.digest("SHA1", SiteSetting.voice_turn_secret, username)
+ [username, Base64.strict_encode64(digest)]
+ end
+
+ # A TURN-only setup with static credentials keeps the historical
+ # relay-only behavior. Secret-authenticated TURN keeps the policy at
+ # "all" even without STUN: server-reflexive candidates come from the
+ # (authenticated) TURN allocation, so direct connections still work.
+ def self.transport_policy
+ ephemeral_active = ephemeral_turn_urls.any? && SiteSetting.voice_turn_secret.present?
+
+ if stun_urls.empty? && !ephemeral_active && static_turn_urls.any?
+ "relay"
+ else
+ "all"
+ end
+ end
+
+ def self.stun_urls
+ parse_url_list(SiteSetting.voice_stun_servers)
+ end
+
+ def self.static_turn_urls
+ parse_url_list(SiteSetting.voice_turn_servers)
+ end
+
+ def self.ephemeral_turn_urls
+ parse_url_list(SiteSetting.voice_turn_secret_servers)
+ end
+
+ def self.parse_url_list(setting)
+ setting.to_s.split("|").map(&:strip).reject(&:empty?)
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit.rb b/plugins/voice/lib/voice/livekit.rb
new file mode 100644
index 00000000000..d0bc72423ce
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Raised when an access token cannot be minted (typically a half-deleted
+ # configuration on a room whose live call is already pinned to LiveKit).
+ class MintError < StandardError
+ end
+
+ TOKEN_TTL = 10.minutes
+ LAST_WEBHOOK_KEY = "voice:livekit:last_webhook_at"
+ LAST_WEBHOOK_TTL = 7.days
+
+ def self.configured?
+ SiteSetting.voice_livekit_url.present? && SiteSetting.voice_livekit_api_key.present? &&
+ SiteSetting.voice_livekit_api_secret.present?
+ end
+
+ def self.available_for?(room)
+ return false unless configured?
+
+ case SiteSetting.voice_livekit_room_policy
+ when "all_rooms"
+ true
+ when "per_room"
+ room.livekit_enabled
+ else
+ false
+ end
+ end
+
+ # Room id, not slug — slugs are mutable. The database prefix keeps rooms
+ # from different sites on a shared cluster apart as defense in depth.
+ def self.room_name(room)
+ "#{room_name_prefix}-r#{room.id}"
+ end
+
+ # Inverse of `room_name`, for webhook events: the room id encoded in a
+ # LiveKit room name, or nil for names outside this site's namespace
+ # (other sites on a shared server, rooms created by other tools).
+ def self.room_id_from_name(name)
+ match = /\A#{Regexp.escape(room_name_prefix)}-r(\d+)\z/.match(name.to_s)
+ match && match[1].to_i
+ end
+
+ def self.room_name_prefix
+ SiteSetting.voice_livekit_room_prefix.presence ||
+ RailsMultisite::ConnectionManagement.current_db
+ end
+
+ # Freshness marker for the admin status panel. Webhooks are a
+ # reconcile-only backstop, so a configured server that stopped delivering
+ # them is a warning there, never an error.
+ def self.touch_last_webhook!
+ Discourse.redis.setex(LAST_WEBHOOK_KEY, LAST_WEBHOOK_TTL.to_i, Time.now.to_f)
+ end
+
+ def self.last_webhook_at
+ raw = Discourse.redis.get(LAST_WEBHOOK_KEY)
+ raw.present? ? Time.at(raw.to_f) : nil
+ end
+
+ # The track sources a publisher may send, matching the room's
+ # capabilities. Lowercase is the access-token grant spelling; RoomService
+ # permission updates use the same names uppercased (the proto enum).
+ def self.publish_sources(room, can_publish)
+ return [] unless can_publish
+
+ sources = ["microphone"]
+ sources.concat(%w[camera screen_share screen_share_audio]) if room.video_allowed?
+ sources
+ end
+
+ # Least-privilege HS256 JWT: a leaked token can only join this one room,
+ # as this one user, for TOKEN_TTL. Guardian remains the sole authority —
+ # callers only mint for users who passed `ensure_can_join_voice_room!`.
+ def self.mint_token(user:, room:, guardian:)
+ raise MintError, "LiveKit is not fully configured" unless configured?
+
+ can_publish = guardian.can_speak_in_voice_room?(room)
+ sources = publish_sources(room, can_publish)
+
+ payload = {
+ iss: SiteSetting.voice_livekit_api_key,
+ sub: user.id.to_s,
+ name: user.username,
+ exp: TOKEN_TTL.from_now.to_i,
+ video: {
+ room: room_name(room),
+ roomJoin: true,
+ canSubscribe: true,
+ canPublish: can_publish,
+ canPublishSources: sources,
+ canPublishData: false,
+ canUpdateOwnMetadata: false,
+ roomCreate: false,
+ roomList: false,
+ roomAdmin: false,
+ roomRecord: false,
+ recorder: false,
+ hidden: false,
+ },
+ }
+
+ JWT.encode(payload, SiteSetting.voice_livekit_api_secret, "HS256")
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit/egress_client.rb b/plugins/voice/lib/voice/livekit/egress_client.rb
new file mode 100644
index 00000000000..ac1b3ecf02d
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit/egress_client.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Twirp-JSON client for LiveKit's Egress service, which records rooms
+ # server-side. Where the recording lands (S3, GCS, local disk) is the
+ # egress deployment's own configuration — Discourse only passes a
+ # filepath, so no storage credentials live here.
+ #
+ # Unlike RoomServiceClient's fire-and-forget sync calls, these return a
+ # structured result: the caller (RecordingManager) must know whether a
+ # recording actually started before telling a room it is being recorded.
+ class EgressClient
+ # Starting an egress spins up a recorder process on the media server,
+ # which is much slower than a RoomService metadata call.
+ TIMEOUT_SECONDS = 10
+
+ class << self
+ def start_room_composite(room, filepath:)
+ request(
+ "StartRoomCompositeEgress",
+ roomName: Livekit.room_name(room),
+ audioOnly: !room.video_allowed?,
+ fileOutputs: [{ filepath: filepath }],
+ )
+ end
+
+ def stop(egress_id)
+ request("StopEgress", egressId: egress_id)
+ end
+
+ def list(egress_id:)
+ request("ListEgress", egressId: egress_id)
+ end
+
+ private
+
+ def request(method, body)
+ return { ok: false, error: "LiveKit is not configured" } unless Livekit.configured?
+
+ response =
+ Twirp.post(
+ service: "Egress",
+ method: method,
+ body: body,
+ grants: {
+ roomRecord: true,
+ },
+ timeout: TIMEOUT_SECONDS,
+ )
+
+ if response.status == 200
+ { ok: true, data: JSON.parse(response.body) }
+ else
+ # The upstream body goes to the log for the operator; the result
+ # surfaced to the UI only carries the status code.
+ Rails.logger.warn(
+ "[voice-livekit] #{method} failed: " \
+ "HTTP #{response.status} #{response.body.to_s.truncate(200)}",
+ )
+ { ok: false, error: "HTTP #{response.status}" }
+ end
+ rescue FinalDestination::SSRFDetector::DisallowedIpError
+ {
+ ok: false,
+ error: "The LiveKit URL resolves to an address this server is not allowed to reach",
+ }
+ rescue StandardError => e
+ Rails.logger.warn("[voice-livekit] #{method} failed: #{e.class} #{e.message}")
+ { ok: false, error: "#{e.class}: #{e.message}" }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit/health_check.rb b/plugins/voice/lib/voice/livekit/health_check.rb
new file mode 100644
index 00000000000..bfba12b10fb
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit/health_check.rb
@@ -0,0 +1,129 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Diagnostics behind the admin status panel and the one-shot probe job:
+ # config-time connectivity checks (token self-mint, RoomService reach)
+ # plus a Redis-presence vs LiveKit-participants diff for live rooms — the
+ # triage view for "connects but no media" and ghost-participant reports.
+ # Results carry booleans, latencies and error strings; never setting
+ # values — the API secret must not be reconstructable from any payload.
+ module HealthCheck
+ LAST_PROBE_KEY = "voice:livekit:last_probe"
+ LAST_PROBE_TTL = 7.days
+
+ def self.settings_status
+ {
+ url_present: SiteSetting.voice_livekit_url.present?,
+ api_key_present: SiteSetting.voice_livekit_api_key.present?,
+ api_secret_present: SiteSetting.voice_livekit_api_secret.present?,
+ policy: SiteSetting.voice_livekit_room_policy,
+ }
+ end
+
+ # Signs and verifies a token locally with the configured key pair — the
+ # cheapest "can we mint at all" check, catching config problems (blank
+ # or truncated secret) without touching the network. Whether the server
+ # *accepts* our signatures is what `server_check` answers: ListRooms
+ # authenticates with a token minted the same way.
+ def self.token_check
+ token =
+ JWT.encode(
+ {
+ iss: SiteSetting.voice_livekit_api_key,
+ exp: 1.minute.from_now.to_i,
+ video: {
+ roomList: true,
+ },
+ },
+ SiteSetting.voice_livekit_api_secret,
+ "HS256",
+ )
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256")
+ { ok: true }
+ rescue StandardError => e
+ { ok: false, error: "#{e.class}: #{e.message}" }
+ end
+
+ def self.server_check
+ result = RoomServiceClient.list_rooms
+
+ if result[:ok]
+ {
+ ok: true,
+ latency_ms: result[:latency_ms],
+ room_count: result[:data]["rooms"].to_a.size,
+ }
+ else
+ { ok: false, latency_ms: result[:latency_ms], error: result[:error] }
+ end
+ end
+
+ def self.connectivity_check
+ token = token_check
+ server = server_check
+
+ { ok: token[:ok] && server[:ok], checked_at: Time.now.utc.iso8601, token:, server: }
+ end
+
+ def self.store_probe!(result)
+ Discourse.redis.setex(LAST_PROBE_KEY, LAST_PROBE_TTL.to_i, result.to_json)
+ end
+
+ def self.last_probe
+ raw = Discourse.redis.get(LAST_PROBE_KEY)
+ raw.present? ? JSON.parse(raw, symbolize_names: true) : nil
+ end
+
+ def self.clear_probe!
+ Discourse.redis.del(LAST_PROBE_KEY)
+ end
+
+ # Every room currently pinned to livekit, with the Redis-side roster
+ # and (when `probe_participants` — callers pass false when the server
+ # is already known unreachable, to avoid stacking per-room timeouts)
+ # the identities LiveKit actually has connected. Pinned rooms are
+ # always recently active: the pin's TTL is refreshed by joins and
+ # heartbeats, which also touch the recently-active set.
+ def self.pinned_rooms_status(probe_participants: true)
+ room_ids =
+ ParticipantTracker.recently_active_room_ids.select do |room_id|
+ ParticipantTracker.pinned_transport(room_id) == "livekit"
+ end
+ return [] if room_ids.empty?
+
+ Voice::Room
+ .where(id: room_ids)
+ .order(:id)
+ .map { |room| room_status(room, probe_participants:) }
+ end
+
+ def self.room_status(room, probe_participants:)
+ status = {
+ room_id: room.id,
+ name: room.name,
+ presence_user_ids: ParticipantTracker.user_ids(room.id).sort,
+ }
+ return status unless probe_participants
+
+ result = RoomServiceClient.list_participants(Livekit.room_name(room))
+ return status.merge(error: result[:error]) if !result[:ok]
+
+ livekit_ids =
+ result[:data]["participants"]
+ .to_a
+ .filter_map do |participant|
+ id = participant["identity"].to_i
+ id if id.positive?
+ end
+ .sort
+
+ status.merge(
+ livekit_user_ids: livekit_ids,
+ missing_on_livekit: status[:presence_user_ids] - livekit_ids,
+ missing_in_presence: livekit_ids - status[:presence_user_ids],
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit/room_service_client.rb b/plugins/voice/lib/voice/livekit/room_service_client.rb
new file mode 100644
index 00000000000..38dad0b5f88
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit/room_service_client.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Minimal Twirp-JSON client for the three RoomService calls that keep the
+ # SFU in sync with Discourse-side moderation and lifecycle events. Every
+ # call is best-effort and no-ops for rooms not pinned to LiveKit: the SFU
+ # being slow or down must never fail the Discourse request that triggered
+ # the call, and mesh rooms must make zero HTTP requests.
+ class RoomServiceClient
+ TIMEOUT_SECONDS = 2
+
+ class << self
+ def remove_participant(room, user_id)
+ call(room, "RemoveParticipant", body: { identity: user_id.to_s })
+ end
+
+ # UpdateParticipant replaces the participant's whole permission
+ # object, so this sends the full set mirroring the access-token
+ # grants — sending only `canPublish` would silently revoke
+ # `canSubscribe` and deafen the participant.
+ def update_participant(room, user)
+ can_publish = user.guardian.can_speak_in_voice_room?(room)
+ call(
+ room,
+ "UpdateParticipant",
+ body: {
+ identity: user.id.to_s,
+ permission: {
+ canSubscribe: true,
+ canPublish: can_publish,
+ canPublishData: false,
+ canPublishSources: Livekit.publish_sources(room, can_publish).map(&:upcase),
+ hidden: false,
+ recorder: false,
+ },
+ },
+ )
+ end
+
+ def delete_room(room)
+ # LiveKit guards DeleteRoom behind the roomCreate grant; a
+ # room-scoped roomAdmin token gets "permissions denied".
+ call(room, "DeleteRoom", grants: { roomCreate: true })
+ end
+
+ # Diagnostic probes for the admin status panel. Unlike the sync calls
+ # above they run regardless of any room's transport pin, and return a
+ # structured result — latency and an error string for the admin to
+ # read — instead of a boolean plus a log line.
+
+ def list_rooms
+ probe("ListRooms", grants: { roomList: true })
+ end
+
+ def list_participants(livekit_room)
+ probe(
+ "ListParticipants",
+ body: {
+ room: livekit_room,
+ },
+ grants: {
+ roomAdmin: true,
+ room: livekit_room,
+ },
+ )
+ end
+
+ private
+
+ def sync?(room)
+ Livekit.configured? && Voice::ParticipantTracker.pinned_transport(room.id) == "livekit"
+ end
+
+ def call(room, method, body: {}, grants: { roomAdmin: true })
+ return unless sync?(room)
+
+ livekit_room = Livekit.room_name(room)
+ response = post(method, body.merge(room: livekit_room), grants.merge(room: livekit_room))
+
+ if response.status == 200
+ true
+ elsif method == "DeleteRoom" && response.status == 404
+ # The SFU tears an emptied room down on its own, so the last
+ # leave's DeleteRoom routinely races it — already-gone is the
+ # desired end state, not a fault worth a Logster entry.
+ Rails.logger.debug("[voice-livekit] DeleteRoom no-op for room #{room.id}: already gone")
+ true
+ else
+ Rails.logger.warn(
+ "[voice-livekit] #{method} failed for room #{room.id}: " \
+ "HTTP #{response.status} #{response.body.to_s.truncate(200)}",
+ )
+ false
+ end
+ rescue StandardError => e
+ Rails.logger.warn(
+ "[voice-livekit] #{method} failed for room #{room.id}: #{e.class} #{e.message}",
+ )
+ false
+ end
+
+ def probe(method, body: {}, grants:)
+ return { ok: false, error: "LiveKit is not configured" } unless Livekit.configured?
+
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ response = post(method, body, grants)
+ latency_ms = elapsed_ms(started)
+
+ if response.status == 200
+ { ok: true, latency_ms:, data: JSON.parse(response.body) }
+ else
+ # The upstream body goes to the log for the operator; the result
+ # shown to admins only carries the status code.
+ Rails.logger.warn(
+ "[voice-livekit] #{method} probe failed: " \
+ "HTTP #{response.status} #{response.body.to_s.truncate(200)}",
+ )
+ { ok: false, latency_ms:, error: "HTTP #{response.status}" }
+ end
+ rescue FinalDestination::SSRFDetector::DisallowedIpError
+ {
+ ok: false,
+ latency_ms: elapsed_ms(started),
+ error: "The LiveKit URL resolves to an address this server is not allowed to reach",
+ }
+ rescue StandardError => e
+ { ok: false, latency_ms: elapsed_ms(started), error: "#{e.class}: #{e.message}" }
+ end
+
+ def elapsed_ms(started)
+ ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
+ end
+
+ def post(method, body, grants)
+ Twirp.post(
+ service: "RoomService",
+ method: method,
+ body: body,
+ grants: grants,
+ timeout: TIMEOUT_SECONDS,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit/twirp.rb b/plugins/voice/lib/voice/livekit/twirp.rb
new file mode 100644
index 00000000000..9cb3bde79c9
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit/twirp.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Shared HTTP layer for LiveKit's Twirp-JSON services (RoomService,
+ # Egress). Callers own error handling and timeouts; this only builds the
+ # request and signs the short-lived admin token that carries the grants.
+ #
+ # The destination comes from an admin-editable setting, so requests go
+ # through FinalDestination::HTTP: it resolves the host itself, refuses
+ # loopback/private/link-local/reserved addresses, and hands only the
+ # vetted addresses to the socket layer — re-resolving on every connect,
+ # which also covers DNS rebinding.
+ module Twirp
+ TOKEN_TTL = 1.minute
+
+ Response = Struct.new(:status, :body)
+
+ def self.post(service:, method:, body:, grants:, timeout:)
+ uri = URI.parse("#{api_base_url}/twirp/livekit.#{service}/#{method}")
+
+ response =
+ FinalDestination::HTTP.start(
+ uri.host,
+ uri.port,
+ use_ssl: uri.scheme == "https",
+ open_timeout: timeout,
+ read_timeout: timeout,
+ write_timeout: timeout,
+ ) do |http|
+ http.post(
+ uri.request_uri,
+ body.to_json,
+ {
+ "Content-Type" => "application/json",
+ "Authorization" => "Bearer #{admin_token(grants)}",
+ },
+ )
+ end
+
+ Response.new(response.code.to_i, response.body)
+ end
+
+ # The Twirp services listen over HTTP(S) on the same host that serves
+ # the SFU's WebSocket signaling.
+ def self.api_base_url
+ SiteSetting.voice_livekit_url.sub(/\Awss:/, "https:").sub(/\Aws:/, "http:")
+ end
+
+ def self.admin_token(grants)
+ payload = {
+ iss: SiteSetting.voice_livekit_api_key,
+ exp: TOKEN_TTL.from_now.to_i,
+ video: grants,
+ }
+ JWT.encode(payload, SiteSetting.voice_livekit_api_secret, "HS256")
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/livekit/webhook_verifier.rb b/plugins/voice/lib/voice/livekit/webhook_verifier.rb
new file mode 100644
index 00000000000..a554854d074
--- /dev/null
+++ b/plugins/voice/lib/voice/livekit/webhook_verifier.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module Voice
+ module Livekit
+ # Verifies LiveKit webhook deliveries. The Authorization header carries a
+ # short-lived HS256 JWT signed with the API secret whose `sha256` claim is
+ # the base64 digest of the exact request body — checking it makes the
+ # payload itself tamper-proof, not just the token's claims.
+ class WebhookVerifier
+ class VerificationError < StandardError
+ end
+
+ def self.verify!(authorization:, body:)
+ raise VerificationError, "LiveKit is not configured" if !Livekit.configured?
+
+ token = authorization.to_s.delete_prefix("Bearer ").strip
+ raise VerificationError, "missing Authorization token" if token.blank?
+
+ begin
+ claims, _headers =
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256")
+ rescue JWT::DecodeError => e
+ raise VerificationError, "invalid token (#{e.class})"
+ end
+
+ if claims["iss"] != SiteSetting.voice_livekit_api_key
+ raise VerificationError, "token issued for a different API key"
+ end
+
+ digest = Digest::SHA256.base64digest(body)
+ if !ActiveSupport::SecurityUtils.secure_compare(claims["sha256"].to_s, digest)
+ raise VerificationError, "body hash mismatch"
+ end
+
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/voice/lib/voice/room_hashtag_data_source.rb b/plugins/voice/lib/voice/room_hashtag_data_source.rb
new file mode 100644
index 00000000000..db84c90ed08
--- /dev/null
+++ b/plugins/voice/lib/voice/room_hashtag_data_source.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module Voice
+ class RoomHashtagDataSource
+ def self.enabled?
+ SiteSetting.voice_enabled
+ end
+
+ def self.icon
+ "microphone-lines"
+ end
+
+ def self.type
+ "room"
+ end
+
+ def self.room_to_hashtag_item(room)
+ HashtagAutocompleteService::HashtagItem.new.tap do |item|
+ item.text = room.name
+ item.description = room.description
+ item.slug = room.slug
+ item.icon = room.stage? ? "podcast" : icon
+ item.style_type = "icon"
+ item.relative_url = "#{Discourse.base_path}/voice/r/#{room.slug}"
+ item.type = type
+ item.id = room.id
+ end
+ end
+
+ def self.find_by_ids(guardian, ids)
+ visible_rooms(guardian, Voice::Room.where(id: ids)).map { |room| room_to_hashtag_item(room) }
+ end
+
+ def self.lookup(guardian, slugs)
+ return [] if slugs.blank?
+
+ visible_rooms(
+ guardian,
+ Voice::Room.where("LOWER(slug) IN (?)", slugs.map(&:downcase)),
+ ).map { |room| room_to_hashtag_item(room) }
+ end
+
+ def self.search(
+ guardian,
+ term,
+ limit,
+ condition = HashtagAutocompleteService.search_conditions[:contains]
+ )
+ escaped_term = ActiveRecord::Base.sanitize_sql_like(term)
+ pattern =
+ if condition == HashtagAutocompleteService.search_conditions[:starts_with]
+ "#{escaped_term}%"
+ else
+ "%#{escaped_term}%"
+ end
+
+ visible_rooms(
+ guardian,
+ Voice::Room.where("slug ILIKE :pattern OR name ILIKE :pattern", pattern: pattern),
+ ).take(limit).map { |room| room_to_hashtag_item(room) }
+ end
+
+ def self.search_sort(search_results, _term)
+ search_results.sort_by { |result| result.text.downcase }
+ end
+
+ def self.search_without_term(guardian, limit)
+ visible_rooms(guardian, Voice::Room.all).take(limit).map { |room| room_to_hashtag_item(room) }
+ end
+
+ # Visibility is a per-room Guardian question (membership, public flag,
+ # manager status), so it can't be expressed as a SQL scope; room counts
+ # are small, so filtering loaded records matches RoomsController#index.
+ def self.visible_rooms(guardian, scope)
+ return [] unless guardian.can_access_voice? || guardian.voice_public_access?
+
+ scope
+ .persistent
+ .includes(:room_memberships)
+ .order(:name)
+ .select { |room| guardian.can_see_voice_room?(room) }
+ end
+ private_class_method :visible_rooms
+ end
+end
diff --git a/plugins/voice/lib/voice/user_extension.rb b/plugins/voice/lib/voice/user_extension.rb
new file mode 100644
index 00000000000..96c8e9a80d0
--- /dev/null
+++ b/plugins/voice/lib/voice/user_extension.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module Voice
+ module UserExtension
+ extend ActiveSupport::Concern
+
+ included do
+ # No dependent option: a deleted creator's rooms are reassigned to the
+ # system user by the plugin's user_destroyed handler, not destroyed.
+ has_many :voice_rooms, class_name: "Voice::Room", foreign_key: :creator_id
+ end
+ end
+end
+
+::User.include Voice::UserExtension
diff --git a/plugins/voice/lib/voice/user_status_manager.rb b/plugins/voice/lib/voice/user_status_manager.rb
new file mode 100644
index 00000000000..dea933ebc40
--- /dev/null
+++ b/plugins/voice/lib/voice/user_status_manager.rb
@@ -0,0 +1,115 @@
+# frozen_string_literal: true
+
+module Voice
+ class UserStatusManager
+ EMOJI = "studio_microphone"
+ AFK_EMOJI = "zzz"
+ # Users whose current status was written by us. Emoji alone can't identify
+ # ownership — anyone can pick zzz from the status picker — and the sweep
+ # must never touch a status it didn't set. Self-healing: heartbeats
+ # re-add, and Redis drops the key once the set empties.
+ OWNERS_KEY = "voice:status_owners"
+ # A status younger than this is skipped by the sweep: it may have been set
+ # by a join that raced the sweep's liveness snapshot, and the heartbeat
+ # only refreshes statuses that still exist, so a wrong clear would stick.
+ STALE_GRACE_PERIOD = 30.seconds
+
+ # Statuses carry no ends_at: they mirror room presence, not a timer, so
+ # the tooltip shows no "until" line. Leave/kick clear them directly;
+ # crashed or lapsed clients are reaped by clear_stale_statuses.
+ def self.set_voice_status(user, room)
+ return unless SiteSetting.enable_user_status
+ return unless SiteSetting.voice_auto_status_enabled
+ return if user_has_non_voice_status?(user)
+
+ set_status(user, status_description(room), EMOJI)
+ end
+
+ def self.set_afk_status(user, room)
+ return unless SiteSetting.enable_user_status
+ return unless voice_status_active?(user)
+
+ set_status(user, status_description(room, afk: true), AFK_EMOJI)
+ end
+
+ def self.clear_voice_status(user)
+ return unless SiteSetting.enable_user_status
+
+ Discourse.redis.srem(OWNERS_KEY, user.id)
+ return unless voice_status_active?(user)
+
+ user.clear_status!
+ end
+
+ # Reaps owned statuses whose user is no longer live in any room — the
+ # backstop for exits that never hit leave/kick (crashed client, dead
+ # network, sleeping laptop). Only statuses we set are candidates.
+ def self.clear_stale_statuses(live_user_ids)
+ return unless SiteSetting.enable_user_status
+
+ owner_ids = Discourse.redis.smembers(OWNERS_KEY).map(&:to_i)
+ stale_ids = owner_ids - live_user_ids
+ return if stale_ids.empty?
+
+ released_ids = []
+ users_by_id = User.where(id: stale_ids).includes(:user_status).index_by(&:id)
+ stale_ids.each do |user_id|
+ user = users_by_id[user_id]
+ status = user&.user_status
+
+ if user.nil? || status.nil? || !voice_emoji?(status.emoji)
+ # Deleted user, or the status was since cleared/replaced: ownership
+ # lapsed on its own.
+ released_ids << user_id
+ elsif status.set_at <= STALE_GRACE_PERIOD.ago
+ user.clear_status!
+ released_ids << user_id
+ end
+ # Within the grace window: a join may have raced this sweep's liveness
+ # snapshot — the next run decides.
+ end
+
+ Discourse.redis.srem(OWNERS_KEY, released_ids) if released_ids.any?
+ end
+
+ def self.voice_status_active?(user)
+ status = user.user_status
+ status && !status.expired? && voice_emoji?(status.emoji)
+ end
+
+ # Statuses are visible site-wide, so a non-public room's name must not
+ # appear in them — even room members get the generic description.
+ private_class_method def self.status_description(room, afk: false)
+ prefix = afk ? "afk_" : ""
+ if room.public?
+ I18n.t("voice.user_status.#{prefix}in_room", room_name: room.name)
+ else
+ I18n.t("voice.user_status.#{prefix}in_private_room")
+ end
+ end
+
+ # Without an expiry to roll, an unchanged status needs no upsert — this
+ # keeps the every-beat heartbeat call from republishing over message bus.
+ # A matching status that still carries an ends_at (written before expiries
+ # were dropped) must be rewritten, or it would expire out from under a
+ # live user.
+ private_class_method def self.set_status(user, description, emoji)
+ status = user.user_status
+ unless status && status.ends_at.nil? && status.description == description &&
+ status.emoji == emoji
+ user.set_status!(description, emoji)
+ end
+
+ Discourse.redis.sadd(OWNERS_KEY, user.id)
+ end
+
+ private_class_method def self.user_has_non_voice_status?(user)
+ status = user.user_status
+ status && !status.expired? && !voice_emoji?(status.emoji)
+ end
+
+ private_class_method def self.voice_emoji?(emoji)
+ [EMOJI, AFK_EMOJI].include?(emoji)
+ end
+ end
+end
diff --git a/plugins/voice/package.json b/plugins/voice/package.json
new file mode 100644
index 00000000000..bce67102625
--- /dev/null
+++ b/plugins/voice/package.json
@@ -0,0 +1,9 @@
+{
+ "private": true,
+ "scripts": {
+ "voice:bots": "node scripts/voice-fake-participants.mjs"
+ },
+ "dependencies": {
+ "discourse": "npm:@discourse/types@*"
+ }
+}
diff --git a/plugins/voice/plugin.rb b/plugins/voice/plugin.rb
new file mode 100644
index 00000000000..08326df60d5
--- /dev/null
+++ b/plugins/voice/plugin.rb
@@ -0,0 +1,208 @@
+# frozen_string_literal: true
+
+# name: voice
+# about: Voice chat rooms powered by WebRTC inside Discourse
+# version: 0.1
+# authors: Discourse Contributors
+# url: https://github.com/discourse/discourse/tree/main/plugins/voice
+
+require "discourse_voice_assets"
+
+# The large media assets (wasm engines, ML models, vendored SDK bundles) ship
+# in the discourse_voice_assets gem under stable filenames. Link its vendor
+# tree into the plugin's public dir — gitignored, rebuilt on every boot — at a
+# gem-version-stamped path: /plugins/ assets are cached long-term as
+# immutable, so the versioned URL is what busts caches on a gem bump. The
+# client learns the current base path from the site serializer.
+voice_javascripts_dir = File.join(__dir__, "public", "javascripts")
+FileUtils.mkdir_p(voice_javascripts_dir)
+Dir
+ .children(voice_javascripts_dir)
+ .each do |entry|
+ if entry != DiscourseVoiceAssets::VERSION
+ FileUtils.rm_rf(File.join(voice_javascripts_dir, entry))
+ end
+ end
+Discourse::Utils.atomic_ln_s(
+ DiscourseVoiceAssets.vendor_path,
+ File.join(voice_javascripts_dir, DiscourseVoiceAssets::VERSION),
+)
+
+enabled_site_setting :voice_enabled
+
+register_svg_icon "microphone-lines"
+register_svg_icon "lock"
+register_svg_icon "phone"
+register_svg_icon "waveform"
+register_svg_icon "ear-listen"
+register_svg_icon "volume-high"
+register_svg_icon "microphone"
+register_svg_icon "microphone-slash"
+register_svg_icon "volume-xmark"
+register_svg_icon "walkie-talkie"
+register_svg_icon "discourse-sparkles"
+register_svg_icon "keyboard"
+register_svg_icon "phone-slash"
+register_svg_icon "phone-volume"
+register_svg_icon "podcast"
+register_svg_icon "handshake"
+register_svg_icon "users"
+register_svg_icon "user-group"
+register_svg_icon "compass"
+register_svg_icon "calendar"
+register_svg_icon "house"
+register_svg_icon "bullhorn"
+register_svg_icon "star"
+register_svg_icon "moon"
+register_svg_icon "sun"
+register_svg_icon "people-group"
+register_svg_icon "calendar-week"
+register_svg_icon "trophy"
+register_svg_icon "clock"
+register_svg_icon "video"
+register_svg_icon "video-slash"
+register_svg_icon "display"
+register_svg_icon "expand"
+register_svg_icon "compress"
+register_svg_icon "far-comment"
+register_svg_icon "comment-slash"
+register_svg_icon "paper-plane"
+register_svg_icon "xmark"
+register_svg_icon "up-right-from-square"
+register_svg_icon "person-chalkboard"
+register_svg_icon "table-cells"
+register_svg_icon "circle-check"
+register_svg_icon "circle-xmark"
+register_svg_icon "triangle-exclamation"
+register_svg_icon "hand"
+register_svg_icon "check"
+register_svg_icon "record-vinyl"
+register_svg_icon "flag"
+register_svg_icon "thumbs-up"
+register_svg_icon "thumbs-down"
+register_svg_icon "ban"
+register_svg_icon "user-plus"
+register_svg_icon "circle-nodes"
+register_svg_icon "magnet"
+register_svg_icon "copy"
+register_svg_icon "closed-captioning"
+register_svg_icon "stop"
+register_svg_icon "far-file-lines"
+register_asset "stylesheets/common/voice.scss"
+register_asset "stylesheets/common/voice-room-page.scss"
+register_asset "stylesheets/common/voice-chat.scss"
+register_asset "stylesheets/common/voice-admin.scss", :admin
+
+add_admin_route "voice.admin.title", "voice", use_new_show_route: true
+
+require_relative "lib/voice"
+
+after_initialize do
+ SeedFu.fixture_paths << Rails.root.join("plugins/voice/db/fixtures").to_s
+
+ require_relative "lib/voice/user_extension"
+
+ Discourse::Application.routes.append { mount ::Voice::Engine, at: "/voice" }
+
+ Guardian.prepend Voice::GuardianExtension
+
+ register_reviewable_type ReviewableVoiceUser
+
+ # Chat snapshots the hashtag orderings into Site.markdown_additional_options
+ # at its own after_initialize, which runs before this one (plugins load
+ # alphabetically) — refresh it so chat transcripts quoted inside posts can
+ # cook room hashtags too. The snapshot also bakes in each source's enabled?
+ # state, so it must be refreshed again when voice_enabled toggles.
+ def self.refresh_chat_hashtag_configurations
+ return unless defined?(::Chat) && Site.markdown_additional_options["chat"]
+
+ Site.markdown_additional_options["chat"][
+ :hashtag_configurations
+ ] = HashtagAutocompleteService.contexts_with_ordered_types
+ end
+
+ # Rooms rank below chat channels (200) but above categories (100) in the
+ # chat composer, and below everything (category 100, tag 50, channel 10) in
+ # the topic composer, so a bare #slug in a post still means the category.
+ register_hashtag_data_source(Voice::RoomHashtagDataSource)
+ register_hashtag_type_priority_for_context("room", "chat-composer", 150)
+ register_hashtag_type_priority_for_context("room", "topic-composer", 5)
+ refresh_chat_hashtag_configurations
+
+ # Gates the user-card call button: the viewer needs the direct-call
+ # permission and the target must be callable by them — voice-room access,
+ # not the viewer themselves or a bot, and not screened out by the target's
+ # mute, ignore, or personal message preferences.
+ add_to_serializer(
+ :user_card,
+ :voice_can_call,
+ include_condition: -> { scope.can_start_voice_call? },
+ ) { scope.can_call_voice_user?(object) }
+
+ # Lets the client decide whether to render the rooms sidebar for anonymous
+ # visitors without exposing the configured group ids.
+ add_to_serializer(:site, :voice_public_access) { scope.voice_public_access? }
+
+ # Base URL for the gem-vendored media assets (see the symlink setup above).
+ # Version-stamped so a gem bump busts the immutable /plugins/ caches; the
+ # client builds every asset URL from this, so filenames can stay stable.
+ add_to_serializer(:site, :voice_assets_path) do
+ "/plugins/voice/javascripts/#{DiscourseVoiceAssets::VERSION}"
+ end
+
+ # Gates the room-form SFU checkbox only — the client never needs the policy
+ # enum itself, and a live room's transport is learned at join, not here.
+ add_to_serializer(:site, :voice_livekit_per_room_available) do
+ SiteSetting.voice_livekit_room_policy == "per_room" && Voice::Livekit.configured?
+ end
+
+ Voice::DefaultRoomSeeder.ensure! if SiteSetting.voice_enabled?
+
+ # This can't live in the on(:site_setting_changed) handler below: plugin
+ # event handlers are skipped while the plugin is disabled, which silently
+ # covers the disabling transition itself.
+ on_enabled_change do |_old_value, new_value|
+ Voice::DefaultRoomSeeder.ensure! if new_value
+ clear_all_voice_statuses unless new_value
+ refresh_chat_hashtag_configurations
+ end
+
+ on(:user_destroyed) do |user|
+ # Sessions are analytics history and survive user deletion (the stats
+ # endpoints tolerate the dangling user_id). Rooms must stay owned, so
+ # they move to the system user; the roster and per-pair contact rows are
+ # meaningless without the user.
+ Voice::Room.where(creator_id: user.id).update_all(creator_id: Discourse.system_user.id)
+ Voice::RoomMembership.where(user_id: user.id).delete_all
+ Voice::CoPresence.where("user_id_1 = :id OR user_id_2 = :id", id: user.id).delete_all
+ end
+
+ on(:site_setting_changed) do |name, _old_value, new_value|
+ if name.to_sym == :voice_badges_enabled
+ if new_value
+ Voice::BadgeGranterHooks.enable_all!
+ else
+ Voice::BadgeGranterHooks.disable_all!
+ end
+ end
+
+ clear_all_voice_statuses if name.to_sym == :voice_auto_status_enabled && !new_value
+
+ # Surface a bad URL or key pair on the admin status panel within seconds
+ # of saving, not at the first user's failed join.
+ livekit_settings = %i[
+ voice_livekit_url
+ voice_livekit_api_key
+ voice_livekit_api_secret
+ voice_livekit_room_policy
+ voice_livekit_mesh_fallback
+ ]
+ Jobs.enqueue(:voice_livekit_probe) if livekit_settings.include?(name.to_sym)
+ end
+
+ def self.clear_all_voice_statuses
+ UserStatus
+ .where(emoji: [Voice::UserStatusManager::EMOJI, Voice::UserStatusManager::AFK_EMOJI])
+ .find_each { |status| User.find_by(id: status.user_id)&.clear_status! }
+ end
+end
diff --git a/plugins/voice/scripts/voice-fake-participants.mjs b/plugins/voice/scripts/voice-fake-participants.mjs
new file mode 100644
index 00000000000..de59a4b9c89
--- /dev/null
+++ b/plugins/voice/scripts/voice-fake-participants.mjs
@@ -0,0 +1,429 @@
+#!/usr/bin/env node
+/* eslint-disable no-console */
+
+const DEFAULT_COLORS = [
+ ["#2563eb", "#f97316"],
+ ["#16a34a", "#7c3aed"],
+ ["#dc2626", "#0891b2"],
+ ["#9333ea", "#facc15"],
+ ["#0f766e", "#e11d48"],
+];
+
+function parseArgs(argv) {
+ const options = {
+ baseUrl: process.env.DISCOURSE_URL || "http://localhost:4200",
+ room: process.env.ROOM || "watercooler",
+ botCount: Number(process.env.BOT_COUNT || 2),
+ botsFile: process.env.VOICE_BOTS_FILE || ".local/voice-bots.json",
+ headed: false,
+ trace: false,
+ screenshots: false,
+ recordVideo: false,
+ camera: true,
+ screenShareBot: Number(process.env.SCREEN_SHARE_BOT || 0),
+ holdMs: Number(process.env.HOLD_MS || 0),
+ loginMode: process.env.LOGIN_MODE || "become",
+ };
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ const next = () => argv[++index];
+
+ switch (arg) {
+ case "--":
+ break;
+ case "--url":
+ options.baseUrl = next();
+ break;
+ case "--room":
+ options.room = next();
+ break;
+ case "--bot-count":
+ options.botCount = Number(next());
+ break;
+ case "--bots-file":
+ options.botsFile = next();
+ break;
+ case "--headed":
+ options.headed = true;
+ break;
+ case "--trace":
+ options.trace = true;
+ break;
+ case "--screenshots":
+ options.screenshots = true;
+ break;
+ case "--record-video":
+ options.recordVideo = true;
+ break;
+ case "--no-camera":
+ options.camera = false;
+ break;
+ case "--screen-share-bot":
+ options.screenShareBot = Number(next());
+ break;
+ case "--hold-ms":
+ options.holdMs = Number(next());
+ break;
+ case "--login-mode":
+ options.loginMode = next();
+ break;
+ case "--help":
+ case "-h":
+ printHelp();
+ process.exit(0);
+ // eslint-disable-next-line no-fallthrough -- process.exit never falls through
+ default:
+ throw new Error(`Unknown option: ${arg}`);
+ }
+ }
+
+ if (!options.baseUrl) {
+ throw new Error("DISCOURSE_URL or --url is required");
+ }
+
+ if (!options.room) {
+ throw new Error("ROOM or --room is required");
+ }
+
+ if (!Number.isInteger(options.botCount) || options.botCount < 1) {
+ throw new Error("BOT_COUNT / --bot-count must be a positive integer");
+ }
+
+ return options;
+}
+
+function printHelp() {
+ console.log(`Usage:
+ DISCOURSE_URL=http://localhost:4200 ROOM=watercooler pnpm voice:bots -- --headed --bot-count 3
+
+Options:
+ --url <url> Base Discourse URL. Env: DISCOURSE_URL
+ --room <slug> Voice room slug. Env: ROOM
+ --bot-count <n> Number of generated bots if no bots file exists. Env: BOT_COUNT
+ --bots-file <path> JSON bot config. Default: .local/voice-bots.json
+ --login-mode <mode> become or password. Default: become
+ --headed Show browser windows
+ --trace Capture Playwright traces under tmp/voice-bots
+ --screenshots Capture screenshots under tmp/voice-bots
+ --record-video Record Playwright videos under tmp/voice-bots
+ --no-camera Join without auto-enabling camera
+ --screen-share-bot <n> 1-based bot index that should start screen share
+ --hold-ms <ms> Auto-close after this many ms; default holds until Ctrl-C
+`);
+}
+
+async function fileExists(path) {
+ const { access } = await import("node:fs/promises");
+ try {
+ await access(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function loadBots(options) {
+ const { readFile } = await import("node:fs/promises");
+
+ if (process.env.VOICE_BOTS_JSON) {
+ return JSON.parse(process.env.VOICE_BOTS_JSON).slice(0, options.botCount);
+ }
+
+ if (options.botsFile && (await fileExists(options.botsFile))) {
+ return JSON.parse(await readFile(options.botsFile, "utf8")).slice(
+ 0,
+ options.botCount
+ );
+ }
+
+ return Array.from({ length: options.botCount }, (_, index) => ({
+ username: `voice_bot_${index + 1}`,
+ name: `Voice Bot ${index + 1}`,
+ }));
+}
+
+function feedFor(bot, index) {
+ const [color, accent] = DEFAULT_COLORS[index % DEFAULT_COLORS.length];
+ return {
+ label: bot.label || bot.name || bot.username || `Voice Bot ${index + 1}`,
+ width: bot.width || 640,
+ height: bot.height || 360,
+ color: bot.color || color,
+ accent: bot.accent || accent,
+ };
+}
+
+function fakeMediaInitScript({ feed }) {
+ const mediaDevices = navigator.mediaDevices || {};
+ Object.defineProperty(navigator, "mediaDevices", {
+ configurable: true,
+ value: mediaDevices,
+ });
+
+ const streams = [];
+
+ function cleanupWhenTrackStops(track, cleanup) {
+ let cleaned = false;
+ const runCleanup = () => {
+ if (cleaned) {
+ return;
+ }
+ cleaned = true;
+ cleanup();
+ };
+ const originalStop = track.stop.bind(track);
+ track.stop = () => {
+ runCleanup();
+ originalStop();
+ };
+ track.addEventListener("ended", runCleanup, { once: true });
+ }
+
+ function createVideoStream(videoFeed) {
+ const canvas = document.createElement("canvas");
+ canvas.width = videoFeed.width;
+ canvas.height = videoFeed.height;
+ const context = canvas.getContext("2d");
+ let frame = 0;
+
+ const drawFrame = () => {
+ frame += 1;
+ const x = (frame * 17) % videoFeed.width;
+ const y = videoFeed.height / 2 - 40;
+
+ context.fillStyle = videoFeed.color;
+ context.fillRect(0, 0, videoFeed.width, videoFeed.height);
+ context.fillStyle = "rgba(255, 255, 255, 0.18)";
+ context.fillRect(0, videoFeed.height - 96, videoFeed.width, 96);
+ context.fillStyle = videoFeed.accent || "rgba(0, 0, 0, 0.35)";
+ context.fillRect(x, y, 120, 80);
+ context.fillStyle = "#fff";
+ context.font = "32px sans-serif";
+ context.fillText(videoFeed.label, 24, 48);
+ context.font = "20px sans-serif";
+ context.fillText(`frame ${frame}`, 24, videoFeed.height - 38);
+ };
+
+ drawFrame();
+ const timer = window.setInterval(drawFrame, 100);
+ const stream = canvas.captureStream(10);
+ stream.getTracks().forEach((track) => {
+ track.__voiceFakeMediaLabel = videoFeed.label;
+ cleanupWhenTrackStops(track, () => window.clearInterval(timer));
+ });
+ streams.push(stream);
+ return stream;
+ }
+
+ function createAudioStream() {
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
+ const audioContext = new AudioContext();
+ const oscillator = audioContext.createOscillator();
+ const gain = audioContext.createGain();
+ const destination = audioContext.createMediaStreamDestination();
+
+ oscillator.frequency.value = 220;
+ gain.gain.value = 0.0001;
+ oscillator.connect(gain);
+ gain.connect(destination);
+ oscillator.start();
+
+ destination.stream.getTracks().forEach((track) => {
+ cleanupWhenTrackStops(track, () => {
+ oscillator.stop();
+ audioContext.close();
+ });
+ });
+
+ streams.push(destination.stream);
+ return destination.stream;
+ }
+
+ function addTracks(target, source) {
+ source.getTracks().forEach((track) => target.addTrack(track));
+ }
+
+ mediaDevices.getUserMedia = async (constraints = {}) => {
+ const stream = new MediaStream();
+
+ if (constraints.audio) {
+ addTracks(stream, createAudioStream());
+ }
+
+ if (constraints.video) {
+ addTracks(stream, createVideoStream(feed));
+ }
+
+ return stream;
+ };
+
+ mediaDevices.getDisplayMedia = async () => {
+ return createVideoStream({
+ ...feed,
+ label: `${feed.label} screen`,
+ width: 1024,
+ height: 576,
+ color: feed.accent || feed.color,
+ accent: "#111827",
+ });
+ };
+
+ window.__voiceFakeBotMedia = { feed, streams };
+}
+
+async function login(page, bot, options) {
+ if (options.loginMode === "become") {
+ const becomeUrl = new URL(
+ `/session/${encodeURIComponent(bot.username)}/become.json`,
+ options.baseUrl
+ );
+ becomeUrl.searchParams.set("redirect", "false");
+ await page.goto(becomeUrl.toString(), { waitUntil: "domcontentloaded" });
+ return;
+ }
+
+ if (options.loginMode !== "password") {
+ throw new Error(`Unsupported login mode: ${options.loginMode}`);
+ }
+
+ if (!bot.password) {
+ throw new Error(
+ `Bot ${bot.username} is missing a password for password login mode`
+ );
+ }
+
+ await page.goto(new URL("/login", options.baseUrl).toString());
+ await page.getByLabel(/email|username/i).fill(bot.username);
+ await page.getByLabel(/password/i).fill(bot.password);
+ await page.getByRole("button", { name: /log in|login/i }).click();
+ await page.waitForLoadState("networkidle");
+}
+
+async function clickIfVisible(page, locator, label) {
+ try {
+ await locator.click({ timeout: 5000 });
+ console.log(` clicked ${label}`);
+ return true;
+ } catch (error) {
+ console.warn(` could not click ${label}: ${error.message}`);
+ return false;
+ }
+}
+
+async function runBot({ browser, bot, index, options, outputDir }) {
+ const feed = feedFor(bot, index);
+ const context = await browser.newContext({
+ recordVideo: options.recordVideo ? { dir: outputDir } : undefined,
+ });
+
+ if (options.trace) {
+ await context.tracing.start({ screenshots: true, snapshots: true });
+ }
+
+ await context.addInitScript(fakeMediaInitScript, { feed });
+
+ const page = await context.newPage();
+ page.on("console", (message) => {
+ console.log(`[${bot.username}] ${message.type()}: ${message.text()}`);
+ });
+ page.on("pageerror", (error) => {
+ console.error(`[${bot.username}] pageerror: ${error.message}`);
+ });
+
+ console.log(`[${bot.username}] logging in (${options.loginMode})`);
+ await login(page, bot, options);
+
+ const roomUrl = new URL(
+ `/voice/r/${encodeURIComponent(options.room)}`,
+ options.baseUrl
+ ).toString();
+ console.log(`[${bot.username}] opening ${roomUrl}`);
+ await page.goto(roomUrl, { waitUntil: "domcontentloaded" });
+
+ await clickIfVisible(
+ page,
+ page.getByRole("button", { name: /join/i }),
+ "join"
+ );
+
+ if (options.camera) {
+ await clickIfVisible(
+ page,
+ page.getByRole("button", { name: /camera/i }),
+ "camera"
+ );
+ }
+
+ if (options.screenShareBot === index + 1) {
+ await clickIfVisible(
+ page,
+ page.getByRole("button", { name: /screen|share/i }),
+ "screen share"
+ );
+ }
+
+ if (options.screenshots) {
+ await page.screenshot({
+ path: `${outputDir}/${String(index + 1).padStart(2, "0")}-${bot.username}.png`,
+ fullPage: true,
+ });
+ }
+
+ return { context, page, bot, feed };
+}
+
+async function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const { chromium } = await import("playwright").catch((error) => {
+ throw new Error(
+ `Could not load Playwright. Run pnpm install first, or execute from a checkout that has Playwright installed. Original error: ${error.message}`
+ );
+ });
+ const { mkdir } = await import("node:fs/promises");
+
+ const outputDir = "tmp/voice-bots";
+ await mkdir(outputDir, { recursive: true });
+
+ const bots = await loadBots(options);
+ if (bots.length === 0) {
+ throw new Error("No bots configured");
+ }
+
+ console.log(
+ `Starting ${bots.length} Voice fake participant(s) against ${options.baseUrl}`
+ );
+ const browser = await chromium.launch({ headless: !options.headed });
+ const sessions = [];
+
+ try {
+ for (let index = 0; index < bots.length; index += 1) {
+ sessions.push(
+ await runBot({ browser, bot: bots[index], index, options, outputDir })
+ );
+ }
+
+ console.log("All bots joined. Press Ctrl-C to close.");
+ if (options.holdMs > 0) {
+ await new Promise((resolve) => setTimeout(resolve, options.holdMs));
+ } else {
+ await new Promise(() => {});
+ }
+ } finally {
+ for (let index = 0; index < sessions.length; index += 1) {
+ const session = sessions[index];
+ if (options.trace) {
+ await session.context.tracing.stop({
+ path: `${outputDir}/${String(index + 1).padStart(2, "0")}-${session.bot.username}.zip`,
+ });
+ }
+ await session.context.close();
+ }
+ await browser.close();
+ }
+}
+
+main().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+});
diff --git a/plugins/voice/spec/fabricators/voice_room_fabricator.rb b/plugins/voice/spec/fabricators/voice_room_fabricator.rb
new file mode 100644
index 00000000000..8c807035601
--- /dev/null
+++ b/plugins/voice/spec/fabricators/voice_room_fabricator.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+Fabricator(:voice_room, class_name: "Voice::Room") do
+ name { sequence(:voice_room_name) { |i| "Voice #{i}" } }
+ public { false }
+ creator { Fabricate(:user) }
+end
+
+Fabricator(:voice_ephemeral_room, from: :voice_room) do
+ ephemeral true
+ last_occupied_at { Time.current }
+end
diff --git a/plugins/voice/spec/fabricators/voice_session_fabricator.rb b/plugins/voice/spec/fabricators/voice_session_fabricator.rb
new file mode 100644
index 00000000000..0fee17d689e
--- /dev/null
+++ b/plugins/voice/spec/fabricators/voice_session_fabricator.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+Fabricator(:voice_session, class_name: "Voice::Session") do
+ user
+ room { Fabricate(:voice_room) }
+ joined_at { 1.hour.ago }
+ left_at { Time.current }
+end
diff --git a/plugins/voice/spec/integrity/livekit_static_import_spec.rb b/plugins/voice/spec/integrity/livekit_static_import_spec.rb
new file mode 100644
index 00000000000..cd78e46e938
--- /dev/null
+++ b/plugins/voice/spec/integrity/livekit_static_import_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+# "Zero LiveKit bytes on the P2P path" as a regression test: the vendored
+# SDK bundle must stay out of the app graph, reachable only through the
+# dynamic `import()` in `livekit-session.js` that runs when a room actually
+# resolves to the livekit transport. A static import — of the vendored
+# bundle path or of the `livekit-client` npm package (a build-time
+# devDependency only) — would ship and parse the SDK for every visitor of
+# every mesh-only install.
+RSpec.describe "LiveKit SDK static import guard" do
+ # `from "<specifier>"` only occurs in static import/export statements —
+ # dynamic `import()` never uses `from` — and `import "<specifier>"` is a
+ # static side-effect import.
+ FORBIDDEN_SPECIFIER = %r{livekit-client|[^"']*javascripts/livekit/[^"']*}
+ STATIC_IMPORT =
+ Regexp.union(
+ /\bfrom\s+["'](?:#{FORBIDDEN_SPECIFIER})["']/,
+ /\bimport\s+["'](?:#{FORBIDDEN_SPECIFIER})["']/,
+ )
+
+ def offenders_in(content)
+ content.match?(STATIC_IMPORT)
+ end
+
+ it "finds no static import of the SDK anywhere under the asset directories" do
+ plugin_root = File.expand_path("../..", __dir__)
+ files = Dir.glob("#{plugin_root}/{assets,admin/assets}/**/*.{js,gjs}")
+ expect(files).not_to be_empty
+
+ offenders = files.select { |path| offenders_in(File.read(path)) }
+ expect(offenders.map { |path| path.delete_prefix("#{plugin_root}/") }).to eq([])
+ end
+
+ # Pin the pattern itself, so the guard cannot rot into matching nothing.
+ it "catches every static import form" do
+ [
+ 'import { Room } from "livekit-client";',
+ "import * as livekit from 'livekit-client';",
+ 'import "livekit-client";',
+ 'export { Room } from "livekit-client";',
+ 'import lk from "../../../public/javascripts/livekit/livekit-client";',
+ "import {\n Room,\n RoomEvent,\n} from \"livekit-client\";",
+ ].each { |snippet| expect(offenders_in(snippet)).to eq(true), "expected match: #{snippet}" }
+ end
+
+ it "allows the dynamic import the session uses" do
+ [
+ 'import(getURL("/plugins/voice/javascripts/livekit/livekit-client.js"))',
+ 'import LivekitRoomSession from "../../lib/voice/livekit-session";',
+ ].each { |snippet| expect(offenders_in(snippet)).to eq(false), "expected no match: #{snippet}" }
+ end
+end
diff --git a/plugins/voice/spec/integrity/voice_assets_spec.rb b/plugins/voice/spec/integrity/voice_assets_spec.rb
new file mode 100644
index 00000000000..6f91d897851
--- /dev/null
+++ b/plugins/voice/spec/integrity/voice_assets_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+# The heavyweight browser assets (wasm engines, ML models, SDK bundles) live
+# in the discourse_voice_assets gem under stable filenames; the plugin mounts
+# the gem's vendor tree at a gem-version-stamped public path and hardcodes
+# those filenames in its loaders. These specs pin that contract: every file
+# the client references must exist in the gem, and the versioned mount must
+# be in place.
+RSpec.describe "discourse_voice_assets integrity" do
+ # Keep in sync with the loaders: subtitles.js, ns-engines.js,
+ # background-blur.js, livekit-session.js.
+ CLIENT_REFERENCED_ASSETS = %w[
+ dfn3/dfn3-worklet.js
+ dfn3/dfn3.wasm
+ dfn3/dfn3-model.bin
+ dtln/dtln-worklet.js
+ dtln/dtln.wasm
+ rnnoise/rnnoise-worklet.js
+ rnnoise/rnnoise.wasm
+ stt/subtitles-worker.js
+ stt/vad.js
+ stt/ort/ort-wasm-simd-threaded.jsep.js
+ stt/ort/ort-wasm-simd-threaded.jsep.wasm
+ stt/vad/
+ livekit/livekit-client.js
+ mediapipe/vision_bundle.js
+ mediapipe/selfie_segmenter.tflite
+ mediapipe/wasm/
+ ]
+
+ CLIENT_REFERENCED_ASSETS.each do |file|
+ it "finds #{file} in the gem's vendor tree" do
+ path = DiscourseVoiceAssets.vendor_path(file)
+ exists = file.end_with?("/") ? File.directory?(path) : File.exist?(path)
+ expect(exists).to be(true), "gem asset missing: #{file}"
+ end
+ end
+
+ it "mounts the gem's vendor tree at the version-stamped public path" do
+ link = File.expand_path("../../public/javascripts/#{DiscourseVoiceAssets::VERSION}", __dir__)
+ expect(File.symlink?(link)).to be(true), "missing symlink: #{link}"
+ expect(File.readlink(link)).to eq(DiscourseVoiceAssets.vendor_path)
+ end
+
+ it "serializes the versioned base path the client builds URLs from" do
+ SiteSetting.voice_enabled = true
+ guardian = Guardian.new
+ serialized = SiteSerializer.new(Site.new(guardian), scope: guardian, root: false).as_json
+ expect(serialized[:voice_assets_path]).to eq(
+ "/plugins/voice/javascripts/#{DiscourseVoiceAssets::VERSION}",
+ )
+ end
+end
diff --git a/plugins/voice/spec/jobs/regular/voice_livekit_probe_spec.rb b/plugins/voice/spec/jobs/regular/voice_livekit_probe_spec.rb
new file mode 100644
index 00000000000..bd780b20e85
--- /dev/null
+++ b/plugins/voice/spec/jobs/regular/voice_livekit_probe_spec.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Jobs::VoiceLivekitProbe do
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ end
+
+ after { Voice::Livekit::HealthCheck.clear_probe! }
+
+ def list_rooms_stub
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/ListRooms")
+ end
+
+ it "stores a passing result when the server is reachable" do
+ list_rooms_stub.to_return(status: 200, body: { rooms: [{ name: "default-r1" }] }.to_json)
+
+ described_class.new.execute({})
+
+ probe = Voice::Livekit::HealthCheck.last_probe
+ expect(probe[:ok]).to eq(true)
+ expect(probe[:token][:ok]).to eq(true)
+ expect(probe[:server][:ok]).to eq(true)
+ expect(probe[:server][:room_count]).to eq(1)
+ expect(probe[:checked_at]).to be_present
+ end
+
+ it "stores the failure and logs it with the [voice-livekit] prefix" do
+ list_rooms_stub.to_timeout
+ Rails.logger.expects(:warn).with(regexp_matches(/\[voice-livekit\] connectivity probe failed/))
+
+ described_class.new.execute({})
+
+ probe = Voice::Livekit::HealthCheck.last_probe
+ expect(probe[:ok]).to eq(false)
+ expect(probe[:server][:ok]).to eq(false)
+ expect(probe[:server][:error]).to be_present
+ end
+
+ it "drops the stored result instead of probing when LiveKit was deconfigured" do
+ Voice::Livekit::HealthCheck.store_probe!(ok: true)
+ SiteSetting.voice_livekit_api_secret = ""
+ probe_stub = stub_request(:post, %r{\Ahttps://})
+
+ described_class.new.execute({})
+
+ expect(Voice::Livekit::HealthCheck.last_probe).to be_nil
+ expect(probe_stub).not_to have_been_requested
+ end
+
+ describe "enqueueing" do
+ it "is enqueued when a LiveKit setting changes" do
+ expect_enqueued_with(job: :voice_livekit_probe) do
+ SiteSetting.voice_livekit_url = "wss://other.example.com"
+ end
+ end
+
+ it "is enqueued when the room policy changes" do
+ expect_enqueued_with(job: :voice_livekit_probe) do
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ end
+ end
+
+ it "is enqueued when the mesh fallback changes" do
+ expect_enqueued_with(job: :voice_livekit_probe) do
+ SiteSetting.voice_livekit_mesh_fallback = true
+ end
+ end
+
+ it "is not enqueued for unrelated settings" do
+ expect_not_enqueued_with(job: :voice_livekit_probe) do
+ SiteSetting.voice_max_rooms_per_user = 6
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/jobs/scheduled/publish_room_participants_spec.rb b/plugins/voice/spec/jobs/scheduled/publish_room_participants_spec.rb
new file mode 100644
index 00000000000..a5d9db7a03f
--- /dev/null
+++ b/plugins/voice/spec/jobs/scheduled/publish_room_participants_spec.rb
@@ -0,0 +1,200 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::PublishRoomParticipants do
+ subject(:job) { described_class.new }
+
+ fab!(:room, :voice_room)
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+
+ before { SiteSetting.voice_enabled = true }
+
+ it "publishes participants for rooms with active participants" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.add(room.id, user2.id)
+
+ # Verify participants were added
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to contain_exactly(user1.id, user2.id)
+
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ room_messages = messages.select { |m| m.channel == Voice.room_channel(room.id) }
+ expect(room_messages.size).to eq(1)
+ expect(room_messages.first.data[:type]).to eq("participants")
+ expect(room_messages.first.data[:participants].map { |p| p[:id] }).to contain_exactly(
+ user1.id,
+ user2.id,
+ )
+ end
+
+ it "reflects TTL-expired participants in broadcast" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.add(room.id, user2.id)
+
+ # Set user2's heartbeat to a stale timestamp to simulate TTL expiration
+ Discourse.redis.zadd(
+ "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants",
+ 1.hour.ago.to_f,
+ user2.id,
+ )
+
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ room_messages = messages.select { |m| m.channel == Voice.room_channel(room.id) }
+ expect(room_messages.size).to eq(1)
+ expect(room_messages.first.data[:participants].map { |p| p[:id] }).to contain_exactly(user1.id)
+ end
+
+ it "does not publish for rooms without recent membership activity" do
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ expect(messages).to be_empty
+ end
+
+ it "publishes an empty list for rooms that recently emptied" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.remove(room.id, user1.id)
+
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ room_messages = messages.select { |m| m.channel == Voice.room_channel(room.id) }
+ expect(room_messages.size).to eq(1)
+ expect(room_messages.first.data[:participants]).to be_empty
+ end
+
+ it "stops publishing once a room's last activity leaves the safety window" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.remove(room.id, user1.id)
+ Discourse.redis.zadd(
+ Voice::ParticipantTracker::RECENTLY_ACTIVE_ROOMS_KEY,
+ 1.hour.ago.to_f,
+ room.id,
+ )
+
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ expect(messages).to be_empty
+ end
+
+ it "handles rooms that no longer exist" do
+ Voice::ParticipantTracker.add(99_999, user1.id)
+
+ expect { job.execute({}) }.not_to raise_error
+ end
+
+ it "deletes an emptied livekit-pinned room from the SFU exactly once" do
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.remove(room.id, user1.id)
+ stub = stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom")
+
+ job.execute({})
+
+ expect(stub).to have_been_requested.once
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+
+ # The room stays in the recently-active sweep for a while; with the pin
+ # gone, later sweeps must not keep re-deleting it.
+ job.execute({})
+
+ expect(stub).to have_been_requested.once
+ end
+
+ describe "stale status sweep" do
+ before do
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ end
+
+ # Statuses set within the sweep's grace window are skipped, so specs set
+ # them in the past and re-add the live user's heartbeat after traveling.
+ it "clears the status of a participant whose heartbeat lapsed" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::ParticipantTracker.add(room.id, user2.id)
+ Voice::UserStatusManager.set_voice_status(user1, room)
+ Voice::UserStatusManager.set_voice_status(user2, room)
+
+ freeze_time(1.minute.from_now)
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Discourse.redis.zadd(
+ "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants",
+ 1.hour.ago.to_f,
+ user2.id,
+ )
+
+ job.execute({})
+
+ expect(user1.reload.user_status).to be_present
+ expect(user2.reload.user_status).to be_nil
+ end
+
+ it "clears lingering statuses of a room that fully emptied" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::UserStatusManager.set_voice_status(user1, room)
+
+ freeze_time(1.minute.from_now)
+ Discourse.redis.zadd(
+ "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants",
+ 1.hour.ago.to_f,
+ user1.id,
+ )
+
+ job.execute({})
+
+ expect(user1.reload.user_status).to be_nil
+ end
+
+ it "keeps a user's status while they are live in another active room" do
+ other_room = Fabricate(:voice_room)
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::UserStatusManager.set_voice_status(user1, other_room)
+
+ freeze_time(1.minute.from_now)
+ Voice::ParticipantTracker.add(other_room.id, user1.id)
+ Discourse.redis.zadd(
+ "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants",
+ 1.hour.ago.to_f,
+ user1.id,
+ )
+
+ job.execute({})
+
+ expect(user1.reload.user_status).to be_present
+ end
+
+ it "keeps a freshly set status even when the user is not yet live" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ Voice::UserStatusManager.set_voice_status(user2, room)
+
+ job.execute({})
+
+ expect(user2.reload.user_status).to be_present
+ end
+
+ it "does not touch manually set statuses, even ones using Voice emojis" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+ user1.set_status!("Sleeping", "zzz")
+ user2.set_status!("On vacation", "palm_tree")
+
+ freeze_time(1.minute.from_now)
+
+ job.execute({})
+
+ expect(user1.reload.user_status.emoji).to eq("zzz")
+ expect(user2.reload.user_status.emoji).to eq("palm_tree")
+ end
+ end
+
+ it "does not publish when plugin is disabled" do
+ Voice::ParticipantTracker.add(room.id, user1.id)
+
+ SiteSetting.voice_enabled = false
+
+ messages = MessageBus.track_publish { job.execute({}) }
+
+ expect(messages).to be_empty
+ end
+end
diff --git a/plugins/voice/spec/jobs/scheduled/voice/cleanup_ephemeral_rooms_spec.rb b/plugins/voice/spec/jobs/scheduled/voice/cleanup_ephemeral_rooms_spec.rb
new file mode 100644
index 00000000000..f6af752a51e
--- /dev/null
+++ b/plugins/voice/spec/jobs/scheduled/voice/cleanup_ephemeral_rooms_spec.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Voice::CleanupEphemeralRooms do
+ fab!(:stale_room) { Fabricate(:voice_ephemeral_room, last_occupied_at: 2.hours.ago) }
+
+ it "reaps stale ephemeral rooms" do
+ SiteSetting.voice_enabled = true
+ room_id = stale_room.id
+
+ described_class.new.execute({})
+
+ expect(Voice::Room.exists?(room_id)).to eq(false)
+ end
+
+ it "does nothing while the plugin is disabled" do
+ SiteSetting.voice_enabled = false
+
+ described_class.new.execute({})
+
+ expect(Voice::Room.exists?(stale_room.id)).to eq(true)
+ end
+end
diff --git a/plugins/voice/spec/jobs/scheduled/voice/close_orphaned_sessions_spec.rb b/plugins/voice/spec/jobs/scheduled/voice/close_orphaned_sessions_spec.rb
new file mode 100644
index 00000000000..ecaa670be0a
--- /dev/null
+++ b/plugins/voice/spec/jobs/scheduled/voice/close_orphaned_sessions_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Voice::CloseOrphanedSessions do
+ subject(:job) { described_class.new }
+
+ fab!(:room, :voice_room)
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_analytics_enabled = true
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def set_stale_participant(room, user, last_heartbeat:)
+ key = "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, last_heartbeat.to_f, user.id)
+ Voice::ParticipantTracker.update_metadata(
+ room.id,
+ user.id,
+ { last_heartbeat_at: last_heartbeat.to_f },
+ )
+ end
+
+ it "closes orphaned sessions using the last heartbeat timestamp" do
+ session =
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 50.minutes.ago, left_at: nil)
+
+ last_heartbeat = 2.minutes.ago
+ set_stale_participant(room, user1, last_heartbeat:)
+
+ job.execute({})
+
+ session.reload
+ expect(session.left_at).to be_within(1.second).of(last_heartbeat)
+ end
+
+ it "falls back to Time.current when Redis data has expired" do
+ session =
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 50.minutes.ago, left_at: nil)
+
+ freeze_time do
+ job.execute({})
+
+ session.reload
+ expect(session.left_at).to be_within(1.second).of(Time.current)
+ end
+ end
+
+ it "does not close sessions for users with fresh heartbeats" do
+ session =
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 10.minutes.ago, left_at: nil)
+
+ Voice::ParticipantTracker.add(room.id, user1.id)
+
+ job.execute({})
+
+ session.reload
+ expect(session.left_at).to be_nil
+ end
+
+ it "cleans up stale Redis entries after closing" do
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 50.minutes.ago, left_at: nil)
+
+ set_stale_participant(room, user1, last_heartbeat: 2.minutes.ago)
+
+ job.execute({})
+
+ expect(Voice::ParticipantTracker.get_metadata(room.id, user1.id)).to eq({})
+ end
+
+ it "closes stale user sessions while keeping active users untouched" do
+ stale_session =
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 50.minutes.ago, left_at: nil)
+ active_session =
+ Fabricate(:voice_session, user: user2, room: room, joined_at: 50.minutes.ago, left_at: nil)
+
+ set_stale_participant(room, user1, last_heartbeat: 2.minutes.ago)
+ Voice::ParticipantTracker.add(room.id, user2.id)
+
+ job.execute({})
+
+ expect(stale_session.reload.left_at).to be_present
+ expect(active_session.reload.left_at).to be_nil
+ end
+
+ it "closes sessions whose room has been deleted" do
+ deleted_room = Fabricate(:voice_room)
+ session =
+ Fabricate(
+ :voice_session,
+ user: user1,
+ room: deleted_room,
+ joined_at: 50.minutes.ago,
+ left_at: nil,
+ )
+ deleted_room.destroy!
+
+ freeze_time do
+ job.execute({})
+
+ expect(session.reload.left_at).to be_within(1.second).of(Time.current)
+ end
+ end
+
+ it "does nothing when plugin is disabled" do
+ SiteSetting.voice_enabled = false
+ session =
+ Fabricate(:voice_session, user: user1, room: room, joined_at: 50.minutes.ago, left_at: nil)
+
+ job.execute({})
+
+ expect(session.reload.left_at).to be_nil
+ end
+end
diff --git a/plugins/voice/spec/jobs/scheduled/voice/reconcile_recordings_spec.rb b/plugins/voice/spec/jobs/scheduled/voice/reconcile_recordings_spec.rb
new file mode 100644
index 00000000000..a3b867707c3
--- /dev/null
+++ b/plugins/voice/spec/jobs/scheduled/voice/reconcile_recordings_spec.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../../db/migrate/20260717172530_create_voice_recordings"
+
+RSpec.describe Jobs::Voice::ReconcileRecordings do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_recordings)
+ CreateVoiceRecordings.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ Voice::Recording.reset_column_information
+ end
+
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_recording_enabled = true
+ end
+
+ def create_stuck_recording
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: "EG_1",
+ filepath: "voice/test-abc123",
+ started_at: 10.minutes.ago,
+ )
+ end
+
+ let!(:list_stub) do
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/ListEgress").to_return(
+ body: {
+ items: [
+ {
+ "egressId" => "EG_1",
+ "status" => "EGRESS_COMPLETE",
+ "fileResults" => [{ "filename" => "test.mp4" }],
+ },
+ ],
+ }.to_json,
+ )
+ end
+
+ it "resolves stuck recordings without webhooks" do
+ recording = create_stuck_recording
+
+ described_class.new.execute({})
+
+ expect(recording.reload.status).to eq("completed")
+ expect(list_stub).to have_been_requested
+ end
+
+ it "makes zero HTTP calls when there is nothing to resolve" do
+ described_class.new.execute({})
+
+ expect(list_stub).not_to have_been_requested
+ end
+
+ it "makes zero HTTP calls when recordings are disabled" do
+ create_stuck_recording
+ SiteSetting.voice_livekit_recording_enabled = false
+
+ described_class.new.execute({})
+
+ expect(list_stub).not_to have_been_requested
+ end
+
+ it "makes zero HTTP calls when LiveKit is not configured" do
+ create_stuck_recording
+ SiteSetting.voice_livekit_api_secret = ""
+
+ described_class.new.execute({})
+
+ expect(list_stub).not_to have_been_requested
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/guardian_extension_spec.rb b/plugins/voice/spec/lib/voice/guardian_extension_spec.rb
new file mode 100644
index 00000000000..d54d018b9a4
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/guardian_extension_spec.rb
@@ -0,0 +1,251 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::GuardianExtension do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ Voice::Room.reset_column_information
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ Voice::Room.reset_column_information
+ end
+ end
+ end
+
+ fab!(:staff, :admin)
+ fab!(:creator) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_moderator) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_speaker) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:member) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ # In voice_create_room_allowed_groups but with no tie to the private room:
+ # the room-creation permission must not leak into other people's rooms.
+ fab!(:outsider) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ fab!(:low_trust_user) { Fabricate(:user, trust_level: TrustLevel[0]) }
+ fab!(:public_room) { Fabricate(:voice_room, creator: staff, public: true) }
+ fab!(:private_room) { Fabricate(:voice_room, creator: creator, public: false) }
+
+ fab!(:moderator_membership) do
+ private_room.room_memberships.create!(
+ user: room_moderator,
+ role: Voice::RoomMembership::ROLE_MODERATOR,
+ )
+ end
+
+ fab!(:speaker_membership) do
+ private_room.room_memberships.create!(
+ user: room_speaker,
+ role: Voice::RoomMembership::ROLE_SPEAKER,
+ )
+ end
+
+ fab!(:participant_membership) do
+ private_room.room_memberships.create!(
+ user: member,
+ role: Voice::RoomMembership::ROLE_PARTICIPANT,
+ )
+ end
+
+ let(:anonymous_guardian) { Guardian.new(nil) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ end
+
+ describe "#voice_public_access?" do
+ it "is true when anonymous visitors are admitted on a public site" do
+ expect(anonymous_guardian.voice_public_access?).to eq(true)
+ end
+
+ it "is false on login-required sites even when anonymous visitors are admitted" do
+ SiteSetting.login_required = true
+
+ expect(anonymous_guardian.voice_public_access?).to eq(false)
+ end
+
+ it "is true when access is open to the anonymous_users pseudogroup" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:anonymous_users]}"
+
+ expect(anonymous_guardian.voice_public_access?).to eq(true)
+ end
+
+ it "is false when access is limited to logged-in users" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:logged_in_users]}"
+
+ expect(anonymous_guardian.voice_public_access?).to eq(false)
+ end
+ end
+
+ describe "#can_create_voice_room?" do
+ it "is true for users in the create-room groups" do
+ expect(outsider.guardian.can_create_voice_room?).to eq(true)
+ end
+
+ it "is false for users outside the create-room groups" do
+ expect(low_trust_user.guardian.can_create_voice_room?).to eq(false)
+ end
+
+ it "is false for anonymous visitors" do
+ expect(anonymous_guardian.can_create_voice_room?).to eq(false)
+ end
+
+ it "is false for users outside the voice allowed groups" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}"
+
+ expect(outsider.guardian.can_create_voice_room?).to eq(false)
+ end
+ end
+
+ describe "#can_manage_voice_room?" do
+ it "is false for a create-room-group user with no tie to the room" do
+ expect(outsider.guardian.can_manage_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for a plain participant member" do
+ expect(member.guardian.can_manage_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for a speaker member" do
+ expect(room_speaker.guardian.can_manage_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is true for the room creator" do
+ expect(creator.guardian.can_manage_voice_room?(private_room)).to eq(true)
+ end
+
+ it "is true for a room moderator" do
+ expect(room_moderator.guardian.can_manage_voice_room?(private_room)).to eq(true)
+ end
+
+ it "is true for site staff" do
+ expect(staff.guardian.can_manage_voice_room?(private_room)).to eq(true)
+ end
+
+ it "is false for everyone when the plugin is disabled" do
+ SiteSetting.voice_enabled = false
+
+ expect(creator.guardian.can_manage_voice_room?(private_room)).to eq(false)
+ expect(staff.guardian.can_manage_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for a create-room-group user on public rooms they don't own" do
+ expect(outsider.guardian.can_manage_voice_room?(public_room)).to eq(false)
+ end
+
+ it "is false for anonymous visitors" do
+ expect(anonymous_guardian.can_manage_voice_room?(public_room)).to eq(false)
+ end
+
+ it "is false for a nil room" do
+ expect(creator.guardian.can_manage_voice_room?(nil)).to eq(false)
+ end
+ end
+
+ describe "#can_join_voice_room?" do
+ it "lets any allowed user join public rooms" do
+ expect(low_trust_user.guardian.can_join_voice_room?(public_room)).to eq(true)
+ end
+
+ it "prevents anonymous visitors from joining public rooms" do
+ expect(anonymous_guardian.can_join_voice_room?(public_room)).to eq(false)
+ end
+
+ it "prevents a create-room-group non-member from joining a private room" do
+ expect(outsider.guardian.can_join_voice_room?(private_room)).to eq(false)
+ end
+
+ it "lets members join a private room regardless of role" do
+ expect(member.guardian.can_join_voice_room?(private_room)).to eq(true)
+ expect(room_speaker.guardian.can_join_voice_room?(private_room)).to eq(true)
+ expect(room_moderator.guardian.can_join_voice_room?(private_room)).to eq(true)
+ end
+
+ it "lets the creator join their private room" do
+ expect(creator.guardian.can_join_voice_room?(private_room)).to eq(true)
+ end
+
+ it "lets site staff join a private room they aren't a member of" do
+ expect(staff.guardian.can_join_voice_room?(private_room)).to eq(true)
+ end
+
+ it "prevents users outside the voice allowed groups from joining" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}"
+
+ expect(member.guardian.can_join_voice_room?(private_room)).to eq(false)
+ end
+ end
+
+ describe "#can_see_voice_room?" do
+ it "lets anonymous visitors see public rooms when anonymous visitors are admitted" do
+ expect(anonymous_guardian.can_see_voice_room?(public_room)).to eq(true)
+ end
+
+ it "hides public rooms from anonymous visitors on login-required sites" do
+ SiteSetting.login_required = true
+
+ expect(anonymous_guardian.can_see_voice_room?(public_room)).to eq(false)
+ end
+
+ it "hides private rooms from anonymous visitors" do
+ expect(anonymous_guardian.can_see_voice_room?(private_room)).to eq(false)
+ end
+
+ it "hides private rooms from a create-room-group non-member" do
+ expect(outsider.guardian.can_see_voice_room?(private_room)).to eq(false)
+ end
+
+ it "shows private rooms to their members" do
+ expect(member.guardian.can_see_voice_room?(private_room)).to eq(true)
+ end
+
+ it "shows private rooms to site staff" do
+ expect(staff.guardian.can_see_voice_room?(private_room)).to eq(true)
+ end
+ end
+
+ describe "#can_request_to_speak_in_voice_room?" do
+ before { private_room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE) }
+
+ it "is true for a stage-room member with the participant role" do
+ expect(member.guardian.can_request_to_speak_in_voice_room?(private_room)).to eq(true)
+ end
+
+ it "is false for a stage speaker, who can already speak" do
+ expect(room_speaker.guardian.can_request_to_speak_in_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for a room moderator, who can already speak" do
+ expect(room_moderator.guardian.can_request_to_speak_in_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for site staff, who can already speak" do
+ expect(staff.guardian.can_request_to_speak_in_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false in an open room, where everyone can already speak" do
+ expect(member.guardian.can_request_to_speak_in_voice_room?(public_room)).to eq(false)
+ end
+
+ it "is false for a non-member who cannot join the private stage room" do
+ expect(outsider.guardian.can_request_to_speak_in_voice_room?(private_room)).to eq(false)
+ end
+
+ it "is false for anonymous visitors" do
+ public_room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+
+ expect(anonymous_guardian.can_request_to_speak_in_voice_room?(public_room)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/ice_config_spec.rb b/plugins/voice/spec/lib/voice/ice_config_spec.rb
new file mode 100644
index 00000000000..24502e53f9d
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/ice_config_spec.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Voice::IceConfig do
+ fab!(:user)
+
+ describe ".payload" do
+ it "builds one entry per STUN url, ignoring blank segments" do
+ SiteSetting.voice_stun_servers = "stun:stun.example.com:3478| |stun:stun2.example.com:19302"
+
+ payload = described_class.payload(user)
+
+ expect(payload[:servers]).to contain_exactly(
+ { urls: "stun:stun.example.com:3478" },
+ { urls: "stun:stun2.example.com:19302" },
+ )
+ end
+
+ it "attaches the static username and credential to every static TURN url" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_servers = "turn:turn.example.com:3478|turns:turn.example.com:5349"
+ SiteSetting.voice_turn_username = "static-user"
+ SiteSetting.voice_turn_credential = "static-pass"
+
+ payload = described_class.payload(user)
+
+ expect(payload[:servers]).to contain_exactly(
+ { urls: "turn:turn.example.com:3478", username: "static-user", credential: "static-pass" },
+ { urls: "turns:turn.example.com:5349", username: "static-user", credential: "static-pass" },
+ )
+ end
+
+ it "omits the username and credential keys when the static credentials are blank" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_servers = "turn:turn.example.com:3478"
+
+ payload = described_class.payload(user)
+
+ expect(payload[:servers]).to contain_exactly({ urls: "turn:turn.example.com:3478" })
+ end
+
+ it "mints ephemeral HMAC credentials scoped to the site and user for secret TURN servers" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:turn.example.com:3478"
+
+ freeze_time do
+ payload = described_class.payload(user)
+ server = payload[:servers].first
+
+ expected_username =
+ "#{(Time.zone.now + described_class::EPHEMERAL_CREDENTIAL_TTL).to_i}:#{Discourse.current_hostname}:#{user.id}"
+ expected_credential =
+ Base64.strict_encode64(
+ OpenSSL::HMAC.digest("SHA1", "coturn-shared-secret", expected_username),
+ )
+
+ expect(server).to eq(
+ urls: "turn:turn.example.com:3478",
+ username: expected_username,
+ credential: expected_credential,
+ )
+ end
+ end
+
+ it "separates quota identities of same-numbered users on different sites" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:coturn.example.com:3478"
+
+ freeze_time do
+ username = described_class.payload(user)[:servers].first[:username]
+
+ SiteSetting.force_hostname = "other-site.example.com"
+ other_site_username = described_class.payload(user)[:servers].first[:username]
+
+ expect(username).not_to eq(other_site_username)
+ expect(other_site_username).to eq(
+ "#{(Time.zone.now + described_class::EPHEMERAL_CREDENTIAL_TTL).to_i}:other-site.example.com:#{user.id}",
+ )
+ end
+ end
+
+ it "keeps static and secret TURN servers side by side with their own credentials" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_servers = "turn:third-party.example.com:3478"
+ SiteSetting.voice_turn_username = "static-user"
+ SiteSetting.voice_turn_credential = "static-pass"
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:coturn.example.com:3478"
+
+ servers = described_class.payload(user)[:servers]
+ static_server = servers.find { |server| server[:urls].include?("third-party") }
+ secret_server = servers.find { |server| server[:urls].include?("coturn") }
+
+ expect(servers.size).to eq(2)
+ expect(static_server[:username]).to eq("static-user")
+ expect(static_server[:credential]).to eq("static-pass")
+ expect(secret_server[:username]).to end_with(":#{Discourse.current_hostname}:#{user.id}")
+ expect(secret_server[:credential]).to eq(
+ Base64.strict_encode64(
+ OpenSSL::HMAC.digest("SHA1", "coturn-shared-secret", secret_server[:username]),
+ ),
+ )
+ end
+
+ it "skips secret TURN servers when the shared secret has been blanked" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:coturn.example.com:3478"
+ SiteSetting.voice_turn_secret = ""
+
+ expect(described_class.payload(user)[:servers]).to eq([])
+ end
+
+ it "forces relay when only static TURN servers are configured" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_servers = "turn:turn.example.com:3478"
+ SiteSetting.voice_turn_credential = "static-pass"
+
+ expect(described_class.payload(user)[:transport_policy]).to eq("relay")
+ end
+
+ it "keeps policy 'all' when secret TURN servers are active, even without STUN" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:coturn.example.com:3478"
+
+ expect(described_class.payload(user)[:transport_policy]).to eq("all")
+ end
+
+ it "keeps policy 'all' when STUN servers are configured alongside static TURN" do
+ SiteSetting.voice_stun_servers = "stun:stun.example.com:3478"
+ SiteSetting.voice_turn_servers = "turn:turn.example.com:3478"
+ SiteSetting.voice_turn_credential = "static-pass"
+
+ expect(described_class.payload(user)[:transport_policy]).to eq("all")
+ end
+
+ it "keeps policy 'all' when no TURN servers are configured" do
+ SiteSetting.voice_stun_servers = ""
+
+ expect(described_class.payload(user)[:transport_policy]).to eq("all")
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb b/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb
new file mode 100644
index 00000000000..4d4941f896e
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::Livekit::EgressClient do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ end
+
+ def twirp_stub(method)
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/#{method}")
+ end
+
+ describe ".start_room_composite" do
+ it "POSTs the room name and file output with a roomRecord-granted token" do
+ SiteSetting.voice_video_enabled = false
+ stub = twirp_stub("StartRoomCompositeEgress").to_return(body: { egressId: "EG_1" }.to_json)
+
+ result = described_class.start_room_composite(room, filepath: "voice/test-abc123")
+
+ expect(result).to eq(ok: true, data: { "egressId" => "EG_1" })
+ expect(stub).to have_been_requested
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).with do |req|
+ body = JSON.parse(req.body)
+ token = req.headers["Authorization"].delete_prefix("Bearer ")
+ claims =
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256").first
+
+ body ==
+ {
+ "roomName" => Voice::Livekit.room_name(room),
+ "audioOnly" => true,
+ "fileOutputs" => [{ "filepath" => "voice/test-abc123" }],
+ } && claims["iss"] == "lk_api_key" && claims["video"] == { "roomRecord" => true }
+ end,
+ ).to have_been_made.once
+ end
+
+ it "requests a full composite for a room with video enabled" do
+ SiteSetting.voice_video_enabled = true
+ room.update!(video_enabled: true)
+ twirp_stub("StartRoomCompositeEgress").to_return(body: "{}")
+
+ described_class.start_room_composite(room, filepath: "voice/test-abc123")
+
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).with { |req| JSON.parse(req.body)["audioOnly"] == false },
+ ).to have_been_made.once
+ end
+
+ it "returns a structured error on an error response, without the upstream body" do
+ upstream_body = "egress unavailable"
+ twirp_stub("StartRoomCompositeEgress").to_return(status: 500, body: upstream_body)
+
+ result = described_class.start_room_composite(room, filepath: "voice/test-abc123")
+
+ expect(result[:ok]).to eq(false)
+ expect(result[:error]).to eq("HTTP 500")
+ expect(result[:error]).not_to include(upstream_body)
+ end
+
+ it "returns a structured error instead of raising on a timeout" do
+ twirp_stub("StartRoomCompositeEgress").to_timeout
+
+ result = described_class.start_room_composite(room, filepath: "voice/test-abc123")
+
+ expect(result[:ok]).to eq(false)
+ end
+
+ it "makes zero HTTP calls when livekit is not configured" do
+ stub = twirp_stub("StartRoomCompositeEgress")
+ SiteSetting.voice_livekit_api_secret = ""
+
+ result = described_class.start_room_composite(room, filepath: "voice/test-abc123")
+
+ expect(result[:ok]).to eq(false)
+ expect(stub).not_to have_been_requested
+ end
+ end
+
+ describe ".stop" do
+ it "POSTs the egress id and returns the parsed response" do
+ stub =
+ twirp_stub("StopEgress").with(body: { egressId: "EG_1" }.to_json).to_return(
+ body: { egressId: "EG_1", status: "EGRESS_ENDING" }.to_json,
+ )
+
+ result = described_class.stop("EG_1")
+
+ expect(stub).to have_been_requested
+ expect(result).to eq(ok: true, data: { "egressId" => "EG_1", "status" => "EGRESS_ENDING" })
+ end
+
+ it "returns a structured error when the egress cannot be stopped" do
+ twirp_stub("StopEgress").to_return(status: 404, body: "egress does not exist")
+
+ result = described_class.stop("EG_missing")
+
+ expect(result[:ok]).to eq(false)
+ expect(result[:error]).to include("HTTP 404")
+ end
+ end
+
+ describe ".list" do
+ it "POSTs the egress id filter and returns the parsed items" do
+ stub =
+ twirp_stub("ListEgress").with(body: { egressId: "EG_1" }.to_json).to_return(
+ body: { items: [{ egressId: "EG_1", status: "EGRESS_COMPLETE" }] }.to_json,
+ )
+
+ result = described_class.list(egress_id: "EG_1")
+
+ expect(stub).to have_been_requested
+ expect(result[:ok]).to eq(true)
+ expect(result[:data]["items"].first["egressId"]).to eq("EG_1")
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/livekit/room_service_client_spec.rb b/plugins/voice/spec/lib/voice/livekit/room_service_client_spec.rb
new file mode 100644
index 00000000000..c763da3b18e
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/livekit/room_service_client_spec.rb
@@ -0,0 +1,272 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::Livekit::RoomServiceClient do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def twirp_stub(method)
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/#{method}")
+ end
+
+ describe ".remove_participant" do
+ it "POSTs the room name and identity with an admin bearer token" do
+ stub = twirp_stub("RemoveParticipant")
+
+ expect(described_class.remove_participant(room, user.id)).to eq(true)
+
+ expect(stub).to have_been_requested
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/RemoveParticipant",
+ ).with do |req|
+ body = JSON.parse(req.body)
+ token = req.headers["Authorization"].delete_prefix("Bearer ")
+ claims =
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256").first
+
+ body == { "room" => Voice::Livekit.room_name(room), "identity" => user.id.to_s } &&
+ req.headers["Content-Type"] == "application/json" && claims["iss"] == "lk_api_key" &&
+ claims["video"] == { "roomAdmin" => true, "room" => Voice::Livekit.room_name(room) }
+ end,
+ ).to have_been_made.once
+ end
+
+ it "converts a ws:// url to http:// for the API endpoint" do
+ SiteSetting.voice_livekit_url = "ws://livekit.internal:7880"
+ stub =
+ stub_request(
+ :post,
+ "http://livekit.internal:7880/twirp/livekit.RoomService/RemoveParticipant",
+ )
+
+ described_class.remove_participant(room, user.id)
+
+ expect(stub).to have_been_requested
+ end
+ end
+
+ describe ".update_participant" do
+ before { SiteSetting.voice_video_enabled = true }
+
+ it "sends the full permission set for a speaker in a video room" do
+ room.update!(video_enabled: true)
+ stub = twirp_stub("UpdateParticipant")
+
+ described_class.update_participant(room, user)
+
+ expect(stub).to have_been_requested
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant",
+ ).with do |req|
+ body = JSON.parse(req.body)
+ body["identity"] == user.id.to_s &&
+ body["permission"] ==
+ {
+ "canSubscribe" => true,
+ "canPublish" => true,
+ "canPublishData" => false,
+ "canPublishSources" => %w[MICROPHONE CAMERA SCREEN_SHARE SCREEN_SHARE_AUDIO],
+ "hidden" => false,
+ "recorder" => false,
+ }
+ end,
+ ).to have_been_made.once
+ end
+
+ it "grants all publish sources to a stage speaker in a video room" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE, video_enabled: true)
+ room.room_memberships.create!(user: user, role: Voice::RoomMembership::ROLE_SPEAKER)
+ twirp_stub("UpdateParticipant")
+
+ described_class.update_participant(room, user)
+
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant",
+ ).with do |req|
+ permission = JSON.parse(req.body)["permission"]
+ permission["canPublish"] == true &&
+ permission["canPublishSources"] == %w[MICROPHONE CAMERA SCREEN_SHARE SCREEN_SHARE_AUDIO]
+ end,
+ ).to have_been_made.once
+ end
+
+ it "keeps canSubscribe for a stage listener who cannot publish" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ stub = twirp_stub("UpdateParticipant")
+
+ described_class.update_participant(room, user)
+
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant",
+ ).with do |req|
+ permission = JSON.parse(req.body)["permission"]
+ permission["canSubscribe"] == true && permission["canPublish"] == false &&
+ permission["canPublishSources"] == []
+ end,
+ ).to have_been_made.once
+ end
+ end
+
+ describe ".delete_room" do
+ it "POSTs the room name with a roomCreate-granted token" do
+ stub = twirp_stub("DeleteRoom").with(body: { room: Voice::Livekit.room_name(room) }.to_json)
+
+ expect(described_class.delete_room(room)).to eq(true)
+
+ expect(stub).to have_been_requested
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom",
+ ).with do |req|
+ token = req.headers["Authorization"].delete_prefix("Bearer ")
+ claims =
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256").first
+
+ # LiveKit authorizes DeleteRoom via roomCreate, not roomAdmin.
+ claims["video"] == { "roomCreate" => true, "room" => Voice::Livekit.room_name(room) }
+ end,
+ ).to have_been_made.once
+ end
+
+ it "treats an already-deleted room as success without a warning" do
+ twirp_stub("DeleteRoom").to_return(status: 404, body: "requested room does not exist")
+ Rails.logger.expects(:warn).never
+
+ expect(described_class.delete_room(room)).to eq(true)
+ end
+ end
+
+ context "when the room is not pinned to livekit" do
+ let!(:stub) { stub_request(:post, %r{\Ahttps://livekit\.example\.com/twirp/}) }
+
+ it "makes zero HTTP calls for a mesh-pinned room" do
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ described_class.remove_participant(room, user.id)
+ described_class.update_participant(room, user)
+ described_class.delete_room(room)
+
+ expect(stub).not_to have_been_requested
+ end
+
+ it "makes zero HTTP calls for an unpinned room" do
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+
+ described_class.delete_room(room)
+
+ expect(stub).not_to have_been_requested
+ end
+
+ it "makes zero HTTP calls when livekit is no longer configured" do
+ SiteSetting.voice_livekit_api_secret = ""
+
+ described_class.delete_room(room)
+
+ expect(stub).not_to have_been_requested
+ end
+ end
+
+ context "when LiveKit is down" do
+ it "never raises on a timeout and logs the failure" do
+ twirp_stub("DeleteRoom").to_timeout
+ Rails.logger.expects(:warn).with(regexp_matches(/\[voice-livekit\] DeleteRoom failed/))
+
+ expect(described_class.delete_room(room)).to eq(false)
+ end
+
+ it "never raises on a refused connection" do
+ twirp_stub("DeleteRoom").to_raise(Errno::ECONNREFUSED)
+
+ expect { described_class.delete_room(room) }.not_to raise_error
+ end
+
+ it "still warns when a call other than DeleteRoom gets a 404" do
+ twirp_stub("RemoveParticipant").to_return(status: 404, body: "participant does not exist")
+ Rails
+ .logger
+ .expects(:warn)
+ .with(regexp_matches(/\[voice-livekit\] RemoveParticipant failed.*HTTP 404/))
+
+ expect(described_class.remove_participant(room, user.id)).to eq(false)
+ end
+
+ it "never raises on an error response and logs the failure" do
+ twirp_stub("RemoveParticipant").to_return(status: 500, body: "internal error")
+ Rails
+ .logger
+ .expects(:warn)
+ .with(regexp_matches(/\[voice-livekit\] RemoveParticipant failed.*HTTP 500/))
+
+ expect(described_class.remove_participant(room, user.id)).to eq(false)
+ end
+ end
+
+ describe ".list_rooms" do
+ it "keeps the upstream response body out of the probe result" do
+ upstream_body = "upstream stack trace with internal hostnames"
+ twirp_stub("ListRooms").to_return(status: 503, body: upstream_body)
+
+ result = described_class.list_rooms
+
+ expect(result[:ok]).to eq(false)
+ expect(result[:error]).to eq("HTTP 503")
+ expect(result[:error]).not_to include(upstream_body)
+ end
+ end
+
+ context "when the URL resolves to a disallowed address" do
+ it "refuses the connection and reports it without probing the host" do
+ FinalDestination::TestHelper.stub_to_fail do
+ result = described_class.list_rooms
+
+ expect(result[:ok]).to eq(false)
+ expect(result[:error]).to eq(
+ "The LiveKit URL resolves to an address this server is not allowed to reach",
+ )
+ end
+ end
+
+ it "fails a sync call without raising" do
+ FinalDestination::TestHelper.stub_to_fail do
+ expect(described_class.remove_participant(room, user.id)).to eq(false)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/livekit_spec.rb b/plugins/voice/spec/lib/voice/livekit_spec.rb
new file mode 100644
index 00000000000..4c5e62291b9
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/livekit_spec.rb
@@ -0,0 +1,172 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms"
+
+RSpec.describe Voice::Livekit do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :livekit_enabled)
+ AddLivekitEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ end
+
+ def decoded_token
+ token = described_class.mint_token(user: user, room: room, guardian: user.guardian)
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256").first
+ end
+
+ describe ".configured?" do
+ it "is true only when url, key, and secret are all present" do
+ expect(described_class.configured?).to eq(true)
+
+ SiteSetting.voice_livekit_api_secret = ""
+ expect(described_class.configured?).to eq(false)
+
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_url = ""
+ expect(described_class.configured?).to eq(false)
+ end
+ end
+
+ describe ".available_for?" do
+ it "follows the room policy" do
+ SiteSetting.voice_livekit_room_policy = "disabled"
+ expect(described_class.available_for?(room)).to eq(false)
+
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ expect(described_class.available_for?(room)).to eq(true)
+ end
+
+ it "follows the room's own flag under the per_room policy" do
+ SiteSetting.voice_livekit_room_policy = "per_room"
+
+ expect(described_class.available_for?(room)).to eq(false)
+
+ room.update!(livekit_enabled: true)
+ expect(described_class.available_for?(room)).to eq(true)
+ end
+
+ it "is false when the policy allows but the config is incomplete" do
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ SiteSetting.voice_livekit_api_secret = ""
+
+ expect(described_class.available_for?(room)).to eq(false)
+ end
+ end
+
+ describe ".room_name" do
+ it "namespaces by database name and room id" do
+ db = RailsMultisite::ConnectionManagement.current_db
+ expect(described_class.room_name(room)).to eq("#{db}-r#{room.id}")
+ end
+
+ it "prefers the configured prefix over the database name" do
+ SiteSetting.voice_livekit_room_prefix = "acme"
+ expect(described_class.room_name(room)).to eq("acme-r#{room.id}")
+ end
+ end
+
+ describe ".mint_token" do
+ it "raises MintError when not fully configured" do
+ SiteSetting.voice_livekit_api_secret = ""
+
+ expect { decoded_token }.to raise_error(described_class::MintError)
+ end
+
+ it "mints a least-privilege token for a speaker in a video room" do
+ SiteSetting.voice_video_enabled = true
+ room.update!(video_enabled: true)
+
+ freeze_time
+
+ payload = decoded_token
+
+ expect(payload["iss"]).to eq("lk_api_key")
+ expect(payload["sub"]).to eq(user.id.to_s)
+ expect(payload["name"]).to eq(user.username)
+ expect(payload["exp"]).to eq(described_class::TOKEN_TTL.from_now.to_i)
+ expect(payload["video"]).to eq(
+ "room" => described_class.room_name(room),
+ "roomJoin" => true,
+ "canSubscribe" => true,
+ "canPublish" => true,
+ "canPublishSources" => %w[microphone camera screen_share screen_share_audio],
+ "canPublishData" => false,
+ "canUpdateOwnMetadata" => false,
+ "roomCreate" => false,
+ "roomList" => false,
+ "roomAdmin" => false,
+ "roomRecord" => false,
+ "recorder" => false,
+ "hidden" => false,
+ )
+ end
+
+ it "grants only the microphone source when the room has no video" do
+ SiteSetting.voice_video_enabled = true
+ room.update!(video_enabled: false)
+
+ payload = decoded_token
+
+ expect(payload["video"]["canPublish"]).to eq(true)
+ expect(payload["video"]["canPublishSources"]).to eq(["microphone"])
+ end
+
+ it "denies publishing entirely to a stage listener" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+
+ payload = decoded_token
+
+ expect(payload["video"]["canSubscribe"]).to eq(true)
+ expect(payload["video"]["canPublish"]).to eq(false)
+ expect(payload["video"]["canPublishSources"]).to eq([])
+ end
+
+ it "grants all publish sources to a stage speaker when the room has video" do
+ SiteSetting.voice_video_enabled = true
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE, video_enabled: true)
+ room.room_memberships.create!(user: user, role: Voice::RoomMembership::ROLE_SPEAKER)
+
+ payload = decoded_token
+
+ expect(payload["video"]["canPublish"]).to eq(true)
+ expect(payload["video"]["canPublishSources"]).to eq(
+ %w[microphone camera screen_share screen_share_audio],
+ )
+ end
+
+ it "grants only the microphone to a stage speaker when the room has no video" do
+ SiteSetting.voice_video_enabled = true
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE, video_enabled: false)
+ room.room_memberships.create!(user: user, role: Voice::RoomMembership::ROLE_SPEAKER)
+
+ payload = decoded_token
+
+ expect(payload["video"]["canPublish"]).to eq(true)
+ expect(payload["video"]["canPublishSources"]).to eq(["microphone"])
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/room_hashtag_data_source_spec.rb b/plugins/voice/spec/lib/voice/room_hashtag_data_source_spec.rb
new file mode 100644
index 00000000000..f815f0b63db
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/room_hashtag_data_source_spec.rb
@@ -0,0 +1,247 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260220154336_add_cooked_description_to_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+
+RSpec.describe Voice::RoomHashtagDataSource do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :cooked_description)
+ AddCookedDescriptionToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ Voice::Room.reset_column_information
+ end
+
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_1].to_s
+ # The default create-rooms groups include TL2, which makes any TL2 user a
+ # global room manager who can see every room — raise the bar so the
+ # visibility assertions below actually exercise the membership checks.
+ SiteSetting.voice_create_room_allowed_groups = Group::AUTO_GROUPS[:trust_level_4].to_s
+ end
+
+ fab!(:creator) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[1], refresh_auto_groups: true) }
+ fab!(:room) do
+ Fabricate(:voice_room, name: "General", description: "Come hang out", public: true, creator:)
+ end
+ fab!(:private_room) { Fabricate(:voice_room, name: "Secret Sessions", creator:) }
+ fab!(:stage_room) do
+ Fabricate(
+ :voice_room,
+ name: "Town Hall",
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ creator:,
+ )
+ end
+
+ let(:guardian) { Guardian.new(user) }
+
+ def hashtag_hash(room)
+ {
+ relative_url: "/voice/r/#{room.slug}",
+ text: room.name,
+ description: room.description,
+ icon: room.stage? ? "podcast" : "microphone-lines",
+ style_type: "icon",
+ emoji: nil,
+ colors: nil,
+ type: "room",
+ ref: nil,
+ slug: room.slug,
+ id: room.id,
+ }
+ end
+
+ describe "#enabled?" do
+ it "follows the voice_enabled setting" do
+ expect(described_class.enabled?).to eq(true)
+ SiteSetting.voice_enabled = false
+ expect(described_class.enabled?).to eq(false)
+ end
+ end
+
+ describe "#lookup" do
+ it "finds a room by slug" do
+ expect(described_class.lookup(guardian, ["general"]).map(&:to_h)).to eq([hashtag_hash(room)])
+ end
+
+ it "matches stored slugs case-insensitively" do
+ room.update_columns(slug: "GeNeRaL")
+ expect(described_class.lookup(guardian, ["general"]).map(&:id)).to eq([room.id])
+ end
+
+ it "can return multiple rooms" do
+ expect(described_class.lookup(guardian, %w[general town-hall]).map(&:slug)).to eq(
+ %w[general town-hall],
+ )
+ end
+
+ it "uses the podcast icon for stage rooms" do
+ expect(described_class.lookup(guardian, ["town-hall"]).first.to_h).to eq(
+ hashtag_hash(stage_room),
+ )
+ end
+
+ it "uses the base icon for private rooms" do
+ expect(described_class.lookup(Guardian.new(creator), ["secret-sessions"]).first.icon).to eq(
+ "microphone-lines",
+ )
+
+ private_room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ expect(described_class.lookup(Guardian.new(creator), ["secret-sessions"]).first.icon).to eq(
+ "podcast",
+ )
+ end
+
+ it "does not return a private room the user is not a member of" do
+ expect(described_class.lookup(guardian, ["secret-sessions"])).to be_empty
+ end
+
+ it "returns a private room to its members" do
+ private_room.room_memberships.create!(user: user)
+ expect(described_class.lookup(guardian, ["secret-sessions"]).map(&:slug)).to eq(
+ ["secret-sessions"],
+ )
+ end
+
+ it "returns a private room to its creator" do
+ expect(described_class.lookup(Guardian.new(creator), ["secret-sessions"]).map(&:slug)).to eq(
+ ["secret-sessions"],
+ )
+ end
+
+ it "never returns ephemeral rooms" do
+ ephemeral = Fabricate(:voice_ephemeral_room, name: "General Call", public: true, creator:)
+
+ expect(described_class.lookup(guardian, [ephemeral.slug])).to be_empty
+ expect(described_class.search(guardian, "general call", 5)).to be_empty
+ end
+
+ it "returns nothing for users outside voice_allowed_groups" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:staff].to_s
+ expect(described_class.lookup(guardian, ["general"])).to be_empty
+ end
+
+ it "returns public rooms to anonymous users when anonymous visitors are admitted" do
+ expect(described_class.lookup(Guardian.new, ["general"])).to be_empty
+
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ expect(described_class.lookup(Guardian.new, %w[general secret-sessions]).map(&:slug)).to eq(
+ ["general"],
+ )
+ end
+ end
+
+ describe "#search" do
+ it "finds a room by name" do
+ expect(described_class.search(guardian, "gener", 10).map(&:to_h)).to eq([hashtag_hash(room)])
+ end
+
+ it "finds a room by slug and matches anywhere in the term" do
+ expect(described_class.search(guardian, "hall", 10).map(&:slug)).to eq(["town-hall"])
+ end
+
+ it "only matches the start of the term with the starts_with condition" do
+ starts_with = HashtagAutocompleteService.search_conditions[:starts_with]
+ expect(described_class.search(guardian, "hall", 10, starts_with)).to be_empty
+ expect(described_class.search(guardian, "town", 10, starts_with).map(&:slug)).to eq(
+ ["town-hall"],
+ )
+ end
+
+ it "does not return private rooms the user cannot see" do
+ expect(described_class.search(guardian, "secret", 10)).to be_empty
+ expect(described_class.search(Guardian.new(creator), "secret", 10).map(&:slug)).to eq(
+ ["secret-sessions"],
+ )
+ end
+
+ it "respects the limit and keeps name ordering when truncating" do
+ expect(described_class.search(Guardian.new(creator), "e", 1).map(&:slug)).to eq(["general"])
+ end
+
+ it "treats SQL wildcard characters in the term literally" do
+ expect(described_class.search(guardian, "%", 10)).to be_empty
+ expect(described_class.search(guardian, "gen_ral", 10)).to be_empty
+ end
+ end
+
+ describe "#search_without_term" do
+ it "returns visible rooms ordered by name" do
+ expect(described_class.search_without_term(guardian, 10).map(&:slug)).to eq(
+ %w[general town-hall],
+ )
+ expect(described_class.search_without_term(Guardian.new(creator), 10).map(&:slug)).to eq(
+ %w[general secret-sessions town-hall],
+ )
+ end
+ end
+
+ describe "#find_by_ids" do
+ it "returns only visible rooms among the ids" do
+ expect(described_class.find_by_ids(guardian, [room.id, private_room.id]).map(&:id)).to eq(
+ [room.id],
+ )
+ end
+ end
+
+ describe "#search_sort" do
+ it "orders results by text" do
+ results = [stage_room, room].map { |r| described_class.room_to_hashtag_item(r) }
+ expect(described_class.search_sort(results, "").map(&:slug)).to eq(%w[general town-hall])
+ end
+ end
+
+ describe "cooking" do
+ it "cooks a room hashtag into a link for a user who can see the room" do
+ cooked = PrettyText.cook("#general::room", user_id: user.id)
+ link = Nokogiri::HTML5.fragment(cooked).css("a.hashtag-cooked").first
+
+ expect(link["href"]).to eq("/voice/r/general")
+ expect(link["data-type"]).to eq("room")
+ expect(link["data-slug"]).to eq("general")
+ expect(link["data-id"]).to eq(room.id.to_s)
+ expect(link["data-icon"]).to eq("microphone-lines")
+ end
+
+ it "leaves the hashtag raw for a user who cannot see the room" do
+ cooked = PrettyText.cook("#secret-sessions::room", user_id: user.id)
+
+ expect(Nokogiri::HTML5.fragment(cooked).css("a.hashtag-cooked")).to be_empty
+ expect(cooked).to include("hashtag-raw")
+ end
+ end
+
+ describe "chat hashtag configuration snapshot" do
+ it "tracks the voice_enabled setting at runtime" do
+ skip "chat plugin not installed" unless defined?(::Chat)
+
+ SiteSetting.voice_enabled = false
+ expect(
+ Site.markdown_additional_options.dig("chat", :hashtag_configurations)["chat-composer"],
+ ).not_to include("room")
+
+ SiteSetting.voice_enabled = true
+ expect(
+ Site.markdown_additional_options.dig("chat", :hashtag_configurations)["chat-composer"],
+ ).to include("room")
+ end
+ end
+end
diff --git a/plugins/voice/spec/lib/voice/user_status_manager_spec.rb b/plugins/voice/spec/lib/voice/user_status_manager_spec.rb
new file mode 100644
index 00000000000..80a9b665aed
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/user_status_manager_spec.rb
@@ -0,0 +1,250 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Voice::UserStatusManager do
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+ fab!(:private_room) { Fabricate(:voice_room, public: false) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ end
+
+ describe ".set_voice_status" do
+ it "sets the user's status with room name and no expiry" do
+ described_class.set_voice_status(user, room)
+
+ user.reload
+ expect(user.user_status.description).to eq("In #{room.name}")
+ expect(user.user_status.emoji).to eq("studio_microphone")
+ expect(user.user_status.ends_at).to be_nil
+ end
+
+ it "does not republish an unchanged status" do
+ described_class.set_voice_status(user, room)
+
+ messages = MessageBus.track_publish { described_class.set_voice_status(user, room) }
+
+ expect(messages).to be_empty
+ end
+
+ it "does not leak the name of a private room" do
+ described_class.set_voice_status(user, private_room)
+
+ user.reload
+ expect(user.user_status.description).to eq("In a voice room")
+ expect(user.user_status.description).not_to include(private_room.name)
+ end
+
+ it "skips when user already has a non-Voice status" do
+ user.set_status!("On vacation", "palm_tree")
+
+ described_class.set_voice_status(user, room)
+
+ user.reload
+ expect(user.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "overwrites an existing Voice status" do
+ user.set_status!("In Old Room", "studio_microphone")
+
+ described_class.set_voice_status(user, room)
+
+ user.reload
+ expect(user.user_status.description).to eq("In #{room.name}")
+ end
+
+ it "rewrites a matching status that still carries an expiry" do
+ user.set_status!("In #{room.name}", "studio_microphone", 2.minutes.from_now)
+
+ described_class.set_voice_status(user, room)
+
+ expect(user.reload.user_status.ends_at).to be_nil
+ end
+
+ it "skips when enable_user_status is false" do
+ SiteSetting.enable_user_status = false
+
+ described_class.set_voice_status(user, room)
+
+ expect(user.user_status).to be_nil
+ end
+
+ it "skips when voice_auto_status_enabled is false" do
+ SiteSetting.voice_auto_status_enabled = false
+
+ described_class.set_voice_status(user, room)
+
+ expect(user.user_status).to be_nil
+ end
+ end
+
+ describe ".set_afk_status" do
+ it "transitions to AFK status when Voice owns the current status" do
+ described_class.set_voice_status(user, room)
+ described_class.set_afk_status(user, room)
+
+ user.reload
+ expect(user.user_status.description).to eq("AFK in #{room.name}")
+ expect(user.user_status.emoji).to eq("zzz")
+ expect(user.user_status.ends_at).to be_nil
+ end
+
+ it "does not leak the name of a private room" do
+ described_class.set_voice_status(user, private_room)
+ described_class.set_afk_status(user, private_room)
+
+ user.reload
+ expect(user.user_status.description).to eq("AFK in a voice room")
+ expect(user.user_status.description).not_to include(private_room.name)
+ end
+
+ it "skips when the user has a non-Voice status" do
+ user.set_status!("On vacation", "palm_tree")
+
+ described_class.set_afk_status(user, room)
+
+ user.reload
+ expect(user.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "skips when user has no status" do
+ described_class.set_afk_status(user, room)
+
+ expect(user.user_status).to be_nil
+ end
+ end
+
+ describe ".clear_voice_status" do
+ it "clears status when Voice owns it" do
+ described_class.set_voice_status(user, room)
+ described_class.clear_voice_status(user)
+
+ user.reload
+ expect(user.user_status).to be_nil
+ end
+
+ it "clears AFK status" do
+ described_class.set_voice_status(user, room)
+ described_class.set_afk_status(user, room)
+ described_class.clear_voice_status(user)
+
+ user.reload
+ expect(user.user_status).to be_nil
+ end
+
+ it "does not clear a non-Voice status" do
+ user.set_status!("On vacation", "palm_tree")
+
+ described_class.clear_voice_status(user)
+
+ user.reload
+ expect(user.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "does nothing when user has no status" do
+ expect { described_class.clear_voice_status(user) }.not_to raise_error
+ end
+ end
+
+ describe ".clear_stale_statuses" do
+ fab!(:other_user, :user)
+
+ it "clears Voice statuses of users not in the live set" do
+ described_class.set_voice_status(user, room)
+ described_class.set_voice_status(other_user, room)
+ described_class.set_afk_status(other_user, room)
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([user.id])
+
+ expect(user.reload.user_status).to be_present
+ expect(other_user.reload.user_status).to be_nil
+ end
+
+ it "clears everything when no one is live" do
+ described_class.set_voice_status(user, room)
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status).to be_nil
+ end
+
+ it "leaves a freshly set status for the next sweep" do
+ described_class.set_voice_status(user, room)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status).to be_present
+ end
+
+ it "does not touch non-Voice statuses" do
+ user.set_status!("On vacation", "palm_tree")
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "does not clear a manually set status that uses a Voice emoji" do
+ user.set_status!("Sleeping", "zzz")
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status.emoji).to eq("zzz")
+ end
+
+ it "does not clear a manual status that replaced a Voice one" do
+ described_class.set_voice_status(user, room)
+ user.set_status!("On vacation", "palm_tree")
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "skips when enable_user_status is false" do
+ described_class.set_voice_status(user, room)
+ SiteSetting.enable_user_status = false
+ freeze_time(1.minute.from_now)
+
+ described_class.clear_stale_statuses([])
+
+ expect(user.reload.user_status).to be_present
+ end
+ end
+
+ describe ".voice_status_active?" do
+ it "returns true for studio_microphone emoji" do
+ user.set_status!("In Room", "studio_microphone", 2.minutes.from_now)
+ expect(described_class.voice_status_active?(user)).to eq(true)
+ end
+
+ it "returns true for zzz emoji" do
+ user.set_status!("AFK in Room", "zzz", 2.minutes.from_now)
+ expect(described_class.voice_status_active?(user)).to eq(true)
+ end
+
+ it "returns false for other emojis" do
+ user.set_status!("On vacation", "palm_tree")
+ expect(described_class.voice_status_active?(user)).to eq(false)
+ end
+
+ it "returns false when user has no status" do
+ expect(described_class.voice_status_active?(user)).to be_falsey
+ end
+
+ it "returns false when status is expired" do
+ user.set_status!("In Room", "studio_microphone", 1.minute.from_now)
+ freeze_time(2.minutes.from_now)
+ expect(described_class.voice_status_active?(user)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/voice/spec/models/reviewable_voice_user_spec.rb b/plugins/voice/spec/models/reviewable_voice_user_spec.rb
new file mode 100644
index 00000000000..44eef886df2
--- /dev/null
+++ b/plugins/voice/spec/models/reviewable_voice_user_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe ReviewableVoiceUser do
+ fab!(:moderator)
+ fab!(:flagger, :user)
+ fab!(:flagged_user, :user)
+ fab!(:room, :voice_room)
+ fab!(:session) { Fabricate(:voice_session, room: room, user: flagged_user) }
+
+ fab!(:reviewable) do
+ reviewable =
+ ReviewableVoiceUser.needs_review!(
+ created_by: flagger,
+ target: session,
+ reviewable_by_moderator: true,
+ )
+ reviewable.update!(
+ target_created_by: flagged_user,
+ payload: {
+ message: "Being disruptive",
+ room_id: room.id,
+ room_name: room.name,
+ room_slug: room.slug,
+ },
+ )
+ reviewable.add_score(flagger, ReviewableScore.types[:notify_moderators])
+ reviewable
+ end
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe "#build_actions" do
+ it "offers agree, suspend/silence, disagree and ignore to a moderator" do
+ actions = reviewable.actions_for(moderator.guardian)
+
+ expect(actions.to_a.map(&:server_action).map(&:to_sym)).to contain_exactly(
+ :agree_and_keep,
+ :agree_and_suspend,
+ :agree_and_silence,
+ :disagree,
+ :ignore,
+ )
+ end
+
+ it "offers no actions once the reviewable is handled" do
+ reviewable.perform(moderator, :ignore)
+
+ expect(reviewable.actions_for(moderator.guardian).to_a).to be_empty
+ end
+ end
+
+ describe "#perform" do
+ it "approves the reviewable and agrees with the flag on agree_and_keep" do
+ reviewable.perform(moderator, :agree_and_keep)
+
+ expect(reviewable.reload).to be_approved
+ expect(reviewable.reviewable_scores.first).to be_agreed
+ end
+
+ it "rejects the reviewable and disagrees with the flag on disagree" do
+ reviewable.perform(moderator, :disagree)
+
+ expect(reviewable.reload).to be_rejected
+ expect(reviewable.reviewable_scores.first).to be_disagreed
+ end
+
+ it "ignores the reviewable and the flag on ignore" do
+ reviewable.perform(moderator, :ignore)
+
+ expect(reviewable.reload).to be_ignored
+ expect(reviewable.reviewable_scores.first).to be_ignored
+ end
+ end
+end
diff --git a/plugins/voice/spec/models/voice/room_spec.rb b/plugins/voice/spec/models/voice/room_spec.rb
new file mode 100644
index 00000000000..308c4fafc1b
--- /dev/null
+++ b/plugins/voice/spec/models/voice/room_spec.rb
@@ -0,0 +1,192 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260728201053_add_max_quality_profile_to_voice_rooms"
+
+RSpec.describe Voice::Room do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :max_quality_profile)
+ AddMaxQualityProfileToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:room, :voice_room)
+
+ describe "slug generation" do
+ it "appends a random suffix for ephemeral rooms so generic names never collide" do
+ persistent = Fabricate(:voice_room, name: "Call")
+ ephemeral = Fabricate(:voice_ephemeral_room, name: "Call")
+
+ expect(persistent.slug).to eq("call")
+ expect(ephemeral.slug).to match(/\Acall-\h{8}\z/)
+ end
+
+ it "normalizes and keeps a user-provided slug" do
+ custom = Fabricate(:voice_room, name: "Game Night", slug: "Friday Hangout")
+
+ expect(custom.slug).to eq("friday-hangout")
+ end
+
+ it "rejects a provided slug that normalizes to nothing" do
+ custom = Fabricate.build(:voice_room, name: "Game Night", slug: "!!!")
+
+ expect(custom).not_to be_valid
+ expect(custom.errors[:slug]).to be_present
+ end
+
+ it "keeps the existing slug when the room is renamed" do
+ room.update!(name: "Renamed room")
+
+ expect(room.reload.slug).not_to eq("renamed-room")
+ end
+
+ it "regenerates the slug from the name when it is cleared" do
+ room.update!(name: "Fresh name", slug: "")
+
+ expect(room.reload.slug).to eq("fresh-name")
+ end
+ end
+
+ describe "#video_allowed?" do
+ before { SiteSetting.voice_video_enabled = true }
+
+ it "is true for a stage room with video enabled" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE, video_enabled: true)
+
+ expect(room.video_allowed?).to eq(true)
+ end
+
+ it "is true for an open room with video enabled" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_OPEN, video_enabled: true)
+
+ expect(room.video_allowed?).to eq(true)
+ end
+
+ it "is false when the site setting is disabled" do
+ SiteSetting.voice_video_enabled = false
+ room.update!(video_enabled: true)
+
+ expect(room.video_allowed?).to eq(false)
+ end
+
+ it "is false when the room has video disabled" do
+ room.update!(video_enabled: false)
+
+ expect(room.video_allowed?).to eq(false)
+ end
+ end
+
+ describe "chat_idle_minutes validation" do
+ it "rejects a value below the 2 minute floor" do
+ room.chat_idle_minutes = 1
+ expect(room).not_to be_valid
+ expect(room.errors[:chat_idle_minutes]).to be_present
+ end
+
+ it "accepts the 2 minute floor" do
+ room.chat_idle_minutes = 2
+ expect(room).to be_valid
+ end
+
+ it "rejects a value above the 1440 minute (24h) ceiling" do
+ room.chat_idle_minutes = 1441
+ expect(room).not_to be_valid
+ end
+
+ it "defaults to 15 minutes" do
+ expect(described_class.new.chat_idle_minutes).to eq(15)
+ end
+ end
+
+ describe "max_quality_profile validation" do
+ it "accepts nil, meaning no room-level cap" do
+ room.max_quality_profile = nil
+ expect(room).to be_valid
+ end
+
+ it "accepts every known profile" do
+ Voice::Room::QUALITY_PROFILES.each_value do |profile|
+ room.max_quality_profile = profile
+ expect(room).to be_valid
+ end
+ end
+
+ it "rejects unknown values" do
+ room.max_quality_profile = 42
+ expect(room).not_to be_valid
+ expect(room.errors[:max_quality_profile]).to be_present
+ end
+ end
+
+ describe "#max_quality_profile_name" do
+ it "maps the stored integer back to its name and nil to nil" do
+ expect(described_class.new(max_quality_profile: 1).max_quality_profile_name).to eq("high")
+ expect(described_class.new.max_quality_profile_name).to be_nil
+ end
+ end
+
+ describe "#chat_idle_seconds" do
+ it "floors to 2 minutes even if a lower value slipped through" do
+ room.update_column(:chat_idle_minutes, 0)
+ expect(room.reload.chat_idle_seconds).to eq(2 * 60)
+ end
+
+ it "converts minutes to seconds" do
+ room.update!(chat_idle_minutes: 5)
+ expect(room.chat_idle_seconds).to eq(5 * 60)
+ end
+ end
+
+ describe "chat_channel_id validation" do
+ fab!(:threaded_channel) { Fabricate(:chat_channel, threading_enabled: true) }
+ fab!(:unthreaded_channel) { Fabricate(:chat_channel, threading_enabled: false) }
+
+ it "allows linking a channel that already has threading enabled" do
+ room.chat_channel_id = threaded_channel.id
+ expect(room).to be_valid
+ end
+
+ it "rejects linking a channel without threading enabled" do
+ room.chat_channel_id = unthreaded_channel.id
+ expect(room).not_to be_valid
+ expect(room.errors[:chat_channel_id]).to be_present
+ end
+
+ it "rejects linking a channel id that doesn't exist" do
+ room.chat_channel_id = unthreaded_channel.id + 100_000
+ expect(room).not_to be_valid
+ expect(room.errors[:chat_channel_id]).to be_present
+ end
+
+ it "allows clearing the channel back to none" do
+ room.update!(chat_channel_id: threaded_channel.id)
+ room.chat_channel_id = nil
+ expect(room).to be_valid
+ end
+
+ it "does not re-validate on an unrelated save once linked, even if the channel's threading is later disabled" do
+ room.update!(chat_channel_id: threaded_channel.id)
+ threaded_channel.update!(threading_enabled: false)
+
+ room.name = "Renamed"
+ expect(room).to be_valid
+ end
+ end
+end
diff --git a/plugins/voice/spec/plugin_spec.rb b/plugins/voice/spec/plugin_spec.rb
new file mode 100644
index 00000000000..fe2c331c198
--- /dev/null
+++ b/plugins/voice/spec/plugin_spec.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+RSpec.describe UserDestroyer do
+ describe "voice cleanup" do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:room) { Fabricate(:voice_room, creator: user, public: true) }
+
+ before { SiteSetting.voice_enabled = true }
+
+ it "moves the deleted user's rooms to the system user" do
+ UserDestroyer.new(admin).destroy(user)
+
+ expect(room.reload.creator_id).to eq(Discourse.system_user.id)
+ end
+
+ it "removes memberships and co-presences but keeps sessions as history" do
+ session = Fabricate(:voice_session, user: user, room: room)
+ ids = [user.id, other_user.id].minmax
+ co_presence =
+ Voice::CoPresence.create!(
+ user_id_1: ids.first,
+ user_id_2: ids.last,
+ date: Time.zone.today,
+ total_seconds: 60,
+ session_count: 1,
+ )
+
+ UserDestroyer.new(admin).destroy(user)
+
+ expect(Voice::RoomMembership.where(user_id: user.id)).to be_empty
+ expect(Voice::CoPresence.exists?(co_presence.id)).to eq(false)
+ expect(session.reload.user_id).to eq(user.id)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/admin_livekit_controller_spec.rb b/plugins/voice/spec/requests/voice/admin_livekit_controller_spec.rb
new file mode 100644
index 00000000000..b796049892c
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/admin_livekit_controller_spec.rb
@@ -0,0 +1,312 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms"
+
+RSpec.describe Voice::AdminLivekitController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :livekit_enabled)
+ AddLivekitEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:admin)
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:ghost_user, :user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before { SiteSetting.voice_enabled = true }
+
+ after do
+ Voice::ParticipantTracker.clear(room.id)
+ Discourse.redis.del(Voice::Livekit::HealthCheck::LAST_PROBE_KEY)
+ Discourse.redis.del(Voice::Livekit::LAST_WEBHOOK_KEY)
+ end
+
+ def configure_livekit!
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ end
+
+ def list_rooms_stub
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/ListRooms")
+ end
+
+ def list_participants_stub
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/ListParticipants")
+ end
+
+ def get_status
+ get "/admin/plugins/voice/livekit/status.json"
+ end
+
+ def post_probe
+ post "/admin/plugins/voice/livekit/probe.json"
+ end
+
+ describe "access control" do
+ it "is hidden from anonymous users" do
+ get_status
+ expect(response.status).to eq(404)
+ end
+
+ it "is hidden from regular users" do
+ sign_in(user)
+ get_status
+ expect(response.status).to eq(404)
+ end
+
+ it "is available to admins" do
+ sign_in(admin)
+ get_status
+ expect(response.status).to eq(200)
+ end
+
+ it "includes the site's webhook endpoint for the config snippet" do
+ sign_in(admin)
+ get_status
+ expect(response.parsed_body["webhook_url"]).to eq(
+ "#{Discourse.base_url}/voice/livekit/webhook",
+ )
+ end
+ end
+
+ describe "when LiveKit is not configured" do
+ before { sign_in(admin) }
+
+ it "reports the missing settings without probing anything" do
+ probe_stub = stub_request(:post, %r{\Ahttps://})
+
+ get_status
+
+ body = response.parsed_body
+ expect(body["configured"]).to eq(false)
+ expect(body["settings"]).to eq(
+ "url_present" => false,
+ "api_key_present" => false,
+ "api_secret_present" => false,
+ "policy" => "disabled",
+ )
+ expect(body["rooms"]).to eq([])
+ expect(body).not_to have_key("token_check")
+ expect(body).not_to have_key("server_check")
+ expect(probe_stub).not_to have_been_requested
+ end
+
+ it "reports which settings are present on a half-configured install" do
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+
+ get_status
+
+ settings = response.parsed_body["settings"]
+ expect(settings["url_present"]).to eq(true)
+ expect(settings["api_key_present"]).to eq(false)
+ expect(settings["api_secret_present"]).to eq(false)
+ end
+ end
+
+ describe "when LiveKit is configured" do
+ before do
+ sign_in(admin)
+ configure_livekit!
+ end
+
+ it "returns a passing token check and a timed server probe" do
+ list_rooms_stub.to_return(
+ status: 200,
+ body: { rooms: [{ name: "default-r1" }, { name: "default-r2" }] }.to_json,
+ )
+
+ get_status
+
+ body = response.parsed_body
+ expect(body["configured"]).to eq(true)
+ expect(body["token_check"]).to eq("ok" => true)
+ expect(body["server_check"]["ok"]).to eq(true)
+ expect(body["server_check"]["latency_ms"]).to be_a(Integer)
+ expect(body["server_check"]["room_count"]).to eq(2)
+ end
+
+ it "probes with a roomList-granted token" do
+ list_rooms_stub.to_return(status: 200, body: { rooms: [] }.to_json)
+
+ get_status
+
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/ListRooms",
+ ).with do |req|
+ token = req.headers["Authorization"].delete_prefix("Bearer ")
+ claims =
+ JWT.decode(token, SiteSetting.voice_livekit_api_secret, true, algorithm: "HS256").first
+ claims["iss"] == "lk_api_key" && claims["video"] == { "roomList" => true }
+ end,
+ ).to have_been_made.once
+ end
+
+ it "surfaces the server error string when the probe fails" do
+ list_rooms_stub.to_return(status: 401, body: "invalid authorization token")
+
+ get_status
+
+ server_check = response.parsed_body["server_check"]
+ expect(server_check["ok"]).to eq(false)
+ expect(server_check["error"]).to include("HTTP 401")
+ end
+
+ it "surfaces connection errors as strings, never raising" do
+ list_rooms_stub.to_timeout
+
+ get_status
+
+ expect(response.status).to eq(200)
+ server_check = response.parsed_body["server_check"]
+ expect(server_check["ok"]).to eq(false)
+ expect(server_check["error"]).to be_present
+ end
+
+ it "surfaces the stored probe result and the webhook freshness marker" do
+ list_rooms_stub.to_return(status: 200, body: { rooms: [] }.to_json)
+ freeze_time
+ Voice::Livekit.touch_last_webhook!
+ Jobs::VoiceLivekitProbe.new.execute({})
+
+ get_status
+
+ body = response.parsed_body
+ # iso8601 truncates fractional seconds, so compare whole seconds
+ expect(Time.parse(body["last_webhook_at"]).to_i).to eq(Time.now.to_i)
+ expect(body["last_probe"]["ok"]).to eq(true)
+ expect(body["last_probe"]["checked_at"]).to eq(Time.now.utc.iso8601)
+ end
+
+ it "stores a fresh connectivity result when an admin refreshes the probe" do
+ list_rooms_stub.to_return(status: 200, body: { rooms: [] }.to_json)
+ freeze_time
+
+ post_probe
+
+ expect(response.status).to eq(200)
+ probe = response.parsed_body["last_probe"]
+ expect(probe["ok"]).to eq(true)
+ expect(probe["checked_at"]).to eq(Time.now.utc.iso8601)
+ expect(probe["token"]).to eq("ok" => true)
+ expect(probe["server"]["latency_ms"]).to be_a(Integer)
+ expect(probe["server"]["room_count"]).to eq(0)
+ expect(Voice::Livekit::HealthCheck.last_probe[:ok]).to eq(true)
+ end
+
+ describe "pinned livekit rooms" do
+ before do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ list_rooms_stub.to_return(status: 200, body: { rooms: [] }.to_json)
+ end
+
+ it "diffs Redis presence against the participants LiveKit reports" do
+ # `other_user` is in the roster but unknown to LiveKit (the classic
+ # "connects but no media" victim); `ghost_user` is connected to the
+ # SFU but fell out of the roster; non-numeric identities (egress,
+ # other tools) are ignored.
+ list_participants_stub.to_return(
+ status: 200,
+ body: {
+ participants: [
+ { identity: user.id.to_s },
+ { identity: ghost_user.id.to_s },
+ { identity: "recorder-1" },
+ ],
+ }.to_json,
+ )
+
+ get_status
+
+ rooms = response.parsed_body["rooms"]
+ expect(rooms.size).to eq(1)
+ room_status = rooms.first
+ expect(room_status["room_id"]).to eq(room.id)
+ expect(room_status["name"]).to eq(room.name)
+ expect(room_status["presence_user_ids"]).to eq([user.id, other_user.id].sort)
+ expect(room_status["livekit_user_ids"]).to eq([user.id, ghost_user.id].sort)
+ expect(room_status["missing_on_livekit"]).to eq([other_user.id])
+ expect(room_status["missing_in_presence"]).to eq([ghost_user.id])
+
+ usernames = response.parsed_body["usernames"]
+ expect(usernames[user.id.to_s]).to eq(user.username)
+ expect(usernames[other_user.id.to_s]).to eq(other_user.username)
+ expect(usernames[ghost_user.id.to_s]).to eq(ghost_user.username)
+ end
+
+ it "reports a per-room error when listing participants fails" do
+ list_participants_stub.to_return(status: 500, body: "internal error")
+
+ get_status
+
+ room_status = response.parsed_body["rooms"].first
+ expect(room_status["error"]).to include("HTTP 500")
+ expect(room_status).not_to have_key("livekit_user_ids")
+ expect(room_status["presence_user_ids"]).to eq([user.id, other_user.id].sort)
+ end
+
+ it "skips per-room probes when the server is already unreachable" do
+ list_rooms_stub.to_timeout
+ participants_stub = list_participants_stub
+
+ get_status
+
+ room_status = response.parsed_body["rooms"].first
+ expect(room_status["presence_user_ids"]).to eq([user.id, other_user.id].sort)
+ expect(room_status).not_to have_key("livekit_user_ids")
+ expect(room_status).not_to have_key("error")
+ expect(participants_stub).not_to have_been_requested
+ end
+
+ it "ignores rooms pinned to mesh" do
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ get_status
+
+ expect(response.parsed_body["rooms"]).to eq([])
+ end
+ end
+
+ it "never leaks the API secret or key in the status payload or the site serializer" do
+ list_rooms_stub.to_return(status: 401, body: "invalid authorization token")
+ list_participants_stub.to_return(status: 401, body: "invalid authorization token")
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+ Jobs::VoiceLivekitProbe.new.execute({})
+
+ get_status
+ expect(response.status).to eq(200)
+ expect(response.body).not_to include("lk_api_secret")
+ expect(response.body).not_to include("lk_api_key")
+
+ get "/site.json"
+ expect(response.status).to eq(200)
+ expect(response.body).not_to include("lk_api_secret")
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/admin_recordings_controller_spec.rb b/plugins/voice/spec/requests/voice/admin_recordings_controller_spec.rb
new file mode 100644
index 00000000000..db0a783dffc
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/admin_recordings_controller_spec.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260717172530_create_voice_recordings"
+
+RSpec.describe Voice::AdminRecordingsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_recordings)
+ CreateVoiceRecordings.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ Voice::Recording.reset_column_information
+ end
+
+ fab!(:admin)
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ fab!(:recording) do
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: "EG_1",
+ status: :completed,
+ filepath: "voice/test-abc123",
+ location: "https://cdn.example.com/voice/test-abc123.mp4",
+ duration_ms: 65_000,
+ started_at: 1.hour.ago,
+ ended_at: 59.minutes.ago,
+ )
+ end
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe "#index" do
+ it "lists recordings newest-first with room, requester, and file details for admins" do
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: "EG_2",
+ filepath: "voice/test-def456",
+ started_at: 5.minutes.ago,
+ )
+ sign_in(admin)
+
+ get "/admin/plugins/voice/recordings.json"
+
+ expect(response.status).to eq(200)
+ payload = response.parsed_body
+ expect(payload["has_more"]).to eq(false)
+ expect(payload["recordings"].map { |row| row["egress_id"] }).to eq(%w[EG_2 EG_1])
+
+ completed = payload["recordings"].last
+ expect(completed["room_name"]).to eq(room.name)
+ expect(completed["started_by"]["username"]).to eq(user.username)
+ expect(completed["status"]).to eq("completed")
+ expect(completed["location"]).to eq("https://cdn.example.com/voice/test-abc123.mp4")
+ expect(completed["duration_ms"]).to eq(65_000)
+ end
+
+ it "paginates past the page size" do
+ stub_const(Voice::AdminRecordingsController, "PAGE_SIZE", 1) do
+ sign_in(admin)
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: "EG_2",
+ filepath: "voice/test-def456",
+ started_at: 5.minutes.ago,
+ )
+
+ get "/admin/plugins/voice/recordings.json"
+ expect(response.parsed_body["has_more"]).to eq(true)
+ expect(response.parsed_body["recordings"].size).to eq(1)
+
+ get "/admin/plugins/voice/recordings.json?offset=1"
+ expect(response.parsed_body["has_more"]).to eq(false)
+ expect(response.parsed_body["recordings"].map { |row| row["egress_id"] }).to eq(["EG_1"])
+ end
+ end
+
+ it "is not available to regular users" do
+ sign_in(user)
+
+ get "/admin/plugins/voice/recordings.json"
+
+ expect(response.status).to eq(404)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/admin_rooms_controller_spec.rb b/plugins/voice/spec/requests/voice/admin_rooms_controller_spec.rb
new file mode 100644
index 00000000000..71dd12189be
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/admin_rooms_controller_spec.rb
@@ -0,0 +1,400 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms"
+
+RSpec.describe Voice::AdminRoomsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :livekit_enabled)
+ AddLivekitEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, creator: admin, public: true, name: "Test Room") }
+ fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe "#index" do
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ get "/admin/plugins/voice/rooms.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns rooms for admin users" do
+ sign_in(admin)
+ get "/admin/plugins/voice/rooms.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["rooms"]).to be_an(Array)
+ expect(response.parsed_body["rooms"].first["name"]).to eq("Test Room")
+ end
+ end
+
+ describe "#show" do
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ get "/admin/plugins/voice/rooms/#{room.id}.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns room details for admin users" do
+ sign_in(admin)
+ get "/admin/plugins/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["id"]).to eq(room.id)
+ expect(response.parsed_body["room"]["name"]).to eq("Test Room")
+ expect(response.parsed_body["room"]["creator"]).to be_present
+ end
+
+ it "includes the chat settings so the edit form can prefill them" do
+ room.update!(chat_channel_id: channel.id, chat_idle_minutes: 2)
+ sign_in(admin)
+
+ get "/admin/plugins/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["chat_channel_id"]).to eq(channel.id)
+ expect(response.parsed_body["room"]["chat_idle_minutes"]).to eq(2)
+ end
+
+ it "returns 404 for non-existent room" do
+ sign_in(admin)
+ get "/admin/plugins/voice/rooms/99999.json"
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#create" do
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ post "/admin/plugins/voice/rooms.json", params: { room: { name: "New Room" } }
+ expect(response.status).to eq(404)
+ end
+
+ it "creates a room for admin users" do
+ sign_in(admin)
+
+ expect {
+ post "/admin/plugins/voice/rooms.json",
+ params: {
+ room: {
+ name: "New Room",
+ description: "A test room",
+ public: true,
+ max_participants: 10,
+ },
+ }
+ }.to change { Voice::Room.count }.by(1)
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body["room"]["name"]).to eq("New Room")
+ expect(response.parsed_body["room"]["description"]).to eq("A test room")
+ expect(response.parsed_body["room"]["public"]).to be(true)
+ expect(response.parsed_body["room"]["max_participants"]).to eq(10)
+ end
+
+ it "creates a stage room when room_type is stage" do
+ sign_in(admin)
+
+ post "/admin/plugins/voice/rooms.json",
+ params: {
+ room: {
+ name: "Town Hall",
+ room_type: "stage",
+ },
+ }
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body["room"]["room_type"]).to eq("stage")
+ expect(Voice::Room.find_by(name: "Town Hall").stage?).to eq(true)
+ end
+
+ it "rejects an unknown room_type" do
+ sign_in(admin)
+
+ expect {
+ post "/admin/plugins/voice/rooms.json",
+ params: {
+ room: {
+ name: "Town Hall",
+ room_type: "arena",
+ },
+ }
+ }.not_to change { Voice::Room.count }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns errors for invalid data" do
+ sign_in(admin)
+
+ post "/admin/plugins/voice/rooms.json", params: { room: { name: "" } }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to be_present
+ end
+
+ it "validates max_participants range" do
+ sign_in(admin)
+
+ post "/admin/plugins/voice/rooms.json",
+ params: {
+ room: {
+ name: "New Room",
+ max_participants: 100,
+ },
+ }
+
+ expect(response.status).to eq(422)
+ end
+ end
+
+ describe "#update" do
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { name: "Updated" } }
+ expect(response.status).to eq(404)
+ end
+
+ it "updates a room for admin users" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json",
+ params: {
+ room: {
+ name: "Updated Room",
+ description: "Updated description",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["name"]).to eq("Updated Room")
+ expect(response.parsed_body["room"]["description"]).to eq("Updated description")
+
+ room.reload
+ expect(room.name).to eq("Updated Room")
+ end
+
+ it "accepts a slug change" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { slug: "New Hangout" } }
+
+ expect(response.status).to eq(200)
+ expect(room.reload.slug).to eq("new-hangout")
+ end
+
+ it "persists and serializes room_type so the edit form can prefill it" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { room_type: "stage" } }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["room_type"]).to eq("stage")
+ expect(room.reload.stage?).to eq(true)
+
+ get "/admin/plugins/voice/rooms/#{room.id}.json"
+
+ expect(response.parsed_body["room"]["room_type"]).to eq("stage")
+ end
+
+ it "keeps a stage room's type when an update rejects an unknown room_type" do
+ sign_in(admin)
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { room_type: "arena" } }
+
+ expect(response.status).to eq(400)
+ expect(room.reload.stage?).to eq(true)
+ end
+
+ it "persists and serializes livekit_enabled" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { livekit_enabled: true } }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["livekit_enabled"]).to eq(true)
+ expect(room.reload.livekit_enabled).to eq(true)
+ end
+
+ it "persists the chat settings fields" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json",
+ params: {
+ room: {
+ chat_channel_id: channel.id,
+ chat_idle_minutes: 2,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["chat_channel_id"]).to eq(channel.id)
+ expect(response.parsed_body["room"]["chat_idle_minutes"]).to eq(2)
+
+ room.reload
+ expect(room.chat_channel_id).to eq(channel.id)
+ expect(room.chat_idle_minutes).to eq(2)
+ end
+
+ it "returns 404 for non-existent room" do
+ sign_in(admin)
+ put "/admin/plugins/voice/rooms/99999.json", params: { room: { name: "Updated" } }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns errors for invalid data" do
+ sign_in(admin)
+
+ put "/admin/plugins/voice/rooms/#{room.id}.json", params: { room: { name: "" } }
+
+ expect(response.status).to eq(422)
+ end
+ end
+
+ describe "#destroy" do
+ it "returns 403 for non-staff users" do
+ sign_in(user)
+ delete "/admin/plugins/voice/rooms/#{room.id}.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "deletes a room for admin users" do
+ sign_in(admin)
+
+ expect { delete "/admin/plugins/voice/rooms/#{room.id}.json" }.to change {
+ Voice::Room.count
+ }.by(-1)
+
+ expect(response.status).to eq(204)
+ end
+
+ it "deletes a room that has session history and keeps the sessions" do
+ session = Fabricate(:voice_session, user: user, room: room)
+ sign_in(admin)
+
+ expect { delete "/admin/plugins/voice/rooms/#{room.id}.json" }.to change {
+ Voice::Room.count
+ }.by(-1)
+
+ expect(response.status).to eq(204)
+ expect(session.reload.room_id).to eq(room.id)
+ end
+
+ it "returns 404 for non-existent room" do
+ sign_in(admin)
+ delete "/admin/plugins/voice/rooms/99999.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "deletes a livekit-pinned room from the SFU and clears the pin" do
+ sign_in(admin)
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ stub = stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom")
+
+ delete "/admin/plugins/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(204)
+ expect(stub).to have_been_requested
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+ end
+
+ describe "#end_call" do
+ fab!(:participant, :user)
+ fab!(:other_participant, :user)
+
+ before do
+ Voice::ParticipantTracker.add(room.id, participant.id)
+ Voice::ParticipantTracker.add(room.id, other_participant.id)
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ it "returns 404 for non-staff users" do
+ sign_in(user)
+ post "/admin/plugins/voice/rooms/#{room.id}/end_call.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for non-existent room" do
+ sign_in(admin)
+ post "/admin/plugins/voice/rooms/99999/end_call.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "kicks every participant and clears the transport pin" do
+ sign_in(admin)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/admin/plugins/voice/rooms/#{room.id}/end_call.json"
+ end
+
+ expect(response.status).to eq(204)
+ kicks = messages.select { |message| message.data[:type] == "kicked" }
+ expect(kicks.map(&:user_ids)).to contain_exactly([participant.id], [other_participant.id])
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "also deletes the SFU room when the call is pinned to livekit" do
+ sign_in(admin)
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ stub =
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom",
+ ).with(body: { room: Voice::Livekit.room_name(room) }.to_json)
+
+ post "/admin/plugins/voice/rooms/#{room.id}/end_call.json"
+
+ expect(response.status).to eq(204)
+ expect(stub).to have_been_requested
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "still ends the call when LiveKit is down" do
+ sign_in(admin)
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom",
+ ).to_timeout
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/admin/plugins/voice/rooms/#{room.id}/end_call.json"
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.count { |message| message.data[:type] == "kicked" }).to eq(2)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/admin_stats_controller_spec.rb b/plugins/voice/spec/requests/voice/admin_stats_controller_spec.rb
new file mode 100644
index 00000000000..a34422e9b91
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/admin_stats_controller_spec.rb
@@ -0,0 +1,222 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::AdminStatsController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, creator: admin, name: "Watercooler") }
+ fab!(:room_2, :voice_room) { Fabricate(:voice_room, creator: admin, name: "Lounge") }
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe "#overview" do
+ it "rejects non-admin users" do
+ sign_in(user)
+ get "/admin/plugins/voice/stats/overview.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns zeroes when there are no sessions" do
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/overview.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ body = response.parsed_body
+ expect(body["total_sessions"]).to eq(0)
+ expect(body["unique_users"]).to eq(0)
+ expect(body["avg_duration"]).to eq(0)
+ end
+
+ it "returns aggregated stats for sessions in the period" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 2.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ Fabricate(:voice_session, user: user, room: room, joined_at: 3.hours.ago, left_at: 1.hour.ago)
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/overview.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ body = response.parsed_body
+ expect(body["total_sessions"]).to eq(2)
+ expect(body["unique_users"]).to eq(2)
+ expect(body["avg_duration"]).to be > 0
+ end
+
+ it "excludes sessions outside the period" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 10.days.ago,
+ left_at: 10.days.ago + 1.hour,
+ )
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/overview.json", params: { period: "weekly" }
+
+ expect(response.parsed_body["total_sessions"]).to eq(0)
+ end
+
+ it "defaults to 7 days for invalid period" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 2.days.ago,
+ left_at: 2.days.ago + 30.minutes,
+ )
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/overview.json", params: { period: "bogus" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["total_sessions"]).to eq(1)
+ end
+
+ it "supports custom date ranges" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 20.days.ago,
+ left_at: 20.days.ago + 1.hour,
+ )
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: room,
+ joined_at: 2.days.ago,
+ left_at: 2.days.ago + 30.minutes,
+ )
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/overview.json",
+ params: {
+ period: "custom",
+ start_date: 25.days.ago.to_date.to_s,
+ end_date: 15.days.ago.to_date.to_s,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["total_sessions"]).to eq(1)
+ expect(response.parsed_body["unique_users"]).to eq(1)
+ end
+ end
+
+ describe "#rooms" do
+ it "rejects non-admin users" do
+ sign_in(user)
+ get "/admin/plugins/voice/stats/rooms.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns rooms ranked by total time" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 3.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: room_2,
+ joined_at: 2.hours.ago,
+ left_at: 1.5.hours.ago,
+ )
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/rooms.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ rooms = response.parsed_body["rooms"]
+ expect(rooms.length).to eq(2)
+ expect(rooms.first["room_name"]).to eq("Watercooler")
+ expect(rooms.first["unique_users"]).to eq(1)
+ expect(rooms.first["total_seconds"]).to be > 0
+ end
+
+ it "keeps sessions of deleted rooms in the ranking with a null name" do
+ doomed_room = Fabricate(:voice_room, creator: admin, name: "Doomed")
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: doomed_room,
+ joined_at: 2.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ doomed_room.destroy!
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/rooms.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ deleted_row = response.parsed_body["rooms"].find { |r| r["room_id"] == doomed_room.id }
+ expect(deleted_row).to be_present
+ expect(deleted_row["room_name"]).to be_nil
+ expect(deleted_row["unique_users"]).to eq(1)
+ end
+ end
+
+ describe "#users" do
+ it "rejects non-admin users" do
+ sign_in(user)
+ get "/admin/plugins/voice/stats/users.json"
+ expect(response.status).to eq(404)
+ end
+
+ it "returns users ranked by total time" do
+ Fabricate(
+ :voice_session,
+ user: admin,
+ room: room,
+ joined_at: 4.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: room,
+ joined_at: 2.hours.ago,
+ left_at: 1.5.hours.ago,
+ )
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/users.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ users = response.parsed_body["users"]
+ expect(users.length).to eq(2)
+ expect(users.first["username"]).to eq(admin.username)
+ expect(users.first["session_count"]).to eq(1)
+ expect(users.first["total_seconds"]).to be > 0
+ expect(users.first["avatar_template"]).to be_present
+ end
+
+ it "keeps sessions of deleted users in the ranking with a null username" do
+ doomed_user = Fabricate(:user)
+ Fabricate(
+ :voice_session,
+ user: doomed_user,
+ room: room,
+ joined_at: 2.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ UserDestroyer.new(admin).destroy(doomed_user)
+
+ sign_in(admin)
+ get "/admin/plugins/voice/stats/users.json", params: { period: "weekly" }
+
+ expect(response.status).to eq(200)
+ deleted_row = response.parsed_body["users"].find { |u| u["user_id"] == doomed_user.id }
+ expect(deleted_row).to be_present
+ expect(deleted_row["username"]).to be_nil
+ expect(deleted_row["session_count"]).to eq(1)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/calls_controller_spec.rb b/plugins/voice/spec/requests/voice/calls_controller_spec.rb
new file mode 100644
index 00000000000..764dc8ceae1
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/calls_controller_spec.rb
@@ -0,0 +1,265 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::CallsController do
+ fab!(:caller) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:callee) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ end
+
+ describe "#create" do
+ it "creates an ephemeral room with both parties as moderators and rings the callee" do
+ sign_in(caller)
+
+ messages =
+ MessageBus.track_publish { post "/voice/calls.json", params: { username: callee.username } }
+ alert_messages = messages.select { |m| m.channel == "/notification-alert/#{callee.id}" }
+ ring_messages = messages.select { |m| m.channel == "/voice/call-ring/#{callee.id}" }
+
+ expect(response.status).to eq(200)
+
+ room = Voice::Room.find(response.parsed_body["room"]["id"])
+ expect(room.ephemeral).to eq(true)
+ expect(room.public).to eq(false)
+ expect(room.name).to eq(
+ I18n.t("voice.call.room_name", caller: caller.username, callee: callee.username),
+ )
+ expect(room.moderator_ids).to contain_exactly(caller.id, callee.id)
+
+ ringing = response.parsed_body["room"]["ringing"]
+ expect(ringing.map { |entry| entry["user"]["id"] }).to contain_exactly(callee.id)
+ expect(ringing.first["notified_at"]).to be_within(5).of(Time.current.to_i)
+
+ invite = Voice::Invite.find_by(room_id: room.id, user_id: callee.id)
+ expect(invite.invited_by_id).to eq(caller.id)
+
+ notification = callee.notifications.order(:id).last
+ expect(notification.notification_type).to eq(Notification.types[:voice_invitation])
+ data = JSON.parse(notification.data)
+ expect(data["call"]).to eq(true)
+ expect(data["room_slug"]).to eq(room.slug)
+ expect(data["display_username"]).to eq(caller.username)
+
+ expect(alert_messages.size).to eq(1)
+ expect(alert_messages.first.data[:translated_title]).to eq(
+ I18n.t("voice.call_notification.title", username: caller.username),
+ )
+
+ expect(ring_messages.size).to eq(1)
+ ring = ring_messages.first
+ expect(ring.user_ids).to contain_exactly(callee.id)
+ expect(ring.data[:room_id]).to eq(room.id)
+ expect(ring.data[:room_slug]).to eq(room.slug)
+ expect(ring.data[:caller_username]).to eq(caller.username)
+ expect(ring.data[:ring_seconds]).to eq(Voice::RoomInviter::RING_SECONDS)
+ expect(ring.data[:sent_at]).to be_within(5).of(Time.current.to_i)
+
+ ringing_event =
+ messages.find do |message|
+ message.channel == "/voice/rooms/#{room.id}" && message.data[:type] == "ringing"
+ end
+ expect(ringing_event).to be_present
+ expect(ringing_event.data[:user][:id]).to eq(callee.id)
+ expect(ringing_event.data[:notified_at]).to eq(ring.data[:sent_at])
+ end
+
+ it "gives the callee a peer's powers: joining and pulling others into the call" do
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ room = Voice::Room.find(response.parsed_body["room"]["id"])
+ expect(callee.guardian.can_join_voice_room?(room)).to eq(true)
+ expect(callee.guardian.can_invite_to_voice_room?(room)).to eq(true)
+ end
+
+ it "returns 404 for an unknown username" do
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: "no-such-user" }
+
+ expect(response.status).to eq(404)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "rejects calling yourself" do
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: caller.username }
+
+ expect(response.status).to eq(400)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "rejects a callee outside the allowed groups" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ outsider = Fabricate(:user, trust_level: TrustLevel[0])
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: outsider.username }
+
+ expect(response.status).to eq(400)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ context "when the callee's preferences screen out the caller" do
+ before { sign_in(caller) }
+
+ it "returns 403 when the callee has muted the caller" do
+ MutedUser.create!(user_id: callee.id, muted_user_id: caller.id)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.cannot_call_user"))
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ expect(callee.notifications.count).to eq(0)
+ end
+
+ it "returns 403 when the callee has ignored the caller" do
+ IgnoredUser.create!(
+ user_id: callee.id,
+ ignored_user_id: caller.id,
+ expiring_at: 1.day.from_now,
+ )
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "returns 403 when the callee does not accept personal messages" do
+ callee.user_option.update!(allow_private_messages: false)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "returns 403 when the callee only accepts personal messages from a list that omits the caller" do
+ callee.user_option.update!(enable_allowed_pm_users: true)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "connects the call when the caller is on the callee's allowed list" do
+ callee.user_option.update!(enable_allowed_pm_users: true)
+ AllowedPmUser.create!(user: callee, allowed_pm_user: caller)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(200)
+ expect(Voice::Room.ephemeral.count).to eq(1)
+ end
+ end
+
+ it "leaves a missed-call notification instead of ringing a callee in do not disturb" do
+ callee.do_not_disturb_timings.create!(starts_at: Time.zone.now, ends_at: 1.hour.from_now)
+ sign_in(caller)
+
+ messages =
+ MessageBus.track_publish { post "/voice/calls.json", params: { username: callee.username } }
+
+ expect(response.status).to eq(200)
+ expect(messages.map(&:channel)).not_to include("/voice/call-ring/#{callee.id}")
+
+ # The caller still sees a normal outgoing ring so do-not-disturb status
+ # is not revealed; the call simply goes unanswered.
+ ringing = response.parsed_body["room"]["ringing"]
+ expect(ringing.map { |entry| entry["user"]["id"] }).to contain_exactly(callee.id)
+
+ notification = callee.notifications.order(:id).last
+ expect(notification.notification_type).to eq(Notification.types[:voice_invitation])
+ end
+
+ it "lets staff call a user whose preferences would screen out other callers" do
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:staff]
+ admin = Fabricate(:admin)
+ MutedUser.create!(user_id: callee.id, muted_user_id: admin.id)
+ callee.user_option.update!(allow_private_messages: false)
+ sign_in(admin)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(200)
+ expect(callee.notifications.count).to eq(1)
+ end
+
+ it "returns 403 when the caller is outside the direct-call groups (the default)" do
+ SiteSetting.voice_direct_calls_allowed_groups = ""
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "returns 403 when the caller lacks voice-room access" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ outsider = Fabricate(:user, trust_level: TrustLevel[0])
+ sign_in(outsider)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+
+ it "requires a logged-in user" do
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ end
+
+ context "with rate limits enabled" do
+ before do
+ RateLimiter.enable
+ sign_in(caller)
+ end
+
+ it "creates no ephemeral room once the daily invite budget is exhausted" do
+ SiteSetting.voice_max_invites_per_day = 1
+ RateLimiter.new(caller, "voice-invites-daily", 1, 1.day).performed!
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(429)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ expect(callee.notifications.count).to eq(0)
+ end
+
+ it "destroys the room instead of orphaning it when the ring fails" do
+ allow(Voice::RoomInviter).to receive(:invite!).and_raise(
+ RateLimiter::LimitExceeded.new(10, "voice-invites-daily"),
+ )
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(429)
+ expect(Voice::Room.ephemeral.count).to eq(0)
+ end
+ end
+
+ it "rejects the call when the caller has too many live ephemeral rooms" do
+ stub_const(Voice::EphemeralRoomManager, :MAX_LIVE_ROOMS_PER_CREATOR, 1) do
+ Voice::EphemeralRoomManager.create!(creator: caller, name: "Ongoing call")
+ sign_in(caller)
+
+ post "/voice/calls.json", params: { username: callee.username }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.ephemeral.count).to eq(1)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/chat_threads_controller_spec.rb b/plugins/voice/spec/requests/voice/chat_threads_controller_spec.rb
new file mode 100644
index 00000000000..0dcafe6c6cc
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/chat_threads_controller_spec.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+
+RSpec.describe Voice::ChatThreadsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
+
+ fab!(:room) { Fabricate(:voice_room, public: true, chat_channel_id: channel.id) }
+
+ fab!(:thread) { Fabricate(:chat_thread, channel: channel) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_chat_enabled = true
+ SiteSetting.chat_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.chat_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ # Keep the signed-in user a plain member — not a global room manager — so
+ # room visibility is decided by membership, not the create-room privilege.
+ SiteSetting.voice_create_room_allowed_groups = Group::AUTO_GROUPS[:trust_level_4].to_s
+ end
+
+ def mark(chat_thread, voice_room)
+ chat_thread.upsert_custom_fields(Voice::THREAD_ROOM_ID_FIELD => voice_room.id)
+ chat_thread
+ end
+
+ describe "#show" do
+ it "requires authentication" do
+ mark(thread, room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ context "when signed in" do
+ before { sign_in(user) }
+
+ it "returns the room behind a marked, visible session thread" do
+ mark(thread, room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to eq(
+ "id" => room.id,
+ "slug" => room.slug,
+ "name" => room.name,
+ "chat_active" => false,
+ )
+ end
+
+ it "reports a thread that is still the room's live session as active" do
+ mark(thread, room)
+ Fabricate(:chat_message, chat_channel: channel, thread: thread)
+ Discourse.redis.set("voice:room:#{room.id}:chat_thread", thread.id)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["chat_active"]).to eq(true)
+ ensure
+ Voice::ChatSession.clear(room.id)
+ end
+
+ it "reports a thread whose session rolled over to a newer thread as inactive" do
+ mark(thread, room)
+ newer_thread = Fabricate(:chat_thread, channel: channel)
+ Fabricate(:chat_message, chat_channel: channel, thread: newer_thread)
+ Discourse.redis.set("voice:room:#{room.id}:chat_thread", newer_thread.id)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["chat_active"]).to eq(false)
+ ensure
+ Voice::ChatSession.clear(room.id)
+ end
+
+ it "returns 404 for a thread that was never marked as a session thread" do
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for a thread id that does not exist" do
+ get "/voice/chat_threads/#{Chat::Thread.maximum(:id).to_i + 1}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the marker points at a room linked to a different channel" do
+ other_channel = Fabricate(:chat_channel, threading_enabled: true)
+ other_room = Fabricate(:voice_room, public: true, chat_channel_id: other_channel.id)
+ mark(thread, other_room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for a marked thread whose room the user cannot see" do
+ private_room = Fabricate(:voice_room, public: false, chat_channel_id: channel.id)
+ mark(thread, private_room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the channel no longer has threading enabled" do
+ mark(thread, room)
+ channel.update!(threading_enabled: false)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the thread's starter message was deleted" do
+ mark(thread, room)
+ thread.original_message.trash!
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "still resolves a deleted-starter thread for someone who can moderate the channel" do
+ mark(thread, room)
+ thread.original_message.trash!
+ sign_in(Fabricate(:admin))
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns 404 when the user cannot preview the thread's channel" do
+ private_channel = Fabricate(:private_category_channel, threading_enabled: true)
+ private_thread = Fabricate(:chat_thread, channel: private_channel)
+ visible_room = Fabricate(:voice_room, public: true, chat_channel_id: private_channel.id)
+ mark(private_thread, visible_room)
+
+ get "/voice/chat_threads/#{private_thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when voice chat is disabled" do
+ SiteSetting.voice_chat_enabled = false
+ mark(thread, room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when chat is disabled site-wide" do
+ SiteSetting.chat_enabled = false
+ mark(thread, room)
+
+ get "/voice/chat_threads/#{thread.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/invites_controller_spec.rb b/plugins/voice/spec/requests/voice/invites_controller_spec.rb
new file mode 100644
index 00000000000..1d275fb6ee5
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/invites_controller_spec.rb
@@ -0,0 +1,385 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305165400_create_voice_sessions"
+require_relative "../../../db/migrate/20260813160047_create_voice_invites"
+
+RSpec.describe Voice::InvitesController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.table_exists?(:voice_sessions)
+ CreateVoiceSessions.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_invites)
+ CreateVoiceInvites.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:invitee) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_owner) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, creator: room_owner, public: true) }
+ fab!(:private_room) { Fabricate(:voice_room, creator: room_owner, public: false) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_analytics_enabled = true
+ end
+
+ describe "#create" do
+ it "records the invite and notifies the invitee, including a live alert with the invite URL" do
+ sign_in(user)
+
+ messages =
+ MessageBus.track_publish("/notification-alert/#{invitee.id}") do
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["invited_usernames"]).to eq([invitee.username])
+
+ invite = Voice::Invite.find_by(room_id: room.id, user_id: invitee.id)
+ expect(invite.invited_by_id).to eq(user.id)
+ expect(invite.source).to eq(Voice::Invite::SOURCES[:notification])
+ expect(invite.redeemed_at).to be_nil
+
+ notification = invitee.notifications.order(:id).last
+ expect(notification.notification_type).to eq(Notification.types[:voice_invitation])
+ expect(notification.high_priority).to eq(true)
+ data = JSON.parse(notification.data)
+ expect(data["room_slug"]).to eq(room.slug)
+ expect(data["room_name"]).to eq(room.name)
+ expect(data["display_username"]).to eq(user.username)
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:post_url]).to eq(
+ "/voice/r/#{room.slug}/invited-by/#{user.username_lower}",
+ )
+ end
+
+ it "does not duplicate the invite or re-notify when the same user is invited again" do
+ sign_in(user)
+
+ 2.times do
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+ end
+
+ expect(Voice::Invite.where(room_id: room.id, user_id: invitee.id).count).to eq(1)
+ expect(
+ invitee.notifications.where(notification_type: Notification.types[:voice_invitation]).count,
+ ).to eq(1)
+ end
+
+ it "notifies again once an unredeemed invite is more than a day old" do
+ invite = Voice::Invite.create!(room_id: room.id, user_id: invitee.id, invited_by_id: user.id)
+ invite.update_columns(updated_at: 2.days.ago)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(
+ invitee.notifications.where(notification_type: Notification.types[:voice_invitation]).count,
+ ).to eq(1)
+ expect(invite.reload.updated_at).to be_within(1.minute).of(Time.current)
+ end
+
+ it "does not notify a redeemed invite again" do
+ Voice::Invite.create!(
+ room_id: room.id,
+ user_id: invitee.id,
+ invited_by_id: user.id,
+ redeemed_at: 2.days.ago,
+ updated_at: 2.days.ago,
+ )
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(invitee.notifications.count).to eq(0)
+ end
+
+ it "silently drops the notification when the invitee has muted the inviter" do
+ MutedUser.create!(user_id: invitee.id, muted_user_id: user.id)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ # Reported as invited so mute status can't be probed.
+ expect(response.parsed_body["invited_usernames"]).to eq([invitee.username])
+ expect(invitee.notifications.count).to eq(0)
+ end
+
+ it "silently drops the notification when the invitee does not accept personal messages" do
+ invitee.user_option.update!(allow_private_messages: false)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(response.parsed_body["invited_usernames"]).to eq([invitee.username])
+ expect(invitee.notifications.count).to eq(0)
+ end
+
+ it "rate limits invite notifications per day" do
+ RateLimiter.enable
+ SiteSetting.voice_max_invites_per_day = 1
+ other_invitee = Fabricate(:user, trust_level: TrustLevel[2])
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json",
+ params: {
+ usernames: [invitee.username, other_invitee.username],
+ }
+
+ expect(response.status).to eq(429)
+ expect(
+ Notification.where(notification_type: Notification.types[:voice_invitation]).count,
+ ).to eq(1)
+ end
+
+ it "skips the inviter themselves and users outside the allowed groups" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ outsider = Fabricate(:user, trust_level: TrustLevel[0])
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/invites.json",
+ params: {
+ usernames: [user.username, outsider.username],
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["invited_usernames"]).to be_empty
+ expect(response.parsed_body["skipped_usernames"]).to contain_exactly(
+ user.username,
+ outsider.username,
+ )
+ expect(Voice::Invite.count).to eq(0)
+ expect(outsider.notifications.count).to eq(0)
+ end
+
+ it "rejects a usernames list over the per-request maximum instead of truncating it" do
+ sign_in(user)
+
+ usernames = (1..Voice::InvitesController::MAX_USERS_PER_REQUEST + 1).map { |i| "user#{i}" }
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: usernames }
+
+ expect(response.status).to eq(400)
+ expect(Voice::Invite.count).to eq(0)
+ end
+
+ it "returns 403 when a non-manager invites to a private room" do
+ private_room.room_memberships.create!(
+ user: user,
+ role: Voice::RoomMembership::ROLE_PARTICIPANT,
+ )
+ sign_in(user)
+
+ post "/voice/rooms/#{private_room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Invite.count).to eq(0)
+ end
+
+ it "grants a private-room invitee a participant membership" do
+ sign_in(room_owner)
+
+ post "/voice/rooms/#{private_room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(response.status).to eq(200)
+ membership = private_room.room_memberships.find_by(user_id: invitee.id)
+ expect(membership.role).to eq(Voice::RoomMembership::ROLE_PARTICIPANT)
+ end
+
+ it "requires a logged-in user" do
+ post "/voice/rooms/#{room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(response.status).to eq(403)
+ end
+
+ context "when the room is ephemeral" do
+ fab!(:call_room) do
+ Fabricate(:voice_room, creator: room_owner, public: false, ephemeral: true)
+ end
+
+ it "sends a call-flavored notification and publishes a ring event to the invitee" do
+ sign_in(room_owner)
+
+ ring_messages =
+ MessageBus.track_publish("/voice/call-ring/#{invitee.id}") do
+ post "/voice/rooms/#{call_room.id}/invites.json",
+ params: {
+ usernames: [invitee.username],
+ }
+ end
+
+ expect(response.status).to eq(200)
+
+ notification = invitee.notifications.order(:id).last
+ data = JSON.parse(notification.data)
+ expect(data["call"]).to eq(true)
+
+ expect(ring_messages.size).to eq(1)
+ expect(ring_messages.first.data[:room_id]).to eq(call_room.id)
+ expect(ring_messages.first.data[:caller_username]).to eq(room_owner.username)
+ end
+
+ it "rings again once the previous ring has run out, but not while it is still sounding" do
+ sign_in(room_owner)
+
+ 2.times do
+ post "/voice/rooms/#{call_room.id}/invites.json",
+ params: {
+ usernames: [invitee.username],
+ }
+ end
+ expect(invitee.notifications.count).to eq(1)
+
+ Voice::Invite.find_by(room_id: call_room.id, user_id: invitee.id).update_columns(
+ updated_at: 2.minutes.ago,
+ )
+ post "/voice/rooms/#{call_room.id}/invites.json", params: { usernames: [invitee.username] }
+
+ expect(invitee.notifications.count).to eq(2)
+ end
+ end
+ end
+
+ describe "#suggestions" do
+ fab!(:closest_companion) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:brief_companion) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ let(:base_time) { Time.zone.now.change(usec: 0) }
+
+ before do
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: room,
+ joined_at: base_time - 2.hours,
+ left_at: base_time - 1.hour,
+ )
+ Fabricate(
+ :voice_session,
+ user: closest_companion,
+ room: room,
+ joined_at: base_time - 2.hours,
+ left_at: base_time - 90.minutes,
+ )
+ Fabricate(
+ :voice_session,
+ user: brief_companion,
+ room: room,
+ joined_at: base_time - 70.minutes,
+ left_at: base_time - 1.hour,
+ )
+ end
+
+ it "returns companions from this room ordered by time spent together" do
+ # Time shared elsewhere must not leak into this room's suggestions.
+ other_room = Fabricate(:voice_room, creator: room_owner, public: true)
+ stranger = Fabricate(:user, trust_level: TrustLevel[2])
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: other_room,
+ joined_at: 2.hours.ago,
+ left_at: 1.hour.ago,
+ )
+ Fabricate(
+ :voice_session,
+ user: stranger,
+ room: other_room,
+ joined_at: 2.hours.ago,
+ left_at: 1.hour.ago,
+ )
+
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/invites/suggestions.json"
+
+ expect(response.status).to eq(200)
+ suggestions = response.parsed_body["suggestions"]
+ expect(suggestions.map { |suggestion| suggestion["username"] }).to eq(
+ [closest_companion.username, brief_companion.username],
+ )
+ expect(suggestions.first["total_seconds"]).to eq(30.minutes.to_i)
+ end
+
+ it "caps time from sessions the orphan sweep closed late and skips sub-five-minute brushes" do
+ stale_companion = Fabricate(:user, trust_level: TrustLevel[2])
+ brush_companion = Fabricate(:user, trust_level: TrustLevel[2])
+ # A dev-instance style pair: both "open" for weeks before being closed.
+ Fabricate(
+ :voice_session,
+ user: user,
+ room: room,
+ joined_at: base_time - 28.days,
+ left_at: base_time - 1.day,
+ )
+ Fabricate(
+ :voice_session,
+ user: stale_companion,
+ room: room,
+ joined_at: base_time - 28.days,
+ left_at: base_time - 1.day,
+ )
+ Fabricate(
+ :voice_session,
+ user: brush_companion,
+ room: room,
+ joined_at: base_time - 62.minutes,
+ left_at: base_time - 1.hour,
+ )
+
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/invites/suggestions.json"
+
+ suggestions = response.parsed_body["suggestions"]
+ stale = suggestions.find { |suggestion| suggestion["username"] == stale_companion.username }
+ expect(stale["total_seconds"]).to eq(12.hours.to_i)
+ expect(suggestions.map { |suggestion| suggestion["username"] }).not_to include(
+ brush_companion.username,
+ )
+ end
+
+ it "excludes companions who no longer have access to voice rooms" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ closest_companion.change_trust_level!(TrustLevel[0])
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/invites/suggestions.json"
+
+ expect(response.parsed_body["suggestions"].map { |s| s["username"] }).to eq(
+ [brief_companion.username],
+ )
+ end
+
+ it "excludes companions who are already in the call" do
+ Voice::ParticipantTracker.add(room.id, closest_companion.id)
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/invites/suggestions.json"
+
+ expect(response.parsed_body["suggestions"].map { |s| s["username"] }).to eq(
+ [brief_companion.username],
+ )
+ ensure
+ Voice::ParticipantTracker.remove(room.id, closest_companion.id)
+ end
+
+ it "returns an empty list when analytics are disabled" do
+ SiteSetting.voice_analytics_enabled = false
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/invites/suggestions.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["suggestions"]).to eq([])
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/livekit_webhooks_controller_spec.rb b/plugins/voice/spec/requests/voice/livekit_webhooks_controller_spec.rb
new file mode 100644
index 00000000000..080c58ef431
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/livekit_webhooks_controller_spec.rb
@@ -0,0 +1,424 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260717172530_create_voice_recordings"
+
+RSpec.describe Voice::LivekitWebhooksController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :livekit_enabled)
+ AddLivekitEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_recordings)
+ CreateVoiceRecordings.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ Voice::Recording.reset_column_information
+ end
+
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ end
+
+ after do
+ Voice::ParticipantTracker.clear(room.id)
+ Discourse.redis.del(Voice::Livekit::LAST_WEBHOOK_KEY)
+ end
+
+ def signed_headers(body, secret: "lk_api_secret", key: "lk_api_key", sha256: nil, exp: nil)
+ token =
+ JWT.encode(
+ {
+ iss: key,
+ exp: (exp || 1.minute.from_now).to_i,
+ sha256: sha256 || Digest::SHA256.base64digest(body),
+ },
+ secret,
+ "HS256",
+ )
+ { "Authorization" => token, "CONTENT_TYPE" => "application/webhook+json" }
+ end
+
+ # `created_at` defaults to the future so presence added a moment earlier in
+ # the test always counts as seen before the event.
+ def event_for(
+ event: "participant_left",
+ room_name: Voice::Livekit.room_name(room),
+ identity: user.id.to_s,
+ sid: "PA_test",
+ created_at: 1.minute.from_now
+ )
+ {
+ "event" => event,
+ "id" => "EV_test",
+ "createdAt" => created_at.to_i.to_s,
+ "room" => {
+ "sid" => "RM_test",
+ "name" => room_name,
+ },
+ "participant" => {
+ "sid" => sid,
+ "identity" => identity,
+ },
+ }
+ end
+
+ def post_webhook(event = event_for, headers: nil)
+ body = event.to_json
+ post "/voice/livekit/webhook", params: body, headers: headers || signed_headers(body)
+ end
+
+ describe "#create" do
+ context "with an invalid delivery" do
+ it "rejects a request with no Authorization token and records no delivery" do
+ body = event_for.to_json
+
+ post "/voice/livekit/webhook",
+ params: body,
+ headers: {
+ "CONTENT_TYPE" => "application/webhook+json",
+ }
+
+ expect(response.status).to eq(403)
+ expect(Voice::Livekit.last_webhook_at).to be_nil
+ end
+
+ it "rejects a token signed with the wrong secret" do
+ body = event_for.to_json
+
+ post "/voice/livekit/webhook",
+ params: body,
+ headers: signed_headers(body, secret: "not-the-secret")
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects an expired token" do
+ body = event_for.to_json
+
+ post "/voice/livekit/webhook",
+ params: body,
+ headers: signed_headers(body, exp: 1.minute.ago)
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects a token issued for a different API key" do
+ body = event_for.to_json
+
+ post "/voice/livekit/webhook", params: body, headers: signed_headers(body, key: "other")
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects a body that does not match the signed hash" do
+ signed_body = event_for.to_json
+ tampered_body = event_for(identity: "999").to_json
+
+ post "/voice/livekit/webhook", params: tampered_body, headers: signed_headers(signed_body)
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "rejects everything when LiveKit is unconfigured" do
+ body = event_for.to_json
+ headers = signed_headers(body)
+ SiteSetting.voice_livekit_api_secret = ""
+
+ post "/voice/livekit/webhook", params: body, headers: headers
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ it "records the delivery time of every verified webhook, including unhandled events" do
+ post_webhook(event_for(event: "room_started"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::Livekit.last_webhook_at).to be_within(5.seconds).of(Time.now)
+ end
+
+ %w[participant_left participant_connection_aborted].each do |event_name|
+ context "with a #{event_name} event" do
+ it "expires the participant's presence, keeps their metadata, and broadcasts the change" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+ Voice::ParticipantTracker.update_metadata(room.id, user.id, { role: "participant" })
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_webhook(event_for(event: event_name))
+ end
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ expect(Voice::ParticipantTracker.get_metadata(room.id, user.id)[:role]).to eq(
+ "participant",
+ )
+ expect(messages.map { |message| message.data[:type] }).to include("participants")
+ end
+ end
+ end
+
+ context "with a participant_left event" do
+ it "leaves presence alone when it was refreshed after the event fired" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook(event_for(created_at: 2.minutes.ago))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "never creates presence for a participant who is not in the room" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+
+ post_webhook
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to be_empty
+ end
+
+ it "ignores rooms pinned to mesh" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "ignores rooms with no pinned transport" do
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "ignores events for rooms outside this site's namespace" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook(event_for(room_name: "othersite-r#{room.id}"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "ignores a non-numeric participant identity" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook(event_for(identity: "recorder-bot"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "leaves the session row open for CloseOrphanedSessions to close" do
+ sign_in(user)
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.status).to eq(200)
+ session = Voice::Session.find_by(user_id: user.id, room_id: room.id)
+
+ post_webhook
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ expect(session.reload.left_at).to be_nil
+
+ Jobs::Voice::CloseOrphanedSessions.new.execute({})
+
+ expect(session.reload.left_at).to be_present
+ end
+ end
+
+ context "with a rejoined participant" do
+ before do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+ end
+
+ it "ignores the superseded session's late departure" do
+ post_webhook(event_for(event: "participant_joined", sid: "PA_new"))
+ post_webhook(event_for(sid: "PA_old"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "expires presence when the departing session is the recorded one" do
+ post_webhook(event_for(event: "participant_joined", sid: "PA_new"))
+ post_webhook(event_for(sid: "PA_new"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ end
+
+ it "expires presence when no session was recorded for the user" do
+ post_webhook(event_for(sid: "PA_old"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ end
+ end
+
+ context "with a room_finished event" do
+ it "clears the transport pin of a livekit room without touching presence" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ post_webhook(event_for(event: "room_finished"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "keeps a mesh room's pin" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ post_webhook(event_for(event: "room_finished"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to eq("mesh")
+ end
+ end
+
+ context "with an egress_ended event" do
+ def egress_event(
+ egress_id: "EG_1",
+ room_name: Voice::Livekit.room_name(room),
+ snake_case: false
+ )
+ egress_info =
+ if snake_case
+ { "egress_id" => egress_id, "room_name" => room_name, "status" => "EGRESS_COMPLETE" }
+ else
+ { "egressId" => egress_id, "roomName" => room_name, "status" => "EGRESS_COMPLETE" }
+ end
+
+ event = {
+ "event" => "egress_ended",
+ "id" => "EV_egress",
+ "createdAt" => 1.minute.from_now.to_i.to_s,
+ }
+ event[snake_case ? "egress_info" : "egressInfo"] = egress_info
+ event
+ end
+
+ before do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.set_recording(
+ room.id,
+ egress_id: "EG_1",
+ user_id: user.id,
+ username: user.username,
+ started_at: Time.now.to_f,
+ )
+ end
+
+ it "clears the recording state and broadcasts the end" do
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) { post_webhook(egress_event) }
+
+ expect(response.status).to eq(200)
+ expect(Voice::RecordingManager.status(room.id)).to be_nil
+ recording_messages = messages.select { |message| message.data[:type] == "recording" }
+ expect(recording_messages.size).to eq(1)
+ expect(recording_messages.first.data[:recording]).to be_nil
+ end
+
+ it "handles a snake_case egress webhook" do
+ post_webhook(egress_event(snake_case: true))
+
+ expect(response.status).to eq(200)
+ expect(Voice::RecordingManager.status(room.id)).to be_nil
+ end
+
+ it "ignores an egress that is not the active recording" do
+ post_webhook(egress_event(egress_id: "EG_other"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::RecordingManager.status(room.id)).to be_present
+ end
+
+ it "ignores events for rooms outside this site's namespace" do
+ post_webhook(egress_event(room_name: "othersite-r#{room.id}"))
+
+ expect(response.status).to eq(200)
+ expect(Voice::RecordingManager.status(room.id)).to be_present
+ end
+
+ it "finalizes the recording row and PMs the requester the file location" do
+ recording =
+ Voice::Recording.create!(
+ room: room,
+ started_by: user,
+ egress_id: "EG_1",
+ filepath: "voice/test-abc123",
+ started_at: 10.minutes.ago,
+ )
+
+ event = egress_event
+ event["egressInfo"]["fileResults"] = [
+ {
+ "filename" => "voice/test-abc123.mp4",
+ "location" => "https://cdn.example.com/voice/test-abc123.mp4",
+ "duration" => (300 * 1_000_000_000).to_s,
+ "size" => "1000",
+ },
+ ]
+ post_webhook(event)
+
+ expect(response.status).to eq(200)
+ expect(recording.reload.status).to eq("completed")
+ expect(recording.location).to eq("https://cdn.example.com/voice/test-abc123.mp4")
+
+ pm_topic =
+ Topic.private_messages_for_user(user).find_by(
+ title: I18n.t("voice.recording_ready_pm.title", room_name: room.name),
+ )
+ expect(pm_topic.first_post.raw).to include(recording.location)
+ end
+ end
+
+ it "returns 404 when the plugin is disabled" do
+ SiteSetting.voice_enabled = false
+
+ post_webhook
+
+ expect(response.status).to eq(404)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/page_controller_spec.rb b/plugins/voice/spec/requests/voice/page_controller_spec.rb
new file mode 100644
index 00000000000..2e71ffee161
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/page_controller_spec.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::PageController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ Voice::Room.reset_column_information
+ end
+ end
+ end
+
+ fab!(:staff, :admin)
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, creator: staff, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ end
+
+ describe "#show" do
+ it "renders the app shell for a visible room" do
+ sign_in(user)
+
+ get "/voice/r/#{room.slug}"
+
+ expect(response.status).to eq(200)
+ expect(response.body).to include("discourse")
+ end
+
+ it "renders the app shell for an invite link carrying the inviter's username" do
+ sign_in(user)
+
+ get "/voice/r/#{room.slug}/invited-by/#{staff.username_lower}"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns 404 for an unknown slug" do
+ sign_in(user)
+
+ get "/voice/r/not-a-room"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "rejects users who cannot see the room" do
+ private_room = Fabricate(:voice_room, creator: staff, public: false)
+ sign_in(user)
+
+ get "/voice/r/#{private_room.slug}"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "renders for anonymous visitors when anonymous visitors are admitted" do
+ get "/voice/r/#{room.slug}"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "rejects anonymous visitors when access is restricted to a group" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+
+ get "/voice/r/#{room.slug}"
+
+ expect(response.status).to eq(403)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/room_memberships_controller_spec.rb b/plugins/voice/spec/requests/voice/room_memberships_controller_spec.rb
new file mode 100644
index 00000000000..a3df90bb7ea
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/room_memberships_controller_spec.rb
@@ -0,0 +1,374 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::RoomMembershipsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:staff, :admin)
+ fab!(:room_owner) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_moderator) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:member) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ # In voice_create_room_allowed_groups but with no tie to the room: being
+ # allowed to create rooms must not grant control over other people's rooms.
+ fab!(:outsider) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ fab!(:invitee) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, creator: room_owner, public: false) }
+
+ fab!(:moderator_membership) do
+ room.room_memberships.create!(user: room_moderator, role: Voice::RoomMembership::ROLE_MODERATOR)
+ end
+
+ fab!(:participant_membership) do
+ room.room_memberships.create!(user: member, role: Voice::RoomMembership::ROLE_PARTICIPANT)
+ end
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ end
+
+ describe "#index" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(outsider)
+
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for a plain participant member" do
+ sign_in(member)
+
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for anonymous visitors" do
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns the memberships to the room creator" do
+ sign_in(room_owner)
+
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(200)
+ user_ids = response.parsed_body["memberships"].map { |membership| membership["user_id"] }
+ expect(user_ids).to contain_exactly(room_owner.id, room_moderator.id, member.id)
+ end
+
+ it "returns the memberships to a room moderator" do
+ sign_in(room_moderator)
+
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns the memberships to site staff" do
+ sign_in(staff)
+
+ get "/voice/rooms/#{room.id}/memberships.json"
+
+ expect(response.status).to eq(200)
+ end
+ end
+
+ describe "#create" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(outsider)
+
+ expect {
+ post "/voice/rooms/#{room.id}/memberships.json", params: { user_id: outsider.id }
+ }.not_to change { room.room_memberships.count }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for a plain participant member" do
+ sign_in(member)
+
+ post "/voice/rooms/#{room.id}/memberships.json", params: { user_id: invitee.id }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "lets the creator add a member by user_id" do
+ sign_in(room_owner)
+
+ post "/voice/rooms/#{room.id}/memberships.json", params: { user_id: invitee.id }
+
+ expect(response.status).to eq(200)
+ expect(room.room_memberships.find_by(user_id: invitee.id)).to be_participant
+ end
+
+ it "lets the creator add a member by username with a role" do
+ sign_in(room_owner)
+
+ post "/voice/rooms/#{room.id}/memberships.json",
+ params: {
+ username: invitee.username,
+ role: "moderator",
+ }
+
+ expect(response.status).to eq(200)
+ expect(room.room_memberships.find_by(user_id: invitee.id)).to be_moderator
+ end
+
+ it "lets a room moderator add a member" do
+ sign_in(room_moderator)
+
+ post "/voice/rooms/#{room.id}/memberships.json", params: { user_id: invitee.id }
+
+ expect(response.status).to eq(200)
+ end
+
+ it "clears a present listener's raised hand when granting them the speaker role" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ Voice::ParticipantTracker.add(room.id, member.id)
+ Voice::ParticipantTracker.raise_hand(room.id, member.id)
+ sign_in(room_owner)
+
+ post "/voice/rooms/#{room.id}/memberships.json",
+ params: {
+ user_id: member.id,
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, member.id)
+ expect(metadata[:role]).to eq("speaker")
+ expect(metadata[:hand_raised_at]).to be_nil
+ end
+ end
+
+ describe "#update" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(outsider)
+
+ expect {
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "moderator",
+ }
+ }.not_to change { participant_membership.reload.role }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "lets the creator change a member's role" do
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ expect(participant_membership.reload).to be_speaker
+ end
+
+ it "updates the tracked role of a member present in the room" do
+ sign_in(room_owner)
+ Voice::ParticipantTracker.add(room.id, member.id)
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "moderator",
+ }
+
+ expect(response.status).to eq(200)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, member.id)
+ expect(metadata[:role]).to eq("moderator")
+ end
+
+ it "clears a present listener's raised hand when promoting them to speaker" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ Voice::ParticipantTracker.add(room.id, member.id)
+ Voice::ParticipantTracker.raise_hand(room.id, member.id)
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, member.id)
+ expect(metadata[:role]).to eq("speaker")
+ expect(metadata[:hand_raised_at]).to be_nil
+ end
+
+ it "keeps a queued listener's raised hand when their role is set to participant" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ Voice::ParticipantTracker.add(room.id, member.id)
+ Voice::ParticipantTracker.raise_hand(room.id, member.id)
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "participant",
+ }
+
+ expect(response.status).to eq(200)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, member.id)
+ expect(metadata[:role]).to eq("participant")
+ expect(metadata[:hand_raised_at]).to be_a(Float)
+ end
+ end
+
+ describe "#destroy" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(outsider)
+
+ expect {
+ delete "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json"
+ }.not_to change { room.room_memberships.count }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for a plain participant member removing another member" do
+ sign_in(member)
+
+ delete "/voice/rooms/#{room.id}/memberships/#{moderator_membership.id}.json"
+
+ expect(response.status).to eq(403)
+ expect(Voice::RoomMembership.exists?(moderator_membership.id)).to eq(true)
+ end
+
+ it "lets the creator remove a member" do
+ sign_in(room_owner)
+
+ delete "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json"
+
+ expect(response.status).to eq(204)
+ expect(Voice::RoomMembership.exists?(participant_membership.id)).to eq(false)
+ end
+
+ it "lets site staff remove a member" do
+ sign_in(staff)
+
+ delete "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json"
+
+ expect(response.status).to eq(204)
+ end
+ end
+
+ describe "livekit permission sync" do
+ before do
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, member.id)
+ sign_in(room_owner)
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def update_participant_stub
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant")
+ end
+
+ it "grants publishing on the SFU when a present stage listener is promoted" do
+ update_participant_stub
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant",
+ ).with do |req|
+ body = JSON.parse(req.body)
+ body["identity"] == member.id.to_s && body["permission"]["canPublish"] == true &&
+ body["permission"]["canSubscribe"] == true
+ end,
+ ).to have_been_made.once
+ end
+
+ it "revokes publishing on the SFU when a present speaker's membership is removed" do
+ participant_membership.update!(role: Voice::RoomMembership::ROLE_SPEAKER)
+ update_participant_stub
+
+ delete "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json"
+
+ expect(response.status).to eq(204)
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/UpdateParticipant",
+ ).with do |req|
+ body = JSON.parse(req.body)
+ body["identity"] == member.id.to_s && body["permission"]["canPublish"] == false
+ end,
+ ).to have_been_made.once
+ end
+
+ it "still succeeds when LiveKit is down" do
+ update_participant_stub.to_timeout
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ expect(participant_membership.reload).to be_speaker
+ end
+
+ it "makes zero HTTP calls for a mesh room" do
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+ stub = update_participant_stub
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ expect(stub).not_to have_been_requested
+ end
+
+ it "makes zero HTTP calls when the member is not in the call" do
+ Voice::ParticipantTracker.remove(room.id, member.id)
+ stub = update_participant_stub
+
+ put "/voice/rooms/#{room.id}/memberships/#{participant_membership.id}.json",
+ params: {
+ role: "speaker",
+ }
+
+ expect(response.status).to eq(200)
+ expect(stub).not_to have_been_requested
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/rooms_controller_flag_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_flag_spec.rb
new file mode 100644
index 00000000000..6eb2114fc22
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/rooms_controller_flag_spec.rb
@@ -0,0 +1,135 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Voice::RoomsController do
+ fab!(:flagger) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:flagged_user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ fab!(:session) { Fabricate(:voice_session, room: room, user: flagged_user, left_at: nil) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ Group.refresh_automatic_groups!
+ end
+
+ describe "#flag" do
+ let(:params) do
+ {
+ user_id: flagged_user.id,
+ flag_type_id: ReviewableScore.types[:notify_moderators],
+ message: "This participant is being disruptive on the call.",
+ }
+ end
+
+ it "requires the user to be logged in" do
+ post "/voice/rooms/#{room.id}/flag.json", params: params
+
+ expect(response.status).to eq(403)
+ end
+
+ it "creates a reviewable targeting the user's session and a companion PM to moderators" do
+ sign_in(flagger)
+
+ expect { post "/voice/rooms/#{room.id}/flag.json", params: params }.to change {
+ ReviewableVoiceUser.count
+ }.by(1).and change { Topic.private_messages.count }.by(1)
+
+ expect(response.status).to eq(200)
+
+ reviewable = ReviewableVoiceUser.last
+ expect(reviewable.target).to eq(session)
+ expect(reviewable.target_created_by).to eq(flagged_user)
+ expect(reviewable.created_by).to eq(flagger)
+ expect(reviewable.payload["message"]).to eq(params[:message])
+ expect(reviewable.payload["room_id"]).to eq(room.id)
+
+ pm = Topic.private_messages.last
+ expect(pm.subtype).to eq(TopicSubtype.notify_moderators)
+ expect(pm.first_post.raw).to include(params[:message])
+ expect(reviewable.reviewable_scores.first.meta_topic_id).to eq(pm.id)
+ end
+
+ it "rejects flag types other than notify_moderators" do
+ sign_in(flagger)
+
+ post "/voice/rooms/#{room.id}/flag.json",
+ params: params.merge(flag_type_id: ReviewableScore.types[:spam])
+
+ expect(response.status).to eq(400)
+ expect(ReviewableVoiceUser.count).to eq(0)
+ end
+
+ it "rejects a flag without a message" do
+ sign_in(flagger)
+
+ post "/voice/rooms/#{room.id}/flag.json", params: params.merge(message: "")
+
+ expect(response.status).to eq(400)
+ expect(ReviewableVoiceUser.count).to eq(0)
+ end
+
+ it "rejects flagging yourself" do
+ sign_in(flagger)
+
+ post "/voice/rooms/#{room.id}/flag.json", params: params.merge(user_id: flagger.id)
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects flagging a user who never joined the room" do
+ other_room = Fabricate(:voice_room, public: true)
+ sign_in(flagger)
+
+ post "/voice/rooms/#{other_room.id}/flag.json", params: params
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("voice.errors.flag_target_never_joined"),
+ )
+ end
+
+ it "rejects a second flag while the flagger already has a pending one" do
+ sign_in(flagger)
+
+ post "/voice/rooms/#{room.id}/flag.json", params: params
+ expect(response.status).to eq(200)
+
+ post "/voice/rooms/#{room.id}/flag.json", params: params
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.flag_already_handled"))
+ expect(ReviewableVoiceUser.count).to eq(1)
+ end
+
+ it "lets another user add a score to the existing reviewable" do
+ other_flagger = Fabricate(:user, trust_level: TrustLevel[2])
+ sign_in(flagger)
+ post "/voice/rooms/#{room.id}/flag.json", params: params
+
+ sign_in(other_flagger)
+ post "/voice/rooms/#{room.id}/flag.json", params: params
+
+ expect(response.status).to eq(200)
+ expect(ReviewableVoiceUser.count).to eq(1)
+ expect(ReviewableVoiceUser.last.reviewable_scores.map(&:user_id)).to contain_exactly(
+ flagger.id,
+ other_flagger.id,
+ )
+ end
+
+ it "rejects flagging in a private room the flagger cannot join" do
+ private_room = Fabricate(:voice_room, public: false)
+ Fabricate(:voice_session, room: private_room, user: flagged_user, left_at: nil)
+ sign_in(flagger)
+
+ post "/voice/rooms/#{private_room.id}/flag.json", params: params
+
+ expect(response.status).to eq(403)
+ expect(ReviewableVoiceUser.count).to eq(0)
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/rooms_controller_livekit_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_livekit_spec.rb
new file mode 100644
index 00000000000..88ab07801a9
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/rooms_controller_livekit_spec.rb
@@ -0,0 +1,564 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260709165411_add_livekit_enabled_to_voice_rooms"
+
+RSpec.describe Voice::RoomsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :livekit_enabled)
+ AddLivekitEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def configure_livekit!
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ end
+
+ describe "#join" do
+ before { sign_in(user) }
+
+ it "resolves to mesh with no livekit payload when unconfigured" do
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.keys).to contain_exactly(
+ "transport",
+ "participant_session_id",
+ "ice",
+ "room",
+ )
+ expect(response.parsed_body["transport"]).to eq("mesh")
+ end
+
+ it "resolves to livekit with a url and a decodable token when configured" do
+ configure_livekit!
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["transport"]).to eq("livekit")
+ expect(response.parsed_body["livekit"]["url"]).to eq("wss://livekit.example.com")
+
+ payload =
+ JWT.decode(
+ response.parsed_body["livekit"]["token"],
+ SiteSetting.voice_livekit_api_secret,
+ true,
+ algorithm: "HS256",
+ ).first
+ expect(payload["sub"]).to eq(user.id.to_s)
+ expect(payload["video"]["room"]).to eq(Voice::Livekit.room_name(room))
+ end
+
+ it "never leaks the api secret in the response" do
+ configure_livekit!
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.body).not_to include(SiteSetting.voice_livekit_api_secret)
+ end
+
+ it "holds the pinned transport across a config change" do
+ configure_livekit!
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+
+ SiteSetting.voice_livekit_room_policy = "disabled"
+
+ sign_in(other_user)
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.parsed_body["transport"]).to eq("livekit")
+ expect(response.parsed_body["livekit"]["token"]).to be_present
+ end
+
+ it "re-resolves the transport once the room has emptied" do
+ configure_livekit!
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+
+ SiteSetting.voice_livekit_room_policy = "disabled"
+ # The last leave also deletes the now-empty room from the SFU.
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom")
+ delete "/voice/rooms/#{room.id}/leave.json"
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.parsed_body["transport"]).to eq("mesh")
+ end
+
+ it "fails the join with a 503 when the token cannot be minted" do
+ configure_livekit!
+ Voice::Livekit.stubs(:mint_token).raises(Voice::Livekit::MintError.new("boom"))
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(503)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.livekit_unavailable"))
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to be_empty
+ end
+
+ it "falls back to mesh on mint failure only when opted in and the room is empty" do
+ configure_livekit!
+ SiteSetting.voice_livekit_mesh_fallback = true
+ Voice::Livekit.stubs(:mint_token).raises(Voice::Livekit::MintError.new("boom"))
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["transport"]).to eq("mesh")
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to eq("mesh")
+ end
+
+ it "never falls back on mint failure while the room is occupied on livekit" do
+ configure_livekit!
+ SiteSetting.voice_livekit_mesh_fallback = true
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ Voice::Livekit.stubs(:mint_token).raises(Voice::Livekit::MintError.new("boom"))
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(503)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to eq("livekit")
+ end
+
+ it "fails a livekit-pinned join when the config was half-deleted" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ SiteSetting.voice_livekit_api_secret = ""
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(503)
+ end
+ end
+
+ describe "#livekit_token" do
+ before { configure_livekit! }
+
+ it "requires login" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "reissues a token, re-adds lapsed presence, and mints a fresh participant session" do
+ sign_in(user)
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["url"]).to eq("wss://livekit.example.com")
+ expect(response.parsed_body["token"]).to be_present
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ expect(
+ Voice::ParticipantTracker.valid_participant_session?(
+ room.id,
+ user.id,
+ response.parsed_body["participant_session_id"],
+ ),
+ ).to eq(true)
+ end
+
+ it "re-establishes presence even for a user who recently left" do
+ sign_in(user)
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.mark_left(room.id, user.id)
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ expect(Voice::ParticipantTracker.recently_left?(room.id, user.id)).to eq(false)
+ end
+
+ it "returns 410 when the room instance ended or runs on mesh" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+ expect(response.status).to eq(410)
+
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+ expect(response.status).to eq(410)
+ end
+
+ it "returns 503 when the pinned room's token cannot be minted" do
+ sign_in(user)
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ SiteSetting.voice_livekit_api_secret = ""
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+
+ expect(response.status).to eq(503)
+ end
+
+ it "rate limits repeated mints" do
+ RateLimiter.enable
+ sign_in(user)
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+
+ 10.times do
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+ expect(response.status).to eq(200)
+ end
+
+ post "/voice/rooms/#{room.id}/livekit_token.json"
+ expect(response.status).to eq(429)
+ end
+ end
+
+ describe "#heartbeat" do
+ before { sign_in(user) }
+
+ it "refreshes the transport pin ttl" do
+ configure_livekit!
+ post "/voice/rooms/#{room.id}/join.json"
+ participant_session_id = response.parsed_body["participant_session_id"]
+
+ key = "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:transport"
+ Discourse.redis.expire(key, 1)
+
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ participant_session_id: participant_session_id,
+ }
+
+ expect(Discourse.redis.ttl(key)).to be > 1
+ end
+ end
+
+ describe "#kick" do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ it "evicts the kicked user's media session from a livekit-pinned room" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ stub =
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/RemoveParticipant",
+ ).with(body: { identity: other_user.id.to_s, room: Voice::Livekit.room_name(room) }.to_json)
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_user.id }
+
+ expect(response.status).to eq(204)
+ expect(stub).to have_been_requested
+ end
+
+ it "still succeeds when LiveKit is down" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/RemoveParticipant",
+ ).to_timeout
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_user.id }
+
+ expect(response.status).to eq(204)
+ end
+
+ it "makes zero HTTP calls for a mesh room" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ stub = stub_request(:post, %r{\Ahttps://livekit\.example\.com/twirp/})
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_user.id }
+
+ expect(response.status).to eq(204)
+ expect(stub).not_to have_been_requested
+ end
+ end
+
+ describe "#destroy" do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ it "deletes a livekit-pinned room from the SFU and clears the pin" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ stub =
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom",
+ ).with(body: { room: Voice::Livekit.room_name(room) }.to_json)
+
+ delete "/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(stub).to have_been_requested
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "makes zero HTTP calls for a mesh room" do
+ configure_livekit!
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+ stub = stub_request(:post, %r{\Ahttps://livekit\.example\.com/twirp/})
+
+ delete "/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(stub).not_to have_been_requested
+ end
+ end
+
+ describe "#leave" do
+ before do
+ configure_livekit!
+ sign_in(user)
+ end
+
+ it "deletes the SFU room when the last participant leaves" do
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+ stub =
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.RoomService/DeleteRoom",
+ ).with(body: { room: Voice::Livekit.room_name(room) }.to_json)
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+
+ expect(response.status).to eq(204)
+ expect(stub).to have_been_requested
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "keeps the SFU room while other participants remain" do
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ post "/voice/rooms/#{room.id}/join.json"
+ stub = stub_request(:post, %r{\Ahttps://livekit\.example\.com/twirp/})
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+
+ expect(response.status).to eq(204)
+ expect(stub).not_to have_been_requested
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to eq("livekit")
+ end
+ end
+
+ describe "#signal" do
+ before { sign_in(user) }
+
+ it "rejects signaling in a livekit-pinned room" do
+ configure_livekit!
+ post "/voice/rooms/#{room.id}/join.json"
+ participant_session_id = response.parsed_body["participant_session_id"]
+
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: other_user.id,
+ type: "offer",
+ sdp: "sdp",
+ },
+ participant_session_id: participant_session_id,
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.livekit_no_signaling"))
+ end
+
+ it "still relays signals in a mesh room" do
+ Voice::ParticipantTracker.add(room.id, other_user.id)
+ Voice::ParticipantTracker.create_participant_session!(room.id, other_user.id)
+ post "/voice/rooms/#{room.id}/join.json"
+ participant_session_id = response.parsed_body["participant_session_id"]
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: other_user.id,
+ type: "offer",
+ sdp: "sdp",
+ },
+ participant_session_id: participant_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.map(&:user_ids)).to eq([[other_user.id]])
+ end
+ end
+
+ describe "per-room policy" do
+ fab!(:managed_room) { Fabricate(:voice_room, creator: user, public: true) }
+
+ before do
+ configure_livekit!
+ SiteSetting.voice_livekit_room_policy = "per_room"
+ end
+
+ after { Voice::ParticipantTracker.clear(managed_room.id) }
+
+ describe "#join" do
+ before { sign_in(user) }
+
+ it "resolves the transport from the room's flag" do
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("mesh")
+
+ managed_room.update!(livekit_enabled: true)
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+ end
+
+ it "keeps a live livekit call on livekit when the flag is disabled mid-call" do
+ managed_room.update!(livekit_enabled: true)
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+
+ managed_room.update!(livekit_enabled: false)
+
+ sign_in(other_user)
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("livekit")
+ end
+
+ it "keeps a live mesh call on mesh when the flag is enabled mid-call" do
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("mesh")
+
+ managed_room.update!(livekit_enabled: true)
+
+ sign_in(other_user)
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("mesh")
+ expect(response.parsed_body["livekit"]).to be_nil
+ end
+ end
+
+ describe "#create" do
+ it "accepts livekit_enabled" do
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ sign_in(Fabricate(:user, trust_level: TrustLevel[2]))
+
+ post "/voice/rooms.json",
+ params: {
+ room: {
+ name: "Town hall",
+ public: true,
+ livekit_enabled: true,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(Voice::Room.find_by(name: "Town hall").livekit_enabled).to eq(true)
+ end
+ end
+
+ describe "#update" do
+ it "lets a room manager toggle the flag" do
+ sign_in(user)
+
+ put "/voice/rooms/#{managed_room.id}.json", params: { room: { livekit_enabled: true } }
+
+ expect(response.status).to eq(200)
+ expect(managed_room.reload.livekit_enabled).to eq(true)
+ expect(response.parsed_body["room"]["livekit_enabled"]).to eq(true)
+ end
+
+ it "accepts a stale form's flag but the resolver ignores it once the policy changed" do
+ SiteSetting.voice_livekit_room_policy = "disabled"
+ sign_in(user)
+
+ put "/voice/rooms/#{managed_room.id}.json", params: { room: { livekit_enabled: true } }
+
+ expect(response.status).to eq(200)
+ expect(managed_room.reload.livekit_enabled).to eq(true)
+
+ post "/voice/rooms/#{managed_room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("mesh")
+ end
+ end
+
+ describe "#show" do
+ it "serializes the flag to managers only" do
+ sign_in(user)
+ get "/voice/rooms/#{managed_room.id}.json"
+ expect(response.parsed_body["room"]).to have_key("livekit_enabled")
+
+ sign_in(other_user)
+ get "/voice/rooms/#{managed_room.id}.json"
+ expect(response.parsed_body["room"]).not_to have_key("livekit_enabled")
+ end
+ end
+ end
+
+ describe "expected_transport in the serialized room" do
+ before { sign_in(user) }
+
+ it "predicts mesh when livekit is unconfigured" do
+ get "/voice/rooms/#{room.id}.json"
+
+ expect(response.parsed_body["room"]["expected_transport"]).to eq("mesh")
+ end
+
+ it "predicts livekit when configured and allowed for the room" do
+ configure_livekit!
+
+ get "/voice/rooms/#{room.id}.json"
+
+ expect(response.parsed_body["room"]["expected_transport"]).to eq("livekit")
+ end
+
+ it "reports the pinned transport of a live call over the current resolution" do
+ post "/voice/rooms/#{room.id}/join.json"
+ expect(response.parsed_body["transport"]).to eq("mesh")
+
+ configure_livekit!
+
+ get "/voice/rooms/#{room.id}.json"
+
+ expect(response.parsed_body["room"]["expected_transport"]).to eq("mesh")
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/rooms_controller_recording_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_recording_spec.rb
new file mode 100644
index 00000000000..fd9a842440b
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/rooms_controller_recording_spec.rb
@@ -0,0 +1,178 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260717172530_create_voice_recordings"
+
+RSpec.describe Voice::RoomsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_recordings)
+ CreateVoiceRecordings.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ Voice::Recording.reset_column_information
+ end
+
+ fab!(:creator, :user)
+ fab!(:participant, :user)
+ fab!(:room) { Fabricate(:voice_room, public: true, creator: creator) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ SiteSetting.voice_livekit_recording_enabled = true
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def stub_start(egress_id: "EG_1")
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).to_return(body: { egressId: egress_id }.to_json)
+ end
+
+ def stub_stop
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/StopEgress").to_return(
+ body: "{}",
+ )
+ end
+
+ describe "#start_recording" do
+ it "starts a recording and returns its room-wide status to a room manager" do
+ sign_in(creator)
+ stub_start
+
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["recording"]["started_by"]["id"]).to eq(creator.id)
+ expect(Voice::RecordingManager.status(room.id)).to be_present
+ end
+
+ it "rejects a participant who cannot manage the room" do
+ sign_in(participant)
+ stub = stub_start
+
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(403)
+ expect(stub).not_to have_been_requested
+ end
+
+ it "rejects the request when recordings are disabled" do
+ sign_in(creator)
+ SiteSetting.voice_livekit_recording_enabled = false
+
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("voice.errors.recording_unavailable"),
+ )
+ end
+
+ it "rejects the request for a mesh call" do
+ sign_in(creator)
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 422 when the egress fails to start" do
+ sign_in(creator)
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).to_return(status: 500, body: "boom")
+
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(422)
+ expect(Voice::RecordingManager.status(room.id)).to be_nil
+ end
+ end
+
+ describe "#stop_recording" do
+ before do
+ sign_in(creator)
+ stub_start
+ post "/voice/rooms/#{room.id}/recording.json"
+ end
+
+ it "stops the recording for a room manager" do
+ stub_stop
+
+ delete "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(204)
+ expect(Voice::RecordingManager.status(room.id)).to be_nil
+ end
+
+ it "rejects a participant who cannot manage the room" do
+ sign_in(participant)
+ stub = stub_stop
+
+ delete "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(403)
+ expect(stub).not_to have_been_requested
+ expect(Voice::RecordingManager.status(room.id)).to be_present
+ end
+
+ it "returns 422 when nothing is being recorded" do
+ stub_stop
+ delete "/voice/rooms/#{room.id}/recording.json"
+
+ delete "/voice/rooms/#{room.id}/recording.json"
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.recording_not_active"))
+ end
+ end
+
+ describe "#show" do
+ it "serializes an active recording for any viewer" do
+ sign_in(creator)
+ stub_start
+ post "/voice/rooms/#{room.id}/recording.json"
+
+ sign_in(participant)
+ get "/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["recording"]["started_by"]["username"]).to eq(
+ creator.username,
+ )
+ end
+
+ it "omits the recording field when nothing is being recorded" do
+ sign_in(participant)
+
+ get "/voice/rooms/#{room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]).not_to have_key("recording")
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/rooms_controller_speak_requests_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_speak_requests_spec.rb
new file mode 100644
index 00000000000..60a4d857392
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/rooms_controller_speak_requests_spec.rb
@@ -0,0 +1,252 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+
+RSpec.describe Voice::RoomsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:staff, :admin)
+ fab!(:room_owner) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:listener) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:other_listener) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_speaker) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room_moderator) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, creator: room_owner, public: true) }
+
+ fab!(:speaker_membership) do
+ room.room_memberships.create!(user: room_speaker, role: Voice::RoomMembership::ROLE_SPEAKER)
+ end
+
+ fab!(:moderator_membership) do
+ room.room_memberships.create!(user: room_moderator, role: Voice::RoomMembership::ROLE_MODERATOR)
+ end
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ Voice::ParticipantTracker.add(room.id, listener.id)
+ @listener_session_id =
+ Voice::ParticipantTracker.create_participant_session!(room.id, listener.id)
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ describe "#request_to_speak" do
+ it "raises a present stage listener's hand and broadcasts the raise plus the roster" do
+ sign_in(listener)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, listener.id)
+ expect(metadata[:hand_raised_at]).to be_a(Float)
+
+ hand_message = messages.find { |message| message.data[:type] == "hand_raise" }
+ expect(hand_message).to be_present
+ expect(hand_message.data[:room_id]).to eq(room.id)
+ expect(hand_message.data[:user_id]).to eq(listener.id)
+ expect(hand_message.data[:raised]).to eq(true)
+ expect(hand_message.data[:raised_at]).to eq(metadata[:hand_raised_at])
+ expect(hand_message.data[:reason]).to eq("raised")
+
+ expect(messages.find { |message| message.data[:type] == "participants" }).to be_present
+ end
+
+ it "keeps the original timestamp and publishes nothing on a repeat request" do
+ sign_in(listener)
+ post "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+ original = Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at]
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at]).to eq(
+ original,
+ )
+ expect(messages).to be_empty
+ end
+
+ it "returns 403 for a stage speaker, who can already speak" do
+ Voice::ParticipantTracker.add(room.id, room_speaker.id)
+ sign_in(room_speaker)
+
+ post "/voice/rooms/#{room.id}/request_to_speak.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for a room moderator, who can already speak" do
+ Voice::ParticipantTracker.add(room.id, room_moderator.id)
+ sign_in(room_moderator)
+
+ post "/voice/rooms/#{room.id}/request_to_speak.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for an admin, who can already speak" do
+ Voice::ParticipantTracker.add(room.id, staff.id)
+ sign_in(staff)
+
+ post "/voice/rooms/#{room.id}/request_to_speak.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 in an open room, where everyone can already speak" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_OPEN)
+ sign_in(listener)
+
+ post "/voice/rooms/#{room.id}/request_to_speak.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 with a session message for a stage listener who is not in the call" do
+ # Leaving revokes the participant session, so the retained session id no
+ # longer authorizes a hand raise.
+ Voice::ParticipantTracker.remove(room.id, listener.id)
+ sign_in(listener)
+
+ post "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+
+ expect(response.status).to eq(403)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("voice.errors.participant_session_required"),
+ )
+ expect(
+ Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at],
+ ).to be_nil
+ end
+
+ it "requires authentication" do
+ post "/voice/rooms/#{room.id}/request_to_speak.json"
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#withdraw_request_to_speak" do
+ it "lowers the caller's raised hand and broadcasts the withdrawal plus the roster" do
+ Voice::ParticipantTracker.raise_hand(room.id, listener.id)
+ sign_in(listener)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ delete "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(
+ Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at],
+ ).to be_nil
+
+ hand_message = messages.find { |message| message.data[:type] == "hand_raise" }
+ expect(hand_message).to be_present
+ expect(hand_message.data[:user_id]).to eq(listener.id)
+ expect(hand_message.data[:raised]).to eq(false)
+ expect(hand_message.data[:reason]).to eq("withdrawn")
+
+ expect(messages.find { |message| message.data[:type] == "participants" }).to be_present
+ end
+
+ it "publishes nothing when the caller's hand is not raised" do
+ sign_in(listener)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ delete "/voice/rooms/#{room.id}/request_to_speak.json",
+ params: {
+ participant_session_id: @listener_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages).to be_empty
+ end
+
+ it "lets the room creator dismiss another participant's raised hand" do
+ Voice::ParticipantTracker.raise_hand(room.id, listener.id)
+ sign_in(room_owner)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ delete "/voice/rooms/#{room.id}/request_to_speak.json", params: { user_id: listener.id }
+ end
+
+ expect(response.status).to eq(204)
+ expect(
+ Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at],
+ ).to be_nil
+
+ hand_message = messages.find { |message| message.data[:type] == "hand_raise" }
+ expect(hand_message).to be_present
+ expect(hand_message.data[:user_id]).to eq(listener.id)
+ expect(hand_message.data[:raised]).to eq(false)
+ expect(hand_message.data[:reason]).to eq("dismissed")
+ end
+
+ it "lets site staff dismiss another participant's raised hand" do
+ Voice::ParticipantTracker.raise_hand(room.id, listener.id)
+ sign_in(staff)
+
+ delete "/voice/rooms/#{room.id}/request_to_speak.json", params: { user_id: listener.id }
+
+ expect(response.status).to eq(204)
+ expect(
+ Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at],
+ ).to be_nil
+ end
+
+ it "returns 403 when a plain participant tries to dismiss someone else's hand" do
+ Voice::ParticipantTracker.raise_hand(room.id, listener.id)
+ Voice::ParticipantTracker.add(room.id, other_listener.id)
+ sign_in(other_listener)
+
+ delete "/voice/rooms/#{room.id}/request_to_speak.json", params: { user_id: listener.id }
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.get_metadata(room.id, listener.id)[:hand_raised_at]).to be_a(
+ Float,
+ )
+ end
+ end
+end
diff --git a/plugins/voice/spec/requests/voice/rooms_controller_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_spec.rb
new file mode 100644
index 00000000000..ebf03d1d9bd
--- /dev/null
+++ b/plugins/voice/spec/requests/voice/rooms_controller_spec.rb
@@ -0,0 +1,2151 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+require_relative "../../../db/migrate/20260813160047_create_voice_invites"
+
+RSpec.describe Voice::RoomsController do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_invites)
+ CreateVoiceInvites.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:staff, :admin)
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:other_participant) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, creator: staff, public: true) }
+ fab!(:room_owner) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:private_room_member) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:private_room) { Fabricate(:voice_room, creator: room_owner, public: false) }
+
+ fab!(:private_room_membership) do
+ private_room.room_memberships.create!(
+ user: private_room_member,
+ role: Voice::RoomMembership::ROLE_PARTICIPANT,
+ )
+ end
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ end
+
+ # Presence plus the server-attested participant session that signal,
+ # heartbeat, and state require. Returns the session id to send back.
+ def establish_presence!(target_room, target_user)
+ Voice::ParticipantTracker.add(target_room.id, target_user.id)
+ Voice::ParticipantTracker.create_participant_session!(target_room.id, target_user.id)
+ end
+
+ describe "#index" do
+ it "returns rooms visible to the user" do
+ sign_in(user)
+
+ get "/voice/rooms.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["rooms"]).to be_present
+ end
+
+ it "returns message-bus positions for gap-free subscriptions" do
+ sign_in(user)
+
+ get "/voice/rooms.json"
+
+ expect(response.parsed_body["index_message_bus_last_id"]).to be_a(Integer)
+ expect(response.parsed_body["rooms"].first["message_bus_last_id"]).to be_a(Integer)
+ end
+
+ it "hides non-public rooms from non-members who can create rooms" do
+ sign_in(user)
+
+ get "/voice/rooms.json"
+
+ expect(response.status).to eq(200)
+ room_ids = response.parsed_body["rooms"].map { |listed_room| listed_room["id"] }
+ expect(room_ids).not_to include(private_room.id)
+ expect(response.parsed_body["can_create_room"]).to eq(true)
+ end
+
+ it "includes non-public rooms for their members" do
+ sign_in(private_room_member)
+
+ get "/voice/rooms.json"
+
+ room_ids = response.parsed_body["rooms"].map { |listed_room| listed_room["id"] }
+ expect(room_ids).to include(room.id, private_room.id)
+ end
+
+ it "includes non-public rooms for site staff" do
+ sign_in(staff)
+
+ get "/voice/rooms.json"
+
+ room_ids = response.parsed_body["rooms"].map { |listed_room| listed_room["id"] }
+ expect(room_ids).to include(private_room.id)
+ end
+
+ it "never lists ephemeral rooms, even to their members or staff" do
+ ephemeral = Fabricate(:voice_ephemeral_room, creator: staff, public: true)
+ sign_in(staff)
+
+ get "/voice/rooms.json"
+
+ room_ids = response.parsed_body["rooms"].map { |listed_room| listed_room["id"] }
+ expect(room_ids).not_to include(ephemeral.id)
+ end
+
+ context "when anonymous" do
+ it "returns only public rooms when access is open to everyone" do
+ get "/voice/rooms.json"
+
+ expect(response.status).to eq(200)
+ room_ids = response.parsed_body["rooms"].map { |r| r["id"] }
+ expect(room_ids).to include(room.id)
+ expect(room_ids).not_to include(private_room.id)
+ expect(response.parsed_body["can_create_room"]).to eq(false)
+ end
+
+ it "returns no rooms when access is restricted to a group" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+
+ get "/voice/rooms.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["rooms"]).to be_empty
+ end
+ end
+ end
+
+ describe "#show" do
+ it "serves an ephemeral room directly, even though it is never listed" do
+ ephemeral = Fabricate(:voice_ephemeral_room, creator: staff, public: true)
+ sign_in(user)
+
+ get "/voice/rooms/#{ephemeral.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["ephemeral"]).to eq(true)
+ end
+
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ get "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns the room to a member" do
+ sign_in(private_room_member)
+
+ get "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["id"]).to eq(private_room.id)
+ end
+
+ it "returns the room to site staff who aren't members" do
+ sign_in(staff)
+
+ get "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns 403 to anonymous visitors for non-public rooms" do
+ get "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#create" do
+ it "allows trusted user to create a room" do
+ sign_in(user)
+
+ post "/voice/rooms.json", params: { room: { name: "Game Night", public: true } }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["name"]).to eq("Game Night")
+ end
+
+ it "accepts an optional slug and generates one when it is blank" do
+ sign_in(user)
+
+ post "/voice/rooms.json",
+ params: {
+ room: {
+ name: "Game Night",
+ slug: "Friday Hangout",
+ public: true,
+ },
+ }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["slug"]).to eq("friday-hangout")
+
+ post "/voice/rooms.json", params: { room: { name: "Movie Night", slug: "", public: true } }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["room"]["slug"]).to eq("movie-night")
+ end
+
+ it "does not count ephemeral rooms against the per-user room limit" do
+ SiteSetting.voice_max_rooms_per_user = 1
+ Fabricate(:voice_ephemeral_room, creator: user)
+ sign_in(user)
+
+ post "/voice/rooms.json", params: { room: { name: "Game Night", public: true } }
+
+ expect(response.status).to eq(200)
+ end
+
+ it "denies room creation to users outside the create-room groups" do
+ low_trust_user = Fabricate(:user, trust_level: TrustLevel[0])
+ sign_in(low_trust_user)
+
+ post "/voice/rooms.json", params: { room: { name: "Game Night", public: true } }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#join" do
+ it "returns a participant session id and rotates it on rejoin" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ first_session_id = response.parsed_body["participant_session_id"]
+
+ expect(first_session_id).to be_present
+ expect(
+ Voice::ParticipantTracker.valid_participant_session?(room.id, user.id, first_session_id),
+ ).to eq(true)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ second_session_id = response.parsed_body["participant_session_id"]
+
+ expect(second_session_id).to be_present
+ expect(second_session_id).not_to eq(first_session_id)
+ expect(
+ Voice::ParticipantTracker.valid_participant_session?(room.id, user.id, first_session_id),
+ ).to eq(false)
+ end
+
+ it "treats a repeated join carrying the live session as idempotent" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ session_id = response.parsed_body["participant_session_id"]
+ expect(Voice::Session.where(user: user, room: room).count).to eq(1)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/join.json", params: { participant_session_id: session_id }
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["participant_session_id"]).to eq(session_id)
+ expect(
+ Voice::ParticipantTracker.valid_participant_session?(room.id, user.id, session_id),
+ ).to eq(true)
+ expect(Voice::Session.where(user: user, room: room).count).to eq(1)
+ expect(messages.select { |message| message.data[:type] == "participants" }).to be_empty
+ end
+
+ it "reuses the open analytics session and skips join side effects for a present user omitting the session id" do
+ SiteSetting.voice_analytics_enabled = true
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ first_session_id = response.parsed_body["participant_session_id"]
+ analytics_id = Voice::Session.find_by(user: user, room: room).id
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ 5.times { post "/voice/rooms/#{room.id}/join.json" }
+ end
+
+ expect(response.status).to eq(200)
+ # The takeover still rotates the participant session so the newest tab
+ # holds signaling authority...
+ expect(response.parsed_body["participant_session_id"]).not_to eq(first_session_id)
+ # ...but replayed joins are not an analytics-row or broadcast factory.
+ sessions = Voice::Session.where(user: user, room: room)
+ expect(sessions.count).to eq(1)
+ expect(sessions.first.id).to eq(analytics_id)
+ expect(sessions.first.left_at).to be_nil
+ expect(messages.select { |message| message.data[:type] == "participants" }).to be_empty
+ end
+
+ it "mints a fresh session and analytics session on a genuine rejoin after leave" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ first_session_id = response.parsed_body["participant_session_id"]
+
+ delete "/voice/rooms/#{room.id}/leave.json",
+ params: {
+ participant_session_id: first_session_id,
+ }
+
+ post "/voice/rooms/#{room.id}/join.json", params: { participant_session_id: first_session_id }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["participant_session_id"]).not_to eq(first_session_id)
+ expect(Voice::Session.where(user: user, room: room).count).to eq(2)
+ end
+
+ it "returns 422 when the room is at its own participant limit" do
+ room.update!(max_participants: 2)
+ establish_presence!(room, staff)
+ establish_presence!(room, other_participant)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(I18n.t("voice.errors.room_full"))
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ end
+
+ it "returns 422 when the room is at the site-wide participant ceiling" do
+ SiteSetting.voice_max_room_participants = 2
+ establish_presence!(room, staff)
+ establish_presence!(room, other_participant)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(422)
+ end
+
+ it "lets an existing participant rejoin a full room" do
+ room.update!(max_participants: 2)
+ establish_presence!(room, staff)
+ establish_presence!(room, user)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "frees the slots of participants whose presence expired" do
+ room.update!(max_participants: 2)
+ establish_presence!(room, staff)
+ establish_presence!(room, other_participant)
+ key = "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, staff.id)
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to contain_exactly(
+ other_participant.id,
+ user.id,
+ )
+ end
+
+ it "returns 403 when a non-member who can create rooms joins a private room" do
+ sign_in(user)
+
+ post "/voice/rooms/#{private_room.id}/join.json"
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.user_ids(private_room.id)).not_to include(user.id)
+ end
+
+ it "lets a member join a private room" do
+ sign_in(private_room_member)
+
+ post "/voice/rooms/#{private_room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(private_room.id)).to include(private_room_member.id)
+ end
+
+ it "lets site staff join a private room they aren't a member of" do
+ sign_in(staff)
+
+ post "/voice/rooms/#{private_room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "redeems a pending invite when joining with the inviter's username" do
+ invite =
+ Voice::Invite.create!(
+ room_id: room.id,
+ user_id: user.id,
+ invited_by_id: other_participant.id,
+ source: Voice::Invite::SOURCES[:notification],
+ )
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json", params: { invited_by: other_participant.username }
+
+ expect(response.status).to eq(200)
+ expect(invite.reload.redeemed_at).to be_present
+ end
+
+ it "marks the room's unread invitation notifications read on join, leaving other rooms' alone" do
+ Voice::RoomInviter.invite!(room: room, inviter: other_participant, users: [user])
+ Voice::RoomInviter.invite!(room: private_room, inviter: room_owner, users: [user])
+ invitation_notifications =
+ user.notifications.where(notification_type: Notification.types[:voice_invitation])
+ room_notification =
+ invitation_notifications.find { |notification| notification.data_hash[:room_id] == room.id }
+ other_room_notification =
+ invitation_notifications.find do |notification|
+ notification.data_hash[:room_id] == private_room.id
+ end
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(room_notification.reload.read).to eq(true)
+ expect(other_room_notification.reload.read).to eq(false)
+ end
+
+ it "records a link invite when joining through a shared invite URL, only once" do
+ sign_in(user)
+
+ 2.times do
+ post "/voice/rooms/#{room.id}/join.json", params: { invited_by: other_participant.username }
+ delete "/voice/rooms/#{room.id}/leave.json"
+ end
+
+ invites = Voice::Invite.where(room_id: room.id, user_id: user.id)
+ expect(invites.count).to eq(1)
+ expect(invites.first.source).to eq(Voice::Invite::SOURCES[:link])
+ expect(invites.first.invited_by_id).to eq(other_participant.id)
+ expect(invites.first.redeemed_at).to be_present
+ end
+
+ it "does not let users credit themselves through their own invite link" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json", params: { invited_by: user.username }
+
+ expect(response.status).to eq(200)
+ expect(Voice::Invite.count).to eq(0)
+ end
+
+ it "returns the ICE configuration with per-user TURN credentials" do
+ SiteSetting.voice_stun_servers = ""
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+ SiteSetting.voice_turn_secret_servers = "turn:turn.example.com:3478"
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+
+ ice = response.parsed_body["ice"]
+ turn_server = ice["servers"].first
+ expiry, site, credential_user_id = turn_server["username"].split(":")
+
+ expect(credential_user_id).to eq(user.id.to_s)
+ expect(site).to eq(Discourse.current_hostname)
+ expect(expiry.to_i).to be > Time.zone.now.to_i
+ expect(turn_server["credential"]).to eq(
+ Base64.strict_encode64(
+ OpenSSL::HMAC.digest("SHA1", "coturn-shared-secret", turn_server["username"]),
+ ),
+ )
+ expect(ice["transport_policy"]).to eq("all")
+ end
+
+ it "tracks users when they join a room" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ json = response.parsed_body
+ expect(json["room"]["active_participants"].map { |p| p["id"] }).to include(user.id)
+ end
+
+ it "broadcasts participants to the allowed groups, anonymous subscribers included" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, other_participant.id)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/join.json"
+ end
+
+ expect(response.status).to eq(200)
+
+ participants_message = messages.find { |message| message.data[:type] == "participants" }
+ expect(participants_message).to be_present
+ expect(participants_message.group_ids).to include(
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ )
+ end
+
+ context "with user status integration" do
+ before do
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ end
+
+ it "sets user status on join" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ user.reload
+ expect(user.user_status.emoji).to eq("studio_microphone")
+ expect(user.user_status.description).to eq("In #{room.name}")
+ end
+
+ it "skips status when user already has one" do
+ sign_in(user)
+ user.set_status!("Busy", "no_entry")
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ user.reload
+ expect(user.user_status.emoji).to eq("no_entry")
+ end
+
+ it "skips status when skip_status param is sent" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json", params: { skip_status: true }
+
+ user.reload
+ expect(user.user_status).to be_nil
+ end
+ end
+ end
+
+ describe "#leave" do
+ before do
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ end
+
+ it "clears Voice status on leave" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, user.id)
+ user.set_status!("In #{room.name}", "studio_microphone", 2.minutes.from_now)
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+
+ expect(response.status).to eq(204)
+ user.reload
+ expect(user.user_status).to be_nil
+ end
+
+ it "preserves non-Voice status on leave" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, user.id)
+ user.set_status!("On vacation", "palm_tree")
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+
+ expect(response.status).to eq(204)
+ user.reload
+ expect(user.user_status.emoji).to eq("palm_tree")
+ end
+
+ it "keeps the user out when a racing heartbeat lands after the leave" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+ post "/voice/rooms/#{room.id}/heartbeat.json"
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ end
+
+ it "lets the user rejoin immediately after leaving" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, user.id)
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "ignores a leave carrying a session that a newer join superseded" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ stale_session_id = response.parsed_body["participant_session_id"]
+
+ post "/voice/rooms/#{room.id}/join.json"
+ current_session_id = response.parsed_body["participant_session_id"]
+
+ delete "/voice/rooms/#{room.id}/leave.json",
+ params: {
+ participant_session_id: stale_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ expect(
+ Voice::ParticipantTracker.valid_participant_session?(room.id, user.id, current_session_id),
+ ).to eq(true)
+ end
+
+ it "removes presence when the leave carries the current session" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ session_id = response.parsed_body["participant_session_id"]
+
+ delete "/voice/rooms/#{room.id}/leave.json", params: { participant_session_id: session_id }
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ expect(Voice::ParticipantTracker.participant_session?(room.id, user.id)).to eq(false)
+ end
+ end
+
+ describe "#heartbeat" do
+ it "refreshes lapsed presence when the participant session is still valid" do
+ sign_in(user)
+ session_id = establish_presence!(room, user)
+
+ # The heartbeat lapsed (laptop asleep) but the session TTL has not.
+ key = "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user.id)
+
+ post "/voice/rooms/#{room.id}/heartbeat.json", params: { participant_session_id: session_id }
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).to include(user.id)
+ end
+
+ it "rejects a heartbeat without a participant session and creates no presence" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/heartbeat.json"
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(user.id)
+ end
+
+ it "broadcasts the participant list when a stale participant has dropped out" do
+ sign_in(user)
+ session_id = establish_presence!(room, user)
+ Voice::ParticipantTracker.add(room.id, other_participant.id)
+
+ # other_participant left abruptly (refresh/close) and their heartbeat lapsed.
+ key = "#{Voice::ParticipantTracker::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, other_participant.id)
+
+ published = []
+ allow(MessageBus).to receive(:publish) { |channel, data, _opts| published << data }
+
+ post "/voice/rooms/#{room.id}/heartbeat.json", params: { participant_session_id: session_id }
+
+ expect(response.status).to eq(204)
+ participants_message = published.find { |data| data[:type] == "participants" }
+ expect(participants_message).to be_present
+ expect(participants_message[:participants].map { |p| p[:id] }).to contain_exactly(user.id)
+ end
+
+ it "does not broadcast when membership and state are unchanged" do
+ sign_in(user)
+ session_id = establish_presence!(room, user)
+ # Prime the stored fingerprint so the next heartbeat sees no change.
+ Voice::RoomBroadcaster.publish_participants_if_changed(room)
+
+ published = []
+ allow(MessageBus).to receive(:publish) { |channel, data, _opts| published << data }
+
+ post "/voice/rooms/#{room.id}/heartbeat.json", params: { participant_session_id: session_id }
+
+ expect(response.status).to eq(204)
+ expect(published.find { |data| data[:type] == "participants" }).to be_nil
+ end
+
+ context "with user status integration" do
+ before do
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ sign_in(user)
+ @participant_session_id = establish_presence!(room, user)
+ Voice::ParticipantTracker.update_metadata(room.id, user.id, { role: "participant" })
+ Voice::UserStatusManager.set_voice_status(user, room)
+ end
+
+ it "keeps the status without an expiry across heartbeats" do
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ participant_session_id: @participant_session_id,
+ }
+
+ user.reload
+ expect(user.user_status.emoji).to eq("studio_microphone")
+ expect(user.user_status.ends_at).to be_nil
+ end
+
+ it "does not republish an unchanged status on heartbeat" do
+ messages =
+ MessageBus.track_publish do
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ participant_session_id: @participant_session_id,
+ }
+ end
+
+ expect(messages.select { |m| m.channel.include?("user-status") }).to be_empty
+ end
+
+ it "transitions to AFK status" do
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ idle_state: "afk",
+ participant_session_id: @participant_session_id,
+ }
+
+ user.reload
+ expect(user.user_status.emoji).to eq("zzz")
+ expect(user.user_status.description).to eq("AFK in #{room.name}")
+ end
+
+ it "transitions back from AFK to active status" do
+ Voice::UserStatusManager.set_afk_status(user, room)
+
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ idle_state: "active",
+ participant_session_id: @participant_session_id,
+ }
+
+ user.reload
+ expect(user.user_status.emoji).to eq("studio_microphone")
+ expect(user.user_status.description).to eq("In #{room.name}")
+ end
+
+ it "skips status refresh when skip_status metadata is set" do
+ Voice::ParticipantTracker.update_metadata(
+ room.id,
+ user.id,
+ { role: "participant", skip_status: true },
+ )
+ user.clear_status!
+
+ post "/voice/rooms/#{room.id}/heartbeat.json",
+ params: {
+ participant_session_id: @participant_session_id,
+ }
+
+ user.reload
+ expect(user.user_status).to be_nil
+ end
+ end
+ end
+
+ describe "#kick" do
+ before { Voice::ParticipantTracker.add(room.id, other_participant.id) }
+
+ it "allows room manager to kick participants" do
+ sign_in(staff)
+
+ published = []
+ allow(MessageBus).to receive(:publish) { |channel, data, opts|
+ published << [channel, data, opts]
+ }
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_participant.id }
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(other_participant.id)
+
+ kick_message = published.find { |(_, data)| data[:type] == "kicked" }
+ expect(kick_message).to be_present
+ expect(kick_message[2][:user_ids]).to eq([other_participant.id])
+ end
+
+ it "prevents non-managers from kicking" do
+ low_trust_user = Fabricate(:user, trust_level: TrustLevel[0])
+ sign_in(low_trust_user)
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_participant.id }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "prevents kicking oneself" do
+ sign_in(staff)
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: staff.id }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "clears kicked user's Voice status" do
+ SiteSetting.enable_user_status = true
+ SiteSetting.voice_auto_status_enabled = true
+ sign_in(staff)
+ other_participant.set_status!("In #{room.name}", "studio_microphone", 2.minutes.from_now)
+
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_participant.id }
+
+ expect(response.status).to eq(204)
+ other_participant.reload
+ expect(other_participant.user_status).to be_nil
+ end
+
+ it "keeps the kicked user out when their racing heartbeat lands after the kick" do
+ sign_in(staff)
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: other_participant.id }
+
+ sign_in(other_participant)
+ post "/voice/rooms/#{room.id}/heartbeat.json"
+
+ expect(response.status).to eq(204)
+ expect(Voice::ParticipantTracker.user_ids(room.id)).not_to include(other_participant.id)
+ end
+
+ it "prevents kicking the room creator" do
+ sign_in(staff)
+ other_room = Fabricate(:voice_room, creator: user, public: true)
+ Voice::ParticipantTracker.add(other_room.id, user.id)
+
+ delete "/voice/rooms/#{other_room.id}/kick.json", params: { user_id: user.id }
+
+ expect(response.status).to eq(400)
+ end
+ end
+
+ describe "#toggle_mute" do
+ before { @participant_session_id = establish_presence!(room, user) }
+
+ it "sets muted metadata and broadcasts participants" do
+ sign_in(user)
+
+ published = []
+ allow(MessageBus).to receive(:publish) { |channel, data, opts|
+ published << [channel, data, opts]
+ }
+
+ post "/voice/rooms/#{room.id}/toggle_mute.json",
+ params: {
+ muted: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_muted]).to eq(true)
+
+ participants_message = published.find { |(_, data)| data[:type] == "participants" }
+ expect(participants_message).to be_present
+ muted_participant = participants_message[1][:participants].find { |p| p[:id] == user.id }
+ expect(muted_participant[:is_muted]).to eq(true)
+ end
+
+ it "unmutes when muted is false" do
+ sign_in(user)
+ Voice::ParticipantTracker.update_metadata(room.id, user.id, { is_muted: true })
+
+ post "/voice/rooms/#{room.id}/toggle_mute.json",
+ params: {
+ muted: false,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_muted]).to eq(false)
+ end
+
+ it "sets deafened metadata" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/toggle_mute.json",
+ params: {
+ muted: true,
+ deafened: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_muted]).to eq(true)
+ expect(metadata[:is_deafened]).to eq(true)
+ end
+
+ it "requires authentication" do
+ post "/voice/rooms/#{room.id}/toggle_mute.json", params: { muted: true }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#state" do
+ before do
+ SiteSetting.voice_video_enabled = true
+ @participant_session_id = establish_presence!(room, user)
+ sign_in(user)
+ end
+
+ it "rejects a state change without a participant session" do
+ post "/voice/rooms/#{room.id}/state.json", params: { watching: true }
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.get_metadata(room.id, user.id)[:watching_video]).to be_nil
+ end
+
+ it "sets video metadata and broadcasts participants" do
+ published = []
+ allow(MessageBus).to receive(:publish) { |channel, data, opts|
+ published << [channel, data, opts]
+ }
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_video_on]).to eq(true)
+
+ participants_message = published.find { |(_, data)| data[:type] == "participants" }
+ expect(participants_message).to be_present
+ participant = participants_message[1][:participants].find { |entry| entry[:id] == user.id }
+ expect(participant[:is_video_on]).to eq(true)
+ end
+
+ it "sets screen sharing and watching metadata" do
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ screen: true,
+ watching: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_screen_sharing]).to eq(true)
+ expect(metadata[:watching_video]).to eq(true)
+ end
+
+ it "sets and clears the transcribing flag" do
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ transcribing: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_transcribing]).to eq(true)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ transcribing: false,
+ participant_session_id: @participant_session_id,
+ }
+
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_transcribing]).to eq(false)
+ end
+
+ it "rejects video when the site setting is disabled" do
+ SiteSetting.voice_video_enabled = false
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects video when the room has video disabled" do
+ room.update!(video_enabled: false)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects video from a stage listener" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects screen share from a stage listener" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ screen: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "allows video from a stage speaker" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ room.room_memberships.create!(user: user, role: Voice::RoomMembership::ROLE_SPEAKER)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_video_on]).to eq(true)
+ end
+
+ it "allows screen share from a stage speaker" do
+ room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ room.room_memberships.create!(user: user, role: Voice::RoomMembership::ROLE_SPEAKER)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ screen: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ end
+
+ it "rejects video when the publisher limit is reached" do
+ SiteSetting.voice_video_max_publishers = 2
+
+ publishers = Fabricate.times(2, :user)
+ publishers.each do |publisher|
+ Voice::ParticipantTracker.add(room.id, publisher.id)
+ Voice::ParticipantTracker.update_metadata(room.id, publisher.id, { is_video_on: true })
+ end
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "allows an existing publisher to keep publishing at the limit" do
+ SiteSetting.voice_video_max_publishers = 2
+
+ publisher = Fabricate(:user)
+ Voice::ParticipantTracker.add(room.id, publisher.id)
+ Voice::ParticipantTracker.update_metadata(room.id, publisher.id, { is_video_on: true })
+ Voice::ParticipantTracker.update_metadata(room.id, user.id, { is_video_on: true })
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ end
+
+ it "allows turning video off even when video is disallowed" do
+ Voice::ParticipantTracker.update_metadata(room.id, user.id, { is_video_on: true })
+ room.update!(video_enabled: false)
+
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ video: false,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_video_on]).to eq(false)
+ end
+
+ it "rejects a request with no supported state field" do
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ participant_session_id: @participant_session_id,
+ something_else: true,
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "publishes nothing when the request changes no state" do
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ muted: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/state.json",
+ params: {
+ muted: true,
+ participant_session_id: @participant_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages).to be_empty
+ end
+
+ it "still updates mute state through the toggle_mute alias" do
+ post "/voice/rooms/#{room.id}/toggle_mute.json",
+ params: {
+ muted: true,
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(204)
+ metadata = Voice::ParticipantTracker.get_metadata(room.id, user.id)
+ expect(metadata[:is_muted]).to eq(true)
+ end
+ end
+
+ describe "#update" do
+ it "lets a room manager toggle video_enabled" do
+ sign_in(staff)
+
+ put "/voice/rooms/#{room.id}.json", params: { room: { video_enabled: false } }
+
+ expect(response.status).to eq(200)
+ expect(room.reload.video_enabled).to eq(false)
+ expect(response.parsed_body["room"]["video_enabled"]).to eq(false)
+ end
+
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ expect {
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { name: "Hijacked" } }
+ }.not_to change { private_room.reload.name }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for a plain participant member" do
+ sign_in(private_room_member)
+
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { name: "Hijacked" } }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "lets the creator update their room" do
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { name: "New name" } }
+
+ expect(response.status).to eq(200)
+ expect(private_room.reload.name).to eq("New name")
+ end
+
+ it "lets a room manager change the slug" do
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { slug: "New Hangout" } }
+
+ expect(response.status).to eq(200)
+ expect(private_room.reload.slug).to eq("new-hangout")
+ end
+
+ it "keeps a stage room's type when an update sends an unknown room_type" do
+ private_room.update!(room_type: Voice::Room::ROOM_TYPE_STAGE)
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { room_type: "arena" } }
+
+ expect(response.status).to eq(400)
+ expect(private_room.reload.stage?).to eq(true)
+ end
+
+ it "stores max_quality_profile by name and serializes it back" do
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{private_room.id}.json", params: { room: { max_quality_profile: "high" } }
+
+ expect(response.status).to eq(200)
+ expect(private_room.reload.max_quality_profile).to eq(Voice::Room::QUALITY_PROFILES["high"])
+ expect(response.parsed_body["room"]["max_quality_profile"]).to eq("high")
+ end
+
+ it "clears the room-level quality cap when set to site_default" do
+ private_room.update!(max_quality_profile: Voice::Room::QUALITY_PROFILES["standard"])
+ sign_in(room_owner)
+
+ put "/voice/rooms/#{private_room.id}.json",
+ params: {
+ room: {
+ max_quality_profile: "site_default",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(private_room.reload.max_quality_profile).to be_nil
+ end
+ end
+
+ describe "#destroy" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ delete "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(403)
+ expect(Voice::Room.exists?(private_room.id)).to eq(true)
+ end
+
+ it "lets the creator destroy their room" do
+ sign_in(room_owner)
+
+ delete "/voice/rooms/#{private_room.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(Voice::Room.exists?(private_room.id)).to eq(false)
+ end
+
+ it "broadcasts the destroy to the members the room had" do
+ sign_in(room_owner)
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ delete "/voice/rooms/#{private_room.id}.json"
+ end
+
+ expect(response.status).to eq(200)
+ destroy_message = messages.find { |message| message.data[:type] == :destroyed }
+ expect(destroy_message).to be_present
+ expect(destroy_message.user_ids).to contain_exactly(room_owner.id, private_room_member.id)
+ end
+ end
+
+ describe "#participants" do
+ before { Voice::ParticipantTracker.add(private_room.id, private_room_member.id) }
+
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ get "/voice/rooms/#{private_room.id}/participants.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns the participant list to a member" do
+ sign_in(private_room_member)
+
+ get "/voice/rooms/#{private_room.id}/participants.json"
+
+ expect(response.status).to eq(200)
+ participant_ids = response.parsed_body["participants"].map { |p| p["id"] }
+ expect(participant_ids).to include(private_room_member.id)
+ end
+ end
+
+ describe "#heartbeat on a private room" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ post "/voice/rooms/#{private_room.id}/heartbeat.json"
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.user_ids(private_room.id)).not_to include(user.id)
+ end
+ end
+
+ describe "#signal on a private room" do
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ post "/voice/rooms/#{private_room.id}/signal.json",
+ params: {
+ payload: {
+ type: "offer",
+ sdp: "v=0",
+ recipient_id: private_room_member.id,
+ },
+ }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#kick on a private room" do
+ before { Voice::ParticipantTracker.add(private_room.id, private_room_member.id) }
+
+ it "returns 403 for a non-member who can create rooms" do
+ sign_in(user)
+
+ delete "/voice/rooms/#{private_room.id}/kick.json",
+ params: {
+ user_id: private_room_member.id,
+ }
+
+ expect(response.status).to eq(403)
+ expect(Voice::ParticipantTracker.user_ids(private_room.id)).to include(private_room_member.id)
+ end
+ end
+
+ describe "#join with metadata" do
+ it "includes is_muted and is_deafened in active_participants when metadata exists" do
+ sign_in(user)
+ Voice::ParticipantTracker.add(room.id, other_participant.id)
+ Voice::ParticipantTracker.update_metadata(
+ room.id,
+ other_participant.id,
+ { is_muted: true, is_deafened: true },
+ )
+
+ post "/voice/rooms/#{room.id}/join.json"
+
+ expect(response.status).to eq(200)
+ participants = response.parsed_body["room"]["active_participants"]
+ participant = participants.find { |p| p["id"] == other_participant.id }
+ expect(participant["is_muted"]).to eq(true)
+ expect(participant["is_deafened"]).to eq(true)
+ end
+ end
+
+ describe "#signal" do
+ before do
+ sign_in(user)
+ @participant_session_id = establish_presence!(room, user)
+ establish_presence!(room, staff)
+ establish_presence!(room, other_participant)
+ end
+
+ it "rejects missing payloads" do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ },
+ participant_session_id: @participant_session_id,
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "relays ICE candidate payloads with the server-serialized sender" do
+ candidate_payload = {
+ candidate: "candidate:347230118 1 udp 41819902 203.0.113.1 54400 typ host",
+ sdpMid: "0",
+ sdpMLineIndex: 0,
+ usernameFragment: "abc123",
+ }
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ type: "candidate",
+ candidate: candidate_payload,
+ recipient_id: staff.id,
+ },
+ participant_session_id: @participant_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+
+ message = messages.first
+ expect(message.data[:type]).to eq("signal")
+ expect(message.data[:room_id]).to eq(room.id)
+ expect(message.data[:sender_id]).to eq(user.id)
+ expect(message.data[:sender][:username]).to eq(user.username)
+ expect(message.data[:events].size).to eq(1)
+ expect(message.data[:events].first[:type]).to eq("candidate")
+ expect(message.data[:events].first[:candidate][:candidate]).to eq(
+ candidate_payload[:candidate],
+ )
+ expect(message.user_ids).to eq([staff.id])
+ end
+
+ it "accepts batched events payloads" do
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: staff.id,
+ events: [
+ { type: "offer", sdp: "v=0" },
+ {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:1 1 udp 2122260223 10.0.0.1 8998 typ host",
+ },
+ },
+ ],
+ },
+ participant_session_id: @participant_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+
+ message = messages.first
+ expect(message.data[:sender_id]).to eq(user.id)
+ expect(message.user_ids).to eq([staff.id])
+
+ events = message.data[:events]
+ expect(events.map { |event| event[:type] }).to eq(%w[offer candidate])
+ expect(events.first[:sdp]).to eq("v=0")
+ expect(events.last[:candidate][:candidate]).to eq(
+ "candidate:1 1 udp 2122260223 10.0.0.1 8998 typ host",
+ )
+ end
+
+ it "relays multi-recipient batched messages" do
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ messages: [
+ { recipient_id: staff.id, events: [{ type: "offer", sdp: "v=0" }] },
+ {
+ recipient_id: other_participant.id,
+ events: [
+ {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:1 1 udp 2122260223 10.0.0.1 8998 typ host",
+ },
+ },
+ ],
+ },
+ ],
+ },
+ participant_session_id: @participant_session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(2)
+ expect(messages.map { |message| message.data[:sender_id] }).to all(eq(user.id))
+
+ offer = messages.find { |message| message.data[:events].first[:type] == "offer" }
+ candidate = messages.find { |message| message.data[:events].first[:type] == "candidate" }
+
+ expect(offer.data[:events].first[:sdp]).to eq("v=0")
+ expect(offer.user_ids).to eq([staff.id])
+ expect(candidate.data[:events].first[:candidate][:candidate]).to eq(
+ "candidate:1 1 udp 2122260223 10.0.0.1 8998 typ host",
+ )
+ expect(candidate.user_ids).to eq([other_participant.id])
+ end
+ end
+
+ describe "#signal validation" do
+ before do
+ sign_in(user)
+ @participant_session_id = establish_presence!(room, user)
+ establish_presence!(room, staff)
+ establish_presence!(room, other_participant)
+ end
+
+ def post_signal_payload(payload)
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: payload,
+ participant_session_id: @participant_session_id,
+ },
+ as: :json
+ end
+ end
+
+ def candidate_event(seq = 1)
+ {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:#{seq} 1 udp 2122260223 10.0.0.1 8998 typ host",
+ },
+ }
+ end
+
+ it "rejects an unknown event type and publishes nothing" do
+ messages = post_signal_payload({ recipient_id: staff.id, events: [{ type: "datachannel" }] })
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects an offer missing its sdp" do
+ messages = post_signal_payload({ recipient_id: staff.id, events: [{ type: "offer" }] })
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects an event carrying fields outside its type's shape" do
+ messages =
+ post_signal_payload(
+ {
+ recipient_id: staff.id,
+ events: [{ type: "offer", sdp: "v=0", metadata: { room: "other" } }],
+ },
+ )
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects a candidate whose body has unexpected keys" do
+ messages =
+ post_signal_payload(
+ {
+ recipient_id: staff.id,
+ events: [{ type: "candidate", candidate: { candidate: "a", extra: "b" } }],
+ },
+ )
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects an oversized sdp" do
+ oversized = "a" * (Voice::SignalValidator::MAX_SDP_BYTES + 1)
+ messages =
+ post_signal_payload({ recipient_id: staff.id, events: [{ type: "offer", sdp: oversized }] })
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects an oversized candidate" do
+ oversized = "a" * (Voice::SignalValidator::MAX_CANDIDATE_BYTES + 1)
+ messages =
+ post_signal_payload(
+ {
+ recipient_id: staff.id,
+ events: [{ type: "candidate", candidate: { candidate: oversized } }],
+ },
+ )
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects a batch with more events than one recipient may receive" do
+ events =
+ (Voice::SignalValidator::MAX_EVENTS_PER_RECIPIENT + 1).times.map do |seq|
+ candidate_event(seq)
+ end
+ messages = post_signal_payload({ recipient_id: staff.id, events: events })
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects a batch with more recipients than the room can hold" do
+ room.update!(max_participants: 2)
+
+ messages =
+ post_signal_payload(
+ {
+ messages: [
+ { recipient_id: staff.id, events: [candidate_event] },
+ { recipient_id: other_participant.id, events: [candidate_event] },
+ ],
+ },
+ )
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "rejects a malformed batch wholesale even when other events are valid" do
+ messages =
+ post_signal_payload(
+ {
+ messages: [
+ { recipient_id: staff.id, events: [{ type: "offer", sdp: "v=0" }] },
+ { recipient_id: other_participant.id, events: [{ type: "evil" }] },
+ ],
+ },
+ )
+
+ expect(response.status).to eq(400)
+ expect(messages).to be_empty
+ end
+
+ it "preserves event order within a recipient's batch" do
+ messages =
+ post_signal_payload(
+ {
+ recipient_id: staff.id,
+ events: [{ type: "offer", sdp: "v=0" }, candidate_event(1), candidate_event(2)],
+ },
+ )
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+
+ events = messages.first.data[:events]
+ expect(events.map { |event| event[:type] }).to eq(%w[offer candidate candidate])
+ expect(events.last[:candidate][:candidate]).to include("candidate:2")
+ end
+
+ it "publishes one envelope per recipient, not per event" do
+ messages =
+ post_signal_payload(
+ {
+ messages: [
+ {
+ recipient_id: staff.id,
+ events: [{ type: "offer", sdp: "v=0" }, candidate_event(1)],
+ },
+ {
+ recipient_id: other_participant.id,
+ events: [{ type: "offer", sdp: "v=0" }, candidate_event(2)],
+ },
+ ],
+ },
+ )
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(2)
+ expect(messages.map(&:user_ids)).to contain_exactly([staff.id], [other_participant.id])
+ expect(messages.map { |message| message.data[:events].size }).to eq([2, 2])
+ end
+ end
+
+ describe "#signal rate limits" do
+ before do
+ RateLimiter.enable
+ sign_in(user)
+ @participant_session_id = establish_presence!(room, user)
+ end
+
+ def candidate_event(seq = 1)
+ {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:#{seq} 1 udp 2122260223 10.0.0.1 8998 typ host",
+ },
+ }
+ end
+
+ # Recipients only need a live participant session for the relay to
+ # deliver; real User records are not required.
+ def recipient_sessions!(count)
+ (1..count).map do |i|
+ fake_id = 100_000 + i
+ Voice::ParticipantTracker.create_participant_session!(room.id, fake_id)
+ fake_id
+ end
+ end
+
+ def post_burst(recipient_ids, events_per_recipient)
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ messages:
+ recipient_ids.map do |recipient_id|
+ { recipient_id: recipient_id, events: events_per_recipient }
+ end,
+ },
+ participant_session_id: @participant_session_id,
+ },
+ as: :json
+ end
+ end
+
+ it "accepts a full 50-person room trickle ICE burst without 429" do
+ recipient_ids = recipient_sessions!(49)
+
+ # The representative burst: one offer plus three 5-candidate batches to
+ # every peer in the room, followed by a straggler candidate round.
+ connect_events = [{ type: "offer", sdp: "v=0" }] + 15.times.map { |seq| candidate_event(seq) }
+ messages = post_burst(recipient_ids, connect_events)
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(49)
+
+ post_burst(recipient_ids, 5.times.map { |seq| candidate_event(seq) })
+ expect(response.status).to eq(204)
+ end
+
+ it "rejects sustained signaling before any MessageBus work happens" do
+ recipient_ids = recipient_sessions!(49)
+ max_events =
+ Voice::SignalValidator::MAX_EVENTS_PER_RECIPIENT.times.map { |seq| candidate_event(seq) }
+
+ 4.times do
+ post_burst(recipient_ids, max_events)
+ expect(response.status).to eq(204)
+ end
+
+ messages = post_burst(recipient_ids, max_events)
+
+ expect(response.status).to eq(429)
+ expect(messages).to be_empty
+ end
+
+ it "limits a room's aggregate signaling across users" do
+ stub_const(Voice::RoomsController, :SIGNAL_EVENTS_PER_ROOM_PER_MINUTE, 40) do
+ staff_session_id = establish_presence!(room, staff)
+ recipient_sessions!(1)
+
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: 100_001,
+ events: 25.times.map { |seq| candidate_event(seq) },
+ },
+ participant_session_id: @participant_session_id,
+ },
+ as: :json
+ expect(response.status).to eq(204)
+
+ sign_in(staff)
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: 100_001,
+ events: 25.times.map { |seq| candidate_event(seq) },
+ },
+ participant_session_id: staff_session_id,
+ },
+ as: :json
+ end
+
+ expect(response.status).to eq(429)
+ expect(messages).to be_empty
+ end
+ end
+
+ it "rate limits repeated invalid-session attempts" do
+ sign_in(other_participant)
+
+ 30.times do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: user.id,
+ events: [candidate_event],
+ },
+ },
+ as: :json
+ expect(response.status).to eq(403)
+ end
+
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ recipient_id: user.id,
+ events: [candidate_event],
+ },
+ },
+ as: :json
+
+ expect(response.status).to eq(429)
+ end
+ end
+
+ describe "#signal participant session enforcement" do
+ def post_signal(sender_room, session_id, recipient:)
+ post "/voice/rooms/#{sender_room.id}/signal.json",
+ params: {
+ payload: {
+ type: "offer",
+ sdp: "v=0",
+ recipient_id: recipient.id,
+ },
+ participant_session_id: session_id,
+ }
+ end
+
+ it "relays a valid-session offer even when the sender's roster broadcast is still in flight" do
+ # The recipient is present; the sender joined but no participants
+ # broadcast has been observed yet — the session alone must authorize the
+ # early offer.
+ sign_in(user)
+ establish_presence!(room, other_participant)
+ post "/voice/rooms/#{room.id}/join.json"
+ session_id = response.parsed_body["participant_session_id"]
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_signal(room, session_id, recipient: other_participant)
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to eq([other_participant.id])
+ end
+
+ it "rejects a signal from a room-eligible user without a participant session" do
+ sign_in(user)
+ establish_presence!(room, other_participant)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_signal(room, nil, recipient: other_participant)
+ end
+
+ expect(response.status).to eq(403)
+ expect(messages).to be_empty
+ end
+
+ it "rejects a pre-leave session after the user rejoined" do
+ sign_in(user)
+ establish_presence!(room, other_participant)
+
+ post "/voice/rooms/#{room.id}/join.json"
+ stale_session_id = response.parsed_body["participant_session_id"]
+
+ delete "/voice/rooms/#{room.id}/leave.json"
+ post "/voice/rooms/#{room.id}/join.json"
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_signal(room, stale_session_id, recipient: other_participant)
+ end
+
+ expect(response.status).to eq(403)
+ expect(messages).to be_empty
+ end
+
+ it "revokes signaling authority when the user is kicked" do
+ sign_in(user)
+ establish_presence!(room, other_participant)
+ post "/voice/rooms/#{room.id}/join.json"
+ session_id = response.parsed_body["participant_session_id"]
+
+ sign_in(staff)
+ delete "/voice/rooms/#{room.id}/kick.json", params: { user_id: user.id }
+
+ sign_in(user)
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_signal(room, session_id, recipient: other_participant)
+ end
+
+ expect(response.status).to eq(403)
+ expect(messages).to be_empty
+ end
+
+ it "discards messages to recipients without a live session and delivers the rest" do
+ sign_in(user)
+ session_id = establish_presence!(room, user)
+ establish_presence!(room, staff)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post "/voice/rooms/#{room.id}/signal.json",
+ params: {
+ payload: {
+ messages: [
+ { recipient_id: staff.id, events: [{ type: "offer", sdp: "v=0" }] },
+ {
+ recipient_id: other_participant.id,
+ events: [{ type: "offer", sdp: "v=0" }],
+ },
+ ],
+ },
+ participant_session_id: session_id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to eq([staff.id])
+ end
+
+ it "discards a queued offer to a recipient who left the room" do
+ sign_in(other_participant)
+ session_id = establish_presence!(room, other_participant)
+ establish_presence!(room, user)
+
+ sign_in(user)
+ delete "/voice/rooms/#{room.id}/leave.json"
+
+ sign_in(other_participant)
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ post_signal(room, session_id, recipient: user)
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages).to be_empty
+ end
+ end
+
+ describe "chat" do
+ fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.chat_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ room.update!(chat_channel_id: channel.id)
+ end
+
+ after do
+ Voice::ChatSession.clear(room.id)
+ Voice::ParticipantTracker.clear(room.id)
+ end
+
+ def join_room!(joining_user)
+ Voice::ParticipantTracker.add(room.id, joining_user.id)
+ end
+
+ describe "chat fields in the serialized room" do
+ # Below the create-rooms group threshold, so not a manager of anything.
+ fab!(:viewer) { Fabricate(:user, trust_level: TrustLevel[1]) }
+
+ it "hides all chat fields from a signed-in non-participant" do
+ sign_in(viewer)
+
+ get "/voice/rooms/#{room.id}.json"
+
+ room_json = response.parsed_body["room"]
+ expect(room_json.keys).not_to include(
+ "chat_available",
+ "chat_channel_id",
+ "chat_idle_minutes",
+ )
+ end
+
+ it "hides all chat fields from the anonymously-scoped directory broadcast" do
+ json = Voice::RoomSerializer.new(room, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json.keys).not_to include(:chat_available, :chat_channel_id, :chat_idle_minutes)
+ end
+
+ it "exposes availability — but not the settings — to a present participant" do
+ sign_in(viewer)
+ join_room!(viewer)
+
+ get "/voice/rooms/#{room.id}.json"
+
+ room_json = response.parsed_body["room"]
+ expect(room_json["chat_available"]).to eq(true)
+ expect(room_json.keys).not_to include("chat_channel_id", "chat_idle_minutes")
+ end
+
+ it "exposes the chat settings to a manager" do
+ sign_in(staff)
+
+ get "/voice/rooms/#{room.id}.json"
+
+ room_json = response.parsed_body["room"]
+ expect(room_json["chat_available"]).to eq(true)
+ expect(room_json["chat_channel_id"]).to eq(channel.id)
+ expect(room_json["chat_idle_minutes"]).to eq(15)
+ end
+ end
+
+ describe "#chat_session" do
+ it "returns the channel and an empty session before any chat" do
+ sign_in(user)
+ join_room!(user)
+
+ get "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channel_id"]).to eq(channel.id)
+ expect(response.parsed_body["thread_id"]).to be_nil
+ end
+
+ it "returns 403 when chat is disabled site-wide" do
+ SiteSetting.chat_enabled = false
+ sign_in(user)
+ join_room!(user)
+
+ get "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 when the room has no linked channel" do
+ room.update!(chat_channel_id: nil)
+ sign_in(user)
+ join_room!(user)
+
+ get "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 when signed in but not present in the voice room" do
+ sign_in(user)
+
+ get "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "requires authentication" do
+ get "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#ensure_chat_session" do
+ it "requires authentication" do
+ post "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 with the room's own message when signed in but not present" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(403)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("voice.errors.chat_requires_presence"),
+ )
+ end
+
+ it "follows the caller on the channel without creating a thread" do
+ sign_in(user)
+ join_room!(user)
+
+ post "/voice/rooms/#{room.id}/chat_session.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["channel_id"]).to eq(channel.id)
+ expect(response.parsed_body["thread_id"]).to be_nil
+ expect(Chat::Thread.where(channel_id: channel.id).count).to eq(0)
+
+ # Followed, so chat's own message endpoints accept the user's posts.
+ membership = channel.membership_for(user)
+ expect(membership).to be_present
+ expect(membership.following).to eq(true)
+ end
+ end
+
+ describe "#chat_message" do
+ it "requires authentication" do
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "hi" }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 with the room's own message when signed in but not present" do
+ sign_in(user)
+
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "hi" }
+
+ expect(response.status).to eq(403)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("voice.errors.chat_requires_presence"),
+ )
+ end
+
+ it "opens a thread rooted on the message and exposes it via GET" do
+ sign_in(user)
+ join_room!(user)
+
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "hello everyone" }
+
+ expect(response.status).to eq(200)
+ thread_id = response.parsed_body["thread_id"]
+ expect(thread_id).to be_present
+
+ thread = Chat::Thread.find(thread_id)
+ expect(thread.channel_id).to eq(channel.id)
+ expect(thread.original_message.message).to eq("In ##{room.slug}::room - hello everyone")
+ expect(thread.original_message.user_id).to eq(user.id)
+
+ get "/voice/rooms/#{room.id}/chat_session.json"
+ expect(response.parsed_body["thread_id"]).to eq(thread_id)
+ end
+
+ it "delivers a racing message to the live thread instead of a new one" do
+ sign_in(user)
+ join_room!(user)
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "first" }
+ thread_id = response.parsed_body["thread_id"]
+
+ sign_in(other_participant)
+ join_room!(other_participant)
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "second" }
+
+ expect(response.parsed_body["thread_id"]).to eq(thread_id)
+ expect(Chat::Thread.find(thread_id).replies.last.message).to eq("second")
+ end
+
+ it "does not bypass chat's per-user flood limit" do
+ RateLimiter.enable
+ SiteSetting.chat_allowed_messages_for_other_trust_levels = 1
+ sign_in(user)
+ join_room!(user)
+
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "one" }
+ expect(response.status).to eq(200)
+
+ # A second message within the window would be free if this endpoint
+ # skipped chat's limiter; it must be capped like normal chat.
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "two" }
+ expect(response.status).to eq(429)
+ end
+
+ it "surfaces the chat plugin's rejection reason as a 422, not a generic 403" do
+ channel.update!(threading_enabled: false)
+ sign_in(user)
+ join_room!(user)
+
+ post "/voice/rooms/#{room.id}/chat_message.json", params: { message: "hello" }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"].join).to match(/threading/i)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/serializers/voice_user_card_serializer_spec.rb b/plugins/voice/spec/serializers/voice_user_card_serializer_spec.rb
new file mode 100644
index 00000000000..8ae43db092a
--- /dev/null
+++ b/plugins/voice/spec/serializers/voice_user_card_serializer_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe UserCardSerializer do
+ fab!(:viewer) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:target) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ end
+
+ def serialize(user, scope_user)
+ described_class.new(user, scope: scope_user.guardian, root: false).as_json
+ end
+
+ describe "#voice_can_call" do
+ it "is true for a callable user when the viewer may start direct calls, false for oneself" do
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+
+ expect(serialize(target, viewer)[:voice_can_call]).to eq(true)
+ expect(serialize(viewer, viewer)[:voice_can_call]).to eq(false)
+ end
+
+ it "is false for a target outside the voice-room groups" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ outsider = Fabricate(:user, trust_level: TrustLevel[0])
+
+ expect(serialize(outsider, viewer)[:voice_can_call]).to eq(false)
+ end
+
+ it "is false when the target has muted the viewer" do
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ MutedUser.create!(user_id: target.id, muted_user_id: viewer.id)
+
+ expect(serialize(target, viewer)[:voice_can_call]).to eq(false)
+ end
+
+ it "is false when the target does not accept personal messages from the viewer" do
+ SiteSetting.voice_direct_calls_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]
+ target.user_option.update!(allow_private_messages: false)
+
+ expect(serialize(target, viewer)[:voice_can_call]).to eq(false)
+ end
+
+ it "is omitted entirely when direct calls are disabled (the default)" do
+ expect(serialize(target, viewer)).not_to have_key(:voice_can_call)
+ end
+ end
+end
diff --git a/plugins/voice/spec/services/voice/badge_granter_hooks_spec.rb b/plugins/voice/spec/services/voice/badge_granter_hooks_spec.rb
new file mode 100644
index 00000000000..f069d38ba72
--- /dev/null
+++ b/plugins/voice/spec/services/voice/badge_granter_hooks_spec.rb
@@ -0,0 +1,284 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Voice::BadgeGranterHooks do
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room, :voice_room) { Fabricate(:voice_room, public: true, max_participants: 3) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_badges_enabled = true
+ SiteSetting.voice_analytics_enabled = true
+ SeedFu.seed(Rails.root.join("plugins/voice/db/fixtures"))
+ described_class.enable_all!
+ end
+
+ describe ".on_leave" do
+ def build_session(joined_at:, left_at:)
+ Voice::Session.create!(user: user, room: room, joined_at: joined_at, left_at: left_at)
+ end
+
+ describe "Mic Check" do
+ it "grants when session is 30+ seconds and others are in the room" do
+ other = Fabricate(:user)
+ Voice::ParticipantTracker.add(room.id, other.id)
+
+ session = build_session(joined_at: 1.minute.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).to include("Mic Check")
+ end
+
+ it "does not grant when session is under 30 seconds" do
+ other = Fabricate(:user)
+ Voice::ParticipantTracker.add(room.id, other.id)
+
+ session = build_session(joined_at: 20.seconds.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).not_to include("Mic Check")
+ end
+
+ it "does not grant when room is empty" do
+ session = build_session(joined_at: 1.minute.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).not_to include("Mic Check")
+ end
+ end
+
+ describe "Night Owl" do
+ it "grants when session started between midnight and 5 AM in user timezone" do
+ user.user_option.update!(timezone: "America/New_York")
+ # 2 AM in New York
+ joined = Time.zone.parse("2026-03-06 07:00:00 UTC")
+ left = joined + 5.minutes
+
+ session = build_session(joined_at: joined, left_at: left)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).to include("Night Owl")
+ end
+
+ it "does not grant during daytime hours" do
+ user.user_option.update!(timezone: "UTC")
+ joined = Time.zone.parse("2026-03-06 14:00:00 UTC")
+ left = joined + 5.minutes
+
+ session = build_session(joined_at: joined, left_at: left)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).not_to include("Night Owl")
+ end
+ end
+
+ describe "Early Bird" do
+ it "grants when session started between 5 AM and 9 AM in user timezone" do
+ user.user_option.update!(timezone: "UTC")
+ joined = Time.zone.parse("2026-03-06 06:00:00 UTC")
+ left = joined + 5.minutes
+
+ session = build_session(joined_at: joined, left_at: left)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).to include("Early Bird")
+ end
+ end
+
+ describe "Marathoner" do
+ it "grants when session lasted 4+ hours" do
+ session = build_session(joined_at: 5.hours.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).to include("Marathoner")
+ end
+
+ it "does not grant for shorter sessions" do
+ session = build_session(joined_at: 3.hours.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges.pluck(:name)).not_to include("Marathoner")
+ end
+ end
+
+ it "does nothing when badges are disabled" do
+ SiteSetting.voice_badges_enabled = false
+
+ session = build_session(joined_at: 5.hours.ago, left_at: Time.current)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges).to be_empty
+ end
+
+ it "does nothing when session has no left_at" do
+ session = Voice::Session.create!(user: user, room: room, joined_at: 5.hours.ago)
+ described_class.on_leave(user, session, room: room)
+
+ expect(user.badges).to be_empty
+ end
+ end
+
+ describe ".on_join" do
+ describe "Packed House" do
+ it "grants when room reaches max capacity" do
+ other1 = Fabricate(:user)
+ other2 = Fabricate(:user)
+ participants = User.where(id: [user.id, other1.id, other2.id])
+
+ described_class.on_join(user, room, participants)
+
+ expect(user.badges.pluck(:name)).to include("Packed House")
+ end
+
+ it "does not grant when room has no max_participants" do
+ room.update!(max_participants: nil)
+ participants = User.where(id: [user.id])
+
+ described_class.on_join(user, room, participants)
+
+ expect(user.badges.pluck(:name)).not_to include("Packed House")
+ end
+ end
+
+ describe "Icebreaker" do
+ fab!(:stranger, :user)
+
+ it "grants when user has no co-presence history with anyone in the room" do
+ Voice::ParticipantTracker.add(room.id, stranger.id)
+ participants = User.where(id: [user.id, stranger.id])
+
+ described_class.on_join(user, room, participants)
+
+ expect(user.badges.pluck(:name)).to include("Icebreaker")
+ end
+
+ it "does not grant when user has co-presence history" do
+ ids = [user.id, stranger.id].sort
+ Voice::CoPresence.create!(
+ user_id_1: ids.first,
+ user_id_2: ids.last,
+ date: Date.current,
+ total_seconds: 60,
+ session_count: 1,
+ )
+ participants = User.where(id: [user.id, stranger.id])
+
+ described_class.on_join(user, room, participants)
+
+ expect(user.badges.pluck(:name)).not_to include("Icebreaker")
+ end
+
+ it "does not grant when user is alone in the room" do
+ participants = User.where(id: [user.id])
+
+ described_class.on_join(user, room, participants)
+
+ expect(user.badges.pluck(:name)).not_to include("Icebreaker")
+ end
+ end
+ end
+
+ describe ".on_room_create" do
+ it "grants Host badge" do
+ described_class.on_room_create(user)
+
+ expect(user.badges.pluck(:name)).to include("Host")
+ end
+
+ it "does nothing when badges are disabled" do
+ SiteSetting.voice_badges_enabled = false
+
+ described_class.on_room_create(user)
+
+ expect(user.badges).to be_empty
+ end
+ end
+
+ describe ".on_invite_redeemed" do
+ fab!(:invitee) { Fabricate(:user, trust_level: TrustLevel[2]) }
+
+ def redeemed_invite
+ Voice::Invite.create!(
+ room_id: room.id,
+ user_id: invitee.id,
+ invited_by_id: user.id,
+ redeemed_at: Time.current,
+ )
+ end
+
+ it "grants Plus One to the inviter" do
+ described_class.on_invite_redeemed(redeemed_invite)
+
+ expect(user.badges.pluck(:name)).to include("Plus One")
+ expect(invitee.badges).to be_empty
+ end
+
+ it "does nothing when badges are disabled" do
+ SiteSetting.voice_badges_enabled = false
+
+ described_class.on_invite_redeemed(redeemed_invite)
+
+ expect(user.badges).to be_empty
+ end
+ end
+
+ describe "fixture seeding" do
+ def voice_badges
+ Badge.joins(:badge_grouping).where(badge_groupings: { name: "Voice" })
+ end
+
+ it "creates all badges as disabled" do
+ described_class.disable_all!
+
+ expect(voice_badges.count).to eq(27)
+ expect(voice_badges.where(enabled: true).count).to eq(0)
+ end
+
+ it "creates the Voice badge grouping" do
+ expect(BadgeGrouping.exists?(name: "Voice")).to eq(true)
+ end
+
+ it "is idempotent" do
+ expect { SeedFu.seed(Rails.root.join("plugins/voice/db/fixtures")) }.not_to change {
+ Badge.count
+ }
+ end
+
+ it "sets SQL queries on scheduled badges" do
+ expect(Badge.find_by(name: "Rookie").query).to include("voice_sessions")
+ expect(Badge.find_by(name: "Social Butterfly").query).to include("voice_co_presences")
+ end
+
+ it "does not set queries on instant badges" do
+ %w[Mic\ Check Host Icebreaker Packed\ House Night\ Owl Early\ Bird Marathoner].each do |name|
+ expect(Badge.find_by(name: name).query).to be_nil, "Expected #{name} to have no query"
+ end
+ end
+
+ it "allows gold badges to be used as title" do
+ gold_badges = voice_badges.where(badge_type_id: BadgeType::Gold)
+ expect(gold_badges).to all(have_attributes(allow_title: true))
+ end
+ end
+
+ describe ".enable_all!" do
+ before { described_class.disable_all! }
+
+ it "enables all Voice badges" do
+ described_class.enable_all!
+
+ voice_badges = Badge.joins(:badge_grouping).where(badge_groupings: { name: "Voice" })
+ expect(voice_badges.where(enabled: false).count).to eq(0)
+ end
+ end
+
+ describe ".disable_all!" do
+ it "disables all Voice badges" do
+ described_class.disable_all!
+
+ voice_badges = Badge.joins(:badge_grouping).where(badge_groupings: { name: "Voice" })
+ expect(voice_badges.where(enabled: true).count).to eq(0)
+ end
+ end
+end
diff --git a/plugins/voice/spec/services/voice/chat_session_spec.rb b/plugins/voice/spec/services/voice/chat_session_spec.rb
new file mode 100644
index 00000000000..079a5224cab
--- /dev/null
+++ b/plugins/voice/spec/services/voice/chat_session_spec.rb
@@ -0,0 +1,294 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260630183841_add_chat_settings_to_voice_rooms"
+
+RSpec.describe Voice::ChatSession do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :chat_channel_id)
+ AddChatSettingsToVoiceRooms.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ end
+
+ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:other) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_chat_enabled = true
+ SiteSetting.chat_enabled = true
+ SiteSetting.chat_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ room.update!(chat_channel_id: channel.id, chat_idle_minutes: 15)
+ described_class.clear(room.id)
+ end
+
+ after { described_class.clear(room.id) }
+
+ def live_thread(state = described_class.state(room))
+ ::Chat::Thread.find(state[:thread_id])
+ end
+
+ def post_reply!(thread_id, poster, text)
+ result =
+ ::Chat::CreateMessage.call(
+ guardian: poster.guardian,
+ params: {
+ chat_channel_id: channel.id,
+ thread_id: thread_id,
+ message: text,
+ },
+ options: {
+ enforce_membership: true,
+ },
+ )
+ raise "reply failed: #{Service::StepsInspector.new(result).inspect}" unless result.success?
+ result.message_instance
+ end
+
+ describe ".available_for?" do
+ it "is false without a linked channel" do
+ room.update!(chat_channel_id: nil)
+ expect(described_class.available_for?(room, user.guardian)).to eq(false)
+ end
+
+ it "is false when chat is disabled" do
+ SiteSetting.chat_enabled = false
+ expect(described_class.available_for?(room, user.guardian)).to eq(false)
+ end
+
+ it "is true with a linked channel and a chat-allowed user" do
+ expect(described_class.available_for?(room, user.guardian)).to eq(true)
+ end
+ end
+
+ describe ".state" do
+ it "returns the channel with no thread before a session starts" do
+ expect(described_class.state(room)).to eq({ channel_id: channel.id, thread_id: nil })
+ end
+ end
+
+ describe ".start!" do
+ it "creates no thread and posts no message" do
+ expect { described_class.start!(room, user) }.not_to change { ::Chat::Thread.count }
+ expect(channel.chat_messages.count).to eq(0)
+ expect(described_class.state(room)[:thread_id]).to be_nil
+ end
+
+ it "follows the caller on the channel so chat's own endpoints accept their posts" do
+ described_class.start!(room, user)
+
+ membership = channel.membership_for(user)
+ expect(membership).to be_present
+ expect(membership.following).to eq(true)
+ end
+
+ it "re-follows a caller who had unfollowed the channel" do
+ described_class.start!(room, user)
+ ::Chat::ChannelMembershipManager.new(channel).unfollow(user)
+
+ described_class.start!(room, user)
+ expect(channel.membership_for(user).following).to eq(true)
+ end
+
+ it "broadcasts nothing" do
+ published = []
+ allow(MessageBus).to receive(:publish) { |ch, data, opts| published << [ch, data, opts] }
+
+ described_class.start!(room, user)
+
+ expect(published.select { |ch, _, _| ch == Voice.room_chat_channel(room.id) }).to be_empty
+ end
+ end
+
+ describe ".post_message!" do
+ it "opens a thread rooted on the first message, prefixed with a room hashtag linking back" do
+ state = described_class.post_message!(room, user, "hello everyone")
+
+ thread = live_thread(state)
+ expect(thread.channel_id).to eq(channel.id)
+ expect(thread.title).to eq("Voice chat in #{room.name}")
+ expect(thread.original_message.message).to eq("In ##{room.slug}::room - hello everyone")
+ expect(thread.original_message.cooked).to include("/voice/r/#{room.slug}")
+ expect(thread.original_message.user_id).to eq(user.id)
+ expect(thread.custom_fields[Voice::THREAD_ROOM_ID_FIELD]).to eq(room.id.to_s)
+ end
+
+ it "inserts a first message containing interpolation tokens literally" do
+ state = described_class.post_message!(room, user, "see %{room} and \\1")
+
+ expect(live_thread(state).original_message.message).to eq(
+ "In ##{room.slug}::room - see %{room} and \\1",
+ )
+ end
+
+ it "inserts a room name containing replacement escapes literally into the title" do
+ room.update!(name: "Studio \\& \\1")
+
+ thread = live_thread(described_class.post_message!(room, user, "hello everyone"))
+ expect(thread.title).to eq("Voice chat in Studio \\& \\1")
+ end
+
+ it "delivers to the live thread instead of spawning a competing one" do
+ first = described_class.post_message!(room, user, "first")
+
+ # A second panel that raced the broadcast still believed no thread
+ # existed — its message must land in the session thread as a reply.
+ second = described_class.post_message!(room, other, "second")
+
+ expect(second[:thread_id]).to eq(first[:thread_id])
+ thread = live_thread(second)
+ expect(thread.replies.last.message).to eq("second")
+ expect(thread.replies.last.user_id).to eq(other.id)
+ end
+
+ it "broadcasts only when a thread is actually opened" do
+ published = []
+ allow(MessageBus).to receive(:publish) { |ch, data, opts| published << [ch, data, opts] }
+
+ described_class.post_message!(room, user, "first")
+ described_class.post_message!(room, other, "second")
+
+ chat_events = published.select { |ch, _, _| ch == Voice.room_chat_channel(room.id) }
+ expect(chat_events.size).to eq(1)
+ end
+
+ # publish_state's audience is the room's (anyone who can see the voice
+ # room), which can be broader than who's authorized for the linked chat
+ # channel — so the payload itself must never carry message content or
+ # thread/channel identifiers. Clients re-fetch through the guarded
+ # chat_session endpoint instead, which re-checks channel access per user.
+ it "never publishes message content or thread/channel identifiers" do
+ published = []
+ allow(MessageBus).to receive(:publish) { |ch, data, opts| published << [ch, data, opts] }
+
+ described_class.post_message!(room, user, "sensitive content")
+
+ chat_events = published.select { |ch, _, _| ch == Voice.room_chat_channel(room.id) }
+ expect(chat_events).to be_present
+ chat_events.each { |_, data, _| expect(data).to eq({ type: "updated" }) }
+ end
+
+ it "rolls over to a fresh thread after the session goes idle and empty" do
+ first = described_class.post_message!(room, user, "first")
+
+ # No messages and no heartbeats for longer than the room's timeout: the
+ # session has gone idle and empty.
+ freeze_time(31.minutes.from_now) do
+ rolled = described_class.post_message!(room, other, "later")
+ expect(rolled[:thread_id]).to be_present
+ expect(rolled[:thread_id]).not_to eq(first[:thread_id])
+ end
+ end
+
+ it "keeps the session alive while its thread has recent messages" do
+ first = described_class.post_message!(room, user, "first")
+
+ # Later messages flow through chat's own API; liveness must still follow
+ # them even though Voice never sees the posts.
+ freeze_time(20.minutes.from_now) { post_reply!(first[:thread_id], user, "still chatting") }
+
+ freeze_time(30.minutes.from_now) do
+ expect(described_class.post_message!(room, other, "me too")[:thread_id]).to eq(
+ first[:thread_id],
+ )
+ end
+ end
+
+ it "keeps the session alive while participants are present (heartbeat)" do
+ first = described_class.post_message!(room, user, "first")
+
+ # A heartbeat within the timeout keeps the session warm...
+ freeze_time(10.minutes.from_now) { described_class.touch!(room) }
+
+ # ...so a message a bit later still lands in the same thread.
+ freeze_time(20.minutes.from_now) do
+ expect(described_class.post_message!(room, user, "still here")[:thread_id]).to eq(
+ first[:thread_id],
+ )
+ end
+ end
+
+ it "does not let a late heartbeat revive an already-idle session" do
+ first = described_class.post_message!(room, user, "first")
+
+ # The session has already gone idle and empty; a heartbeat from a
+ # returning joiner must not resurrect it.
+ freeze_time(31.minutes.from_now) do
+ described_class.touch!(room)
+ expect(described_class.post_message!(room, user, "later")[:thread_id]).not_to eq(
+ first[:thread_id],
+ )
+ end
+ end
+
+ it "abandons a thread whose original message was deleted" do
+ first = described_class.post_message!(room, user, "first")
+ live_thread(first).original_message.trash!(Discourse.system_user)
+
+ expect(described_class.state(room)[:thread_id]).to be_nil
+
+ fresh = described_class.post_message!(room, other, "again")
+ expect(fresh[:thread_id]).to be_present
+ expect(fresh[:thread_id]).not_to eq(first[:thread_id])
+ end
+
+ it "surfaces the chat plugin's own error when a message is rejected" do
+ # The opener is prefixed with the room hashtag, so the collision needs
+ # two identical replies rather than an opener and a reply.
+ described_class.post_message!(room, user, "opener")
+ described_class.post_message!(room, user, "dup")
+
+ # The chat plugin blocks an identical message posted seconds apart; that
+ # reason must reach the caller, not be masked as a generic access error.
+ expect { described_class.post_message!(room, user, "dup") }.to raise_error(
+ Voice::ChatSession::Error,
+ /identical message/i,
+ )
+ end
+
+ it "raises a clear error without orphaning the message when threading is off" do
+ channel.update!(threading_enabled: false)
+ # The room memoizes its channel per instance (a fresh load in production
+ # requests); pick the flip up here explicitly.
+ room.reload
+
+ expect { described_class.post_message!(room, user, "hello") }.to raise_error(
+ Voice::ChatSession::Error,
+ /threading/i,
+ )
+
+ # The message must not be left behind as a loose channel message.
+ expect(channel.chat_messages.count).to eq(0)
+ expect(described_class.state(room)[:thread_id]).to be_nil
+ end
+ end
+
+ describe ".touch!" do
+ it "is a no-op when there is no live session" do
+ described_class.touch!(room)
+ expect(Discourse.redis.get("voice:room:#{room.id}:chat_seen_at")).to be_nil
+ end
+
+ it "refreshes the session key TTL so a long quiet session isn't dropped" do
+ described_class.post_message!(room, user, "hello")
+ thread_key = "voice:room:#{room.id}:chat_thread"
+
+ Discourse.redis.expire(thread_key, 60)
+ described_class.touch!(room)
+
+ expect(Discourse.redis.ttl(thread_key)).to be > 60
+ end
+ end
+end
diff --git a/plugins/voice/spec/services/voice/default_room_seeder_spec.rb b/plugins/voice/spec/services/voice/default_room_seeder_spec.rb
new file mode 100644
index 00000000000..78cdfdb9ef3
--- /dev/null
+++ b/plugins/voice/spec/services/voice/default_room_seeder_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+
+RSpec.describe Voice::DefaultRoomSeeder do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ end
+ end
+
+ before { wipe_rooms! }
+
+ it "creates a Watercooler room when voice is enabled and no rooms exist" do
+ SiteSetting.voice_enabled = true
+ wipe_rooms!
+
+ expect { described_class.ensure! }.to change { Voice::Room.count }.by(1)
+
+ room = Voice::Room.first
+ expect(room.name).to eq("Watercooler")
+ expect(room.public).to eq(true)
+ end
+
+ it "does nothing if voice is disabled" do
+ SiteSetting.voice_enabled = false
+
+ expect { described_class.ensure! }.not_to change { Voice::Room.count }
+ end
+
+ it "still seeds when only ephemeral rooms exist" do
+ SiteSetting.voice_enabled = true
+ wipe_rooms!
+ Fabricate(:voice_ephemeral_room, creator: Fabricate(:admin))
+
+ expect { described_class.ensure! }.to change { Voice::Room.persistent.count }.by(1)
+ end
+
+ it "does nothing if rooms already exist" do
+ SiteSetting.voice_enabled = true
+ wipe_rooms!
+ Fabricate(:voice_room, name: "Existing", creator: Fabricate(:admin))
+
+ expect { described_class.ensure! }.not_to change { Voice::Room.count }
+ end
+
+ def wipe_rooms!
+ Voice::RoomMembership.delete_all
+ Voice::Room.delete_all
+ end
+end
diff --git a/plugins/voice/spec/services/voice/directory_broadcaster_spec.rb b/plugins/voice/spec/services/voice/directory_broadcaster_spec.rb
new file mode 100644
index 00000000000..dafbc5b32a2
--- /dev/null
+++ b/plugins/voice/spec/services/voice/directory_broadcaster_spec.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::DirectoryBroadcaster do
+ before { SiteSetting.voice_enabled = true }
+
+ it "reaches anonymous subscribers through the anonymous_users pseudogroup when they are admitted" do
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ room = Fabricate(:voice_room, public: true)
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.broadcast(action: :updated, room: room)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.group_ids).to contain_exactly(
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ )
+
+ # Anonymous message-bus clients carry only the anonymous_users
+ # pseudo-group (see config/initializers/004-message_bus.rb).
+ anonymous_client =
+ MessageBus::Client.new(
+ client_id: "anonymous",
+ user_id: nil,
+ group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ expect(anonymous_client.allowed?(messages.first)).to eq(true)
+ end
+
+ it "excludes anonymous subscribers when allowed groups are logged_in_users" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:logged_in_users].to_s
+ room = Fabricate(:voice_room, public: true)
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.broadcast(action: :updated, room: room)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.group_ids).to contain_exactly(Group::AUTO_GROUPS[:logged_in_users])
+
+ # Subscriber-level check with the group ids real clients get from
+ # config/initializers/004-message_bus.rb: logged-in clients carry the
+ # logged_in_users pseudo-group, anonymous clients only anonymous_users.
+ logged_in_client =
+ MessageBus::Client.new(
+ client_id: "logged-in",
+ user_id: room.creator_id,
+ group_ids: [Group::AUTO_GROUPS[:logged_in_users]],
+ )
+ anonymous_client =
+ MessageBus::Client.new(
+ client_id: "anonymous",
+ user_id: nil,
+ group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+
+ expect(logged_in_client.allowed?(messages.first)).to eq(true)
+ expect(anonymous_client.allowed?(messages.first)).to eq(false)
+ end
+
+ it "targets the anonymous_users pseudogroup when only anonymous access is configured" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:anonymous_users].to_s
+ room = Fabricate(:voice_room, public: true)
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.broadcast(action: :updated, room: room)
+ end
+
+ expect(messages.first.user_ids).to be_nil
+ expect(messages.first.group_ids).to contain_exactly(Group::AUTO_GROUPS[:anonymous_users])
+ end
+
+ it "targets members for private room events" do
+ room = Fabricate(:voice_room, public: false)
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.broadcast(action: :updated, room: room)
+ end
+
+ expect(messages.first.user_ids).to contain_exactly(room.creator_id)
+ end
+
+ it "never publishes events for ephemeral rooms" do
+ room = Fabricate(:voice_ephemeral_room, public: true)
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.broadcast(action: :created, room: room)
+ end
+
+ expect(messages).to be_empty
+ end
+end
diff --git a/plugins/voice/spec/services/voice/ephemeral_room_manager_spec.rb b/plugins/voice/spec/services/voice/ephemeral_room_manager_spec.rb
new file mode 100644
index 00000000000..fc74c341e7b
--- /dev/null
+++ b/plugins/voice/spec/services/voice/ephemeral_room_manager_spec.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::EphemeralRoomManager do
+ fab!(:creator, :user)
+ fab!(:member, :user)
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe ".create!" do
+ it "creates an ephemeral room with the creator as moderator and members as participants" do
+ room = described_class.create!(creator: creator, name: "Call", members: [member, creator])
+
+ expect(room.ephemeral).to eq(true)
+ expect(room.public).to eq(false)
+ expect(room.last_occupied_at).to be_present
+ expect(room.room_memberships.moderator.pluck(:user_id)).to contain_exactly(creator.id)
+ expect(room.member_ids).to contain_exactly(creator.id, member.id)
+ end
+
+ it "generates slugs that never collide with existing rooms of the same name" do
+ persistent = Fabricate(:voice_room, name: "Call")
+ first = described_class.create!(creator: creator, name: "Call")
+ second = described_class.create!(creator: creator, name: "Call")
+
+ expect([persistent.slug, first.slug, second.slug].uniq.size).to eq(3)
+ expect(first.slug).to start_with("call-")
+ end
+
+ it "makes all parties moderators when passed as such, so any of them can invite" do
+ room = described_class.create!(creator: creator, name: "Call", moderators: [member, creator])
+
+ expect(room.moderator_ids).to contain_exactly(creator.id, member.id)
+ expect(member.guardian.can_manage_voice_room?(room)).to eq(true)
+ end
+
+ it "keeps the moderator role for a user listed as both moderator and member" do
+ room =
+ described_class.create!(
+ creator: creator,
+ name: "Call",
+ members: [member],
+ moderators: [member],
+ )
+
+ expect(room.moderator_ids).to contain_exactly(creator.id, member.id)
+ end
+
+ it "caps how many live ephemeral rooms one creator can accumulate" do
+ stub_const(described_class, :MAX_LIVE_ROOMS_PER_CREATOR, 2) do
+ 2.times { |i| described_class.create!(creator: creator, name: "Call #{i}") }
+
+ expect { described_class.create!(creator: creator, name: "One too many") }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ expect(Voice::Room.ephemeral.where(creator_id: creator.id).count).to eq(2)
+ end
+ end
+
+ it "does not count other creators' rooms against the cap" do
+ stub_const(described_class, :MAX_LIVE_ROOMS_PER_CREATOR, 1) do
+ described_class.create!(creator: member, name: "Someone else's call")
+
+ expect(described_class.create!(creator: creator, name: "Call")).to be_persisted
+ end
+ end
+
+ it "passes room attributes through" do
+ room =
+ described_class.create!(
+ creator: creator,
+ name: "Event stage",
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ )
+
+ expect(room.public).to eq(true)
+ expect(room.stage?).to eq(true)
+ end
+
+ it "does not broadcast a directory event" do
+ messages =
+ MessageBus.track_publish(Voice.room_index_channel) do
+ described_class.create!(creator: creator, name: "Call", members: [member])
+ end
+
+ expect(messages).to be_empty
+ end
+ end
+
+ describe ".cleanup!" do
+ fab!(:persistent_room, :voice_room)
+
+ before { SiteSetting.voice_ephemeral_room_ttl_minutes = 30 }
+
+ it "destroys an ephemeral room empty past the TTL and clears its live state" do
+ room = Fabricate(:voice_ephemeral_room, last_occupied_at: 31.minutes.ago)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ described_class.cleanup!
+
+ expect(Voice::Room.exists?(room.id)).to eq(false)
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to be_nil
+ end
+
+ it "uses created_at when the room was never occupied" do
+ room = Fabricate(:voice_ephemeral_room, last_occupied_at: nil, created_at: 31.minutes.ago)
+
+ described_class.cleanup!
+
+ expect(Voice::Room.exists?(room.id)).to eq(false)
+ end
+
+ it "keeps an ephemeral room emptied more recently than the TTL" do
+ room = Fabricate(:voice_ephemeral_room, last_occupied_at: 5.minutes.ago)
+
+ described_class.cleanup!
+
+ expect(Voice::Room.exists?(room.id)).to eq(true)
+ end
+
+ it "resets the clock on an occupied ephemeral room instead of destroying it" do
+ room = Fabricate(:voice_ephemeral_room, last_occupied_at: 31.minutes.ago)
+ Voice::ParticipantTracker.add(room.id, Fabricate(:user).id)
+
+ described_class.cleanup!
+
+ expect(room.reload.last_occupied_at).to be_within(1.minute).of(Time.current)
+ end
+
+ it "never touches persistent rooms" do
+ persistent_room.update_column(:last_occupied_at, 2.days.ago)
+
+ expect { described_class.cleanup! }.not_to change { Voice::Room.persistent.count }
+ end
+ end
+
+ describe ".destroy!" do
+ it "refuses to tear down a persistent room" do
+ room = Fabricate(:voice_room)
+
+ expect { described_class.destroy!(room) }.to raise_error(Discourse::InvalidParameters)
+ expect(Voice::Room.exists?(room.id)).to eq(true)
+ end
+ end
+end
diff --git a/plugins/voice/spec/services/voice/participant_tracker_spec.rb b/plugins/voice/spec/services/voice/participant_tracker_spec.rb
new file mode 100644
index 00000000000..845ca5bcfaf
--- /dev/null
+++ b/plugins/voice/spec/services/voice/participant_tracker_spec.rb
@@ -0,0 +1,368 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::ParticipantTracker do
+ fab!(:room, :voice_room)
+ fab!(:user1, :user)
+ fab!(:user2, :user)
+
+ before { SiteSetting.voice_enabled = true }
+
+ after { described_class.clear(room.id) }
+
+ describe ".add" do
+ it "stores the user in the room's participant set" do
+ described_class.add(room.id, user1.id)
+ expect(described_class.user_ids(room.id)).to contain_exactly(user1.id)
+ end
+
+ it "ignores invalid user ids" do
+ described_class.add(room.id, 0)
+ described_class.add(room.id, -1)
+ expect(described_class.user_ids(room.id)).to be_empty
+ end
+ end
+
+ describe ".remove" do
+ it "removes the user from participants and metadata" do
+ described_class.add(room.id, user1.id)
+ described_class.update_metadata(room.id, user1.id, { role: "participant" })
+
+ described_class.remove(room.id, user1.id)
+
+ expect(described_class.user_ids(room.id)).to be_empty
+ expect(described_class.get_metadata(room.id, user1.id)).to eq({})
+ end
+
+ it "revokes the participant session" do
+ described_class.add(room.id, user1.id)
+ session_id = described_class.create_participant_session!(room.id, user1.id)
+
+ described_class.remove(room.id, user1.id)
+
+ expect(described_class.valid_participant_session?(room.id, user1.id, session_id)).to eq(false)
+ expect(described_class.participant_session?(room.id, user1.id)).to eq(false)
+ end
+ end
+
+ describe ".add_within_capacity" do
+ it "admits users until the capacity is reached, then returns :full" do
+ expect(described_class.add_within_capacity(room.id, user1.id, 2)).to eq(:added)
+ expect(described_class.add_within_capacity(room.id, user2.id, 2)).to eq(:added)
+
+ expect(described_class.add_within_capacity(room.id, 999, 2)).to eq(:full)
+ expect(described_class.user_ids(room.id)).to contain_exactly(user1.id, user2.id)
+ end
+
+ it "refreshes an existing participant even when the room is full" do
+ described_class.add_within_capacity(room.id, user1.id, 2)
+ described_class.add_within_capacity(room.id, user2.id, 2)
+
+ expect(described_class.add_within_capacity(room.id, user1.id, 2)).to eq(:existing)
+ expect(described_class.user_ids(room.id)).to contain_exactly(user1.id, user2.id)
+ end
+
+ it "frees slots held by expired presence" do
+ described_class.add_within_capacity(room.id, user1.id, 2)
+ described_class.add_within_capacity(room.id, user2.id, 2)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user1.id)
+
+ expect(described_class.add_within_capacity(room.id, 999, 2)).to eq(:added)
+ expect(described_class.user_ids(room.id)).to contain_exactly(user2.id, 999)
+ end
+
+ it "never admits concurrent joiners past the capacity" do
+ results =
+ (1..10)
+ .map do |candidate_id|
+ Thread.new { described_class.add_within_capacity(room.id, candidate_id, 3) }
+ end
+ .map(&:value)
+
+ expect(results.count(:added)).to eq(3)
+ expect(results.count(:full)).to eq(7)
+ expect(described_class.user_ids(room.id).size).to eq(3)
+ end
+
+ it "rejects invalid user ids" do
+ expect(described_class.add_within_capacity(room.id, 0, 2)).to eq(:full)
+ expect(described_class.user_ids(room.id)).to be_empty
+ end
+ end
+
+ describe ".mark_left" do
+ it "reports a recent departure until cleared" do
+ described_class.mark_left(room.id, user1.id)
+
+ expect(described_class.recently_left?(room.id, user1.id)).to eq(true)
+ expect(described_class.recently_left?(room.id, user2.id)).to eq(false)
+
+ described_class.clear_left(room.id, user1.id)
+
+ expect(described_class.recently_left?(room.id, user1.id)).to eq(false)
+ end
+ end
+
+ describe ".create_participant_session!" do
+ it "mints a session that validates only for the exact id" do
+ session_id = described_class.create_participant_session!(room.id, user1.id)
+
+ expect(described_class.valid_participant_session?(room.id, user1.id, session_id)).to eq(true)
+ expect(described_class.valid_participant_session?(room.id, user1.id, "other")).to eq(false)
+ expect(described_class.valid_participant_session?(room.id, user1.id, nil)).to eq(false)
+ expect(described_class.valid_participant_session?(room.id, user2.id, session_id)).to eq(false)
+ end
+
+ it "invalidates the previous session when a new one is minted" do
+ first_session_id = described_class.create_participant_session!(room.id, user1.id)
+ second_session_id = described_class.create_participant_session!(room.id, user1.id)
+
+ expect(described_class.valid_participant_session?(room.id, user1.id, first_session_id)).to eq(
+ false,
+ )
+ expect(
+ described_class.valid_participant_session?(room.id, user1.id, second_session_id),
+ ).to eq(true)
+ end
+
+ it "expires with the session TTL" do
+ session_id = described_class.create_participant_session!(room.id, user1.id)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participant_session:#{user1.id}"
+ expect(Discourse.redis.ttl(key)).to be_between(1, described_class.participant_session_ttl)
+
+ Discourse.redis.del(key)
+
+ expect(described_class.valid_participant_session?(room.id, user1.id, session_id)).to eq(false)
+ end
+ end
+
+ describe ".raise_hand" do
+ it "sets the raise timestamp and returns true on the first raise" do
+ freeze_time do
+ expect(described_class.raise_hand(room.id, user1.id)).to eq(true)
+
+ # The timestamp round-trips through JSON, which can shave float digits.
+ expect(described_class.get_metadata(room.id, user1.id)[:hand_raised_at]).to be_within(
+ 0.001,
+ ).of(Time.now.to_f)
+ end
+ end
+
+ it "returns false and keeps the original timestamp when already raised" do
+ described_class.raise_hand(room.id, user1.id)
+ original = described_class.get_metadata(room.id, user1.id)[:hand_raised_at]
+
+ expect(described_class.raise_hand(room.id, user1.id)).to eq(false)
+ expect(described_class.get_metadata(room.id, user1.id)[:hand_raised_at]).to eq(original)
+ end
+ end
+
+ describe ".lower_hand" do
+ it "clears the raised hand and returns true" do
+ described_class.raise_hand(room.id, user1.id)
+
+ expect(described_class.lower_hand(room.id, user1.id)).to eq(true)
+ expect(described_class.get_metadata(room.id, user1.id)[:hand_raised_at]).to be_nil
+ end
+
+ it "returns false when the hand is not raised" do
+ expect(described_class.lower_hand(room.id, user1.id)).to eq(false)
+ end
+ end
+
+ describe ".pin_transport!" do
+ it "pins the first transport and keeps it under a race" do
+ expect(described_class.pin_transport!(room.id, "livekit")).to eq("livekit")
+
+ # A concurrent joiner resolving differently must get the pinned value.
+ expect(described_class.pin_transport!(room.id, "mesh")).to eq("livekit")
+ expect(described_class.pinned_transport(room.id)).to eq("livekit")
+ end
+
+ it "expires on its own so a crashed room self-heals" do
+ described_class.pin_transport!(room.id, "livekit")
+
+ ttl = Discourse.redis.ttl("#{described_class::KEY_NAMESPACE}:#{room.id}:transport")
+ expect(ttl).to be_between(1, SiteSetting.voice_participant_ttl_seconds * 2)
+ end
+ end
+
+ describe ".pinned_transport" do
+ it "returns nil when no pin exists" do
+ expect(described_class.pinned_transport(room.id)).to be_nil
+ end
+ end
+
+ describe ".refresh_transport_pin" do
+ it "extends the pin's ttl" do
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:transport"
+ described_class.pin_transport!(room.id, "livekit")
+ Discourse.redis.expire(key, 1)
+
+ described_class.refresh_transport_pin(room.id)
+
+ expect(Discourse.redis.ttl(key)).to be > 1
+ end
+ end
+
+ describe ".clear_transport_pin" do
+ it "removes the pin" do
+ described_class.pin_transport!(room.id, "mesh")
+
+ described_class.clear_transport_pin(room.id)
+
+ expect(described_class.pinned_transport(room.id)).to be_nil
+ end
+ end
+
+ describe ".recently_active_room_ids" do
+ it "includes rooms with recent membership changes, even once emptied" do
+ described_class.add(room.id, user1.id)
+ described_class.remove(room.id, user1.id)
+
+ expect(described_class.recently_active_room_ids).to include(room.id)
+ end
+
+ it "prunes rooms whose last change is older than the safety window" do
+ described_class.add(room.id, user1.id)
+ Discourse.redis.zadd(described_class::RECENTLY_ACTIVE_ROOMS_KEY, 1.hour.ago.to_f, room.id)
+
+ expect(described_class.recently_active_room_ids).not_to include(room.id)
+ expect(Discourse.redis.zscore(described_class::RECENTLY_ACTIVE_ROOMS_KEY, room.id)).to be_nil
+ end
+ end
+
+ describe ".user_ids" do
+ it "returns only users with fresh heartbeats" do
+ described_class.add(room.id, user1.id)
+ described_class.add(room.id, user2.id)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user2.id)
+
+ expect(described_class.user_ids(room.id)).to contain_exactly(user1.id)
+ end
+
+ it "returns empty when all heartbeats are stale" do
+ described_class.add(room.id, user1.id)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user1.id)
+
+ expect(described_class.user_ids(room.id)).to be_empty
+ end
+ end
+
+ describe ".list" do
+ it "returns User records for fresh participants only" do
+ described_class.add(room.id, user1.id)
+ described_class.add(room.id, user2.id)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user2.id)
+
+ expect(described_class.list(room.id)).to contain_exactly(user1)
+ end
+ end
+
+ describe ".last_heartbeat_at" do
+ it "returns the time from metadata" do
+ freeze_time do
+ described_class.add(room.id, user1.id)
+ described_class.update_metadata(room.id, user1.id, { last_heartbeat_at: Time.now.to_f })
+
+ expect(described_class.last_heartbeat_at(room.id, user1.id)).to be_within(1.second).of(
+ Time.now,
+ )
+ end
+ end
+
+ it "returns nil when no metadata exists" do
+ expect(described_class.last_heartbeat_at(room.id, user1.id)).to be_nil
+ end
+ end
+
+ describe ".clear" do
+ it "removes all participants and metadata" do
+ described_class.add(room.id, user1.id)
+ described_class.update_metadata(room.id, user1.id, { role: "participant" })
+
+ described_class.clear(room.id)
+
+ expect(described_class.user_ids(room.id)).to be_empty
+ expect(described_class.get_metadata(room.id, user1.id)).to eq({})
+ end
+ end
+
+ describe ".participants_fingerprint" do
+ it "is stable across calls and independent of insertion order" do
+ described_class.add(room.id, user1.id)
+ described_class.add(room.id, user2.id)
+
+ fingerprint = described_class.participants_fingerprint(room.id)
+
+ expect(described_class.participants_fingerprint(room.id)).to eq(fingerprint)
+ end
+
+ it "ignores last_heartbeat_at so plain heartbeats don't look like changes" do
+ described_class.add(room.id, user1.id)
+ described_class.update_metadata(room.id, user1.id, { last_heartbeat_at: 1.0 })
+ before = described_class.participants_fingerprint(room.id)
+
+ described_class.update_metadata(room.id, user1.id, { last_heartbeat_at: 2.0 })
+
+ expect(described_class.participants_fingerprint(room.id)).to eq(before)
+ end
+
+ it "changes when a participant joins" do
+ described_class.add(room.id, user1.id)
+ before = described_class.participants_fingerprint(room.id)
+
+ described_class.add(room.id, user2.id)
+
+ expect(described_class.participants_fingerprint(room.id)).not_to eq(before)
+ end
+
+ it "changes when a participant's heartbeat goes stale" do
+ described_class.add(room.id, user1.id)
+ described_class.add(room.id, user2.id)
+ before = described_class.participants_fingerprint(room.id)
+
+ key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"
+ Discourse.redis.zadd(key, 1.hour.ago.to_f, user2.id)
+
+ expect(described_class.participants_fingerprint(room.id)).not_to eq(before)
+ end
+
+ it "changes when a hand is raised and again when it is lowered" do
+ described_class.add(room.id, user1.id)
+ before_raise = described_class.participants_fingerprint(room.id)
+
+ described_class.raise_hand(room.id, user1.id)
+ after_raise = described_class.participants_fingerprint(room.id)
+ expect(after_raise).not_to eq(before_raise)
+
+ described_class.lower_hand(room.id, user1.id)
+ expect(described_class.participants_fingerprint(room.id)).not_to eq(after_raise)
+ end
+
+ it "changes when rendered metadata such as idle_state changes" do
+ described_class.add(room.id, user1.id)
+ described_class.update_metadata(room.id, user1.id, { idle_state: "active" })
+ before = described_class.participants_fingerprint(room.id)
+
+ described_class.update_metadata(room.id, user1.id, { idle_state: "afk" })
+
+ expect(described_class.participants_fingerprint(room.id)).not_to eq(before)
+ end
+ end
+
+ describe ".swap_fingerprint" do
+ it "stores the new fingerprint and returns the previous value" do
+ expect(described_class.swap_fingerprint(room.id, "first")).to be_nil
+ expect(described_class.swap_fingerprint(room.id, "second")).to eq("first")
+ end
+ end
+end
diff --git a/plugins/voice/spec/services/voice/recording_manager_spec.rb b/plugins/voice/spec/services/voice/recording_manager_spec.rb
new file mode 100644
index 00000000000..b0ac20e7185
--- /dev/null
+++ b/plugins/voice/spec/services/voice/recording_manager_spec.rb
@@ -0,0 +1,380 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../../../db/migrate/20241107000000_create_voice_rooms"
+require_relative "../../../db/migrate/20260305162426_add_room_type_to_voice_rooms"
+require_relative "../../../db/migrate/20260612135211_add_video_enabled_to_voice_rooms"
+require_relative "../../../db/migrate/20260717172530_create_voice_recordings"
+
+RSpec.describe Voice::RecordingManager do
+ before do
+ ActiveRecord::Migration.suppress_messages do
+ CreateVoiceRooms.new.change unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :room_type)
+ AddRoomTypeToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.column_exists?(:voice_rooms, :video_enabled)
+ AddVideoEnabledToVoiceRooms.new.change
+ end
+ unless ActiveRecord::Base.connection.table_exists?(:voice_recordings)
+ CreateVoiceRecordings.new.change
+ end
+ end
+ Voice::Room.reset_column_information
+ Voice::Recording.reset_column_information
+ end
+
+ fab!(:moderator, :user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+ SiteSetting.voice_livekit_recording_enabled = true
+ Voice::ParticipantTracker.pin_transport!(room.id, "livekit")
+ end
+
+ after { Voice::ParticipantTracker.clear(room.id) }
+
+ def stub_start(egress_id: "EG_1", status: 200, response_key: "egressId")
+ stub_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).to_return(status: status, body: { response_key => egress_id }.to_json)
+ end
+
+ def stub_stop(status: 200)
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/StopEgress").to_return(
+ status: status,
+ body: "{}",
+ )
+ end
+
+ def egress_info(egress_id: "EG_1", error: nil, file: :default)
+ file = { "filename" => "test.mp4", "location" => nil } if file == :default
+ info = { "egressId" => egress_id, "status" => "EGRESS_COMPLETE" }
+ info["error"] = error if error
+ info["fileResults"] = [file] if file
+ info
+ end
+
+ describe ".start!" do
+ it "starts an egress, persists a recording row with a tokenized filepath, and broadcasts" do
+ stub_start
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ result = described_class.start!(room, moderator)
+ expect(result[:started_by]).to eq(id: moderator.id, username: moderator.username)
+ end
+
+ recording = Voice::Recording.find_by(egress_id: "EG_1")
+ expect(recording.room_id).to eq(room.id)
+ expect(recording.started_by_id).to eq(moderator.id)
+ expect(recording.status).to eq("recording")
+ expect(recording.filepath).to match(
+ /\A#{Regexp.escape(SiteSetting.voice_livekit_recording_filepath)}-\h{16}\z/,
+ )
+
+ recording_messages = messages.select { |message| message.data[:type] == "recording" }
+ expect(recording_messages.size).to eq(1)
+ expect(recording_messages.first.data[:recording][:started_by][:id]).to eq(moderator.id)
+ end
+
+ it "sends the tokenized filepath to the egress service" do
+ stub_start
+
+ described_class.start!(room, moderator)
+
+ filepath = Voice::Recording.find_by(egress_id: "EG_1").filepath
+ expect(
+ a_request(
+ :post,
+ "https://livekit.example.com/twirp/livekit.Egress/StartRoomCompositeEgress",
+ ).with { |req| JSON.parse(req.body)["fileOutputs"] == [{ "filepath" => filepath }] },
+ ).to have_been_made.once
+ end
+
+ it "persists the egress ID from a snake_case API response" do
+ stub_start(response_key: "egress_id")
+
+ described_class.start!(room, moderator)
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1")).to be_present
+ end
+
+ it "refuses when recordings are disabled" do
+ SiteSetting.voice_livekit_recording_enabled = false
+
+ expect { described_class.start!(room, moderator) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_unavailable"),
+ )
+ end
+
+ it "refuses for a call not pinned to livekit" do
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+ Voice::ParticipantTracker.pin_transport!(room.id, "mesh")
+
+ expect { described_class.start!(room, moderator) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_unavailable"),
+ )
+ end
+
+ it "refuses when a recording is already running" do
+ stub_start
+ described_class.start!(room, moderator)
+
+ expect { described_class.start!(room, moderator) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_already_active"),
+ )
+ end
+
+ it "persists nothing and broadcasts nothing when the egress fails to start" do
+ stub_start(status: 500)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ expect { described_class.start!(room, moderator) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_failed"),
+ )
+ end
+
+ expect(described_class.status(room.id)).to be_nil
+ expect(Voice::Recording.count).to eq(0)
+ expect(messages).to be_empty
+ end
+ end
+
+ describe ".stop!" do
+ it "stops the egress, clears the live state, and broadcasts the end" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_stop
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) { described_class.stop!(room) }
+
+ expect(described_class.status(room.id)).to be_nil
+ recording_messages = messages.select { |message| message.data[:type] == "recording" }
+ expect(recording_messages.size).to eq(1)
+ expect(recording_messages.first.data[:recording]).to be_nil
+ end
+
+ it "refuses when nothing is being recorded" do
+ expect { described_class.stop!(room) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_not_active"),
+ )
+ end
+
+ it "keeps the state when the egress cannot be stopped" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_stop(status: 500)
+
+ expect { described_class.stop!(room) }.to raise_error(
+ described_class::Error,
+ I18n.t("voice.errors.recording_stop_failed"),
+ )
+ expect(described_class.status(room.id)).to be_present
+ end
+ end
+
+ describe ".handle_egress_ended" do
+ it "completes the row, clears the live state, broadcasts, and PMs the requester a link" do
+ stub_start
+ described_class.start!(room, moderator)
+
+ file = {
+ "filename" => "voice/watercooler.mp4",
+ "location" => "https://cdn.example.com/voice/watercooler.mp4",
+ "duration" => (65 * 1_000_000_000).to_s,
+ "size" => "12345678",
+ }
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.handle_egress_ended(room, egress_info(file: file))
+ end
+
+ recording = Voice::Recording.find_by(egress_id: "EG_1")
+ expect(recording.status).to eq("completed")
+ expect(recording.location).to eq("https://cdn.example.com/voice/watercooler.mp4")
+ expect(recording.duration_ms).to eq(65_000)
+ expect(recording.size_bytes).to eq(12_345_678)
+ expect(recording.ended_at).to be_present
+
+ expect(described_class.status(room.id)).to be_nil
+ expect(messages.map { |message| message.data[:type] }).to include("recording")
+
+ pm_topic =
+ Topic.private_messages_for_user(moderator).find_by(
+ title: I18n.t("voice.recording_ready_pm.title", room_name: room.name),
+ )
+ expect(pm_topic).to be_present
+ expect(pm_topic.first_post.raw).to include(
+ "https://cdn.example.com/voice/watercooler.mp4",
+ ).and include("1:05")
+ end
+
+ it "PMs the storage path when the egress reports no URL" do
+ stub_start
+ described_class.start!(room, moderator)
+ recording = Voice::Recording.find_by(egress_id: "EG_1")
+
+ described_class.handle_egress_ended(room, egress_info)
+
+ pm_topic =
+ Topic.private_messages_for_user(moderator).find_by(
+ title: I18n.t("voice.recording_ready_pm.title", room_name: room.name),
+ )
+ expect(pm_topic.first_post.raw).to include(recording.filepath)
+ end
+
+ it "marks the row failed and sends no PM when the egress reports an error" do
+ stub_start
+ described_class.start!(room, moderator)
+
+ described_class.handle_egress_ended(room, egress_info(error: "could not connect", file: nil))
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("failed")
+ expect(Topic.private_messages_for_user(moderator)).to be_empty
+ end
+
+ it "finalizes a recording from a snake_case egress response" do
+ stub_start
+ described_class.start!(room, moderator)
+
+ described_class.handle_egress_ended(
+ room,
+ {
+ "egress_id" => "EG_1",
+ "status" => "EGRESS_COMPLETE",
+ "file_results" => [{ "filename" => "test.mp4", "location" => nil }],
+ },
+ )
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1")).to be_completed
+ end
+
+ it "finalizes the row even when the live room state is already gone" do
+ stub_start
+ described_class.start!(room, moderator)
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+
+ described_class.handle_egress_ended(room, egress_info)
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("completed")
+ expect(Topic.private_messages_for_user(moderator).count).to eq(1)
+ end
+
+ it "ignores an egress that was never tracked" do
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.handle_egress_ended(room, egress_info(egress_id: "EG_unknown"))
+ end
+
+ expect(messages).to be_empty
+ expect(Voice::Recording.count).to eq(0)
+ end
+
+ it "does not finalize twice or resend the PM for an already-finalized egress" do
+ stub_start
+ described_class.start!(room, moderator)
+ described_class.handle_egress_ended(room, egress_info)
+
+ described_class.handle_egress_ended(room, egress_info)
+
+ expect(Topic.private_messages_for_user(moderator).count).to eq(1)
+ end
+ end
+
+ describe ".reconcile_pending!" do
+ def stub_list(items:)
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/ListEgress").to_return(
+ body: { items: items }.to_json,
+ )
+ end
+
+ it "finalizes a stuck row, PMs the requester, and clears the live state" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_list(
+ items: [
+ {
+ "egressId" => "EG_1",
+ "status" => "EGRESS_COMPLETE",
+ "fileResults" => [
+ { "filename" => "test.mp4", "location" => "https://cdn.example.com/test.mp4" },
+ ],
+ },
+ ],
+ )
+
+ described_class.reconcile_pending!
+
+ recording = Voice::Recording.find_by(egress_id: "EG_1")
+ expect(recording.status).to eq("completed")
+ expect(recording.location).to eq("https://cdn.example.com/test.mp4")
+ expect(described_class.status(room.id)).to be_nil
+ expect(Topic.private_messages_for_user(moderator).count).to eq(1)
+ end
+
+ it "leaves a still-active egress alone" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_list(items: [{ "egressId" => "EG_1", "status" => "EGRESS_ACTIVE" }])
+
+ described_class.reconcile_pending!
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("recording")
+ expect(described_class.status(room.id)).to be_present
+ end
+
+ it "writes off an old row the egress service no longer remembers, without a PM" do
+ stub_start
+ described_class.start!(room, moderator)
+ Voice::Recording.find_by(egress_id: "EG_1").update!(started_at: 25.hours.ago)
+ stub_list(items: [])
+
+ described_class.reconcile_pending!
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("failed")
+ expect(Topic.private_messages_for_user(moderator)).to be_empty
+ end
+
+ it "keeps a recent row the egress service did not return yet" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_list(items: [])
+
+ described_class.reconcile_pending!
+
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("recording")
+ end
+
+ it "keeps a stuck row when the egress service is unreachable" do
+ stub_start
+ described_class.start!(room, moderator)
+ stub_request(:post, "https://livekit.example.com/twirp/livekit.Egress/ListEgress").to_timeout
+
+ expect { described_class.reconcile_pending! }.not_to raise_error
+ expect(Voice::Recording.find_by(egress_id: "EG_1").status).to eq("recording")
+ end
+ end
+
+ it "clears the live recording state together with the transport pin" do
+ stub_start
+ described_class.start!(room, moderator)
+
+ Voice::ParticipantTracker.clear_transport_pin(room.id)
+
+ expect(described_class.status(room.id)).to be_nil
+ end
+end
diff --git a/plugins/voice/spec/services/voice/room_broadcaster_spec.rb b/plugins/voice/spec/services/voice/room_broadcaster_spec.rb
new file mode 100644
index 00000000000..29c13908d61
--- /dev/null
+++ b/plugins/voice/spec/services/voice/room_broadcaster_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec.describe Voice::RoomBroadcaster do
+ fab!(:participant, :user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before { SiteSetting.voice_enabled = true }
+
+ describe ".publish_participants" do
+ it "reaches anonymous subscribers through the anonymous_users pseudogroup when they are admitted" do
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ Voice::ParticipantTracker.add(room.id, participant.id)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.publish_participants(room)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.group_ids).to contain_exactly(
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ )
+
+ anonymous_client =
+ MessageBus::Client.new(
+ client_id: "anonymous",
+ user_id: nil,
+ group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ expect(anonymous_client.allowed?(messages.first)).to eq(true)
+ end
+
+ it "targets logged-in subscribers, never anonymous ones, when allowed groups are logged_in_users" do
+ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:logged_in_users].to_s
+ Voice::ParticipantTracker.add(room.id, participant.id)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.publish_participants(room)
+ end
+
+ expect(messages.first.group_ids).to contain_exactly(Group::AUTO_GROUPS[:logged_in_users])
+
+ anonymous_client =
+ MessageBus::Client.new(
+ client_id: "anonymous",
+ user_id: nil,
+ group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ expect(anonymous_client.allowed?(messages.first)).to eq(false)
+ end
+
+ it "targets allowed groups plus current participants when access is restricted" do
+ group = Fabricate(:group)
+ SiteSetting.voice_allowed_groups = group.id.to_s
+ Voice::ParticipantTracker.add(room.id, participant.id)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.publish_participants(room)
+ end
+
+ expect(messages.first.group_ids).to contain_exactly(group.id)
+ expect(messages.first.user_ids).to contain_exactly(participant.id)
+ end
+
+ it "targets members plus current participants for private rooms" do
+ private_room = Fabricate(:voice_room, public: false)
+ Voice::ParticipantTracker.add(private_room.id, participant.id)
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(private_room.id)) do
+ described_class.publish_participants(private_room)
+ end
+
+ expect(messages.first.user_ids).to contain_exactly(private_room.creator_id, participant.id)
+ end
+ end
+
+ describe ".publish_hand_raise" do
+ fab!(:second_participant, :user)
+
+ it "publishes the hand event to exactly the tracked participants" do
+ Voice::ParticipantTracker.add(room.id, participant.id)
+ Voice::ParticipantTracker.add(room.id, second_participant.id)
+ raised_at = Time.now.to_f
+
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.publish_hand_raise(
+ room,
+ participant.id,
+ raised: true,
+ raised_at: raised_at,
+ reason: "raised",
+ )
+ end
+
+ expect(messages.size).to eq(1)
+ message = messages.first
+ expect(message.user_ids).to contain_exactly(participant.id, second_participant.id)
+ expect(message.data).to eq(
+ type: "hand_raise",
+ room_id: room.id,
+ user_id: participant.id,
+ raised: true,
+ raised_at: raised_at,
+ reason: "raised",
+ )
+ end
+
+ it "does not publish when the room has no participants" do
+ messages =
+ MessageBus.track_publish(Voice.room_channel(room.id)) do
+ described_class.publish_hand_raise(
+ room,
+ participant.id,
+ raised: false,
+ reason: "withdrawn",
+ )
+ end
+
+ expect(messages).to be_empty
+ end
+ end
+end
diff --git a/plugins/voice/spec/support/voice_fake_media.rb b/plugins/voice/spec/support/voice_fake_media.rb
new file mode 100644
index 00000000000..580e87b2731
--- /dev/null
+++ b/plugins/voice/spec/support/voice_fake_media.rb
@@ -0,0 +1,214 @@
+# frozen_string_literal: true
+
+require "json"
+
+module VoiceFakeMedia
+ DEFAULT_VIDEO_FEEDS = [
+ { label: "Voice fake camera A", width: 640, height: 360, color: "#2563eb", accent: "#f97316" },
+ { label: "Voice fake camera B", width: 640, height: 360, color: "#16a34a", accent: "#7c3aed" },
+ { label: "Voice fake camera C", width: 640, height: 360, color: "#dc2626", accent: "#0891b2" },
+ ].freeze
+
+ def install_voice_fake_media(video_feeds: DEFAULT_VIDEO_FEEDS)
+ feeds_json = JSON.generate(video_feeds)
+
+ page.driver.with_playwright_page do |playwright_page|
+ playwright_page.add_init_script(script: <<~JS)
+ (() => {
+ if (window.__voiceFakeMediaInstalled) {
+ return;
+ }
+
+ window.__voiceFakeMediaInstalled = true;
+ window.__voiceFakeMediaStreams = [];
+ window.__voiceFakeMediaVideoFeeds = #{feeds_json};
+ window.__voiceFakeMediaVideoFeedIndex = 0;
+
+ const mediaDevices = navigator.mediaDevices || {};
+ Object.defineProperty(navigator, "mediaDevices", {
+ configurable: true,
+ value: mediaDevices,
+ });
+
+ function nextVideoFeed() {
+ const feeds = window.__voiceFakeMediaVideoFeeds;
+ const index = window.__voiceFakeMediaVideoFeedIndex % feeds.length;
+ window.__voiceFakeMediaVideoFeedIndex += 1;
+ return feeds[index];
+ }
+
+ function cleanupWhenTrackStops(track, cleanup) {
+ let cleaned = false;
+ const runCleanup = () => {
+ if (cleaned) {
+ return;
+ }
+ cleaned = true;
+ cleanup();
+ };
+ const originalStop = track.stop.bind(track);
+ track.stop = () => {
+ runCleanup();
+ originalStop();
+ };
+ track.addEventListener("ended", runCleanup, { once: true });
+ }
+
+ function createVideoStream(feed) {
+ const { label, width, height, color, accent } = feed;
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const context = canvas.getContext("2d");
+ let frame = 0;
+
+ const drawFrame = () => {
+ frame += 1;
+ const x = (frame * 17) % width;
+ const y = height / 2 - 40;
+
+ context.fillStyle = color;
+ context.fillRect(0, 0, width, height);
+ context.fillStyle = "rgba(255, 255, 255, 0.18)";
+ context.fillRect(0, height - 96, width, 96);
+ context.fillStyle = accent || "rgba(0, 0, 0, 0.35)";
+ context.fillRect(x, y, 120, 80);
+ context.fillStyle = "#fff";
+ context.font = "32px sans-serif";
+ context.fillText(label, 24, 48);
+ context.font = "20px sans-serif";
+ context.fillText(`frame ${frame}`, 24, height - 38);
+ };
+
+ drawFrame();
+ const timer = window.setInterval(drawFrame, 100);
+ const stream = canvas.captureStream(10);
+ stream.__voiceFakeMediaLabel = label;
+ stream.getTracks().forEach((track) => {
+ track.__voiceFakeMediaLabel = label;
+ cleanupWhenTrackStops(track, () => window.clearInterval(timer));
+ });
+ window.__voiceFakeMediaStreams.push(stream);
+ return stream;
+ }
+
+ function createAudioStream() {
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
+ const audioContext = new AudioContext();
+ const oscillator = audioContext.createOscillator();
+ const gain = audioContext.createGain();
+ const destination = audioContext.createMediaStreamDestination();
+
+ oscillator.frequency.value = 220;
+ gain.gain.value = 0.0001;
+ oscillator.connect(gain);
+ gain.connect(destination);
+ oscillator.start();
+ destination.stream.getTracks().forEach((track) => {
+ cleanupWhenTrackStops(track, () => {
+ oscillator.stop();
+ audioContext.close();
+ });
+ });
+ window.__voiceFakeMediaStreams.push(destination.stream);
+ return destination.stream;
+ }
+
+ function addTracks(target, source) {
+ source.getTracks().forEach((track) => target.addTrack(track));
+ }
+
+ mediaDevices.getUserMedia = async (constraints = {}) => {
+ const stream = new MediaStream();
+
+ if (constraints.audio) {
+ addTracks(stream, createAudioStream());
+ }
+
+ if (constraints.video) {
+ const videoStream = createVideoStream(nextVideoFeed());
+ stream.__voiceFakeMediaLabel = videoStream.__voiceFakeMediaLabel;
+ addTracks(stream, videoStream);
+ }
+
+ return stream;
+ };
+
+ mediaDevices.getDisplayMedia = async () => {
+ return createVideoStream({
+ label: "Voice fake screen",
+ width: 1024,
+ height: 576,
+ color: "#16a34a",
+ accent: "#111827",
+ });
+ };
+
+ mediaDevices.enumerateDevices = async () => {
+ return window.__voiceFakeMediaVideoFeeds.map((feed, index) => ({
+ deviceId: `voice-fake-camera-${index}`,
+ groupId: `voice-fake-group-${index}`,
+ kind: "videoinput",
+ label: feed.label,
+ toJSON() {
+ return this;
+ },
+ }));
+ };
+ })();
+ JS
+ end
+ end
+
+ def voice_media_track_count(selector, kind: :video, timeout: 5)
+ page.evaluate_async_script(<<~JS, selector, kind.to_s, timeout * 1000)
+ const [selector, kind, timeoutMs, done] = arguments;
+ const startedAt = performance.now();
+ const trackCount = () => {
+ const stream = document.querySelector(selector)?.srcObject;
+ if (!stream) {
+ return 0;
+ }
+ return kind === "audio" ? stream.getAudioTracks().length : stream.getVideoTracks().length;
+ };
+ const waitForTracks = () => {
+ const count = trackCount();
+ if (count > 0 || performance.now() - startedAt > timeoutMs) {
+ done(count);
+ } else {
+ requestAnimationFrame(waitForTracks);
+ }
+ };
+ waitForTracks();
+ JS
+ end
+
+ def voice_media_track_live?(selector, kind: :video, timeout: 5)
+ page.evaluate_async_script(<<~JS, selector, kind.to_s, timeout * 1000)
+ const [selector, kind, timeoutMs, done] = arguments;
+ const startedAt = performance.now();
+ const trackLive = () => {
+ const stream = document.querySelector(selector)?.srcObject;
+ if (!stream?.active) {
+ return false;
+ }
+
+ const tracks =
+ kind === "audio" ? stream.getAudioTracks() : stream.getVideoTracks();
+ return tracks.some((track) => track.readyState === "live" && track.enabled);
+ };
+ const waitForLiveTrack = () => {
+ if (trackLive()) {
+ done(true);
+ } else if (performance.now() - startedAt > timeoutMs) {
+ done(false);
+ } else {
+ requestAnimationFrame(waitForLiveTrack);
+ }
+ };
+ waitForLiveTrack();
+ JS
+ end
+end
+
+RSpec.configure { |config| config.include VoiceFakeMedia, type: :system }
diff --git a/plugins/voice/spec/system/back_to_voice_room_spec.rb b/plugins/voice/spec/system/back_to_voice_room_spec.rb
new file mode 100644
index 00000000000..09f7f52bec8
--- /dev/null
+++ b/plugins/voice/spec/system/back_to_voice_room_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Back to voice room button" do
+ include ThemeScreenshotMarker
+
+ fab!(:user)
+ fab!(:channel, :chat_channel) { Fabricate(:chat_channel, threading_enabled: true) }
+
+ fab!(:room) do
+ Fabricate(:voice_room, name: "Team Room", public: true, chat_channel_id: channel.id)
+ end
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+ let(:chat_drawer_page) { PageObjects::Pages::ChatDrawer.new }
+ let(:back_to_voice_room) { PageObjects::Components::VoiceBackToVoiceRoom.new }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_chat_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ chat_system_bootstrap(user, [channel])
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ it "takes the user from a session thread straight into its voice room" do
+ session = Voice::ChatSession.post_message!(room, user, "hi from the room")
+ thread = Chat::Thread.find(session[:thread_id])
+
+ chat_page.visit_thread(thread)
+
+ expect(back_to_voice_room).to have_back_to_room_button
+ screenshot_marker(label: "back-to-voice-room-full-page", only: :desktop)
+ back_to_voice_room.click
+
+ expect(page).to have_current_path("/voice/r/#{room.slug}", ignore_query: true)
+
+ # The click joins the call directly — no interstitial join button — and,
+ # since this session is still live, arrives with its chat panel open.
+ expect(page).to have_button(I18n.t("js.voice.room.leave"))
+ expect(page).to have_no_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-chat")
+ end
+
+ it "shows the button on the drawer thread header" do
+ Voice::ChatSession.post_message!(room, user, "hi from the room")
+ session = Voice::ChatSession.post_message!(room, user, "and a reply")
+ thread = Chat::Thread.find(session[:thread_id])
+
+ chat_drawer_page.visit_channel(channel)
+ channel_page.message_thread_indicator(thread.original_message).click
+
+ expect(chat_drawer_page).to have_open_thread(thread)
+ expect(back_to_voice_room).to have_back_to_room_button
+ screenshot_marker(label: "back-to-voice-room-drawer", only: :desktop)
+ end
+
+ it "hides the button on a thread that is not a voice-room session" do
+ thread = Fabricate(:chat_thread, channel: channel)
+
+ chat_page.visit_thread(thread)
+
+ expect(back_to_voice_room).to have_no_back_to_room_button
+ end
+end
diff --git a/plugins/voice/spec/system/page_objects/components/voice_back_to_voice_room.rb b/plugins/voice/spec/system/page_objects/components/voice_back_to_voice_room.rb
new file mode 100644
index 00000000000..d03b3b9f4f7
--- /dev/null
+++ b/plugins/voice/spec/system/page_objects/components/voice_back_to_voice_room.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class VoiceBackToVoiceRoom < PageObjects::Components::Base
+ SELECTOR = ".c-navbar__back-to-voice-room"
+
+ def has_back_to_room_button?
+ has_css?(SELECTOR)
+ end
+
+ def has_no_back_to_room_button?
+ has_no_css?(SELECTOR)
+ end
+
+ def click
+ find(SELECTOR).click
+ self
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/page_objects/components/voice_sidebar.rb b/plugins/voice/spec/system/page_objects/components/voice_sidebar.rb
new file mode 100644
index 00000000000..fdf637f2ef4
--- /dev/null
+++ b/plugins/voice/spec/system/page_objects/components/voice_sidebar.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class VoiceSidebar < PageObjects::Components::Base
+ ROOM_LINK_SELECTOR = ".sidebar-section-link.voice-sidebar-link"
+
+ attr_reader :section_selector
+
+ def initialize(section_name: "voice-rooms")
+ @section_selector = ".sidebar-section[data-section-name='#{section_name}']"
+ end
+
+ def visible?
+ page.has_css?(section_selector)
+ end
+
+ def not_visible?
+ page.has_no_css?(section_selector)
+ end
+
+ def has_room?(room_name)
+ page.has_css?(section_selector, text: room_name)
+ end
+
+ def has_no_room?(room_name)
+ page.has_no_css?(section_selector, text: room_name)
+ end
+
+ def room_link(room_id)
+ find("#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}']")
+ end
+
+ def has_room_link?(room_id)
+ page.has_css?("#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}']")
+ end
+
+ def has_no_room_link?(room_id)
+ page.has_no_css?("#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}']")
+ end
+
+ def click_room(room_id)
+ room_link(room_id).click
+ self
+ end
+
+ def has_active_room?(room_id)
+ page.has_css?(
+ "#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}'].sidebar-section-link--active",
+ )
+ end
+
+ def has_no_active_room?(room_id)
+ page.has_no_css?(
+ "#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}'].sidebar-section-link--active",
+ )
+ end
+
+ def has_participants?(room_id)
+ page.has_css?(
+ "#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}'] .voice-sidebar-link__participants",
+ )
+ end
+
+ def has_no_participants?(room_id)
+ page.has_no_css?(
+ "#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}'] .voice-sidebar-link__participants",
+ )
+ end
+
+ def has_speaking_indicator?(room_id)
+ page.has_css?(
+ "#{ROOM_LINK_SELECTOR}[data-link-name='voice-room-#{room_id}'] .voice-sidebar-link__avatar--speaking",
+ )
+ end
+
+ def section_title
+ find("#{section_selector} .sidebar-section-header-text").text
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/voice_chat_sidebar_spec.rb b/plugins/voice/spec/system/voice_chat_sidebar_spec.rb
new file mode 100644
index 00000000000..c1414c145ad
--- /dev/null
+++ b/plugins/voice/spec/system/voice_chat_sidebar_spec.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+require_relative "page_objects/components/voice_sidebar"
+
+describe "Voice rooms in the chat sidebar" do
+ let(:chat_rooms_sidebar) do
+ PageObjects::Components::VoiceSidebar.new(section_name: "voice-rooms-chat")
+ end
+ let(:main_rooms_sidebar) { PageObjects::Components::VoiceSidebar.new }
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+
+ fab!(:user)
+ fab!(:admin)
+ fab!(:channel, :category_channel)
+ fab!(:room) { Fabricate(:voice_room, name: "Watercooler", creator: admin, public: true) }
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ chat_system_bootstrap(user, [channel])
+ sign_in(user)
+ end
+
+ context "when the chat separate sidebar mode keeps the chat panel on its own" do
+ before do
+ user.user_option.update!(
+ chat_separate_sidebar_mode: UserOption.chat_separate_sidebar_modes[:always],
+ )
+ end
+
+ it "shows the voice rooms in the full-screen chat sidebar" do
+ chat_page.visit_channel(channel)
+
+ expect(chat_rooms_sidebar).to be_visible
+ expect(chat_rooms_sidebar).to have_room(room.name)
+ end
+ end
+
+ context "when the chat separate sidebar mode is combined" do
+ before do
+ user.user_option.update!(
+ chat_separate_sidebar_mode: UserOption.chat_separate_sidebar_modes[:never],
+ )
+ end
+
+ it "shows the rooms once via the main panel and not as a duplicate chat section" do
+ chat_page.visit_channel(channel)
+
+ expect(main_rooms_sidebar).to be_visible
+ expect(main_rooms_sidebar).to have_room(room.name)
+ expect(chat_rooms_sidebar).to be_not_visible
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/voice_livekit_spec.rb b/plugins/voice/spec/system/voice_livekit_spec.rb
new file mode 100644
index 00000000000..c7c22edaccd
--- /dev/null
+++ b/plugins/voice/spec/system/voice_livekit_spec.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+# Exercises a real LiveKit server end-to-end, so it only runs when one is
+# reachable. Start a disposable dev server and point the spec at it:
+#
+# docker run --rm -p 7880:7880 livekit/livekit-server --dev
+#
+# VOICE_LIVEKIT_TEST_URL=ws://localhost:7880 \
+# bin/rspec plugins/voice/spec/system/voice_livekit_spec.rb
+#
+# The --dev server uses the API key "devkey" with secret "secret"; set
+# VOICE_LIVEKIT_TEST_KEY / VOICE_LIVEKIT_TEST_SECRET to target a server
+# with real credentials. Without VOICE_LIVEKIT_TEST_URL the whole file is
+# excluded, keeping CI runs byte-identical to before it existed.
+#
+# NOTE: outside CI, core pins every test browser to one fixed
+# --remote-debugging-port, so any spec that opens a second session (this one,
+# and the mesh two-browser specs) needs CI=1 in the environment to launch the
+# second browser locally.
+#
+# Besides the transport itself, this doubles as the proof that the fake
+# media harness satisfies the LiveKit SDK: livekit-client never calls
+# getUserMedia here — the service acquires media itself (through the fakes)
+# and hands the SDK finished MediaStreamTracks via publishTrack, exactly as
+# it hands them to RTCPeerConnection on the mesh path.
+describe "Voice LiveKit rooms", if: ENV["VOICE_LIVEKIT_TEST_URL"] do
+ fab!(:admin)
+ fab!(:alice) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:bob) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ fab!(:room) { Fabricate(:voice_room, name: "LiveKit Room", creator: admin, public: true) }
+
+ before do
+ alice.activate
+ bob.activate
+ Group.refresh_automatic_groups!
+
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_video_enabled = true
+
+ # The policy validator requires url + key + secret to be present first.
+ SiteSetting.voice_livekit_url = ENV["VOICE_LIVEKIT_TEST_URL"]
+ SiteSetting.voice_livekit_api_key = ENV.fetch("VOICE_LIVEKIT_TEST_KEY", "devkey")
+ SiteSetting.voice_livekit_api_secret = ENV.fetch("VOICE_LIVEKIT_TEST_SECRET", "secret")
+ SiteSetting.voice_livekit_room_policy = "all_rooms"
+ end
+
+ # Records WebSocket URLs so the spec can prove the browser really connected
+ # to the SFU. Belt and braces on top of the transport-pin assertion below:
+ # a stale client bundle once ran this whole flow green on mesh.
+ def install_sfu_connection_probe
+ page.driver.with_playwright_page { |pw| pw.add_init_script(script: <<~JS) }
+ window.__voiceWsUrls = [];
+ const NativeWebSocket = window.WebSocket;
+ window.WebSocket = new Proxy(NativeWebSocket, {
+ construct(target, args) {
+ window.__voiceWsUrls.push(String(args[0]));
+ return new target(...args);
+ },
+ });
+ JS
+ end
+
+ def sfu_websocket_urls
+ page
+ .evaluate_script("window.__voiceWsUrls")
+ .select { |url| url.start_with?(ENV["VOICE_LIVEKIT_TEST_URL"]) }
+ end
+
+ it "runs a two-browser camera call through the LiveKit server" do
+ using_session(:alice) do
+ sign_in(alice)
+ install_sfu_connection_probe
+ install_voice_fake_media(
+ video_feeds: [
+ {
+ label: "Alice fake camera",
+ width: 640,
+ height: 360,
+ color: "#2563eb",
+ accent: "#f97316",
+ },
+ ],
+ )
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ end
+
+ # The first join must have resolved and pinned the SFU transport — this
+ # is what distinguishes the call below from silently running on mesh.
+ expect(Voice::ParticipantTracker.pinned_transport(room.id)).to eq("livekit")
+
+ using_session(:bob) do
+ sign_in(bob)
+ install_voice_fake_media(
+ video_feeds: [
+ {
+ label: "Bob fake camera",
+ width: 640,
+ height: 360,
+ color: "#16a34a",
+ accent: "#7c3aed",
+ },
+ ],
+ )
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ local_video_selector =
+ ".voice-video-tile.--video[data-user-id='#{bob.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(local_video_selector)
+ expect(voice_media_track_count(local_video_selector)).to eq(1)
+ end
+
+ using_session(:alice) do
+ # Bob's camera arrives through the SFU rather than a direct peer
+ # connection; a longer wait absorbs the extra publish/subscribe hop.
+ remote_video_selector =
+ ".voice-video-tile.--video[data-user-id='#{bob.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(remote_video_selector, wait: 15)
+ expect(voice_media_track_count(remote_video_selector, timeout: 15)).to eq(1)
+ expect(voice_media_track_live?(remote_video_selector, timeout: 15)).to eq(true)
+
+ expect(sfu_websocket_urls).not_to be_empty
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/voice_mesh_privacy_warning_spec.rb b/plugins/voice/spec/system/voice_mesh_privacy_warning_spec.rb
new file mode 100644
index 00000000000..8d1ca08338b
--- /dev/null
+++ b/plugins/voice/spec/system/voice_mesh_privacy_warning_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Voice mesh privacy warning" do
+ fab!(:user)
+ fab!(:room) { Fabricate(:voice_room, public: true) }
+
+ before do
+ user.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ def click_join
+ click_button(I18n.t("js.voice.room.join"))
+ end
+
+ it "gates a mesh join behind the warning" do
+ visit("/voice/r/#{room.slug}")
+
+ click_join
+ expect(page).to have_css(".voice-mesh-privacy-warning-modal")
+ click_button(I18n.t("js.voice.mesh_privacy_warning.cancel"))
+ expect(page).to have_no_css(".voice-mesh-privacy-warning-modal")
+ expect(page).to have_no_css(".voice-room-page__leave")
+
+ click_join
+ click_button(I18n.t("js.voice.mesh_privacy_warning.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ end
+
+ it "doesn't warn again on a device that opted out" do
+ visit("/voice/r/#{room.slug}")
+
+ click_join
+ find(".voice-mesh-privacy-warning-modal__dont-show-again input").click
+ click_button(I18n.t("js.voice.mesh_privacy_warning.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ click_button(I18n.t("js.voice.room.leave"))
+
+ click_join
+ expect(page).to have_css(".voice-room-page__leave")
+ expect(page).to have_no_css(".voice-mesh-privacy-warning-modal")
+ end
+
+ it "doesn't warn when disabled site-wide" do
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+
+ visit("/voice/r/#{room.slug}")
+
+ click_join
+ expect(page).to have_css(".voice-room-page__leave")
+ expect(page).to have_no_css(".voice-mesh-privacy-warning-modal")
+ end
+end
diff --git a/plugins/voice/spec/system/voice_room_chat_panel_spec.rb b/plugins/voice/spec/system/voice_room_chat_panel_spec.rb
new file mode 100644
index 00000000000..d8200ebab5f
--- /dev/null
+++ b/plugins/voice/spec/system/voice_room_chat_panel_spec.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Voice room chat panel" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:channel, :chat_channel) { Fabricate(:chat_channel, threading_enabled: true) }
+ fab!(:room) do
+ Fabricate(
+ :voice_room,
+ name: "Team Room",
+ creator: admin,
+ public: true,
+ chat_channel_id: channel.id,
+ chat_idle_minutes: 15,
+ )
+ end
+
+ before do
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ chat_system_bootstrap(user, [channel])
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ it "renders an existing session thread through chat's own thread UI and posts through it" do
+ Voice::ChatSession.post_message!(room, admin, "hi from admin")
+
+ visit("/voice/r/#{room.slug}?chat=true")
+ click_button(I18n.t("js.voice.room.join"))
+ # The panel slides in; typing into it mid-animation can miss the composer.
+ wait_for_animation(find(".voice-room-page__sidebar"))
+
+ # The real chat thread component, not a re-implementation.
+ expect(page).to have_css(".voice-chat .chat-thread")
+ expect(page).to have_css(".voice-chat .chat-message-text", text: "hi from admin")
+
+ # The native composer posts through chat's own API.
+ find(".voice-chat .chat-composer__input").fill_in(with: "hello from the room")
+ find(".voice-chat .chat-composer__input").send_keys(:enter)
+
+ expect(page).to have_css(".voice-chat .chat-message-text", text: "hello from the room")
+
+ # The message renders staged before the create request lands — wait for
+ # the server to actually persist it.
+ try_until_success do
+ expect(
+ Chat::Message.where(chat_channel_id: channel.id).order(:created_at).last&.message,
+ ).to eq("hello from the room")
+ end
+ end
+
+ it "opens the chat panel by default after joining a stage room" do
+ stage_room =
+ Fabricate(
+ :voice_room,
+ name: "Stage Team Room",
+ creator: admin,
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ chat_channel_id: channel.id,
+ )
+
+ visit("/voice/r/#{stage_room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+
+ expect(page).to have_css(".voice-room-page__sidebar .voice-chat")
+ expect(page).to have_current_path("/voice/r/#{stage_room.slug}")
+ end
+
+ it "keeps the chat panel closed by default after joining an open room" do
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+
+ expect(page).to have_css(".voice-room-page__leave")
+ expect(page).to have_no_css(".voice-room-page__sidebar")
+ end
+
+ it "opens the session thread from the first message sent through the starter composer" do
+ visit("/voice/r/#{room.slug}?chat=true")
+ click_button(I18n.t("js.voice.room.join"))
+ # The panel slides in; typing into it mid-animation can miss the composer.
+ wait_for_animation(find(".voice-room-page__sidebar"))
+
+ # No thread yet: the panel offers the starter composer, not the thread UI.
+ expect(page).to have_css(".voice-chat__input")
+ expect(page).to have_no_css(".voice-chat .chat-thread")
+
+ find(".voice-chat__input").fill_in(with: "kicking things off")
+ # See the note above: the first send races thread creation, its message
+ # fetch, and the native composer's mount/focus against the settle check.
+ using_wait_time(20) { find(".voice-chat__input").send_keys(:enter) }
+
+ # The first message creates the thread and the panel swaps to the native UI.
+ expect(page).to have_css(".voice-chat .chat-thread")
+ expect(page).to have_css(".voice-chat .chat-message-text", text: "kicking things off")
+
+ thread = Chat::Thread.find_by(channel_id: channel.id)
+ expect(thread.original_message.message).to eq("In ##{room.slug}::room - kicking things off")
+ expect(thread.original_message.user_id).to eq(user.id)
+ end
+end
diff --git a/plugins/voice/spec/system/voice_rooms_spec.rb b/plugins/voice/spec/system/voice_rooms_spec.rb
new file mode 100644
index 00000000000..7b042dd2b9c
--- /dev/null
+++ b/plugins/voice/spec/system/voice_rooms_spec.rb
@@ -0,0 +1,412 @@
+# frozen_string_literal: true
+
+require_relative "page_objects/components/voice_sidebar"
+require_relative "../support/voice_fake_media"
+
+describe "Voice rooms" do
+ let(:voice_sidebar) { PageObjects::Components::VoiceSidebar.new }
+
+ def click_room_page_widget_mode_button
+ find("button[data-identifier='voice-room-menu']").click
+ within(".fk-d-menu[data-identifier='voice-room-menu']") do
+ click_button(I18n.t("js.voice.room.widget_mode"))
+ end
+ end
+
+ def click_call_widget_open_page_button
+ within(".voice-call-widget__controls") { find(".d-icon-expand").ancestor("button").click }
+ end
+
+ def click_call_widget_leave_button
+ within(".voice-call-widget__controls") { find(".voice-call-widget__leave").click }
+ end
+
+ def switch_layout(layout_label)
+ find("button[data-identifier='voice-room-menu']").click
+ within(".fk-d-menu[data-identifier='voice-room-menu']") do
+ click_button(I18n.t("js.voice.room.layout"))
+ end
+ click_button(layout_label)
+ end
+
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:admin)
+
+ before do
+ user.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ end
+
+ context "when plugin is disabled" do
+ it "does not show voice rooms section" do
+ SiteSetting.voice_enabled = false
+ Fabricate(:voice_room, name: "Test Room", creator: admin, public: true)
+ sign_in(user)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to be_not_visible
+ end
+ end
+
+ context "when plugin is enabled" do
+ context "as anonymous user" do
+ it "shows public rooms when access is open to everyone" do
+ Fabricate(:voice_room, name: "Test Room", creator: admin, public: true)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to be_visible
+ end
+
+ it "does not show voice rooms section when access is restricted to a group" do
+ SiteSetting.voice_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ Fabricate(:voice_room, name: "Test Room", creator: admin, public: true)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to be_not_visible
+ end
+ end
+
+ context "as logged in user" do
+ fab!(:room) { Fabricate(:voice_room, name: "Test Room", creator: admin, public: true) }
+
+ before do
+ user.update!(trust_level: TrustLevel[2])
+ Group.refresh_automatic_groups!
+ sign_in(user)
+ end
+
+ it "shows voice rooms section when rooms exist" do
+ visit("/latest")
+
+ expect(voice_sidebar).to be_visible
+ end
+
+ it "displays public rooms in the sidebar" do
+ visit("/latest")
+
+ expect(voice_sidebar).to be_visible
+ expect(voice_sidebar).to have_room(room.name)
+ end
+
+ it "hides private rooms from non-members even when they can create rooms" do
+ private_room = Fabricate(:voice_room, name: "Private Room", creator: admin, public: false)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to have_room(room.name)
+ expect(voice_sidebar).to have_no_room(private_room.name)
+ end
+
+ it "shows private rooms to their members" do
+ private_room = Fabricate(:voice_room, name: "Private Room", creator: admin, public: false)
+ private_room.room_memberships.create!(user: user)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to have_room(private_room.name)
+ end
+
+ it "can publish a fake camera stream on the room page" do
+ SiteSetting.voice_video_enabled = true
+ install_voice_fake_media
+
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ video_selector =
+ ".voice-video-tile.--video[data-user-id='#{user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(video_selector)
+ expect(voice_media_track_count(video_selector)).to eq(1)
+ end
+
+ it "switches between presentation and tiled layouts from the menu" do
+ SiteSetting.voice_video_enabled = true
+ install_voice_fake_media
+
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ expect(page).to have_css(".voice-room-page.--tiled")
+
+ switch_layout(I18n.t("js.voice.video.layout_presentation"))
+ expect(page).to have_css(".voice-room-page.--presentation")
+
+ switch_layout(I18n.t("js.voice.video.layout_tiled"))
+ expect(page).to have_css(".voice-room-page.--tiled")
+ end
+
+ it "keeps the active call in a widget after switching to widget mode" do
+ SiteSetting.voice_video_enabled = true
+ install_voice_fake_media
+
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ click_room_page_widget_mode_button
+
+ expect(page).to have_css(".voice-call-widget", text: room.name)
+ expect(page).to have_button(I18n.t("js.voice.video.camera_off"))
+
+ widget_video_selector =
+ ".voice-call-widget .voice-video-tile.--video[data-user-id='#{user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(widget_video_selector)
+ expect(voice_media_track_count(widget_video_selector)).to eq(1)
+
+ click_call_widget_open_page_button
+
+ page_video_selector =
+ ".voice-room-page .voice-video-tile.--video[data-user-id='#{user.id}'] video.voice-video-tile__video"
+ expect(page).to have_current_path("/voice/r/#{room.slug}")
+ expect(page).to have_css(page_video_selector)
+ expect(voice_media_track_count(page_video_selector)).to eq(1)
+ end
+
+ it "can stop video and leave the call from the persistent widget" do
+ SiteSetting.voice_video_enabled = true
+ install_voice_fake_media
+
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ click_room_page_widget_mode_button
+
+ within(".voice-call-widget") { click_button(I18n.t("js.voice.video.camera_off")) }
+
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ expect(page).to have_no_css(".voice-call-widget .voice-video-tile.--video")
+
+ click_call_widget_leave_button
+
+ expect(page).to have_no_css(".voice-call-widget")
+ end
+
+ it "opens room actions from the widget overflow menu" do
+ SiteSetting.voice_video_enabled = true
+ install_voice_fake_media
+
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_room_page_widget_mode_button
+
+ expect(page).to have_css(".voice-call-widget", text: room.name)
+
+ # The overflow menu portals out at the dropdown z-index; opening it and
+ # clicking an item asserts it renders above the widget rather than
+ # behind it.
+ find(".voice-call-widget button[data-identifier='voice-widget-room-menu']").click
+ within(".fk-d-menu[data-identifier='voice-widget-room-menu']") do
+ click_button(I18n.t("js.voice.room.info"))
+ end
+
+ expect(page).to have_css(".voice-room-info-modal")
+ end
+
+ it "shows remote fake video when another user publishes a camera stream" do
+ SiteSetting.voice_video_enabled = true
+ other_user.activate
+ other_user.update!(trust_level: TrustLevel[2])
+ Group.refresh_automatic_groups!
+
+ using_session(:alice) do
+ sign_in(user)
+ install_voice_fake_media(
+ video_feeds: [
+ {
+ label: "Alice fake camera",
+ width: 640,
+ height: 360,
+ color: "#2563eb",
+ accent: "#f97316",
+ },
+ ],
+ )
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ end
+
+ using_session(:bob) do
+ sign_in(other_user)
+ install_voice_fake_media(
+ video_feeds: [
+ {
+ label: "Bob fake camera",
+ width: 640,
+ height: 360,
+ color: "#16a34a",
+ accent: "#7c3aed",
+ },
+ ],
+ )
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ local_video_selector =
+ ".voice-video-tile.--video[data-user-id='#{other_user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(local_video_selector)
+ expect(voice_media_track_count(local_video_selector)).to eq(1)
+ end
+
+ using_session(:alice) do
+ remote_video_selector =
+ ".voice-video-tile.--video[data-user-id='#{other_user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(remote_video_selector, wait: 10)
+ expect(voice_media_track_count(remote_video_selector, timeout: 10)).to eq(1)
+ end
+ end
+
+ it "keeps remote video attached in widget mode" do
+ SiteSetting.voice_video_enabled = true
+ other_user.activate
+ other_user.update!(trust_level: TrustLevel[2])
+ Group.refresh_automatic_groups!
+
+ using_session(:alice) do
+ sign_in(user)
+ install_voice_fake_media
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_room_page_widget_mode_button
+
+ expect(page).to have_css(".voice-call-widget", text: room.name)
+ expect(page).to have_current_path("/latest")
+ end
+
+ using_session(:bob) do
+ sign_in(other_user)
+ install_voice_fake_media(
+ video_feeds: [
+ {
+ label: "Bob widget camera",
+ width: 640,
+ height: 360,
+ color: "#16a34a",
+ accent: "#7c3aed",
+ },
+ ],
+ )
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ local_video_selector =
+ ".voice-video-tile.--video[data-user-id='#{other_user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(local_video_selector)
+ expect(voice_media_track_count(local_video_selector)).to eq(1)
+ end
+
+ using_session(:alice) do
+ remote_tile_selector =
+ ".voice-call-widget .voice-video-tile[data-user-id='#{other_user.id}']"
+ remote_video_selector = "#{remote_tile_selector}.--video video.voice-video-tile__video"
+
+ expect(page).to have_css(remote_tile_selector, wait: 10)
+ expect(page).to have_css(remote_video_selector, wait: 10)
+ expect(voice_media_track_count(remote_video_selector, timeout: 10)).to eq(1)
+ expect(voice_media_track_live?(remote_video_selector, timeout: 10)).to eq(true)
+ end
+ end
+ end
+
+ context "with a stage room" do
+ fab!(:stage_room) do
+ Fabricate(
+ :voice_room,
+ name: "Stage Room",
+ creator: user,
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ )
+ end
+
+ before do
+ other_user.activate
+ SiteSetting.voice_video_enabled = true
+ end
+
+ it "lets a joined moderator publish camera video while a listener gets no capture buttons" do
+ using_session(:moderator) do
+ sign_in(user)
+ install_voice_fake_media
+
+ visit("/voice/r/#{stage_room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+
+ # Stage rooms feature the presenter by default instead of the grid.
+ expect(page).to have_css(".voice-room-page.--presentation")
+
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ video_selector =
+ ".voice-video-tile.--video[data-user-id='#{user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(video_selector)
+ expect(voice_media_track_count(video_selector)).to eq(1)
+ end
+
+ using_session(:listener) do
+ sign_in(other_user)
+ install_voice_fake_media
+
+ visit("/voice/r/#{stage_room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+
+ expect(page).to have_css(".voice-room-page.--presentation")
+ expect(page).to have_no_button(I18n.t("js.voice.video.camera_on"))
+ expect(page).to have_no_button(I18n.t("js.voice.video.screen_share_start"))
+ end
+ end
+ end
+
+ context "as admin" do
+ before do
+ admin.activate
+ sign_in(admin)
+ end
+
+ it "shows voice rooms section when rooms exist" do
+ Fabricate(:voice_room, name: "Admin Room", creator: admin, public: true)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to be_visible
+ end
+ end
+
+ context "when user is not in create room groups" do
+ fab!(:low_trust_user) { Fabricate(:user, trust_level: TrustLevel[0]) }
+
+ before do
+ low_trust_user.activate
+ SiteSetting.voice_create_room_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_2]}"
+ sign_in(low_trust_user)
+ end
+
+ it "shows public rooms but hides private rooms" do
+ public_room = Fabricate(:voice_room, name: "Public Room", creator: admin, public: true)
+ private_room = Fabricate(:voice_room, name: "Private Room", creator: admin, public: false)
+
+ visit("/latest")
+
+ expect(voice_sidebar).to be_visible
+ expect(voice_sidebar).to have_room(public_room.name)
+ expect(voice_sidebar).to have_no_room(private_room.name)
+ end
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/voice_settings_spec.rb b/plugins/voice/spec/system/voice_settings_spec.rb
new file mode 100644
index 00000000000..d0307689a80
--- /dev/null
+++ b/plugins/voice/spec/system/voice_settings_spec.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Voice settings" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:room) { Fabricate(:voice_room, name: "Voice Room", creator: admin, public: true) }
+
+ before do
+ user.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ def join_room
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ end
+
+ def open_voice_settings
+ find("button[data-identifier='voice-audio-menu']").click
+ within(".fk-d-menu[data-identifier='voice-audio-menu']") do
+ click_button(I18n.t("js.voice.voice_settings.audio_settings"))
+ end
+ expect(page).to have_css(".voice-voice-settings-modal")
+ end
+
+ it "offers the audio processing controls" do
+ join_room
+ open_voice_settings
+
+ within(".voice-voice-settings") do
+ expect(page).to have_css(".voice-voice-settings__noise-suppression-select")
+ expect(page).to have_content(I18n.t("js.voice.voice_settings.echo_cancellation"))
+ expect(page).to have_content(I18n.t("js.voice.voice_settings.auto_gain_control"))
+ end
+ end
+
+ it "toggles echo cancellation and automatic gain control" do
+ join_room
+ open_voice_settings
+
+ ec_toggle =
+ PageObjects::Components::DToggleSwitch.new(".voice-voice-settings__echo-cancellation-toggle")
+ agc_toggle =
+ PageObjects::Components::DToggleSwitch.new(".voice-voice-settings__auto-gain-toggle")
+
+ expect(ec_toggle.checked?).to eq(true)
+ expect(agc_toggle.checked?).to eq(true)
+
+ ec_toggle.toggle
+ expect(ec_toggle.unchecked?).to eq(true)
+ expect(agc_toggle.checked?).to eq(true)
+ end
+
+ # These run the real engine pipelines (wasm fetch, worklet ready
+ # handshake), so the "AI" assertions only pass once the filter is genuinely
+ # running — the modal spec covers DTLN, the submenu spec covers RNNoise.
+ it "enables AI noise cancellation from the voice settings modal and shows the mic badge" do
+ join_room
+ open_voice_settings
+
+ mode_select =
+ PageObjects::Components::SelectKit.new(".voice-voice-settings__noise-suppression-select")
+ mode_select.expand
+ mode_select.select_row_by_value("ai:dtln")
+
+ expect(page).to have_css(".voice-call-controls__ns-badge", wait: 15)
+ end
+
+ it "enables AI noise cancellation from the mic dropdown submenu" do
+ join_room
+
+ find("button[data-identifier='voice-audio-menu']").click
+ within(".fk-d-menu[data-identifier='voice-audio-menu']") do
+ click_button(I18n.t("js.voice.voice_settings.noise_suppression"))
+ end
+ within(".fk-d-menu[data-identifier='voice-call-submenu']") do
+ click_button(I18n.t("js.voice.voice_settings.noise_suppression_modes.ai_rnnoise"))
+ end
+
+ expect(page).to have_css(".voice-call-controls__ns-badge", wait: 15)
+ end
+end
diff --git a/plugins/voice/spec/system/voice_stage_speak_queue_spec.rb b/plugins/voice/spec/system/voice_stage_speak_queue_spec.rb
new file mode 100644
index 00000000000..4fa61ce87da
--- /dev/null
+++ b/plugins/voice/spec/system/voice_stage_speak_queue_spec.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+# NOTE: outside CI, core pins every test browser to one fixed
+# --remote-debugging-port, so these two-session specs need CI=1 in the
+# environment to launch the second browser locally.
+describe "Voice stage speak queue" do
+ fab!(:moderator, :user)
+ fab!(:listener, :user)
+ fab!(:room) do
+ Fabricate(
+ :voice_room,
+ name: "Stage Room",
+ creator: moderator,
+ public: true,
+ room_type: Voice::Room::ROOM_TYPE_STAGE,
+ )
+ end
+
+ let(:toasts) { PageObjects::Components::Toasts.new }
+
+ before do
+ moderator.activate
+ listener.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_video_enabled = true
+ end
+
+ def join_room(user)
+ sign_in(user)
+ install_voice_fake_media
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ end
+
+ def open_speak_queue
+ find("button[data-identifier='voice-speak-queue-menu']").click
+ end
+
+ def speak_queue_menu
+ ".fk-d-menu[data-identifier='voice-speak-queue-menu']"
+ end
+
+ it "promotes the listener to speaker when a moderator approves their request" do
+ using_session(:alice) { join_room(moderator) }
+
+ using_session(:bob) do
+ join_room(listener)
+
+ expect(page).to have_css(".voice-call-controls__raise-hand")
+ find(".voice-call-controls__raise-hand").click
+ expect(page).to have_css(".voice-call-controls__raise-hand.--active")
+ end
+
+ using_session(:alice) do
+ expect(page).to have_css(".voice-speak-queue-trigger__count", text: "1", wait: 10)
+ expect(page).to have_css(
+ ".sidebar-section[data-section-name='voice-rooms'] .voice-participant-suffix .d-icon-hand",
+ )
+
+ open_speak_queue
+ within(speak_queue_menu) do
+ expect(page).to have_css(".voice-speak-queue__item", text: listener.username)
+ expect(page).to have_css(".voice-speak-queue__position", text: "1")
+ find(".voice-speak-queue__approve").click
+ end
+ end
+
+ using_session(:bob) do
+ expect(toasts).to have_success(I18n.t("js.voice.stage.promoted_to_speaker"))
+ expect(page).to have_no_css(".voice-call-controls__raise-hand")
+ expect(page).to have_button(I18n.t("js.voice.video.camera_on"))
+ end
+
+ using_session(:alice) do
+ within(speak_queue_menu) { expect(page).to have_css(".voice-speak-queue__empty") }
+ expect(page).to have_no_css(".voice-speak-queue-trigger__count")
+ end
+ end
+
+ it "lets the listener raise their hand again after a moderator dismisses the request" do
+ using_session(:alice) { join_room(moderator) }
+
+ using_session(:bob) do
+ join_room(listener)
+
+ find(".voice-call-controls__raise-hand").click
+ expect(page).to have_css(".voice-call-controls__raise-hand.--active")
+ end
+
+ using_session(:alice) do
+ expect(page).to have_css(".voice-speak-queue-trigger__count", text: "1", wait: 10)
+
+ open_speak_queue
+ within(speak_queue_menu) do
+ find(".voice-speak-queue__dismiss").click
+ expect(page).to have_css(".voice-speak-queue__empty")
+ end
+ expect(page).to have_no_css(".voice-speak-queue-trigger__count")
+ end
+
+ using_session(:bob) do
+ expect(toasts).to have_default(I18n.t("js.voice.stage.request_dismissed"))
+ expect(page).to have_css(".voice-call-controls__raise-hand:not(.--active)")
+
+ find(".voice-call-controls__raise-hand").click
+ expect(page).to have_css(".voice-call-controls__raise-hand.--active")
+ end
+
+ using_session(:alice) do
+ expect(page).to have_css(".voice-speak-queue-trigger__count", text: "1", wait: 10)
+ end
+ end
+
+ it "clears the moderator's queue when the listener lowers their own hand" do
+ using_session(:alice) { join_room(moderator) }
+
+ using_session(:bob) do
+ join_room(listener)
+
+ find(".voice-call-controls__raise-hand").click
+ expect(page).to have_css(".voice-call-controls__raise-hand.--active")
+ end
+
+ using_session(:alice) do
+ expect(page).to have_css(".voice-speak-queue-trigger__count", text: "1", wait: 10)
+ end
+
+ using_session(:bob) do
+ find(".voice-call-controls__raise-hand.--active").click
+ expect(page).to have_css(".voice-call-controls__raise-hand:not(.--active)")
+ end
+
+ using_session(:alice) do
+ expect(page).to have_no_css(".voice-speak-queue-trigger__count", wait: 10)
+
+ open_speak_queue
+ within(speak_queue_menu) { expect(page).to have_css(".voice-speak-queue__empty") }
+ end
+ end
+end
diff --git a/plugins/voice/spec/system/voice_subtitles_spec.rb b/plugins/voice/spec/system/voice_subtitles_spec.rb
new file mode 100644
index 00000000000..6feb048f6b4
--- /dev/null
+++ b/plugins/voice/spec/system/voice_subtitles_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Voice subtitles" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:room) { Fabricate(:voice_room, name: "Voice Room", creator: admin, public: true) }
+
+ before do
+ user.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ def stub_webgpu
+ page.driver.with_playwright_page do |playwright_page|
+ playwright_page.add_init_script(script: <<~JS)
+ if (!navigator.gpu) {
+ Object.defineProperty(navigator, "gpu", { configurable: true, value: {} });
+ }
+ JS
+ end
+ end
+
+ def join_room
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ end
+
+ def open_voice_settings
+ find("button[data-identifier='voice-audio-menu']").click
+ within(".fk-d-menu[data-identifier='voice-audio-menu']") do
+ click_button(I18n.t("js.voice.voice_settings.audio_settings"))
+ end
+ expect(page).to have_css(".voice-voice-settings-modal")
+ end
+
+ it "hides the subtitles toggle when the site setting is off" do
+ SiteSetting.voice_subtitles_enabled = false
+ stub_webgpu
+ join_room
+ open_voice_settings
+
+ within(".voice-voice-settings") do
+ expect(page).to have_no_content(I18n.t("js.voice.voice_settings.subtitles"))
+ end
+ end
+
+ it "offers the subtitles toggle and enables the caption overlay" do
+ SiteSetting.voice_subtitles_enabled = true
+ stub_webgpu
+ join_room
+ open_voice_settings
+
+ within(".voice-voice-settings") do
+ expect(page).to have_content(I18n.t("js.voice.voice_settings.subtitles"))
+ end
+
+ toggle = PageObjects::Components::DToggleSwitch.new(".voice-voice-settings__subtitles-toggle")
+ toggle.toggle
+ expect(toggle.checked?).to eq(true)
+
+ find(".modal-close").click
+ expect(page).to have_css(".voice-captions", visible: :all)
+ end
+end
diff --git a/plugins/voice/spec/system/voice_video_settings_spec.rb b/plugins/voice/spec/system/voice_video_settings_spec.rb
new file mode 100644
index 00000000000..696438f4f2f
--- /dev/null
+++ b/plugins/voice/spec/system/voice_video_settings_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+require_relative "../support/voice_fake_media"
+
+describe "Voice video settings" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:room) { Fabricate(:voice_room, name: "Video Room", creator: admin, public: true) }
+
+ let(:camera_select) do
+ PageObjects::Components::SelectKit.new(".voice-video-settings__camera-select")
+ end
+
+ before do
+ user.activate
+ SiteSetting.voice_enabled = true
+ SiteSetting.voice_mesh_privacy_warning_enabled = false
+ SiteSetting.voice_allowed_groups =
+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"
+ SiteSetting.voice_video_enabled = true
+ sign_in(user)
+ install_voice_fake_media
+ end
+
+ def join_room
+ visit("/voice/r/#{room.slug}")
+ click_button(I18n.t("js.voice.room.join"))
+ expect(page).to have_css(".voice-room-page__leave")
+ end
+
+ def open_video_menu
+ find("button[data-identifier='voice-video-menu']").click
+ expect(page).to have_css(".fk-d-menu[data-identifier='voice-video-menu']")
+ end
+
+ def open_video_settings
+ open_video_menu
+ within(".fk-d-menu[data-identifier='voice-video-menu']") do
+ click_button(I18n.t("js.voice.video_settings.title"))
+ end
+ expect(page).to have_css(".voice-video-settings-modal")
+ end
+
+ it "offers voice and video settings from the call menus" do
+ join_room
+
+ find("button[data-identifier='voice-audio-menu']").click
+ within(".fk-d-menu[data-identifier='voice-audio-menu']") do
+ expect(page).to have_button(I18n.t("js.voice.voice_settings.audio_settings"))
+ end
+ find("button[data-identifier='voice-audio-menu']").click
+
+ open_video_menu
+ within(".fk-d-menu[data-identifier='voice-video-menu']") do
+ expect(page).to have_button(I18n.t("js.voice.video_settings.title"))
+ end
+ end
+
+ it "shows a camera preview and lists camera devices" do
+ join_room
+ open_video_settings
+
+ expect(page).to have_css(".voice-video-settings__preview video")
+ expect(voice_media_track_live?(".voice-video-settings__preview video")).to eq(true)
+
+ camera_select.expand
+ expect(camera_select).to have_option_name("Voice fake camera A")
+ expect(camera_select).to have_option_name("Voice fake camera B")
+ end
+
+ it "keeps the published camera live after switching devices" do
+ join_room
+ click_button(I18n.t("js.voice.video.camera_on"))
+
+ video_selector =
+ ".voice-video-tile.--video[data-user-id='#{user.id}'] video.voice-video-tile__video"
+ expect(page).to have_css(video_selector)
+
+ open_video_settings
+ camera_select.expand
+ camera_select.select_row_by_name("Voice fake camera B")
+
+ expect(camera_select).to have_selected_name("Voice fake camera B")
+ expect(voice_media_track_live?(video_selector)).to eq(true)
+ end
+
+ it "shows the background blur toggle when the setting is enabled" do
+ join_room
+ open_video_settings
+
+ within(".voice-video-settings") { expect(page).to have_css(".d-toggle-switch") }
+ end
+
+ it "hides background blur when the site setting is disabled" do
+ SiteSetting.voice_video_background_blur_enabled = false
+
+ join_room
+ open_video_settings
+
+ within(".voice-video-settings") do
+ expect(page).to have_css(".voice-video-settings__camera-select")
+ expect(page).to have_no_css(".d-toggle-switch")
+ end
+ end
+end
diff --git a/plugins/voice/spec/validators/voice_livekit_policy_validator_spec.rb b/plugins/voice/spec/validators/voice_livekit_policy_validator_spec.rb
new file mode 100644
index 00000000000..93d1760b548
--- /dev/null
+++ b/plugins/voice/spec/validators/voice_livekit_policy_validator_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+RSpec.describe VoiceLivekitPolicyValidator do
+ subject(:validator) { described_class.new }
+
+ it "always accepts the disabled policy, even unconfigured" do
+ expect(validator.valid_value?("disabled")).to eq(true)
+ end
+
+ it "accepts a non-disabled policy when fully configured" do
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+
+ expect(validator.valid_value?("per_room")).to eq(true)
+ expect(validator.valid_value?("all_rooms")).to eq(true)
+ end
+
+ it "rejects a non-disabled policy when the url is blank or invalid" do
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+
+ expect(validator.valid_value?("per_room")).to eq(false)
+
+ # An invalid stored value (the URL validator refuses assignments, so this
+ # can only be pre-existing data) still blocks policy activation.
+ SiteSetting.stubs(:voice_livekit_url).returns("https://livekit.example.com")
+ expect(validator.valid_value?("per_room")).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_livekit_policy_requires_url"),
+ )
+ end
+
+ it "rejects a non-disabled policy when the api key is missing" do
+ SiteSetting.voice_livekit_url = "wss://livekit.example.com"
+ SiteSetting.voice_livekit_api_secret = "lk_api_secret"
+
+ expect(validator.valid_value?("all_rooms")).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_livekit_policy_requires_api_key"),
+ )
+ end
+
+ it "rejects a non-disabled policy when the api secret is missing" do
+ SiteSetting.voice_livekit_url = "ws://livekit.internal:7880"
+ SiteSetting.voice_livekit_api_key = "lk_api_key"
+
+ expect(validator.valid_value?("all_rooms")).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_livekit_policy_requires_api_secret"),
+ )
+ end
+end
diff --git a/plugins/voice/spec/validators/voice_livekit_url_validator_spec.rb b/plugins/voice/spec/validators/voice_livekit_url_validator_spec.rb
new file mode 100644
index 00000000000..944cab0b5b1
--- /dev/null
+++ b/plugins/voice/spec/validators/voice_livekit_url_validator_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+RSpec.describe VoiceLivekitUrlValidator do
+ subject(:validator) { described_class.new }
+
+ it "accepts a blank value" do
+ expect(validator.valid_value?("")).to eq(true)
+ expect(validator.valid_value?(nil)).to eq(true)
+ end
+
+ it "accepts ws:// and wss:// origins outside production" do
+ expect(validator.valid_value?("wss://livekit.example.com")).to eq(true)
+ expect(validator.valid_value?("ws://livekit.internal:7880")).to eq(true)
+ end
+
+ it "rejects URLs that are not ws(s)://, have no host, or embed credentials" do
+ [
+ "https://livekit.example.com",
+ "wss://",
+ "wss://user:[email protected]",
+ "not a url",
+ ].each do |value|
+ expect(validator.valid_value?(value)).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_livekit_url_invalid"),
+ )
+ end
+ end
+
+ it "requires wss:// in production" do
+ Rails.env.stubs(:production?).returns(true)
+
+ expect(validator.valid_value?("wss://livekit.example.com")).to eq(true)
+ expect(validator.valid_value?("ws://livekit.example.com")).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_livekit_url_requires_wss"),
+ )
+ end
+
+ describe ".acceptable?" do
+ it "requires a present, valid URL" do
+ expect(described_class.acceptable?("")).to eq(false)
+ expect(described_class.acceptable?("https://livekit.example.com")).to eq(false)
+ expect(described_class.acceptable?("wss://livekit.example.com")).to eq(true)
+ end
+ end
+end
diff --git a/plugins/voice/spec/validators/voice_turn_secret_servers_validator_spec.rb b/plugins/voice/spec/validators/voice_turn_secret_servers_validator_spec.rb
new file mode 100644
index 00000000000..1a5945be9bd
--- /dev/null
+++ b/plugins/voice/spec/validators/voice_turn_secret_servers_validator_spec.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+RSpec.describe VoiceTurnSecretServersValidator do
+ subject(:validator) { described_class.new }
+
+ it "always accepts a blank value" do
+ expect(validator.valid_value?("")).to eq(true)
+ expect(validator.valid_value?(nil)).to eq(true)
+ end
+
+ it "accepts server urls when the TURN secret is configured" do
+ SiteSetting.voice_turn_secret = "coturn-shared-secret"
+
+ expect(validator.valid_value?("turn:coturn.example.com:3478")).to eq(true)
+ end
+
+ it "rejects server urls when the TURN secret is blank" do
+ expect(validator.valid_value?("turn:coturn.example.com:3478")).to eq(false)
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.voice_turn_secret_servers_requires_secret"),
+ )
+ end
+end
diff --git a/plugins/voice/test/javascripts/acceptance/voice-anon-sidebar-test.gjs b/plugins/voice/test/javascripts/acceptance/voice-anon-sidebar-test.gjs
new file mode 100644
index 00000000000..6189d1c0486
--- /dev/null
+++ b/plugins/voice/test/javascripts/acceptance/voice-anon-sidebar-test.gjs
@@ -0,0 +1,62 @@
+import { visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Voice anon sidebar", function (needs) {
+ needs.settings({ voice_enabled: true });
+ needs.site({ voice_public_access: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/voice/rooms.json", () =>
+ helper.response({
+ rooms: [
+ {
+ id: 1,
+ name: "Public room",
+ slug: "public-room",
+ public: true,
+ room_type: "open",
+ active_participants: [
+ {
+ id: 2,
+ username: "jane",
+ name: "Jane",
+ avatar_template: "/letter_avatar_proxy/v4/letter/j/{size}.png",
+ },
+ ],
+ },
+ ],
+ can_create_room: false,
+ })
+ );
+ });
+
+ test("renders public rooms for anonymous visitors", async function (assert) {
+ await visit("/latest");
+
+ assert
+ .dom(".sidebar-section[data-section-name='voice-rooms']")
+ .exists("the rooms section is rendered");
+ assert
+ .dom("[data-link-name='voice-room-1']")
+ .hasText("Public room", "the public room link is rendered");
+ assert
+ .dom("[data-link-name='voice-participant-1-2']")
+ .hasText("jane", "public room participants are rendered");
+
+ const sectionNames = [
+ ...document.querySelectorAll(
+ ".sidebar-sections-anonymous > .sidebar-section"
+ ),
+ ].map((section) => section.dataset.sectionName);
+
+ assert.true(
+ sectionNames.includes("categories"),
+ "the standard navigation sections are rendered"
+ );
+ assert.true(
+ sectionNames.indexOf("voice-rooms") > sectionNames.indexOf("categories"),
+ "rooms render after the standard navigation sections, as they do for logged-in users"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/acceptance/voice-participant-menu-test.gjs b/plugins/voice/test/javascripts/acceptance/voice-participant-menu-test.gjs
new file mode 100644
index 00000000000..aa0c0c4edf6
--- /dev/null
+++ b/plugins/voice/test/javascripts/acceptance/voice-participant-menu-test.gjs
@@ -0,0 +1,69 @@
+import { getOwner } from "@ember/owner";
+import { click, triggerEvent, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+const PARTICIPANT_ROW = "[data-link-name='voice-participant-1-2']";
+const MENU = ".fk-d-menu[data-identifier='voice-participant-menu']";
+
+acceptance("Voice participant context menu", function (needs) {
+ needs.user();
+ needs.settings({ voice_enabled: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/voice/rooms.json", () =>
+ helper.response({
+ rooms: [
+ {
+ id: 1,
+ name: "Conf room",
+ slug: "conf-room",
+ public: true,
+ room_type: "open",
+ active_participants: [
+ {
+ id: 2,
+ username: "jane",
+ name: "Jane",
+ avatar_template: "/letter_avatar_proxy/v4/letter/j/{size}.png",
+ },
+ ],
+ },
+ ],
+ can_create_room: false,
+ })
+ );
+ });
+
+ test("offers no menu for a room the user is not connected to", async function (assert) {
+ await visit("/latest");
+
+ assert.dom(PARTICIPANT_ROW).exists("the participant row still renders");
+ assert
+ .dom(`${PARTICIPANT_ROW} .sidebar-section-hover-button`)
+ .doesNotExist("the hover menu button is not rendered");
+
+ await triggerEvent(PARTICIPANT_ROW, "contextmenu");
+
+ assert.dom(MENU).doesNotExist("right-click does not open the menu either");
+ });
+
+ test("offers the menu for a room the user is connected to", async function (assert) {
+ const voiceWebrtc = getOwner(this).lookup("service:voice-webrtc");
+ voiceWebrtc.connectionStateFor = () => "connected";
+
+ await visit("/latest");
+
+ await click(`${PARTICIPANT_ROW} .sidebar-section-hover-button`);
+
+ assert.dom(MENU).exists("the participant menu opens");
+ assert
+ .dom(".voice-participant-sidebar-context-menu__volume-slider")
+ .exists("audio controls are available");
+ assert
+ .dom(".voice-participant-sidebar-context-menu__spotlight-btn")
+ .doesNotExist(
+ "page-only spotlight controls are not shown in the sidebar"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/acceptance/voice-transcript-draft-icon-test.js b/plugins/voice/test/javascripts/acceptance/voice-transcript-draft-icon-test.js
new file mode 100644
index 00000000000..2509f0068b6
--- /dev/null
+++ b/plugins/voice/test/javascripts/acceptance/voice-transcript-draft-icon-test.js
@@ -0,0 +1,43 @@
+import { click, visit, waitFor } from "@ember/test-helpers";
+import { test } from "qunit";
+import {
+ acceptance,
+ updateCurrentUser,
+} from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Voice transcript draft icon", function (needs) {
+ needs.user();
+ needs.settings({ voice_enabled: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/voice/rooms.json", () =>
+ helper.response({ rooms: [], can_create_room: false })
+ );
+ server.get("/drafts.json", () =>
+ helper.response({
+ drafts: [
+ {
+ draft_key: "new_topic_voice_1_1756400000000",
+ data: '{"title":"Sala do Bar — transcript"}',
+ },
+ { draft_key: "new_topic", data: '{"title":"A topic draft"}' },
+ ],
+ })
+ );
+ });
+
+ test("transcript drafts get the transcript icon, others keep theirs", async function (assert) {
+ updateCurrentUser({ draft_count: 2 });
+
+ await visit("/");
+ await click("button.topic-drafts-menu-trigger");
+ await waitFor(".topic-drafts-menu-content");
+
+ assert
+ .dom(".topic-drafts-item:first-child svg.d-icon-closed-captioning")
+ .exists("the transcript draft uses the transcript icon");
+ assert
+ .dom(".topic-drafts-item:last-child svg.d-icon-layer-group")
+ .exists("an ordinary topic draft keeps the default icon");
+ });
+});
diff --git a/plugins/voice/test/javascripts/acceptance/voice-widget-mode-test.js b/plugins/voice/test/javascripts/acceptance/voice-widget-mode-test.js
new file mode 100644
index 00000000000..1d5d9d8c69a
--- /dev/null
+++ b/plugins/voice/test/javascripts/acceptance/voice-widget-mode-test.js
@@ -0,0 +1,227 @@
+import { getOwner } from "@ember/owner";
+import { click, currentURL, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+const ROOM = {
+ id: 1,
+ name: "Sala do Bar",
+ slug: "sala-do-bar",
+ public: true,
+ room_type: "open",
+ active_participants: [],
+};
+
+function stubRooms(needs) {
+ needs.settings({ voice_enabled: true });
+ needs.pretender((server, helper) => {
+ server.get("/voice/rooms.json", () =>
+ helper.response({ rooms: [ROOM], can_create_room: false })
+ );
+ server.get(`/voice/rooms/${ROOM.slug}.json`, () =>
+ helper.response({ room: ROOM })
+ );
+ });
+}
+
+function stubJoin(context) {
+ const joined = [];
+ const voiceWebrtc = getOwner(context).lookup("service:voice-webrtc");
+ voiceWebrtc.join = (room) => {
+ joined.push(room.slug);
+ return Promise.resolve();
+ };
+ return { joined, voiceWebrtc };
+}
+
+acceptance("Voice room widget mode", function (needs) {
+ needs.user();
+ stubRooms(needs);
+
+ test("joins the room without leaving the current page", async function (assert) {
+ await visit("/latest");
+ const { joined } = stubJoin(this);
+
+ try {
+ await visit(`/voice/r/${ROOM.slug}?join=true&widget=true`);
+ } catch (error) {
+ assert.strictEqual(
+ error.message,
+ "TransitionAborted",
+ "it aborts the transition"
+ );
+ }
+
+ assert.strictEqual(currentURL(), "/latest", "stays where the user was");
+ assert.deepEqual(joined, [ROOM.slug], "joins the room in the background");
+ });
+
+ test("lands on the homepage when opened from a full page load", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?join=true&widget=true`);
+
+ assert.strictEqual(currentURL(), "/latest", "does not open the room page");
+ assert.deepEqual(joined, [ROOM.slug], "joins the room in the background");
+ });
+
+ test("accepts a valueless widget param", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?join=true&widget`);
+
+ assert.strictEqual(currentURL(), "/latest", "does not open the room page");
+ assert.deepEqual(joined, [ROOM.slug], "joins the room in the background");
+ });
+
+ test("ignores an explicitly falsy widget param", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?widget=false`);
+
+ assert.strictEqual(
+ currentURL(),
+ `/voice/r/${ROOM.slug}?widget=false`,
+ "opens the room page"
+ );
+ assert.deepEqual(joined, [], "does not join");
+ });
+
+ test("needs a join to dock, so the widget param alone opens the room page", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?widget=true`);
+
+ assert.strictEqual(
+ currentURL(),
+ `/voice/r/${ROOM.slug}?widget=true`,
+ "opens the room page"
+ );
+ assert.deepEqual(joined, [], "does not join without being asked to");
+ });
+
+ test("docks the call back to the page the user came from when they join", async function (assert) {
+ const { joined, voiceWebrtc } = stubJoin(this);
+ voiceWebrtc.setCallWidgetHidden(true);
+
+ await visit("/t/internationalization-localization/280");
+ await visit(`/voice/r/${ROOM.slug}?widget=true`);
+ await click(".voice-room-page__join");
+
+ assert.deepEqual(joined, [ROOM.slug], "joins the room");
+ assert.strictEqual(
+ currentURL(),
+ "/t/internationalization-localization/280",
+ "returns to where the user was instead of resetting their place"
+ );
+ assert.false(
+ voiceWebrtc.callWidgetHidden,
+ "the call widget is no longer hidden"
+ );
+ });
+
+ test("skips room pages when picking somewhere to return to", async function (assert) {
+ const { joined } = stubJoin(this);
+ // Consuming `?join` leaves this room in the history under another spelling.
+ getOwner(this)
+ .lookup("service:session-store")
+ .setObject({
+ key: "routeHistory",
+ value: [`/voice/r/${ROOM.slug}?join=true`, "/latest"],
+ });
+
+ await visit(`/voice/r/${ROOM.slug}?widget=true`);
+ await click(".voice-room-page__join");
+
+ assert.deepEqual(joined, [ROOM.slug], "joins the room");
+ assert.strictEqual(
+ currentURL(),
+ "/latest",
+ "does not dock back onto a room page"
+ );
+ });
+
+ test("docks to the homepage when there is nowhere to return to", async function (assert) {
+ const { joined } = stubJoin(this);
+ getOwner(this).lookup("service:session-store").remove("routeHistory");
+
+ await visit(`/voice/r/${ROOM.slug}?widget=true`);
+ await click(".voice-room-page__join");
+
+ assert.deepEqual(joined, [ROOM.slug], "joins the room");
+ assert.strictEqual(currentURL(), "/latest", "leaves the room page");
+ });
+
+ test("keeps a join on the room page when the param is falsy", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?widget=false`);
+ await click(".voice-room-page__join");
+
+ assert.deepEqual(joined, [ROOM.slug], "joins the room");
+ assert.strictEqual(
+ currentURL(),
+ `/voice/r/${ROOM.slug}?widget=false`,
+ "stays on the room page"
+ );
+ });
+
+ test("leaves a join without a widget param on the room page", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?join=true`);
+
+ assert.strictEqual(
+ currentURL(),
+ `/voice/r/${ROOM.slug}`,
+ "opens the room page and consumes the join param"
+ );
+ assert.deepEqual(joined, [ROOM.slug], "the room page joins the call");
+ });
+
+ test("shows a widget the user had dismissed", async function (assert) {
+ const { voiceWebrtc } = stubJoin(this);
+ voiceWebrtc.setCallWidgetHidden(true);
+
+ await visit(`/voice/r/${ROOM.slug}?join=true&widget=true`);
+
+ assert.false(
+ voiceWebrtc.callWidgetHidden,
+ "the call widget is no longer hidden"
+ );
+ });
+
+ test("opens the room page when the params are absent", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}`);
+
+ assert.strictEqual(currentURL(), `/voice/r/${ROOM.slug}`);
+ assert.deepEqual(joined, [], "does not join without being asked to");
+ });
+});
+
+acceptance("Voice room widget mode - anonymous", function (needs) {
+ stubRooms(needs);
+ needs.site({ voice_public_access: true });
+
+ test("does not dock the call, since anonymous visitors cannot join", async function (assert) {
+ const { joined } = stubJoin(this);
+
+ await visit(`/voice/r/${ROOM.slug}?join=true&widget=true`);
+
+ // The room page takes the join request instead, which prompts for a login.
+ assert.strictEqual(currentURL(), "/login", "prompts for a login");
+ assert.deepEqual(joined, [], "does not join");
+ });
+
+ test("opens the room page for a widget param on its own", async function (assert) {
+ await visit(`/voice/r/${ROOM.slug}?widget=true`);
+
+ assert.strictEqual(
+ currentURL(),
+ `/voice/r/${ROOM.slug}?widget=true`,
+ "opens the room page"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-context-menu-test.gjs b/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-context-menu-test.gjs
new file mode 100644
index 00000000000..c77d87cb235
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-context-menu-test.gjs
@@ -0,0 +1,85 @@
+import Service from "@ember/service";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import VoiceParticipantSidebarContextMenu from "discourse/plugins/voice/discourse/components/voice-participant-sidebar-context-menu";
+
+class VoiceWebrtcStub extends Service {
+ getParticipantVolume() {
+ return 1;
+ }
+
+ isParticipantMuted() {
+ return false;
+ }
+}
+
+module(
+ "Integration | Component | VoiceParticipantSidebarContextMenu",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ logIn(this.owner);
+ this.owner.unregister("service:voice-webrtc");
+ this.owner.register("service:voice-webrtc", VoiceWebrtcStub);
+
+ this.selectedParticipantId = null;
+ this.closed = false;
+ this.menuData = {
+ room: { id: 1, room_type: "open" },
+ participant: { id: 2, username: "bob" },
+ isCurrentUser: false,
+ onSpotlight: (participantId) => {
+ this.selectedParticipantId = participantId;
+ },
+ };
+ this.closeMenu = () => {
+ this.closed = true;
+ };
+ });
+
+ test("spotlights the participant for the viewer", async function (assert) {
+ await render(
+ <template>
+ <VoiceParticipantSidebarContextMenu
+ @data={{this.menuData}}
+ @close={{this.closeMenu}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".voice-participant-sidebar-context-menu__spotlight-btn")
+ .hasText("Spotlight for me", "offers the local spotlight action");
+
+ await click(".voice-participant-sidebar-context-menu__spotlight-btn");
+
+ assert.strictEqual(
+ this.selectedParticipantId,
+ 2,
+ "selects the menu's participant"
+ );
+ assert.true(this.closed, "closes the participant menu");
+ });
+
+ test("shows when the participant is already spotlighted", async function (assert) {
+ this.menuData.isSpotlighted = true;
+
+ await render(
+ <template>
+ <VoiceParticipantSidebarContextMenu
+ @data={{this.menuData}}
+ @close={{this.closeMenu}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".voice-participant-sidebar-context-menu__spotlight-btn")
+ .hasText("Remove from spotlight", "offers to remove the spotlight")
+ .hasAttribute("aria-pressed", "true", "exposes the active state");
+ });
+ }
+);
diff --git a/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-suffix-test.gjs b/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-suffix-test.gjs
new file mode 100644
index 00000000000..afa4127c6fe
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice-participant-sidebar-suffix-test.gjs
@@ -0,0 +1,51 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import VoiceParticipantSidebarSuffix from "discourse/plugins/voice/discourse/components/voice-participant-sidebar-suffix";
+
+module(
+ "Integration | Component | voice-participant-sidebar-suffix",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders every applicable state icon simultaneously", async function (assert) {
+ const suffixArgs = {
+ isScreenSharing: true,
+ isVideoOn: true,
+ isPtt: false,
+ isMuted: true,
+ isDeafened: true,
+ };
+
+ await render(
+ <template>
+ <VoiceParticipantSidebarSuffix @suffixArgs={{suffixArgs}} />
+ </template>
+ );
+
+ assert.dom(".voice-participant-suffix .d-icon-display").exists();
+ assert.dom(".voice-participant-suffix .d-icon-video").exists();
+ assert.dom(".voice-participant-suffix .d-icon-microphone-slash").exists();
+ assert.dom(".voice-participant-suffix .d-icon-volume-xmark").exists();
+ });
+
+ test("renders the wrapper even with no active states", async function (assert) {
+ const suffixArgs = {
+ isScreenSharing: false,
+ isVideoOn: false,
+ isPtt: false,
+ isMuted: false,
+ isDeafened: false,
+ };
+
+ await render(
+ <template>
+ <VoiceParticipantSidebarSuffix @suffixArgs={{suffixArgs}} />
+ </template>
+ );
+
+ assert.dom(".voice-participant-suffix").exists();
+ assert.dom(".voice-participant-suffix .d-icon").doesNotExist();
+ });
+ }
+);
diff --git a/plugins/voice/test/javascripts/integration/components/voice-room-form-test.gjs b/plugins/voice/test/javascripts/integration/components/voice-room-form-test.gjs
new file mode 100644
index 00000000000..fb091cd6279
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice-room-form-test.gjs
@@ -0,0 +1,114 @@
+import Service from "@ember/service";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import VoiceRoomForm from "discourse/plugins/voice/discourse/components/voice-room-form";
+
+class ChatApiStub extends Service {
+ channels() {
+ return {
+ items: [{ id: 6, title: "Team Meeting", threadingEnabled: true }],
+ async load() {},
+ };
+ }
+}
+
+module("Integration | Component | voice-room-form", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.chat_enabled = true;
+ this.siteSettings.voice_chat_enabled = true;
+ this.siteSettings.voice_video_enabled = false;
+
+ this.owner.unregister("service:chat-api");
+ this.owner.register("service:chat-api", ChatApiStub);
+ });
+
+ test("shows the chat settings for a room that already has a chat channel linked", async function (assert) {
+ this.room = {
+ name: "Team Meeting",
+ description: "",
+ public: true,
+ room_type: "open",
+ max_participants: null,
+ video_enabled: true,
+ chat_channel_id: 6,
+ chat_idle_minutes: 2,
+ };
+
+ await render(<template><VoiceRoomForm @room={{this.room}} /></template>);
+
+ assert.dom('select[name="chat_channel_id"]').hasValue("6");
+ assert
+ .dom('input[name="chat_idle_minutes"]')
+ .exists("the idle-minutes field is shown once a channel is linked");
+ });
+
+ test("can clear a linked chat channel back to none", async function (assert) {
+ this.room = {
+ name: "Team Meeting",
+ description: "",
+ public: true,
+ room_type: "open",
+ max_participants: null,
+ video_enabled: true,
+ chat_channel_id: 6,
+ chat_idle_minutes: 2,
+ };
+
+ await render(<template><VoiceRoomForm @room={{this.room}} /></template>);
+ assert.dom('input[name="chat_idle_minutes"]').exists();
+
+ await formKit().field("chat_channel_id").select("__NONE__");
+
+ assert.dom('select[name="chat_channel_id"]').hasValue("__NONE__");
+ assert
+ .dom('input[name="chat_idle_minutes"]')
+ .doesNotExist("idle-minutes field hides once the channel is cleared");
+ });
+
+ test("shows the media server toggle only when per-room LiveKit is available", async function (assert) {
+ this.room = {
+ name: "Town hall",
+ description: "",
+ public: true,
+ room_type: "open",
+ max_participants: null,
+ video_enabled: true,
+ livekit_enabled: false,
+ chat_channel_id: null,
+ chat_idle_minutes: 15,
+ };
+
+ this.owner
+ .lookup("service:site")
+ .set("voice_livekit_per_room_available", true);
+ await render(<template><VoiceRoomForm @room={{this.room}} /></template>);
+ assert.dom('[data-name="livekit_enabled"]').exists();
+
+ this.owner
+ .lookup("service:site")
+ .set("voice_livekit_per_room_available", false);
+ await render(<template><VoiceRoomForm @room={{this.room}} /></template>);
+ assert.dom('[data-name="livekit_enabled"]').doesNotExist();
+ });
+
+ test("hides the chat settings when no chat channel is linked", async function (assert) {
+ this.room = {
+ name: "Chill",
+ description: "",
+ public: true,
+ room_type: "open",
+ max_participants: null,
+ video_enabled: true,
+ chat_channel_id: null,
+ chat_idle_minutes: 15,
+ };
+
+ await render(<template><VoiceRoomForm @room={{this.room}} /></template>);
+
+ assert.dom('input[name="chat_idle_minutes"]').doesNotExist();
+ });
+});
diff --git a/plugins/voice/test/javascripts/integration/components/voice-room-page-test.gjs b/plugins/voice/test/javascripts/integration/components/voice-room-page-test.gjs
new file mode 100644
index 00000000000..a52a1018142
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice-room-page-test.gjs
@@ -0,0 +1,343 @@
+import { tracked } from "@glimmer/tracking";
+import Service from "@ember/service";
+import { click, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import VoiceRoomPage from "discourse/plugins/voice/discourse/components/voice/room-page";
+
+class VoiceRoomsStub extends Service {
+ @tracked rooms = [];
+
+ roomById(id) {
+ return this.rooms.find((room) => Number(room.id) === Number(id));
+ }
+
+ isParticipantSpeaking() {
+ return false;
+ }
+}
+
+class VoiceWebrtcStub extends Service {
+ @tracked activeRoomId = 1;
+ @tracked audioEnabled = true;
+ @tracked deafened = false;
+ @tracked localVideoKind = null;
+ @tracked pttEnabled = false;
+
+ screenShareSupported = true;
+
+ get activeRoom() {
+ return this.voiceRooms.roomById(this.activeRoomId);
+ }
+
+ connectionStateFor() {
+ return "connected";
+ }
+
+ videoAllowedIn() {
+ return true;
+ }
+
+ canPublishVideo() {
+ return true;
+ }
+
+ isActiveRoom() {
+ return false;
+ }
+
+ isTranscribingRoom() {
+ return false;
+ }
+
+ setWatching() {}
+ join() {}
+ leave() {}
+ toggleMute() {}
+ toggleDeafen() {}
+ toggleCamera() {}
+ toggleScreenShare() {}
+ attachVideoStream() {}
+ getParticipantVolume() {
+ return 1;
+ }
+
+ isParticipantMuted() {
+ return false;
+ }
+
+ remoteStreamFor() {
+ return { id: "stream" };
+ }
+}
+
+class RouterStub extends Service {
+ transitionTo() {}
+}
+
+class ModalStub extends Service {
+ show() {}
+}
+
+class CapabilitiesStub extends Service {
+ viewport = { md: true };
+ touch = false;
+}
+
+async function selectParticipantFromOpenMenu(owner) {
+ const menuService = owner.lookup("service:menu");
+ const menu = menuService.getByIdentifier("voice-participant-menu");
+ menu.options.data.onSpotlight(menu.options.data.participant.id);
+ await menuService.close(menu);
+}
+
+module("Integration | Component | Voice | RoomPage", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.currentUser = logIn(this.owner);
+
+ this.owner.unregister("service:capabilities");
+ this.owner.register("service:capabilities", CapabilitiesStub);
+ this.owner.unregister("service:voice-rooms");
+ this.owner.register("service:voice-rooms", VoiceRoomsStub);
+ this.owner.unregister("service:voice-webrtc");
+ this.owner.register("service:voice-webrtc", VoiceWebrtcStub);
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+ this.owner.unregister("service:modal");
+ this.owner.register("service:modal", ModalStub);
+
+ this.voiceRooms = this.owner.lookup("service:voice-rooms");
+ this.voiceWebrtc = this.owner.lookup("service:voice-webrtc");
+ this.voiceWebrtc.voiceRooms = this.voiceRooms;
+
+ this.room = {
+ id: 1,
+ slug: "test-room",
+ name: "Test Room",
+ chat_available: true,
+ video_enabled: true,
+ description_excerpt: "Room description",
+ active_participants: [
+ {
+ id: this.currentUser.id,
+ username: this.currentUser.username,
+ avatar_template: "/letter_avatar_proxy/v4/letter/a/{size}.png",
+ },
+ {
+ id: 2,
+ username: "bob",
+ avatar_template: "/letter_avatar_proxy/v4/letter/b/{size}.png",
+ is_video_on: true,
+ },
+ {
+ id: 3,
+ username: "cara",
+ avatar_template: "/letter_avatar_proxy/v4/letter/c/{size}.png",
+ is_video_on: true,
+ },
+ ],
+ };
+
+ this.voiceRooms.rooms = [this.room];
+ });
+
+ test("defaults to the tiled layout with the layout switcher available", async function (assert) {
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ assert
+ .dom(".voice-room-page")
+ .hasClass("--tiled", "defaults to tiled layout");
+ assert.dom(".voice-room-page__grid").exists("renders the tiled grid");
+
+ // The layout switcher lives behind the overflow menu. Switching layouts
+ // through the nested `menu`-service submenu needs the app's modal/portal
+ // outlets, so the end-to-end switch is covered by a system spec.
+ await click(".voice-room-menu-trigger");
+ assert
+ .dom(".voice-room-page__layout-trigger")
+ .exists("exposes the layout switcher in the overflow menu");
+ });
+
+ test("a stage room defaults to the presentation layout", async function (assert) {
+ this.room.room_type = "stage";
+ // Keep the chat panel out of this test; the chat-open default is covered
+ // separately.
+ this.room.chat_available = false;
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ assert
+ .dom(".voice-room-page")
+ .hasClass("--presentation", "stage rooms default to presentation");
+ assert
+ .dom(".voice-room-page")
+ .doesNotHaveClass("--tiled", "the tiled default no longer applies");
+ assert
+ .dom(".voice-room-page__presentation")
+ .exists("renders the featured-presenter layout");
+ });
+
+ test("presentation layout automatically features the first screen share", async function (assert) {
+ this.room.room_type = "stage";
+ this.room.chat_available = false;
+ this.room.active_participants[1].is_screen_sharing = true;
+ this.room.active_participants[2].is_screen_sharing = true;
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='2']"
+ )
+ .exists("automatically features the first screen share");
+ assert
+ .dom(
+ ".voice-room-page__presentation-rail .voice-video-tile[data-user-id='3']"
+ )
+ .exists("keeps the other screen share in the rail");
+ });
+
+ test("spotlights a selected participant for the viewer", async function (assert) {
+ this.room.active_participants[1].is_screen_sharing = true;
+ this.room.active_participants[2].is_screen_sharing = true;
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ await click(".voice-video-tile[data-user-id='3'] .voice-video-tile__menu");
+ await selectParticipantFromOpenMenu(this.owner);
+ await settled();
+
+ assert
+ .dom(".voice-room-page")
+ .hasClass("--presentation", "switches to presentation layout");
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='3']"
+ )
+ .exists("features the selected screen share");
+
+ await click(".voice-room-page__presentation-main .voice-video-tile__menu");
+ const participantMenu = this.owner
+ .lookup("service:menu")
+ .getByIdentifier("voice-participant-menu");
+ assert.true(
+ participantMenu.options.data.isSpotlighted,
+ "marks the spotlight as active"
+ );
+ await selectParticipantFromOpenMenu(this.owner);
+ await settled();
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='2']"
+ )
+ .exists("returns to automatic screen-share selection");
+ });
+
+ test("the normal presentation layout control restores automatic selection", async function (assert) {
+ this.room.active_participants[1].is_screen_sharing = true;
+ this.room.active_participants[2].is_screen_sharing = true;
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ await click(".voice-video-tile[data-user-id='3'] .voice-video-tile__menu");
+ await selectParticipantFromOpenMenu(this.owner);
+ await settled();
+ await click(".voice-room-menu-trigger");
+ await click(".voice-room-page__layout-trigger");
+
+ this.owner
+ .lookup("service:menu")
+ .getByIdentifier("voice-call-submenu")
+ .options.data.onSelect("presentation");
+ await settled();
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='2']"
+ )
+ .exists("the default control restores automatic selection");
+ });
+
+ test("a spotlighted publisher receives the mobile video budget", async function (assert) {
+ this.owner.lookup("service:capabilities").viewport.md = false;
+ this.room.active_participants.push(
+ ...[4, 5, 6].map((id) => ({
+ id,
+ username: `user${id}`,
+ avatar_template: `/letter_avatar_proxy/v4/letter/u/{size}.png`,
+ is_video_on: true,
+ }))
+ );
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ assert
+ .dom(".voice-video-tile[data-user-id='6']")
+ .hasClass("--avatar", "the last publisher starts outside the budget");
+
+ await click(".voice-video-tile[data-user-id='6'] .voice-video-tile__menu");
+ await selectParticipantFromOpenMenu(this.owner);
+ await settled();
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='6']"
+ )
+ .hasClass("--video", "the spotlighted publisher receives live video");
+ });
+
+ test("falls back when the spotlighted participant leaves", async function (assert) {
+ this.room.active_participants[1].is_screen_sharing = true;
+ this.room.active_participants[2].is_screen_sharing = true;
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+ await click(".voice-video-tile[data-user-id='3'] .voice-video-tile__menu");
+ await selectParticipantFromOpenMenu(this.owner);
+ await settled();
+
+ this.voiceRooms.rooms = [
+ {
+ ...this.room,
+ active_participants: this.room.active_participants.filter(
+ (participant) => participant.id !== 3
+ ),
+ },
+ ];
+ await settled();
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='2']"
+ )
+ .exists("falls back to automatic selection");
+
+ this.voiceRooms.rooms = [this.room];
+ await settled();
+
+ assert
+ .dom(
+ ".voice-room-page__presentation-main .voice-video-tile[data-user-id='2']"
+ )
+ .exists("does not restore a stale spotlight if the participant rejoins");
+ });
+
+ test("a joined stage room with chat available opens the chat panel by default", async function (assert) {
+ // The panel prepares its chat session on mount; an empty payload keeps it
+ // in the pre-thread composer state without touching chat internals.
+ pretender.post("/voice/rooms/1/chat_session", () => response({}));
+
+ this.room.room_type = "stage";
+
+ await render(<template><VoiceRoomPage @room={{this.room}} /></template>);
+
+ assert
+ .dom(".voice-room-page")
+ .hasClass("--chat-open", "the chat panel is open by default");
+ assert.dom(".voice-chat").exists("mounts the chat panel");
+ });
+});
diff --git a/plugins/voice/test/javascripts/integration/components/voice/call-widget-test.gjs b/plugins/voice/test/javascripts/integration/components/voice/call-widget-test.gjs
new file mode 100644
index 00000000000..2b96e36357d
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice/call-widget-test.gjs
@@ -0,0 +1,412 @@
+import { tracked } from "@glimmer/tracking";
+import Service from "@ember/service";
+import {
+ click,
+ render,
+ settled,
+ triggerEvent,
+ waitUntil,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import VoiceCallWidget from "discourse/plugins/voice/discourse/components/voice/call-widget";
+
+class VoiceRoomsStub extends Service {
+ @tracked rooms = [];
+
+ roomById(id) {
+ return this.rooms.find((room) => Number(room.id) === Number(id));
+ }
+
+ setParticipants(roomId, participants) {
+ this.rooms = this.rooms.map((room) => {
+ if (Number(room.id) !== Number(roomId)) {
+ return room;
+ }
+
+ return { ...room, active_participants: participants };
+ });
+ }
+
+ isParticipantSpeaking() {
+ return false;
+ }
+}
+
+class VoiceWebrtcStub extends Service {
+ @tracked activeRoomId = 1;
+ @tracked audioEnabled = true;
+ @tracked callWidgetHidden = false;
+ @tracked deafened = false;
+ @tracked localVideoKind = null;
+ @tracked pttEnabled = false;
+
+ screenShareSupported = false;
+ watchingCalls = [];
+ videoStreams = new Map();
+ leaveCalls = [];
+
+ get activeRoom() {
+ return this.voiceRooms.roomById(this.activeRoomId);
+ }
+
+ videoAllowedIn() {
+ return true;
+ }
+
+ canPublishVideo() {
+ return true;
+ }
+
+ connectionStateFor() {
+ return "connected";
+ }
+
+ isTranscribingRoom() {
+ return false;
+ }
+
+ remoteStreamFor(roomId, userId) {
+ return this.videoStreams.get(`${roomId}:${userId}`);
+ }
+
+ setWatching(roomId, watching, options = {}) {
+ this.watchingCalls.push({ roomId, watching, options });
+ }
+
+ attachVideoStream() {}
+ toggleMute() {}
+ toggleDeafen() {}
+ toggleCamera() {}
+ toggleScreenShare() {}
+ leave(room) {
+ this.leaveCalls.push(room);
+ }
+}
+
+class RouterStub extends Service {
+ @tracked currentURL = "/latest";
+ @tracked currentRoute = null;
+
+ transitionTo() {}
+}
+
+module("Integration | Component | voice/call-widget", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.currentUser = logIn(this.owner);
+
+ this.owner.unregister("service:voice-rooms");
+ this.owner.register("service:voice-rooms", VoiceRoomsStub);
+ this.owner.unregister("service:voice-webrtc");
+ this.owner.register("service:voice-webrtc", VoiceWebrtcStub);
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+
+ this.voiceRooms = this.owner.lookup("service:voice-rooms");
+ this.voiceWebrtc = this.owner.lookup("service:voice-webrtc");
+ this.voiceWebrtc.voiceRooms = this.voiceRooms;
+
+ this.voiceRooms.rooms = [
+ {
+ id: 1,
+ slug: "test-room",
+ name: "Test Room",
+ video_enabled: true,
+ // Makes the chat button eligible, so the extra-minimized test's exact
+ // control count guards against it leaking into that mode.
+ chat_available: true,
+ active_participants: [
+ {
+ id: this.currentUser.id,
+ username: this.currentUser.username,
+ avatar_template: "/letter_avatar_proxy/v4/letter/a/{size}.png",
+ },
+ ],
+ },
+ ];
+ });
+
+ test("keeps video watching and participant tiles live in widget mode", async function (assert) {
+ this.set("renderWidget", true);
+ await render(
+ <template>
+ {{#if this.renderWidget}}
+ <VoiceCallWidget />
+ {{/if}}
+ </template>
+ );
+
+ assert.deepEqual(
+ this.voiceWebrtc.watchingCalls.at(-1),
+ { roomId: 1, watching: true, options: {} },
+ "marks the room watched while the widget is visible"
+ );
+
+ this.voiceWebrtc.videoStreams.set("1:2", { id: "bob-video" });
+ this.voiceRooms.setParticipants(1, [
+ ...this.voiceRooms.roomById(1).active_participants,
+ {
+ id: 2,
+ username: "bob",
+ avatar_template: "/letter_avatar_proxy/v4/letter/b/{size}.png",
+ is_video_on: true,
+ },
+ ]);
+ await settled();
+
+ assert
+ .dom(".voice-call-widget .voice-video-tile[data-user-id='2']")
+ .exists("adds a participant tile while the widget is docked");
+ assert
+ .dom(
+ ".voice-call-widget .voice-video-tile[data-user-id='2'] video.voice-video-tile__video"
+ )
+ .exists("renders the live remote video element in the widget");
+
+ this.voiceRooms.setParticipants(1, [
+ this.voiceRooms.roomById(1).active_participants[0],
+ ]);
+ await settled();
+
+ assert
+ .dom(".voice-call-widget .voice-video-tile[data-user-id='2']")
+ .doesNotExist("removes the participant tile while the widget is docked");
+
+ this.set("renderWidget", false);
+ await settled();
+
+ assert.deepEqual(
+ this.voiceWebrtc.watchingCalls.at(-1),
+ { roomId: 1, watching: false, options: { keepVideo: true } },
+ "clears the widget watch state when the widget is removed"
+ );
+ });
+
+ test("hides on the room's own page even when the URL carries extra query params", async function (assert) {
+ const router = this.owner.lookup("service:router");
+
+ await render(<template><VoiceCallWidget /></template>);
+ assert.dom(".voice-call-widget").exists("shows while docked elsewhere");
+
+ router.currentRoute = {
+ name: "voice-room",
+ params: { slug: "test-room" },
+ queryParams: { chat: "true" },
+ };
+ await settled();
+
+ assert
+ .dom(".voice-call-widget")
+ .doesNotExist("hides on the room's own page, regardless of query params");
+
+ router.currentRoute = { name: "discovery.latest", params: {} };
+ await settled();
+
+ assert
+ .dom(".voice-call-widget")
+ .exists("shows again once navigated away from the room page");
+ });
+
+ test("stays hidden while the user has hidden the call widget", async function (assert) {
+ await render(<template><VoiceCallWidget /></template>);
+ assert.dom(".voice-call-widget").exists("shows by default");
+
+ this.voiceWebrtc.callWidgetHidden = true;
+ await settled();
+
+ assert
+ .dom(".voice-call-widget")
+ .doesNotExist("hides while the preference is on");
+
+ this.voiceWebrtc.callWidgetHidden = false;
+ await settled();
+
+ assert
+ .dom(".voice-call-widget")
+ .exists("shows again once the preference is turned off");
+ });
+
+ test("collapses a crowd into a +N overflow tile", async function (assert) {
+ // A small persisted size makes the solver's slot count independent of the
+ // test viewport.
+ this.owner.lookup("service:key-value-store").set({
+ key: "voice-widget-size",
+ value: JSON.stringify({ width: 320, height: 220 }),
+ });
+
+ const fakes = Array.from({ length: 11 }, (_, i) => {
+ const letter = String.fromCharCode(97 + i);
+ return {
+ id: 100 + i,
+ username: `user_${letter}`,
+ avatar_template: `/letter_avatar_proxy/v4/letter/${letter}/{size}.png`,
+ };
+ });
+ this.voiceRooms.setParticipants(1, [
+ ...this.voiceRooms.roomById(1).active_participants,
+ ...fakes,
+ ]);
+
+ await render(<template><VoiceCallWidget /></template>);
+ await waitUntil(() =>
+ document.querySelector(".voice-call-widget__overflow-tile")
+ );
+
+ const tileCount = document.querySelectorAll(
+ ".voice-call-widget .voice-video-tile"
+ ).length;
+ const hidden = parseInt(
+ document
+ .querySelector(".voice-call-widget__overflow-count")
+ .textContent.trim()
+ .replace("+", ""),
+ 10
+ );
+
+ assert.true(tileCount < 12, "hides part of the crowd");
+ assert.true(hidden >= 2, "the overflow tile absorbs at least two people");
+ assert.strictEqual(
+ tileCount + hidden,
+ 12,
+ "every participant is either a tile or counted"
+ );
+ assert
+ .dom(".voice-call-widget__overflow-avatars img")
+ .exists("previews hidden participants' avatars");
+ });
+
+ test("keeps camera publishers out of the overflow", async function (assert) {
+ this.owner.lookup("service:key-value-store").set({
+ key: "voice-widget-size",
+ value: JSON.stringify({ width: 320, height: 220 }),
+ });
+
+ const fakes = Array.from({ length: 9 }, (_, i) => {
+ const letter = String.fromCharCode(97 + i);
+ return {
+ id: 100 + i,
+ username: `user_${letter}`,
+ avatar_template: `/letter_avatar_proxy/v4/letter/${letter}/{size}.png`,
+ };
+ });
+ this.voiceWebrtc.videoStreams.set("1:300", { id: "zed-video" });
+ this.voiceRooms.setParticipants(1, [
+ ...this.voiceRooms.roomById(1).active_participants,
+ ...fakes,
+ {
+ id: 300,
+ username: "zed",
+ avatar_template: "/letter_avatar_proxy/v4/letter/z/{size}.png",
+ is_video_on: true,
+ },
+ ]);
+
+ await render(<template><VoiceCallWidget /></template>);
+ await waitUntil(() =>
+ document.querySelector(".voice-call-widget__overflow-tile")
+ );
+
+ assert
+ .dom(
+ ".voice-call-widget .voice-video-tile[data-user-id='300'] video.voice-video-tile__video"
+ )
+ .exists("the camera publisher is promoted out of the overflow tail");
+ assert
+ .dom(".voice-call-widget .voice-video-tile[data-user-id='100']")
+ .doesNotExist("an avatar-only participant yields the slot");
+ });
+
+ test("shows everyone without an overflow tile when they fit", async function (assert) {
+ const fakes = Array.from({ length: 3 }, (_, i) => {
+ const letter = String.fromCharCode(97 + i);
+ return {
+ id: 100 + i,
+ username: `user_${letter}`,
+ avatar_template: `/letter_avatar_proxy/v4/letter/${letter}/{size}.png`,
+ };
+ });
+ this.voiceRooms.setParticipants(1, [
+ ...this.voiceRooms.roomById(1).active_participants,
+ ...fakes,
+ ]);
+
+ await render(<template><VoiceCallWidget /></template>);
+ await waitUntil(
+ () =>
+ document.querySelectorAll(".voice-call-widget .voice-video-tile")
+ .length === 4
+ );
+
+ assert
+ .dom(".voice-call-widget .voice-video-tile")
+ .exists({ count: 4 }, "renders a tile per participant");
+ assert
+ .dom(".voice-call-widget__overflow-tile")
+ .doesNotExist("no overflow tile when everyone fits");
+ });
+
+ test("resizing below the widget threshold enters extra minimized mode", async function (assert) {
+ await render(<template><VoiceCallWidget /></template>);
+
+ const widget = document.querySelector(".voice-call-widget");
+ widget.getBoundingClientRect = () => ({
+ left: 100,
+ top: 100,
+ right: 500,
+ bottom: 340,
+ width: 400,
+ height: 240,
+ });
+
+ await triggerEvent(".voice-call-widget__resize.--se", "mousedown", {
+ button: 0,
+ clientX: 500,
+ clientY: 340,
+ });
+ await triggerEvent(window, "mousemove", {
+ clientX: 250,
+ clientY: 220,
+ });
+ await triggerEvent(window, "mouseup");
+
+ assert
+ .dom(".voice-call-widget")
+ .hasClass(
+ "--extra-minimized",
+ "marks the widget as extra minimized after crossing the resize threshold"
+ );
+ assert
+ .dom(".voice-call-widget__tiles")
+ .doesNotExist("hides participant tiles in extra minimized mode");
+ assert
+ .dom(".voice-call-widget__controls button")
+ .exists({ count: 2 }, "only renders expand and leave controls");
+ assert.false(
+ /inset-inline-start|inset-block-start/.test(
+ document.querySelector(".voice-call-widget").getAttribute("style") ?? ""
+ ),
+ "keeps the extra minimized widget pinned to the bottom-right corner"
+ );
+
+ await click(".voice-call-widget__expand");
+
+ assert
+ .dom(".voice-call-widget")
+ .doesNotHaveClass(
+ "--extra-minimized",
+ "expands back to the default widget dimensions"
+ );
+ assert
+ .dom(".voice-call-widget__tiles")
+ .exists("restores the default widget content");
+ assert.false(
+ /inset-inline-start|inset-block-start/.test(
+ document.querySelector(".voice-call-widget").getAttribute("style") ?? ""
+ ),
+ "expands from the bottom-right corner instead of the old resize position"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/integration/components/voice/voice-canvas-test.gjs b/plugins/voice/test/javascripts/integration/components/voice/voice-canvas-test.gjs
new file mode 100644
index 00000000000..f9ce517587c
--- /dev/null
+++ b/plugins/voice/test/javascripts/integration/components/voice/voice-canvas-test.gjs
@@ -0,0 +1,73 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import Service from "@ember/service";
+import { render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import VoiceVoiceCanvas from "discourse/plugins/voice/discourse/components/voice/voice-canvas";
+
+class VoiceWebrtcStub extends Service {
+ @tracked localStream = null;
+ @tracked remoteStreams = [];
+ @tracked remoteScreenAudioStreams = [];
+ attachCalls = [];
+
+ @action
+ attachStream(stream, element) {
+ this.attachCalls.push({ stream, element });
+ }
+}
+
+module("Integration | Component | voice/voice-canvas", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.owner.unregister("service:voice-webrtc");
+ this.owner.register("service:voice-webrtc", VoiceWebrtcStub);
+ this.voiceWebrtc = this.owner.lookup("service:voice-webrtc");
+ });
+
+ test("re-attaches a remote stream when the object changes but the id stays the same", async function (assert) {
+ const firstStream = { id: "peer-stream" };
+ const secondStream = { id: "peer-stream" };
+
+ this.voiceWebrtc.remoteStreams = [firstStream];
+
+ await render(<template><VoiceVoiceCanvas /></template>);
+
+ assert.strictEqual(this.voiceWebrtc.attachCalls.length, 1);
+ assert.strictEqual(this.voiceWebrtc.attachCalls[0].stream, firstStream);
+
+ const element = this.voiceWebrtc.attachCalls[0].element;
+
+ this.voiceWebrtc.remoteStreams = [secondStream];
+ await settled();
+
+ assert.strictEqual(this.voiceWebrtc.attachCalls.length, 2);
+ assert.strictEqual(this.voiceWebrtc.attachCalls[1].stream, secondStream);
+ assert.strictEqual(this.voiceWebrtc.attachCalls[1].element, element);
+ });
+
+ test("renders a dedicated sink for each remote screen audio stream", async function (assert) {
+ const voiceStream = { id: "voice-stream" };
+ const screenAudioStream = { id: "screen-audio-stream" };
+
+ this.voiceWebrtc.remoteStreams = [voiceStream];
+
+ await render(<template><VoiceVoiceCanvas /></template>);
+
+ assert.strictEqual(this.voiceWebrtc.attachCalls.length, 1);
+
+ this.voiceWebrtc.remoteScreenAudioStreams = [screenAudioStream];
+ await settled();
+
+ assert.strictEqual(this.voiceWebrtc.attachCalls.length, 2);
+ assert.strictEqual(
+ this.voiceWebrtc.attachCalls[1].stream,
+ screenAudioStream
+ );
+ assert
+ .dom(".voice-voice-canvas audio")
+ .exists({ count: 2 }, "keeps the voice sink alongside the screen sink");
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/audio-monitor-test.js b/plugins/voice/test/javascripts/unit/lib/audio-monitor-test.js
new file mode 100644
index 00000000000..614d7c23d86
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/audio-monitor-test.js
@@ -0,0 +1,177 @@
+import { module, test } from "qunit";
+import AudioMonitor from "discourse/plugins/voice/discourse/lib/voice/audio-monitor";
+
+function wait(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+module("Voice | Unit | Lib | audio-monitor", function (hooks) {
+ hooks.beforeEach(function () {
+ const testContext = this;
+
+ this.originalWindowAudioContext = window.AudioContext;
+ this.originalWindowWebkitAudioContext = window.webkitAudioContext;
+ this.originalGlobalAudioContext = globalThis.AudioContext;
+ this.originalRequestAnimationFrame = window.requestAnimationFrame;
+ this.originalCancelAnimationFrame = window.cancelAnimationFrame;
+
+ this.analyserSampleCount = 0;
+ this.requestAnimationFrameCalls = 0;
+
+ class FakeAudioContext {
+ createMediaStreamSource() {
+ return {
+ connect(target) {
+ return target;
+ },
+ disconnect() {},
+ };
+ }
+
+ createAnalyser() {
+ return {
+ fftSize: 0,
+ frequencyBinCount: 32,
+ getByteTimeDomainData(array) {
+ testContext.analyserSampleCount++;
+ array.fill(140);
+ },
+ };
+ }
+
+ close() {
+ return Promise.resolve();
+ }
+ }
+
+ window.AudioContext = FakeAudioContext;
+ window.webkitAudioContext = FakeAudioContext;
+ globalThis.AudioContext = FakeAudioContext;
+ window.requestAnimationFrame = () => {
+ this.requestAnimationFrameCalls++;
+ return 1;
+ };
+ window.cancelAnimationFrame = () => {};
+ });
+
+ hooks.afterEach(function () {
+ window.AudioContext = this.originalWindowAudioContext;
+ window.webkitAudioContext = this.originalWindowWebkitAudioContext;
+ globalThis.AudioContext = this.originalGlobalAudioContext;
+ window.requestAnimationFrame = this.originalRequestAnimationFrame;
+ window.cancelAnimationFrame = this.originalCancelAnimationFrame;
+ });
+
+ test("detects quiet speech and holds through short pauses", async function (assert) {
+ assert.timeout(5000);
+
+ const testContext = this;
+ this.amplitude = 0.0005;
+
+ class FloatFakeAudioContext {
+ createMediaStreamSource() {
+ return {
+ connect(target) {
+ return target;
+ },
+ disconnect() {},
+ };
+ }
+
+ createAnalyser() {
+ return {
+ fftSize: 0,
+ frequencyBinCount: 32,
+ getFloatTimeDomainData(array) {
+ array.fill(testContext.amplitude);
+ },
+ };
+ }
+
+ close() {
+ return Promise.resolve();
+ }
+ }
+
+ window.AudioContext = FloatFakeAudioContext;
+ window.webkitAudioContext = FloatFakeAudioContext;
+
+ const speakingChanges = [];
+ const monitor = new AudioMonitor({
+ onSpeakingChange: (roomId, userId, speaking) => {
+ speakingChanges.push(speaking);
+ },
+ onVoiceActivity: () => {},
+ });
+
+ const stream = {
+ getAudioTracks() {
+ return [{ kind: "audio" }];
+ },
+ };
+
+ monitor.ensure(1, 1, stream, true);
+
+ // Let the noise floor adapt down to near-silence.
+ await wait(800);
+ assert.deepEqual(speakingChanges, [], "silence never reads as speech");
+
+ // Well below the old fixed threshold (byte RMS 8 ≈ 0.06), but far above
+ // the adapted noise floor.
+ this.amplitude = 0.02;
+ await wait(300);
+ assert.deepEqual(speakingChanges, [true], "quiet speech starts speaking");
+
+ // A between-words pause shorter than the hangover keeps the state on.
+ this.amplitude = 0.0005;
+ await wait(300);
+ assert.deepEqual(
+ speakingChanges,
+ [true],
+ "short pauses don't flap the indicator"
+ );
+
+ monitor.teardown(1, 1);
+ assert.deepEqual(
+ speakingChanges,
+ [true, false],
+ "teardown clears the speaking state"
+ );
+ });
+
+ test("keeps sampling voice activity when animation frames are stalled", async function (assert) {
+ assert.timeout(2000);
+
+ let voiceActivityCalls = 0;
+ const monitor = new AudioMonitor({
+ onSpeakingChange: () => {},
+ onVoiceActivity: () => {
+ voiceActivityCalls++;
+ },
+ });
+
+ const stream = {
+ getAudioTracks() {
+ return [{ kind: "audio" }];
+ },
+ };
+
+ monitor.ensure(1, 1, stream, true);
+ await wait(250);
+ monitor.teardown(1, 1);
+
+ assert.true(
+ voiceActivityCalls >= 2,
+ "continues reporting voice activity without relying on requestAnimationFrame callbacks"
+ );
+ assert.strictEqual(
+ this.requestAnimationFrameCalls,
+ 0,
+ "does not depend on requestAnimationFrame for audio sampling"
+ );
+ assert.true(
+ this.analyserSampleCount >= 2,
+ "keeps polling the analyser after the initial sample"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/fullscreen-test.js b/plugins/voice/test/javascripts/unit/lib/fullscreen-test.js
new file mode 100644
index 00000000000..464da542b24
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/fullscreen-test.js
@@ -0,0 +1,81 @@
+import { module, test } from "qunit";
+import {
+ toggleFullscreen,
+ toggleTileFullscreen,
+} from "discourse/plugins/voice/discourse/lib/voice/fullscreen";
+
+// Nothing is fullscreen during these tests, so toggle always takes the enter
+// path; each case exposes only one browser's API to assert the fallback order.
+module("Voice | Unit | Lib | fullscreen", function () {
+ test("prefers the standard Fullscreen API on the tile", function (assert) {
+ let called = false;
+ const tile = {
+ requestFullscreen() {
+ called = true;
+ return Promise.resolve();
+ },
+ };
+
+ toggleTileFullscreen(tile);
+ assert.true(called, "calls requestFullscreen on the tile");
+ });
+
+ test("falls back to the webkit-prefixed API", function (assert) {
+ let called = false;
+ const tile = {
+ webkitRequestFullscreen() {
+ called = true;
+ },
+ };
+
+ toggleTileFullscreen(tile);
+ assert.true(
+ called,
+ "calls webkitRequestFullscreen when the standard API is absent"
+ );
+ });
+
+ test("falls back to the iOS video element API", function (assert) {
+ let called = false;
+ const video = {
+ webkitEnterFullscreen() {
+ called = true;
+ },
+ };
+ const tile = {
+ querySelector() {
+ return video;
+ },
+ };
+
+ toggleTileFullscreen(tile);
+ assert.true(
+ called,
+ "enters fullscreen on the <video> when only the iOS API exists"
+ );
+ });
+
+ test("does nothing without a tile", function (assert) {
+ toggleTileFullscreen(null);
+ assert.true(true, "returns without throwing");
+ });
+
+ test("the generic toggle never falls back to a descendant video", function (assert) {
+ let videoCalled = false;
+ const element = {
+ querySelector() {
+ return {
+ webkitEnterFullscreen() {
+ videoCalled = true;
+ },
+ };
+ },
+ };
+
+ toggleFullscreen(element);
+ assert.false(
+ videoCalled,
+ "fullscreening the gallery container does not hijack a single video"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/local-audio-pipeline-test.js b/plugins/voice/test/javascripts/unit/lib/local-audio-pipeline-test.js
new file mode 100644
index 00000000000..0619d927ba7
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/local-audio-pipeline-test.js
@@ -0,0 +1,425 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import Site from "discourse/models/site";
+import LocalAudioPipeline from "discourse/plugins/voice/discourse/lib/voice/local-audio-pipeline";
+
+const STORAGE_KEYS = [
+ "voice:noise-suppression",
+ "voice:noise-suppression-mode",
+ "voice:echo-cancellation",
+ "voice:auto-gain-control",
+];
+
+function clearStoredPreferences() {
+ STORAGE_KEYS.forEach((key) => localStorage.removeItem(key));
+}
+
+function createFakeTrack(id) {
+ return { id, kind: "audio", enabled: true, stop() {} };
+}
+
+function createFakeStream(id, track) {
+ return {
+ id,
+ getTracks: () => [track],
+ getAudioTracks: () => [track],
+ };
+}
+
+// A controllable stand-in for the DTLN worklet environment: tests decide
+// when (and how) each AudioWorkletNode answers the ready handshake, and the
+// getUserMedia constraints of every capture are recorded.
+function installFakeEnvironment(context, { rawStream, processedStream }) {
+ const workletNodes = [];
+ const captureConstraints = [];
+
+ class FakeAudioContext {
+ state = "running";
+ audioWorklet = {
+ addModule: async () => {},
+ };
+
+ resume() {
+ this.state = "running";
+ return Promise.resolve();
+ }
+
+ createMediaStreamSource() {
+ return {
+ connect: (target) => target,
+ disconnect() {},
+ };
+ }
+
+ createMediaStreamDestination() {
+ return { stream: processedStream };
+ }
+
+ close() {
+ return Promise.resolve();
+ }
+ }
+
+ class FakeAudioWorkletNode {
+ port = {
+ onmessage: null,
+ postMessage: (data) => {
+ if (data?.type === "init") {
+ this.wasmReceived = true;
+ }
+ },
+ };
+
+ constructor() {
+ workletNodes.push(this);
+ }
+
+ emit(message) {
+ this.port.onmessage?.({ data: message });
+ }
+
+ connect(target) {
+ return target;
+ }
+
+ disconnect() {}
+ }
+
+ context.originals = {
+ audioContext: globalThis.AudioContext,
+ workletNode: globalThis.AudioWorkletNode,
+ windowAudioContext: window.AudioContext,
+ fetch: globalThis.fetch,
+ getUserMedia: navigator.mediaDevices?.getUserMedia,
+ };
+
+ // The gem-vendored asset base the loaders read at runtime.
+ Site.current().set("voice_assets_path", "/plugins/voice/javascripts/0.0.0");
+ const originalFetch = globalThis.fetch;
+ globalThis.AudioContext = FakeAudioContext;
+ window.AudioContext = FakeAudioContext;
+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;
+ globalThis.fetch = (url, options) => {
+ if (String(url).includes("/plugins/voice/javascripts/")) {
+ return Promise.resolve({
+ ok: true,
+ arrayBuffer: async () => new ArrayBuffer(8),
+ });
+ }
+ return originalFetch(url, options);
+ };
+ navigator.mediaDevices ||= {};
+ navigator.mediaDevices.getUserMedia = async (constraints) => {
+ captureConstraints.push(constraints.audio);
+ return rawStream;
+ };
+
+ return { workletNodes, captureConstraints };
+}
+
+function restoreEnvironment(context) {
+ globalThis.AudioContext = context.originals.audioContext;
+ window.AudioContext = context.originals.windowAudioContext;
+ globalThis.AudioWorkletNode = context.originals.workletNode;
+ globalThis.fetch = context.originals.fetch;
+ if (context.originals.getUserMedia) {
+ navigator.mediaDevices.getUserMedia = context.originals.getUserMedia;
+ } else {
+ delete navigator.mediaDevices.getUserMedia;
+ }
+}
+
+// Yields until the pipeline has posted the wasm to a worklet node, i.e. a
+// setup() is parked on the ready handshake.
+async function waitForWorkletNode(workletNodes, index = 0) {
+ for (let i = 0; i < 50; i++) {
+ if (workletNodes[index]?.wasmReceived) {
+ return workletNodes[index];
+ }
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ throw new Error("worklet node never received wasm bytes");
+}
+
+module("Voice | Unit | Lib | local-audio-pipeline", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ clearStoredPreferences();
+
+ this.rawTrack = createFakeTrack("raw-track");
+ this.rawStream = createFakeStream("raw-stream", this.rawTrack);
+ this.processedTrack = createFakeTrack("processed-track");
+ this.processedStream = createFakeStream(
+ "processed-stream",
+ this.processedTrack
+ );
+
+ this.env = installFakeEnvironment(this, {
+ rawStream: this.rawStream,
+ processedStream: this.processedStream,
+ });
+
+ this.suppressionFailures = 0;
+ this.trackReplacements = 0;
+ this.buildPipeline = () =>
+ new LocalAudioPipeline({
+ onStreamChanged: () => {},
+ onSuppressionFailed: () => this.suppressionFailures++,
+ replaceTrackOnPeers: async () => this.trackReplacements++,
+ });
+ this.pipeline = this.buildPipeline();
+ });
+
+ hooks.afterEach(function () {
+ this.pipeline.stop();
+ restoreEnvironment(this);
+ clearStoredPreferences();
+ });
+
+ test("captures with the browser processing defaults", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ assert.deepEqual(this.env.captureConstraints[0], {
+ echoCancellation: true,
+ autoGainControl: true,
+ noiseSuppression: true,
+ });
+ assert.strictEqual(this.pipeline.noiseSuppressionMode, "standard");
+ assert.strictEqual(
+ this.env.workletNodes.length,
+ 0,
+ "standard mode never touches the worklet"
+ );
+ });
+
+ test("AI mode resolves only after the worklet ready handshake and disables native suppression", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ const change = this.pipeline.setNoiseSuppressionMode("ai:dtln");
+ const node = await waitForWorkletNode(this.env.workletNodes);
+
+ assert.strictEqual(
+ this.pipeline.noiseSuppressionState,
+ "starting",
+ "stays in starting until the worklet confirms"
+ );
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.rawStream,
+ "keeps publishing the previous stream while starting"
+ );
+
+ node.emit({ type: "ready" });
+ await change;
+
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "on");
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.processedStream,
+ "publishes the suppressed stream after ready"
+ );
+ assert.false(
+ this.env.captureConstraints.at(-1).noiseSuppression,
+ "native suppression is off underneath the AI filter"
+ );
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "ai:dtln",
+ "persists the mode only on success"
+ );
+ assert.strictEqual(this.trackReplacements, 1);
+ });
+
+ test("worklet init error reverts to the previous mode and notifies", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ const change = this.pipeline.setNoiseSuppressionMode("ai:dtln");
+ const node = await waitForWorkletNode(this.env.workletNodes);
+ node.emit({ type: "error", message: "boom" });
+ await change;
+
+ assert.strictEqual(this.pipeline.noiseSuppressionMode, "standard");
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "off");
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.rawStream,
+ "keeps the raw stream"
+ );
+ assert.strictEqual(this.suppressionFailures, 1, "notifies the failure");
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "standard",
+ "does not persist the failed mode"
+ );
+ assert.true(
+ this.env.captureConstraints.at(-1).noiseSuppression,
+ "recaptures with native suppression restored"
+ );
+ });
+
+ test("rapid mode changes are serialized", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ const first = this.pipeline.setNoiseSuppressionMode("ai:dtln");
+ const second = this.pipeline.setNoiseSuppressionMode("standard");
+
+ const node = await waitForWorkletNode(this.env.workletNodes);
+ node.emit({ type: "ready" });
+ await first;
+ await second;
+
+ assert.strictEqual(
+ this.pipeline.noiseSuppressionMode,
+ "standard",
+ "the second change runs after the first completes"
+ );
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "off");
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.rawStream,
+ "ends on the raw stream"
+ );
+ assert.strictEqual(
+ this.env.workletNodes.length,
+ 1,
+ "only one worklet setup ran"
+ );
+ });
+
+ test("stop() during setup supersedes it without failure side effects", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ const change = this.pipeline.setNoiseSuppressionMode("ai:dtln");
+ await waitForWorkletNode(this.env.workletNodes);
+
+ this.pipeline.stop();
+ await change;
+
+ assert.strictEqual(
+ this.suppressionFailures,
+ 0,
+ "a superseded setup is not reported as a failure"
+ );
+ assert.strictEqual(this.pipeline.stream, null, "pipeline is stopped");
+ });
+
+ test("mid-call bypass falls back to standard suppression", async function (assert) {
+ localStorage.setItem("voice:noise-suppression-mode", "ai:dtln");
+ this.pipeline = this.buildPipeline();
+
+ const acquired = this.pipeline.acquireMicrophone();
+ const node = await waitForWorkletNode(this.env.workletNodes);
+ node.emit({ type: "ready" });
+ await acquired;
+
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "on");
+
+ node.emit({ type: "bypass" });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ assert.strictEqual(this.pipeline.noiseSuppressionMode, "standard");
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "off");
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.rawStream,
+ "peers fall back to the native-suppressed stream"
+ );
+ assert.strictEqual(this.suppressionFailures, 1);
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "standard",
+ "persists the fallback so it doesn't loop"
+ );
+ });
+
+ test("changing the mode without a microphone only stores the preference", async function (assert) {
+ await this.pipeline.setNoiseSuppressionMode("ai:dtln");
+
+ assert.strictEqual(this.pipeline.noiseSuppressionMode, "ai:dtln");
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "ai:dtln"
+ );
+ assert.strictEqual(
+ this.env.workletNodes.length,
+ 0,
+ "no worklet setup runs"
+ );
+
+ await this.pipeline.setNoiseSuppressionMode("none");
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "none"
+ );
+ });
+
+ test("migrates the legacy boolean preference to AI mode", function (assert) {
+ localStorage.setItem("voice:noise-suppression", "1");
+
+ const pipeline = this.buildPipeline();
+
+ assert.strictEqual(pipeline.noiseSuppressionMode, "ai:dtln");
+ });
+
+ test('migrates the legacy plain "ai" mode to the DTLN engine', function (assert) {
+ localStorage.setItem("voice:noise-suppression-mode", "ai");
+
+ const pipeline = this.buildPipeline();
+
+ assert.strictEqual(pipeline.noiseSuppressionMode, "ai:dtln");
+ });
+
+ test("switching between AI engines rebuilds the worklet pipeline", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ const first = this.pipeline.setNoiseSuppressionMode("ai:dtln");
+ (await waitForWorkletNode(this.env.workletNodes, 0)).emit({
+ type: "ready",
+ });
+ await first;
+
+ const second = this.pipeline.setNoiseSuppressionMode("ai:rnnoise");
+ (await waitForWorkletNode(this.env.workletNodes, 1)).emit({
+ type: "ready",
+ });
+ await second;
+
+ assert.strictEqual(this.pipeline.noiseSuppressionMode, "ai:rnnoise");
+ assert.strictEqual(this.pipeline.noiseSuppressionState, "on");
+ assert.strictEqual(
+ this.pipeline.stream,
+ this.processedStream,
+ "publishes the new engine's stream"
+ );
+ assert.strictEqual(
+ this.env.workletNodes.length,
+ 2,
+ "each engine got its own worklet"
+ );
+ assert.false(
+ this.env.captureConstraints.at(-1).noiseSuppression,
+ "native suppression stays off across AI engines"
+ );
+ });
+
+ test("echo cancellation and auto gain changes recapture with new constraints", async function (assert) {
+ await this.pipeline.acquireMicrophone();
+
+ await this.pipeline.setEchoCancellation(false);
+ assert.deepEqual(this.env.captureConstraints.at(-1), {
+ echoCancellation: false,
+ autoGainControl: true,
+ noiseSuppression: true,
+ });
+ assert.strictEqual(localStorage.getItem("voice:echo-cancellation"), "0");
+
+ await this.pipeline.setAutoGainControl(false);
+ assert.deepEqual(this.env.captureConstraints.at(-1), {
+ echoCancellation: false,
+ autoGainControl: false,
+ noiseSuppression: true,
+ });
+ assert.strictEqual(this.trackReplacements, 2);
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/peer-manager-test.js b/plugins/voice/test/javascripts/unit/lib/peer-manager-test.js
new file mode 100644
index 00000000000..bd8cfe80383
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/peer-manager-test.js
@@ -0,0 +1,265 @@
+import { module, test } from "qunit";
+import PeerManager from "discourse/plugins/voice/discourse/lib/voice/peer-manager";
+
+class FakeRTCPeerConnection {
+ signalingState = "stable";
+ connectionState = "new";
+ iceConnectionState = "new";
+ iceGatheringState = "new";
+ localDescription = null;
+ #senders = [];
+ #transceivers = [];
+
+ constructor() {}
+
+ addTrack(track) {
+ const sender = { track };
+ this.#senders.push(sender);
+ return sender;
+ }
+
+ addTransceiver(kind) {
+ const sender = {
+ track: null,
+ async replaceTrack(newTrack) {
+ this.track = newTrack;
+ },
+ };
+ const transceiver = {
+ mid: null,
+ direction: "sendrecv",
+ sender,
+ receiver: { track: { kind } },
+ };
+ this.#transceivers.push(transceiver);
+ this.#senders.push(sender);
+ return transceiver;
+ }
+
+ getTransceivers() {
+ return this.#transceivers;
+ }
+
+ getSenders() {
+ return this.#senders;
+ }
+
+ async createOffer() {
+ return { type: "offer", sdp: "fake-offer" };
+ }
+
+ async setLocalDescription(description) {
+ this.localDescription = description;
+ }
+
+ close() {
+ this.connectionState = "closed";
+ }
+}
+
+module("Voice | Unit | Lib | peer-manager", function (hooks) {
+ hooks.beforeEach(function () {
+ this.originalRTCPeerConnection = globalThis.RTCPeerConnection;
+ globalThis.RTCPeerConnection = FakeRTCPeerConnection;
+ });
+
+ hooks.afterEach(function () {
+ globalThis.RTCPeerConnection = this.originalRTCPeerConnection;
+ });
+
+ test("does not keep a restarted peer when the room becomes ineligible mid-restart", async function (assert) {
+ let shouldRestart = true;
+ let sentSignals = 0;
+
+ const manager = new PeerManager({
+ getIceServers: () => [],
+ getLocalStream: () => null,
+ sendSignal: () => {
+ sentSignals++;
+ return Promise.resolve();
+ },
+ flushQueuedSignals: () => Promise.resolve(),
+ onTrack: () => {},
+ clearSignalQueue: () => {},
+ onPeerDestroyed: () => {},
+ shouldRestartPeer: () => shouldRestart,
+ });
+
+ await manager.create(1, 2);
+ assert.true(manager.has(1, 2), "creates the initial peer");
+
+ const restart = manager.restart(1, 2);
+ shouldRestart = false;
+ await restart;
+
+ assert.false(
+ manager.has(1, 2),
+ "does not keep a recreated peer when restart is no longer allowed"
+ );
+ assert.strictEqual(sentSignals, 0, "does not emit a new offer");
+ });
+
+ test("alignVideoTransceiverForAnswer makes the negotiated transceiver sendable and migrates the orphaned track", async function (assert) {
+ const makeSender = (track = null) => ({
+ track,
+ async replaceTrack(newTrack) {
+ this.track = newTrack;
+ },
+ });
+
+ const cameraTrack = { id: "camera", kind: "video" };
+ const orphan = {
+ mid: null,
+ direction: "sendrecv",
+ sender: makeSender(cameraTrack),
+ receiver: { track: { kind: "video" } },
+ };
+ const associated = {
+ mid: "1",
+ direction: "recvonly",
+ sender: makeSender(),
+ receiver: { track: { kind: "video" } },
+ };
+ const pc = {
+ getTransceivers() {
+ return [orphan, associated];
+ },
+ };
+
+ PeerManager.alignVideoTransceiverForAnswer(pc);
+ await Promise.resolve();
+
+ assert.strictEqual(
+ associated.direction,
+ "sendrecv",
+ "flips the negotiated transceiver to sendrecv before the answer"
+ );
+ assert.strictEqual(
+ associated.sender.track,
+ cameraTrack,
+ "moves the camera track onto the negotiated transceiver"
+ );
+ assert.strictEqual(
+ orphan.sender.track,
+ null,
+ "detaches the camera track from the orphaned transceiver"
+ );
+ assert.strictEqual(
+ PeerManager.videoTransceiverFor(pc),
+ associated,
+ "videoTransceiverFor prefers the negotiated transceiver"
+ );
+ });
+
+ test("alignScreenAudioTransceiverForAnswer adopts the negotiated m-line and migrates the orphaned track", async function (assert) {
+ const screenAudioTrack = { id: "screen-audio", kind: "audio" };
+
+ const manager = new PeerManager({
+ getIceServers: () => [],
+ getLocalStream: () => null,
+ getLocalScreenAudioTrack: () => screenAudioTrack,
+ sendSignal: () => Promise.resolve(),
+ flushQueuedSignals: () => Promise.resolve(),
+ onTrack: () => {},
+ clearSignalQueue: () => {},
+ onPeerDestroyed: () => {},
+ });
+
+ const pc = await manager.create(1, 2);
+ await Promise.resolve();
+
+ const preAllocated = PeerManager.screenAudioTransceiverFor(pc);
+ assert.strictEqual(
+ preAllocated.sender.track,
+ screenAudioTrack,
+ "attaches the local screen audio track at peer setup"
+ );
+
+ // Simulate applying a remote offer: fresh recvonly transceivers appear
+ // for each m-line the pre-allocated ones couldn't be reused for.
+ const makeSender = (track = null) => ({
+ track,
+ async replaceTrack(newTrack) {
+ this.track = newTrack;
+ },
+ });
+ const micTransceiver = {
+ mid: "0",
+ direction: "recvonly",
+ sender: makeSender(),
+ receiver: { track: { kind: "audio" } },
+ };
+ const negotiated = {
+ mid: "2",
+ direction: "recvonly",
+ sender: makeSender(),
+ receiver: { track: { kind: "audio" } },
+ };
+ pc.getTransceivers().push(micTransceiver, negotiated);
+
+ PeerManager.alignScreenAudioTransceiverForAnswer(pc);
+ await Promise.resolve();
+
+ assert.strictEqual(
+ negotiated.direction,
+ "sendrecv",
+ "flips the negotiated transceiver to sendrecv before the answer"
+ );
+ assert.strictEqual(
+ negotiated.sender.track,
+ screenAudioTrack,
+ "moves the screen audio track onto the negotiated transceiver"
+ );
+ assert.strictEqual(
+ preAllocated.sender.track,
+ null,
+ "detaches the track from the orphaned transceiver"
+ );
+ assert.strictEqual(
+ micTransceiver.direction,
+ "recvonly",
+ "leaves the mic m-line alone"
+ );
+ assert.strictEqual(
+ PeerManager.screenAudioTransceiverFor(pc),
+ negotiated,
+ "screenAudioTransceiverFor returns the negotiated transceiver"
+ );
+ });
+
+ test("alignScreenAudioTransceiverForAnswer leaves single-audio offers from older clients alone", async function (assert) {
+ const manager = new PeerManager({
+ getIceServers: () => [],
+ getLocalStream: () => null,
+ sendSignal: () => Promise.resolve(),
+ flushQueuedSignals: () => Promise.resolve(),
+ onTrack: () => {},
+ clearSignalQueue: () => {},
+ onPeerDestroyed: () => {},
+ });
+
+ const pc = await manager.create(1, 2);
+ const preAllocated = PeerManager.screenAudioTransceiverFor(pc);
+
+ const micTransceiver = {
+ mid: "0",
+ direction: "recvonly",
+ sender: { track: null },
+ receiver: { track: { kind: "audio" } },
+ };
+ pc.getTransceivers().push(micTransceiver);
+
+ PeerManager.alignScreenAudioTransceiverForAnswer(pc);
+
+ assert.strictEqual(
+ micTransceiver.direction,
+ "recvonly",
+ "does not adopt the mic m-line as the screen audio slot"
+ );
+ assert.strictEqual(
+ PeerManager.screenAudioTransceiverFor(pc),
+ preAllocated,
+ "keeps the pre-allocated transceiver as the screen audio slot"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/room-message-queue-test.js b/plugins/voice/test/javascripts/unit/lib/room-message-queue-test.js
new file mode 100644
index 00000000000..ec089b4dd35
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/room-message-queue-test.js
@@ -0,0 +1,40 @@
+import { module, test } from "qunit";
+import RoomMessageQueue from "discourse/plugins/voice/discourse/lib/voice/room-message-queue";
+
+module("Voice | Unit | Lib | room-message-queue", function () {
+ test("continues processing later messages after a failure", async function (assert) {
+ const queue = new RoomMessageQueue();
+ const processed = [];
+
+ const first = queue.enqueue("1", async () => {
+ processed.push("first");
+ throw new Error("boom");
+ });
+
+ const second = queue.enqueue("1", async () => {
+ processed.push("second");
+ });
+
+ await Promise.allSettled([first, second]);
+
+ assert.deepEqual(processed, ["first", "second"]);
+ });
+
+ test("keeps messages serialized per room", async function (assert) {
+ const queue = new RoomMessageQueue();
+ const processed = [];
+
+ const first = queue.enqueue("1", async () => {
+ await Promise.resolve();
+ processed.push("first");
+ });
+
+ const second = queue.enqueue("1", async () => {
+ processed.push("second");
+ });
+
+ await Promise.all([first, second]);
+
+ assert.deepEqual(processed, ["first", "second"]);
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/signaling-test.js b/plugins/voice/test/javascripts/unit/lib/signaling-test.js
new file mode 100644
index 00000000000..2c87aad517c
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/signaling-test.js
@@ -0,0 +1,150 @@
+import { module, test } from "qunit";
+import SignalingManager from "discourse/plugins/voice/discourse/lib/voice/signaling";
+
+function wait(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+
+ return { promise, resolve, reject };
+}
+
+module("Voice | Unit | Lib | signaling", function () {
+ test("clearForPeer drops unsent HTTP-batched signals for destroyed peers", async function (assert) {
+ assert.timeout(1000);
+
+ let requests = 0;
+
+ const manager = new SignalingManager({
+ isActiveRoom: () => true,
+ hasPeer: () => true,
+ httpBatchDelayMs: 5,
+ requestSignals: async () => {
+ requests++;
+ },
+ });
+
+ const send = manager.send(1, 2, { type: "offer", sdp: "v=0" });
+ await Promise.resolve();
+ manager.clearForPeer(1, 2);
+
+ await send;
+ await wait(50);
+
+ assert.strictEqual(
+ requests,
+ 0,
+ "does not send signals that were cleared during teardown"
+ );
+
+ manager.destroy();
+ });
+
+ test("flushes a recipient's batch early once it reaches the event cap", async function (assert) {
+ assert.timeout(2000);
+
+ const payloads = [];
+
+ const manager = new SignalingManager({
+ isActiveRoom: () => true,
+ hasPeer: () => true,
+ // Far beyond the test's patience: only the early flush can send.
+ httpBatchDelayMs: 5000,
+ requestSignals: async (roomId, payload) => {
+ payloads.push(payload);
+ },
+ });
+
+ const sends = [];
+ for (let i = 0; i < 20; i++) {
+ sends.push(manager.send(1, 2, { type: "offer", sdp: `sdp-${i}` }));
+ }
+ await Promise.all(sends);
+
+ assert.strictEqual(
+ payloads.length,
+ 1,
+ "sends without waiting for the batch timer"
+ );
+ assert.strictEqual(
+ payloads[0].events.length,
+ 20,
+ "carries the whole accumulated batch"
+ );
+
+ manager.destroy();
+ });
+
+ test("each HTTP flush only settles the signals it actually sent", async function (assert) {
+ assert.timeout(2000);
+
+ const requests = [];
+ let firstResolved = false;
+ let secondResolved = false;
+
+ const manager = new SignalingManager({
+ isActiveRoom: () => true,
+ hasPeer: () => true,
+ httpBatchDelayMs: 5,
+ requestSignals: () => {
+ const request = deferred();
+ requests.push(request);
+ return request.promise;
+ },
+ });
+
+ const firstSend = manager
+ .send(1, 2, { type: "offer", sdp: "first" })
+ .then(() => {
+ firstResolved = true;
+ });
+
+ await wait(50);
+
+ assert.strictEqual(requests.length, 1, "starts the first HTTP flush");
+
+ const secondSend = manager
+ .send(1, 3, {
+ type: "offer",
+ sdp: "second",
+ })
+ .then(() => {
+ secondResolved = true;
+ });
+
+ await wait(50);
+
+ assert.strictEqual(
+ requests.length,
+ 2,
+ "starts a second HTTP flush for signals queued during the first one"
+ );
+
+ requests[0].resolve();
+ await firstSend;
+
+ assert.true(firstResolved, "resolves the first send after the first flush");
+ assert.false(
+ secondResolved,
+ "does not resolve later sends when an earlier flush completes"
+ );
+
+ requests[1].resolve();
+ await secondSend;
+
+ assert.true(
+ secondResolved,
+ "resolves the second send after its own flush completes"
+ );
+
+ manager.destroy();
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/sound-effects-test.js b/plugins/voice/test/javascripts/unit/lib/sound-effects-test.js
new file mode 100644
index 00000000000..9615d588a55
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/sound-effects-test.js
@@ -0,0 +1,276 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import {
+ DEFAULT_SOUND_NAME,
+ normalizeSoundName,
+ playConnectedSound,
+ playDeafenSound,
+ playDisconnectedSound,
+ playMuteSound,
+ playUndeafenSound,
+ playUnmuteSound,
+ playUserJoinedSound,
+ playUserLeftSound,
+ resetSoundEffectsForTesting,
+ startRingtone,
+ startWaitingSound,
+ stopCallSounds,
+} from "discourse/plugins/voice/discourse/lib/voice/sound-effects";
+
+const ROOM_CUES = [
+ playConnectedSound,
+ playDisconnectedSound,
+ playUserJoinedSound,
+ playUserLeftSound,
+ playMuteSound,
+ playUnmuteSound,
+ playDeafenSound,
+ playUndeafenSound,
+];
+
+class MockAudioParam {
+ value = null;
+ events = [];
+
+ setValueAtTime(value, time) {
+ this.events.push({ method: "set", value, time });
+ }
+
+ linearRampToValueAtTime(value, time) {
+ this.events.push({ method: "linear", value, time });
+ }
+
+ exponentialRampToValueAtTime(value, time) {
+ this.events.push({ method: "exponential", value, time });
+ }
+}
+
+class MockAudioContext {
+ state = "running";
+ currentTime = 1;
+ destination = {};
+ oscillators = [];
+ gains = [];
+
+ resume() {
+ return Promise.resolve();
+ }
+
+ createOscillator() {
+ const oscillator = {
+ type: "sine",
+ frequency: new MockAudioParam(),
+ connect: (node) => node,
+ start(time) {
+ this.startedAt = time;
+ },
+ stop(time) {
+ this.stoppedAt = time;
+ },
+ };
+ this.oscillators.push(oscillator);
+ return oscillator;
+ }
+
+ createGain() {
+ const gain = {
+ disconnected: false,
+ gain: new MockAudioParam(),
+ connect: (node) => node,
+ disconnect() {
+ this.disconnected = true;
+ },
+ };
+ this.gains.push(gain);
+ return gain;
+ }
+}
+
+module("Unit | Lib | sound-effects", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ resetSoundEffectsForTesting();
+ this.originalAudioContext = window.AudioContext;
+ this.context = new MockAudioContext();
+ const context = this.context;
+
+ window.AudioContext = class {
+ constructor() {
+ return context;
+ }
+ };
+ });
+
+ hooks.afterEach(function () {
+ resetSoundEffectsForTesting();
+ window.AudioContext = this.originalAudioContext;
+ });
+
+ test("normalizes sound names", function (assert) {
+ for (const name of ["classic", "soft", "retro", "bubble", "ethereal"]) {
+ assert.strictEqual(
+ normalizeSoundName(name),
+ name,
+ `${name} is a supported sound theme`
+ );
+ }
+
+ assert.strictEqual(
+ normalizeSoundName(),
+ DEFAULT_SOUND_NAME,
+ "missing preferences use the default call sound"
+ );
+ assert.strictEqual(
+ normalizeSoundName("ding"),
+ DEFAULT_SOUND_NAME,
+ "legacy preferences use the default call sound"
+ );
+ });
+
+ test("applies every theme to all room cues", async function (assert) {
+ for (const name of ["classic", "soft", "retro", "bubble", "ethereal"]) {
+ this.context.oscillators = [];
+
+ for (const playCue of ROOM_CUES) {
+ await playCue(name);
+ }
+
+ assert.strictEqual(
+ this.context.oscillators.length,
+ 12,
+ `${name} schedules every room cue`
+ );
+ assert.strictEqual(
+ this.context.oscillators.filter(({ type }) => type === "square").length,
+ name === "retro" ? 12 : 0,
+ `${name} uses the expected timbre`
+ );
+ assert.strictEqual(
+ this.context.oscillators.filter(({ frequency }) =>
+ frequency.events.some(({ method }) => method === "exponential")
+ ).length,
+ name === "bubble" ? 12 : 0,
+ `${name} uses the expected pitch motion`
+ );
+ }
+
+ await playConnectedSound("soft");
+ assert.true(
+ this.context.oscillators.at(-2).frequency.value < 400,
+ "soft cues use the lower register"
+ );
+
+ await playConnectedSound("ethereal");
+ const ethereal = this.context.oscillators.at(-2);
+ assert.true(
+ ethereal.stoppedAt - ethereal.startedAt > 0.4,
+ "ethereal cues have a glassy sustain"
+ );
+ });
+
+ test("ringtone themes have distinct call motifs", async function (assert) {
+ const expected = {
+ classic: { oscillators: 8, square: 0, sweeps: 0 },
+ soft: { oscillators: 6, square: 0, sweeps: 0 },
+ retro: { oscillators: 8, square: 8, sweeps: 0 },
+ bubble: { oscillators: 4, square: 0, sweeps: 4 },
+ ethereal: { oscillators: 4, square: 0, sweeps: 1 },
+ };
+
+ for (const [name, signature] of Object.entries(expected)) {
+ this.context.oscillators = [];
+ assert.true(await startRingtone(name), `${name} ringtone starts`);
+
+ assert.strictEqual(
+ this.context.oscillators.length,
+ signature.oscillators,
+ `${name} schedules its ringtone motif`
+ );
+ assert.strictEqual(
+ this.context.oscillators.filter(({ type }) => type === "square").length,
+ signature.square,
+ `${name} uses the expected oscillator timbre`
+ );
+ assert.strictEqual(
+ this.context.oscillators.filter(({ frequency }) =>
+ frequency.events.some(({ method }) => method === "exponential")
+ ).length,
+ signature.sweeps,
+ `${name} uses the expected pitch sweeps`
+ );
+ }
+ });
+
+ test("waiting themes are calmer variants of each ringtone", async function (assert) {
+ const expectedOscillators = {
+ classic: 2,
+ soft: 2,
+ retro: 2,
+ bubble: 1,
+ ethereal: 3,
+ };
+
+ for (const [name, oscillatorCount] of Object.entries(expectedOscillators)) {
+ this.context.oscillators = [];
+ assert.true(
+ await startWaitingSound(1000, name),
+ `${name} waiting sound starts`
+ );
+ assert.strictEqual(
+ this.context.oscillators.length,
+ oscillatorCount,
+ `${name} schedules its waiting motif`
+ );
+ }
+ });
+
+ test("stopping a call sound silences scheduled audio", async function (assert) {
+ await startRingtone("classic");
+ const output = this.context.gains[0];
+
+ stopCallSounds();
+
+ assert.true(output.disconnected, "the shared call output is disconnected");
+ });
+
+ test("a stopped suspended start cannot ring later", async function (assert) {
+ let resume;
+ this.context.state = "suspended";
+ this.context.resume = () =>
+ new Promise((resolve) => {
+ resume = resolve;
+ });
+
+ const start = startRingtone("soft");
+ stopCallSounds();
+ this.context.state = "running";
+ resume();
+
+ assert.false(await start, "the stale start is discarded");
+ assert.strictEqual(
+ this.context.oscillators.length,
+ 0,
+ "no ringtone is scheduled after it was stopped"
+ );
+ });
+
+ test("waiting sounds stop after their duration cap", async function (assert) {
+ const clock = sinon.useFakeTimers({
+ now: Date.now(),
+ toFake: ["Date", "setTimeout", "clearTimeout"],
+ });
+
+ try {
+ await startWaitingSound(10, "bubble");
+ const output = this.context.gains[0];
+
+ clock.tick(4000);
+
+ assert.true(output.disconnected, "the capped waiting sound is stopped");
+ } finally {
+ clock.restore();
+ }
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/speak-queue-test.js b/plugins/voice/test/javascripts/unit/lib/speak-queue-test.js
new file mode 100644
index 00000000000..48183ddb2d0
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/speak-queue-test.js
@@ -0,0 +1,97 @@
+import { module, test } from "qunit";
+import {
+ queuePosition,
+ speakQueue,
+} from "discourse/plugins/voice/discourse/lib/voice/speak-queue";
+
+function stageRoom(participants) {
+ return { room_type: "stage", active_participants: participants };
+}
+
+module("Voice | Unit | Lib | speak-queue", function () {
+ test("orders raised hands by hand_raised_at ascending", function (assert) {
+ const room = stageRoom([
+ { id: 1, hand_raised_at: 300 },
+ { id: 2, hand_raised_at: 100 },
+ { id: 3, hand_raised_at: 200 },
+ ]);
+
+ assert.deepEqual(
+ speakQueue(room).map((participant) => participant.id),
+ [2, 3, 1],
+ "the earliest raised hand comes first"
+ );
+ });
+
+ test("breaks equal timestamps by numeric user id", function (assert) {
+ const room = stageRoom([
+ { id: "10", hand_raised_at: 100 },
+ { id: "9", hand_raised_at: 100 },
+ ]);
+
+ assert.deepEqual(
+ speakQueue(room).map((participant) => participant.id),
+ ["9", "10"],
+ "ids compare numerically, not lexicographically"
+ );
+ });
+
+ test("excludes participants without a raised hand", function (assert) {
+ const room = stageRoom([
+ { id: 1 },
+ { id: 2, hand_raised_at: 100 },
+ { id: 3, hand_raised_at: null },
+ ]);
+
+ assert.deepEqual(
+ speakQueue(room).map((participant) => participant.id),
+ [2],
+ "only participants with hand_raised_at enter the queue"
+ );
+ });
+
+ test("returns an empty queue for non-stage rooms", function (assert) {
+ const room = {
+ room_type: "open",
+ active_participants: [{ id: 1, hand_raised_at: 100 }],
+ };
+
+ assert.deepEqual(
+ speakQueue(room),
+ [],
+ "raised hands are meaningless outside stage rooms"
+ );
+ assert.deepEqual(speakQueue(null), [], "a missing room yields no queue");
+ });
+
+ test("queuePosition returns the 1-based position in the queue", function (assert) {
+ const room = stageRoom([
+ { id: 1, hand_raised_at: 300 },
+ { id: 2, hand_raised_at: 100 },
+ { id: 3, hand_raised_at: 200 },
+ ]);
+
+ assert.strictEqual(queuePosition(room, 2), 1, "first raised hand is #1");
+ assert.strictEqual(queuePosition(room, 1), 3, "latest raised hand is #3");
+ });
+
+ test("queuePosition is null for un-queued users and falsy user ids", function (assert) {
+ const room = stageRoom([{ id: 1, hand_raised_at: 100 }, { id: 2 }]);
+
+ assert.strictEqual(
+ queuePosition(room, 2),
+ null,
+ "a participant without a raised hand has no position"
+ );
+ assert.strictEqual(
+ queuePosition(room, 99),
+ null,
+ "a user outside the room has no position"
+ );
+ assert.strictEqual(
+ queuePosition(room, null),
+ null,
+ "a falsy user id has no position"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/subtitles-test.js b/plugins/voice/test/javascripts/unit/lib/subtitles-test.js
new file mode 100644
index 00000000000..26bec43a9b4
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/subtitles-test.js
@@ -0,0 +1,354 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import SubtitlesManager from "discourse/plugins/voice/discourse/lib/voice/subtitles";
+
+function createFakeStream(id, trackId = `${id}-track`) {
+ return {
+ id,
+ getAudioTracks: () => [{ id: trackId, kind: "audio" }],
+ getTracks: () => [{ id: trackId, kind: "audio" }],
+ };
+}
+
+// Speaks the worker protocol: init → ready (immediately), transcribe →
+// caption echoing a canned text.
+class FakeWorker {
+ static instances = [];
+
+ onmessage = null;
+ onerror = null;
+ terminated = false;
+ jobs = [];
+ messages = [];
+
+ constructor() {
+ FakeWorker.instances.push(this);
+ }
+
+ postMessage(message) {
+ this.messages.push(message);
+ if (message.type === "init") {
+ Promise.resolve().then(() =>
+ this.onmessage?.({ data: { type: "ready" } })
+ );
+ } else if (message.type === "transcribe") {
+ this.jobs.push(message);
+ Promise.resolve().then(() =>
+ this.onmessage?.({
+ data: {
+ type: "caption",
+ roomId: message.roomId,
+ userId: message.userId,
+ utteranceId: message.utteranceId,
+ interim: message.interim,
+ text: message.interim ? "hello" : "hello world",
+ },
+ })
+ );
+ }
+ }
+
+ emit(data) {
+ this.onmessage?.({ data });
+ }
+
+ terminate() {
+ this.terminated = true;
+ }
+}
+
+class FakeVad {
+ static instances = [];
+
+ destroyed = false;
+
+ constructor(options) {
+ this.options = options;
+ FakeVad.instances.push(this);
+ }
+
+ async start() {}
+
+ destroy() {
+ this.destroyed = true;
+ }
+
+ speak(samples = 16000) {
+ this.options.onSpeechStart?.();
+ this.options.onSpeechEnd(new Float32Array(samples));
+ }
+
+ // Simulates an in-progress utterance: speech start plus `samples` worth of
+ // 512-sample VAD frames, without the closing speech end.
+ speakFrames(samples) {
+ this.options.onSpeechStart?.();
+ this.emitFrames(samples);
+ }
+
+ emitFrames(samples) {
+ for (let emitted = 0; emitted < samples; emitted += 512) {
+ this.options.onFrameProcessed?.({}, new Float32Array(512));
+ }
+ }
+
+ misfire() {
+ this.options.onVADMisfire?.();
+ }
+}
+
+function fakeVadModule() {
+ return {
+ MicVAD: {
+ new: async (options) => new FakeVad(options),
+ },
+ };
+}
+
+module("Voice | Unit | Lib | subtitles", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ localStorage.removeItem("voice:subtitles");
+ FakeWorker.instances = [];
+ FakeVad.instances = [];
+
+ this.captions = [];
+ this.errors = [];
+ this.progress = [];
+ this.manager = new SubtitlesManager({
+ onCaption: (roomId, userId, utterance) =>
+ this.captions.push({ roomId, userId, ...utterance }),
+ onLoadingChange: () => {},
+ onProgress: (message) => this.progress.push(message),
+ onError: (error) => this.errors.push(error),
+ loadVad: async () => fakeVadModule(),
+ createWorker: () => new FakeWorker(),
+ });
+ });
+
+ hooks.afterEach(function () {
+ this.manager.destroy();
+ localStorage.removeItem("voice:subtitles");
+ });
+
+ test("attaching taps a stream and captions flow end to end", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+
+ assert.strictEqual(FakeWorker.instances.length, 1, "one shared worker");
+ assert.strictEqual(FakeVad.instances.length, 1, "one VAD per stream");
+
+ FakeVad.instances[0].speak();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ assert.strictEqual(this.captions.length, 1);
+ assert.propContains(this.captions[0], {
+ roomId: 1,
+ userId: 42,
+ text: "hello world",
+ final: true,
+ });
+ assert.strictEqual(
+ FakeWorker.instances[0].jobs[0].userId,
+ 42,
+ "the utterance is attributed to its speaker"
+ );
+ });
+
+ test("captions carry the utterance's start wall-clock", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const vad = FakeVad.instances[0];
+
+ const before = Date.now();
+ vad.speakFrames(3 * 16000);
+ const after = Date.now();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ const interim = this.captions.at(-1);
+ assert.false(interim.final);
+ assert.true(
+ interim.startedAt >= before,
+ "the interim's start time is not earlier than the speech start"
+ );
+ assert.true(
+ interim.startedAt <= after,
+ "the interim's start time is not later than the speech start"
+ );
+
+ vad.options.onSpeechEnd(new Float32Array(4 * 16000));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ assert.strictEqual(
+ this.captions.at(-1).startedAt,
+ interim.startedAt,
+ "the final shares the interim's start time"
+ );
+ });
+
+ test("no worker or taps are created while disabled", async function (assert) {
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+
+ assert.strictEqual(FakeWorker.instances.length, 0);
+ assert.strictEqual(FakeVad.instances.length, 0);
+ });
+
+ test("re-attaching the same track is a no-op, a new track rebuilds the tap", async function (assert) {
+ this.manager.setEnabled(true);
+ const stream = createFakeStream("s1", "track-a");
+ await this.manager.attach(1, 42, stream);
+ await this.manager.attach(1, 42, stream);
+
+ assert.strictEqual(FakeVad.instances.length, 1, "same track reuses tap");
+
+ await this.manager.attach(1, 42, createFakeStream("s1", "track-b"));
+
+ assert.strictEqual(FakeVad.instances.length, 2, "new track rebuilds");
+ assert.true(FakeVad.instances[0].destroyed, "old tap is torn down");
+ });
+
+ test("disable tears everything down and drops in-flight utterances", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const vad = FakeVad.instances[0];
+
+ this.manager.setEnabled(false);
+
+ assert.true(vad.destroyed, "VAD destroyed");
+ assert.true(FakeWorker.instances[0].terminated, "worker terminated");
+
+ vad.speak();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.deepEqual(this.captions, [], "stale utterances are ignored");
+ });
+
+ test("detachRoom only removes that room's taps", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ await this.manager.attach(2, 43, createFakeStream("s2"));
+
+ this.manager.detachRoom(1);
+
+ assert.true(FakeVad.instances[0].destroyed);
+ assert.false(FakeVad.instances[1].destroyed);
+ });
+
+ test("a worker error surfaces once and terminates the worker", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+
+ FakeWorker.instances[0].emit({ type: "error", message: "boom" });
+
+ assert.strictEqual(this.errors.length, 1);
+ assert.true(FakeWorker.instances[0].terminated);
+ });
+
+ test("a long in-progress utterance produces interim captions on a cadence", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const vad = FakeVad.instances[0];
+ const worker = FakeWorker.instances[0];
+
+ // 3s of speech without a pause: past the 1s minimum and the 1.5s
+ // interim cadence (twice).
+ vad.speakFrames(3 * 16000);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ const interims = worker.jobs.filter((job) => job.interim);
+ assert.true(interims.length >= 1, "provisional snapshots were sent");
+ assert.false(
+ this.captions.at(-1).final,
+ "the caption is marked provisional"
+ );
+
+ vad.options.onSpeechEnd(new Float32Array(4 * 16000));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ const finals = worker.jobs.filter((job) => !job.interim);
+ assert.strictEqual(finals.length, 1, "one final pass");
+ assert.strictEqual(
+ finals[0].utteranceId,
+ interims[0].utteranceId,
+ "final and interims share the utterance"
+ );
+ assert.propContains(this.captions.at(-1), {
+ text: "hello world",
+ final: true,
+ });
+ });
+
+ test("a VAD misfire retracts the provisional caption", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const vad = FakeVad.instances[0];
+
+ vad.speakFrames(3 * 16000);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.false(this.captions.at(-1).final);
+
+ vad.misfire();
+
+ assert.propContains(this.captions.at(-1), { text: null, final: true });
+ });
+
+ test("detaching flushes the speaker's queue and drops in-flight captions", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const worker = FakeWorker.instances[0];
+
+ // The caption for this utterance is still "in flight" (a microtask away)
+ // when the tap is detached.
+ FakeVad.instances[0].speak();
+ this.manager.detach(1, 42);
+
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ assert.deepEqual(this.captions, [], "stale caption is dropped");
+ assert.propContains(
+ worker.messages.at(-1),
+ { type: "flush", roomId: 1, userId: 42 },
+ "the worker is told to discard the speaker's queued jobs"
+ );
+ });
+
+ test("a slow-throughput signal sheds interim passes until recovery", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(1, 42, createFakeStream("s1"));
+ const vad = FakeVad.instances[0];
+ const worker = FakeWorker.instances[0];
+
+ worker.emit({ type: "throughput", slow: true });
+ vad.speakFrames(4 * 16000);
+ assert.deepEqual(
+ worker.jobs.filter((job) => job.interim),
+ [],
+ "no provisional snapshots while the model is behind"
+ );
+
+ worker.emit({ type: "throughput", slow: false });
+ vad.emitFrames(4 * 16000);
+ assert.true(
+ worker.jobs.filter((job) => job.interim).length >= 1,
+ "provisional snapshots resume once throughput recovers"
+ );
+
+ vad.options.onSpeechEnd(new Float32Array(4 * 16000));
+ assert.strictEqual(
+ worker.jobs.filter((job) => !job.interim).length,
+ 1,
+ "the final pass is never shed"
+ );
+ });
+
+ test("short utterances still reach the worker with identity attached", async function (assert) {
+ this.manager.setEnabled(true);
+ await this.manager.attach(7, 9, createFakeStream("s1"));
+
+ FakeVad.instances[0].speak(8000);
+
+ const job = FakeWorker.instances[0].jobs[0];
+ assert.strictEqual(job.roomId, 7);
+ assert.strictEqual(job.userId, 9);
+ assert.strictEqual(job.pcm.byteLength, 8000 * 4);
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/transcript-draft-sync-test.js b/plugins/voice/test/javascripts/unit/lib/transcript-draft-sync-test.js
new file mode 100644
index 00000000000..5216a75cccb
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/transcript-draft-sync-test.js
@@ -0,0 +1,111 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import TranscriptDraftSync from "discourse/plugins/voice/discourse/lib/voice/transcript-draft-sync";
+
+module("Voice | Unit | Lib | transcript-draft-sync", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.saves = [];
+ this.data = { reply: "transcript", action: "createTopic" };
+ this.saveResult = () => ({ draft_sequence: this.saves.length });
+
+ this.sync = new TranscriptDraftSync({
+ save: (key, sequence, data) => {
+ this.saves.push({ key, sequence, data });
+ return Promise.resolve(this.saveResult());
+ },
+ buildData: () => this.data,
+ });
+ });
+
+ hooks.afterEach(function () {
+ this.sync.dispose();
+ });
+
+ test("flushes only when dirty and tracks the sequence", async function (assert) {
+ this.sync.start(5, 1000);
+ assert.strictEqual(this.sync.key, "new_topic_voice_5_1000");
+
+ await this.sync.flush();
+ assert.strictEqual(this.saves.length, 0, "clean flush is a no-op");
+
+ this.sync.markDirty();
+ await this.sync.flush();
+ assert.strictEqual(this.saves.length, 1);
+ assert.strictEqual(this.saves[0].sequence, 0);
+
+ await this.sync.flush();
+ assert.strictEqual(this.saves.length, 1, "saved content is not resent");
+
+ this.sync.markDirty();
+ await this.sync.flush();
+ assert.strictEqual(
+ this.saves[1].sequence,
+ 1,
+ "the server's sequence is used for the next save"
+ );
+ });
+
+ test("does not save an empty transcript", async function (assert) {
+ this.sync.start(5, 1000);
+ this.data = null;
+ this.sync.markDirty();
+
+ await this.sync.flush();
+
+ assert.strictEqual(this.saves.length, 0);
+ });
+
+ test("a sequence conflict hands off permanently", async function (assert) {
+ let attempts = 0;
+ const sync = new TranscriptDraftSync({
+ save: () => {
+ attempts++;
+ return Promise.reject({ jqXHR: { status: 409 } });
+ },
+ buildData: () => this.data,
+ });
+ sync.start(7, 3000);
+
+ sync.markDirty();
+ await sync.flush();
+ assert.strictEqual(attempts, 1);
+
+ sync.markDirty();
+ await sync.flush();
+ assert.strictEqual(attempts, 1, "a conflicted draft is never retried");
+ sync.dispose();
+ });
+
+ test("a transient failure retries on the next flush", async function (assert) {
+ let attempts = 0;
+ const sync = new TranscriptDraftSync({
+ save: () => {
+ attempts++;
+ return attempts === 1
+ ? Promise.reject({ jqXHR: { status: 500 } })
+ : Promise.resolve({ draft_sequence: 1 });
+ },
+ buildData: () => this.data,
+ });
+ sync.start(6, 2000);
+
+ sync.markDirty();
+ await sync.flush();
+ await sync.flush();
+
+ assert.strictEqual(attempts, 2, "stays dirty and retries");
+ sync.dispose();
+ });
+
+ test("stop flushes what is pending", async function (assert) {
+ this.sync.start(5, 1000);
+ this.sync.markDirty();
+
+ await this.sync.stop();
+
+ assert.strictEqual(this.saves.length, 1);
+ assert.strictEqual(this.sync.key, "new_topic_voice_5_1000", "key kept");
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/transcript-markdown-test.js b/plugins/voice/test/javascripts/unit/lib/transcript-markdown-test.js
new file mode 100644
index 00000000000..5a251cd43f5
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/transcript-markdown-test.js
@@ -0,0 +1,57 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { transcriptToMarkdown } from "discourse/plugins/voice/discourse/lib/voice/transcript-markdown";
+
+module("Voice | Unit | Lib | transcript-markdown", function (hooks) {
+ setupTest(hooks);
+
+ const entries = [
+ {
+ utteranceId: 7,
+ userId: 42,
+ username: "alice",
+ text: "hello world",
+ startedAt: Date.UTC(2026, 7, 20, 16, 38, 24),
+ },
+ {
+ utteranceId: 8,
+ userId: 43,
+ username: "bob",
+ text: "hi there",
+ startedAt: Date.UTC(2026, 7, 20, 16, 38, 46),
+ },
+ ];
+
+ test("renders chained chat transcript markup", function (assert) {
+ const markdown = transcriptToMarkdown(entries);
+
+ assert.strictEqual(
+ markdown,
+ [
+ '[chat quote="alice;7;2026-08-20T16:38:24.000Z" chained="true"]\nhello world\n[/chat]',
+ '[chat quote="bob;8;2026-08-20T16:38:46.000Z" chained="true"]\nhi there\n[/chat]',
+ ].join("\n\n")
+ );
+ });
+
+ test("falls back to plain quotes without chat markup", function (assert) {
+ const markdown = transcriptToMarkdown(entries, { chatMarkup: false });
+
+ assert.strictEqual(
+ markdown,
+ [
+ '[quote="alice"]\nhello world\n[/quote]',
+ '[quote="bob"]\nhi there\n[/quote]',
+ ].join("\n\n")
+ );
+ });
+
+ test("a missing username gets a placeholder", function (assert) {
+ const markdown = transcriptToMarkdown([
+ { utteranceId: 9, text: "who dis", startedAt: 0 },
+ ]);
+
+ assert.false(markdown.includes('"undefined;'));
+ assert.true(markdown.startsWith("[chat quote="));
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/transcript-recorder-test.js b/plugins/voice/test/javascripts/unit/lib/transcript-recorder-test.js
new file mode 100644
index 00000000000..0e428bf021d
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/transcript-recorder-test.js
@@ -0,0 +1,138 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import TranscriptRecorder from "discourse/plugins/voice/discourse/lib/voice/transcript-recorder";
+
+module("Voice | Unit | Lib | transcript-recorder", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.changes = 0;
+ this.recorder = new TranscriptRecorder({
+ onChange: () => this.changes++,
+ });
+ });
+
+ test("records final utterances with speaker and start time", function (assert) {
+ this.recorder.start(1);
+ this.recorder.record(1, 42, "alice", {
+ id: 7,
+ text: "hello world",
+ final: true,
+ startedAt: 1000,
+ });
+
+ assert.deepEqual(this.recorder.entries, [
+ {
+ utteranceId: 7,
+ userId: 42,
+ username: "alice",
+ text: "hello world",
+ startedAt: 1000,
+ },
+ ]);
+ });
+
+ test("ignores interims, other rooms, and captions while not recording", function (assert) {
+ this.recorder.record(1, 42, "alice", {
+ id: 1,
+ text: "before start",
+ final: true,
+ startedAt: 1,
+ });
+
+ this.recorder.start(1);
+ this.recorder.record(1, 42, "alice", {
+ id: 2,
+ text: "provisional",
+ final: false,
+ startedAt: 2,
+ });
+ this.recorder.record(2, 42, "alice", {
+ id: 3,
+ text: "other room",
+ final: true,
+ startedAt: 3,
+ });
+
+ assert.deepEqual(this.recorder.entries, []);
+ });
+
+ test("a null-text final withdraws the entry", function (assert) {
+ this.recorder.start(1);
+ this.recorder.record(1, 42, "alice", {
+ id: 7,
+ text: "oops",
+ final: true,
+ startedAt: 1000,
+ });
+ this.recorder.record(1, 42, "alice", { id: 7, text: null, final: true });
+
+ assert.deepEqual(this.recorder.entries, []);
+ });
+
+ test("entries are ordered by utterance start, not arrival", function (assert) {
+ this.recorder.start(1);
+ // The shared worker serializes jobs, so with overlapping speakers the
+ // later-started utterance can be transcribed first.
+ this.recorder.record(1, 43, "bob", {
+ id: 8,
+ text: "second",
+ final: true,
+ startedAt: 2000,
+ });
+ this.recorder.record(1, 42, "alice", {
+ id: 7,
+ text: "first",
+ final: true,
+ startedAt: 1000,
+ });
+
+ assert.deepEqual(
+ this.recorder.entries.map((entry) => entry.text),
+ ["first", "second"]
+ );
+ });
+
+ test("stop keeps the transcript, a new start discards it", function (assert) {
+ this.recorder.start(1);
+ this.recorder.record(1, 42, "alice", {
+ id: 7,
+ text: "kept",
+ final: true,
+ startedAt: 1000,
+ });
+
+ this.recorder.stop();
+ assert.false(this.recorder.recording);
+ assert.strictEqual(this.recorder.entries.length, 1, "entries survive stop");
+ assert.strictEqual(
+ this.recorder.entriesRoomId,
+ 1,
+ "the entries' room survives stop"
+ );
+
+ this.recorder.record(1, 42, "alice", {
+ id: 8,
+ text: "after stop",
+ final: true,
+ startedAt: 2000,
+ });
+ assert.strictEqual(this.recorder.entries.length, 1, "stopped is stopped");
+
+ this.recorder.start(1);
+ assert.deepEqual(this.recorder.entries, [], "restart clears");
+ });
+
+ test("onChange fires for every mutation", function (assert) {
+ this.recorder.start(1);
+ this.recorder.record(1, 42, "alice", {
+ id: 7,
+ text: "hello",
+ final: true,
+ startedAt: 1000,
+ });
+ this.recorder.stop();
+
+ assert.strictEqual(this.changes, 3);
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/video-grid-layout-test.js b/plugins/voice/test/javascripts/unit/lib/video-grid-layout-test.js
new file mode 100644
index 00000000000..84ff1d1fd1c
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/video-grid-layout-test.js
@@ -0,0 +1,219 @@
+import { module, test } from "qunit";
+import {
+ bestRowHeight,
+ computeWidgetGrid,
+ DEFAULT_TILE_ASPECT,
+} from "discourse/plugins/voice/discourse/lib/voice/video-grid-layout";
+
+const LANDSCAPE = DEFAULT_TILE_ASPECT; // 16 / 9
+const PORTRAIT = 9 / 16;
+
+module("Voice | Unit | Lib | video-grid-layout", function () {
+ test("a single tile fills the constraining dimension", function (assert) {
+ // Wide container: a landscape tile is limited by height.
+ assert.strictEqual(
+ bestRowHeight(4000, 900, [LANDSCAPE], 0),
+ 900,
+ "height-limited single landscape tile spans the full height"
+ );
+
+ // Narrow container: limited by width.
+ assert.strictEqual(
+ bestRowHeight(1000, 4000, [LANDSCAPE], 0),
+ 562,
+ "width-limited single landscape tile spans the full width"
+ );
+ });
+
+ test("a portrait tile fills the height of a landscape container", function (assert) {
+ const height = bestRowHeight(1920, 1080, [PORTRAIT], 0);
+ assert.strictEqual(
+ height,
+ 1080,
+ "portrait tile uses the full height instead of being letterboxed"
+ );
+ assert.true(
+ height * PORTRAIT <= 1920,
+ "and stays within the container width"
+ );
+ });
+
+ test("more tiles shrink the row height without overflowing", function (assert) {
+ const width = 1920;
+ const height = 1080;
+ const counts = [1, 2, 4, 9];
+
+ const heights = counts.map((count) =>
+ bestRowHeight(width, height, Array(count).fill(LANDSCAPE), 8)
+ );
+
+ assert.deepEqual(
+ [...heights].sort((a, b) => b - a),
+ heights,
+ "row height is monotonically non-increasing as tiles are added"
+ );
+
+ heights.forEach((rowHeight, index) => {
+ assert.true(rowHeight > 0, `${counts[index]} tiles get a usable height`);
+ assert.true(
+ rowHeight <= height,
+ `${counts[index]} tiles fit within the container height`
+ );
+ });
+ });
+
+ test("mixed portrait and landscape tiles share a row at a common height", function (assert) {
+ const rowHeight = bestRowHeight(1920, 1080, [LANDSCAPE, PORTRAIT], 8);
+
+ // One row beats stacking (which would cap height near 536), so the shared
+ // height lands well above that.
+ assert.true(rowHeight > 600, "lays the two tiles out side by side");
+
+ const totalWidth = rowHeight * LANDSCAPE + 8 + rowHeight * PORTRAIT;
+ assert.true(
+ totalWidth <= 1920,
+ "the mixed-aspect row fits the container width"
+ );
+ });
+
+ test("returns zero when nothing can fit", function (assert) {
+ assert.strictEqual(
+ bestRowHeight(10, 10, Array(50).fill(LANDSCAPE), 8),
+ 0,
+ "degenerate space yields no usable height"
+ );
+ });
+});
+
+module("Voice | Unit | Lib | video-grid-layout | widget grid", function () {
+ test("a lone participant fills the box, aspect permitting", function (assert) {
+ assert.deepEqual(
+ computeWidgetGrid({ width: 400, height: 300, count: 1, gap: 8 }),
+ {
+ shown: 1,
+ overflow: 0,
+ cols: 1,
+ rows: 1,
+ tileWidth: 400,
+ tileHeight: 300,
+ },
+ "a 4:3 box is within the aspect band, so the tile takes all of it"
+ );
+ });
+
+ test("shows everyone in the largest-tile arrangement when they fit", function (assert) {
+ assert.deepEqual(
+ computeWidgetGrid({ width: 400, height: 300, count: 4, gap: 8 }),
+ {
+ shown: 4,
+ overflow: 0,
+ cols: 2,
+ rows: 2,
+ tileWidth: 196,
+ tileHeight: 146,
+ },
+ "four participants get a 2×2 grid of cell-filling tiles"
+ );
+ });
+
+ test("collapses a crowd into an overflow slot when tiles would go illegible", function (assert) {
+ assert.deepEqual(
+ computeWidgetGrid({ width: 360, height: 200, count: 12, gap: 8 }),
+ {
+ shown: 5,
+ overflow: 7,
+ cols: 3,
+ rows: 2,
+ tileWidth: 114,
+ tileHeight: 86,
+ },
+ "drops to the six-slot arrangement: five participants plus the overflow tile"
+ );
+ });
+
+ test("never hides exactly one participant", function (assert) {
+ const boxes = [
+ { width: 360, height: 200 },
+ { width: 300, height: 150 },
+ { width: 800, height: 600 },
+ { width: 150, height: 100 },
+ ];
+
+ for (const { width, height } of boxes) {
+ for (let count = 1; count <= 30; count++) {
+ const layout = computeWidgetGrid({ width, height, count, gap: 8 });
+ assert.notStrictEqual(
+ layout.overflow,
+ 1,
+ `${count} in ${width}×${height}: overflow of ${layout.overflow} is never one`
+ );
+ assert.strictEqual(
+ layout.shown + layout.overflow,
+ count,
+ `${count} in ${width}×${height}: everyone is shown or counted`
+ );
+ assert.true(
+ layout.shown >= 1,
+ `${count} in ${width}×${height}: at least one participant stays visible`
+ );
+ }
+ }
+ });
+
+ test("flooring never lets an extra tile squeeze onto a row", function (assert) {
+ // 366×140 at gap 7.5 floors the 2×2 tile to 117px — exactly three of
+ // which would fit one flex row (3×117 + 2×7.5 = 366) without the guard,
+ // rendering 3+1 instead of the solved grid.
+ const layout = computeWidgetGrid({
+ width: 366,
+ height: 140,
+ count: 4,
+ gap: 7.5,
+ });
+ assert.strictEqual(layout.cols, 2, "solves a 2×2");
+ assert.true(
+ layout.tileWidth * 3 + 2 * 7.5 > 366,
+ "three tiles cannot share a row"
+ );
+ assert.true(
+ layout.tileWidth * 2 + 7.5 <= 366,
+ "two tiles still fit their row"
+ );
+ });
+
+ test("caps visible slots even with room to spare", function (assert) {
+ const layout = computeWidgetGrid({
+ width: 2000,
+ height: 1500,
+ count: 40,
+ gap: 8,
+ });
+ assert.strictEqual(layout.shown, 11, "eleven participants plus overflow");
+ assert.strictEqual(layout.overflow, 29, "the rest collapse into the count");
+ });
+
+ test("yields the legibility floor rather than vanishing in a tiny box", function (assert) {
+ const layout = computeWidgetGrid({
+ width: 150,
+ height: 100,
+ count: 6,
+ gap: 8,
+ });
+ assert.strictEqual(layout.shown, 1, "keeps one participant visible");
+ assert.strictEqual(layout.overflow, 5, "counts the rest");
+ assert.true(layout.tileWidth > 0, "with a usable tile size");
+ });
+
+ test("returns null for degenerate input", function (assert) {
+ assert.strictEqual(
+ computeWidgetGrid({ width: 400, height: 300, count: 0, gap: 8 }),
+ null,
+ "no participants"
+ );
+ assert.strictEqual(
+ computeWidgetGrid({ width: 0, height: 300, count: 4, gap: 8 }),
+ null,
+ "no measured space"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/models/voice-room-test.js b/plugins/voice/test/javascripts/unit/models/voice-room-test.js
new file mode 100644
index 00000000000..b1352821d3f
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/models/voice-room-test.js
@@ -0,0 +1,48 @@
+import { module, test } from "qunit";
+import VoiceRoom from "discourse/plugins/voice/admin/models/voice-room";
+
+module("Unit | model | voice-room", function () {
+ const attrs = () => ({
+ name: "Team Meeting",
+ description: "Recurring sync",
+ public: true,
+ max_participants: 20,
+ video_enabled: true,
+ livekit_enabled: false,
+ chat_channel_id: 6,
+ chat_idle_minutes: 2,
+ });
+
+ test("createProperties includes the chat settings fields", function (assert) {
+ const room = VoiceRoom.create(attrs());
+
+ assert.deepEqual(room.createProperties(), attrs());
+ });
+
+ test("updateProperties includes the chat settings fields", function (assert) {
+ const room = VoiceRoom.create(attrs());
+
+ assert.deepEqual(room.updateProperties(), attrs());
+ });
+
+ test("updateProperties sends an explicit null for a cleared chat channel", function (assert) {
+ // FormKit's select control reports `undefined` for its "None" option.
+ // JSON.stringify (used by this model's adapter) silently drops
+ // `undefined`-valued keys, so the clear would never reach the server
+ // unless it's normalized to `null` first.
+ const room = VoiceRoom.create({ ...attrs(), chat_channel_id: undefined });
+
+ const saved = room.updateProperties();
+
+ assert.strictEqual(saved.chat_channel_id, null);
+ assert.true(
+ Object.prototype.hasOwnProperty.call(saved, "chat_channel_id"),
+ "the key survives JSON.stringify instead of being dropped"
+ );
+ assert.strictEqual(
+ JSON.parse(JSON.stringify(saved)).chat_channel_id,
+ null,
+ "round-trips through JSON as an explicit null"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/services/voice-rooms-test.js b/plugins/voice/test/javascripts/unit/services/voice-rooms-test.js
new file mode 100644
index 00000000000..4a37dfb5f47
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/services/voice-rooms-test.js
@@ -0,0 +1,52 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+
+module("Voice | Unit | Service | voice-rooms", function (hooks) {
+ setupTest(hooks);
+
+ test("participant lists keep one canonical order across updates", function (assert) {
+ const service = this.owner.lookup("service:voice-rooms");
+
+ service.handleDirectoryEvent({
+ type: "created",
+ room: {
+ id: 1,
+ slug: "watercooler",
+ active_participants: [
+ { id: 3, username: "zoe" },
+ { id: 1, username: "adam" },
+ ],
+ },
+ });
+
+ assert.deepEqual(
+ service.roomById(1).active_participants.map((entry) => entry.username),
+ ["adam", "zoe"],
+ "directory payloads are normalized"
+ );
+
+ service.handleRoomBroadcast({
+ room_id: 1,
+ type: "participants",
+ participants: [
+ { id: 2, username: "Mia" },
+ { id: 3, username: "zoe" },
+ { id: 1, username: "adam" },
+ ],
+ });
+
+ assert.deepEqual(
+ service.roomById(1).active_participants.map((entry) => entry.username),
+ ["adam", "Mia", "zoe"],
+ "broadcasts arriving in arbitrary order are normalized"
+ );
+
+ service.addParticipant(1, { id: 4, username: "bea" });
+
+ assert.deepEqual(
+ service.roomById(1).active_participants.map((entry) => entry.username),
+ ["adam", "bea", "Mia", "zoe"],
+ "locally added participants slot into the canonical order"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/services/voice-webrtc-livekit-test.js b/plugins/voice/test/javascripts/unit/services/voice-webrtc-livekit-test.js
new file mode 100644
index 00000000000..6cf79f56e21
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/services/voice-webrtc-livekit-test.js
@@ -0,0 +1,1414 @@
+import Service from "@ember/service";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import Site from "discourse/models/site";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import {
+ setLivekitReconnectDelaysForTesting,
+ setLivekitSdkLoaderForTesting,
+} from "discourse/plugins/voice/discourse/lib/voice/livekit-session";
+import { setPeerTimingForTesting } from "discourse/plugins/voice/discourse/lib/voice/peer-manager";
+
+// Park the mesh peer machinery's wall-clock timers far outside any test's
+// window. This suite mostly runs on the livekit transport, but its mesh
+// tests still create peers whose fallback-offer/restart timers would
+// otherwise fire mid-test under CI load (QUnit shuffles test order every
+// run, so a late firing poisons whichever test happens to be running).
+const SAFE_PEER_TIMING = {
+ offerRetryBaseDelayMs: 60_000,
+ maxOfferRetryDelayMs: 60_000,
+ restartImmediateDelayMs: 60_000,
+ restartDisconnectedDelayMs: 60_000,
+ maxRestartDelayMs: 60_000,
+ connectionTimeoutMs: 60_000,
+};
+
+class VoiceRoomsStub extends Service {
+ #roomHandlers = new Map();
+ #roomsById = new Map();
+
+ seedRoom(room) {
+ this.#roomsById.set(room.id, room);
+ }
+
+ roomById(id) {
+ return this.#roomsById.get(id);
+ }
+
+ registerRoomHandler(roomId, callback) {
+ let callbacks = this.#roomHandlers.get(roomId);
+
+ if (!callbacks) {
+ callbacks = new Set();
+ this.#roomHandlers.set(roomId, callbacks);
+ }
+
+ callbacks.add(callback);
+ }
+
+ unregisterRoomHandler(roomId, callback) {
+ const callbacks = this.#roomHandlers.get(roomId);
+ if (!callbacks) {
+ return;
+ }
+
+ callbacks.delete(callback);
+ if (!callbacks.size) {
+ this.#roomHandlers.delete(roomId);
+ }
+ }
+
+ emit(roomId, payload) {
+ const room = this.#roomsById.get(roomId);
+
+ if (payload.type === "participants" && room) {
+ room.active_participants = payload.participants;
+ }
+
+ this.#roomHandlers.get(roomId)?.forEach((callback) => callback(payload));
+ }
+
+ addParticipant(roomId, participant) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ const existing = room.active_participants || [];
+ if (existing.some((entry) => Number(entry.id) === Number(participant.id))) {
+ return;
+ }
+
+ room.active_participants = [...existing, participant];
+ }
+
+ removeParticipant(roomId, userId) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ room.active_participants = (room.active_participants || []).filter(
+ (participant) => Number(participant.id) !== Number(userId)
+ );
+ }
+
+ setParticipantMuted() {}
+ setParticipantDeafened() {}
+ setParticipantSpeaking() {}
+ setParticipantIdleState() {}
+ setParticipantVideoState() {}
+}
+
+class RecordingToastsStub extends Service {
+ errors = [];
+ defaults = [];
+
+ error(args) {
+ this.errors.push(args);
+ }
+
+ success() {}
+
+ default(args) {
+ this.defaults.push(args);
+ }
+}
+
+class FakeRTCPeerConnection {
+ static created = 0;
+
+ constructor() {
+ FakeRTCPeerConnection.created++;
+ }
+
+ addTrack() {
+ return { track: null, async replaceTrack() {} };
+ }
+
+ addTransceiver() {
+ return {
+ direction: "sendrecv",
+ sender: { track: null, async replaceTrack() {} },
+ receiver: { track: null },
+ };
+ }
+
+ getTransceivers() {
+ return [];
+ }
+
+ getSenders() {
+ return [];
+ }
+
+ async createOffer() {
+ return { type: "offer", sdp: "fake-offer" };
+ }
+
+ async setLocalDescription() {}
+
+ close() {}
+}
+
+// A minimal livekit-client stand-in exposing exactly the surface
+// LivekitRoomSession touches, injected via the module test loader.
+function buildFakeSdk() {
+ const RoomEvent = {
+ TrackSubscribed: "trackSubscribed",
+ TrackUnsubscribed: "trackUnsubscribed",
+ TrackPublished: "trackPublished",
+ ParticipantDisconnected: "participantDisconnected",
+ ParticipantPermissionsChanged: "participantPermissionsChanged",
+ Disconnected: "disconnected",
+ Reconnecting: "reconnecting",
+ Reconnected: "reconnected",
+ };
+
+ const VideoQuality = {
+ LOW: 0,
+ MEDIUM: 1,
+ HIGH: 2,
+ };
+
+ const DisconnectReason = {
+ UNKNOWN_REASON: 0,
+ CLIENT_INITIATED: 1,
+ DUPLICATE_IDENTITY: 2,
+ SERVER_SHUTDOWN: 3,
+ 0: "UNKNOWN_REASON",
+ 1: "CLIENT_INITIATED",
+ 2: "DUPLICATE_IDENTITY",
+ 3: "SERVER_SHUTDOWN",
+ };
+
+ const Track = {
+ Source: {
+ Camera: "camera",
+ Microphone: "microphone",
+ ScreenShare: "screen_share",
+ ScreenShareAudio: "screen_share_audio",
+ },
+ };
+
+ class FakeLivekitRoom {
+ static instances = [];
+ static connectErrors = [];
+
+ options;
+ connectCalls = [];
+ disconnectCalls = 0;
+ remoteParticipants = new Map();
+ #handlers = new Map();
+
+ constructor(options) {
+ this.options = options;
+ FakeLivekitRoom.instances.push(this);
+
+ const room = this;
+ this.localParticipant = {
+ published: [],
+ unpublishCalls: [],
+ async publishTrack(track, publishOptions) {
+ const publication = {
+ source: publishOptions?.source,
+ options: publishOptions,
+ track: {
+ mediaStreamTrack: track,
+ replaceCalls: [],
+ async replaceTrack(newTrack) {
+ this.mediaStreamTrack = newTrack;
+ this.replaceCalls.push(newTrack);
+ },
+ },
+ };
+ room.localParticipant.published.push(publication);
+ return publication;
+ },
+ async unpublishTrack(track, stopOnUnpublish) {
+ room.localParticipant.unpublishCalls.push({ track, stopOnUnpublish });
+ room.localParticipant.published =
+ room.localParticipant.published.filter(
+ (publication) => publication.track !== track
+ );
+ },
+ };
+ }
+
+ on(event, handler) {
+ const handlers = this.#handlers.get(event) || [];
+ handlers.push(handler);
+ this.#handlers.set(event, handlers);
+ return this;
+ }
+
+ emit(event, ...args) {
+ (this.#handlers.get(event) || []).forEach((handler) => handler(...args));
+ }
+
+ async connect(url, token) {
+ this.connectCalls.push({ url, token });
+
+ const error = FakeLivekitRoom.connectErrors.shift();
+ if (error) {
+ throw error;
+ }
+ }
+
+ async disconnect() {
+ this.disconnectCalls++;
+ }
+
+ removeAllListeners() {
+ this.#handlers.clear();
+ }
+ }
+
+ return {
+ sdk: {
+ Room: FakeLivekitRoom,
+ RoomEvent,
+ DisconnectReason,
+ Track,
+ VideoQuality,
+ isBrowserSupported: () => true,
+ },
+ FakeLivekitRoom,
+ };
+}
+
+function createFakeRemotePublication(source, kind) {
+ return {
+ source,
+ kind,
+ isSubscribed: true,
+ subscribedCalls: [],
+ qualityCalls: [],
+ setSubscribed(value) {
+ this.isSubscribed = value;
+ this.subscribedCalls.push(value);
+ },
+ setVideoQuality(quality) {
+ this.qualityCalls.push(quality);
+ },
+ };
+}
+
+function wait(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function waitUntil(callback, timeout = 500) {
+ const startedAt = Date.now();
+
+ while (!callback()) {
+ if (Date.now() - startedAt > timeout) {
+ throw new Error("Timed out waiting for condition");
+ }
+ await wait(10);
+ }
+}
+
+function createFakeTrack(id, kind = "audio") {
+ return {
+ id,
+ kind,
+ enabled: true,
+ stop() {},
+ addEventListener() {},
+ };
+}
+
+function createFakeStream(id, track) {
+ return {
+ id,
+ getTracks() {
+ return [track];
+ },
+ getAudioTracks() {
+ return [track];
+ },
+ };
+}
+
+function createFakeMediaStream(id, tracks) {
+ return {
+ id,
+ getTracks: () => [...tracks],
+ getAudioTracks: () => tracks.filter((track) => track.kind === "audio"),
+ getVideoTracks: () => tracks.filter((track) => track.kind === "video"),
+ };
+}
+
+function installFakeAudioEnvironment({ rawStream, processedStream }) {
+ const originalAudioContext = globalThis.AudioContext;
+ const originalAudioWorkletNode = globalThis.AudioWorkletNode;
+ const originalRequestAnimationFrame = window.requestAnimationFrame;
+ const originalCancelAnimationFrame = window.cancelAnimationFrame;
+ const originalWindowAudioContext = window.AudioContext;
+ const originalWindowWebkitAudioContext = window.webkitAudioContext;
+ const originalGetUserMedia = navigator.mediaDevices?.getUserMedia;
+
+ class FakeAudioContext {
+ currentTime = 0;
+ state = "running";
+ destination = {};
+ audioWorklet = {
+ addModule: async () => {},
+ };
+
+ resume() {
+ this.state = "running";
+ return Promise.resolve();
+ }
+
+ createMediaStreamSource() {
+ return {
+ connect(target) {
+ return target;
+ },
+ disconnect() {},
+ };
+ }
+
+ createAnalyser() {
+ return {
+ fftSize: 0,
+ frequencyBinCount: 32,
+ getByteTimeDomainData(array) {
+ array.fill(128);
+ },
+ };
+ }
+
+ createMediaStreamDestination() {
+ return { stream: processedStream };
+ }
+
+ createOscillator() {
+ return {
+ frequency: { value: 0 },
+ connect(target) {
+ return target;
+ },
+ start() {},
+ stop() {},
+ };
+ }
+
+ createGain() {
+ return {
+ gain: {
+ setValueAtTime() {},
+ exponentialRampToValueAtTime() {},
+ },
+ connect(target) {
+ return target;
+ },
+ };
+ }
+
+ close() {
+ return Promise.resolve();
+ }
+ }
+
+ // Mirrors the DTLN worklet protocol: the manager posts the wasm bytes and
+ // waits for "ready" before publishing the suppressed stream.
+ class FakeAudioWorkletNode {
+ port = {
+ onmessage: null,
+ postMessage: (data) => {
+ if (data?.type === "init") {
+ Promise.resolve().then(() =>
+ this.port.onmessage?.({ data: { type: "ready" } })
+ );
+ }
+ },
+ };
+
+ connect(target) {
+ return target;
+ }
+
+ disconnect() {}
+ }
+
+ // The gem-vendored asset base the loaders read at runtime.
+ Site.current().set("voice_assets_path", "/plugins/voice/javascripts/0.0.0");
+
+ const originalFetch = globalThis.fetch;
+ const fakeFetch = (url, options) => {
+ if (String(url).includes("/plugins/voice/javascripts/")) {
+ return Promise.resolve({
+ ok: true,
+ arrayBuffer: async () => new ArrayBuffer(8),
+ });
+ }
+ return originalFetch(url, options);
+ };
+
+ globalThis.AudioContext = FakeAudioContext;
+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;
+ globalThis.fetch = fakeFetch;
+ window.AudioContext = FakeAudioContext;
+ window.webkitAudioContext = FakeAudioContext;
+ window.requestAnimationFrame = () => 1;
+ window.cancelAnimationFrame = () => {};
+
+ navigator.mediaDevices ||= {};
+ navigator.mediaDevices.getUserMedia = async () => rawStream;
+
+ return {
+ restore() {
+ globalThis.AudioContext = originalAudioContext;
+ globalThis.AudioWorkletNode = originalAudioWorkletNode;
+ globalThis.fetch = originalFetch;
+ window.AudioContext = originalWindowAudioContext;
+ window.webkitAudioContext = originalWindowWebkitAudioContext;
+ window.requestAnimationFrame = originalRequestAnimationFrame;
+ window.cancelAnimationFrame = originalCancelAnimationFrame;
+
+ if (originalGetUserMedia) {
+ navigator.mediaDevices.getUserMedia = originalGetUserMedia;
+ } else {
+ delete navigator.mediaDevices.getUserMedia;
+ }
+ },
+ };
+}
+
+module("Voice | Unit | Service | voice-webrtc-livekit", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ setPeerTimingForTesting(SAFE_PEER_TIMING);
+ this.currentUser = logIn(this.owner);
+ this.currentUser.id = 10;
+ this.siteSettings = this.owner.lookup("service:site-settings");
+ this.siteSettings.voice_auto_status_enabled = true;
+ this.siteSettings.voice_video_enabled = true;
+ this.siteSettings.voice_video_max_publishers = 4;
+ localStorage.removeItem("voice:noise-suppression");
+ localStorage.removeItem("voice:noise-suppression-mode");
+
+ this.owner.unregister("service:voice-rooms");
+ this.owner.register("service:voice-rooms", VoiceRoomsStub);
+ this.owner.unregister("service:toasts");
+ this.owner.register("service:toasts", RecordingToastsStub);
+
+ this.rooms = this.owner.lookup("service:voice-rooms");
+ this.toasts = this.owner.lookup("service:toasts");
+ this.room = {
+ id: 1,
+ name: "Voice",
+ room_type: "open",
+ video_enabled: true,
+ membership: { role_name: "participant" },
+ active_participants: [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ],
+ };
+ this.rooms.seedRoom(this.room);
+
+ ({ sdk: this.sdk, FakeLivekitRoom: this.FakeLivekitRoom } = buildFakeSdk());
+ this.sdkLoads = 0;
+ setLivekitSdkLoaderForTesting(async () => {
+ this.sdkLoads++;
+ return this.sdk;
+ });
+ setLivekitReconnectDelaysForTesting([0, 0, 0]);
+
+ this.joinRequests = 0;
+ this.leaveRequests = 0;
+ pretender.post("/voice/rooms/1/join", () => {
+ this.joinRequests++;
+ return response({
+ transport: "livekit",
+ livekit: { url: "wss://sfu.example.com", token: "token-1" },
+ room: JSON.parse(JSON.stringify(this.room)),
+ });
+ });
+ pretender.post("/voice/rooms/1/toggle_mute", () => response({}));
+ pretender.post("/voice/rooms/1/signal", () => response({}));
+ this.stateRequests = [];
+ pretender.post("/voice/rooms/1/state", (request) => {
+ this.stateRequests.push(
+ Object.fromEntries(new URLSearchParams(request.requestBody))
+ );
+ return response({});
+ });
+ pretender.delete("/voice/rooms/1/leave", () => {
+ this.leaveRequests++;
+ return response({});
+ });
+
+ this.originalRTCPeerConnection = globalThis.RTCPeerConnection;
+ this.originalMediaStream = globalThis.MediaStream;
+ FakeRTCPeerConnection.created = 0;
+ globalThis.RTCPeerConnection = FakeRTCPeerConnection;
+ globalThis.MediaStream = class {
+ constructor(tracks = []) {
+ this.tracks = [...tracks];
+ }
+
+ getTracks() {
+ return [...this.tracks];
+ }
+
+ getAudioTracks() {
+ return this.tracks.filter((track) => track.kind === "audio");
+ }
+
+ getVideoTracks() {
+ return this.tracks.filter((track) => track.kind === "video");
+ }
+
+ addTrack(track) {
+ this.tracks.push(track);
+ }
+
+ removeTrack(track) {
+ this.tracks = this.tracks.filter((existing) => existing !== track);
+ }
+ };
+
+ const rawTrack = createFakeTrack("raw-track");
+ this.rawTrack = rawTrack;
+ this.rawStream = createFakeStream("raw-stream", rawTrack);
+ this.processedTrack = createFakeTrack("processed-track");
+ this.processedStream = createFakeStream(
+ "processed-stream",
+ this.processedTrack
+ );
+ this.audioEnvironment = installFakeAudioEnvironment({
+ rawStream: this.rawStream,
+ processedStream: this.processedStream,
+ });
+
+ // Video capture fakes on top of the audio environment: getUserMedia with
+ // video constraints returns the fake camera, getDisplayMedia the fake
+ // screen. audioEnvironment.restore() puts getUserMedia back.
+ this.cameraTrack = createFakeTrack("camera-track", "video");
+ this.cameraStream = createFakeMediaStream("camera-stream", [
+ this.cameraTrack,
+ ]);
+ this.screenVideoTrack = createFakeTrack("screen-video-track", "video");
+ this.screenAudioTrack = createFakeTrack("screen-audio-track", "audio");
+ this.screenStream = createFakeMediaStream("screen-stream", [
+ this.screenVideoTrack,
+ this.screenAudioTrack,
+ ]);
+ const audioGetUserMedia = navigator.mediaDevices.getUserMedia;
+ navigator.mediaDevices.getUserMedia = async (constraints) =>
+ constraints?.video ? this.cameraStream : audioGetUserMedia(constraints);
+ this.originalGetDisplayMedia = navigator.mediaDevices.getDisplayMedia;
+ navigator.mediaDevices.getDisplayMedia = async () => this.screenStream;
+
+ this.subject = this.owner.lookup("service:voice-webrtc");
+ });
+
+ hooks.afterEach(function () {
+ this.subject?.leave({ id: 1 }, { keepLocalStream: true });
+
+ setPeerTimingForTesting(null);
+ setLivekitSdkLoaderForTesting(null);
+ setLivekitReconnectDelaysForTesting(null);
+ localStorage.removeItem("voice:noise-suppression");
+ localStorage.removeItem("voice:noise-suppression-mode");
+ this.audioEnvironment.restore();
+ if (this.originalGetDisplayMedia) {
+ navigator.mediaDevices.getDisplayMedia = this.originalGetDisplayMedia;
+ } else {
+ delete navigator.mediaDevices.getDisplayMedia;
+ }
+ globalThis.RTCPeerConnection = this.originalRTCPeerConnection;
+ globalThis.MediaStream = this.originalMediaStream;
+ });
+
+ test("mesh rooms never load the LiveKit SDK", async function (assert) {
+ pretender.post("/voice/rooms/1/join", () =>
+ response({
+ transport: "mesh",
+ room: JSON.parse(JSON.stringify(this.room)),
+ })
+ );
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "connected",
+ "the mesh join completes normally"
+ );
+ assert.strictEqual(
+ this.sdkLoads,
+ 0,
+ "the SDK loader is never invoked for a mesh room"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 0,
+ "no LiveKit room object is ever constructed"
+ );
+ });
+
+ test("livekit join connects to the SFU and publishes the microphone", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(this.sdkLoads, 1, "loads the SDK once");
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "connected",
+ "the room reaches the connected state"
+ );
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ assert.deepEqual(
+ lkRoom.options,
+ { adaptiveStream: false, dynacast: true },
+ "constructs the room with adaptiveStream off and dynacast on"
+ );
+ assert.deepEqual(
+ lkRoom.connectCalls,
+ [{ url: "wss://sfu.example.com", token: "token-1" }],
+ "connects with the url and token from the join response"
+ );
+
+ const publication = lkRoom.localParticipant.published[0];
+ assert.strictEqual(
+ publication.track.mediaStreamTrack,
+ this.rawTrack,
+ "publishes the local microphone track"
+ );
+ assert.deepEqual(
+ publication.options,
+ { source: "microphone", dtx: true, red: true },
+ "publishes as a DTX+RED microphone source"
+ );
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "never creates mesh peer connections for a livekit room"
+ );
+ });
+
+ test("joining an active room does not create a second LiveKit session", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ await this.subject.join(this.room);
+
+ assert.strictEqual(
+ this.joinRequests,
+ 1,
+ "does not request a second room join"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "does not create a second media session with the same identity"
+ );
+ });
+
+ test("noise suppression toggle replaces the published audio track", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ await this.subject.setNoiseSuppressionMode("ai:dtln");
+
+ const publication =
+ this.FakeLivekitRoom.instances[0].localParticipant.published[0];
+ assert.deepEqual(
+ publication.track.replaceCalls,
+ [this.processedTrack],
+ "moves the live publication onto the processed track"
+ );
+ });
+
+ test("subscribed tracks land in the remote registry under numeric user ids", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ // Screen audio is watch-gated; the mic below is not.
+ this.subject.setWatching(1, true);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const micTrack = createFakeTrack("remote-mic-2");
+ lkRoom.emit(
+ "trackSubscribed",
+ { kind: "audio", mediaStreamTrack: micTrack, mediaStream: null },
+ { source: "microphone" },
+ { identity: "2" }
+ );
+ await wait(10);
+
+ const stream = this.subject.remoteStreamFor(1, 2);
+ assert.true(!!stream, "registers a stream keyed by the numeric user id");
+ assert.deepEqual(
+ stream.getTracks().map((track) => track.id),
+ ["remote-mic-2"],
+ "the stream carries the subscribed microphone track"
+ );
+
+ const screenAudioTrack = createFakeTrack("remote-screen-audio-2");
+ lkRoom.emit(
+ "trackSubscribed",
+ {
+ kind: "audio",
+ mediaStreamTrack: screenAudioTrack,
+ mediaStream: null,
+ },
+ { source: "screen_share_audio" },
+ { identity: "2" }
+ );
+ await wait(10);
+
+ assert.deepEqual(
+ this.subject.remoteScreenAudioStreams.map(
+ (screenStream) => screenStream.getTracks()[0].id
+ ),
+ ["remote-screen-audio-2"],
+ "a screen-share-audio source keeps the bare-track convention and lands in the screen audio registry"
+ );
+ assert.deepEqual(
+ this.subject
+ .remoteStreamFor(1, 2)
+ .getTracks()
+ .map((track) => track.id),
+ ["remote-mic-2"],
+ "screen audio never clobbers the participant's voice stream"
+ );
+ });
+
+ test("a participant expelled from the roster loses their media", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const subscribedCalls = [];
+ lkRoom.remoteParticipants.set("2", {
+ identity: "2",
+ trackPublications: new Map([
+ [
+ "mic-sid",
+ {
+ setSubscribed(value) {
+ subscribedCalls.push(value);
+ },
+ },
+ ],
+ ]),
+ });
+
+ lkRoom.emit(
+ "trackSubscribed",
+ {
+ kind: "audio",
+ mediaStreamTrack: createFakeTrack("remote-mic-2"),
+ mediaStream: null,
+ },
+ { source: "microphone" },
+ { identity: "2" }
+ );
+ await wait(10);
+
+ assert.true(!!this.subject.remoteStreamFor(1, 2), "media is registered");
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [{ id: this.currentUser.id, role: "participant" }],
+ });
+ await wait(20);
+
+ assert.strictEqual(
+ this.subject.remoteStreamFor(1, 2),
+ undefined,
+ "the registry entry is dropped when the roster no longer lists the user"
+ );
+ assert.deepEqual(
+ subscribedCalls,
+ [false],
+ "their SFU subscriptions are dropped too"
+ );
+ });
+
+ test("a duplicate-identity disconnect tears down locally without DELETE /leave", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ lkRoom.emit("disconnected", this.sdk.DisconnectReason.DUPLICATE_IDENTITY);
+ await wait(50);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "the local call state is torn down"
+ );
+ assert.strictEqual(
+ this.toasts.defaults.length,
+ 1,
+ "the user is told the call moved to another tab"
+ );
+
+ // The deferred room teardown runs 500ms after leave.
+ await wait(600);
+
+ assert.strictEqual(
+ this.leaveRequests,
+ 0,
+ "no DELETE /leave is issued — the presence/session now belongs to the newer tab"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "no reconnection is attempted"
+ );
+ });
+
+ test("a connect failure cleans up server presence and fails the join", async function (assert) {
+ this.FakeLivekitRoom.connectErrors.push(new Error("firewall"));
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "the join fails instead of leaving a half-joined room"
+ );
+ assert.strictEqual(
+ this.leaveRequests,
+ 1,
+ "tells the server we left so the roster doesn't carry a ghost"
+ );
+ assert.strictEqual(
+ this.toasts.errors.length,
+ 1,
+ "shows the unreachable-voice-server toast"
+ );
+ });
+
+ test("a terminal disconnect reconnects with a freshly minted token", async function (assert) {
+ let mintCalls = 0;
+ pretender.post("/voice/rooms/1/livekit_token", () => {
+ mintCalls++;
+ return response({ url: "wss://sfu.example.com", token: "token-2" });
+ });
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ lkRoom.emit("disconnected", this.sdk.DisconnectReason.SERVER_SHUTDOWN);
+ await waitUntil(() => this.FakeLivekitRoom.instances.length === 2);
+ await wait(20);
+
+ assert.strictEqual(mintCalls, 1, "mints one fresh token");
+
+ const reconnectedRoom = this.FakeLivekitRoom.instances[1];
+ assert.deepEqual(
+ reconnectedRoom.connectCalls,
+ [{ url: "wss://sfu.example.com", token: "token-2" }],
+ "reconnects with the newly minted token"
+ );
+ assert.strictEqual(
+ reconnectedRoom.localParticipant.published.length,
+ 1,
+ "republishes the microphone after reconnecting"
+ );
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "connected",
+ "the call stays up"
+ );
+ assert.strictEqual(this.leaveRequests, 0, "never leaves the room");
+ });
+
+ test("the reconnect ladder stops immediately on 410 Gone", async function (assert) {
+ let mintCalls = 0;
+ pretender.post("/voice/rooms/1/livekit_token", () => {
+ mintCalls++;
+ return response(410, { errors: ["room instance ended"] });
+ });
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ lkRoom.emit("disconnected", this.sdk.DisconnectReason.SERVER_SHUTDOWN);
+ await waitUntil(() => this.subject.connectionStateFor(1) === "idle");
+ await wait(20);
+
+ assert.strictEqual(
+ mintCalls,
+ 1,
+ "gives up after the first 410 instead of burning the remaining attempts"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "never constructs a new SFU connection"
+ );
+ assert.strictEqual(
+ this.leaveRequests,
+ 1,
+ "leaves cleanly so stale presence and session rows get closed"
+ );
+ assert.strictEqual(this.toasts.defaults.length, 1, "offers a rejoin toast");
+ });
+
+ test("an exhausted reconnect ladder leaves the room", async function (assert) {
+ let mintCalls = 0;
+ pretender.post("/voice/rooms/1/livekit_token", () => {
+ mintCalls++;
+ return response({ url: "wss://sfu.example.com", token: "token-2" });
+ });
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.FakeLivekitRoom.connectErrors.push(
+ new Error("down"),
+ new Error("down"),
+ new Error("down")
+ );
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ lkRoom.emit("disconnected", this.sdk.DisconnectReason.SERVER_SHUTDOWN);
+ await waitUntil(() => this.subject.connectionStateFor(1) === "idle", 1000);
+ await wait(20);
+
+ assert.strictEqual(mintCalls, 3, "retries three times with fresh tokens");
+ assert.strictEqual(
+ this.leaveRequests,
+ 1,
+ "leaves the room after exhausting the ladder"
+ );
+ assert.strictEqual(
+ this.toasts.errors.length,
+ 1,
+ "tells the user the connection could not be recovered"
+ );
+ });
+
+ test("toggleCamera publishes a simulcast camera track and broadcasts state", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ await this.subject.toggleCamera();
+ await wait(20);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const publication = lkRoom.localParticipant.published[1];
+ assert.strictEqual(
+ publication.track.mediaStreamTrack,
+ this.cameraTrack,
+ "publishes the camera track"
+ );
+ assert.deepEqual(
+ publication.options,
+ {
+ source: "camera",
+ simulcast: true,
+ videoEncoding: { maxBitrate: 1_200_000, maxFramerate: 24 },
+ },
+ "publishes with simulcast and the camera encoding preset"
+ );
+ assert.deepEqual(
+ this.stateRequests.at(-1),
+ { video: "true", screen: "false" },
+ "broadcasts the video state exactly like mesh does"
+ );
+
+ await this.subject.toggleCamera();
+ await wait(20);
+
+ assert.deepEqual(
+ lkRoom.localParticipant.unpublishCalls.map((call) => [
+ call.track.mediaStreamTrack.id,
+ call.stopOnUnpublish,
+ ]),
+ [["camera-track", false]],
+ "unpublishes the camera without stopping the service-owned track"
+ );
+ assert.strictEqual(
+ lkRoom.localParticipant.published.length,
+ 1,
+ "only the microphone remains published"
+ );
+ assert.deepEqual(
+ this.stateRequests.at(-1),
+ { video: "false", screen: "false" },
+ "broadcasts the stopped state"
+ );
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "video never creates mesh peer connections"
+ );
+ });
+
+ test("toggleScreenShare publishes the screen track and content audio", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ await this.subject.toggleScreenShare();
+ await wait(20);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const videoPublication = lkRoom.localParticipant.published[1];
+ assert.strictEqual(
+ videoPublication.track.mediaStreamTrack,
+ this.screenVideoTrack,
+ "publishes the screen video track"
+ );
+ assert.deepEqual(
+ videoPublication.options,
+ {
+ source: "screen_share",
+ simulcast: true,
+ screenShareEncoding: { maxBitrate: 2_500_000, maxFramerate: 15 },
+ },
+ "publishes with the screenshare encoding preset"
+ );
+
+ const audioPublication = lkRoom.localParticipant.published[2];
+ assert.strictEqual(
+ audioPublication.track.mediaStreamTrack,
+ this.screenAudioTrack,
+ "publishes the screen audio track"
+ );
+ assert.deepEqual(
+ audioPublication.options,
+ { source: "screen_share_audio", dtx: false, audioBitrate: 128_000 },
+ "publishes content audio without DTX and with the higher Opus ceiling"
+ );
+ assert.deepEqual(
+ this.stateRequests.at(-1),
+ { video: "false", screen: "true" },
+ "broadcasts the screen-sharing state"
+ );
+
+ await this.subject.toggleScreenShare();
+ await wait(20);
+
+ assert.strictEqual(
+ lkRoom.localParticipant.published.length,
+ 1,
+ "stopping the share unpublishes both screen tracks"
+ );
+ assert.deepEqual(
+ lkRoom.localParticipant.unpublishCalls.map(
+ (call) => call.stopOnUnpublish
+ ),
+ [false, false],
+ "the service keeps ownership of the capture tracks"
+ );
+ });
+
+ test("setWatching gates remote video subscriptions on the subscriber side", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const micPublication = createFakeRemotePublication("microphone", "audio");
+ const cameraPublication = createFakeRemotePublication("camera", "video");
+ const screenAudioPublication = createFakeRemotePublication(
+ "screen_share_audio",
+ "audio"
+ );
+ const publications = new Map([
+ ["mic-sid", micPublication],
+ ["camera-sid", cameraPublication],
+ ["screen-audio-sid", screenAudioPublication],
+ ]);
+ lkRoom.remoteParticipants.set("2", {
+ identity: "2",
+ trackPublications: publications,
+ });
+
+ this.subject.setWatching(1, true);
+
+ assert.deepEqual(
+ cameraPublication.subscribedCalls,
+ [true],
+ "watching subscribes the camera"
+ );
+ assert.deepEqual(
+ screenAudioPublication.subscribedCalls,
+ [true],
+ "watching subscribes screen audio"
+ );
+
+ this.subject.setWatching(1, false);
+
+ assert.deepEqual(
+ cameraPublication.subscribedCalls,
+ [true, false],
+ "leaving the page unsubscribes the camera"
+ );
+ assert.deepEqual(
+ screenAudioPublication.subscribedCalls,
+ [true, false],
+ "leaving the page unsubscribes screen audio"
+ );
+ assert.deepEqual(
+ micPublication.subscribedCalls,
+ [],
+ "microphone subscriptions are never gated"
+ );
+
+ const latePublication = createFakeRemotePublication("camera", "video");
+ publications.set("late-camera-sid", latePublication);
+ lkRoom.emit("trackPublished", latePublication, { identity: "2" });
+
+ assert.deepEqual(
+ latePublication.subscribedCalls,
+ [false],
+ "a camera published while not watching starts unsubscribed"
+ );
+
+ this.subject.setWatching(1, true);
+
+ assert.deepEqual(
+ latePublication.subscribedCalls,
+ [false, true],
+ "watching again picks the late publication up"
+ );
+ });
+
+ test("subscriptions pick simulcast layers from the publisher count", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.subject.setWatching(1, true);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ const cameraPublication = createFakeRemotePublication("camera", "video");
+ const screenPublication = createFakeRemotePublication(
+ "screen_share",
+ "video"
+ );
+ lkRoom.remoteParticipants.set("2", {
+ identity: "2",
+ trackPublications: new Map([
+ ["camera-sid", cameraPublication],
+ ["screen-sid", screenPublication],
+ ]),
+ });
+
+ lkRoom.emit(
+ "trackSubscribed",
+ {
+ kind: "video",
+ mediaStreamTrack: createFakeTrack("remote-camera-2", "video"),
+ mediaStream: null,
+ },
+ cameraPublication,
+ { identity: "2" }
+ );
+ lkRoom.emit(
+ "trackSubscribed",
+ {
+ kind: "video",
+ mediaStreamTrack: createFakeTrack("remote-screen-2", "video"),
+ mediaStream: null,
+ },
+ screenPublication,
+ { identity: "2" }
+ );
+ await wait(10);
+
+ assert.deepEqual(
+ cameraPublication.qualityCalls,
+ [1],
+ "cameras subscribe at the MEDIUM layer in small rooms"
+ );
+ assert.deepEqual(
+ screenPublication.qualityCalls,
+ [2],
+ "screenshares subscribe at the HIGH layer"
+ );
+
+ const participants = [{ id: this.currentUser.id, role: "participant" }];
+ for (let id = 2; id <= 8; id++) {
+ participants.push({ id, role: "participant", is_video_on: true });
+ }
+ this.rooms.emit(1, { type: "participants", participants });
+ await wait(20);
+
+ assert.strictEqual(
+ cameraPublication.qualityCalls.at(-1),
+ 0,
+ "more than six publishers drops cameras to the LOW layer"
+ );
+ assert.strictEqual(
+ screenPublication.qualityCalls.at(-1),
+ 2,
+ "screenshares stay on the HIGH layer regardless of room size"
+ );
+ });
+
+ test("a stage promotion publishes the microphone without reconnecting", async function (assert) {
+ this.room.room_type = "stage";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "listener" },
+ { id: 2, role: "moderator" },
+ ];
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ assert.strictEqual(
+ lkRoom.localParticipant.published.length,
+ 0,
+ "a stage listener publishes nothing"
+ );
+
+ this.rooms.emit(1, {
+ type: "role_change",
+ user_id: this.currentUser.id,
+ role: "speaker",
+ });
+ await waitUntil(() => lkRoom.localParticipant.published.length === 1);
+
+ const publication = lkRoom.localParticipant.published[0];
+ assert.strictEqual(
+ publication.track.mediaStreamTrack,
+ this.rawTrack,
+ "publishes the freshly acquired microphone"
+ );
+ assert.deepEqual(
+ publication.options,
+ { source: "microphone", dtx: true, red: true },
+ "publishes it as a regular microphone source"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "the promotion never reconnects the media session"
+ );
+ });
+
+ test("a stage demotion releases the microphone publication", async function (assert) {
+ this.room.room_type = "stage";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "moderator" },
+ ];
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ assert.strictEqual(
+ lkRoom.localParticipant.published.length,
+ 1,
+ "a speaker starts out publishing the microphone"
+ );
+
+ this.rooms.emit(1, {
+ type: "role_change",
+ user_id: this.currentUser.id,
+ role: "listener",
+ });
+ await waitUntil(() => lkRoom.localParticipant.published.length === 0);
+
+ assert.deepEqual(
+ lkRoom.localParticipant.unpublishCalls.map(
+ (call) => call.stopOnUnpublish
+ ),
+ [false],
+ "the microphone is unpublished without the SDK stopping the track"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "the demotion never reconnects the media session"
+ );
+ });
+
+ test("a stage demotion stops a live camera along with the microphone", async function (assert) {
+ this.room.room_type = "stage";
+ this.room.video_enabled = true;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "moderator" },
+ ];
+
+ await this.subject.join(this.room);
+ await wait(50);
+ await this.subject.toggleCamera();
+ await wait(20);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ assert.deepEqual(
+ lkRoom.localParticipant.published.map(
+ (publication) => publication.source
+ ),
+ ["microphone", "camera"],
+ "a publishing speaker holds both the microphone and camera publications"
+ );
+
+ this.rooms.emit(1, {
+ type: "role_change",
+ user_id: this.currentUser.id,
+ role: "participant",
+ });
+ await waitUntil(() => lkRoom.localParticipant.published.length === 0);
+
+ assert.false(
+ lkRoom.localParticipant.published.some(
+ (publication) => publication.source === "camera"
+ ),
+ "the camera publication is unpublished on demotion"
+ );
+ assert.strictEqual(
+ this.subject.localVideoKind,
+ null,
+ "the local video capture is fully stopped"
+ );
+ assert.strictEqual(
+ this.FakeLivekitRoom.instances.length,
+ 1,
+ "the demotion never reconnects the media session"
+ );
+ });
+
+ test("a ladder reconnect republishes the live camera", async function (assert) {
+ pretender.post("/voice/rooms/1/livekit_token", () =>
+ response({ url: "wss://sfu.example.com", token: "token-2" })
+ );
+
+ await this.subject.join(this.room);
+ await wait(50);
+ await this.subject.toggleCamera();
+ await wait(20);
+
+ const lkRoom = this.FakeLivekitRoom.instances[0];
+ lkRoom.emit("disconnected", this.sdk.DisconnectReason.SERVER_SHUTDOWN);
+ await waitUntil(() => this.FakeLivekitRoom.instances.length === 2);
+ await wait(20);
+
+ const reconnectedRoom = this.FakeLivekitRoom.instances[1];
+ assert.deepEqual(
+ reconnectedRoom.localParticipant.published.map(
+ (publication) => publication.source
+ ),
+ ["microphone", "camera"],
+ "the new connection carries both the microphone and the camera"
+ );
+ assert.strictEqual(
+ reconnectedRoom.localParticipant.published[1].track.mediaStreamTrack,
+ this.cameraTrack,
+ "the same capture track is republished"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/services/voice-webrtc-test.js b/plugins/voice/test/javascripts/unit/services/voice-webrtc-test.js
new file mode 100644
index 00000000000..5ce24361f13
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/services/voice-webrtc-test.js
@@ -0,0 +1,2548 @@
+import Service from "@ember/service";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import Site from "discourse/models/site";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { logIn } from "discourse/tests/helpers/qunit-helpers";
+import { setPeerTimingForTesting } from "discourse/plugins/voice/discourse/lib/voice/peer-manager";
+
+// Park the service's wall-clock timers far outside any test's window so a
+// CPU-starved run can't have a fallback offer, peer restart, or stuck-"new"
+// rescue fire mid-test (QUnit shuffles test order every run, so an unexpected
+// firing poisons whichever test happens to be running). Tests that exercise
+// one of these timers override just that delay with something small enough to
+// await deterministically.
+const SAFE_PEER_TIMING = {
+ offerRetryBaseDelayMs: 60_000,
+ maxOfferRetryDelayMs: 60_000,
+ restartImmediateDelayMs: 60_000,
+ restartDisconnectedDelayMs: 60_000,
+ maxRestartDelayMs: 60_000,
+ connectionTimeoutMs: 60_000,
+};
+
+class VoiceRoomsStub extends Service {
+ #roomHandlers = new Map();
+ #roomsById = new Map();
+
+ seedRoom(room) {
+ this.#roomsById.set(room.id, room);
+ }
+
+ roomById(id) {
+ return this.#roomsById.get(id);
+ }
+
+ registerRoomHandler(roomId, callback) {
+ let callbacks = this.#roomHandlers.get(roomId);
+
+ if (!callbacks) {
+ callbacks = new Set();
+ this.#roomHandlers.set(roomId, callbacks);
+ }
+
+ callbacks.add(callback);
+ }
+
+ unregisterRoomHandler(roomId, callback) {
+ const callbacks = this.#roomHandlers.get(roomId);
+ if (!callbacks) {
+ return;
+ }
+
+ callbacks.delete(callback);
+ if (!callbacks.size) {
+ this.#roomHandlers.delete(roomId);
+ }
+ }
+
+ emit(roomId, payload) {
+ const room = this.#roomsById.get(roomId);
+
+ if (payload.type === "participants" && room) {
+ room.active_participants = payload.participants;
+ }
+
+ this.#roomHandlers.get(roomId)?.forEach((callback) => callback(payload));
+ }
+
+ addParticipant(roomId, participant) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ const existing = room.active_participants || [];
+ if (existing.some((entry) => Number(entry.id) === Number(participant.id))) {
+ return;
+ }
+
+ room.active_participants = [...existing, participant];
+ }
+
+ removeParticipant(roomId, userId) {
+ const room = this.#roomsById.get(roomId);
+ if (!room) {
+ return;
+ }
+
+ room.active_participants = (room.active_participants || []).filter(
+ (participant) => Number(participant.id) !== Number(userId)
+ );
+ }
+
+ setParticipantMuted() {}
+ setParticipantDeafened() {}
+ setParticipantSpeaking() {}
+ setParticipantIdleState() {}
+ setParticipantVideoState() {}
+}
+
+class ToastsStub extends Service {
+ error() {}
+ success() {}
+ default() {}
+}
+
+class FakeRTCPeerConnection {
+ static created = 0;
+ static instances = [];
+
+ signalingState = "stable";
+ connectionState = "new";
+ iceConnectionState = "new";
+ iceGatheringState = "new";
+ localDescription = null;
+ remoteDescription = null;
+ senders = [];
+ transceivers = [];
+
+ addedCandidates = [];
+
+ constructor() {
+ FakeRTCPeerConnection.created++;
+ FakeRTCPeerConnection.instances.push(this);
+ }
+
+ addTrack(track) {
+ const sender = {
+ track,
+ replaceCalls: [],
+ async replaceTrack(newTrack) {
+ this.track = newTrack;
+ this.replaceCalls.push(newTrack);
+ },
+ };
+
+ this.senders.push(sender);
+ return sender;
+ }
+
+ addTransceiver(kind, options) {
+ const receiverTrack = {
+ id: `${kind}-receiver-${this.transceivers.length + 1}`,
+ kind,
+ };
+ const sender = {
+ track: null,
+ replaceCalls: [],
+ async replaceTrack(newTrack) {
+ this.track = newTrack;
+ this.replaceCalls.push(newTrack);
+ },
+ getParameters() {
+ return { encodings: [{}] };
+ },
+ async setParameters() {},
+ };
+
+ const transceiver = {
+ direction: options?.direction ?? "sendrecv",
+ sender,
+ receiver: { track: receiverTrack },
+ };
+
+ this.transceivers.push(transceiver);
+ this.senders.push(sender);
+ return transceiver;
+ }
+
+ getTransceivers() {
+ return this.transceivers;
+ }
+
+ getSenders() {
+ return this.senders;
+ }
+
+ async createOffer() {
+ return { type: "offer", sdp: "fake-offer" };
+ }
+
+ async createAnswer() {
+ return { type: "answer", sdp: "fake-answer" };
+ }
+
+ async setLocalDescription(description) {
+ this.localDescription = description;
+
+ if (description?.type === "offer") {
+ this.signalingState = "have-local-offer";
+ } else if (
+ description?.type === "answer" ||
+ description?.type === "rollback"
+ ) {
+ this.signalingState = "stable";
+ }
+ }
+
+ async setRemoteDescription(description) {
+ this.remoteDescription = description;
+
+ if (description?.type === "offer") {
+ this.signalingState = "have-remote-offer";
+ } else if (description?.type === "answer") {
+ this.signalingState = "stable";
+ }
+ }
+
+ async addIceCandidate(candidate) {
+ this.addedCandidates.push(candidate);
+ }
+
+ close() {
+ this.connectionState = "closed";
+ }
+}
+
+function wait(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function waitUntil(callback, timeout = 500) {
+ const startedAt = Date.now();
+
+ while (!callback()) {
+ if (Date.now() - startedAt > timeout) {
+ throw new Error("Timed out waiting for condition");
+ }
+ await wait(10);
+ }
+}
+
+function signalPayloadFrom(request) {
+ const params = new URLSearchParams(request.requestBody);
+
+ return {
+ recipientId: Number(params.get("payload[recipient_id]")),
+ type: params.get("payload[type]"),
+ sdp: params.get("payload[sdp]"),
+ };
+}
+
+// Flattens a signal POST into individual { recipientId, type, sdp } entries,
+// tolerating the three payload shapes the signaling layer emits: a single
+// event, a single recipient with multiple coalesced events, and multiple
+// recipients. Use when signals to the same peer may land in one HTTP batch.
+function signalsFrom(request) {
+ const params = new URLSearchParams(request.requestBody);
+ const get = (key) => params.get(key);
+
+ if (get("payload[messages][0][recipient_id]")) {
+ const signals = [];
+ for (let m = 0; get(`payload[messages][${m}][recipient_id]`); m++) {
+ const recipientId = Number(get(`payload[messages][${m}][recipient_id]`));
+ for (let e = 0; get(`payload[messages][${m}][events][${e}][type]`); e++) {
+ signals.push({
+ recipientId,
+ type: get(`payload[messages][${m}][events][${e}][type]`),
+ sdp: get(`payload[messages][${m}][events][${e}][sdp]`),
+ });
+ }
+ }
+ return signals;
+ }
+
+ const recipientId = Number(get("payload[recipient_id]"));
+
+ if (get("payload[events][0][type]")) {
+ const signals = [];
+ for (let e = 0; get(`payload[events][${e}][type]`); e++) {
+ signals.push({
+ recipientId,
+ type: get(`payload[events][${e}][type]`),
+ sdp: get(`payload[events][${e}][sdp]`),
+ });
+ }
+ return signals;
+ }
+
+ return [
+ { recipientId, type: get("payload[type]"), sdp: get("payload[sdp]") },
+ ];
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+
+ return { promise, resolve, reject };
+}
+
+function createFakeTrack(id, kind = "audio") {
+ return {
+ id,
+ kind,
+ enabled: true,
+ stop() {},
+ };
+}
+
+function createFakeStream(id, track) {
+ return {
+ id,
+ getTracks() {
+ return [track];
+ },
+ getAudioTracks() {
+ return [track];
+ },
+ };
+}
+
+function installFakeAudioEnvironment({ rawStream, processedStream }) {
+ const sourceStreams = [];
+ const originalAudioContext = globalThis.AudioContext;
+ const originalAudioWorkletNode = globalThis.AudioWorkletNode;
+ const originalRequestAnimationFrame = window.requestAnimationFrame;
+ const originalCancelAnimationFrame = window.cancelAnimationFrame;
+ const originalWindowAudioContext = window.AudioContext;
+ const originalWindowWebkitAudioContext = window.webkitAudioContext;
+ const originalGetUserMedia = navigator.mediaDevices?.getUserMedia;
+
+ class FakeAudioContext {
+ currentTime = 0;
+ state = "running";
+ destination = {};
+ audioWorklet = {
+ addModule: async () => {},
+ };
+
+ resume() {
+ this.state = "running";
+ return Promise.resolve();
+ }
+
+ createMediaStreamSource(stream) {
+ sourceStreams.push(stream);
+
+ return {
+ connect(target) {
+ return target;
+ },
+ disconnect() {},
+ };
+ }
+
+ createAnalyser() {
+ return {
+ fftSize: 0,
+ frequencyBinCount: 32,
+ getByteTimeDomainData(array) {
+ array.fill(128);
+ },
+ };
+ }
+
+ createMediaStreamDestination() {
+ return { stream: processedStream };
+ }
+
+ createOscillator() {
+ return {
+ frequency: { value: 0 },
+ connect(target) {
+ return target;
+ },
+ start() {},
+ stop() {},
+ };
+ }
+
+ createGain() {
+ return {
+ gain: {
+ setValueAtTime() {},
+ exponentialRampToValueAtTime() {},
+ },
+ connect(target) {
+ return target;
+ },
+ };
+ }
+
+ close() {
+ return Promise.resolve();
+ }
+ }
+
+ // Mirrors the DTLN worklet protocol: the manager posts the wasm bytes and
+ // waits for "ready" before publishing the suppressed stream.
+ class FakeAudioWorkletNode {
+ port = {
+ onmessage: null,
+ postMessage: (data) => {
+ if (data?.type === "init") {
+ Promise.resolve().then(() =>
+ this.port.onmessage?.({ data: { type: "ready" } })
+ );
+ }
+ },
+ };
+
+ connect(target) {
+ return target;
+ }
+
+ disconnect() {}
+ }
+
+ // The gem-vendored asset base the loaders read at runtime.
+ Site.current().set("voice_assets_path", "/plugins/voice/javascripts/0.0.0");
+ const originalFetch = globalThis.fetch;
+ const fakeFetch = (url, options) => {
+ if (String(url).includes("/plugins/voice/javascripts/")) {
+ return Promise.resolve({
+ ok: true,
+ arrayBuffer: async () => new ArrayBuffer(8),
+ });
+ }
+ return originalFetch(url, options);
+ };
+
+ globalThis.AudioContext = FakeAudioContext;
+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;
+ globalThis.fetch = fakeFetch;
+ window.AudioContext = FakeAudioContext;
+ window.webkitAudioContext = FakeAudioContext;
+ window.requestAnimationFrame = () => 1;
+ window.cancelAnimationFrame = () => {};
+
+ navigator.mediaDevices ||= {};
+ navigator.mediaDevices.getUserMedia = async () => rawStream;
+
+ return {
+ sourceStreams,
+ restore() {
+ globalThis.AudioContext = originalAudioContext;
+ globalThis.AudioWorkletNode = originalAudioWorkletNode;
+ globalThis.fetch = originalFetch;
+ window.AudioContext = originalWindowAudioContext;
+ window.webkitAudioContext = originalWindowWebkitAudioContext;
+ window.requestAnimationFrame = originalRequestAnimationFrame;
+ window.cancelAnimationFrame = originalCancelAnimationFrame;
+
+ if (originalGetUserMedia) {
+ navigator.mediaDevices.getUserMedia = originalGetUserMedia;
+ } else {
+ delete navigator.mediaDevices.getUserMedia;
+ }
+ },
+ };
+}
+
+module("Voice | Unit | Service | voice-webrtc", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ setPeerTimingForTesting(SAFE_PEER_TIMING);
+ this.currentUser = logIn(this.owner);
+ this.siteSettings = this.owner.lookup("service:site-settings");
+ this.siteSettings.voice_auto_status_enabled = true;
+ localStorage.removeItem("voice:noise-suppression");
+ localStorage.removeItem("voice:noise-suppression-mode");
+
+ this.owner.unregister("service:voice-rooms");
+ this.owner.register("service:voice-rooms", VoiceRoomsStub);
+ this.owner.unregister("service:toasts");
+ this.owner.register("service:toasts", ToastsStub);
+
+ this.rooms = this.owner.lookup("service:voice-rooms");
+ this.room = {
+ id: 1,
+ name: "Stage",
+ room_type: "stage",
+ membership: { role_name: "listener" },
+ active_participants: [
+ { id: this.currentUser.id, role: "listener" },
+ { id: 2, role: "speaker" },
+ ],
+ };
+ this.rooms.seedRoom(this.room);
+
+ pretender.post("/voice/rooms/1/join", () =>
+ response({
+ participant_session_id: "session-abc",
+ room: JSON.parse(JSON.stringify(this.room)),
+ })
+ );
+ pretender.post("/voice/rooms/1/signal", () => response({}));
+ pretender.post("/voice/rooms/1/toggle_mute", () => response({}));
+ pretender.delete("/voice/rooms/1/leave", () => response({}));
+
+ this.originalRTCPeerConnection = globalThis.RTCPeerConnection;
+ this.originalRTCIceCandidate = globalThis.RTCIceCandidate;
+ this.originalRTCSessionDescription = globalThis.RTCSessionDescription;
+ this.originalMediaStream = globalThis.MediaStream;
+
+ FakeRTCPeerConnection.created = 0;
+ FakeRTCPeerConnection.instances = [];
+ globalThis.RTCPeerConnection = FakeRTCPeerConnection;
+ globalThis.MediaStream = class {
+ static counter = 0;
+
+ constructor(tracks = []) {
+ this.id = `fake-media-stream-${++globalThis.MediaStream.counter}`;
+ this.tracks = [...tracks];
+ }
+
+ getTracks() {
+ return [...this.tracks];
+ }
+
+ getAudioTracks() {
+ return this.tracks.filter((track) => track.kind === "audio");
+ }
+
+ getVideoTracks() {
+ return this.tracks.filter((track) => track.kind === "video");
+ }
+
+ addTrack(track) {
+ this.tracks.push(track);
+ }
+
+ removeTrack(track) {
+ this.tracks = this.tracks.filter((existing) => existing !== track);
+ }
+ };
+ globalThis.RTCIceCandidate = class {
+ constructor(candidate) {
+ Object.assign(this, candidate);
+ }
+ };
+ globalThis.RTCSessionDescription = class {
+ constructor(description) {
+ Object.assign(this, description);
+ }
+ };
+
+ this.subject = this.owner.lookup("service:voice-webrtc");
+ });
+
+ hooks.afterEach(function () {
+ this.subject?.leave({ id: 1 }, { keepLocalStream: true });
+
+ setPeerTimingForTesting(null);
+ globalThis.RTCPeerConnection = this.originalRTCPeerConnection;
+ globalThis.RTCIceCandidate = this.originalRTCIceCandidate;
+ globalThis.RTCSessionDescription = this.originalRTCSessionDescription;
+ globalThis.MediaStream = this.originalMediaStream;
+ });
+
+ test("ICE configuration defaults to no servers and policy 'all' before any join", function (assert) {
+ assert.deepEqual(this.subject.iceServers, []);
+ assert.strictEqual(this.subject.iceTransportPolicy, "all");
+ });
+
+ test("ICE configuration comes from the join response", async function (assert) {
+ const servers = [
+ { urls: "stun:stun.example.com:3478" },
+ {
+ urls: "turn:turn.example.com:3478",
+ username: "1750000000:1",
+ credential: "hmac-credential",
+ },
+ ];
+
+ pretender.post("/voice/rooms/1/join", () =>
+ response({
+ room: JSON.parse(JSON.stringify(this.room)),
+ ice: { servers, transport_policy: "relay" },
+ })
+ );
+
+ await this.subject.join(this.room);
+
+ assert.deepEqual(this.subject.iceServers, servers);
+ assert.strictEqual(this.subject.iceTransportPolicy, "relay");
+ });
+
+ test("ICE configuration survives a join response without an ice payload", async function (assert) {
+ const servers = [{ urls: "stun:stun.example.com:3478" }];
+
+ pretender.post("/voice/rooms/1/join", () =>
+ response({
+ room: JSON.parse(JSON.stringify(this.room)),
+ ice: { servers, transport_policy: "all" },
+ })
+ );
+
+ await this.subject.join(this.room);
+ this.subject.leave(this.room, { keepLocalStream: true });
+
+ pretender.post("/voice/rooms/1/join", () =>
+ response({ room: JSON.parse(JSON.stringify(this.room)) })
+ );
+
+ await this.subject.join(this.room);
+
+ assert.deepEqual(this.subject.iceServers, servers);
+ assert.strictEqual(this.subject.iceTransportPolicy, "all");
+ });
+
+ test("ignores stale signals after a participant has left the room", async function (assert) {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "creates the initial peer for the active speaker"
+ );
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [{ id: this.currentUser.id, role: "listener" }],
+ });
+ await wait(10);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:1 1 UDP 2122252543 127.0.0.1 3478 typ host",
+ sdpMid: "0",
+ sdpMLineIndex: 0,
+ },
+ },
+ });
+ await wait(10);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "does not recreate a peer from a delayed signal after the participant left"
+ );
+ });
+
+ test("leave cancels a pending join before the late response can activate the room", async function (assert) {
+ assert.timeout(2000);
+
+ const joinResponse = deferred();
+
+ pretender.post("/voice/rooms/1/join", () =>
+ joinResponse.promise.then(() =>
+ response({
+ room: JSON.parse(JSON.stringify(this.room)),
+ })
+ )
+ );
+
+ const join = this.subject.join(this.room);
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "connecting",
+ "marks the room as connecting while the join is pending"
+ );
+
+ this.subject.leave({ id: 1 }, { keepLocalStream: true });
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "returns to idle immediately after leaving"
+ );
+
+ joinResponse.resolve();
+ await join;
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "keeps the room idle after the late join response arrives"
+ );
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "does not create peers for a canceled join"
+ );
+ });
+
+ test("join uses the latest participant list when more users join during connect", async function (assert) {
+ assert.timeout(2000);
+
+ const joinResponse = deferred();
+ const staleRoom = {
+ ...this.room,
+ active_participants: [{ id: this.currentUser.id, role: "listener" }],
+ };
+
+ pretender.post("/voice/rooms/1/join", () =>
+ joinResponse.promise.then(() =>
+ response({
+ room: JSON.parse(JSON.stringify(staleRoom)),
+ })
+ )
+ );
+
+ const join = this.subject.join(this.room);
+ await wait(10);
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [
+ { id: this.currentUser.id, role: "listener" },
+ { id: 2, role: "speaker" },
+ { id: 30, role: "speaker" },
+ ],
+ });
+
+ joinResponse.resolve();
+ await join;
+ await wait(10);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 2,
+ "creates peers for participants that joined while the room was still connecting"
+ );
+ });
+
+ test("join still uses the join response when no newer participant broadcast arrived", async function (assert) {
+ const responseRoom = {
+ ...this.room,
+ active_participants: [
+ { id: this.currentUser.id, role: "listener" },
+ { id: 2, role: "speaker" },
+ { id: 30, role: "speaker" },
+ ],
+ };
+
+ pretender.post("/voice/rooms/1/join", () =>
+ response({
+ room: JSON.parse(JSON.stringify(responseRoom)),
+ })
+ );
+
+ await this.subject.join(this.room);
+ await wait(10);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 2,
+ "creates peers for participants only present in the fresher join response"
+ );
+ });
+
+ test("kicked while connecting cancels the pending join", async function (assert) {
+ assert.timeout(2000);
+
+ const joinResponse = deferred();
+
+ pretender.post("/voice/rooms/1/join", () =>
+ joinResponse.promise.then(() =>
+ response({
+ room: JSON.parse(JSON.stringify(this.room)),
+ })
+ )
+ );
+
+ const join = this.subject.join(this.room);
+ await wait(10);
+
+ this.rooms.emit(1, { type: "kicked" });
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "drops back to idle immediately after the kick"
+ );
+
+ joinResponse.resolve();
+ await join;
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.connectionStateFor(1),
+ "idle",
+ "stays idle after the late join response arrives"
+ );
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "does not create peers after a connect-time kick"
+ );
+ });
+
+ test("join replays queued connect-time signals for existing peers", async function (assert) {
+ assert.timeout(2000);
+
+ const joinResponse = deferred();
+ let signalRequests = 0;
+
+ pretender.post("/voice/rooms/1/join", () =>
+ joinResponse.promise.then(() =>
+ response({
+ room: JSON.parse(JSON.stringify(this.room)),
+ })
+ )
+ );
+ pretender.post("/voice/rooms/1/signal", () => {
+ signalRequests++;
+ return response({});
+ });
+
+ const join = this.subject.join(this.room);
+ await wait(10);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "queued-offer" },
+ });
+
+ joinResponse.resolve();
+ await join;
+ // Wait past the signaling HTTP batch window (200ms); the offer fallback
+ // retry is parked far out by SAFE_PEER_TIMING, so a single request proves
+ // the answer was sent via the immediate replay rather than the fallback.
+ await wait(300);
+
+ assert.strictEqual(
+ signalRequests,
+ 1,
+ "sends an answer immediately after join instead of waiting for the fallback retry"
+ );
+ });
+
+ test("join offers deterministically based on user id to avoid glare", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+
+ // Current user id is higher than the existing peer's, so it must NOT
+ // offer immediately (that is what caused glare); the lower-id peer owns
+ // the immediate offer. A short fallback offer fires only if the peer
+ // never offers — shrink its delay so the test can await it.
+ setPeerTimingForTesting({ ...SAFE_PEER_TIMING, offerRetryBaseDelayMs: 50 });
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ signalRequests.length,
+ 0,
+ "does not send an immediate offer when the current user id is higher than the peer id"
+ );
+
+ await waitUntil(() => signalRequests.length === 1, 1500);
+
+ assert.deepEqual(
+ signalRequests[0],
+ { recipientId: 2, type: "offer", sdp: "fake-offer" },
+ "sends a fallback offer to the lower-id peer after the short retry delay"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("simultaneous join offers resolve glare by rolling back the lower user id side", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+
+ this.currentUser.id = 2;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 50, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await waitUntil(() => signalRequests.length === 1);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 50,
+ data: { type: "offer", sdp: "simultaneous-offer" },
+ });
+ await waitUntil(() => signalRequests.length === 2);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ assert.deepEqual(
+ signalRequests[0],
+ { recipientId: 50, type: "offer", sdp: "fake-offer" },
+ "sends the initial offer before receiving the competing offer"
+ );
+ assert.deepEqual(
+ signalRequests[1],
+ { recipientId: 50, type: "answer", sdp: "fake-answer" },
+ "answers the competing offer after rollback"
+ );
+ assert.strictEqual(
+ pc.remoteDescription.sdp,
+ "simultaneous-offer",
+ "accepts the competing offer after rolling back local offer"
+ );
+ assert.strictEqual(
+ pc.localDescription.type,
+ "answer",
+ "finishes glare resolution with an answer"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("higher-id peer joining a populated room connects to the lower-id peer without glare", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+
+ // The reported regression: a new participant whose id is higher than an
+ // already-connected peer's joins the room. With the deterministic
+ // offerer the joiner does not offer; it answers the lower-id peer and
+ // ends up connected with that peer's audio, without waiting for the 30s
+ // connection timeout.
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ signalRequests.length,
+ 0,
+ "does not send a competing offer that would collide with the peer's"
+ );
+
+ const pc = FakeRTCPeerConnection.instances[0];
+
+ // The lower-id peer owns the immediate offer.
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "peer-offer" },
+ });
+ await waitUntil(() => signalRequests.length === 1, 1500);
+
+ assert.deepEqual(
+ signalRequests[0],
+ { recipientId: 2, type: "answer", sdp: "fake-answer" },
+ "answers the lower-id peer's offer instead of racing it with its own"
+ );
+ assert.strictEqual(
+ pc.signalingState,
+ "stable",
+ "negotiation completes without leaving a dangling local offer"
+ );
+
+ // The peer's audio track arrives and is exposed to the room.
+ const remoteTrack = createFakeTrack("peer-2-track");
+ const remoteStream = createFakeStream("peer-2-stream", remoteTrack);
+ pc.ontrack({ streams: [remoteStream], track: remoteTrack });
+ await wait(10);
+
+ assert.true(
+ this.subject
+ .remoteStreamsFor(1)
+ .some((stream) =>
+ stream.getTracks().some((track) => track.id === "peer-2-track")
+ ),
+ "exposes the peer's audio stream after negotiation completes"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("processes a batched signal envelope's events in order", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ // One envelope per recipient: the offer plus its trickle candidate ride
+ // in a single ordered event batch.
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ events: [
+ { type: "offer", sdp: "peer-offer" },
+ {
+ type: "candidate",
+ candidate: {
+ candidate: "candidate:1 1 UDP 2122252543 127.0.0.1 3478 typ host",
+ sdpMid: "0",
+ },
+ },
+ ],
+ });
+ await waitUntil(() => signalRequests.length === 1, 1500);
+
+ assert.deepEqual(
+ signalRequests[0],
+ { recipientId: 2, type: "answer", sdp: "fake-answer" },
+ "answers the offer delivered in a batched envelope"
+ );
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ await waitUntil(() => pc.addedCandidates.length === 1, 1500);
+ assert.strictEqual(
+ pc.addedCandidates[0].candidate,
+ "candidate:1 1 UDP 2122252543 127.0.0.1 3478 typ host",
+ "applies the candidate after the offer it followed in the batch"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ // Answers the remote offer over the first (and only) peer connection and
+ // returns that connection once negotiation settled.
+ async function answerRemoteOffer(context, senderId) {
+ context.rooms.emit(1, {
+ type: "signal",
+ sender_id: senderId,
+ data: { type: "offer", sdp: `peer-${senderId}-offer` },
+ });
+ await waitUntil(() => FakeRTCPeerConnection.instances.length >= 1, 1500);
+ const pc = FakeRTCPeerConnection.instances[0];
+ await waitUntil(
+ () => pc.remoteDescription && pc.signalingState === "stable",
+ 1500
+ );
+ return pc;
+ }
+
+ test("drops a microphone track published by a stage listener", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ // A speaker keeps a connection to every listener so they can receive the
+ // stage — the exact connection a modified listener client can abuse to
+ // attach a microphone track the server would never let it unmute.
+ this.room.membership = { role_name: "speaker" };
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "listener" },
+ ];
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const pc = await answerRemoteOffer(this, 2);
+
+ let stopped = false;
+ const remoteTrack = createFakeTrack("listener-mic");
+ remoteTrack.stop = () => (stopped = true);
+ pc.ontrack({
+ streams: [createFakeStream("listener-stream", remoteTrack)],
+ track: remoteTrack,
+ });
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.remoteStreamsFor(1).length,
+ 0,
+ "audio from a role that cannot publish is never registered or played"
+ );
+ assert.true(stopped, "the disallowed track is stopped");
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("plays a stage speaker's microphone and keeps a listener's transceivers receive-only", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ // The default room: current user is a listener, user 2 is a speaker.
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const pc = await answerRemoteOffer(this, 2);
+
+ assert.true(
+ pc.transceivers.every(
+ (transceiver) => transceiver.direction === "recvonly"
+ ),
+ "a listener's pre-negotiated transceivers never advertise sending"
+ );
+
+ const remoteTrack = createFakeTrack("speaker-mic");
+ pc.ontrack({
+ streams: [createFakeStream("speaker-stream", remoteTrack)],
+ track: remoteTrack,
+ });
+ await wait(10);
+
+ assert.true(
+ this.subject
+ .remoteStreamsFor(1)
+ .some((stream) =>
+ stream.getTracks().some((track) => track.id === "speaker-mic")
+ ),
+ "audio from a role allowed to publish plays normally"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("drops a video track when the room does not allow video", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.video_allowed = false;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const pc = await answerRemoteOffer(this, 2);
+
+ pc.ontrack({ streams: [], track: createFakeTrack("rogue-cam", "video") });
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.remoteStreamsFor(1).length,
+ 0,
+ "video is dropped while the room's media policy disallows it"
+ );
+
+ this.room.video_allowed = true;
+ pc.ontrack({ streams: [], track: createFakeTrack("real-cam", "video") });
+ await wait(10);
+
+ assert.true(
+ this.subject
+ .remoteStreamsFor(1)
+ .some((stream) =>
+ stream.getTracks().some((track) => track.id === "real-cam")
+ ),
+ "video registers once the room allows it"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("a roster refresh drops media from a participant demoted to listener", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ this.room.membership = { role_name: "speaker" };
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "speaker" },
+ ];
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const pc = await answerRemoteOffer(this, 2);
+
+ const remoteTrack = createFakeTrack("peer-2-mic");
+ pc.ontrack({
+ streams: [createFakeStream("peer-2-stream", remoteTrack)],
+ track: remoteTrack,
+ });
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.remoteStreamsFor(1).length,
+ 1,
+ "the other speaker's audio plays while both hold speaking roles"
+ );
+
+ // Demotion arriving as a roster refresh, not a role_change message: the
+ // connection survives (a speaker still transmits to the listener) but
+ // the demoted participant's registered media must stop immediately.
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "listener" },
+ ],
+ });
+ await wait(20);
+
+ assert.strictEqual(
+ this.subject.remoteStreamsFor(1).length,
+ 0,
+ "the demoted participant's registered media is dropped"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("slow mic, lower-id local user: offer queued during the permission prompt connects via rollback", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+ const micGranted = deferred();
+ navigator.mediaDevices.getUserMedia = () =>
+ micGranted.promise.then(() => rawStream);
+
+ // Local user is the designated (lower-id) offerer, but is slow to grant
+ // mic access. The higher-id peer's fallback offer arrives while the
+ // permission prompt is still open. The immediate offer and the rollback
+ // answer to the same peer can land in one HTTP batch, so flatten them.
+ this.currentUser.id = 2;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 50, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(...signalsFrom(request));
+ return response({});
+ });
+
+ try {
+ const join = this.subject.join(this.room);
+ await wait(20);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 50,
+ data: { type: "offer", sdp: "peer-offer" },
+ });
+ await wait(20);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "does not create peers or signal before microphone permission is granted"
+ );
+ assert.strictEqual(
+ signalRequests.length,
+ 0,
+ "queues the inbound offer instead of acting on it while connecting"
+ );
+
+ micGranted.resolve();
+ await join;
+ await waitUntil(() => signalRequests.length === 2, 1000);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ assert.deepEqual(
+ signalRequests,
+ [
+ { recipientId: 50, type: "offer", sdp: "fake-offer" },
+ { recipientId: 50, type: "answer", sdp: "fake-answer" },
+ ],
+ "offers immediately on grant, then rolls back and answers the queued offer"
+ );
+ assert.strictEqual(
+ pc.signalingState,
+ "stable",
+ "ends negotiation in a stable state, not stuck on a dangling offer"
+ );
+
+ const remoteTrack = createFakeTrack("peer-50-track");
+ const remoteStream = createFakeStream("peer-50-stream", remoteTrack);
+ pc.ontrack({ streams: [remoteStream], track: remoteTrack });
+ await wait(10);
+
+ assert.true(
+ this.subject
+ .remoteStreamsFor(1)
+ .some((stream) =>
+ stream.getTracks().some((track) => track.id === "peer-50-track")
+ ),
+ "exposes the peer's audio after a slow-permission join"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("slow mic, higher-id local user: queued offer is answered on grant without a competing offer", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+ const micGranted = deferred();
+ navigator.mediaDevices.getUserMedia = () =>
+ micGranted.promise.then(() => rawStream);
+
+ // Local user is higher-id, so the lower-id peer owns the offer. That
+ // offer lands while the mic prompt is open; on grant the local user
+ // must answer it rather than racing it with a fallback offer. Keep the
+ // fallback delay small so a broken cancelation would fire well inside
+ // the observation window below.
+ setPeerTimingForTesting({
+ ...SAFE_PEER_TIMING,
+ offerRetryBaseDelayMs: 200,
+ });
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ const join = this.subject.join(this.room);
+ await wait(20);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "peer-offer" },
+ });
+ await wait(20);
+
+ micGranted.resolve();
+ await join;
+ await waitUntil(() => signalRequests.length === 1, 1000);
+ // Wait 3x past the 200ms fallback delay to prove no late competing
+ // offer fires.
+ await wait(600);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ assert.deepEqual(
+ signalRequests,
+ [{ recipientId: 2, type: "answer", sdp: "fake-answer" }],
+ "answers the queued offer and never sends a competing fallback offer"
+ );
+ assert.strictEqual(
+ pc.signalingState,
+ "stable",
+ "ends negotiation in a stable state"
+ );
+
+ const remoteTrack = createFakeTrack("peer-2-track");
+ const remoteStream = createFakeStream("peer-2-stream", remoteTrack);
+ pc.ontrack({ streams: [remoteStream], track: remoteTrack });
+ await wait(10);
+
+ assert.true(
+ this.subject
+ .remoteStreamsFor(1)
+ .some((stream) =>
+ stream.getTracks().some((track) => track.id === "peer-2-track")
+ ),
+ "exposes the peer's audio after a slow-permission join"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("join with both a lower- and higher-id peer only offers to the higher-id one", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+
+ // Local id sits between the two peers: it owns the offer to the
+ // higher-id peer (99) and waits for the lower-id peer (2) to offer.
+ this.currentUser.id = 10;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ { id: 99, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await waitUntil(() => signalRequests.length === 1, 1000);
+
+ assert.deepEqual(
+ signalRequests,
+ [{ recipientId: 99, type: "offer", sdp: "fake-offer" }],
+ "offers immediately only to the higher-id peer, not the lower-id one"
+ );
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "peer-offer" },
+ });
+ await waitUntil(() => signalRequests.length === 2, 1000);
+
+ assert.deepEqual(
+ signalRequests[1],
+ { recipientId: 2, type: "answer", sdp: "fake-answer" },
+ "answers the lower-id peer when its offer arrives"
+ );
+ assert.false(
+ signalRequests.some(
+ (request) => request.recipientId === 2 && request.type === "offer"
+ ),
+ "never sends a competing offer to the lower-id peer"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("honors an early offer from a participant whose presence has not propagated yet", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ const signalRequests = [];
+ const signalSessionIds = [];
+
+ // The regression: two peers join near-simultaneously. The other peer
+ // gathers and offers before our presence broadcast lists it, so
+ // active_participants still only contains us when its offer arrives.
+ // Gating on the local roster used to silently drop that offer and strand
+ // the connection; the relay is server-attested (the server only relays
+ // for senders holding a live participant session), so we must answer it.
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", (request) => {
+ signalRequests.push(signalPayloadFrom(request));
+ signalSessionIds.push(
+ new URLSearchParams(request.requestBody).get("participant_session_id")
+ );
+ return response({});
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ signalRequests.length,
+ 0,
+ "is alone in the room per presence, so sends nothing on its own"
+ );
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ sender: { id: 2, username: "early-bird" },
+ data: { type: "offer", sdp: "early-offer" },
+ });
+ await waitUntil(() => signalRequests.length === 1, 1500);
+
+ assert.deepEqual(
+ signalRequests[0],
+ { recipientId: 2, type: "answer", sdp: "fake-answer" },
+ "answers the early offer despite the sender being absent from presence"
+ );
+ assert.strictEqual(
+ signalSessionIds[0],
+ "session-abc",
+ "authenticates the answer with the join's participant session"
+ );
+ assert.true(
+ (this.room.active_participants || []).some(
+ (participant) => Number(participant.id) === 2
+ ),
+ "renders the server-serialized sender as a provisional participant"
+ );
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ assert.strictEqual(
+ pc.remoteDescription.sdp,
+ "early-offer",
+ "applies the early offer as the remote description"
+ );
+ assert.strictEqual(
+ pc.signalingState,
+ "stable",
+ "completes negotiation rather than dropping the offer"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("queues an early ICE candidate that arrives before its offer and applies it once engaged", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", () => response({}));
+
+ const candidate = {
+ candidate: "candidate:1 1 UDP 2122252543 127.0.0.1 3478 typ host",
+ sdpMid: "0",
+ sdpMLineIndex: 0,
+ };
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ // A candidate can land a beat ahead of its offer; with no peer yet it
+ // must be stashed, not dropped.
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "candidate", candidate },
+ });
+ await wait(20);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 0,
+ "does not create a peer from a lone candidate"
+ );
+
+ // The offer then engages the peer, which flushes the queued candidate.
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "early-offer" },
+ });
+ await waitUntil(() => FakeRTCPeerConnection.instances.length === 1, 1500);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ await waitUntil(() => pc.addedCandidates.length === 1, 1000);
+
+ assert.strictEqual(
+ pc.addedCandidates[0].candidate,
+ candidate.candidate,
+ "applies the candidate that arrived before the offer"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("keeps an early-offer peer alive through stale participant snapshots", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", () => response({}));
+
+ const candidate = {
+ candidate: "candidate:1 1 UDP 2122252543 127.0.0.1 3478 typ host",
+ sdpMid: "0",
+ sdpMLineIndex: 0,
+ };
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "early-offer" },
+ });
+ await waitUntil(() => FakeRTCPeerConnection.instances.length === 1);
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [{ id: this.currentUser.id, role: "participant" }],
+ });
+ await wait(20);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "keeps the peer created by the early targeted offer"
+ );
+
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "candidate", candidate },
+ });
+ await waitUntil(() => pc.addedCandidates.length === 1);
+
+ assert.strictEqual(
+ pc.addedCandidates[0].candidate,
+ candidate.candidate,
+ "applies candidates while waiting for presence to include the peer"
+ );
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ],
+ });
+ await wait(20);
+
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "does not recreate the peer once presence catches up"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("recreates the peer when the remote restarts ICE after a rejoin", async function (assert) {
+ assert.timeout(2000);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+
+ // Local user is higher-id, so it answers the peer rather than offering.
+ this.currentUser.id = 50;
+ this.room.room_type = "open";
+ this.room.membership.role_name = "participant";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/signal", () => response({}));
+
+ const offer = (ufrag) => ({
+ type: "offer",
+ sdp: `v=0\r\na=ice-ufrag:${ufrag}\r\na=ice-pwd:secret\r\n`,
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(20);
+
+ this.rooms.emit(1, { type: "signal", sender_id: 2, data: offer("AAAA") });
+ await wait(20);
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "creates a single peer for the initial offer"
+ );
+
+ // A resent offer with the same ICE ufrag is not a restart; keep the peer.
+ this.rooms.emit(1, { type: "signal", sender_id: 2, data: offer("AAAA") });
+ await wait(20);
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "does not recreate the peer when the ICE ufrag is unchanged"
+ );
+
+ // A fresh offer with a NEW ufrag means the peer left and rejoined; the
+ // stale transport can't recover, so the peer must be rebuilt.
+ this.rooms.emit(1, { type: "signal", sender_id: 2, data: offer("BBBB") });
+ await waitUntil(() => FakeRTCPeerConnection.created === 2, 1000);
+
+ const freshPc = FakeRTCPeerConnection.instances.at(-1);
+ assert.true(
+ freshPc.remoteDescription.sdp.includes("ice-ufrag:BBBB"),
+ "applies the restarted offer on the freshly created peer"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("inbound recovery signals cancel a pending peer restart", async function (assert) {
+ assert.timeout(5000);
+
+ // Short restart delay so a restart that survives the cancelation would
+ // fire well inside the observation window below.
+ setPeerTimingForTesting({
+ ...SAFE_PEER_TIMING,
+ restartDisconnectedDelayMs: 400,
+ });
+
+ let signalRequests = 0;
+
+ pretender.post("/voice/rooms/1/signal", () => {
+ signalRequests++;
+ return response({});
+ });
+
+ await this.subject.join(this.room);
+ await wait(50);
+
+ const pc = FakeRTCPeerConnection.instances[0];
+ pc.connectionState = "disconnected";
+ pc.onconnectionstatechange();
+
+ // The recovery offer is emitted immediately, so its handling (which
+ // cancels the pending restart) only races the restart timer across a
+ // microtask hop, not across fixed waits.
+ this.rooms.emit(1, {
+ type: "signal",
+ sender_id: 2,
+ data: { type: "offer", sdp: "recovery-offer" },
+ });
+ await waitUntil(() => signalRequests === 1, 1000);
+ // Wait 3x past the restart delay to prove the canceled timer stays dead.
+ await wait(1200);
+
+ assert.strictEqual(
+ signalRequests,
+ 1,
+ "sends only the recovery answer and does not fire a stale restart offer"
+ );
+ assert.strictEqual(
+ FakeRTCPeerConnection.created,
+ 1,
+ "keeps the existing peer instead of recreating it after recovery signaling"
+ );
+ });
+
+ test("enabling noise suppression preserves mute state across multiple peers", async function (assert) {
+ const rawTrack = createFakeTrack("raw-track");
+ const processedTrack = createFakeTrack("processed-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const processedStream = createFakeStream(
+ "processed-stream",
+ processedTrack
+ );
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream,
+ });
+
+ this.room.membership.role_name = "speaker";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "speaker" },
+ { id: 30, role: "speaker" },
+ ];
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.subject.toggleMute();
+
+ await this.subject.setNoiseSuppressionMode("ai:dtln");
+
+ assert.true(
+ this.subject.noiseSuppressionEnabled,
+ "marks noise suppression as enabled"
+ );
+ assert.strictEqual(
+ this.subject.localStream,
+ processedStream,
+ "swaps to the processed stream"
+ );
+
+ FakeRTCPeerConnection.instances.forEach((pc, index) => {
+ const sender = pc.getSenders()[0];
+
+ assert.strictEqual(
+ sender.track,
+ processedTrack,
+ `peer ${index + 1} switches to the processed track`
+ );
+ assert.false(
+ sender.track.enabled,
+ `peer ${index + 1} keeps the muted state after the stream swap`
+ );
+ });
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("disabling noise suppression preserves mute state across multiple peers", async function (assert) {
+ const rawTrack = createFakeTrack("raw-track");
+ const processedTrack = createFakeTrack("processed-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const processedStream = createFakeStream(
+ "processed-stream",
+ processedTrack
+ );
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream,
+ });
+
+ this.room.membership.role_name = "speaker";
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "speaker" },
+ { id: 30, role: "speaker" },
+ ];
+
+ localStorage.setItem("voice:noise-suppression-mode", "ai:dtln");
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.subject.toggleMute();
+ await this.subject.setNoiseSuppressionMode("standard");
+
+ assert.false(
+ this.subject.noiseSuppressionEnabled,
+ "marks noise suppression as disabled"
+ );
+ assert.strictEqual(
+ this.subject.localStream,
+ rawStream,
+ "restores the raw microphone stream"
+ );
+ assert.strictEqual(
+ audioEnvironment.sourceStreams.filter((stream) => stream === rawStream)
+ .length,
+ 2,
+ "rebinds the local speaking monitor to the restored raw stream"
+ );
+
+ FakeRTCPeerConnection.instances.forEach((pc, index) => {
+ const sender = pc.getSenders()[0];
+
+ assert.strictEqual(
+ sender.track,
+ rawTrack,
+ `peer ${index + 1} switches back to the raw track`
+ );
+ assert.false(
+ sender.track.enabled,
+ `peer ${index + 1} keeps the muted state after restoring the raw stream`
+ );
+ });
+ } finally {
+ localStorage.removeItem("voice:noise-suppression");
+ localStorage.removeItem("voice:noise-suppression-mode");
+ audioEnvironment.restore();
+ }
+ });
+
+ test("changing the noise suppression mode without a microphone only stores the preference", async function (assert) {
+ try {
+ await this.subject.setNoiseSuppressionMode("ai:dtln");
+
+ assert.strictEqual(
+ this.subject.noiseSuppressionMode,
+ "ai:dtln",
+ "marks AI suppression as preferred for the next mic acquisition"
+ );
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "ai:dtln",
+ "persists the preference"
+ );
+
+ await this.subject.setNoiseSuppressionMode("standard");
+
+ assert.strictEqual(
+ this.subject.noiseSuppressionMode,
+ "standard",
+ "marks standard suppression as preferred"
+ );
+ assert.strictEqual(
+ localStorage.getItem("voice:noise-suppression-mode"),
+ "standard",
+ "persists the new mode"
+ );
+ } finally {
+ localStorage.removeItem("voice:noise-suppression-mode");
+ }
+ });
+
+ test("leaving the room page stops an active camera publication", async function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.siteSettings.voice_video_max_publishers = 8;
+
+ this.room.room_type = "open";
+ this.room.video_enabled = true;
+ this.room.membership = { role_name: "participant" };
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant", watching_video: true },
+ ];
+
+ const stateRequests = [];
+ pretender.post("/voice/rooms/1/state", (request) => {
+ stateRequests.push(
+ Object.fromEntries(new URLSearchParams(request.requestBody))
+ );
+ return response({});
+ });
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: rawStream,
+ });
+
+ let cameraStopped = false;
+ const cameraTrack = {
+ id: "camera-track",
+ kind: "video",
+ enabled: true,
+ contentHint: "",
+ stop() {
+ cameraStopped = true;
+ },
+ addEventListener() {},
+ };
+ const cameraStream = {
+ id: "camera-stream",
+ getTracks: () => [cameraTrack],
+ getVideoTracks: () => [cameraTrack],
+ };
+
+ navigator.mediaDevices.getUserMedia = async (constraints) =>
+ constraints?.video ? cameraStream : rawStream;
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ this.subject.setWatching(1, true);
+ await this.subject.toggleCamera();
+
+ assert.strictEqual(
+ this.subject.localVideoKind,
+ "camera",
+ "camera publication starts from the room page"
+ );
+
+ const requestsBeforeLeave = stateRequests.length;
+ this.subject.setWatching(1, false);
+ await wait(10);
+
+ assert.strictEqual(
+ this.subject.localVideoKind,
+ null,
+ "publication stops when the user leaves the room page"
+ );
+ assert.true(
+ cameraStopped,
+ "the camera track is stopped so the device light turns off"
+ );
+
+ const leaveRequests = stateRequests.slice(requestsBeforeLeave);
+ assert.deepEqual(
+ leaveRequests,
+ [
+ {
+ watching: "false",
+ video: "false",
+ screen: "false",
+ participant_session_id: "session-abc",
+ },
+ ],
+ "page leave sends one combined state request so concurrent " +
+ "read-modify-write updates cannot resurrect stale publisher flags"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ function createFakeCameraTrack(id) {
+ return {
+ id,
+ kind: "video",
+ enabled: true,
+ contentHint: "",
+ stopped: false,
+ stop() {
+ this.stopped = true;
+ },
+ addEventListener() {},
+ };
+ }
+
+ function createFakeCameraStream(id, track) {
+ return {
+ id,
+ getTracks: () => [track],
+ getVideoTracks: () => [track],
+ };
+ }
+
+ function setupCameraRoom(context) {
+ context.siteSettings.voice_video_enabled = true;
+ context.siteSettings.voice_video_max_publishers = 8;
+
+ context.room.room_type = "open";
+ context.room.video_enabled = true;
+ context.room.membership = { role_name: "participant" };
+ context.room.active_participants = [
+ { id: context.currentUser.id, role: "participant" },
+ ];
+
+ pretender.post("/voice/rooms/1/state", () => response({}));
+ }
+
+ test("setVideoInputDevice releases the live camera and retries when the hardware is busy", async function (assert) {
+ setupCameraRoom(this);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: rawStream,
+ });
+
+ const frontTrack = createFakeCameraTrack("front-track");
+ const frontStream = createFakeCameraStream("front-stream", frontTrack);
+ const rearTrack = createFakeCameraTrack("rear-track");
+ const rearStream = createFakeCameraStream("rear-stream", rearTrack);
+
+ // Mimics a phone: the rear camera can't open until the front capture is
+ // released.
+ navigator.mediaDevices.getUserMedia = async (constraints) => {
+ if (!constraints?.video) {
+ return rawStream;
+ }
+ if (constraints.video.deviceId?.exact === "rear") {
+ if (!frontTrack.stopped) {
+ throw new DOMException("busy", "NotReadableError");
+ }
+ return rearStream;
+ }
+ return frontStream;
+ };
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+ this.subject.setWatching(1, true);
+ await this.subject.toggleCamera();
+
+ assert.true(await this.subject.setVideoInputDevice("rear"));
+ assert.strictEqual(
+ this.subject.videoInputDeviceId,
+ "rear",
+ "the selection lands on the requested camera"
+ );
+ assert.true(
+ frontTrack.stopped,
+ "releases the current capture so the new camera can open"
+ );
+ assert.false(rearTrack.stopped, "keeps the new capture live");
+ assert.strictEqual(
+ this.subject.localVideoTrack?.id,
+ "rear-track",
+ "publishes the new camera's track"
+ );
+ } finally {
+ audioEnvironment.restore();
+ localStorage.removeItem("voice_video_input_device");
+ }
+ });
+
+ test("setVideoInputDevice reacquires the previous camera when the retry also fails", async function (assert) {
+ setupCameraRoom(this);
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: rawStream,
+ });
+
+ const frontTrack = createFakeCameraTrack("front-track");
+ const frontStream = createFakeCameraStream("front-stream", frontTrack);
+ const recoveredTrack = createFakeCameraTrack("recovered-track");
+ const recoveredStream = createFakeCameraStream(
+ "recovered-stream",
+ recoveredTrack
+ );
+
+ let frontOpens = 0;
+ navigator.mediaDevices.getUserMedia = async (constraints) => {
+ if (!constraints?.video) {
+ return rawStream;
+ }
+ if (constraints.video.deviceId?.exact === "rear") {
+ throw new DOMException("busy", "NotReadableError");
+ }
+ frontOpens += 1;
+ return frontOpens === 1 ? frontStream : recoveredStream;
+ };
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+ this.subject.setWatching(1, true);
+ await this.subject.toggleCamera();
+
+ assert.false(await this.subject.setVideoInputDevice("rear"));
+ assert.strictEqual(
+ this.subject.videoInputDeviceId,
+ "system_default",
+ "keeps the selection on the camera that is actually live"
+ );
+ assert.strictEqual(
+ this.subject.localVideoKind,
+ "camera",
+ "the camera stays published"
+ );
+ assert.strictEqual(
+ this.subject.localVideoTrack?.id,
+ "recovered-track",
+ "publishes a fresh capture of the previous camera, since the old one was released for the retry"
+ );
+ } finally {
+ audioEnvironment.restore();
+ localStorage.removeItem("voice_video_input_device");
+ }
+ });
+
+ test("remote camera start exposes the negotiated video track without a refresh", async function (assert) {
+ assert.timeout(2000);
+
+ this.siteSettings.voice_video_enabled = true;
+ this.siteSettings.voice_video_max_publishers = 8;
+
+ this.room.room_type = "open";
+ this.room.video_enabled = true;
+ // The serializer's combined room+site flag; the receive-side track
+ // policy consults it before registering the remote video track.
+ this.room.video_allowed = true;
+ this.room.membership = { role_name: "participant" };
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ {
+ id: 2,
+ role: "participant",
+ is_video_on: false,
+ is_screen_sharing: false,
+ },
+ ];
+
+ const rawTrack = createFakeTrack("raw-track");
+ const rawStream = createFakeStream("raw-stream", rawTrack);
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: rawStream,
+ });
+
+ try {
+ await this.subject.join(this.room);
+ await wait(50);
+
+ assert.strictEqual(
+ this.subject.remoteStreamFor(1, 2),
+ undefined,
+ "starts without a stored remote media stream when no track event has fired"
+ );
+
+ this.rooms.emit(1, {
+ type: "participants",
+ participants: [
+ { id: this.currentUser.id, role: "participant" },
+ {
+ id: 2,
+ role: "participant",
+ is_video_on: true,
+ is_screen_sharing: false,
+ },
+ ],
+ });
+
+ await waitUntil(() => this.subject.remoteStreamFor(1, 2), 1000);
+
+ assert.deepEqual(
+ this.subject
+ .remoteStreamFor(1, 2)
+ .getVideoTracks()
+ .map((track) => track.id),
+ ["video-receiver-1"],
+ "adds the already-negotiated remote video track when presence says the peer started publishing"
+ );
+ } finally {
+ audioEnvironment.restore();
+ }
+ });
+
+ test("videoAllowedIn denies a stage listener", function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.room.video_enabled = true;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "listener" },
+ { id: 2, role: "speaker" },
+ ];
+
+ assert.false(
+ this.subject.videoAllowedIn(this.room),
+ "a stage listener cannot publish video"
+ );
+ });
+
+ test("videoAllowedIn allows a stage speaker", function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.room.video_enabled = true;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "listener" },
+ ];
+
+ assert.true(
+ this.subject.videoAllowedIn(this.room),
+ "a stage speaker can publish video"
+ );
+ });
+
+ test("videoAllowedIn allows a stage moderator", function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.room.video_enabled = true;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "moderator" },
+ { id: 2, role: "listener" },
+ ];
+
+ assert.true(
+ this.subject.videoAllowedIn(this.room),
+ "a stage moderator can publish video"
+ );
+ });
+
+ test("videoAllowedIn still requires the room's video flag for a stage speaker", function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.room.video_enabled = false;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "speaker" },
+ { id: 2, role: "listener" },
+ ];
+
+ assert.false(
+ this.subject.videoAllowedIn(this.room),
+ "the speaker role does not override a video-disabled room"
+ );
+ });
+
+ test("videoAllowedIn does not role-gate open rooms", function (assert) {
+ this.siteSettings.voice_video_enabled = true;
+ this.room.room_type = "open";
+ this.room.video_enabled = true;
+ this.room.active_participants = [
+ { id: this.currentUser.id, role: "participant" },
+ { id: 2, role: "participant" },
+ ];
+
+ assert.true(
+ this.subject.videoAllowedIn(this.room),
+ "open-room participants can publish video regardless of role"
+ );
+ });
+
+ function createDeviceTrack(id, deviceId) {
+ return {
+ id,
+ kind: "audio",
+ enabled: true,
+ stopped: false,
+ stop() {
+ this.stopped = true;
+ },
+ getSettings() {
+ return { deviceId };
+ },
+ };
+ }
+
+ async function joinWithMic(context, rawStream) {
+ const audioEnvironment = installFakeAudioEnvironment({
+ rawStream,
+ processedStream: createFakeStream(
+ "processed-stream",
+ createFakeTrack("processed-track")
+ ),
+ });
+ context.room.room_type = "open";
+ context.room.membership.role_name = "participant";
+ context.room.active_participants = [
+ { id: context.currentUser.id, role: "participant" },
+ ];
+ await context.subject.join(context.room);
+ return audioEnvironment;
+ }
+
+ test("setInputDevice opens the picked device with an exact constraint and swaps streams", async function (assert) {
+ const oldTrack = createDeviceTrack("track-a", "mic-a");
+ const audioEnvironment = await joinWithMic(
+ this,
+ createFakeStream("stream-a", oldTrack)
+ );
+
+ const newTrack = createDeviceTrack("track-b", "mic-b");
+ const requests = [];
+ navigator.mediaDevices.getUserMedia = async (constraints) => {
+ requests.push(constraints);
+ return createFakeStream("stream-b", newTrack);
+ };
+
+ try {
+ assert.true(await this.subject.setInputDevice("mic-b"));
+ assert.deepEqual(
+ requests[0].audio.deviceId,
+ { exact: "mic-b" },
+ "requires the picked device instead of treating it as a preference"
+ );
+ assert.true(oldTrack.stopped, "stops the replaced capture");
+ assert.false(newTrack.stopped, "keeps the new capture live");
+ } finally {
+ audioEnvironment.restore();
+ localStorage.removeItem("voice_audio_input_device");
+ }
+ });
+
+ test("setInputDevice reverts and keeps the current capture when the device can't be opened", async function (assert) {
+ const oldTrack = createDeviceTrack("track-a", "mic-a");
+ const audioEnvironment = await joinWithMic(
+ this,
+ createFakeStream("stream-a", oldTrack)
+ );
+
+ navigator.mediaDevices.getUserMedia = async () => {
+ throw new DOMException("busy", "NotReadableError");
+ };
+
+ try {
+ assert.false(await this.subject.setInputDevice("mic-b"));
+ assert.strictEqual(
+ this.subject.inputDeviceId,
+ "system_default",
+ "keeps the selection on the device that is actually live"
+ );
+ assert.false(oldTrack.stopped, "the live capture is left untouched");
+ } finally {
+ audioEnvironment.restore();
+ localStorage.removeItem("voice_audio_input_device");
+ }
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a99bb222693..4b6dce25a5c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -981,6 +981,12 @@ importers:
specifier: npm:@discourse/[email protected]
version: '@discourse/[email protected]'
+ plugins/voice:
+ dependencies:
+ discourse:
+ specifier: npm:@discourse/types@*
+ version: '@discourse/[email protected]'
+
themes/horizon:
dependencies:
discourse:
@@ -1862,6 +1868,10 @@ packages:
resolution: {integrity: sha512-2ER4lt8lFtFNcuyj7Y0Ry8RMLFPBYDfix8TNCh4TKP3FKlCMv+FzvDJ6Ix+CFBTqvh4KJ4uR/oCGYR3Q45yQow==}
engines: {node: '>= 20', npm: please-use-pnpm, pnpm: ^10, yarn: please-use-pnpm}
+ '@discourse/[email protected]':
+ resolution: {integrity: sha512-u1KukGjlYXg6owV5WNWc4oCVWATBu0MZPHxBotZ3581hv5+atHtdHwjKFLA7b8pwJe9gZrJc9Pmcc9axk3g4Tg==}
+ engines: {node: '>= 20', npm: please-use-pnpm, pnpm: ^10, yarn: please-use-pnpm}
+
'@discourse/[email protected]':
resolution: {integrity: sha512-2dXuEED+ISG26RbWij3NvdQmgHCD8ssnPoHMd0LnLKJc/dtd2lqg1dhrrA/WYDxfFoJaoGepoxFOsqe0d2/wqw==}
@@ -9626,6 +9636,8 @@ snapshots:
'@discourse/[email protected]': {}
+ '@discourse/[email protected]': {}
+
'@discourse/[email protected]':
dependencies:
wasm-feature-detect: 1.8.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 32401c3a76d..c3ece7825a9 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -58,6 +58,7 @@ packages:
- "plugins/poll"
- "plugins/spoiler-alert"
- "plugins/styleguide"
+- "plugins/voice"
- "themes/horizon"
patchedDependencies:
diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.json
index 4d841428036..2e24483641a 100644
--- a/spec/requests/api/schemas/json/site_response.json
+++ b/spec/requests/api/schemas/json/site_response.json
@@ -155,7 +155,7 @@
"suggested_edit_accepted": {
"type": "integer"
},
- "resenha_invitation": {
+ "voice_invitation": {
"type": "integer"
}
},