A platform for community discussion. Free, open, simple.
FEATURE: Add connection diagnostics for mesh live rooms (#45525)
Rafael dos Santos Silva6bea1bd88b34
diff --git a/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js b/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.jsindex 6d8aaed3b57..b9cd05ce764 100644--- a/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js+++ b/plugins/live/assets/javascripts/discourse/app/services/live-webrtc.js@@ -11,6 +11,11 @@ import { confirmMeshPrivacy } from "../../components/modal/live-mesh-privacy-warimport { reportMicAcquisitionFailure } from "../../components/modal/live-mic-permission.gjs";import AudioMonitor from "../../lib/live/audio-monitor.js";import { RING_SECONDS } from "../../lib/live/call-constants.js";+import {+ collectLocalInfo,+ collectPeers,+ probeIceServers,+} from "../../lib/live/connection-diagnostics.js";import HeartbeatManager from "../../lib/live/heartbeat-manager.js";import IdleTracker, { idleThresholds } from "../../lib/live/idle-tracker.js";import { consumePendingInviteRef } from "../../lib/live/invite-ref.js";@@ -739,6 +744,37 @@ export default class LiveWebrtcService extends Service {return this.#roomTransports.get(roomId) === "livekit";}+ // Peer-level diagnostics only exist for mesh rooms; in SFU rooms the single+ // server connection is owned by the SFU client library.+ canDiagnoseConnection(roomId) {+ return (+ this.connectionStateFor(roomId) === "connected" &&+ this.#isMeshRoom(roomId)+ );+ }++ async connectionDiagnostics(roomId) {+ const room = this.liveRooms.roomById(roomId);+ return {+ room,+ transport: this.#roomTransports.get(roomId) ?? "mesh",+ iceTransportPolicy: this.iceTransportPolicy,+ local: collectLocalInfo(this.localStream),+ peers: await collectPeers({+ room,+ currentUserId: this.currentUser?.id,+ peerManager: this.#peerManager,+ shouldMaintainPeer: (userId) =>+ this.#meshSignals.shouldMaintainPeerConnection(roomId, userId),+ }),+ collectedAt: Date.now(),+ };+ }++ probeIceServers() {+ return probeIceServers(this.iceServers);+ }+async join(room) {if (!room?.id) {return;diff --git a/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs b/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjsindex 7d043ab7337..f857f165936 100644--- a/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/call-widget.gjs@@ -19,6 +19,7 @@ import {trackGridSize,} from "../../lib/live/video-grid-layout.js";import LiveInviteAgentButton from "../live-invite-agent-button.gjs";+import LiveConnectionDiagnosticsModal from "../modal/live-connection-diagnostics.gjs";import LiveInviteUsersModal from "../modal/live-invite-users.gjs";import LiveRoomInfoModal from "../modal/live-room-info.gjs";import LiveCallControls from "./call-controls.gjs";@@ -312,6 +313,10 @@ export default class LiveCallWidget extends Component {return parts.length ? trustHTML(parts.join(" ")) : null;}+ get canDiagnoseConnection() {+ return this.liveWebrtc.canDiagnoseConnection(this.room?.id);+ }+@actionopenRoom() {if (this.room?.slug) {@@ -532,6 +537,14 @@ export default class LiveCallWidget extends Component {this.openChat();}+ @action+ openConnectionDiagnostics(closeMenu) {+ closeMenu?.();+ this.modal.show(LiveConnectionDiagnosticsModal, {+ model: { room: this.room },+ });+ }+@actionopenRoomInfo(closeMenu) {closeMenu?.();@@ -820,6 +833,19 @@ export default class LiveCallWidget extends Component {/></dropdown.item>{{/if}}+ {{#if this.canDiagnoseConnection}}+ <dropdown.item>+ <DButton+ class="btn-transparent live-connection-diagnostics-trigger"+ @action={{fn+ this.openConnectionDiagnostics+ roomMenu.close+ }}+ @icon="stethoscope"+ @label="live.connection_diagnostics.menu"+ />+ </dropdown.item>+ {{/if}}<dropdown.item><DButtonclass="btn-transparent"diff --git a/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs b/plugins/live/assets/javascripts/discourse/components/live/room-page.gjsindex 8a836edc026..3e501da444a 100644--- a/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/room-page.gjs@@ -30,6 +30,7 @@ import {trackGridSize,} from "../../lib/live/video-grid-layout.js";import LiveInviteAgentButton from "../live-invite-agent-button.gjs";+import LiveConnectionDiagnosticsModal from "../modal/live-connection-diagnostics.gjs";import LiveInviteUsersModal from "../modal/live-invite-users.gjs";import LiveRoomInfoModal from "../modal/live-room-info.gjs";import LiveCallControls from "./call-controls.gjs";@@ -406,6 +407,10 @@ export default class LiveRoomPage extends Component {: i18n("live.transcript.draft_topic");}+ get canDiagnoseConnection() {+ return this.liveWebrtc.canDiagnoseConnection(this.room?.id);+ }+@actiontoggleSpotlight(participantId) {this.spotlightParticipantId =@@ -610,6 +615,14 @@ export default class LiveRoomPage extends Component {}}+ @action+ openConnectionDiagnostics(closeMenu) {+ closeMenu?.();+ this.modal.show(LiveConnectionDiagnosticsModal, {+ model: { room: this.room },+ });+ }+@actionopenRoomInfo(closeMenu) {closeMenu?.();@@ -957,6 +970,19 @@ export default class LiveRoomPage extends Component {</dropdown.item>{{/if}}{{/if}}+ {{#if this.canDiagnoseConnection}}+ <dropdown.item>+ <DButton+ class="btn-transparent live-connection-diagnostics-trigger"+ @action={{fn+ this.openConnectionDiagnostics+ roomMenu.close+ }}+ @icon="stethoscope"+ @label="live.connection_diagnostics.menu"+ />+ </dropdown.item>+ {{/if}}<dropdown.item><DButtonclass="btn-transparent"diff --git a/plugins/live/assets/javascripts/discourse/components/modal/live-connection-diagnostics.gjs b/plugins/live/assets/javascripts/discourse/components/modal/live-connection-diagnostics.gjsnew file mode 100644index 00000000000..191282a4f5a--- /dev/null+++ b/plugins/live/assets/javascripts/discourse/components/modal/live-connection-diagnostics.gjs@@ -0,0 +1,510 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { concat } from "@ember/helper";+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 DModal from "discourse/ui-kit/d-modal";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+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 {+ formatBitrate,+ formatCandidateCounts,+ formatReport,+ formatRtt,+} from "../../lib/live/connection-diagnostics.js";++const REFRESH_INTERVAL_MS = 3000;++const ROUTE_ICONS = {+ host: "network-wired",+ stun: "arrow-right-arrow-left",+ "relay-local": "server",+ "relay-remote": "server",+ "relay-both": "server",+ unknown: "circle-question",+};++function peerStatus(peer) {+ const state = peer.connection?.connectionState;+ if (!peer.connection) {+ return peer.expected ? "missing" : "not_needed";+ }+ if (state === "connected") {+ return "connected";+ }+ if (state === "failed" || state === "disconnected" || state === "closed") {+ return "failed";+ }+ return "connecting";+}++function candidateLabel(candidate) {+ if (!candidate) {+ return null;+ }+ return [+ candidate.address &&+ (candidate.port+ ? `${candidate.address}:${candidate.port}`+ : candidate.address),+ candidate.type,+ candidate.protocol?.toUpperCase(),+ candidate.relayProtocol &&+ i18n("live.connection_diagnostics.relay_over", {+ protocol: candidate.relayProtocol.toUpperCase(),+ }),+ candidate.networkType,+ ]+ .filter(Boolean)+ .join(" · ");+}++export default class LiveConnectionDiagnosticsModal extends Component {+ @service liveWebrtc;+ @service toasts;++ @tracked diagnostics = null;+ @tracked probes = null;+ @tracked probing = false;++ #refreshTimer = null;++ constructor() {+ super(...arguments);+ this.refresh();+ this.#refreshTimer = setInterval(+ () => this.#collectPeers(),+ REFRESH_INTERVAL_MS+ );+ }++ willDestroy() {+ super.willDestroy(...arguments);+ clearInterval(this.#refreshTimer);+ }++ get room() {+ return this.args.model.room;+ }++ get peers() {+ return (this.diagnostics?.peers || [])+ .map((peer) => {+ const status = peerStatus(peer);+ const stats = peer.connection?.stats;+ const pair = stats?.selectedPair;+ const route = stats?.route ?? "unknown";+ const recovery = peer.recovery;++ return {+ key: peer.userId,+ user: {+ username: peer.username,+ avatar_template: peer.avatarTemplate,+ },+ displayName:+ peer.username ||+ i18n("live.connection_diagnostics.unknown_user", {+ id: peer.userId,+ }),+ inRoster: peer.inRoster,+ status,+ statusLabel: i18n(`live.connection_diagnostics.status.${status}`),+ hasConnection: !!peer.connection,+ route,+ routeIcon: ROUTE_ICONS[route],+ routeLabel: i18n(`live.connection_diagnostics.route.${route}`),+ isRelayed: route.startsWith("relay"),+ states: peer.connection+ ? [+ ["connection", peer.connection.connectionState],+ ["ice", peer.connection.iceConnectionState],+ ["gathering", peer.connection.iceGatheringState],+ ["signaling", peer.connection.signalingState],+ ].map(([name, value]) => ({+ label: i18n(`live.connection_diagnostics.states.${name}`),+ value,+ }))+ : [],+ localCandidate: candidateLabel(pair?.local),+ localServer: pair?.local?.url,+ remoteCandidate: candidateLabel(pair?.remote),+ rtt: pair ? formatRtt(pair.currentRoundTripTime) : null,+ bitrate:+ typeof pair?.availableOutgoingBitrate === "number"+ ? formatBitrate(pair.availableOutgoingBitrate)+ : null,+ localCandidates:+ stats && formatCandidateCounts(stats.localCandidates),+ remoteCandidates:+ stats && formatCandidateCounts(stats.remoteCandidates),+ candidatePairs:+ stats &&+ i18n("live.connection_diagnostics.candidate_pairs_value", {+ total: stats.candidatePairs.total,+ succeeded: stats.candidatePairs.succeeded,+ failed: stats.candidatePairs.failed,+ }),+ restarts: i18n("live.connection_diagnostics.restarts_value", {+ count: recovery.restartAttempts,+ max: recovery.maxRestartAttempts,+ }),+ restartsExhausted:+ recovery.restartAttempts >= recovery.maxRestartAttempts &&+ status !== "connected",+ iceErrors: recovery.iceCandidateErrors.map((error) =>+ [error.url, error.errorCode, error.errorText]+ .filter(Boolean)+ .join(" — ")+ ),+ };+ })+ .sort((a, b) => (a.status === "connected") - (b.status === "connected"));+ }++ get connectedCount() {+ return this.peers.filter((peer) => peer.status === "connected").length;+ }++ get expectedCount() {+ return this.peers.filter((peer) => peer.status !== "not_needed").length;+ }++ get summary() {+ return i18n("live.connection_diagnostics.summary", {+ connected: this.connectedCount,+ total: this.expectedCount,+ });+ }++ get relayOnly() {+ return this.diagnostics?.iceTransportPolicy === "relay";+ }++ get probeRows() {+ return (this.probes || []).map((probe) => {+ let status = "failed";+ if (probe.reachable) {+ status = "ok";+ } else if (probe.timedOut) {+ status = "timeout";+ }+ return {+ url: probe.url,+ kind: probe.kind.toUpperCase(),+ addresses: probe.addresses.join(", "),+ status,+ statusLabel: probe.reachable+ ? i18n("live.connection_diagnostics.probe.ok", {+ ms: probe.durationMs,+ })+ : i18n(`live.connection_diagnostics.probe.${status}`),+ errors: probe.errors.map((error) =>+ [error.errorCode, error.errorText].filter(Boolean).join(" — ")+ ),+ };+ });+ }++ get localRows() {+ const local = this.diagnostics?.local;+ if (!local) {+ return [];+ }++ const rows = [+ ["browser", local.userAgent],+ ["platform", local.platform],+ [+ "online",+ local.online+ ? i18n("live.connection_diagnostics.answer_yes")+ : i18n("live.connection_diagnostics.answer_no"),+ ],+ ["cpu_cores", local.hardwareConcurrency],+ ];++ if (local.connection) {+ const { effectiveType, type, downlink, rtt } = local.connection;+ rows.push([+ "network",+ [+ type,+ effectiveType,+ downlink && `${downlink} Mbps`,+ typeof rtt === "number" && `${rtt} ms`,+ ]+ .filter(Boolean)+ .join(" · "),+ ]);+ }++ for (const track of local.localTracks) {+ rows.push([+ track.kind === "video" ? "camera" : "microphone",+ [+ track.label,+ track.readyState,+ track.enabled ? null : i18n("live.connection_diagnostics.disabled"),+ track.muted ? i18n("live.connection_diagnostics.no_signal") : null,+ ]+ .filter(Boolean)+ .join(" · "),+ ]);+ }++ return rows+ .filter(([, value]) => value !== undefined && value !== null)+ .map(([key, value]) => ({+ label: i18n(`live.connection_diagnostics.local.${key}`),+ value,+ }));+ }++ @action+ async refresh() {+ await Promise.all([this.#collectPeers(), this.#probe()]);+ }++ @action+ async copyReport() {+ if (!this.diagnostics) {+ return;+ }+ await clipboardCopy(+ formatReport({ ...this.diagnostics, probes: this.probes })+ );+ this.toasts.success({+ duration: "short",+ data: { message: i18n("live.connection_diagnostics.copied") },+ });+ }++ async #collectPeers() {+ const diagnostics = await this.liveWebrtc.connectionDiagnostics(+ this.room.id+ );+ if (!this.isDestroying) {+ this.diagnostics = diagnostics;+ }+ }++ async #probe() {+ if (this.probing) {+ return;+ }+ this.probing = true;+ try {+ const probes = await this.liveWebrtc.probeIceServers();+ if (!this.isDestroying) {+ this.probes = probes;+ }+ } finally {+ if (!this.isDestroying) {+ this.probing = false;+ }+ }+ }++ <template>+ <DModal+ class="live-connection-diagnostics"+ @closeModal={{@closeModal}}+ @title={{i18n "live.connection_diagnostics.title"}}+ >+ <:body>+ {{#if this.diagnostics}}+ <p class="live-connection-diagnostics__summary">+ {{this.summary}}+ {{#if this.relayOnly}}+ <span class="live-connection-diagnostics__note">+ {{i18n "live.connection_diagnostics.relay_only"}}+ </span>+ {{/if}}+ </p>++ <section class="live-connection-diagnostics__section">+ <h3>{{i18n "live.connection_diagnostics.peers"}}</h3>+ {{#each this.peers key="key" as |peer|}}+ <div+ class={{dConcatClass+ "live-connection-diagnostics__peer"+ (concat "--" peer.status)+ }}+ >+ <div class="live-connection-diagnostics__peer-header">+ {{#if peer.user.avatar_template}}+ {{dAvatar peer.user imageSize="small"}}+ {{/if}}+ <span class="live-connection-diagnostics__peer-name">+ {{peer.displayName}}+ </span>+ {{#unless peer.inRoster}}+ <span class="live-connection-diagnostics__note">+ {{i18n "live.connection_diagnostics.not_in_roster"}}+ </span>+ {{/unless}}+ <span+ class={{dConcatClass+ "live-connection-diagnostics__badge"+ (concat "--" peer.status)+ }}+ >{{peer.statusLabel}}</span>+ </div>++ {{#if peer.hasConnection}}+ <div+ class={{dConcatClass+ "live-connection-diagnostics__route"+ (if peer.isRelayed "--relayed")+ }}+ >+ {{dIcon peer.routeIcon}}+ {{peer.routeLabel}}+ </div>++ <dl class="live-connection-diagnostics__details">+ {{#each peer.states as |state|}}+ <dt>{{state.label}}</dt>+ <dd>{{state.value}}</dd>+ {{/each}}+ {{#if peer.localCandidate}}+ <dt>{{i18n+ "live.connection_diagnostics.local_candidate"+ }}</dt>+ <dd>{{peer.localCandidate}}</dd>+ {{/if}}+ {{#if peer.localServer}}+ <dt>{{i18n "live.connection_diagnostics.via_server"}}</dt>+ <dd><code>{{peer.localServer}}</code></dd>+ {{/if}}+ {{#if peer.remoteCandidate}}+ <dt>{{i18n+ "live.connection_diagnostics.remote_candidate"+ }}</dt>+ <dd>{{peer.remoteCandidate}}</dd>+ {{/if}}+ {{#if peer.rtt}}+ <dt>{{i18n "live.connection_diagnostics.rtt"}}</dt>+ <dd>{{peer.rtt}}</dd>+ {{/if}}+ {{#if peer.bitrate}}+ <dt>{{i18n "live.connection_diagnostics.bitrate"}}</dt>+ <dd>{{peer.bitrate}}</dd>+ {{/if}}+ {{#if peer.candidatePairs}}+ <dt>{{i18n+ "live.connection_diagnostics.candidate_pairs"+ }}</dt>+ <dd>{{peer.candidatePairs}}</dd>+ <dt>{{i18n+ "live.connection_diagnostics.local_candidates"+ }}</dt>+ <dd><code>{{peer.localCandidates}}</code></dd>+ <dt>{{i18n+ "live.connection_diagnostics.remote_candidates"+ }}</dt>+ <dd><code>{{peer.remoteCandidates}}</code></dd>+ {{/if}}+ <dt>{{i18n "live.connection_diagnostics.restarts"}}</dt>+ <dd>+ {{peer.restarts}}+ {{#if peer.restartsExhausted}}+ <span class="live-connection-diagnostics__note">+ {{i18n "live.connection_diagnostics.gave_up"}}+ </span>+ {{/if}}+ </dd>+ </dl>+ {{/if}}++ {{#if peer.iceErrors.length}}+ <ul class="live-connection-diagnostics__errors">+ {{#each peer.iceErrors as |error|}}+ <li>{{error}}</li>+ {{/each}}+ </ul>+ {{/if}}+ </div>+ {{else}}+ <p>{{i18n "live.connection_diagnostics.no_peers"}}</p>+ {{/each}}+ </section>++ <section class="live-connection-diagnostics__section">+ <h3>{{i18n "live.connection_diagnostics.servers"}}</h3>+ {{#if this.probing}}+ <p class="live-connection-diagnostics__note">+ {{i18n "live.connection_diagnostics.probing"}}+ </p>+ {{else}}+ {{#each this.probeRows as |probe|}}+ <div class="live-connection-diagnostics__server">+ <span+ class="live-connection-diagnostics__server-kind"+ >{{probe.kind}}</span>+ <code>{{probe.url}}</code>+ <span+ class={{dConcatClass+ "live-connection-diagnostics__badge"+ (concat "--" probe.status)+ }}+ >{{probe.statusLabel}}</span>+ {{#if probe.addresses}}+ <span+ class="live-connection-diagnostics__server-addresses"+ >{{probe.addresses}}</span>+ {{/if}}+ {{#if probe.errors.length}}+ <ul class="live-connection-diagnostics__errors">+ {{#each probe.errors as |error|}}+ <li>{{error}}</li>+ {{/each}}+ </ul>+ {{/if}}+ </div>+ {{else}}+ <p>{{i18n "live.connection_diagnostics.no_servers"}}</p>+ {{/each}}+ {{/if}}+ </section>++ <section class="live-connection-diagnostics__section">+ <h3>{{i18n "live.connection_diagnostics.this_device"}}</h3>+ <dl class="live-connection-diagnostics__details">+ {{#each this.localRows as |row|}}+ <dt>{{row.label}}</dt>+ <dd>{{row.value}}</dd>+ {{/each}}+ </dl>+ </section>+ {{else}}+ <div class="spinner small"></div>+ {{/if}}+ </:body>+ <:footer>+ <p class="live-connection-diagnostics__privacy">+ {{i18n "live.connection_diagnostics.privacy_note"}}+ </p>+ <DButton+ class="btn-primary"+ @action={{this.copyReport}}+ @disabled={{not this.diagnostics}}+ @icon="copy"+ @label="live.connection_diagnostics.copy_report"+ />+ <DButton+ class="btn-default"+ @action={{this.refresh}}+ @disabled={{this.probing}}+ @icon="arrows-rotate"+ @label="live.connection_diagnostics.refresh"+ />+ </:footer>+ </DModal>+ </template>+}diff --git a/plugins/live/assets/javascripts/discourse/lib/live/connection-diagnostics.js b/plugins/live/assets/javascripts/discourse/lib/live/connection-diagnostics.jsnew file mode 100644index 00000000000..5e26c9a7fca--- /dev/null+++ b/plugins/live/assets/javascripts/discourse/lib/live/connection-diagnostics.js@@ -0,0 +1,590 @@+// Gathers what the browser exposes about mesh peer connections so a user+// reporting "I can't hear X" can hand over something actionable. Candidate+// addresses are included because NAT/firewall triage needs them; mesh peers+// already see each other's addresses, but the report goes wider than that, so+// the UI warns before it is shared.++const PROBE_TIMEOUT_MS = 6000;++const CANDIDATE_TYPES = ["host", "srflx", "prflx", "relay"];++function statsValues(report) {+ if (!report) {+ return [];+ }+ return typeof report.values === "function"+ ? Array.from(report.values())+ : Object.values(report);+}++function emptyCandidateCounts() {+ return Object.fromEntries(CANDIDATE_TYPES.map((type) => [type, 0]));+}++function candidateSummary(stat) {+ if (!stat) {+ return null;+ }+ return {+ type: stat.candidateType,+ // Older Chromium reports `ip` instead of `address`.+ address: stat.address ?? stat.ip,+ port: stat.port,+ protocol: stat.protocol,+ relayProtocol: stat.relayProtocol,+ url: stat.url,+ networkType: stat.networkType,+ };+}++function selectedPairFrom(stats, byId) {+ for (const stat of stats) {+ if (stat.type === "transport" && stat.selectedCandidatePairId) {+ const pair = byId.get(stat.selectedCandidatePairId);+ if (pair) {+ return pair;+ }+ }+ }++ const pairs = stats.filter((stat) => stat.type === "candidate-pair");+ return (+ pairs.find((pair) => pair.selected) ??+ pairs.find((pair) => pair.nominated && pair.state === "succeeded")+ );+}++/**+ * Classifies how media flows between us and a peer.+ *+ * @param {{type?: string}|null} local+ * @param {{type?: string}|null} remote+ * @returns {"relay-both"|"relay-local"|"relay-remote"|"stun"|"host"|"unknown"}+ */+export function routeFor(local, remote) {+ const localRelay = local?.type === "relay";+ const remoteRelay = remote?.type === "relay";++ if (localRelay && remoteRelay) {+ return "relay-both";+ }+ if (localRelay) {+ return "relay-local";+ }+ if (remoteRelay) {+ return "relay-remote";+ }+ if (!local?.type || !remote?.type) {+ return "unknown";+ }+ if (local.type === "host" && remote.type === "host") {+ return "host";+ }+ return "stun";+}++/**+ * Reduces an RTCStatsReport to the fields useful for connection triage.+ *+ * @param {RTCStatsReport|Map<string, object>} report+ */+export function summarizeStats(report) {+ const stats = statsValues(report);+ const byId = new Map(stats.map((stat) => [stat.id, stat]));++ const pair = selectedPairFrom(stats, byId);+ const local = candidateSummary(byId.get(pair?.localCandidateId));+ const remote = candidateSummary(byId.get(pair?.remoteCandidateId));++ const localCandidates = emptyCandidateCounts();+ const remoteCandidates = emptyCandidateCounts();+ const candidatePairs = { total: 0, succeeded: 0, failed: 0, inProgress: 0 };+ const inbound = [];+ const outbound = [];+ let transport = null;++ const codecName = (id) => byId.get(id)?.mimeType?.split("/")[1];++ for (const stat of stats) {+ switch (stat.type) {+ case "local-candidate":+ if (stat.candidateType in localCandidates) {+ localCandidates[stat.candidateType]++;+ }+ break;+ case "remote-candidate":+ if (stat.candidateType in remoteCandidates) {+ remoteCandidates[stat.candidateType]++;+ }+ break;+ case "candidate-pair":+ candidatePairs.total++;+ if (stat.state === "succeeded") {+ candidatePairs.succeeded++;+ } else if (stat.state === "failed") {+ candidatePairs.failed++;+ } else if (stat.state === "in-progress") {+ candidatePairs.inProgress++;+ }+ break;+ case "transport":+ transport ??= {+ dtlsState: stat.dtlsState,+ iceState: stat.iceState,+ iceRole: stat.iceRole,+ tlsVersion: stat.tlsVersion,+ srtpCipher: stat.srtpCipher,+ };+ break;+ case "inbound-rtp":+ inbound.push({+ kind: stat.kind,+ codec: codecName(stat.codecId),+ packetsReceived: stat.packetsReceived,+ packetsLost: stat.packetsLost,+ jitter: stat.jitter,+ bytesReceived: stat.bytesReceived,+ framesPerSecond: stat.framesPerSecond,+ frameWidth: stat.frameWidth,+ frameHeight: stat.frameHeight,+ });+ break;+ case "outbound-rtp":+ outbound.push({+ kind: stat.kind,+ codec: codecName(stat.codecId),+ packetsSent: stat.packetsSent,+ bytesSent: stat.bytesSent,+ framesPerSecond: stat.framesPerSecond,+ frameWidth: stat.frameWidth,+ frameHeight: stat.frameHeight,+ qualityLimitationReason: stat.qualityLimitationReason,+ });+ break;+ }+ }++ return {+ route: routeFor(local, remote),+ selectedPair: pair+ ? {+ local,+ remote,+ state: pair.state,+ currentRoundTripTime: pair.currentRoundTripTime,+ availableOutgoingBitrate: pair.availableOutgoingBitrate,+ availableIncomingBitrate: pair.availableIncomingBitrate,+ bytesSent: pair.bytesSent,+ bytesReceived: pair.bytesReceived,+ }+ : null,+ localCandidates,+ remoteCandidates,+ candidatePairs,+ transport,+ // Pre-negotiated idle m-lines report zero-packet RTP entries; they are+ // noise when nothing is being sent on them.+ inbound: inbound.filter((entry) => entry.packetsReceived > 0),+ outbound: outbound.filter((entry) => entry.packetsSent > 0),+ };+}++/**+ * Collects state and stats for one peer connection.+ *+ * @param {RTCPeerConnection} pc+ */+export async function collectPeerConnection(pc) {+ const states = {+ connectionState: pc.connectionState,+ iceConnectionState: pc.iceConnectionState,+ iceGatheringState: pc.iceGatheringState,+ signalingState: pc.signalingState,+ };++ try {+ return { ...states, stats: summarizeStats(await pc.getStats()) };+ } catch (error) {+ return { ...states, stats: null, statsError: String(error?.message) };+ }+}++/**+ * Details about this browser and network the WebRTC stack doesn't report.+ *+ * @param {MediaStream|null} localStream+ */+export function collectLocalInfo(localStream) {+ const nav = globalThis.navigator || {};+ const connection = nav.connection;++ return {+ userAgent: nav.userAgent,+ platform: nav.userAgentData?.platform || nav.platform,+ online: nav.onLine,+ secureContext: globalThis.isSecureContext,+ hardwareConcurrency: nav.hardwareConcurrency,+ deviceMemory: nav.deviceMemory,+ connection: connection+ ? {+ type: connection.type,+ effectiveType: connection.effectiveType,+ downlink: connection.downlink,+ rtt: connection.rtt,+ saveData: connection.saveData,+ }+ : null,+ localTracks: (localStream?.getTracks() || []).map((track) => ({+ kind: track.kind,+ label: track.label,+ enabled: track.enabled,+ muted: track.muted,+ readyState: track.readyState,+ })),+ };+}++function iceServerUrls(iceServers) {+ const entries = [];+ for (const server of iceServers || []) {+ const urls = Array.isArray(server.urls) ? server.urls : [server.urls];+ for (const url of urls.filter(Boolean)) {+ entries.push({ url, server });+ }+ }+ return entries;+}++/**+ * Checks one STUN/TURN URL in isolation: a throwaway connection gathers+ * candidates against only that server, so a srflx (STUN) or relay (TURN)+ * candidate proves this browser can reach and authenticate with it.+ *+ * @param {string} url+ * @param {RTCIceServer} server+ * @param {{timeoutMs?: number}} [options]+ */+export async function probeIceServer(url, server, options = {}) {+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;+ const isTurn = /^turns?:/i.test(url);+ const expectedType = isTurn ? "relay" : "srflx";+ const startedAt = performance.now();++ const result = {+ url,+ kind: isTurn ? "turn" : "stun",+ reachable: false,+ candidates: emptyCandidateCounts(),+ // The public (srflx) or relay addresses the server handed back.+ addresses: [],+ errors: [],+ timedOut: false,+ durationMs: null,+ };++ let pc;+ try {+ pc = new RTCPeerConnection({+ iceServers: [+ {+ urls: url,+ username: server.username,+ credential: server.credential,+ },+ ],+ });+ } catch (error) {+ result.errors.push({ errorText: String(error?.message) });+ return result;+ }++ try {+ await new Promise((resolve) => {+ const timer = setTimeout(() => {+ result.timedOut = true;+ resolve();+ }, timeoutMs);++ pc.onicecandidate = (event) => {+ const type = event.candidate?.type;+ if (type && type in result.candidates) {+ result.candidates[type]++;+ const address = event.candidate.address;+ if (+ type === expectedType &&+ address &&+ !result.addresses.includes(address)+ ) {+ result.addresses.push(address);+ }+ if (type === expectedType && !result.reachable) {+ result.reachable = true;+ result.durationMs = Math.round(performance.now() - startedAt);+ }+ }+ if (!event.candidate) {+ clearTimeout(timer);+ resolve();+ }+ };+ pc.onicecandidateerror = (event) => {+ result.errors.push({+ errorCode: event.errorCode,+ errorText: event.errorText,+ });+ };++ pc.createDataChannel("diagnostics");+ pc.createOffer()+ .then((offer) => pc.setLocalDescription(offer))+ .catch((error) => {+ result.errors.push({ errorText: String(error?.message) });+ clearTimeout(timer);+ resolve();+ });+ });+ } finally {+ pc.onicecandidate = null;+ pc.onicecandidateerror = null;+ pc.close();+ }++ return result;+}++/**+ * Probes every configured STUN/TURN URL in parallel.+ *+ * @param {RTCIceServer[]} iceServers+ * @param {{timeoutMs?: number}} [options]+ */+export function probeIceServers(iceServers, options = {}) {+ return Promise.all(+ iceServerUrls(iceServers).map(({ url, server }) =>+ probeIceServer(url, server, options)+ )+ );+}++/**+ * Builds per-participant diagnostics for a mesh room.+ *+ * @param {object} params+ * @param {object} params.room - Room with `active_participants`.+ * @param {number} params.currentUserId+ * @param {import("./peer-manager.js").default} params.peerManager+ * @param {(userId: number) => boolean} params.shouldMaintainPeer+ */+export async function collectPeers({+ room,+ currentUserId,+ peerManager,+ shouldMaintainPeer,+}) {+ const participants = new Map();+ for (const participant of room?.active_participants || []) {+ const id = Number(participant?.id);+ if (id > 0 && id !== currentUserId) {+ participants.set(id, participant);+ }+ }++ // A connection to someone no longer in the roster is itself a symptom.+ for (const [userId] of peerManager.getRoomPeers(room?.id) || []) {+ if (!participants.has(Number(userId))) {+ participants.set(Number(userId), { id: userId });+ }+ }++ return Promise.all(+ Array.from(participants.values()).map(async (participant) => {+ const userId = Number(participant.id);+ const pc = peerManager.get(room.id, userId);+ return {+ userId,+ username: participant.username,+ name: participant.name,+ avatarTemplate: participant.avatar_template,+ inRoster: !!participant.username,+ expected: shouldMaintainPeer(userId),+ recovery: peerManager.diagnosticsFor(room.id, userId),+ connection: pc ? await collectPeerConnection(pc) : null,+ };+ })+ );+}++export function formatBitrate(bps) {+ if (typeof bps !== "number") {+ return "?";+ }+ return bps >= 1e6+ ? `${(bps / 1e6).toFixed(2)} Mbps`+ : `${Math.round(bps / 1e3)} kbps`;+}++export function formatRtt(seconds) {+ return typeof seconds === "number" ? `${Math.round(seconds * 1000)} ms` : "?";+}++function formatCandidate(candidate) {+ if (!candidate) {+ return "?";+ }+ return [+ candidate.address &&+ (candidate.port+ ? `${candidate.address}:${candidate.port}`+ : candidate.address),+ candidate.type,+ candidate.protocol,+ candidate.relayProtocol && `relay over ${candidate.relayProtocol}`,+ candidate.networkType,+ candidate.url,+ ]+ .filter(Boolean)+ .join(" / ");+}++export function formatCandidateCounts(counts) {+ return CANDIDATE_TYPES.map((type) => `${type}=${counts?.[type] ?? 0}`).join(+ " "+ );+}++/**+ * Renders collected diagnostics as plain text for copying into a bug report.+ * Intentionally untranslated so reports read the same for whoever triages.+ */+export function formatReport({+ room,+ transport,+ iceTransportPolicy,+ local,+ probes,+ peers,+ collectedAt,+}) {+ const lines = [];+ const push = (line = "") => lines.push(line);++ push("Live connection diagnostics");+ push(`Collected: ${new Date(collectedAt).toISOString()}`);+ push(`Room: ${room?.id} (${transport}, ${room?.room_type || "open"})`);+ push(`ICE transport policy: ${iceTransportPolicy}`);+ push();++ push("== This device ==");+ push(`User agent: ${local.userAgent}`);+ push(`Platform: ${local.platform}`);+ push(`Online: ${local.online} Secure context: ${local.secureContext}`);+ push(+ `CPU cores: ${local.hardwareConcurrency ?? "?"} Memory: ${local.deviceMemory ?? "?"} GB`+ );+ if (local.connection) {+ const c = local.connection;+ push(+ `Network: type=${c.type ?? "?"} effective=${c.effectiveType ?? "?"} downlink=${c.downlink ?? "?"}Mbps rtt=${c.rtt ?? "?"}ms saveData=${c.saveData ?? "?"}`+ );+ }+ for (const track of local.localTracks) {+ push(+ `Local ${track.kind}: "${track.label}" enabled=${track.enabled} muted=${track.muted} state=${track.readyState}`+ );+ }+ push();++ push("== STUN/TURN servers ==");+ if (!probes) {+ push("(probe not run)");+ } else if (!probes.length) {+ push("(none configured)");+ }+ for (const probe of probes || []) {+ const status = probe.reachable+ ? `OK in ${probe.durationMs} ms`+ : probe.timedOut+ ? "NO RESPONSE (timed out)"+ : "FAILED";+ push(`${probe.url}: ${status}`);+ push(` candidates: ${formatCandidateCounts(probe.candidates)}`);+ if (probe.addresses?.length) {+ push(` addresses: ${probe.addresses.join(", ")}`);+ }+ for (const error of probe.errors) {+ push(` error: ${error.errorCode ?? ""} ${error.errorText ?? ""}`.trim());+ }+ }+ push();++ push(`== Peers (${peers.length}) ==`);+ for (const peer of peers) {+ push(+ `-- ${peer.username || `user ${peer.userId}`} (id ${peer.userId})${peer.inRoster ? "" : " [not in roster]"}`+ );+ const recovery = peer.recovery;+ push(+ ` restarts: ${recovery.restartAttempts}/${recovery.maxRestartAttempts}${recovery.restartScheduled ? " (restart pending)" : ""} offer retries: ${recovery.offerRetryAttempts}/${recovery.maxOfferRetries} queued candidates: ${recovery.pendingCandidates}`+ );+ for (const error of recovery.iceCandidateErrors) {+ push(+ ` ICE error: ${error.url ?? "?"} ${error.errorCode ?? ""} ${error.errorText ?? ""}`.trimEnd()+ );+ }++ const connection = peer.connection;+ if (!connection) {+ push(+ peer.expected+ ? " NO PEER CONNECTION (expected one)"+ : " no peer connection (not expected in this room)"+ );+ continue;+ }++ push(+ ` state: connection=${connection.connectionState} ice=${connection.iceConnectionState} gathering=${connection.iceGatheringState} signaling=${connection.signalingState}`+ );+ const stats = connection.stats;+ if (!stats) {+ push(` stats unavailable: ${connection.statsError}`);+ continue;+ }+ push(` route: ${stats.route}`);+ if (stats.selectedPair) {+ const pair = stats.selectedPair;+ push(` local candidate: ${formatCandidate(pair.local)}`);+ push(` remote candidate: ${formatCandidate(pair.remote)}`);+ push(+ ` rtt: ${formatRtt(pair.currentRoundTripTime)} out bitrate: ${formatBitrate(pair.availableOutgoingBitrate)} sent: ${pair.bytesSent ?? "?"} B received: ${pair.bytesReceived ?? "?"} B`+ );+ } else {+ push(" no selected candidate pair");+ }+ push(+ ` candidate pairs: total=${stats.candidatePairs.total} succeeded=${stats.candidatePairs.succeeded} failed=${stats.candidatePairs.failed} in-progress=${stats.candidatePairs.inProgress}`+ );+ push(` local candidates: ${formatCandidateCounts(stats.localCandidates)}`);+ push(+ ` remote candidates: ${formatCandidateCounts(stats.remoteCandidates)}`+ );+ if (stats.transport) {+ const t = stats.transport;+ push(+ ` dtls: ${t.dtlsState ?? "?"} ice role: ${t.iceRole ?? "?"} tls: ${t.tlsVersion ?? "?"} srtp: ${t.srtpCipher ?? "?"}`+ );+ }+ for (const entry of stats.inbound) {+ push(+ ` in ${entry.kind} ${entry.codec ?? ""}: packets=${entry.packetsReceived} lost=${entry.packetsLost ?? "?"} jitter=${entry.jitter ?? "?"}${entry.frameWidth ? ` ${entry.frameWidth}x${entry.frameHeight}@${entry.framesPerSecond ?? "?"}` : ""}`+ );+ }+ for (const entry of stats.outbound) {+ push(+ ` out ${entry.kind} ${entry.codec ?? ""}: packets=${entry.packetsSent}${entry.qualityLimitationReason ? ` limited=${entry.qualityLimitationReason}` : ""}${entry.frameWidth ? ` ${entry.frameWidth}x${entry.frameHeight}@${entry.framesPerSecond ?? "?"}` : ""}`+ );+ }+ }++ return lines.join("\n");+}diff --git a/plugins/live/assets/javascripts/discourse/lib/live/peer-manager.js b/plugins/live/assets/javascripts/discourse/lib/live/peer-manager.jsindex ce388feeabc..fe618d3abf7 100644--- a/plugins/live/assets/javascripts/discourse/lib/live/peer-manager.js+++ b/plugins/live/assets/javascripts/discourse/lib/live/peer-manager.js@@ -6,6 +6,12 @@ import liveLog from "discourse/plugins/live/discourse/lib/live/logger";// order at every lookup.const screenAudioTransceivers = new WeakMap();+// Recent ICE candidate errors per connection, kept for connection diagnostics:+// they are the only signal that a STUN/TURN server rejected or never answered+// this peer's allocation.+const iceCandidateErrors = new WeakMap();+const MAX_ICE_CANDIDATE_ERRORS = 10;+const DEFAULT_TIMING = {offerRetryBaseDelayMs: 400,maxOfferRetryDelayMs: 5000,@@ -237,6 +243,23 @@ export default class PeerManager {return PeerManager.screenAudioTransceiverFor(pc)?.receiver?.track || null;}+ // Recovery bookkeeping for one peer, so diagnostics can tell a peer that is+ // still retrying from one that exhausted its restarts and gave up.+ diagnosticsFor(roomId, remoteUserId) {+ const key = PeerManager.peerKey(roomId, remoteUserId);+ const pc = this.get(roomId, remoteUserId);++ return {+ restartAttempts: this.#restartAttempts.get(key) || 0,+ maxRestartAttempts: PeerManager.#maxRestartAttempts,+ restartScheduled: this.#peerReconnectTimers.has(key),+ offerRetryAttempts: this.#offerRetryAttempts.get(key) || 0,+ maxOfferRetries: PeerManager.#maxOfferRetries,+ pendingCandidates: this.#pendingCandidates.get(key)?.length || 0,+ iceCandidateErrors: (pc && iceCandidateErrors.get(pc)) || [],+ };+ }+allPeerConnections() {return this.#peerConnections;}@@ -367,8 +390,16 @@ export default class PeerManager {}};- pc.onicecandidateerror = () => {+ pc.onicecandidateerror = (event) => {liveLog.warn("[live] ICE candidate error for peer");+ const errors = iceCandidateErrors.get(pc) || [];+ errors.push({+ url: event.url,+ errorCode: event.errorCode,+ errorText: event.errorText,+ at: Date.now(),+ });+ iceCandidateErrors.set(pc, errors.slice(-MAX_ICE_CANDIDATE_ERRORS));};pc.onconnectionstatechange = () => {diff --git a/plugins/live/assets/stylesheets/common/live.scss b/plugins/live/assets/stylesheets/common/live.scssindex 6145f1d409e..5c107c80446 100644--- a/plugins/live/assets/stylesheets/common/live.scss+++ b/plugins/live/assets/stylesheets/common/live.scss@@ -1330,3 +1330,151 @@}}}++.live-connection-diagnostics {+ &__summary {+ margin-top: 0;+ font-weight: 600;+ }++ &__note {+ font-weight: normal;+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ }++ &__section {+ margin-bottom: 1.5rem;++ h3 {+ font-size: var(--font-0);+ margin-bottom: 0.5rem;+ }+ }++ &__peer {+ border: 1px solid var(--primary-low);+ border-left-width: 4px;+ border-radius: var(--d-border-radius);+ padding: 0.75rem;+ margin-bottom: 0.5rem;++ &.--connected {+ border-left-color: var(--success);+ }++ &.--connecting {+ border-left-color: var(--highlight);+ }++ &.--failed,+ &.--missing {+ border-left-color: var(--danger);+ }+ }++ &__peer-header {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex-wrap: wrap;+ }++ &__peer-name {+ font-weight: 600;+ }++ &__badge {+ margin-left: auto;+ padding: 0.1rem 0.5rem;+ border-radius: 1em;+ font-size: var(--font-down-1);+ background: var(--primary-very-low);+ color: var(--primary-high);++ &.--connected,+ &.--ok {+ background: var(--success-low);+ color: var(--success);+ }++ &.--failed,+ &.--missing,+ &.--timeout {+ background: var(--danger-low);+ color: var(--danger);+ }+ }++ &__route {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin-top: 0.5rem;++ &.--relayed {+ color: var(--tertiary);+ }+ }++ &__details {+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 0.2rem 1rem;+ margin: 0.5rem 0 0;+ font-size: var(--font-down-1);++ dt {+ color: var(--primary-medium);+ }++ dd {+ margin: 0;+ overflow-wrap: anywhere;+ }+ }++ &__errors {+ margin: 0.5rem 0 0;+ padding-left: 1.25rem;+ font-size: var(--font-down-1);+ color: var(--danger);+ overflow-wrap: anywhere;+ }++ &__server {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.5rem;+ padding: 0.4rem 0;+ border-bottom: 1px solid var(--primary-very-low);++ code {+ overflow-wrap: anywhere;+ }++ .live-connection-diagnostics__errors {+ flex-basis: 100%;+ }+ }++ &__server-addresses {+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ overflow-wrap: anywhere;+ }++ &__privacy {+ flex-basis: 100%;+ margin: 0 0 0.5rem;+ font-size: var(--font-down-1);+ color: var(--primary-medium);+ }++ &__server-kind {+ font-size: var(--font-down-2);+ font-weight: 600;+ color: var(--primary-medium);+ }+}diff --git a/plugins/live/config/locales/client.en.yml b/plugins/live/config/locales/client.en.ymlindex 34decb3e699..ee75076dc4c 100644--- a/plugins/live/config/locales/client.en.yml+++ b/plugins/live/config/locales/client.en.yml@@ -285,6 +285,70 @@ en:ignore:title: "Ignore flag"description: "Remove the flag from the queue without taking action."+ connection_diagnostics:+ menu: "Connection diagnostics"+ title: "Connection diagnostics"+ summary: "Connected to %{connected} of %{total} peers."+ relay_only: "This site only allows relayed (TURN) connections."+ peers: "Peers"+ servers: "STUN/TURN servers"+ this_device: "This device"+ no_peers: "No one else is in this room."+ no_servers: "No STUN/TURN servers are configured."+ probing: "Checking servers…"+ not_in_roster: "Not in room roster"+ unknown_user: "User %{id}"+ local_candidate: "Your side"+ remote_candidate: "Their side"+ via_server: "Through server"+ rtt: "Round-trip time"+ bitrate: "Available upload"+ candidate_pairs: "Candidate pairs"+ candidate_pairs_value: "%{total} total, %{succeeded} succeeded, %{failed} failed"+ local_candidates: "Your candidates"+ remote_candidates: "Their candidates"+ restarts: "Reconnect attempts"+ restarts_value: "%{count} of %{max}"+ gave_up: "Stopped retrying"+ relay_over: "relay over %{protocol}"+ copy_report: "Copy report"+ privacy_note: "This report includes your IP addresses and those of other participants. Only share it with staff."+ copied: "Diagnostics report copied to clipboard"+ refresh: "Refresh"+ answer_yes: "Yes"+ answer_no: "No"+ disabled: "disabled"+ no_signal: "no signal"+ status:+ connected: "Connected"+ connecting: "Connecting"+ failed: "Failed"+ missing: "No connection"+ not_needed: "Not needed"+ route:+ host: "Direct (same network)"+ stun: "Direct (through NAT via STUN)"+ relay-local: "Relayed through TURN (your side)"+ relay-remote: "Relayed through TURN (their side)"+ relay-both: "Relayed through TURN (both sides)"+ unknown: "Not established"+ states:+ connection: "Connection"+ ice: "ICE"+ gathering: "ICE gathering"+ signaling: "Signaling"+ probe:+ ok: "Reachable (%{ms} ms)"+ timeout: "No response"+ failed: "Unreachable"+ local:+ browser: "Browser"+ platform: "Platform"+ online: "Online"+ cpu_cores: "CPU cores"+ network: "Network"+ microphone: "Microphone"+ camera: "Camera"room_info:title: "Room Info"status: "Status"diff --git a/plugins/live/plugin.rb b/plugins/live/plugin.rbindex 7e5564f58a9..d890ce13a4e 100644--- a/plugins/live/plugin.rb+++ b/plugins/live/plugin.rb@@ -89,6 +89,10 @@ register_svg_icon "copy"register_svg_icon "closed-captioning"register_svg_icon "stop"register_svg_icon "far-file-lines"+register_svg_icon "stethoscope"+register_svg_icon "network-wired"+register_svg_icon "arrow-right-arrow-left"+register_svg_icon "server"register_asset "stylesheets/common/live.scss"register_asset "stylesheets/common/live-room-page.scss"register_asset "stylesheets/common/live-chat.scss"diff --git a/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs b/plugins/live/test/javascripts/integration/components/live-room-page-test.gjsindex c6df74b16a6..c3f45702fc0 100644--- a/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs+++ b/plugins/live/test/javascripts/integration/components/live-room-page-test.gjs@@ -36,6 +36,10 @@ class LiveWebrtcStub extends Service {return "connected";}+ canDiagnoseConnection() {+ return false;+ }+videoAllowedIn() {return true;}diff --git a/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs b/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjsindex 0a7b93fb201..9ecd4437a94 100644--- a/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs+++ b/plugins/live/test/javascripts/integration/components/live/call-widget-test.gjs@@ -71,6 +71,10 @@ class LiveWebrtcStub extends Service {return "connected";}+ canDiagnoseConnection() {+ return false;+ }+isTranscribingRoom() {return false;}diff --git a/plugins/live/test/javascripts/unit/lib/connection-diagnostics-test.js b/plugins/live/test/javascripts/unit/lib/connection-diagnostics-test.jsnew file mode 100644index 00000000000..b089d4b642b--- /dev/null+++ b/plugins/live/test/javascripts/unit/lib/connection-diagnostics-test.js@@ -0,0 +1,229 @@+import { module, test } from "qunit";+import {+ collectPeers,+ formatReport,+ routeFor,+ summarizeStats,+} from "discourse/plugins/live/discourse/lib/live/connection-diagnostics";++function statsReport(entries) {+ return new Map(entries.map((entry) => [entry.id, entry]));+}++const RELAYED_REPORT = statsReport([+ {+ id: "T1",+ type: "transport",+ selectedCandidatePairId: "CP1",+ dtlsState: "connected",+ iceRole: "controlling",+ },+ {+ id: "CP1",+ type: "candidate-pair",+ state: "succeeded",+ nominated: true,+ localCandidateId: "L1",+ remoteCandidateId: "R1",+ currentRoundTripTime: 0.042,+ availableOutgoingBitrate: 1_500_000,+ },+ {+ id: "CP2",+ type: "candidate-pair",+ state: "failed",+ localCandidateId: "L2",+ remoteCandidateId: "R1",+ },+ {+ id: "L1",+ type: "local-candidate",+ candidateType: "relay",+ protocol: "udp",+ relayProtocol: "tls",+ url: "turns:turn.example.com:443",+ address: "203.0.113.5",+ },+ { id: "L2", type: "local-candidate", candidateType: "host", protocol: "udp" },+ {+ id: "R1",+ type: "remote-candidate",+ candidateType: "srflx",+ protocol: "udp",+ address: "198.51.100.7",+ },+ { id: "C1", type: "codec", mimeType: "audio/opus" },+ {+ id: "IN1",+ type: "inbound-rtp",+ kind: "audio",+ codecId: "C1",+ packetsReceived: 100,+ packetsLost: 2,+ },+ { id: "IN2", type: "inbound-rtp", kind: "video", packetsReceived: 0 },+]);++module("Live | Unit | Lib | connection-diagnostics", function () {+ test("routeFor classifies the media path", function (assert) {+ assert.strictEqual(routeFor({ type: "host" }, { type: "host" }), "host");+ assert.strictEqual(routeFor({ type: "srflx" }, { type: "host" }), "stun");+ assert.strictEqual(+ routeFor({ type: "relay" }, { type: "srflx" }),+ "relay-local"+ );+ assert.strictEqual(+ routeFor({ type: "host" }, { type: "relay" }),+ "relay-remote"+ );+ assert.strictEqual(+ routeFor({ type: "relay" }, { type: "relay" }),+ "relay-both"+ );+ assert.strictEqual(routeFor(null, null), "unknown");+ });++ test("summarizeStats follows the transport's selected pair", function (assert) {+ const summary = summarizeStats(RELAYED_REPORT);++ assert.strictEqual(summary.route, "relay-local");+ assert.deepEqual(summary.selectedPair.local, {+ type: "relay",+ address: "203.0.113.5",+ port: undefined,+ protocol: "udp",+ relayProtocol: "tls",+ url: "turns:turn.example.com:443",+ networkType: undefined,+ });+ assert.strictEqual(summary.selectedPair.currentRoundTripTime, 0.042);+ assert.deepEqual(summary.candidatePairs, {+ total: 2,+ succeeded: 1,+ failed: 1,+ inProgress: 0,+ });+ assert.strictEqual(summary.localCandidates.relay, 1);+ assert.strictEqual(summary.localCandidates.host, 1);+ assert.strictEqual(summary.remoteCandidates.srflx, 1);+ assert.strictEqual(summary.transport.dtlsState, "connected");+ assert.strictEqual(summary.inbound.length, 1, "drops idle m-lines");+ assert.strictEqual(summary.inbound[0].codec, "opus");+ });++ test("summarizeStats falls back to the nominated succeeded pair", function (assert) {+ const summary = summarizeStats(+ statsReport([+ {+ id: "CP1",+ type: "candidate-pair",+ state: "succeeded",+ nominated: true,+ localCandidateId: "L1",+ remoteCandidateId: "R1",+ },+ { id: "L1", type: "local-candidate", candidateType: "host" },+ { id: "R1", type: "remote-candidate", candidateType: "host" },+ ])+ );++ assert.strictEqual(summary.route, "host");+ });++ test("summarizeStats reads the legacy ip field when address is missing", function (assert) {+ const summary = summarizeStats(+ statsReport([+ {+ id: "CP1",+ type: "candidate-pair",+ selected: true,+ localCandidateId: "L1",+ remoteCandidateId: "R1",+ },+ {+ id: "L1",+ type: "local-candidate",+ candidateType: "host",+ ip: "192.0.2.10",+ port: 50000,+ },+ { id: "R1", type: "remote-candidate", candidateType: "host" },+ ])+ );++ assert.strictEqual(summary.selectedPair.local.address, "192.0.2.10");+ assert.strictEqual(summary.selectedPair.local.port, 50000);+ });++ test("collectPeers flags expected peers that have no connection", async function (assert) {+ const pc = {+ connectionState: "connected",+ iceConnectionState: "connected",+ iceGatheringState: "complete",+ signalingState: "stable",+ getStats: async () => RELAYED_REPORT,+ };+ const peerManager = {+ get: (roomId, userId) => (userId === 2 ? pc : undefined),+ getRoomPeers: () => new Map([[2, pc]]),+ diagnosticsFor: () => ({+ restartAttempts: 0,+ maxRestartAttempts: 5,+ restartScheduled: false,+ offerRetryAttempts: 0,+ maxOfferRetries: 8,+ pendingCandidates: 0,+ iceCandidateErrors: [],+ }),+ };++ const peers = await collectPeers({+ room: {+ id: 1,+ active_participants: [+ { id: 1, username: "me" },+ { id: 2, username: "alice" },+ { id: 3, username: "bob" },+ ],+ },+ currentUserId: 1,+ peerManager,+ shouldMaintainPeer: () => true,+ });++ assert.deepEqual(+ peers.map((peer) => peer.username),+ ["alice", "bob"]+ );+ assert.strictEqual(peers[0].connection.stats.route, "relay-local");+ assert.strictEqual(peers[1].connection, null);+ assert.true(peers[1].expected);++ const report = formatReport({+ room: { id: 1, room_type: "open" },+ transport: "mesh",+ iceTransportPolicy: "all",+ local: { localTracks: [] },+ probes: [+ {+ url: "stun:stun.example.com:3478",+ reachable: false,+ timedOut: true,+ candidates: {},+ addresses: [],+ errors: [{ errorCode: 701, errorText: "STUN timeout" }],+ },+ ],+ peers,+ collectedAt: 0,+ });++ assert.true(report.includes("route: relay-local"));+ assert.true(report.includes("turns:turn.example.com:443"));+ assert.true(report.includes("203.0.113.5"), "includes local address");+ assert.true(report.includes("198.51.100.7"), "includes remote address");+ assert.true(report.includes("NO PEER CONNECTION (expected one)"));+ assert.true(report.includes("stun:stun.example.com:3478: NO RESPONSE"));+ assert.true(report.includes("701 STUN timeout"));+ });+});diff --git a/plugins/live/test/javascripts/unit/lib/peer-manager-test.js b/plugins/live/test/javascripts/unit/lib/peer-manager-test.jsindex 670a2cc1501..42513319bd8 100644--- a/plugins/live/test/javascripts/unit/lib/peer-manager-test.js+++ b/plugins/live/test/javascripts/unit/lib/peer-manager-test.js@@ -263,4 +263,36 @@ module("Live | Unit | Lib | peer-manager", function (hooks) {"keeps the pre-allocated transceiver as the screen audio slot");});++ test("diagnosticsFor reports ICE candidate errors for the current connection", async function (assert) {+ const manager = (this.manager = new PeerManager({+ getIceServers: () => [],+ getLocalStream: () => null,+ sendSignal: () => Promise.resolve(),+ flushQueuedSignals: () => Promise.resolve(),+ onTrack: () => {},+ clearSignalQueue: () => {},+ onPeerDestroyed: () => {},+ }));++ const pc = await manager.create(1, 2);+ pc.onicecandidateerror({+ url: "turn:turn.example.com:3478",+ errorCode: 401,+ errorText: "Unauthorized",+ });+ manager.queuePendingCandidate(1, 2, { candidate: "x" });++ const diagnostics = manager.diagnosticsFor(1, 2);++ assert.strictEqual(diagnostics.restartAttempts, 0);+ assert.strictEqual(diagnostics.pendingCandidates, 1);+ assert.strictEqual(diagnostics.iceCandidateErrors.length, 1);+ assert.strictEqual(diagnostics.iceCandidateErrors[0].errorCode, 401);+ assert.deepEqual(+ manager.diagnosticsFor(1, 3).iceCandidateErrors,+ [],+ "a peer without a connection has no errors"+ );+ });});