Skip to content

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

FIX: gate reads on browser attention (#40864)

Sam5ffae2043d1c
diff --git a/frontend/discourse/app/lib/user-presence.js b/frontend/discourse/app/lib/user-presence.js
index 04fc14cec5b..1aec806dbbe 100644
--- a/frontend/discourse/app/lib/user-presence.js
+++ b/frontend/discourse/app/lib/user-presence.js
@@ -1,6 +1,7 @@
import { isTesting } from "discourse/lib/environment";
const callbacks = [];
+const browserAttentionCallbacks = [];
const DEFAULT_USER_UNSEEN_MS = 60000;
const DEFAULT_BROWSER_HIDDEN_MS = 0;
@@ -69,6 +70,37 @@ export function removeOnPresenceChange(callback) {
}
}
+export function browserAttention() {
+ return {
+ focused: document.hasFocus?.() ?? true,
+ visible: (document.visibilityState ?? "visible") === "visible",
+ };
+}
+
+export function onBrowserAttentionChange(callback) {
+ browserAttentionCallbacks.push(callback);
+}
+
+export function removeOnBrowserAttentionChange(callback) {
+ const i = browserAttentionCallbacks.indexOf(callback);
+ if (i > -1) {
+ browserAttentionCallbacks.splice(i, 1);
+ }
+}
+
+export function processBrowserAttentionChange() {
+ const attention = browserAttention();
+
+ browserAttentionCallbacks.forEach((callback) => {
+ try {
+ callback(attention);
+ } catch (e) {
+ // eslint-disable-next-line no-console
+ console.error("Error in browser attention change callback:", e);
+ }
+ });
+}
+
function processChanges() {
const browserHidden = document.hidden;
if (!!browserHiddenAt !== browserHidden) {
@@ -139,17 +171,30 @@ export function setTestPresence(value) {
export function clearPresenceCallbacks() {
callbacks.length = 0;
+ browserAttentionCallbacks.length = 0;
}
if (!isTesting()) {
+ const onWindowFocus = () => {
+ seenUser();
+ processBrowserAttentionChange();
+ };
+ const onVisibilityChange = () => {
+ visibilityChanged();
+ processBrowserAttentionChange();
+ };
+
// Some of these events occur very frequently. Therefore seenUser() is as fast as possible.
document.addEventListener("touchmove", seenUser, { passive: true });
document.addEventListener("click", seenUser, { passive: true });
document.addEventListener("keydown", seenUser, { passive: true });
window.addEventListener("scroll", seenUser, { passive: true });
- window.addEventListener("focus", seenUser, { passive: true });
+ window.addEventListener("focus", onWindowFocus, { passive: true });
+ window.addEventListener("blur", processBrowserAttentionChange, {
+ passive: true,
+ });
- document.addEventListener("visibilitychange", visibilityChanged, {
+ document.addEventListener("visibilitychange", onVisibilityChange, {
passive: true,
});
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
index b06f2e9c86b..ccb15e88b96 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs
@@ -66,7 +66,7 @@ export default class ChatChannel extends Component {
paneState = new ChatPaneState(getOwner(this), {
contextKey: this.pendingContextKey,
- onUserPresent: this.debouncedUpdateLastReadMessage,
+ onUserPresent: this.maybeDebouncedUpdateLastReadMessage,
});
_mentionWarningsSeen = {};
@@ -116,7 +116,7 @@ export default class ChatChannel extends Component {
@action
didResizePane() {
this.debounceFillPaneAttempt();
- this.debouncedUpdateLastReadMessage();
+ this.maybeDebouncedUpdateLastReadMessage();
DatesSeparatorsPositioner.apply(this.scroller);
this.paneState.updatePendingContentFromScrollerPosition({
@@ -186,11 +186,17 @@ export default class ChatChannel extends Component {
@bind
onNewMessage(message) {
+ const isOwnMessage = message.user.id === this.currentUser.id;
+
this.paneState.handleIncomingMessage({
scroller: this.scroller,
- shouldAutoScroll: this.paneState.userIsPresent && this.atBottom,
+ shouldAutoScroll: this.paneState.shouldAutoScrollIncomingMessage({
+ isAtLiveEdge: this.paneState.isAtLiveEdge,
+ isOwnMessage,
+ }),
addMessage: () => this.messagesManager.addMessages([message]),
- onAutoAdd: () => this.debouncedUpdateLastReadMessage(),
+ onAutoAdd: () => this.maybeDebouncedUpdateLastReadMessage(),
+ isOwnMessage,
});
}
@@ -226,7 +232,7 @@ export default class ChatChannel extends Component {
}
this.debounceFillPaneAttempt();
- this.debouncedUpdateLastReadMessage();
+ this.maybeDebouncedUpdateLastReadMessage();
}
async fetchMoreMessages({ direction }, opts = {}) {
@@ -261,7 +267,7 @@ export default class ChatChannel extends Component {
async scrollToBottom() {
this._ignoreNextScroll = true;
await scrollListToBottom(this.scroller);
- if (this.paneState.userIsPresent) {
+ if (this.paneState.shouldMarkRead()) {
this.debouncedUpdateLastReadMessage();
}
this.paneState.clearPendingMessages();
@@ -416,6 +422,13 @@ export default class ChatChannel extends Component {
}
}
+ @bind
+ maybeDebouncedUpdateLastReadMessage() {
+ if (this.paneState.shouldMarkRead()) {
+ this.debouncedUpdateLastReadMessage();
+ }
+ }
+
@bind
debouncedUpdateLastReadMessage() {
this._debouncedUpdateLastReadMessageHandler = discourseDebounce(
@@ -426,7 +439,7 @@ export default class ChatChannel extends Component {
}
updateLastReadMessage() {
- if (!this.paneState.userIsPresent) {
+ if (!this.paneState.shouldMarkRead()) {
return;
}
@@ -472,11 +485,11 @@ export default class ChatChannel extends Component {
}
@action
- scrollToLatestMessage() {
+ async scrollToLatestMessage() {
if (this.messagesLoader.canLoadMoreFuture) {
- this.fetchMessages();
+ await this.fetchMessages();
} else if (this.messagesManager.messages.length > 0) {
- this.scrollToBottom();
+ await this.scrollToBottom();
}
}
@@ -495,7 +508,7 @@ export default class ChatChannel extends Component {
state,
});
this.isScrolling = true;
- this.debouncedUpdateLastReadMessage();
+ this.maybeDebouncedUpdateLastReadMessage();
if (
state.atTop ||
@@ -514,8 +527,11 @@ export default class ChatChannel extends Component {
onScrollEnd(state) {
this.isScrolling = false;
this.atBottom = state.atBottom;
+ this.paneState.updateLiveEdgeFromScrollState(state);
if (state.atBottom) {
+ // Visible but unfocused panes can passively live-follow. Clear their
+ // pending affordance at the bottom while keeping hidden/away panes pending.
if (this.paneState.userIsPresent) {
this.paneState.clearPendingMessages();
}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs
index c198d51f9b7..4ae2209bfdf 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs
@@ -60,7 +60,7 @@ export default class ChatThread extends Component {
paneState = new ChatPaneState(getOwner(this), {
contextKey: this.pendingContextKey,
- onUserPresent: this.debouncedUpdateLastReadMessage,
+ onUserPresent: this.maybeDebouncedUpdateLastReadMessage,
});
@action
@@ -127,7 +127,7 @@ export default class ChatThread extends Component {
state,
});
this.isScrolling = true;
- this.debouncedUpdateLastReadMessage();
+ this.maybeDebouncedUpdateLastReadMessage();
if (
state.atTop ||
@@ -146,8 +146,11 @@ export default class ChatThread extends Component {
onScrollEnd(state) {
this.isScrolling = false;
this.atBottom = state.atBottom;
+ this.paneState.updateLiveEdgeFromScrollState(state);
if (state.atBottom) {
+ // Visible but unfocused panes can passively live-follow. Clear their
+ // pending affordance at the bottom while keeping hidden/away panes pending.
if (this.paneState.userIsPresent) {
this.paneState.clearPendingMessages();
}
@@ -162,6 +165,13 @@ export default class ChatThread extends Component {
}
}
+ @bind
+ maybeDebouncedUpdateLastReadMessage() {
+ if (this.paneState.shouldMarkRead()) {
+ this.debouncedUpdateLastReadMessage();
+ }
+ }
+
@bind
debouncedUpdateLastReadMessage() {
this._debouncedUpdateLastReadMessageHandler = discourseDebounce(
@@ -173,7 +183,7 @@ export default class ChatThread extends Component {
@bind
updateLastReadMessage() {
- if (!this.paneState.userIsPresent) {
+ if (!this.paneState.shouldMarkRead()) {
return;
}
@@ -219,7 +229,7 @@ export default class ChatThread extends Component {
didResizePane() {
this._ignoreNextScroll = true;
this.debounceFillPaneAttempt();
- this.debouncedUpdateLastReadMessage();
+ this.maybeDebouncedUpdateLastReadMessage();
DatesSeparatorsPositioner.apply(this.scroller);
this.paneState.updatePendingContentFromScrollerPosition({
@@ -295,11 +305,13 @@ export default class ChatThread extends Component {
}
@action
- scrollToLatestMessage() {
+ async scrollToLatestMessage() {
if (this.messagesLoader.canLoadMoreFuture) {
- this.fetchMessages();
+ await this.fetchMessages({
+ target_message_id: this.args.thread.lastMessageId,
+ });
} else if (this.messagesManager.messages.length > 0) {
- this.scrollToBottom();
+ await this.scrollToBottom();
}
}
@@ -344,11 +356,17 @@ export default class ChatThread extends Component {
@bind
onNewMessage(message) {
+ const isOwnMessage = message.user.id === this.currentUser.id;
+
this.paneState.handleIncomingMessage({
scroller: this.scroller,
- shouldAutoScroll: this.paneState.userIsPresent && this.atBottom,
+ shouldAutoScroll: this.paneState.shouldAutoScrollIncomingMessage({
+ isAtLiveEdge: this.paneState.isAtLiveEdge,
+ isOwnMessage,
+ }),
addMessage: () => this.messagesManager.addMessages([message]),
- onAutoAdd: () => this.debouncedUpdateLastReadMessage(),
+ onAutoAdd: () => this.maybeDebouncedUpdateLastReadMessage(),
+ isOwnMessage,
});
}
@@ -514,6 +532,9 @@ export default class ChatThread extends Component {
async scrollToBottom() {
this._ignoreNextScroll = true;
await scrollListToBottom(this.scroller);
+ if (this.paneState.shouldMarkRead()) {
+ this.debouncedUpdateLastReadMessage();
+ }
this.paneState.clearPendingMessages();
}
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js
index 0db9914161f..3155f223024 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js
@@ -4,7 +4,10 @@ import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { bind } from "discourse/lib/decorators";
import userPresent, {
+ browserAttention,
+ onBrowserAttentionChange as addBrowserAttentionChangeCallback,
onPresenceChange,
+ removeOnBrowserAttentionChange,
removeOnPresenceChange,
} from "discourse/lib/user-presence";
import { maintainScrollPosition } from "discourse/plugins/chat/discourse/lib/scroll-helpers";
@@ -14,6 +17,8 @@ const CHAT_PRESENCE_OPTIONS = {
browserHiddenTime: 0,
};
+const LIVE_EDGE_THRESHOLD_PIXELS = 10;
+
/**
* Shared state and helpers for chat panes (channel and thread).
*
@@ -43,6 +48,10 @@ export default class ChatPaneState {
* @type {boolean}
*/
@tracked userIsPresent = true;
+ @tracked isDocumentFocused = true;
+ @tracked isDocumentVisible = true;
+ @tracked wasAtLiveEdge = true;
+ @tracked isAtLiveEdge = true;
/**
* Whether there is pending content below the current scroll position.
@@ -78,10 +87,12 @@ export default class ChatPaneState {
this.contextKey = options.contextKey;
this.#onUserPresent = options.onUserPresent ?? null;
this.userIsPresent = userPresent(CHAT_PRESENCE_OPTIONS);
+ this.#refreshDocumentAttention();
onPresenceChange({
callback: this.onPresenceChangeCallback,
...CHAT_PRESENCE_OPTIONS,
});
+ addBrowserAttentionChangeCallback(this.onBrowserAttentionChange);
}
/**
@@ -89,6 +100,7 @@ export default class ChatPaneState {
*/
teardown() {
removeOnPresenceChange(this.onPresenceChangeCallback);
+ removeOnBrowserAttentionChange(this.onBrowserAttentionChange);
this.clearPendingMessages();
}
@@ -102,6 +114,12 @@ export default class ChatPaneState {
return this.chatPanePendingManager.hasPending(this.contextKey);
}
+ get isActiveReader() {
+ return (
+ this.userIsPresent && this.isDocumentFocused && this.isDocumentVisible
+ );
+ }
+
/**
* Checks if the scroller element has overflow (can scroll).
*
@@ -143,6 +161,14 @@ export default class ChatPaneState {
);
}
+ updateLiveEdgeFromScrollState(state) {
+ this.updateLiveEdgeFromDistance(state?.distanceToBottom?.pixels ?? 0);
+ }
+
+ updateLiveEdgeFromDistance(distanceToBottomPixels) {
+ this.isAtLiveEdge = distanceToBottomPixels <= LIVE_EDGE_THRESHOLD_PIXELS;
+ }
+
/**
* Updates hasPendingContentBelow based on scroll position and loader state.
*
@@ -182,6 +208,8 @@ export default class ChatPaneState {
distanceThresholdPixels,
} = options;
+ this.updateLiveEdgeFromScrollState(state);
+
this.#updateHasPendingContentBelow({
scroller,
fetchedOnce,
@@ -215,6 +243,7 @@ export default class ChatPaneState {
}
const distanceToBottomPixels = -scroller.scrollTop;
+ this.updateLiveEdgeFromDistance(distanceToBottomPixels);
this.#updateHasPendingContentBelow({
scroller,
@@ -233,8 +262,31 @@ export default class ChatPaneState {
*/
@bind
onPresenceChangeCallback(present) {
+ const wasActiveReader = this.isActiveReader;
this.userIsPresent = present;
- if (present) {
+ this.#handleActiveReaderTransition(wasActiveReader);
+ }
+
+ @bind
+ onBrowserAttentionChange(attention = browserAttention()) {
+ const wasActiveReader = this.isActiveReader;
+ this.#refreshDocumentAttention(attention);
+ this.#handleActiveReaderTransition(wasActiveReader);
+ }
+
+ #refreshDocumentAttention(attention = browserAttention()) {
+ this.isDocumentFocused = attention.focused;
+ this.isDocumentVisible = attention.visible;
+ }
+
+ #handleActiveReaderTransition(wasActiveReader) {
+ const isActiveReader = this.isActiveReader;
+
+ if (wasActiveReader && !isActiveReader) {
+ this.wasAtLiveEdge = this.isAtLiveEdge;
+ }
+
+ if (!wasActiveReader && isActiveReader) {
this.#onUserPresent?.();
}
}
@@ -284,6 +336,38 @@ export default class ChatPaneState {
});
}
+ shouldAutoScrollIncomingMessage({ isAtLiveEdge, isOwnMessage = false } = {}) {
+ if (!isAtLiveEdge) {
+ return false;
+ }
+
+ if (isOwnMessage) {
+ return true;
+ }
+
+ if (this.isActiveReader) {
+ return true;
+ }
+
+ if (!this.isDocumentVisible) {
+ return false;
+ }
+
+ if (this.isDocumentFocused) {
+ return false;
+ }
+
+ return this.#shouldContinueLiveFollowing();
+ }
+
+ shouldMarkRead() {
+ return this.isActiveReader;
+ }
+
+ #shouldContinueLiveFollowing() {
+ return this.wasAtLiveEdge;
+ }
+
/**
* Compute whether there is pending content below the current scroll position.
*
diff --git a/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs b/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs
index 702599135bd..e49a005c484 100644
--- a/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs
+++ b/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs
@@ -4,6 +4,7 @@ import { module, test } from "qunit";
import sinon from "sinon";
import {
clearPresenceCallbacks,
+ processBrowserAttentionChange,
setTestPresence,
} from "discourse/lib/user-presence";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -24,6 +25,40 @@ function setScrollerHeight(scroller, { clientHeight, scrollHeight }) {
});
}
+function stubDocumentAttention({
+ hasFocus = true,
+ visibilityState = "visible",
+}) {
+ sinon.stub(document, "hasFocus").returns(hasFocus);
+ sinon.stub(document, "visibilityState").value(visibilityState);
+}
+
+function publishChannelMessage(channelId, messageId, user) {
+ publishToMessageBus(`/chat/${channelId}`, {
+ type: "sent",
+ chat_message: {
+ id: messageId,
+ message: `hello ${messageId}`,
+ cooked: `<p>hello ${messageId}</p>`,
+ excerpt: `hello ${messageId}`,
+ created_at: "2025-01-01T00:00:00.000Z",
+ user,
+ },
+ });
+}
+
+function setChannelMembership(channel, lastReadMessageId = 1) {
+ channel.currentUserMembership.following = true;
+ channel.currentUserMembership.lastReadMessageId = lastReadMessageId;
+}
+
+function readRequests() {
+ return pretender.handledRequests.filter(
+ ({ method, url }) =>
+ method === "PUT" && url.startsWith("/chat/api/channels/1/read")
+ );
+}
+
module("Unit | Components | presence gating", function (hooks) {
setupRenderingTest(hooks);
@@ -56,6 +91,12 @@ module("Unit | Components | presence gating", function (hooks) {
},
})
);
+ pretender.put(`/chat/api/channels/1/read`, () =>
+ response({ success: true })
+ );
+ pretender.post(`/chat/api/channels/1/drafts`, () =>
+ response({ success: true })
+ );
});
hooks.afterEach(function () {
@@ -65,10 +106,7 @@ module("Unit | Components | presence gating", function (hooks) {
});
test("does not show arrow when user not present but pane cannot scroll", async function (assert) {
- const channel = this.fabricators.channel({
- id: 1,
- currentUserMembership: { following: true, last_read_message_id: 1 },
- });
+ const channel = this.fabricators.channel({ id: 1 });
const readUpdateStub = sinon.stub(
ChatChannel.prototype,
@@ -109,10 +147,7 @@ module("Unit | Components | presence gating", function (hooks) {
});
test("shows arrow when user not present and pane can scroll", async function (assert) {
- const channel = this.fabricators.channel({
- id: 1,
- currentUserMembership: { following: true, last_read_message_id: 1 },
- });
+ const channel = this.fabricators.channel({ id: 1 });
this.channel = channel;
await render(
@@ -143,10 +178,7 @@ module("Unit | Components | presence gating", function (hooks) {
});
test("pending manager tracks messages across contexts", async function (assert) {
- const channel = this.fabricators.channel({
- id: 1,
- currentUserMembership: { following: true, last_read_message_id: 1 },
- });
+ const channel = this.fabricators.channel({ id: 1 });
this.channel = channel;
await render(
@@ -183,10 +215,7 @@ module("Unit | Components | presence gating", function (hooks) {
});
test("clears pending state when scrolling to bottom", async function (assert) {
- const channel = this.fabricators.channel({
- id: 1,
- currentUserMembership: { following: true, last_read_message_id: 1 },
- });
+ const channel = this.fabricators.channel({ id: 1 });
this.channel = channel;
await render(
@@ -234,10 +263,7 @@ module("Unit | Components | presence gating", function (hooks) {
});
test("pending count contributes to document title", async function (assert) {
- const channel = this.fabricators.channel({
- id: 1,
- currentUserMembership: { following: true, last_read_message_id: 1 },
- });
+ const channel = this.fabricators.channel({ id: 1 });
this.channel = channel;
await render(
@@ -267,11 +293,125 @@ module("Unit | Components | presence gating", function (hooks) {
);
});
+ test("unfocused visible window at bottom follows without marking read until focus", async function (assert) {
+ setTestPresence(true);
+ stubDocumentAttention({ hasFocus: false, visibilityState: "visible" });
+
+ const channel = this.fabricators.channel({ id: 1 });
+ setChannelMembership(channel);
+ const otherUser = { id: 9999, username: "other" };
+
+ this.channel = channel;
+ await render(
+ <template><ChatChannel @channel={{this.channel}} /></template>
+ );
+
+ pretender.handledRequests.length = 0;
+
+ publishChannelMessage(1, 999, otherUser);
+ publishChannelMessage(1, 1000, otherUser);
+ publishChannelMessage(1, 1001, otherUser);
+ await settled();
+
+ assert.strictEqual(
+ channel.messagesManager.messages.length,
+ 3,
+ "appends messages while passively following"
+ );
+ assert.strictEqual(
+ readRequests().length,
+ 0,
+ "does not schedule read update"
+ );
+ assert.strictEqual(
+ channel.currentUserMembership.lastReadMessageId,
+ 1,
+ "does not advance local durable read state while unfocused"
+ );
+ assert
+ .dom(".chat-scroll-to-bottom__button.visible")
+ .doesNotExist("does not show the scroll arrow while live-following");
+
+ document.hasFocus.returns(true);
+ processBrowserAttentionChange();
+ await settled();
+
+ assert.strictEqual(
+ readRequests().length,
+ 1,
+ "marks read when focus returns"
+ );
+ assert.strictEqual(
+ channel.currentUserMembership.lastReadMessageId,
+ 1001,
+ "advances local durable read state when focus returns"
+ );
+ });
+
+ test("hidden tab enqueues messages without marking read", async function (assert) {
+ setTestPresence(true);
+ stubDocumentAttention({ hasFocus: false, visibilityState: "hidden" });
+
+ const channel = this.fabricators.channel({ id: 1 });
+ setChannelMembership(channel);
+ const otherUser = { id: 9999, username: "other" };
+
+ const readUpdateStub = sinon.stub(
+ ChatChannel.prototype,
+ "debouncedUpdateLastReadMessage"
+ );
+
+ this.channel = channel;
+ await render(
+ <template><ChatChannel @channel={{this.channel}} /></template>
+ );
+
+ setScrollerHeight(this.element.querySelector(".chat-messages-scroller"), {
+ clientHeight: 100,
+ scrollHeight: 500,
+ });
+ readUpdateStub.resetHistory();
+
+ publishChannelMessage(1, 999, otherUser);
+ await settled();
+
+ assert.false(readUpdateStub.called, "does not schedule read update");
+ assert
+ .dom(".chat-scroll-to-bottom__button.visible")
+ .exists("shows jump affordance for hidden-tab messages");
+ });
+
+ test("own messages still follow while unfocused", async function (assert) {
+ setTestPresence(true);
+ stubDocumentAttention({ hasFocus: false, visibilityState: "visible" });
+
+ const channel = this.fabricators.channel({ id: 1 });
+
+ this.channel = channel;
+ await render(
+ <template><ChatChannel @channel={{this.channel}} /></template>
+ );
+
+ publishChannelMessage(1, 999, {
+ id: this.currentUser.id,
+ username: this.currentUser.username,
+ });
+ await settled();
+
+ assert.strictEqual(
+ channel.messagesManager.messages.length,
+ 1,
+ "appends the current user's message"
+ );
+ assert
+ .dom(".chat-scroll-to-bottom__button.visible")
+ .doesNotExist("does not show the scroll arrow for own live messages");
+ });
+
test("thread enqueues messages when user not present", async function (assert) {
const thread = this.fabricators.thread({
id: 1,
channel: this.fabricators.channel({ id: 1 }),
- currentUserMembership: { last_read_message_id: 1 },
});
const readUpdateStub = sinon.stub(
diff --git a/plugins/chat/test/javascripts/unit/lib/chat-pane-state-test.js b/plugins/chat/test/javascripts/unit/lib/chat-pane-state-test.js
new file mode 100644
index 00000000000..fd2ef8624d5
--- /dev/null
+++ b/plugins/chat/test/javascripts/unit/lib/chat-pane-state-test.js
@@ -0,0 +1,128 @@
+import { getOwner } from "@ember/owner";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import {
+ clearPresenceCallbacks,
+ setTestPresence,
+} from "discourse/lib/user-presence";
+import ChatPaneState from "discourse/plugins/chat/discourse/lib/chat-pane-state";
+
+module("Unit | Lib | chat-pane-state", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ setTestPresence(true);
+ sinon.stub(document, "hasFocus").returns(false);
+ sinon.stub(document, "visibilityState").value("visible");
+ });
+
+ hooks.afterEach(function () {
+ setTestPresence(true);
+ clearPresenceCallbacks();
+ sinon.restore();
+ });
+
+ test("live-follow can continue while unfocused without marking read", function (assert) {
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ });
+ let addedMessageCount = 0;
+ const addMessage = () => addedMessageCount++;
+
+ for (let i = 0; i < 700; i++) {
+ paneState.handleIncomingMessage({
+ shouldAutoScroll: true,
+ addMessage,
+ });
+ }
+
+ assert.strictEqual(addedMessageCount, 700, "live-follow can continue");
+ assert.false(paneState.shouldMarkRead(), "suppresses read acknowledgement");
+
+ paneState.teardown();
+ });
+
+ test("active-reader transition runs return callback when focus returns", function (assert) {
+ const onUserPresent = sinon.spy();
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ onUserPresent,
+ });
+
+ document.hasFocus.returns(true);
+ paneState.onBrowserAttentionChange();
+
+ assert.true(onUserPresent.calledOnce, "notifies the pane to mark read");
+ assert.true(paneState.shouldMarkRead(), "allows read acknowledgements");
+
+ paneState.teardown();
+ });
+
+ test("own messages can live-follow while unfocused", function (assert) {
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ });
+
+ assert.true(
+ paneState.shouldAutoScrollIncomingMessage({
+ isAtLiveEdge: true,
+ isOwnMessage: true,
+ }),
+ "own messages keep following the live edge"
+ );
+
+ paneState.teardown();
+ });
+
+ test("active readers can mark visible messages read away from the live edge", function (assert) {
+ document.hasFocus.returns(true);
+
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ });
+
+ paneState.updateLiveEdgeFromDistance(250);
+
+ assert.true(
+ paneState.shouldMarkRead(),
+ "read acknowledgement follows attention, not only the live edge"
+ );
+
+ paneState.teardown();
+ });
+
+ test("uses a small live-edge threshold", function (assert) {
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ });
+
+ paneState.updateLiveEdgeFromDistance(11);
+ assert.false(paneState.isAtLiveEdge, "11px from the bottom is not live");
+
+ paneState.updateLiveEdgeFromDistance(10);
+ assert.true(paneState.isAtLiveEdge, "10px from the bottom is live");
+
+ paneState.teardown();
+ });
+
+ test("captures live-edge state when the reader becomes passive", function (assert) {
+ document.hasFocus.returns(true);
+
+ const paneState = new ChatPaneState(getOwner(this), {
+ contextKey: "channel:1",
+ });
+
+ paneState.updateLiveEdgeFromDistance(250);
+ paneState.updateLiveEdgeFromDistance(0);
+ document.hasFocus.returns(false);
+ paneState.onBrowserAttentionChange();
+
+ assert.true(
+ paneState.shouldAutoScrollIncomingMessage({ isAtLiveEdge: true }),
+ "continues live-follow after focus leaves while at the live edge"
+ );
+
+ paneState.teardown();
+ });
+});