Skip to content

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

FIX: improve the reliability of chat sounds (#41373)

Kris0d45f2093527
diff --git a/app/views/static/service-worker.js.erb b/app/views/static/service-worker.js.erb
index 0a0e94126a1..a3b5940745a 100644
--- a/app/views/static/service-worker.js.erb
+++ b/app/views/static/service-worker.js.erb
@@ -196,18 +196,23 @@ self.addEventListener('fetch', function (event) {
});
self.addEventListener('message', function(event) {
- if (event.data?.action !== "primaryTab") {
+ if (event.data?.action !== "primaryTab" || !event.source) {
return;
}
event.waitUntil(
- self.clients.matchAll().then(function(clients) {
- const activeClient = clients.find(client => client.focused) || clients.find(client => client.visibilityState === "visible");
-
- clients.forEach(function(client) {
- client.postMessage({
- primaryTab: client.id === activeClient?.id
- });
+ // includeUncontrolled so first-visit and hard-reloaded tabs take part in
+ // the election instead of silently failing open client-side
+ self.clients.matchAll({ includeUncontrolled: true }).then(function(clients) {
+ const activeClient =
+ clients.find(client => client.focused) ||
+ clients.find(client => client.visibilityState === "visible");
+
+ // when every tab is hidden (user is in another app or on another site),
+ // the requester acts as primary — unlike an elected hidden tab it is
+ // provably running, and simultaneous self-elections are deduped
+ event.source.postMessage({
+ primaryTab: activeClient ? event.source.id === activeClient.id : true
});
})
);
diff --git a/frontend/discourse/app/lib/utilities.js b/frontend/discourse/app/lib/utilities.js
index 768dad5552c..cdd2030571b 100644
--- a/frontend/discourse/app/lib/utilities.js
+++ b/frontend/discourse/app/lib/utilities.js
@@ -1,9 +1,11 @@
/* eslint-disable ember/no-jquery */
+import { cancel } from "@ember/runloop";
import $ from "jquery";
import * as AvatarUtils from "discourse/lib/avatar-utils";
import deprecated from "discourse/lib/deprecated";
import escape from "discourse/lib/escape";
import getURL from "discourse/lib/get-url";
+import discourseLater from "discourse/lib/later";
import { processSelectionFragment } from "discourse/lib/selection/preserve-list-structure";
import { parseAsync } from "discourse/lib/text";
import toMarkdown from "discourse/lib/to-markdown";
@@ -819,18 +821,35 @@ export function getElement(node) {
}
export function isPrimaryTab() {
+ if (!capabilities.supportsServiceWorker) {
+ return Promise.resolve(true);
+ }
+
return new Promise((resolve) => {
- if (capabilities.supportsServiceWorker) {
- navigator.serviceWorker.addEventListener("message", (event) => {
- resolve(event.data.primaryTab);
- });
+ let timer;
+
+ const finish = (isPrimary) => {
+ cancel(timer);
+ navigator.serviceWorker.removeEventListener("message", onMessage);
+ resolve(isPrimary);
+ };
+
+ const onMessage = (event) => {
+ // the service worker also posts unrelated messages on this channel
+ if (typeof event.data?.primaryTab === "boolean") {
+ finish(event.data.primaryTab);
+ }
+ };
- navigator.serviceWorker.ready.then((registration) => {
- registration.active.postMessage({ action: "primaryTab" });
- });
- } else {
- resolve(true);
- }
+ navigator.serviceWorker.addEventListener("message", onMessage);
+
+ // if the service worker never answers (no active registration), assume
+ // primary rather than hanging forever and silently dropping the action
+ timer = discourseLater(() => finish(true), 1000);
+
+ navigator.serviceWorker.ready.then((registration) => {
+ registration.active?.postMessage({ action: "primaryTab" });
+ });
});
}
diff --git a/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb b/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
index 80d185bba79..c64394a8cd9 100644
--- a/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
+++ b/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
@@ -74,6 +74,7 @@ module Jobs
payload = {
notification_type: ::Notification.types[:chat_mention],
username: @creator.username,
+ chat_message_id: @chat_message.id,
tag: ::Chat::Notifier.push_notification_tag(:mention, @chat_channel.id),
excerpt: @chat_message.push_notification_excerpt,
post_url: post_url,
diff --git a/plugins/chat/app/jobs/regular/chat/notify_watching.rb b/plugins/chat/app/jobs/regular/chat/notify_watching.rb
index 9172f0f6849..1abb8fe97d4 100644
--- a/plugins/chat/app/jobs/regular/chat/notify_watching.rb
+++ b/plugins/chat/app/jobs/regular/chat/notify_watching.rb
@@ -76,6 +76,7 @@ module Jobs
payload = {
username: @creator.username,
notification_type: ::Notification.types[:chat_message],
+ chat_message_id: @chat_message.id,
post_url: @chat_message.url,
translated_title: translated_title,
tag: ::Chat::Notifier.push_notification_tag(:message, @chat_channel.id),
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
index afefe2ef9d2..09164b8b0b6 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
@@ -1,5 +1,9 @@
import { withPluginApi } from "discourse/lib/plugin-api";
import { isPrimaryTab } from "discourse/lib/utilities";
+import {
+ claimChatAlert,
+ releaseChatAlert,
+} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
import { INDICATOR_PREFERENCES } from "discourse/plugins/chat/discourse/lib/chat-constants";
const MENTION = 29;
@@ -49,14 +53,21 @@ export default {
}
if (CHAT_NOTIFICATION_TYPES.includes(data.notification_type)) {
- this.canPlaySound().then((success) => {
- if (success) {
- const chatAudioManager = container.lookup(
- "service:chat-audio-manager"
- );
- chatAudioManager.play(user.chat_sound, {
- type: isMention ? "mention" : "incoming",
- });
+ return this.canPlaySound().then(async (success) => {
+ if (!success || !claimChatAlert(data.chat_message_id)) {
+ return;
+ }
+
+ const chatAudioManager = container.lookup(
+ "service:chat-audio-manager"
+ );
+ const handled = await chatAudioManager.play(user.chat_sound, {
+ type: isMention ? "mention" : "incoming",
+ });
+
+ if (!handled) {
+ // audio is unavailable in this tab, let another tab play it
+ releaseChatAlert(data.chat_message_id);
}
});
}
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-alert-dedup.js b/plugins/chat/assets/javascripts/discourse/lib/chat-alert-dedup.js
new file mode 100644
index 00000000000..2fcd49bb9b2
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-alert-dedup.js
@@ -0,0 +1,53 @@
+import KeyValueStore from "discourse/lib/key-value-store";
+
+const STORE_CONTEXT = "discourse_chat_alerts_";
+const STORE_KEY = "handled";
+const EXPIRY_MS = 5 * 60 * 1000;
+const MAX_ENTRIES = 100;
+
+const store = new KeyValueStore(STORE_CONTEXT);
+
+function readEntries() {
+ const now = Date.now();
+ return (store.getObject(STORE_KEY) || []).filter(
+ (entry) => now - entry.at < EXPIRY_MS
+ );
+}
+
+function writeEntries(entries) {
+ store.setObject({ key: STORE_KEY, value: entries.slice(-MAX_ENTRIES) });
+}
+
+// Tabs receive the same alert at different times, hidden tabs get the
+// MessageBus backlog when they wake — so the first tab to handle an alert
+// records it here to keep later tabs from replaying its sound.
+export function claimChatAlert(key) {
+ if (!key) {
+ return true;
+ }
+
+ const entries = readEntries();
+
+ if (entries.some((entry) => entry.key === key)) {
+ return false;
+ }
+
+ entries.push({ key, at: Date.now() });
+ writeEntries(entries);
+
+ return true;
+}
+
+// for claims that turned out to be unplayable in this tab (e.g. suspended
+// audio context), so another tab can still play the sound
+export function releaseChatAlert(key) {
+ if (!key) {
+ return;
+ }
+
+ writeEntries(readEntries().filter((entry) => entry.key !== key));
+}
+
+export function resetChatAlerts() {
+ store.abandonLocal();
+}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
index 355de136487..387327be77e 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js
@@ -1,5 +1,7 @@
+import { cancel } from "@ember/runloop";
import Service from "@ember/service";
import { isTesting } from "discourse/lib/environment";
+import discourseLater from "discourse/lib/later";
export const CHAT_SOUNDS = {
classic: {},
@@ -12,6 +14,7 @@ export const CHAT_SOUNDS = {
export const DEFAULT_SOUND_NAME = "classic";
const THROTTLE_TIME = 3000; // 3 seconds
+const RESUME_TIMEOUT = 500;
const MIN_GAIN = 0.001;
let sharedAudioContext;
@@ -32,7 +35,24 @@ async function getAudioContext() {
}
if (sharedAudioContext.state === "suspended") {
- await sharedAudioContext.resume();
+ // browsers keep resume() pending until the user interacts with the page;
+ // racing a timeout keeps sounds from queuing up and bursting all at once
+ // on the next interaction
+ let timer;
+ try {
+ await Promise.race([
+ sharedAudioContext.resume().catch(() => {}),
+ new Promise((resolve) => {
+ timer = discourseLater(resolve, RESUME_TIMEOUT);
+ }),
+ ]);
+ } finally {
+ cancel(timer);
+ }
+
+ if (sharedAudioContext.state === "suspended") {
+ throw new Error("audio context is suspended");
+ }
}
return sharedAudioContext;
@@ -180,19 +200,36 @@ const SOUND_SEQUENCES = {
export default class ChatAudioManager extends Service {
canPlay = true;
- async play(name, { throttle = true, type = "incoming" } = {}) {
- if (!throttle || this.canPlay) {
- await this.#tryPlay(name, type);
+ #throttleTimer;
- if (!throttle) {
- return;
+ // resolves false only when audio could not be produced in this tab (e.g.
+ // suspended context); a rate-limited drop is intentional and still counts
+ // as handled
+ async play(name, { throttle = true, type = "incoming" } = {}) {
+ if (throttle) {
+ if (!this.canPlay) {
+ return true;
}
+ // consume the throttle before awaiting so concurrent calls can't all
+ // slip past the check
this.canPlay = false;
- setTimeout(() => {
+ this.#throttleTimer = discourseLater(() => {
this.canPlay = true;
}, THROTTLE_TIME);
}
+
+ const played = await this.#tryPlay(name, type);
+
+ if (throttle && !played) {
+ // a failed attempt played nothing, so it shouldn't burn the window —
+ // otherwise alerts arriving in the next 3s report handled and keep
+ // their claims without any tab making a sound
+ cancel(this.#throttleTimer);
+ this.canPlay = true;
+ }
+
+ return played;
}
async #tryPlay(name, type) {
@@ -200,13 +237,15 @@ export default class ChatAudioManager extends Service {
const ctx = await getAudioContext();
const sequence = SOUND_SEQUENCES[normalizeChatSoundName(name)];
(sequence[type] || sequence.incoming)(ctx, ctx.currentTime);
+ return true;
} catch {
if (!isTesting()) {
// eslint-disable-next-line no-console
console.info(
- "[chat] User needs to interact with DOM before we can play notification sounds."
+ "[chat] User needs to interact with page before we can play notification sounds."
);
}
+ return false;
}
}
}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-notification-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-notification-manager.js
index 0ba959ae3ed..9d900e766a1 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-notification-manager.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-notification-manager.js
@@ -5,6 +5,7 @@ import {
onNotification as onDesktopNotification,
} from "discourse/lib/desktop-notifications";
import { isTesting } from "discourse/lib/environment";
+import { claimChatAlert } from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
export default class ChatNotificationManager extends Service {
@service capabilities;
@@ -37,11 +38,17 @@ export default class ChatNotificationManager extends Service {
@bind
async onMessage(data) {
// if the user is currently focused on this tab and channel,
- // we don't want to show a desktop notification
+ // we don't want to show a desktop notification; claim the alert so
+ // a backgrounded tab catching up later doesn't replay its sound
if (
this.session.hasFocus &&
data.channel_id === this.chat.activeChannel?.id
) {
+ // hasFocus tracks visibility, not focus, and starts out true — a tab
+ // that has never been shown must not claim the alert
+ if (!document.hidden) {
+ claimChatAlert(data.chat_message_id);
+ }
return;
}
diff --git a/plugins/chat/test/javascripts/unit/lib/chat-alert-dedup-test.js b/plugins/chat/test/javascripts/unit/lib/chat-alert-dedup-test.js
new file mode 100644
index 00000000000..a6da055307d
--- /dev/null
+++ b/plugins/chat/test/javascripts/unit/lib/chat-alert-dedup-test.js
@@ -0,0 +1,57 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import {
+ claimChatAlert,
+ releaseChatAlert,
+ resetChatAlerts,
+} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
+
+module("Unit | chat-alert-dedup", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ resetChatAlerts();
+ });
+
+ hooks.afterEach(function () {
+ resetChatAlerts();
+ });
+
+ test("claims an alert only once", function (assert) {
+ assert.true(claimChatAlert(1), "first claim succeeds");
+ assert.false(claimChatAlert(1), "second claim is rejected");
+ assert.true(claimChatAlert(2), "a different alert can be claimed");
+ });
+
+ test("always allows alerts without a key", function (assert) {
+ assert.true(claimChatAlert(undefined));
+ assert.true(claimChatAlert(undefined));
+ });
+
+ test("released alerts can be claimed again", function (assert) {
+ assert.true(claimChatAlert(1), "first claim succeeds");
+
+ releaseChatAlert(1);
+
+ assert.true(claimChatAlert(1), "claim succeeds again after release");
+ assert.false(claimChatAlert(1), "and is exclusive again");
+ });
+
+ test("expires old claims", function (assert) {
+ const clock = sinon.useFakeTimers({
+ now: Date.now(),
+ toFake: ["Date"],
+ });
+
+ try {
+ assert.true(claimChatAlert(1), "first claim succeeds");
+
+ clock.tick(6 * 60 * 1000);
+
+ assert.true(claimChatAlert(1), "claim succeeds again after expiry");
+ } finally {
+ clock.restore();
+ }
+ });
+});
diff --git a/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js b/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js
index 49eace0fbe4..0174c4e3a0d 100644
--- a/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js
+++ b/plugins/chat/test/javascripts/unit/lib/chat-audio-test.js
@@ -4,11 +4,13 @@ import sinon from "sinon";
import { withPluginApi } from "discourse/lib/plugin-api";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import chatAudioInitializer from "discourse/plugins/chat/discourse/initializers/chat-audio";
+import { resetChatAlerts } from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
module("Unit | chat-audio", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
+ resetChatAlerts();
const chatAudioManager = getOwner(this).lookup(
"service:chat-audio-manager"
);
@@ -33,13 +35,17 @@ module("Unit | chat-audio", function (hooks) {
.returns(Promise.resolve(true));
this.notificationHandler = this.stub.getCall(0).callback;
- this.playStub = sinon.stub(chatAudioManager, "play");
+ this.playStub = sinon.stub(chatAudioManager, "play").resolves(true);
this.handleNotification = (data = {}) => {
if (!data.notification_type) {
data.notification_type = 30;
}
- this.notificationHandler(data, this.siteSettings, this.currentUser);
+ return this.notificationHandler(
+ data,
+ this.siteSettings,
+ this.currentUser
+ );
};
});
});
@@ -118,4 +124,27 @@ module("Unit | chat-audio", function (hooks) {
assert.true(this.playStub.notCalled, "does not play a sound");
});
+
+ test("plays the sound only once for the same message", async function (assert) {
+ await this.handleNotification({ chat_message_id: 1234 });
+ await this.handleNotification({ chat_message_id: 1234 });
+
+ assert.true(this.playStub.calledOnce, "skips the replayed alert");
+
+ await this.handleNotification({ chat_message_id: 1235 });
+
+ assert.true(this.playStub.calledTwice, "plays a sound for a new message");
+ });
+
+ test("releases the claim when the sound could not be played", async function (assert) {
+ this.playStub.resolves(false);
+ await this.handleNotification({ chat_message_id: 42 });
+
+ assert.true(this.playStub.calledOnce, "attempts the sound");
+
+ this.playStub.resolves(true);
+ await this.handleNotification({ chat_message_id: 42 });
+
+ assert.true(this.playStub.calledTwice, "the alert can be claimed again");
+ });
});
diff --git a/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js b/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
index 25b13a6be6d..4a5f8a9346e 100644
--- a/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
+++ b/plugins/chat/test/javascripts/unit/services/chat-audio-manager-test.js
@@ -9,6 +9,10 @@ class MockAudioContext {
destination = {};
oscillators = [];
+ resume() {
+ return Promise.resolve();
+ }
+
createOscillator() {
const oscillator = {
frequency: {
@@ -96,8 +100,11 @@ module("Unit | Service | chat-audio-manager", function (hooks) {
});
test("throttles notification sounds by default", async function (assert) {
- await this.subject.play("classic");
- await this.subject.play("soft");
+ assert.true(await this.subject.play("classic"), "plays the first sound");
+ assert.true(
+ await this.subject.play("soft"),
+ "reports a throttled drop as handled"
+ );
assert.strictEqual(
this.context.oscillators.length,
@@ -117,6 +124,38 @@ module("Unit | Service | chat-audio-manager", function (hooks) {
);
});
+ test("skips the sound when the audio context stays suspended", async function (assert) {
+ this.context.state = "suspended";
+
+ assert.false(
+ await this.subject.play("classic"),
+ "reports the sound as unplayable"
+ );
+ assert.strictEqual(
+ this.context.oscillators.length,
+ 0,
+ "does not schedule a sound without user interaction"
+ );
+ });
+
+ test("a failed attempt does not consume the throttle", async function (assert) {
+ this.context.state = "suspended";
+
+ assert.false(await this.subject.play("classic"), "first attempt fails");
+
+ this.context.state = "running";
+
+ assert.true(
+ await this.subject.play("classic"),
+ "the next alert can play immediately"
+ );
+ assert.strictEqual(
+ this.context.oscillators.length,
+ 2,
+ "schedules the sound"
+ );
+ });
+
test("normalizes legacy sound names to the default theme", function (assert) {
assert.strictEqual(
normalizeChatSoundName("ding"),