A platform for community discussion. Free, open, simple.
FEATURE: respect user presence when chat is on screen (#36652)
Samd85becccefbe
diff --git a/frontend/discourse/app/instance-initializers/message-bus.js b/frontend/discourse/app/instance-initializers/message-bus.jsindex 162539945e5..92f9aee3cec 100644--- a/frontend/discourse/app/instance-initializers/message-bus.js+++ b/frontend/discourse/app/instance-initializers/message-bus.js@@ -75,7 +75,7 @@ export default {// present// When 20 minutes pass we stop long polling due to "shouldLongPollCallback".onPresenceChange({- unseenTime: LONG_POLL_AFTER_UNSEEN_TIME,+ userUnseenTime: LONG_POLL_AFTER_UNSEEN_TIME,callback: (present) => {if (present && messageBus.onVisibilityChange) {messageBus.onVisibilityChange();diff --git a/frontend/discourse/app/lib/user-presence.js b/frontend/discourse/app/lib/user-presence.jsindex 3ba9e7143d9..04fc14cec5b 100644--- a/frontend/discourse/app/lib/user-presence.js+++ b/frontend/discourse/app/lib/user-presence.js@@ -7,11 +7,10 @@ const DEFAULT_BROWSER_HIDDEN_MS = 0;let browserHiddenAt = null;let lastUserActivity = Date.now();-let userSeenJustNow = false;-let callbackWaitingForPresence = false;let testPresence = true;+let debounceUpdateDateTimeout = null;// Check whether the document is currently visible, and the user is actively using the site// Will return false if the browser went into the background more than `browserHiddenTime` milliseconds ago@@ -52,17 +51,22 @@ export function onPresenceChange({if (userUnseenTime < DEFAULT_USER_UNSEEN_MS) {throw `userUnseenTime must be at least ${DEFAULT_USER_UNSEEN_MS}`;}+ if (browserHiddenTime < 0) {+ throw "browserHiddenTime must be non-negative";+ }callbacks.push({userUnseenTime,browserHiddenTime,- lastState: true,+ lastState: userPresent({ userUnseenTime, browserHiddenTime }),callback,});}export function removeOnPresenceChange(callback) {const i = callbacks.findIndex((c) => c.callback === callback);- callbacks.splice(i, 1);+ if (i > -1) {+ callbacks.splice(i, 1);+ }}function processChanges() {@@ -71,11 +75,6 @@ function processChanges() {browserHiddenAt = browserHidden ? Date.now() : null;}- if (userSeenJustNow) {- lastUserActivity = Date.now();- userSeenJustNow = false;- }-callbackWaitingForPresence = false;for (const callback of callbacks) {const currentState = userPresent({@@ -86,6 +85,9 @@ function processChanges() {if (callback.lastState !== currentState) {try {callback.callback(currentState);+ } catch (e) {+ // eslint-disable-next-line no-console+ console.error("Error in presence change callback:", e);} finally {callback.lastState = currentState;}@@ -98,9 +100,25 @@ function processChanges() {}export function seenUser() {- userSeenJustNow = true;+ // a boolean check is going to be 10x to 80x faster than Date.now()+ // scroll, touchmove, click, keydown can all happen very frequently+ // this debounces to de-riskif (callbackWaitingForPresence) {+ if (debounceUpdateDateTimeout) {+ clearTimeout(debounceUpdateDateTimeout);+ debounceUpdateDateTimeout = null;+ }+ // we are in the background waiting for presence, do this right away+ lastUserActivity = Date.now();processChanges();+ } else {+ // app is in foreground, debounce updates to lastUserActivity+ if (!debounceUpdateDateTimeout) {+ debounceUpdateDateTimeout = setTimeout(() => {+ debounceUpdateDateTimeout = null;+ lastUserActivity = Date.now();+ }, 1000);+ }}}@@ -127,6 +145,7 @@ if (!isTesting()) {// 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 });diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex 86dc5f32647..bf10fbd571a 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -12,10 +12,6 @@ import { popupAjaxError } from "discourse/lib/ajax-error";import discourseDebounce from "discourse/lib/debounce";import { bind } from "discourse/lib/decorators";import DiscourseURL from "discourse/lib/url";-import {- onPresenceChange,- removeOnPresenceChange,-} from "discourse/lib/user-presence";import { and, not } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";import ChatChannelStatus from "discourse/plugins/chat/discourse/components/chat-channel-status";@@ -27,6 +23,7 @@ import {READ_INTERVAL_MS,} from "discourse/plugins/chat/discourse/lib/chat-constants";import ChatMessagesLoader from "discourse/plugins/chat/discourse/lib/chat-messages-loader";+import ChatPaneState from "discourse/plugins/chat/discourse/lib/chat-pane-state";import { checkMessageTopVisibility } from "discourse/plugins/chat/discourse/lib/check-message-visibility";import DatesSeparatorsPositioner from "discourse/plugins/chat/discourse/lib/dates-separators-positioner";import { extractCurrentTopicInfo } from "discourse/plugins/chat/discourse/lib/extract-current-topic-info";@@ -65,16 +62,26 @@ export default class ChatChannel extends Component {@tracked sending = false;@tracked showChatQuoteSuccess = false;@tracked includeHeader = true;- @tracked needsArrow = false;@tracked atBottom = true;@tracked uploadDropZone;@tracked isScrolling = false;scroller = null;++ paneState = new ChatPaneState(getOwner(this), {+ contextKey: this.pendingContextKey,+ onUserPresent: this.debouncedUpdateLastReadMessage,+ });+_mentionWarningsSeen = {};_unreachableGroupMentions = [];_overMembersLimitGroupMentions = [];+ @action+ registerScroller(element) {+ this.scroller = element;+ }+@cachedget messagesLoader() {return new ChatMessagesLoader(getOwner(this), this.args.channel);@@ -92,16 +99,15 @@ export default class ChatChannel extends Component {return !!this.chatChannelScrollPositions.get(this.args.channel.id);}- @action- registerScroller(element) {- this.scroller = element;+ get pendingContextKey() {+ return this.args.channel?.id ? `channel:${this.args.channel.id}` : null;}@actionteardown() {document.removeEventListener("keydown", this._autoFocus);this.#cancelHandlers();- removeOnPresenceChange(this.onPresenceChangeCallback);+ this.paneState.teardown();this.subscriptionManager.teardown();this.updateLastReadMessage();@@ -116,13 +122,18 @@ export default class ChatChannel extends Component {this.debounceFillPaneAttempt();this.debouncedUpdateLastReadMessage();DatesSeparatorsPositioner.apply(this.scroller);++ this.paneState.updatePendingContentFromScrollerPosition({+ scroller: this.scroller,+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ });}@actionsetup(element) {this.uploadDropZone = element;document.addEventListener("keydown", this._autoFocus);- onPresenceChange({ callback: this.onPresenceChangeCallback });this.messagesManager.clear();@@ -179,21 +190,12 @@ export default class ChatChannel extends Component {@bindonNewMessage(message) {- if (!this.atBottom) {- this.needsArrow = true;- this.messagesLoader.canLoadMoreFuture = true;- return;- }-- this.messagesManager.addMessages([message]);- this.debouncedUpdateLastReadMessage();- }-- @bind- onPresenceChangeCallback(present) {- if (present) {- this.debouncedUpdateLastReadMessage();- }+ this.paneState.handleIncomingMessage({+ scroller: this.scroller,+ shouldAutoScroll: this.paneState.userIsPresent && this.atBottom,+ addMessage: () => this.messagesManager.addMessages([message]),+ onAutoAdd: () => this.debouncedUpdateLastReadMessage(),+ });}async fetchMessages(findArgs = {}) {@@ -263,7 +265,10 @@ export default class ChatChannel extends Component {async scrollToBottom() {this._ignoreNextScroll = true;await scrollListToBottom(this.scroller);- this.debouncedUpdateLastReadMessage();+ if (this.paneState.userIsPresent) {+ this.debouncedUpdateLastReadMessage();+ }+ this.paneState.clearPendingMessages();}scrollToMessageId(messageId, options = {}) {@@ -406,6 +411,7 @@ export default class ChatChannel extends Component {}}+ @binddebouncedUpdateLastReadMessage() {this._debouncedUpdateLastReadMessageHandler = discourseDebounce(this,@@ -415,6 +421,10 @@ export default class ChatChannel extends Component {}updateLastReadMessage() {+ if (!this.paneState.userIsPresent) {+ return;+ }+if (!this.args.channel.isFollowing) {return;}@@ -452,7 +462,7 @@ export default class ChatChannel extends Component {if (this.messagesLoader.canLoadMoreFuture) {this.fetchMessages();} else if (this.messagesManager.messages.length > 0) {- this.scrollToBottom(this.scroller);+ this.scrollToBottom();}}@@ -464,11 +474,11 @@ export default class ChatChannel extends Component {}DatesSeparatorsPositioner.apply(this.scroller);-- this.needsArrow =- (this.messagesLoader.fetchedOnce &&- this.messagesLoader.canLoadMoreFuture) ||- (state.distanceToBottom.pixels > 250 && !state.atBottom);+ this.paneState.updatePendingContentFromScrollState({+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ state,+ });this.isScrolling = true;this.debouncedUpdateLastReadMessage();@@ -487,17 +497,19 @@ export default class ChatChannel extends Component {@actiononScrollEnd(state) {- this.needsArrow =- (this.messagesLoader.fetchedOnce &&- this.messagesLoader.canLoadMoreFuture) ||- (state.distanceToBottom.pixels > 250 && !state.atBottom);this.isScrolling = false;this.atBottom = state.atBottom;if (state.atBottom) {+ this.paneState.clearPendingMessages();this.fetchMoreMessages({ direction: FUTURE });this.chatChannelScrollPositions.delete(this.args.channel.id);} else {+ this.paneState.updatePendingContentFromScrollState({+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ state,+ });this.chatChannelScrollPositions.set(this.args.channel.id,state.firstVisibleId@@ -748,7 +760,7 @@ export default class ChatChannel extends Component {<ChatScrollToBottomArrow@onScrollToBottom={{this.scrollToLatestMessage}}- @isVisible={{this.needsArrow}}+ @isVisible={{this.paneState.hasPendingContentBelow}}/>{{#if this.pane.selectingMessages}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjsindex 5ecea743e9d..e0e2b1d348b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs@@ -21,6 +21,7 @@ import {READ_INTERVAL_MS,} from "discourse/plugins/chat/discourse/lib/chat-constants";import ChatMessagesLoader from "discourse/plugins/chat/discourse/lib/chat-messages-loader";+import ChatPaneState from "discourse/plugins/chat/discourse/lib/chat-pane-state";import DatesSeparatorsPositioner from "discourse/plugins/chat/discourse/lib/dates-separators-positioner";import { extractCurrentTopicInfo } from "discourse/plugins/chat/discourse/lib/extract-current-topic-info";import {@@ -55,11 +56,20 @@ export default class ChatThread extends Component {@tracked atBottom = true;@tracked isScrolling = false;- @tracked needsArrow = false;@tracked uploadDropZone;scroller = null;+ paneState = new ChatPaneState(getOwner(this), {+ contextKey: this.pendingContextKey,+ onUserPresent: this.debouncedUpdateLastReadMessage,+ });++ @action+ registerScroller(element) {+ this.scroller = element;+ }+@cachedget messagesLoader() {return new ChatMessagesLoader(getOwner(this), this.args.thread);@@ -74,6 +84,10 @@ export default class ChatThread extends Component {return channel?.isCategoryChannel && !channel?.isFollowing;}+ get pendingContextKey() {+ return this.args.thread?.id ? `thread:${this.args.thread.id}` : null;+ }+@actionhandleKeydown(event) {if (event.key === "Escape") {@@ -104,9 +118,10 @@ export default class ChatThread extends Component {@actionteardown() {+ this.paneState.teardown();this.subscriptionManager.teardown();cancel(this._debouncedFillPaneAttemptHandler);- cancel(this._debounceUpdateLastReadMessageHandler);+ cancel(this._debouncedUpdateLastReadMessageHandler);}@action@@ -117,13 +132,13 @@ export default class ChatThread extends Component {}DatesSeparatorsPositioner.apply(this.scroller);-- this.needsArrow =- (this.messagesLoader.fetchedOnce &&- this.messagesLoader.canLoadMoreFuture) ||- (state.distanceToBottom.pixels > 250 && !state.atBottom);+ this.paneState.updatePendingContentFromScrollState({+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ state,+ });this.isScrolling = true;- this.debounceUpdateLastReadMessage();+ this.debouncedUpdateLastReadMessage();if (state.atTop ||@@ -140,20 +155,24 @@ export default class ChatThread extends Component {@actiononScrollEnd(state) {- this.needsArrow =- (this.messagesLoader.fetchedOnce &&- this.messagesLoader.canLoadMoreFuture) ||- (state.distanceToBottom.pixels > 250 && !state.atBottom);this.isScrolling = false;this.atBottom = state.atBottom;if (state.atBottom) {+ this.paneState.clearPendingMessages();this.fetchMoreMessages({ direction: FUTURE });+ } else {+ this.paneState.updatePendingContentFromScrollState({+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ state,+ });}}- debounceUpdateLastReadMessage() {- this._debounceUpdateLastReadMessageHandler = discourseDebounce(+ @bind+ debouncedUpdateLastReadMessage() {+ this._debouncedUpdateLastReadMessageHandler = discourseDebounce(this,this.updateLastReadMessage,READ_INTERVAL_MS@@ -162,6 +181,10 @@ export default class ChatThread extends Component {@bindupdateLastReadMessage() {+ if (!this.paneState.userIsPresent) {+ return;+ }+if (!this.args.thread?.currentUserMembership) {return;}@@ -190,11 +213,6 @@ export default class ChatThread extends Component {);}- @action- registerScroller(element) {- this.scroller = element;- }-@actionloadMessages() {this.fetchMessages();@@ -209,8 +227,14 @@ export default class ChatThread extends Component {didResizePane() {this._ignoreNextScroll = true;this.debounceFillPaneAttempt();- this.debounceUpdateLastReadMessage();+ this.debouncedUpdateLastReadMessage();DatesSeparatorsPositioner.apply(this.scroller);++ this.paneState.updatePendingContentFromScrollerPosition({+ scroller: this.scroller,+ fetchedOnce: this.messagesLoader.fetchedOnce,+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,+ });}async fetchMessages(findArgs = {}) {@@ -328,13 +352,12 @@ export default class ChatThread extends Component {@bindonNewMessage(message) {- if (!this.atBottom) {- this.needsArrow = true;- this.messagesLoader.canLoadMoreFuture = true;- return;- }-- this.messagesManager.addMessages([message]);+ this.paneState.handleIncomingMessage({+ scroller: this.scroller,+ shouldAutoScroll: this.paneState.userIsPresent && this.atBottom,+ addMessage: () => this.messagesManager.addMessages([message]),+ onAutoAdd: () => this.debouncedUpdateLastReadMessage(),+ });}@bind@@ -499,6 +522,7 @@ export default class ChatThread extends Component {async scrollToBottom() {this._ignoreNextScroll = true;await scrollListToBottom(this.scroller);+ this.paneState.clearPendingMessages();}@action@@ -570,7 +594,7 @@ export default class ChatThread extends Component {<ChatScrollToBottomArrow@onScrollToBottom={{this.scrollToLatestMessage}}- @isVisible={{this.needsArrow}}+ @isVisible={{this.paneState.hasPendingContentBelow}}/>{{#if this.chatThreadPane.selectingMessages}}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.jsnew file mode 100644index 00000000000..f4404364d10--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js@@ -0,0 +1,309 @@+import { tracked } from "@glimmer/tracking";+import { setOwner } from "@ember/owner";+import { schedule } from "@ember/runloop";+import { service } from "@ember/service";+import { bind } from "discourse/lib/decorators";+import userPresent, {+ onPresenceChange,+ removeOnPresenceChange,+} from "discourse/lib/user-presence";+import { maintainScrollPosition } from "discourse/plugins/chat/discourse/lib/scroll-helpers";++const CHAT_PRESENCE_OPTIONS = {+ userUnseenTime: 1 * 60 * 1000,+ browserHiddenTime: 0,+};++/**+ * Shared state and helpers for chat panes (channel and thread).+ *+ * Manages:+ * - User presence detection (is the user actively viewing the tab?)+ * - Pending message tracking (messages that arrived while scrolled away)+ * - Pending content indicator visibility+ *+ * Used via composition rather than inheritance so callers can be explicit+ * about which behaviors they're invoking.+ *+ * @example+ * ```js+ * this.paneState = new ChatPaneState(getOwner(this), {+ * contextKey: `channel:${this.channel.id}`,+ * onUserPresent: this.handleUserReturned,+ * });+ * // Call teardown() when done+ * ```+ */+export default class ChatPaneState {+ @service chatPanePendingManager;++ /**+ * Whether the user is currently present (tab visible and recently active).+ *+ * @type {boolean}+ */+ @tracked userIsPresent = true;++ /**+ * Whether there is pending content below the current scroll position.+ * True when there are pending messages or the user is scrolled away.+ *+ * @type {boolean}+ */+ @tracked hasPendingContentBelow = false;++ /**+ * Identifier for this chat context (e.g. "channel-123" or "thread-456").+ * Used to track pending messages per-context in ChatPanePendingManager.+ *+ * @type {string | null}+ */+ contextKey = null;++ /**+ * Callback invoked when user returns after being away.+ *+ * @type {(() => void) | null}+ */+ #onUserPresent = null;++ /**+ * @param {object} owner - The Ember owner for dependency injection+ * @param {object} options+ * @param {string} options.contextKey - The context identifier (e.g. "channel-123")+ * @param {(() => void) | null} [options.onUserPresent] - Called when user returns+ */+ constructor(owner, options) {+ setOwner(this, owner);+ this.contextKey = options.contextKey;+ this.#onUserPresent = options.onUserPresent ?? null;+ this.userIsPresent = userPresent(CHAT_PRESENCE_OPTIONS);+ onPresenceChange({+ callback: this.onPresenceChangeCallback,+ ...CHAT_PRESENCE_OPTIONS,+ });+ }++ /**+ * Cleanup presence tracking. Call from component teardown (e.g. willDestroy).+ */+ teardown() {+ removeOnPresenceChange(this.onPresenceChangeCallback);+ this.clearPendingMessages();+ }++ /**+ * Whether there are pending messages for this context.+ * Reads from ChatPanePendingManager (the single source of truth).+ *+ * @returns {boolean}+ */+ get hasPendingMessages() {+ return this.chatPanePendingManager.hasPending(this.contextKey);+ }++ /**+ * Checks if the scroller element has overflow (can scroll).+ *+ * @param {HTMLElement | null} scroller+ * @returns {boolean}+ */+ #canScroll(scroller) {+ if (!scroller) {+ return false;+ }++ // Use a small tolerance because scrollHeight and clientHeight can+ // occasionally differ by subpixel rounding.+ return scroller.scrollHeight - scroller.clientHeight > 1;+ }++ /**+ * Computes whether the user is scrolled away from the bottom.+ * True if there are more messages to load OR they've scrolled up past the threshold.+ *+ * @param {object} options+ * @param {boolean} options.fetchedOnce - Whether initial fetch has completed+ * @param {boolean} options.canLoadMoreFuture - Whether more future messages exist+ * @param {number} options.distanceToBottomPixels - Current distance from bottom+ * @param {number} [options.distanceThresholdPixels=250] - Threshold to trigger "scrolled away"+ * @returns {boolean}+ */+ #computeIsScrolledAway(options) {+ const {+ fetchedOnce,+ canLoadMoreFuture,+ distanceToBottomPixels,+ distanceThresholdPixels = 250,+ } = options;++ return (+ (fetchedOnce && canLoadMoreFuture) ||+ distanceToBottomPixels > distanceThresholdPixels+ );+ }++ /**+ * Updates hasPendingContentBelow based on scroll position and loader state.+ *+ * @param {object} options+ * @param {HTMLElement | null} options.scroller+ * @param {boolean} options.fetchedOnce+ * @param {boolean} options.canLoadMoreFuture+ * @param {number} options.distanceToBottomPixels+ * @param {number} [options.distanceThresholdPixels]+ */+ #updateHasPendingContentBelow(options) {+ const { scroller } = options;+ const isScrolledAway = this.#computeIsScrolledAway(options);+ this.hasPendingContentBelow = this.#computeHasPendingContentBelow(+ scroller,+ isScrolledAway+ );+ }++ /**+ * Update pending content state from a scroll event's state object.+ * Use this in scroll handlers that already have distanceToBottom computed.+ *+ * @param {object} options+ * @param {boolean} options.fetchedOnce+ * @param {boolean} options.canLoadMoreFuture+ * @param {object} options.state - Scroll state with scroller and distanceToBottom+ * @param {number} [options.distanceThresholdPixels]+ */+ updatePendingContentFromScrollState(options) {+ const { fetchedOnce, canLoadMoreFuture, state, distanceThresholdPixels } =+ options;++ this.#updateHasPendingContentBelow({+ scroller: state?.scroller,+ fetchedOnce,+ canLoadMoreFuture,+ distanceToBottomPixels: state?.distanceToBottom?.pixels ?? 0,+ distanceThresholdPixels,+ });+ }++ /**+ * Update pending content state by reading current scroller position.+ * Use this when you need to recompute after a resize or similar event.+ *+ * @param {object} options+ * @param {HTMLElement | null} options.scroller+ * @param {boolean} options.fetchedOnce+ * @param {boolean} options.canLoadMoreFuture+ * @param {number} [options.distanceThresholdPixels]+ */+ updatePendingContentFromScrollerPosition(options) {+ const {+ scroller,+ fetchedOnce,+ canLoadMoreFuture,+ distanceThresholdPixels,+ } = options;++ if (!scroller) {+ this.hasPendingContentBelow = false;+ return;+ }++ const distanceToBottomPixels = -scroller.scrollTop;++ this.#updateHasPendingContentBelow({+ scroller,+ fetchedOnce,+ canLoadMoreFuture,+ distanceToBottomPixels,+ distanceThresholdPixels,+ });+ }++ /**+ * Callback for presence change events. Updates userIsPresent and+ * triggers onUserPresent callback when user returns.+ *+ * @param {boolean} present+ */+ @bind+ onPresenceChangeCallback(present) {+ this.userIsPresent = present;+ if (present) {+ this.#onUserPresent?.();+ }+ }++ /**+ * Handle an incoming message by either auto-scrolling or preserving viewport.+ *+ * If shouldAutoScroll is true, adds the message and scrolls to show it.+ * Otherwise, preserves the current scroll position and tracks the message as pending.+ *+ * @param {object} options+ * @param {HTMLElement | null} options.scroller - The scrollable container+ * @param {boolean} options.shouldAutoScroll - Whether to auto-scroll to the new message+ * @param {Function} options.addMessage - Function that adds the message to the list+ * @param {Function} [options.onAutoAdd] - Callback after auto-adding (e.g. to scroll)+ * @param {number} [options.messageCount=1] - Number of messages being added+ */+ handleIncomingMessage(options = {}) {+ const {+ scroller,+ shouldAutoScroll,+ addMessage,+ onAutoAdd,+ messageCount = 1,+ } = options;++ if (shouldAutoScroll) {+ addMessage?.();+ this.clearPendingMessages();+ onAutoAdd?.();+ return;+ }++ maintainScrollPosition(scroller, addMessage);+ this.addPendingMessages(messageCount);++ schedule("afterRender", () => {+ this.hasPendingContentBelow = this.#computeHasPendingContentBelow(+ scroller,+ false+ );+ });+ }++ /**+ * Compute whether there is pending content below the current scroll position.+ *+ * @param {HTMLElement | null} scroller+ * @param {boolean} isScrolledAway - Whether user is scrolled away from bottom+ * @returns {boolean}+ */+ #computeHasPendingContentBelow(scroller, isScrolledAway) {+ return (+ this.#canScroll(scroller) && (this.hasPendingMessages || isScrolledAway)+ );+ }++ /**+ * Add pending messages to the count for this context.+ *+ * @param {number} [count=1] - Number of messages to add+ */+ addPendingMessages(count = 1) {+ if (this.contextKey && count > 0) {+ this.chatPanePendingManager.add(this.contextKey, count);+ }+ }++ /**+ * Clear all pending messages for this context and reset pending content state.+ */+ clearPendingMessages() {+ if (this.contextKey) {+ this.chatPanePendingManager.clear(this.contextKey);+ }+ this.hasPendingContentBelow = false;+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.jsindex 30179374ddd..0ce49eceb3c 100644--- a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js+++ b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js@@ -1,5 +1,60 @@import { next, schedule } from "@ember/runloop";+/**+ * Tracks pending scroll adjustments to handle re-entrant calls.+ * Maps scroller elements to their captured state.+ *+ * @type {WeakMap<HTMLElement, { scrollTop: number; scrollHeight: number }>}+ */+const pendingAdjustments = new WeakMap();++/**+ * Prevent viewport drift when the list grows while scrolled away from bottom.+ *+ * Our chat scroller uses flex-direction: column-reverse for bottom-origin scroll.+ * Appending content can shift the viewport unless we compensate for height changes.+ *+ * @param {HTMLElement | null} scroller - The scrollable container+ * @param {Function} callback - Function that modifies the list content+ */+export function maintainScrollPosition(scroller, callback) {+ if (!scroller) {+ callback?.();+ return;+ }++ const existing = pendingAdjustments.get(scroller);+ if (existing) {+ existing.scrollTop = scroller.scrollTop;+ callback?.();+ return;+ }++ const state = {+ scrollTop: scroller.scrollTop,+ scrollHeight: scroller.scrollHeight,+ };++ pendingAdjustments.set(scroller, state);+ callback?.();++ schedule("afterRender", () => {+ const captured = pendingAdjustments.get(scroller);+ pendingAdjustments.delete(scroller);++ if (!captured || !scroller.isConnected) {+ return;+ }++ const heightDiff = scroller.scrollHeight - captured.scrollHeight;+ if (!heightDiff || heightDiff < 1) {+ return;+ }++ scroller.scrollTop = captured.scrollTop - heightDiff;+ });+}+export async function scrollListToBottom(list) {await new Promise((resolve) => {list.scrollTo({ top: 0, behavior: "auto" });diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-pane-pending-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-pane-pending-manager.jsnew file mode 100644index 00000000000..ce8560d7020--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/services/chat-pane-pending-manager.js@@ -0,0 +1,113 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";++/**+ * Single source of truth for pending message counts across all chat contexts.+ * Tracks how many messages arrived while the user was scrolled away or inactive.+ *+ * A "context" is identified by a key like "channel-123" or "thread-456".+ * The service maintains per-context counts and a global total used for+ * document title badges.+ */+export default class ChatPanePendingManager extends Service {+ @service appEvents;++ /**+ * Total pending messages across all contexts. Used for document title count.+ *+ * @type {number}+ */+ @tracked totalPendingMessageCount = 0;++ /**+ * Per-context pending counts.+ *+ * @type {Map<string, number>}+ */+ #countsByContext = new Map();++ /**+ * Get the pending message count for a specific context.+ *+ * @param {string} contextKey - The context identifier (e.g. "channel-123")+ * @returns {number}+ */+ getCount(contextKey) {+ return this.#countsByContext.get(contextKey) || 0;+ }++ /**+ * Check if a context has any pending messages.+ *+ * @param {string} contextKey - The context identifier+ * @returns {boolean}+ */+ hasPending(contextKey) {+ return this.getCount(contextKey) > 0;+ }++ /**+ * Add to the pending count for a context and trigger notifications.+ *+ * @param {string} contextKey - The context identifier+ * @param {number} [count=1] - Number of messages to add+ */+ add(contextKey, count = 1) {+ if (!contextKey || count <= 0) {+ return;+ }++ const current = this.#countsByContext.get(contextKey) || 0;+ const changed = this.#setCount(contextKey, current + count);++ if (changed) {+ this.appEvents.trigger("notifications:changed");+ }+ }++ /**+ * Clear all pending messages for a context and trigger notifications.+ *+ * @param {string} contextKey - The context identifier+ */+ clear(contextKey) {+ if (!contextKey) {+ return;+ }++ const changed = this.#setCount(contextKey, 0);++ if (changed) {+ this.appEvents.trigger("notifications:changed");+ }+ }++ /**+ * Update the count for a context and sync the global total.+ *+ * @param {string} contextKey+ * @param {number} newCount+ * @returns {boolean} Whether the count actually changed+ */+ #setCount(contextKey, newCount) {+ const oldCount = this.#countsByContext.get(contextKey) || 0;++ if (newCount === oldCount) {+ return false;+ }++ if (newCount > 0) {+ this.#countsByContext.set(contextKey, newCount);+ } else {+ this.#countsByContext.delete(contextKey);+ }++ const delta = newCount - oldCount;+ this.totalPendingMessageCount = Math.max(+ 0,+ this.totalPendingMessageCount + delta+ );++ return true;+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat.js b/plugins/chat/assets/javascripts/discourse/services/chat.jsindex db81a333888..eef4967c822 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat.js@@ -29,6 +29,7 @@ export default class Chat extends Service {@service router;@service chatChannelsManager;@service chatTrackingStateManager;+ @service chatPanePendingManager;cook = null;presenceChannel = null;@@ -252,7 +253,10 @@ export default class Chat extends Service {}getDocumentTitleCount() {- return this.chatTrackingStateManager.allChannelUrgentCount;+ return (+ this.chatTrackingStateManager.allChannelUrgentCount ++ this.chatPanePendingManager.totalPendingMessageCount+ );}switchChannelUpOrDown(direction, unreadOnly = false) {diff --git a/plugins/chat/spec/system/chat_channel_spec.rb b/plugins/chat/spec/system/chat_channel_spec.rbindex 96fc62ee581..287f04c04b3 100644--- a/plugins/chat/spec/system/chat_channel_spec.rb+++ b/plugins/chat/spec/system/chat_channel_spec.rb@@ -94,19 +94,21 @@ RSpec.describe "Chat channel", type: :system doit "syncs the messages" doJobs.run_immediately!- using_session(:tab_1) do- sign_in(current_user)- chat_page.visit_channel(channel_1)- end+ sign_in(current_user)+ chat_page.visit_channel(channel_1)- using_session(:tab_2) do- sign_in(current_user)+ original_window = current_window+ new_tab = open_new_window(:tab)++ within_window new_tab dochat_page.visit_channel(channel_1)end- using_session(:tab_1) { channel_page.send_message("test_message") }+ within_window original_window do+ channel_page.send_message("test_message")+ end- using_session(:tab_2) do+ within_window(new_tab) doexpect(channel_page.messages).to have_message(text: "test_message")endend@@ -159,13 +161,18 @@ RSpec.describe "Chat channel", type: :system docontext "when a new message is created" dobefore { Fabricate.times(50, :chat_message, chat_channel: channel_1) }- it "doesn’t append the message when not at bottom" do+ # this is skipped cause it is not correct+ xit "doesn’t append the message when not at bottom" dovisit("/chat/c/-/#{channel_1.id}/#{message_1.id}")expect(page).to have_css(".chat-scroll-to-bottom__button.visible")new_message = Fabricate(:chat_message, chat_channel: channel_1, use_service: true)+ expect(page).to have_css(".chat-scroll-to-bottom__button.visible")+ # sleep 5 <- this will cause this to consistently fail, cause the message+ # has always actually been unconditionally appended, we don't have logic to+ # prevent that yetexpect(channel_page.messages).to have_no_message(id: new_message.id)endenddiff --git a/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs b/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjsnew file mode 100644index 00000000000..a6b98cf7096--- /dev/null+++ b/plugins/chat/test/javascripts/unit/components/chat-presence-behavior-test.gjs@@ -0,0 +1,318 @@+import { getOwner } from "@ember/owner";+import { click, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import {+ clearPresenceCallbacks,+ setTestPresence,+} from "discourse/lib/user-presence";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { publishToMessageBus } from "discourse/tests/helpers/qunit-helpers";+import ChatChannel from "discourse/plugins/chat/discourse/components/chat-channel";+import ChatThread from "discourse/plugins/chat/discourse/components/chat-thread";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++function setScrollerHeight(scroller, { clientHeight, scrollHeight }) {+ Object.defineProperty(scroller, "clientHeight", {+ configurable: true,+ value: clientHeight,+ });+ Object.defineProperty(scroller, "scrollHeight", {+ configurable: true,+ value: scrollHeight,+ });+}++module(+ "Discourse Chat | Unit | Components | presence gating",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.fabricators = new ChatFabricators(getOwner(this));+ setTestPresence(false);++ pretender.get(`/chat/api/channels/1/messages`, () =>+ response({+ messages: [],+ meta: {+ can_delete_self: true,+ can_load_more_future: false,+ can_load_more_past: false,+ },+ })+ );+ pretender.get(`/chat/api/me/channels`, () =>+ response({+ direct_message_channels: [],+ public_channels: [],+ })+ );+ pretender.get(`/chat/api/channels/1/threads/1/messages`, () =>+ response({+ messages: [],+ meta: {+ can_load_more_future: false,+ can_load_more_past: false,+ },+ })+ );+ });++ hooks.afterEach(function () {+ setTestPresence(true);+ clearPresenceCallbacks();+ sinon.restore();+ });++ 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 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: 500,+ scrollHeight: 500,+ });++ const addMessagesStub = sinon.stub(+ channel.messagesManager,+ "addMessages"+ );+ readUpdateStub.resetHistory();++ publishToMessageBus(`/chat/1`, {+ type: "sent",+ chat_message: {+ id: 999,+ message: "hello",+ cooked: "<p>hello</p>",+ excerpt: "hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert.true(addMessagesStub.calledOnce, "appends messages");+ assert.false(readUpdateStub.called, "does not schedule read update");+ assert+ .dom(".chat-scroll-to-bottom__button.visible")+ .doesNotExist("does not show scroll-to-bottom arrow");+ });++ 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 },+ });++ this.channel = channel;+ await render(+ <template><ChatChannel @channel={{this.channel}} /></template>+ );++ setScrollerHeight(this.element.querySelector(".chat-messages-scroller"), {+ clientHeight: 100,+ scrollHeight: 500,+ });++ publishToMessageBus(`/chat/1`, {+ type: "sent",+ chat_message: {+ id: 999,+ message: "hello",+ cooked: "<p>hello</p>",+ excerpt: "hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert+ .dom(".chat-scroll-to-bottom__button.visible")+ .exists("shows scroll-to-bottom arrow");+ });++ 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 },+ });++ this.channel = channel;+ await render(+ <template><ChatChannel @channel={{this.channel}} /></template>+ );++ const pendingManager = getOwner(this).lookup(+ "service:chat-pane-pending-manager"+ );+ assert.strictEqual(+ pendingManager.totalPendingMessageCount,+ 0,+ "starts at zero"+ );++ publishToMessageBus(`/chat/1`, {+ type: "sent",+ chat_message: {+ id: 999,+ message: "hello",+ cooked: "<p>hello</p>",+ excerpt: "hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert.strictEqual(+ pendingManager.totalPendingMessageCount,+ 1,+ "increments on new message"+ );+ });++ 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 },+ });++ this.channel = channel;+ await render(+ <template><ChatChannel @channel={{this.channel}} /></template>+ );++ setScrollerHeight(this.element.querySelector(".chat-messages-scroller"), {+ clientHeight: 100,+ scrollHeight: 500,+ });++ const pendingManager = getOwner(this).lookup(+ "service:chat-pane-pending-manager"+ );++ publishToMessageBus(`/chat/1`, {+ type: "sent",+ chat_message: {+ id: 999,+ message: "hello",+ cooked: "<p>hello</p>",+ excerpt: "hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert.strictEqual(+ pendingManager.totalPendingMessageCount,+ 1,+ "has pending message"+ );++ await click(".chat-scroll-to-bottom__button");++ assert.strictEqual(+ pendingManager.totalPendingMessageCount,+ 0,+ "clears pending on scroll to bottom"+ );+ assert+ .dom(".chat-scroll-to-bottom__button.visible")+ .doesNotExist("hides arrow after scroll");+ });++ 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 },+ });++ this.channel = channel;+ await render(+ <template><ChatChannel @channel={{this.channel}} /></template>+ );++ const chatService = getOwner(this).lookup("service:chat");+ const initialCount = chatService.getDocumentTitleCount();++ publishToMessageBus(`/chat/1`, {+ type: "sent",+ chat_message: {+ id: 999,+ message: "hello",+ cooked: "<p>hello</p>",+ excerpt: "hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert.strictEqual(+ chatService.getDocumentTitleCount(),+ initialCount + 1,+ "pending message increments document title count"+ );+ });++ 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(+ ChatThread.prototype,+ "debouncedUpdateLastReadMessage"+ );++ this.thread = thread;+ await render(<template><ChatThread @thread={{this.thread}} /></template>);++ setScrollerHeight(this.element.querySelector(".chat-messages-scroller"), {+ clientHeight: 100,+ scrollHeight: 500,+ });++ const addMessagesStub = sinon.stub(thread.messagesManager, "addMessages");+ readUpdateStub.resetHistory();++ publishToMessageBus(`/chat/1/thread/1`, {+ type: "sent",+ chat_message: {+ id: 1001,+ message: "thread hello",+ cooked: "<p>thread hello</p>",+ excerpt: "thread hello",+ created_at: "2025-01-01T00:00:00.000Z",+ user: { id: 1, username: "eviltrout" },+ },+ });+ await settled();++ assert.true(addMessagesStub.calledOnce, "appends messages");+ assert.false(readUpdateStub.called, "does not schedule read update");+ assert+ .dom(".chat-scroll-to-bottom__button.visible")+ .exists("shows scroll-to-bottom arrow");+ });+ }+);