Skip to content

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

DEV: Add voice_verbose_logging setting (#43488)

Penar Musarajae80cc6f81a3
diff --git a/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb b/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb
index d4bd3c14e40..01ba227856b 100644
--- a/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb
+++ b/plugins/voice/app/controllers/voice/livekit_webhooks_controller.rb
@@ -23,8 +23,8 @@ module Voice
authorization: request.headers["Authorization"],
body: body,
)
- rescue Livekit::WebhookVerifier::VerificationError => e
- Rails.logger.warn("[voice-livekit] rejected webhook: #{e.message}")
+ rescue Livekit::WebhookVerifier::VerificationError
+ Voice.warn("[voice-livekit] rejected webhook: verification failed")
return head :forbidden
end
diff --git a/plugins/voice/app/controllers/voice/rooms_controller.rb b/plugins/voice/app/controllers/voice/rooms_controller.rb
index 68f1ad61a5d..5cd734b9894 100644
--- a/plugins/voice/app/controllers/voice/rooms_controller.rb
+++ b/plugins/voice/app/controllers/voice/rooms_controller.rb
@@ -734,9 +734,7 @@ module Voice
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}",
- )
+ Rails.logger.error("[voice-livekit] token mint failed for room #{@room.id}: #{e.class}")
nil
end
diff --git a/plugins/voice/app/jobs/regular/voice_livekit_probe.rb b/plugins/voice/app/jobs/regular/voice_livekit_probe.rb
index eff3cdbbca8..2a8cc3a3b19 100644
--- a/plugins/voice/app/jobs/regular/voice_livekit_probe.rb
+++ b/plugins/voice/app/jobs/regular/voice_livekit_probe.rb
@@ -18,10 +18,7 @@ module Jobs
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
+ ::Voice.warn("[voice-livekit] connectivity probe failed") if !result[:ok]
end
end
end
diff --git a/plugins/voice/app/services/voice/chat_session.rb b/plugins/voice/app/services/voice/chat_session.rb
index 75662b61829..38300c938f5 100644
--- a/plugins/voice/app/services/voice/chat_session.rb
+++ b/plugins/voice/app/services/voice/chat_session.rb
@@ -244,9 +244,7 @@ module Voice
def raise_unless_chat_success(result)
return if result.success?
- Rails.logger.warn(
- "[voice] chat operation failed: #{Service::StepsInspector.new(result).inspect}",
- )
+ Voice.warn("[voice] chat operation failed")
raise Error, chat_failure_message(result)
end
diff --git a/plugins/voice/app/services/voice/recording_manager.rb b/plugins/voice/app/services/voice/recording_manager.rb
index 120d6be9c91..4c3081b815e 100644
--- a/plugins/voice/app/services/voice/recording_manager.rb
+++ b/plugins/voice/app/services/voice/recording_manager.rb
@@ -194,9 +194,9 @@ module Voice
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.warn(
"[voice-livekit] recording PM failed for recording #{recording.id}: " \
- "#{e.class} #{e.message}",
+ "#{e.class}",
)
end
diff --git a/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js b/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js
index 3ec9184e919..83b5c4777a1 100644
--- a/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js
+++ b/plugins/voice/assets/javascripts/discourse/app/services/voice-webrtc.js
@@ -6,6 +6,7 @@ import { ajax } from "discourse/lib/ajax";
import { manuallyTrack } from "discourse/lib/tracked-tools";
import Draft from "discourse/models/draft";
import { i18n } from "discourse-i18n";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import { confirmMeshPrivacy } from "../../components/modal/voice-mesh-privacy-warning";
import { reportMicAcquisitionFailure } from "../../components/modal/voice-mic-permission";
import AudioMonitor from "../../lib/voice/audio-monitor";
@@ -728,8 +729,7 @@ export default class VoiceWebrtcService extends Service {
}
}
- // eslint-disable-next-line no-console
- console.log(`[voice] joining room ${room.id}`);
+ voiceLog.info(`[voice] joining room ${room.id}`);
this.#registerRoomHandler(room.id);
@@ -757,9 +757,8 @@ export default class VoiceWebrtcService extends Service {
type: "POST",
data: joinData,
});
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to join room", error);
+ } catch {
+ voiceLog.warn("[voice] failed to join room");
this.#handleJoinFailure(room.id);
return;
}
@@ -772,11 +771,7 @@ export default class VoiceWebrtcService extends Service {
return;
}
- // eslint-disable-next-line no-console
- console.log(
- `[voice] join response, active_participants:`,
- response?.room?.active_participants
- );
+ voiceLog.info("[voice] join response received");
this.#roomTransports.set(room.id, response?.transport ?? "mesh");
if (response?.participant_session_id) {
@@ -1011,16 +1006,14 @@ export default class VoiceWebrtcService extends Service {
if (error?.name === "NotAllowedError") {
schedulePlaybackResume(element, this.#pendingPlaybackElements);
} else {
- // eslint-disable-next-line no-console
- console.warn("[voice] audio element failed to play", error);
+ voiceLog.warn("[voice] audio element failed to play");
}
});
} 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);
+ voiceLog.warn("[voice] audio element failed to play");
}
}
}
@@ -1272,9 +1265,8 @@ export default class VoiceWebrtcService extends Service {
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);
+ this.#localVideo.stop({ broadcast: false }).catch(() => {
+ voiceLog.warn("[voice] failed to stop video on page leave");
});
}
@@ -1479,9 +1471,8 @@ export default class VoiceWebrtcService extends Service {
this.#cameraPreferred(userId) &&
this.canPublishVideo(roomId),
})
- .catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to restore preferred camera state", error);
+ .catch(() => {
+ voiceLog.warn("[voice] failed to restore preferred camera state");
});
this.#cameraRestorePromise = restorePromise;
@@ -1652,16 +1643,14 @@ export default class VoiceWebrtcService extends Service {
}
return this.#processRoomMessage(roomId, payload);
})
- .catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to process room message", error);
+ .catch(() => {
+ voiceLog.warn("[voice] failed to process room message");
});
}
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)}`
+ voiceLog.info(
+ `[voice] πŸ“¨ MessageBus message: room=${roomId}, active=${this.#activeRoomIds.has(roomId)}`
);
if (!this.#activeRoomIds.has(roomId)) {
@@ -1710,8 +1699,7 @@ export default class VoiceWebrtcService extends Service {
}
#handleKicked(roomId) {
- // eslint-disable-next-line no-console
- console.log(`[voice] kicked from room ${roomId}`);
+ voiceLog.info(`[voice] kicked from room ${roomId}`);
this.leave({ id: roomId });
}
@@ -1762,9 +1750,8 @@ export default class VoiceWebrtcService extends Service {
#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}`
+ voiceLog.warn(
+ `[voice] dropping ${track?.kind} track from peer: not allowed to publish in room ${roomId}`
);
try {
track?.stop();
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js
index 4f3713f5888..3473d84d8b3 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/audio-monitor.js
@@ -1,3 +1,5 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
+
const SAMPLE_INTERVAL_MS = 100;
const FFT_SIZE = 2048;
@@ -83,9 +85,8 @@ export default class AudioMonitor {
});
this.#startSampling();
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to initialize audio monitor", error);
+ } catch {
+ voiceLog.warn("[voice] failed to initialize audio monitor");
}
}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js b/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js
index 407854fed0a..c9946cbf25b 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/background-blur.js
@@ -1,3 +1,4 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
// Camera background blur.
//
// Runs the raw camera stream through MediaPipe selfie segmentation and
@@ -5,7 +6,6 @@
// 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";
@@ -256,9 +256,8 @@ export default class BackgroundBlurManager {
try {
this.#renderFrame();
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] background blur frame failed", error);
+ } catch {
+ voiceLog.warn("[voice] background blur frame failed");
}
this.#scheduleRender();
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js
index 75c4dc91152..026781ada2e 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/heartbeat-manager.js
@@ -1,4 +1,5 @@
import { ajax } from "discourse/lib/ajax";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
const HEARTBEAT_INTERVAL_MS = 10000;
@@ -34,8 +35,8 @@ export default class HeartbeatManager {
clearInterval(timer);
this.#timers.delete(roomId);
this.#inFlight.delete(roomId);
- // eslint-disable-next-line no-console
- console.log(`[voice] heartbeat stopped for room ${roomId}`);
+
+ voiceLog.info(`[voice] heartbeat stopped for room ${roomId}`);
}
}
@@ -62,12 +63,12 @@ export default class HeartbeatManager {
type: "POST",
data: this.#buildPayload(roomId),
});
- // eslint-disable-next-line no-console
- console.log(`[voice] heartbeat sent for room ${roomId}`);
+
+ voiceLog.info(`[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);
+
+ voiceLog.warn(`[voice] heartbeat failed for room ${roomId}`);
if (status === 403 || status === 404 || status === 410) {
this.#onExpelled(roomId);
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js
index e2576ea1557..46bca3b73ba 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-coordinator.js
@@ -1,4 +1,5 @@
import { ajax } from "discourse/lib/ajax";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import LivekitRoomSession from "./livekit-session";
// Owns the livekit sessions for SFU-transport rooms: connecting on join,
@@ -115,10 +116,8 @@ export default class LivekitCoordinator {
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
+ voiceLog.warn(
+ `[voice-livekit] failed to connect to the media server for room ${room.id}`
);
failureMessage = error?.unsupportedBrowser
? "voice.livekit.browser_unsupported"
@@ -222,11 +221,9 @@ export default class LivekitCoordinator {
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
+ } catch {
+ voiceLog.warn(
+ `[voice-livekit] failed to replace the published audio track for room ${roomId}`
);
}
}
@@ -269,8 +266,7 @@ export default class LivekitCoordinator {
return;
}
- // eslint-disable-next-line no-console
- console.warn(
+ voiceLog.warn(
`[voice-livekit] disconnected from the media server for room ${roomId} (${reason})`
);
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js
index 0ec4c89a45a..6cf9830030d 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/livekit-session.js
@@ -1,3 +1,4 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
// LiveKit room session.
//
// One instance per active room on the "livekit" transport, owned by the
@@ -6,7 +7,6 @@
// 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,
@@ -341,8 +341,7 @@ export default class LivekitRoomSession {
await this.connect(minted.url, minted.token);
return this.#closed ? "aborted" : "reconnected";
} catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
+ voiceLog.warn(
`[voice-livekit] reconnect attempt failed for room ${this.#roomId}`,
error
);
@@ -414,8 +413,7 @@ export default class LivekitRoomSession {
);
this.#videoKind = kind;
} catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
+ voiceLog.warn(
`[voice-livekit] failed to publish ${kind} video for room ${this.#roomId}`,
error
);
@@ -442,8 +440,7 @@ export default class LivekitRoomSession {
audioBitrate: SCREEN_AUDIO_BITRATE,
});
} catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
+ voiceLog.warn(
`[voice-livekit] failed to publish screen audio for room ${this.#roomId}`,
error
);
@@ -463,8 +460,7 @@ export default class LivekitRoomSession {
false
);
} catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
+ voiceLog.warn(
`[voice-livekit] failed to unpublish a track for room ${this.#roomId}`,
error
);
@@ -580,8 +576,7 @@ export default class LivekitRoomSession {
// 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(
+ voiceLog.warn(
`[voice-livekit] failed to refresh publications for room ${this.#roomId}`,
error
);
@@ -634,16 +629,14 @@ export default class LivekitRoomSession {
});
room.on(RoomEvent.Reconnecting, () => {
- // eslint-disable-next-line no-console
- console.log(
+ voiceLog.info(
`[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(
+ voiceLog.info(
`[voice-livekit] connection resumed for room ${this.#roomId}`
);
this.#onConnectionChange("connected");
@@ -676,8 +669,8 @@ export default class LivekitRoomSession {
} 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(
+
+ voiceLog.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
index 383f5aaeee1..f84fbf95ce3 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/local-audio-pipeline.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/local-audio-pipeline.js
@@ -1,4 +1,5 @@
import { tracked } from "@glimmer/tracking";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import {
autoGainControlPreferred,
echoCancellationPreferred,
@@ -161,8 +162,8 @@ export default class LocalAudioPipeline {
audio: audioConstraints(this.inputDeviceId),
});
this.lastAcquisitionError = null;
- // eslint-disable-next-line no-console
- console.log("[voice] local stream obtained");
+
+ voiceLog.info("[voice] local stream obtained");
this.#rawStream = rawStream;
@@ -182,8 +183,8 @@ export default class LocalAudioPipeline {
return true;
} catch (error) {
this.lastAcquisitionError = error;
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to obtain local stream", error);
+
+ voiceLog.warn("[voice] failed to obtain local stream");
return false;
}
}
@@ -213,16 +214,15 @@ export default class LocalAudioPipeline {
}
// 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);
+
+ voiceLog.warn("[voice] failed to apply noise suppression mode");
this.noiseSuppressionMode = previousMode;
setPreferredNoiseSuppressionMode(previousMode);
return;
}
if (reacquired) {
- // eslint-disable-next-line no-console
- console.log(`[voice] noise suppression mode: ${mode}`);
+ voiceLog.info(`[voice] noise suppression mode: ${mode}`);
return;
}
@@ -235,8 +235,7 @@ export default class LocalAudioPipeline {
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);
+ voiceLog.warn("[voice] failed to restore previous mode");
}
}
}
@@ -257,8 +256,8 @@ export default class LocalAudioPipeline {
if (error instanceof SupersededError) {
return true;
}
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to switch input device", error);
+
+ voiceLog.warn("[voice] failed to switch input device");
this.inputDeviceId = previousDeviceId;
setPreferredInputDeviceId(previousDeviceId);
return false;
@@ -308,8 +307,8 @@ export default class LocalAudioPipeline {
if (error instanceof SupersededError) {
return;
}
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to apply audio processing change", error);
+
+ voiceLog.warn("[voice] failed to apply audio processing change");
}
}
@@ -333,15 +332,15 @@ export default class LocalAudioPipeline {
});
this.noiseSuppressionState = "on";
this.#setOutgoingStream(suppressed);
- // eslint-disable-next-line no-console
- console.log("[voice] AI noise suppression enabled");
+
+ voiceLog.info("[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);
+
+ voiceLog.warn("[voice] AI noise suppression setup failed");
this.noiseSuppressionState = "off";
this.#setOutgoingStream(rawStream);
return false;
@@ -366,10 +365,9 @@ export default class LocalAudioPipeline {
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
+
+ voiceLog.warn(
+ "[voice] failed to reacquire after suppression breakdown"
);
this.#noiseSuppression.teardown();
this.noiseSuppressionState = "off";
@@ -392,9 +390,8 @@ export default class LocalAudioPipeline {
upstream,
sliderToRms(this.gateThreshold)
);
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to set up input gate", error);
+ } catch {
+ voiceLog.warn("[voice] failed to set up input gate");
stream = upstream;
}
}
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
index 9477fd0fd56..2c29a51b13f 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/local-video-manager.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/local-video-manager.js
@@ -1,6 +1,7 @@
import { tracked } from "@glimmer/tracking";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import BackgroundBlurManager from "./background-blur";
import {
cameraConstraints,
@@ -202,8 +203,7 @@ export default class LocalVideoManager {
});
}
} catch (error) {
- // eslint-disable-next-line no-console
- console.warn(`[voice] failed to obtain ${kind} stream`, error);
+ voiceLog.warn(`[voice] failed to obtain ${kind} stream`);
if (
!silent &&
error?.name !== "NotAllowedError" &&
@@ -364,9 +364,8 @@ export default class LocalVideoManager {
this.#getCameraQuality(roomId)
)
);
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to re-apply camera constraints", error);
+ } catch {
+ voiceLog.warn("[voice] failed to re-apply camera constraints");
}
}
}
@@ -402,12 +401,8 @@ export default class LocalVideoManager {
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
- );
+ } catch {
+ voiceLog.warn("[voice] failed to sync video sender for peer");
}
}
@@ -421,12 +416,8 @@ export default class LocalVideoManager {
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
- );
+ } catch {
+ voiceLog.warn("[voice] failed to sync screen audio sender for peer");
}
}
}
@@ -528,8 +519,7 @@ export default class LocalVideoManager {
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);
+ voiceLog.warn("[voice] failed to switch camera");
this.inputDeviceId = previousDeviceId;
this.#showSwitchError(error);
return false;
@@ -578,8 +568,7 @@ export default class LocalVideoManager {
// 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);
+ voiceLog.warn("[voice] failed to switch camera");
this.inputDeviceId = previousDeviceId;
if (epoch === this.#epoch && this.kind === "camera") {
@@ -681,9 +670,8 @@ export default class LocalVideoManager {
track.contentHint = "motion";
});
return { manager, processed };
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to start background blur", error);
+ } catch {
+ voiceLog.warn("[voice] failed to start background blur");
manager.teardown();
return null;
}
@@ -717,9 +705,8 @@ export default class LocalVideoManager {
this.#onScreenShareEnded?.();
}
})
- .catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to stop local video", error);
+ .catch(() => {
+ voiceLog.warn("[voice] failed to stop local video");
});
}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/logger.js b/plugins/voice/assets/javascripts/discourse/lib/voice/logger.js
new file mode 100644
index 00000000000..291e5cd6942
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/logger.js
@@ -0,0 +1,27 @@
+import { getOwnerWithFallback } from "discourse/lib/get-owner";
+import sanitizeError from "./sanitize-error";
+
+// The diagnostic message must contain only trusted metadata. Error details
+// belong in the optional error argument so they pass through sanitization.
+export default {
+ info(message) {
+ if (
+ getOwnerWithFallback()?.lookup("service:site-settings")
+ ?.voice_verbose_logging
+ ) {
+ // eslint-disable-next-line no-console
+ console.info(message);
+ }
+ },
+
+ warn(message, error) {
+ if (
+ getOwnerWithFallback()?.lookup("service:site-settings")
+ ?.voice_verbose_logging
+ ) {
+ const details = sanitizeError(error);
+ // eslint-disable-next-line no-console
+ console.warn(message, ...(details ? [details] : []));
+ }
+ },
+};
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js b/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js
index a8188224640..1d22e347071 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/media-devices.js
@@ -1,4 +1,5 @@
import { i18n } from "discourse-i18n";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import { processingConstraints } from "./audio-processing";
const INPUT_STORAGE_KEY = "voice_audio_input_device";
@@ -203,8 +204,7 @@ export function applyOutputDevice(element, deviceId) {
return;
}
- element.setSinkId(sinkId).catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to set audio output device", error);
+ element.setSinkId(sinkId).catch(() => {
+ voiceLog.warn("[voice] failed to set audio output device");
});
}
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
index b80fbf9f3dd..5d75556aacb 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/mesh-signal-handler.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/mesh-signal-handler.js
@@ -1,3 +1,4 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import PeerManager from "./peer-manager";
import { iceUfrag } from "./sdp-utils";
import { participantCanSpeak } from "./stage-roles";
@@ -145,10 +146,7 @@ export default class MeshSignalHandler {
return;
}
- // eslint-disable-next-line no-console
- console.log(
- `[voice] πŸ“₯ received ${data.type} from user ${remoteUserId} in room ${roomId}`
- );
+ voiceLog.info(`[voice] πŸ“₯ received signal from peer in room ${roomId}`);
let pc = await this.#peerManager.create(roomId, remoteUserId);
if (!pc) {
return;
@@ -182,9 +180,8 @@ export default class MeshSignalHandler {
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`
+ voiceLog.info(
+ "[voice] remote ICE restart from peer; recreating peer"
);
this.#peerManager.destroy(roomId, remoteUserId);
pc = await this.#peerManager.create(roomId, remoteUserId);
@@ -196,15 +193,13 @@ export default class MeshSignalHandler {
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}`
+ voiceLog.info(
+ "[voice] glare detected, rolling back local offer for peer"
);
await pc.setLocalDescription({ type: "rollback" });
} else {
- // eslint-disable-next-line no-console
- console.log(
- `[voice] glare detected, ignoring remote offer from user ${remoteUserId}`
+ voiceLog.info(
+ "[voice] glare detected, ignoring remote offer from peer"
);
return;
}
@@ -224,26 +219,20 @@ export default class MeshSignalHandler {
);
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);
+ this.#signaling.send(roomId, remoteUserId, answer).catch(() => {
+ voiceLog.warn("[voice] failed to send answer");
});
await this.#onOfferHandled(roomId);
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
- `[voice] failed to handle offer from user ${remoteUserId}`,
- error
- );
+ } catch {
+ voiceLog.warn("[voice] failed to handle offer from peer");
}
} 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}`
+ voiceLog.warn(
+ `[voice] ignoring answer in state ${pc.signalingState} from peer`
);
return;
}
@@ -255,12 +244,8 @@ export default class MeshSignalHandler {
remoteUserId,
pc
);
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn(
- `[voice] failed to handle answer from user ${remoteUserId}`,
- error
- );
+ } catch {
+ voiceLog.warn("[voice] failed to handle answer from peer");
}
} else if (data.type === "candidate") {
this.#peerManager.clearOfferRetry(roomId, remoteUserId);
@@ -276,12 +261,8 @@ export default class MeshSignalHandler {
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
- );
+ } catch {
+ voiceLog.warn("[voice] failed to add ICE candidate from peer");
}
}
}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js b/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js
index d7b5e94bfb7..83102b36f38 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/peer-manager.js
@@ -1,3 +1,5 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
+
// 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
@@ -102,9 +104,8 @@ export default class PeerManager {
);
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);
+ associated.sender.replaceTrack(orphanTrack).catch(() => {
+ voiceLog.warn("[voice] failed to migrate video track");
});
orphan.sender.replaceTrack(null).catch(() => {});
}
@@ -142,9 +143,8 @@ export default class PeerManager {
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);
+ screenTransceiver.sender.replaceTrack(orphanTrack).catch(() => {
+ voiceLog.warn("[voice] failed to migrate screen audio track");
});
orphan.sender.replaceTrack(null).catch(() => {});
}
@@ -250,9 +250,8 @@ export default class PeerManager {
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);
+ } catch {
+ voiceLog.warn("[voice] failed to replace track on peer");
}
}
}
@@ -299,9 +298,8 @@ export default class PeerManager {
});
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);
+ videoTransceiver.sender.replaceTrack(videoTrack).catch(() => {
+ voiceLog.warn("[voice] failed to attach video track");
});
}
@@ -318,12 +316,9 @@ export default class PeerManager {
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);
- });
+ screenAudioTransceiver.sender.replaceTrack(screenAudioTrack).catch(() => {
+ voiceLog.warn("[voice] failed to attach screen audio track");
+ });
}
pc.ontrack = (event) => {
@@ -345,40 +340,30 @@ export default class PeerManager {
this.#sendSignal(roomId, remoteUserId, {
type: "candidate",
candidate: candidatePayload,
- }).catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to send candidate", error);
+ }).catch(() => {
+ voiceLog.warn("[voice] failed to send candidate");
});
} else {
- this.#flushQueuedSignals(roomId, remoteUserId).catch((error) => {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to flush signal queue", error);
+ this.#flushQueuedSignals(roomId, remoteUserId).catch(() => {
+ voiceLog.warn("[voice] failed to flush signal queue");
});
}
};
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);
+ this.#flushQueuedSignals(roomId, remoteUserId).catch(() => {
+ voiceLog.warn("[voice] failed to flush signal queue");
});
}
};
- pc.onicecandidateerror = (event) => {
- // eslint-disable-next-line no-console
- console.warn(
- `[voice] ICE candidate error for user ${remoteUserId}`,
- event
- );
+ pc.onicecandidateerror = () => {
+ voiceLog.warn("[voice] ICE candidate error for peer");
};
pc.onconnectionstatechange = () => {
- // eslint-disable-next-line no-console
- console.log(
- `[voice] connectionState ${pc.connectionState} for user ${remoteUserId}`
- );
+ voiceLog.info(`[voice] connectionState ${pc.connectionState} for peer`);
if (pc.connectionState === "connected") {
this.#clearOfferRetry(roomId, remoteUserId);
this.#clearPeerRestart(roomId, remoteUserId);
@@ -405,9 +390,8 @@ export default class PeerManager {
};
pc.oniceconnectionstatechange = () => {
- // eslint-disable-next-line no-console
- console.log(
- `[voice] iceConnectionState ${pc.iceConnectionState} for user ${remoteUserId}`
+ voiceLog.info(
+ `[voice] iceConnectionState ${pc.iceConnectionState} for peer`
);
if (pc.iceConnectionState === "failed") {
this.#schedulePeerRestart(roomId, remoteUserId, { immediate: true });
@@ -482,9 +466,9 @@ export default class PeerManager {
// 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}`
+
+ voiceLog.info(
+ `[voice] skipping offer for peer: signalingState=${pc.signalingState}`
);
return;
}
@@ -492,13 +476,11 @@ export default class PeerManager {
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);
+ this.#sendSignal(roomId, remoteUserId, offer).catch(() => {
+ voiceLog.warn("[voice] failed to send offer");
});
- } catch (error) {
- // eslint-disable-next-line no-console
- console.warn("[voice] failed to create offer", error);
+ } catch {
+ voiceLog.warn("[voice] failed to create offer");
}
}
@@ -514,9 +496,8 @@ export default class PeerManager {
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}`
+ voiceLog.warn(
+ `[voice] max offer retries (${PeerManager.#maxOfferRetries}) reached for peer`
);
return;
}
@@ -526,9 +507,8 @@ export default class PeerManager {
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)`
+ voiceLog.info(
+ `[voice] scheduling offer retry for peer (attempt ${attempts + 1}/${PeerManager.#maxOfferRetries}, delay ${actualDelay}ms)`
);
const timer = setTimeout(async () => {
@@ -553,9 +533,9 @@ export default class PeerManager {
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)`
+
+ voiceLog.info(
+ `[voice] queued ICE candidate for peer (${queue.length} pending)`
);
}
@@ -568,20 +548,16 @@ export default class PeerManager {
}
this.#pendingCandidates.delete(key);
- // eslint-disable-next-line no-console
- console.log(
- `[voice] flushing ${candidates.length} queued ICE candidates for user ${remoteUserId}`
+
+ voiceLog.info(
+ `[voice] flushing ${candidates.length} queued ICE candidates for peer`
);
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
- );
+ } catch {
+ voiceLog.warn("[voice] failed to add queued ICE candidate for peer");
}
}
}
@@ -654,9 +630,8 @@ export default class PeerManager {
// 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`
+ voiceLog.warn(
+ `[voice] connection stuck in "new" (${timing.connectionTimeoutMs}ms) for peer; restarting`
);
this.#schedulePeerRestart(roomId, remoteUserId, { immediate: true });
}
@@ -697,9 +672,8 @@ export default class PeerManager {
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}`
+ voiceLog.warn(
+ `[voice] max restart attempts (${PeerManager.#maxRestartAttempts}) reached for peer`
);
return;
}
@@ -712,17 +686,15 @@ export default class PeerManager {
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)`
+ voiceLog.info(
+ `[voice] scheduling peer restart for peer (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);
+ this.restart(roomId, remoteUserId).catch(() => {
+ voiceLog.warn("[voice] failed to restart peer connection");
});
}, delay);
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js b/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js
index cf328113fb3..3b2469b38cd 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/roster-handler.js
@@ -1,4 +1,5 @@
import { i18n } from "discourse-i18n";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import {
playUserJoinedSound,
playUserLeftSound,
@@ -98,9 +99,8 @@ export default class RosterHandler {
);
const currentUserId = this.#getCurrentUserId();
- // eslint-disable-next-line no-console
- console.log(
- `[voice] handleParticipants room=${roomId}, participants=[${Array.from(participantIds)}], currentUser=${currentUserId}`
+ voiceLog.info(
+ `[voice] handleParticipants room=${roomId}, count=${participantIds.size}`
);
if (this.#roleChangeInProgress.has(roomId)) {
@@ -156,10 +156,8 @@ export default class RosterHandler {
if (existingPeerIds.size > 0 || !this.#isConnectingRoom(roomId)) {
hasNewPeer = true;
}
- // eslint-disable-next-line no-console
- console.log(
- `[voice] creating peer connection to user ${participantId}`
- );
+
+ voiceLog.info("[voice] creating peer connection");
await this.#createAndOfferPeer(roomId, participantId);
} else {
@@ -343,11 +341,9 @@ export default class RosterHandler {
// 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
+ } catch {
+ voiceLog.warn(
+ `[voice-livekit] failed to refresh publications after a role change in room ${roomId}`
);
}
}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/sanitize-error.js b/plugins/voice/assets/javascripts/discourse/lib/voice/sanitize-error.js
new file mode 100644
index 00000000000..2564a355b2e
--- /dev/null
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/sanitize-error.js
@@ -0,0 +1,51 @@
+const MAX_MESSAGE_LENGTH = 200;
+
+function sanitizeMessage(message) {
+ // Payloads and additional lines can contain session descriptions or server responses.
+ return message
+ .replace(/\s*(?:[\r\n{]|\[)[\s\S]*/, " [FILTERED]")
+ .replace(
+ /\b(?:sdp|candidate|transcript|response body)\s*[:=][\s\S]*/gi,
+ "[FILTERED]"
+ )
+ .replace(/\b(?:https?|wss?|turns?|stun):[^\s<>"']+/gi, "[FILTERED]")
+ .replace(/\bBearer\s+[^\s,;"']+/gi, "[FILTERED]")
+ .replace(/\beyJ[\w-]+\.[\w-]+(?:\.[\w-]+)?\b/g, "[FILTERED]")
+ .replace(
+ /\b(?:access[_-]?token|token|api[_-]?key|secret|password|credential|authorization)\b["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;]+)/gi,
+ "[FILTERED]"
+ )
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, "[FILTERED]")
+ .replace(/\b(?:[\da-f]{0,4}:){2,}[\da-f:.]*(?:%[\w-]+)?/gi, "[FILTERED]")
+ .replace(/\b[\w.+-]+@[\w.-]+\.[a-z]{2,}\b/gi, "[FILTERED]")
+ .slice(0, MAX_MESSAGE_LENGTH);
+}
+
+/** Extracts bounded diagnostics without serializing errors, stacks, or nested payloads. */
+export default function sanitizeError(error) {
+ if (!error) {
+ return;
+ }
+
+ const details = {};
+ if (
+ typeof error.name === "string" &&
+ /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(error.name)
+ ) {
+ details.name = error.name;
+ }
+ if (
+ (typeof error.code === "number" && Number.isFinite(error.code)) ||
+ (typeof error.code === "string" &&
+ /^[A-Z][A-Z0-9_]{0,63}$/.test(error.code))
+ ) {
+ details.code = error.code;
+ }
+
+ const message = typeof error === "string" ? error : error.message;
+ if (typeof message === "string") {
+ details.message = sanitizeMessage(message);
+ }
+
+ return Object.keys(details).length ? details : undefined;
+}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js b/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js
index c3a00a318ba..24e20f7feb4 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/signaling.js
@@ -1,4 +1,5 @@
import { ajax } from "discourse/lib/ajax";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
export default class SignalingManager {
static peerKey(roomId, userId) {
@@ -223,9 +224,8 @@ export default class SignalingManager {
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);
+ this.flushQueued(roomId, recipientId).catch(() => {
+ voiceLog.warn("[voice] failed to flush signal queue");
});
return;
}
@@ -237,9 +237,8 @@ export default class SignalingManager {
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.flushQueued(roomId, recipientId).catch(() => {
+ voiceLog.warn("[voice] failed to flush signal queue");
});
}, this.#candidateBatchDelayMs);
@@ -290,9 +289,8 @@ export default class SignalingManager {
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);
+ this.#flushHttp(roomId).catch(() => {
+ voiceLog.warn("[voice] failed to flush HTTP signal queue");
});
} else {
this.#scheduleHttpFlush(roomId);
@@ -308,9 +306,8 @@ export default class SignalingManager {
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.#flushHttp(roomId).catch(() => {
+ voiceLog.warn("[voice] failed to flush HTTP signal queue");
});
}, this.#httpBatchDelayMs);
@@ -374,8 +371,7 @@ export default class SignalingManager {
const payload = SignalingManager.#buildPayload(messages);
- // eslint-disable-next-line no-console
- console.log(
+ voiceLog.info(
`[voice] πŸš€ sending ${messages.length} batched signal recipient(s) in room ${roomId}`
);
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js b/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js
index 4d1eedec7b1..3dabc99006f 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/subtitles.js
@@ -1,3 +1,4 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import { voiceAssetAppUrl, voiceAssetUrl } from "./voice-assets";
// Stable filenames in the discourse_voice_assets gem's stt/ directory.
@@ -407,8 +408,8 @@ export default class SubtitlesManager {
}
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);
+
+ voiceLog.warn("[voice] subtitles transcription error");
break;
}
}
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js b/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js
index a1a895f5f29..8ab259e4614 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/transcription-coordinator.js
@@ -4,6 +4,7 @@ import { manuallyTrack } from "discourse/lib/tracked-tools";
import Composer from "discourse/models/composer";
import Draft from "discourse/models/draft";
import { i18n } from "discourse-i18n";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import SubtitlesManager from "./subtitles";
import TranscriptDraftSync from "./transcript-draft-sync";
import { transcriptToMarkdown } from "./transcript-markdown";
@@ -101,7 +102,7 @@ export default class TranscriptionCoordinator {
this.progress = Math.min(100, Math.round((loaded / total) * 100));
}
},
- onError: (error) => this.#handleError(error),
+ onError: () => this.#handleError(),
});
this.enabled = this.available && this.#subtitles.isPreferred();
@@ -394,9 +395,8 @@ export default class TranscriptionCoordinator {
// 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);
+ #handleError() {
+ voiceLog.warn("[voice] subtitles failed");
if (!this.enabled && !this.recording) {
return;
diff --git a/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js b/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js
index 0abd0797ad9..6038d5c5f96 100644
--- a/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js
+++ b/plugins/voice/assets/javascripts/discourse/lib/voice/video-quality.js
@@ -1,3 +1,4 @@
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
import {
QUALITY_HIGH,
QUALITY_MAXIMUM,
@@ -114,9 +115,8 @@ export async function applyVideoQuality(
}
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);
+ } catch {
+ voiceLog.warn("[voice] failed to apply video quality");
}
}
}
@@ -136,9 +136,8 @@ export async function applyVoiceQuality(senders, tier = QUALITY_STANDARD) {
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);
+ } catch {
+ voiceLog.warn("[voice] failed to apply voice quality");
}
}
}
@@ -157,8 +156,7 @@ export async function applyScreenAudioQuality(sender) {
}
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);
+ } catch {
+ voiceLog.warn("[voice] failed to apply screen audio quality");
}
}
diff --git a/plugins/voice/config/locales/server.en.yml b/plugins/voice/config/locales/server.en.yml
index 4cdf05092d2..e071b4d5285 100644
--- a/plugins/voice/config/locales/server.en.yml
+++ b/plugins/voice/config/locales/server.en.yml
@@ -1,5 +1,6 @@
en:
site_settings:
+ voice_verbose_logging: "Log voice diagnostic information and warnings in server logs and browser consoles. Disabled by default. Logs exclude credentials, transcripts, signaling payloads, and raw error details."
voice_enabled: "Voice brings integrated voice and video rooms to Discourse, with screen sharing, background blur, noise suppression, live subtitles, direct calls, room chat, and group-based permissions. Members can keep browsing while they talk, with no external app required."
voice_allowed_groups: "Groups that can access voice rooms."
voice_create_room_allowed_groups: "Groups that can create new voice rooms."
diff --git a/plugins/voice/config/settings.yml b/plugins/voice/config/settings.yml
index 6b0503e2a4c..f7b1281c3b8 100644
--- a/plugins/voice/config/settings.yml
+++ b/plugins/voice/config/settings.yml
@@ -11,6 +11,9 @@ plugins:
learn_more_url: "https://meta.discourse.org/t/-/411337"
requires_plugin_enabled: false
permanent_warning: false
+ voice_verbose_logging:
+ default: false
+ client: true
voice_allowed_groups:
type: group_list
list_type: compact
diff --git a/plugins/voice/lib/voice.rb b/plugins/voice/lib/voice.rb
index 66c0520b624..d0a042d71bd 100644
--- a/plugins/voice/lib/voice.rb
+++ b/plugins/voice/lib/voice.rb
@@ -18,6 +18,11 @@ module ::Voice
SiteSetting.voice_enabled
end
+ # Callers must omit raw errors and payloads, which can contain credentials or content.
+ def self.warn(message)
+ Rails.logger.warn(message) if SiteSetting.voice_verbose_logging
+ end
+
def self.room_channel(room_id)
"#{ROOM_CHANNEL_PREFIX}/#{room_id}"
end
diff --git a/plugins/voice/lib/voice/livekit/egress_client.rb b/plugins/voice/lib/voice/livekit/egress_client.rb
index d02b9715cce..9bf40557301 100644
--- a/plugins/voice/lib/voice/livekit/egress_client.rb
+++ b/plugins/voice/lib/voice/livekit/egress_client.rb
@@ -20,8 +20,8 @@ module Voice
if SiteSetting.voice_livekit_recording_s3_bucket.present?
validator = VoiceLivekitRecordingS3BucketValidator.new
unless validator.valid_value?(SiteSetting.voice_livekit_recording_s3_bucket)
- Rails.logger.warn(
- "[voice-livekit] StartRoomCompositeEgress refused: #{validator.error_message}",
+ Voice.warn(
+ "[voice-livekit] StartRoomCompositeEgress refused: invalid recording storage configuration",
)
return { ok: false, error: validator.error_message }
end
@@ -73,11 +73,9 @@ module Voice
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.warn(
"[voice-livekit] #{method} failed: " \
- "HTTP #{response.status} #{redact_credentials(response.body).truncate(200)}",
+ "HTTP #{response.status}",
)
{ ok: false, error: "HTTP #{response.status}" }
end
@@ -88,7 +86,7 @@ module Voice
}
rescue StandardError => e
message = redact_credentials(e.message)
- Rails.logger.warn("[voice-livekit] #{method} failed: #{e.class} #{message}")
+ Voice.warn("[voice-livekit] #{method} failed: #{e.class}")
{ ok: false, error: "#{e.class}: #{message}" }
end
diff --git a/plugins/voice/lib/voice/livekit/room_service_client.rb b/plugins/voice/lib/voice/livekit/room_service_client.rb
index 38dad0b5f88..00b2b4786a6 100644
--- a/plugins/voice/lib/voice/livekit/room_service_client.rb
+++ b/plugins/voice/lib/voice/livekit/room_service_client.rb
@@ -87,16 +87,14 @@ module Voice
Rails.logger.debug("[voice-livekit] DeleteRoom no-op for room #{room.id}: already gone")
true
else
- Rails.logger.warn(
+ Voice.warn(
"[voice-livekit] #{method} failed for room #{room.id}: " \
- "HTTP #{response.status} #{response.body.to_s.truncate(200)}",
+ "HTTP #{response.status}",
)
false
end
rescue StandardError => e
- Rails.logger.warn(
- "[voice-livekit] #{method} failed for room #{room.id}: #{e.class} #{e.message}",
- )
+ Voice.warn("[voice-livekit] #{method} failed for room #{room.id}: #{e.class}")
false
end
@@ -110,11 +108,9 @@ module Voice
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.warn(
"[voice-livekit] #{method} probe failed: " \
- "HTTP #{response.status} #{response.body.to_s.truncate(200)}",
+ "HTTP #{response.status}",
)
{ ok: false, latency_ms:, error: "HTTP #{response.status}" }
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
index bd780b20e85..76ced51a45f 100644
--- a/plugins/voice/spec/jobs/regular/voice_livekit_probe_spec.rb
+++ b/plugins/voice/spec/jobs/regular/voice_livekit_probe_spec.rb
@@ -30,6 +30,7 @@ RSpec.describe Jobs::VoiceLivekitProbe do
end
it "stores the failure and logs it with the [voice-livekit] prefix" do
+ SiteSetting.voice_verbose_logging = true
list_rooms_stub.to_timeout
Rails.logger.expects(:warn).with(regexp_matches(/\[voice-livekit\] connectivity probe failed/))
diff --git a/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb b/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb
index a8efc0272d2..941189887db 100644
--- a/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb
+++ b/plugins/voice/spec/lib/voice/livekit/egress_client_spec.rb
@@ -119,7 +119,8 @@ RSpec.describe Voice::Livekit::EgressClient do
expect(stub).not_to have_been_requested
end
- it "redacts recording credentials echoed in upstream errors" do
+ it "omits response bodies containing recording credentials from verbose logs" do
+ SiteSetting.voice_verbose_logging = true
configure_recording_s3
credentials = [
SiteSetting.voice_livekit_recording_s3_access_key_id,
@@ -133,7 +134,7 @@ RSpec.describe Voice::Livekit::EgressClient do
expect(result).to eq(ok: false, error: "HTTP 400")
end
- expect(logs.warnings.join).to include("[FILTERED]")
+ expect(logs.warnings).to eq(["[voice-livekit] StartRoomCompositeEgress failed: HTTP 400"])
credentials.each { |credential| expect(logs.warnings.join).not_to include(credential) }
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
index c763da3b18e..12efb268f40 100644
--- a/plugins/voice/spec/lib/voice/livekit/room_service_client_spec.rb
+++ b/plugins/voice/spec/lib/voice/livekit/room_service_client_spec.rb
@@ -204,6 +204,8 @@ RSpec.describe Voice::Livekit::RoomServiceClient do
end
context "when LiveKit is down" do
+ before { SiteSetting.voice_verbose_logging = true }
+
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/))
diff --git a/plugins/voice/spec/lib/voice/logging_spec.rb b/plugins/voice/spec/lib/voice/logging_spec.rb
new file mode 100644
index 00000000000..990beb93483
--- /dev/null
+++ b/plugins/voice/spec/lib/voice/logging_spec.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe Voice do
+ describe ".warn" do
+ it "disables warning logs by default" do
+ expect(SiteSetting.voice_verbose_logging).to eq(false)
+
+ logs = track_log_messages { described_class.warn("[voice] chat operation failed") }
+
+ expect(logs.warnings).to be_empty
+ end
+
+ it "logs warnings only while verbose logging is enabled" do
+ logs =
+ track_log_messages do
+ SiteSetting.voice_verbose_logging = true
+ described_class.warn("[voice] chat operation failed")
+ SiteSetting.voice_verbose_logging = false
+ described_class.warn("[voice] chat operation failed")
+ end
+
+ expect(logs.warnings).to eq(["[voice] chat operation failed"])
+ end
+ end
+end
diff --git a/plugins/voice/test/javascripts/unit/lib/logger-test.js b/plugins/voice/test/javascripts/unit/lib/logger-test.js
new file mode 100644
index 00000000000..007f6ca2d22
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/logger-test.js
@@ -0,0 +1,77 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { getOwnerWithFallback, setDefaultOwner } from "discourse/lib/get-owner";
+import voiceLog from "discourse/plugins/voice/discourse/lib/voice/logger";
+
+module("Voice | Unit | Lib | logger", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.originalOwner = getOwnerWithFallback();
+ setDefaultOwner(this.owner);
+ this.info = sinon.stub(console, "info");
+ this.warn = sinon.stub(console, "warn");
+ this.siteSettings = this.owner.lookup("service:site-settings");
+ });
+
+ hooks.afterEach(function () {
+ setDefaultOwner(this.originalOwner);
+ this.info.restore();
+ this.warn.restore();
+ });
+
+ test("logging is disabled by default", function (assert) {
+ assert.false(
+ this.siteSettings.voice_verbose_logging,
+ "verbose logging defaults to off"
+ );
+
+ voiceLog.info("[voice] local stream obtained");
+ voiceLog.warn("[voice] failed to obtain local stream");
+
+ assert.false(this.info.called, "info is silent");
+ assert.false(this.warn.called, "warnings are silent");
+ });
+
+ test("logging follows changes to the setting", function (assert) {
+ this.siteSettings.voice_verbose_logging = true;
+ voiceLog.info("[voice] local stream obtained");
+ voiceLog.warn("[voice] failed to obtain local stream");
+ this.siteSettings.voice_verbose_logging = false;
+ voiceLog.info("[voice] local stream obtained");
+ voiceLog.warn("[voice] failed to obtain local stream");
+
+ assert.true(
+ this.info.calledOnceWithExactly("[voice] local stream obtained"),
+ "info logs only when enabled"
+ );
+ assert.true(
+ this.warn.calledOnceWithExactly("[voice] failed to obtain local stream"),
+ "warnings log only when enabled"
+ );
+ });
+
+ test("only sanitized error fields are logged", function (assert) {
+ this.siteSettings.voice_verbose_logging = true;
+ const error = new Error("publish failed: token=secret");
+ const payload = { candidate: "private IP address", token: "secret token" };
+
+ voiceLog.info("[voice] received signal", payload);
+ voiceLog.warn("[voice] failed to obtain local stream", error, payload);
+
+ assert.deepEqual(
+ this.info.firstCall.args,
+ ["[voice] received signal"],
+ "payloads are omitted"
+ );
+ assert.deepEqual(
+ this.warn.firstCall.args,
+ [
+ "[voice] failed to obtain local stream",
+ { name: "Error", message: "publish failed: [FILTERED]" },
+ ],
+ "only sanitized error details are included"
+ );
+ });
+});
diff --git a/plugins/voice/test/javascripts/unit/lib/sanitize-error-test.js b/plugins/voice/test/javascripts/unit/lib/sanitize-error-test.js
new file mode 100644
index 00000000000..40eef7b5ebf
--- /dev/null
+++ b/plugins/voice/test/javascripts/unit/lib/sanitize-error-test.js
@@ -0,0 +1,81 @@
+import { module, test } from "qunit";
+import sanitizeError from "discourse/plugins/voice/discourse/lib/voice/sanitize-error";
+
+module("Voice | Unit | Lib | sanitize-error", function () {
+ test("retains diagnostic fields without stacks or nested payloads", function (assert) {
+ const error = new Error("track publication timed out");
+ error.name = "PublishError";
+ error.code = 401;
+ error.cause = { token: "private-token" };
+ error.track = { label: "private-device" };
+
+ assert.deepEqual(
+ sanitizeError(error),
+ {
+ name: "PublishError",
+ code: 401,
+ message: "track publication timed out",
+ },
+ "only diagnostic fields are retained"
+ );
+ });
+
+ test("redacts sensitive message content", function (assert) {
+ const messages = [
+ "connect failed: wss://user:[email protected]/rtc?access_token=secret",
+ "connect failed: Bearer secret-token",
+ 'connect failed: token="secret token"',
+ "connect failed: api_key=private-key",
+ "connect failed: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.signature",
+ "connect failed: 192.168.1.2",
+ "connect failed: 2001:db8::1",
+ "connect failed: [email protected]",
+ "connect failed: sdp=v=0 private SDP",
+ "connect failed: transcript=private words",
+ ];
+ for (const message of messages) {
+ assert.strictEqual(
+ sanitizeError(new Error(message)).message,
+ "connect failed: [FILTERED]",
+ "sensitive content is redacted"
+ );
+ }
+ });
+
+ test("drops embedded payloads and limits message length", function (assert) {
+ for (const message of [
+ 'publish failed {"token":"secret"}',
+ 'publish failed ["private words"]',
+ "publish failed\nprivate SDP",
+ ]) {
+ assert.strictEqual(
+ sanitizeError(new Error(message)).message,
+ "publish failed [FILTERED]",
+ "payload is omitted"
+ );
+ }
+ assert.strictEqual(
+ sanitizeError(new Error("x".repeat(300))).message.length,
+ 200,
+ "message length is bounded"
+ );
+ });
+
+ test("handles missing and non-error values without serializing them", function (assert) {
+ assert.strictEqual(
+ sanitizeError(null),
+ undefined,
+ "missing error is omitted"
+ );
+ assert.strictEqual(
+ sanitizeError({ response: { token: "secret" } }),
+ undefined,
+ "response objects are omitted"
+ );
+ assert.deepEqual(
+ sanitizeError("publish failed"),
+ { message: "publish failed" },
+ "string errors retain a sanitized message"
+ );
+ });
+});