Skip to content

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

FIX: Play chat alert sounds promptly and only once (#44925)

Kris9941729d0299
diff --git a/frontend/discourse/app/lib/desktop-notifications.js b/frontend/discourse/app/lib/desktop-notifications.js
index 5f8b9dd8360..2c03dbd2f58 100644
--- a/frontend/discourse/app/lib/desktop-notifications.js
+++ b/frontend/discourse/app/lib/desktop-notifications.js
@@ -144,6 +144,12 @@ function canUserReceiveNotifications(user) {
// Call-in point from message bus
async function onNotification(data, siteSettings, user, appEvents) {
+ // handlers run first: the permission request below can reject, or stay
+ // pending until a background tab is shown again
+ desktopNotificationHandlers.forEach((handler) =>
+ handler(data, siteSettings, user)
+ );
+
const showNotifications = canUserReceiveNotifications(user) && liveEnabled;
if (showNotifications) {
@@ -184,10 +190,6 @@ async function onNotification(data, siteSettings, user, appEvents) {
{ once: true }
);
}
-
- desktopNotificationHandlers.forEach((handler) =>
- handler(data, siteSettings, user)
- );
}
// Utility function
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
index 09164b8b0b6..36ddac0ffe8 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-audio.js
@@ -2,6 +2,7 @@ import { withPluginApi } from "discourse/lib/plugin-api";
import { isPrimaryTab } from "discourse/lib/utilities";
import {
claimChatAlert,
+ confirmChatAlert,
releaseChatAlert,
} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
import { INDICATOR_PREFERENCES } from "discourse/plugins/chat/discourse/lib/chat-constants";
@@ -65,7 +66,9 @@ export default {
type: isMention ? "mention" : "incoming",
});
- if (!handled) {
+ if (handled) {
+ confirmChatAlert(data.chat_message_id);
+ } else {
// 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
index 2fcd49bb9b2..b506b2ccf3c 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-alert-dedup.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-alert-dedup.js
@@ -7,6 +7,10 @@ const MAX_ENTRIES = 100;
const store = new KeyValueStore(STORE_CONTEXT);
+// claims are read-then-written, so two tabs can both claim the same alert;
+// tagging them keeps one tab's release from dropping the other's claim
+const TAB_ID = Math.random().toString(36).slice(2);
+
function readEntries() {
const now = Date.now();
return (store.getObject(STORE_KEY) || []).filter(
@@ -32,12 +36,30 @@ export function claimChatAlert(key) {
return false;
}
- entries.push({ key, at: Date.now() });
+ entries.push({ key, at: Date.now(), tab: TAB_ID });
writeEntries(entries);
return true;
}
+// for alerts this tab actually played: re-records the claim as this tab's in
+// case another tab claimed it in the same instant and later releases it
+export function confirmChatAlert(key) {
+ if (!key) {
+ return;
+ }
+
+ const entries = readEntries().filter((entry) => entry.key !== key);
+ entries.push({ key, at: Date.now(), tab: TAB_ID, played: true });
+ writeEntries(entries);
+}
+
+// a claim alone doesn't mean a sound played, a visible tab claims alerts for
+// its open channel silently
+export function chatAlertPlayed(key) {
+ return readEntries().some((entry) => entry.key === key && entry.played);
+}
+
// 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) {
@@ -45,7 +67,9 @@ export function releaseChatAlert(key) {
return;
}
- writeEntries(readEntries().filter((entry) => entry.key !== key));
+ writeEntries(
+ readEntries().filter((entry) => entry.key !== key || entry.tab !== TAB_ID)
+ );
}
export function resetChatAlerts() {
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
index e746a167ea2..a1d77e77dde 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js
@@ -2,6 +2,10 @@ import { cancel } from "@ember/runloop";
import Service, { service } from "@ember/service";
import discourseLater from "discourse/lib/later";
import { i18n } from "discourse-i18n";
+import {
+ chatAlertPlayed,
+ confirmChatAlert,
+} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
import { messageAnnouncementText } from "discourse/plugins/chat/discourse/lib/chat-message-announcement";
import { DEFAULT_SOUND_NAME } from "discourse/plugins/chat/discourse/services/chat-audio-manager";
@@ -35,7 +39,7 @@ export default class ChatNewMessageAnnouncer extends Service {
}
this.#maybeAnnounce(message, visible);
- this.#maybePlaySound(active);
+ this.#maybePlaySound(message, active);
}
#maybeAnnounce(message, visible) {
@@ -72,7 +76,7 @@ export default class ChatNewMessageAnnouncer extends Service {
this.a11y.announce(announcement, "polite");
}
- #maybePlaySound(active) {
+ async #maybePlaySound(message, active) {
if (
!active ||
!this.currentUser?.user_option?.chat_new_message_sound ||
@@ -85,11 +89,24 @@ export default class ChatNewMessageAnnouncer extends Service {
if (now - this.#lastMessageSoundAt < NEW_MESSAGE_SOUND_INTERVAL_MS) {
return;
}
+
+ // opening a channel replays messages that arrived while it was closed,
+ // which may already have played as a background alert
+ if (chatAlertPlayed(message.id)) {
+ return;
+ }
+
this.#lastMessageSoundAt = now;
// fall back to the default when no sound is selected.
const sound = this.currentUser.chat_sound || DEFAULT_SOUND_NAME;
// throttle false so this doesn't consume the shared chat-audio throttle
- this.chatAudioManager.play(sound, { throttle: false });
+ const handled = await this.chatAudioManager.play(sound, {
+ throttle: false,
+ });
+
+ if (handled) {
+ confirmChatAlert(message.id);
+ }
}
}
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
index a6da055307d..1abd4017195 100644
--- a/plugins/chat/test/javascripts/unit/lib/chat-alert-dedup-test.js
+++ b/plugins/chat/test/javascripts/unit/lib/chat-alert-dedup-test.js
@@ -1,12 +1,27 @@
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
+import KeyValueStore from "discourse/lib/key-value-store";
import {
+ chatAlertPlayed,
claimChatAlert,
+ confirmChatAlert,
releaseChatAlert,
resetChatAlerts,
} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
+function alertStore() {
+ return new KeyValueStore("discourse_chat_alerts_");
+}
+
+// what another tab writes when it claims an alert in the same instant
+function claimFromAnotherTab(key) {
+ alertStore().setObject({
+ key: "handled",
+ value: [{ key, at: Date.now(), tab: "other-tab" }],
+ });
+}
+
module("Unit | chat-alert-dedup", function (hooks) {
setupTest(hooks);
@@ -54,4 +69,33 @@ module("Unit | chat-alert-dedup", function (hooks) {
clock.restore();
}
});
+
+ test("doesn't release another tab's claim", function (assert) {
+ claimFromAnotherTab(1);
+
+ releaseChatAlert(1);
+
+ assert.false(claimChatAlert(1), "the other tab's claim survives");
+ });
+
+ test("a played alert takes over a racing tab's claim", function (assert) {
+ claimFromAnotherTab(1);
+
+ confirmChatAlert(1);
+
+ const [entry] = alertStore().getObject("handled");
+ assert.notStrictEqual(
+ entry.tab,
+ "other-tab",
+ "the other tab's release can no longer drop it"
+ );
+ });
+
+ test("only confirmed alerts count as played", function (assert) {
+ claimChatAlert(1);
+ assert.false(chatAlertPlayed(1), "a claim alone isn't played");
+
+ confirmChatAlert(1);
+ assert.true(chatAlertPlayed(1), "a confirmed alert is played");
+ });
});
diff --git a/plugins/chat/test/javascripts/unit/services/chat-new-message-announcer-test.js b/plugins/chat/test/javascripts/unit/services/chat-new-message-announcer-test.js
new file mode 100644
index 00000000000..d8c98319671
--- /dev/null
+++ b/plugins/chat/test/javascripts/unit/services/chat-new-message-announcer-test.js
@@ -0,0 +1,47 @@
+import { getOwner } from "@ember/owner";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ claimChatAlert,
+ confirmChatAlert,
+ resetChatAlerts,
+} from "discourse/plugins/chat/discourse/lib/chat-alert-dedup";
+
+module("Unit | Service | chat-new-message-announcer", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ resetChatAlerts();
+ this.currentUser.user_option.chat_new_message_sound = true;
+
+ const chatAudioManager = getOwner(this).lookup(
+ "service:chat-audio-manager"
+ );
+ this.play = sinon.stub(chatAudioManager, "play").resolves(true);
+
+ this.subject = getOwner(this).lookup("service:chat-new-message-announcer");
+ });
+
+ test("plays a sound for a new message in the active channel", function (assert) {
+ this.subject.notify({ id: 1, user: {} }, { active: true });
+
+ assert.true(this.play.calledOnce);
+ });
+
+ test("skips a message that already played as a background alert", function (assert) {
+ confirmChatAlert(2);
+
+ this.subject.notify({ id: 2, user: {} }, { active: true });
+
+ assert.true(this.play.notCalled);
+ });
+
+ test("plays a message that another tab claimed without playing", function (assert) {
+ claimChatAlert(3);
+
+ this.subject.notify({ id: 3, user: {} }, { active: true });
+
+ assert.true(this.play.calledOnce);
+ });
+});